xref: /openbmc/linux/fs/ext4/extents.c (revision 378f32bab3714f04c4e0c3aee4129f6703805550)
1f5166768STheodore Ts'o // SPDX-License-Identifier: GPL-2.0
2a86c6181SAlex Tomas /*
3a86c6181SAlex Tomas  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4a86c6181SAlex Tomas  * Written by Alex Tomas <alex@clusterfs.com>
5a86c6181SAlex Tomas  *
6a86c6181SAlex Tomas  * Architecture independence:
7a86c6181SAlex Tomas  *   Copyright (c) 2005, Bull S.A.
8a86c6181SAlex Tomas  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
9a86c6181SAlex Tomas  */
10a86c6181SAlex Tomas 
11a86c6181SAlex Tomas /*
12a86c6181SAlex Tomas  * Extents support for EXT4
13a86c6181SAlex Tomas  *
14a86c6181SAlex Tomas  * TODO:
15a86c6181SAlex Tomas  *   - ext4*_error() should be used in some situations
16a86c6181SAlex Tomas  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
17a86c6181SAlex Tomas  *   - smart tree reduction
18a86c6181SAlex Tomas  */
19a86c6181SAlex Tomas 
20a86c6181SAlex Tomas #include <linux/fs.h>
21a86c6181SAlex Tomas #include <linux/time.h>
22cd02ff0bSMingming Cao #include <linux/jbd2.h>
23a86c6181SAlex Tomas #include <linux/highuid.h>
24a86c6181SAlex Tomas #include <linux/pagemap.h>
25a86c6181SAlex Tomas #include <linux/quotaops.h>
26a86c6181SAlex Tomas #include <linux/string.h>
27a86c6181SAlex Tomas #include <linux/slab.h>
287c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
296873fa0dSEric Sandeen #include <linux/fiemap.h>
3066114cadSTejun Heo #include <linux/backing-dev.h>
313dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
324a092d73STheodore Ts'o #include "ext4_extents.h"
33f19d5870STao Ma #include "xattr.h"
34a86c6181SAlex Tomas 
350562e0baSJiaying Zhang #include <trace/events/ext4.h>
360562e0baSJiaying Zhang 
375f95d21fSLukas Czerner /*
385f95d21fSLukas Czerner  * used by extent splitting.
395f95d21fSLukas Czerner  */
405f95d21fSLukas Czerner #define EXT4_EXT_MAY_ZEROOUT	0x1  /* safe to zeroout if split fails \
415f95d21fSLukas Czerner 					due to ENOSPC */
42556615dcSLukas Czerner #define EXT4_EXT_MARK_UNWRIT1	0x2  /* mark first half unwritten */
43556615dcSLukas Czerner #define EXT4_EXT_MARK_UNWRIT2	0x4  /* mark second half unwritten */
445f95d21fSLukas Czerner 
45dee1f973SDmitry Monakhov #define EXT4_EXT_DATA_VALID1	0x8  /* first half contains valid data */
46dee1f973SDmitry Monakhov #define EXT4_EXT_DATA_VALID2	0x10 /* second half contains valid data */
47dee1f973SDmitry Monakhov 
487ac5990dSDarrick J. Wong static __le32 ext4_extent_block_csum(struct inode *inode,
497ac5990dSDarrick J. Wong 				     struct ext4_extent_header *eh)
507ac5990dSDarrick J. Wong {
517ac5990dSDarrick J. Wong 	struct ext4_inode_info *ei = EXT4_I(inode);
527ac5990dSDarrick J. Wong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
537ac5990dSDarrick J. Wong 	__u32 csum;
547ac5990dSDarrick J. Wong 
557ac5990dSDarrick J. Wong 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
567ac5990dSDarrick J. Wong 			   EXT4_EXTENT_TAIL_OFFSET(eh));
577ac5990dSDarrick J. Wong 	return cpu_to_le32(csum);
587ac5990dSDarrick J. Wong }
597ac5990dSDarrick J. Wong 
607ac5990dSDarrick J. Wong static int ext4_extent_block_csum_verify(struct inode *inode,
617ac5990dSDarrick J. Wong 					 struct ext4_extent_header *eh)
627ac5990dSDarrick J. Wong {
637ac5990dSDarrick J. Wong 	struct ext4_extent_tail *et;
647ac5990dSDarrick J. Wong 
659aa5d32bSDmitry Monakhov 	if (!ext4_has_metadata_csum(inode->i_sb))
667ac5990dSDarrick J. Wong 		return 1;
677ac5990dSDarrick J. Wong 
687ac5990dSDarrick J. Wong 	et = find_ext4_extent_tail(eh);
697ac5990dSDarrick J. Wong 	if (et->et_checksum != ext4_extent_block_csum(inode, eh))
707ac5990dSDarrick J. Wong 		return 0;
717ac5990dSDarrick J. Wong 	return 1;
727ac5990dSDarrick J. Wong }
737ac5990dSDarrick J. Wong 
747ac5990dSDarrick J. Wong static void ext4_extent_block_csum_set(struct inode *inode,
757ac5990dSDarrick J. Wong 				       struct ext4_extent_header *eh)
767ac5990dSDarrick J. Wong {
777ac5990dSDarrick J. Wong 	struct ext4_extent_tail *et;
787ac5990dSDarrick J. Wong 
799aa5d32bSDmitry Monakhov 	if (!ext4_has_metadata_csum(inode->i_sb))
807ac5990dSDarrick J. Wong 		return;
817ac5990dSDarrick J. Wong 
827ac5990dSDarrick J. Wong 	et = find_ext4_extent_tail(eh);
837ac5990dSDarrick J. Wong 	et->et_checksum = ext4_extent_block_csum(inode, eh);
847ac5990dSDarrick J. Wong }
857ac5990dSDarrick J. Wong 
86d583fb87SAllison Henderson static int ext4_split_extent(handle_t *handle,
87d583fb87SAllison Henderson 				struct inode *inode,
88dfe50809STheodore Ts'o 				struct ext4_ext_path **ppath,
89d583fb87SAllison Henderson 				struct ext4_map_blocks *map,
90d583fb87SAllison Henderson 				int split_flag,
91d583fb87SAllison Henderson 				int flags);
92d583fb87SAllison Henderson 
935f95d21fSLukas Czerner static int ext4_split_extent_at(handle_t *handle,
945f95d21fSLukas Czerner 			     struct inode *inode,
95dfe50809STheodore Ts'o 			     struct ext4_ext_path **ppath,
965f95d21fSLukas Czerner 			     ext4_lblk_t split,
975f95d21fSLukas Czerner 			     int split_flag,
985f95d21fSLukas Czerner 			     int flags);
995f95d21fSLukas Czerner 
10091dd8c11SLukas Czerner static int ext4_find_delayed_extent(struct inode *inode,
10169eb33dcSZheng Liu 				    struct extent_status *newes);
10291dd8c11SLukas Czerner 
103487caeefSJan Kara static int ext4_ext_truncate_extend_restart(handle_t *handle,
104487caeefSJan Kara 					    struct inode *inode,
105487caeefSJan Kara 					    int needed)
106a86c6181SAlex Tomas {
107a86c6181SAlex Tomas 	int err;
108a86c6181SAlex Tomas 
1090390131bSFrank Mayhar 	if (!ext4_handle_valid(handle))
1100390131bSFrank Mayhar 		return 0;
1117b808191STheodore Ts'o 	if (handle->h_buffer_credits >= needed)
1129102e4faSShen Feng 		return 0;
1137b808191STheodore Ts'o 	/*
1147b808191STheodore Ts'o 	 * If we need to extend the journal get a few extra blocks
1157b808191STheodore Ts'o 	 * while we're at it for efficiency's sake.
1167b808191STheodore Ts'o 	 */
1177b808191STheodore Ts'o 	needed += 3;
1187b808191STheodore Ts'o 	err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
1190123c939STheodore Ts'o 	if (err <= 0)
1209102e4faSShen Feng 		return err;
121487caeefSJan Kara 	err = ext4_truncate_restart_trans(handle, inode, needed);
1220617b83fSDmitry Monakhov 	if (err == 0)
1230617b83fSDmitry Monakhov 		err = -EAGAIN;
124487caeefSJan Kara 
125487caeefSJan Kara 	return err;
126a86c6181SAlex Tomas }
127a86c6181SAlex Tomas 
128a86c6181SAlex Tomas /*
129a86c6181SAlex Tomas  * could return:
130a86c6181SAlex Tomas  *  - EROFS
131a86c6181SAlex Tomas  *  - ENOMEM
132a86c6181SAlex Tomas  */
133a86c6181SAlex Tomas static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
134a86c6181SAlex Tomas 				struct ext4_ext_path *path)
135a86c6181SAlex Tomas {
136a86c6181SAlex Tomas 	if (path->p_bh) {
137a86c6181SAlex Tomas 		/* path points to block */
1385d601255Sliang xie 		BUFFER_TRACE(path->p_bh, "get_write_access");
139a86c6181SAlex Tomas 		return ext4_journal_get_write_access(handle, path->p_bh);
140a86c6181SAlex Tomas 	}
141a86c6181SAlex Tomas 	/* path points to leaf/index in inode body */
142a86c6181SAlex Tomas 	/* we use in-core data, no need to protect them */
143a86c6181SAlex Tomas 	return 0;
144a86c6181SAlex Tomas }
145a86c6181SAlex Tomas 
146a86c6181SAlex Tomas /*
147a86c6181SAlex Tomas  * could return:
148a86c6181SAlex Tomas  *  - EROFS
149a86c6181SAlex Tomas  *  - ENOMEM
150a86c6181SAlex Tomas  *  - EIO
151a86c6181SAlex Tomas  */
1522656497bSDarrick J. Wong int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
1532656497bSDarrick J. Wong 		     struct inode *inode, struct ext4_ext_path *path)
154a86c6181SAlex Tomas {
155a86c6181SAlex Tomas 	int err;
1564b1f1660SDmitry Monakhov 
1574b1f1660SDmitry Monakhov 	WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
158a86c6181SAlex Tomas 	if (path->p_bh) {
1597ac5990dSDarrick J. Wong 		ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
160a86c6181SAlex Tomas 		/* path points to block */
1619ea7a0dfSTheodore Ts'o 		err = __ext4_handle_dirty_metadata(where, line, handle,
1629ea7a0dfSTheodore Ts'o 						   inode, path->p_bh);
163a86c6181SAlex Tomas 	} else {
164a86c6181SAlex Tomas 		/* path points to leaf/index in inode body */
165a86c6181SAlex Tomas 		err = ext4_mark_inode_dirty(handle, inode);
166a86c6181SAlex Tomas 	}
167a86c6181SAlex Tomas 	return err;
168a86c6181SAlex Tomas }
169a86c6181SAlex Tomas 
170f65e6fbaSAlex Tomas static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
171a86c6181SAlex Tomas 			      struct ext4_ext_path *path,
172725d26d3SAneesh Kumar K.V 			      ext4_lblk_t block)
173a86c6181SAlex Tomas {
174a86c6181SAlex Tomas 	if (path) {
17581fdbb4aSYongqiang Yang 		int depth = path->p_depth;
176a86c6181SAlex Tomas 		struct ext4_extent *ex;
177a86c6181SAlex Tomas 
178ad4fb9caSKazuya Mio 		/*
179ad4fb9caSKazuya Mio 		 * Try to predict block placement assuming that we are
180ad4fb9caSKazuya Mio 		 * filling in a file which will eventually be
181ad4fb9caSKazuya Mio 		 * non-sparse --- i.e., in the case of libbfd writing
182ad4fb9caSKazuya Mio 		 * an ELF object sections out-of-order but in a way
183ad4fb9caSKazuya Mio 		 * the eventually results in a contiguous object or
184ad4fb9caSKazuya Mio 		 * executable file, or some database extending a table
185ad4fb9caSKazuya Mio 		 * space file.  However, this is actually somewhat
186ad4fb9caSKazuya Mio 		 * non-ideal if we are writing a sparse file such as
187ad4fb9caSKazuya Mio 		 * qemu or KVM writing a raw image file that is going
188ad4fb9caSKazuya Mio 		 * to stay fairly sparse, since it will end up
189ad4fb9caSKazuya Mio 		 * fragmenting the file system's free space.  Maybe we
190ad4fb9caSKazuya Mio 		 * should have some hueristics or some way to allow
191ad4fb9caSKazuya Mio 		 * userspace to pass a hint to file system,
192b8d6568aSTao Ma 		 * especially if the latter case turns out to be
193ad4fb9caSKazuya Mio 		 * common.
194ad4fb9caSKazuya Mio 		 */
1957e028976SAvantika Mathur 		ex = path[depth].p_ext;
196ad4fb9caSKazuya Mio 		if (ex) {
197ad4fb9caSKazuya Mio 			ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
198ad4fb9caSKazuya Mio 			ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
199ad4fb9caSKazuya Mio 
200ad4fb9caSKazuya Mio 			if (block > ext_block)
201ad4fb9caSKazuya Mio 				return ext_pblk + (block - ext_block);
202ad4fb9caSKazuya Mio 			else
203ad4fb9caSKazuya Mio 				return ext_pblk - (ext_block - block);
204ad4fb9caSKazuya Mio 		}
205a86c6181SAlex Tomas 
206d0d856e8SRandy Dunlap 		/* it looks like index is empty;
207d0d856e8SRandy Dunlap 		 * try to find starting block from index itself */
208a86c6181SAlex Tomas 		if (path[depth].p_bh)
209a86c6181SAlex Tomas 			return path[depth].p_bh->b_blocknr;
210a86c6181SAlex Tomas 	}
211a86c6181SAlex Tomas 
212a86c6181SAlex Tomas 	/* OK. use inode's group */
213f86186b4SEric Sandeen 	return ext4_inode_to_goal_block(inode);
214a86c6181SAlex Tomas }
215a86c6181SAlex Tomas 
216654b4908SAneesh Kumar K.V /*
217654b4908SAneesh Kumar K.V  * Allocation for a meta data block
218654b4908SAneesh Kumar K.V  */
219f65e6fbaSAlex Tomas static ext4_fsblk_t
220654b4908SAneesh Kumar K.V ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
221a86c6181SAlex Tomas 			struct ext4_ext_path *path,
22255f020dbSAllison Henderson 			struct ext4_extent *ex, int *err, unsigned int flags)
223a86c6181SAlex Tomas {
224f65e6fbaSAlex Tomas 	ext4_fsblk_t goal, newblock;
225a86c6181SAlex Tomas 
226a86c6181SAlex Tomas 	goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
22755f020dbSAllison Henderson 	newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
22855f020dbSAllison Henderson 					NULL, err);
229a86c6181SAlex Tomas 	return newblock;
230a86c6181SAlex Tomas }
231a86c6181SAlex Tomas 
23255ad63bfSTheodore Ts'o static inline int ext4_ext_space_block(struct inode *inode, int check)
233a86c6181SAlex Tomas {
234a86c6181SAlex Tomas 	int size;
235a86c6181SAlex Tomas 
236a86c6181SAlex Tomas 	size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
237a86c6181SAlex Tomas 			/ sizeof(struct ext4_extent);
238bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
23902dc62fbSYongqiang Yang 	if (!check && size > 6)
240a86c6181SAlex Tomas 		size = 6;
241a86c6181SAlex Tomas #endif
242a86c6181SAlex Tomas 	return size;
243a86c6181SAlex Tomas }
244a86c6181SAlex Tomas 
24555ad63bfSTheodore Ts'o static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
246a86c6181SAlex Tomas {
247a86c6181SAlex Tomas 	int size;
248a86c6181SAlex Tomas 
249a86c6181SAlex Tomas 	size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
250a86c6181SAlex Tomas 			/ sizeof(struct ext4_extent_idx);
251bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
25202dc62fbSYongqiang Yang 	if (!check && size > 5)
253a86c6181SAlex Tomas 		size = 5;
254a86c6181SAlex Tomas #endif
255a86c6181SAlex Tomas 	return size;
256a86c6181SAlex Tomas }
257a86c6181SAlex Tomas 
25855ad63bfSTheodore Ts'o static inline int ext4_ext_space_root(struct inode *inode, int check)
259a86c6181SAlex Tomas {
260a86c6181SAlex Tomas 	int size;
261a86c6181SAlex Tomas 
262a86c6181SAlex Tomas 	size = sizeof(EXT4_I(inode)->i_data);
263a86c6181SAlex Tomas 	size -= sizeof(struct ext4_extent_header);
264a86c6181SAlex Tomas 	size /= sizeof(struct ext4_extent);
265bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
26602dc62fbSYongqiang Yang 	if (!check && size > 3)
267a86c6181SAlex Tomas 		size = 3;
268a86c6181SAlex Tomas #endif
269a86c6181SAlex Tomas 	return size;
270a86c6181SAlex Tomas }
271a86c6181SAlex Tomas 
27255ad63bfSTheodore Ts'o static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
273a86c6181SAlex Tomas {
274a86c6181SAlex Tomas 	int size;
275a86c6181SAlex Tomas 
276a86c6181SAlex Tomas 	size = sizeof(EXT4_I(inode)->i_data);
277a86c6181SAlex Tomas 	size -= sizeof(struct ext4_extent_header);
278a86c6181SAlex Tomas 	size /= sizeof(struct ext4_extent_idx);
279bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
28002dc62fbSYongqiang Yang 	if (!check && size > 4)
281a86c6181SAlex Tomas 		size = 4;
282a86c6181SAlex Tomas #endif
283a86c6181SAlex Tomas 	return size;
284a86c6181SAlex Tomas }
285a86c6181SAlex Tomas 
286fcf6b1b7SDmitry Monakhov static inline int
287fcf6b1b7SDmitry Monakhov ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
288dfe50809STheodore Ts'o 			   struct ext4_ext_path **ppath, ext4_lblk_t lblk,
289fcf6b1b7SDmitry Monakhov 			   int nofail)
290fcf6b1b7SDmitry Monakhov {
291dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
292fcf6b1b7SDmitry Monakhov 	int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
293fcf6b1b7SDmitry Monakhov 
294dfe50809STheodore Ts'o 	return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
295fcf6b1b7SDmitry Monakhov 			EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
296fcf6b1b7SDmitry Monakhov 			EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
297fcf6b1b7SDmitry Monakhov 			(nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
298fcf6b1b7SDmitry Monakhov }
299fcf6b1b7SDmitry Monakhov 
300d2a17637SMingming Cao /*
301d2a17637SMingming Cao  * Calculate the number of metadata blocks needed
302d2a17637SMingming Cao  * to allocate @blocks
303d2a17637SMingming Cao  * Worse case is one block per extent
304d2a17637SMingming Cao  */
30501f49d0bSTheodore Ts'o int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
306d2a17637SMingming Cao {
3079d0be502STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
30881fdbb4aSYongqiang Yang 	int idxs;
309d2a17637SMingming Cao 
3109d0be502STheodore Ts'o 	idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
3119d0be502STheodore Ts'o 		/ sizeof(struct ext4_extent_idx));
312d2a17637SMingming Cao 
313d2a17637SMingming Cao 	/*
3149d0be502STheodore Ts'o 	 * If the new delayed allocation block is contiguous with the
3159d0be502STheodore Ts'o 	 * previous da block, it can share index blocks with the
3169d0be502STheodore Ts'o 	 * previous block, so we only need to allocate a new index
3179d0be502STheodore Ts'o 	 * block every idxs leaf blocks.  At ldxs**2 blocks, we need
3189d0be502STheodore Ts'o 	 * an additional index block, and at ldxs**3 blocks, yet
3199d0be502STheodore Ts'o 	 * another index blocks.
320d2a17637SMingming Cao 	 */
3219d0be502STheodore Ts'o 	if (ei->i_da_metadata_calc_len &&
3229d0be502STheodore Ts'o 	    ei->i_da_metadata_calc_last_lblock+1 == lblock) {
32381fdbb4aSYongqiang Yang 		int num = 0;
32481fdbb4aSYongqiang Yang 
3259d0be502STheodore Ts'o 		if ((ei->i_da_metadata_calc_len % idxs) == 0)
3269d0be502STheodore Ts'o 			num++;
3279d0be502STheodore Ts'o 		if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
3289d0be502STheodore Ts'o 			num++;
3299d0be502STheodore Ts'o 		if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
3309d0be502STheodore Ts'o 			num++;
3319d0be502STheodore Ts'o 			ei->i_da_metadata_calc_len = 0;
3329d0be502STheodore Ts'o 		} else
3339d0be502STheodore Ts'o 			ei->i_da_metadata_calc_len++;
3349d0be502STheodore Ts'o 		ei->i_da_metadata_calc_last_lblock++;
335d2a17637SMingming Cao 		return num;
336d2a17637SMingming Cao 	}
337d2a17637SMingming Cao 
3389d0be502STheodore Ts'o 	/*
3399d0be502STheodore Ts'o 	 * In the worst case we need a new set of index blocks at
3409d0be502STheodore Ts'o 	 * every level of the inode's extent tree.
3419d0be502STheodore Ts'o 	 */
3429d0be502STheodore Ts'o 	ei->i_da_metadata_calc_len = 1;
3439d0be502STheodore Ts'o 	ei->i_da_metadata_calc_last_lblock = lblock;
3449d0be502STheodore Ts'o 	return ext_depth(inode) + 1;
3459d0be502STheodore Ts'o }
3469d0be502STheodore Ts'o 
347c29c0ae7SAlex Tomas static int
348c29c0ae7SAlex Tomas ext4_ext_max_entries(struct inode *inode, int depth)
349c29c0ae7SAlex Tomas {
350c29c0ae7SAlex Tomas 	int max;
351c29c0ae7SAlex Tomas 
352c29c0ae7SAlex Tomas 	if (depth == ext_depth(inode)) {
353c29c0ae7SAlex Tomas 		if (depth == 0)
35455ad63bfSTheodore Ts'o 			max = ext4_ext_space_root(inode, 1);
355c29c0ae7SAlex Tomas 		else
35655ad63bfSTheodore Ts'o 			max = ext4_ext_space_root_idx(inode, 1);
357c29c0ae7SAlex Tomas 	} else {
358c29c0ae7SAlex Tomas 		if (depth == 0)
35955ad63bfSTheodore Ts'o 			max = ext4_ext_space_block(inode, 1);
360c29c0ae7SAlex Tomas 		else
36155ad63bfSTheodore Ts'o 			max = ext4_ext_space_block_idx(inode, 1);
362c29c0ae7SAlex Tomas 	}
363c29c0ae7SAlex Tomas 
364c29c0ae7SAlex Tomas 	return max;
365c29c0ae7SAlex Tomas }
366c29c0ae7SAlex Tomas 
36756b19868SAneesh Kumar K.V static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
36856b19868SAneesh Kumar K.V {
369bf89d16fSTheodore Ts'o 	ext4_fsblk_t block = ext4_ext_pblock(ext);
37056b19868SAneesh Kumar K.V 	int len = ext4_ext_get_actual_len(ext);
3715946d089SEryu Guan 	ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
372e84a26ceSTheodore Ts'o 
373f70749caSVegard Nossum 	/*
374f70749caSVegard Nossum 	 * We allow neither:
375f70749caSVegard Nossum 	 *  - zero length
376f70749caSVegard Nossum 	 *  - overflow/wrap-around
377f70749caSVegard Nossum 	 */
378f70749caSVegard Nossum 	if (lblock + len <= lblock)
37931d4f3a2STheodore Ts'o 		return 0;
3806fd058f7STheodore Ts'o 	return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
38156b19868SAneesh Kumar K.V }
38256b19868SAneesh Kumar K.V 
38356b19868SAneesh Kumar K.V static int ext4_valid_extent_idx(struct inode *inode,
38456b19868SAneesh Kumar K.V 				struct ext4_extent_idx *ext_idx)
38556b19868SAneesh Kumar K.V {
386bf89d16fSTheodore Ts'o 	ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
387e84a26ceSTheodore Ts'o 
3886fd058f7STheodore Ts'o 	return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
38956b19868SAneesh Kumar K.V }
39056b19868SAneesh Kumar K.V 
39156b19868SAneesh Kumar K.V static int ext4_valid_extent_entries(struct inode *inode,
39256b19868SAneesh Kumar K.V 				struct ext4_extent_header *eh,
39356b19868SAneesh Kumar K.V 				int depth)
39456b19868SAneesh Kumar K.V {
39556b19868SAneesh Kumar K.V 	unsigned short entries;
39656b19868SAneesh Kumar K.V 	if (eh->eh_entries == 0)
39756b19868SAneesh Kumar K.V 		return 1;
39856b19868SAneesh Kumar K.V 
39956b19868SAneesh Kumar K.V 	entries = le16_to_cpu(eh->eh_entries);
40056b19868SAneesh Kumar K.V 
40156b19868SAneesh Kumar K.V 	if (depth == 0) {
40256b19868SAneesh Kumar K.V 		/* leaf entries */
40381fdbb4aSYongqiang Yang 		struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
4045946d089SEryu Guan 		struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
4055946d089SEryu Guan 		ext4_fsblk_t pblock = 0;
4065946d089SEryu Guan 		ext4_lblk_t lblock = 0;
4075946d089SEryu Guan 		ext4_lblk_t prev = 0;
4085946d089SEryu Guan 		int len = 0;
40956b19868SAneesh Kumar K.V 		while (entries) {
41056b19868SAneesh Kumar K.V 			if (!ext4_valid_extent(inode, ext))
41156b19868SAneesh Kumar K.V 				return 0;
4125946d089SEryu Guan 
4135946d089SEryu Guan 			/* Check for overlapping extents */
4145946d089SEryu Guan 			lblock = le32_to_cpu(ext->ee_block);
4155946d089SEryu Guan 			len = ext4_ext_get_actual_len(ext);
4165946d089SEryu Guan 			if ((lblock <= prev) && prev) {
4175946d089SEryu Guan 				pblock = ext4_ext_pblock(ext);
4185946d089SEryu Guan 				es->s_last_error_block = cpu_to_le64(pblock);
4195946d089SEryu Guan 				return 0;
4205946d089SEryu Guan 			}
42156b19868SAneesh Kumar K.V 			ext++;
42256b19868SAneesh Kumar K.V 			entries--;
4235946d089SEryu Guan 			prev = lblock + len - 1;
42456b19868SAneesh Kumar K.V 		}
42556b19868SAneesh Kumar K.V 	} else {
42681fdbb4aSYongqiang Yang 		struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
42756b19868SAneesh Kumar K.V 		while (entries) {
42856b19868SAneesh Kumar K.V 			if (!ext4_valid_extent_idx(inode, ext_idx))
42956b19868SAneesh Kumar K.V 				return 0;
43056b19868SAneesh Kumar K.V 			ext_idx++;
43156b19868SAneesh Kumar K.V 			entries--;
43256b19868SAneesh Kumar K.V 		}
43356b19868SAneesh Kumar K.V 	}
43456b19868SAneesh Kumar K.V 	return 1;
43556b19868SAneesh Kumar K.V }
43656b19868SAneesh Kumar K.V 
437c398eda0STheodore Ts'o static int __ext4_ext_check(const char *function, unsigned int line,
438c398eda0STheodore Ts'o 			    struct inode *inode, struct ext4_extent_header *eh,
439c349179bSTheodore Ts'o 			    int depth, ext4_fsblk_t pblk)
440c29c0ae7SAlex Tomas {
441c29c0ae7SAlex Tomas 	const char *error_msg;
4426a797d27SDarrick J. Wong 	int max = 0, err = -EFSCORRUPTED;
443c29c0ae7SAlex Tomas 
444c29c0ae7SAlex Tomas 	if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
445c29c0ae7SAlex Tomas 		error_msg = "invalid magic";
446c29c0ae7SAlex Tomas 		goto corrupted;
447c29c0ae7SAlex Tomas 	}
448c29c0ae7SAlex Tomas 	if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
449c29c0ae7SAlex Tomas 		error_msg = "unexpected eh_depth";
450c29c0ae7SAlex Tomas 		goto corrupted;
451c29c0ae7SAlex Tomas 	}
452c29c0ae7SAlex Tomas 	if (unlikely(eh->eh_max == 0)) {
453c29c0ae7SAlex Tomas 		error_msg = "invalid eh_max";
454c29c0ae7SAlex Tomas 		goto corrupted;
455c29c0ae7SAlex Tomas 	}
456c29c0ae7SAlex Tomas 	max = ext4_ext_max_entries(inode, depth);
457c29c0ae7SAlex Tomas 	if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
458c29c0ae7SAlex Tomas 		error_msg = "too large eh_max";
459c29c0ae7SAlex Tomas 		goto corrupted;
460c29c0ae7SAlex Tomas 	}
461c29c0ae7SAlex Tomas 	if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
462c29c0ae7SAlex Tomas 		error_msg = "invalid eh_entries";
463c29c0ae7SAlex Tomas 		goto corrupted;
464c29c0ae7SAlex Tomas 	}
46556b19868SAneesh Kumar K.V 	if (!ext4_valid_extent_entries(inode, eh, depth)) {
46656b19868SAneesh Kumar K.V 		error_msg = "invalid extent entries";
46756b19868SAneesh Kumar K.V 		goto corrupted;
46856b19868SAneesh Kumar K.V 	}
4697bc94916SVegard Nossum 	if (unlikely(depth > 32)) {
4707bc94916SVegard Nossum 		error_msg = "too large eh_depth";
4717bc94916SVegard Nossum 		goto corrupted;
4727bc94916SVegard Nossum 	}
4737ac5990dSDarrick J. Wong 	/* Verify checksum on non-root extent tree nodes */
4747ac5990dSDarrick J. Wong 	if (ext_depth(inode) != depth &&
4757ac5990dSDarrick J. Wong 	    !ext4_extent_block_csum_verify(inode, eh)) {
4767ac5990dSDarrick J. Wong 		error_msg = "extent tree corrupted";
4776a797d27SDarrick J. Wong 		err = -EFSBADCRC;
4787ac5990dSDarrick J. Wong 		goto corrupted;
4797ac5990dSDarrick J. Wong 	}
480c29c0ae7SAlex Tomas 	return 0;
481c29c0ae7SAlex Tomas 
482c29c0ae7SAlex Tomas corrupted:
483c398eda0STheodore Ts'o 	ext4_error_inode(inode, function, line, 0,
484c349179bSTheodore Ts'o 			 "pblk %llu bad header/extent: %s - magic %x, "
485c29c0ae7SAlex Tomas 			 "entries %u, max %u(%u), depth %u(%u)",
486c349179bSTheodore Ts'o 			 (unsigned long long) pblk, error_msg,
487c349179bSTheodore Ts'o 			 le16_to_cpu(eh->eh_magic),
488c29c0ae7SAlex Tomas 			 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
489c29c0ae7SAlex Tomas 			 max, le16_to_cpu(eh->eh_depth), depth);
4906a797d27SDarrick J. Wong 	return err;
491c29c0ae7SAlex Tomas }
492c29c0ae7SAlex Tomas 
493c349179bSTheodore Ts'o #define ext4_ext_check(inode, eh, depth, pblk)			\
494c349179bSTheodore Ts'o 	__ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
495c29c0ae7SAlex Tomas 
4967a262f7cSAneesh Kumar K.V int ext4_ext_check_inode(struct inode *inode)
4977a262f7cSAneesh Kumar K.V {
498c349179bSTheodore Ts'o 	return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
4997a262f7cSAneesh Kumar K.V }
5007a262f7cSAneesh Kumar K.V 
5017d7ea89eSTheodore Ts'o static struct buffer_head *
5027d7ea89eSTheodore Ts'o __read_extent_tree_block(const char *function, unsigned int line,
503107a7bd3STheodore Ts'o 			 struct inode *inode, ext4_fsblk_t pblk, int depth,
504107a7bd3STheodore Ts'o 			 int flags)
505f8489128SDarrick J. Wong {
5067d7ea89eSTheodore Ts'o 	struct buffer_head		*bh;
5077d7ea89eSTheodore Ts'o 	int				err;
508f8489128SDarrick J. Wong 
509c45653c3SNikolay Borisov 	bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
5107d7ea89eSTheodore Ts'o 	if (unlikely(!bh))
5117d7ea89eSTheodore Ts'o 		return ERR_PTR(-ENOMEM);
5127d7ea89eSTheodore Ts'o 
5137d7ea89eSTheodore Ts'o 	if (!bh_uptodate_or_lock(bh)) {
5147d7ea89eSTheodore Ts'o 		trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
5157d7ea89eSTheodore Ts'o 		err = bh_submit_read(bh);
5167d7ea89eSTheodore Ts'o 		if (err < 0)
5177d7ea89eSTheodore Ts'o 			goto errout;
5187d7ea89eSTheodore Ts'o 	}
5197869a4a6STheodore Ts'o 	if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
5207d7ea89eSTheodore Ts'o 		return bh;
5210a944e8aSTheodore Ts'o 	if (!ext4_has_feature_journal(inode->i_sb) ||
5220a944e8aSTheodore Ts'o 	    (inode->i_ino !=
5230a944e8aSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum))) {
5247d7ea89eSTheodore Ts'o 		err = __ext4_ext_check(function, line, inode,
525c349179bSTheodore Ts'o 				       ext_block_hdr(bh), depth, pblk);
5267d7ea89eSTheodore Ts'o 		if (err)
5277d7ea89eSTheodore Ts'o 			goto errout;
5280a944e8aSTheodore Ts'o 	}
529f8489128SDarrick J. Wong 	set_buffer_verified(bh);
530107a7bd3STheodore Ts'o 	/*
531107a7bd3STheodore Ts'o 	 * If this is a leaf block, cache all of its entries
532107a7bd3STheodore Ts'o 	 */
533107a7bd3STheodore Ts'o 	if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
534107a7bd3STheodore Ts'o 		struct ext4_extent_header *eh = ext_block_hdr(bh);
535107a7bd3STheodore Ts'o 		struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
536107a7bd3STheodore Ts'o 		ext4_lblk_t prev = 0;
537107a7bd3STheodore Ts'o 		int i;
538107a7bd3STheodore Ts'o 
539107a7bd3STheodore Ts'o 		for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
540107a7bd3STheodore Ts'o 			unsigned int status = EXTENT_STATUS_WRITTEN;
541107a7bd3STheodore Ts'o 			ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
542107a7bd3STheodore Ts'o 			int len = ext4_ext_get_actual_len(ex);
543107a7bd3STheodore Ts'o 
544107a7bd3STheodore Ts'o 			if (prev && (prev != lblk))
545107a7bd3STheodore Ts'o 				ext4_es_cache_extent(inode, prev,
546107a7bd3STheodore Ts'o 						     lblk - prev, ~0,
547107a7bd3STheodore Ts'o 						     EXTENT_STATUS_HOLE);
548107a7bd3STheodore Ts'o 
549556615dcSLukas Czerner 			if (ext4_ext_is_unwritten(ex))
550107a7bd3STheodore Ts'o 				status = EXTENT_STATUS_UNWRITTEN;
551107a7bd3STheodore Ts'o 			ext4_es_cache_extent(inode, lblk, len,
552107a7bd3STheodore Ts'o 					     ext4_ext_pblock(ex), status);
553107a7bd3STheodore Ts'o 			prev = lblk + len;
554107a7bd3STheodore Ts'o 		}
555107a7bd3STheodore Ts'o 	}
5567d7ea89eSTheodore Ts'o 	return bh;
5577d7ea89eSTheodore Ts'o errout:
5587d7ea89eSTheodore Ts'o 	put_bh(bh);
5597d7ea89eSTheodore Ts'o 	return ERR_PTR(err);
5607d7ea89eSTheodore Ts'o 
561f8489128SDarrick J. Wong }
562f8489128SDarrick J. Wong 
563107a7bd3STheodore Ts'o #define read_extent_tree_block(inode, pblk, depth, flags)		\
564107a7bd3STheodore Ts'o 	__read_extent_tree_block(__func__, __LINE__, (inode), (pblk),   \
565107a7bd3STheodore Ts'o 				 (depth), (flags))
566f8489128SDarrick J. Wong 
5677869a4a6STheodore Ts'o /*
5687869a4a6STheodore Ts'o  * This function is called to cache a file's extent information in the
5697869a4a6STheodore Ts'o  * extent status tree
5707869a4a6STheodore Ts'o  */
5717869a4a6STheodore Ts'o int ext4_ext_precache(struct inode *inode)
5727869a4a6STheodore Ts'o {
5737869a4a6STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5747869a4a6STheodore Ts'o 	struct ext4_ext_path *path = NULL;
5757869a4a6STheodore Ts'o 	struct buffer_head *bh;
5767869a4a6STheodore Ts'o 	int i = 0, depth, ret = 0;
5777869a4a6STheodore Ts'o 
5787869a4a6STheodore Ts'o 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5797869a4a6STheodore Ts'o 		return 0;	/* not an extent-mapped inode */
5807869a4a6STheodore Ts'o 
5817869a4a6STheodore Ts'o 	down_read(&ei->i_data_sem);
5827869a4a6STheodore Ts'o 	depth = ext_depth(inode);
5837869a4a6STheodore Ts'o 
5846396bb22SKees Cook 	path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
5857869a4a6STheodore Ts'o 		       GFP_NOFS);
5867869a4a6STheodore Ts'o 	if (path == NULL) {
5877869a4a6STheodore Ts'o 		up_read(&ei->i_data_sem);
5887869a4a6STheodore Ts'o 		return -ENOMEM;
5897869a4a6STheodore Ts'o 	}
5907869a4a6STheodore Ts'o 
5917869a4a6STheodore Ts'o 	/* Don't cache anything if there are no external extent blocks */
5927869a4a6STheodore Ts'o 	if (depth == 0)
5937869a4a6STheodore Ts'o 		goto out;
5947869a4a6STheodore Ts'o 	path[0].p_hdr = ext_inode_hdr(inode);
5957869a4a6STheodore Ts'o 	ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
5967869a4a6STheodore Ts'o 	if (ret)
5977869a4a6STheodore Ts'o 		goto out;
5987869a4a6STheodore Ts'o 	path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
5997869a4a6STheodore Ts'o 	while (i >= 0) {
6007869a4a6STheodore Ts'o 		/*
6017869a4a6STheodore Ts'o 		 * If this is a leaf block or we've reached the end of
6027869a4a6STheodore Ts'o 		 * the index block, go up
6037869a4a6STheodore Ts'o 		 */
6047869a4a6STheodore Ts'o 		if ((i == depth) ||
6057869a4a6STheodore Ts'o 		    path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
6067869a4a6STheodore Ts'o 			brelse(path[i].p_bh);
6077869a4a6STheodore Ts'o 			path[i].p_bh = NULL;
6087869a4a6STheodore Ts'o 			i--;
6097869a4a6STheodore Ts'o 			continue;
6107869a4a6STheodore Ts'o 		}
6117869a4a6STheodore Ts'o 		bh = read_extent_tree_block(inode,
6127869a4a6STheodore Ts'o 					    ext4_idx_pblock(path[i].p_idx++),
6137869a4a6STheodore Ts'o 					    depth - i - 1,
6147869a4a6STheodore Ts'o 					    EXT4_EX_FORCE_CACHE);
6157869a4a6STheodore Ts'o 		if (IS_ERR(bh)) {
6167869a4a6STheodore Ts'o 			ret = PTR_ERR(bh);
6177869a4a6STheodore Ts'o 			break;
6187869a4a6STheodore Ts'o 		}
6197869a4a6STheodore Ts'o 		i++;
6207869a4a6STheodore Ts'o 		path[i].p_bh = bh;
6217869a4a6STheodore Ts'o 		path[i].p_hdr = ext_block_hdr(bh);
6227869a4a6STheodore Ts'o 		path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
6237869a4a6STheodore Ts'o 	}
6247869a4a6STheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
6257869a4a6STheodore Ts'o out:
6267869a4a6STheodore Ts'o 	up_read(&ei->i_data_sem);
6277869a4a6STheodore Ts'o 	ext4_ext_drop_refs(path);
6287869a4a6STheodore Ts'o 	kfree(path);
6297869a4a6STheodore Ts'o 	return ret;
6307869a4a6STheodore Ts'o }
6317869a4a6STheodore Ts'o 
632a86c6181SAlex Tomas #ifdef EXT_DEBUG
633a86c6181SAlex Tomas static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
634a86c6181SAlex Tomas {
635a86c6181SAlex Tomas 	int k, l = path->p_depth;
636a86c6181SAlex Tomas 
637a86c6181SAlex Tomas 	ext_debug("path:");
638a86c6181SAlex Tomas 	for (k = 0; k <= l; k++, path++) {
639a86c6181SAlex Tomas 		if (path->p_idx) {
6402ae02107SMingming Cao 		  ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
641bf89d16fSTheodore Ts'o 			    ext4_idx_pblock(path->p_idx));
642a86c6181SAlex Tomas 		} else if (path->p_ext) {
643553f9008SMingming 			ext_debug("  %d:[%d]%d:%llu ",
644a86c6181SAlex Tomas 				  le32_to_cpu(path->p_ext->ee_block),
645556615dcSLukas Czerner 				  ext4_ext_is_unwritten(path->p_ext),
646a2df2a63SAmit Arora 				  ext4_ext_get_actual_len(path->p_ext),
647bf89d16fSTheodore Ts'o 				  ext4_ext_pblock(path->p_ext));
648a86c6181SAlex Tomas 		} else
649a86c6181SAlex Tomas 			ext_debug("  []");
650a86c6181SAlex Tomas 	}
651a86c6181SAlex Tomas 	ext_debug("\n");
652a86c6181SAlex Tomas }
653a86c6181SAlex Tomas 
654a86c6181SAlex Tomas static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
655a86c6181SAlex Tomas {
656a86c6181SAlex Tomas 	int depth = ext_depth(inode);
657a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
658a86c6181SAlex Tomas 	struct ext4_extent *ex;
659a86c6181SAlex Tomas 	int i;
660a86c6181SAlex Tomas 
661a86c6181SAlex Tomas 	if (!path)
662a86c6181SAlex Tomas 		return;
663a86c6181SAlex Tomas 
664a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
665a86c6181SAlex Tomas 	ex = EXT_FIRST_EXTENT(eh);
666a86c6181SAlex Tomas 
667553f9008SMingming 	ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
668553f9008SMingming 
669a86c6181SAlex Tomas 	for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
670553f9008SMingming 		ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
671556615dcSLukas Czerner 			  ext4_ext_is_unwritten(ex),
672bf89d16fSTheodore Ts'o 			  ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
673a86c6181SAlex Tomas 	}
674a86c6181SAlex Tomas 	ext_debug("\n");
675a86c6181SAlex Tomas }
6761b16da77SYongqiang Yang 
6771b16da77SYongqiang Yang static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
6781b16da77SYongqiang Yang 			ext4_fsblk_t newblock, int level)
6791b16da77SYongqiang Yang {
6801b16da77SYongqiang Yang 	int depth = ext_depth(inode);
6811b16da77SYongqiang Yang 	struct ext4_extent *ex;
6821b16da77SYongqiang Yang 
6831b16da77SYongqiang Yang 	if (depth != level) {
6841b16da77SYongqiang Yang 		struct ext4_extent_idx *idx;
6851b16da77SYongqiang Yang 		idx = path[level].p_idx;
6861b16da77SYongqiang Yang 		while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
6871b16da77SYongqiang Yang 			ext_debug("%d: move %d:%llu in new index %llu\n", level,
6881b16da77SYongqiang Yang 					le32_to_cpu(idx->ei_block),
6891b16da77SYongqiang Yang 					ext4_idx_pblock(idx),
6901b16da77SYongqiang Yang 					newblock);
6911b16da77SYongqiang Yang 			idx++;
6921b16da77SYongqiang Yang 		}
6931b16da77SYongqiang Yang 
6941b16da77SYongqiang Yang 		return;
6951b16da77SYongqiang Yang 	}
6961b16da77SYongqiang Yang 
6971b16da77SYongqiang Yang 	ex = path[depth].p_ext;
6981b16da77SYongqiang Yang 	while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
6991b16da77SYongqiang Yang 		ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
7001b16da77SYongqiang Yang 				le32_to_cpu(ex->ee_block),
7011b16da77SYongqiang Yang 				ext4_ext_pblock(ex),
702556615dcSLukas Czerner 				ext4_ext_is_unwritten(ex),
7031b16da77SYongqiang Yang 				ext4_ext_get_actual_len(ex),
7041b16da77SYongqiang Yang 				newblock);
7051b16da77SYongqiang Yang 		ex++;
7061b16da77SYongqiang Yang 	}
7071b16da77SYongqiang Yang }
7081b16da77SYongqiang Yang 
709a86c6181SAlex Tomas #else
710a86c6181SAlex Tomas #define ext4_ext_show_path(inode, path)
711a86c6181SAlex Tomas #define ext4_ext_show_leaf(inode, path)
7121b16da77SYongqiang Yang #define ext4_ext_show_move(inode, path, newblock, level)
713a86c6181SAlex Tomas #endif
714a86c6181SAlex Tomas 
715b35905c1SAneesh Kumar K.V void ext4_ext_drop_refs(struct ext4_ext_path *path)
716a86c6181SAlex Tomas {
717b7ea89adSTheodore Ts'o 	int depth, i;
718a86c6181SAlex Tomas 
719b7ea89adSTheodore Ts'o 	if (!path)
720b7ea89adSTheodore Ts'o 		return;
721b7ea89adSTheodore Ts'o 	depth = path->p_depth;
722a86c6181SAlex Tomas 	for (i = 0; i <= depth; i++, path++)
723a86c6181SAlex Tomas 		if (path->p_bh) {
724a86c6181SAlex Tomas 			brelse(path->p_bh);
725a86c6181SAlex Tomas 			path->p_bh = NULL;
726a86c6181SAlex Tomas 		}
727a86c6181SAlex Tomas }
728a86c6181SAlex Tomas 
729a86c6181SAlex Tomas /*
730d0d856e8SRandy Dunlap  * ext4_ext_binsearch_idx:
731d0d856e8SRandy Dunlap  * binary search for the closest index of the given block
732c29c0ae7SAlex Tomas  * the header must be checked before calling this
733a86c6181SAlex Tomas  */
734a86c6181SAlex Tomas static void
735725d26d3SAneesh Kumar K.V ext4_ext_binsearch_idx(struct inode *inode,
736725d26d3SAneesh Kumar K.V 			struct ext4_ext_path *path, ext4_lblk_t block)
737a86c6181SAlex Tomas {
738a86c6181SAlex Tomas 	struct ext4_extent_header *eh = path->p_hdr;
739a86c6181SAlex Tomas 	struct ext4_extent_idx *r, *l, *m;
740a86c6181SAlex Tomas 
741a86c6181SAlex Tomas 
742bba90743SEric Sandeen 	ext_debug("binsearch for %u(idx):  ", block);
743a86c6181SAlex Tomas 
744a86c6181SAlex Tomas 	l = EXT_FIRST_INDEX(eh) + 1;
745e9f410b1SDmitry Monakhov 	r = EXT_LAST_INDEX(eh);
746a86c6181SAlex Tomas 	while (l <= r) {
747a86c6181SAlex Tomas 		m = l + (r - l) / 2;
748a86c6181SAlex Tomas 		if (block < le32_to_cpu(m->ei_block))
749a86c6181SAlex Tomas 			r = m - 1;
750a86c6181SAlex Tomas 		else
751a86c6181SAlex Tomas 			l = m + 1;
75226d535edSDmitry Monakhov 		ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
75326d535edSDmitry Monakhov 				m, le32_to_cpu(m->ei_block),
75426d535edSDmitry Monakhov 				r, le32_to_cpu(r->ei_block));
755a86c6181SAlex Tomas 	}
756a86c6181SAlex Tomas 
757a86c6181SAlex Tomas 	path->p_idx = l - 1;
7584a3c3a51SZheng Liu 	ext_debug("  -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
759bf89d16fSTheodore Ts'o 		  ext4_idx_pblock(path->p_idx));
760a86c6181SAlex Tomas 
761a86c6181SAlex Tomas #ifdef CHECK_BINSEARCH
762a86c6181SAlex Tomas 	{
763a86c6181SAlex Tomas 		struct ext4_extent_idx *chix, *ix;
764a86c6181SAlex Tomas 		int k;
765a86c6181SAlex Tomas 
766a86c6181SAlex Tomas 		chix = ix = EXT_FIRST_INDEX(eh);
767a86c6181SAlex Tomas 		for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
768a86c6181SAlex Tomas 		  if (k != 0 &&
769a86c6181SAlex Tomas 		      le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
7704776004fSTheodore Ts'o 				printk(KERN_DEBUG "k=%d, ix=0x%p, "
7714776004fSTheodore Ts'o 				       "first=0x%p\n", k,
772a86c6181SAlex Tomas 				       ix, EXT_FIRST_INDEX(eh));
7734776004fSTheodore Ts'o 				printk(KERN_DEBUG "%u <= %u\n",
774a86c6181SAlex Tomas 				       le32_to_cpu(ix->ei_block),
775a86c6181SAlex Tomas 				       le32_to_cpu(ix[-1].ei_block));
776a86c6181SAlex Tomas 			}
777a86c6181SAlex Tomas 			BUG_ON(k && le32_to_cpu(ix->ei_block)
778a86c6181SAlex Tomas 					   <= le32_to_cpu(ix[-1].ei_block));
779a86c6181SAlex Tomas 			if (block < le32_to_cpu(ix->ei_block))
780a86c6181SAlex Tomas 				break;
781a86c6181SAlex Tomas 			chix = ix;
782a86c6181SAlex Tomas 		}
783a86c6181SAlex Tomas 		BUG_ON(chix != path->p_idx);
784a86c6181SAlex Tomas 	}
785a86c6181SAlex Tomas #endif
786a86c6181SAlex Tomas 
787a86c6181SAlex Tomas }
788a86c6181SAlex Tomas 
789a86c6181SAlex Tomas /*
790d0d856e8SRandy Dunlap  * ext4_ext_binsearch:
791d0d856e8SRandy Dunlap  * binary search for closest extent of the given block
792c29c0ae7SAlex Tomas  * the header must be checked before calling this
793a86c6181SAlex Tomas  */
794a86c6181SAlex Tomas static void
795725d26d3SAneesh Kumar K.V ext4_ext_binsearch(struct inode *inode,
796725d26d3SAneesh Kumar K.V 		struct ext4_ext_path *path, ext4_lblk_t block)
797a86c6181SAlex Tomas {
798a86c6181SAlex Tomas 	struct ext4_extent_header *eh = path->p_hdr;
799a86c6181SAlex Tomas 	struct ext4_extent *r, *l, *m;
800a86c6181SAlex Tomas 
801a86c6181SAlex Tomas 	if (eh->eh_entries == 0) {
802a86c6181SAlex Tomas 		/*
803d0d856e8SRandy Dunlap 		 * this leaf is empty:
804a86c6181SAlex Tomas 		 * we get such a leaf in split/add case
805a86c6181SAlex Tomas 		 */
806a86c6181SAlex Tomas 		return;
807a86c6181SAlex Tomas 	}
808a86c6181SAlex Tomas 
809bba90743SEric Sandeen 	ext_debug("binsearch for %u:  ", block);
810a86c6181SAlex Tomas 
811a86c6181SAlex Tomas 	l = EXT_FIRST_EXTENT(eh) + 1;
812e9f410b1SDmitry Monakhov 	r = EXT_LAST_EXTENT(eh);
813a86c6181SAlex Tomas 
814a86c6181SAlex Tomas 	while (l <= r) {
815a86c6181SAlex Tomas 		m = l + (r - l) / 2;
816a86c6181SAlex Tomas 		if (block < le32_to_cpu(m->ee_block))
817a86c6181SAlex Tomas 			r = m - 1;
818a86c6181SAlex Tomas 		else
819a86c6181SAlex Tomas 			l = m + 1;
82026d535edSDmitry Monakhov 		ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
82126d535edSDmitry Monakhov 				m, le32_to_cpu(m->ee_block),
82226d535edSDmitry Monakhov 				r, le32_to_cpu(r->ee_block));
823a86c6181SAlex Tomas 	}
824a86c6181SAlex Tomas 
825a86c6181SAlex Tomas 	path->p_ext = l - 1;
826553f9008SMingming 	ext_debug("  -> %d:%llu:[%d]%d ",
827a86c6181SAlex Tomas 			le32_to_cpu(path->p_ext->ee_block),
828bf89d16fSTheodore Ts'o 			ext4_ext_pblock(path->p_ext),
829556615dcSLukas Czerner 			ext4_ext_is_unwritten(path->p_ext),
830a2df2a63SAmit Arora 			ext4_ext_get_actual_len(path->p_ext));
831a86c6181SAlex Tomas 
832a86c6181SAlex Tomas #ifdef CHECK_BINSEARCH
833a86c6181SAlex Tomas 	{
834a86c6181SAlex Tomas 		struct ext4_extent *chex, *ex;
835a86c6181SAlex Tomas 		int k;
836a86c6181SAlex Tomas 
837a86c6181SAlex Tomas 		chex = ex = EXT_FIRST_EXTENT(eh);
838a86c6181SAlex Tomas 		for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
839a86c6181SAlex Tomas 			BUG_ON(k && le32_to_cpu(ex->ee_block)
840a86c6181SAlex Tomas 					  <= le32_to_cpu(ex[-1].ee_block));
841a86c6181SAlex Tomas 			if (block < le32_to_cpu(ex->ee_block))
842a86c6181SAlex Tomas 				break;
843a86c6181SAlex Tomas 			chex = ex;
844a86c6181SAlex Tomas 		}
845a86c6181SAlex Tomas 		BUG_ON(chex != path->p_ext);
846a86c6181SAlex Tomas 	}
847a86c6181SAlex Tomas #endif
848a86c6181SAlex Tomas 
849a86c6181SAlex Tomas }
850a86c6181SAlex Tomas 
851a86c6181SAlex Tomas int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
852a86c6181SAlex Tomas {
853a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
854a86c6181SAlex Tomas 
855a86c6181SAlex Tomas 	eh = ext_inode_hdr(inode);
856a86c6181SAlex Tomas 	eh->eh_depth = 0;
857a86c6181SAlex Tomas 	eh->eh_entries = 0;
858a86c6181SAlex Tomas 	eh->eh_magic = EXT4_EXT_MAGIC;
85955ad63bfSTheodore Ts'o 	eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
860a86c6181SAlex Tomas 	ext4_mark_inode_dirty(handle, inode);
861a86c6181SAlex Tomas 	return 0;
862a86c6181SAlex Tomas }
863a86c6181SAlex Tomas 
864a86c6181SAlex Tomas struct ext4_ext_path *
865ed8a1a76STheodore Ts'o ext4_find_extent(struct inode *inode, ext4_lblk_t block,
866705912caSTheodore Ts'o 		 struct ext4_ext_path **orig_path, int flags)
867a86c6181SAlex Tomas {
868a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
869a86c6181SAlex Tomas 	struct buffer_head *bh;
870705912caSTheodore Ts'o 	struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
871705912caSTheodore Ts'o 	short int depth, i, ppos = 0;
872860d21e2STheodore Ts'o 	int ret;
873a86c6181SAlex Tomas 
874a86c6181SAlex Tomas 	eh = ext_inode_hdr(inode);
875c29c0ae7SAlex Tomas 	depth = ext_depth(inode);
876bc890a60STheodore Ts'o 	if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
877bc890a60STheodore Ts'o 		EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
878bc890a60STheodore Ts'o 				 depth);
879bc890a60STheodore Ts'o 		ret = -EFSCORRUPTED;
880bc890a60STheodore Ts'o 		goto err;
881bc890a60STheodore Ts'o 	}
882a86c6181SAlex Tomas 
88310809df8STheodore Ts'o 	if (path) {
884523f431cSTheodore Ts'o 		ext4_ext_drop_refs(path);
88510809df8STheodore Ts'o 		if (depth > path[0].p_maxdepth) {
88610809df8STheodore Ts'o 			kfree(path);
88710809df8STheodore Ts'o 			*orig_path = path = NULL;
88810809df8STheodore Ts'o 		}
88910809df8STheodore Ts'o 	}
89010809df8STheodore Ts'o 	if (!path) {
891a86c6181SAlex Tomas 		/* account possible depth increase */
8926396bb22SKees Cook 		path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
893a86c6181SAlex Tomas 				GFP_NOFS);
89419008f6dSTheodore Ts'o 		if (unlikely(!path))
895a86c6181SAlex Tomas 			return ERR_PTR(-ENOMEM);
89610809df8STheodore Ts'o 		path[0].p_maxdepth = depth + 1;
897a86c6181SAlex Tomas 	}
898a86c6181SAlex Tomas 	path[0].p_hdr = eh;
8991973adcbSShen Feng 	path[0].p_bh = NULL;
900a86c6181SAlex Tomas 
901c29c0ae7SAlex Tomas 	i = depth;
902a86c6181SAlex Tomas 	/* walk through the tree */
903a86c6181SAlex Tomas 	while (i) {
904a86c6181SAlex Tomas 		ext_debug("depth %d: num %d, max %d\n",
905a86c6181SAlex Tomas 			  ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
906c29c0ae7SAlex Tomas 
907a86c6181SAlex Tomas 		ext4_ext_binsearch_idx(inode, path + ppos, block);
908bf89d16fSTheodore Ts'o 		path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
909a86c6181SAlex Tomas 		path[ppos].p_depth = i;
910a86c6181SAlex Tomas 		path[ppos].p_ext = NULL;
911a86c6181SAlex Tomas 
912107a7bd3STheodore Ts'o 		bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
913107a7bd3STheodore Ts'o 					    flags);
914a1c83681SViresh Kumar 		if (IS_ERR(bh)) {
9157d7ea89eSTheodore Ts'o 			ret = PTR_ERR(bh);
916a86c6181SAlex Tomas 			goto err;
917860d21e2STheodore Ts'o 		}
9187d7ea89eSTheodore Ts'o 
919a86c6181SAlex Tomas 		eh = ext_block_hdr(bh);
920a86c6181SAlex Tomas 		ppos++;
921a86c6181SAlex Tomas 		path[ppos].p_bh = bh;
922a86c6181SAlex Tomas 		path[ppos].p_hdr = eh;
923a86c6181SAlex Tomas 	}
924a86c6181SAlex Tomas 
925a86c6181SAlex Tomas 	path[ppos].p_depth = i;
926a86c6181SAlex Tomas 	path[ppos].p_ext = NULL;
927a86c6181SAlex Tomas 	path[ppos].p_idx = NULL;
928a86c6181SAlex Tomas 
929a86c6181SAlex Tomas 	/* find extent */
930a86c6181SAlex Tomas 	ext4_ext_binsearch(inode, path + ppos, block);
9311973adcbSShen Feng 	/* if not an empty leaf */
9321973adcbSShen Feng 	if (path[ppos].p_ext)
933bf89d16fSTheodore Ts'o 		path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
934a86c6181SAlex Tomas 
935a86c6181SAlex Tomas 	ext4_ext_show_path(inode, path);
936a86c6181SAlex Tomas 
937a86c6181SAlex Tomas 	return path;
938a86c6181SAlex Tomas 
939a86c6181SAlex Tomas err:
940a86c6181SAlex Tomas 	ext4_ext_drop_refs(path);
941a86c6181SAlex Tomas 	kfree(path);
942705912caSTheodore Ts'o 	if (orig_path)
943705912caSTheodore Ts'o 		*orig_path = NULL;
944860d21e2STheodore Ts'o 	return ERR_PTR(ret);
945a86c6181SAlex Tomas }
946a86c6181SAlex Tomas 
947a86c6181SAlex Tomas /*
948d0d856e8SRandy Dunlap  * ext4_ext_insert_index:
949d0d856e8SRandy Dunlap  * insert new index [@logical;@ptr] into the block at @curp;
950d0d856e8SRandy Dunlap  * check where to insert: before @curp or after @curp
951a86c6181SAlex Tomas  */
9521f109d5aSTheodore Ts'o static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
953a86c6181SAlex Tomas 				 struct ext4_ext_path *curp,
954f65e6fbaSAlex Tomas 				 int logical, ext4_fsblk_t ptr)
955a86c6181SAlex Tomas {
956a86c6181SAlex Tomas 	struct ext4_extent_idx *ix;
957a86c6181SAlex Tomas 	int len, err;
958a86c6181SAlex Tomas 
9597e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, curp);
9607e028976SAvantika Mathur 	if (err)
961a86c6181SAlex Tomas 		return err;
962a86c6181SAlex Tomas 
963273df556SFrank Mayhar 	if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
964273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
965273df556SFrank Mayhar 				 "logical %d == ei_block %d!",
966273df556SFrank Mayhar 				 logical, le32_to_cpu(curp->p_idx->ei_block));
9676a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
968273df556SFrank Mayhar 	}
969d4620315SRobin Dong 
970d4620315SRobin Dong 	if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
971d4620315SRobin Dong 			     >= le16_to_cpu(curp->p_hdr->eh_max))) {
972d4620315SRobin Dong 		EXT4_ERROR_INODE(inode,
973d4620315SRobin Dong 				 "eh_entries %d >= eh_max %d!",
974d4620315SRobin Dong 				 le16_to_cpu(curp->p_hdr->eh_entries),
975d4620315SRobin Dong 				 le16_to_cpu(curp->p_hdr->eh_max));
9766a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
977d4620315SRobin Dong 	}
978d4620315SRobin Dong 
979a86c6181SAlex Tomas 	if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
980a86c6181SAlex Tomas 		/* insert after */
98180e675f9SEric Gouriou 		ext_debug("insert new index %d after: %llu\n", logical, ptr);
982a86c6181SAlex Tomas 		ix = curp->p_idx + 1;
983a86c6181SAlex Tomas 	} else {
984a86c6181SAlex Tomas 		/* insert before */
98580e675f9SEric Gouriou 		ext_debug("insert new index %d before: %llu\n", logical, ptr);
986a86c6181SAlex Tomas 		ix = curp->p_idx;
987a86c6181SAlex Tomas 	}
988a86c6181SAlex Tomas 
98980e675f9SEric Gouriou 	len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
99080e675f9SEric Gouriou 	BUG_ON(len < 0);
99180e675f9SEric Gouriou 	if (len > 0) {
99280e675f9SEric Gouriou 		ext_debug("insert new index %d: "
99380e675f9SEric Gouriou 				"move %d indices from 0x%p to 0x%p\n",
99480e675f9SEric Gouriou 				logical, len, ix, ix + 1);
99580e675f9SEric Gouriou 		memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
99680e675f9SEric Gouriou 	}
99780e675f9SEric Gouriou 
998f472e026STao Ma 	if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
999f472e026STao Ma 		EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
10006a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1001f472e026STao Ma 	}
1002f472e026STao Ma 
1003a86c6181SAlex Tomas 	ix->ei_block = cpu_to_le32(logical);
1004f65e6fbaSAlex Tomas 	ext4_idx_store_pblock(ix, ptr);
1005e8546d06SMarcin Slusarz 	le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1006a86c6181SAlex Tomas 
1007273df556SFrank Mayhar 	if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1008273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
10096a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1010273df556SFrank Mayhar 	}
1011a86c6181SAlex Tomas 
1012a86c6181SAlex Tomas 	err = ext4_ext_dirty(handle, inode, curp);
1013a86c6181SAlex Tomas 	ext4_std_error(inode->i_sb, err);
1014a86c6181SAlex Tomas 
1015a86c6181SAlex Tomas 	return err;
1016a86c6181SAlex Tomas }
1017a86c6181SAlex Tomas 
1018a86c6181SAlex Tomas /*
1019d0d856e8SRandy Dunlap  * ext4_ext_split:
1020d0d856e8SRandy Dunlap  * inserts new subtree into the path, using free index entry
1021d0d856e8SRandy Dunlap  * at depth @at:
1022a86c6181SAlex Tomas  * - allocates all needed blocks (new leaf and all intermediate index blocks)
1023a86c6181SAlex Tomas  * - makes decision where to split
1024d0d856e8SRandy Dunlap  * - moves remaining extents and index entries (right to the split point)
1025a86c6181SAlex Tomas  *   into the newly allocated blocks
1026d0d856e8SRandy Dunlap  * - initializes subtree
1027a86c6181SAlex Tomas  */
1028a86c6181SAlex Tomas static int ext4_ext_split(handle_t *handle, struct inode *inode,
102955f020dbSAllison Henderson 			  unsigned int flags,
1030a86c6181SAlex Tomas 			  struct ext4_ext_path *path,
1031a86c6181SAlex Tomas 			  struct ext4_extent *newext, int at)
1032a86c6181SAlex Tomas {
1033a86c6181SAlex Tomas 	struct buffer_head *bh = NULL;
1034a86c6181SAlex Tomas 	int depth = ext_depth(inode);
1035a86c6181SAlex Tomas 	struct ext4_extent_header *neh;
1036a86c6181SAlex Tomas 	struct ext4_extent_idx *fidx;
1037a86c6181SAlex Tomas 	int i = at, k, m, a;
1038f65e6fbaSAlex Tomas 	ext4_fsblk_t newblock, oldblock;
1039a86c6181SAlex Tomas 	__le32 border;
1040f65e6fbaSAlex Tomas 	ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1041a86c6181SAlex Tomas 	int err = 0;
1042592acbf1SSriram Rajagopalan 	size_t ext_size = 0;
1043a86c6181SAlex Tomas 
1044a86c6181SAlex Tomas 	/* make decision: where to split? */
1045d0d856e8SRandy Dunlap 	/* FIXME: now decision is simplest: at current extent */
1046a86c6181SAlex Tomas 
1047d0d856e8SRandy Dunlap 	/* if current leaf will be split, then we should use
1048a86c6181SAlex Tomas 	 * border from split point */
1049273df556SFrank Mayhar 	if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1050273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
10516a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1052273df556SFrank Mayhar 	}
1053a86c6181SAlex Tomas 	if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1054a86c6181SAlex Tomas 		border = path[depth].p_ext[1].ee_block;
1055d0d856e8SRandy Dunlap 		ext_debug("leaf will be split."
1056a86c6181SAlex Tomas 				" next leaf starts at %d\n",
1057a86c6181SAlex Tomas 				  le32_to_cpu(border));
1058a86c6181SAlex Tomas 	} else {
1059a86c6181SAlex Tomas 		border = newext->ee_block;
1060a86c6181SAlex Tomas 		ext_debug("leaf will be added."
1061a86c6181SAlex Tomas 				" next leaf starts at %d\n",
1062a86c6181SAlex Tomas 				le32_to_cpu(border));
1063a86c6181SAlex Tomas 	}
1064a86c6181SAlex Tomas 
1065a86c6181SAlex Tomas 	/*
1066d0d856e8SRandy Dunlap 	 * If error occurs, then we break processing
1067d0d856e8SRandy Dunlap 	 * and mark filesystem read-only. index won't
1068a86c6181SAlex Tomas 	 * be inserted and tree will be in consistent
1069d0d856e8SRandy Dunlap 	 * state. Next mount will repair buffers too.
1070a86c6181SAlex Tomas 	 */
1071a86c6181SAlex Tomas 
1072a86c6181SAlex Tomas 	/*
1073d0d856e8SRandy Dunlap 	 * Get array to track all allocated blocks.
1074d0d856e8SRandy Dunlap 	 * We need this to handle errors and free blocks
1075d0d856e8SRandy Dunlap 	 * upon them.
1076a86c6181SAlex Tomas 	 */
10776396bb22SKees Cook 	ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), GFP_NOFS);
1078a86c6181SAlex Tomas 	if (!ablocks)
1079a86c6181SAlex Tomas 		return -ENOMEM;
1080a86c6181SAlex Tomas 
1081a86c6181SAlex Tomas 	/* allocate all needed blocks */
1082a86c6181SAlex Tomas 	ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1083a86c6181SAlex Tomas 	for (a = 0; a < depth - at; a++) {
1084654b4908SAneesh Kumar K.V 		newblock = ext4_ext_new_meta_block(handle, inode, path,
108555f020dbSAllison Henderson 						   newext, &err, flags);
1086a86c6181SAlex Tomas 		if (newblock == 0)
1087a86c6181SAlex Tomas 			goto cleanup;
1088a86c6181SAlex Tomas 		ablocks[a] = newblock;
1089a86c6181SAlex Tomas 	}
1090a86c6181SAlex Tomas 
1091a86c6181SAlex Tomas 	/* initialize new leaf */
1092a86c6181SAlex Tomas 	newblock = ablocks[--a];
1093273df556SFrank Mayhar 	if (unlikely(newblock == 0)) {
1094273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "newblock == 0!");
10956a797d27SDarrick J. Wong 		err = -EFSCORRUPTED;
1096273df556SFrank Mayhar 		goto cleanup;
1097273df556SFrank Mayhar 	}
1098c45653c3SNikolay Borisov 	bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1099aebf0243SWang Shilong 	if (unlikely(!bh)) {
1100860d21e2STheodore Ts'o 		err = -ENOMEM;
1101a86c6181SAlex Tomas 		goto cleanup;
1102a86c6181SAlex Tomas 	}
1103a86c6181SAlex Tomas 	lock_buffer(bh);
1104a86c6181SAlex Tomas 
11057e028976SAvantika Mathur 	err = ext4_journal_get_create_access(handle, bh);
11067e028976SAvantika Mathur 	if (err)
1107a86c6181SAlex Tomas 		goto cleanup;
1108a86c6181SAlex Tomas 
1109a86c6181SAlex Tomas 	neh = ext_block_hdr(bh);
1110a86c6181SAlex Tomas 	neh->eh_entries = 0;
111155ad63bfSTheodore Ts'o 	neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1112a86c6181SAlex Tomas 	neh->eh_magic = EXT4_EXT_MAGIC;
1113a86c6181SAlex Tomas 	neh->eh_depth = 0;
1114a86c6181SAlex Tomas 
1115d0d856e8SRandy Dunlap 	/* move remainder of path[depth] to the new leaf */
1116273df556SFrank Mayhar 	if (unlikely(path[depth].p_hdr->eh_entries !=
1117273df556SFrank Mayhar 		     path[depth].p_hdr->eh_max)) {
1118273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1119273df556SFrank Mayhar 				 path[depth].p_hdr->eh_entries,
1120273df556SFrank Mayhar 				 path[depth].p_hdr->eh_max);
11216a797d27SDarrick J. Wong 		err = -EFSCORRUPTED;
1122273df556SFrank Mayhar 		goto cleanup;
1123273df556SFrank Mayhar 	}
1124a86c6181SAlex Tomas 	/* start copy from next extent */
11251b16da77SYongqiang Yang 	m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
11261b16da77SYongqiang Yang 	ext4_ext_show_move(inode, path, newblock, depth);
1127a86c6181SAlex Tomas 	if (m) {
11281b16da77SYongqiang Yang 		struct ext4_extent *ex;
11291b16da77SYongqiang Yang 		ex = EXT_FIRST_EXTENT(neh);
11301b16da77SYongqiang Yang 		memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1131e8546d06SMarcin Slusarz 		le16_add_cpu(&neh->eh_entries, m);
1132a86c6181SAlex Tomas 	}
1133a86c6181SAlex Tomas 
1134592acbf1SSriram Rajagopalan 	/* zero out unused area in the extent block */
1135592acbf1SSriram Rajagopalan 	ext_size = sizeof(struct ext4_extent_header) +
1136592acbf1SSriram Rajagopalan 		sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1137592acbf1SSriram Rajagopalan 	memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
11387ac5990dSDarrick J. Wong 	ext4_extent_block_csum_set(inode, neh);
1139a86c6181SAlex Tomas 	set_buffer_uptodate(bh);
1140a86c6181SAlex Tomas 	unlock_buffer(bh);
1141a86c6181SAlex Tomas 
11420390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, inode, bh);
11437e028976SAvantika Mathur 	if (err)
1144a86c6181SAlex Tomas 		goto cleanup;
1145a86c6181SAlex Tomas 	brelse(bh);
1146a86c6181SAlex Tomas 	bh = NULL;
1147a86c6181SAlex Tomas 
1148a86c6181SAlex Tomas 	/* correct old leaf */
1149a86c6181SAlex Tomas 	if (m) {
11507e028976SAvantika Mathur 		err = ext4_ext_get_access(handle, inode, path + depth);
11517e028976SAvantika Mathur 		if (err)
1152a86c6181SAlex Tomas 			goto cleanup;
1153e8546d06SMarcin Slusarz 		le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
11547e028976SAvantika Mathur 		err = ext4_ext_dirty(handle, inode, path + depth);
11557e028976SAvantika Mathur 		if (err)
1156a86c6181SAlex Tomas 			goto cleanup;
1157a86c6181SAlex Tomas 
1158a86c6181SAlex Tomas 	}
1159a86c6181SAlex Tomas 
1160a86c6181SAlex Tomas 	/* create intermediate indexes */
1161a86c6181SAlex Tomas 	k = depth - at - 1;
1162273df556SFrank Mayhar 	if (unlikely(k < 0)) {
1163273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "k %d < 0!", k);
11646a797d27SDarrick J. Wong 		err = -EFSCORRUPTED;
1165273df556SFrank Mayhar 		goto cleanup;
1166273df556SFrank Mayhar 	}
1167a86c6181SAlex Tomas 	if (k)
1168a86c6181SAlex Tomas 		ext_debug("create %d intermediate indices\n", k);
1169a86c6181SAlex Tomas 	/* insert new index into current index block */
1170a86c6181SAlex Tomas 	/* current depth stored in i var */
1171a86c6181SAlex Tomas 	i = depth - 1;
1172a86c6181SAlex Tomas 	while (k--) {
1173a86c6181SAlex Tomas 		oldblock = newblock;
1174a86c6181SAlex Tomas 		newblock = ablocks[--a];
1175bba90743SEric Sandeen 		bh = sb_getblk(inode->i_sb, newblock);
1176aebf0243SWang Shilong 		if (unlikely(!bh)) {
1177860d21e2STheodore Ts'o 			err = -ENOMEM;
1178a86c6181SAlex Tomas 			goto cleanup;
1179a86c6181SAlex Tomas 		}
1180a86c6181SAlex Tomas 		lock_buffer(bh);
1181a86c6181SAlex Tomas 
11827e028976SAvantika Mathur 		err = ext4_journal_get_create_access(handle, bh);
11837e028976SAvantika Mathur 		if (err)
1184a86c6181SAlex Tomas 			goto cleanup;
1185a86c6181SAlex Tomas 
1186a86c6181SAlex Tomas 		neh = ext_block_hdr(bh);
1187a86c6181SAlex Tomas 		neh->eh_entries = cpu_to_le16(1);
1188a86c6181SAlex Tomas 		neh->eh_magic = EXT4_EXT_MAGIC;
118955ad63bfSTheodore Ts'o 		neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1190a86c6181SAlex Tomas 		neh->eh_depth = cpu_to_le16(depth - i);
1191a86c6181SAlex Tomas 		fidx = EXT_FIRST_INDEX(neh);
1192a86c6181SAlex Tomas 		fidx->ei_block = border;
1193f65e6fbaSAlex Tomas 		ext4_idx_store_pblock(fidx, oldblock);
1194a86c6181SAlex Tomas 
1195bba90743SEric Sandeen 		ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1196bba90743SEric Sandeen 				i, newblock, le32_to_cpu(border), oldblock);
1197a86c6181SAlex Tomas 
11981b16da77SYongqiang Yang 		/* move remainder of path[i] to the new index block */
1199273df556SFrank Mayhar 		if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1200273df556SFrank Mayhar 					EXT_LAST_INDEX(path[i].p_hdr))) {
1201273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
1202273df556SFrank Mayhar 					 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1203273df556SFrank Mayhar 					 le32_to_cpu(path[i].p_ext->ee_block));
12046a797d27SDarrick J. Wong 			err = -EFSCORRUPTED;
1205273df556SFrank Mayhar 			goto cleanup;
1206273df556SFrank Mayhar 		}
12071b16da77SYongqiang Yang 		/* start copy indexes */
12081b16da77SYongqiang Yang 		m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
12091b16da77SYongqiang Yang 		ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
12101b16da77SYongqiang Yang 				EXT_MAX_INDEX(path[i].p_hdr));
12111b16da77SYongqiang Yang 		ext4_ext_show_move(inode, path, newblock, i);
1212a86c6181SAlex Tomas 		if (m) {
12131b16da77SYongqiang Yang 			memmove(++fidx, path[i].p_idx,
1214a86c6181SAlex Tomas 				sizeof(struct ext4_extent_idx) * m);
1215e8546d06SMarcin Slusarz 			le16_add_cpu(&neh->eh_entries, m);
1216a86c6181SAlex Tomas 		}
1217592acbf1SSriram Rajagopalan 		/* zero out unused area in the extent block */
1218592acbf1SSriram Rajagopalan 		ext_size = sizeof(struct ext4_extent_header) +
1219592acbf1SSriram Rajagopalan 		   (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1220592acbf1SSriram Rajagopalan 		memset(bh->b_data + ext_size, 0,
1221592acbf1SSriram Rajagopalan 			inode->i_sb->s_blocksize - ext_size);
12227ac5990dSDarrick J. Wong 		ext4_extent_block_csum_set(inode, neh);
1223a86c6181SAlex Tomas 		set_buffer_uptodate(bh);
1224a86c6181SAlex Tomas 		unlock_buffer(bh);
1225a86c6181SAlex Tomas 
12260390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
12277e028976SAvantika Mathur 		if (err)
1228a86c6181SAlex Tomas 			goto cleanup;
1229a86c6181SAlex Tomas 		brelse(bh);
1230a86c6181SAlex Tomas 		bh = NULL;
1231a86c6181SAlex Tomas 
1232a86c6181SAlex Tomas 		/* correct old index */
1233a86c6181SAlex Tomas 		if (m) {
1234a86c6181SAlex Tomas 			err = ext4_ext_get_access(handle, inode, path + i);
1235a86c6181SAlex Tomas 			if (err)
1236a86c6181SAlex Tomas 				goto cleanup;
1237e8546d06SMarcin Slusarz 			le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1238a86c6181SAlex Tomas 			err = ext4_ext_dirty(handle, inode, path + i);
1239a86c6181SAlex Tomas 			if (err)
1240a86c6181SAlex Tomas 				goto cleanup;
1241a86c6181SAlex Tomas 		}
1242a86c6181SAlex Tomas 
1243a86c6181SAlex Tomas 		i--;
1244a86c6181SAlex Tomas 	}
1245a86c6181SAlex Tomas 
1246a86c6181SAlex Tomas 	/* insert new index */
1247a86c6181SAlex Tomas 	err = ext4_ext_insert_index(handle, inode, path + at,
1248a86c6181SAlex Tomas 				    le32_to_cpu(border), newblock);
1249a86c6181SAlex Tomas 
1250a86c6181SAlex Tomas cleanup:
1251a86c6181SAlex Tomas 	if (bh) {
1252a86c6181SAlex Tomas 		if (buffer_locked(bh))
1253a86c6181SAlex Tomas 			unlock_buffer(bh);
1254a86c6181SAlex Tomas 		brelse(bh);
1255a86c6181SAlex Tomas 	}
1256a86c6181SAlex Tomas 
1257a86c6181SAlex Tomas 	if (err) {
1258a86c6181SAlex Tomas 		/* free all allocated blocks in error case */
1259a86c6181SAlex Tomas 		for (i = 0; i < depth; i++) {
1260a86c6181SAlex Tomas 			if (!ablocks[i])
1261a86c6181SAlex Tomas 				continue;
12627dc57615SPeter Huewe 			ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1263e6362609STheodore Ts'o 					 EXT4_FREE_BLOCKS_METADATA);
1264a86c6181SAlex Tomas 		}
1265a86c6181SAlex Tomas 	}
1266a86c6181SAlex Tomas 	kfree(ablocks);
1267a86c6181SAlex Tomas 
1268a86c6181SAlex Tomas 	return err;
1269a86c6181SAlex Tomas }
1270a86c6181SAlex Tomas 
1271a86c6181SAlex Tomas /*
1272d0d856e8SRandy Dunlap  * ext4_ext_grow_indepth:
1273d0d856e8SRandy Dunlap  * implements tree growing procedure:
1274a86c6181SAlex Tomas  * - allocates new block
1275a86c6181SAlex Tomas  * - moves top-level data (index block or leaf) into the new block
1276d0d856e8SRandy Dunlap  * - initializes new top-level, creating index that points to the
1277a86c6181SAlex Tomas  *   just created block
1278a86c6181SAlex Tomas  */
1279a86c6181SAlex Tomas static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1280be5cd90dSDmitry Monakhov 				 unsigned int flags)
1281a86c6181SAlex Tomas {
1282a86c6181SAlex Tomas 	struct ext4_extent_header *neh;
1283a86c6181SAlex Tomas 	struct buffer_head *bh;
1284be5cd90dSDmitry Monakhov 	ext4_fsblk_t newblock, goal = 0;
1285be5cd90dSDmitry Monakhov 	struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1286a86c6181SAlex Tomas 	int err = 0;
1287592acbf1SSriram Rajagopalan 	size_t ext_size = 0;
1288a86c6181SAlex Tomas 
1289be5cd90dSDmitry Monakhov 	/* Try to prepend new index to old one */
1290be5cd90dSDmitry Monakhov 	if (ext_depth(inode))
1291be5cd90dSDmitry Monakhov 		goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1292be5cd90dSDmitry Monakhov 	if (goal > le32_to_cpu(es->s_first_data_block)) {
1293be5cd90dSDmitry Monakhov 		flags |= EXT4_MB_HINT_TRY_GOAL;
1294be5cd90dSDmitry Monakhov 		goal--;
1295be5cd90dSDmitry Monakhov 	} else
1296be5cd90dSDmitry Monakhov 		goal = ext4_inode_to_goal_block(inode);
1297be5cd90dSDmitry Monakhov 	newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1298be5cd90dSDmitry Monakhov 					NULL, &err);
1299a86c6181SAlex Tomas 	if (newblock == 0)
1300a86c6181SAlex Tomas 		return err;
1301a86c6181SAlex Tomas 
1302c45653c3SNikolay Borisov 	bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1303aebf0243SWang Shilong 	if (unlikely(!bh))
1304860d21e2STheodore Ts'o 		return -ENOMEM;
1305a86c6181SAlex Tomas 	lock_buffer(bh);
1306a86c6181SAlex Tomas 
13077e028976SAvantika Mathur 	err = ext4_journal_get_create_access(handle, bh);
13087e028976SAvantika Mathur 	if (err) {
1309a86c6181SAlex Tomas 		unlock_buffer(bh);
1310a86c6181SAlex Tomas 		goto out;
1311a86c6181SAlex Tomas 	}
1312a86c6181SAlex Tomas 
1313592acbf1SSriram Rajagopalan 	ext_size = sizeof(EXT4_I(inode)->i_data);
1314a86c6181SAlex Tomas 	/* move top-level index/leaf into new block */
1315592acbf1SSriram Rajagopalan 	memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1316592acbf1SSriram Rajagopalan 	/* zero out unused area in the extent block */
1317592acbf1SSriram Rajagopalan 	memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1318a86c6181SAlex Tomas 
1319a86c6181SAlex Tomas 	/* set size of new block */
1320a86c6181SAlex Tomas 	neh = ext_block_hdr(bh);
1321a86c6181SAlex Tomas 	/* old root could have indexes or leaves
1322a86c6181SAlex Tomas 	 * so calculate e_max right way */
1323a86c6181SAlex Tomas 	if (ext_depth(inode))
132455ad63bfSTheodore Ts'o 		neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1325a86c6181SAlex Tomas 	else
132655ad63bfSTheodore Ts'o 		neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1327a86c6181SAlex Tomas 	neh->eh_magic = EXT4_EXT_MAGIC;
13287ac5990dSDarrick J. Wong 	ext4_extent_block_csum_set(inode, neh);
1329a86c6181SAlex Tomas 	set_buffer_uptodate(bh);
1330a86c6181SAlex Tomas 	unlock_buffer(bh);
1331a86c6181SAlex Tomas 
13320390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, inode, bh);
13337e028976SAvantika Mathur 	if (err)
1334a86c6181SAlex Tomas 		goto out;
1335a86c6181SAlex Tomas 
13361939dd84SDmitry Monakhov 	/* Update top-level index: num,max,pointer */
1337a86c6181SAlex Tomas 	neh = ext_inode_hdr(inode);
13381939dd84SDmitry Monakhov 	neh->eh_entries = cpu_to_le16(1);
13391939dd84SDmitry Monakhov 	ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
13401939dd84SDmitry Monakhov 	if (neh->eh_depth == 0) {
13411939dd84SDmitry Monakhov 		/* Root extent block becomes index block */
13421939dd84SDmitry Monakhov 		neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
13431939dd84SDmitry Monakhov 		EXT_FIRST_INDEX(neh)->ei_block =
13441939dd84SDmitry Monakhov 			EXT_FIRST_EXTENT(neh)->ee_block;
13451939dd84SDmitry Monakhov 	}
13462ae02107SMingming Cao 	ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1347a86c6181SAlex Tomas 		  le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
13485a0790c2SAndi Kleen 		  le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1349bf89d16fSTheodore Ts'o 		  ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1350a86c6181SAlex Tomas 
1351ba39ebb6SWei Yongjun 	le16_add_cpu(&neh->eh_depth, 1);
13521939dd84SDmitry Monakhov 	ext4_mark_inode_dirty(handle, inode);
1353a86c6181SAlex Tomas out:
1354a86c6181SAlex Tomas 	brelse(bh);
1355a86c6181SAlex Tomas 
1356a86c6181SAlex Tomas 	return err;
1357a86c6181SAlex Tomas }
1358a86c6181SAlex Tomas 
1359a86c6181SAlex Tomas /*
1360d0d856e8SRandy Dunlap  * ext4_ext_create_new_leaf:
1361d0d856e8SRandy Dunlap  * finds empty index and adds new leaf.
1362d0d856e8SRandy Dunlap  * if no free index is found, then it requests in-depth growing.
1363a86c6181SAlex Tomas  */
1364a86c6181SAlex Tomas static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1365107a7bd3STheodore Ts'o 				    unsigned int mb_flags,
1366107a7bd3STheodore Ts'o 				    unsigned int gb_flags,
1367dfe50809STheodore Ts'o 				    struct ext4_ext_path **ppath,
1368a86c6181SAlex Tomas 				    struct ext4_extent *newext)
1369a86c6181SAlex Tomas {
1370dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
1371a86c6181SAlex Tomas 	struct ext4_ext_path *curp;
1372a86c6181SAlex Tomas 	int depth, i, err = 0;
1373a86c6181SAlex Tomas 
1374a86c6181SAlex Tomas repeat:
1375a86c6181SAlex Tomas 	i = depth = ext_depth(inode);
1376a86c6181SAlex Tomas 
1377a86c6181SAlex Tomas 	/* walk up to the tree and look for free index entry */
1378a86c6181SAlex Tomas 	curp = path + depth;
1379a86c6181SAlex Tomas 	while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1380a86c6181SAlex Tomas 		i--;
1381a86c6181SAlex Tomas 		curp--;
1382a86c6181SAlex Tomas 	}
1383a86c6181SAlex Tomas 
1384d0d856e8SRandy Dunlap 	/* we use already allocated block for index block,
1385d0d856e8SRandy Dunlap 	 * so subsequent data blocks should be contiguous */
1386a86c6181SAlex Tomas 	if (EXT_HAS_FREE_INDEX(curp)) {
1387a86c6181SAlex Tomas 		/* if we found index with free entry, then use that
1388a86c6181SAlex Tomas 		 * entry: create all needed subtree and add new leaf */
1389107a7bd3STheodore Ts'o 		err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1390787e0981SShen Feng 		if (err)
1391787e0981SShen Feng 			goto out;
1392a86c6181SAlex Tomas 
1393a86c6181SAlex Tomas 		/* refill path */
1394ed8a1a76STheodore Ts'o 		path = ext4_find_extent(inode,
1395725d26d3SAneesh Kumar K.V 				    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1396dfe50809STheodore Ts'o 				    ppath, gb_flags);
1397a86c6181SAlex Tomas 		if (IS_ERR(path))
1398a86c6181SAlex Tomas 			err = PTR_ERR(path);
1399a86c6181SAlex Tomas 	} else {
1400a86c6181SAlex Tomas 		/* tree is full, time to grow in depth */
1401be5cd90dSDmitry Monakhov 		err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1402a86c6181SAlex Tomas 		if (err)
1403a86c6181SAlex Tomas 			goto out;
1404a86c6181SAlex Tomas 
1405a86c6181SAlex Tomas 		/* refill path */
1406ed8a1a76STheodore Ts'o 		path = ext4_find_extent(inode,
1407725d26d3SAneesh Kumar K.V 				   (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1408dfe50809STheodore Ts'o 				    ppath, gb_flags);
1409a86c6181SAlex Tomas 		if (IS_ERR(path)) {
1410a86c6181SAlex Tomas 			err = PTR_ERR(path);
1411a86c6181SAlex Tomas 			goto out;
1412a86c6181SAlex Tomas 		}
1413a86c6181SAlex Tomas 
1414a86c6181SAlex Tomas 		/*
1415d0d856e8SRandy Dunlap 		 * only first (depth 0 -> 1) produces free space;
1416d0d856e8SRandy Dunlap 		 * in all other cases we have to split the grown tree
1417a86c6181SAlex Tomas 		 */
1418a86c6181SAlex Tomas 		depth = ext_depth(inode);
1419a86c6181SAlex Tomas 		if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1420d0d856e8SRandy Dunlap 			/* now we need to split */
1421a86c6181SAlex Tomas 			goto repeat;
1422a86c6181SAlex Tomas 		}
1423a86c6181SAlex Tomas 	}
1424a86c6181SAlex Tomas 
1425a86c6181SAlex Tomas out:
1426a86c6181SAlex Tomas 	return err;
1427a86c6181SAlex Tomas }
1428a86c6181SAlex Tomas 
1429a86c6181SAlex Tomas /*
14301988b51eSAlex Tomas  * search the closest allocated block to the left for *logical
14311988b51eSAlex Tomas  * and returns it at @logical + it's physical address at @phys
14321988b51eSAlex Tomas  * if *logical is the smallest allocated block, the function
14331988b51eSAlex Tomas  * returns 0 at @phys
14341988b51eSAlex Tomas  * return value contains 0 (success) or error code
14351988b51eSAlex Tomas  */
14361f109d5aSTheodore Ts'o static int ext4_ext_search_left(struct inode *inode,
14371f109d5aSTheodore Ts'o 				struct ext4_ext_path *path,
14381988b51eSAlex Tomas 				ext4_lblk_t *logical, ext4_fsblk_t *phys)
14391988b51eSAlex Tomas {
14401988b51eSAlex Tomas 	struct ext4_extent_idx *ix;
14411988b51eSAlex Tomas 	struct ext4_extent *ex;
1442b939e376SAneesh Kumar K.V 	int depth, ee_len;
14431988b51eSAlex Tomas 
1444273df556SFrank Mayhar 	if (unlikely(path == NULL)) {
1445273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
14466a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1447273df556SFrank Mayhar 	}
14481988b51eSAlex Tomas 	depth = path->p_depth;
14491988b51eSAlex Tomas 	*phys = 0;
14501988b51eSAlex Tomas 
14511988b51eSAlex Tomas 	if (depth == 0 && path->p_ext == NULL)
14521988b51eSAlex Tomas 		return 0;
14531988b51eSAlex Tomas 
14541988b51eSAlex Tomas 	/* usually extent in the path covers blocks smaller
14551988b51eSAlex Tomas 	 * then *logical, but it can be that extent is the
14561988b51eSAlex Tomas 	 * first one in the file */
14571988b51eSAlex Tomas 
14581988b51eSAlex Tomas 	ex = path[depth].p_ext;
1459b939e376SAneesh Kumar K.V 	ee_len = ext4_ext_get_actual_len(ex);
14601988b51eSAlex Tomas 	if (*logical < le32_to_cpu(ex->ee_block)) {
1461273df556SFrank Mayhar 		if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1462273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
1463273df556SFrank Mayhar 					 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1464273df556SFrank Mayhar 					 *logical, le32_to_cpu(ex->ee_block));
14656a797d27SDarrick J. Wong 			return -EFSCORRUPTED;
1466273df556SFrank Mayhar 		}
14671988b51eSAlex Tomas 		while (--depth >= 0) {
14681988b51eSAlex Tomas 			ix = path[depth].p_idx;
1469273df556SFrank Mayhar 			if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1470273df556SFrank Mayhar 				EXT4_ERROR_INODE(inode,
1471273df556SFrank Mayhar 				  "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
14726ee3b212STao Ma 				  ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1473273df556SFrank Mayhar 				  EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
14746ee3b212STao Ma 		le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1475273df556SFrank Mayhar 				  depth);
14766a797d27SDarrick J. Wong 				return -EFSCORRUPTED;
1477273df556SFrank Mayhar 			}
14781988b51eSAlex Tomas 		}
14791988b51eSAlex Tomas 		return 0;
14801988b51eSAlex Tomas 	}
14811988b51eSAlex Tomas 
1482273df556SFrank Mayhar 	if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1483273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
1484273df556SFrank Mayhar 				 "logical %d < ee_block %d + ee_len %d!",
1485273df556SFrank Mayhar 				 *logical, le32_to_cpu(ex->ee_block), ee_len);
14866a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1487273df556SFrank Mayhar 	}
14881988b51eSAlex Tomas 
1489b939e376SAneesh Kumar K.V 	*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1490bf89d16fSTheodore Ts'o 	*phys = ext4_ext_pblock(ex) + ee_len - 1;
14911988b51eSAlex Tomas 	return 0;
14921988b51eSAlex Tomas }
14931988b51eSAlex Tomas 
14941988b51eSAlex Tomas /*
14951988b51eSAlex Tomas  * search the closest allocated block to the right for *logical
14961988b51eSAlex Tomas  * and returns it at @logical + it's physical address at @phys
1497df3ab170STao Ma  * if *logical is the largest allocated block, the function
14981988b51eSAlex Tomas  * returns 0 at @phys
14991988b51eSAlex Tomas  * return value contains 0 (success) or error code
15001988b51eSAlex Tomas  */
15011f109d5aSTheodore Ts'o static int ext4_ext_search_right(struct inode *inode,
15021f109d5aSTheodore Ts'o 				 struct ext4_ext_path *path,
15034d33b1efSTheodore Ts'o 				 ext4_lblk_t *logical, ext4_fsblk_t *phys,
15044d33b1efSTheodore Ts'o 				 struct ext4_extent **ret_ex)
15051988b51eSAlex Tomas {
15061988b51eSAlex Tomas 	struct buffer_head *bh = NULL;
15071988b51eSAlex Tomas 	struct ext4_extent_header *eh;
15081988b51eSAlex Tomas 	struct ext4_extent_idx *ix;
15091988b51eSAlex Tomas 	struct ext4_extent *ex;
15101988b51eSAlex Tomas 	ext4_fsblk_t block;
1511395a87bfSEric Sandeen 	int depth;	/* Note, NOT eh_depth; depth from top of tree */
1512395a87bfSEric Sandeen 	int ee_len;
15131988b51eSAlex Tomas 
1514273df556SFrank Mayhar 	if (unlikely(path == NULL)) {
1515273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
15166a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1517273df556SFrank Mayhar 	}
15181988b51eSAlex Tomas 	depth = path->p_depth;
15191988b51eSAlex Tomas 	*phys = 0;
15201988b51eSAlex Tomas 
15211988b51eSAlex Tomas 	if (depth == 0 && path->p_ext == NULL)
15221988b51eSAlex Tomas 		return 0;
15231988b51eSAlex Tomas 
15241988b51eSAlex Tomas 	/* usually extent in the path covers blocks smaller
15251988b51eSAlex Tomas 	 * then *logical, but it can be that extent is the
15261988b51eSAlex Tomas 	 * first one in the file */
15271988b51eSAlex Tomas 
15281988b51eSAlex Tomas 	ex = path[depth].p_ext;
1529b939e376SAneesh Kumar K.V 	ee_len = ext4_ext_get_actual_len(ex);
15301988b51eSAlex Tomas 	if (*logical < le32_to_cpu(ex->ee_block)) {
1531273df556SFrank Mayhar 		if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1532273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
1533273df556SFrank Mayhar 					 "first_extent(path[%d].p_hdr) != ex",
1534273df556SFrank Mayhar 					 depth);
15356a797d27SDarrick J. Wong 			return -EFSCORRUPTED;
1536273df556SFrank Mayhar 		}
15371988b51eSAlex Tomas 		while (--depth >= 0) {
15381988b51eSAlex Tomas 			ix = path[depth].p_idx;
1539273df556SFrank Mayhar 			if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1540273df556SFrank Mayhar 				EXT4_ERROR_INODE(inode,
1541273df556SFrank Mayhar 						 "ix != EXT_FIRST_INDEX *logical %d!",
1542273df556SFrank Mayhar 						 *logical);
15436a797d27SDarrick J. Wong 				return -EFSCORRUPTED;
1544273df556SFrank Mayhar 			}
15451988b51eSAlex Tomas 		}
15464d33b1efSTheodore Ts'o 		goto found_extent;
15471988b51eSAlex Tomas 	}
15481988b51eSAlex Tomas 
1549273df556SFrank Mayhar 	if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1550273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
1551273df556SFrank Mayhar 				 "logical %d < ee_block %d + ee_len %d!",
1552273df556SFrank Mayhar 				 *logical, le32_to_cpu(ex->ee_block), ee_len);
15536a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1554273df556SFrank Mayhar 	}
15551988b51eSAlex Tomas 
15561988b51eSAlex Tomas 	if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
15571988b51eSAlex Tomas 		/* next allocated block in this leaf */
15581988b51eSAlex Tomas 		ex++;
15594d33b1efSTheodore Ts'o 		goto found_extent;
15601988b51eSAlex Tomas 	}
15611988b51eSAlex Tomas 
15621988b51eSAlex Tomas 	/* go up and search for index to the right */
15631988b51eSAlex Tomas 	while (--depth >= 0) {
15641988b51eSAlex Tomas 		ix = path[depth].p_idx;
15651988b51eSAlex Tomas 		if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
156625f1ee3aSWu Fengguang 			goto got_index;
15671988b51eSAlex Tomas 	}
15681988b51eSAlex Tomas 
156925f1ee3aSWu Fengguang 	/* we've gone up to the root and found no index to the right */
15701988b51eSAlex Tomas 	return 0;
15711988b51eSAlex Tomas 
157225f1ee3aSWu Fengguang got_index:
15731988b51eSAlex Tomas 	/* we've found index to the right, let's
15741988b51eSAlex Tomas 	 * follow it and find the closest allocated
15751988b51eSAlex Tomas 	 * block to the right */
15761988b51eSAlex Tomas 	ix++;
1577bf89d16fSTheodore Ts'o 	block = ext4_idx_pblock(ix);
15781988b51eSAlex Tomas 	while (++depth < path->p_depth) {
1579395a87bfSEric Sandeen 		/* subtract from p_depth to get proper eh_depth */
15807d7ea89eSTheodore Ts'o 		bh = read_extent_tree_block(inode, block,
1581107a7bd3STheodore Ts'o 					    path->p_depth - depth, 0);
15827d7ea89eSTheodore Ts'o 		if (IS_ERR(bh))
15837d7ea89eSTheodore Ts'o 			return PTR_ERR(bh);
15847d7ea89eSTheodore Ts'o 		eh = ext_block_hdr(bh);
15851988b51eSAlex Tomas 		ix = EXT_FIRST_INDEX(eh);
1586bf89d16fSTheodore Ts'o 		block = ext4_idx_pblock(ix);
15871988b51eSAlex Tomas 		put_bh(bh);
15881988b51eSAlex Tomas 	}
15891988b51eSAlex Tomas 
1590107a7bd3STheodore Ts'o 	bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
15917d7ea89eSTheodore Ts'o 	if (IS_ERR(bh))
15927d7ea89eSTheodore Ts'o 		return PTR_ERR(bh);
15931988b51eSAlex Tomas 	eh = ext_block_hdr(bh);
15941988b51eSAlex Tomas 	ex = EXT_FIRST_EXTENT(eh);
15954d33b1efSTheodore Ts'o found_extent:
15961988b51eSAlex Tomas 	*logical = le32_to_cpu(ex->ee_block);
1597bf89d16fSTheodore Ts'o 	*phys = ext4_ext_pblock(ex);
15984d33b1efSTheodore Ts'o 	*ret_ex = ex;
15994d33b1efSTheodore Ts'o 	if (bh)
16001988b51eSAlex Tomas 		put_bh(bh);
16011988b51eSAlex Tomas 	return 0;
16021988b51eSAlex Tomas }
16031988b51eSAlex Tomas 
16041988b51eSAlex Tomas /*
1605d0d856e8SRandy Dunlap  * ext4_ext_next_allocated_block:
1606f17722f9SLukas Czerner  * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1607d0d856e8SRandy Dunlap  * NOTE: it considers block number from index entry as
1608d0d856e8SRandy Dunlap  * allocated block. Thus, index entries have to be consistent
1609d0d856e8SRandy Dunlap  * with leaves.
1610a86c6181SAlex Tomas  */
1611fcf6b1b7SDmitry Monakhov ext4_lblk_t
1612a86c6181SAlex Tomas ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1613a86c6181SAlex Tomas {
1614a86c6181SAlex Tomas 	int depth;
1615a86c6181SAlex Tomas 
1616a86c6181SAlex Tomas 	BUG_ON(path == NULL);
1617a86c6181SAlex Tomas 	depth = path->p_depth;
1618a86c6181SAlex Tomas 
1619a86c6181SAlex Tomas 	if (depth == 0 && path->p_ext == NULL)
1620f17722f9SLukas Czerner 		return EXT_MAX_BLOCKS;
1621a86c6181SAlex Tomas 
1622a86c6181SAlex Tomas 	while (depth >= 0) {
1623a86c6181SAlex Tomas 		if (depth == path->p_depth) {
1624a86c6181SAlex Tomas 			/* leaf */
16256f8ff537SCurt Wohlgemuth 			if (path[depth].p_ext &&
16266f8ff537SCurt Wohlgemuth 				path[depth].p_ext !=
1627a86c6181SAlex Tomas 					EXT_LAST_EXTENT(path[depth].p_hdr))
1628a86c6181SAlex Tomas 			  return le32_to_cpu(path[depth].p_ext[1].ee_block);
1629a86c6181SAlex Tomas 		} else {
1630a86c6181SAlex Tomas 			/* index */
1631a86c6181SAlex Tomas 			if (path[depth].p_idx !=
1632a86c6181SAlex Tomas 					EXT_LAST_INDEX(path[depth].p_hdr))
1633a86c6181SAlex Tomas 			  return le32_to_cpu(path[depth].p_idx[1].ei_block);
1634a86c6181SAlex Tomas 		}
1635a86c6181SAlex Tomas 		depth--;
1636a86c6181SAlex Tomas 	}
1637a86c6181SAlex Tomas 
1638f17722f9SLukas Czerner 	return EXT_MAX_BLOCKS;
1639a86c6181SAlex Tomas }
1640a86c6181SAlex Tomas 
1641a86c6181SAlex Tomas /*
1642d0d856e8SRandy Dunlap  * ext4_ext_next_leaf_block:
1643f17722f9SLukas Czerner  * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1644a86c6181SAlex Tomas  */
16455718789dSRobin Dong static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1646a86c6181SAlex Tomas {
1647a86c6181SAlex Tomas 	int depth;
1648a86c6181SAlex Tomas 
1649a86c6181SAlex Tomas 	BUG_ON(path == NULL);
1650a86c6181SAlex Tomas 	depth = path->p_depth;
1651a86c6181SAlex Tomas 
1652a86c6181SAlex Tomas 	/* zero-tree has no leaf blocks at all */
1653a86c6181SAlex Tomas 	if (depth == 0)
1654f17722f9SLukas Czerner 		return EXT_MAX_BLOCKS;
1655a86c6181SAlex Tomas 
1656a86c6181SAlex Tomas 	/* go to index block */
1657a86c6181SAlex Tomas 	depth--;
1658a86c6181SAlex Tomas 
1659a86c6181SAlex Tomas 	while (depth >= 0) {
1660a86c6181SAlex Tomas 		if (path[depth].p_idx !=
1661a86c6181SAlex Tomas 				EXT_LAST_INDEX(path[depth].p_hdr))
1662725d26d3SAneesh Kumar K.V 			return (ext4_lblk_t)
1663725d26d3SAneesh Kumar K.V 				le32_to_cpu(path[depth].p_idx[1].ei_block);
1664a86c6181SAlex Tomas 		depth--;
1665a86c6181SAlex Tomas 	}
1666a86c6181SAlex Tomas 
1667f17722f9SLukas Czerner 	return EXT_MAX_BLOCKS;
1668a86c6181SAlex Tomas }
1669a86c6181SAlex Tomas 
1670a86c6181SAlex Tomas /*
1671d0d856e8SRandy Dunlap  * ext4_ext_correct_indexes:
1672d0d856e8SRandy Dunlap  * if leaf gets modified and modified extent is first in the leaf,
1673d0d856e8SRandy Dunlap  * then we have to correct all indexes above.
1674a86c6181SAlex Tomas  * TODO: do we need to correct tree in all cases?
1675a86c6181SAlex Tomas  */
16761d03ec98SAneesh Kumar K.V static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1677a86c6181SAlex Tomas 				struct ext4_ext_path *path)
1678a86c6181SAlex Tomas {
1679a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
1680a86c6181SAlex Tomas 	int depth = ext_depth(inode);
1681a86c6181SAlex Tomas 	struct ext4_extent *ex;
1682a86c6181SAlex Tomas 	__le32 border;
1683a86c6181SAlex Tomas 	int k, err = 0;
1684a86c6181SAlex Tomas 
1685a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
1686a86c6181SAlex Tomas 	ex = path[depth].p_ext;
1687273df556SFrank Mayhar 
1688273df556SFrank Mayhar 	if (unlikely(ex == NULL || eh == NULL)) {
1689273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
1690273df556SFrank Mayhar 				 "ex %p == NULL or eh %p == NULL", ex, eh);
16916a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1692273df556SFrank Mayhar 	}
1693a86c6181SAlex Tomas 
1694a86c6181SAlex Tomas 	if (depth == 0) {
1695a86c6181SAlex Tomas 		/* there is no tree at all */
1696a86c6181SAlex Tomas 		return 0;
1697a86c6181SAlex Tomas 	}
1698a86c6181SAlex Tomas 
1699a86c6181SAlex Tomas 	if (ex != EXT_FIRST_EXTENT(eh)) {
1700a86c6181SAlex Tomas 		/* we correct tree if first leaf got modified only */
1701a86c6181SAlex Tomas 		return 0;
1702a86c6181SAlex Tomas 	}
1703a86c6181SAlex Tomas 
1704a86c6181SAlex Tomas 	/*
1705d0d856e8SRandy Dunlap 	 * TODO: we need correction if border is smaller than current one
1706a86c6181SAlex Tomas 	 */
1707a86c6181SAlex Tomas 	k = depth - 1;
1708a86c6181SAlex Tomas 	border = path[depth].p_ext->ee_block;
17097e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, path + k);
17107e028976SAvantika Mathur 	if (err)
1711a86c6181SAlex Tomas 		return err;
1712a86c6181SAlex Tomas 	path[k].p_idx->ei_block = border;
17137e028976SAvantika Mathur 	err = ext4_ext_dirty(handle, inode, path + k);
17147e028976SAvantika Mathur 	if (err)
1715a86c6181SAlex Tomas 		return err;
1716a86c6181SAlex Tomas 
1717a86c6181SAlex Tomas 	while (k--) {
1718a86c6181SAlex Tomas 		/* change all left-side indexes */
1719a86c6181SAlex Tomas 		if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1720a86c6181SAlex Tomas 			break;
17217e028976SAvantika Mathur 		err = ext4_ext_get_access(handle, inode, path + k);
17227e028976SAvantika Mathur 		if (err)
1723a86c6181SAlex Tomas 			break;
1724a86c6181SAlex Tomas 		path[k].p_idx->ei_block = border;
17257e028976SAvantika Mathur 		err = ext4_ext_dirty(handle, inode, path + k);
17267e028976SAvantika Mathur 		if (err)
1727a86c6181SAlex Tomas 			break;
1728a86c6181SAlex Tomas 	}
1729a86c6181SAlex Tomas 
1730a86c6181SAlex Tomas 	return err;
1731a86c6181SAlex Tomas }
1732a86c6181SAlex Tomas 
1733748de673SAkira Fujita int
1734a86c6181SAlex Tomas ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1735a86c6181SAlex Tomas 				struct ext4_extent *ex2)
1736a86c6181SAlex Tomas {
1737da0169b3SEric Sandeen 	unsigned short ext1_ee_len, ext2_ee_len;
1738a2df2a63SAmit Arora 
1739556615dcSLukas Czerner 	if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1740a2df2a63SAmit Arora 		return 0;
1741a2df2a63SAmit Arora 
1742a2df2a63SAmit Arora 	ext1_ee_len = ext4_ext_get_actual_len(ex1);
1743a2df2a63SAmit Arora 	ext2_ee_len = ext4_ext_get_actual_len(ex2);
1744a2df2a63SAmit Arora 
1745a2df2a63SAmit Arora 	if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
174663f57933SAndrew Morton 			le32_to_cpu(ex2->ee_block))
1747a86c6181SAlex Tomas 		return 0;
1748a86c6181SAlex Tomas 
1749471d4011SSuparna Bhattacharya 	/*
1750471d4011SSuparna Bhattacharya 	 * To allow future support for preallocated extents to be added
1751471d4011SSuparna Bhattacharya 	 * as an RO_COMPAT feature, refuse to merge to extents if
1752d0d856e8SRandy Dunlap 	 * this can result in the top bit of ee_len being set.
1753471d4011SSuparna Bhattacharya 	 */
1754da0169b3SEric Sandeen 	if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1755471d4011SSuparna Bhattacharya 		return 0;
1756*378f32baSMatthew Bobrowski 
1757556615dcSLukas Czerner 	if (ext4_ext_is_unwritten(ex1) &&
1758*378f32baSMatthew Bobrowski 	    ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)
1759a9b82415SDarrick J. Wong 		return 0;
1760bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
1761b939e376SAneesh Kumar K.V 	if (ext1_ee_len >= 4)
1762a86c6181SAlex Tomas 		return 0;
1763a86c6181SAlex Tomas #endif
1764a86c6181SAlex Tomas 
1765bf89d16fSTheodore Ts'o 	if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1766a86c6181SAlex Tomas 		return 1;
1767a86c6181SAlex Tomas 	return 0;
1768a86c6181SAlex Tomas }
1769a86c6181SAlex Tomas 
1770a86c6181SAlex Tomas /*
177156055d3aSAmit Arora  * This function tries to merge the "ex" extent to the next extent in the tree.
177256055d3aSAmit Arora  * It always tries to merge towards right. If you want to merge towards
177356055d3aSAmit Arora  * left, pass "ex - 1" as argument instead of "ex".
177456055d3aSAmit Arora  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
177556055d3aSAmit Arora  * 1 if they got merged.
177656055d3aSAmit Arora  */
1777197217a5SYongqiang Yang static int ext4_ext_try_to_merge_right(struct inode *inode,
177856055d3aSAmit Arora 				 struct ext4_ext_path *path,
177956055d3aSAmit Arora 				 struct ext4_extent *ex)
178056055d3aSAmit Arora {
178156055d3aSAmit Arora 	struct ext4_extent_header *eh;
178256055d3aSAmit Arora 	unsigned int depth, len;
1783556615dcSLukas Czerner 	int merge_done = 0, unwritten;
178456055d3aSAmit Arora 
178556055d3aSAmit Arora 	depth = ext_depth(inode);
178656055d3aSAmit Arora 	BUG_ON(path[depth].p_hdr == NULL);
178756055d3aSAmit Arora 	eh = path[depth].p_hdr;
178856055d3aSAmit Arora 
178956055d3aSAmit Arora 	while (ex < EXT_LAST_EXTENT(eh)) {
179056055d3aSAmit Arora 		if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
179156055d3aSAmit Arora 			break;
179256055d3aSAmit Arora 		/* merge with next extent! */
1793556615dcSLukas Czerner 		unwritten = ext4_ext_is_unwritten(ex);
179456055d3aSAmit Arora 		ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
179556055d3aSAmit Arora 				+ ext4_ext_get_actual_len(ex + 1));
1796556615dcSLukas Czerner 		if (unwritten)
1797556615dcSLukas Czerner 			ext4_ext_mark_unwritten(ex);
179856055d3aSAmit Arora 
179956055d3aSAmit Arora 		if (ex + 1 < EXT_LAST_EXTENT(eh)) {
180056055d3aSAmit Arora 			len = (EXT_LAST_EXTENT(eh) - ex - 1)
180156055d3aSAmit Arora 				* sizeof(struct ext4_extent);
180256055d3aSAmit Arora 			memmove(ex + 1, ex + 2, len);
180356055d3aSAmit Arora 		}
1804e8546d06SMarcin Slusarz 		le16_add_cpu(&eh->eh_entries, -1);
180556055d3aSAmit Arora 		merge_done = 1;
180656055d3aSAmit Arora 		WARN_ON(eh->eh_entries == 0);
180756055d3aSAmit Arora 		if (!eh->eh_entries)
180824676da4STheodore Ts'o 			EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
180956055d3aSAmit Arora 	}
181056055d3aSAmit Arora 
181156055d3aSAmit Arora 	return merge_done;
181256055d3aSAmit Arora }
181356055d3aSAmit Arora 
181456055d3aSAmit Arora /*
1815ecb94f5fSTheodore Ts'o  * This function does a very simple check to see if we can collapse
1816ecb94f5fSTheodore Ts'o  * an extent tree with a single extent tree leaf block into the inode.
1817ecb94f5fSTheodore Ts'o  */
1818ecb94f5fSTheodore Ts'o static void ext4_ext_try_to_merge_up(handle_t *handle,
1819ecb94f5fSTheodore Ts'o 				     struct inode *inode,
1820ecb94f5fSTheodore Ts'o 				     struct ext4_ext_path *path)
1821ecb94f5fSTheodore Ts'o {
1822ecb94f5fSTheodore Ts'o 	size_t s;
1823ecb94f5fSTheodore Ts'o 	unsigned max_root = ext4_ext_space_root(inode, 0);
1824ecb94f5fSTheodore Ts'o 	ext4_fsblk_t blk;
1825ecb94f5fSTheodore Ts'o 
1826ecb94f5fSTheodore Ts'o 	if ((path[0].p_depth != 1) ||
1827ecb94f5fSTheodore Ts'o 	    (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1828ecb94f5fSTheodore Ts'o 	    (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1829ecb94f5fSTheodore Ts'o 		return;
1830ecb94f5fSTheodore Ts'o 
1831ecb94f5fSTheodore Ts'o 	/*
1832ecb94f5fSTheodore Ts'o 	 * We need to modify the block allocation bitmap and the block
1833ecb94f5fSTheodore Ts'o 	 * group descriptor to release the extent tree block.  If we
1834ecb94f5fSTheodore Ts'o 	 * can't get the journal credits, give up.
1835ecb94f5fSTheodore Ts'o 	 */
1836ecb94f5fSTheodore Ts'o 	if (ext4_journal_extend(handle, 2))
1837ecb94f5fSTheodore Ts'o 		return;
1838ecb94f5fSTheodore Ts'o 
1839ecb94f5fSTheodore Ts'o 	/*
1840ecb94f5fSTheodore Ts'o 	 * Copy the extent data up to the inode
1841ecb94f5fSTheodore Ts'o 	 */
1842ecb94f5fSTheodore Ts'o 	blk = ext4_idx_pblock(path[0].p_idx);
1843ecb94f5fSTheodore Ts'o 	s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1844ecb94f5fSTheodore Ts'o 		sizeof(struct ext4_extent_idx);
1845ecb94f5fSTheodore Ts'o 	s += sizeof(struct ext4_extent_header);
1846ecb94f5fSTheodore Ts'o 
184710809df8STheodore Ts'o 	path[1].p_maxdepth = path[0].p_maxdepth;
1848ecb94f5fSTheodore Ts'o 	memcpy(path[0].p_hdr, path[1].p_hdr, s);
1849ecb94f5fSTheodore Ts'o 	path[0].p_depth = 0;
1850ecb94f5fSTheodore Ts'o 	path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1851ecb94f5fSTheodore Ts'o 		(path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1852ecb94f5fSTheodore Ts'o 	path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1853ecb94f5fSTheodore Ts'o 
1854ecb94f5fSTheodore Ts'o 	brelse(path[1].p_bh);
1855ecb94f5fSTheodore Ts'o 	ext4_free_blocks(handle, inode, NULL, blk, 1,
185671d4f7d0STheodore Ts'o 			 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1857ecb94f5fSTheodore Ts'o }
1858ecb94f5fSTheodore Ts'o 
1859ecb94f5fSTheodore Ts'o /*
1860197217a5SYongqiang Yang  * This function tries to merge the @ex extent to neighbours in the tree.
1861197217a5SYongqiang Yang  * return 1 if merge left else 0.
1862197217a5SYongqiang Yang  */
1863ecb94f5fSTheodore Ts'o static void ext4_ext_try_to_merge(handle_t *handle,
1864ecb94f5fSTheodore Ts'o 				  struct inode *inode,
1865197217a5SYongqiang Yang 				  struct ext4_ext_path *path,
1866197217a5SYongqiang Yang 				  struct ext4_extent *ex) {
1867197217a5SYongqiang Yang 	struct ext4_extent_header *eh;
1868197217a5SYongqiang Yang 	unsigned int depth;
1869197217a5SYongqiang Yang 	int merge_done = 0;
1870197217a5SYongqiang Yang 
1871197217a5SYongqiang Yang 	depth = ext_depth(inode);
1872197217a5SYongqiang Yang 	BUG_ON(path[depth].p_hdr == NULL);
1873197217a5SYongqiang Yang 	eh = path[depth].p_hdr;
1874197217a5SYongqiang Yang 
1875197217a5SYongqiang Yang 	if (ex > EXT_FIRST_EXTENT(eh))
1876197217a5SYongqiang Yang 		merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1877197217a5SYongqiang Yang 
1878197217a5SYongqiang Yang 	if (!merge_done)
1879ecb94f5fSTheodore Ts'o 		(void) ext4_ext_try_to_merge_right(inode, path, ex);
1880197217a5SYongqiang Yang 
1881ecb94f5fSTheodore Ts'o 	ext4_ext_try_to_merge_up(handle, inode, path);
1882197217a5SYongqiang Yang }
1883197217a5SYongqiang Yang 
1884197217a5SYongqiang Yang /*
188525d14f98SAmit Arora  * check if a portion of the "newext" extent overlaps with an
188625d14f98SAmit Arora  * existing extent.
188725d14f98SAmit Arora  *
188825d14f98SAmit Arora  * If there is an overlap discovered, it updates the length of the newext
188925d14f98SAmit Arora  * such that there will be no overlap, and then returns 1.
189025d14f98SAmit Arora  * If there is no overlap found, it returns 0.
189125d14f98SAmit Arora  */
18924d33b1efSTheodore Ts'o static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
18934d33b1efSTheodore Ts'o 					   struct inode *inode,
189425d14f98SAmit Arora 					   struct ext4_extent *newext,
189525d14f98SAmit Arora 					   struct ext4_ext_path *path)
189625d14f98SAmit Arora {
1897725d26d3SAneesh Kumar K.V 	ext4_lblk_t b1, b2;
189825d14f98SAmit Arora 	unsigned int depth, len1;
189925d14f98SAmit Arora 	unsigned int ret = 0;
190025d14f98SAmit Arora 
190125d14f98SAmit Arora 	b1 = le32_to_cpu(newext->ee_block);
1902a2df2a63SAmit Arora 	len1 = ext4_ext_get_actual_len(newext);
190325d14f98SAmit Arora 	depth = ext_depth(inode);
190425d14f98SAmit Arora 	if (!path[depth].p_ext)
190525d14f98SAmit Arora 		goto out;
1906f5a44db5STheodore Ts'o 	b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
190725d14f98SAmit Arora 
190825d14f98SAmit Arora 	/*
190925d14f98SAmit Arora 	 * get the next allocated block if the extent in the path
191025d14f98SAmit Arora 	 * is before the requested block(s)
191125d14f98SAmit Arora 	 */
191225d14f98SAmit Arora 	if (b2 < b1) {
191325d14f98SAmit Arora 		b2 = ext4_ext_next_allocated_block(path);
1914f17722f9SLukas Czerner 		if (b2 == EXT_MAX_BLOCKS)
191525d14f98SAmit Arora 			goto out;
1916f5a44db5STheodore Ts'o 		b2 = EXT4_LBLK_CMASK(sbi, b2);
191725d14f98SAmit Arora 	}
191825d14f98SAmit Arora 
1919725d26d3SAneesh Kumar K.V 	/* check for wrap through zero on extent logical start block*/
192025d14f98SAmit Arora 	if (b1 + len1 < b1) {
1921f17722f9SLukas Czerner 		len1 = EXT_MAX_BLOCKS - b1;
192225d14f98SAmit Arora 		newext->ee_len = cpu_to_le16(len1);
192325d14f98SAmit Arora 		ret = 1;
192425d14f98SAmit Arora 	}
192525d14f98SAmit Arora 
192625d14f98SAmit Arora 	/* check for overlap */
192725d14f98SAmit Arora 	if (b1 + len1 > b2) {
192825d14f98SAmit Arora 		newext->ee_len = cpu_to_le16(b2 - b1);
192925d14f98SAmit Arora 		ret = 1;
193025d14f98SAmit Arora 	}
193125d14f98SAmit Arora out:
193225d14f98SAmit Arora 	return ret;
193325d14f98SAmit Arora }
193425d14f98SAmit Arora 
193525d14f98SAmit Arora /*
1936d0d856e8SRandy Dunlap  * ext4_ext_insert_extent:
1937d0d856e8SRandy Dunlap  * tries to merge requsted extent into the existing extent or
1938d0d856e8SRandy Dunlap  * inserts requested extent as new one into the tree,
1939d0d856e8SRandy Dunlap  * creating new leaf in the no-space case.
1940a86c6181SAlex Tomas  */
1941a86c6181SAlex Tomas int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1942dfe50809STheodore Ts'o 				struct ext4_ext_path **ppath,
1943107a7bd3STheodore Ts'o 				struct ext4_extent *newext, int gb_flags)
1944a86c6181SAlex Tomas {
1945dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
1946a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
1947a86c6181SAlex Tomas 	struct ext4_extent *ex, *fex;
1948a86c6181SAlex Tomas 	struct ext4_extent *nearex; /* nearest extent */
1949a86c6181SAlex Tomas 	struct ext4_ext_path *npath = NULL;
1950725d26d3SAneesh Kumar K.V 	int depth, len, err;
1951725d26d3SAneesh Kumar K.V 	ext4_lblk_t next;
1952556615dcSLukas Czerner 	int mb_flags = 0, unwritten;
1953a86c6181SAlex Tomas 
1954e3cf5d5dSTheodore Ts'o 	if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1955e3cf5d5dSTheodore Ts'o 		mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1956273df556SFrank Mayhar 	if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1957273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
19586a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1959273df556SFrank Mayhar 	}
1960a86c6181SAlex Tomas 	depth = ext_depth(inode);
1961a86c6181SAlex Tomas 	ex = path[depth].p_ext;
1962be8981beSLukas Czerner 	eh = path[depth].p_hdr;
1963273df556SFrank Mayhar 	if (unlikely(path[depth].p_hdr == NULL)) {
1964273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
19656a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
1966273df556SFrank Mayhar 	}
1967a86c6181SAlex Tomas 
1968a86c6181SAlex Tomas 	/* try to insert block into found extent and return */
1969107a7bd3STheodore Ts'o 	if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1970be8981beSLukas Czerner 
1971be8981beSLukas Czerner 		/*
1972be8981beSLukas Czerner 		 * Try to see whether we should rather test the extent on
1973be8981beSLukas Czerner 		 * right from ex, or from the left of ex. This is because
1974ed8a1a76STheodore Ts'o 		 * ext4_find_extent() can return either extent on the
1975be8981beSLukas Czerner 		 * left, or on the right from the searched position. This
1976be8981beSLukas Czerner 		 * will make merging more effective.
1977be8981beSLukas Czerner 		 */
1978be8981beSLukas Czerner 		if (ex < EXT_LAST_EXTENT(eh) &&
1979be8981beSLukas Czerner 		    (le32_to_cpu(ex->ee_block) +
1980be8981beSLukas Czerner 		    ext4_ext_get_actual_len(ex) <
1981be8981beSLukas Czerner 		    le32_to_cpu(newext->ee_block))) {
1982be8981beSLukas Czerner 			ex += 1;
1983be8981beSLukas Czerner 			goto prepend;
1984be8981beSLukas Czerner 		} else if ((ex > EXT_FIRST_EXTENT(eh)) &&
1985be8981beSLukas Czerner 			   (le32_to_cpu(newext->ee_block) +
1986be8981beSLukas Czerner 			   ext4_ext_get_actual_len(newext) <
1987be8981beSLukas Czerner 			   le32_to_cpu(ex->ee_block)))
1988be8981beSLukas Czerner 			ex -= 1;
1989be8981beSLukas Czerner 
1990be8981beSLukas Czerner 		/* Try to append newex to the ex */
1991be8981beSLukas Czerner 		if (ext4_can_extents_be_merged(inode, ex, newext)) {
1992be8981beSLukas Czerner 			ext_debug("append [%d]%d block to %u:[%d]%d"
1993be8981beSLukas Czerner 				  "(from %llu)\n",
1994556615dcSLukas Czerner 				  ext4_ext_is_unwritten(newext),
1995a2df2a63SAmit Arora 				  ext4_ext_get_actual_len(newext),
1996a86c6181SAlex Tomas 				  le32_to_cpu(ex->ee_block),
1997556615dcSLukas Czerner 				  ext4_ext_is_unwritten(ex),
1998bf89d16fSTheodore Ts'o 				  ext4_ext_get_actual_len(ex),
1999bf89d16fSTheodore Ts'o 				  ext4_ext_pblock(ex));
2000be8981beSLukas Czerner 			err = ext4_ext_get_access(handle, inode,
2001be8981beSLukas Czerner 						  path + depth);
20027e028976SAvantika Mathur 			if (err)
2003a86c6181SAlex Tomas 				return err;
2004556615dcSLukas Czerner 			unwritten = ext4_ext_is_unwritten(ex);
2005a2df2a63SAmit Arora 			ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2006a2df2a63SAmit Arora 					+ ext4_ext_get_actual_len(newext));
2007556615dcSLukas Czerner 			if (unwritten)
2008556615dcSLukas Czerner 				ext4_ext_mark_unwritten(ex);
2009a86c6181SAlex Tomas 			eh = path[depth].p_hdr;
2010a86c6181SAlex Tomas 			nearex = ex;
2011a86c6181SAlex Tomas 			goto merge;
2012a86c6181SAlex Tomas 		}
2013a86c6181SAlex Tomas 
2014be8981beSLukas Czerner prepend:
2015be8981beSLukas Czerner 		/* Try to prepend newex to the ex */
2016be8981beSLukas Czerner 		if (ext4_can_extents_be_merged(inode, newext, ex)) {
2017be8981beSLukas Czerner 			ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2018be8981beSLukas Czerner 				  "(from %llu)\n",
2019be8981beSLukas Czerner 				  le32_to_cpu(newext->ee_block),
2020556615dcSLukas Czerner 				  ext4_ext_is_unwritten(newext),
2021be8981beSLukas Czerner 				  ext4_ext_get_actual_len(newext),
2022be8981beSLukas Czerner 				  le32_to_cpu(ex->ee_block),
2023556615dcSLukas Czerner 				  ext4_ext_is_unwritten(ex),
2024be8981beSLukas Czerner 				  ext4_ext_get_actual_len(ex),
2025be8981beSLukas Czerner 				  ext4_ext_pblock(ex));
2026be8981beSLukas Czerner 			err = ext4_ext_get_access(handle, inode,
2027be8981beSLukas Czerner 						  path + depth);
2028be8981beSLukas Czerner 			if (err)
2029be8981beSLukas Czerner 				return err;
2030be8981beSLukas Czerner 
2031556615dcSLukas Czerner 			unwritten = ext4_ext_is_unwritten(ex);
2032be8981beSLukas Czerner 			ex->ee_block = newext->ee_block;
2033be8981beSLukas Czerner 			ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2034be8981beSLukas Czerner 			ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2035be8981beSLukas Czerner 					+ ext4_ext_get_actual_len(newext));
2036556615dcSLukas Czerner 			if (unwritten)
2037556615dcSLukas Czerner 				ext4_ext_mark_unwritten(ex);
2038be8981beSLukas Czerner 			eh = path[depth].p_hdr;
2039be8981beSLukas Czerner 			nearex = ex;
2040be8981beSLukas Czerner 			goto merge;
2041be8981beSLukas Czerner 		}
2042be8981beSLukas Czerner 	}
2043be8981beSLukas Czerner 
2044a86c6181SAlex Tomas 	depth = ext_depth(inode);
2045a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
2046a86c6181SAlex Tomas 	if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2047a86c6181SAlex Tomas 		goto has_space;
2048a86c6181SAlex Tomas 
2049a86c6181SAlex Tomas 	/* probably next leaf has space for us? */
2050a86c6181SAlex Tomas 	fex = EXT_LAST_EXTENT(eh);
2051598dbdf2SRobin Dong 	next = EXT_MAX_BLOCKS;
2052598dbdf2SRobin Dong 	if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
20535718789dSRobin Dong 		next = ext4_ext_next_leaf_block(path);
2054598dbdf2SRobin Dong 	if (next != EXT_MAX_BLOCKS) {
205532de6756SYongqiang Yang 		ext_debug("next leaf block - %u\n", next);
2056a86c6181SAlex Tomas 		BUG_ON(npath != NULL);
2057ed8a1a76STheodore Ts'o 		npath = ext4_find_extent(inode, next, NULL, 0);
2058a86c6181SAlex Tomas 		if (IS_ERR(npath))
2059a86c6181SAlex Tomas 			return PTR_ERR(npath);
2060a86c6181SAlex Tomas 		BUG_ON(npath->p_depth != path->p_depth);
2061a86c6181SAlex Tomas 		eh = npath[depth].p_hdr;
2062a86c6181SAlex Tomas 		if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
206325985edcSLucas De Marchi 			ext_debug("next leaf isn't full(%d)\n",
2064a86c6181SAlex Tomas 				  le16_to_cpu(eh->eh_entries));
2065a86c6181SAlex Tomas 			path = npath;
2066ffb505ffSRobin Dong 			goto has_space;
2067a86c6181SAlex Tomas 		}
2068a86c6181SAlex Tomas 		ext_debug("next leaf has no free space(%d,%d)\n",
2069a86c6181SAlex Tomas 			  le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2070a86c6181SAlex Tomas 	}
2071a86c6181SAlex Tomas 
2072a86c6181SAlex Tomas 	/*
2073d0d856e8SRandy Dunlap 	 * There is no free space in the found leaf.
2074d0d856e8SRandy Dunlap 	 * We're gonna add a new leaf in the tree.
2075a86c6181SAlex Tomas 	 */
2076107a7bd3STheodore Ts'o 	if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2077e3cf5d5dSTheodore Ts'o 		mb_flags |= EXT4_MB_USE_RESERVED;
2078107a7bd3STheodore Ts'o 	err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2079dfe50809STheodore Ts'o 				       ppath, newext);
2080a86c6181SAlex Tomas 	if (err)
2081a86c6181SAlex Tomas 		goto cleanup;
2082a86c6181SAlex Tomas 	depth = ext_depth(inode);
2083a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
2084a86c6181SAlex Tomas 
2085a86c6181SAlex Tomas has_space:
2086a86c6181SAlex Tomas 	nearex = path[depth].p_ext;
2087a86c6181SAlex Tomas 
20887e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, path + depth);
20897e028976SAvantika Mathur 	if (err)
2090a86c6181SAlex Tomas 		goto cleanup;
2091a86c6181SAlex Tomas 
2092a86c6181SAlex Tomas 	if (!nearex) {
2093a86c6181SAlex Tomas 		/* there is no extent in this leaf, create first one */
209432de6756SYongqiang Yang 		ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
2095a86c6181SAlex Tomas 				le32_to_cpu(newext->ee_block),
2096bf89d16fSTheodore Ts'o 				ext4_ext_pblock(newext),
2097556615dcSLukas Czerner 				ext4_ext_is_unwritten(newext),
2098a2df2a63SAmit Arora 				ext4_ext_get_actual_len(newext));
209980e675f9SEric Gouriou 		nearex = EXT_FIRST_EXTENT(eh);
2100a86c6181SAlex Tomas 	} else {
210180e675f9SEric Gouriou 		if (le32_to_cpu(newext->ee_block)
210280e675f9SEric Gouriou 			   > le32_to_cpu(nearex->ee_block)) {
210380e675f9SEric Gouriou 			/* Insert after */
210432de6756SYongqiang Yang 			ext_debug("insert %u:%llu:[%d]%d before: "
210532de6756SYongqiang Yang 					"nearest %p\n",
2106a86c6181SAlex Tomas 					le32_to_cpu(newext->ee_block),
2107bf89d16fSTheodore Ts'o 					ext4_ext_pblock(newext),
2108556615dcSLukas Czerner 					ext4_ext_is_unwritten(newext),
2109a2df2a63SAmit Arora 					ext4_ext_get_actual_len(newext),
211080e675f9SEric Gouriou 					nearex);
211180e675f9SEric Gouriou 			nearex++;
211280e675f9SEric Gouriou 		} else {
211380e675f9SEric Gouriou 			/* Insert before */
211480e675f9SEric Gouriou 			BUG_ON(newext->ee_block == nearex->ee_block);
211532de6756SYongqiang Yang 			ext_debug("insert %u:%llu:[%d]%d after: "
211632de6756SYongqiang Yang 					"nearest %p\n",
211780e675f9SEric Gouriou 					le32_to_cpu(newext->ee_block),
211880e675f9SEric Gouriou 					ext4_ext_pblock(newext),
2119556615dcSLukas Czerner 					ext4_ext_is_unwritten(newext),
212080e675f9SEric Gouriou 					ext4_ext_get_actual_len(newext),
212180e675f9SEric Gouriou 					nearex);
212280e675f9SEric Gouriou 		}
212380e675f9SEric Gouriou 		len = EXT_LAST_EXTENT(eh) - nearex + 1;
212480e675f9SEric Gouriou 		if (len > 0) {
212532de6756SYongqiang Yang 			ext_debug("insert %u:%llu:[%d]%d: "
212680e675f9SEric Gouriou 					"move %d extents from 0x%p to 0x%p\n",
212780e675f9SEric Gouriou 					le32_to_cpu(newext->ee_block),
212880e675f9SEric Gouriou 					ext4_ext_pblock(newext),
2129556615dcSLukas Czerner 					ext4_ext_is_unwritten(newext),
213080e675f9SEric Gouriou 					ext4_ext_get_actual_len(newext),
213180e675f9SEric Gouriou 					len, nearex, nearex + 1);
213280e675f9SEric Gouriou 			memmove(nearex + 1, nearex,
213380e675f9SEric Gouriou 				len * sizeof(struct ext4_extent));
213480e675f9SEric Gouriou 		}
2135a86c6181SAlex Tomas 	}
2136a86c6181SAlex Tomas 
2137e8546d06SMarcin Slusarz 	le16_add_cpu(&eh->eh_entries, 1);
213880e675f9SEric Gouriou 	path[depth].p_ext = nearex;
2139a86c6181SAlex Tomas 	nearex->ee_block = newext->ee_block;
2140bf89d16fSTheodore Ts'o 	ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2141a86c6181SAlex Tomas 	nearex->ee_len = newext->ee_len;
2142a86c6181SAlex Tomas 
2143a86c6181SAlex Tomas merge:
2144e7bcf823SHaiboLiu 	/* try to merge extents */
2145107a7bd3STheodore Ts'o 	if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2146ecb94f5fSTheodore Ts'o 		ext4_ext_try_to_merge(handle, inode, path, nearex);
2147a86c6181SAlex Tomas 
2148a86c6181SAlex Tomas 
2149a86c6181SAlex Tomas 	/* time to correct all indexes above */
2150a86c6181SAlex Tomas 	err = ext4_ext_correct_indexes(handle, inode, path);
2151a86c6181SAlex Tomas 	if (err)
2152a86c6181SAlex Tomas 		goto cleanup;
2153a86c6181SAlex Tomas 
2154ecb94f5fSTheodore Ts'o 	err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2155a86c6181SAlex Tomas 
2156a86c6181SAlex Tomas cleanup:
2157a86c6181SAlex Tomas 	ext4_ext_drop_refs(npath);
2158a86c6181SAlex Tomas 	kfree(npath);
2159a86c6181SAlex Tomas 	return err;
2160a86c6181SAlex Tomas }
2161a86c6181SAlex Tomas 
216291dd8c11SLukas Czerner static int ext4_fill_fiemap_extents(struct inode *inode,
216391dd8c11SLukas Czerner 				    ext4_lblk_t block, ext4_lblk_t num,
216491dd8c11SLukas Czerner 				    struct fiemap_extent_info *fieinfo)
21656873fa0dSEric Sandeen {
21666873fa0dSEric Sandeen 	struct ext4_ext_path *path = NULL;
21676873fa0dSEric Sandeen 	struct ext4_extent *ex;
216869eb33dcSZheng Liu 	struct extent_status es;
216991dd8c11SLukas Czerner 	ext4_lblk_t next, next_del, start = 0, end = 0;
21706873fa0dSEric Sandeen 	ext4_lblk_t last = block + num;
217191dd8c11SLukas Czerner 	int exists, depth = 0, err = 0;
217291dd8c11SLukas Czerner 	unsigned int flags = 0;
217391dd8c11SLukas Czerner 	unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
21746873fa0dSEric Sandeen 
2175f17722f9SLukas Czerner 	while (block < last && block != EXT_MAX_BLOCKS) {
21766873fa0dSEric Sandeen 		num = last - block;
21776873fa0dSEric Sandeen 		/* find extent for this block */
2178fab3a549STheodore Ts'o 		down_read(&EXT4_I(inode)->i_data_sem);
217991dd8c11SLukas Czerner 
2180ed8a1a76STheodore Ts'o 		path = ext4_find_extent(inode, block, &path, 0);
21816873fa0dSEric Sandeen 		if (IS_ERR(path)) {
218291dd8c11SLukas Czerner 			up_read(&EXT4_I(inode)->i_data_sem);
21836873fa0dSEric Sandeen 			err = PTR_ERR(path);
21846873fa0dSEric Sandeen 			path = NULL;
21856873fa0dSEric Sandeen 			break;
21866873fa0dSEric Sandeen 		}
21876873fa0dSEric Sandeen 
21886873fa0dSEric Sandeen 		depth = ext_depth(inode);
2189273df556SFrank Mayhar 		if (unlikely(path[depth].p_hdr == NULL)) {
219091dd8c11SLukas Czerner 			up_read(&EXT4_I(inode)->i_data_sem);
2191273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
21926a797d27SDarrick J. Wong 			err = -EFSCORRUPTED;
2193273df556SFrank Mayhar 			break;
2194273df556SFrank Mayhar 		}
21956873fa0dSEric Sandeen 		ex = path[depth].p_ext;
21966873fa0dSEric Sandeen 		next = ext4_ext_next_allocated_block(path);
21976873fa0dSEric Sandeen 
219891dd8c11SLukas Czerner 		flags = 0;
21996873fa0dSEric Sandeen 		exists = 0;
22006873fa0dSEric Sandeen 		if (!ex) {
22016873fa0dSEric Sandeen 			/* there is no extent yet, so try to allocate
22026873fa0dSEric Sandeen 			 * all requested space */
22036873fa0dSEric Sandeen 			start = block;
22046873fa0dSEric Sandeen 			end = block + num;
22056873fa0dSEric Sandeen 		} else if (le32_to_cpu(ex->ee_block) > block) {
22066873fa0dSEric Sandeen 			/* need to allocate space before found extent */
22076873fa0dSEric Sandeen 			start = block;
22086873fa0dSEric Sandeen 			end = le32_to_cpu(ex->ee_block);
22096873fa0dSEric Sandeen 			if (block + num < end)
22106873fa0dSEric Sandeen 				end = block + num;
22116873fa0dSEric Sandeen 		} else if (block >= le32_to_cpu(ex->ee_block)
22126873fa0dSEric Sandeen 					+ ext4_ext_get_actual_len(ex)) {
22136873fa0dSEric Sandeen 			/* need to allocate space after found extent */
22146873fa0dSEric Sandeen 			start = block;
22156873fa0dSEric Sandeen 			end = block + num;
22166873fa0dSEric Sandeen 			if (end >= next)
22176873fa0dSEric Sandeen 				end = next;
22186873fa0dSEric Sandeen 		} else if (block >= le32_to_cpu(ex->ee_block)) {
22196873fa0dSEric Sandeen 			/*
22206873fa0dSEric Sandeen 			 * some part of requested space is covered
22216873fa0dSEric Sandeen 			 * by found extent
22226873fa0dSEric Sandeen 			 */
22236873fa0dSEric Sandeen 			start = block;
22246873fa0dSEric Sandeen 			end = le32_to_cpu(ex->ee_block)
22256873fa0dSEric Sandeen 				+ ext4_ext_get_actual_len(ex);
22266873fa0dSEric Sandeen 			if (block + num < end)
22276873fa0dSEric Sandeen 				end = block + num;
22286873fa0dSEric Sandeen 			exists = 1;
22296873fa0dSEric Sandeen 		} else {
22306873fa0dSEric Sandeen 			BUG();
22316873fa0dSEric Sandeen 		}
22326873fa0dSEric Sandeen 		BUG_ON(end <= start);
22336873fa0dSEric Sandeen 
22346873fa0dSEric Sandeen 		if (!exists) {
223569eb33dcSZheng Liu 			es.es_lblk = start;
223669eb33dcSZheng Liu 			es.es_len = end - start;
223769eb33dcSZheng Liu 			es.es_pblk = 0;
22386873fa0dSEric Sandeen 		} else {
223969eb33dcSZheng Liu 			es.es_lblk = le32_to_cpu(ex->ee_block);
224069eb33dcSZheng Liu 			es.es_len = ext4_ext_get_actual_len(ex);
224169eb33dcSZheng Liu 			es.es_pblk = ext4_ext_pblock(ex);
2242556615dcSLukas Czerner 			if (ext4_ext_is_unwritten(ex))
224391dd8c11SLukas Czerner 				flags |= FIEMAP_EXTENT_UNWRITTEN;
22446873fa0dSEric Sandeen 		}
22456873fa0dSEric Sandeen 
224691dd8c11SLukas Czerner 		/*
224769eb33dcSZheng Liu 		 * Find delayed extent and update es accordingly. We call
224869eb33dcSZheng Liu 		 * it even in !exists case to find out whether es is the
224991dd8c11SLukas Czerner 		 * last existing extent or not.
225091dd8c11SLukas Czerner 		 */
225169eb33dcSZheng Liu 		next_del = ext4_find_delayed_extent(inode, &es);
225291dd8c11SLukas Czerner 		if (!exists && next_del) {
225391dd8c11SLukas Czerner 			exists = 1;
225472dac95dSJie Liu 			flags |= (FIEMAP_EXTENT_DELALLOC |
225572dac95dSJie Liu 				  FIEMAP_EXTENT_UNKNOWN);
225691dd8c11SLukas Czerner 		}
225791dd8c11SLukas Czerner 		up_read(&EXT4_I(inode)->i_data_sem);
225891dd8c11SLukas Czerner 
225969eb33dcSZheng Liu 		if (unlikely(es.es_len == 0)) {
226069eb33dcSZheng Liu 			EXT4_ERROR_INODE(inode, "es.es_len == 0");
22616a797d27SDarrick J. Wong 			err = -EFSCORRUPTED;
2262273df556SFrank Mayhar 			break;
2263273df556SFrank Mayhar 		}
22646873fa0dSEric Sandeen 
2265f7fec032SZheng Liu 		/*
2266f7fec032SZheng Liu 		 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2267f7fec032SZheng Liu 		 * we need to check next == EXT_MAX_BLOCKS because it is
2268f7fec032SZheng Liu 		 * possible that an extent is with unwritten and delayed
2269f7fec032SZheng Liu 		 * status due to when an extent is delayed allocated and
2270f7fec032SZheng Liu 		 * is allocated by fallocate status tree will track both of
2271f7fec032SZheng Liu 		 * them in a extent.
2272f7fec032SZheng Liu 		 *
2273f7fec032SZheng Liu 		 * So we could return a unwritten and delayed extent, and
2274f7fec032SZheng Liu 		 * its block is equal to 'next'.
2275f7fec032SZheng Liu 		 */
2276f7fec032SZheng Liu 		if (next == next_del && next == EXT_MAX_BLOCKS) {
227791dd8c11SLukas Czerner 			flags |= FIEMAP_EXTENT_LAST;
227891dd8c11SLukas Czerner 			if (unlikely(next_del != EXT_MAX_BLOCKS ||
227991dd8c11SLukas Czerner 				     next != EXT_MAX_BLOCKS)) {
228091dd8c11SLukas Czerner 				EXT4_ERROR_INODE(inode,
228191dd8c11SLukas Czerner 						 "next extent == %u, next "
228291dd8c11SLukas Czerner 						 "delalloc extent = %u",
228391dd8c11SLukas Czerner 						 next, next_del);
22846a797d27SDarrick J. Wong 				err = -EFSCORRUPTED;
228591dd8c11SLukas Czerner 				break;
228691dd8c11SLukas Czerner 			}
228791dd8c11SLukas Czerner 		}
228891dd8c11SLukas Czerner 
228991dd8c11SLukas Czerner 		if (exists) {
229091dd8c11SLukas Czerner 			err = fiemap_fill_next_extent(fieinfo,
229169eb33dcSZheng Liu 				(__u64)es.es_lblk << blksize_bits,
229269eb33dcSZheng Liu 				(__u64)es.es_pblk << blksize_bits,
229369eb33dcSZheng Liu 				(__u64)es.es_len << blksize_bits,
229491dd8c11SLukas Czerner 				flags);
22956873fa0dSEric Sandeen 			if (err < 0)
22966873fa0dSEric Sandeen 				break;
229791dd8c11SLukas Czerner 			if (err == 1) {
22986873fa0dSEric Sandeen 				err = 0;
22996873fa0dSEric Sandeen 				break;
23006873fa0dSEric Sandeen 			}
23016873fa0dSEric Sandeen 		}
23026873fa0dSEric Sandeen 
230369eb33dcSZheng Liu 		block = es.es_lblk + es.es_len;
23046873fa0dSEric Sandeen 	}
23056873fa0dSEric Sandeen 
23066873fa0dSEric Sandeen 	ext4_ext_drop_refs(path);
23076873fa0dSEric Sandeen 	kfree(path);
23086873fa0dSEric Sandeen 	return err;
23096873fa0dSEric Sandeen }
23106873fa0dSEric Sandeen 
2311bb5835edSTheodore Ts'o static int ext4_fill_es_cache_info(struct inode *inode,
2312bb5835edSTheodore Ts'o 				   ext4_lblk_t block, ext4_lblk_t num,
2313bb5835edSTheodore Ts'o 				   struct fiemap_extent_info *fieinfo)
2314bb5835edSTheodore Ts'o {
2315bb5835edSTheodore Ts'o 	ext4_lblk_t next, end = block + num - 1;
2316bb5835edSTheodore Ts'o 	struct extent_status es;
2317bb5835edSTheodore Ts'o 	unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2318bb5835edSTheodore Ts'o 	unsigned int flags;
2319bb5835edSTheodore Ts'o 	int err;
2320bb5835edSTheodore Ts'o 
2321bb5835edSTheodore Ts'o 	while (block <= end) {
2322bb5835edSTheodore Ts'o 		next = 0;
2323bb5835edSTheodore Ts'o 		flags = 0;
2324bb5835edSTheodore Ts'o 		if (!ext4_es_lookup_extent(inode, block, &next, &es))
2325bb5835edSTheodore Ts'o 			break;
2326bb5835edSTheodore Ts'o 		if (ext4_es_is_unwritten(&es))
2327bb5835edSTheodore Ts'o 			flags |= FIEMAP_EXTENT_UNWRITTEN;
2328bb5835edSTheodore Ts'o 		if (ext4_es_is_delayed(&es))
2329bb5835edSTheodore Ts'o 			flags |= (FIEMAP_EXTENT_DELALLOC |
2330bb5835edSTheodore Ts'o 				  FIEMAP_EXTENT_UNKNOWN);
2331bb5835edSTheodore Ts'o 		if (ext4_es_is_hole(&es))
2332bb5835edSTheodore Ts'o 			flags |= EXT4_FIEMAP_EXTENT_HOLE;
2333bb5835edSTheodore Ts'o 		if (next == 0)
2334bb5835edSTheodore Ts'o 			flags |= FIEMAP_EXTENT_LAST;
2335bb5835edSTheodore Ts'o 		if (flags & (FIEMAP_EXTENT_DELALLOC|
2336bb5835edSTheodore Ts'o 			     EXT4_FIEMAP_EXTENT_HOLE))
2337bb5835edSTheodore Ts'o 			es.es_pblk = 0;
2338bb5835edSTheodore Ts'o 		else
2339bb5835edSTheodore Ts'o 			es.es_pblk = ext4_es_pblock(&es);
2340bb5835edSTheodore Ts'o 		err = fiemap_fill_next_extent(fieinfo,
2341bb5835edSTheodore Ts'o 				(__u64)es.es_lblk << blksize_bits,
2342bb5835edSTheodore Ts'o 				(__u64)es.es_pblk << blksize_bits,
2343bb5835edSTheodore Ts'o 				(__u64)es.es_len << blksize_bits,
2344bb5835edSTheodore Ts'o 				flags);
2345bb5835edSTheodore Ts'o 		if (next == 0)
2346bb5835edSTheodore Ts'o 			break;
2347bb5835edSTheodore Ts'o 		block = next;
2348bb5835edSTheodore Ts'o 		if (err < 0)
2349bb5835edSTheodore Ts'o 			return err;
2350bb5835edSTheodore Ts'o 		if (err == 1)
2351bb5835edSTheodore Ts'o 			return 0;
2352bb5835edSTheodore Ts'o 	}
2353bb5835edSTheodore Ts'o 	return 0;
2354bb5835edSTheodore Ts'o }
2355bb5835edSTheodore Ts'o 
2356bb5835edSTheodore Ts'o 
2357a86c6181SAlex Tomas /*
2358140a5250SJan Kara  * ext4_ext_determine_hole - determine hole around given block
2359140a5250SJan Kara  * @inode:	inode we lookup in
2360140a5250SJan Kara  * @path:	path in extent tree to @lblk
2361140a5250SJan Kara  * @lblk:	pointer to logical block around which we want to determine hole
2362140a5250SJan Kara  *
2363140a5250SJan Kara  * Determine hole length (and start if easily possible) around given logical
2364140a5250SJan Kara  * block. We don't try too hard to find the beginning of the hole but @path
2365140a5250SJan Kara  * actually points to extent before @lblk, we provide it.
2366140a5250SJan Kara  *
2367140a5250SJan Kara  * The function returns the length of a hole starting at @lblk. We update @lblk
2368140a5250SJan Kara  * to the beginning of the hole if we managed to find it.
2369140a5250SJan Kara  */
2370140a5250SJan Kara static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2371140a5250SJan Kara 					   struct ext4_ext_path *path,
2372140a5250SJan Kara 					   ext4_lblk_t *lblk)
2373140a5250SJan Kara {
2374140a5250SJan Kara 	int depth = ext_depth(inode);
2375140a5250SJan Kara 	struct ext4_extent *ex;
2376140a5250SJan Kara 	ext4_lblk_t len;
2377140a5250SJan Kara 
2378140a5250SJan Kara 	ex = path[depth].p_ext;
2379140a5250SJan Kara 	if (ex == NULL) {
2380140a5250SJan Kara 		/* there is no extent yet, so gap is [0;-] */
2381140a5250SJan Kara 		*lblk = 0;
2382140a5250SJan Kara 		len = EXT_MAX_BLOCKS;
2383140a5250SJan Kara 	} else if (*lblk < le32_to_cpu(ex->ee_block)) {
2384140a5250SJan Kara 		len = le32_to_cpu(ex->ee_block) - *lblk;
2385140a5250SJan Kara 	} else if (*lblk >= le32_to_cpu(ex->ee_block)
2386140a5250SJan Kara 			+ ext4_ext_get_actual_len(ex)) {
2387140a5250SJan Kara 		ext4_lblk_t next;
2388140a5250SJan Kara 
2389140a5250SJan Kara 		*lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2390140a5250SJan Kara 		next = ext4_ext_next_allocated_block(path);
2391140a5250SJan Kara 		BUG_ON(next == *lblk);
2392140a5250SJan Kara 		len = next - *lblk;
2393140a5250SJan Kara 	} else {
2394140a5250SJan Kara 		BUG();
2395140a5250SJan Kara 	}
2396140a5250SJan Kara 	return len;
2397140a5250SJan Kara }
2398140a5250SJan Kara 
2399140a5250SJan Kara /*
2400d0d856e8SRandy Dunlap  * ext4_ext_put_gap_in_cache:
2401d0d856e8SRandy Dunlap  * calculate boundaries of the gap that the requested block fits into
2402a86c6181SAlex Tomas  * and cache this gap
2403a86c6181SAlex Tomas  */
240409b88252SAvantika Mathur static void
2405140a5250SJan Kara ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2406140a5250SJan Kara 			  ext4_lblk_t hole_len)
2407a86c6181SAlex Tomas {
24082f8e0a7cSZheng Liu 	struct extent_status es;
2409a86c6181SAlex Tomas 
2410ad431025SEric Whitney 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
2411140a5250SJan Kara 				  hole_start + hole_len - 1, &es);
24122f8e0a7cSZheng Liu 	if (es.es_len) {
24132f8e0a7cSZheng Liu 		/* There's delayed extent containing lblock? */
2414140a5250SJan Kara 		if (es.es_lblk <= hole_start)
24152f8e0a7cSZheng Liu 			return;
2416140a5250SJan Kara 		hole_len = min(es.es_lblk - hole_start, hole_len);
24172f8e0a7cSZheng Liu 	}
2418140a5250SJan Kara 	ext_debug(" -> %u:%u\n", hole_start, hole_len);
2419140a5250SJan Kara 	ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2420140a5250SJan Kara 			      EXTENT_STATUS_HOLE);
2421a86c6181SAlex Tomas }
2422a86c6181SAlex Tomas 
2423a86c6181SAlex Tomas /*
2424d0d856e8SRandy Dunlap  * ext4_ext_rm_idx:
2425d0d856e8SRandy Dunlap  * removes index from the index block.
2426a86c6181SAlex Tomas  */
24271d03ec98SAneesh Kumar K.V static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2428c36575e6SForrest Liu 			struct ext4_ext_path *path, int depth)
2429a86c6181SAlex Tomas {
2430a86c6181SAlex Tomas 	int err;
2431f65e6fbaSAlex Tomas 	ext4_fsblk_t leaf;
2432a86c6181SAlex Tomas 
2433a86c6181SAlex Tomas 	/* free index block */
2434c36575e6SForrest Liu 	depth--;
2435c36575e6SForrest Liu 	path = path + depth;
2436bf89d16fSTheodore Ts'o 	leaf = ext4_idx_pblock(path->p_idx);
2437273df556SFrank Mayhar 	if (unlikely(path->p_hdr->eh_entries == 0)) {
2438273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
24396a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
2440273df556SFrank Mayhar 	}
24417e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, path);
24427e028976SAvantika Mathur 	if (err)
2443a86c6181SAlex Tomas 		return err;
24440e1147b0SRobin Dong 
24450e1147b0SRobin Dong 	if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
24460e1147b0SRobin Dong 		int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
24470e1147b0SRobin Dong 		len *= sizeof(struct ext4_extent_idx);
24480e1147b0SRobin Dong 		memmove(path->p_idx, path->p_idx + 1, len);
24490e1147b0SRobin Dong 	}
24500e1147b0SRobin Dong 
2451e8546d06SMarcin Slusarz 	le16_add_cpu(&path->p_hdr->eh_entries, -1);
24527e028976SAvantika Mathur 	err = ext4_ext_dirty(handle, inode, path);
24537e028976SAvantika Mathur 	if (err)
2454a86c6181SAlex Tomas 		return err;
24552ae02107SMingming Cao 	ext_debug("index is empty, remove it, free block %llu\n", leaf);
2456d8990240SAditya Kali 	trace_ext4_ext_rm_idx(inode, leaf);
2457d8990240SAditya Kali 
24587dc57615SPeter Huewe 	ext4_free_blocks(handle, inode, NULL, leaf, 1,
2459e6362609STheodore Ts'o 			 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2460c36575e6SForrest Liu 
2461c36575e6SForrest Liu 	while (--depth >= 0) {
2462c36575e6SForrest Liu 		if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2463c36575e6SForrest Liu 			break;
2464c36575e6SForrest Liu 		path--;
2465c36575e6SForrest Liu 		err = ext4_ext_get_access(handle, inode, path);
2466c36575e6SForrest Liu 		if (err)
2467c36575e6SForrest Liu 			break;
2468c36575e6SForrest Liu 		path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2469c36575e6SForrest Liu 		err = ext4_ext_dirty(handle, inode, path);
2470c36575e6SForrest Liu 		if (err)
2471c36575e6SForrest Liu 			break;
2472c36575e6SForrest Liu 	}
2473a86c6181SAlex Tomas 	return err;
2474a86c6181SAlex Tomas }
2475a86c6181SAlex Tomas 
2476a86c6181SAlex Tomas /*
2477ee12b630SMingming Cao  * ext4_ext_calc_credits_for_single_extent:
2478ee12b630SMingming Cao  * This routine returns max. credits that needed to insert an extent
2479ee12b630SMingming Cao  * to the extent tree.
2480ee12b630SMingming Cao  * When pass the actual path, the caller should calculate credits
2481ee12b630SMingming Cao  * under i_data_sem.
2482a86c6181SAlex Tomas  */
2483525f4ed8SMingming Cao int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2484a86c6181SAlex Tomas 						struct ext4_ext_path *path)
2485a86c6181SAlex Tomas {
2486a86c6181SAlex Tomas 	if (path) {
2487ee12b630SMingming Cao 		int depth = ext_depth(inode);
2488f3bd1f3fSMingming Cao 		int ret = 0;
2489ee12b630SMingming Cao 
2490a86c6181SAlex Tomas 		/* probably there is space in leaf? */
2491a86c6181SAlex Tomas 		if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2492ee12b630SMingming Cao 				< le16_to_cpu(path[depth].p_hdr->eh_max)) {
2493ee12b630SMingming Cao 
2494ee12b630SMingming Cao 			/*
2495ee12b630SMingming Cao 			 *  There are some space in the leaf tree, no
2496ee12b630SMingming Cao 			 *  need to account for leaf block credit
2497ee12b630SMingming Cao 			 *
2498ee12b630SMingming Cao 			 *  bitmaps and block group descriptor blocks
2499df3ab170STao Ma 			 *  and other metadata blocks still need to be
2500ee12b630SMingming Cao 			 *  accounted.
2501ee12b630SMingming Cao 			 */
2502525f4ed8SMingming Cao 			/* 1 bitmap, 1 block group descriptor */
2503ee12b630SMingming Cao 			ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
25045887e98bSAneesh Kumar K.V 			return ret;
2505ee12b630SMingming Cao 		}
2506ee12b630SMingming Cao 	}
2507ee12b630SMingming Cao 
2508525f4ed8SMingming Cao 	return ext4_chunk_trans_blocks(inode, nrblocks);
2509a86c6181SAlex Tomas }
2510a86c6181SAlex Tomas 
2511a86c6181SAlex Tomas /*
2512fffb2739SJan Kara  * How many index/leaf blocks need to change/allocate to add @extents extents?
2513ee12b630SMingming Cao  *
2514fffb2739SJan Kara  * If we add a single extent, then in the worse case, each tree level
2515fffb2739SJan Kara  * index/leaf need to be changed in case of the tree split.
2516ee12b630SMingming Cao  *
2517fffb2739SJan Kara  * If more extents are inserted, they could cause the whole tree split more
2518fffb2739SJan Kara  * than once, but this is really rare.
2519a86c6181SAlex Tomas  */
2520fffb2739SJan Kara int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2521ee12b630SMingming Cao {
2522ee12b630SMingming Cao 	int index;
2523f19d5870STao Ma 	int depth;
2524f19d5870STao Ma 
2525f19d5870STao Ma 	/* If we are converting the inline data, only one is needed here. */
2526f19d5870STao Ma 	if (ext4_has_inline_data(inode))
2527f19d5870STao Ma 		return 1;
2528f19d5870STao Ma 
2529f19d5870STao Ma 	depth = ext_depth(inode);
2530a86c6181SAlex Tomas 
2531fffb2739SJan Kara 	if (extents <= 1)
2532ee12b630SMingming Cao 		index = depth * 2;
2533ee12b630SMingming Cao 	else
2534ee12b630SMingming Cao 		index = depth * 3;
2535a86c6181SAlex Tomas 
2536ee12b630SMingming Cao 	return index;
2537a86c6181SAlex Tomas }
2538a86c6181SAlex Tomas 
2539981250caSTheodore Ts'o static inline int get_default_free_blocks_flags(struct inode *inode)
2540981250caSTheodore Ts'o {
2541ddfa17e4STahsin Erdogan 	if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2542ddfa17e4STahsin Erdogan 	    ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2543981250caSTheodore Ts'o 		return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2544981250caSTheodore Ts'o 	else if (ext4_should_journal_data(inode))
2545981250caSTheodore Ts'o 		return EXT4_FREE_BLOCKS_FORGET;
2546981250caSTheodore Ts'o 	return 0;
2547981250caSTheodore Ts'o }
2548981250caSTheodore Ts'o 
25499fe67149SEric Whitney /*
25509fe67149SEric Whitney  * ext4_rereserve_cluster - increment the reserved cluster count when
25519fe67149SEric Whitney  *                          freeing a cluster with a pending reservation
25529fe67149SEric Whitney  *
25539fe67149SEric Whitney  * @inode - file containing the cluster
25549fe67149SEric Whitney  * @lblk - logical block in cluster to be reserved
25559fe67149SEric Whitney  *
25569fe67149SEric Whitney  * Increments the reserved cluster count and adjusts quota in a bigalloc
25579fe67149SEric Whitney  * file system when freeing a partial cluster containing at least one
25589fe67149SEric Whitney  * delayed and unwritten block.  A partial cluster meeting that
25599fe67149SEric Whitney  * requirement will have a pending reservation.  If so, the
25609fe67149SEric Whitney  * RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
25619fe67149SEric Whitney  * defer reserved and allocated space accounting to a subsequent call
25629fe67149SEric Whitney  * to this function.
25639fe67149SEric Whitney  */
25649fe67149SEric Whitney static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
25659fe67149SEric Whitney {
25669fe67149SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
25679fe67149SEric Whitney 	struct ext4_inode_info *ei = EXT4_I(inode);
25689fe67149SEric Whitney 
25699fe67149SEric Whitney 	dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
25709fe67149SEric Whitney 
25719fe67149SEric Whitney 	spin_lock(&ei->i_block_reservation_lock);
25729fe67149SEric Whitney 	ei->i_reserved_data_blocks++;
25739fe67149SEric Whitney 	percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
25749fe67149SEric Whitney 	spin_unlock(&ei->i_block_reservation_lock);
25759fe67149SEric Whitney 
25769fe67149SEric Whitney 	percpu_counter_add(&sbi->s_freeclusters_counter, 1);
25779fe67149SEric Whitney 	ext4_remove_pending(inode, lblk);
25789fe67149SEric Whitney }
25799fe67149SEric Whitney 
2580a86c6181SAlex Tomas static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2581a86c6181SAlex Tomas 			      struct ext4_extent *ex,
25829fe67149SEric Whitney 			      struct partial_cluster *partial,
2583725d26d3SAneesh Kumar K.V 			      ext4_lblk_t from, ext4_lblk_t to)
2584a86c6181SAlex Tomas {
25850aa06000STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2586a2df2a63SAmit Arora 	unsigned short ee_len = ext4_ext_get_actual_len(ex);
25879fe67149SEric Whitney 	ext4_fsblk_t last_pblk, pblk;
25889fe67149SEric Whitney 	ext4_lblk_t num;
25899fe67149SEric Whitney 	int flags;
259018888cf0SAndrey Sidorov 
25919fe67149SEric Whitney 	/* only extent tail removal is allowed */
25929fe67149SEric Whitney 	if (from < le32_to_cpu(ex->ee_block) ||
25939fe67149SEric Whitney 	    to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
25949fe67149SEric Whitney 		ext4_error(sbi->s_sb,
25959fe67149SEric Whitney 			   "strange request: removal(2) %u-%u from %u:%u",
25969fe67149SEric Whitney 			   from, to, le32_to_cpu(ex->ee_block), ee_len);
25979fe67149SEric Whitney 		return 0;
25980aa06000STheodore Ts'o 	}
25990aa06000STheodore Ts'o 
2600a86c6181SAlex Tomas #ifdef EXTENTS_STATS
2601a86c6181SAlex Tomas 	spin_lock(&sbi->s_ext_stats_lock);
2602a86c6181SAlex Tomas 	sbi->s_ext_blocks += ee_len;
2603a86c6181SAlex Tomas 	sbi->s_ext_extents++;
2604a86c6181SAlex Tomas 	if (ee_len < sbi->s_ext_min)
2605a86c6181SAlex Tomas 		sbi->s_ext_min = ee_len;
2606a86c6181SAlex Tomas 	if (ee_len > sbi->s_ext_max)
2607a86c6181SAlex Tomas 		sbi->s_ext_max = ee_len;
2608a86c6181SAlex Tomas 	if (ext_depth(inode) > sbi->s_depth_max)
2609a86c6181SAlex Tomas 		sbi->s_depth_max = ext_depth(inode);
2610a86c6181SAlex Tomas 	spin_unlock(&sbi->s_ext_stats_lock);
2611a86c6181SAlex Tomas #endif
26129fe67149SEric Whitney 
26139fe67149SEric Whitney 	trace_ext4_remove_blocks(inode, ex, from, to, partial);
26149fe67149SEric Whitney 
26159fe67149SEric Whitney 	/*
26169fe67149SEric Whitney 	 * if we have a partial cluster, and it's different from the
26179fe67149SEric Whitney 	 * cluster of the last block in the extent, we free it
26189fe67149SEric Whitney 	 */
26199fe67149SEric Whitney 	last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
26209fe67149SEric Whitney 
26219fe67149SEric Whitney 	if (partial->state != initial &&
26229fe67149SEric Whitney 	    partial->pclu != EXT4_B2C(sbi, last_pblk)) {
26239fe67149SEric Whitney 		if (partial->state == tofree) {
26249fe67149SEric Whitney 			flags = get_default_free_blocks_flags(inode);
26259fe67149SEric Whitney 			if (ext4_is_pending(inode, partial->lblk))
26269fe67149SEric Whitney 				flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
26279fe67149SEric Whitney 			ext4_free_blocks(handle, inode, NULL,
26289fe67149SEric Whitney 					 EXT4_C2B(sbi, partial->pclu),
26299fe67149SEric Whitney 					 sbi->s_cluster_ratio, flags);
26309fe67149SEric Whitney 			if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
26319fe67149SEric Whitney 				ext4_rereserve_cluster(inode, partial->lblk);
26329fe67149SEric Whitney 		}
26339fe67149SEric Whitney 		partial->state = initial;
26349fe67149SEric Whitney 	}
2635725d26d3SAneesh Kumar K.V 
2636a2df2a63SAmit Arora 	num = le32_to_cpu(ex->ee_block) + ee_len - from;
26370aa06000STheodore Ts'o 	pblk = ext4_ext_pblock(ex) + ee_len - num;
26389fe67149SEric Whitney 
2639d23142c6SLukas Czerner 	/*
26409fe67149SEric Whitney 	 * We free the partial cluster at the end of the extent (if any),
26419fe67149SEric Whitney 	 * unless the cluster is used by another extent (partial_cluster
26429fe67149SEric Whitney 	 * state is nofree).  If a partial cluster exists here, it must be
26439fe67149SEric Whitney 	 * shared with the last block in the extent.
2644d23142c6SLukas Czerner 	 */
26459fe67149SEric Whitney 	flags = get_default_free_blocks_flags(inode);
26469fe67149SEric Whitney 
26479fe67149SEric Whitney 	/* partial, left end cluster aligned, right end unaligned */
26489fe67149SEric Whitney 	if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
26499fe67149SEric Whitney 	    (EXT4_LBLK_CMASK(sbi, to) >= from) &&
26509fe67149SEric Whitney 	    (partial->state != nofree)) {
26519fe67149SEric Whitney 		if (ext4_is_pending(inode, to))
26529fe67149SEric Whitney 			flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
26539fe67149SEric Whitney 		ext4_free_blocks(handle, inode, NULL,
26549fe67149SEric Whitney 				 EXT4_PBLK_CMASK(sbi, last_pblk),
26559fe67149SEric Whitney 				 sbi->s_cluster_ratio, flags);
26569fe67149SEric Whitney 		if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
26579fe67149SEric Whitney 			ext4_rereserve_cluster(inode, to);
26589fe67149SEric Whitney 		partial->state = initial;
26599fe67149SEric Whitney 		flags = get_default_free_blocks_flags(inode);
26609fe67149SEric Whitney 	}
26619fe67149SEric Whitney 
2662d23142c6SLukas Czerner 	flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2663d23142c6SLukas Czerner 
26640aa06000STheodore Ts'o 	/*
26659fe67149SEric Whitney 	 * For bigalloc file systems, we never free a partial cluster
26669fe67149SEric Whitney 	 * at the beginning of the extent.  Instead, we check to see if we
26679fe67149SEric Whitney 	 * need to free it on a subsequent call to ext4_remove_blocks,
26689fe67149SEric Whitney 	 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
26690aa06000STheodore Ts'o 	 */
26709fe67149SEric Whitney 	flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
26719fe67149SEric Whitney 	ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
26729fe67149SEric Whitney 
26739fe67149SEric Whitney 	/* reset the partial cluster if we've freed past it */
26749fe67149SEric Whitney 	if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
26759fe67149SEric Whitney 		partial->state = initial;
26769fe67149SEric Whitney 
26779fe67149SEric Whitney 	/*
26789fe67149SEric Whitney 	 * If we've freed the entire extent but the beginning is not left
26799fe67149SEric Whitney 	 * cluster aligned and is not marked as ineligible for freeing we
26809fe67149SEric Whitney 	 * record the partial cluster at the beginning of the extent.  It
26819fe67149SEric Whitney 	 * wasn't freed by the preceding ext4_free_blocks() call, and we
26829fe67149SEric Whitney 	 * need to look farther to the left to determine if it's to be freed
26839fe67149SEric Whitney 	 * (not shared with another extent). Else, reset the partial
26849fe67149SEric Whitney 	 * cluster - we're either  done freeing or the beginning of the
26859fe67149SEric Whitney 	 * extent is left cluster aligned.
26869fe67149SEric Whitney 	 */
26879fe67149SEric Whitney 	if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
26889fe67149SEric Whitney 		if (partial->state == initial) {
26899fe67149SEric Whitney 			partial->pclu = EXT4_B2C(sbi, pblk);
26909fe67149SEric Whitney 			partial->lblk = from;
26919fe67149SEric Whitney 			partial->state = tofree;
2692345ee947SEric Whitney 		}
26939fe67149SEric Whitney 	} else {
26949fe67149SEric Whitney 		partial->state = initial;
2695a86c6181SAlex Tomas 	}
2696a86c6181SAlex Tomas 
26979fe67149SEric Whitney 	return 0;
26989fe67149SEric Whitney }
2699d583fb87SAllison Henderson 
2700d583fb87SAllison Henderson /*
2701d583fb87SAllison Henderson  * ext4_ext_rm_leaf() Removes the extents associated with the
27025bf43760SEric Whitney  * blocks appearing between "start" and "end".  Both "start"
27035bf43760SEric Whitney  * and "end" must appear in the same extent or EIO is returned.
2704d583fb87SAllison Henderson  *
2705d583fb87SAllison Henderson  * @handle: The journal handle
2706d583fb87SAllison Henderson  * @inode:  The files inode
2707d583fb87SAllison Henderson  * @path:   The path to the leaf
2708d23142c6SLukas Czerner  * @partial_cluster: The cluster which we'll have to free if all extents
27095bf43760SEric Whitney  *                   has been released from it.  However, if this value is
27105bf43760SEric Whitney  *                   negative, it's a cluster just to the right of the
27115bf43760SEric Whitney  *                   punched region and it must not be freed.
2712d583fb87SAllison Henderson  * @start:  The first block to remove
2713d583fb87SAllison Henderson  * @end:   The last block to remove
2714d583fb87SAllison Henderson  */
2715a86c6181SAlex Tomas static int
2716a86c6181SAlex Tomas ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2717d23142c6SLukas Czerner 		 struct ext4_ext_path *path,
27189fe67149SEric Whitney 		 struct partial_cluster *partial,
27190aa06000STheodore Ts'o 		 ext4_lblk_t start, ext4_lblk_t end)
2720a86c6181SAlex Tomas {
27210aa06000STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2722a86c6181SAlex Tomas 	int err = 0, correct_index = 0;
2723a86c6181SAlex Tomas 	int depth = ext_depth(inode), credits;
2724a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
2725750c9c47SDmitry Monakhov 	ext4_lblk_t a, b;
2726725d26d3SAneesh Kumar K.V 	unsigned num;
2727725d26d3SAneesh Kumar K.V 	ext4_lblk_t ex_ee_block;
2728a86c6181SAlex Tomas 	unsigned short ex_ee_len;
2729556615dcSLukas Czerner 	unsigned unwritten = 0;
2730a86c6181SAlex Tomas 	struct ext4_extent *ex;
2731d23142c6SLukas Czerner 	ext4_fsblk_t pblk;
2732a86c6181SAlex Tomas 
2733c29c0ae7SAlex Tomas 	/* the header must be checked already in ext4_ext_remove_space() */
27345f95d21fSLukas Czerner 	ext_debug("truncate since %u in leaf to %u\n", start, end);
2735a86c6181SAlex Tomas 	if (!path[depth].p_hdr)
2736a86c6181SAlex Tomas 		path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2737a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
2738273df556SFrank Mayhar 	if (unlikely(path[depth].p_hdr == NULL)) {
2739273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
27406a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
2741273df556SFrank Mayhar 	}
2742a86c6181SAlex Tomas 	/* find where to start removing */
27436ae06ff5SAshish Sangwan 	ex = path[depth].p_ext;
27446ae06ff5SAshish Sangwan 	if (!ex)
2745a86c6181SAlex Tomas 		ex = EXT_LAST_EXTENT(eh);
2746a86c6181SAlex Tomas 
2747a86c6181SAlex Tomas 	ex_ee_block = le32_to_cpu(ex->ee_block);
2748a2df2a63SAmit Arora 	ex_ee_len = ext4_ext_get_actual_len(ex);
2749a86c6181SAlex Tomas 
27509fe67149SEric Whitney 	trace_ext4_ext_rm_leaf(inode, start, ex, partial);
2751d8990240SAditya Kali 
2752a86c6181SAlex Tomas 	while (ex >= EXT_FIRST_EXTENT(eh) &&
2753a86c6181SAlex Tomas 			ex_ee_block + ex_ee_len > start) {
2754a41f2071SAneesh Kumar K.V 
2755556615dcSLukas Czerner 		if (ext4_ext_is_unwritten(ex))
2756556615dcSLukas Czerner 			unwritten = 1;
2757a41f2071SAneesh Kumar K.V 		else
2758556615dcSLukas Czerner 			unwritten = 0;
2759a41f2071SAneesh Kumar K.V 
2760553f9008SMingming 		ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2761556615dcSLukas Czerner 			  unwritten, ex_ee_len);
2762a86c6181SAlex Tomas 		path[depth].p_ext = ex;
2763a86c6181SAlex Tomas 
2764a86c6181SAlex Tomas 		a = ex_ee_block > start ? ex_ee_block : start;
2765d583fb87SAllison Henderson 		b = ex_ee_block+ex_ee_len - 1 < end ?
2766d583fb87SAllison Henderson 			ex_ee_block+ex_ee_len - 1 : end;
2767a86c6181SAlex Tomas 
2768a86c6181SAlex Tomas 		ext_debug("  border %u:%u\n", a, b);
2769a86c6181SAlex Tomas 
2770d583fb87SAllison Henderson 		/* If this extent is beyond the end of the hole, skip it */
27715f95d21fSLukas Czerner 		if (end < ex_ee_block) {
2772d23142c6SLukas Czerner 			/*
2773d23142c6SLukas Czerner 			 * We're going to skip this extent and move to another,
2774f4226d9eSEric Whitney 			 * so note that its first cluster is in use to avoid
2775f4226d9eSEric Whitney 			 * freeing it when removing blocks.  Eventually, the
2776f4226d9eSEric Whitney 			 * right edge of the truncated/punched region will
2777f4226d9eSEric Whitney 			 * be just to the left.
2778d23142c6SLukas Czerner 			 */
2779f4226d9eSEric Whitney 			if (sbi->s_cluster_ratio > 1) {
2780d23142c6SLukas Czerner 				pblk = ext4_ext_pblock(ex);
27819fe67149SEric Whitney 				partial->pclu = EXT4_B2C(sbi, pblk);
27829fe67149SEric Whitney 				partial->state = nofree;
2783f4226d9eSEric Whitney 			}
2784d583fb87SAllison Henderson 			ex--;
2785d583fb87SAllison Henderson 			ex_ee_block = le32_to_cpu(ex->ee_block);
2786d583fb87SAllison Henderson 			ex_ee_len = ext4_ext_get_actual_len(ex);
2787d583fb87SAllison Henderson 			continue;
2788750c9c47SDmitry Monakhov 		} else if (b != ex_ee_block + ex_ee_len - 1) {
2789dc1841d6SLukas Czerner 			EXT4_ERROR_INODE(inode,
2790dc1841d6SLukas Czerner 					 "can not handle truncate %u:%u "
2791dc1841d6SLukas Czerner 					 "on extent %u:%u",
2792dc1841d6SLukas Czerner 					 start, end, ex_ee_block,
2793dc1841d6SLukas Czerner 					 ex_ee_block + ex_ee_len - 1);
27946a797d27SDarrick J. Wong 			err = -EFSCORRUPTED;
2795d583fb87SAllison Henderson 			goto out;
2796a86c6181SAlex Tomas 		} else if (a != ex_ee_block) {
2797a86c6181SAlex Tomas 			/* remove tail of the extent */
2798750c9c47SDmitry Monakhov 			num = a - ex_ee_block;
2799a86c6181SAlex Tomas 		} else {
2800a86c6181SAlex Tomas 			/* remove whole extent: excellent! */
2801a86c6181SAlex Tomas 			num = 0;
2802d583fb87SAllison Henderson 		}
280334071da7STheodore Ts'o 		/*
280434071da7STheodore Ts'o 		 * 3 for leaf, sb, and inode plus 2 (bmap and group
280534071da7STheodore Ts'o 		 * descriptor) for each block group; assume two block
280634071da7STheodore Ts'o 		 * groups plus ex_ee_len/blocks_per_block_group for
280734071da7STheodore Ts'o 		 * the worst case
280834071da7STheodore Ts'o 		 */
280934071da7STheodore Ts'o 		credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2810a86c6181SAlex Tomas 		if (ex == EXT_FIRST_EXTENT(eh)) {
2811a86c6181SAlex Tomas 			correct_index = 1;
2812a86c6181SAlex Tomas 			credits += (ext_depth(inode)) + 1;
2813a86c6181SAlex Tomas 		}
28145aca07ebSDmitry Monakhov 		credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2815a86c6181SAlex Tomas 
2816487caeefSJan Kara 		err = ext4_ext_truncate_extend_restart(handle, inode, credits);
28179102e4faSShen Feng 		if (err)
2818a86c6181SAlex Tomas 			goto out;
2819a86c6181SAlex Tomas 
2820a86c6181SAlex Tomas 		err = ext4_ext_get_access(handle, inode, path + depth);
2821a86c6181SAlex Tomas 		if (err)
2822a86c6181SAlex Tomas 			goto out;
2823a86c6181SAlex Tomas 
28249fe67149SEric Whitney 		err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
2825a86c6181SAlex Tomas 		if (err)
2826a86c6181SAlex Tomas 			goto out;
2827a86c6181SAlex Tomas 
2828750c9c47SDmitry Monakhov 		if (num == 0)
2829d0d856e8SRandy Dunlap 			/* this extent is removed; mark slot entirely unused */
2830f65e6fbaSAlex Tomas 			ext4_ext_store_pblock(ex, 0);
2831a86c6181SAlex Tomas 
2832a86c6181SAlex Tomas 		ex->ee_len = cpu_to_le16(num);
2833749269faSAmit Arora 		/*
2834556615dcSLukas Czerner 		 * Do not mark unwritten if all the blocks in the
2835749269faSAmit Arora 		 * extent have been removed.
2836749269faSAmit Arora 		 */
2837556615dcSLukas Czerner 		if (unwritten && num)
2838556615dcSLukas Czerner 			ext4_ext_mark_unwritten(ex);
2839d583fb87SAllison Henderson 		/*
2840d583fb87SAllison Henderson 		 * If the extent was completely released,
2841d583fb87SAllison Henderson 		 * we need to remove it from the leaf
2842d583fb87SAllison Henderson 		 */
2843d583fb87SAllison Henderson 		if (num == 0) {
2844f17722f9SLukas Czerner 			if (end != EXT_MAX_BLOCKS - 1) {
2845d583fb87SAllison Henderson 				/*
2846d583fb87SAllison Henderson 				 * For hole punching, we need to scoot all the
2847d583fb87SAllison Henderson 				 * extents up when an extent is removed so that
2848d583fb87SAllison Henderson 				 * we dont have blank extents in the middle
2849d583fb87SAllison Henderson 				 */
2850d583fb87SAllison Henderson 				memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2851d583fb87SAllison Henderson 					sizeof(struct ext4_extent));
2852d583fb87SAllison Henderson 
2853d583fb87SAllison Henderson 				/* Now get rid of the one at the end */
2854d583fb87SAllison Henderson 				memset(EXT_LAST_EXTENT(eh), 0,
2855d583fb87SAllison Henderson 					sizeof(struct ext4_extent));
2856d583fb87SAllison Henderson 			}
2857d583fb87SAllison Henderson 			le16_add_cpu(&eh->eh_entries, -1);
28585bf43760SEric Whitney 		}
2859d583fb87SAllison Henderson 
2860750c9c47SDmitry Monakhov 		err = ext4_ext_dirty(handle, inode, path + depth);
2861750c9c47SDmitry Monakhov 		if (err)
2862750c9c47SDmitry Monakhov 			goto out;
2863750c9c47SDmitry Monakhov 
2864bf52c6f7SYongqiang Yang 		ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2865bf89d16fSTheodore Ts'o 				ext4_ext_pblock(ex));
2866a86c6181SAlex Tomas 		ex--;
2867a86c6181SAlex Tomas 		ex_ee_block = le32_to_cpu(ex->ee_block);
2868a2df2a63SAmit Arora 		ex_ee_len = ext4_ext_get_actual_len(ex);
2869a86c6181SAlex Tomas 	}
2870a86c6181SAlex Tomas 
2871a86c6181SAlex Tomas 	if (correct_index && eh->eh_entries)
2872a86c6181SAlex Tomas 		err = ext4_ext_correct_indexes(handle, inode, path);
2873a86c6181SAlex Tomas 
28740aa06000STheodore Ts'o 	/*
2875ad6599abSEric Whitney 	 * If there's a partial cluster and at least one extent remains in
2876ad6599abSEric Whitney 	 * the leaf, free the partial cluster if it isn't shared with the
28775bf43760SEric Whitney 	 * current extent.  If it is shared with the current extent
28789fe67149SEric Whitney 	 * we reset the partial cluster because we've reached the start of the
28795bf43760SEric Whitney 	 * truncated/punched region and we're done removing blocks.
28800aa06000STheodore Ts'o 	 */
28819fe67149SEric Whitney 	if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
28825bf43760SEric Whitney 		pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
28839fe67149SEric Whitney 		if (partial->pclu != EXT4_B2C(sbi, pblk)) {
28849fe67149SEric Whitney 			int flags = get_default_free_blocks_flags(inode);
28859fe67149SEric Whitney 
28869fe67149SEric Whitney 			if (ext4_is_pending(inode, partial->lblk))
28879fe67149SEric Whitney 				flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
28880aa06000STheodore Ts'o 			ext4_free_blocks(handle, inode, NULL,
28899fe67149SEric Whitney 					 EXT4_C2B(sbi, partial->pclu),
28909fe67149SEric Whitney 					 sbi->s_cluster_ratio, flags);
28919fe67149SEric Whitney 			if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
28929fe67149SEric Whitney 				ext4_rereserve_cluster(inode, partial->lblk);
28935bf43760SEric Whitney 		}
28949fe67149SEric Whitney 		partial->state = initial;
28950aa06000STheodore Ts'o 	}
28960aa06000STheodore Ts'o 
2897a86c6181SAlex Tomas 	/* if this leaf is free, then we should
2898a86c6181SAlex Tomas 	 * remove it from index block above */
2899a86c6181SAlex Tomas 	if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2900c36575e6SForrest Liu 		err = ext4_ext_rm_idx(handle, inode, path, depth);
2901a86c6181SAlex Tomas 
2902a86c6181SAlex Tomas out:
2903a86c6181SAlex Tomas 	return err;
2904a86c6181SAlex Tomas }
2905a86c6181SAlex Tomas 
2906a86c6181SAlex Tomas /*
2907d0d856e8SRandy Dunlap  * ext4_ext_more_to_rm:
2908d0d856e8SRandy Dunlap  * returns 1 if current index has to be freed (even partial)
2909a86c6181SAlex Tomas  */
291009b88252SAvantika Mathur static int
2911a86c6181SAlex Tomas ext4_ext_more_to_rm(struct ext4_ext_path *path)
2912a86c6181SAlex Tomas {
2913a86c6181SAlex Tomas 	BUG_ON(path->p_idx == NULL);
2914a86c6181SAlex Tomas 
2915a86c6181SAlex Tomas 	if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2916a86c6181SAlex Tomas 		return 0;
2917a86c6181SAlex Tomas 
2918a86c6181SAlex Tomas 	/*
2919d0d856e8SRandy Dunlap 	 * if truncate on deeper level happened, it wasn't partial,
2920a86c6181SAlex Tomas 	 * so we have to consider current index for truncation
2921a86c6181SAlex Tomas 	 */
2922a86c6181SAlex Tomas 	if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2923a86c6181SAlex Tomas 		return 0;
2924a86c6181SAlex Tomas 	return 1;
2925a86c6181SAlex Tomas }
2926a86c6181SAlex Tomas 
292726a4c0c6STheodore Ts'o int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
29285f95d21fSLukas Czerner 			  ext4_lblk_t end)
2929a86c6181SAlex Tomas {
2930f4226d9eSEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2931a86c6181SAlex Tomas 	int depth = ext_depth(inode);
2932968dee77SAshish Sangwan 	struct ext4_ext_path *path = NULL;
29339fe67149SEric Whitney 	struct partial_cluster partial;
2934a86c6181SAlex Tomas 	handle_t *handle;
29356f2080e6SDmitry Monakhov 	int i = 0, err = 0;
2936a86c6181SAlex Tomas 
29379fe67149SEric Whitney 	partial.pclu = 0;
29389fe67149SEric Whitney 	partial.lblk = 0;
29399fe67149SEric Whitney 	partial.state = initial;
29409fe67149SEric Whitney 
29415f95d21fSLukas Czerner 	ext_debug("truncate since %u to %u\n", start, end);
2942a86c6181SAlex Tomas 
2943a86c6181SAlex Tomas 	/* probably first extent we're gonna free will be last in block */
29449924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
2945a86c6181SAlex Tomas 	if (IS_ERR(handle))
2946a86c6181SAlex Tomas 		return PTR_ERR(handle);
2947a86c6181SAlex Tomas 
29480617b83fSDmitry Monakhov again:
294961801325SLukas Czerner 	trace_ext4_ext_remove_space(inode, start, end, depth);
2950d8990240SAditya Kali 
2951a86c6181SAlex Tomas 	/*
29525f95d21fSLukas Czerner 	 * Check if we are removing extents inside the extent tree. If that
29535f95d21fSLukas Czerner 	 * is the case, we are going to punch a hole inside the extent tree
29545f95d21fSLukas Czerner 	 * so we have to check whether we need to split the extent covering
29555f95d21fSLukas Czerner 	 * the last block to remove so we can easily remove the part of it
29565f95d21fSLukas Czerner 	 * in ext4_ext_rm_leaf().
29575f95d21fSLukas Czerner 	 */
29585f95d21fSLukas Czerner 	if (end < EXT_MAX_BLOCKS - 1) {
29595f95d21fSLukas Czerner 		struct ext4_extent *ex;
2960f4226d9eSEric Whitney 		ext4_lblk_t ee_block, ex_end, lblk;
2961f4226d9eSEric Whitney 		ext4_fsblk_t pblk;
29625f95d21fSLukas Czerner 
2963f4226d9eSEric Whitney 		/* find extent for or closest extent to this block */
2964ed8a1a76STheodore Ts'o 		path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
29655f95d21fSLukas Czerner 		if (IS_ERR(path)) {
29665f95d21fSLukas Czerner 			ext4_journal_stop(handle);
29675f95d21fSLukas Czerner 			return PTR_ERR(path);
29685f95d21fSLukas Czerner 		}
29695f95d21fSLukas Czerner 		depth = ext_depth(inode);
29706f2080e6SDmitry Monakhov 		/* Leaf not may not exist only if inode has no blocks at all */
29715f95d21fSLukas Czerner 		ex = path[depth].p_ext;
2972968dee77SAshish Sangwan 		if (!ex) {
29736f2080e6SDmitry Monakhov 			if (depth) {
29746f2080e6SDmitry Monakhov 				EXT4_ERROR_INODE(inode,
29756f2080e6SDmitry Monakhov 						 "path[%d].p_hdr == NULL",
29766f2080e6SDmitry Monakhov 						 depth);
29776a797d27SDarrick J. Wong 				err = -EFSCORRUPTED;
29786f2080e6SDmitry Monakhov 			}
29796f2080e6SDmitry Monakhov 			goto out;
2980968dee77SAshish Sangwan 		}
29815f95d21fSLukas Czerner 
29825f95d21fSLukas Czerner 		ee_block = le32_to_cpu(ex->ee_block);
2983f4226d9eSEric Whitney 		ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
29845f95d21fSLukas Czerner 
29855f95d21fSLukas Czerner 		/*
29865f95d21fSLukas Czerner 		 * See if the last block is inside the extent, if so split
29875f95d21fSLukas Czerner 		 * the extent at 'end' block so we can easily remove the
29885f95d21fSLukas Czerner 		 * tail of the first part of the split extent in
29895f95d21fSLukas Czerner 		 * ext4_ext_rm_leaf().
29905f95d21fSLukas Czerner 		 */
2991f4226d9eSEric Whitney 		if (end >= ee_block && end < ex_end) {
2992f4226d9eSEric Whitney 
2993f4226d9eSEric Whitney 			/*
2994f4226d9eSEric Whitney 			 * If we're going to split the extent, note that
2995f4226d9eSEric Whitney 			 * the cluster containing the block after 'end' is
2996f4226d9eSEric Whitney 			 * in use to avoid freeing it when removing blocks.
2997f4226d9eSEric Whitney 			 */
2998f4226d9eSEric Whitney 			if (sbi->s_cluster_ratio > 1) {
2999f4226d9eSEric Whitney 				pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
30009fe67149SEric Whitney 				partial.pclu = EXT4_B2C(sbi, pblk);
30019fe67149SEric Whitney 				partial.state = nofree;
3002f4226d9eSEric Whitney 			}
3003f4226d9eSEric Whitney 
30045f95d21fSLukas Czerner 			/*
30055f95d21fSLukas Czerner 			 * Split the extent in two so that 'end' is the last
300627dd4385SLukas Czerner 			 * block in the first new extent. Also we should not
300727dd4385SLukas Czerner 			 * fail removing space due to ENOSPC so try to use
300827dd4385SLukas Czerner 			 * reserved block if that happens.
30095f95d21fSLukas Czerner 			 */
3010dfe50809STheodore Ts'o 			err = ext4_force_split_extent_at(handle, inode, &path,
3011fcf6b1b7SDmitry Monakhov 							 end + 1, 1);
30125f95d21fSLukas Czerner 			if (err < 0)
30135f95d21fSLukas Czerner 				goto out;
3014f4226d9eSEric Whitney 
30157bd75230SEric Whitney 		} else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
30167bd75230SEric Whitney 			   partial.state == initial) {
3017f4226d9eSEric Whitney 			/*
30187bd75230SEric Whitney 			 * If we're punching, there's an extent to the right.
30197bd75230SEric Whitney 			 * If the partial cluster hasn't been set, set it to
30207bd75230SEric Whitney 			 * that extent's first cluster and its state to nofree
30217bd75230SEric Whitney 			 * so it won't be freed should it contain blocks to be
30227bd75230SEric Whitney 			 * removed. If it's already set (tofree/nofree), we're
30237bd75230SEric Whitney 			 * retrying and keep the original partial cluster info
30247bd75230SEric Whitney 			 * so a cluster marked tofree as a result of earlier
30257bd75230SEric Whitney 			 * extent removal is not lost.
3026f4226d9eSEric Whitney 			 */
3027f4226d9eSEric Whitney 			lblk = ex_end + 1;
3028f4226d9eSEric Whitney 			err = ext4_ext_search_right(inode, path, &lblk, &pblk,
3029f4226d9eSEric Whitney 						    &ex);
3030f4226d9eSEric Whitney 			if (err)
3031f4226d9eSEric Whitney 				goto out;
30329fe67149SEric Whitney 			if (pblk) {
30339fe67149SEric Whitney 				partial.pclu = EXT4_B2C(sbi, pblk);
30349fe67149SEric Whitney 				partial.state = nofree;
30359fe67149SEric Whitney 			}
30365f95d21fSLukas Czerner 		}
30375f95d21fSLukas Czerner 	}
30385f95d21fSLukas Czerner 	/*
3039d0d856e8SRandy Dunlap 	 * We start scanning from right side, freeing all the blocks
3040d0d856e8SRandy Dunlap 	 * after i_size and walking into the tree depth-wise.
3041a86c6181SAlex Tomas 	 */
30420617b83fSDmitry Monakhov 	depth = ext_depth(inode);
3043968dee77SAshish Sangwan 	if (path) {
3044968dee77SAshish Sangwan 		int k = i = depth;
3045968dee77SAshish Sangwan 		while (--k > 0)
3046968dee77SAshish Sangwan 			path[k].p_block =
3047968dee77SAshish Sangwan 				le16_to_cpu(path[k].p_hdr->eh_entries)+1;
3048968dee77SAshish Sangwan 	} else {
30496396bb22SKees Cook 		path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
3050968dee77SAshish Sangwan 			       GFP_NOFS);
3051a86c6181SAlex Tomas 		if (path == NULL) {
3052a86c6181SAlex Tomas 			ext4_journal_stop(handle);
3053a86c6181SAlex Tomas 			return -ENOMEM;
3054a86c6181SAlex Tomas 		}
305510809df8STheodore Ts'o 		path[0].p_maxdepth = path[0].p_depth = depth;
3056a86c6181SAlex Tomas 		path[0].p_hdr = ext_inode_hdr(inode);
305789a4e48fSTheodore Ts'o 		i = 0;
30585f95d21fSLukas Czerner 
3059c349179bSTheodore Ts'o 		if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
30606a797d27SDarrick J. Wong 			err = -EFSCORRUPTED;
3061a86c6181SAlex Tomas 			goto out;
3062a86c6181SAlex Tomas 		}
3063968dee77SAshish Sangwan 	}
3064968dee77SAshish Sangwan 	err = 0;
3065a86c6181SAlex Tomas 
3066a86c6181SAlex Tomas 	while (i >= 0 && err == 0) {
3067a86c6181SAlex Tomas 		if (i == depth) {
3068a86c6181SAlex Tomas 			/* this is leaf block */
3069d583fb87SAllison Henderson 			err = ext4_ext_rm_leaf(handle, inode, path,
30709fe67149SEric Whitney 					       &partial, start, end);
3071d0d856e8SRandy Dunlap 			/* root level has p_bh == NULL, brelse() eats this */
3072a86c6181SAlex Tomas 			brelse(path[i].p_bh);
3073a86c6181SAlex Tomas 			path[i].p_bh = NULL;
3074a86c6181SAlex Tomas 			i--;
3075a86c6181SAlex Tomas 			continue;
3076a86c6181SAlex Tomas 		}
3077a86c6181SAlex Tomas 
3078a86c6181SAlex Tomas 		/* this is index block */
3079a86c6181SAlex Tomas 		if (!path[i].p_hdr) {
3080a86c6181SAlex Tomas 			ext_debug("initialize header\n");
3081a86c6181SAlex Tomas 			path[i].p_hdr = ext_block_hdr(path[i].p_bh);
3082a86c6181SAlex Tomas 		}
3083a86c6181SAlex Tomas 
3084a86c6181SAlex Tomas 		if (!path[i].p_idx) {
3085d0d856e8SRandy Dunlap 			/* this level hasn't been touched yet */
3086a86c6181SAlex Tomas 			path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
3087a86c6181SAlex Tomas 			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
3088a86c6181SAlex Tomas 			ext_debug("init index ptr: hdr 0x%p, num %d\n",
3089a86c6181SAlex Tomas 				  path[i].p_hdr,
3090a86c6181SAlex Tomas 				  le16_to_cpu(path[i].p_hdr->eh_entries));
3091a86c6181SAlex Tomas 		} else {
3092d0d856e8SRandy Dunlap 			/* we were already here, see at next index */
3093a86c6181SAlex Tomas 			path[i].p_idx--;
3094a86c6181SAlex Tomas 		}
3095a86c6181SAlex Tomas 
3096a86c6181SAlex Tomas 		ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
3097a86c6181SAlex Tomas 				i, EXT_FIRST_INDEX(path[i].p_hdr),
3098a86c6181SAlex Tomas 				path[i].p_idx);
3099a86c6181SAlex Tomas 		if (ext4_ext_more_to_rm(path + i)) {
3100c29c0ae7SAlex Tomas 			struct buffer_head *bh;
3101a86c6181SAlex Tomas 			/* go to the next level */
31022ae02107SMingming Cao 			ext_debug("move to level %d (block %llu)\n",
3103bf89d16fSTheodore Ts'o 				  i + 1, ext4_idx_pblock(path[i].p_idx));
3104a86c6181SAlex Tomas 			memset(path + i + 1, 0, sizeof(*path));
31057d7ea89eSTheodore Ts'o 			bh = read_extent_tree_block(inode,
3106107a7bd3STheodore Ts'o 				ext4_idx_pblock(path[i].p_idx), depth - i - 1,
3107107a7bd3STheodore Ts'o 				EXT4_EX_NOCACHE);
31087d7ea89eSTheodore Ts'o 			if (IS_ERR(bh)) {
3109a86c6181SAlex Tomas 				/* should we reset i_size? */
31107d7ea89eSTheodore Ts'o 				err = PTR_ERR(bh);
3111a86c6181SAlex Tomas 				break;
3112a86c6181SAlex Tomas 			}
311376828c88STheodore Ts'o 			/* Yield here to deal with large extent trees.
311476828c88STheodore Ts'o 			 * Should be a no-op if we did IO above. */
311576828c88STheodore Ts'o 			cond_resched();
3116c29c0ae7SAlex Tomas 			if (WARN_ON(i + 1 > depth)) {
31176a797d27SDarrick J. Wong 				err = -EFSCORRUPTED;
3118c29c0ae7SAlex Tomas 				break;
3119c29c0ae7SAlex Tomas 			}
3120c29c0ae7SAlex Tomas 			path[i + 1].p_bh = bh;
3121a86c6181SAlex Tomas 
3122d0d856e8SRandy Dunlap 			/* save actual number of indexes since this
3123d0d856e8SRandy Dunlap 			 * number is changed at the next iteration */
3124a86c6181SAlex Tomas 			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3125a86c6181SAlex Tomas 			i++;
3126a86c6181SAlex Tomas 		} else {
3127d0d856e8SRandy Dunlap 			/* we finished processing this index, go up */
3128a86c6181SAlex Tomas 			if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3129d0d856e8SRandy Dunlap 				/* index is empty, remove it;
3130a86c6181SAlex Tomas 				 * handle must be already prepared by the
3131a86c6181SAlex Tomas 				 * truncatei_leaf() */
3132c36575e6SForrest Liu 				err = ext4_ext_rm_idx(handle, inode, path, i);
3133a86c6181SAlex Tomas 			}
3134d0d856e8SRandy Dunlap 			/* root level has p_bh == NULL, brelse() eats this */
3135a86c6181SAlex Tomas 			brelse(path[i].p_bh);
3136a86c6181SAlex Tomas 			path[i].p_bh = NULL;
3137a86c6181SAlex Tomas 			i--;
3138a86c6181SAlex Tomas 			ext_debug("return to level %d\n", i);
3139a86c6181SAlex Tomas 		}
3140a86c6181SAlex Tomas 	}
3141a86c6181SAlex Tomas 
31429fe67149SEric Whitney 	trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
31439fe67149SEric Whitney 					 path->p_hdr->eh_entries);
3144d8990240SAditya Kali 
31450756b908SEric Whitney 	/*
31469fe67149SEric Whitney 	 * if there's a partial cluster and we have removed the first extent
31479fe67149SEric Whitney 	 * in the file, then we also free the partial cluster, if any
31480756b908SEric Whitney 	 */
31499fe67149SEric Whitney 	if (partial.state == tofree && err == 0) {
31509fe67149SEric Whitney 		int flags = get_default_free_blocks_flags(inode);
31519fe67149SEric Whitney 
31529fe67149SEric Whitney 		if (ext4_is_pending(inode, partial.lblk))
31539fe67149SEric Whitney 			flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
31547b415bf6SAditya Kali 		ext4_free_blocks(handle, inode, NULL,
31559fe67149SEric Whitney 				 EXT4_C2B(sbi, partial.pclu),
31569fe67149SEric Whitney 				 sbi->s_cluster_ratio, flags);
31579fe67149SEric Whitney 		if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
31589fe67149SEric Whitney 			ext4_rereserve_cluster(inode, partial.lblk);
31599fe67149SEric Whitney 		partial.state = initial;
31607b415bf6SAditya Kali 	}
31617b415bf6SAditya Kali 
3162a86c6181SAlex Tomas 	/* TODO: flexible tree reduction should be here */
3163a86c6181SAlex Tomas 	if (path->p_hdr->eh_entries == 0) {
3164a86c6181SAlex Tomas 		/*
3165d0d856e8SRandy Dunlap 		 * truncate to zero freed all the tree,
3166d0d856e8SRandy Dunlap 		 * so we need to correct eh_depth
3167a86c6181SAlex Tomas 		 */
3168a86c6181SAlex Tomas 		err = ext4_ext_get_access(handle, inode, path);
3169a86c6181SAlex Tomas 		if (err == 0) {
3170a86c6181SAlex Tomas 			ext_inode_hdr(inode)->eh_depth = 0;
3171a86c6181SAlex Tomas 			ext_inode_hdr(inode)->eh_max =
317255ad63bfSTheodore Ts'o 				cpu_to_le16(ext4_ext_space_root(inode, 0));
3173a86c6181SAlex Tomas 			err = ext4_ext_dirty(handle, inode, path);
3174a86c6181SAlex Tomas 		}
3175a86c6181SAlex Tomas 	}
3176a86c6181SAlex Tomas out:
3177a86c6181SAlex Tomas 	ext4_ext_drop_refs(path);
3178a86c6181SAlex Tomas 	kfree(path);
3179968dee77SAshish Sangwan 	path = NULL;
3180dfe50809STheodore Ts'o 	if (err == -EAGAIN)
3181dfe50809STheodore Ts'o 		goto again;
3182a86c6181SAlex Tomas 	ext4_journal_stop(handle);
3183a86c6181SAlex Tomas 
3184a86c6181SAlex Tomas 	return err;
3185a86c6181SAlex Tomas }
3186a86c6181SAlex Tomas 
3187a86c6181SAlex Tomas /*
3188a86c6181SAlex Tomas  * called at mount time
3189a86c6181SAlex Tomas  */
3190a86c6181SAlex Tomas void ext4_ext_init(struct super_block *sb)
3191a86c6181SAlex Tomas {
3192a86c6181SAlex Tomas 	/*
3193a86c6181SAlex Tomas 	 * possible initialization would be here
3194a86c6181SAlex Tomas 	 */
3195a86c6181SAlex Tomas 
3196e2b911c5SDarrick J. Wong 	if (ext4_has_feature_extents(sb)) {
319790576c0bSTheodore Ts'o #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
319892b97816STheodore Ts'o 		printk(KERN_INFO "EXT4-fs: file extents enabled"
3199bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
320092b97816STheodore Ts'o 		       ", aggressive tests"
3201a86c6181SAlex Tomas #endif
3202a86c6181SAlex Tomas #ifdef CHECK_BINSEARCH
320392b97816STheodore Ts'o 		       ", check binsearch"
3204a86c6181SAlex Tomas #endif
3205a86c6181SAlex Tomas #ifdef EXTENTS_STATS
320692b97816STheodore Ts'o 		       ", stats"
3207a86c6181SAlex Tomas #endif
320892b97816STheodore Ts'o 		       "\n");
320990576c0bSTheodore Ts'o #endif
3210a86c6181SAlex Tomas #ifdef EXTENTS_STATS
3211a86c6181SAlex Tomas 		spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3212a86c6181SAlex Tomas 		EXT4_SB(sb)->s_ext_min = 1 << 30;
3213a86c6181SAlex Tomas 		EXT4_SB(sb)->s_ext_max = 0;
3214a86c6181SAlex Tomas #endif
3215a86c6181SAlex Tomas 	}
3216a86c6181SAlex Tomas }
3217a86c6181SAlex Tomas 
3218a86c6181SAlex Tomas /*
3219a86c6181SAlex Tomas  * called at umount time
3220a86c6181SAlex Tomas  */
3221a86c6181SAlex Tomas void ext4_ext_release(struct super_block *sb)
3222a86c6181SAlex Tomas {
3223e2b911c5SDarrick J. Wong 	if (!ext4_has_feature_extents(sb))
3224a86c6181SAlex Tomas 		return;
3225a86c6181SAlex Tomas 
3226a86c6181SAlex Tomas #ifdef EXTENTS_STATS
3227a86c6181SAlex Tomas 	if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3228a86c6181SAlex Tomas 		struct ext4_sb_info *sbi = EXT4_SB(sb);
3229a86c6181SAlex Tomas 		printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3230a86c6181SAlex Tomas 			sbi->s_ext_blocks, sbi->s_ext_extents,
3231a86c6181SAlex Tomas 			sbi->s_ext_blocks / sbi->s_ext_extents);
3232a86c6181SAlex Tomas 		printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3233a86c6181SAlex Tomas 			sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3234a86c6181SAlex Tomas 	}
3235a86c6181SAlex Tomas #endif
3236a86c6181SAlex Tomas }
3237a86c6181SAlex Tomas 
3238d7b2a00cSZheng Liu static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3239d7b2a00cSZheng Liu {
3240d7b2a00cSZheng Liu 	ext4_lblk_t  ee_block;
3241d7b2a00cSZheng Liu 	ext4_fsblk_t ee_pblock;
3242d7b2a00cSZheng Liu 	unsigned int ee_len;
3243d7b2a00cSZheng Liu 
3244d7b2a00cSZheng Liu 	ee_block  = le32_to_cpu(ex->ee_block);
3245d7b2a00cSZheng Liu 	ee_len    = ext4_ext_get_actual_len(ex);
3246d7b2a00cSZheng Liu 	ee_pblock = ext4_ext_pblock(ex);
3247d7b2a00cSZheng Liu 
3248d7b2a00cSZheng Liu 	if (ee_len == 0)
3249d7b2a00cSZheng Liu 		return 0;
3250d7b2a00cSZheng Liu 
3251d7b2a00cSZheng Liu 	return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3252d7b2a00cSZheng Liu 				     EXTENT_STATUS_WRITTEN);
3253d7b2a00cSZheng Liu }
3254d7b2a00cSZheng Liu 
3255093a088bSAneesh Kumar K.V /* FIXME!! we need to try to merge to left or right after zero-out  */
3256093a088bSAneesh Kumar K.V static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3257093a088bSAneesh Kumar K.V {
32582407518dSLukas Czerner 	ext4_fsblk_t ee_pblock;
32592407518dSLukas Czerner 	unsigned int ee_len;
3260093a088bSAneesh Kumar K.V 
3261093a088bSAneesh Kumar K.V 	ee_len    = ext4_ext_get_actual_len(ex);
3262bf89d16fSTheodore Ts'o 	ee_pblock = ext4_ext_pblock(ex);
326353085facSJan Kara 	return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
326453085facSJan Kara 				  ee_len);
3265093a088bSAneesh Kumar K.V }
3266093a088bSAneesh Kumar K.V 
326747ea3bb5SYongqiang Yang /*
326847ea3bb5SYongqiang Yang  * ext4_split_extent_at() splits an extent at given block.
326947ea3bb5SYongqiang Yang  *
327047ea3bb5SYongqiang Yang  * @handle: the journal handle
327147ea3bb5SYongqiang Yang  * @inode: the file inode
327247ea3bb5SYongqiang Yang  * @path: the path to the extent
327347ea3bb5SYongqiang Yang  * @split: the logical block where the extent is splitted.
327447ea3bb5SYongqiang Yang  * @split_flags: indicates if the extent could be zeroout if split fails, and
3275556615dcSLukas Czerner  *		 the states(init or unwritten) of new extents.
327647ea3bb5SYongqiang Yang  * @flags: flags used to insert new extent to extent tree.
327747ea3bb5SYongqiang Yang  *
327847ea3bb5SYongqiang Yang  *
327947ea3bb5SYongqiang Yang  * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
328047ea3bb5SYongqiang Yang  * of which are deterimined by split_flag.
328147ea3bb5SYongqiang Yang  *
328247ea3bb5SYongqiang Yang  * There are two cases:
328347ea3bb5SYongqiang Yang  *  a> the extent are splitted into two extent.
328447ea3bb5SYongqiang Yang  *  b> split is not needed, and just mark the extent.
328547ea3bb5SYongqiang Yang  *
328647ea3bb5SYongqiang Yang  * return 0 on success.
328747ea3bb5SYongqiang Yang  */
328847ea3bb5SYongqiang Yang static int ext4_split_extent_at(handle_t *handle,
328947ea3bb5SYongqiang Yang 			     struct inode *inode,
3290dfe50809STheodore Ts'o 			     struct ext4_ext_path **ppath,
329147ea3bb5SYongqiang Yang 			     ext4_lblk_t split,
329247ea3bb5SYongqiang Yang 			     int split_flag,
329347ea3bb5SYongqiang Yang 			     int flags)
329447ea3bb5SYongqiang Yang {
3295dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
329647ea3bb5SYongqiang Yang 	ext4_fsblk_t newblock;
329747ea3bb5SYongqiang Yang 	ext4_lblk_t ee_block;
3298adb23551SZheng Liu 	struct ext4_extent *ex, newex, orig_ex, zero_ex;
329947ea3bb5SYongqiang Yang 	struct ext4_extent *ex2 = NULL;
330047ea3bb5SYongqiang Yang 	unsigned int ee_len, depth;
330147ea3bb5SYongqiang Yang 	int err = 0;
330247ea3bb5SYongqiang Yang 
3303dee1f973SDmitry Monakhov 	BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3304dee1f973SDmitry Monakhov 	       (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3305dee1f973SDmitry Monakhov 
330647ea3bb5SYongqiang Yang 	ext_debug("ext4_split_extents_at: inode %lu, logical"
330747ea3bb5SYongqiang Yang 		"block %llu\n", inode->i_ino, (unsigned long long)split);
330847ea3bb5SYongqiang Yang 
330947ea3bb5SYongqiang Yang 	ext4_ext_show_leaf(inode, path);
331047ea3bb5SYongqiang Yang 
331147ea3bb5SYongqiang Yang 	depth = ext_depth(inode);
331247ea3bb5SYongqiang Yang 	ex = path[depth].p_ext;
331347ea3bb5SYongqiang Yang 	ee_block = le32_to_cpu(ex->ee_block);
331447ea3bb5SYongqiang Yang 	ee_len = ext4_ext_get_actual_len(ex);
331547ea3bb5SYongqiang Yang 	newblock = split - ee_block + ext4_ext_pblock(ex);
331647ea3bb5SYongqiang Yang 
331747ea3bb5SYongqiang Yang 	BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3318556615dcSLukas Czerner 	BUG_ON(!ext4_ext_is_unwritten(ex) &&
3319357b66fdSDmitry Monakhov 	       split_flag & (EXT4_EXT_MAY_ZEROOUT |
3320556615dcSLukas Czerner 			     EXT4_EXT_MARK_UNWRIT1 |
3321556615dcSLukas Czerner 			     EXT4_EXT_MARK_UNWRIT2));
332247ea3bb5SYongqiang Yang 
332347ea3bb5SYongqiang Yang 	err = ext4_ext_get_access(handle, inode, path + depth);
332447ea3bb5SYongqiang Yang 	if (err)
332547ea3bb5SYongqiang Yang 		goto out;
332647ea3bb5SYongqiang Yang 
332747ea3bb5SYongqiang Yang 	if (split == ee_block) {
332847ea3bb5SYongqiang Yang 		/*
332947ea3bb5SYongqiang Yang 		 * case b: block @split is the block that the extent begins with
333047ea3bb5SYongqiang Yang 		 * then we just change the state of the extent, and splitting
333147ea3bb5SYongqiang Yang 		 * is not needed.
333247ea3bb5SYongqiang Yang 		 */
3333556615dcSLukas Czerner 		if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3334556615dcSLukas Czerner 			ext4_ext_mark_unwritten(ex);
333547ea3bb5SYongqiang Yang 		else
333647ea3bb5SYongqiang Yang 			ext4_ext_mark_initialized(ex);
333747ea3bb5SYongqiang Yang 
333847ea3bb5SYongqiang Yang 		if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3339ecb94f5fSTheodore Ts'o 			ext4_ext_try_to_merge(handle, inode, path, ex);
334047ea3bb5SYongqiang Yang 
3341ecb94f5fSTheodore Ts'o 		err = ext4_ext_dirty(handle, inode, path + path->p_depth);
334247ea3bb5SYongqiang Yang 		goto out;
334347ea3bb5SYongqiang Yang 	}
334447ea3bb5SYongqiang Yang 
334547ea3bb5SYongqiang Yang 	/* case a */
334647ea3bb5SYongqiang Yang 	memcpy(&orig_ex, ex, sizeof(orig_ex));
334747ea3bb5SYongqiang Yang 	ex->ee_len = cpu_to_le16(split - ee_block);
3348556615dcSLukas Czerner 	if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3349556615dcSLukas Czerner 		ext4_ext_mark_unwritten(ex);
335047ea3bb5SYongqiang Yang 
335147ea3bb5SYongqiang Yang 	/*
335247ea3bb5SYongqiang Yang 	 * path may lead to new leaf, not to original leaf any more
335347ea3bb5SYongqiang Yang 	 * after ext4_ext_insert_extent() returns,
335447ea3bb5SYongqiang Yang 	 */
335547ea3bb5SYongqiang Yang 	err = ext4_ext_dirty(handle, inode, path + depth);
335647ea3bb5SYongqiang Yang 	if (err)
335747ea3bb5SYongqiang Yang 		goto fix_extent_len;
335847ea3bb5SYongqiang Yang 
335947ea3bb5SYongqiang Yang 	ex2 = &newex;
336047ea3bb5SYongqiang Yang 	ex2->ee_block = cpu_to_le32(split);
336147ea3bb5SYongqiang Yang 	ex2->ee_len   = cpu_to_le16(ee_len - (split - ee_block));
336247ea3bb5SYongqiang Yang 	ext4_ext_store_pblock(ex2, newblock);
3363556615dcSLukas Czerner 	if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3364556615dcSLukas Czerner 		ext4_ext_mark_unwritten(ex2);
336547ea3bb5SYongqiang Yang 
3366dfe50809STheodore Ts'o 	err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
336747ea3bb5SYongqiang Yang 	if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3368dee1f973SDmitry Monakhov 		if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3369adb23551SZheng Liu 			if (split_flag & EXT4_EXT_DATA_VALID1) {
3370dee1f973SDmitry Monakhov 				err = ext4_ext_zeroout(inode, ex2);
3371adb23551SZheng Liu 				zero_ex.ee_block = ex2->ee_block;
33728cde7ad1SZheng Liu 				zero_ex.ee_len = cpu_to_le16(
33738cde7ad1SZheng Liu 						ext4_ext_get_actual_len(ex2));
3374adb23551SZheng Liu 				ext4_ext_store_pblock(&zero_ex,
3375adb23551SZheng Liu 						      ext4_ext_pblock(ex2));
3376adb23551SZheng Liu 			} else {
3377dee1f973SDmitry Monakhov 				err = ext4_ext_zeroout(inode, ex);
3378adb23551SZheng Liu 				zero_ex.ee_block = ex->ee_block;
33798cde7ad1SZheng Liu 				zero_ex.ee_len = cpu_to_le16(
33808cde7ad1SZheng Liu 						ext4_ext_get_actual_len(ex));
3381adb23551SZheng Liu 				ext4_ext_store_pblock(&zero_ex,
3382adb23551SZheng Liu 						      ext4_ext_pblock(ex));
3383adb23551SZheng Liu 			}
3384adb23551SZheng Liu 		} else {
338547ea3bb5SYongqiang Yang 			err = ext4_ext_zeroout(inode, &orig_ex);
3386adb23551SZheng Liu 			zero_ex.ee_block = orig_ex.ee_block;
33878cde7ad1SZheng Liu 			zero_ex.ee_len = cpu_to_le16(
33888cde7ad1SZheng Liu 						ext4_ext_get_actual_len(&orig_ex));
3389adb23551SZheng Liu 			ext4_ext_store_pblock(&zero_ex,
3390adb23551SZheng Liu 					      ext4_ext_pblock(&orig_ex));
3391adb23551SZheng Liu 		}
3392dee1f973SDmitry Monakhov 
339347ea3bb5SYongqiang Yang 		if (err)
339447ea3bb5SYongqiang Yang 			goto fix_extent_len;
339547ea3bb5SYongqiang Yang 		/* update the extent length and mark as initialized */
3396af1584f5SAl Viro 		ex->ee_len = cpu_to_le16(ee_len);
3397ecb94f5fSTheodore Ts'o 		ext4_ext_try_to_merge(handle, inode, path, ex);
3398ecb94f5fSTheodore Ts'o 		err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3399adb23551SZheng Liu 		if (err)
3400adb23551SZheng Liu 			goto fix_extent_len;
3401adb23551SZheng Liu 
3402adb23551SZheng Liu 		/* update extent status tree */
3403d7b2a00cSZheng Liu 		err = ext4_zeroout_es(inode, &zero_ex);
3404adb23551SZheng Liu 
340547ea3bb5SYongqiang Yang 		goto out;
340647ea3bb5SYongqiang Yang 	} else if (err)
340747ea3bb5SYongqiang Yang 		goto fix_extent_len;
340847ea3bb5SYongqiang Yang 
340947ea3bb5SYongqiang Yang out:
341047ea3bb5SYongqiang Yang 	ext4_ext_show_leaf(inode, path);
341147ea3bb5SYongqiang Yang 	return err;
341247ea3bb5SYongqiang Yang 
341347ea3bb5SYongqiang Yang fix_extent_len:
341447ea3bb5SYongqiang Yang 	ex->ee_len = orig_ex.ee_len;
341529faed16SDmitry Monakhov 	ext4_ext_dirty(handle, inode, path + path->p_depth);
341647ea3bb5SYongqiang Yang 	return err;
341747ea3bb5SYongqiang Yang }
341847ea3bb5SYongqiang Yang 
341947ea3bb5SYongqiang Yang /*
342047ea3bb5SYongqiang Yang  * ext4_split_extents() splits an extent and mark extent which is covered
342147ea3bb5SYongqiang Yang  * by @map as split_flags indicates
342247ea3bb5SYongqiang Yang  *
342347ea3bb5SYongqiang Yang  * It may result in splitting the extent into multiple extents (up to three)
342447ea3bb5SYongqiang Yang  * There are three possibilities:
342547ea3bb5SYongqiang Yang  *   a> There is no split required
342647ea3bb5SYongqiang Yang  *   b> Splits in two extents: Split is happening at either end of the extent
342747ea3bb5SYongqiang Yang  *   c> Splits in three extents: Somone is splitting in middle of the extent
342847ea3bb5SYongqiang Yang  *
342947ea3bb5SYongqiang Yang  */
343047ea3bb5SYongqiang Yang static int ext4_split_extent(handle_t *handle,
343147ea3bb5SYongqiang Yang 			      struct inode *inode,
3432dfe50809STheodore Ts'o 			      struct ext4_ext_path **ppath,
343347ea3bb5SYongqiang Yang 			      struct ext4_map_blocks *map,
343447ea3bb5SYongqiang Yang 			      int split_flag,
343547ea3bb5SYongqiang Yang 			      int flags)
343647ea3bb5SYongqiang Yang {
3437dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
343847ea3bb5SYongqiang Yang 	ext4_lblk_t ee_block;
343947ea3bb5SYongqiang Yang 	struct ext4_extent *ex;
344047ea3bb5SYongqiang Yang 	unsigned int ee_len, depth;
344147ea3bb5SYongqiang Yang 	int err = 0;
3442556615dcSLukas Czerner 	int unwritten;
344347ea3bb5SYongqiang Yang 	int split_flag1, flags1;
34443a225670SZheng Liu 	int allocated = map->m_len;
344547ea3bb5SYongqiang Yang 
344647ea3bb5SYongqiang Yang 	depth = ext_depth(inode);
344747ea3bb5SYongqiang Yang 	ex = path[depth].p_ext;
344847ea3bb5SYongqiang Yang 	ee_block = le32_to_cpu(ex->ee_block);
344947ea3bb5SYongqiang Yang 	ee_len = ext4_ext_get_actual_len(ex);
3450556615dcSLukas Czerner 	unwritten = ext4_ext_is_unwritten(ex);
345147ea3bb5SYongqiang Yang 
345247ea3bb5SYongqiang Yang 	if (map->m_lblk + map->m_len < ee_block + ee_len) {
3453dee1f973SDmitry Monakhov 		split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
345447ea3bb5SYongqiang Yang 		flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3455556615dcSLukas Czerner 		if (unwritten)
3456556615dcSLukas Czerner 			split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3457556615dcSLukas Czerner 				       EXT4_EXT_MARK_UNWRIT2;
3458dee1f973SDmitry Monakhov 		if (split_flag & EXT4_EXT_DATA_VALID2)
3459dee1f973SDmitry Monakhov 			split_flag1 |= EXT4_EXT_DATA_VALID1;
3460dfe50809STheodore Ts'o 		err = ext4_split_extent_at(handle, inode, ppath,
346147ea3bb5SYongqiang Yang 				map->m_lblk + map->m_len, split_flag1, flags1);
346293917411SYongqiang Yang 		if (err)
346393917411SYongqiang Yang 			goto out;
34643a225670SZheng Liu 	} else {
34653a225670SZheng Liu 		allocated = ee_len - (map->m_lblk - ee_block);
346647ea3bb5SYongqiang Yang 	}
3467357b66fdSDmitry Monakhov 	/*
3468357b66fdSDmitry Monakhov 	 * Update path is required because previous ext4_split_extent_at() may
3469357b66fdSDmitry Monakhov 	 * result in split of original leaf or extent zeroout.
3470357b66fdSDmitry Monakhov 	 */
3471ed8a1a76STheodore Ts'o 	path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
347247ea3bb5SYongqiang Yang 	if (IS_ERR(path))
347347ea3bb5SYongqiang Yang 		return PTR_ERR(path);
3474357b66fdSDmitry Monakhov 	depth = ext_depth(inode);
3475357b66fdSDmitry Monakhov 	ex = path[depth].p_ext;
3476a18ed359SDmitry Monakhov 	if (!ex) {
3477a18ed359SDmitry Monakhov 		EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3478a18ed359SDmitry Monakhov 				 (unsigned long) map->m_lblk);
34796a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
3480a18ed359SDmitry Monakhov 	}
3481556615dcSLukas Czerner 	unwritten = ext4_ext_is_unwritten(ex);
3482357b66fdSDmitry Monakhov 	split_flag1 = 0;
348347ea3bb5SYongqiang Yang 
348447ea3bb5SYongqiang Yang 	if (map->m_lblk >= ee_block) {
3485357b66fdSDmitry Monakhov 		split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3486556615dcSLukas Czerner 		if (unwritten) {
3487556615dcSLukas Czerner 			split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3488357b66fdSDmitry Monakhov 			split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3489556615dcSLukas Czerner 						     EXT4_EXT_MARK_UNWRIT2);
3490357b66fdSDmitry Monakhov 		}
3491dfe50809STheodore Ts'o 		err = ext4_split_extent_at(handle, inode, ppath,
349247ea3bb5SYongqiang Yang 				map->m_lblk, split_flag1, flags);
349347ea3bb5SYongqiang Yang 		if (err)
349447ea3bb5SYongqiang Yang 			goto out;
349547ea3bb5SYongqiang Yang 	}
349647ea3bb5SYongqiang Yang 
349747ea3bb5SYongqiang Yang 	ext4_ext_show_leaf(inode, path);
349847ea3bb5SYongqiang Yang out:
34993a225670SZheng Liu 	return err ? err : allocated;
350047ea3bb5SYongqiang Yang }
350147ea3bb5SYongqiang Yang 
350256055d3aSAmit Arora /*
3503e35fd660STheodore Ts'o  * This function is called by ext4_ext_map_blocks() if someone tries to write
3504556615dcSLukas Czerner  * to an unwritten extent. It may result in splitting the unwritten
350556055d3aSAmit Arora  * extent into multiple extents (up to three - one initialized and two
3506556615dcSLukas Czerner  * unwritten).
350756055d3aSAmit Arora  * There are three possibilities:
350856055d3aSAmit Arora  *   a> There is no split required: Entire extent should be initialized
350956055d3aSAmit Arora  *   b> Splits in two extents: Write is happening at either end of the extent
351056055d3aSAmit Arora  *   c> Splits in three extents: Somone is writing in middle of the extent
35116f91bc5fSEric Gouriou  *
35126f91bc5fSEric Gouriou  * Pre-conditions:
3513556615dcSLukas Czerner  *  - The extent pointed to by 'path' is unwritten.
35146f91bc5fSEric Gouriou  *  - The extent pointed to by 'path' contains a superset
35156f91bc5fSEric Gouriou  *    of the logical span [map->m_lblk, map->m_lblk + map->m_len).
35166f91bc5fSEric Gouriou  *
35176f91bc5fSEric Gouriou  * Post-conditions on success:
35186f91bc5fSEric Gouriou  *  - the returned value is the number of blocks beyond map->l_lblk
35196f91bc5fSEric Gouriou  *    that are allocated and initialized.
35206f91bc5fSEric Gouriou  *    It is guaranteed to be >= map->m_len.
352156055d3aSAmit Arora  */
3522725d26d3SAneesh Kumar K.V static int ext4_ext_convert_to_initialized(handle_t *handle,
3523725d26d3SAneesh Kumar K.V 					   struct inode *inode,
3524e35fd660STheodore Ts'o 					   struct ext4_map_blocks *map,
3525dfe50809STheodore Ts'o 					   struct ext4_ext_path **ppath,
352627dd4385SLukas Czerner 					   int flags)
352756055d3aSAmit Arora {
3528dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
352967a5da56SZheng Liu 	struct ext4_sb_info *sbi;
35306f91bc5fSEric Gouriou 	struct ext4_extent_header *eh;
3531667eff35SYongqiang Yang 	struct ext4_map_blocks split_map;
35324f8caa60SJan Kara 	struct ext4_extent zero_ex1, zero_ex2;
3533bc2d9db4SLukas Czerner 	struct ext4_extent *ex, *abut_ex;
353421ca087aSDmitry Monakhov 	ext4_lblk_t ee_block, eof_block;
3535bc2d9db4SLukas Czerner 	unsigned int ee_len, depth, map_len = map->m_len;
3536bc2d9db4SLukas Czerner 	int allocated = 0, max_zeroout = 0;
353756055d3aSAmit Arora 	int err = 0;
35384f8caa60SJan Kara 	int split_flag = EXT4_EXT_DATA_VALID2;
353921ca087aSDmitry Monakhov 
354021ca087aSDmitry Monakhov 	ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
354121ca087aSDmitry Monakhov 		"block %llu, max_blocks %u\n", inode->i_ino,
3542bc2d9db4SLukas Czerner 		(unsigned long long)map->m_lblk, map_len);
354321ca087aSDmitry Monakhov 
354467a5da56SZheng Liu 	sbi = EXT4_SB(inode->i_sb);
354521ca087aSDmitry Monakhov 	eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
354621ca087aSDmitry Monakhov 		inode->i_sb->s_blocksize_bits;
3547bc2d9db4SLukas Czerner 	if (eof_block < map->m_lblk + map_len)
3548bc2d9db4SLukas Czerner 		eof_block = map->m_lblk + map_len;
354956055d3aSAmit Arora 
355056055d3aSAmit Arora 	depth = ext_depth(inode);
35516f91bc5fSEric Gouriou 	eh = path[depth].p_hdr;
355256055d3aSAmit Arora 	ex = path[depth].p_ext;
355356055d3aSAmit Arora 	ee_block = le32_to_cpu(ex->ee_block);
355456055d3aSAmit Arora 	ee_len = ext4_ext_get_actual_len(ex);
35554f8caa60SJan Kara 	zero_ex1.ee_len = 0;
35564f8caa60SJan Kara 	zero_ex2.ee_len = 0;
355721ca087aSDmitry Monakhov 
35586f91bc5fSEric Gouriou 	trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
35596f91bc5fSEric Gouriou 
35606f91bc5fSEric Gouriou 	/* Pre-conditions */
3561556615dcSLukas Czerner 	BUG_ON(!ext4_ext_is_unwritten(ex));
35626f91bc5fSEric Gouriou 	BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
35636f91bc5fSEric Gouriou 
35646f91bc5fSEric Gouriou 	/*
35656f91bc5fSEric Gouriou 	 * Attempt to transfer newly initialized blocks from the currently
3566556615dcSLukas Czerner 	 * unwritten extent to its neighbor. This is much cheaper
35676f91bc5fSEric Gouriou 	 * than an insertion followed by a merge as those involve costly
3568bc2d9db4SLukas Czerner 	 * memmove() calls. Transferring to the left is the common case in
3569bc2d9db4SLukas Czerner 	 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3570bc2d9db4SLukas Czerner 	 * followed by append writes.
35716f91bc5fSEric Gouriou 	 *
35726f91bc5fSEric Gouriou 	 * Limitations of the current logic:
3573bc2d9db4SLukas Czerner 	 *  - L1: we do not deal with writes covering the whole extent.
35746f91bc5fSEric Gouriou 	 *    This would require removing the extent if the transfer
35756f91bc5fSEric Gouriou 	 *    is possible.
3576bc2d9db4SLukas Czerner 	 *  - L2: we only attempt to merge with an extent stored in the
35776f91bc5fSEric Gouriou 	 *    same extent tree node.
35786f91bc5fSEric Gouriou 	 */
3579bc2d9db4SLukas Czerner 	if ((map->m_lblk == ee_block) &&
3580bc2d9db4SLukas Czerner 		/* See if we can merge left */
3581bc2d9db4SLukas Czerner 		(map_len < ee_len) &&		/*L1*/
3582bc2d9db4SLukas Czerner 		(ex > EXT_FIRST_EXTENT(eh))) {	/*L2*/
35836f91bc5fSEric Gouriou 		ext4_lblk_t prev_lblk;
35846f91bc5fSEric Gouriou 		ext4_fsblk_t prev_pblk, ee_pblk;
3585bc2d9db4SLukas Czerner 		unsigned int prev_len;
35866f91bc5fSEric Gouriou 
3587bc2d9db4SLukas Czerner 		abut_ex = ex - 1;
3588bc2d9db4SLukas Czerner 		prev_lblk = le32_to_cpu(abut_ex->ee_block);
3589bc2d9db4SLukas Czerner 		prev_len = ext4_ext_get_actual_len(abut_ex);
3590bc2d9db4SLukas Czerner 		prev_pblk = ext4_ext_pblock(abut_ex);
35916f91bc5fSEric Gouriou 		ee_pblk = ext4_ext_pblock(ex);
35926f91bc5fSEric Gouriou 
35936f91bc5fSEric Gouriou 		/*
3594bc2d9db4SLukas Czerner 		 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
35956f91bc5fSEric Gouriou 		 * upon those conditions:
3596bc2d9db4SLukas Czerner 		 * - C1: abut_ex is initialized,
3597bc2d9db4SLukas Czerner 		 * - C2: abut_ex is logically abutting ex,
3598bc2d9db4SLukas Czerner 		 * - C3: abut_ex is physically abutting ex,
3599bc2d9db4SLukas Czerner 		 * - C4: abut_ex can receive the additional blocks without
36006f91bc5fSEric Gouriou 		 *   overflowing the (initialized) length limit.
36016f91bc5fSEric Gouriou 		 */
3602556615dcSLukas Czerner 		if ((!ext4_ext_is_unwritten(abut_ex)) &&		/*C1*/
36036f91bc5fSEric Gouriou 			((prev_lblk + prev_len) == ee_block) &&		/*C2*/
36046f91bc5fSEric Gouriou 			((prev_pblk + prev_len) == ee_pblk) &&		/*C3*/
3605bc2d9db4SLukas Czerner 			(prev_len < (EXT_INIT_MAX_LEN - map_len))) {	/*C4*/
36066f91bc5fSEric Gouriou 			err = ext4_ext_get_access(handle, inode, path + depth);
36076f91bc5fSEric Gouriou 			if (err)
36086f91bc5fSEric Gouriou 				goto out;
36096f91bc5fSEric Gouriou 
36106f91bc5fSEric Gouriou 			trace_ext4_ext_convert_to_initialized_fastpath(inode,
3611bc2d9db4SLukas Czerner 				map, ex, abut_ex);
36126f91bc5fSEric Gouriou 
3613bc2d9db4SLukas Czerner 			/* Shift the start of ex by 'map_len' blocks */
3614bc2d9db4SLukas Czerner 			ex->ee_block = cpu_to_le32(ee_block + map_len);
3615bc2d9db4SLukas Czerner 			ext4_ext_store_pblock(ex, ee_pblk + map_len);
3616bc2d9db4SLukas Czerner 			ex->ee_len = cpu_to_le16(ee_len - map_len);
3617556615dcSLukas Czerner 			ext4_ext_mark_unwritten(ex); /* Restore the flag */
36186f91bc5fSEric Gouriou 
3619bc2d9db4SLukas Czerner 			/* Extend abut_ex by 'map_len' blocks */
3620bc2d9db4SLukas Czerner 			abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
36216f91bc5fSEric Gouriou 
3622bc2d9db4SLukas Czerner 			/* Result: number of initialized blocks past m_lblk */
3623bc2d9db4SLukas Czerner 			allocated = map_len;
3624bc2d9db4SLukas Czerner 		}
3625bc2d9db4SLukas Czerner 	} else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3626bc2d9db4SLukas Czerner 		   (map_len < ee_len) &&	/*L1*/
3627bc2d9db4SLukas Czerner 		   ex < EXT_LAST_EXTENT(eh)) {	/*L2*/
3628bc2d9db4SLukas Czerner 		/* See if we can merge right */
3629bc2d9db4SLukas Czerner 		ext4_lblk_t next_lblk;
3630bc2d9db4SLukas Czerner 		ext4_fsblk_t next_pblk, ee_pblk;
3631bc2d9db4SLukas Czerner 		unsigned int next_len;
3632bc2d9db4SLukas Czerner 
3633bc2d9db4SLukas Czerner 		abut_ex = ex + 1;
3634bc2d9db4SLukas Czerner 		next_lblk = le32_to_cpu(abut_ex->ee_block);
3635bc2d9db4SLukas Czerner 		next_len = ext4_ext_get_actual_len(abut_ex);
3636bc2d9db4SLukas Czerner 		next_pblk = ext4_ext_pblock(abut_ex);
3637bc2d9db4SLukas Czerner 		ee_pblk = ext4_ext_pblock(ex);
3638bc2d9db4SLukas Czerner 
3639bc2d9db4SLukas Czerner 		/*
3640bc2d9db4SLukas Czerner 		 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3641bc2d9db4SLukas Czerner 		 * upon those conditions:
3642bc2d9db4SLukas Czerner 		 * - C1: abut_ex is initialized,
3643bc2d9db4SLukas Czerner 		 * - C2: abut_ex is logically abutting ex,
3644bc2d9db4SLukas Czerner 		 * - C3: abut_ex is physically abutting ex,
3645bc2d9db4SLukas Czerner 		 * - C4: abut_ex can receive the additional blocks without
3646bc2d9db4SLukas Czerner 		 *   overflowing the (initialized) length limit.
3647bc2d9db4SLukas Czerner 		 */
3648556615dcSLukas Czerner 		if ((!ext4_ext_is_unwritten(abut_ex)) &&		/*C1*/
3649bc2d9db4SLukas Czerner 		    ((map->m_lblk + map_len) == next_lblk) &&		/*C2*/
3650bc2d9db4SLukas Czerner 		    ((ee_pblk + ee_len) == next_pblk) &&		/*C3*/
3651bc2d9db4SLukas Czerner 		    (next_len < (EXT_INIT_MAX_LEN - map_len))) {	/*C4*/
3652bc2d9db4SLukas Czerner 			err = ext4_ext_get_access(handle, inode, path + depth);
3653bc2d9db4SLukas Czerner 			if (err)
3654bc2d9db4SLukas Czerner 				goto out;
3655bc2d9db4SLukas Czerner 
3656bc2d9db4SLukas Czerner 			trace_ext4_ext_convert_to_initialized_fastpath(inode,
3657bc2d9db4SLukas Czerner 				map, ex, abut_ex);
3658bc2d9db4SLukas Czerner 
3659bc2d9db4SLukas Czerner 			/* Shift the start of abut_ex by 'map_len' blocks */
3660bc2d9db4SLukas Czerner 			abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3661bc2d9db4SLukas Czerner 			ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3662bc2d9db4SLukas Czerner 			ex->ee_len = cpu_to_le16(ee_len - map_len);
3663556615dcSLukas Czerner 			ext4_ext_mark_unwritten(ex); /* Restore the flag */
3664bc2d9db4SLukas Czerner 
3665bc2d9db4SLukas Czerner 			/* Extend abut_ex by 'map_len' blocks */
3666bc2d9db4SLukas Czerner 			abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3667bc2d9db4SLukas Czerner 
3668bc2d9db4SLukas Czerner 			/* Result: number of initialized blocks past m_lblk */
3669bc2d9db4SLukas Czerner 			allocated = map_len;
3670bc2d9db4SLukas Czerner 		}
3671bc2d9db4SLukas Czerner 	}
3672bc2d9db4SLukas Czerner 	if (allocated) {
36736f91bc5fSEric Gouriou 		/* Mark the block containing both extents as dirty */
36746f91bc5fSEric Gouriou 		ext4_ext_dirty(handle, inode, path + depth);
36756f91bc5fSEric Gouriou 
36766f91bc5fSEric Gouriou 		/* Update path to point to the right extent */
3677bc2d9db4SLukas Czerner 		path[depth].p_ext = abut_ex;
36786f91bc5fSEric Gouriou 		goto out;
3679bc2d9db4SLukas Czerner 	} else
3680bc2d9db4SLukas Czerner 		allocated = ee_len - (map->m_lblk - ee_block);
36816f91bc5fSEric Gouriou 
3682667eff35SYongqiang Yang 	WARN_ON(map->m_lblk < ee_block);
368321ca087aSDmitry Monakhov 	/*
368421ca087aSDmitry Monakhov 	 * It is safe to convert extent to initialized via explicit
36859e740568SYongqiang Yang 	 * zeroout only if extent is fully inside i_size or new_size.
368621ca087aSDmitry Monakhov 	 */
3687667eff35SYongqiang Yang 	split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
368821ca087aSDmitry Monakhov 
368967a5da56SZheng Liu 	if (EXT4_EXT_MAY_ZEROOUT & split_flag)
369067a5da56SZheng Liu 		max_zeroout = sbi->s_extent_max_zeroout_kb >>
36914f42f80aSLukas Czerner 			(inode->i_sb->s_blocksize_bits - 10);
369267a5da56SZheng Liu 
3693592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode))
369436086d43STheodore Ts'o 		max_zeroout = 0;
369536086d43STheodore Ts'o 
3696667eff35SYongqiang Yang 	/*
36974f8caa60SJan Kara 	 * five cases:
3698667eff35SYongqiang Yang 	 * 1. split the extent into three extents.
36994f8caa60SJan Kara 	 * 2. split the extent into two extents, zeroout the head of the first
37004f8caa60SJan Kara 	 *    extent.
37014f8caa60SJan Kara 	 * 3. split the extent into two extents, zeroout the tail of the second
37024f8caa60SJan Kara 	 *    extent.
3703667eff35SYongqiang Yang 	 * 4. split the extent into two extents with out zeroout.
37044f8caa60SJan Kara 	 * 5. no splitting needed, just possibly zeroout the head and / or the
37054f8caa60SJan Kara 	 *    tail of the extent.
3706667eff35SYongqiang Yang 	 */
3707667eff35SYongqiang Yang 	split_map.m_lblk = map->m_lblk;
3708667eff35SYongqiang Yang 	split_map.m_len = map->m_len;
3709667eff35SYongqiang Yang 
37104f8caa60SJan Kara 	if (max_zeroout && (allocated > split_map.m_len)) {
371167a5da56SZheng Liu 		if (allocated <= max_zeroout) {
37124f8caa60SJan Kara 			/* case 3 or 5 */
37134f8caa60SJan Kara 			zero_ex1.ee_block =
37144f8caa60SJan Kara 				 cpu_to_le32(split_map.m_lblk +
37154f8caa60SJan Kara 					     split_map.m_len);
37164f8caa60SJan Kara 			zero_ex1.ee_len =
37174f8caa60SJan Kara 				cpu_to_le16(allocated - split_map.m_len);
37184f8caa60SJan Kara 			ext4_ext_store_pblock(&zero_ex1,
37194f8caa60SJan Kara 				ext4_ext_pblock(ex) + split_map.m_lblk +
37204f8caa60SJan Kara 				split_map.m_len - ee_block);
37214f8caa60SJan Kara 			err = ext4_ext_zeroout(inode, &zero_ex1);
3722667eff35SYongqiang Yang 			if (err)
3723667eff35SYongqiang Yang 				goto out;
3724667eff35SYongqiang Yang 			split_map.m_len = allocated;
37254f8caa60SJan Kara 		}
37264f8caa60SJan Kara 		if (split_map.m_lblk - ee_block + split_map.m_len <
37274f8caa60SJan Kara 								max_zeroout) {
37284f8caa60SJan Kara 			/* case 2 or 5 */
37294f8caa60SJan Kara 			if (split_map.m_lblk != ee_block) {
37304f8caa60SJan Kara 				zero_ex2.ee_block = ex->ee_block;
37314f8caa60SJan Kara 				zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3732667eff35SYongqiang Yang 							ee_block);
37334f8caa60SJan Kara 				ext4_ext_store_pblock(&zero_ex2,
3734667eff35SYongqiang Yang 						      ext4_ext_pblock(ex));
37354f8caa60SJan Kara 				err = ext4_ext_zeroout(inode, &zero_ex2);
3736667eff35SYongqiang Yang 				if (err)
3737667eff35SYongqiang Yang 					goto out;
3738667eff35SYongqiang Yang 			}
3739667eff35SYongqiang Yang 
37404f8caa60SJan Kara 			split_map.m_len += split_map.m_lblk - ee_block;
3741667eff35SYongqiang Yang 			split_map.m_lblk = ee_block;
37429b940f8eSAllison Henderson 			allocated = map->m_len;
3743667eff35SYongqiang Yang 		}
3744667eff35SYongqiang Yang 	}
3745667eff35SYongqiang Yang 
3746ae9e9c6aSJan Kara 	err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3747ae9e9c6aSJan Kara 				flags);
3748ae9e9c6aSJan Kara 	if (err > 0)
3749ae9e9c6aSJan Kara 		err = 0;
3750667eff35SYongqiang Yang out:
3751adb23551SZheng Liu 	/* If we have gotten a failure, don't zero out status tree */
37524f8caa60SJan Kara 	if (!err) {
37534f8caa60SJan Kara 		err = ext4_zeroout_es(inode, &zero_ex1);
3754adb23551SZheng Liu 		if (!err)
37554f8caa60SJan Kara 			err = ext4_zeroout_es(inode, &zero_ex2);
37564f8caa60SJan Kara 	}
3757667eff35SYongqiang Yang 	return err ? err : allocated;
375856055d3aSAmit Arora }
375956055d3aSAmit Arora 
3760c278bfecSAneesh Kumar K.V /*
3761e35fd660STheodore Ts'o  * This function is called by ext4_ext_map_blocks() from
37620031462bSMingming Cao  * ext4_get_blocks_dio_write() when DIO to write
3763556615dcSLukas Czerner  * to an unwritten extent.
37640031462bSMingming Cao  *
3765556615dcSLukas Czerner  * Writing to an unwritten extent may result in splitting the unwritten
3766556615dcSLukas Czerner  * extent into multiple initialized/unwritten extents (up to three)
37670031462bSMingming Cao  * There are three possibilities:
3768556615dcSLukas Czerner  *   a> There is no split required: Entire extent should be unwritten
37690031462bSMingming Cao  *   b> Splits in two extents: Write is happening at either end of the extent
37700031462bSMingming Cao  *   c> Splits in three extents: Somone is writing in middle of the extent
37710031462bSMingming Cao  *
3772b8a86845SLukas Czerner  * This works the same way in the case of initialized -> unwritten conversion.
3773b8a86845SLukas Czerner  *
37740031462bSMingming Cao  * One of more index blocks maybe needed if the extent tree grow after
3775556615dcSLukas Czerner  * the unwritten extent split. To prevent ENOSPC occur at the IO
3776556615dcSLukas Czerner  * complete, we need to split the unwritten extent before DIO submit
3777556615dcSLukas Czerner  * the IO. The unwritten extent called at this time will be split
3778556615dcSLukas Czerner  * into three unwritten extent(at most). After IO complete, the part
37790031462bSMingming Cao  * being filled will be convert to initialized by the end_io callback function
37800031462bSMingming Cao  * via ext4_convert_unwritten_extents().
3781ba230c3fSMingming  *
3782556615dcSLukas Czerner  * Returns the size of unwritten extent to be written on success.
37830031462bSMingming Cao  */
3784b8a86845SLukas Czerner static int ext4_split_convert_extents(handle_t *handle,
37850031462bSMingming Cao 					struct inode *inode,
3786e35fd660STheodore Ts'o 					struct ext4_map_blocks *map,
3787dfe50809STheodore Ts'o 					struct ext4_ext_path **ppath,
37880031462bSMingming Cao 					int flags)
37890031462bSMingming Cao {
3790dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
3791667eff35SYongqiang Yang 	ext4_lblk_t eof_block;
3792667eff35SYongqiang Yang 	ext4_lblk_t ee_block;
3793667eff35SYongqiang Yang 	struct ext4_extent *ex;
3794667eff35SYongqiang Yang 	unsigned int ee_len;
3795667eff35SYongqiang Yang 	int split_flag = 0, depth;
37960031462bSMingming Cao 
3797b8a86845SLukas Czerner 	ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3798b8a86845SLukas Czerner 		  __func__, inode->i_ino,
3799e35fd660STheodore Ts'o 		  (unsigned long long)map->m_lblk, map->m_len);
380021ca087aSDmitry Monakhov 
380121ca087aSDmitry Monakhov 	eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
380221ca087aSDmitry Monakhov 		inode->i_sb->s_blocksize_bits;
3803e35fd660STheodore Ts'o 	if (eof_block < map->m_lblk + map->m_len)
3804e35fd660STheodore Ts'o 		eof_block = map->m_lblk + map->m_len;
38050031462bSMingming Cao 	/*
380621ca087aSDmitry Monakhov 	 * It is safe to convert extent to initialized via explicit
380721ca087aSDmitry Monakhov 	 * zeroout only if extent is fully insde i_size or new_size.
380821ca087aSDmitry Monakhov 	 */
3809667eff35SYongqiang Yang 	depth = ext_depth(inode);
38100031462bSMingming Cao 	ex = path[depth].p_ext;
3811667eff35SYongqiang Yang 	ee_block = le32_to_cpu(ex->ee_block);
3812667eff35SYongqiang Yang 	ee_len = ext4_ext_get_actual_len(ex);
38130031462bSMingming Cao 
3814b8a86845SLukas Czerner 	/* Convert to unwritten */
3815b8a86845SLukas Czerner 	if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3816b8a86845SLukas Czerner 		split_flag |= EXT4_EXT_DATA_VALID1;
3817b8a86845SLukas Czerner 	/* Convert to initialized */
3818b8a86845SLukas Czerner 	} else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3819b8a86845SLukas Czerner 		split_flag |= ee_block + ee_len <= eof_block ?
3820b8a86845SLukas Czerner 			      EXT4_EXT_MAY_ZEROOUT : 0;
3821556615dcSLukas Czerner 		split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3822b8a86845SLukas Czerner 	}
3823667eff35SYongqiang Yang 	flags |= EXT4_GET_BLOCKS_PRE_IO;
3824dfe50809STheodore Ts'o 	return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
38250031462bSMingming Cao }
3826197217a5SYongqiang Yang 
3827c7064ef1SJiaying Zhang static int ext4_convert_unwritten_extents_endio(handle_t *handle,
38280031462bSMingming Cao 						struct inode *inode,
3829dee1f973SDmitry Monakhov 						struct ext4_map_blocks *map,
3830dfe50809STheodore Ts'o 						struct ext4_ext_path **ppath)
38310031462bSMingming Cao {
3832dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
38330031462bSMingming Cao 	struct ext4_extent *ex;
3834dee1f973SDmitry Monakhov 	ext4_lblk_t ee_block;
3835dee1f973SDmitry Monakhov 	unsigned int ee_len;
38360031462bSMingming Cao 	int depth;
38370031462bSMingming Cao 	int err = 0;
38380031462bSMingming Cao 
38390031462bSMingming Cao 	depth = ext_depth(inode);
38400031462bSMingming Cao 	ex = path[depth].p_ext;
3841dee1f973SDmitry Monakhov 	ee_block = le32_to_cpu(ex->ee_block);
3842dee1f973SDmitry Monakhov 	ee_len = ext4_ext_get_actual_len(ex);
38430031462bSMingming Cao 
3844197217a5SYongqiang Yang 	ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3845197217a5SYongqiang Yang 		"block %llu, max_blocks %u\n", inode->i_ino,
3846dee1f973SDmitry Monakhov 		  (unsigned long long)ee_block, ee_len);
3847dee1f973SDmitry Monakhov 
3848ff95ec22SDmitry Monakhov 	/* If extent is larger than requested it is a clear sign that we still
3849ff95ec22SDmitry Monakhov 	 * have some extent state machine issues left. So extent_split is still
3850ff95ec22SDmitry Monakhov 	 * required.
3851ff95ec22SDmitry Monakhov 	 * TODO: Once all related issues will be fixed this situation should be
3852ff95ec22SDmitry Monakhov 	 * illegal.
3853ff95ec22SDmitry Monakhov 	 */
3854dee1f973SDmitry Monakhov 	if (ee_block != map->m_lblk || ee_len > map->m_len) {
3855e3d550c2SRakesh Pandit #ifdef CONFIG_EXT4_DEBUG
3856e3d550c2SRakesh Pandit 		ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
38578d2ae1cbSJakub Wilk 			     " len %u; IO logical block %llu, len %u",
3858ff95ec22SDmitry Monakhov 			     inode->i_ino, (unsigned long long)ee_block, ee_len,
3859ff95ec22SDmitry Monakhov 			     (unsigned long long)map->m_lblk, map->m_len);
3860ff95ec22SDmitry Monakhov #endif
3861dfe50809STheodore Ts'o 		err = ext4_split_convert_extents(handle, inode, map, ppath,
3862dee1f973SDmitry Monakhov 						 EXT4_GET_BLOCKS_CONVERT);
3863dee1f973SDmitry Monakhov 		if (err < 0)
3864dfe50809STheodore Ts'o 			return err;
3865ed8a1a76STheodore Ts'o 		path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3866dfe50809STheodore Ts'o 		if (IS_ERR(path))
3867dfe50809STheodore Ts'o 			return PTR_ERR(path);
3868dee1f973SDmitry Monakhov 		depth = ext_depth(inode);
3869dee1f973SDmitry Monakhov 		ex = path[depth].p_ext;
3870dee1f973SDmitry Monakhov 	}
3871197217a5SYongqiang Yang 
38720031462bSMingming Cao 	err = ext4_ext_get_access(handle, inode, path + depth);
38730031462bSMingming Cao 	if (err)
38740031462bSMingming Cao 		goto out;
38750031462bSMingming Cao 	/* first mark the extent as initialized */
38760031462bSMingming Cao 	ext4_ext_mark_initialized(ex);
38770031462bSMingming Cao 
3878197217a5SYongqiang Yang 	/* note: ext4_ext_correct_indexes() isn't needed here because
3879197217a5SYongqiang Yang 	 * borders are not changed
38800031462bSMingming Cao 	 */
3881ecb94f5fSTheodore Ts'o 	ext4_ext_try_to_merge(handle, inode, path, ex);
3882197217a5SYongqiang Yang 
38830031462bSMingming Cao 	/* Mark modified extent as dirty */
3884ecb94f5fSTheodore Ts'o 	err = ext4_ext_dirty(handle, inode, path + path->p_depth);
38850031462bSMingming Cao out:
38860031462bSMingming Cao 	ext4_ext_show_leaf(inode, path);
38870031462bSMingming Cao 	return err;
38880031462bSMingming Cao }
38890031462bSMingming Cao 
389058590b06STheodore Ts'o /*
389158590b06STheodore Ts'o  * Handle EOFBLOCKS_FL flag, clearing it if necessary
389258590b06STheodore Ts'o  */
389358590b06STheodore Ts'o static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3894d002ebf1SEric Sandeen 			      ext4_lblk_t lblk,
389558590b06STheodore Ts'o 			      struct ext4_ext_path *path,
389658590b06STheodore Ts'o 			      unsigned int len)
389758590b06STheodore Ts'o {
389858590b06STheodore Ts'o 	int i, depth;
389958590b06STheodore Ts'o 	struct ext4_extent_header *eh;
390065922cb5SSergey Senozhatsky 	struct ext4_extent *last_ex;
390158590b06STheodore Ts'o 
390258590b06STheodore Ts'o 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
390358590b06STheodore Ts'o 		return 0;
390458590b06STheodore Ts'o 
390558590b06STheodore Ts'o 	depth = ext_depth(inode);
390658590b06STheodore Ts'o 	eh = path[depth].p_hdr;
390758590b06STheodore Ts'o 
3908afcff5d8SLukas Czerner 	/*
3909afcff5d8SLukas Czerner 	 * We're going to remove EOFBLOCKS_FL entirely in future so we
3910afcff5d8SLukas Czerner 	 * do not care for this case anymore. Simply remove the flag
3911afcff5d8SLukas Czerner 	 * if there are no extents.
3912afcff5d8SLukas Czerner 	 */
3913afcff5d8SLukas Czerner 	if (unlikely(!eh->eh_entries))
3914afcff5d8SLukas Czerner 		goto out;
391558590b06STheodore Ts'o 	last_ex = EXT_LAST_EXTENT(eh);
391658590b06STheodore Ts'o 	/*
391758590b06STheodore Ts'o 	 * We should clear the EOFBLOCKS_FL flag if we are writing the
391858590b06STheodore Ts'o 	 * last block in the last extent in the file.  We test this by
391958590b06STheodore Ts'o 	 * first checking to see if the caller to
392058590b06STheodore Ts'o 	 * ext4_ext_get_blocks() was interested in the last block (or
392158590b06STheodore Ts'o 	 * a block beyond the last block) in the current extent.  If
392258590b06STheodore Ts'o 	 * this turns out to be false, we can bail out from this
392358590b06STheodore Ts'o 	 * function immediately.
392458590b06STheodore Ts'o 	 */
3925d002ebf1SEric Sandeen 	if (lblk + len < le32_to_cpu(last_ex->ee_block) +
392658590b06STheodore Ts'o 	    ext4_ext_get_actual_len(last_ex))
392758590b06STheodore Ts'o 		return 0;
392858590b06STheodore Ts'o 	/*
392958590b06STheodore Ts'o 	 * If the caller does appear to be planning to write at or
393058590b06STheodore Ts'o 	 * beyond the end of the current extent, we then test to see
393158590b06STheodore Ts'o 	 * if the current extent is the last extent in the file, by
393258590b06STheodore Ts'o 	 * checking to make sure it was reached via the rightmost node
393358590b06STheodore Ts'o 	 * at each level of the tree.
393458590b06STheodore Ts'o 	 */
393558590b06STheodore Ts'o 	for (i = depth-1; i >= 0; i--)
393658590b06STheodore Ts'o 		if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
393758590b06STheodore Ts'o 			return 0;
3938afcff5d8SLukas Czerner out:
393958590b06STheodore Ts'o 	ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
394058590b06STheodore Ts'o 	return ext4_mark_inode_dirty(handle, inode);
394158590b06STheodore Ts'o }
394258590b06STheodore Ts'o 
39430031462bSMingming Cao static int
3944e8b83d93STheodore Ts'o convert_initialized_extent(handle_t *handle, struct inode *inode,
3945b8a86845SLukas Czerner 			   struct ext4_map_blocks *map,
394629c6eaffSEric Whitney 			   struct ext4_ext_path **ppath,
394756263b4cSEryu Guan 			   unsigned int allocated)
3948b8a86845SLukas Czerner {
39494f224b8bSTheodore Ts'o 	struct ext4_ext_path *path = *ppath;
3950e8b83d93STheodore Ts'o 	struct ext4_extent *ex;
3951e8b83d93STheodore Ts'o 	ext4_lblk_t ee_block;
3952e8b83d93STheodore Ts'o 	unsigned int ee_len;
3953e8b83d93STheodore Ts'o 	int depth;
3954b8a86845SLukas Czerner 	int err = 0;
3955b8a86845SLukas Czerner 
3956b8a86845SLukas Czerner 	/*
3957b8a86845SLukas Czerner 	 * Make sure that the extent is no bigger than we support with
3958556615dcSLukas Czerner 	 * unwritten extent
3959b8a86845SLukas Czerner 	 */
3960556615dcSLukas Czerner 	if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3961556615dcSLukas Czerner 		map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3962b8a86845SLukas Czerner 
3963e8b83d93STheodore Ts'o 	depth = ext_depth(inode);
3964e8b83d93STheodore Ts'o 	ex = path[depth].p_ext;
3965e8b83d93STheodore Ts'o 	ee_block = le32_to_cpu(ex->ee_block);
3966e8b83d93STheodore Ts'o 	ee_len = ext4_ext_get_actual_len(ex);
3967e8b83d93STheodore Ts'o 
3968e8b83d93STheodore Ts'o 	ext_debug("%s: inode %lu, logical"
3969e8b83d93STheodore Ts'o 		"block %llu, max_blocks %u\n", __func__, inode->i_ino,
3970e8b83d93STheodore Ts'o 		  (unsigned long long)ee_block, ee_len);
3971e8b83d93STheodore Ts'o 
3972e8b83d93STheodore Ts'o 	if (ee_block != map->m_lblk || ee_len > map->m_len) {
3973dfe50809STheodore Ts'o 		err = ext4_split_convert_extents(handle, inode, map, ppath,
3974e8b83d93STheodore Ts'o 				EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3975e8b83d93STheodore Ts'o 		if (err < 0)
3976e8b83d93STheodore Ts'o 			return err;
3977ed8a1a76STheodore Ts'o 		path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3978e8b83d93STheodore Ts'o 		if (IS_ERR(path))
3979e8b83d93STheodore Ts'o 			return PTR_ERR(path);
3980e8b83d93STheodore Ts'o 		depth = ext_depth(inode);
3981e8b83d93STheodore Ts'o 		ex = path[depth].p_ext;
3982e8b83d93STheodore Ts'o 		if (!ex) {
3983e8b83d93STheodore Ts'o 			EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3984e8b83d93STheodore Ts'o 					 (unsigned long) map->m_lblk);
39856a797d27SDarrick J. Wong 			return -EFSCORRUPTED;
3986e8b83d93STheodore Ts'o 		}
3987e8b83d93STheodore Ts'o 	}
3988e8b83d93STheodore Ts'o 
3989e8b83d93STheodore Ts'o 	err = ext4_ext_get_access(handle, inode, path + depth);
3990e8b83d93STheodore Ts'o 	if (err)
3991e8b83d93STheodore Ts'o 		return err;
3992e8b83d93STheodore Ts'o 	/* first mark the extent as unwritten */
3993e8b83d93STheodore Ts'o 	ext4_ext_mark_unwritten(ex);
3994e8b83d93STheodore Ts'o 
3995e8b83d93STheodore Ts'o 	/* note: ext4_ext_correct_indexes() isn't needed here because
3996e8b83d93STheodore Ts'o 	 * borders are not changed
3997e8b83d93STheodore Ts'o 	 */
3998e8b83d93STheodore Ts'o 	ext4_ext_try_to_merge(handle, inode, path, ex);
3999e8b83d93STheodore Ts'o 
4000e8b83d93STheodore Ts'o 	/* Mark modified extent as dirty */
4001e8b83d93STheodore Ts'o 	err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4002e8b83d93STheodore Ts'o 	if (err)
4003e8b83d93STheodore Ts'o 		return err;
4004e8b83d93STheodore Ts'o 	ext4_ext_show_leaf(inode, path);
4005e8b83d93STheodore Ts'o 
4006b8a86845SLukas Czerner 	ext4_update_inode_fsync_trans(handle, inode, 1);
4007e8b83d93STheodore Ts'o 	err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4008e8b83d93STheodore Ts'o 	if (err)
4009e8b83d93STheodore Ts'o 		return err;
4010b8a86845SLukas Czerner 	map->m_flags |= EXT4_MAP_UNWRITTEN;
4011b8a86845SLukas Czerner 	if (allocated > map->m_len)
4012b8a86845SLukas Czerner 		allocated = map->m_len;
4013b8a86845SLukas Czerner 	map->m_len = allocated;
4014e8b83d93STheodore Ts'o 	return allocated;
4015b8a86845SLukas Czerner }
4016b8a86845SLukas Czerner 
4017b8a86845SLukas Czerner static int
4018556615dcSLukas Czerner ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4019e35fd660STheodore Ts'o 			struct ext4_map_blocks *map,
4020dfe50809STheodore Ts'o 			struct ext4_ext_path **ppath, int flags,
4021e35fd660STheodore Ts'o 			unsigned int allocated, ext4_fsblk_t newblock)
40220031462bSMingming Cao {
4023dfe50809STheodore Ts'o 	struct ext4_ext_path *path = *ppath;
40240031462bSMingming Cao 	int ret = 0;
40250031462bSMingming Cao 	int err = 0;
40260031462bSMingming Cao 
4027556615dcSLukas Czerner 	ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
402888635ca2SZheng Liu 		  "block %llu, max_blocks %u, flags %x, allocated %u\n",
4029e35fd660STheodore Ts'o 		  inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
40300031462bSMingming Cao 		  flags, allocated);
40310031462bSMingming Cao 	ext4_ext_show_leaf(inode, path);
40320031462bSMingming Cao 
403327dd4385SLukas Czerner 	/*
4034556615dcSLukas Czerner 	 * When writing into unwritten space, we should not fail to
403527dd4385SLukas Czerner 	 * allocate metadata blocks for the new extent block if needed.
403627dd4385SLukas Czerner 	 */
403727dd4385SLukas Czerner 	flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
403827dd4385SLukas Czerner 
4039556615dcSLukas Czerner 	trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4040b5645534SZheng Liu 						    allocated, newblock);
4041d8990240SAditya Kali 
4042c7064ef1SJiaying Zhang 	/* get_block() before submit the IO, split the extent */
4043c8b459f4SLukas Czerner 	if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4044dfe50809STheodore Ts'o 		ret = ext4_split_convert_extents(handle, inode, map, ppath,
4045dfe50809STheodore Ts'o 					 flags | EXT4_GET_BLOCKS_CONVERT);
404682e54229SDmitry Monakhov 		if (ret <= 0)
404782e54229SDmitry Monakhov 			goto out;
4048a25a4e1aSZheng Liu 		map->m_flags |= EXT4_MAP_UNWRITTEN;
40490031462bSMingming Cao 		goto out;
40500031462bSMingming Cao 	}
4051c7064ef1SJiaying Zhang 	/* IO end_io complete, convert the filled extent to written */
4052c8b459f4SLukas Czerner 	if (flags & EXT4_GET_BLOCKS_CONVERT) {
4053c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO) {
4054c86d8db3SJan Kara 			if (allocated > map->m_len)
4055c86d8db3SJan Kara 				allocated = map->m_len;
4056c86d8db3SJan Kara 			err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4057c86d8db3SJan Kara 						 allocated);
4058c86d8db3SJan Kara 			if (err < 0)
4059c86d8db3SJan Kara 				goto out2;
4060c86d8db3SJan Kara 		}
4061dee1f973SDmitry Monakhov 		ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4062dfe50809STheodore Ts'o 							   ppath);
406358590b06STheodore Ts'o 		if (ret >= 0) {
4064b436b9beSJan Kara 			ext4_update_inode_fsync_trans(handle, inode, 1);
4065d002ebf1SEric Sandeen 			err = check_eofblocks_fl(handle, inode, map->m_lblk,
4066d002ebf1SEric Sandeen 						 path, map->m_len);
406758590b06STheodore Ts'o 		} else
406858590b06STheodore Ts'o 			err = ret;
4069cdee7843SZheng Liu 		map->m_flags |= EXT4_MAP_MAPPED;
407015cc1767SEric Whitney 		map->m_pblk = newblock;
4071cdee7843SZheng Liu 		if (allocated > map->m_len)
4072cdee7843SZheng Liu 			allocated = map->m_len;
4073cdee7843SZheng Liu 		map->m_len = allocated;
40740031462bSMingming Cao 		goto out2;
40750031462bSMingming Cao 	}
40760031462bSMingming Cao 	/* buffered IO case */
40770031462bSMingming Cao 	/*
40780031462bSMingming Cao 	 * repeat fallocate creation request
40790031462bSMingming Cao 	 * we already have an unwritten extent
40800031462bSMingming Cao 	 */
4081556615dcSLukas Czerner 	if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4082a25a4e1aSZheng Liu 		map->m_flags |= EXT4_MAP_UNWRITTEN;
40830031462bSMingming Cao 		goto map_out;
4084a25a4e1aSZheng Liu 	}
40850031462bSMingming Cao 
40860031462bSMingming Cao 	/* buffered READ or buffered write_begin() lookup */
40870031462bSMingming Cao 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
40880031462bSMingming Cao 		/*
40890031462bSMingming Cao 		 * We have blocks reserved already.  We
40900031462bSMingming Cao 		 * return allocated blocks so that delalloc
40910031462bSMingming Cao 		 * won't do block reservation for us.  But
40920031462bSMingming Cao 		 * the buffer head will be unmapped so that
40930031462bSMingming Cao 		 * a read from the block returns 0s.
40940031462bSMingming Cao 		 */
4095e35fd660STheodore Ts'o 		map->m_flags |= EXT4_MAP_UNWRITTEN;
40960031462bSMingming Cao 		goto out1;
40970031462bSMingming Cao 	}
40980031462bSMingming Cao 
40990031462bSMingming Cao 	/* buffered write, writepage time, convert*/
4100dfe50809STheodore Ts'o 	ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4101a4e5d88bSDmitry Monakhov 	if (ret >= 0)
4102b436b9beSJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
41030031462bSMingming Cao out:
41040031462bSMingming Cao 	if (ret <= 0) {
41050031462bSMingming Cao 		err = ret;
41060031462bSMingming Cao 		goto out2;
41070031462bSMingming Cao 	} else
41080031462bSMingming Cao 		allocated = ret;
4109e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_NEW;
411016e08b14Szhangyi (F) 	if (allocated > map->m_len)
4111e35fd660STheodore Ts'o 		allocated = map->m_len;
41123a225670SZheng Liu 	map->m_len = allocated;
41135f634d06SAneesh Kumar K.V 
41140031462bSMingming Cao map_out:
4115e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_MAPPED;
4116a4e5d88bSDmitry Monakhov 	if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4117a4e5d88bSDmitry Monakhov 		err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4118a4e5d88bSDmitry Monakhov 					 map->m_len);
4119a4e5d88bSDmitry Monakhov 		if (err < 0)
4120a4e5d88bSDmitry Monakhov 			goto out2;
4121a4e5d88bSDmitry Monakhov 	}
41220031462bSMingming Cao out1:
4123e35fd660STheodore Ts'o 	if (allocated > map->m_len)
4124e35fd660STheodore Ts'o 		allocated = map->m_len;
41250031462bSMingming Cao 	ext4_ext_show_leaf(inode, path);
4126e35fd660STheodore Ts'o 	map->m_pblk = newblock;
4127e35fd660STheodore Ts'o 	map->m_len = allocated;
41280031462bSMingming Cao out2:
41290031462bSMingming Cao 	return err ? err : allocated;
41300031462bSMingming Cao }
413158590b06STheodore Ts'o 
41320031462bSMingming Cao /*
41334d33b1efSTheodore Ts'o  * get_implied_cluster_alloc - check to see if the requested
41344d33b1efSTheodore Ts'o  * allocation (in the map structure) overlaps with a cluster already
41354d33b1efSTheodore Ts'o  * allocated in an extent.
4136d8990240SAditya Kali  *	@sb	The filesystem superblock structure
41374d33b1efSTheodore Ts'o  *	@map	The requested lblk->pblk mapping
41384d33b1efSTheodore Ts'o  *	@ex	The extent structure which might contain an implied
41394d33b1efSTheodore Ts'o  *			cluster allocation
41404d33b1efSTheodore Ts'o  *
41414d33b1efSTheodore Ts'o  * This function is called by ext4_ext_map_blocks() after we failed to
41424d33b1efSTheodore Ts'o  * find blocks that were already in the inode's extent tree.  Hence,
41434d33b1efSTheodore Ts'o  * we know that the beginning of the requested region cannot overlap
41444d33b1efSTheodore Ts'o  * the extent from the inode's extent tree.  There are three cases we
41454d33b1efSTheodore Ts'o  * want to catch.  The first is this case:
41464d33b1efSTheodore Ts'o  *
41474d33b1efSTheodore Ts'o  *		 |--- cluster # N--|
41484d33b1efSTheodore Ts'o  *    |--- extent ---|	|---- requested region ---|
41494d33b1efSTheodore Ts'o  *			|==========|
41504d33b1efSTheodore Ts'o  *
41514d33b1efSTheodore Ts'o  * The second case that we need to test for is this one:
41524d33b1efSTheodore Ts'o  *
41534d33b1efSTheodore Ts'o  *   |--------- cluster # N ----------------|
41544d33b1efSTheodore Ts'o  *	   |--- requested region --|   |------- extent ----|
41554d33b1efSTheodore Ts'o  *	   |=======================|
41564d33b1efSTheodore Ts'o  *
41574d33b1efSTheodore Ts'o  * The third case is when the requested region lies between two extents
41584d33b1efSTheodore Ts'o  * within the same cluster:
41594d33b1efSTheodore Ts'o  *          |------------- cluster # N-------------|
41604d33b1efSTheodore Ts'o  * |----- ex -----|                  |---- ex_right ----|
41614d33b1efSTheodore Ts'o  *                  |------ requested region ------|
41624d33b1efSTheodore Ts'o  *                  |================|
41634d33b1efSTheodore Ts'o  *
41644d33b1efSTheodore Ts'o  * In each of the above cases, we need to set the map->m_pblk and
41654d33b1efSTheodore Ts'o  * map->m_len so it corresponds to the return the extent labelled as
41664d33b1efSTheodore Ts'o  * "|====|" from cluster #N, since it is already in use for data in
41674d33b1efSTheodore Ts'o  * cluster EXT4_B2C(sbi, map->m_lblk).	We will then return 1 to
41684d33b1efSTheodore Ts'o  * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
41694d33b1efSTheodore Ts'o  * as a new "allocated" block region.  Otherwise, we will return 0 and
41704d33b1efSTheodore Ts'o  * ext4_ext_map_blocks() will then allocate one or more new clusters
41714d33b1efSTheodore Ts'o  * by calling ext4_mb_new_blocks().
41724d33b1efSTheodore Ts'o  */
4173d8990240SAditya Kali static int get_implied_cluster_alloc(struct super_block *sb,
41744d33b1efSTheodore Ts'o 				     struct ext4_map_blocks *map,
41754d33b1efSTheodore Ts'o 				     struct ext4_extent *ex,
41764d33b1efSTheodore Ts'o 				     struct ext4_ext_path *path)
41774d33b1efSTheodore Ts'o {
4178d8990240SAditya Kali 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4179f5a44db5STheodore Ts'o 	ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
41804d33b1efSTheodore Ts'o 	ext4_lblk_t ex_cluster_start, ex_cluster_end;
418114d7f3efSCurt Wohlgemuth 	ext4_lblk_t rr_cluster_start;
41824d33b1efSTheodore Ts'o 	ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
41834d33b1efSTheodore Ts'o 	ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
41844d33b1efSTheodore Ts'o 	unsigned short ee_len = ext4_ext_get_actual_len(ex);
41854d33b1efSTheodore Ts'o 
41864d33b1efSTheodore Ts'o 	/* The extent passed in that we are trying to match */
41874d33b1efSTheodore Ts'o 	ex_cluster_start = EXT4_B2C(sbi, ee_block);
41884d33b1efSTheodore Ts'o 	ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
41894d33b1efSTheodore Ts'o 
41904d33b1efSTheodore Ts'o 	/* The requested region passed into ext4_map_blocks() */
41914d33b1efSTheodore Ts'o 	rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
41924d33b1efSTheodore Ts'o 
41934d33b1efSTheodore Ts'o 	if ((rr_cluster_start == ex_cluster_end) ||
41944d33b1efSTheodore Ts'o 	    (rr_cluster_start == ex_cluster_start)) {
41954d33b1efSTheodore Ts'o 		if (rr_cluster_start == ex_cluster_end)
41964d33b1efSTheodore Ts'o 			ee_start += ee_len - 1;
4197f5a44db5STheodore Ts'o 		map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
41984d33b1efSTheodore Ts'o 		map->m_len = min(map->m_len,
41994d33b1efSTheodore Ts'o 				 (unsigned) sbi->s_cluster_ratio - c_offset);
42004d33b1efSTheodore Ts'o 		/*
42014d33b1efSTheodore Ts'o 		 * Check for and handle this case:
42024d33b1efSTheodore Ts'o 		 *
42034d33b1efSTheodore Ts'o 		 *   |--------- cluster # N-------------|
42044d33b1efSTheodore Ts'o 		 *		       |------- extent ----|
42054d33b1efSTheodore Ts'o 		 *	   |--- requested region ---|
42064d33b1efSTheodore Ts'o 		 *	   |===========|
42074d33b1efSTheodore Ts'o 		 */
42084d33b1efSTheodore Ts'o 
42094d33b1efSTheodore Ts'o 		if (map->m_lblk < ee_block)
42104d33b1efSTheodore Ts'o 			map->m_len = min(map->m_len, ee_block - map->m_lblk);
42114d33b1efSTheodore Ts'o 
42124d33b1efSTheodore Ts'o 		/*
42134d33b1efSTheodore Ts'o 		 * Check for the case where there is already another allocated
42144d33b1efSTheodore Ts'o 		 * block to the right of 'ex' but before the end of the cluster.
42154d33b1efSTheodore Ts'o 		 *
42164d33b1efSTheodore Ts'o 		 *          |------------- cluster # N-------------|
42174d33b1efSTheodore Ts'o 		 * |----- ex -----|                  |---- ex_right ----|
42184d33b1efSTheodore Ts'o 		 *                  |------ requested region ------|
42194d33b1efSTheodore Ts'o 		 *                  |================|
42204d33b1efSTheodore Ts'o 		 */
42214d33b1efSTheodore Ts'o 		if (map->m_lblk > ee_block) {
42224d33b1efSTheodore Ts'o 			ext4_lblk_t next = ext4_ext_next_allocated_block(path);
42234d33b1efSTheodore Ts'o 			map->m_len = min(map->m_len, next - map->m_lblk);
42244d33b1efSTheodore Ts'o 		}
4225d8990240SAditya Kali 
4226d8990240SAditya Kali 		trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
42274d33b1efSTheodore Ts'o 		return 1;
42284d33b1efSTheodore Ts'o 	}
4229d8990240SAditya Kali 
4230d8990240SAditya Kali 	trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
42314d33b1efSTheodore Ts'o 	return 0;
42324d33b1efSTheodore Ts'o }
42334d33b1efSTheodore Ts'o 
42344d33b1efSTheodore Ts'o 
42354d33b1efSTheodore Ts'o /*
4236f5ab0d1fSMingming Cao  * Block allocation/map/preallocation routine for extents based files
4237f5ab0d1fSMingming Cao  *
4238f5ab0d1fSMingming Cao  *
4239c278bfecSAneesh Kumar K.V  * Need to be called with
42400e855ac8SAneesh Kumar K.V  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
42410e855ac8SAneesh Kumar K.V  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4242f5ab0d1fSMingming Cao  *
4243f5ab0d1fSMingming Cao  * return > 0, number of of blocks already mapped/allocated
4244f5ab0d1fSMingming Cao  *          if create == 0 and these are pre-allocated blocks
4245f5ab0d1fSMingming Cao  *          	buffer head is unmapped
4246f5ab0d1fSMingming Cao  *          otherwise blocks are mapped
4247f5ab0d1fSMingming Cao  *
4248f5ab0d1fSMingming Cao  * return = 0, if plain look up failed (blocks have not been allocated)
4249f5ab0d1fSMingming Cao  *          buffer head is unmapped
4250f5ab0d1fSMingming Cao  *
4251f5ab0d1fSMingming Cao  * return < 0, error case.
4252c278bfecSAneesh Kumar K.V  */
4253e35fd660STheodore Ts'o int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4254e35fd660STheodore Ts'o 			struct ext4_map_blocks *map, int flags)
4255a86c6181SAlex Tomas {
4256a86c6181SAlex Tomas 	struct ext4_ext_path *path = NULL;
42574d33b1efSTheodore Ts'o 	struct ext4_extent newex, *ex, *ex2;
42584d33b1efSTheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
42590562e0baSJiaying Zhang 	ext4_fsblk_t newblock = 0;
4260ce37c429SEric Whitney 	int free_on_err = 0, err = 0, depth, ret;
42614d33b1efSTheodore Ts'o 	unsigned int allocated = 0, offset = 0;
426281fdbb4aSYongqiang Yang 	unsigned int allocated_clusters = 0;
4263c9de560dSAlex Tomas 	struct ext4_allocation_request ar;
42644d33b1efSTheodore Ts'o 	ext4_lblk_t cluster_offset;
4265cbd7584eSJan Kara 	bool map_from_cluster = false;
4266a86c6181SAlex Tomas 
426784fe3befSMingming 	ext_debug("blocks %u/%u requested for inode %lu\n",
4268e35fd660STheodore Ts'o 		  map->m_lblk, map->m_len, inode->i_ino);
42690562e0baSJiaying Zhang 	trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4270a86c6181SAlex Tomas 
4271a86c6181SAlex Tomas 	/* find extent for this block */
4272ed8a1a76STheodore Ts'o 	path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4273a86c6181SAlex Tomas 	if (IS_ERR(path)) {
4274a86c6181SAlex Tomas 		err = PTR_ERR(path);
4275a86c6181SAlex Tomas 		path = NULL;
4276a86c6181SAlex Tomas 		goto out2;
4277a86c6181SAlex Tomas 	}
4278a86c6181SAlex Tomas 
4279a86c6181SAlex Tomas 	depth = ext_depth(inode);
4280a86c6181SAlex Tomas 
4281a86c6181SAlex Tomas 	/*
4282d0d856e8SRandy Dunlap 	 * consistent leaf must not be empty;
4283d0d856e8SRandy Dunlap 	 * this situation is possible, though, _during_ tree modification;
4284ed8a1a76STheodore Ts'o 	 * this is why assert can't be put in ext4_find_extent()
4285a86c6181SAlex Tomas 	 */
4286273df556SFrank Mayhar 	if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4287273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "bad extent address "
4288f70f362bSTheodore Ts'o 				 "lblock: %lu, depth: %d pblock %lld",
4289f70f362bSTheodore Ts'o 				 (unsigned long) map->m_lblk, depth,
4290f70f362bSTheodore Ts'o 				 path[depth].p_block);
42916a797d27SDarrick J. Wong 		err = -EFSCORRUPTED;
4292034fb4c9SSurbhi Palande 		goto out2;
4293034fb4c9SSurbhi Palande 	}
4294a86c6181SAlex Tomas 
42957e028976SAvantika Mathur 	ex = path[depth].p_ext;
42967e028976SAvantika Mathur 	if (ex) {
4297725d26d3SAneesh Kumar K.V 		ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4298bf89d16fSTheodore Ts'o 		ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4299a2df2a63SAmit Arora 		unsigned short ee_len;
4300471d4011SSuparna Bhattacharya 
4301b8a86845SLukas Czerner 
4302471d4011SSuparna Bhattacharya 		/*
4303556615dcSLukas Czerner 		 * unwritten extents are treated as holes, except that
430456055d3aSAmit Arora 		 * we split out initialized portions during a write.
4305471d4011SSuparna Bhattacharya 		 */
4306a2df2a63SAmit Arora 		ee_len = ext4_ext_get_actual_len(ex);
4307d8990240SAditya Kali 
4308d8990240SAditya Kali 		trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4309d8990240SAditya Kali 
4310d0d856e8SRandy Dunlap 		/* if found extent covers block, simply return it */
4311e35fd660STheodore Ts'o 		if (in_range(map->m_lblk, ee_block, ee_len)) {
4312e35fd660STheodore Ts'o 			newblock = map->m_lblk - ee_block + ee_start;
4313d0d856e8SRandy Dunlap 			/* number of remaining blocks in the extent */
4314e35fd660STheodore Ts'o 			allocated = ee_len - (map->m_lblk - ee_block);
4315e35fd660STheodore Ts'o 			ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4316a86c6181SAlex Tomas 				  ee_block, ee_len, newblock);
431756055d3aSAmit Arora 
4318b8a86845SLukas Czerner 			/*
4319b8a86845SLukas Czerner 			 * If the extent is initialized check whether the
4320b8a86845SLukas Czerner 			 * caller wants to convert it to unwritten.
4321b8a86845SLukas Czerner 			 */
4322556615dcSLukas Czerner 			if ((!ext4_ext_is_unwritten(ex)) &&
4323b8a86845SLukas Czerner 			    (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4324e8b83d93STheodore Ts'o 				allocated = convert_initialized_extent(
43254f224b8bSTheodore Ts'o 						handle, inode, map, &path,
432629c6eaffSEric Whitney 						allocated);
4327b8a86845SLukas Czerner 				goto out2;
4328556615dcSLukas Czerner 			} else if (!ext4_ext_is_unwritten(ex))
4329a86c6181SAlex Tomas 				goto out;
433069eb33dcSZheng Liu 
4331556615dcSLukas Czerner 			ret = ext4_ext_handle_unwritten_extents(
4332dfe50809STheodore Ts'o 				handle, inode, map, &path, flags,
4333e861304bSAllison Henderson 				allocated, newblock);
4334ce37c429SEric Whitney 			if (ret < 0)
4335ce37c429SEric Whitney 				err = ret;
4336ce37c429SEric Whitney 			else
4337ce37c429SEric Whitney 				allocated = ret;
433831cf0f2cSEric Whitney 			goto out2;
433956055d3aSAmit Arora 		}
4340a86c6181SAlex Tomas 	}
4341a86c6181SAlex Tomas 
4342a86c6181SAlex Tomas 	/*
4343d0d856e8SRandy Dunlap 	 * requested block isn't allocated yet;
4344a86c6181SAlex Tomas 	 * we couldn't try to create block if create flag is zero
4345a86c6181SAlex Tomas 	 */
4346c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4347140a5250SJan Kara 		ext4_lblk_t hole_start, hole_len;
4348140a5250SJan Kara 
4349facab4d9SJan Kara 		hole_start = map->m_lblk;
4350facab4d9SJan Kara 		hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
435156055d3aSAmit Arora 		/*
435256055d3aSAmit Arora 		 * put just found gap into cache to speed up
435356055d3aSAmit Arora 		 * subsequent requests
435456055d3aSAmit Arora 		 */
4355140a5250SJan Kara 		ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4356facab4d9SJan Kara 
4357facab4d9SJan Kara 		/* Update hole_len to reflect hole size after map->m_lblk */
4358facab4d9SJan Kara 		if (hole_start != map->m_lblk)
4359facab4d9SJan Kara 			hole_len -= map->m_lblk - hole_start;
4360facab4d9SJan Kara 		map->m_pblk = 0;
4361facab4d9SJan Kara 		map->m_len = min_t(unsigned int, map->m_len, hole_len);
4362facab4d9SJan Kara 
4363a86c6181SAlex Tomas 		goto out2;
4364a86c6181SAlex Tomas 	}
43654d33b1efSTheodore Ts'o 
4366a86c6181SAlex Tomas 	/*
4367c2ea3fdeSTheodore Ts'o 	 * Okay, we need to do block allocation.
4368a86c6181SAlex Tomas 	 */
43694d33b1efSTheodore Ts'o 	newex.ee_block = cpu_to_le32(map->m_lblk);
4370d0abafacSEric Whitney 	cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
43714d33b1efSTheodore Ts'o 
43724d33b1efSTheodore Ts'o 	/*
43734d33b1efSTheodore Ts'o 	 * If we are doing bigalloc, check to see if the extent returned
4374ed8a1a76STheodore Ts'o 	 * by ext4_find_extent() implies a cluster we can use.
43754d33b1efSTheodore Ts'o 	 */
43764d33b1efSTheodore Ts'o 	if (cluster_offset && ex &&
4377d8990240SAditya Kali 	    get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
43784d33b1efSTheodore Ts'o 		ar.len = allocated = map->m_len;
43794d33b1efSTheodore Ts'o 		newblock = map->m_pblk;
4380cbd7584eSJan Kara 		map_from_cluster = true;
43814d33b1efSTheodore Ts'o 		goto got_allocated_blocks;
43824d33b1efSTheodore Ts'o 	}
4383a86c6181SAlex Tomas 
4384c9de560dSAlex Tomas 	/* find neighbour allocated blocks */
4385e35fd660STheodore Ts'o 	ar.lleft = map->m_lblk;
4386c9de560dSAlex Tomas 	err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4387c9de560dSAlex Tomas 	if (err)
4388c9de560dSAlex Tomas 		goto out2;
4389e35fd660STheodore Ts'o 	ar.lright = map->m_lblk;
43904d33b1efSTheodore Ts'o 	ex2 = NULL;
43914d33b1efSTheodore Ts'o 	err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4392c9de560dSAlex Tomas 	if (err)
4393c9de560dSAlex Tomas 		goto out2;
439425d14f98SAmit Arora 
43954d33b1efSTheodore Ts'o 	/* Check if the extent after searching to the right implies a
43964d33b1efSTheodore Ts'o 	 * cluster we can use. */
43974d33b1efSTheodore Ts'o 	if ((sbi->s_cluster_ratio > 1) && ex2 &&
4398d8990240SAditya Kali 	    get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
43994d33b1efSTheodore Ts'o 		ar.len = allocated = map->m_len;
44004d33b1efSTheodore Ts'o 		newblock = map->m_pblk;
4401cbd7584eSJan Kara 		map_from_cluster = true;
44024d33b1efSTheodore Ts'o 		goto got_allocated_blocks;
44034d33b1efSTheodore Ts'o 	}
44044d33b1efSTheodore Ts'o 
4405749269faSAmit Arora 	/*
4406749269faSAmit Arora 	 * See if request is beyond maximum number of blocks we can have in
4407749269faSAmit Arora 	 * a single extent. For an initialized extent this limit is
4408556615dcSLukas Czerner 	 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4409556615dcSLukas Czerner 	 * EXT_UNWRITTEN_MAX_LEN.
4410749269faSAmit Arora 	 */
4411e35fd660STheodore Ts'o 	if (map->m_len > EXT_INIT_MAX_LEN &&
4412556615dcSLukas Czerner 	    !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4413e35fd660STheodore Ts'o 		map->m_len = EXT_INIT_MAX_LEN;
4414556615dcSLukas Czerner 	else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4415556615dcSLukas Czerner 		 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4416556615dcSLukas Czerner 		map->m_len = EXT_UNWRITTEN_MAX_LEN;
4417749269faSAmit Arora 
4418e35fd660STheodore Ts'o 	/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4419e35fd660STheodore Ts'o 	newex.ee_len = cpu_to_le16(map->m_len);
44204d33b1efSTheodore Ts'o 	err = ext4_ext_check_overlap(sbi, inode, &newex, path);
442125d14f98SAmit Arora 	if (err)
4422b939e376SAneesh Kumar K.V 		allocated = ext4_ext_get_actual_len(&newex);
442325d14f98SAmit Arora 	else
4424e35fd660STheodore Ts'o 		allocated = map->m_len;
4425c9de560dSAlex Tomas 
4426c9de560dSAlex Tomas 	/* allocate new block */
4427c9de560dSAlex Tomas 	ar.inode = inode;
4428e35fd660STheodore Ts'o 	ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4429e35fd660STheodore Ts'o 	ar.logical = map->m_lblk;
44304d33b1efSTheodore Ts'o 	/*
44314d33b1efSTheodore Ts'o 	 * We calculate the offset from the beginning of the cluster
44324d33b1efSTheodore Ts'o 	 * for the logical block number, since when we allocate a
44334d33b1efSTheodore Ts'o 	 * physical cluster, the physical block should start at the
44344d33b1efSTheodore Ts'o 	 * same offset from the beginning of the cluster.  This is
44354d33b1efSTheodore Ts'o 	 * needed so that future calls to get_implied_cluster_alloc()
44364d33b1efSTheodore Ts'o 	 * work correctly.
44374d33b1efSTheodore Ts'o 	 */
4438f5a44db5STheodore Ts'o 	offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
44394d33b1efSTheodore Ts'o 	ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
44404d33b1efSTheodore Ts'o 	ar.goal -= offset;
44414d33b1efSTheodore Ts'o 	ar.logical -= offset;
4442c9de560dSAlex Tomas 	if (S_ISREG(inode->i_mode))
4443c9de560dSAlex Tomas 		ar.flags = EXT4_MB_HINT_DATA;
4444c9de560dSAlex Tomas 	else
4445c9de560dSAlex Tomas 		/* disable in-core preallocation for non-regular files */
4446c9de560dSAlex Tomas 		ar.flags = 0;
4447556b27abSVivek Haldar 	if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4448556b27abSVivek Haldar 		ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4449e3cf5d5dSTheodore Ts'o 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4450e3cf5d5dSTheodore Ts'o 		ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4451c5e298aeSTheodore Ts'o 	if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4452c5e298aeSTheodore Ts'o 		ar.flags |= EXT4_MB_USE_RESERVED;
4453c9de560dSAlex Tomas 	newblock = ext4_mb_new_blocks(handle, &ar, &err);
4454a86c6181SAlex Tomas 	if (!newblock)
4455a86c6181SAlex Tomas 		goto out2;
445684fe3befSMingming 	ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4457498e5f24STheodore Ts'o 		  ar.goal, newblock, allocated);
44584d33b1efSTheodore Ts'o 	free_on_err = 1;
44597b415bf6SAditya Kali 	allocated_clusters = ar.len;
44604d33b1efSTheodore Ts'o 	ar.len = EXT4_C2B(sbi, ar.len) - offset;
44614d33b1efSTheodore Ts'o 	if (ar.len > allocated)
44624d33b1efSTheodore Ts'o 		ar.len = allocated;
4463a86c6181SAlex Tomas 
44644d33b1efSTheodore Ts'o got_allocated_blocks:
4465a86c6181SAlex Tomas 	/* try to insert new extent into found leaf and return */
44664d33b1efSTheodore Ts'o 	ext4_ext_store_pblock(&newex, newblock + offset);
4467c9de560dSAlex Tomas 	newex.ee_len = cpu_to_le16(ar.len);
4468556615dcSLukas Czerner 	/* Mark unwritten */
4469556615dcSLukas Czerner 	if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4470556615dcSLukas Czerner 		ext4_ext_mark_unwritten(&newex);
4471a25a4e1aSZheng Liu 		map->m_flags |= EXT4_MAP_UNWRITTEN;
44728d5d02e6SMingming Cao 	}
4473c8d46e41SJiaying Zhang 
4474a4e5d88bSDmitry Monakhov 	err = 0;
4475a4e5d88bSDmitry Monakhov 	if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4476a4e5d88bSDmitry Monakhov 		err = check_eofblocks_fl(handle, inode, map->m_lblk,
4477a4e5d88bSDmitry Monakhov 					 path, ar.len);
4478575a1d4bSJiaying Zhang 	if (!err)
4479dfe50809STheodore Ts'o 		err = ext4_ext_insert_extent(handle, inode, &path,
4480575a1d4bSJiaying Zhang 					     &newex, flags);
448182e54229SDmitry Monakhov 
44824d33b1efSTheodore Ts'o 	if (err && free_on_err) {
44837132de74SMaxim Patlasov 		int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
44847132de74SMaxim Patlasov 			EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4485315054f0SAlex Tomas 		/* free data blocks we just allocated */
4486c9de560dSAlex Tomas 		/* not a good idea to call discard here directly,
4487c9de560dSAlex Tomas 		 * but otherwise we'd need to call it every free() */
4488c2ea3fdeSTheodore Ts'o 		ext4_discard_preallocations(inode);
4489c8e15130STheodore Ts'o 		ext4_free_blocks(handle, inode, NULL, newblock,
4490c8e15130STheodore Ts'o 				 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4491a86c6181SAlex Tomas 		goto out2;
4492315054f0SAlex Tomas 	}
4493a86c6181SAlex Tomas 
4494a86c6181SAlex Tomas 	/* previous routine could use block we allocated */
4495bf89d16fSTheodore Ts'o 	newblock = ext4_ext_pblock(&newex);
4496b939e376SAneesh Kumar K.V 	allocated = ext4_ext_get_actual_len(&newex);
4497e35fd660STheodore Ts'o 	if (allocated > map->m_len)
4498e35fd660STheodore Ts'o 		allocated = map->m_len;
4499e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_NEW;
4500a86c6181SAlex Tomas 
4501b436b9beSJan Kara 	/*
4502b6bf9171SEric Whitney 	 * Reduce the reserved cluster count to reflect successful deferred
4503b6bf9171SEric Whitney 	 * allocation of delayed allocated clusters or direct allocation of
4504b6bf9171SEric Whitney 	 * clusters discovered to be delayed allocated.  Once allocated, a
4505b6bf9171SEric Whitney 	 * cluster is not included in the reserved count.
45065f634d06SAneesh Kumar K.V 	 */
4507b6bf9171SEric Whitney 	if (test_opt(inode->i_sb, DELALLOC) && !map_from_cluster) {
45087b415bf6SAditya Kali 		if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
45097b415bf6SAditya Kali 			/*
4510b6bf9171SEric Whitney 			 * When allocating delayed allocated clusters, simply
4511b6bf9171SEric Whitney 			 * reduce the reserved cluster count and claim quota
4512232ec872SLukas Czerner 			 */
4513232ec872SLukas Czerner 			ext4_da_update_reserve_space(inode, allocated_clusters,
4514232ec872SLukas Czerner 							1);
4515b6bf9171SEric Whitney 		} else {
4516b6bf9171SEric Whitney 			ext4_lblk_t lblk, len;
4517b6bf9171SEric Whitney 			unsigned int n;
4518b6bf9171SEric Whitney 
4519b6bf9171SEric Whitney 			/*
4520b6bf9171SEric Whitney 			 * When allocating non-delayed allocated clusters
4521b6bf9171SEric Whitney 			 * (from fallocate, filemap, DIO, or clusters
4522b6bf9171SEric Whitney 			 * allocated when delalloc has been disabled by
4523b6bf9171SEric Whitney 			 * ext4_nonda_switch), reduce the reserved cluster
4524b6bf9171SEric Whitney 			 * count by the number of allocated clusters that
4525b6bf9171SEric Whitney 			 * have previously been delayed allocated.  Quota
4526b6bf9171SEric Whitney 			 * has been claimed by ext4_mb_new_blocks() above,
4527b6bf9171SEric Whitney 			 * so release the quota reservations made for any
4528b6bf9171SEric Whitney 			 * previously delayed allocated clusters.
4529b6bf9171SEric Whitney 			 */
4530b6bf9171SEric Whitney 			lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
4531b6bf9171SEric Whitney 			len = allocated_clusters << sbi->s_cluster_bits;
4532b6bf9171SEric Whitney 			n = ext4_es_delayed_clu(inode, lblk, len);
4533b6bf9171SEric Whitney 			if (n > 0)
4534b6bf9171SEric Whitney 				ext4_da_update_reserve_space(inode, (int) n, 0);
45357b415bf6SAditya Kali 		}
45367b415bf6SAditya Kali 	}
45375f634d06SAneesh Kumar K.V 
45385f634d06SAneesh Kumar K.V 	/*
4539b436b9beSJan Kara 	 * Cache the extent and update transaction to commit on fdatasync only
4540556615dcSLukas Czerner 	 * when it is _not_ an unwritten extent.
4541b436b9beSJan Kara 	 */
4542556615dcSLukas Czerner 	if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4543b436b9beSJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
454469eb33dcSZheng Liu 	else
4545b436b9beSJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 0);
4546a86c6181SAlex Tomas out:
4547e35fd660STheodore Ts'o 	if (allocated > map->m_len)
4548e35fd660STheodore Ts'o 		allocated = map->m_len;
4549a86c6181SAlex Tomas 	ext4_ext_show_leaf(inode, path);
4550e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_MAPPED;
4551e35fd660STheodore Ts'o 	map->m_pblk = newblock;
4552e35fd660STheodore Ts'o 	map->m_len = allocated;
4553a86c6181SAlex Tomas out2:
4554a86c6181SAlex Tomas 	ext4_ext_drop_refs(path);
4555a86c6181SAlex Tomas 	kfree(path);
4556e861304bSAllison Henderson 
455763b99968STheodore Ts'o 	trace_ext4_ext_map_blocks_exit(inode, flags, map,
455863b99968STheodore Ts'o 				       err ? err : allocated);
45597877191cSLukas Czerner 	return err ? err : allocated;
4560a86c6181SAlex Tomas }
4561a86c6181SAlex Tomas 
4562d0abb36dSTheodore Ts'o int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4563a86c6181SAlex Tomas {
4564a86c6181SAlex Tomas 	struct super_block *sb = inode->i_sb;
4565725d26d3SAneesh Kumar K.V 	ext4_lblk_t last_block;
4566a86c6181SAlex Tomas 	int err = 0;
4567a86c6181SAlex Tomas 
4568a86c6181SAlex Tomas 	/*
4569d0d856e8SRandy Dunlap 	 * TODO: optimization is possible here.
4570d0d856e8SRandy Dunlap 	 * Probably we need not scan at all,
4571d0d856e8SRandy Dunlap 	 * because page truncation is enough.
4572a86c6181SAlex Tomas 	 */
4573a86c6181SAlex Tomas 
4574a86c6181SAlex Tomas 	/* we have to know where to truncate from in crash case */
4575a86c6181SAlex Tomas 	EXT4_I(inode)->i_disksize = inode->i_size;
4576d0abb36dSTheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
4577d0abb36dSTheodore Ts'o 	if (err)
4578d0abb36dSTheodore Ts'o 		return err;
4579a86c6181SAlex Tomas 
4580a86c6181SAlex Tomas 	last_block = (inode->i_size + sb->s_blocksize - 1)
4581a86c6181SAlex Tomas 			>> EXT4_BLOCK_SIZE_BITS(sb);
45828acd5e9bSTheodore Ts'o retry:
458351865fdaSZheng Liu 	err = ext4_es_remove_extent(inode, last_block,
458451865fdaSZheng Liu 				    EXT_MAX_BLOCKS - last_block);
458594eec0fcSTheodore Ts'o 	if (err == -ENOMEM) {
45868acd5e9bSTheodore Ts'o 		cond_resched();
45878acd5e9bSTheodore Ts'o 		congestion_wait(BLK_RW_ASYNC, HZ/50);
45888acd5e9bSTheodore Ts'o 		goto retry;
45898acd5e9bSTheodore Ts'o 	}
4590d0abb36dSTheodore Ts'o 	if (err)
4591d0abb36dSTheodore Ts'o 		return err;
4592d0abb36dSTheodore Ts'o 	return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4593a86c6181SAlex Tomas }
4594a86c6181SAlex Tomas 
45950e8b6879SLukas Czerner static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4596c174e6d6SDmitry Monakhov 				  ext4_lblk_t len, loff_t new_size,
459777a2e84dSTahsin Erdogan 				  int flags)
4598a2df2a63SAmit Arora {
4599496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4600a2df2a63SAmit Arora 	handle_t *handle;
4601a2df2a63SAmit Arora 	int ret = 0;
4602a2df2a63SAmit Arora 	int ret2 = 0;
4603a2df2a63SAmit Arora 	int retries = 0;
46044134f5c8SLukas Czerner 	int depth = 0;
46052ed88685STheodore Ts'o 	struct ext4_map_blocks map;
46060e8b6879SLukas Czerner 	unsigned int credits;
4607c174e6d6SDmitry Monakhov 	loff_t epos;
4608a2df2a63SAmit Arora 
4609c3fe493cSFabian Frederick 	BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
46100e8b6879SLukas Czerner 	map.m_lblk = offset;
4611c174e6d6SDmitry Monakhov 	map.m_len = len;
46123c6fe770SGreg Harm 	/*
46133c6fe770SGreg Harm 	 * Don't normalize the request if it can fit in one extent so
46143c6fe770SGreg Harm 	 * that it doesn't get unnecessarily split into multiple
46153c6fe770SGreg Harm 	 * extents.
46163c6fe770SGreg Harm 	 */
4617556615dcSLukas Czerner 	if (len <= EXT_UNWRITTEN_MAX_LEN)
46183c6fe770SGreg Harm 		flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
461960d4616fSDmitry Monakhov 
46200e8b6879SLukas Czerner 	/*
46210e8b6879SLukas Czerner 	 * credits to insert 1 extent into extent tree
46220e8b6879SLukas Czerner 	 */
46230e8b6879SLukas Czerner 	credits = ext4_chunk_trans_blocks(inode, len);
46244134f5c8SLukas Czerner 	depth = ext_depth(inode);
46250e8b6879SLukas Czerner 
4626a2df2a63SAmit Arora retry:
4627c174e6d6SDmitry Monakhov 	while (ret >= 0 && len) {
46284134f5c8SLukas Czerner 		/*
46294134f5c8SLukas Czerner 		 * Recalculate credits when extent tree depth changes.
46304134f5c8SLukas Czerner 		 */
4631011c88e3SDan Carpenter 		if (depth != ext_depth(inode)) {
46324134f5c8SLukas Czerner 			credits = ext4_chunk_trans_blocks(inode, len);
46334134f5c8SLukas Czerner 			depth = ext_depth(inode);
46344134f5c8SLukas Czerner 		}
46354134f5c8SLukas Czerner 
46369924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
46379924a92aSTheodore Ts'o 					    credits);
4638a2df2a63SAmit Arora 		if (IS_ERR(handle)) {
4639a2df2a63SAmit Arora 			ret = PTR_ERR(handle);
4640a2df2a63SAmit Arora 			break;
4641a2df2a63SAmit Arora 		}
4642a4e5d88bSDmitry Monakhov 		ret = ext4_map_blocks(handle, inode, &map, flags);
4643221879c9SAneesh Kumar K.V 		if (ret <= 0) {
4644f282ac19SLukas Czerner 			ext4_debug("inode #%lu: block %u: len %u: "
4645b06acd38SLukas Czerner 				   "ext4_ext_map_blocks returned %d",
4646b06acd38SLukas Czerner 				   inode->i_ino, map.m_lblk,
4647b06acd38SLukas Czerner 				   map.m_len, ret);
4648a2df2a63SAmit Arora 			ext4_mark_inode_dirty(handle, inode);
4649a2df2a63SAmit Arora 			ret2 = ext4_journal_stop(handle);
4650a2df2a63SAmit Arora 			break;
4651a2df2a63SAmit Arora 		}
4652c174e6d6SDmitry Monakhov 		map.m_lblk += ret;
4653c174e6d6SDmitry Monakhov 		map.m_len = len = len - ret;
4654c174e6d6SDmitry Monakhov 		epos = (loff_t)map.m_lblk << inode->i_blkbits;
4655eeca7ea1SDeepa Dinamani 		inode->i_ctime = current_time(inode);
4656c174e6d6SDmitry Monakhov 		if (new_size) {
4657c174e6d6SDmitry Monakhov 			if (epos > new_size)
4658c174e6d6SDmitry Monakhov 				epos = new_size;
4659c174e6d6SDmitry Monakhov 			if (ext4_update_inode_size(inode, epos) & 0x1)
4660c174e6d6SDmitry Monakhov 				inode->i_mtime = inode->i_ctime;
4661c174e6d6SDmitry Monakhov 		} else {
4662c174e6d6SDmitry Monakhov 			if (epos > inode->i_size)
4663c174e6d6SDmitry Monakhov 				ext4_set_inode_flag(inode,
4664c174e6d6SDmitry Monakhov 						    EXT4_INODE_EOFBLOCKS);
4665c174e6d6SDmitry Monakhov 		}
4666c174e6d6SDmitry Monakhov 		ext4_mark_inode_dirty(handle, inode);
4667c894aa97SEryu Guan 		ext4_update_inode_fsync_trans(handle, inode, 1);
4668a2df2a63SAmit Arora 		ret2 = ext4_journal_stop(handle);
4669a2df2a63SAmit Arora 		if (ret2)
4670a2df2a63SAmit Arora 			break;
4671a2df2a63SAmit Arora 	}
4672fd28784aSAneesh Kumar K.V 	if (ret == -ENOSPC &&
4673fd28784aSAneesh Kumar K.V 			ext4_should_retry_alloc(inode->i_sb, &retries)) {
4674fd28784aSAneesh Kumar K.V 		ret = 0;
4675a2df2a63SAmit Arora 		goto retry;
4676a2df2a63SAmit Arora 	}
4677f282ac19SLukas Czerner 
46780e8b6879SLukas Czerner 	return ret > 0 ? ret2 : ret;
46790e8b6879SLukas Czerner }
46800e8b6879SLukas Czerner 
4681b8a86845SLukas Czerner static long ext4_zero_range(struct file *file, loff_t offset,
4682b8a86845SLukas Czerner 			    loff_t len, int mode)
4683b8a86845SLukas Czerner {
4684b8a86845SLukas Czerner 	struct inode *inode = file_inode(file);
4685b8a86845SLukas Czerner 	handle_t *handle = NULL;
4686b8a86845SLukas Czerner 	unsigned int max_blocks;
4687b8a86845SLukas Czerner 	loff_t new_size = 0;
4688b8a86845SLukas Czerner 	int ret = 0;
4689b8a86845SLukas Czerner 	int flags;
469069dc9536SDmitry Monakhov 	int credits;
4691c174e6d6SDmitry Monakhov 	int partial_begin, partial_end;
4692b8a86845SLukas Czerner 	loff_t start, end;
4693b8a86845SLukas Czerner 	ext4_lblk_t lblk;
4694b8a86845SLukas Czerner 	unsigned int blkbits = inode->i_blkbits;
4695b8a86845SLukas Czerner 
4696b8a86845SLukas Czerner 	trace_ext4_zero_range(inode, offset, len, mode);
4697b8a86845SLukas Czerner 
46986c5e73d3Sjon ernst 	if (!S_ISREG(inode->i_mode))
46996c5e73d3Sjon ernst 		return -EINVAL;
47006c5e73d3Sjon ernst 
4701e1ee60fdSNamjae Jeon 	/* Call ext4_force_commit to flush all data in case of data=journal. */
4702e1ee60fdSNamjae Jeon 	if (ext4_should_journal_data(inode)) {
4703e1ee60fdSNamjae Jeon 		ret = ext4_force_commit(inode->i_sb);
4704e1ee60fdSNamjae Jeon 		if (ret)
4705e1ee60fdSNamjae Jeon 			return ret;
4706e1ee60fdSNamjae Jeon 	}
4707e1ee60fdSNamjae Jeon 
4708b8a86845SLukas Czerner 	/*
4709b8a86845SLukas Czerner 	 * Round up offset. This is not fallocate, we neet to zero out
4710b8a86845SLukas Czerner 	 * blocks, so convert interior block aligned part of the range to
4711b8a86845SLukas Czerner 	 * unwritten and possibly manually zero out unaligned parts of the
4712b8a86845SLukas Czerner 	 * range.
4713b8a86845SLukas Czerner 	 */
4714b8a86845SLukas Czerner 	start = round_up(offset, 1 << blkbits);
4715b8a86845SLukas Czerner 	end = round_down((offset + len), 1 << blkbits);
4716b8a86845SLukas Czerner 
4717b8a86845SLukas Czerner 	if (start < offset || end > offset + len)
4718b8a86845SLukas Czerner 		return -EINVAL;
4719c174e6d6SDmitry Monakhov 	partial_begin = offset & ((1 << blkbits) - 1);
4720c174e6d6SDmitry Monakhov 	partial_end = (offset + len) & ((1 << blkbits) - 1);
4721b8a86845SLukas Czerner 
4722b8a86845SLukas Czerner 	lblk = start >> blkbits;
4723b8a86845SLukas Czerner 	max_blocks = (end >> blkbits);
4724b8a86845SLukas Czerner 	if (max_blocks < lblk)
4725b8a86845SLukas Czerner 		max_blocks = 0;
4726b8a86845SLukas Czerner 	else
4727b8a86845SLukas Czerner 		max_blocks -= lblk;
4728b8a86845SLukas Czerner 
47295955102cSAl Viro 	inode_lock(inode);
4730b8a86845SLukas Czerner 
4731b8a86845SLukas Czerner 	/*
4732b8a86845SLukas Czerner 	 * Indirect files do not support unwritten extnets
4733b8a86845SLukas Czerner 	 */
4734b8a86845SLukas Czerner 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4735b8a86845SLukas Czerner 		ret = -EOPNOTSUPP;
4736b8a86845SLukas Czerner 		goto out_mutex;
4737b8a86845SLukas Czerner 	}
4738b8a86845SLukas Czerner 
4739b8a86845SLukas Czerner 	if (!(mode & FALLOC_FL_KEEP_SIZE) &&
474051e3ae81STheodore Ts'o 	    (offset + len > i_size_read(inode) ||
474151e3ae81STheodore Ts'o 	     offset + len > EXT4_I(inode)->i_disksize)) {
4742b8a86845SLukas Czerner 		new_size = offset + len;
4743b8a86845SLukas Czerner 		ret = inode_newsize_ok(inode, new_size);
4744b8a86845SLukas Czerner 		if (ret)
4745b8a86845SLukas Czerner 			goto out_mutex;
4746b8a86845SLukas Czerner 	}
4747b8a86845SLukas Czerner 
47480f2af21aSLukas Czerner 	flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
47490f2af21aSLukas Czerner 	if (mode & FALLOC_FL_KEEP_SIZE)
47500f2af21aSLukas Czerner 		flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
47510f2af21aSLukas Czerner 
475217048e8aSJan Kara 	/* Wait all existing dio workers, newcomers will block on i_mutex */
475317048e8aSJan Kara 	inode_dio_wait(inode);
475417048e8aSJan Kara 
47550f2af21aSLukas Czerner 	/* Preallocate the range including the unaligned edges */
47560f2af21aSLukas Czerner 	if (partial_begin || partial_end) {
47570f2af21aSLukas Czerner 		ret = ext4_alloc_file_blocks(file,
47580f2af21aSLukas Czerner 				round_down(offset, 1 << blkbits) >> blkbits,
47590f2af21aSLukas Czerner 				(round_up((offset + len), 1 << blkbits) -
47600f2af21aSLukas Czerner 				 round_down(offset, 1 << blkbits)) >> blkbits,
476177a2e84dSTahsin Erdogan 				new_size, flags);
47620f2af21aSLukas Czerner 		if (ret)
47631d39834fSNikolay Borisov 			goto out_mutex;
47640f2af21aSLukas Czerner 
47650f2af21aSLukas Czerner 	}
47660f2af21aSLukas Czerner 
47670f2af21aSLukas Czerner 	/* Zero range excluding the unaligned edges */
4768b8a86845SLukas Czerner 	if (max_blocks > 0) {
47690f2af21aSLukas Czerner 		flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
47700f2af21aSLukas Czerner 			  EXT4_EX_NOCACHE);
4771b8a86845SLukas Czerner 
4772ea3d7209SJan Kara 		/*
4773ea3d7209SJan Kara 		 * Prevent page faults from reinstantiating pages we have
4774ea3d7209SJan Kara 		 * released from page cache.
4775ea3d7209SJan Kara 		 */
4776ea3d7209SJan Kara 		down_write(&EXT4_I(inode)->i_mmap_sem);
4777430657b6SRoss Zwisler 
4778430657b6SRoss Zwisler 		ret = ext4_break_layouts(inode);
4779430657b6SRoss Zwisler 		if (ret) {
4780430657b6SRoss Zwisler 			up_write(&EXT4_I(inode)->i_mmap_sem);
4781430657b6SRoss Zwisler 			goto out_mutex;
4782430657b6SRoss Zwisler 		}
4783430657b6SRoss Zwisler 
478401127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, len);
478501127848SJan Kara 		if (ret) {
478601127848SJan Kara 			up_write(&EXT4_I(inode)->i_mmap_sem);
47871d39834fSNikolay Borisov 			goto out_mutex;
478801127848SJan Kara 		}
4789ea3d7209SJan Kara 		/* Now release the pages and zero block aligned part of pages */
4790ea3d7209SJan Kara 		truncate_pagecache_range(inode, start, end - 1);
4791eeca7ea1SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
4792ea3d7209SJan Kara 
4793c174e6d6SDmitry Monakhov 		ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
479477a2e84dSTahsin Erdogan 					     flags);
4795ea3d7209SJan Kara 		up_write(&EXT4_I(inode)->i_mmap_sem);
4796b8a86845SLukas Czerner 		if (ret)
47971d39834fSNikolay Borisov 			goto out_mutex;
4798b8a86845SLukas Czerner 	}
4799c174e6d6SDmitry Monakhov 	if (!partial_begin && !partial_end)
48001d39834fSNikolay Borisov 		goto out_mutex;
4801c174e6d6SDmitry Monakhov 
480269dc9536SDmitry Monakhov 	/*
480369dc9536SDmitry Monakhov 	 * In worst case we have to writeout two nonadjacent unwritten
480469dc9536SDmitry Monakhov 	 * blocks and update the inode
480569dc9536SDmitry Monakhov 	 */
480669dc9536SDmitry Monakhov 	credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
480769dc9536SDmitry Monakhov 	if (ext4_should_journal_data(inode))
480869dc9536SDmitry Monakhov 		credits += 2;
480969dc9536SDmitry Monakhov 	handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4810b8a86845SLukas Czerner 	if (IS_ERR(handle)) {
4811b8a86845SLukas Czerner 		ret = PTR_ERR(handle);
4812b8a86845SLukas Czerner 		ext4_std_error(inode->i_sb, ret);
48131d39834fSNikolay Borisov 		goto out_mutex;
4814b8a86845SLukas Czerner 	}
4815b8a86845SLukas Czerner 
4816eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
4817e5b30416SLukas Czerner 	if (new_size) {
48184631dbf6SDmitry Monakhov 		ext4_update_inode_size(inode, new_size);
4819e5b30416SLukas Czerner 	} else {
4820b8a86845SLukas Czerner 		/*
4821b8a86845SLukas Czerner 		* Mark that we allocate beyond EOF so the subsequent truncate
4822b8a86845SLukas Czerner 		* can proceed even if the new size is the same as i_size.
4823b8a86845SLukas Czerner 		*/
4824b8a86845SLukas Czerner 		if ((offset + len) > i_size_read(inode))
4825b8a86845SLukas Czerner 			ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4826b8a86845SLukas Czerner 	}
4827b8a86845SLukas Czerner 	ext4_mark_inode_dirty(handle, inode);
4828b8a86845SLukas Czerner 
4829b8a86845SLukas Czerner 	/* Zero out partial block at the edges of the range */
4830b8a86845SLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset, len);
483167a7d5f5SJan Kara 	if (ret >= 0)
483267a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
4833b8a86845SLukas Czerner 
4834b8a86845SLukas Czerner 	if (file->f_flags & O_SYNC)
4835b8a86845SLukas Czerner 		ext4_handle_sync(handle);
4836b8a86845SLukas Czerner 
4837b8a86845SLukas Czerner 	ext4_journal_stop(handle);
4838b8a86845SLukas Czerner out_mutex:
48395955102cSAl Viro 	inode_unlock(inode);
4840b8a86845SLukas Czerner 	return ret;
4841b8a86845SLukas Czerner }
4842b8a86845SLukas Czerner 
48430e8b6879SLukas Czerner /*
48440e8b6879SLukas Czerner  * preallocate space for a file. This implements ext4's fallocate file
48450e8b6879SLukas Czerner  * operation, which gets called from sys_fallocate system call.
48460e8b6879SLukas Czerner  * For block-mapped files, posix_fallocate should fall back to the method
48470e8b6879SLukas Czerner  * of writing zeroes to the required new blocks (the same behavior which is
48480e8b6879SLukas Czerner  * expected for file systems which do not support fallocate() system call).
48490e8b6879SLukas Czerner  */
48500e8b6879SLukas Czerner long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
48510e8b6879SLukas Czerner {
48520e8b6879SLukas Czerner 	struct inode *inode = file_inode(file);
48530e8b6879SLukas Czerner 	loff_t new_size = 0;
48540e8b6879SLukas Czerner 	unsigned int max_blocks;
48550e8b6879SLukas Czerner 	int ret = 0;
48560e8b6879SLukas Czerner 	int flags;
48570e8b6879SLukas Czerner 	ext4_lblk_t lblk;
48580e8b6879SLukas Czerner 	unsigned int blkbits = inode->i_blkbits;
48590e8b6879SLukas Czerner 
48602058f83aSMichael Halcrow 	/*
48612058f83aSMichael Halcrow 	 * Encrypted inodes can't handle collapse range or insert
48622058f83aSMichael Halcrow 	 * range since we would need to re-encrypt blocks with a
48632058f83aSMichael Halcrow 	 * different IV or XTS tweak (which are based on the logical
48642058f83aSMichael Halcrow 	 * block number).
48652058f83aSMichael Halcrow 	 *
48662058f83aSMichael Halcrow 	 * XXX It's not clear why zero range isn't working, but we'll
48672058f83aSMichael Halcrow 	 * leave it disabled for encrypted inodes for now.  This is a
48682058f83aSMichael Halcrow 	 * bug we should fix....
48692058f83aSMichael Halcrow 	 */
4870592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) &&
4871331573feSNamjae Jeon 	    (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
4872331573feSNamjae Jeon 		     FALLOC_FL_ZERO_RANGE)))
48732058f83aSMichael Halcrow 		return -EOPNOTSUPP;
48742058f83aSMichael Halcrow 
48750e8b6879SLukas Czerner 	/* Return error if mode is not supported */
48760e8b6879SLukas Czerner 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4877331573feSNamjae Jeon 		     FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4878331573feSNamjae Jeon 		     FALLOC_FL_INSERT_RANGE))
48790e8b6879SLukas Czerner 		return -EOPNOTSUPP;
48800e8b6879SLukas Czerner 
48810e8b6879SLukas Czerner 	if (mode & FALLOC_FL_PUNCH_HOLE)
48820e8b6879SLukas Czerner 		return ext4_punch_hole(inode, offset, len);
48830e8b6879SLukas Czerner 
48840e8b6879SLukas Czerner 	ret = ext4_convert_inline_data(inode);
48850e8b6879SLukas Czerner 	if (ret)
48860e8b6879SLukas Czerner 		return ret;
48870e8b6879SLukas Czerner 
488840c406c7STheodore Ts'o 	if (mode & FALLOC_FL_COLLAPSE_RANGE)
488940c406c7STheodore Ts'o 		return ext4_collapse_range(inode, offset, len);
489040c406c7STheodore Ts'o 
4891331573feSNamjae Jeon 	if (mode & FALLOC_FL_INSERT_RANGE)
4892331573feSNamjae Jeon 		return ext4_insert_range(inode, offset, len);
4893331573feSNamjae Jeon 
4894b8a86845SLukas Czerner 	if (mode & FALLOC_FL_ZERO_RANGE)
4895b8a86845SLukas Czerner 		return ext4_zero_range(file, offset, len, mode);
4896b8a86845SLukas Czerner 
48970e8b6879SLukas Czerner 	trace_ext4_fallocate_enter(inode, offset, len, mode);
48980e8b6879SLukas Czerner 	lblk = offset >> blkbits;
48990e8b6879SLukas Czerner 
4900518eaa63SFabian Frederick 	max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4901556615dcSLukas Czerner 	flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
49020e8b6879SLukas Czerner 	if (mode & FALLOC_FL_KEEP_SIZE)
49030e8b6879SLukas Czerner 		flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
49040e8b6879SLukas Czerner 
49055955102cSAl Viro 	inode_lock(inode);
49060e8b6879SLukas Czerner 
4907280227a7SDavide Italiano 	/*
4908280227a7SDavide Italiano 	 * We only support preallocation for extent-based files only
4909280227a7SDavide Italiano 	 */
4910280227a7SDavide Italiano 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4911280227a7SDavide Italiano 		ret = -EOPNOTSUPP;
4912280227a7SDavide Italiano 		goto out;
4913280227a7SDavide Italiano 	}
4914280227a7SDavide Italiano 
49150e8b6879SLukas Czerner 	if (!(mode & FALLOC_FL_KEEP_SIZE) &&
491651e3ae81STheodore Ts'o 	    (offset + len > i_size_read(inode) ||
491751e3ae81STheodore Ts'o 	     offset + len > EXT4_I(inode)->i_disksize)) {
49180e8b6879SLukas Czerner 		new_size = offset + len;
49190e8b6879SLukas Czerner 		ret = inode_newsize_ok(inode, new_size);
49200e8b6879SLukas Czerner 		if (ret)
49210e8b6879SLukas Czerner 			goto out;
49220e8b6879SLukas Czerner 	}
49230e8b6879SLukas Czerner 
492417048e8aSJan Kara 	/* Wait all existing dio workers, newcomers will block on i_mutex */
492517048e8aSJan Kara 	inode_dio_wait(inode);
492617048e8aSJan Kara 
492777a2e84dSTahsin Erdogan 	ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
49280e8b6879SLukas Czerner 	if (ret)
49290e8b6879SLukas Czerner 		goto out;
49300e8b6879SLukas Czerner 
4931c174e6d6SDmitry Monakhov 	if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
4932c174e6d6SDmitry Monakhov 		ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
4933c174e6d6SDmitry Monakhov 						EXT4_I(inode)->i_sync_tid);
4934f282ac19SLukas Czerner 	}
4935f282ac19SLukas Czerner out:
49365955102cSAl Viro 	inode_unlock(inode);
49370e8b6879SLukas Czerner 	trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
49380e8b6879SLukas Czerner 	return ret;
4939a2df2a63SAmit Arora }
49406873fa0dSEric Sandeen 
49416873fa0dSEric Sandeen /*
49420031462bSMingming Cao  * This function convert a range of blocks to written extents
49430031462bSMingming Cao  * The caller of this function will pass the start offset and the size.
49440031462bSMingming Cao  * all unwritten extents within this range will be converted to
49450031462bSMingming Cao  * written extents.
49460031462bSMingming Cao  *
49470031462bSMingming Cao  * This function is called from the direct IO end io call back
49480031462bSMingming Cao  * function, to convert the fallocated extents after IO is completed.
4949109f5565SMingming  * Returns 0 on success.
49500031462bSMingming Cao  */
49516b523df4SJan Kara int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
49526b523df4SJan Kara 				   loff_t offset, ssize_t len)
49530031462bSMingming Cao {
49540031462bSMingming Cao 	unsigned int max_blocks;
49550031462bSMingming Cao 	int ret = 0;
49560031462bSMingming Cao 	int ret2 = 0;
49572ed88685STheodore Ts'o 	struct ext4_map_blocks map;
4958a00713eaSRitesh Harjani 	unsigned int blkbits = inode->i_blkbits;
4959a00713eaSRitesh Harjani 	unsigned int credits = 0;
49600031462bSMingming Cao 
49612ed88685STheodore Ts'o 	map.m_lblk = offset >> blkbits;
4962518eaa63SFabian Frederick 	max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4963518eaa63SFabian Frederick 
4964a00713eaSRitesh Harjani 	if (!handle) {
49656b523df4SJan Kara 		/*
49660031462bSMingming Cao 		 * credits to insert 1 extent into extent tree
49670031462bSMingming Cao 		 */
49680031462bSMingming Cao 		credits = ext4_chunk_trans_blocks(inode, max_blocks);
49696b523df4SJan Kara 	}
49700031462bSMingming Cao 	while (ret >= 0 && ret < max_blocks) {
49712ed88685STheodore Ts'o 		map.m_lblk += ret;
49722ed88685STheodore Ts'o 		map.m_len = (max_blocks -= ret);
49736b523df4SJan Kara 		if (credits) {
49746b523df4SJan Kara 			handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
49756b523df4SJan Kara 						    credits);
49760031462bSMingming Cao 			if (IS_ERR(handle)) {
49770031462bSMingming Cao 				ret = PTR_ERR(handle);
49780031462bSMingming Cao 				break;
49790031462bSMingming Cao 			}
49806b523df4SJan Kara 		}
49812ed88685STheodore Ts'o 		ret = ext4_map_blocks(handle, inode, &map,
4982c7064ef1SJiaying Zhang 				      EXT4_GET_BLOCKS_IO_CONVERT_EXT);
4983b06acd38SLukas Czerner 		if (ret <= 0)
4984b06acd38SLukas Czerner 			ext4_warning(inode->i_sb,
4985b06acd38SLukas Czerner 				     "inode #%lu: block %u: len %u: "
498692b97816STheodore Ts'o 				     "ext4_ext_map_blocks returned %d",
4987b06acd38SLukas Czerner 				     inode->i_ino, map.m_lblk,
498892b97816STheodore Ts'o 				     map.m_len, ret);
49890031462bSMingming Cao 		ext4_mark_inode_dirty(handle, inode);
49906b523df4SJan Kara 		if (credits)
49910031462bSMingming Cao 			ret2 = ext4_journal_stop(handle);
49920031462bSMingming Cao 		if (ret <= 0 || ret2)
49930031462bSMingming Cao 			break;
49940031462bSMingming Cao 	}
49950031462bSMingming Cao 	return ret > 0 ? ret2 : ret;
49960031462bSMingming Cao }
49976d9c85ebSYongqiang Yang 
4998a00713eaSRitesh Harjani int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
4999a00713eaSRitesh Harjani {
5000a00713eaSRitesh Harjani 	int ret, err = 0;
5001c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
5002a00713eaSRitesh Harjani 
5003a00713eaSRitesh Harjani 	/*
5004a00713eaSRitesh Harjani 	 * This is somewhat ugly but the idea is clear: When transaction is
5005a00713eaSRitesh Harjani 	 * reserved, everything goes into it. Otherwise we rather start several
5006a00713eaSRitesh Harjani 	 * smaller transactions for conversion of each extent separately.
5007a00713eaSRitesh Harjani 	 */
5008a00713eaSRitesh Harjani 	if (handle) {
5009a00713eaSRitesh Harjani 		handle = ext4_journal_start_reserved(handle,
5010a00713eaSRitesh Harjani 						     EXT4_HT_EXT_CONVERT);
5011a00713eaSRitesh Harjani 		if (IS_ERR(handle))
5012a00713eaSRitesh Harjani 			return PTR_ERR(handle);
5013a00713eaSRitesh Harjani 	}
5014a00713eaSRitesh Harjani 
5015c8cc8816SRitesh Harjani 	list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
5016a00713eaSRitesh Harjani 		ret = ext4_convert_unwritten_extents(handle, io_end->inode,
5017c8cc8816SRitesh Harjani 						     io_end_vec->offset,
5018c8cc8816SRitesh Harjani 						     io_end_vec->size);
5019c8cc8816SRitesh Harjani 		if (ret)
5020c8cc8816SRitesh Harjani 			break;
5021c8cc8816SRitesh Harjani 	}
5022c8cc8816SRitesh Harjani 
5023a00713eaSRitesh Harjani 	if (handle)
5024a00713eaSRitesh Harjani 		err = ext4_journal_stop(handle);
5025a00713eaSRitesh Harjani 
5026a00713eaSRitesh Harjani 	return ret < 0 ? ret : err;
5027a00713eaSRitesh Harjani }
5028a00713eaSRitesh Harjani 
50290031462bSMingming Cao /*
503069eb33dcSZheng Liu  * If newes is not existing extent (newes->ec_pblk equals zero) find
503169eb33dcSZheng Liu  * delayed extent at start of newes and update newes accordingly and
503291dd8c11SLukas Czerner  * return start of the next delayed extent.
503391dd8c11SLukas Czerner  *
503469eb33dcSZheng Liu  * If newes is existing extent (newes->ec_pblk is not equal zero)
503591dd8c11SLukas Czerner  * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
503669eb33dcSZheng Liu  * extent found. Leave newes unmodified.
50376873fa0dSEric Sandeen  */
503891dd8c11SLukas Czerner static int ext4_find_delayed_extent(struct inode *inode,
503969eb33dcSZheng Liu 				    struct extent_status *newes)
50406873fa0dSEric Sandeen {
5041b3aff3e3SZheng Liu 	struct extent_status es;
5042be401363SZheng Liu 	ext4_lblk_t block, next_del;
50436873fa0dSEric Sandeen 
504469eb33dcSZheng Liu 	if (newes->es_pblk == 0) {
5045ad431025SEric Whitney 		ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
5046ad431025SEric Whitney 					  newes->es_lblk,
5047ad431025SEric Whitney 					  newes->es_lblk + newes->es_len - 1,
5048ad431025SEric Whitney 					  &es);
5049e30b5dcaSYan, Zheng 
50506d9c85ebSYongqiang Yang 		/*
505169eb33dcSZheng Liu 		 * No extent in extent-tree contains block @newes->es_pblk,
50526d9c85ebSYongqiang Yang 		 * then the block may stay in 1)a hole or 2)delayed-extent.
50536d9c85ebSYongqiang Yang 		 */
505406b0c886SZheng Liu 		if (es.es_len == 0)
5055b3aff3e3SZheng Liu 			/* A hole found. */
505691dd8c11SLukas Czerner 			return 0;
50576d9c85ebSYongqiang Yang 
505869eb33dcSZheng Liu 		if (es.es_lblk > newes->es_lblk) {
5059b3aff3e3SZheng Liu 			/* A hole found. */
506069eb33dcSZheng Liu 			newes->es_len = min(es.es_lblk - newes->es_lblk,
506169eb33dcSZheng Liu 					    newes->es_len);
506291dd8c11SLukas Czerner 			return 0;
50636873fa0dSEric Sandeen 		}
50646d9c85ebSYongqiang Yang 
506569eb33dcSZheng Liu 		newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
50666d9c85ebSYongqiang Yang 	}
50676873fa0dSEric Sandeen 
506869eb33dcSZheng Liu 	block = newes->es_lblk + newes->es_len;
5069ad431025SEric Whitney 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed, block,
5070ad431025SEric Whitney 				  EXT_MAX_BLOCKS, &es);
5071be401363SZheng Liu 	if (es.es_len == 0)
5072be401363SZheng Liu 		next_del = EXT_MAX_BLOCKS;
5073be401363SZheng Liu 	else
5074be401363SZheng Liu 		next_del = es.es_lblk;
5075be401363SZheng Liu 
507691dd8c11SLukas Czerner 	return next_del;
50776873fa0dSEric Sandeen }
50786873fa0dSEric Sandeen 
50793a06d778SAneesh Kumar K.V static int ext4_xattr_fiemap(struct inode *inode,
50803a06d778SAneesh Kumar K.V 				struct fiemap_extent_info *fieinfo)
50816873fa0dSEric Sandeen {
50826873fa0dSEric Sandeen 	__u64 physical = 0;
50836873fa0dSEric Sandeen 	__u64 length;
50846873fa0dSEric Sandeen 	__u32 flags = FIEMAP_EXTENT_LAST;
50856873fa0dSEric Sandeen 	int blockbits = inode->i_sb->s_blocksize_bits;
50866873fa0dSEric Sandeen 	int error = 0;
50876873fa0dSEric Sandeen 
50886873fa0dSEric Sandeen 	/* in-inode? */
508919f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
50906873fa0dSEric Sandeen 		struct ext4_iloc iloc;
50916873fa0dSEric Sandeen 		int offset;	/* offset of xattr in inode */
50926873fa0dSEric Sandeen 
50936873fa0dSEric Sandeen 		error = ext4_get_inode_loc(inode, &iloc);
50946873fa0dSEric Sandeen 		if (error)
50956873fa0dSEric Sandeen 			return error;
5096a60697f4SJan Kara 		physical = (__u64)iloc.bh->b_blocknr << blockbits;
50976873fa0dSEric Sandeen 		offset = EXT4_GOOD_OLD_INODE_SIZE +
50986873fa0dSEric Sandeen 				EXT4_I(inode)->i_extra_isize;
50996873fa0dSEric Sandeen 		physical += offset;
51006873fa0dSEric Sandeen 		length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
51016873fa0dSEric Sandeen 		flags |= FIEMAP_EXTENT_DATA_INLINE;
5102fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
51036873fa0dSEric Sandeen 	} else { /* external block */
5104a60697f4SJan Kara 		physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
51056873fa0dSEric Sandeen 		length = inode->i_sb->s_blocksize;
51066873fa0dSEric Sandeen 	}
51076873fa0dSEric Sandeen 
51086873fa0dSEric Sandeen 	if (physical)
51096873fa0dSEric Sandeen 		error = fiemap_fill_next_extent(fieinfo, 0, physical,
51106873fa0dSEric Sandeen 						length, flags);
51116873fa0dSEric Sandeen 	return (error < 0 ? error : 0);
51126873fa0dSEric Sandeen }
51136873fa0dSEric Sandeen 
5114bb5835edSTheodore Ts'o static int _ext4_fiemap(struct inode *inode,
5115bb5835edSTheodore Ts'o 			struct fiemap_extent_info *fieinfo,
5116bb5835edSTheodore Ts'o 			__u64 start, __u64 len,
5117bb5835edSTheodore Ts'o 			int (*fill)(struct inode *, ext4_lblk_t,
5118bb5835edSTheodore Ts'o 				    ext4_lblk_t,
5119bb5835edSTheodore Ts'o 				    struct fiemap_extent_info *))
51206873fa0dSEric Sandeen {
51216873fa0dSEric Sandeen 	ext4_lblk_t start_blk;
5122bb5835edSTheodore Ts'o 	u32 ext4_fiemap_flags = FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR;
5123bb5835edSTheodore Ts'o 
51246873fa0dSEric Sandeen 	int error = 0;
51256873fa0dSEric Sandeen 
512694191985STao Ma 	if (ext4_has_inline_data(inode)) {
512794191985STao Ma 		int has_inline = 1;
512894191985STao Ma 
5129d952d69eSDmitry Monakhov 		error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5130d952d69eSDmitry Monakhov 						start, len);
513194191985STao Ma 
513294191985STao Ma 		if (has_inline)
513394191985STao Ma 			return error;
513494191985STao Ma 	}
513594191985STao Ma 
51367869a4a6STheodore Ts'o 	if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
51377869a4a6STheodore Ts'o 		error = ext4_ext_precache(inode);
51387869a4a6STheodore Ts'o 		if (error)
51397869a4a6STheodore Ts'o 			return error;
5140bb5835edSTheodore Ts'o 		fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
51417869a4a6STheodore Ts'o 	}
51427869a4a6STheodore Ts'o 
51436873fa0dSEric Sandeen 	/* fallback to generic here if not in extents fmt */
5144bb5835edSTheodore Ts'o 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
5145bb5835edSTheodore Ts'o 	    fill == ext4_fill_fiemap_extents)
5146ad7fefb1STheodore Ts'o 		return generic_block_fiemap(inode, fieinfo, start, len,
51476873fa0dSEric Sandeen 			ext4_get_block);
51486873fa0dSEric Sandeen 
5149bb5835edSTheodore Ts'o 	if (fill == ext4_fill_es_cache_info)
5150bb5835edSTheodore Ts'o 		ext4_fiemap_flags &= FIEMAP_FLAG_XATTR;
5151bb5835edSTheodore Ts'o 	if (fiemap_check_flags(fieinfo, ext4_fiemap_flags))
51526873fa0dSEric Sandeen 		return -EBADR;
51536873fa0dSEric Sandeen 
51546873fa0dSEric Sandeen 	if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
51556873fa0dSEric Sandeen 		error = ext4_xattr_fiemap(inode, fieinfo);
51566873fa0dSEric Sandeen 	} else {
5157aca92ff6SLeonard Michlmayr 		ext4_lblk_t len_blks;
5158aca92ff6SLeonard Michlmayr 		__u64 last_blk;
5159aca92ff6SLeonard Michlmayr 
51606873fa0dSEric Sandeen 		start_blk = start >> inode->i_sb->s_blocksize_bits;
5161aca92ff6SLeonard Michlmayr 		last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5162f17722f9SLukas Czerner 		if (last_blk >= EXT_MAX_BLOCKS)
5163f17722f9SLukas Czerner 			last_blk = EXT_MAX_BLOCKS-1;
5164aca92ff6SLeonard Michlmayr 		len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
51656873fa0dSEric Sandeen 
51666873fa0dSEric Sandeen 		/*
516791dd8c11SLukas Czerner 		 * Walk the extent tree gathering extent information
516891dd8c11SLukas Czerner 		 * and pushing extents back to the user.
51696873fa0dSEric Sandeen 		 */
5170bb5835edSTheodore Ts'o 		error = fill(inode, start_blk, len_blks, fieinfo);
51716873fa0dSEric Sandeen 	}
51726873fa0dSEric Sandeen 	return error;
51736873fa0dSEric Sandeen }
51749eb79482SNamjae Jeon 
5175bb5835edSTheodore Ts'o int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5176bb5835edSTheodore Ts'o 		__u64 start, __u64 len)
5177bb5835edSTheodore Ts'o {
5178bb5835edSTheodore Ts'o 	return _ext4_fiemap(inode, fieinfo, start, len,
5179bb5835edSTheodore Ts'o 			    ext4_fill_fiemap_extents);
5180bb5835edSTheodore Ts'o }
5181bb5835edSTheodore Ts'o 
5182bb5835edSTheodore Ts'o int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
5183bb5835edSTheodore Ts'o 		      __u64 start, __u64 len)
5184bb5835edSTheodore Ts'o {
5185bb5835edSTheodore Ts'o 	if (ext4_has_inline_data(inode)) {
5186bb5835edSTheodore Ts'o 		int has_inline;
5187bb5835edSTheodore Ts'o 
5188bb5835edSTheodore Ts'o 		down_read(&EXT4_I(inode)->xattr_sem);
5189bb5835edSTheodore Ts'o 		has_inline = ext4_has_inline_data(inode);
5190bb5835edSTheodore Ts'o 		up_read(&EXT4_I(inode)->xattr_sem);
5191bb5835edSTheodore Ts'o 		if (has_inline)
5192bb5835edSTheodore Ts'o 			return 0;
5193bb5835edSTheodore Ts'o 	}
5194bb5835edSTheodore Ts'o 
5195bb5835edSTheodore Ts'o 	return _ext4_fiemap(inode, fieinfo, start, len,
5196bb5835edSTheodore Ts'o 			    ext4_fill_es_cache_info);
5197bb5835edSTheodore Ts'o }
5198bb5835edSTheodore Ts'o 
5199bb5835edSTheodore Ts'o 
52009eb79482SNamjae Jeon /*
52019eb79482SNamjae Jeon  * ext4_access_path:
52029eb79482SNamjae Jeon  * Function to access the path buffer for marking it dirty.
52039eb79482SNamjae Jeon  * It also checks if there are sufficient credits left in the journal handle
52049eb79482SNamjae Jeon  * to update path.
52059eb79482SNamjae Jeon  */
52069eb79482SNamjae Jeon static int
52079eb79482SNamjae Jeon ext4_access_path(handle_t *handle, struct inode *inode,
52089eb79482SNamjae Jeon 		struct ext4_ext_path *path)
52099eb79482SNamjae Jeon {
52109eb79482SNamjae Jeon 	int credits, err;
52119eb79482SNamjae Jeon 
52129eb79482SNamjae Jeon 	if (!ext4_handle_valid(handle))
52139eb79482SNamjae Jeon 		return 0;
52149eb79482SNamjae Jeon 
52159eb79482SNamjae Jeon 	/*
52169eb79482SNamjae Jeon 	 * Check if need to extend journal credits
52179eb79482SNamjae Jeon 	 * 3 for leaf, sb, and inode plus 2 (bmap and group
52189eb79482SNamjae Jeon 	 * descriptor) for each block group; assume two block
52199eb79482SNamjae Jeon 	 * groups
52209eb79482SNamjae Jeon 	 */
52219eb79482SNamjae Jeon 	if (handle->h_buffer_credits < 7) {
52229eb79482SNamjae Jeon 		credits = ext4_writepage_trans_blocks(inode);
52239eb79482SNamjae Jeon 		err = ext4_ext_truncate_extend_restart(handle, inode, credits);
52249eb79482SNamjae Jeon 		/* EAGAIN is success */
52259eb79482SNamjae Jeon 		if (err && err != -EAGAIN)
52269eb79482SNamjae Jeon 			return err;
52279eb79482SNamjae Jeon 	}
52289eb79482SNamjae Jeon 
52299eb79482SNamjae Jeon 	err = ext4_ext_get_access(handle, inode, path);
52309eb79482SNamjae Jeon 	return err;
52319eb79482SNamjae Jeon }
52329eb79482SNamjae Jeon 
52339eb79482SNamjae Jeon /*
52349eb79482SNamjae Jeon  * ext4_ext_shift_path_extents:
52359eb79482SNamjae Jeon  * Shift the extents of a path structure lying between path[depth].p_ext
5236331573feSNamjae Jeon  * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5237331573feSNamjae Jeon  * if it is right shift or left shift operation.
52389eb79482SNamjae Jeon  */
52399eb79482SNamjae Jeon static int
52409eb79482SNamjae Jeon ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
52419eb79482SNamjae Jeon 			    struct inode *inode, handle_t *handle,
5242331573feSNamjae Jeon 			    enum SHIFT_DIRECTION SHIFT)
52439eb79482SNamjae Jeon {
52449eb79482SNamjae Jeon 	int depth, err = 0;
52459eb79482SNamjae Jeon 	struct ext4_extent *ex_start, *ex_last;
52469eb79482SNamjae Jeon 	bool update = 0;
52479eb79482SNamjae Jeon 	depth = path->p_depth;
52489eb79482SNamjae Jeon 
52499eb79482SNamjae Jeon 	while (depth >= 0) {
52509eb79482SNamjae Jeon 		if (depth == path->p_depth) {
52519eb79482SNamjae Jeon 			ex_start = path[depth].p_ext;
52529eb79482SNamjae Jeon 			if (!ex_start)
52536a797d27SDarrick J. Wong 				return -EFSCORRUPTED;
52549eb79482SNamjae Jeon 
52559eb79482SNamjae Jeon 			ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
52569eb79482SNamjae Jeon 
52579eb79482SNamjae Jeon 			err = ext4_access_path(handle, inode, path + depth);
52589eb79482SNamjae Jeon 			if (err)
52599eb79482SNamjae Jeon 				goto out;
52609eb79482SNamjae Jeon 
52619eb79482SNamjae Jeon 			if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
52629eb79482SNamjae Jeon 				update = 1;
52639eb79482SNamjae Jeon 
52649eb79482SNamjae Jeon 			while (ex_start <= ex_last) {
5265331573feSNamjae Jeon 				if (SHIFT == SHIFT_LEFT) {
5266331573feSNamjae Jeon 					le32_add_cpu(&ex_start->ee_block,
5267331573feSNamjae Jeon 						-shift);
52686dd834efSLukas Czerner 					/* Try to merge to the left. */
52696dd834efSLukas Czerner 					if ((ex_start >
5270331573feSNamjae Jeon 					    EXT_FIRST_EXTENT(path[depth].p_hdr))
5271331573feSNamjae Jeon 					    &&
52726dd834efSLukas Czerner 					    ext4_ext_try_to_merge_right(inode,
52739eb79482SNamjae Jeon 					    path, ex_start - 1))
52749eb79482SNamjae Jeon 						ex_last--;
52756dd834efSLukas Czerner 					else
52769eb79482SNamjae Jeon 						ex_start++;
5277331573feSNamjae Jeon 				} else {
5278331573feSNamjae Jeon 					le32_add_cpu(&ex_last->ee_block, shift);
5279331573feSNamjae Jeon 					ext4_ext_try_to_merge_right(inode, path,
5280331573feSNamjae Jeon 						ex_last);
5281331573feSNamjae Jeon 					ex_last--;
5282331573feSNamjae Jeon 				}
52839eb79482SNamjae Jeon 			}
52849eb79482SNamjae Jeon 			err = ext4_ext_dirty(handle, inode, path + depth);
52859eb79482SNamjae Jeon 			if (err)
52869eb79482SNamjae Jeon 				goto out;
52879eb79482SNamjae Jeon 
52889eb79482SNamjae Jeon 			if (--depth < 0 || !update)
52899eb79482SNamjae Jeon 				break;
52909eb79482SNamjae Jeon 		}
52919eb79482SNamjae Jeon 
52929eb79482SNamjae Jeon 		/* Update index too */
52939eb79482SNamjae Jeon 		err = ext4_access_path(handle, inode, path + depth);
52949eb79482SNamjae Jeon 		if (err)
52959eb79482SNamjae Jeon 			goto out;
52969eb79482SNamjae Jeon 
5297331573feSNamjae Jeon 		if (SHIFT == SHIFT_LEFT)
5298847c6c42SZheng Liu 			le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5299331573feSNamjae Jeon 		else
5300331573feSNamjae Jeon 			le32_add_cpu(&path[depth].p_idx->ei_block, shift);
53019eb79482SNamjae Jeon 		err = ext4_ext_dirty(handle, inode, path + depth);
53029eb79482SNamjae Jeon 		if (err)
53039eb79482SNamjae Jeon 			goto out;
53049eb79482SNamjae Jeon 
53059eb79482SNamjae Jeon 		/* we are done if current index is not a starting index */
53069eb79482SNamjae Jeon 		if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
53079eb79482SNamjae Jeon 			break;
53089eb79482SNamjae Jeon 
53099eb79482SNamjae Jeon 		depth--;
53109eb79482SNamjae Jeon 	}
53119eb79482SNamjae Jeon 
53129eb79482SNamjae Jeon out:
53139eb79482SNamjae Jeon 	return err;
53149eb79482SNamjae Jeon }
53159eb79482SNamjae Jeon 
53169eb79482SNamjae Jeon /*
53179eb79482SNamjae Jeon  * ext4_ext_shift_extents:
5318331573feSNamjae Jeon  * All the extents which lies in the range from @start to the last allocated
5319331573feSNamjae Jeon  * block for the @inode are shifted either towards left or right (depending
5320331573feSNamjae Jeon  * upon @SHIFT) by @shift blocks.
53219eb79482SNamjae Jeon  * On success, 0 is returned, error otherwise.
53229eb79482SNamjae Jeon  */
53239eb79482SNamjae Jeon static int
53249eb79482SNamjae Jeon ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5325331573feSNamjae Jeon 		       ext4_lblk_t start, ext4_lblk_t shift,
5326331573feSNamjae Jeon 		       enum SHIFT_DIRECTION SHIFT)
53279eb79482SNamjae Jeon {
53289eb79482SNamjae Jeon 	struct ext4_ext_path *path;
53299eb79482SNamjae Jeon 	int ret = 0, depth;
53309eb79482SNamjae Jeon 	struct ext4_extent *extent;
5331331573feSNamjae Jeon 	ext4_lblk_t stop, *iterator, ex_start, ex_end;
53329eb79482SNamjae Jeon 
53339eb79482SNamjae Jeon 	/* Let path point to the last extent */
533403e916faSRoman Pen 	path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
533503e916faSRoman Pen 				EXT4_EX_NOCACHE);
53369eb79482SNamjae Jeon 	if (IS_ERR(path))
53379eb79482SNamjae Jeon 		return PTR_ERR(path);
53389eb79482SNamjae Jeon 
53399eb79482SNamjae Jeon 	depth = path->p_depth;
53409eb79482SNamjae Jeon 	extent = path[depth].p_ext;
5341ee4bd0d9STheodore Ts'o 	if (!extent)
5342ee4bd0d9STheodore Ts'o 		goto out;
53439eb79482SNamjae Jeon 
53442a9b8cbaSRoman Pen 	stop = le32_to_cpu(extent->ee_block);
53459eb79482SNamjae Jeon 
53469eb79482SNamjae Jeon        /*
5347349fa7d6SEric Biggers 	* For left shifts, make sure the hole on the left is big enough to
5348349fa7d6SEric Biggers 	* accommodate the shift.  For right shifts, make sure the last extent
5349349fa7d6SEric Biggers 	* won't be shifted beyond EXT_MAX_BLOCKS.
53509eb79482SNamjae Jeon 	*/
5351331573feSNamjae Jeon 	if (SHIFT == SHIFT_LEFT) {
535203e916faSRoman Pen 		path = ext4_find_extent(inode, start - 1, &path,
535303e916faSRoman Pen 					EXT4_EX_NOCACHE);
53548dc79ec4SDmitry Monakhov 		if (IS_ERR(path))
53558dc79ec4SDmitry Monakhov 			return PTR_ERR(path);
53569eb79482SNamjae Jeon 		depth = path->p_depth;
53579eb79482SNamjae Jeon 		extent =  path[depth].p_ext;
53588dc79ec4SDmitry Monakhov 		if (extent) {
5359847c6c42SZheng Liu 			ex_start = le32_to_cpu(extent->ee_block);
5360847c6c42SZheng Liu 			ex_end = le32_to_cpu(extent->ee_block) +
5361847c6c42SZheng Liu 				ext4_ext_get_actual_len(extent);
53628dc79ec4SDmitry Monakhov 		} else {
53638dc79ec4SDmitry Monakhov 			ex_start = 0;
53648dc79ec4SDmitry Monakhov 			ex_end = 0;
53658dc79ec4SDmitry Monakhov 		}
53669eb79482SNamjae Jeon 
53679eb79482SNamjae Jeon 		if ((start == ex_start && shift > ex_start) ||
5368331573feSNamjae Jeon 		    (shift > start - ex_end)) {
5369349fa7d6SEric Biggers 			ret = -EINVAL;
5370349fa7d6SEric Biggers 			goto out;
5371349fa7d6SEric Biggers 		}
5372349fa7d6SEric Biggers 	} else {
5373349fa7d6SEric Biggers 		if (shift > EXT_MAX_BLOCKS -
5374349fa7d6SEric Biggers 		    (stop + ext4_ext_get_actual_len(extent))) {
5375349fa7d6SEric Biggers 			ret = -EINVAL;
5376349fa7d6SEric Biggers 			goto out;
5377331573feSNamjae Jeon 		}
5378331573feSNamjae Jeon 	}
5379331573feSNamjae Jeon 
5380331573feSNamjae Jeon 	/*
5381331573feSNamjae Jeon 	 * In case of left shift, iterator points to start and it is increased
5382331573feSNamjae Jeon 	 * till we reach stop. In case of right shift, iterator points to stop
5383331573feSNamjae Jeon 	 * and it is decreased till we reach start.
5384331573feSNamjae Jeon 	 */
5385331573feSNamjae Jeon 	if (SHIFT == SHIFT_LEFT)
5386331573feSNamjae Jeon 		iterator = &start;
5387331573feSNamjae Jeon 	else
5388331573feSNamjae Jeon 		iterator = &stop;
53899eb79482SNamjae Jeon 
53902a9b8cbaSRoman Pen 	/*
53912a9b8cbaSRoman Pen 	 * Its safe to start updating extents.  Start and stop are unsigned, so
53922a9b8cbaSRoman Pen 	 * in case of right shift if extent with 0 block is reached, iterator
53932a9b8cbaSRoman Pen 	 * becomes NULL to indicate the end of the loop.
53942a9b8cbaSRoman Pen 	 */
53952a9b8cbaSRoman Pen 	while (iterator && start <= stop) {
539603e916faSRoman Pen 		path = ext4_find_extent(inode, *iterator, &path,
539703e916faSRoman Pen 					EXT4_EX_NOCACHE);
53989eb79482SNamjae Jeon 		if (IS_ERR(path))
53999eb79482SNamjae Jeon 			return PTR_ERR(path);
54009eb79482SNamjae Jeon 		depth = path->p_depth;
54019eb79482SNamjae Jeon 		extent = path[depth].p_ext;
5402a18ed359SDmitry Monakhov 		if (!extent) {
5403a18ed359SDmitry Monakhov 			EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5404331573feSNamjae Jeon 					 (unsigned long) *iterator);
54056a797d27SDarrick J. Wong 			return -EFSCORRUPTED;
5406a18ed359SDmitry Monakhov 		}
5407331573feSNamjae Jeon 		if (SHIFT == SHIFT_LEFT && *iterator >
5408331573feSNamjae Jeon 		    le32_to_cpu(extent->ee_block)) {
54099eb79482SNamjae Jeon 			/* Hole, move to the next extent */
5410f8fb4f41SDmitry Monakhov 			if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5411f8fb4f41SDmitry Monakhov 				path[depth].p_ext++;
5412f8fb4f41SDmitry Monakhov 			} else {
5413331573feSNamjae Jeon 				*iterator = ext4_ext_next_allocated_block(path);
5414f8fb4f41SDmitry Monakhov 				continue;
54159eb79482SNamjae Jeon 			}
54169eb79482SNamjae Jeon 		}
5417331573feSNamjae Jeon 
5418331573feSNamjae Jeon 		if (SHIFT == SHIFT_LEFT) {
5419331573feSNamjae Jeon 			extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5420331573feSNamjae Jeon 			*iterator = le32_to_cpu(extent->ee_block) +
5421331573feSNamjae Jeon 					ext4_ext_get_actual_len(extent);
5422331573feSNamjae Jeon 		} else {
5423331573feSNamjae Jeon 			extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
54242a9b8cbaSRoman Pen 			if (le32_to_cpu(extent->ee_block) > 0)
54252a9b8cbaSRoman Pen 				*iterator = le32_to_cpu(extent->ee_block) - 1;
54262a9b8cbaSRoman Pen 			else
54272a9b8cbaSRoman Pen 				/* Beginning is reached, end of the loop */
54282a9b8cbaSRoman Pen 				iterator = NULL;
5429331573feSNamjae Jeon 			/* Update path extent in case we need to stop */
5430331573feSNamjae Jeon 			while (le32_to_cpu(extent->ee_block) < start)
5431331573feSNamjae Jeon 				extent++;
5432331573feSNamjae Jeon 			path[depth].p_ext = extent;
5433331573feSNamjae Jeon 		}
54349eb79482SNamjae Jeon 		ret = ext4_ext_shift_path_extents(path, shift, inode,
5435331573feSNamjae Jeon 				handle, SHIFT);
54369eb79482SNamjae Jeon 		if (ret)
54379eb79482SNamjae Jeon 			break;
54389eb79482SNamjae Jeon 	}
5439ee4bd0d9STheodore Ts'o out:
5440ee4bd0d9STheodore Ts'o 	ext4_ext_drop_refs(path);
5441ee4bd0d9STheodore Ts'o 	kfree(path);
54429eb79482SNamjae Jeon 	return ret;
54439eb79482SNamjae Jeon }
54449eb79482SNamjae Jeon 
54459eb79482SNamjae Jeon /*
54469eb79482SNamjae Jeon  * ext4_collapse_range:
54479eb79482SNamjae Jeon  * This implements the fallocate's collapse range functionality for ext4
54489eb79482SNamjae Jeon  * Returns: 0 and non-zero on error.
54499eb79482SNamjae Jeon  */
54509eb79482SNamjae Jeon int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
54519eb79482SNamjae Jeon {
54529eb79482SNamjae Jeon 	struct super_block *sb = inode->i_sb;
54539eb79482SNamjae Jeon 	ext4_lblk_t punch_start, punch_stop;
54549eb79482SNamjae Jeon 	handle_t *handle;
54559eb79482SNamjae Jeon 	unsigned int credits;
5456a8680e0dSNamjae Jeon 	loff_t new_size, ioffset;
54579eb79482SNamjae Jeon 	int ret;
54589eb79482SNamjae Jeon 
5459b9576fc3STheodore Ts'o 	/*
5460b9576fc3STheodore Ts'o 	 * We need to test this early because xfstests assumes that a
5461b9576fc3STheodore Ts'o 	 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5462b9576fc3STheodore Ts'o 	 * system does not support collapse range.
5463b9576fc3STheodore Ts'o 	 */
5464b9576fc3STheodore Ts'o 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5465b9576fc3STheodore Ts'o 		return -EOPNOTSUPP;
5466b9576fc3STheodore Ts'o 
54679eb79482SNamjae Jeon 	/* Collapse range works only on fs block size aligned offsets. */
5468ee98fa3aSNamjae Jeon 	if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5469ee98fa3aSNamjae Jeon 	    len & (EXT4_CLUSTER_SIZE(sb) - 1))
54709eb79482SNamjae Jeon 		return -EINVAL;
54719eb79482SNamjae Jeon 
54729eb79482SNamjae Jeon 	if (!S_ISREG(inode->i_mode))
547386f1ca38STheodore Ts'o 		return -EINVAL;
54749eb79482SNamjae Jeon 
54759eb79482SNamjae Jeon 	trace_ext4_collapse_range(inode, offset, len);
54769eb79482SNamjae Jeon 
54779eb79482SNamjae Jeon 	punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
54789eb79482SNamjae Jeon 	punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
54799eb79482SNamjae Jeon 
54801ce01c4aSNamjae Jeon 	/* Call ext4_force_commit to flush all data in case of data=journal. */
54811ce01c4aSNamjae Jeon 	if (ext4_should_journal_data(inode)) {
54821ce01c4aSNamjae Jeon 		ret = ext4_force_commit(inode->i_sb);
54831ce01c4aSNamjae Jeon 		if (ret)
54841ce01c4aSNamjae Jeon 			return ret;
54851ce01c4aSNamjae Jeon 	}
54861ce01c4aSNamjae Jeon 
54875955102cSAl Viro 	inode_lock(inode);
548823fffa92SLukas Czerner 	/*
548923fffa92SLukas Czerner 	 * There is no need to overlap collapse range with EOF, in which case
549023fffa92SLukas Czerner 	 * it is effectively a truncate operation
549123fffa92SLukas Czerner 	 */
549223fffa92SLukas Czerner 	if (offset + len >= i_size_read(inode)) {
549323fffa92SLukas Czerner 		ret = -EINVAL;
549423fffa92SLukas Czerner 		goto out_mutex;
549523fffa92SLukas Czerner 	}
549623fffa92SLukas Czerner 
54979eb79482SNamjae Jeon 	/* Currently just for extent based files */
54989eb79482SNamjae Jeon 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
54999eb79482SNamjae Jeon 		ret = -EOPNOTSUPP;
55009eb79482SNamjae Jeon 		goto out_mutex;
55019eb79482SNamjae Jeon 	}
55029eb79482SNamjae Jeon 
55039eb79482SNamjae Jeon 	/* Wait for existing dio to complete */
55049eb79482SNamjae Jeon 	inode_dio_wait(inode);
55059eb79482SNamjae Jeon 
5506ea3d7209SJan Kara 	/*
5507ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
5508ea3d7209SJan Kara 	 * page cache.
5509ea3d7209SJan Kara 	 */
5510ea3d7209SJan Kara 	down_write(&EXT4_I(inode)->i_mmap_sem);
5511430657b6SRoss Zwisler 
5512430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
5513430657b6SRoss Zwisler 	if (ret)
5514430657b6SRoss Zwisler 		goto out_mmap;
5515430657b6SRoss Zwisler 
551632ebffd3SJan Kara 	/*
551732ebffd3SJan Kara 	 * Need to round down offset to be aligned with page size boundary
551832ebffd3SJan Kara 	 * for page size > block size.
551932ebffd3SJan Kara 	 */
552032ebffd3SJan Kara 	ioffset = round_down(offset, PAGE_SIZE);
552132ebffd3SJan Kara 	/*
552232ebffd3SJan Kara 	 * Write tail of the last page before removed range since it will get
552332ebffd3SJan Kara 	 * removed from the page cache below.
552432ebffd3SJan Kara 	 */
552532ebffd3SJan Kara 	ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
552632ebffd3SJan Kara 	if (ret)
552732ebffd3SJan Kara 		goto out_mmap;
552832ebffd3SJan Kara 	/*
552932ebffd3SJan Kara 	 * Write data that will be shifted to preserve them when discarding
553032ebffd3SJan Kara 	 * page cache below. We are also protected from pages becoming dirty
553132ebffd3SJan Kara 	 * by i_mmap_sem.
553232ebffd3SJan Kara 	 */
553332ebffd3SJan Kara 	ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
553432ebffd3SJan Kara 					   LLONG_MAX);
553532ebffd3SJan Kara 	if (ret)
553632ebffd3SJan Kara 		goto out_mmap;
5537ea3d7209SJan Kara 	truncate_pagecache(inode, ioffset);
5538ea3d7209SJan Kara 
55399eb79482SNamjae Jeon 	credits = ext4_writepage_trans_blocks(inode);
55409eb79482SNamjae Jeon 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
55419eb79482SNamjae Jeon 	if (IS_ERR(handle)) {
55429eb79482SNamjae Jeon 		ret = PTR_ERR(handle);
5543ea3d7209SJan Kara 		goto out_mmap;
55449eb79482SNamjae Jeon 	}
55459eb79482SNamjae Jeon 
55469eb79482SNamjae Jeon 	down_write(&EXT4_I(inode)->i_data_sem);
55479eb79482SNamjae Jeon 	ext4_discard_preallocations(inode);
55489eb79482SNamjae Jeon 
55499eb79482SNamjae Jeon 	ret = ext4_es_remove_extent(inode, punch_start,
55502c1d2328SLukas Czerner 				    EXT_MAX_BLOCKS - punch_start);
55519eb79482SNamjae Jeon 	if (ret) {
55529eb79482SNamjae Jeon 		up_write(&EXT4_I(inode)->i_data_sem);
55539eb79482SNamjae Jeon 		goto out_stop;
55549eb79482SNamjae Jeon 	}
55559eb79482SNamjae Jeon 
55569eb79482SNamjae Jeon 	ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
55579eb79482SNamjae Jeon 	if (ret) {
55589eb79482SNamjae Jeon 		up_write(&EXT4_I(inode)->i_data_sem);
55599eb79482SNamjae Jeon 		goto out_stop;
55609eb79482SNamjae Jeon 	}
5561ef24f6c2SLukas Czerner 	ext4_discard_preallocations(inode);
55629eb79482SNamjae Jeon 
55639eb79482SNamjae Jeon 	ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5564331573feSNamjae Jeon 				     punch_stop - punch_start, SHIFT_LEFT);
55659eb79482SNamjae Jeon 	if (ret) {
55669eb79482SNamjae Jeon 		up_write(&EXT4_I(inode)->i_data_sem);
55679eb79482SNamjae Jeon 		goto out_stop;
55689eb79482SNamjae Jeon 	}
55699eb79482SNamjae Jeon 
55709eb79482SNamjae Jeon 	new_size = i_size_read(inode) - len;
55719337d5d3SLukas Czerner 	i_size_write(inode, new_size);
55729eb79482SNamjae Jeon 	EXT4_I(inode)->i_disksize = new_size;
55739eb79482SNamjae Jeon 
55749eb79482SNamjae Jeon 	up_write(&EXT4_I(inode)->i_data_sem);
55759eb79482SNamjae Jeon 	if (IS_SYNC(inode))
55769eb79482SNamjae Jeon 		ext4_handle_sync(handle);
5577eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
55789eb79482SNamjae Jeon 	ext4_mark_inode_dirty(handle, inode);
557967a7d5f5SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, 1);
55809eb79482SNamjae Jeon 
55819eb79482SNamjae Jeon out_stop:
55829eb79482SNamjae Jeon 	ext4_journal_stop(handle);
5583ea3d7209SJan Kara out_mmap:
5584ea3d7209SJan Kara 	up_write(&EXT4_I(inode)->i_mmap_sem);
55859eb79482SNamjae Jeon out_mutex:
55865955102cSAl Viro 	inode_unlock(inode);
55879eb79482SNamjae Jeon 	return ret;
55889eb79482SNamjae Jeon }
5589fcf6b1b7SDmitry Monakhov 
5590331573feSNamjae Jeon /*
5591331573feSNamjae Jeon  * ext4_insert_range:
5592331573feSNamjae Jeon  * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5593331573feSNamjae Jeon  * The data blocks starting from @offset to the EOF are shifted by @len
5594331573feSNamjae Jeon  * towards right to create a hole in the @inode. Inode size is increased
5595331573feSNamjae Jeon  * by len bytes.
5596331573feSNamjae Jeon  * Returns 0 on success, error otherwise.
5597331573feSNamjae Jeon  */
5598331573feSNamjae Jeon int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5599331573feSNamjae Jeon {
5600331573feSNamjae Jeon 	struct super_block *sb = inode->i_sb;
5601331573feSNamjae Jeon 	handle_t *handle;
5602331573feSNamjae Jeon 	struct ext4_ext_path *path;
5603331573feSNamjae Jeon 	struct ext4_extent *extent;
5604331573feSNamjae Jeon 	ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5605331573feSNamjae Jeon 	unsigned int credits, ee_len;
5606331573feSNamjae Jeon 	int ret = 0, depth, split_flag = 0;
5607331573feSNamjae Jeon 	loff_t ioffset;
5608331573feSNamjae Jeon 
5609331573feSNamjae Jeon 	/*
5610331573feSNamjae Jeon 	 * We need to test this early because xfstests assumes that an
5611331573feSNamjae Jeon 	 * insert range of (0, 1) will return EOPNOTSUPP if the file
5612331573feSNamjae Jeon 	 * system does not support insert range.
5613331573feSNamjae Jeon 	 */
5614331573feSNamjae Jeon 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5615331573feSNamjae Jeon 		return -EOPNOTSUPP;
5616331573feSNamjae Jeon 
5617331573feSNamjae Jeon 	/* Insert range works only on fs block size aligned offsets. */
5618331573feSNamjae Jeon 	if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5619331573feSNamjae Jeon 			len & (EXT4_CLUSTER_SIZE(sb) - 1))
5620331573feSNamjae Jeon 		return -EINVAL;
5621331573feSNamjae Jeon 
5622331573feSNamjae Jeon 	if (!S_ISREG(inode->i_mode))
5623331573feSNamjae Jeon 		return -EOPNOTSUPP;
5624331573feSNamjae Jeon 
5625331573feSNamjae Jeon 	trace_ext4_insert_range(inode, offset, len);
5626331573feSNamjae Jeon 
5627331573feSNamjae Jeon 	offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5628331573feSNamjae Jeon 	len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5629331573feSNamjae Jeon 
5630331573feSNamjae Jeon 	/* Call ext4_force_commit to flush all data in case of data=journal */
5631331573feSNamjae Jeon 	if (ext4_should_journal_data(inode)) {
5632331573feSNamjae Jeon 		ret = ext4_force_commit(inode->i_sb);
5633331573feSNamjae Jeon 		if (ret)
5634331573feSNamjae Jeon 			return ret;
5635331573feSNamjae Jeon 	}
5636331573feSNamjae Jeon 
56375955102cSAl Viro 	inode_lock(inode);
5638331573feSNamjae Jeon 	/* Currently just for extent based files */
5639331573feSNamjae Jeon 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5640331573feSNamjae Jeon 		ret = -EOPNOTSUPP;
5641331573feSNamjae Jeon 		goto out_mutex;
5642331573feSNamjae Jeon 	}
5643331573feSNamjae Jeon 
5644331573feSNamjae Jeon 	/* Check for wrap through zero */
5645331573feSNamjae Jeon 	if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5646331573feSNamjae Jeon 		ret = -EFBIG;
5647331573feSNamjae Jeon 		goto out_mutex;
5648331573feSNamjae Jeon 	}
5649331573feSNamjae Jeon 
5650331573feSNamjae Jeon 	/* Offset should be less than i_size */
5651331573feSNamjae Jeon 	if (offset >= i_size_read(inode)) {
5652331573feSNamjae Jeon 		ret = -EINVAL;
5653331573feSNamjae Jeon 		goto out_mutex;
5654331573feSNamjae Jeon 	}
5655331573feSNamjae Jeon 
5656331573feSNamjae Jeon 	/* Wait for existing dio to complete */
5657331573feSNamjae Jeon 	inode_dio_wait(inode);
5658331573feSNamjae Jeon 
5659ea3d7209SJan Kara 	/*
5660ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
5661ea3d7209SJan Kara 	 * page cache.
5662ea3d7209SJan Kara 	 */
5663ea3d7209SJan Kara 	down_write(&EXT4_I(inode)->i_mmap_sem);
5664430657b6SRoss Zwisler 
5665430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
5666430657b6SRoss Zwisler 	if (ret)
5667430657b6SRoss Zwisler 		goto out_mmap;
5668430657b6SRoss Zwisler 
566932ebffd3SJan Kara 	/*
567032ebffd3SJan Kara 	 * Need to round down to align start offset to page size boundary
567132ebffd3SJan Kara 	 * for page size > block size.
567232ebffd3SJan Kara 	 */
567332ebffd3SJan Kara 	ioffset = round_down(offset, PAGE_SIZE);
567432ebffd3SJan Kara 	/* Write out all dirty pages */
567532ebffd3SJan Kara 	ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
567632ebffd3SJan Kara 			LLONG_MAX);
567732ebffd3SJan Kara 	if (ret)
567832ebffd3SJan Kara 		goto out_mmap;
5679ea3d7209SJan Kara 	truncate_pagecache(inode, ioffset);
5680ea3d7209SJan Kara 
5681331573feSNamjae Jeon 	credits = ext4_writepage_trans_blocks(inode);
5682331573feSNamjae Jeon 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5683331573feSNamjae Jeon 	if (IS_ERR(handle)) {
5684331573feSNamjae Jeon 		ret = PTR_ERR(handle);
5685ea3d7209SJan Kara 		goto out_mmap;
5686331573feSNamjae Jeon 	}
5687331573feSNamjae Jeon 
5688331573feSNamjae Jeon 	/* Expand file to avoid data loss if there is error while shifting */
5689331573feSNamjae Jeon 	inode->i_size += len;
5690331573feSNamjae Jeon 	EXT4_I(inode)->i_disksize += len;
5691eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
5692331573feSNamjae Jeon 	ret = ext4_mark_inode_dirty(handle, inode);
5693331573feSNamjae Jeon 	if (ret)
5694331573feSNamjae Jeon 		goto out_stop;
5695331573feSNamjae Jeon 
5696331573feSNamjae Jeon 	down_write(&EXT4_I(inode)->i_data_sem);
5697331573feSNamjae Jeon 	ext4_discard_preallocations(inode);
5698331573feSNamjae Jeon 
5699331573feSNamjae Jeon 	path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5700331573feSNamjae Jeon 	if (IS_ERR(path)) {
5701331573feSNamjae Jeon 		up_write(&EXT4_I(inode)->i_data_sem);
5702331573feSNamjae Jeon 		goto out_stop;
5703331573feSNamjae Jeon 	}
5704331573feSNamjae Jeon 
5705331573feSNamjae Jeon 	depth = ext_depth(inode);
5706331573feSNamjae Jeon 	extent = path[depth].p_ext;
5707331573feSNamjae Jeon 	if (extent) {
5708331573feSNamjae Jeon 		ee_start_lblk = le32_to_cpu(extent->ee_block);
5709331573feSNamjae Jeon 		ee_len = ext4_ext_get_actual_len(extent);
5710331573feSNamjae Jeon 
5711331573feSNamjae Jeon 		/*
5712331573feSNamjae Jeon 		 * If offset_lblk is not the starting block of extent, split
5713331573feSNamjae Jeon 		 * the extent @offset_lblk
5714331573feSNamjae Jeon 		 */
5715331573feSNamjae Jeon 		if ((offset_lblk > ee_start_lblk) &&
5716331573feSNamjae Jeon 				(offset_lblk < (ee_start_lblk + ee_len))) {
5717331573feSNamjae Jeon 			if (ext4_ext_is_unwritten(extent))
5718331573feSNamjae Jeon 				split_flag = EXT4_EXT_MARK_UNWRIT1 |
5719331573feSNamjae Jeon 					EXT4_EXT_MARK_UNWRIT2;
5720331573feSNamjae Jeon 			ret = ext4_split_extent_at(handle, inode, &path,
5721331573feSNamjae Jeon 					offset_lblk, split_flag,
5722331573feSNamjae Jeon 					EXT4_EX_NOCACHE |
5723331573feSNamjae Jeon 					EXT4_GET_BLOCKS_PRE_IO |
5724331573feSNamjae Jeon 					EXT4_GET_BLOCKS_METADATA_NOFAIL);
5725331573feSNamjae Jeon 		}
5726331573feSNamjae Jeon 
5727331573feSNamjae Jeon 		ext4_ext_drop_refs(path);
5728331573feSNamjae Jeon 		kfree(path);
5729331573feSNamjae Jeon 		if (ret < 0) {
5730331573feSNamjae Jeon 			up_write(&EXT4_I(inode)->i_data_sem);
5731331573feSNamjae Jeon 			goto out_stop;
5732331573feSNamjae Jeon 		}
5733edf15aa1SFabian Frederick 	} else {
5734edf15aa1SFabian Frederick 		ext4_ext_drop_refs(path);
5735edf15aa1SFabian Frederick 		kfree(path);
5736331573feSNamjae Jeon 	}
5737331573feSNamjae Jeon 
5738331573feSNamjae Jeon 	ret = ext4_es_remove_extent(inode, offset_lblk,
5739331573feSNamjae Jeon 			EXT_MAX_BLOCKS - offset_lblk);
5740331573feSNamjae Jeon 	if (ret) {
5741331573feSNamjae Jeon 		up_write(&EXT4_I(inode)->i_data_sem);
5742331573feSNamjae Jeon 		goto out_stop;
5743331573feSNamjae Jeon 	}
5744331573feSNamjae Jeon 
5745331573feSNamjae Jeon 	/*
5746331573feSNamjae Jeon 	 * if offset_lblk lies in a hole which is at start of file, use
5747331573feSNamjae Jeon 	 * ee_start_lblk to shift extents
5748331573feSNamjae Jeon 	 */
5749331573feSNamjae Jeon 	ret = ext4_ext_shift_extents(inode, handle,
5750331573feSNamjae Jeon 		ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5751331573feSNamjae Jeon 		len_lblk, SHIFT_RIGHT);
5752331573feSNamjae Jeon 
5753331573feSNamjae Jeon 	up_write(&EXT4_I(inode)->i_data_sem);
5754331573feSNamjae Jeon 	if (IS_SYNC(inode))
5755331573feSNamjae Jeon 		ext4_handle_sync(handle);
575667a7d5f5SJan Kara 	if (ret >= 0)
575767a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
5758331573feSNamjae Jeon 
5759331573feSNamjae Jeon out_stop:
5760331573feSNamjae Jeon 	ext4_journal_stop(handle);
5761ea3d7209SJan Kara out_mmap:
5762ea3d7209SJan Kara 	up_write(&EXT4_I(inode)->i_mmap_sem);
5763331573feSNamjae Jeon out_mutex:
57645955102cSAl Viro 	inode_unlock(inode);
5765331573feSNamjae Jeon 	return ret;
5766331573feSNamjae Jeon }
5767331573feSNamjae Jeon 
5768fcf6b1b7SDmitry Monakhov /**
5769c60990b3STheodore Ts'o  * ext4_swap_extents() - Swap extents between two inodes
5770c60990b3STheodore Ts'o  * @handle: handle for this transaction
5771fcf6b1b7SDmitry Monakhov  * @inode1:	First inode
5772fcf6b1b7SDmitry Monakhov  * @inode2:	Second inode
5773fcf6b1b7SDmitry Monakhov  * @lblk1:	Start block for first inode
5774fcf6b1b7SDmitry Monakhov  * @lblk2:	Start block for second inode
5775fcf6b1b7SDmitry Monakhov  * @count:	Number of blocks to swap
5776dcae058aSzhenwei.pi  * @unwritten: Mark second inode's extents as unwritten after swap
5777fcf6b1b7SDmitry Monakhov  * @erp:	Pointer to save error value
5778fcf6b1b7SDmitry Monakhov  *
5779fcf6b1b7SDmitry Monakhov  * This helper routine does exactly what is promise "swap extents". All other
5780fcf6b1b7SDmitry Monakhov  * stuff such as page-cache locking consistency, bh mapping consistency or
5781fcf6b1b7SDmitry Monakhov  * extent's data copying must be performed by caller.
5782fcf6b1b7SDmitry Monakhov  * Locking:
5783fcf6b1b7SDmitry Monakhov  * 		i_mutex is held for both inodes
5784fcf6b1b7SDmitry Monakhov  * 		i_data_sem is locked for write for both inodes
5785fcf6b1b7SDmitry Monakhov  * Assumptions:
5786fcf6b1b7SDmitry Monakhov  *		All pages from requested range are locked for both inodes
5787fcf6b1b7SDmitry Monakhov  */
5788fcf6b1b7SDmitry Monakhov int
5789fcf6b1b7SDmitry Monakhov ext4_swap_extents(handle_t *handle, struct inode *inode1,
5790fcf6b1b7SDmitry Monakhov 		  struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5791fcf6b1b7SDmitry Monakhov 		  ext4_lblk_t count, int unwritten, int *erp)
5792fcf6b1b7SDmitry Monakhov {
5793fcf6b1b7SDmitry Monakhov 	struct ext4_ext_path *path1 = NULL;
5794fcf6b1b7SDmitry Monakhov 	struct ext4_ext_path *path2 = NULL;
5795fcf6b1b7SDmitry Monakhov 	int replaced_count = 0;
5796fcf6b1b7SDmitry Monakhov 
5797fcf6b1b7SDmitry Monakhov 	BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5798fcf6b1b7SDmitry Monakhov 	BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
57995955102cSAl Viro 	BUG_ON(!inode_is_locked(inode1));
58005955102cSAl Viro 	BUG_ON(!inode_is_locked(inode2));
5801fcf6b1b7SDmitry Monakhov 
5802fcf6b1b7SDmitry Monakhov 	*erp = ext4_es_remove_extent(inode1, lblk1, count);
580319008f6dSTheodore Ts'o 	if (unlikely(*erp))
5804fcf6b1b7SDmitry Monakhov 		return 0;
5805fcf6b1b7SDmitry Monakhov 	*erp = ext4_es_remove_extent(inode2, lblk2, count);
580619008f6dSTheodore Ts'o 	if (unlikely(*erp))
5807fcf6b1b7SDmitry Monakhov 		return 0;
5808fcf6b1b7SDmitry Monakhov 
5809fcf6b1b7SDmitry Monakhov 	while (count) {
5810fcf6b1b7SDmitry Monakhov 		struct ext4_extent *ex1, *ex2, tmp_ex;
5811fcf6b1b7SDmitry Monakhov 		ext4_lblk_t e1_blk, e2_blk;
5812fcf6b1b7SDmitry Monakhov 		int e1_len, e2_len, len;
5813fcf6b1b7SDmitry Monakhov 		int split = 0;
5814fcf6b1b7SDmitry Monakhov 
5815ed8a1a76STheodore Ts'o 		path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5816a1c83681SViresh Kumar 		if (IS_ERR(path1)) {
5817fcf6b1b7SDmitry Monakhov 			*erp = PTR_ERR(path1);
581819008f6dSTheodore Ts'o 			path1 = NULL;
581919008f6dSTheodore Ts'o 		finish:
582019008f6dSTheodore Ts'o 			count = 0;
582119008f6dSTheodore Ts'o 			goto repeat;
5822fcf6b1b7SDmitry Monakhov 		}
5823ed8a1a76STheodore Ts'o 		path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5824a1c83681SViresh Kumar 		if (IS_ERR(path2)) {
5825fcf6b1b7SDmitry Monakhov 			*erp = PTR_ERR(path2);
582619008f6dSTheodore Ts'o 			path2 = NULL;
582719008f6dSTheodore Ts'o 			goto finish;
5828fcf6b1b7SDmitry Monakhov 		}
5829fcf6b1b7SDmitry Monakhov 		ex1 = path1[path1->p_depth].p_ext;
5830fcf6b1b7SDmitry Monakhov 		ex2 = path2[path2->p_depth].p_ext;
5831fcf6b1b7SDmitry Monakhov 		/* Do we have somthing to swap ? */
5832fcf6b1b7SDmitry Monakhov 		if (unlikely(!ex2 || !ex1))
583319008f6dSTheodore Ts'o 			goto finish;
5834fcf6b1b7SDmitry Monakhov 
5835fcf6b1b7SDmitry Monakhov 		e1_blk = le32_to_cpu(ex1->ee_block);
5836fcf6b1b7SDmitry Monakhov 		e2_blk = le32_to_cpu(ex2->ee_block);
5837fcf6b1b7SDmitry Monakhov 		e1_len = ext4_ext_get_actual_len(ex1);
5838fcf6b1b7SDmitry Monakhov 		e2_len = ext4_ext_get_actual_len(ex2);
5839fcf6b1b7SDmitry Monakhov 
5840fcf6b1b7SDmitry Monakhov 		/* Hole handling */
5841fcf6b1b7SDmitry Monakhov 		if (!in_range(lblk1, e1_blk, e1_len) ||
5842fcf6b1b7SDmitry Monakhov 		    !in_range(lblk2, e2_blk, e2_len)) {
5843fcf6b1b7SDmitry Monakhov 			ext4_lblk_t next1, next2;
5844fcf6b1b7SDmitry Monakhov 
5845fcf6b1b7SDmitry Monakhov 			/* if hole after extent, then go to next extent */
5846fcf6b1b7SDmitry Monakhov 			next1 = ext4_ext_next_allocated_block(path1);
5847fcf6b1b7SDmitry Monakhov 			next2 = ext4_ext_next_allocated_block(path2);
5848fcf6b1b7SDmitry Monakhov 			/* If hole before extent, then shift to that extent */
5849fcf6b1b7SDmitry Monakhov 			if (e1_blk > lblk1)
5850fcf6b1b7SDmitry Monakhov 				next1 = e1_blk;
5851fcf6b1b7SDmitry Monakhov 			if (e2_blk > lblk2)
58524e562013SManinder Singh 				next2 = e2_blk;
5853fcf6b1b7SDmitry Monakhov 			/* Do we have something to swap */
5854fcf6b1b7SDmitry Monakhov 			if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
585519008f6dSTheodore Ts'o 				goto finish;
5856fcf6b1b7SDmitry Monakhov 			/* Move to the rightest boundary */
5857fcf6b1b7SDmitry Monakhov 			len = next1 - lblk1;
5858fcf6b1b7SDmitry Monakhov 			if (len < next2 - lblk2)
5859fcf6b1b7SDmitry Monakhov 				len = next2 - lblk2;
5860fcf6b1b7SDmitry Monakhov 			if (len > count)
5861fcf6b1b7SDmitry Monakhov 				len = count;
5862fcf6b1b7SDmitry Monakhov 			lblk1 += len;
5863fcf6b1b7SDmitry Monakhov 			lblk2 += len;
5864fcf6b1b7SDmitry Monakhov 			count -= len;
5865fcf6b1b7SDmitry Monakhov 			goto repeat;
5866fcf6b1b7SDmitry Monakhov 		}
5867fcf6b1b7SDmitry Monakhov 
5868fcf6b1b7SDmitry Monakhov 		/* Prepare left boundary */
5869fcf6b1b7SDmitry Monakhov 		if (e1_blk < lblk1) {
5870fcf6b1b7SDmitry Monakhov 			split = 1;
5871fcf6b1b7SDmitry Monakhov 			*erp = ext4_force_split_extent_at(handle, inode1,
5872dfe50809STheodore Ts'o 						&path1, lblk1, 0);
587319008f6dSTheodore Ts'o 			if (unlikely(*erp))
587419008f6dSTheodore Ts'o 				goto finish;
5875fcf6b1b7SDmitry Monakhov 		}
5876fcf6b1b7SDmitry Monakhov 		if (e2_blk < lblk2) {
5877fcf6b1b7SDmitry Monakhov 			split = 1;
5878fcf6b1b7SDmitry Monakhov 			*erp = ext4_force_split_extent_at(handle, inode2,
5879dfe50809STheodore Ts'o 						&path2,  lblk2, 0);
588019008f6dSTheodore Ts'o 			if (unlikely(*erp))
588119008f6dSTheodore Ts'o 				goto finish;
5882fcf6b1b7SDmitry Monakhov 		}
5883dfe50809STheodore Ts'o 		/* ext4_split_extent_at() may result in leaf extent split,
5884fcf6b1b7SDmitry Monakhov 		 * path must to be revalidated. */
5885fcf6b1b7SDmitry Monakhov 		if (split)
5886fcf6b1b7SDmitry Monakhov 			goto repeat;
5887fcf6b1b7SDmitry Monakhov 
5888fcf6b1b7SDmitry Monakhov 		/* Prepare right boundary */
5889fcf6b1b7SDmitry Monakhov 		len = count;
5890fcf6b1b7SDmitry Monakhov 		if (len > e1_blk + e1_len - lblk1)
5891fcf6b1b7SDmitry Monakhov 			len = e1_blk + e1_len - lblk1;
5892fcf6b1b7SDmitry Monakhov 		if (len > e2_blk + e2_len - lblk2)
5893fcf6b1b7SDmitry Monakhov 			len = e2_blk + e2_len - lblk2;
5894fcf6b1b7SDmitry Monakhov 
5895fcf6b1b7SDmitry Monakhov 		if (len != e1_len) {
5896fcf6b1b7SDmitry Monakhov 			split = 1;
5897fcf6b1b7SDmitry Monakhov 			*erp = ext4_force_split_extent_at(handle, inode1,
5898dfe50809STheodore Ts'o 						&path1, lblk1 + len, 0);
589919008f6dSTheodore Ts'o 			if (unlikely(*erp))
590019008f6dSTheodore Ts'o 				goto finish;
5901fcf6b1b7SDmitry Monakhov 		}
5902fcf6b1b7SDmitry Monakhov 		if (len != e2_len) {
5903fcf6b1b7SDmitry Monakhov 			split = 1;
5904fcf6b1b7SDmitry Monakhov 			*erp = ext4_force_split_extent_at(handle, inode2,
5905dfe50809STheodore Ts'o 						&path2, lblk2 + len, 0);
5906fcf6b1b7SDmitry Monakhov 			if (*erp)
590719008f6dSTheodore Ts'o 				goto finish;
5908fcf6b1b7SDmitry Monakhov 		}
5909dfe50809STheodore Ts'o 		/* ext4_split_extent_at() may result in leaf extent split,
5910fcf6b1b7SDmitry Monakhov 		 * path must to be revalidated. */
5911fcf6b1b7SDmitry Monakhov 		if (split)
5912fcf6b1b7SDmitry Monakhov 			goto repeat;
5913fcf6b1b7SDmitry Monakhov 
5914fcf6b1b7SDmitry Monakhov 		BUG_ON(e2_len != e1_len);
5915fcf6b1b7SDmitry Monakhov 		*erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
591619008f6dSTheodore Ts'o 		if (unlikely(*erp))
591719008f6dSTheodore Ts'o 			goto finish;
5918fcf6b1b7SDmitry Monakhov 		*erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
591919008f6dSTheodore Ts'o 		if (unlikely(*erp))
592019008f6dSTheodore Ts'o 			goto finish;
5921fcf6b1b7SDmitry Monakhov 
5922fcf6b1b7SDmitry Monakhov 		/* Both extents are fully inside boundaries. Swap it now */
5923fcf6b1b7SDmitry Monakhov 		tmp_ex = *ex1;
5924fcf6b1b7SDmitry Monakhov 		ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5925fcf6b1b7SDmitry Monakhov 		ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5926fcf6b1b7SDmitry Monakhov 		ex1->ee_len = cpu_to_le16(e2_len);
5927fcf6b1b7SDmitry Monakhov 		ex2->ee_len = cpu_to_le16(e1_len);
5928fcf6b1b7SDmitry Monakhov 		if (unwritten)
5929fcf6b1b7SDmitry Monakhov 			ext4_ext_mark_unwritten(ex2);
5930fcf6b1b7SDmitry Monakhov 		if (ext4_ext_is_unwritten(&tmp_ex))
5931fcf6b1b7SDmitry Monakhov 			ext4_ext_mark_unwritten(ex1);
5932fcf6b1b7SDmitry Monakhov 
5933fcf6b1b7SDmitry Monakhov 		ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5934fcf6b1b7SDmitry Monakhov 		ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5935fcf6b1b7SDmitry Monakhov 		*erp = ext4_ext_dirty(handle, inode2, path2 +
5936fcf6b1b7SDmitry Monakhov 				      path2->p_depth);
593719008f6dSTheodore Ts'o 		if (unlikely(*erp))
593819008f6dSTheodore Ts'o 			goto finish;
5939fcf6b1b7SDmitry Monakhov 		*erp = ext4_ext_dirty(handle, inode1, path1 +
5940fcf6b1b7SDmitry Monakhov 				      path1->p_depth);
5941fcf6b1b7SDmitry Monakhov 		/*
5942fcf6b1b7SDmitry Monakhov 		 * Looks scarry ah..? second inode already points to new blocks,
5943fcf6b1b7SDmitry Monakhov 		 * and it was successfully dirtied. But luckily error may happen
5944fcf6b1b7SDmitry Monakhov 		 * only due to journal error, so full transaction will be
5945fcf6b1b7SDmitry Monakhov 		 * aborted anyway.
5946fcf6b1b7SDmitry Monakhov 		 */
594719008f6dSTheodore Ts'o 		if (unlikely(*erp))
594819008f6dSTheodore Ts'o 			goto finish;
5949fcf6b1b7SDmitry Monakhov 		lblk1 += len;
5950fcf6b1b7SDmitry Monakhov 		lblk2 += len;
5951fcf6b1b7SDmitry Monakhov 		replaced_count += len;
5952fcf6b1b7SDmitry Monakhov 		count -= len;
5953fcf6b1b7SDmitry Monakhov 
5954fcf6b1b7SDmitry Monakhov 	repeat:
5955fcf6b1b7SDmitry Monakhov 		ext4_ext_drop_refs(path1);
5956fcf6b1b7SDmitry Monakhov 		kfree(path1);
5957fcf6b1b7SDmitry Monakhov 		ext4_ext_drop_refs(path2);
5958fcf6b1b7SDmitry Monakhov 		kfree(path2);
5959b7ea89adSTheodore Ts'o 		path1 = path2 = NULL;
5960fcf6b1b7SDmitry Monakhov 	}
5961fcf6b1b7SDmitry Monakhov 	return replaced_count;
5962fcf6b1b7SDmitry Monakhov }
59630b02f4c0SEric Whitney 
59640b02f4c0SEric Whitney /*
59650b02f4c0SEric Whitney  * ext4_clu_mapped - determine whether any block in a logical cluster has
59660b02f4c0SEric Whitney  *                   been mapped to a physical cluster
59670b02f4c0SEric Whitney  *
59680b02f4c0SEric Whitney  * @inode - file containing the logical cluster
59690b02f4c0SEric Whitney  * @lclu - logical cluster of interest
59700b02f4c0SEric Whitney  *
59710b02f4c0SEric Whitney  * Returns 1 if any block in the logical cluster is mapped, signifying
59720b02f4c0SEric Whitney  * that a physical cluster has been allocated for it.  Otherwise,
59730b02f4c0SEric Whitney  * returns 0.  Can also return negative error codes.  Derived from
59740b02f4c0SEric Whitney  * ext4_ext_map_blocks().
59750b02f4c0SEric Whitney  */
59760b02f4c0SEric Whitney int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
59770b02f4c0SEric Whitney {
59780b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
59790b02f4c0SEric Whitney 	struct ext4_ext_path *path;
59800b02f4c0SEric Whitney 	int depth, mapped = 0, err = 0;
59810b02f4c0SEric Whitney 	struct ext4_extent *extent;
59820b02f4c0SEric Whitney 	ext4_lblk_t first_lblk, first_lclu, last_lclu;
59830b02f4c0SEric Whitney 
59840b02f4c0SEric Whitney 	/* search for the extent closest to the first block in the cluster */
59850b02f4c0SEric Whitney 	path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
59860b02f4c0SEric Whitney 	if (IS_ERR(path)) {
59870b02f4c0SEric Whitney 		err = PTR_ERR(path);
59880b02f4c0SEric Whitney 		path = NULL;
59890b02f4c0SEric Whitney 		goto out;
59900b02f4c0SEric Whitney 	}
59910b02f4c0SEric Whitney 
59920b02f4c0SEric Whitney 	depth = ext_depth(inode);
59930b02f4c0SEric Whitney 
59940b02f4c0SEric Whitney 	/*
59950b02f4c0SEric Whitney 	 * A consistent leaf must not be empty.  This situation is possible,
59960b02f4c0SEric Whitney 	 * though, _during_ tree modification, and it's why an assert can't
59970b02f4c0SEric Whitney 	 * be put in ext4_find_extent().
59980b02f4c0SEric Whitney 	 */
59990b02f4c0SEric Whitney 	if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
60000b02f4c0SEric Whitney 		EXT4_ERROR_INODE(inode,
60010b02f4c0SEric Whitney 		    "bad extent address - lblock: %lu, depth: %d, pblock: %lld",
60020b02f4c0SEric Whitney 				 (unsigned long) EXT4_C2B(sbi, lclu),
60030b02f4c0SEric Whitney 				 depth, path[depth].p_block);
60040b02f4c0SEric Whitney 		err = -EFSCORRUPTED;
60050b02f4c0SEric Whitney 		goto out;
60060b02f4c0SEric Whitney 	}
60070b02f4c0SEric Whitney 
60080b02f4c0SEric Whitney 	extent = path[depth].p_ext;
60090b02f4c0SEric Whitney 
60100b02f4c0SEric Whitney 	/* can't be mapped if the extent tree is empty */
60110b02f4c0SEric Whitney 	if (extent == NULL)
60120b02f4c0SEric Whitney 		goto out;
60130b02f4c0SEric Whitney 
60140b02f4c0SEric Whitney 	first_lblk = le32_to_cpu(extent->ee_block);
60150b02f4c0SEric Whitney 	first_lclu = EXT4_B2C(sbi, first_lblk);
60160b02f4c0SEric Whitney 
60170b02f4c0SEric Whitney 	/*
60180b02f4c0SEric Whitney 	 * Three possible outcomes at this point - found extent spanning
60190b02f4c0SEric Whitney 	 * the target cluster, to the left of the target cluster, or to the
60200b02f4c0SEric Whitney 	 * right of the target cluster.  The first two cases are handled here.
60210b02f4c0SEric Whitney 	 * The last case indicates the target cluster is not mapped.
60220b02f4c0SEric Whitney 	 */
60230b02f4c0SEric Whitney 	if (lclu >= first_lclu) {
60240b02f4c0SEric Whitney 		last_lclu = EXT4_B2C(sbi, first_lblk +
60250b02f4c0SEric Whitney 				     ext4_ext_get_actual_len(extent) - 1);
60260b02f4c0SEric Whitney 		if (lclu <= last_lclu) {
60270b02f4c0SEric Whitney 			mapped = 1;
60280b02f4c0SEric Whitney 		} else {
60290b02f4c0SEric Whitney 			first_lblk = ext4_ext_next_allocated_block(path);
60300b02f4c0SEric Whitney 			first_lclu = EXT4_B2C(sbi, first_lblk);
60310b02f4c0SEric Whitney 			if (lclu == first_lclu)
60320b02f4c0SEric Whitney 				mapped = 1;
60330b02f4c0SEric Whitney 		}
60340b02f4c0SEric Whitney 	}
60350b02f4c0SEric Whitney 
60360b02f4c0SEric Whitney out:
60370b02f4c0SEric Whitney 	ext4_ext_drop_refs(path);
60380b02f4c0SEric Whitney 	kfree(path);
60390b02f4c0SEric Whitney 
60400b02f4c0SEric Whitney 	return err ? err : mapped;
60410b02f4c0SEric Whitney }
6042