xref: /openbmc/linux/fs/ext4/inode.c (revision 5704265188ffe4290ed73b3cb685206c3ed8209d)
1ac27a0ecSDave Kleikamp /*
2617ba13bSMingming Cao  *  linux/fs/ext4/inode.c
3ac27a0ecSDave Kleikamp  *
4ac27a0ecSDave Kleikamp  * Copyright (C) 1992, 1993, 1994, 1995
5ac27a0ecSDave Kleikamp  * Remy Card (card@masi.ibp.fr)
6ac27a0ecSDave Kleikamp  * Laboratoire MASI - Institut Blaise Pascal
7ac27a0ecSDave Kleikamp  * Universite Pierre et Marie Curie (Paris VI)
8ac27a0ecSDave Kleikamp  *
9ac27a0ecSDave Kleikamp  *  from
10ac27a0ecSDave Kleikamp  *
11ac27a0ecSDave Kleikamp  *  linux/fs/minix/inode.c
12ac27a0ecSDave Kleikamp  *
13ac27a0ecSDave Kleikamp  *  Copyright (C) 1991, 1992  Linus Torvalds
14ac27a0ecSDave Kleikamp  *
15ac27a0ecSDave Kleikamp  *  64-bit file support on 64-bit platforms by Jakub Jelinek
16ac27a0ecSDave Kleikamp  *	(jj@sunsite.ms.mff.cuni.cz)
17ac27a0ecSDave Kleikamp  *
18617ba13bSMingming Cao  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
19ac27a0ecSDave Kleikamp  */
20ac27a0ecSDave Kleikamp 
21ac27a0ecSDave Kleikamp #include <linux/module.h>
22ac27a0ecSDave Kleikamp #include <linux/fs.h>
23ac27a0ecSDave Kleikamp #include <linux/time.h>
24dab291afSMingming Cao #include <linux/jbd2.h>
25ac27a0ecSDave Kleikamp #include <linux/highuid.h>
26ac27a0ecSDave Kleikamp #include <linux/pagemap.h>
27ac27a0ecSDave Kleikamp #include <linux/quotaops.h>
28ac27a0ecSDave Kleikamp #include <linux/string.h>
29ac27a0ecSDave Kleikamp #include <linux/buffer_head.h>
30ac27a0ecSDave Kleikamp #include <linux/writeback.h>
3164769240SAlex Tomas #include <linux/pagevec.h>
32ac27a0ecSDave Kleikamp #include <linux/mpage.h>
33e83c1397SDuane Griffin #include <linux/namei.h>
34ac27a0ecSDave Kleikamp #include <linux/uio.h>
35ac27a0ecSDave Kleikamp #include <linux/bio.h>
364c0425ffSMingming Cao #include <linux/workqueue.h>
37744692dcSJiaying Zhang #include <linux/kernel.h>
386db26ffcSAndrew Morton #include <linux/printk.h>
395a0e3ad6STejun Heo #include <linux/slab.h>
40a8901d34STheodore Ts'o #include <linux/ratelimit.h>
419bffad1eSTheodore Ts'o 
423dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
43ac27a0ecSDave Kleikamp #include "xattr.h"
44ac27a0ecSDave Kleikamp #include "acl.h"
45d2a17637SMingming Cao #include "ext4_extents.h"
469f125d64STheodore Ts'o #include "truncate.h"
47ac27a0ecSDave Kleikamp 
489bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
499bffad1eSTheodore Ts'o 
50a1d6cc56SAneesh Kumar K.V #define MPAGE_DA_EXTENT_TAIL 0x01
51a1d6cc56SAneesh Kumar K.V 
52678aaf48SJan Kara static inline int ext4_begin_ordered_truncate(struct inode *inode,
53678aaf48SJan Kara 					      loff_t new_size)
54678aaf48SJan Kara {
557ff9c073STheodore Ts'o 	trace_ext4_begin_ordered_truncate(inode, new_size);
568aefcd55STheodore Ts'o 	/*
578aefcd55STheodore Ts'o 	 * If jinode is zero, then we never opened the file for
588aefcd55STheodore Ts'o 	 * writing, so there's no need to call
598aefcd55STheodore Ts'o 	 * jbd2_journal_begin_ordered_truncate() since there's no
608aefcd55STheodore Ts'o 	 * outstanding writes we need to flush.
618aefcd55STheodore Ts'o 	 */
628aefcd55STheodore Ts'o 	if (!EXT4_I(inode)->jinode)
638aefcd55STheodore Ts'o 		return 0;
648aefcd55STheodore Ts'o 	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
658aefcd55STheodore Ts'o 						   EXT4_I(inode)->jinode,
66678aaf48SJan Kara 						   new_size);
67678aaf48SJan Kara }
68678aaf48SJan Kara 
6964769240SAlex Tomas static void ext4_invalidatepage(struct page *page, unsigned long offset);
70cb20d518STheodore Ts'o static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
71cb20d518STheodore Ts'o 				   struct buffer_head *bh_result, int create);
72cb20d518STheodore Ts'o static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
73cb20d518STheodore Ts'o static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
74cb20d518STheodore Ts'o static int __ext4_journalled_writepage(struct page *page, unsigned int len);
75cb20d518STheodore Ts'o static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
7664769240SAlex Tomas 
77ac27a0ecSDave Kleikamp /*
78ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
79ac27a0ecSDave Kleikamp  */
80617ba13bSMingming Cao static int ext4_inode_is_fast_symlink(struct inode *inode)
81ac27a0ecSDave Kleikamp {
82617ba13bSMingming Cao 	int ea_blocks = EXT4_I(inode)->i_file_acl ?
83ac27a0ecSDave Kleikamp 		(inode->i_sb->s_blocksize >> 9) : 0;
84ac27a0ecSDave Kleikamp 
85ac27a0ecSDave Kleikamp 	return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
86ac27a0ecSDave Kleikamp }
87ac27a0ecSDave Kleikamp 
88ac27a0ecSDave Kleikamp /*
89ac27a0ecSDave Kleikamp  * Restart the transaction associated with *handle.  This does a commit,
90ac27a0ecSDave Kleikamp  * so before we call here everything must be consistently dirtied against
91ac27a0ecSDave Kleikamp  * this transaction.
92ac27a0ecSDave Kleikamp  */
93487caeefSJan Kara int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
94487caeefSJan Kara 				 int nblocks)
95ac27a0ecSDave Kleikamp {
96487caeefSJan Kara 	int ret;
97487caeefSJan Kara 
98487caeefSJan Kara 	/*
99e35fd660STheodore Ts'o 	 * Drop i_data_sem to avoid deadlock with ext4_map_blocks.  At this
100487caeefSJan Kara 	 * moment, get_block can be called only for blocks inside i_size since
101487caeefSJan Kara 	 * page cache has been already dropped and writes are blocked by
102487caeefSJan Kara 	 * i_mutex. So we can safely drop the i_data_sem here.
103487caeefSJan Kara 	 */
1040390131bSFrank Mayhar 	BUG_ON(EXT4_JOURNAL(inode) == NULL);
105ac27a0ecSDave Kleikamp 	jbd_debug(2, "restarting handle %p\n", handle);
106487caeefSJan Kara 	up_write(&EXT4_I(inode)->i_data_sem);
1078e8eaabeSAmir Goldstein 	ret = ext4_journal_restart(handle, nblocks);
108487caeefSJan Kara 	down_write(&EXT4_I(inode)->i_data_sem);
109fa5d1113SAneesh Kumar K.V 	ext4_discard_preallocations(inode);
110487caeefSJan Kara 
111487caeefSJan Kara 	return ret;
112ac27a0ecSDave Kleikamp }
113ac27a0ecSDave Kleikamp 
114ac27a0ecSDave Kleikamp /*
115ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
116ac27a0ecSDave Kleikamp  */
1170930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
118ac27a0ecSDave Kleikamp {
119ac27a0ecSDave Kleikamp 	handle_t *handle;
120bc965ab3STheodore Ts'o 	int err;
121ac27a0ecSDave Kleikamp 
1227ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1232581fdc8SJiaying Zhang 
1242581fdc8SJiaying Zhang 	ext4_ioend_wait(inode);
1252581fdc8SJiaying Zhang 
1260930fcc1SAl Viro 	if (inode->i_nlink) {
1272d859db3SJan Kara 		/*
1282d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1292d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1302d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1312d859db3SJan Kara 		 * write in the running transaction or waiting to be
1322d859db3SJan Kara 		 * checkpointed. Thus calling jbd2_journal_invalidatepage()
1332d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1342d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1352d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1362d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
1372d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
1382d859db3SJan Kara 		 * careful and force everything to disk here... We use
1392d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
1402d859db3SJan Kara 		 * containing inode's data.
1412d859db3SJan Kara 		 *
1422d859db3SJan Kara 		 * Note that directories do not have this problem because they
1432d859db3SJan Kara 		 * don't use page cache.
1442d859db3SJan Kara 		 */
1452d859db3SJan Kara 		if (ext4_should_journal_data(inode) &&
1462d859db3SJan Kara 		    (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
1472d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
1482d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
1492d859db3SJan Kara 
1502d859db3SJan Kara 			jbd2_log_start_commit(journal, commit_tid);
1512d859db3SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
1522d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
1532d859db3SJan Kara 		}
1540930fcc1SAl Viro 		truncate_inode_pages(&inode->i_data, 0);
1550930fcc1SAl Viro 		goto no_delete;
1560930fcc1SAl Viro 	}
1570930fcc1SAl Viro 
158907f4554SChristoph Hellwig 	if (!is_bad_inode(inode))
159871a2931SChristoph Hellwig 		dquot_initialize(inode);
160907f4554SChristoph Hellwig 
161678aaf48SJan Kara 	if (ext4_should_order_data(inode))
162678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
163ac27a0ecSDave Kleikamp 	truncate_inode_pages(&inode->i_data, 0);
164ac27a0ecSDave Kleikamp 
165ac27a0ecSDave Kleikamp 	if (is_bad_inode(inode))
166ac27a0ecSDave Kleikamp 		goto no_delete;
167ac27a0ecSDave Kleikamp 
1689f125d64STheodore Ts'o 	handle = ext4_journal_start(inode, ext4_blocks_for_truncate(inode)+3);
169ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
170bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
171ac27a0ecSDave Kleikamp 		/*
172ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
173ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
174ac27a0ecSDave Kleikamp 		 * cleaned up.
175ac27a0ecSDave Kleikamp 		 */
176617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
177ac27a0ecSDave Kleikamp 		goto no_delete;
178ac27a0ecSDave Kleikamp 	}
179ac27a0ecSDave Kleikamp 
180ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
1810390131bSFrank Mayhar 		ext4_handle_sync(handle);
182ac27a0ecSDave Kleikamp 	inode->i_size = 0;
183bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
184bc965ab3STheodore Ts'o 	if (err) {
18512062dddSEric Sandeen 		ext4_warning(inode->i_sb,
186bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
187bc965ab3STheodore Ts'o 		goto stop_handle;
188bc965ab3STheodore Ts'o 	}
189ac27a0ecSDave Kleikamp 	if (inode->i_blocks)
190617ba13bSMingming Cao 		ext4_truncate(inode);
191bc965ab3STheodore Ts'o 
192bc965ab3STheodore Ts'o 	/*
193bc965ab3STheodore Ts'o 	 * ext4_ext_truncate() doesn't reserve any slop when it
194bc965ab3STheodore Ts'o 	 * restarts journal transactions; therefore there may not be
195bc965ab3STheodore Ts'o 	 * enough credits left in the handle to remove the inode from
196bc965ab3STheodore Ts'o 	 * the orphan list and set the dtime field.
197bc965ab3STheodore Ts'o 	 */
1980390131bSFrank Mayhar 	if (!ext4_handle_has_enough_credits(handle, 3)) {
199bc965ab3STheodore Ts'o 		err = ext4_journal_extend(handle, 3);
200bc965ab3STheodore Ts'o 		if (err > 0)
201bc965ab3STheodore Ts'o 			err = ext4_journal_restart(handle, 3);
202bc965ab3STheodore Ts'o 		if (err != 0) {
20312062dddSEric Sandeen 			ext4_warning(inode->i_sb,
204bc965ab3STheodore Ts'o 				     "couldn't extend journal (err %d)", err);
205bc965ab3STheodore Ts'o 		stop_handle:
206bc965ab3STheodore Ts'o 			ext4_journal_stop(handle);
20745388219STheodore Ts'o 			ext4_orphan_del(NULL, inode);
208bc965ab3STheodore Ts'o 			goto no_delete;
209bc965ab3STheodore Ts'o 		}
210bc965ab3STheodore Ts'o 	}
211bc965ab3STheodore Ts'o 
212ac27a0ecSDave Kleikamp 	/*
213617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
214ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
215617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
216ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
217617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
218ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
219ac27a0ecSDave Kleikamp 	 */
220617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
221617ba13bSMingming Cao 	EXT4_I(inode)->i_dtime	= get_seconds();
222ac27a0ecSDave Kleikamp 
223ac27a0ecSDave Kleikamp 	/*
224ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
225ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
226ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
227ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
228ac27a0ecSDave Kleikamp 	 * fails.
229ac27a0ecSDave Kleikamp 	 */
230617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
231ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
2320930fcc1SAl Viro 		ext4_clear_inode(inode);
233ac27a0ecSDave Kleikamp 	else
234617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
235617ba13bSMingming Cao 	ext4_journal_stop(handle);
236ac27a0ecSDave Kleikamp 	return;
237ac27a0ecSDave Kleikamp no_delete:
2380930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
239ac27a0ecSDave Kleikamp }
240ac27a0ecSDave Kleikamp 
241a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
242a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
24360e58e0fSMingming Cao {
244a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
24560e58e0fSMingming Cao }
246a9e7f447SDmitry Monakhov #endif
2479d0be502STheodore Ts'o 
24812219aeaSAneesh Kumar K.V /*
24912219aeaSAneesh Kumar K.V  * Calculate the number of metadata blocks need to reserve
2509d0be502STheodore Ts'o  * to allocate a block located at @lblock
25112219aeaSAneesh Kumar K.V  */
25201f49d0bSTheodore Ts'o static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
25312219aeaSAneesh Kumar K.V {
25412e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
2559d0be502STheodore Ts'o 		return ext4_ext_calc_metadata_amount(inode, lblock);
25612219aeaSAneesh Kumar K.V 
2578bb2b247SAmir Goldstein 	return ext4_ind_calc_metadata_amount(inode, lblock);
25812219aeaSAneesh Kumar K.V }
25912219aeaSAneesh Kumar K.V 
2600637c6f4STheodore Ts'o /*
2610637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
2620637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
2630637c6f4STheodore Ts'o  */
2645f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
2655f634d06SAneesh Kumar K.V 					int used, int quota_claim)
26612219aeaSAneesh Kumar K.V {
26712219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2680637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
26912219aeaSAneesh Kumar K.V 
2700637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
271f8ec9d68STheodore Ts'o 	trace_ext4_da_update_reserve_space(inode, used);
2720637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
2730637c6f4STheodore Ts'o 		ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
2740637c6f4STheodore Ts'o 			 "with only %d reserved data blocks\n",
2750637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
2760637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
2770637c6f4STheodore Ts'o 		WARN_ON(1);
2780637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
2796bc6e63fSAneesh Kumar K.V 	}
28012219aeaSAneesh Kumar K.V 
2810637c6f4STheodore Ts'o 	/* Update per-inode reservations */
2820637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
2830637c6f4STheodore Ts'o 	ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
284*57042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter,
28572b8ab9dSEric Sandeen 			   used + ei->i_allocated_meta_blocks);
2860637c6f4STheodore Ts'o 	ei->i_allocated_meta_blocks = 0;
2870637c6f4STheodore Ts'o 
2880637c6f4STheodore Ts'o 	if (ei->i_reserved_data_blocks == 0) {
2890637c6f4STheodore Ts'o 		/*
2900637c6f4STheodore Ts'o 		 * We can release all of the reserved metadata blocks
2910637c6f4STheodore Ts'o 		 * only when we have written all of the delayed
2920637c6f4STheodore Ts'o 		 * allocation blocks.
2930637c6f4STheodore Ts'o 		 */
294*57042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
29572b8ab9dSEric Sandeen 				   ei->i_reserved_meta_blocks);
296ee5f4d9cSTheodore Ts'o 		ei->i_reserved_meta_blocks = 0;
2979d0be502STheodore Ts'o 		ei->i_da_metadata_calc_len = 0;
2980637c6f4STheodore Ts'o 	}
29912219aeaSAneesh Kumar K.V 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
30060e58e0fSMingming Cao 
30172b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
30272b8ab9dSEric Sandeen 	if (quota_claim)
3035dd4056dSChristoph Hellwig 		dquot_claim_block(inode, used);
30472b8ab9dSEric Sandeen 	else {
3055f634d06SAneesh Kumar K.V 		/*
3065f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3075f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
30872b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3095f634d06SAneesh Kumar K.V 		 */
31072b8ab9dSEric Sandeen 		dquot_release_reservation_block(inode, used);
3115f634d06SAneesh Kumar K.V 	}
312d6014301SAneesh Kumar K.V 
313d6014301SAneesh Kumar K.V 	/*
314d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
315d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
316d6014301SAneesh Kumar K.V 	 * inode's preallocations.
317d6014301SAneesh Kumar K.V 	 */
3180637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
3190637c6f4STheodore Ts'o 	    (atomic_read(&inode->i_writecount) == 0))
320d6014301SAneesh Kumar K.V 		ext4_discard_preallocations(inode);
32112219aeaSAneesh Kumar K.V }
32212219aeaSAneesh Kumar K.V 
323e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
324c398eda0STheodore Ts'o 				unsigned int line,
32524676da4STheodore Ts'o 				struct ext4_map_blocks *map)
3266fd058f7STheodore Ts'o {
32724676da4STheodore Ts'o 	if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
32824676da4STheodore Ts'o 				   map->m_len)) {
329c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
330c398eda0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock "
33124676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
332c398eda0STheodore Ts'o 				 map->m_len);
3336fd058f7STheodore Ts'o 		return -EIO;
3346fd058f7STheodore Ts'o 	}
3356fd058f7STheodore Ts'o 	return 0;
3366fd058f7STheodore Ts'o }
3376fd058f7STheodore Ts'o 
338e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
339c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
340e29136f8STheodore Ts'o 
341f5ab0d1fSMingming Cao /*
3421f94533dSTheodore Ts'o  * Return the number of contiguous dirty pages in a given inode
3431f94533dSTheodore Ts'o  * starting at page frame idx.
34455138e0bSTheodore Ts'o  */
34555138e0bSTheodore Ts'o static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
34655138e0bSTheodore Ts'o 				    unsigned int max_pages)
34755138e0bSTheodore Ts'o {
34855138e0bSTheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
34955138e0bSTheodore Ts'o 	pgoff_t	index;
35055138e0bSTheodore Ts'o 	struct pagevec pvec;
35155138e0bSTheodore Ts'o 	pgoff_t num = 0;
35255138e0bSTheodore Ts'o 	int i, nr_pages, done = 0;
35355138e0bSTheodore Ts'o 
35455138e0bSTheodore Ts'o 	if (max_pages == 0)
35555138e0bSTheodore Ts'o 		return 0;
35655138e0bSTheodore Ts'o 	pagevec_init(&pvec, 0);
35755138e0bSTheodore Ts'o 	while (!done) {
35855138e0bSTheodore Ts'o 		index = idx;
35955138e0bSTheodore Ts'o 		nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
36055138e0bSTheodore Ts'o 					      PAGECACHE_TAG_DIRTY,
36155138e0bSTheodore Ts'o 					      (pgoff_t)PAGEVEC_SIZE);
36255138e0bSTheodore Ts'o 		if (nr_pages == 0)
36355138e0bSTheodore Ts'o 			break;
36455138e0bSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
36555138e0bSTheodore Ts'o 			struct page *page = pvec.pages[i];
36655138e0bSTheodore Ts'o 			struct buffer_head *bh, *head;
36755138e0bSTheodore Ts'o 
36855138e0bSTheodore Ts'o 			lock_page(page);
36955138e0bSTheodore Ts'o 			if (unlikely(page->mapping != mapping) ||
37055138e0bSTheodore Ts'o 			    !PageDirty(page) ||
37155138e0bSTheodore Ts'o 			    PageWriteback(page) ||
37255138e0bSTheodore Ts'o 			    page->index != idx) {
37355138e0bSTheodore Ts'o 				done = 1;
37455138e0bSTheodore Ts'o 				unlock_page(page);
37555138e0bSTheodore Ts'o 				break;
37655138e0bSTheodore Ts'o 			}
3771f94533dSTheodore Ts'o 			if (page_has_buffers(page)) {
3781f94533dSTheodore Ts'o 				bh = head = page_buffers(page);
37955138e0bSTheodore Ts'o 				do {
38055138e0bSTheodore Ts'o 					if (!buffer_delay(bh) &&
3811f94533dSTheodore Ts'o 					    !buffer_unwritten(bh))
38255138e0bSTheodore Ts'o 						done = 1;
3831f94533dSTheodore Ts'o 					bh = bh->b_this_page;
3841f94533dSTheodore Ts'o 				} while (!done && (bh != head));
38555138e0bSTheodore Ts'o 			}
38655138e0bSTheodore Ts'o 			unlock_page(page);
38755138e0bSTheodore Ts'o 			if (done)
38855138e0bSTheodore Ts'o 				break;
38955138e0bSTheodore Ts'o 			idx++;
39055138e0bSTheodore Ts'o 			num++;
391659c6009SEric Sandeen 			if (num >= max_pages) {
392659c6009SEric Sandeen 				done = 1;
39355138e0bSTheodore Ts'o 				break;
39455138e0bSTheodore Ts'o 			}
395659c6009SEric Sandeen 		}
39655138e0bSTheodore Ts'o 		pagevec_release(&pvec);
39755138e0bSTheodore Ts'o 	}
39855138e0bSTheodore Ts'o 	return num;
39955138e0bSTheodore Ts'o }
40055138e0bSTheodore Ts'o 
40155138e0bSTheodore Ts'o /*
402e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4032b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
404f5ab0d1fSMingming Cao  *
405f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
406f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
407f5ab0d1fSMingming Cao  * mapped.
408f5ab0d1fSMingming Cao  *
409e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
410e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
411f5ab0d1fSMingming Cao  * based files
412f5ab0d1fSMingming Cao  *
413f5ab0d1fSMingming Cao  * On success, it returns the number of blocks being mapped or allocate.
414f5ab0d1fSMingming Cao  * if create==0 and the blocks are pre-allocated and uninitialized block,
415f5ab0d1fSMingming Cao  * the result buffer head is unmapped. If the create ==1, it will make sure
416f5ab0d1fSMingming Cao  * the buffer head is mapped.
417f5ab0d1fSMingming Cao  *
418f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
419f5ab0d1fSMingming Cao  * that casem, buffer head is unmapped
420f5ab0d1fSMingming Cao  *
421f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
422f5ab0d1fSMingming Cao  */
423e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
424e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
4250e855ac8SAneesh Kumar K.V {
4260e855ac8SAneesh Kumar K.V 	int retval;
427f5ab0d1fSMingming Cao 
428e35fd660STheodore Ts'o 	map->m_flags = 0;
429e35fd660STheodore Ts'o 	ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
430e35fd660STheodore Ts'o 		  "logical block %lu\n", inode->i_ino, flags, map->m_len,
431e35fd660STheodore Ts'o 		  (unsigned long) map->m_lblk);
4324df3d265SAneesh Kumar K.V 	/*
433b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
434b920c755STheodore Ts'o 	 * file system block.
4354df3d265SAneesh Kumar K.V 	 */
4360e855ac8SAneesh Kumar K.V 	down_read((&EXT4_I(inode)->i_data_sem));
43712e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
438e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
4394df3d265SAneesh Kumar K.V 	} else {
440e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
4410e855ac8SAneesh Kumar K.V 	}
4424df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
443f5ab0d1fSMingming Cao 
444e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
445e29136f8STheodore Ts'o 		int ret = check_block_validity(inode, map);
4466fd058f7STheodore Ts'o 		if (ret != 0)
4476fd058f7STheodore Ts'o 			return ret;
4486fd058f7STheodore Ts'o 	}
4496fd058f7STheodore Ts'o 
450f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
451c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
4524df3d265SAneesh Kumar K.V 		return retval;
4534df3d265SAneesh Kumar K.V 
4544df3d265SAneesh Kumar K.V 	/*
455f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
456f5ab0d1fSMingming Cao 	 *
457f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
458f5ab0d1fSMingming Cao 	 * ext4_ext_get_block() returns th create = 0
459f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
460f5ab0d1fSMingming Cao 	 */
461e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
462f5ab0d1fSMingming Cao 		return retval;
463f5ab0d1fSMingming Cao 
464f5ab0d1fSMingming Cao 	/*
4652a8964d6SAneesh Kumar K.V 	 * When we call get_blocks without the create flag, the
4662a8964d6SAneesh Kumar K.V 	 * BH_Unwritten flag could have gotten set if the blocks
4672a8964d6SAneesh Kumar K.V 	 * requested were part of a uninitialized extent.  We need to
4682a8964d6SAneesh Kumar K.V 	 * clear this flag now that we are committed to convert all or
4692a8964d6SAneesh Kumar K.V 	 * part of the uninitialized extent to be an initialized
4702a8964d6SAneesh Kumar K.V 	 * extent.  This is because we need to avoid the combination
4712a8964d6SAneesh Kumar K.V 	 * of BH_Unwritten and BH_Mapped flags being simultaneously
4722a8964d6SAneesh Kumar K.V 	 * set on the buffer_head.
4732a8964d6SAneesh Kumar K.V 	 */
474e35fd660STheodore Ts'o 	map->m_flags &= ~EXT4_MAP_UNWRITTEN;
4752a8964d6SAneesh Kumar K.V 
4762a8964d6SAneesh Kumar K.V 	/*
477f5ab0d1fSMingming Cao 	 * New blocks allocate and/or writing to uninitialized extent
478f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
479f5ab0d1fSMingming Cao 	 * the write lock of i_data_sem, and call get_blocks()
480f5ab0d1fSMingming Cao 	 * with create == 1 flag.
4814df3d265SAneesh Kumar K.V 	 */
4824df3d265SAneesh Kumar K.V 	down_write((&EXT4_I(inode)->i_data_sem));
483d2a17637SMingming Cao 
484d2a17637SMingming Cao 	/*
485d2a17637SMingming Cao 	 * if the caller is from delayed allocation writeout path
486d2a17637SMingming Cao 	 * we have already reserved fs blocks for allocation
487d2a17637SMingming Cao 	 * let the underlying get_block() function know to
488d2a17637SMingming Cao 	 * avoid double accounting
489d2a17637SMingming Cao 	 */
490c2177057STheodore Ts'o 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
491f2321097STheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
4924df3d265SAneesh Kumar K.V 	/*
4934df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
4944df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
4954df3d265SAneesh Kumar K.V 	 */
49612e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
497e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
4980e855ac8SAneesh Kumar K.V 	} else {
499e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
500267e4db9SAneesh Kumar K.V 
501e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
502267e4db9SAneesh Kumar K.V 			/*
503267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
504267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
505267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
506267e4db9SAneesh Kumar K.V 			 */
50719f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
508267e4db9SAneesh Kumar K.V 		}
5092ac3b6e0STheodore Ts'o 
510d2a17637SMingming Cao 		/*
5112ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
5125f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
5135f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
5145f634d06SAneesh Kumar K.V 		 * reserve space here.
515d2a17637SMingming Cao 		 */
5165f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
5171296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
5185f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
5195f634d06SAneesh Kumar K.V 	}
5205f634d06SAneesh Kumar K.V 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
521f2321097STheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
522d2a17637SMingming Cao 
5230e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
524e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
525e29136f8STheodore Ts'o 		int ret = check_block_validity(inode, map);
5266fd058f7STheodore Ts'o 		if (ret != 0)
5276fd058f7STheodore Ts'o 			return ret;
5286fd058f7STheodore Ts'o 	}
5290e855ac8SAneesh Kumar K.V 	return retval;
5300e855ac8SAneesh Kumar K.V }
5310e855ac8SAneesh Kumar K.V 
532f3bd1f3fSMingming Cao /* Maximum number of blocks we map for direct IO at once. */
533f3bd1f3fSMingming Cao #define DIO_MAX_BLOCKS 4096
534f3bd1f3fSMingming Cao 
5352ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
5362ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
537ac27a0ecSDave Kleikamp {
5383e4fdaf8SDmitriy Monakhov 	handle_t *handle = ext4_journal_current_handle();
5392ed88685STheodore Ts'o 	struct ext4_map_blocks map;
5407fb5409dSJan Kara 	int ret = 0, started = 0;
541f3bd1f3fSMingming Cao 	int dio_credits;
542ac27a0ecSDave Kleikamp 
5432ed88685STheodore Ts'o 	map.m_lblk = iblock;
5442ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
5452ed88685STheodore Ts'o 
5462ed88685STheodore Ts'o 	if (flags && !handle) {
5477fb5409dSJan Kara 		/* Direct IO write... */
5482ed88685STheodore Ts'o 		if (map.m_len > DIO_MAX_BLOCKS)
5492ed88685STheodore Ts'o 			map.m_len = DIO_MAX_BLOCKS;
5502ed88685STheodore Ts'o 		dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
551f3bd1f3fSMingming Cao 		handle = ext4_journal_start(inode, dio_credits);
5527fb5409dSJan Kara 		if (IS_ERR(handle)) {
553ac27a0ecSDave Kleikamp 			ret = PTR_ERR(handle);
5542ed88685STheodore Ts'o 			return ret;
5557fb5409dSJan Kara 		}
5567fb5409dSJan Kara 		started = 1;
557ac27a0ecSDave Kleikamp 	}
558ac27a0ecSDave Kleikamp 
5592ed88685STheodore Ts'o 	ret = ext4_map_blocks(handle, inode, &map, flags);
560ac27a0ecSDave Kleikamp 	if (ret > 0) {
5612ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
5622ed88685STheodore Ts'o 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
5632ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
564ac27a0ecSDave Kleikamp 		ret = 0;
565ac27a0ecSDave Kleikamp 	}
5667fb5409dSJan Kara 	if (started)
5677fb5409dSJan Kara 		ext4_journal_stop(handle);
568ac27a0ecSDave Kleikamp 	return ret;
569ac27a0ecSDave Kleikamp }
570ac27a0ecSDave Kleikamp 
5712ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
5722ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
5732ed88685STheodore Ts'o {
5742ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
5752ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
5762ed88685STheodore Ts'o }
5772ed88685STheodore Ts'o 
578ac27a0ecSDave Kleikamp /*
579ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
580ac27a0ecSDave Kleikamp  */
581617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
582725d26d3SAneesh Kumar K.V 				ext4_lblk_t block, int create, int *errp)
583ac27a0ecSDave Kleikamp {
5842ed88685STheodore Ts'o 	struct ext4_map_blocks map;
5852ed88685STheodore Ts'o 	struct buffer_head *bh;
586ac27a0ecSDave Kleikamp 	int fatal = 0, err;
587ac27a0ecSDave Kleikamp 
588ac27a0ecSDave Kleikamp 	J_ASSERT(handle != NULL || create == 0);
589ac27a0ecSDave Kleikamp 
5902ed88685STheodore Ts'o 	map.m_lblk = block;
5912ed88685STheodore Ts'o 	map.m_len = 1;
5922ed88685STheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map,
5932ed88685STheodore Ts'o 			      create ? EXT4_GET_BLOCKS_CREATE : 0);
5942ed88685STheodore Ts'o 
5952ed88685STheodore Ts'o 	if (err < 0)
596ac27a0ecSDave Kleikamp 		*errp = err;
5972ed88685STheodore Ts'o 	if (err <= 0)
5982ed88685STheodore Ts'o 		return NULL;
5992ed88685STheodore Ts'o 	*errp = 0;
6002ed88685STheodore Ts'o 
6012ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
602ac27a0ecSDave Kleikamp 	if (!bh) {
603ac27a0ecSDave Kleikamp 		*errp = -EIO;
6042ed88685STheodore Ts'o 		return NULL;
605ac27a0ecSDave Kleikamp 	}
6062ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
607ac27a0ecSDave Kleikamp 		J_ASSERT(create != 0);
608ac39849dSAneesh Kumar K.V 		J_ASSERT(handle != NULL);
609ac27a0ecSDave Kleikamp 
610ac27a0ecSDave Kleikamp 		/*
611ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
612ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
613ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
614617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
615ac27a0ecSDave Kleikamp 		 * problem.
616ac27a0ecSDave Kleikamp 		 */
617ac27a0ecSDave Kleikamp 		lock_buffer(bh);
618ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
619617ba13bSMingming Cao 		fatal = ext4_journal_get_create_access(handle, bh);
620ac27a0ecSDave Kleikamp 		if (!fatal && !buffer_uptodate(bh)) {
621ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
622ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
623ac27a0ecSDave Kleikamp 		}
624ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
6250390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
6260390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
627ac27a0ecSDave Kleikamp 		if (!fatal)
628ac27a0ecSDave Kleikamp 			fatal = err;
629ac27a0ecSDave Kleikamp 	} else {
630ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
631ac27a0ecSDave Kleikamp 	}
632ac27a0ecSDave Kleikamp 	if (fatal) {
633ac27a0ecSDave Kleikamp 		*errp = fatal;
634ac27a0ecSDave Kleikamp 		brelse(bh);
635ac27a0ecSDave Kleikamp 		bh = NULL;
636ac27a0ecSDave Kleikamp 	}
637ac27a0ecSDave Kleikamp 	return bh;
638ac27a0ecSDave Kleikamp }
639ac27a0ecSDave Kleikamp 
640617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
641725d26d3SAneesh Kumar K.V 			       ext4_lblk_t block, int create, int *err)
642ac27a0ecSDave Kleikamp {
643ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
644ac27a0ecSDave Kleikamp 
645617ba13bSMingming Cao 	bh = ext4_getblk(handle, inode, block, create, err);
646ac27a0ecSDave Kleikamp 	if (!bh)
647ac27a0ecSDave Kleikamp 		return bh;
648ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
649ac27a0ecSDave Kleikamp 		return bh;
650ac27a0ecSDave Kleikamp 	ll_rw_block(READ_META, 1, &bh);
651ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
652ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
653ac27a0ecSDave Kleikamp 		return bh;
654ac27a0ecSDave Kleikamp 	put_bh(bh);
655ac27a0ecSDave Kleikamp 	*err = -EIO;
656ac27a0ecSDave Kleikamp 	return NULL;
657ac27a0ecSDave Kleikamp }
658ac27a0ecSDave Kleikamp 
659ac27a0ecSDave Kleikamp static int walk_page_buffers(handle_t *handle,
660ac27a0ecSDave Kleikamp 			     struct buffer_head *head,
661ac27a0ecSDave Kleikamp 			     unsigned from,
662ac27a0ecSDave Kleikamp 			     unsigned to,
663ac27a0ecSDave Kleikamp 			     int *partial,
664ac27a0ecSDave Kleikamp 			     int (*fn)(handle_t *handle,
665ac27a0ecSDave Kleikamp 				       struct buffer_head *bh))
666ac27a0ecSDave Kleikamp {
667ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
668ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
669ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
670ac27a0ecSDave Kleikamp 	int err, ret = 0;
671ac27a0ecSDave Kleikamp 	struct buffer_head *next;
672ac27a0ecSDave Kleikamp 
673ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
674ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
675de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
676ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
677ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
678ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
679ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
680ac27a0ecSDave Kleikamp 				*partial = 1;
681ac27a0ecSDave Kleikamp 			continue;
682ac27a0ecSDave Kleikamp 		}
683ac27a0ecSDave Kleikamp 		err = (*fn)(handle, bh);
684ac27a0ecSDave Kleikamp 		if (!ret)
685ac27a0ecSDave Kleikamp 			ret = err;
686ac27a0ecSDave Kleikamp 	}
687ac27a0ecSDave Kleikamp 	return ret;
688ac27a0ecSDave Kleikamp }
689ac27a0ecSDave Kleikamp 
690ac27a0ecSDave Kleikamp /*
691ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
692ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
693617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
694dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
695ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
696ac27a0ecSDave Kleikamp  *
697617ba13bSMingming Cao  * Also, this function can nest inside ext4_writepage() ->
698617ba13bSMingming Cao  * block_write_full_page(). In that case, we *know* that ext4_writepage()
699ac27a0ecSDave Kleikamp  * has generated enough buffer credits to do the whole page.  So we won't
700ac27a0ecSDave Kleikamp  * block on the journal in that case, which is good, because the caller may
701ac27a0ecSDave Kleikamp  * be PF_MEMALLOC.
702ac27a0ecSDave Kleikamp  *
703617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
704ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
705ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
706ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
707ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
708ac27a0ecSDave Kleikamp  * violation.
709ac27a0ecSDave Kleikamp  *
710dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
711ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
712ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
713ac27a0ecSDave Kleikamp  * write.
714ac27a0ecSDave Kleikamp  */
715ac27a0ecSDave Kleikamp static int do_journal_get_write_access(handle_t *handle,
716ac27a0ecSDave Kleikamp 				       struct buffer_head *bh)
717ac27a0ecSDave Kleikamp {
71856d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
71956d35a4cSJan Kara 	int ret;
72056d35a4cSJan Kara 
721ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
722ac27a0ecSDave Kleikamp 		return 0;
72356d35a4cSJan Kara 	/*
724ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
72556d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
72656d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
727ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
72856d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
72956d35a4cSJan Kara 	 * ever write the buffer.
73056d35a4cSJan Kara 	 */
73156d35a4cSJan Kara 	if (dirty)
73256d35a4cSJan Kara 		clear_buffer_dirty(bh);
73356d35a4cSJan Kara 	ret = ext4_journal_get_write_access(handle, bh);
73456d35a4cSJan Kara 	if (!ret && dirty)
73556d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
73656d35a4cSJan Kara 	return ret;
737ac27a0ecSDave Kleikamp }
738ac27a0ecSDave Kleikamp 
739744692dcSJiaying Zhang static int ext4_get_block_write(struct inode *inode, sector_t iblock,
740744692dcSJiaying Zhang 		   struct buffer_head *bh_result, int create);
741bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
742bfc1af65SNick Piggin 			    loff_t pos, unsigned len, unsigned flags,
743bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
744ac27a0ecSDave Kleikamp {
745bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
7461938a150SAneesh Kumar K.V 	int ret, needed_blocks;
747ac27a0ecSDave Kleikamp 	handle_t *handle;
748ac27a0ecSDave Kleikamp 	int retries = 0;
749bfc1af65SNick Piggin 	struct page *page;
750bfc1af65SNick Piggin 	pgoff_t index;
751bfc1af65SNick Piggin 	unsigned from, to;
752bfc1af65SNick Piggin 
7539bffad1eSTheodore Ts'o 	trace_ext4_write_begin(inode, pos, len, flags);
7541938a150SAneesh Kumar K.V 	/*
7551938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
7561938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
7571938a150SAneesh Kumar K.V 	 */
7581938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
759bfc1af65SNick Piggin 	index = pos >> PAGE_CACHE_SHIFT;
760bfc1af65SNick Piggin 	from = pos & (PAGE_CACHE_SIZE - 1);
761bfc1af65SNick Piggin 	to = from + len;
762ac27a0ecSDave Kleikamp 
763ac27a0ecSDave Kleikamp retry:
764617ba13bSMingming Cao 	handle = ext4_journal_start(inode, needed_blocks);
7657479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
7667479d2b9SAndrew Morton 		ret = PTR_ERR(handle);
7677479d2b9SAndrew Morton 		goto out;
7687479d2b9SAndrew Morton 	}
769ac27a0ecSDave Kleikamp 
770ebd3610bSJan Kara 	/* We cannot recurse into the filesystem as the transaction is already
771ebd3610bSJan Kara 	 * started */
772ebd3610bSJan Kara 	flags |= AOP_FLAG_NOFS;
773ebd3610bSJan Kara 
77454566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
775cf108bcaSJan Kara 	if (!page) {
776cf108bcaSJan Kara 		ext4_journal_stop(handle);
777cf108bcaSJan Kara 		ret = -ENOMEM;
778cf108bcaSJan Kara 		goto out;
779cf108bcaSJan Kara 	}
780cf108bcaSJan Kara 	*pagep = page;
781cf108bcaSJan Kara 
782744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
7836e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block_write);
784744692dcSJiaying Zhang 	else
7856e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
786bfc1af65SNick Piggin 
787bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
788ac27a0ecSDave Kleikamp 		ret = walk_page_buffers(handle, page_buffers(page),
789ac27a0ecSDave Kleikamp 				from, to, NULL, do_journal_get_write_access);
790b46be050SAndrey Savochkin 	}
791bfc1af65SNick Piggin 
792bfc1af65SNick Piggin 	if (ret) {
793bfc1af65SNick Piggin 		unlock_page(page);
794bfc1af65SNick Piggin 		page_cache_release(page);
795ae4d5372SAneesh Kumar K.V 		/*
7966e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
797ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
798ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
7991938a150SAneesh Kumar K.V 		 *
8001938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
8011938a150SAneesh Kumar K.V 		 * truncate finishes
802ae4d5372SAneesh Kumar K.V 		 */
803ffacfa7aSJan Kara 		if (pos + len > inode->i_size && ext4_can_truncate(inode))
8041938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
8051938a150SAneesh Kumar K.V 
8061938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
8071938a150SAneesh Kumar K.V 		if (pos + len > inode->i_size) {
808b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
8091938a150SAneesh Kumar K.V 			/*
810ffacfa7aSJan Kara 			 * If truncate failed early the inode might
8111938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
8121938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
8131938a150SAneesh Kumar K.V 			 * orphan list in that case.
8141938a150SAneesh Kumar K.V 			 */
8151938a150SAneesh Kumar K.V 			if (inode->i_nlink)
8161938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
8171938a150SAneesh Kumar K.V 		}
818bfc1af65SNick Piggin 	}
819bfc1af65SNick Piggin 
820617ba13bSMingming Cao 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
821ac27a0ecSDave Kleikamp 		goto retry;
8227479d2b9SAndrew Morton out:
823ac27a0ecSDave Kleikamp 	return ret;
824ac27a0ecSDave Kleikamp }
825ac27a0ecSDave Kleikamp 
826bfc1af65SNick Piggin /* For write_end() in data=journal mode */
827bfc1af65SNick Piggin static int write_end_fn(handle_t *handle, struct buffer_head *bh)
828ac27a0ecSDave Kleikamp {
829ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
830ac27a0ecSDave Kleikamp 		return 0;
831ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
8320390131bSFrank Mayhar 	return ext4_handle_dirty_metadata(handle, NULL, bh);
833ac27a0ecSDave Kleikamp }
834ac27a0ecSDave Kleikamp 
835f8514083SAneesh Kumar K.V static int ext4_generic_write_end(struct file *file,
836f8514083SAneesh Kumar K.V 				  struct address_space *mapping,
837f8514083SAneesh Kumar K.V 				  loff_t pos, unsigned len, unsigned copied,
838f8514083SAneesh Kumar K.V 				  struct page *page, void *fsdata)
839f8514083SAneesh Kumar K.V {
840f8514083SAneesh Kumar K.V 	int i_size_changed = 0;
841f8514083SAneesh Kumar K.V 	struct inode *inode = mapping->host;
842f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
843f8514083SAneesh Kumar K.V 
844f8514083SAneesh Kumar K.V 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
845f8514083SAneesh Kumar K.V 
846f8514083SAneesh Kumar K.V 	/*
847f8514083SAneesh Kumar K.V 	 * No need to use i_size_read() here, the i_size
848f8514083SAneesh Kumar K.V 	 * cannot change under us because we hold i_mutex.
849f8514083SAneesh Kumar K.V 	 *
850f8514083SAneesh Kumar K.V 	 * But it's important to update i_size while still holding page lock:
851f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
852f8514083SAneesh Kumar K.V 	 */
853f8514083SAneesh Kumar K.V 	if (pos + copied > inode->i_size) {
854f8514083SAneesh Kumar K.V 		i_size_write(inode, pos + copied);
855f8514083SAneesh Kumar K.V 		i_size_changed = 1;
856f8514083SAneesh Kumar K.V 	}
857f8514083SAneesh Kumar K.V 
858f8514083SAneesh Kumar K.V 	if (pos + copied >  EXT4_I(inode)->i_disksize) {
859f8514083SAneesh Kumar K.V 		/* We need to mark inode dirty even if
860f8514083SAneesh Kumar K.V 		 * new_i_size is less that inode->i_size
861f8514083SAneesh Kumar K.V 		 * bu greater than i_disksize.(hint delalloc)
862f8514083SAneesh Kumar K.V 		 */
863f8514083SAneesh Kumar K.V 		ext4_update_i_disksize(inode, (pos + copied));
864f8514083SAneesh Kumar K.V 		i_size_changed = 1;
865f8514083SAneesh Kumar K.V 	}
866f8514083SAneesh Kumar K.V 	unlock_page(page);
867f8514083SAneesh Kumar K.V 	page_cache_release(page);
868f8514083SAneesh Kumar K.V 
869f8514083SAneesh Kumar K.V 	/*
870f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
871f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
872f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
873f8514083SAneesh Kumar K.V 	 * filesystems.
874f8514083SAneesh Kumar K.V 	 */
875f8514083SAneesh Kumar K.V 	if (i_size_changed)
876f8514083SAneesh Kumar K.V 		ext4_mark_inode_dirty(handle, inode);
877f8514083SAneesh Kumar K.V 
878f8514083SAneesh Kumar K.V 	return copied;
879f8514083SAneesh Kumar K.V }
880f8514083SAneesh Kumar K.V 
881ac27a0ecSDave Kleikamp /*
882ac27a0ecSDave Kleikamp  * We need to pick up the new inode size which generic_commit_write gave us
883ac27a0ecSDave Kleikamp  * `file' can be NULL - eg, when called from page_symlink().
884ac27a0ecSDave Kleikamp  *
885617ba13bSMingming Cao  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
886ac27a0ecSDave Kleikamp  * buffers are managed internally.
887ac27a0ecSDave Kleikamp  */
888bfc1af65SNick Piggin static int ext4_ordered_write_end(struct file *file,
889bfc1af65SNick Piggin 				  struct address_space *mapping,
890bfc1af65SNick Piggin 				  loff_t pos, unsigned len, unsigned copied,
891bfc1af65SNick Piggin 				  struct page *page, void *fsdata)
892ac27a0ecSDave Kleikamp {
893617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
894cf108bcaSJan Kara 	struct inode *inode = mapping->host;
895ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
896ac27a0ecSDave Kleikamp 
8979bffad1eSTheodore Ts'o 	trace_ext4_ordered_write_end(inode, pos, len, copied);
898678aaf48SJan Kara 	ret = ext4_jbd2_file_inode(handle, inode);
899ac27a0ecSDave Kleikamp 
900ac27a0ecSDave Kleikamp 	if (ret == 0) {
901f8514083SAneesh Kumar K.V 		ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
902bfc1af65SNick Piggin 							page, fsdata);
903f8a87d89SRoel Kluin 		copied = ret2;
904ffacfa7aSJan Kara 		if (pos + len > inode->i_size && ext4_can_truncate(inode))
905f8514083SAneesh Kumar K.V 			/* if we have allocated more blocks and copied
906f8514083SAneesh Kumar K.V 			 * less. We will have blocks allocated outside
907f8514083SAneesh Kumar K.V 			 * inode->i_size. So truncate them
908f8514083SAneesh Kumar K.V 			 */
909f8514083SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
910f8a87d89SRoel Kluin 		if (ret2 < 0)
911f8a87d89SRoel Kluin 			ret = ret2;
912ac27a0ecSDave Kleikamp 	}
913617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
914ac27a0ecSDave Kleikamp 	if (!ret)
915ac27a0ecSDave Kleikamp 		ret = ret2;
916bfc1af65SNick Piggin 
917f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
918b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
919f8514083SAneesh Kumar K.V 		/*
920ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
921f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
922f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
923f8514083SAneesh Kumar K.V 		 */
924f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
925f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
926f8514083SAneesh Kumar K.V 	}
927f8514083SAneesh Kumar K.V 
928f8514083SAneesh Kumar K.V 
929bfc1af65SNick Piggin 	return ret ? ret : copied;
930ac27a0ecSDave Kleikamp }
931ac27a0ecSDave Kleikamp 
932bfc1af65SNick Piggin static int ext4_writeback_write_end(struct file *file,
933bfc1af65SNick Piggin 				    struct address_space *mapping,
934bfc1af65SNick Piggin 				    loff_t pos, unsigned len, unsigned copied,
935bfc1af65SNick Piggin 				    struct page *page, void *fsdata)
936ac27a0ecSDave Kleikamp {
937617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
938cf108bcaSJan Kara 	struct inode *inode = mapping->host;
939ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
940ac27a0ecSDave Kleikamp 
9419bffad1eSTheodore Ts'o 	trace_ext4_writeback_write_end(inode, pos, len, copied);
942f8514083SAneesh Kumar K.V 	ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
943bfc1af65SNick Piggin 							page, fsdata);
944f8a87d89SRoel Kluin 	copied = ret2;
945ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
946f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
947f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
948f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
949f8514083SAneesh Kumar K.V 		 */
950f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
951f8514083SAneesh Kumar K.V 
952f8a87d89SRoel Kluin 	if (ret2 < 0)
953f8a87d89SRoel Kluin 		ret = ret2;
954ac27a0ecSDave Kleikamp 
955617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
956ac27a0ecSDave Kleikamp 	if (!ret)
957ac27a0ecSDave Kleikamp 		ret = ret2;
958bfc1af65SNick Piggin 
959f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
960b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
961f8514083SAneesh Kumar K.V 		/*
962ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
963f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
964f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
965f8514083SAneesh Kumar K.V 		 */
966f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
967f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
968f8514083SAneesh Kumar K.V 	}
969f8514083SAneesh Kumar K.V 
970bfc1af65SNick Piggin 	return ret ? ret : copied;
971ac27a0ecSDave Kleikamp }
972ac27a0ecSDave Kleikamp 
973bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
974bfc1af65SNick Piggin 				     struct address_space *mapping,
975bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
976bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
977ac27a0ecSDave Kleikamp {
978617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
979bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
980ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
981ac27a0ecSDave Kleikamp 	int partial = 0;
982bfc1af65SNick Piggin 	unsigned from, to;
983cf17fea6SAneesh Kumar K.V 	loff_t new_i_size;
984ac27a0ecSDave Kleikamp 
9859bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
986bfc1af65SNick Piggin 	from = pos & (PAGE_CACHE_SIZE - 1);
987bfc1af65SNick Piggin 	to = from + len;
988bfc1af65SNick Piggin 
989441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
990441c8508SCurt Wohlgemuth 
991bfc1af65SNick Piggin 	if (copied < len) {
992bfc1af65SNick Piggin 		if (!PageUptodate(page))
993bfc1af65SNick Piggin 			copied = 0;
994bfc1af65SNick Piggin 		page_zero_new_buffers(page, from+copied, to);
995bfc1af65SNick Piggin 	}
996ac27a0ecSDave Kleikamp 
997ac27a0ecSDave Kleikamp 	ret = walk_page_buffers(handle, page_buffers(page), from,
998bfc1af65SNick Piggin 				to, &partial, write_end_fn);
999ac27a0ecSDave Kleikamp 	if (!partial)
1000ac27a0ecSDave Kleikamp 		SetPageUptodate(page);
1001cf17fea6SAneesh Kumar K.V 	new_i_size = pos + copied;
1002cf17fea6SAneesh Kumar K.V 	if (new_i_size > inode->i_size)
1003bfc1af65SNick Piggin 		i_size_write(inode, pos+copied);
100419f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
10052d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1006cf17fea6SAneesh Kumar K.V 	if (new_i_size > EXT4_I(inode)->i_disksize) {
1007cf17fea6SAneesh Kumar K.V 		ext4_update_i_disksize(inode, new_i_size);
1008617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1009ac27a0ecSDave Kleikamp 		if (!ret)
1010ac27a0ecSDave Kleikamp 			ret = ret2;
1011ac27a0ecSDave Kleikamp 	}
1012bfc1af65SNick Piggin 
1013cf108bcaSJan Kara 	unlock_page(page);
1014f8514083SAneesh Kumar K.V 	page_cache_release(page);
1015ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
1016f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1017f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1018f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1019f8514083SAneesh Kumar K.V 		 */
1020f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1021f8514083SAneesh Kumar K.V 
1022617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1023ac27a0ecSDave Kleikamp 	if (!ret)
1024ac27a0ecSDave Kleikamp 		ret = ret2;
1025f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1026b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1027f8514083SAneesh Kumar K.V 		/*
1028ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1029f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1030f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1031f8514083SAneesh Kumar K.V 		 */
1032f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1033f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1034f8514083SAneesh Kumar K.V 	}
1035bfc1af65SNick Piggin 
1036bfc1af65SNick Piggin 	return ret ? ret : copied;
1037ac27a0ecSDave Kleikamp }
1038d2a17637SMingming Cao 
10399d0be502STheodore Ts'o /*
10409d0be502STheodore Ts'o  * Reserve a single block located at lblock
10419d0be502STheodore Ts'o  */
104201f49d0bSTheodore Ts'o static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1043d2a17637SMingming Cao {
1044030ba6bcSAneesh Kumar K.V 	int retries = 0;
1045d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
10460637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
104772b8ab9dSEric Sandeen 	unsigned long md_needed;
10485dd4056dSChristoph Hellwig 	int ret;
1049d2a17637SMingming Cao 
1050d2a17637SMingming Cao 	/*
1051d2a17637SMingming Cao 	 * recalculate the amount of metadata blocks to reserve
1052d2a17637SMingming Cao 	 * in order to allocate nrblocks
1053d2a17637SMingming Cao 	 * worse case is one extent per block
1054d2a17637SMingming Cao 	 */
1055030ba6bcSAneesh Kumar K.V repeat:
10560637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
10579d0be502STheodore Ts'o 	md_needed = ext4_calc_metadata_amount(inode, lblock);
1058f8ec9d68STheodore Ts'o 	trace_ext4_da_reserve_space(inode, md_needed);
10590637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
1060d2a17637SMingming Cao 
106160e58e0fSMingming Cao 	/*
106272b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
106372b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
106472b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
106560e58e0fSMingming Cao 	 */
106672b8ab9dSEric Sandeen 	ret = dquot_reserve_block(inode, 1);
10675dd4056dSChristoph Hellwig 	if (ret)
10685dd4056dSChristoph Hellwig 		return ret;
106972b8ab9dSEric Sandeen 	/*
107072b8ab9dSEric Sandeen 	 * We do still charge estimated metadata to the sb though;
107172b8ab9dSEric Sandeen 	 * we cannot afford to run out of free blocks.
107272b8ab9dSEric Sandeen 	 */
107355f020dbSAllison Henderson 	if (ext4_claim_free_blocks(sbi, md_needed + 1, 0)) {
107472b8ab9dSEric Sandeen 		dquot_release_reservation_block(inode, 1);
1075030ba6bcSAneesh Kumar K.V 		if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1076030ba6bcSAneesh Kumar K.V 			yield();
1077030ba6bcSAneesh Kumar K.V 			goto repeat;
1078030ba6bcSAneesh Kumar K.V 		}
1079d2a17637SMingming Cao 		return -ENOSPC;
1080d2a17637SMingming Cao 	}
10810637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
10829d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
10830637c6f4STheodore Ts'o 	ei->i_reserved_meta_blocks += md_needed;
10840637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
108539bc680aSDmitry Monakhov 
1086d2a17637SMingming Cao 	return 0;       /* success */
1087d2a17637SMingming Cao }
1088d2a17637SMingming Cao 
108912219aeaSAneesh Kumar K.V static void ext4_da_release_space(struct inode *inode, int to_free)
1090d2a17637SMingming Cao {
1091d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
10920637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1093d2a17637SMingming Cao 
1094cd213226SMingming Cao 	if (!to_free)
1095cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1096cd213226SMingming Cao 
1097d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1098cd213226SMingming Cao 
10995a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
11000637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1101cd213226SMingming Cao 		/*
11020637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
11030637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
11040637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
11050637c6f4STheodore Ts'o 		 * harmless to return without any action.
1106cd213226SMingming Cao 		 */
11070637c6f4STheodore Ts'o 		ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
11080637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
11090637c6f4STheodore Ts'o 			 "data blocks\n", inode->i_ino, to_free,
11100637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
11110637c6f4STheodore Ts'o 		WARN_ON(1);
11120637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
11130637c6f4STheodore Ts'o 	}
11140637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
11150637c6f4STheodore Ts'o 
11160637c6f4STheodore Ts'o 	if (ei->i_reserved_data_blocks == 0) {
11170637c6f4STheodore Ts'o 		/*
11180637c6f4STheodore Ts'o 		 * We can release all of the reserved metadata blocks
11190637c6f4STheodore Ts'o 		 * only when we have written all of the delayed
11200637c6f4STheodore Ts'o 		 * allocation blocks.
11210637c6f4STheodore Ts'o 		 */
1122*57042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
112372b8ab9dSEric Sandeen 				   ei->i_reserved_meta_blocks);
1124ee5f4d9cSTheodore Ts'o 		ei->i_reserved_meta_blocks = 0;
11259d0be502STheodore Ts'o 		ei->i_da_metadata_calc_len = 0;
1126cd213226SMingming Cao 	}
1127cd213226SMingming Cao 
112872b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
1129*57042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1130d2a17637SMingming Cao 
1131d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
113260e58e0fSMingming Cao 
11335dd4056dSChristoph Hellwig 	dquot_release_reservation_block(inode, to_free);
1134d2a17637SMingming Cao }
1135d2a17637SMingming Cao 
1136d2a17637SMingming Cao static void ext4_da_page_release_reservation(struct page *page,
1137d2a17637SMingming Cao 					     unsigned long offset)
1138d2a17637SMingming Cao {
1139d2a17637SMingming Cao 	int to_release = 0;
1140d2a17637SMingming Cao 	struct buffer_head *head, *bh;
1141d2a17637SMingming Cao 	unsigned int curr_off = 0;
1142d2a17637SMingming Cao 
1143d2a17637SMingming Cao 	head = page_buffers(page);
1144d2a17637SMingming Cao 	bh = head;
1145d2a17637SMingming Cao 	do {
1146d2a17637SMingming Cao 		unsigned int next_off = curr_off + bh->b_size;
1147d2a17637SMingming Cao 
1148d2a17637SMingming Cao 		if ((offset <= curr_off) && (buffer_delay(bh))) {
1149d2a17637SMingming Cao 			to_release++;
1150d2a17637SMingming Cao 			clear_buffer_delay(bh);
1151d2a17637SMingming Cao 		}
1152d2a17637SMingming Cao 		curr_off = next_off;
1153d2a17637SMingming Cao 	} while ((bh = bh->b_this_page) != head);
115412219aeaSAneesh Kumar K.V 	ext4_da_release_space(page->mapping->host, to_release);
1155d2a17637SMingming Cao }
1156ac27a0ecSDave Kleikamp 
1157ac27a0ecSDave Kleikamp /*
115864769240SAlex Tomas  * Delayed allocation stuff
115964769240SAlex Tomas  */
116064769240SAlex Tomas 
116164769240SAlex Tomas /*
116264769240SAlex Tomas  * mpage_da_submit_io - walks through extent of pages and try to write
1163a1d6cc56SAneesh Kumar K.V  * them with writepage() call back
116464769240SAlex Tomas  *
116564769240SAlex Tomas  * @mpd->inode: inode
116664769240SAlex Tomas  * @mpd->first_page: first page of the extent
116764769240SAlex Tomas  * @mpd->next_page: page after the last page of the extent
116864769240SAlex Tomas  *
116964769240SAlex Tomas  * By the time mpage_da_submit_io() is called we expect all blocks
117064769240SAlex Tomas  * to be allocated. this may be wrong if allocation failed.
117164769240SAlex Tomas  *
117264769240SAlex Tomas  * As pages are already locked by write_cache_pages(), we can't use it
117364769240SAlex Tomas  */
11741de3e3dfSTheodore Ts'o static int mpage_da_submit_io(struct mpage_da_data *mpd,
11751de3e3dfSTheodore Ts'o 			      struct ext4_map_blocks *map)
117664769240SAlex Tomas {
1177791b7f08SAneesh Kumar K.V 	struct pagevec pvec;
1178791b7f08SAneesh Kumar K.V 	unsigned long index, end;
1179791b7f08SAneesh Kumar K.V 	int ret = 0, err, nr_pages, i;
1180791b7f08SAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1181791b7f08SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
1182cb20d518STheodore Ts'o 	loff_t size = i_size_read(inode);
11833ecdb3a1STheodore Ts'o 	unsigned int len, block_start;
11843ecdb3a1STheodore Ts'o 	struct buffer_head *bh, *page_bufs = NULL;
1185cb20d518STheodore Ts'o 	int journal_data = ext4_should_journal_data(inode);
11861de3e3dfSTheodore Ts'o 	sector_t pblock = 0, cur_logical = 0;
1187bd2d0210STheodore Ts'o 	struct ext4_io_submit io_submit;
118864769240SAlex Tomas 
118964769240SAlex Tomas 	BUG_ON(mpd->next_page <= mpd->first_page);
1190bd2d0210STheodore Ts'o 	memset(&io_submit, 0, sizeof(io_submit));
1191791b7f08SAneesh Kumar K.V 	/*
1192791b7f08SAneesh Kumar K.V 	 * We need to start from the first_page to the next_page - 1
1193791b7f08SAneesh Kumar K.V 	 * to make sure we also write the mapped dirty buffer_heads.
11948dc207c0STheodore Ts'o 	 * If we look at mpd->b_blocknr we would only be looking
1195791b7f08SAneesh Kumar K.V 	 * at the currently mapped buffer_heads.
1196791b7f08SAneesh Kumar K.V 	 */
119764769240SAlex Tomas 	index = mpd->first_page;
119864769240SAlex Tomas 	end = mpd->next_page - 1;
119964769240SAlex Tomas 
1200791b7f08SAneesh Kumar K.V 	pagevec_init(&pvec, 0);
120164769240SAlex Tomas 	while (index <= end) {
1202791b7f08SAneesh Kumar K.V 		nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
120364769240SAlex Tomas 		if (nr_pages == 0)
120464769240SAlex Tomas 			break;
120564769240SAlex Tomas 		for (i = 0; i < nr_pages; i++) {
120697498956STheodore Ts'o 			int commit_write = 0, skip_page = 0;
120764769240SAlex Tomas 			struct page *page = pvec.pages[i];
120864769240SAlex Tomas 
1209791b7f08SAneesh Kumar K.V 			index = page->index;
1210791b7f08SAneesh Kumar K.V 			if (index > end)
1211791b7f08SAneesh Kumar K.V 				break;
1212cb20d518STheodore Ts'o 
1213cb20d518STheodore Ts'o 			if (index == size >> PAGE_CACHE_SHIFT)
1214cb20d518STheodore Ts'o 				len = size & ~PAGE_CACHE_MASK;
1215cb20d518STheodore Ts'o 			else
1216cb20d518STheodore Ts'o 				len = PAGE_CACHE_SIZE;
12171de3e3dfSTheodore Ts'o 			if (map) {
12181de3e3dfSTheodore Ts'o 				cur_logical = index << (PAGE_CACHE_SHIFT -
12191de3e3dfSTheodore Ts'o 							inode->i_blkbits);
12201de3e3dfSTheodore Ts'o 				pblock = map->m_pblk + (cur_logical -
12211de3e3dfSTheodore Ts'o 							map->m_lblk);
12221de3e3dfSTheodore Ts'o 			}
1223791b7f08SAneesh Kumar K.V 			index++;
1224791b7f08SAneesh Kumar K.V 
1225791b7f08SAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
1226791b7f08SAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
1227791b7f08SAneesh Kumar K.V 
122822208dedSAneesh Kumar K.V 			/*
1229cb20d518STheodore Ts'o 			 * If the page does not have buffers (for
1230cb20d518STheodore Ts'o 			 * whatever reason), try to create them using
1231a107e5a3STheodore Ts'o 			 * __block_write_begin.  If this fails,
123297498956STheodore Ts'o 			 * skip the page and move on.
123322208dedSAneesh Kumar K.V 			 */
1234cb20d518STheodore Ts'o 			if (!page_has_buffers(page)) {
1235a107e5a3STheodore Ts'o 				if (__block_write_begin(page, 0, len,
1236cb20d518STheodore Ts'o 						noalloc_get_block_write)) {
123797498956STheodore Ts'o 				skip_page:
1238cb20d518STheodore Ts'o 					unlock_page(page);
1239cb20d518STheodore Ts'o 					continue;
1240cb20d518STheodore Ts'o 				}
1241cb20d518STheodore Ts'o 				commit_write = 1;
1242cb20d518STheodore Ts'o 			}
12433ecdb3a1STheodore Ts'o 
12443ecdb3a1STheodore Ts'o 			bh = page_bufs = page_buffers(page);
12453ecdb3a1STheodore Ts'o 			block_start = 0;
12463ecdb3a1STheodore Ts'o 			do {
12471de3e3dfSTheodore Ts'o 				if (!bh)
124897498956STheodore Ts'o 					goto skip_page;
12491de3e3dfSTheodore Ts'o 				if (map && (cur_logical >= map->m_lblk) &&
12501de3e3dfSTheodore Ts'o 				    (cur_logical <= (map->m_lblk +
12511de3e3dfSTheodore Ts'o 						     (map->m_len - 1)))) {
12521de3e3dfSTheodore Ts'o 					if (buffer_delay(bh)) {
12531de3e3dfSTheodore Ts'o 						clear_buffer_delay(bh);
12541de3e3dfSTheodore Ts'o 						bh->b_blocknr = pblock;
12551de3e3dfSTheodore Ts'o 					}
12561de3e3dfSTheodore Ts'o 					if (buffer_unwritten(bh) ||
12571de3e3dfSTheodore Ts'o 					    buffer_mapped(bh))
12581de3e3dfSTheodore Ts'o 						BUG_ON(bh->b_blocknr != pblock);
12591de3e3dfSTheodore Ts'o 					if (map->m_flags & EXT4_MAP_UNINIT)
12601de3e3dfSTheodore Ts'o 						set_buffer_uninit(bh);
12611de3e3dfSTheodore Ts'o 					clear_buffer_unwritten(bh);
12621de3e3dfSTheodore Ts'o 				}
12631de3e3dfSTheodore Ts'o 
126497498956STheodore Ts'o 				/* skip page if block allocation undone */
12651de3e3dfSTheodore Ts'o 				if (buffer_delay(bh) || buffer_unwritten(bh))
126697498956STheodore Ts'o 					skip_page = 1;
12673ecdb3a1STheodore Ts'o 				bh = bh->b_this_page;
12683ecdb3a1STheodore Ts'o 				block_start += bh->b_size;
12691de3e3dfSTheodore Ts'o 				cur_logical++;
12701de3e3dfSTheodore Ts'o 				pblock++;
12711de3e3dfSTheodore Ts'o 			} while (bh != page_bufs);
12721de3e3dfSTheodore Ts'o 
127397498956STheodore Ts'o 			if (skip_page)
127497498956STheodore Ts'o 				goto skip_page;
1275cb20d518STheodore Ts'o 
1276cb20d518STheodore Ts'o 			if (commit_write)
1277cb20d518STheodore Ts'o 				/* mark the buffer_heads as dirty & uptodate */
1278cb20d518STheodore Ts'o 				block_commit_write(page, 0, len);
1279cb20d518STheodore Ts'o 
128097498956STheodore Ts'o 			clear_page_dirty_for_io(page);
1281bd2d0210STheodore Ts'o 			/*
1282bd2d0210STheodore Ts'o 			 * Delalloc doesn't support data journalling,
1283bd2d0210STheodore Ts'o 			 * but eventually maybe we'll lift this
1284bd2d0210STheodore Ts'o 			 * restriction.
1285bd2d0210STheodore Ts'o 			 */
1286bd2d0210STheodore Ts'o 			if (unlikely(journal_data && PageChecked(page)))
1287cb20d518STheodore Ts'o 				err = __ext4_journalled_writepage(page, len);
12881449032bSTheodore Ts'o 			else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
1289bd2d0210STheodore Ts'o 				err = ext4_bio_write_page(&io_submit, page,
1290bd2d0210STheodore Ts'o 							  len, mpd->wbc);
12919dd75f1fSTheodore Ts'o 			else if (buffer_uninit(page_bufs)) {
12929dd75f1fSTheodore Ts'o 				ext4_set_bh_endio(page_bufs, inode);
12939dd75f1fSTheodore Ts'o 				err = block_write_full_page_endio(page,
12949dd75f1fSTheodore Ts'o 					noalloc_get_block_write,
12959dd75f1fSTheodore Ts'o 					mpd->wbc, ext4_end_io_buffer_write);
12969dd75f1fSTheodore Ts'o 			} else
12971449032bSTheodore Ts'o 				err = block_write_full_page(page,
12981449032bSTheodore Ts'o 					noalloc_get_block_write, mpd->wbc);
1299cb20d518STheodore Ts'o 
1300cb20d518STheodore Ts'o 			if (!err)
1301a1d6cc56SAneesh Kumar K.V 				mpd->pages_written++;
130264769240SAlex Tomas 			/*
130364769240SAlex Tomas 			 * In error case, we have to continue because
130464769240SAlex Tomas 			 * remaining pages are still locked
130564769240SAlex Tomas 			 */
130664769240SAlex Tomas 			if (ret == 0)
130764769240SAlex Tomas 				ret = err;
130864769240SAlex Tomas 		}
130964769240SAlex Tomas 		pagevec_release(&pvec);
131064769240SAlex Tomas 	}
1311bd2d0210STheodore Ts'o 	ext4_io_submit(&io_submit);
131264769240SAlex Tomas 	return ret;
131364769240SAlex Tomas }
131464769240SAlex Tomas 
1315c7f5938aSCurt Wohlgemuth static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1316c4a0c46eSAneesh Kumar K.V {
1317c4a0c46eSAneesh Kumar K.V 	int nr_pages, i;
1318c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1319c4a0c46eSAneesh Kumar K.V 	struct pagevec pvec;
1320c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1321c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
1322c4a0c46eSAneesh Kumar K.V 
1323c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1324c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
1325c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1326c4a0c46eSAneesh Kumar K.V 		nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1327c4a0c46eSAneesh Kumar K.V 		if (nr_pages == 0)
1328c4a0c46eSAneesh Kumar K.V 			break;
1329c4a0c46eSAneesh Kumar K.V 		for (i = 0; i < nr_pages; i++) {
1330c4a0c46eSAneesh Kumar K.V 			struct page *page = pvec.pages[i];
13319b1d0998SJan Kara 			if (page->index > end)
1332c4a0c46eSAneesh Kumar K.V 				break;
1333c4a0c46eSAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
1334c4a0c46eSAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
1335c4a0c46eSAneesh Kumar K.V 			block_invalidatepage(page, 0);
1336c4a0c46eSAneesh Kumar K.V 			ClearPageUptodate(page);
1337c4a0c46eSAneesh Kumar K.V 			unlock_page(page);
1338c4a0c46eSAneesh Kumar K.V 		}
13399b1d0998SJan Kara 		index = pvec.pages[nr_pages - 1]->index + 1;
13409b1d0998SJan Kara 		pagevec_release(&pvec);
1341c4a0c46eSAneesh Kumar K.V 	}
1342c4a0c46eSAneesh Kumar K.V 	return;
1343c4a0c46eSAneesh Kumar K.V }
1344c4a0c46eSAneesh Kumar K.V 
1345df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1346df22291fSAneesh Kumar K.V {
1347df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
13481693918eSTheodore Ts'o 	printk(KERN_CRIT "Total free blocks count %lld\n",
1349df22291fSAneesh Kumar K.V 	       ext4_count_free_blocks(inode->i_sb));
13501693918eSTheodore Ts'o 	printk(KERN_CRIT "Free/Dirty block details\n");
13511693918eSTheodore Ts'o 	printk(KERN_CRIT "free_blocks=%lld\n",
1352*57042651STheodore Ts'o 	       (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1353*57042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
13541693918eSTheodore Ts'o 	printk(KERN_CRIT "dirty_blocks=%lld\n",
1355*57042651STheodore Ts'o 	       (long long) percpu_counter_sum(&sbi->s_dirtyclusters_counter));
13561693918eSTheodore Ts'o 	printk(KERN_CRIT "Block reservation details\n");
13571693918eSTheodore Ts'o 	printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
1358df22291fSAneesh Kumar K.V 	       EXT4_I(inode)->i_reserved_data_blocks);
13591693918eSTheodore Ts'o 	printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
1360df22291fSAneesh Kumar K.V 	       EXT4_I(inode)->i_reserved_meta_blocks);
1361df22291fSAneesh Kumar K.V 	return;
1362df22291fSAneesh Kumar K.V }
1363df22291fSAneesh Kumar K.V 
1364b920c755STheodore Ts'o /*
13655a87b7a5STheodore Ts'o  * mpage_da_map_and_submit - go through given space, map them
13665a87b7a5STheodore Ts'o  *       if necessary, and then submit them for I/O
136764769240SAlex Tomas  *
13688dc207c0STheodore Ts'o  * @mpd - bh describing space
136964769240SAlex Tomas  *
137064769240SAlex Tomas  * The function skips space we know is already mapped to disk blocks.
137164769240SAlex Tomas  *
137264769240SAlex Tomas  */
13735a87b7a5STheodore Ts'o static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
137464769240SAlex Tomas {
13752ac3b6e0STheodore Ts'o 	int err, blks, get_blocks_flags;
13761de3e3dfSTheodore Ts'o 	struct ext4_map_blocks map, *mapp = NULL;
13772fa3cdfbSTheodore Ts'o 	sector_t next = mpd->b_blocknr;
13782fa3cdfbSTheodore Ts'o 	unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
13792fa3cdfbSTheodore Ts'o 	loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
13802fa3cdfbSTheodore Ts'o 	handle_t *handle = NULL;
138164769240SAlex Tomas 
138264769240SAlex Tomas 	/*
13835a87b7a5STheodore Ts'o 	 * If the blocks are mapped already, or we couldn't accumulate
13845a87b7a5STheodore Ts'o 	 * any blocks, then proceed immediately to the submission stage.
138564769240SAlex Tomas 	 */
13865a87b7a5STheodore Ts'o 	if ((mpd->b_size == 0) ||
13875a87b7a5STheodore Ts'o 	    ((mpd->b_state  & (1 << BH_Mapped)) &&
138829fa89d0SAneesh Kumar K.V 	     !(mpd->b_state & (1 << BH_Delay)) &&
13895a87b7a5STheodore Ts'o 	     !(mpd->b_state & (1 << BH_Unwritten))))
13905a87b7a5STheodore Ts'o 		goto submit_io;
13912fa3cdfbSTheodore Ts'o 
13922fa3cdfbSTheodore Ts'o 	handle = ext4_journal_current_handle();
13932fa3cdfbSTheodore Ts'o 	BUG_ON(!handle);
13942fa3cdfbSTheodore Ts'o 
139579ffab34SAneesh Kumar K.V 	/*
139679e83036SEric Sandeen 	 * Call ext4_map_blocks() to allocate any delayed allocation
13972ac3b6e0STheodore Ts'o 	 * blocks, or to convert an uninitialized extent to be
13982ac3b6e0STheodore Ts'o 	 * initialized (in the case where we have written into
13992ac3b6e0STheodore Ts'o 	 * one or more preallocated blocks).
14002ac3b6e0STheodore Ts'o 	 *
14012ac3b6e0STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
14022ac3b6e0STheodore Ts'o 	 * indicate that we are on the delayed allocation path.  This
14032ac3b6e0STheodore Ts'o 	 * affects functions in many different parts of the allocation
14042ac3b6e0STheodore Ts'o 	 * call path.  This flag exists primarily because we don't
140579e83036SEric Sandeen 	 * want to change *many* call functions, so ext4_map_blocks()
1406f2321097STheodore Ts'o 	 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
14072ac3b6e0STheodore Ts'o 	 * inode's allocation semaphore is taken.
14082ac3b6e0STheodore Ts'o 	 *
14092ac3b6e0STheodore Ts'o 	 * If the blocks in questions were delalloc blocks, set
14102ac3b6e0STheodore Ts'o 	 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
14112ac3b6e0STheodore Ts'o 	 * variables are updated after the blocks have been allocated.
141279ffab34SAneesh Kumar K.V 	 */
14132ed88685STheodore Ts'o 	map.m_lblk = next;
14142ed88685STheodore Ts'o 	map.m_len = max_blocks;
14151296cc85SAneesh Kumar K.V 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1416744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(mpd->inode))
1417744692dcSJiaying Zhang 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
14182ac3b6e0STheodore Ts'o 	if (mpd->b_state & (1 << BH_Delay))
14191296cc85SAneesh Kumar K.V 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
14201296cc85SAneesh Kumar K.V 
14212ed88685STheodore Ts'o 	blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
14222fa3cdfbSTheodore Ts'o 	if (blks < 0) {
1423e3570639SEric Sandeen 		struct super_block *sb = mpd->inode->i_sb;
1424e3570639SEric Sandeen 
14252fa3cdfbSTheodore Ts'o 		err = blks;
1426ed5bde0bSTheodore Ts'o 		/*
14275a87b7a5STheodore Ts'o 		 * If get block returns EAGAIN or ENOSPC and there
142897498956STheodore Ts'o 		 * appears to be free blocks we will just let
142997498956STheodore Ts'o 		 * mpage_da_submit_io() unlock all of the pages.
1430c4a0c46eSAneesh Kumar K.V 		 */
1431c4a0c46eSAneesh Kumar K.V 		if (err == -EAGAIN)
14325a87b7a5STheodore Ts'o 			goto submit_io;
1433df22291fSAneesh Kumar K.V 
1434df22291fSAneesh Kumar K.V 		if (err == -ENOSPC &&
1435e3570639SEric Sandeen 		    ext4_count_free_blocks(sb)) {
1436df22291fSAneesh Kumar K.V 			mpd->retval = err;
14375a87b7a5STheodore Ts'o 			goto submit_io;
1438df22291fSAneesh Kumar K.V 		}
1439df22291fSAneesh Kumar K.V 
1440c4a0c46eSAneesh Kumar K.V 		/*
1441ed5bde0bSTheodore Ts'o 		 * get block failure will cause us to loop in
1442ed5bde0bSTheodore Ts'o 		 * writepages, because a_ops->writepage won't be able
1443ed5bde0bSTheodore Ts'o 		 * to make progress. The page will be redirtied by
1444ed5bde0bSTheodore Ts'o 		 * writepage and writepages will again try to write
1445ed5bde0bSTheodore Ts'o 		 * the same.
1446c4a0c46eSAneesh Kumar K.V 		 */
1447e3570639SEric Sandeen 		if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1448e3570639SEric Sandeen 			ext4_msg(sb, KERN_CRIT,
1449e3570639SEric Sandeen 				 "delayed block allocation failed for inode %lu "
1450e3570639SEric Sandeen 				 "at logical offset %llu with max blocks %zd "
1451e3570639SEric Sandeen 				 "with error %d", mpd->inode->i_ino,
1452c4a0c46eSAneesh Kumar K.V 				 (unsigned long long) next,
14538dc207c0STheodore Ts'o 				 mpd->b_size >> mpd->inode->i_blkbits, err);
1454e3570639SEric Sandeen 			ext4_msg(sb, KERN_CRIT,
1455e3570639SEric Sandeen 				"This should not happen!! Data will be lost\n");
1456e3570639SEric Sandeen 			if (err == -ENOSPC)
1457df22291fSAneesh Kumar K.V 				ext4_print_free_blocks(mpd->inode);
1458030ba6bcSAneesh Kumar K.V 		}
14592fa3cdfbSTheodore Ts'o 		/* invalidate all the pages */
1460c7f5938aSCurt Wohlgemuth 		ext4_da_block_invalidatepages(mpd);
1461e0fd9b90SCurt Wohlgemuth 
1462e0fd9b90SCurt Wohlgemuth 		/* Mark this page range as having been completed */
1463e0fd9b90SCurt Wohlgemuth 		mpd->io_done = 1;
14645a87b7a5STheodore Ts'o 		return;
1465c4a0c46eSAneesh Kumar K.V 	}
14662fa3cdfbSTheodore Ts'o 	BUG_ON(blks == 0);
14672fa3cdfbSTheodore Ts'o 
14681de3e3dfSTheodore Ts'o 	mapp = &map;
14692ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
14702ed88685STheodore Ts'o 		struct block_device *bdev = mpd->inode->i_sb->s_bdev;
14712ed88685STheodore Ts'o 		int i;
147264769240SAlex Tomas 
14732ed88685STheodore Ts'o 		for (i = 0; i < map.m_len; i++)
14742ed88685STheodore Ts'o 			unmap_underlying_metadata(bdev, map.m_pblk + i);
147564769240SAlex Tomas 
14762fa3cdfbSTheodore Ts'o 		if (ext4_should_order_data(mpd->inode)) {
14772fa3cdfbSTheodore Ts'o 			err = ext4_jbd2_file_inode(handle, mpd->inode);
14782fa3cdfbSTheodore Ts'o 			if (err)
1479decbd919STheodore Ts'o 				/* Only if the journal is aborted */
14805a87b7a5STheodore Ts'o 				return;
14812fa3cdfbSTheodore Ts'o 		}
1482decbd919STheodore Ts'o 	}
14832fa3cdfbSTheodore Ts'o 
14842fa3cdfbSTheodore Ts'o 	/*
148503f5d8bcSJan Kara 	 * Update on-disk size along with block allocation.
14862fa3cdfbSTheodore Ts'o 	 */
14872fa3cdfbSTheodore Ts'o 	disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
14882fa3cdfbSTheodore Ts'o 	if (disksize > i_size_read(mpd->inode))
14892fa3cdfbSTheodore Ts'o 		disksize = i_size_read(mpd->inode);
14902fa3cdfbSTheodore Ts'o 	if (disksize > EXT4_I(mpd->inode)->i_disksize) {
14912fa3cdfbSTheodore Ts'o 		ext4_update_i_disksize(mpd->inode, disksize);
14925a87b7a5STheodore Ts'o 		err = ext4_mark_inode_dirty(handle, mpd->inode);
14935a87b7a5STheodore Ts'o 		if (err)
14945a87b7a5STheodore Ts'o 			ext4_error(mpd->inode->i_sb,
14955a87b7a5STheodore Ts'o 				   "Failed to mark inode %lu dirty",
14965a87b7a5STheodore Ts'o 				   mpd->inode->i_ino);
14972fa3cdfbSTheodore Ts'o 	}
14982fa3cdfbSTheodore Ts'o 
14995a87b7a5STheodore Ts'o submit_io:
15001de3e3dfSTheodore Ts'o 	mpage_da_submit_io(mpd, mapp);
15015a87b7a5STheodore Ts'o 	mpd->io_done = 1;
150264769240SAlex Tomas }
150364769240SAlex Tomas 
1504bf068ee2SAneesh Kumar K.V #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1505bf068ee2SAneesh Kumar K.V 		(1 << BH_Delay) | (1 << BH_Unwritten))
150664769240SAlex Tomas 
150764769240SAlex Tomas /*
150864769240SAlex Tomas  * mpage_add_bh_to_extent - try to add one more block to extent of blocks
150964769240SAlex Tomas  *
151064769240SAlex Tomas  * @mpd->lbh - extent of blocks
151164769240SAlex Tomas  * @logical - logical number of the block in the file
151264769240SAlex Tomas  * @bh - bh of the block (used to access block's state)
151364769240SAlex Tomas  *
151464769240SAlex Tomas  * the function is used to collect contig. blocks in same state
151564769240SAlex Tomas  */
151664769240SAlex Tomas static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
15178dc207c0STheodore Ts'o 				   sector_t logical, size_t b_size,
15188dc207c0STheodore Ts'o 				   unsigned long b_state)
151964769240SAlex Tomas {
152064769240SAlex Tomas 	sector_t next;
15218dc207c0STheodore Ts'o 	int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
152264769240SAlex Tomas 
1523c445e3e0SEric Sandeen 	/*
1524c445e3e0SEric Sandeen 	 * XXX Don't go larger than mballoc is willing to allocate
1525c445e3e0SEric Sandeen 	 * This is a stopgap solution.  We eventually need to fold
1526c445e3e0SEric Sandeen 	 * mpage_da_submit_io() into this function and then call
152779e83036SEric Sandeen 	 * ext4_map_blocks() multiple times in a loop
1528c445e3e0SEric Sandeen 	 */
1529c445e3e0SEric Sandeen 	if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
1530c445e3e0SEric Sandeen 		goto flush_it;
1531c445e3e0SEric Sandeen 
1532525f4ed8SMingming Cao 	/* check if thereserved journal credits might overflow */
153312e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
1534525f4ed8SMingming Cao 		if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1535525f4ed8SMingming Cao 			/*
1536525f4ed8SMingming Cao 			 * With non-extent format we are limited by the journal
1537525f4ed8SMingming Cao 			 * credit available.  Total credit needed to insert
1538525f4ed8SMingming Cao 			 * nrblocks contiguous blocks is dependent on the
1539525f4ed8SMingming Cao 			 * nrblocks.  So limit nrblocks.
1540525f4ed8SMingming Cao 			 */
1541525f4ed8SMingming Cao 			goto flush_it;
1542525f4ed8SMingming Cao 		} else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1543525f4ed8SMingming Cao 				EXT4_MAX_TRANS_DATA) {
1544525f4ed8SMingming Cao 			/*
1545525f4ed8SMingming Cao 			 * Adding the new buffer_head would make it cross the
1546525f4ed8SMingming Cao 			 * allowed limit for which we have journal credit
1547525f4ed8SMingming Cao 			 * reserved. So limit the new bh->b_size
1548525f4ed8SMingming Cao 			 */
1549525f4ed8SMingming Cao 			b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1550525f4ed8SMingming Cao 						mpd->inode->i_blkbits;
1551525f4ed8SMingming Cao 			/* we will do mpage_da_submit_io in the next loop */
1552525f4ed8SMingming Cao 		}
1553525f4ed8SMingming Cao 	}
155464769240SAlex Tomas 	/*
155564769240SAlex Tomas 	 * First block in the extent
155664769240SAlex Tomas 	 */
15578dc207c0STheodore Ts'o 	if (mpd->b_size == 0) {
15588dc207c0STheodore Ts'o 		mpd->b_blocknr = logical;
15598dc207c0STheodore Ts'o 		mpd->b_size = b_size;
15608dc207c0STheodore Ts'o 		mpd->b_state = b_state & BH_FLAGS;
156164769240SAlex Tomas 		return;
156264769240SAlex Tomas 	}
156364769240SAlex Tomas 
15648dc207c0STheodore Ts'o 	next = mpd->b_blocknr + nrblocks;
156564769240SAlex Tomas 	/*
156664769240SAlex Tomas 	 * Can we merge the block to our big extent?
156764769240SAlex Tomas 	 */
15688dc207c0STheodore Ts'o 	if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
15698dc207c0STheodore Ts'o 		mpd->b_size += b_size;
157064769240SAlex Tomas 		return;
157164769240SAlex Tomas 	}
157264769240SAlex Tomas 
1573525f4ed8SMingming Cao flush_it:
157464769240SAlex Tomas 	/*
157564769240SAlex Tomas 	 * We couldn't merge the block to our extent, so we
157664769240SAlex Tomas 	 * need to flush current  extent and start new one
157764769240SAlex Tomas 	 */
15785a87b7a5STheodore Ts'o 	mpage_da_map_and_submit(mpd);
1579a1d6cc56SAneesh Kumar K.V 	return;
158064769240SAlex Tomas }
158164769240SAlex Tomas 
1582c364b22cSAneesh Kumar K.V static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
158329fa89d0SAneesh Kumar K.V {
1584c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
158529fa89d0SAneesh Kumar K.V }
158629fa89d0SAneesh Kumar K.V 
158764769240SAlex Tomas /*
1588b920c755STheodore Ts'o  * This is a special get_blocks_t callback which is used by
1589b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1590b920c755STheodore Ts'o  * reserve space for a single block.
159129fa89d0SAneesh Kumar K.V  *
159229fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
159329fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
159429fa89d0SAneesh Kumar K.V  *
159529fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
159629fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
159729fa89d0SAneesh Kumar K.V  * initialized properly.
159864769240SAlex Tomas  */
159964769240SAlex Tomas static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
16002ed88685STheodore Ts'o 				  struct buffer_head *bh, int create)
160164769240SAlex Tomas {
16022ed88685STheodore Ts'o 	struct ext4_map_blocks map;
160364769240SAlex Tomas 	int ret = 0;
160433b9817eSAneesh Kumar K.V 	sector_t invalid_block = ~((sector_t) 0xffff);
160533b9817eSAneesh Kumar K.V 
160633b9817eSAneesh Kumar K.V 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
160733b9817eSAneesh Kumar K.V 		invalid_block = ~0;
160864769240SAlex Tomas 
160964769240SAlex Tomas 	BUG_ON(create == 0);
16102ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
16112ed88685STheodore Ts'o 
16122ed88685STheodore Ts'o 	map.m_lblk = iblock;
16132ed88685STheodore Ts'o 	map.m_len = 1;
161464769240SAlex Tomas 
161564769240SAlex Tomas 	/*
161664769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
161764769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
161864769240SAlex Tomas 	 * the same as allocated blocks.
161964769240SAlex Tomas 	 */
16202ed88685STheodore Ts'o 	ret = ext4_map_blocks(NULL, inode, &map, 0);
16212ed88685STheodore Ts'o 	if (ret < 0)
16222ed88685STheodore Ts'o 		return ret;
16232ed88685STheodore Ts'o 	if (ret == 0) {
16242ed88685STheodore Ts'o 		if (buffer_delay(bh))
16252ed88685STheodore Ts'o 			return 0; /* Not sure this could or should happen */
162664769240SAlex Tomas 		/*
1627ebdec241SChristoph Hellwig 		 * XXX: __block_write_begin() unmaps passed block, is it OK?
162864769240SAlex Tomas 		 */
16299d0be502STheodore Ts'o 		ret = ext4_da_reserve_space(inode, iblock);
1630d2a17637SMingming Cao 		if (ret)
1631d2a17637SMingming Cao 			/* not enough space to reserve */
1632d2a17637SMingming Cao 			return ret;
1633d2a17637SMingming Cao 
16342ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, invalid_block);
16352ed88685STheodore Ts'o 		set_buffer_new(bh);
16362ed88685STheodore Ts'o 		set_buffer_delay(bh);
16372ed88685STheodore Ts'o 		return 0;
163864769240SAlex Tomas 	}
163964769240SAlex Tomas 
16402ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
16412ed88685STheodore Ts'o 	bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
16422ed88685STheodore Ts'o 
16432ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
16442ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
16452ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
16462ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
16472ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
16482ed88685STheodore Ts'o 		 * for partial write.
16492ed88685STheodore Ts'o 		 */
16502ed88685STheodore Ts'o 		set_buffer_new(bh);
1651c8205636STheodore Ts'o 		set_buffer_mapped(bh);
16522ed88685STheodore Ts'o 	}
16532ed88685STheodore Ts'o 	return 0;
165464769240SAlex Tomas }
165561628a3fSMingming Cao 
1656b920c755STheodore Ts'o /*
1657b920c755STheodore Ts'o  * This function is used as a standard get_block_t calback function
1658b920c755STheodore Ts'o  * when there is no desire to allocate any blocks.  It is used as a
1659ebdec241SChristoph Hellwig  * callback function for block_write_begin() and block_write_full_page().
1660206f7ab4SChristoph Hellwig  * These functions should only try to map a single block at a time.
1661b920c755STheodore Ts'o  *
1662b920c755STheodore Ts'o  * Since this function doesn't do block allocations even if the caller
1663b920c755STheodore Ts'o  * requests it by passing in create=1, it is critically important that
1664b920c755STheodore Ts'o  * any caller checks to make sure that any buffer heads are returned
1665b920c755STheodore Ts'o  * by this function are either all already mapped or marked for
1666206f7ab4SChristoph Hellwig  * delayed allocation before calling  block_write_full_page().  Otherwise,
1667206f7ab4SChristoph Hellwig  * b_blocknr could be left unitialized, and the page write functions will
1668206f7ab4SChristoph Hellwig  * be taken by surprise.
1669b920c755STheodore Ts'o  */
1670b920c755STheodore Ts'o static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
1671f0e6c985SAneesh Kumar K.V 				   struct buffer_head *bh_result, int create)
1672f0e6c985SAneesh Kumar K.V {
1673a2dc52b5STheodore Ts'o 	BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
16742ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh_result, 0);
167561628a3fSMingming Cao }
167661628a3fSMingming Cao 
167762e086beSAneesh Kumar K.V static int bget_one(handle_t *handle, struct buffer_head *bh)
167862e086beSAneesh Kumar K.V {
167962e086beSAneesh Kumar K.V 	get_bh(bh);
168062e086beSAneesh Kumar K.V 	return 0;
168162e086beSAneesh Kumar K.V }
168262e086beSAneesh Kumar K.V 
168362e086beSAneesh Kumar K.V static int bput_one(handle_t *handle, struct buffer_head *bh)
168462e086beSAneesh Kumar K.V {
168562e086beSAneesh Kumar K.V 	put_bh(bh);
168662e086beSAneesh Kumar K.V 	return 0;
168762e086beSAneesh Kumar K.V }
168862e086beSAneesh Kumar K.V 
168962e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
169062e086beSAneesh Kumar K.V 				       unsigned int len)
169162e086beSAneesh Kumar K.V {
169262e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
169362e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
169462e086beSAneesh Kumar K.V 	struct buffer_head *page_bufs;
169562e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
169662e086beSAneesh Kumar K.V 	int ret = 0;
169762e086beSAneesh Kumar K.V 	int err;
169862e086beSAneesh Kumar K.V 
1699cb20d518STheodore Ts'o 	ClearPageChecked(page);
170062e086beSAneesh Kumar K.V 	page_bufs = page_buffers(page);
170162e086beSAneesh Kumar K.V 	BUG_ON(!page_bufs);
170262e086beSAneesh Kumar K.V 	walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
170362e086beSAneesh Kumar K.V 	/* As soon as we unlock the page, it can go away, but we have
170462e086beSAneesh Kumar K.V 	 * references to buffers so we are safe */
170562e086beSAneesh Kumar K.V 	unlock_page(page);
170662e086beSAneesh Kumar K.V 
170762e086beSAneesh Kumar K.V 	handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
170862e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
170962e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
171062e086beSAneesh Kumar K.V 		goto out;
171162e086beSAneesh Kumar K.V 	}
171262e086beSAneesh Kumar K.V 
1713441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1714441c8508SCurt Wohlgemuth 
171562e086beSAneesh Kumar K.V 	ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
171662e086beSAneesh Kumar K.V 				do_journal_get_write_access);
171762e086beSAneesh Kumar K.V 
171862e086beSAneesh Kumar K.V 	err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
171962e086beSAneesh Kumar K.V 				write_end_fn);
172062e086beSAneesh Kumar K.V 	if (ret == 0)
172162e086beSAneesh Kumar K.V 		ret = err;
17222d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
172362e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
172462e086beSAneesh Kumar K.V 	if (!ret)
172562e086beSAneesh Kumar K.V 		ret = err;
172662e086beSAneesh Kumar K.V 
172762e086beSAneesh Kumar K.V 	walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
172819f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
172962e086beSAneesh Kumar K.V out:
173062e086beSAneesh Kumar K.V 	return ret;
173162e086beSAneesh Kumar K.V }
173262e086beSAneesh Kumar K.V 
1733744692dcSJiaying Zhang static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
1734744692dcSJiaying Zhang static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
1735744692dcSJiaying Zhang 
173661628a3fSMingming Cao /*
173743ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
173843ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
173943ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
174043ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
174143ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
174243ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
174343ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
174443ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
174543ce1d23SAneesh Kumar K.V  *
1746b920c755STheodore Ts'o  * This function can get called via...
1747b920c755STheodore Ts'o  *   - ext4_da_writepages after taking page lock (have journal handle)
1748b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
1749b920c755STheodore Ts'o  *   - shrink_page_list via pdflush (no journal handle)
1750b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
175143ce1d23SAneesh Kumar K.V  *
175243ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
175343ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
175443ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
175543ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
175643ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
175743ce1d23SAneesh Kumar K.V  * a[0] = 'a';
175843ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
175943ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
176043ce1d23SAneesh Kumar K.V  * but other bufer_heads would be unmapped but dirty(dirty done via the
176143ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
176243ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
176343ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
176443ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
176543ce1d23SAneesh Kumar K.V  *
176643ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
176743ce1d23SAneesh Kumar K.V  * unwritten in the page.
176843ce1d23SAneesh Kumar K.V  *
176943ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
177043ce1d23SAneesh Kumar K.V  *
177143ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
177243ce1d23SAneesh Kumar K.V  *		ext4_writepage()
177343ce1d23SAneesh Kumar K.V  *
177443ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
177543ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
177661628a3fSMingming Cao  */
177743ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
177864769240SAlex Tomas 			  struct writeback_control *wbc)
177964769240SAlex Tomas {
1780a42afc5fSTheodore Ts'o 	int ret = 0, commit_write = 0;
178161628a3fSMingming Cao 	loff_t size;
1782498e5f24STheodore Ts'o 	unsigned int len;
1783744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
178461628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
178564769240SAlex Tomas 
1786a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
178761628a3fSMingming Cao 	size = i_size_read(inode);
178861628a3fSMingming Cao 	if (page->index == size >> PAGE_CACHE_SHIFT)
178961628a3fSMingming Cao 		len = size & ~PAGE_CACHE_MASK;
179061628a3fSMingming Cao 	else
179161628a3fSMingming Cao 		len = PAGE_CACHE_SIZE;
179261628a3fSMingming Cao 
1793a42afc5fSTheodore Ts'o 	/*
1794a42afc5fSTheodore Ts'o 	 * If the page does not have buffers (for whatever reason),
1795a107e5a3STheodore Ts'o 	 * try to create them using __block_write_begin.  If this
1796a42afc5fSTheodore Ts'o 	 * fails, redirty the page and move on.
1797a42afc5fSTheodore Ts'o 	 */
1798b1142e8fSTheodore Ts'o 	if (!page_has_buffers(page)) {
1799a107e5a3STheodore Ts'o 		if (__block_write_begin(page, 0, len,
1800a42afc5fSTheodore Ts'o 					noalloc_get_block_write)) {
1801a42afc5fSTheodore Ts'o 		redirty_page:
1802a42afc5fSTheodore Ts'o 			redirty_page_for_writepage(wbc, page);
1803a42afc5fSTheodore Ts'o 			unlock_page(page);
1804a42afc5fSTheodore Ts'o 			return 0;
1805a42afc5fSTheodore Ts'o 		}
1806a42afc5fSTheodore Ts'o 		commit_write = 1;
1807a42afc5fSTheodore Ts'o 	}
1808f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
1809f0e6c985SAneesh Kumar K.V 	if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1810c364b22cSAneesh Kumar K.V 			      ext4_bh_delay_or_unwritten)) {
181161628a3fSMingming Cao 		/*
1812b1142e8fSTheodore Ts'o 		 * We don't want to do block allocation, so redirty
1813b1142e8fSTheodore Ts'o 		 * the page and return.  We may reach here when we do
1814b1142e8fSTheodore Ts'o 		 * a journal commit via journal_submit_inode_data_buffers.
1815b1142e8fSTheodore Ts'o 		 * We can also reach here via shrink_page_list
1816f0e6c985SAneesh Kumar K.V 		 */
1817a42afc5fSTheodore Ts'o 		goto redirty_page;
1818f0e6c985SAneesh Kumar K.V 	}
1819a42afc5fSTheodore Ts'o 	if (commit_write)
1820ed9b3e33SAneesh Kumar K.V 		/* now mark the buffer_heads as dirty and uptodate */
1821b767e78aSAneesh Kumar K.V 		block_commit_write(page, 0, len);
182264769240SAlex Tomas 
1823cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
182443ce1d23SAneesh Kumar K.V 		/*
182543ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
182643ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
182743ce1d23SAneesh Kumar K.V 		 */
18283f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
182943ce1d23SAneesh Kumar K.V 
1830a42afc5fSTheodore Ts'o 	if (buffer_uninit(page_bufs)) {
1831744692dcSJiaying Zhang 		ext4_set_bh_endio(page_bufs, inode);
1832744692dcSJiaying Zhang 		ret = block_write_full_page_endio(page, noalloc_get_block_write,
1833744692dcSJiaying Zhang 					    wbc, ext4_end_io_buffer_write);
1834744692dcSJiaying Zhang 	} else
1835b920c755STheodore Ts'o 		ret = block_write_full_page(page, noalloc_get_block_write,
1836f0e6c985SAneesh Kumar K.V 					    wbc);
183764769240SAlex Tomas 
183864769240SAlex Tomas 	return ret;
183964769240SAlex Tomas }
184064769240SAlex Tomas 
184161628a3fSMingming Cao /*
1842525f4ed8SMingming Cao  * This is called via ext4_da_writepages() to
184325985edcSLucas De Marchi  * calculate the total number of credits to reserve to fit
1844525f4ed8SMingming Cao  * a single extent allocation into a single transaction,
1845525f4ed8SMingming Cao  * ext4_da_writpeages() will loop calling this before
1846525f4ed8SMingming Cao  * the block allocation.
184761628a3fSMingming Cao  */
1848525f4ed8SMingming Cao 
1849525f4ed8SMingming Cao static int ext4_da_writepages_trans_blocks(struct inode *inode)
1850525f4ed8SMingming Cao {
1851525f4ed8SMingming Cao 	int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
1852525f4ed8SMingming Cao 
1853525f4ed8SMingming Cao 	/*
1854525f4ed8SMingming Cao 	 * With non-extent format the journal credit needed to
1855525f4ed8SMingming Cao 	 * insert nrblocks contiguous block is dependent on
1856525f4ed8SMingming Cao 	 * number of contiguous block. So we will limit
1857525f4ed8SMingming Cao 	 * number of contiguous block to a sane value
1858525f4ed8SMingming Cao 	 */
185912e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
1860525f4ed8SMingming Cao 	    (max_blocks > EXT4_MAX_TRANS_DATA))
1861525f4ed8SMingming Cao 		max_blocks = EXT4_MAX_TRANS_DATA;
1862525f4ed8SMingming Cao 
1863525f4ed8SMingming Cao 	return ext4_chunk_trans_blocks(inode, max_blocks);
1864525f4ed8SMingming Cao }
186561628a3fSMingming Cao 
18668e48dcfbSTheodore Ts'o /*
18678e48dcfbSTheodore Ts'o  * write_cache_pages_da - walk the list of dirty pages of the given
18688eb9e5ceSTheodore Ts'o  * address space and accumulate pages that need writing, and call
1869168fc022STheodore Ts'o  * mpage_da_map_and_submit to map a single contiguous memory region
1870168fc022STheodore Ts'o  * and then write them.
18718e48dcfbSTheodore Ts'o  */
18728e48dcfbSTheodore Ts'o static int write_cache_pages_da(struct address_space *mapping,
18738e48dcfbSTheodore Ts'o 				struct writeback_control *wbc,
187472f84e65SEric Sandeen 				struct mpage_da_data *mpd,
187572f84e65SEric Sandeen 				pgoff_t *done_index)
18768e48dcfbSTheodore Ts'o {
18778eb9e5ceSTheodore Ts'o 	struct buffer_head	*bh, *head;
1878168fc022STheodore Ts'o 	struct inode		*inode = mapping->host;
18798e48dcfbSTheodore Ts'o 	struct pagevec		pvec;
18804f01b02cSTheodore Ts'o 	unsigned int		nr_pages;
18814f01b02cSTheodore Ts'o 	sector_t		logical;
18824f01b02cSTheodore Ts'o 	pgoff_t			index, end;
18838e48dcfbSTheodore Ts'o 	long			nr_to_write = wbc->nr_to_write;
18844f01b02cSTheodore Ts'o 	int			i, tag, ret = 0;
18858e48dcfbSTheodore Ts'o 
1886168fc022STheodore Ts'o 	memset(mpd, 0, sizeof(struct mpage_da_data));
1887168fc022STheodore Ts'o 	mpd->wbc = wbc;
1888168fc022STheodore Ts'o 	mpd->inode = inode;
18898e48dcfbSTheodore Ts'o 	pagevec_init(&pvec, 0);
18908e48dcfbSTheodore Ts'o 	index = wbc->range_start >> PAGE_CACHE_SHIFT;
18918e48dcfbSTheodore Ts'o 	end = wbc->range_end >> PAGE_CACHE_SHIFT;
18928e48dcfbSTheodore Ts'o 
18936e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
18945b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
18955b41d924SEric Sandeen 	else
18965b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
18975b41d924SEric Sandeen 
189872f84e65SEric Sandeen 	*done_index = index;
18994f01b02cSTheodore Ts'o 	while (index <= end) {
19005b41d924SEric Sandeen 		nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
19018e48dcfbSTheodore Ts'o 			      min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
19028e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
19034f01b02cSTheodore Ts'o 			return 0;
19048e48dcfbSTheodore Ts'o 
19058e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
19068e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
19078e48dcfbSTheodore Ts'o 
19088e48dcfbSTheodore Ts'o 			/*
19098e48dcfbSTheodore Ts'o 			 * At this point, the page may be truncated or
19108e48dcfbSTheodore Ts'o 			 * invalidated (changing page->mapping to NULL), or
19118e48dcfbSTheodore Ts'o 			 * even swizzled back from swapper_space to tmpfs file
19128e48dcfbSTheodore Ts'o 			 * mapping. However, page->index will not change
19138e48dcfbSTheodore Ts'o 			 * because we have a reference on the page.
19148e48dcfbSTheodore Ts'o 			 */
19154f01b02cSTheodore Ts'o 			if (page->index > end)
19164f01b02cSTheodore Ts'o 				goto out;
19178e48dcfbSTheodore Ts'o 
191872f84e65SEric Sandeen 			*done_index = page->index + 1;
191972f84e65SEric Sandeen 
192078aaced3STheodore Ts'o 			/*
192178aaced3STheodore Ts'o 			 * If we can't merge this page, and we have
192278aaced3STheodore Ts'o 			 * accumulated an contiguous region, write it
192378aaced3STheodore Ts'o 			 */
192478aaced3STheodore Ts'o 			if ((mpd->next_page != page->index) &&
192578aaced3STheodore Ts'o 			    (mpd->next_page != mpd->first_page)) {
192678aaced3STheodore Ts'o 				mpage_da_map_and_submit(mpd);
192778aaced3STheodore Ts'o 				goto ret_extent_tail;
192878aaced3STheodore Ts'o 			}
192978aaced3STheodore Ts'o 
19308e48dcfbSTheodore Ts'o 			lock_page(page);
19318e48dcfbSTheodore Ts'o 
19328e48dcfbSTheodore Ts'o 			/*
19334f01b02cSTheodore Ts'o 			 * If the page is no longer dirty, or its
19344f01b02cSTheodore Ts'o 			 * mapping no longer corresponds to inode we
19354f01b02cSTheodore Ts'o 			 * are writing (which means it has been
19364f01b02cSTheodore Ts'o 			 * truncated or invalidated), or the page is
19374f01b02cSTheodore Ts'o 			 * already under writeback and we are not
19384f01b02cSTheodore Ts'o 			 * doing a data integrity writeback, skip the page
19398e48dcfbSTheodore Ts'o 			 */
19404f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
19414f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
19424f01b02cSTheodore Ts'o 			     (wbc->sync_mode == WB_SYNC_NONE)) ||
19434f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
19448e48dcfbSTheodore Ts'o 				unlock_page(page);
19458e48dcfbSTheodore Ts'o 				continue;
19468e48dcfbSTheodore Ts'o 			}
19478e48dcfbSTheodore Ts'o 
19488e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
19498e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
19508e48dcfbSTheodore Ts'o 
1951168fc022STheodore Ts'o 			if (mpd->next_page != page->index)
19528eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
19538eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
19548eb9e5ceSTheodore Ts'o 			logical = (sector_t) page->index <<
19558eb9e5ceSTheodore Ts'o 				(PAGE_CACHE_SHIFT - inode->i_blkbits);
19568eb9e5ceSTheodore Ts'o 
19578eb9e5ceSTheodore Ts'o 			if (!page_has_buffers(page)) {
19584f01b02cSTheodore Ts'o 				mpage_add_bh_to_extent(mpd, logical,
19594f01b02cSTheodore Ts'o 						       PAGE_CACHE_SIZE,
19608eb9e5ceSTheodore Ts'o 						       (1 << BH_Dirty) | (1 << BH_Uptodate));
19614f01b02cSTheodore Ts'o 				if (mpd->io_done)
19624f01b02cSTheodore Ts'o 					goto ret_extent_tail;
19638e48dcfbSTheodore Ts'o 			} else {
19648eb9e5ceSTheodore Ts'o 				/*
19654f01b02cSTheodore Ts'o 				 * Page with regular buffer heads,
19664f01b02cSTheodore Ts'o 				 * just add all dirty ones
19678eb9e5ceSTheodore Ts'o 				 */
19688eb9e5ceSTheodore Ts'o 				head = page_buffers(page);
19698eb9e5ceSTheodore Ts'o 				bh = head;
19708eb9e5ceSTheodore Ts'o 				do {
19718eb9e5ceSTheodore Ts'o 					BUG_ON(buffer_locked(bh));
19728eb9e5ceSTheodore Ts'o 					/*
19738eb9e5ceSTheodore Ts'o 					 * We need to try to allocate
19748eb9e5ceSTheodore Ts'o 					 * unmapped blocks in the same page.
19758eb9e5ceSTheodore Ts'o 					 * Otherwise we won't make progress
19768eb9e5ceSTheodore Ts'o 					 * with the page in ext4_writepage
19778eb9e5ceSTheodore Ts'o 					 */
19788eb9e5ceSTheodore Ts'o 					if (ext4_bh_delay_or_unwritten(NULL, bh)) {
19798eb9e5ceSTheodore Ts'o 						mpage_add_bh_to_extent(mpd, logical,
19808eb9e5ceSTheodore Ts'o 								       bh->b_size,
19818eb9e5ceSTheodore Ts'o 								       bh->b_state);
19824f01b02cSTheodore Ts'o 						if (mpd->io_done)
19834f01b02cSTheodore Ts'o 							goto ret_extent_tail;
19848eb9e5ceSTheodore Ts'o 					} else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
19858eb9e5ceSTheodore Ts'o 						/*
19864f01b02cSTheodore Ts'o 						 * mapped dirty buffer. We need
19874f01b02cSTheodore Ts'o 						 * to update the b_state
19884f01b02cSTheodore Ts'o 						 * because we look at b_state
19894f01b02cSTheodore Ts'o 						 * in mpage_da_map_blocks.  We
19904f01b02cSTheodore Ts'o 						 * don't update b_size because
19914f01b02cSTheodore Ts'o 						 * if we find an unmapped
19924f01b02cSTheodore Ts'o 						 * buffer_head later we need to
19934f01b02cSTheodore Ts'o 						 * use the b_state flag of that
19944f01b02cSTheodore Ts'o 						 * buffer_head.
19958eb9e5ceSTheodore Ts'o 						 */
19968eb9e5ceSTheodore Ts'o 						if (mpd->b_size == 0)
19978eb9e5ceSTheodore Ts'o 							mpd->b_state = bh->b_state & BH_FLAGS;
19988e48dcfbSTheodore Ts'o 					}
19998eb9e5ceSTheodore Ts'o 					logical++;
20008eb9e5ceSTheodore Ts'o 				} while ((bh = bh->b_this_page) != head);
20018e48dcfbSTheodore Ts'o 			}
20028e48dcfbSTheodore Ts'o 
20038e48dcfbSTheodore Ts'o 			if (nr_to_write > 0) {
20048e48dcfbSTheodore Ts'o 				nr_to_write--;
20058e48dcfbSTheodore Ts'o 				if (nr_to_write == 0 &&
20064f01b02cSTheodore Ts'o 				    wbc->sync_mode == WB_SYNC_NONE)
20078e48dcfbSTheodore Ts'o 					/*
20088e48dcfbSTheodore Ts'o 					 * We stop writing back only if we are
20098e48dcfbSTheodore Ts'o 					 * not doing integrity sync. In case of
20108e48dcfbSTheodore Ts'o 					 * integrity sync we have to keep going
20118e48dcfbSTheodore Ts'o 					 * because someone may be concurrently
20128e48dcfbSTheodore Ts'o 					 * dirtying pages, and we might have
20138e48dcfbSTheodore Ts'o 					 * synced a lot of newly appeared dirty
20148e48dcfbSTheodore Ts'o 					 * pages, but have not synced all of the
20158e48dcfbSTheodore Ts'o 					 * old dirty pages.
20168e48dcfbSTheodore Ts'o 					 */
20174f01b02cSTheodore Ts'o 					goto out;
20188e48dcfbSTheodore Ts'o 			}
20198e48dcfbSTheodore Ts'o 		}
20208e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
20218e48dcfbSTheodore Ts'o 		cond_resched();
20228e48dcfbSTheodore Ts'o 	}
20234f01b02cSTheodore Ts'o 	return 0;
20244f01b02cSTheodore Ts'o ret_extent_tail:
20254f01b02cSTheodore Ts'o 	ret = MPAGE_DA_EXTENT_TAIL;
20268eb9e5ceSTheodore Ts'o out:
20278eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
20288eb9e5ceSTheodore Ts'o 	cond_resched();
20298e48dcfbSTheodore Ts'o 	return ret;
20308e48dcfbSTheodore Ts'o }
20318e48dcfbSTheodore Ts'o 
20328e48dcfbSTheodore Ts'o 
203364769240SAlex Tomas static int ext4_da_writepages(struct address_space *mapping,
203464769240SAlex Tomas 			      struct writeback_control *wbc)
203564769240SAlex Tomas {
203622208dedSAneesh Kumar K.V 	pgoff_t	index;
203722208dedSAneesh Kumar K.V 	int range_whole = 0;
203861628a3fSMingming Cao 	handle_t *handle = NULL;
2039df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
20405e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
2041498e5f24STheodore Ts'o 	int pages_written = 0;
204255138e0bSTheodore Ts'o 	unsigned int max_pages;
20432acf2c26SAneesh Kumar K.V 	int range_cyclic, cycled = 1, io_done = 0;
204455138e0bSTheodore Ts'o 	int needed_blocks, ret = 0;
204555138e0bSTheodore Ts'o 	long desired_nr_to_write, nr_to_writebump = 0;
2046de89de6eSTheodore Ts'o 	loff_t range_start = wbc->range_start;
20475e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
204872f84e65SEric Sandeen 	pgoff_t done_index = 0;
20495b41d924SEric Sandeen 	pgoff_t end;
205061628a3fSMingming Cao 
20519bffad1eSTheodore Ts'o 	trace_ext4_da_writepages(inode, wbc);
2052ba80b101STheodore Ts'o 
205361628a3fSMingming Cao 	/*
205461628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
205561628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
205661628a3fSMingming Cao 	 * because that could violate lock ordering on umount
205761628a3fSMingming Cao 	 */
2058a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
205961628a3fSMingming Cao 		return 0;
20602a21e37eSTheodore Ts'o 
20612a21e37eSTheodore Ts'o 	/*
20622a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
20632a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
20642a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
20654ab2f15bSTheodore Ts'o 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
20662a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
20672a21e37eSTheodore Ts'o 	 * read-only, and in that case, ext4_da_writepages should
20682a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
20692a21e37eSTheodore Ts'o 	 * the stack trace.
20702a21e37eSTheodore Ts'o 	 */
20714ab2f15bSTheodore Ts'o 	if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
20722a21e37eSTheodore Ts'o 		return -EROFS;
20732a21e37eSTheodore Ts'o 
207422208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
207522208dedSAneesh Kumar K.V 		range_whole = 1;
207661628a3fSMingming Cao 
20772acf2c26SAneesh Kumar K.V 	range_cyclic = wbc->range_cyclic;
20782acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
207922208dedSAneesh Kumar K.V 		index = mapping->writeback_index;
20802acf2c26SAneesh Kumar K.V 		if (index)
20812acf2c26SAneesh Kumar K.V 			cycled = 0;
20822acf2c26SAneesh Kumar K.V 		wbc->range_start = index << PAGE_CACHE_SHIFT;
20832acf2c26SAneesh Kumar K.V 		wbc->range_end  = LLONG_MAX;
20842acf2c26SAneesh Kumar K.V 		wbc->range_cyclic = 0;
20855b41d924SEric Sandeen 		end = -1;
20865b41d924SEric Sandeen 	} else {
208722208dedSAneesh Kumar K.V 		index = wbc->range_start >> PAGE_CACHE_SHIFT;
20885b41d924SEric Sandeen 		end = wbc->range_end >> PAGE_CACHE_SHIFT;
20895b41d924SEric Sandeen 	}
2090a1d6cc56SAneesh Kumar K.V 
209155138e0bSTheodore Ts'o 	/*
209255138e0bSTheodore Ts'o 	 * This works around two forms of stupidity.  The first is in
209355138e0bSTheodore Ts'o 	 * the writeback code, which caps the maximum number of pages
209455138e0bSTheodore Ts'o 	 * written to be 1024 pages.  This is wrong on multiple
209555138e0bSTheodore Ts'o 	 * levels; different architectues have a different page size,
209655138e0bSTheodore Ts'o 	 * which changes the maximum amount of data which gets
209755138e0bSTheodore Ts'o 	 * written.  Secondly, 4 megabytes is way too small.  XFS
209855138e0bSTheodore Ts'o 	 * forces this value to be 16 megabytes by multiplying
209955138e0bSTheodore Ts'o 	 * nr_to_write parameter by four, and then relies on its
210055138e0bSTheodore Ts'o 	 * allocator to allocate larger extents to make them
210155138e0bSTheodore Ts'o 	 * contiguous.  Unfortunately this brings us to the second
210255138e0bSTheodore Ts'o 	 * stupidity, which is that ext4's mballoc code only allocates
210355138e0bSTheodore Ts'o 	 * at most 2048 blocks.  So we force contiguous writes up to
210455138e0bSTheodore Ts'o 	 * the number of dirty blocks in the inode, or
210555138e0bSTheodore Ts'o 	 * sbi->max_writeback_mb_bump whichever is smaller.
210655138e0bSTheodore Ts'o 	 */
210755138e0bSTheodore Ts'o 	max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2108b443e733SEric Sandeen 	if (!range_cyclic && range_whole) {
2109b443e733SEric Sandeen 		if (wbc->nr_to_write == LONG_MAX)
2110b443e733SEric Sandeen 			desired_nr_to_write = wbc->nr_to_write;
211155138e0bSTheodore Ts'o 		else
2112b443e733SEric Sandeen 			desired_nr_to_write = wbc->nr_to_write * 8;
2113b443e733SEric Sandeen 	} else
211455138e0bSTheodore Ts'o 		desired_nr_to_write = ext4_num_dirty_pages(inode, index,
211555138e0bSTheodore Ts'o 							   max_pages);
211655138e0bSTheodore Ts'o 	if (desired_nr_to_write > max_pages)
211755138e0bSTheodore Ts'o 		desired_nr_to_write = max_pages;
211855138e0bSTheodore Ts'o 
211955138e0bSTheodore Ts'o 	if (wbc->nr_to_write < desired_nr_to_write) {
212055138e0bSTheodore Ts'o 		nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
212155138e0bSTheodore Ts'o 		wbc->nr_to_write = desired_nr_to_write;
212255138e0bSTheodore Ts'o 	}
212355138e0bSTheodore Ts'o 
21242acf2c26SAneesh Kumar K.V retry:
21256e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
21265b41d924SEric Sandeen 		tag_pages_for_writeback(mapping, index, end);
21275b41d924SEric Sandeen 
212822208dedSAneesh Kumar K.V 	while (!ret && wbc->nr_to_write > 0) {
2129a1d6cc56SAneesh Kumar K.V 
2130a1d6cc56SAneesh Kumar K.V 		/*
2131a1d6cc56SAneesh Kumar K.V 		 * we  insert one extent at a time. So we need
2132a1d6cc56SAneesh Kumar K.V 		 * credit needed for single extent allocation.
2133a1d6cc56SAneesh Kumar K.V 		 * journalled mode is currently not supported
2134a1d6cc56SAneesh Kumar K.V 		 * by delalloc
2135a1d6cc56SAneesh Kumar K.V 		 */
2136a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2137525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2138a1d6cc56SAneesh Kumar K.V 
213961628a3fSMingming Cao 		/* start a new transaction*/
214061628a3fSMingming Cao 		handle = ext4_journal_start(inode, needed_blocks);
214161628a3fSMingming Cao 		if (IS_ERR(handle)) {
214261628a3fSMingming Cao 			ret = PTR_ERR(handle);
21431693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2144fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2145a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
214661628a3fSMingming Cao 			goto out_writepages;
214761628a3fSMingming Cao 		}
2148f63e6005STheodore Ts'o 
2149f63e6005STheodore Ts'o 		/*
21508eb9e5ceSTheodore Ts'o 		 * Now call write_cache_pages_da() to find the next
2151f63e6005STheodore Ts'o 		 * contiguous region of logical blocks that need
21528eb9e5ceSTheodore Ts'o 		 * blocks to be allocated by ext4 and submit them.
2153f63e6005STheodore Ts'o 		 */
215472f84e65SEric Sandeen 		ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
2155f63e6005STheodore Ts'o 		/*
2156af901ca1SAndré Goddard Rosa 		 * If we have a contiguous extent of pages and we
2157f63e6005STheodore Ts'o 		 * haven't done the I/O yet, map the blocks and submit
2158f63e6005STheodore Ts'o 		 * them for I/O.
2159f63e6005STheodore Ts'o 		 */
2160f63e6005STheodore Ts'o 		if (!mpd.io_done && mpd.next_page != mpd.first_page) {
21615a87b7a5STheodore Ts'o 			mpage_da_map_and_submit(&mpd);
2162f63e6005STheodore Ts'o 			ret = MPAGE_DA_EXTENT_TAIL;
2163f63e6005STheodore Ts'o 		}
2164b3a3ca8cSTheodore Ts'o 		trace_ext4_da_write_pages(inode, &mpd);
2165f63e6005STheodore Ts'o 		wbc->nr_to_write -= mpd.pages_written;
2166df22291fSAneesh Kumar K.V 
216761628a3fSMingming Cao 		ext4_journal_stop(handle);
2168df22291fSAneesh Kumar K.V 
21698f64b32eSEric Sandeen 		if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
217022208dedSAneesh Kumar K.V 			/* commit the transaction which would
217122208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
217222208dedSAneesh Kumar K.V 			 * and try again
217322208dedSAneesh Kumar K.V 			 */
2174df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
217522208dedSAneesh Kumar K.V 			ret = 0;
217622208dedSAneesh Kumar K.V 		} else if (ret == MPAGE_DA_EXTENT_TAIL) {
2177a1d6cc56SAneesh Kumar K.V 			/*
2178a1d6cc56SAneesh Kumar K.V 			 * got one extent now try with
2179a1d6cc56SAneesh Kumar K.V 			 * rest of the pages
2180a1d6cc56SAneesh Kumar K.V 			 */
218122208dedSAneesh Kumar K.V 			pages_written += mpd.pages_written;
2182a1d6cc56SAneesh Kumar K.V 			ret = 0;
21832acf2c26SAneesh Kumar K.V 			io_done = 1;
218422208dedSAneesh Kumar K.V 		} else if (wbc->nr_to_write)
218561628a3fSMingming Cao 			/*
218661628a3fSMingming Cao 			 * There is no more writeout needed
218761628a3fSMingming Cao 			 * or we requested for a noblocking writeout
218861628a3fSMingming Cao 			 * and we found the device congested
218961628a3fSMingming Cao 			 */
219061628a3fSMingming Cao 			break;
219161628a3fSMingming Cao 	}
21922acf2c26SAneesh Kumar K.V 	if (!io_done && !cycled) {
21932acf2c26SAneesh Kumar K.V 		cycled = 1;
21942acf2c26SAneesh Kumar K.V 		index = 0;
21952acf2c26SAneesh Kumar K.V 		wbc->range_start = index << PAGE_CACHE_SHIFT;
21962acf2c26SAneesh Kumar K.V 		wbc->range_end  = mapping->writeback_index - 1;
21972acf2c26SAneesh Kumar K.V 		goto retry;
21982acf2c26SAneesh Kumar K.V 	}
219961628a3fSMingming Cao 
220022208dedSAneesh Kumar K.V 	/* Update index */
22012acf2c26SAneesh Kumar K.V 	wbc->range_cyclic = range_cyclic;
220222208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
220322208dedSAneesh Kumar K.V 		/*
220422208dedSAneesh Kumar K.V 		 * set the writeback_index so that range_cyclic
220522208dedSAneesh Kumar K.V 		 * mode will write it back later
220622208dedSAneesh Kumar K.V 		 */
220772f84e65SEric Sandeen 		mapping->writeback_index = done_index;
2208a1d6cc56SAneesh Kumar K.V 
220961628a3fSMingming Cao out_writepages:
221022208dedSAneesh Kumar K.V 	wbc->nr_to_write -= nr_to_writebump;
2211de89de6eSTheodore Ts'o 	wbc->range_start = range_start;
22129bffad1eSTheodore Ts'o 	trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
221361628a3fSMingming Cao 	return ret;
221464769240SAlex Tomas }
221564769240SAlex Tomas 
221679f0be8dSAneesh Kumar K.V #define FALL_BACK_TO_NONDELALLOC 1
221779f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
221879f0be8dSAneesh Kumar K.V {
221979f0be8dSAneesh Kumar K.V 	s64 free_blocks, dirty_blocks;
222079f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
222179f0be8dSAneesh Kumar K.V 
222279f0be8dSAneesh Kumar K.V 	/*
222379f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
222479f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2225179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
222679f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
222779f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
222879f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
222979f0be8dSAneesh Kumar K.V 	 */
2230*57042651STheodore Ts'o 	free_blocks  = EXT4_C2B(sbi,
2231*57042651STheodore Ts'o 		percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2232*57042651STheodore Ts'o 	dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
223379f0be8dSAneesh Kumar K.V 	if (2 * free_blocks < 3 * dirty_blocks ||
223479f0be8dSAneesh Kumar K.V 		free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
223579f0be8dSAneesh Kumar K.V 		/*
2236c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2237c8afb446SEric Sandeen 		 * or free blocks is less than watermark
223879f0be8dSAneesh Kumar K.V 		 */
223979f0be8dSAneesh Kumar K.V 		return 1;
224079f0be8dSAneesh Kumar K.V 	}
2241c8afb446SEric Sandeen 	/*
2242c8afb446SEric Sandeen 	 * Even if we don't switch but are nearing capacity,
2243c8afb446SEric Sandeen 	 * start pushing delalloc when 1/2 of free blocks are dirty.
2244c8afb446SEric Sandeen 	 */
2245c8afb446SEric Sandeen 	if (free_blocks < 2 * dirty_blocks)
2246c8afb446SEric Sandeen 		writeback_inodes_sb_if_idle(sb);
2247c8afb446SEric Sandeen 
224879f0be8dSAneesh Kumar K.V 	return 0;
224979f0be8dSAneesh Kumar K.V }
225079f0be8dSAneesh Kumar K.V 
225164769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
225264769240SAlex Tomas 			       loff_t pos, unsigned len, unsigned flags,
225364769240SAlex Tomas 			       struct page **pagep, void **fsdata)
225464769240SAlex Tomas {
225572b8ab9dSEric Sandeen 	int ret, retries = 0;
225664769240SAlex Tomas 	struct page *page;
225764769240SAlex Tomas 	pgoff_t index;
225864769240SAlex Tomas 	struct inode *inode = mapping->host;
225964769240SAlex Tomas 	handle_t *handle;
226002fac129SAllison Henderson 	loff_t page_len;
226164769240SAlex Tomas 
226264769240SAlex Tomas 	index = pos >> PAGE_CACHE_SHIFT;
226379f0be8dSAneesh Kumar K.V 
226479f0be8dSAneesh Kumar K.V 	if (ext4_nonda_switch(inode->i_sb)) {
226579f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
226679f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
226779f0be8dSAneesh Kumar K.V 					len, flags, pagep, fsdata);
226879f0be8dSAneesh Kumar K.V 	}
226979f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
22709bffad1eSTheodore Ts'o 	trace_ext4_da_write_begin(inode, pos, len, flags);
2271d2a17637SMingming Cao retry:
227264769240SAlex Tomas 	/*
227364769240SAlex Tomas 	 * With delayed allocation, we don't log the i_disksize update
227464769240SAlex Tomas 	 * if there is delayed block allocation. But we still need
227564769240SAlex Tomas 	 * to journalling the i_disksize update if writes to the end
227664769240SAlex Tomas 	 * of file which has an already mapped buffer.
227764769240SAlex Tomas 	 */
227864769240SAlex Tomas 	handle = ext4_journal_start(inode, 1);
227964769240SAlex Tomas 	if (IS_ERR(handle)) {
228064769240SAlex Tomas 		ret = PTR_ERR(handle);
228164769240SAlex Tomas 		goto out;
228264769240SAlex Tomas 	}
2283ebd3610bSJan Kara 	/* We cannot recurse into the filesystem as the transaction is already
2284ebd3610bSJan Kara 	 * started */
2285ebd3610bSJan Kara 	flags |= AOP_FLAG_NOFS;
228664769240SAlex Tomas 
228754566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
2288d5a0d4f7SEric Sandeen 	if (!page) {
2289d5a0d4f7SEric Sandeen 		ext4_journal_stop(handle);
2290d5a0d4f7SEric Sandeen 		ret = -ENOMEM;
2291d5a0d4f7SEric Sandeen 		goto out;
2292d5a0d4f7SEric Sandeen 	}
229364769240SAlex Tomas 	*pagep = page;
229464769240SAlex Tomas 
22956e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
229664769240SAlex Tomas 	if (ret < 0) {
229764769240SAlex Tomas 		unlock_page(page);
229864769240SAlex Tomas 		ext4_journal_stop(handle);
229964769240SAlex Tomas 		page_cache_release(page);
2300ae4d5372SAneesh Kumar K.V 		/*
2301ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
2302ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
2303ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
2304ae4d5372SAneesh Kumar K.V 		 */
2305ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
2306b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
230702fac129SAllison Henderson 	} else {
230802fac129SAllison Henderson 		page_len = pos & (PAGE_CACHE_SIZE - 1);
230902fac129SAllison Henderson 		if (page_len > 0) {
231002fac129SAllison Henderson 			ret = ext4_discard_partial_page_buffers_no_lock(handle,
231102fac129SAllison Henderson 				inode, page, pos - page_len, page_len,
231202fac129SAllison Henderson 				EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED);
231302fac129SAllison Henderson 		}
231464769240SAlex Tomas 	}
231564769240SAlex Tomas 
2316d2a17637SMingming Cao 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2317d2a17637SMingming Cao 		goto retry;
231864769240SAlex Tomas out:
231964769240SAlex Tomas 	return ret;
232064769240SAlex Tomas }
232164769240SAlex Tomas 
2322632eaeabSMingming Cao /*
2323632eaeabSMingming Cao  * Check if we should update i_disksize
2324632eaeabSMingming Cao  * when write to the end of file but not require block allocation
2325632eaeabSMingming Cao  */
2326632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
2327632eaeabSMingming Cao 					    unsigned long offset)
2328632eaeabSMingming Cao {
2329632eaeabSMingming Cao 	struct buffer_head *bh;
2330632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
2331632eaeabSMingming Cao 	unsigned int idx;
2332632eaeabSMingming Cao 	int i;
2333632eaeabSMingming Cao 
2334632eaeabSMingming Cao 	bh = page_buffers(page);
2335632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
2336632eaeabSMingming Cao 
2337632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
2338632eaeabSMingming Cao 		bh = bh->b_this_page;
2339632eaeabSMingming Cao 
234029fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2341632eaeabSMingming Cao 		return 0;
2342632eaeabSMingming Cao 	return 1;
2343632eaeabSMingming Cao }
2344632eaeabSMingming Cao 
234564769240SAlex Tomas static int ext4_da_write_end(struct file *file,
234664769240SAlex Tomas 			     struct address_space *mapping,
234764769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
234864769240SAlex Tomas 			     struct page *page, void *fsdata)
234964769240SAlex Tomas {
235064769240SAlex Tomas 	struct inode *inode = mapping->host;
235164769240SAlex Tomas 	int ret = 0, ret2;
235264769240SAlex Tomas 	handle_t *handle = ext4_journal_current_handle();
235364769240SAlex Tomas 	loff_t new_i_size;
2354632eaeabSMingming Cao 	unsigned long start, end;
235579f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
235602fac129SAllison Henderson 	loff_t page_len;
235779f0be8dSAneesh Kumar K.V 
235879f0be8dSAneesh Kumar K.V 	if (write_mode == FALL_BACK_TO_NONDELALLOC) {
235979f0be8dSAneesh Kumar K.V 		if (ext4_should_order_data(inode)) {
236079f0be8dSAneesh Kumar K.V 			return ext4_ordered_write_end(file, mapping, pos,
236179f0be8dSAneesh Kumar K.V 					len, copied, page, fsdata);
236279f0be8dSAneesh Kumar K.V 		} else if (ext4_should_writeback_data(inode)) {
236379f0be8dSAneesh Kumar K.V 			return ext4_writeback_write_end(file, mapping, pos,
236479f0be8dSAneesh Kumar K.V 					len, copied, page, fsdata);
236579f0be8dSAneesh Kumar K.V 		} else {
236679f0be8dSAneesh Kumar K.V 			BUG();
236779f0be8dSAneesh Kumar K.V 		}
236879f0be8dSAneesh Kumar K.V 	}
2369632eaeabSMingming Cao 
23709bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
2371632eaeabSMingming Cao 	start = pos & (PAGE_CACHE_SIZE - 1);
2372632eaeabSMingming Cao 	end = start + copied - 1;
237364769240SAlex Tomas 
237464769240SAlex Tomas 	/*
237564769240SAlex Tomas 	 * generic_write_end() will run mark_inode_dirty() if i_size
237664769240SAlex Tomas 	 * changes.  So let's piggyback the i_disksize mark_inode_dirty
237764769240SAlex Tomas 	 * into that.
237864769240SAlex Tomas 	 */
237964769240SAlex Tomas 
238064769240SAlex Tomas 	new_i_size = pos + copied;
2381632eaeabSMingming Cao 	if (new_i_size > EXT4_I(inode)->i_disksize) {
2382632eaeabSMingming Cao 		if (ext4_da_should_update_i_disksize(page, end)) {
2383632eaeabSMingming Cao 			down_write(&EXT4_I(inode)->i_data_sem);
2384632eaeabSMingming Cao 			if (new_i_size > EXT4_I(inode)->i_disksize) {
238564769240SAlex Tomas 				/*
2386632eaeabSMingming Cao 				 * Updating i_disksize when extending file
2387632eaeabSMingming Cao 				 * without needing block allocation
238864769240SAlex Tomas 				 */
238964769240SAlex Tomas 				if (ext4_should_order_data(inode))
2390632eaeabSMingming Cao 					ret = ext4_jbd2_file_inode(handle,
2391632eaeabSMingming Cao 								   inode);
239264769240SAlex Tomas 
239364769240SAlex Tomas 				EXT4_I(inode)->i_disksize = new_i_size;
239464769240SAlex Tomas 			}
2395632eaeabSMingming Cao 			up_write(&EXT4_I(inode)->i_data_sem);
2396cf17fea6SAneesh Kumar K.V 			/* We need to mark inode dirty even if
2397cf17fea6SAneesh Kumar K.V 			 * new_i_size is less that inode->i_size
2398cf17fea6SAneesh Kumar K.V 			 * bu greater than i_disksize.(hint delalloc)
2399cf17fea6SAneesh Kumar K.V 			 */
2400cf17fea6SAneesh Kumar K.V 			ext4_mark_inode_dirty(handle, inode);
2401632eaeabSMingming Cao 		}
2402632eaeabSMingming Cao 	}
240364769240SAlex Tomas 	ret2 = generic_write_end(file, mapping, pos, len, copied,
240464769240SAlex Tomas 							page, fsdata);
240502fac129SAllison Henderson 
240602fac129SAllison Henderson 	page_len = PAGE_CACHE_SIZE -
240702fac129SAllison Henderson 			((pos + copied - 1) & (PAGE_CACHE_SIZE - 1));
240802fac129SAllison Henderson 
240902fac129SAllison Henderson 	if (page_len > 0) {
241002fac129SAllison Henderson 		ret = ext4_discard_partial_page_buffers_no_lock(handle,
241102fac129SAllison Henderson 			inode, page, pos + copied - 1, page_len,
241202fac129SAllison Henderson 			EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED);
241302fac129SAllison Henderson 	}
241402fac129SAllison Henderson 
241564769240SAlex Tomas 	copied = ret2;
241664769240SAlex Tomas 	if (ret2 < 0)
241764769240SAlex Tomas 		ret = ret2;
241864769240SAlex Tomas 	ret2 = ext4_journal_stop(handle);
241964769240SAlex Tomas 	if (!ret)
242064769240SAlex Tomas 		ret = ret2;
242164769240SAlex Tomas 
242264769240SAlex Tomas 	return ret ? ret : copied;
242364769240SAlex Tomas }
242464769240SAlex Tomas 
242564769240SAlex Tomas static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
242664769240SAlex Tomas {
242764769240SAlex Tomas 	/*
242864769240SAlex Tomas 	 * Drop reserved blocks
242964769240SAlex Tomas 	 */
243064769240SAlex Tomas 	BUG_ON(!PageLocked(page));
243164769240SAlex Tomas 	if (!page_has_buffers(page))
243264769240SAlex Tomas 		goto out;
243364769240SAlex Tomas 
2434d2a17637SMingming Cao 	ext4_da_page_release_reservation(page, offset);
243564769240SAlex Tomas 
243664769240SAlex Tomas out:
243764769240SAlex Tomas 	ext4_invalidatepage(page, offset);
243864769240SAlex Tomas 
243964769240SAlex Tomas 	return;
244064769240SAlex Tomas }
244164769240SAlex Tomas 
2442ccd2506bSTheodore Ts'o /*
2443ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
2444ccd2506bSTheodore Ts'o  */
2445ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
2446ccd2506bSTheodore Ts'o {
2447fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
2448fb40ba0dSTheodore Ts'o 
2449ccd2506bSTheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks &&
2450ccd2506bSTheodore Ts'o 	    !EXT4_I(inode)->i_reserved_meta_blocks)
2451ccd2506bSTheodore Ts'o 		return 0;
2452ccd2506bSTheodore Ts'o 
2453ccd2506bSTheodore Ts'o 	/*
2454ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
2455ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
2456ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
2457ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
2458ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
2459ccd2506bSTheodore Ts'o 	 *
2460ccd2506bSTheodore Ts'o 	 * ext4_da_writepages() ->
2461ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
2462ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
2463ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
2464ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
2465ccd2506bSTheodore Ts'o 	 *
2466ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
2467ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
2468ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
2469ccd2506bSTheodore Ts'o 	 * doing I/O at all.
2470ccd2506bSTheodore Ts'o 	 *
2471ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
2472380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
2473ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
2474ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
247525985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
2476ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
2477ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
2478ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
2479ccd2506bSTheodore Ts'o 	 *
2480ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
2481ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
2482ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
2483ccd2506bSTheodore Ts'o 	 */
2484ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
2485ccd2506bSTheodore Ts'o }
248664769240SAlex Tomas 
248764769240SAlex Tomas /*
2488ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
2489ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
2490ac27a0ecSDave Kleikamp  *
2491ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
2492617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
2493ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
2494ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
2495ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
2496ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
2497ac27a0ecSDave Kleikamp  *
2498ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
2499ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
2500ac27a0ecSDave Kleikamp  */
2501617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2502ac27a0ecSDave Kleikamp {
2503ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
2504ac27a0ecSDave Kleikamp 	journal_t *journal;
2505ac27a0ecSDave Kleikamp 	int err;
2506ac27a0ecSDave Kleikamp 
250764769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
250864769240SAlex Tomas 			test_opt(inode->i_sb, DELALLOC)) {
250964769240SAlex Tomas 		/*
251064769240SAlex Tomas 		 * With delalloc we want to sync the file
251164769240SAlex Tomas 		 * so that we can make sure we allocate
251264769240SAlex Tomas 		 * blocks for file
251364769240SAlex Tomas 		 */
251464769240SAlex Tomas 		filemap_write_and_wait(mapping);
251564769240SAlex Tomas 	}
251664769240SAlex Tomas 
251719f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
251819f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2519ac27a0ecSDave Kleikamp 		/*
2520ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
2521ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
2522ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
2523ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
2524ac27a0ecSDave Kleikamp 		 *
2525ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
2526ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
2527ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
2528ac27a0ecSDave Kleikamp 		 * will.)
2529ac27a0ecSDave Kleikamp 		 *
2530617ba13bSMingming Cao 		 * NB. EXT4_STATE_JDATA is not set on files other than
2531ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
2532ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
2533ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
2534ac27a0ecSDave Kleikamp 		 * everything they get.
2535ac27a0ecSDave Kleikamp 		 */
2536ac27a0ecSDave Kleikamp 
253719f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2538617ba13bSMingming Cao 		journal = EXT4_JOURNAL(inode);
2539dab291afSMingming Cao 		jbd2_journal_lock_updates(journal);
2540dab291afSMingming Cao 		err = jbd2_journal_flush(journal);
2541dab291afSMingming Cao 		jbd2_journal_unlock_updates(journal);
2542ac27a0ecSDave Kleikamp 
2543ac27a0ecSDave Kleikamp 		if (err)
2544ac27a0ecSDave Kleikamp 			return 0;
2545ac27a0ecSDave Kleikamp 	}
2546ac27a0ecSDave Kleikamp 
2547617ba13bSMingming Cao 	return generic_block_bmap(mapping, block, ext4_get_block);
2548ac27a0ecSDave Kleikamp }
2549ac27a0ecSDave Kleikamp 
2550617ba13bSMingming Cao static int ext4_readpage(struct file *file, struct page *page)
2551ac27a0ecSDave Kleikamp {
25520562e0baSJiaying Zhang 	trace_ext4_readpage(page);
2553617ba13bSMingming Cao 	return mpage_readpage(page, ext4_get_block);
2554ac27a0ecSDave Kleikamp }
2555ac27a0ecSDave Kleikamp 
2556ac27a0ecSDave Kleikamp static int
2557617ba13bSMingming Cao ext4_readpages(struct file *file, struct address_space *mapping,
2558ac27a0ecSDave Kleikamp 		struct list_head *pages, unsigned nr_pages)
2559ac27a0ecSDave Kleikamp {
2560617ba13bSMingming Cao 	return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2561ac27a0ecSDave Kleikamp }
2562ac27a0ecSDave Kleikamp 
2563744692dcSJiaying Zhang static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
2564744692dcSJiaying Zhang {
2565744692dcSJiaying Zhang 	struct buffer_head *head, *bh;
2566744692dcSJiaying Zhang 	unsigned int curr_off = 0;
2567744692dcSJiaying Zhang 
2568744692dcSJiaying Zhang 	if (!page_has_buffers(page))
2569744692dcSJiaying Zhang 		return;
2570744692dcSJiaying Zhang 	head = bh = page_buffers(page);
2571744692dcSJiaying Zhang 	do {
2572744692dcSJiaying Zhang 		if (offset <= curr_off && test_clear_buffer_uninit(bh)
2573744692dcSJiaying Zhang 					&& bh->b_private) {
2574744692dcSJiaying Zhang 			ext4_free_io_end(bh->b_private);
2575744692dcSJiaying Zhang 			bh->b_private = NULL;
2576744692dcSJiaying Zhang 			bh->b_end_io = NULL;
2577744692dcSJiaying Zhang 		}
2578744692dcSJiaying Zhang 		curr_off = curr_off + bh->b_size;
2579744692dcSJiaying Zhang 		bh = bh->b_this_page;
2580744692dcSJiaying Zhang 	} while (bh != head);
2581744692dcSJiaying Zhang }
2582744692dcSJiaying Zhang 
2583617ba13bSMingming Cao static void ext4_invalidatepage(struct page *page, unsigned long offset)
2584ac27a0ecSDave Kleikamp {
2585617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2586ac27a0ecSDave Kleikamp 
25870562e0baSJiaying Zhang 	trace_ext4_invalidatepage(page, offset);
25880562e0baSJiaying Zhang 
2589ac27a0ecSDave Kleikamp 	/*
2590744692dcSJiaying Zhang 	 * free any io_end structure allocated for buffers to be discarded
2591744692dcSJiaying Zhang 	 */
2592744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(page->mapping->host))
2593744692dcSJiaying Zhang 		ext4_invalidatepage_free_endio(page, offset);
2594744692dcSJiaying Zhang 	/*
2595ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
2596ac27a0ecSDave Kleikamp 	 */
2597ac27a0ecSDave Kleikamp 	if (offset == 0)
2598ac27a0ecSDave Kleikamp 		ClearPageChecked(page);
2599ac27a0ecSDave Kleikamp 
26000390131bSFrank Mayhar 	if (journal)
2601dab291afSMingming Cao 		jbd2_journal_invalidatepage(journal, page, offset);
26020390131bSFrank Mayhar 	else
26030390131bSFrank Mayhar 		block_invalidatepage(page, offset);
2604ac27a0ecSDave Kleikamp }
2605ac27a0ecSDave Kleikamp 
2606617ba13bSMingming Cao static int ext4_releasepage(struct page *page, gfp_t wait)
2607ac27a0ecSDave Kleikamp {
2608617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2609ac27a0ecSDave Kleikamp 
26100562e0baSJiaying Zhang 	trace_ext4_releasepage(page);
26110562e0baSJiaying Zhang 
2612ac27a0ecSDave Kleikamp 	WARN_ON(PageChecked(page));
2613ac27a0ecSDave Kleikamp 	if (!page_has_buffers(page))
2614ac27a0ecSDave Kleikamp 		return 0;
26150390131bSFrank Mayhar 	if (journal)
2616dab291afSMingming Cao 		return jbd2_journal_try_to_free_buffers(journal, page, wait);
26170390131bSFrank Mayhar 	else
26180390131bSFrank Mayhar 		return try_to_free_buffers(page);
2619ac27a0ecSDave Kleikamp }
2620ac27a0ecSDave Kleikamp 
2621ac27a0ecSDave Kleikamp /*
26222ed88685STheodore Ts'o  * ext4_get_block used when preparing for a DIO write or buffer write.
26232ed88685STheodore Ts'o  * We allocate an uinitialized extent if blocks haven't been allocated.
26242ed88685STheodore Ts'o  * The extent will be converted to initialized after the IO is complete.
26252ed88685STheodore Ts'o  */
2626c7064ef1SJiaying Zhang static int ext4_get_block_write(struct inode *inode, sector_t iblock,
26274c0425ffSMingming Cao 		   struct buffer_head *bh_result, int create)
26284c0425ffSMingming Cao {
2629c7064ef1SJiaying Zhang 	ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
26308d5d02e6SMingming Cao 		   inode->i_ino, create);
26312ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh_result,
26322ed88685STheodore Ts'o 			       EXT4_GET_BLOCKS_IO_CREATE_EXT);
26334c0425ffSMingming Cao }
26344c0425ffSMingming Cao 
26354c0425ffSMingming Cao static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2636552ef802SChristoph Hellwig 			    ssize_t size, void *private, int ret,
2637552ef802SChristoph Hellwig 			    bool is_async)
26384c0425ffSMingming Cao {
263972c5052dSChristoph Hellwig 	struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
26404c0425ffSMingming Cao         ext4_io_end_t *io_end = iocb->private;
26414c0425ffSMingming Cao 	struct workqueue_struct *wq;
2642744692dcSJiaying Zhang 	unsigned long flags;
2643744692dcSJiaying Zhang 	struct ext4_inode_info *ei;
26444c0425ffSMingming Cao 
26454b70df18SMingming 	/* if not async direct IO or dio with 0 bytes write, just return */
26464b70df18SMingming 	if (!io_end || !size)
2647552ef802SChristoph Hellwig 		goto out;
26484b70df18SMingming 
26498d5d02e6SMingming Cao 	ext_debug("ext4_end_io_dio(): io_end 0x%p"
26508d5d02e6SMingming Cao 		  "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
26518d5d02e6SMingming Cao  		  iocb->private, io_end->inode->i_ino, iocb, offset,
26528d5d02e6SMingming Cao 		  size);
26538d5d02e6SMingming Cao 
26548d5d02e6SMingming Cao 	/* if not aio dio with unwritten extents, just free io and return */
2655bd2d0210STheodore Ts'o 	if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
26568d5d02e6SMingming Cao 		ext4_free_io_end(io_end);
26578d5d02e6SMingming Cao 		iocb->private = NULL;
26585b3ff237Sjiayingz@google.com (Jiaying Zhang) out:
26595b3ff237Sjiayingz@google.com (Jiaying Zhang) 		if (is_async)
26605b3ff237Sjiayingz@google.com (Jiaying Zhang) 			aio_complete(iocb, ret, 0);
266172c5052dSChristoph Hellwig 		inode_dio_done(inode);
26625b3ff237Sjiayingz@google.com (Jiaying Zhang) 		return;
26638d5d02e6SMingming Cao 	}
26648d5d02e6SMingming Cao 
26654c0425ffSMingming Cao 	io_end->offset = offset;
26664c0425ffSMingming Cao 	io_end->size = size;
26675b3ff237Sjiayingz@google.com (Jiaying Zhang) 	if (is_async) {
26685b3ff237Sjiayingz@google.com (Jiaying Zhang) 		io_end->iocb = iocb;
26695b3ff237Sjiayingz@google.com (Jiaying Zhang) 		io_end->result = ret;
26705b3ff237Sjiayingz@google.com (Jiaying Zhang) 	}
26714c0425ffSMingming Cao 	wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
26724c0425ffSMingming Cao 
26738d5d02e6SMingming Cao 	/* Add the io_end to per-inode completed aio dio list*/
2674744692dcSJiaying Zhang 	ei = EXT4_I(io_end->inode);
2675744692dcSJiaying Zhang 	spin_lock_irqsave(&ei->i_completed_io_lock, flags);
2676744692dcSJiaying Zhang 	list_add_tail(&io_end->list, &ei->i_completed_io_list);
2677744692dcSJiaying Zhang 	spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
2678c999af2bSEric Sandeen 
2679c999af2bSEric Sandeen 	/* queue the work to convert unwritten extents to written */
2680c999af2bSEric Sandeen 	queue_work(wq, &io_end->work);
26814c0425ffSMingming Cao 	iocb->private = NULL;
268272c5052dSChristoph Hellwig 
268372c5052dSChristoph Hellwig 	/* XXX: probably should move into the real I/O completion handler */
268472c5052dSChristoph Hellwig 	inode_dio_done(inode);
26854c0425ffSMingming Cao }
2686c7064ef1SJiaying Zhang 
2687744692dcSJiaying Zhang static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
2688744692dcSJiaying Zhang {
2689744692dcSJiaying Zhang 	ext4_io_end_t *io_end = bh->b_private;
2690744692dcSJiaying Zhang 	struct workqueue_struct *wq;
2691744692dcSJiaying Zhang 	struct inode *inode;
2692744692dcSJiaying Zhang 	unsigned long flags;
2693744692dcSJiaying Zhang 
2694744692dcSJiaying Zhang 	if (!test_clear_buffer_uninit(bh) || !io_end)
2695744692dcSJiaying Zhang 		goto out;
2696744692dcSJiaying Zhang 
2697744692dcSJiaying Zhang 	if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
2698744692dcSJiaying Zhang 		printk("sb umounted, discard end_io request for inode %lu\n",
2699744692dcSJiaying Zhang 			io_end->inode->i_ino);
2700744692dcSJiaying Zhang 		ext4_free_io_end(io_end);
2701744692dcSJiaying Zhang 		goto out;
2702744692dcSJiaying Zhang 	}
2703744692dcSJiaying Zhang 
270432c80b32STao Ma 	/*
270532c80b32STao Ma 	 * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
270632c80b32STao Ma 	 * but being more careful is always safe for the future change.
270732c80b32STao Ma 	 */
2708744692dcSJiaying Zhang 	inode = io_end->inode;
270932c80b32STao Ma 	if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
271032c80b32STao Ma 		io_end->flag |= EXT4_IO_END_UNWRITTEN;
271132c80b32STao Ma 		atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
271232c80b32STao Ma 	}
2713744692dcSJiaying Zhang 
2714744692dcSJiaying Zhang 	/* Add the io_end to per-inode completed io list*/
2715744692dcSJiaying Zhang 	spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
2716744692dcSJiaying Zhang 	list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
2717744692dcSJiaying Zhang 	spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
2718744692dcSJiaying Zhang 
2719744692dcSJiaying Zhang 	wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
2720744692dcSJiaying Zhang 	/* queue the work to convert unwritten extents to written */
2721744692dcSJiaying Zhang 	queue_work(wq, &io_end->work);
2722744692dcSJiaying Zhang out:
2723744692dcSJiaying Zhang 	bh->b_private = NULL;
2724744692dcSJiaying Zhang 	bh->b_end_io = NULL;
2725744692dcSJiaying Zhang 	clear_buffer_uninit(bh);
2726744692dcSJiaying Zhang 	end_buffer_async_write(bh, uptodate);
2727744692dcSJiaying Zhang }
2728744692dcSJiaying Zhang 
2729744692dcSJiaying Zhang static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
2730744692dcSJiaying Zhang {
2731744692dcSJiaying Zhang 	ext4_io_end_t *io_end;
2732744692dcSJiaying Zhang 	struct page *page = bh->b_page;
2733744692dcSJiaying Zhang 	loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
2734744692dcSJiaying Zhang 	size_t size = bh->b_size;
2735744692dcSJiaying Zhang 
2736744692dcSJiaying Zhang retry:
2737744692dcSJiaying Zhang 	io_end = ext4_init_io_end(inode, GFP_ATOMIC);
2738744692dcSJiaying Zhang 	if (!io_end) {
27396db26ffcSAndrew Morton 		pr_warn_ratelimited("%s: allocation fail\n", __func__);
2740744692dcSJiaying Zhang 		schedule();
2741744692dcSJiaying Zhang 		goto retry;
2742744692dcSJiaying Zhang 	}
2743744692dcSJiaying Zhang 	io_end->offset = offset;
2744744692dcSJiaying Zhang 	io_end->size = size;
2745744692dcSJiaying Zhang 	/*
2746744692dcSJiaying Zhang 	 * We need to hold a reference to the page to make sure it
2747744692dcSJiaying Zhang 	 * doesn't get evicted before ext4_end_io_work() has a chance
2748744692dcSJiaying Zhang 	 * to convert the extent from written to unwritten.
2749744692dcSJiaying Zhang 	 */
2750744692dcSJiaying Zhang 	io_end->page = page;
2751744692dcSJiaying Zhang 	get_page(io_end->page);
2752744692dcSJiaying Zhang 
2753744692dcSJiaying Zhang 	bh->b_private = io_end;
2754744692dcSJiaying Zhang 	bh->b_end_io = ext4_end_io_buffer_write;
2755744692dcSJiaying Zhang 	return 0;
2756744692dcSJiaying Zhang }
2757744692dcSJiaying Zhang 
27584c0425ffSMingming Cao /*
27594c0425ffSMingming Cao  * For ext4 extent files, ext4 will do direct-io write to holes,
27604c0425ffSMingming Cao  * preallocated extents, and those write extend the file, no need to
27614c0425ffSMingming Cao  * fall back to buffered IO.
27624c0425ffSMingming Cao  *
2763b595076aSUwe Kleine-König  * For holes, we fallocate those blocks, mark them as uninitialized
27644c0425ffSMingming Cao  * If those blocks were preallocated, we mark sure they are splited, but
2765b595076aSUwe Kleine-König  * still keep the range to write as uninitialized.
27664c0425ffSMingming Cao  *
27678d5d02e6SMingming Cao  * The unwrritten extents will be converted to written when DIO is completed.
27688d5d02e6SMingming Cao  * For async direct IO, since the IO may still pending when return, we
276925985edcSLucas De Marchi  * set up an end_io call back function, which will do the conversion
27708d5d02e6SMingming Cao  * when async direct IO completed.
27714c0425ffSMingming Cao  *
27724c0425ffSMingming Cao  * If the O_DIRECT write will extend the file then add this inode to the
27734c0425ffSMingming Cao  * orphan list.  So recovery will truncate it back to the original size
27744c0425ffSMingming Cao  * if the machine crashes during the write.
27754c0425ffSMingming Cao  *
27764c0425ffSMingming Cao  */
27774c0425ffSMingming Cao static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
27784c0425ffSMingming Cao 			      const struct iovec *iov, loff_t offset,
27794c0425ffSMingming Cao 			      unsigned long nr_segs)
27804c0425ffSMingming Cao {
27814c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
27824c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
27834c0425ffSMingming Cao 	ssize_t ret;
27844c0425ffSMingming Cao 	size_t count = iov_length(iov, nr_segs);
27854c0425ffSMingming Cao 
27864c0425ffSMingming Cao 	loff_t final_size = offset + count;
27874c0425ffSMingming Cao 	if (rw == WRITE && final_size <= inode->i_size) {
27884c0425ffSMingming Cao 		/*
27898d5d02e6SMingming Cao  		 * We could direct write to holes and fallocate.
27908d5d02e6SMingming Cao 		 *
27918d5d02e6SMingming Cao  		 * Allocated blocks to fill the hole are marked as uninitialized
279225985edcSLucas De Marchi  		 * to prevent parallel buffered read to expose the stale data
27934c0425ffSMingming Cao  		 * before DIO complete the data IO.
27948d5d02e6SMingming Cao 		 *
27958d5d02e6SMingming Cao  		 * As to previously fallocated extents, ext4 get_block
27964c0425ffSMingming Cao  		 * will just simply mark the buffer mapped but still
27974c0425ffSMingming Cao  		 * keep the extents uninitialized.
27984c0425ffSMingming Cao  		 *
27998d5d02e6SMingming Cao 		 * for non AIO case, we will convert those unwritten extents
28008d5d02e6SMingming Cao 		 * to written after return back from blockdev_direct_IO.
28014c0425ffSMingming Cao 		 *
28028d5d02e6SMingming Cao 		 * for async DIO, the conversion needs to be defered when
28038d5d02e6SMingming Cao 		 * the IO is completed. The ext4 end_io callback function
28048d5d02e6SMingming Cao 		 * will be called to take care of the conversion work.
28058d5d02e6SMingming Cao 		 * Here for async case, we allocate an io_end structure to
28068d5d02e6SMingming Cao 		 * hook to the iocb.
28074c0425ffSMingming Cao  		 */
28088d5d02e6SMingming Cao 		iocb->private = NULL;
28098d5d02e6SMingming Cao 		EXT4_I(inode)->cur_aio_dio = NULL;
28108d5d02e6SMingming Cao 		if (!is_sync_kiocb(iocb)) {
2811744692dcSJiaying Zhang 			iocb->private = ext4_init_io_end(inode, GFP_NOFS);
28124c0425ffSMingming Cao 			if (!iocb->private)
28134c0425ffSMingming Cao 				return -ENOMEM;
28148d5d02e6SMingming Cao 			/*
28158d5d02e6SMingming Cao 			 * we save the io structure for current async
281679e83036SEric Sandeen 			 * direct IO, so that later ext4_map_blocks()
28178d5d02e6SMingming Cao 			 * could flag the io structure whether there
28188d5d02e6SMingming Cao 			 * is a unwritten extents needs to be converted
28198d5d02e6SMingming Cao 			 * when IO is completed.
28208d5d02e6SMingming Cao 			 */
28218d5d02e6SMingming Cao 			EXT4_I(inode)->cur_aio_dio = iocb->private;
28228d5d02e6SMingming Cao 		}
28238d5d02e6SMingming Cao 
2824aacfc19cSChristoph Hellwig 		ret = __blockdev_direct_IO(rw, iocb, inode,
28254c0425ffSMingming Cao 					 inode->i_sb->s_bdev, iov,
28264c0425ffSMingming Cao 					 offset, nr_segs,
2827c7064ef1SJiaying Zhang 					 ext4_get_block_write,
2828aacfc19cSChristoph Hellwig 					 ext4_end_io_dio,
2829aacfc19cSChristoph Hellwig 					 NULL,
2830aacfc19cSChristoph Hellwig 					 DIO_LOCKING | DIO_SKIP_HOLES);
28318d5d02e6SMingming Cao 		if (iocb->private)
28328d5d02e6SMingming Cao 			EXT4_I(inode)->cur_aio_dio = NULL;
28338d5d02e6SMingming Cao 		/*
28348d5d02e6SMingming Cao 		 * The io_end structure takes a reference to the inode,
28358d5d02e6SMingming Cao 		 * that structure needs to be destroyed and the
28368d5d02e6SMingming Cao 		 * reference to the inode need to be dropped, when IO is
28378d5d02e6SMingming Cao 		 * complete, even with 0 byte write, or failed.
28388d5d02e6SMingming Cao 		 *
28398d5d02e6SMingming Cao 		 * In the successful AIO DIO case, the io_end structure will be
28408d5d02e6SMingming Cao 		 * desctroyed and the reference to the inode will be dropped
28418d5d02e6SMingming Cao 		 * after the end_io call back function is called.
28428d5d02e6SMingming Cao 		 *
28438d5d02e6SMingming Cao 		 * In the case there is 0 byte write, or error case, since
28448d5d02e6SMingming Cao 		 * VFS direct IO won't invoke the end_io call back function,
28458d5d02e6SMingming Cao 		 * we need to free the end_io structure here.
28468d5d02e6SMingming Cao 		 */
28478d5d02e6SMingming Cao 		if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
28488d5d02e6SMingming Cao 			ext4_free_io_end(iocb->private);
28498d5d02e6SMingming Cao 			iocb->private = NULL;
285019f5fb7aSTheodore Ts'o 		} else if (ret > 0 && ext4_test_inode_state(inode,
28515f524950SMingming 						EXT4_STATE_DIO_UNWRITTEN)) {
2852109f5565SMingming 			int err;
28538d5d02e6SMingming Cao 			/*
28548d5d02e6SMingming Cao 			 * for non AIO case, since the IO is already
285525985edcSLucas De Marchi 			 * completed, we could do the conversion right here
28568d5d02e6SMingming Cao 			 */
2857109f5565SMingming 			err = ext4_convert_unwritten_extents(inode,
28588d5d02e6SMingming Cao 							     offset, ret);
2859109f5565SMingming 			if (err < 0)
2860109f5565SMingming 				ret = err;
286119f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
2862109f5565SMingming 		}
28634c0425ffSMingming Cao 		return ret;
28644c0425ffSMingming Cao 	}
28658d5d02e6SMingming Cao 
28668d5d02e6SMingming Cao 	/* for write the the end of file case, we fall back to old way */
28674c0425ffSMingming Cao 	return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
28684c0425ffSMingming Cao }
28694c0425ffSMingming Cao 
28704c0425ffSMingming Cao static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
28714c0425ffSMingming Cao 			      const struct iovec *iov, loff_t offset,
28724c0425ffSMingming Cao 			      unsigned long nr_segs)
28734c0425ffSMingming Cao {
28744c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
28754c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
28760562e0baSJiaying Zhang 	ssize_t ret;
28774c0425ffSMingming Cao 
287884ebd795STheodore Ts'o 	/*
287984ebd795STheodore Ts'o 	 * If we are doing data journalling we don't support O_DIRECT
288084ebd795STheodore Ts'o 	 */
288184ebd795STheodore Ts'o 	if (ext4_should_journal_data(inode))
288284ebd795STheodore Ts'o 		return 0;
288384ebd795STheodore Ts'o 
28840562e0baSJiaying Zhang 	trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
288512e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
28860562e0baSJiaying Zhang 		ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
28870562e0baSJiaying Zhang 	else
28880562e0baSJiaying Zhang 		ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
28890562e0baSJiaying Zhang 	trace_ext4_direct_IO_exit(inode, offset,
28900562e0baSJiaying Zhang 				iov_length(iov, nr_segs), rw, ret);
28910562e0baSJiaying Zhang 	return ret;
28924c0425ffSMingming Cao }
28934c0425ffSMingming Cao 
2894ac27a0ecSDave Kleikamp /*
2895617ba13bSMingming Cao  * Pages can be marked dirty completely asynchronously from ext4's journalling
2896ac27a0ecSDave Kleikamp  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
2897ac27a0ecSDave Kleikamp  * much here because ->set_page_dirty is called under VFS locks.  The page is
2898ac27a0ecSDave Kleikamp  * not necessarily locked.
2899ac27a0ecSDave Kleikamp  *
2900ac27a0ecSDave Kleikamp  * We cannot just dirty the page and leave attached buffers clean, because the
2901ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
2902ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
2903ac27a0ecSDave Kleikamp  *
2904ac27a0ecSDave Kleikamp  * So what we do is to mark the page "pending dirty" and next time writepage
2905ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
2906ac27a0ecSDave Kleikamp  */
2907617ba13bSMingming Cao static int ext4_journalled_set_page_dirty(struct page *page)
2908ac27a0ecSDave Kleikamp {
2909ac27a0ecSDave Kleikamp 	SetPageChecked(page);
2910ac27a0ecSDave Kleikamp 	return __set_page_dirty_nobuffers(page);
2911ac27a0ecSDave Kleikamp }
2912ac27a0ecSDave Kleikamp 
2913617ba13bSMingming Cao static const struct address_space_operations ext4_ordered_aops = {
2914617ba13bSMingming Cao 	.readpage		= ext4_readpage,
2915617ba13bSMingming Cao 	.readpages		= ext4_readpages,
291643ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
2917bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
2918bfc1af65SNick Piggin 	.write_end		= ext4_ordered_write_end,
2919617ba13bSMingming Cao 	.bmap			= ext4_bmap,
2920617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
2921617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
2922617ba13bSMingming Cao 	.direct_IO		= ext4_direct_IO,
2923ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
29248ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
2925aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
2926ac27a0ecSDave Kleikamp };
2927ac27a0ecSDave Kleikamp 
2928617ba13bSMingming Cao static const struct address_space_operations ext4_writeback_aops = {
2929617ba13bSMingming Cao 	.readpage		= ext4_readpage,
2930617ba13bSMingming Cao 	.readpages		= ext4_readpages,
293143ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
2932bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
2933bfc1af65SNick Piggin 	.write_end		= ext4_writeback_write_end,
2934617ba13bSMingming Cao 	.bmap			= ext4_bmap,
2935617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
2936617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
2937617ba13bSMingming Cao 	.direct_IO		= ext4_direct_IO,
2938ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
29398ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
2940aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
2941ac27a0ecSDave Kleikamp };
2942ac27a0ecSDave Kleikamp 
2943617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
2944617ba13bSMingming Cao 	.readpage		= ext4_readpage,
2945617ba13bSMingming Cao 	.readpages		= ext4_readpages,
294643ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
2947bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
2948bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
2949617ba13bSMingming Cao 	.set_page_dirty		= ext4_journalled_set_page_dirty,
2950617ba13bSMingming Cao 	.bmap			= ext4_bmap,
2951617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
2952617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
295384ebd795STheodore Ts'o 	.direct_IO		= ext4_direct_IO,
29548ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
2955aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
2956ac27a0ecSDave Kleikamp };
2957ac27a0ecSDave Kleikamp 
295864769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
295964769240SAlex Tomas 	.readpage		= ext4_readpage,
296064769240SAlex Tomas 	.readpages		= ext4_readpages,
296143ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
296264769240SAlex Tomas 	.writepages		= ext4_da_writepages,
296364769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
296464769240SAlex Tomas 	.write_end		= ext4_da_write_end,
296564769240SAlex Tomas 	.bmap			= ext4_bmap,
296664769240SAlex Tomas 	.invalidatepage		= ext4_da_invalidatepage,
296764769240SAlex Tomas 	.releasepage		= ext4_releasepage,
296864769240SAlex Tomas 	.direct_IO		= ext4_direct_IO,
296964769240SAlex Tomas 	.migratepage		= buffer_migrate_page,
29708ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
2971aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
297264769240SAlex Tomas };
297364769240SAlex Tomas 
2974617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
2975ac27a0ecSDave Kleikamp {
2976cd1aac32SAneesh Kumar K.V 	if (ext4_should_order_data(inode) &&
2977cd1aac32SAneesh Kumar K.V 		test_opt(inode->i_sb, DELALLOC))
2978cd1aac32SAneesh Kumar K.V 		inode->i_mapping->a_ops = &ext4_da_aops;
2979cd1aac32SAneesh Kumar K.V 	else if (ext4_should_order_data(inode))
2980617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_ordered_aops;
298164769240SAlex Tomas 	else if (ext4_should_writeback_data(inode) &&
298264769240SAlex Tomas 		 test_opt(inode->i_sb, DELALLOC))
298364769240SAlex Tomas 		inode->i_mapping->a_ops = &ext4_da_aops;
2984617ba13bSMingming Cao 	else if (ext4_should_writeback_data(inode))
2985617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_writeback_aops;
2986ac27a0ecSDave Kleikamp 	else
2987617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
2988ac27a0ecSDave Kleikamp }
2989ac27a0ecSDave Kleikamp 
29904e96b2dbSAllison Henderson 
29914e96b2dbSAllison Henderson /*
29924e96b2dbSAllison Henderson  * ext4_discard_partial_page_buffers()
29934e96b2dbSAllison Henderson  * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
29944e96b2dbSAllison Henderson  * This function finds and locks the page containing the offset
29954e96b2dbSAllison Henderson  * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
29964e96b2dbSAllison Henderson  * Calling functions that already have the page locked should call
29974e96b2dbSAllison Henderson  * ext4_discard_partial_page_buffers_no_lock directly.
29984e96b2dbSAllison Henderson  */
29994e96b2dbSAllison Henderson int ext4_discard_partial_page_buffers(handle_t *handle,
30004e96b2dbSAllison Henderson 		struct address_space *mapping, loff_t from,
30014e96b2dbSAllison Henderson 		loff_t length, int flags)
30024e96b2dbSAllison Henderson {
30034e96b2dbSAllison Henderson 	struct inode *inode = mapping->host;
30044e96b2dbSAllison Henderson 	struct page *page;
30054e96b2dbSAllison Henderson 	int err = 0;
30064e96b2dbSAllison Henderson 
30074e96b2dbSAllison Henderson 	page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
30084e96b2dbSAllison Henderson 				   mapping_gfp_mask(mapping) & ~__GFP_FS);
30094e96b2dbSAllison Henderson 	if (!page)
30104e96b2dbSAllison Henderson 		return -EINVAL;
30114e96b2dbSAllison Henderson 
30124e96b2dbSAllison Henderson 	err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
30134e96b2dbSAllison Henderson 		from, length, flags);
30144e96b2dbSAllison Henderson 
30154e96b2dbSAllison Henderson 	unlock_page(page);
30164e96b2dbSAllison Henderson 	page_cache_release(page);
30174e96b2dbSAllison Henderson 	return err;
30184e96b2dbSAllison Henderson }
30194e96b2dbSAllison Henderson 
30204e96b2dbSAllison Henderson /*
30214e96b2dbSAllison Henderson  * ext4_discard_partial_page_buffers_no_lock()
30224e96b2dbSAllison Henderson  * Zeros a page range of length 'length' starting from offset 'from'.
30234e96b2dbSAllison Henderson  * Buffer heads that correspond to the block aligned regions of the
30244e96b2dbSAllison Henderson  * zeroed range will be unmapped.  Unblock aligned regions
30254e96b2dbSAllison Henderson  * will have the corresponding buffer head mapped if needed so that
30264e96b2dbSAllison Henderson  * that region of the page can be updated with the partial zero out.
30274e96b2dbSAllison Henderson  *
30284e96b2dbSAllison Henderson  * This function assumes that the page has already been  locked.  The
30294e96b2dbSAllison Henderson  * The range to be discarded must be contained with in the given page.
30304e96b2dbSAllison Henderson  * If the specified range exceeds the end of the page it will be shortened
30314e96b2dbSAllison Henderson  * to the end of the page that corresponds to 'from'.  This function is
30324e96b2dbSAllison Henderson  * appropriate for updating a page and it buffer heads to be unmapped and
30334e96b2dbSAllison Henderson  * zeroed for blocks that have been either released, or are going to be
30344e96b2dbSAllison Henderson  * released.
30354e96b2dbSAllison Henderson  *
30364e96b2dbSAllison Henderson  * handle: The journal handle
30374e96b2dbSAllison Henderson  * inode:  The files inode
30384e96b2dbSAllison Henderson  * page:   A locked page that contains the offset "from"
30394e96b2dbSAllison Henderson  * from:   The starting byte offset (from the begining of the file)
30404e96b2dbSAllison Henderson  *         to begin discarding
30414e96b2dbSAllison Henderson  * len:    The length of bytes to discard
30424e96b2dbSAllison Henderson  * flags:  Optional flags that may be used:
30434e96b2dbSAllison Henderson  *
30444e96b2dbSAllison Henderson  *         EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
30454e96b2dbSAllison Henderson  *         Only zero the regions of the page whose buffer heads
30464e96b2dbSAllison Henderson  *         have already been unmapped.  This flag is appropriate
30474e96b2dbSAllison Henderson  *         for updateing the contents of a page whose blocks may
30484e96b2dbSAllison Henderson  *         have already been released, and we only want to zero
30494e96b2dbSAllison Henderson  *         out the regions that correspond to those released blocks.
30504e96b2dbSAllison Henderson  *
30514e96b2dbSAllison Henderson  * Returns zero on sucess or negative on failure.
30524e96b2dbSAllison Henderson  */
30534e96b2dbSAllison Henderson int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
30544e96b2dbSAllison Henderson 		struct inode *inode, struct page *page, loff_t from,
30554e96b2dbSAllison Henderson 		loff_t length, int flags)
30564e96b2dbSAllison Henderson {
30574e96b2dbSAllison Henderson 	ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
30584e96b2dbSAllison Henderson 	unsigned int offset = from & (PAGE_CACHE_SIZE-1);
30594e96b2dbSAllison Henderson 	unsigned int blocksize, max, pos;
30604e96b2dbSAllison Henderson 	unsigned int end_of_block, range_to_discard;
30614e96b2dbSAllison Henderson 	ext4_lblk_t iblock;
30624e96b2dbSAllison Henderson 	struct buffer_head *bh;
30634e96b2dbSAllison Henderson 	int err = 0;
30644e96b2dbSAllison Henderson 
30654e96b2dbSAllison Henderson 	blocksize = inode->i_sb->s_blocksize;
30664e96b2dbSAllison Henderson 	max = PAGE_CACHE_SIZE - offset;
30674e96b2dbSAllison Henderson 
30684e96b2dbSAllison Henderson 	if (index != page->index)
30694e96b2dbSAllison Henderson 		return -EINVAL;
30704e96b2dbSAllison Henderson 
30714e96b2dbSAllison Henderson 	/*
30724e96b2dbSAllison Henderson 	 * correct length if it does not fall between
30734e96b2dbSAllison Henderson 	 * 'from' and the end of the page
30744e96b2dbSAllison Henderson 	 */
30754e96b2dbSAllison Henderson 	if (length > max || length < 0)
30764e96b2dbSAllison Henderson 		length = max;
30774e96b2dbSAllison Henderson 
30784e96b2dbSAllison Henderson 	iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
30794e96b2dbSAllison Henderson 
30804e96b2dbSAllison Henderson 	if (!page_has_buffers(page)) {
30814e96b2dbSAllison Henderson 		/*
30824e96b2dbSAllison Henderson 		 * If the range to be discarded covers a partial block
30834e96b2dbSAllison Henderson 		 * we need to get the page buffers.  This is because
30844e96b2dbSAllison Henderson 		 * partial blocks cannot be released and the page needs
30854e96b2dbSAllison Henderson 		 * to be updated with the contents of the block before
30864e96b2dbSAllison Henderson 		 * we write the zeros on top of it.
30874e96b2dbSAllison Henderson 		 */
30884e96b2dbSAllison Henderson 		if (!(from & (blocksize - 1)) ||
30894e96b2dbSAllison Henderson 		    !((from + length) & (blocksize - 1))) {
30904e96b2dbSAllison Henderson 			create_empty_buffers(page, blocksize, 0);
30914e96b2dbSAllison Henderson 		} else {
30924e96b2dbSAllison Henderson 			/*
30934e96b2dbSAllison Henderson 			 * If there are no partial blocks,
30944e96b2dbSAllison Henderson 			 * there is nothing to update,
30954e96b2dbSAllison Henderson 			 * so we can return now
30964e96b2dbSAllison Henderson 			 */
30974e96b2dbSAllison Henderson 			return 0;
30984e96b2dbSAllison Henderson 		}
30994e96b2dbSAllison Henderson 	}
31004e96b2dbSAllison Henderson 
31014e96b2dbSAllison Henderson 	/* Find the buffer that contains "offset" */
31024e96b2dbSAllison Henderson 	bh = page_buffers(page);
31034e96b2dbSAllison Henderson 	pos = blocksize;
31044e96b2dbSAllison Henderson 	while (offset >= pos) {
31054e96b2dbSAllison Henderson 		bh = bh->b_this_page;
31064e96b2dbSAllison Henderson 		iblock++;
31074e96b2dbSAllison Henderson 		pos += blocksize;
31084e96b2dbSAllison Henderson 	}
31094e96b2dbSAllison Henderson 
31104e96b2dbSAllison Henderson 	pos = offset;
31114e96b2dbSAllison Henderson 	while (pos < offset + length) {
31124e96b2dbSAllison Henderson 		err = 0;
31134e96b2dbSAllison Henderson 
31144e96b2dbSAllison Henderson 		/* The length of space left to zero and unmap */
31154e96b2dbSAllison Henderson 		range_to_discard = offset + length - pos;
31164e96b2dbSAllison Henderson 
31174e96b2dbSAllison Henderson 		/* The length of space until the end of the block */
31184e96b2dbSAllison Henderson 		end_of_block = blocksize - (pos & (blocksize-1));
31194e96b2dbSAllison Henderson 
31204e96b2dbSAllison Henderson 		/*
31214e96b2dbSAllison Henderson 		 * Do not unmap or zero past end of block
31224e96b2dbSAllison Henderson 		 * for this buffer head
31234e96b2dbSAllison Henderson 		 */
31244e96b2dbSAllison Henderson 		if (range_to_discard > end_of_block)
31254e96b2dbSAllison Henderson 			range_to_discard = end_of_block;
31264e96b2dbSAllison Henderson 
31274e96b2dbSAllison Henderson 
31284e96b2dbSAllison Henderson 		/*
31294e96b2dbSAllison Henderson 		 * Skip this buffer head if we are only zeroing unampped
31304e96b2dbSAllison Henderson 		 * regions of the page
31314e96b2dbSAllison Henderson 		 */
31324e96b2dbSAllison Henderson 		if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
31334e96b2dbSAllison Henderson 			buffer_mapped(bh))
31344e96b2dbSAllison Henderson 				goto next;
31354e96b2dbSAllison Henderson 
31364e96b2dbSAllison Henderson 		/* If the range is block aligned, unmap */
31374e96b2dbSAllison Henderson 		if (range_to_discard == blocksize) {
31384e96b2dbSAllison Henderson 			clear_buffer_dirty(bh);
31394e96b2dbSAllison Henderson 			bh->b_bdev = NULL;
31404e96b2dbSAllison Henderson 			clear_buffer_mapped(bh);
31414e96b2dbSAllison Henderson 			clear_buffer_req(bh);
31424e96b2dbSAllison Henderson 			clear_buffer_new(bh);
31434e96b2dbSAllison Henderson 			clear_buffer_delay(bh);
31444e96b2dbSAllison Henderson 			clear_buffer_unwritten(bh);
31454e96b2dbSAllison Henderson 			clear_buffer_uptodate(bh);
31464e96b2dbSAllison Henderson 			zero_user(page, pos, range_to_discard);
31474e96b2dbSAllison Henderson 			BUFFER_TRACE(bh, "Buffer discarded");
31484e96b2dbSAllison Henderson 			goto next;
31494e96b2dbSAllison Henderson 		}
31504e96b2dbSAllison Henderson 
31514e96b2dbSAllison Henderson 		/*
31524e96b2dbSAllison Henderson 		 * If this block is not completely contained in the range
31534e96b2dbSAllison Henderson 		 * to be discarded, then it is not going to be released. Because
31544e96b2dbSAllison Henderson 		 * we need to keep this block, we need to make sure this part
31554e96b2dbSAllison Henderson 		 * of the page is uptodate before we modify it by writeing
31564e96b2dbSAllison Henderson 		 * partial zeros on it.
31574e96b2dbSAllison Henderson 		 */
31584e96b2dbSAllison Henderson 		if (!buffer_mapped(bh)) {
31594e96b2dbSAllison Henderson 			/*
31604e96b2dbSAllison Henderson 			 * Buffer head must be mapped before we can read
31614e96b2dbSAllison Henderson 			 * from the block
31624e96b2dbSAllison Henderson 			 */
31634e96b2dbSAllison Henderson 			BUFFER_TRACE(bh, "unmapped");
31644e96b2dbSAllison Henderson 			ext4_get_block(inode, iblock, bh, 0);
31654e96b2dbSAllison Henderson 			/* unmapped? It's a hole - nothing to do */
31664e96b2dbSAllison Henderson 			if (!buffer_mapped(bh)) {
31674e96b2dbSAllison Henderson 				BUFFER_TRACE(bh, "still unmapped");
31684e96b2dbSAllison Henderson 				goto next;
31694e96b2dbSAllison Henderson 			}
31704e96b2dbSAllison Henderson 		}
31714e96b2dbSAllison Henderson 
31724e96b2dbSAllison Henderson 		/* Ok, it's mapped. Make sure it's up-to-date */
31734e96b2dbSAllison Henderson 		if (PageUptodate(page))
31744e96b2dbSAllison Henderson 			set_buffer_uptodate(bh);
31754e96b2dbSAllison Henderson 
31764e96b2dbSAllison Henderson 		if (!buffer_uptodate(bh)) {
31774e96b2dbSAllison Henderson 			err = -EIO;
31784e96b2dbSAllison Henderson 			ll_rw_block(READ, 1, &bh);
31794e96b2dbSAllison Henderson 			wait_on_buffer(bh);
31804e96b2dbSAllison Henderson 			/* Uhhuh. Read error. Complain and punt.*/
31814e96b2dbSAllison Henderson 			if (!buffer_uptodate(bh))
31824e96b2dbSAllison Henderson 				goto next;
31834e96b2dbSAllison Henderson 		}
31844e96b2dbSAllison Henderson 
31854e96b2dbSAllison Henderson 		if (ext4_should_journal_data(inode)) {
31864e96b2dbSAllison Henderson 			BUFFER_TRACE(bh, "get write access");
31874e96b2dbSAllison Henderson 			err = ext4_journal_get_write_access(handle, bh);
31884e96b2dbSAllison Henderson 			if (err)
31894e96b2dbSAllison Henderson 				goto next;
31904e96b2dbSAllison Henderson 		}
31914e96b2dbSAllison Henderson 
31924e96b2dbSAllison Henderson 		zero_user(page, pos, range_to_discard);
31934e96b2dbSAllison Henderson 
31944e96b2dbSAllison Henderson 		err = 0;
31954e96b2dbSAllison Henderson 		if (ext4_should_journal_data(inode)) {
31964e96b2dbSAllison Henderson 			err = ext4_handle_dirty_metadata(handle, inode, bh);
3197decbd919STheodore Ts'o 		} else
31984e96b2dbSAllison Henderson 			mark_buffer_dirty(bh);
31994e96b2dbSAllison Henderson 
32004e96b2dbSAllison Henderson 		BUFFER_TRACE(bh, "Partial buffer zeroed");
32014e96b2dbSAllison Henderson next:
32024e96b2dbSAllison Henderson 		bh = bh->b_this_page;
32034e96b2dbSAllison Henderson 		iblock++;
32044e96b2dbSAllison Henderson 		pos += range_to_discard;
32054e96b2dbSAllison Henderson 	}
32064e96b2dbSAllison Henderson 
32074e96b2dbSAllison Henderson 	return err;
32084e96b2dbSAllison Henderson }
32094e96b2dbSAllison Henderson 
3210ac27a0ecSDave Kleikamp /*
3211617ba13bSMingming Cao  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3212ac27a0ecSDave Kleikamp  * up to the end of the block which corresponds to `from'.
3213ac27a0ecSDave Kleikamp  * This required during truncate. We need to physically zero the tail end
3214ac27a0ecSDave Kleikamp  * of that block so it doesn't yield old data if the file is later grown.
3215ac27a0ecSDave Kleikamp  */
3216cf108bcaSJan Kara int ext4_block_truncate_page(handle_t *handle,
3217ac27a0ecSDave Kleikamp 		struct address_space *mapping, loff_t from)
3218ac27a0ecSDave Kleikamp {
321930848851SAllison Henderson 	unsigned offset = from & (PAGE_CACHE_SIZE-1);
322030848851SAllison Henderson 	unsigned length;
322130848851SAllison Henderson 	unsigned blocksize;
322230848851SAllison Henderson 	struct inode *inode = mapping->host;
322330848851SAllison Henderson 
322430848851SAllison Henderson 	blocksize = inode->i_sb->s_blocksize;
322530848851SAllison Henderson 	length = blocksize - (offset & (blocksize - 1));
322630848851SAllison Henderson 
322730848851SAllison Henderson 	return ext4_block_zero_page_range(handle, mapping, from, length);
322830848851SAllison Henderson }
322930848851SAllison Henderson 
323030848851SAllison Henderson /*
323130848851SAllison Henderson  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
323230848851SAllison Henderson  * starting from file offset 'from'.  The range to be zero'd must
323330848851SAllison Henderson  * be contained with in one block.  If the specified range exceeds
323430848851SAllison Henderson  * the end of the block it will be shortened to end of the block
323530848851SAllison Henderson  * that cooresponds to 'from'
323630848851SAllison Henderson  */
323730848851SAllison Henderson int ext4_block_zero_page_range(handle_t *handle,
323830848851SAllison Henderson 		struct address_space *mapping, loff_t from, loff_t length)
323930848851SAllison Henderson {
3240617ba13bSMingming Cao 	ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3241ac27a0ecSDave Kleikamp 	unsigned offset = from & (PAGE_CACHE_SIZE-1);
324230848851SAllison Henderson 	unsigned blocksize, max, pos;
3243725d26d3SAneesh Kumar K.V 	ext4_lblk_t iblock;
3244ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3245ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
3246cf108bcaSJan Kara 	struct page *page;
3247ac27a0ecSDave Kleikamp 	int err = 0;
3248ac27a0ecSDave Kleikamp 
3249f4a01017STheodore Ts'o 	page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3250f4a01017STheodore Ts'o 				   mapping_gfp_mask(mapping) & ~__GFP_FS);
3251cf108bcaSJan Kara 	if (!page)
3252cf108bcaSJan Kara 		return -EINVAL;
3253cf108bcaSJan Kara 
3254ac27a0ecSDave Kleikamp 	blocksize = inode->i_sb->s_blocksize;
325530848851SAllison Henderson 	max = blocksize - (offset & (blocksize - 1));
325630848851SAllison Henderson 
325730848851SAllison Henderson 	/*
325830848851SAllison Henderson 	 * correct length if it does not fall between
325930848851SAllison Henderson 	 * 'from' and the end of the block
326030848851SAllison Henderson 	 */
326130848851SAllison Henderson 	if (length > max || length < 0)
326230848851SAllison Henderson 		length = max;
326330848851SAllison Henderson 
3264ac27a0ecSDave Kleikamp 	iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3265ac27a0ecSDave Kleikamp 
3266ac27a0ecSDave Kleikamp 	if (!page_has_buffers(page))
3267ac27a0ecSDave Kleikamp 		create_empty_buffers(page, blocksize, 0);
3268ac27a0ecSDave Kleikamp 
3269ac27a0ecSDave Kleikamp 	/* Find the buffer that contains "offset" */
3270ac27a0ecSDave Kleikamp 	bh = page_buffers(page);
3271ac27a0ecSDave Kleikamp 	pos = blocksize;
3272ac27a0ecSDave Kleikamp 	while (offset >= pos) {
3273ac27a0ecSDave Kleikamp 		bh = bh->b_this_page;
3274ac27a0ecSDave Kleikamp 		iblock++;
3275ac27a0ecSDave Kleikamp 		pos += blocksize;
3276ac27a0ecSDave Kleikamp 	}
3277ac27a0ecSDave Kleikamp 
3278ac27a0ecSDave Kleikamp 	err = 0;
3279ac27a0ecSDave Kleikamp 	if (buffer_freed(bh)) {
3280ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "freed: skip");
3281ac27a0ecSDave Kleikamp 		goto unlock;
3282ac27a0ecSDave Kleikamp 	}
3283ac27a0ecSDave Kleikamp 
3284ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh)) {
3285ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "unmapped");
3286617ba13bSMingming Cao 		ext4_get_block(inode, iblock, bh, 0);
3287ac27a0ecSDave Kleikamp 		/* unmapped? It's a hole - nothing to do */
3288ac27a0ecSDave Kleikamp 		if (!buffer_mapped(bh)) {
3289ac27a0ecSDave Kleikamp 			BUFFER_TRACE(bh, "still unmapped");
3290ac27a0ecSDave Kleikamp 			goto unlock;
3291ac27a0ecSDave Kleikamp 		}
3292ac27a0ecSDave Kleikamp 	}
3293ac27a0ecSDave Kleikamp 
3294ac27a0ecSDave Kleikamp 	/* Ok, it's mapped. Make sure it's up-to-date */
3295ac27a0ecSDave Kleikamp 	if (PageUptodate(page))
3296ac27a0ecSDave Kleikamp 		set_buffer_uptodate(bh);
3297ac27a0ecSDave Kleikamp 
3298ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
3299ac27a0ecSDave Kleikamp 		err = -EIO;
3300ac27a0ecSDave Kleikamp 		ll_rw_block(READ, 1, &bh);
3301ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
3302ac27a0ecSDave Kleikamp 		/* Uhhuh. Read error. Complain and punt. */
3303ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh))
3304ac27a0ecSDave Kleikamp 			goto unlock;
3305ac27a0ecSDave Kleikamp 	}
3306ac27a0ecSDave Kleikamp 
3307617ba13bSMingming Cao 	if (ext4_should_journal_data(inode)) {
3308ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "get write access");
3309617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, bh);
3310ac27a0ecSDave Kleikamp 		if (err)
3311ac27a0ecSDave Kleikamp 			goto unlock;
3312ac27a0ecSDave Kleikamp 	}
3313ac27a0ecSDave Kleikamp 
3314eebd2aa3SChristoph Lameter 	zero_user(page, offset, length);
3315ac27a0ecSDave Kleikamp 
3316ac27a0ecSDave Kleikamp 	BUFFER_TRACE(bh, "zeroed end of block");
3317ac27a0ecSDave Kleikamp 
3318ac27a0ecSDave Kleikamp 	err = 0;
3319617ba13bSMingming Cao 	if (ext4_should_journal_data(inode)) {
33200390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
3321decbd919STheodore Ts'o 	} else
3322ac27a0ecSDave Kleikamp 		mark_buffer_dirty(bh);
3323ac27a0ecSDave Kleikamp 
3324ac27a0ecSDave Kleikamp unlock:
3325ac27a0ecSDave Kleikamp 	unlock_page(page);
3326ac27a0ecSDave Kleikamp 	page_cache_release(page);
3327ac27a0ecSDave Kleikamp 	return err;
3328ac27a0ecSDave Kleikamp }
3329ac27a0ecSDave Kleikamp 
333091ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
333191ef4cafSDuane Griffin {
333291ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
333391ef4cafSDuane Griffin 		return 1;
333491ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
333591ef4cafSDuane Griffin 		return 1;
333691ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
333791ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
333891ef4cafSDuane Griffin 	return 0;
333991ef4cafSDuane Griffin }
334091ef4cafSDuane Griffin 
3341ac27a0ecSDave Kleikamp /*
3342a4bb6b64SAllison Henderson  * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3343a4bb6b64SAllison Henderson  * associated with the given offset and length
3344a4bb6b64SAllison Henderson  *
3345a4bb6b64SAllison Henderson  * @inode:  File inode
3346a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3347a4bb6b64SAllison Henderson  * @len:    The length of the hole
3348a4bb6b64SAllison Henderson  *
3349a4bb6b64SAllison Henderson  * Returns: 0 on sucess or negative on failure
3350a4bb6b64SAllison Henderson  */
3351a4bb6b64SAllison Henderson 
3352a4bb6b64SAllison Henderson int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3353a4bb6b64SAllison Henderson {
3354a4bb6b64SAllison Henderson 	struct inode *inode = file->f_path.dentry->d_inode;
3355a4bb6b64SAllison Henderson 	if (!S_ISREG(inode->i_mode))
3356a4bb6b64SAllison Henderson 		return -ENOTSUPP;
3357a4bb6b64SAllison Henderson 
3358a4bb6b64SAllison Henderson 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3359a4bb6b64SAllison Henderson 		/* TODO: Add support for non extent hole punching */
3360a4bb6b64SAllison Henderson 		return -ENOTSUPP;
3361a4bb6b64SAllison Henderson 	}
3362a4bb6b64SAllison Henderson 
3363bab08ab9STheodore Ts'o 	if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3364bab08ab9STheodore Ts'o 		/* TODO: Add support for bigalloc file systems */
3365bab08ab9STheodore Ts'o 		return -ENOTSUPP;
3366bab08ab9STheodore Ts'o 	}
3367bab08ab9STheodore Ts'o 
3368a4bb6b64SAllison Henderson 	return ext4_ext_punch_hole(file, offset, length);
3369a4bb6b64SAllison Henderson }
3370a4bb6b64SAllison Henderson 
3371a4bb6b64SAllison Henderson /*
3372617ba13bSMingming Cao  * ext4_truncate()
3373ac27a0ecSDave Kleikamp  *
3374617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
3375617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3376ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
3377ac27a0ecSDave Kleikamp  *
3378ac27a0ecSDave Kleikamp  * As we work through the truncate and commmit bits of it to the journal there
3379ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
3380ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
3381ac27a0ecSDave Kleikamp  *
3382ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
3383ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
3384ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
3385ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
3386ac27a0ecSDave Kleikamp  * left-to-right works OK too).
3387ac27a0ecSDave Kleikamp  *
3388ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
3389ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
3390ac27a0ecSDave Kleikamp  *
3391ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
3392617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
3393ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
3394617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
3395617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
3396ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
3397617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
3398ac27a0ecSDave Kleikamp  */
3399617ba13bSMingming Cao void ext4_truncate(struct inode *inode)
3400ac27a0ecSDave Kleikamp {
34010562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
34020562e0baSJiaying Zhang 
340391ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
3404ac27a0ecSDave Kleikamp 		return;
3405ac27a0ecSDave Kleikamp 
340612e9b892SDmitry Monakhov 	ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3407c8d46e41SJiaying Zhang 
34085534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
340919f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
34107d8f9f7dSTheodore Ts'o 
3411ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3412cf108bcaSJan Kara 		ext4_ext_truncate(inode);
3413ff9893dcSAmir Goldstein 	else
3414ff9893dcSAmir Goldstein 		ext4_ind_truncate(inode);
3415a86c6181SAlex Tomas 
34160562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
3417ac27a0ecSDave Kleikamp }
3418ac27a0ecSDave Kleikamp 
3419ac27a0ecSDave Kleikamp /*
3420617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
3421ac27a0ecSDave Kleikamp  * underlying buffer_head on success. If 'in_mem' is true, we have all
3422ac27a0ecSDave Kleikamp  * data in memory that is needed to recreate the on-disk version of this
3423ac27a0ecSDave Kleikamp  * inode.
3424ac27a0ecSDave Kleikamp  */
3425617ba13bSMingming Cao static int __ext4_get_inode_loc(struct inode *inode,
3426617ba13bSMingming Cao 				struct ext4_iloc *iloc, int in_mem)
3427ac27a0ecSDave Kleikamp {
3428240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
3429ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
3430240799cdSTheodore Ts'o 	struct super_block	*sb = inode->i_sb;
3431240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
3432240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
3433ac27a0ecSDave Kleikamp 
34343a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
3435240799cdSTheodore Ts'o 	if (!ext4_valid_inum(sb, inode->i_ino))
3436ac27a0ecSDave Kleikamp 		return -EIO;
3437ac27a0ecSDave Kleikamp 
3438240799cdSTheodore Ts'o 	iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3439240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3440240799cdSTheodore Ts'o 	if (!gdp)
3441240799cdSTheodore Ts'o 		return -EIO;
3442240799cdSTheodore Ts'o 
3443240799cdSTheodore Ts'o 	/*
3444240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
3445240799cdSTheodore Ts'o 	 */
344600d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3447240799cdSTheodore Ts'o 	inode_offset = ((inode->i_ino - 1) %
3448240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
3449240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3450240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3451240799cdSTheodore Ts'o 
3452240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
3453ac27a0ecSDave Kleikamp 	if (!bh) {
3454c398eda0STheodore Ts'o 		EXT4_ERROR_INODE_BLOCK(inode, block,
3455c398eda0STheodore Ts'o 				       "unable to read itable block");
3456ac27a0ecSDave Kleikamp 		return -EIO;
3457ac27a0ecSDave Kleikamp 	}
3458ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
3459ac27a0ecSDave Kleikamp 		lock_buffer(bh);
34609c83a923SHidehiro Kawai 
34619c83a923SHidehiro Kawai 		/*
34629c83a923SHidehiro Kawai 		 * If the buffer has the write error flag, we have failed
34639c83a923SHidehiro Kawai 		 * to write out another inode in the same block.  In this
34649c83a923SHidehiro Kawai 		 * case, we don't have to read the block because we may
34659c83a923SHidehiro Kawai 		 * read the old inode data successfully.
34669c83a923SHidehiro Kawai 		 */
34679c83a923SHidehiro Kawai 		if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
34689c83a923SHidehiro Kawai 			set_buffer_uptodate(bh);
34699c83a923SHidehiro Kawai 
3470ac27a0ecSDave Kleikamp 		if (buffer_uptodate(bh)) {
3471ac27a0ecSDave Kleikamp 			/* someone brought it uptodate while we waited */
3472ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
3473ac27a0ecSDave Kleikamp 			goto has_buffer;
3474ac27a0ecSDave Kleikamp 		}
3475ac27a0ecSDave Kleikamp 
3476ac27a0ecSDave Kleikamp 		/*
3477ac27a0ecSDave Kleikamp 		 * If we have all information of the inode in memory and this
3478ac27a0ecSDave Kleikamp 		 * is the only valid inode in the block, we need not read the
3479ac27a0ecSDave Kleikamp 		 * block.
3480ac27a0ecSDave Kleikamp 		 */
3481ac27a0ecSDave Kleikamp 		if (in_mem) {
3482ac27a0ecSDave Kleikamp 			struct buffer_head *bitmap_bh;
3483240799cdSTheodore Ts'o 			int i, start;
3484ac27a0ecSDave Kleikamp 
3485240799cdSTheodore Ts'o 			start = inode_offset & ~(inodes_per_block - 1);
3486ac27a0ecSDave Kleikamp 
3487ac27a0ecSDave Kleikamp 			/* Is the inode bitmap in cache? */
3488240799cdSTheodore Ts'o 			bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3489ac27a0ecSDave Kleikamp 			if (!bitmap_bh)
3490ac27a0ecSDave Kleikamp 				goto make_io;
3491ac27a0ecSDave Kleikamp 
3492ac27a0ecSDave Kleikamp 			/*
3493ac27a0ecSDave Kleikamp 			 * If the inode bitmap isn't in cache then the
3494ac27a0ecSDave Kleikamp 			 * optimisation may end up performing two reads instead
3495ac27a0ecSDave Kleikamp 			 * of one, so skip it.
3496ac27a0ecSDave Kleikamp 			 */
3497ac27a0ecSDave Kleikamp 			if (!buffer_uptodate(bitmap_bh)) {
3498ac27a0ecSDave Kleikamp 				brelse(bitmap_bh);
3499ac27a0ecSDave Kleikamp 				goto make_io;
3500ac27a0ecSDave Kleikamp 			}
3501240799cdSTheodore Ts'o 			for (i = start; i < start + inodes_per_block; i++) {
3502ac27a0ecSDave Kleikamp 				if (i == inode_offset)
3503ac27a0ecSDave Kleikamp 					continue;
3504617ba13bSMingming Cao 				if (ext4_test_bit(i, bitmap_bh->b_data))
3505ac27a0ecSDave Kleikamp 					break;
3506ac27a0ecSDave Kleikamp 			}
3507ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
3508240799cdSTheodore Ts'o 			if (i == start + inodes_per_block) {
3509ac27a0ecSDave Kleikamp 				/* all other inodes are free, so skip I/O */
3510ac27a0ecSDave Kleikamp 				memset(bh->b_data, 0, bh->b_size);
3511ac27a0ecSDave Kleikamp 				set_buffer_uptodate(bh);
3512ac27a0ecSDave Kleikamp 				unlock_buffer(bh);
3513ac27a0ecSDave Kleikamp 				goto has_buffer;
3514ac27a0ecSDave Kleikamp 			}
3515ac27a0ecSDave Kleikamp 		}
3516ac27a0ecSDave Kleikamp 
3517ac27a0ecSDave Kleikamp make_io:
3518ac27a0ecSDave Kleikamp 		/*
3519240799cdSTheodore Ts'o 		 * If we need to do any I/O, try to pre-readahead extra
3520240799cdSTheodore Ts'o 		 * blocks from the inode table.
3521240799cdSTheodore Ts'o 		 */
3522240799cdSTheodore Ts'o 		if (EXT4_SB(sb)->s_inode_readahead_blks) {
3523240799cdSTheodore Ts'o 			ext4_fsblk_t b, end, table;
3524240799cdSTheodore Ts'o 			unsigned num;
3525240799cdSTheodore Ts'o 
3526240799cdSTheodore Ts'o 			table = ext4_inode_table(sb, gdp);
3527b713a5ecSTheodore Ts'o 			/* s_inode_readahead_blks is always a power of 2 */
3528240799cdSTheodore Ts'o 			b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3529240799cdSTheodore Ts'o 			if (table > b)
3530240799cdSTheodore Ts'o 				b = table;
3531240799cdSTheodore Ts'o 			end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3532240799cdSTheodore Ts'o 			num = EXT4_INODES_PER_GROUP(sb);
3533240799cdSTheodore Ts'o 			if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3534240799cdSTheodore Ts'o 				       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
3535560671a0SAneesh Kumar K.V 				num -= ext4_itable_unused_count(sb, gdp);
3536240799cdSTheodore Ts'o 			table += num / inodes_per_block;
3537240799cdSTheodore Ts'o 			if (end > table)
3538240799cdSTheodore Ts'o 				end = table;
3539240799cdSTheodore Ts'o 			while (b <= end)
3540240799cdSTheodore Ts'o 				sb_breadahead(sb, b++);
3541240799cdSTheodore Ts'o 		}
3542240799cdSTheodore Ts'o 
3543240799cdSTheodore Ts'o 		/*
3544ac27a0ecSDave Kleikamp 		 * There are other valid inodes in the buffer, this inode
3545ac27a0ecSDave Kleikamp 		 * has in-inode xattrs, or we don't have this inode in memory.
3546ac27a0ecSDave Kleikamp 		 * Read the block from disk.
3547ac27a0ecSDave Kleikamp 		 */
35480562e0baSJiaying Zhang 		trace_ext4_load_inode(inode);
3549ac27a0ecSDave Kleikamp 		get_bh(bh);
3550ac27a0ecSDave Kleikamp 		bh->b_end_io = end_buffer_read_sync;
3551ac27a0ecSDave Kleikamp 		submit_bh(READ_META, bh);
3552ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
3553ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh)) {
3554c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, block,
3555c398eda0STheodore Ts'o 					       "unable to read itable block");
3556ac27a0ecSDave Kleikamp 			brelse(bh);
3557ac27a0ecSDave Kleikamp 			return -EIO;
3558ac27a0ecSDave Kleikamp 		}
3559ac27a0ecSDave Kleikamp 	}
3560ac27a0ecSDave Kleikamp has_buffer:
3561ac27a0ecSDave Kleikamp 	iloc->bh = bh;
3562ac27a0ecSDave Kleikamp 	return 0;
3563ac27a0ecSDave Kleikamp }
3564ac27a0ecSDave Kleikamp 
3565617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3566ac27a0ecSDave Kleikamp {
3567ac27a0ecSDave Kleikamp 	/* We have all inode data except xattrs in memory here. */
3568617ba13bSMingming Cao 	return __ext4_get_inode_loc(inode, iloc,
356919f5fb7aSTheodore Ts'o 		!ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3570ac27a0ecSDave Kleikamp }
3571ac27a0ecSDave Kleikamp 
3572617ba13bSMingming Cao void ext4_set_inode_flags(struct inode *inode)
3573ac27a0ecSDave Kleikamp {
3574617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
3575ac27a0ecSDave Kleikamp 
3576ac27a0ecSDave Kleikamp 	inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3577617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
3578ac27a0ecSDave Kleikamp 		inode->i_flags |= S_SYNC;
3579617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
3580ac27a0ecSDave Kleikamp 		inode->i_flags |= S_APPEND;
3581617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
3582ac27a0ecSDave Kleikamp 		inode->i_flags |= S_IMMUTABLE;
3583617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
3584ac27a0ecSDave Kleikamp 		inode->i_flags |= S_NOATIME;
3585617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
3586ac27a0ecSDave Kleikamp 		inode->i_flags |= S_DIRSYNC;
3587ac27a0ecSDave Kleikamp }
3588ac27a0ecSDave Kleikamp 
3589ff9ddf7eSJan Kara /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3590ff9ddf7eSJan Kara void ext4_get_inode_flags(struct ext4_inode_info *ei)
3591ff9ddf7eSJan Kara {
359284a8dce2SDmitry Monakhov 	unsigned int vfs_fl;
359384a8dce2SDmitry Monakhov 	unsigned long old_fl, new_fl;
3594ff9ddf7eSJan Kara 
359584a8dce2SDmitry Monakhov 	do {
359684a8dce2SDmitry Monakhov 		vfs_fl = ei->vfs_inode.i_flags;
359784a8dce2SDmitry Monakhov 		old_fl = ei->i_flags;
359884a8dce2SDmitry Monakhov 		new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
359984a8dce2SDmitry Monakhov 				EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
360084a8dce2SDmitry Monakhov 				EXT4_DIRSYNC_FL);
360184a8dce2SDmitry Monakhov 		if (vfs_fl & S_SYNC)
360284a8dce2SDmitry Monakhov 			new_fl |= EXT4_SYNC_FL;
360384a8dce2SDmitry Monakhov 		if (vfs_fl & S_APPEND)
360484a8dce2SDmitry Monakhov 			new_fl |= EXT4_APPEND_FL;
360584a8dce2SDmitry Monakhov 		if (vfs_fl & S_IMMUTABLE)
360684a8dce2SDmitry Monakhov 			new_fl |= EXT4_IMMUTABLE_FL;
360784a8dce2SDmitry Monakhov 		if (vfs_fl & S_NOATIME)
360884a8dce2SDmitry Monakhov 			new_fl |= EXT4_NOATIME_FL;
360984a8dce2SDmitry Monakhov 		if (vfs_fl & S_DIRSYNC)
361084a8dce2SDmitry Monakhov 			new_fl |= EXT4_DIRSYNC_FL;
361184a8dce2SDmitry Monakhov 	} while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3612ff9ddf7eSJan Kara }
3613de9a55b8STheodore Ts'o 
36140fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
36150fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
36160fc1b451SAneesh Kumar K.V {
36170fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
36188180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
36198180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
36200fc1b451SAneesh Kumar K.V 
36210fc1b451SAneesh Kumar K.V 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
36220fc1b451SAneesh Kumar K.V 				EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
36230fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
36240fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
36250fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
362607a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
36278180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
36288180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
36298180a562SAneesh Kumar K.V 		} else {
36300fc1b451SAneesh Kumar K.V 			return i_blocks;
36318180a562SAneesh Kumar K.V 		}
36320fc1b451SAneesh Kumar K.V 	} else {
36330fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
36340fc1b451SAneesh Kumar K.V 	}
36350fc1b451SAneesh Kumar K.V }
3636ff9ddf7eSJan Kara 
36371d1fe1eeSDavid Howells struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3638ac27a0ecSDave Kleikamp {
3639617ba13bSMingming Cao 	struct ext4_iloc iloc;
3640617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
36411d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
36421d1fe1eeSDavid Howells 	struct inode *inode;
3643b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
36441d1fe1eeSDavid Howells 	long ret;
3645ac27a0ecSDave Kleikamp 	int block;
3646ac27a0ecSDave Kleikamp 
36471d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
36481d1fe1eeSDavid Howells 	if (!inode)
36491d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
36501d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
36511d1fe1eeSDavid Howells 		return inode;
36521d1fe1eeSDavid Howells 
36531d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
36547dc57615SPeter Huewe 	iloc.bh = NULL;
3655ac27a0ecSDave Kleikamp 
36561d1fe1eeSDavid Howells 	ret = __ext4_get_inode_loc(inode, &iloc, 0);
36571d1fe1eeSDavid Howells 	if (ret < 0)
3658ac27a0ecSDave Kleikamp 		goto bad_inode;
3659617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
3660ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3661ac27a0ecSDave Kleikamp 	inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3662ac27a0ecSDave Kleikamp 	inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3663ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
3664ac27a0ecSDave Kleikamp 		inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3665ac27a0ecSDave Kleikamp 		inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3666ac27a0ecSDave Kleikamp 	}
3667ac27a0ecSDave Kleikamp 	inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
3668ac27a0ecSDave Kleikamp 
3669353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
3670ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
3671ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3672ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
3673ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
3674ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
3675ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
3676ac27a0ecSDave Kleikamp 	 */
3677ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
3678ac27a0ecSDave Kleikamp 		if (inode->i_mode == 0 ||
3679617ba13bSMingming Cao 		    !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3680ac27a0ecSDave Kleikamp 			/* this inode is deleted */
36811d1fe1eeSDavid Howells 			ret = -ESTALE;
3682ac27a0ecSDave Kleikamp 			goto bad_inode;
3683ac27a0ecSDave Kleikamp 		}
3684ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
3685ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
3686ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
3687ac27a0ecSDave Kleikamp 		 * the process of deleting those. */
3688ac27a0ecSDave Kleikamp 	}
3689ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
36900fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
36917973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3692a9e81742STheodore Ts'o 	if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3693a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
3694a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3695a48380f7SAneesh Kumar K.V 	inode->i_size = ext4_isize(raw_inode);
3696ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
3697a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
3698a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
3699a9e7f447SDmitry Monakhov #endif
3700ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3701ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
3702a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
3703ac27a0ecSDave Kleikamp 	/*
3704ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
3705ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
3706ac27a0ecSDave Kleikamp 	 */
3707617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
3708ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
3709ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
3710ac27a0ecSDave Kleikamp 
3711b436b9beSJan Kara 	/*
3712b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
3713b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
3714b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
3715b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
3716b436b9beSJan Kara 	 * now it is reread from disk.
3717b436b9beSJan Kara 	 */
3718b436b9beSJan Kara 	if (journal) {
3719b436b9beSJan Kara 		transaction_t *transaction;
3720b436b9beSJan Kara 		tid_t tid;
3721b436b9beSJan Kara 
3722a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
3723b436b9beSJan Kara 		if (journal->j_running_transaction)
3724b436b9beSJan Kara 			transaction = journal->j_running_transaction;
3725b436b9beSJan Kara 		else
3726b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
3727b436b9beSJan Kara 		if (transaction)
3728b436b9beSJan Kara 			tid = transaction->t_tid;
3729b436b9beSJan Kara 		else
3730b436b9beSJan Kara 			tid = journal->j_commit_sequence;
3731a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
3732b436b9beSJan Kara 		ei->i_sync_tid = tid;
3733b436b9beSJan Kara 		ei->i_datasync_tid = tid;
3734b436b9beSJan Kara 	}
3735b436b9beSJan Kara 
37360040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3737ac27a0ecSDave Kleikamp 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3738617ba13bSMingming Cao 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3739e5d2861fSKirill Korotaev 		    EXT4_INODE_SIZE(inode->i_sb)) {
37401d1fe1eeSDavid Howells 			ret = -EIO;
3741ac27a0ecSDave Kleikamp 			goto bad_inode;
3742e5d2861fSKirill Korotaev 		}
3743ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
3744ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
3745617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
3746617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
3747ac27a0ecSDave Kleikamp 		} else {
3748ac27a0ecSDave Kleikamp 			__le32 *magic = (void *)raw_inode +
3749617ba13bSMingming Cao 					EXT4_GOOD_OLD_INODE_SIZE +
3750ac27a0ecSDave Kleikamp 					ei->i_extra_isize;
3751617ba13bSMingming Cao 			if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
375219f5fb7aSTheodore Ts'o 				ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3753ac27a0ecSDave Kleikamp 		}
3754ac27a0ecSDave Kleikamp 	} else
3755ac27a0ecSDave Kleikamp 		ei->i_extra_isize = 0;
3756ac27a0ecSDave Kleikamp 
3757ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3758ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3759ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3760ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3761ef7f3835SKalpak Shah 
376225ec56b5SJean Noel Cordenner 	inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
376325ec56b5SJean Noel Cordenner 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
376425ec56b5SJean Noel Cordenner 		if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
376525ec56b5SJean Noel Cordenner 			inode->i_version |=
376625ec56b5SJean Noel Cordenner 			(__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
376725ec56b5SJean Noel Cordenner 	}
376825ec56b5SJean Noel Cordenner 
3769c4b5a614STheodore Ts'o 	ret = 0;
3770485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
37711032988cSTheodore Ts'o 	    !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
377224676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
377324676da4STheodore Ts'o 				 ei->i_file_acl);
3774485c26ecSTheodore Ts'o 		ret = -EIO;
3775485c26ecSTheodore Ts'o 		goto bad_inode;
377607a03824STheodore Ts'o 	} else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3777c4b5a614STheodore Ts'o 		if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3778c4b5a614STheodore Ts'o 		    (S_ISLNK(inode->i_mode) &&
3779c4b5a614STheodore Ts'o 		     !ext4_inode_is_fast_symlink(inode)))
37807a262f7cSAneesh Kumar K.V 			/* Validate extent which is part of inode */
37817a262f7cSAneesh Kumar K.V 			ret = ext4_ext_check_inode(inode);
3782fe2c8191SThiemo Nagel 	} else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3783fe2c8191SThiemo Nagel 		   (S_ISLNK(inode->i_mode) &&
3784fe2c8191SThiemo Nagel 		    !ext4_inode_is_fast_symlink(inode))) {
3785fe2c8191SThiemo Nagel 		/* Validate block references which are part of inode */
37861f7d1e77STheodore Ts'o 		ret = ext4_ind_check_inode(inode);
3787fe2c8191SThiemo Nagel 	}
3788567f3e9aSTheodore Ts'o 	if (ret)
37897a262f7cSAneesh Kumar K.V 		goto bad_inode;
37907a262f7cSAneesh Kumar K.V 
3791ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
3792617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
3793617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
3794617ba13bSMingming Cao 		ext4_set_aops(inode);
3795ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
3796617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
3797617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
3798ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
3799e83c1397SDuane Griffin 		if (ext4_inode_is_fast_symlink(inode)) {
3800617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
3801e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
3802e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
3803e83c1397SDuane Griffin 		} else {
3804617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
3805617ba13bSMingming Cao 			ext4_set_aops(inode);
3806ac27a0ecSDave Kleikamp 		}
3807563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3808563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3809617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
3810ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
3811ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
3812ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3813ac27a0ecSDave Kleikamp 		else
3814ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
3815ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3816563bdd61STheodore Ts'o 	} else {
3817563bdd61STheodore Ts'o 		ret = -EIO;
381824676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3819563bdd61STheodore Ts'o 		goto bad_inode;
3820ac27a0ecSDave Kleikamp 	}
3821ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
3822617ba13bSMingming Cao 	ext4_set_inode_flags(inode);
38231d1fe1eeSDavid Howells 	unlock_new_inode(inode);
38241d1fe1eeSDavid Howells 	return inode;
3825ac27a0ecSDave Kleikamp 
3826ac27a0ecSDave Kleikamp bad_inode:
3827567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
38281d1fe1eeSDavid Howells 	iget_failed(inode);
38291d1fe1eeSDavid Howells 	return ERR_PTR(ret);
3830ac27a0ecSDave Kleikamp }
3831ac27a0ecSDave Kleikamp 
38320fc1b451SAneesh Kumar K.V static int ext4_inode_blocks_set(handle_t *handle,
38330fc1b451SAneesh Kumar K.V 				struct ext4_inode *raw_inode,
38340fc1b451SAneesh Kumar K.V 				struct ext4_inode_info *ei)
38350fc1b451SAneesh Kumar K.V {
38360fc1b451SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
38370fc1b451SAneesh Kumar K.V 	u64 i_blocks = inode->i_blocks;
38380fc1b451SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
38390fc1b451SAneesh Kumar K.V 
38400fc1b451SAneesh Kumar K.V 	if (i_blocks <= ~0U) {
38410fc1b451SAneesh Kumar K.V 		/*
38420fc1b451SAneesh Kumar K.V 		 * i_blocks can be represnted in a 32 bit variable
38430fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
38440fc1b451SAneesh Kumar K.V 		 */
38458180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
38460fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = 0;
384784a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3848f287a1a5STheodore Ts'o 		return 0;
3849f287a1a5STheodore Ts'o 	}
3850f287a1a5STheodore Ts'o 	if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
3851f287a1a5STheodore Ts'o 		return -EFBIG;
3852f287a1a5STheodore Ts'o 
3853f287a1a5STheodore Ts'o 	if (i_blocks <= 0xffffffffffffULL) {
38540fc1b451SAneesh Kumar K.V 		/*
38550fc1b451SAneesh Kumar K.V 		 * i_blocks can be represented in a 48 bit variable
38560fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
38570fc1b451SAneesh Kumar K.V 		 */
38588180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
38590fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
386084a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
38610fc1b451SAneesh Kumar K.V 	} else {
386284a8dce2SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
38638180a562SAneesh Kumar K.V 		/* i_block is stored in file system block size */
38648180a562SAneesh Kumar K.V 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
38658180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
38668180a562SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
38670fc1b451SAneesh Kumar K.V 	}
3868f287a1a5STheodore Ts'o 	return 0;
38690fc1b451SAneesh Kumar K.V }
38700fc1b451SAneesh Kumar K.V 
3871ac27a0ecSDave Kleikamp /*
3872ac27a0ecSDave Kleikamp  * Post the struct inode info into an on-disk inode location in the
3873ac27a0ecSDave Kleikamp  * buffer-cache.  This gobbles the caller's reference to the
3874ac27a0ecSDave Kleikamp  * buffer_head in the inode location struct.
3875ac27a0ecSDave Kleikamp  *
3876ac27a0ecSDave Kleikamp  * The caller must have write access to iloc->bh.
3877ac27a0ecSDave Kleikamp  */
3878617ba13bSMingming Cao static int ext4_do_update_inode(handle_t *handle,
3879ac27a0ecSDave Kleikamp 				struct inode *inode,
3880830156c7SFrank Mayhar 				struct ext4_iloc *iloc)
3881ac27a0ecSDave Kleikamp {
3882617ba13bSMingming Cao 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
3883617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
3884ac27a0ecSDave Kleikamp 	struct buffer_head *bh = iloc->bh;
3885ac27a0ecSDave Kleikamp 	int err = 0, rc, block;
3886ac27a0ecSDave Kleikamp 
3887ac27a0ecSDave Kleikamp 	/* For fields not not tracking in the in-memory inode,
3888ac27a0ecSDave Kleikamp 	 * initialise them to zero for new inodes. */
388919f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
3890617ba13bSMingming Cao 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
3891ac27a0ecSDave Kleikamp 
3892ff9ddf7eSJan Kara 	ext4_get_inode_flags(ei);
3893ac27a0ecSDave Kleikamp 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
3894ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
3895ac27a0ecSDave Kleikamp 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
3896ac27a0ecSDave Kleikamp 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
3897ac27a0ecSDave Kleikamp /*
3898ac27a0ecSDave Kleikamp  * Fix up interoperability with old kernels. Otherwise, old inodes get
3899ac27a0ecSDave Kleikamp  * re-used with the upper 16 bits of the uid/gid intact
3900ac27a0ecSDave Kleikamp  */
3901ac27a0ecSDave Kleikamp 		if (!ei->i_dtime) {
3902ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high =
3903ac27a0ecSDave Kleikamp 				cpu_to_le16(high_16_bits(inode->i_uid));
3904ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high =
3905ac27a0ecSDave Kleikamp 				cpu_to_le16(high_16_bits(inode->i_gid));
3906ac27a0ecSDave Kleikamp 		} else {
3907ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high = 0;
3908ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high = 0;
3909ac27a0ecSDave Kleikamp 		}
3910ac27a0ecSDave Kleikamp 	} else {
3911ac27a0ecSDave Kleikamp 		raw_inode->i_uid_low =
3912ac27a0ecSDave Kleikamp 			cpu_to_le16(fs_high2lowuid(inode->i_uid));
3913ac27a0ecSDave Kleikamp 		raw_inode->i_gid_low =
3914ac27a0ecSDave Kleikamp 			cpu_to_le16(fs_high2lowgid(inode->i_gid));
3915ac27a0ecSDave Kleikamp 		raw_inode->i_uid_high = 0;
3916ac27a0ecSDave Kleikamp 		raw_inode->i_gid_high = 0;
3917ac27a0ecSDave Kleikamp 	}
3918ac27a0ecSDave Kleikamp 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
3919ef7f3835SKalpak Shah 
3920ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
3921ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
3922ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
3923ef7f3835SKalpak Shah 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
3924ef7f3835SKalpak Shah 
39250fc1b451SAneesh Kumar K.V 	if (ext4_inode_blocks_set(handle, raw_inode, ei))
39260fc1b451SAneesh Kumar K.V 		goto out_brelse;
3927ac27a0ecSDave Kleikamp 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
3928353eb83cSTheodore Ts'o 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
39299b8f1f01SMingming Cao 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
39309b8f1f01SMingming Cao 	    cpu_to_le32(EXT4_OS_HURD))
3931a1ddeb7eSBadari Pulavarty 		raw_inode->i_file_acl_high =
3932a1ddeb7eSBadari Pulavarty 			cpu_to_le16(ei->i_file_acl >> 32);
39337973c0c1SAneesh Kumar K.V 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
3934a48380f7SAneesh Kumar K.V 	ext4_isize_set(raw_inode, ei->i_disksize);
3935ac27a0ecSDave Kleikamp 	if (ei->i_disksize > 0x7fffffffULL) {
3936ac27a0ecSDave Kleikamp 		struct super_block *sb = inode->i_sb;
3937617ba13bSMingming Cao 		if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
3938617ba13bSMingming Cao 				EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
3939617ba13bSMingming Cao 				EXT4_SB(sb)->s_es->s_rev_level ==
3940617ba13bSMingming Cao 				cpu_to_le32(EXT4_GOOD_OLD_REV)) {
3941ac27a0ecSDave Kleikamp 			/* If this is the first large file
3942ac27a0ecSDave Kleikamp 			 * created, add a flag to the superblock.
3943ac27a0ecSDave Kleikamp 			 */
3944617ba13bSMingming Cao 			err = ext4_journal_get_write_access(handle,
3945617ba13bSMingming Cao 					EXT4_SB(sb)->s_sbh);
3946ac27a0ecSDave Kleikamp 			if (err)
3947ac27a0ecSDave Kleikamp 				goto out_brelse;
3948617ba13bSMingming Cao 			ext4_update_dynamic_rev(sb);
3949617ba13bSMingming Cao 			EXT4_SET_RO_COMPAT_FEATURE(sb,
3950617ba13bSMingming Cao 					EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
3951ac27a0ecSDave Kleikamp 			sb->s_dirt = 1;
39520390131bSFrank Mayhar 			ext4_handle_sync(handle);
395373b50c1cSCurt Wohlgemuth 			err = ext4_handle_dirty_metadata(handle, NULL,
3954617ba13bSMingming Cao 					EXT4_SB(sb)->s_sbh);
3955ac27a0ecSDave Kleikamp 		}
3956ac27a0ecSDave Kleikamp 	}
3957ac27a0ecSDave Kleikamp 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
3958ac27a0ecSDave Kleikamp 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
3959ac27a0ecSDave Kleikamp 		if (old_valid_dev(inode->i_rdev)) {
3960ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] =
3961ac27a0ecSDave Kleikamp 				cpu_to_le32(old_encode_dev(inode->i_rdev));
3962ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] = 0;
3963ac27a0ecSDave Kleikamp 		} else {
3964ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] = 0;
3965ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] =
3966ac27a0ecSDave Kleikamp 				cpu_to_le32(new_encode_dev(inode->i_rdev));
3967ac27a0ecSDave Kleikamp 			raw_inode->i_block[2] = 0;
3968ac27a0ecSDave Kleikamp 		}
3969de9a55b8STheodore Ts'o 	} else
3970de9a55b8STheodore Ts'o 		for (block = 0; block < EXT4_N_BLOCKS; block++)
3971ac27a0ecSDave Kleikamp 			raw_inode->i_block[block] = ei->i_data[block];
3972ac27a0ecSDave Kleikamp 
397325ec56b5SJean Noel Cordenner 	raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
397425ec56b5SJean Noel Cordenner 	if (ei->i_extra_isize) {
397525ec56b5SJean Noel Cordenner 		if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
397625ec56b5SJean Noel Cordenner 			raw_inode->i_version_hi =
397725ec56b5SJean Noel Cordenner 			cpu_to_le32(inode->i_version >> 32);
3978ac27a0ecSDave Kleikamp 		raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
397925ec56b5SJean Noel Cordenner 	}
398025ec56b5SJean Noel Cordenner 
39810390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
398273b50c1cSCurt Wohlgemuth 	rc = ext4_handle_dirty_metadata(handle, NULL, bh);
3983ac27a0ecSDave Kleikamp 	if (!err)
3984ac27a0ecSDave Kleikamp 		err = rc;
398519f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
3986ac27a0ecSDave Kleikamp 
3987b436b9beSJan Kara 	ext4_update_inode_fsync_trans(handle, inode, 0);
3988ac27a0ecSDave Kleikamp out_brelse:
3989ac27a0ecSDave Kleikamp 	brelse(bh);
3990617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
3991ac27a0ecSDave Kleikamp 	return err;
3992ac27a0ecSDave Kleikamp }
3993ac27a0ecSDave Kleikamp 
3994ac27a0ecSDave Kleikamp /*
3995617ba13bSMingming Cao  * ext4_write_inode()
3996ac27a0ecSDave Kleikamp  *
3997ac27a0ecSDave Kleikamp  * We are called from a few places:
3998ac27a0ecSDave Kleikamp  *
3999ac27a0ecSDave Kleikamp  * - Within generic_file_write() for O_SYNC files.
4000ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
4001ac27a0ecSDave Kleikamp  *   trasnaction to commit.
4002ac27a0ecSDave Kleikamp  *
4003ac27a0ecSDave Kleikamp  * - Within sys_sync(), kupdate and such.
4004ac27a0ecSDave Kleikamp  *   We wait on commit, if tol to.
4005ac27a0ecSDave Kleikamp  *
4006ac27a0ecSDave Kleikamp  * - Within prune_icache() (PF_MEMALLOC == true)
4007ac27a0ecSDave Kleikamp  *   Here we simply return.  We can't afford to block kswapd on the
4008ac27a0ecSDave Kleikamp  *   journal commit.
4009ac27a0ecSDave Kleikamp  *
4010ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
4011ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
4012617ba13bSMingming Cao  * ext4_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
4013ac27a0ecSDave Kleikamp  * knfsd.
4014ac27a0ecSDave Kleikamp  *
4015ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
4016ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
4017ac27a0ecSDave Kleikamp  * which we are interested.
4018ac27a0ecSDave Kleikamp  *
4019ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
4020ac27a0ecSDave Kleikamp  *
4021ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
4022ac27a0ecSDave Kleikamp  *	stuff();
4023ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
4024ac27a0ecSDave Kleikamp  *
4025ac27a0ecSDave Kleikamp  * is in error because a kswapd-driven write_inode() could occur while
4026ac27a0ecSDave Kleikamp  * `stuff()' is running, and the new i_size will be lost.  Plus the inode
4027ac27a0ecSDave Kleikamp  * will no longer be on the superblock's dirty inode list.
4028ac27a0ecSDave Kleikamp  */
4029a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4030ac27a0ecSDave Kleikamp {
403191ac6f43SFrank Mayhar 	int err;
403291ac6f43SFrank Mayhar 
4033ac27a0ecSDave Kleikamp 	if (current->flags & PF_MEMALLOC)
4034ac27a0ecSDave Kleikamp 		return 0;
4035ac27a0ecSDave Kleikamp 
403691ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
4037617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
4038b38bd33aSMingming Cao 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4039ac27a0ecSDave Kleikamp 			dump_stack();
4040ac27a0ecSDave Kleikamp 			return -EIO;
4041ac27a0ecSDave Kleikamp 		}
4042ac27a0ecSDave Kleikamp 
4043a9185b41SChristoph Hellwig 		if (wbc->sync_mode != WB_SYNC_ALL)
4044ac27a0ecSDave Kleikamp 			return 0;
4045ac27a0ecSDave Kleikamp 
404691ac6f43SFrank Mayhar 		err = ext4_force_commit(inode->i_sb);
404791ac6f43SFrank Mayhar 	} else {
404891ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
404991ac6f43SFrank Mayhar 
40508b472d73SCurt Wohlgemuth 		err = __ext4_get_inode_loc(inode, &iloc, 0);
405191ac6f43SFrank Mayhar 		if (err)
405291ac6f43SFrank Mayhar 			return err;
4053a9185b41SChristoph Hellwig 		if (wbc->sync_mode == WB_SYNC_ALL)
4054830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
4055830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4056c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4057c398eda0STheodore Ts'o 					 "IO error syncing inode");
4058830156c7SFrank Mayhar 			err = -EIO;
4059830156c7SFrank Mayhar 		}
4060fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
406191ac6f43SFrank Mayhar 	}
406291ac6f43SFrank Mayhar 	return err;
4063ac27a0ecSDave Kleikamp }
4064ac27a0ecSDave Kleikamp 
4065ac27a0ecSDave Kleikamp /*
4066617ba13bSMingming Cao  * ext4_setattr()
4067ac27a0ecSDave Kleikamp  *
4068ac27a0ecSDave Kleikamp  * Called from notify_change.
4069ac27a0ecSDave Kleikamp  *
4070ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
4071ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
4072ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
4073ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
4074ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
4075ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
4076ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
4077ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
4078ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
4079ac27a0ecSDave Kleikamp  *
4080678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
4081678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
4082678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
4083678aaf48SJan Kara  * This way we are sure that all the data written in the previous
4084678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
4085678aaf48SJan Kara  * writeback).
4086678aaf48SJan Kara  *
4087678aaf48SJan Kara  * Called with inode->i_mutex down.
4088ac27a0ecSDave Kleikamp  */
4089617ba13bSMingming Cao int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4090ac27a0ecSDave Kleikamp {
4091ac27a0ecSDave Kleikamp 	struct inode *inode = dentry->d_inode;
4092ac27a0ecSDave Kleikamp 	int error, rc = 0;
40933d287de3SDmitry Monakhov 	int orphan = 0;
4094ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
4095ac27a0ecSDave Kleikamp 
4096ac27a0ecSDave Kleikamp 	error = inode_change_ok(inode, attr);
4097ac27a0ecSDave Kleikamp 	if (error)
4098ac27a0ecSDave Kleikamp 		return error;
4099ac27a0ecSDave Kleikamp 
410012755627SDmitry Monakhov 	if (is_quota_modification(inode, attr))
4101871a2931SChristoph Hellwig 		dquot_initialize(inode);
4102ac27a0ecSDave Kleikamp 	if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4103ac27a0ecSDave Kleikamp 		(ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4104ac27a0ecSDave Kleikamp 		handle_t *handle;
4105ac27a0ecSDave Kleikamp 
4106ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
4107ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
41085aca07ebSDmitry Monakhov 		handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
4109194074acSDmitry Monakhov 					EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
4110ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
4111ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
4112ac27a0ecSDave Kleikamp 			goto err_out;
4113ac27a0ecSDave Kleikamp 		}
4114b43fa828SChristoph Hellwig 		error = dquot_transfer(inode, attr);
4115ac27a0ecSDave Kleikamp 		if (error) {
4116617ba13bSMingming Cao 			ext4_journal_stop(handle);
4117ac27a0ecSDave Kleikamp 			return error;
4118ac27a0ecSDave Kleikamp 		}
4119ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
4120ac27a0ecSDave Kleikamp 		 * one transaction */
4121ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_UID)
4122ac27a0ecSDave Kleikamp 			inode->i_uid = attr->ia_uid;
4123ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_GID)
4124ac27a0ecSDave Kleikamp 			inode->i_gid = attr->ia_gid;
4125617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
4126617ba13bSMingming Cao 		ext4_journal_stop(handle);
4127ac27a0ecSDave Kleikamp 	}
4128ac27a0ecSDave Kleikamp 
4129e2b46574SEric Sandeen 	if (attr->ia_valid & ATTR_SIZE) {
4130562c72aaSChristoph Hellwig 		inode_dio_wait(inode);
4131562c72aaSChristoph Hellwig 
413212e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4133e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4134e2b46574SEric Sandeen 
41350c095c7fSTheodore Ts'o 			if (attr->ia_size > sbi->s_bitmap_maxbytes)
41360c095c7fSTheodore Ts'o 				return -EFBIG;
4137e2b46574SEric Sandeen 		}
4138e2b46574SEric Sandeen 	}
4139e2b46574SEric Sandeen 
4140ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode) &&
4141c8d46e41SJiaying Zhang 	    attr->ia_valid & ATTR_SIZE &&
4142072bd7eaSTheodore Ts'o 	    (attr->ia_size < inode->i_size)) {
4143ac27a0ecSDave Kleikamp 		handle_t *handle;
4144ac27a0ecSDave Kleikamp 
4145617ba13bSMingming Cao 		handle = ext4_journal_start(inode, 3);
4146ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
4147ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
4148ac27a0ecSDave Kleikamp 			goto err_out;
4149ac27a0ecSDave Kleikamp 		}
41503d287de3SDmitry Monakhov 		if (ext4_handle_valid(handle)) {
4151617ba13bSMingming Cao 			error = ext4_orphan_add(handle, inode);
41523d287de3SDmitry Monakhov 			orphan = 1;
41533d287de3SDmitry Monakhov 		}
4154617ba13bSMingming Cao 		EXT4_I(inode)->i_disksize = attr->ia_size;
4155617ba13bSMingming Cao 		rc = ext4_mark_inode_dirty(handle, inode);
4156ac27a0ecSDave Kleikamp 		if (!error)
4157ac27a0ecSDave Kleikamp 			error = rc;
4158617ba13bSMingming Cao 		ext4_journal_stop(handle);
4159678aaf48SJan Kara 
4160678aaf48SJan Kara 		if (ext4_should_order_data(inode)) {
4161678aaf48SJan Kara 			error = ext4_begin_ordered_truncate(inode,
4162678aaf48SJan Kara 							    attr->ia_size);
4163678aaf48SJan Kara 			if (error) {
4164678aaf48SJan Kara 				/* Do as much error cleanup as possible */
4165678aaf48SJan Kara 				handle = ext4_journal_start(inode, 3);
4166678aaf48SJan Kara 				if (IS_ERR(handle)) {
4167678aaf48SJan Kara 					ext4_orphan_del(NULL, inode);
4168678aaf48SJan Kara 					goto err_out;
4169678aaf48SJan Kara 				}
4170678aaf48SJan Kara 				ext4_orphan_del(handle, inode);
41713d287de3SDmitry Monakhov 				orphan = 0;
4172678aaf48SJan Kara 				ext4_journal_stop(handle);
4173678aaf48SJan Kara 				goto err_out;
4174678aaf48SJan Kara 			}
4175678aaf48SJan Kara 		}
4176ac27a0ecSDave Kleikamp 	}
4177ac27a0ecSDave Kleikamp 
4178072bd7eaSTheodore Ts'o 	if (attr->ia_valid & ATTR_SIZE) {
4179072bd7eaSTheodore Ts'o 		if (attr->ia_size != i_size_read(inode)) {
4180072bd7eaSTheodore Ts'o 			truncate_setsize(inode, attr->ia_size);
4181072bd7eaSTheodore Ts'o 			ext4_truncate(inode);
4182072bd7eaSTheodore Ts'o 		} else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
4183072bd7eaSTheodore Ts'o 			ext4_truncate(inode);
4184072bd7eaSTheodore Ts'o 	}
4185ac27a0ecSDave Kleikamp 
41861025774cSChristoph Hellwig 	if (!rc) {
41871025774cSChristoph Hellwig 		setattr_copy(inode, attr);
41881025774cSChristoph Hellwig 		mark_inode_dirty(inode);
41891025774cSChristoph Hellwig 	}
41901025774cSChristoph Hellwig 
41911025774cSChristoph Hellwig 	/*
41921025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
41931025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
41941025774cSChristoph Hellwig 	 */
41953d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
4196617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
4197ac27a0ecSDave Kleikamp 
4198ac27a0ecSDave Kleikamp 	if (!rc && (ia_valid & ATTR_MODE))
4199617ba13bSMingming Cao 		rc = ext4_acl_chmod(inode);
4200ac27a0ecSDave Kleikamp 
4201ac27a0ecSDave Kleikamp err_out:
4202617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, error);
4203ac27a0ecSDave Kleikamp 	if (!error)
4204ac27a0ecSDave Kleikamp 		error = rc;
4205ac27a0ecSDave Kleikamp 	return error;
4206ac27a0ecSDave Kleikamp }
4207ac27a0ecSDave Kleikamp 
42083e3398a0SMingming Cao int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
42093e3398a0SMingming Cao 		 struct kstat *stat)
42103e3398a0SMingming Cao {
42113e3398a0SMingming Cao 	struct inode *inode;
42123e3398a0SMingming Cao 	unsigned long delalloc_blocks;
42133e3398a0SMingming Cao 
42143e3398a0SMingming Cao 	inode = dentry->d_inode;
42153e3398a0SMingming Cao 	generic_fillattr(inode, stat);
42163e3398a0SMingming Cao 
42173e3398a0SMingming Cao 	/*
42183e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
42193e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
42203e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
42213e3398a0SMingming Cao 	 * on-disk file blocks.
42223e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
42233e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
42243e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
42253e3398a0SMingming Cao 	 * blocks for this file.
42263e3398a0SMingming Cao 	 */
42273e3398a0SMingming Cao 	delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
42283e3398a0SMingming Cao 
42293e3398a0SMingming Cao 	stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
42303e3398a0SMingming Cao 	return 0;
42313e3398a0SMingming Cao }
4232ac27a0ecSDave Kleikamp 
4233a02908f1SMingming Cao static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4234a02908f1SMingming Cao {
423512e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
42368bb2b247SAmir Goldstein 		return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4237ac51d837STheodore Ts'o 	return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4238a02908f1SMingming Cao }
4239ac51d837STheodore Ts'o 
4240a02908f1SMingming Cao /*
4241a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
4242a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
4243a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
4244a02908f1SMingming Cao  *
4245a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
4246af901ca1SAndré Goddard Rosa  * different block groups too. If they are contiuguous, with flexbg,
4247a02908f1SMingming Cao  * they could still across block group boundary.
4248a02908f1SMingming Cao  *
4249a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
4250a02908f1SMingming Cao  */
42511f109d5aSTheodore Ts'o static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4252a02908f1SMingming Cao {
42538df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
42548df9675fSTheodore Ts'o 	int gdpblocks;
4255a02908f1SMingming Cao 	int idxblocks;
4256a02908f1SMingming Cao 	int ret = 0;
4257a02908f1SMingming Cao 
4258a02908f1SMingming Cao 	/*
4259a02908f1SMingming Cao 	 * How many index blocks need to touch to modify nrblocks?
4260a02908f1SMingming Cao 	 * The "Chunk" flag indicating whether the nrblocks is
4261a02908f1SMingming Cao 	 * physically contiguous on disk
4262a02908f1SMingming Cao 	 *
4263a02908f1SMingming Cao 	 * For Direct IO and fallocate, they calls get_block to allocate
4264a02908f1SMingming Cao 	 * one single extent at a time, so they could set the "Chunk" flag
4265a02908f1SMingming Cao 	 */
4266a02908f1SMingming Cao 	idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4267a02908f1SMingming Cao 
4268a02908f1SMingming Cao 	ret = idxblocks;
4269a02908f1SMingming Cao 
4270a02908f1SMingming Cao 	/*
4271a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
4272a02908f1SMingming Cao 	 * to account
4273a02908f1SMingming Cao 	 */
4274a02908f1SMingming Cao 	groups = idxblocks;
4275a02908f1SMingming Cao 	if (chunk)
4276a02908f1SMingming Cao 		groups += 1;
4277ac27a0ecSDave Kleikamp 	else
4278a02908f1SMingming Cao 		groups += nrblocks;
4279ac27a0ecSDave Kleikamp 
4280a02908f1SMingming Cao 	gdpblocks = groups;
42818df9675fSTheodore Ts'o 	if (groups > ngroups)
42828df9675fSTheodore Ts'o 		groups = ngroups;
4283a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4284a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4285a02908f1SMingming Cao 
4286a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
4287a02908f1SMingming Cao 	ret += groups + gdpblocks;
4288a02908f1SMingming Cao 
4289a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
4290a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4291ac27a0ecSDave Kleikamp 
4292ac27a0ecSDave Kleikamp 	return ret;
4293ac27a0ecSDave Kleikamp }
4294ac27a0ecSDave Kleikamp 
4295ac27a0ecSDave Kleikamp /*
429625985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
4297f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
4298f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
4299a02908f1SMingming Cao  *
4300525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
4301a02908f1SMingming Cao  *
4302525f4ed8SMingming Cao  * We need to consider the worse case, when
4303a02908f1SMingming Cao  * one new block per extent.
4304a02908f1SMingming Cao  */
4305a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
4306a02908f1SMingming Cao {
4307a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
4308a02908f1SMingming Cao 	int ret;
4309a02908f1SMingming Cao 
4310a02908f1SMingming Cao 	ret = ext4_meta_trans_blocks(inode, bpp, 0);
4311a02908f1SMingming Cao 
4312a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
4313a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
4314a02908f1SMingming Cao 		ret += bpp;
4315a02908f1SMingming Cao 	return ret;
4316a02908f1SMingming Cao }
4317f3bd1f3fSMingming Cao 
4318f3bd1f3fSMingming Cao /*
4319f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
4320f3bd1f3fSMingming Cao  *
4321f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
432279e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4323f3bd1f3fSMingming Cao  *
4324f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
4325f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
4326f3bd1f3fSMingming Cao  */
4327f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4328f3bd1f3fSMingming Cao {
4329f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
4330f3bd1f3fSMingming Cao }
4331f3bd1f3fSMingming Cao 
4332a02908f1SMingming Cao /*
4333617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
4334ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
4335ac27a0ecSDave Kleikamp  */
4336617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
4337617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
4338ac27a0ecSDave Kleikamp {
4339ac27a0ecSDave Kleikamp 	int err = 0;
4340ac27a0ecSDave Kleikamp 
434125ec56b5SJean Noel Cordenner 	if (test_opt(inode->i_sb, I_VERSION))
434225ec56b5SJean Noel Cordenner 		inode_inc_iversion(inode);
434325ec56b5SJean Noel Cordenner 
4344ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
4345ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
4346ac27a0ecSDave Kleikamp 
4347dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4348830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
4349ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
4350ac27a0ecSDave Kleikamp 	return err;
4351ac27a0ecSDave Kleikamp }
4352ac27a0ecSDave Kleikamp 
4353ac27a0ecSDave Kleikamp /*
4354ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
4355ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
4356ac27a0ecSDave Kleikamp  */
4357ac27a0ecSDave Kleikamp 
4358ac27a0ecSDave Kleikamp int
4359617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4360617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
4361ac27a0ecSDave Kleikamp {
43620390131bSFrank Mayhar 	int err;
43630390131bSFrank Mayhar 
4364617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
4365ac27a0ecSDave Kleikamp 	if (!err) {
4366ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
4367617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, iloc->bh);
4368ac27a0ecSDave Kleikamp 		if (err) {
4369ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
4370ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
4371ac27a0ecSDave Kleikamp 		}
4372ac27a0ecSDave Kleikamp 	}
4373617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
4374ac27a0ecSDave Kleikamp 	return err;
4375ac27a0ecSDave Kleikamp }
4376ac27a0ecSDave Kleikamp 
4377ac27a0ecSDave Kleikamp /*
43786dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
43796dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
43806dd4ee7cSKalpak Shah  */
43811d03ec98SAneesh Kumar K.V static int ext4_expand_extra_isize(struct inode *inode,
43821d03ec98SAneesh Kumar K.V 				   unsigned int new_extra_isize,
43831d03ec98SAneesh Kumar K.V 				   struct ext4_iloc iloc,
43841d03ec98SAneesh Kumar K.V 				   handle_t *handle)
43856dd4ee7cSKalpak Shah {
43866dd4ee7cSKalpak Shah 	struct ext4_inode *raw_inode;
43876dd4ee7cSKalpak Shah 	struct ext4_xattr_ibody_header *header;
43886dd4ee7cSKalpak Shah 
43896dd4ee7cSKalpak Shah 	if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
43906dd4ee7cSKalpak Shah 		return 0;
43916dd4ee7cSKalpak Shah 
43926dd4ee7cSKalpak Shah 	raw_inode = ext4_raw_inode(&iloc);
43936dd4ee7cSKalpak Shah 
43946dd4ee7cSKalpak Shah 	header = IHDR(inode, raw_inode);
43956dd4ee7cSKalpak Shah 
43966dd4ee7cSKalpak Shah 	/* No extended attributes present */
439719f5fb7aSTheodore Ts'o 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
43986dd4ee7cSKalpak Shah 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
43996dd4ee7cSKalpak Shah 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
44006dd4ee7cSKalpak Shah 			new_extra_isize);
44016dd4ee7cSKalpak Shah 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
44026dd4ee7cSKalpak Shah 		return 0;
44036dd4ee7cSKalpak Shah 	}
44046dd4ee7cSKalpak Shah 
44056dd4ee7cSKalpak Shah 	/* try to expand with EAs present */
44066dd4ee7cSKalpak Shah 	return ext4_expand_extra_isize_ea(inode, new_extra_isize,
44076dd4ee7cSKalpak Shah 					  raw_inode, handle);
44086dd4ee7cSKalpak Shah }
44096dd4ee7cSKalpak Shah 
44106dd4ee7cSKalpak Shah /*
4411ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
4412ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
4413ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
4414ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
4415ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
4416ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
4417ac27a0ecSDave Kleikamp  *
4418ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
4419ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
4420ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4421ac27a0ecSDave Kleikamp  * we start and wait on commits.
4422ac27a0ecSDave Kleikamp  *
4423ac27a0ecSDave Kleikamp  * Is this efficient/effective?  Well, we're being nice to the system
4424ac27a0ecSDave Kleikamp  * by cleaning up our inodes proactively so they can be reaped
4425ac27a0ecSDave Kleikamp  * without I/O.  But we are potentially leaving up to five seconds'
4426ac27a0ecSDave Kleikamp  * worth of inodes floating about which prune_icache wants us to
4427ac27a0ecSDave Kleikamp  * write out.  One way to fix that would be to get prune_icache()
4428ac27a0ecSDave Kleikamp  * to do a write_super() to free up some memory.  It has the desired
4429ac27a0ecSDave Kleikamp  * effect.
4430ac27a0ecSDave Kleikamp  */
4431617ba13bSMingming Cao int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4432ac27a0ecSDave Kleikamp {
4433617ba13bSMingming Cao 	struct ext4_iloc iloc;
44346dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
44356dd4ee7cSKalpak Shah 	static unsigned int mnt_count;
44366dd4ee7cSKalpak Shah 	int err, ret;
4437ac27a0ecSDave Kleikamp 
4438ac27a0ecSDave Kleikamp 	might_sleep();
44397ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4440617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
44410390131bSFrank Mayhar 	if (ext4_handle_valid(handle) &&
44420390131bSFrank Mayhar 	    EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
444319f5fb7aSTheodore Ts'o 	    !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
44446dd4ee7cSKalpak Shah 		/*
44456dd4ee7cSKalpak Shah 		 * We need extra buffer credits since we may write into EA block
44466dd4ee7cSKalpak Shah 		 * with this same handle. If journal_extend fails, then it will
44476dd4ee7cSKalpak Shah 		 * only result in a minor loss of functionality for that inode.
44486dd4ee7cSKalpak Shah 		 * If this is felt to be critical, then e2fsck should be run to
44496dd4ee7cSKalpak Shah 		 * force a large enough s_min_extra_isize.
44506dd4ee7cSKalpak Shah 		 */
44516dd4ee7cSKalpak Shah 		if ((jbd2_journal_extend(handle,
44526dd4ee7cSKalpak Shah 			     EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
44536dd4ee7cSKalpak Shah 			ret = ext4_expand_extra_isize(inode,
44546dd4ee7cSKalpak Shah 						      sbi->s_want_extra_isize,
44556dd4ee7cSKalpak Shah 						      iloc, handle);
44566dd4ee7cSKalpak Shah 			if (ret) {
445719f5fb7aSTheodore Ts'o 				ext4_set_inode_state(inode,
445819f5fb7aSTheodore Ts'o 						     EXT4_STATE_NO_EXPAND);
4459c1bddad9SAneesh Kumar K.V 				if (mnt_count !=
4460c1bddad9SAneesh Kumar K.V 					le16_to_cpu(sbi->s_es->s_mnt_count)) {
446112062dddSEric Sandeen 					ext4_warning(inode->i_sb,
44626dd4ee7cSKalpak Shah 					"Unable to expand inode %lu. Delete"
44636dd4ee7cSKalpak Shah 					" some EAs or run e2fsck.",
44646dd4ee7cSKalpak Shah 					inode->i_ino);
4465c1bddad9SAneesh Kumar K.V 					mnt_count =
4466c1bddad9SAneesh Kumar K.V 					  le16_to_cpu(sbi->s_es->s_mnt_count);
44676dd4ee7cSKalpak Shah 				}
44686dd4ee7cSKalpak Shah 			}
44696dd4ee7cSKalpak Shah 		}
44706dd4ee7cSKalpak Shah 	}
4471ac27a0ecSDave Kleikamp 	if (!err)
4472617ba13bSMingming Cao 		err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4473ac27a0ecSDave Kleikamp 	return err;
4474ac27a0ecSDave Kleikamp }
4475ac27a0ecSDave Kleikamp 
4476ac27a0ecSDave Kleikamp /*
4477617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
4478ac27a0ecSDave Kleikamp  *
4479ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
4480ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
4481ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
4482ac27a0ecSDave Kleikamp  *
44835dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
4484ac27a0ecSDave Kleikamp  * are allocated to the file.
4485ac27a0ecSDave Kleikamp  *
4486ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
4487ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
4488ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
4489ac27a0ecSDave Kleikamp  */
4490aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
4491ac27a0ecSDave Kleikamp {
4492ac27a0ecSDave Kleikamp 	handle_t *handle;
4493ac27a0ecSDave Kleikamp 
4494617ba13bSMingming Cao 	handle = ext4_journal_start(inode, 2);
4495ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
4496ac27a0ecSDave Kleikamp 		goto out;
4497f3dc272fSCurt Wohlgemuth 
4498617ba13bSMingming Cao 	ext4_mark_inode_dirty(handle, inode);
4499f3dc272fSCurt Wohlgemuth 
4500617ba13bSMingming Cao 	ext4_journal_stop(handle);
4501ac27a0ecSDave Kleikamp out:
4502ac27a0ecSDave Kleikamp 	return;
4503ac27a0ecSDave Kleikamp }
4504ac27a0ecSDave Kleikamp 
4505ac27a0ecSDave Kleikamp #if 0
4506ac27a0ecSDave Kleikamp /*
4507ac27a0ecSDave Kleikamp  * Bind an inode's backing buffer_head into this transaction, to prevent
4508ac27a0ecSDave Kleikamp  * it from being flushed to disk early.  Unlike
4509617ba13bSMingming Cao  * ext4_reserve_inode_write, this leaves behind no bh reference and
4510ac27a0ecSDave Kleikamp  * returns no iloc structure, so the caller needs to repeat the iloc
4511ac27a0ecSDave Kleikamp  * lookup to mark the inode dirty later.
4512ac27a0ecSDave Kleikamp  */
4513617ba13bSMingming Cao static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4514ac27a0ecSDave Kleikamp {
4515617ba13bSMingming Cao 	struct ext4_iloc iloc;
4516ac27a0ecSDave Kleikamp 
4517ac27a0ecSDave Kleikamp 	int err = 0;
4518ac27a0ecSDave Kleikamp 	if (handle) {
4519617ba13bSMingming Cao 		err = ext4_get_inode_loc(inode, &iloc);
4520ac27a0ecSDave Kleikamp 		if (!err) {
4521ac27a0ecSDave Kleikamp 			BUFFER_TRACE(iloc.bh, "get_write_access");
4522dab291afSMingming Cao 			err = jbd2_journal_get_write_access(handle, iloc.bh);
4523ac27a0ecSDave Kleikamp 			if (!err)
45240390131bSFrank Mayhar 				err = ext4_handle_dirty_metadata(handle,
452573b50c1cSCurt Wohlgemuth 								 NULL,
4526ac27a0ecSDave Kleikamp 								 iloc.bh);
4527ac27a0ecSDave Kleikamp 			brelse(iloc.bh);
4528ac27a0ecSDave Kleikamp 		}
4529ac27a0ecSDave Kleikamp 	}
4530617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
4531ac27a0ecSDave Kleikamp 	return err;
4532ac27a0ecSDave Kleikamp }
4533ac27a0ecSDave Kleikamp #endif
4534ac27a0ecSDave Kleikamp 
4535617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
4536ac27a0ecSDave Kleikamp {
4537ac27a0ecSDave Kleikamp 	journal_t *journal;
4538ac27a0ecSDave Kleikamp 	handle_t *handle;
4539ac27a0ecSDave Kleikamp 	int err;
4540ac27a0ecSDave Kleikamp 
4541ac27a0ecSDave Kleikamp 	/*
4542ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
4543ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
4544ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
4545ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
4546ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
4547ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
4548ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
4549ac27a0ecSDave Kleikamp 	 */
4550ac27a0ecSDave Kleikamp 
4551617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
45520390131bSFrank Mayhar 	if (!journal)
45530390131bSFrank Mayhar 		return 0;
4554d699594dSDave Hansen 	if (is_journal_aborted(journal))
4555ac27a0ecSDave Kleikamp 		return -EROFS;
4556ac27a0ecSDave Kleikamp 
4557dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
4558dab291afSMingming Cao 	jbd2_journal_flush(journal);
4559ac27a0ecSDave Kleikamp 
4560ac27a0ecSDave Kleikamp 	/*
4561ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
4562ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
4563ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
4564ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
4565ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
4566ac27a0ecSDave Kleikamp 	 */
4567ac27a0ecSDave Kleikamp 
4568ac27a0ecSDave Kleikamp 	if (val)
456912e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4570ac27a0ecSDave Kleikamp 	else
457112e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4572617ba13bSMingming Cao 	ext4_set_aops(inode);
4573ac27a0ecSDave Kleikamp 
4574dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
4575ac27a0ecSDave Kleikamp 
4576ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
4577ac27a0ecSDave Kleikamp 
4578617ba13bSMingming Cao 	handle = ext4_journal_start(inode, 1);
4579ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
4580ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
4581ac27a0ecSDave Kleikamp 
4582617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
45830390131bSFrank Mayhar 	ext4_handle_sync(handle);
4584617ba13bSMingming Cao 	ext4_journal_stop(handle);
4585617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
4586ac27a0ecSDave Kleikamp 
4587ac27a0ecSDave Kleikamp 	return err;
4588ac27a0ecSDave Kleikamp }
45892e9ee850SAneesh Kumar K.V 
45902e9ee850SAneesh Kumar K.V static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
45912e9ee850SAneesh Kumar K.V {
45922e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
45932e9ee850SAneesh Kumar K.V }
45942e9ee850SAneesh Kumar K.V 
4595c2ec175cSNick Piggin int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
45962e9ee850SAneesh Kumar K.V {
4597c2ec175cSNick Piggin 	struct page *page = vmf->page;
45982e9ee850SAneesh Kumar K.V 	loff_t size;
45992e9ee850SAneesh Kumar K.V 	unsigned long len;
46009ea7df53SJan Kara 	int ret;
46012e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
46022e9ee850SAneesh Kumar K.V 	struct inode *inode = file->f_path.dentry->d_inode;
46032e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
46049ea7df53SJan Kara 	handle_t *handle;
46059ea7df53SJan Kara 	get_block_t *get_block;
46069ea7df53SJan Kara 	int retries = 0;
46072e9ee850SAneesh Kumar K.V 
46082e9ee850SAneesh Kumar K.V 	/*
46099ea7df53SJan Kara 	 * This check is racy but catches the common case. We rely on
46109ea7df53SJan Kara 	 * __block_page_mkwrite() to do a reliable check.
46112e9ee850SAneesh Kumar K.V 	 */
46129ea7df53SJan Kara 	vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
46139ea7df53SJan Kara 	/* Delalloc case is easy... */
46149ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
46159ea7df53SJan Kara 	    !ext4_should_journal_data(inode) &&
46169ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
46179ea7df53SJan Kara 		do {
46189ea7df53SJan Kara 			ret = __block_page_mkwrite(vma, vmf,
46199ea7df53SJan Kara 						   ext4_da_get_block_prep);
46209ea7df53SJan Kara 		} while (ret == -ENOSPC &&
46219ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
46229ea7df53SJan Kara 		goto out_ret;
46232e9ee850SAneesh Kumar K.V 	}
46240e499890SDarrick J. Wong 
46250e499890SDarrick J. Wong 	lock_page(page);
46269ea7df53SJan Kara 	size = i_size_read(inode);
46279ea7df53SJan Kara 	/* Page got truncated from under us? */
46289ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
46299ea7df53SJan Kara 		unlock_page(page);
46309ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
46319ea7df53SJan Kara 		goto out;
46320e499890SDarrick J. Wong 	}
46332e9ee850SAneesh Kumar K.V 
46342e9ee850SAneesh Kumar K.V 	if (page->index == size >> PAGE_CACHE_SHIFT)
46352e9ee850SAneesh Kumar K.V 		len = size & ~PAGE_CACHE_MASK;
46362e9ee850SAneesh Kumar K.V 	else
46372e9ee850SAneesh Kumar K.V 		len = PAGE_CACHE_SIZE;
4638a827eaffSAneesh Kumar K.V 	/*
46399ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
46409ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
4641a827eaffSAneesh Kumar K.V 	 */
46422e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
46432e9ee850SAneesh Kumar K.V 		if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
4644a827eaffSAneesh Kumar K.V 					ext4_bh_unmapped)) {
46459ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
46469ea7df53SJan Kara 			wait_on_page_writeback(page);
46479ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
46489ea7df53SJan Kara 			goto out;
46492e9ee850SAneesh Kumar K.V 		}
4650a827eaffSAneesh Kumar K.V 	}
4651a827eaffSAneesh Kumar K.V 	unlock_page(page);
46529ea7df53SJan Kara 	/* OK, we need to fill the hole... */
46539ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
46549ea7df53SJan Kara 		get_block = ext4_get_block_write;
46559ea7df53SJan Kara 	else
46569ea7df53SJan Kara 		get_block = ext4_get_block;
46579ea7df53SJan Kara retry_alloc:
46589ea7df53SJan Kara 	handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
46599ea7df53SJan Kara 	if (IS_ERR(handle)) {
4660c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
46619ea7df53SJan Kara 		goto out;
46629ea7df53SJan Kara 	}
46639ea7df53SJan Kara 	ret = __block_page_mkwrite(vma, vmf, get_block);
46649ea7df53SJan Kara 	if (!ret && ext4_should_journal_data(inode)) {
46659ea7df53SJan Kara 		if (walk_page_buffers(handle, page_buffers(page), 0,
46669ea7df53SJan Kara 			  PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
46679ea7df53SJan Kara 			unlock_page(page);
46689ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
46699ea7df53SJan Kara 			goto out;
46709ea7df53SJan Kara 		}
46719ea7df53SJan Kara 		ext4_set_inode_state(inode, EXT4_STATE_JDATA);
46729ea7df53SJan Kara 	}
46739ea7df53SJan Kara 	ext4_journal_stop(handle);
46749ea7df53SJan Kara 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
46759ea7df53SJan Kara 		goto retry_alloc;
46769ea7df53SJan Kara out_ret:
46779ea7df53SJan Kara 	ret = block_page_mkwrite_return(ret);
46789ea7df53SJan Kara out:
46792e9ee850SAneesh Kumar K.V 	return ret;
46802e9ee850SAneesh Kumar K.V }
4681