xref: /openbmc/linux/fs/ext4/extents.c (revision 0562e0bad483d10e9651fbb8f21dc3d0bad57374)
1a86c6181SAlex Tomas /*
2a86c6181SAlex Tomas  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3a86c6181SAlex Tomas  * Written by Alex Tomas <alex@clusterfs.com>
4a86c6181SAlex Tomas  *
5a86c6181SAlex Tomas  * Architecture independence:
6a86c6181SAlex Tomas  *   Copyright (c) 2005, Bull S.A.
7a86c6181SAlex Tomas  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
8a86c6181SAlex Tomas  *
9a86c6181SAlex Tomas  * This program is free software; you can redistribute it and/or modify
10a86c6181SAlex Tomas  * it under the terms of the GNU General Public License version 2 as
11a86c6181SAlex Tomas  * published by the Free Software Foundation.
12a86c6181SAlex Tomas  *
13a86c6181SAlex Tomas  * This program is distributed in the hope that it will be useful,
14a86c6181SAlex Tomas  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15a86c6181SAlex Tomas  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16a86c6181SAlex Tomas  * GNU General Public License for more details.
17a86c6181SAlex Tomas  *
18a86c6181SAlex Tomas  * You should have received a copy of the GNU General Public Licens
19a86c6181SAlex Tomas  * along with this program; if not, write to the Free Software
20a86c6181SAlex Tomas  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
21a86c6181SAlex Tomas  */
22a86c6181SAlex Tomas 
23a86c6181SAlex Tomas /*
24a86c6181SAlex Tomas  * Extents support for EXT4
25a86c6181SAlex Tomas  *
26a86c6181SAlex Tomas  * TODO:
27a86c6181SAlex Tomas  *   - ext4*_error() should be used in some situations
28a86c6181SAlex Tomas  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29a86c6181SAlex Tomas  *   - smart tree reduction
30a86c6181SAlex Tomas  */
31a86c6181SAlex Tomas 
32a86c6181SAlex Tomas #include <linux/module.h>
33a86c6181SAlex Tomas #include <linux/fs.h>
34a86c6181SAlex Tomas #include <linux/time.h>
35cd02ff0bSMingming Cao #include <linux/jbd2.h>
36a86c6181SAlex Tomas #include <linux/highuid.h>
37a86c6181SAlex Tomas #include <linux/pagemap.h>
38a86c6181SAlex Tomas #include <linux/quotaops.h>
39a86c6181SAlex Tomas #include <linux/string.h>
40a86c6181SAlex Tomas #include <linux/slab.h>
41a2df2a63SAmit Arora #include <linux/falloc.h>
42a86c6181SAlex Tomas #include <asm/uaccess.h>
436873fa0dSEric Sandeen #include <linux/fiemap.h>
443dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
453dcf5451SChristoph Hellwig #include "ext4_extents.h"
46a86c6181SAlex Tomas 
47*0562e0baSJiaying Zhang #include <trace/events/ext4.h>
48*0562e0baSJiaying Zhang 
49487caeefSJan Kara static int ext4_ext_truncate_extend_restart(handle_t *handle,
50487caeefSJan Kara 					    struct inode *inode,
51487caeefSJan Kara 					    int needed)
52a86c6181SAlex Tomas {
53a86c6181SAlex Tomas 	int err;
54a86c6181SAlex Tomas 
550390131bSFrank Mayhar 	if (!ext4_handle_valid(handle))
560390131bSFrank Mayhar 		return 0;
57a86c6181SAlex Tomas 	if (handle->h_buffer_credits > needed)
589102e4faSShen Feng 		return 0;
599102e4faSShen Feng 	err = ext4_journal_extend(handle, needed);
600123c939STheodore Ts'o 	if (err <= 0)
619102e4faSShen Feng 		return err;
62487caeefSJan Kara 	err = ext4_truncate_restart_trans(handle, inode, needed);
630617b83fSDmitry Monakhov 	if (err == 0)
640617b83fSDmitry Monakhov 		err = -EAGAIN;
65487caeefSJan Kara 
66487caeefSJan Kara 	return err;
67a86c6181SAlex Tomas }
68a86c6181SAlex Tomas 
69a86c6181SAlex Tomas /*
70a86c6181SAlex Tomas  * could return:
71a86c6181SAlex Tomas  *  - EROFS
72a86c6181SAlex Tomas  *  - ENOMEM
73a86c6181SAlex Tomas  */
74a86c6181SAlex Tomas static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
75a86c6181SAlex Tomas 				struct ext4_ext_path *path)
76a86c6181SAlex Tomas {
77a86c6181SAlex Tomas 	if (path->p_bh) {
78a86c6181SAlex Tomas 		/* path points to block */
79a86c6181SAlex Tomas 		return ext4_journal_get_write_access(handle, path->p_bh);
80a86c6181SAlex Tomas 	}
81a86c6181SAlex Tomas 	/* path points to leaf/index in inode body */
82a86c6181SAlex Tomas 	/* we use in-core data, no need to protect them */
83a86c6181SAlex Tomas 	return 0;
84a86c6181SAlex Tomas }
85a86c6181SAlex Tomas 
86a86c6181SAlex Tomas /*
87a86c6181SAlex Tomas  * could return:
88a86c6181SAlex Tomas  *  - EROFS
89a86c6181SAlex Tomas  *  - ENOMEM
90a86c6181SAlex Tomas  *  - EIO
91a86c6181SAlex Tomas  */
92a86c6181SAlex Tomas static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
93a86c6181SAlex Tomas 				struct ext4_ext_path *path)
94a86c6181SAlex Tomas {
95a86c6181SAlex Tomas 	int err;
96a86c6181SAlex Tomas 	if (path->p_bh) {
97a86c6181SAlex Tomas 		/* path points to block */
980390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, path->p_bh);
99a86c6181SAlex Tomas 	} else {
100a86c6181SAlex Tomas 		/* path points to leaf/index in inode body */
101a86c6181SAlex Tomas 		err = ext4_mark_inode_dirty(handle, inode);
102a86c6181SAlex Tomas 	}
103a86c6181SAlex Tomas 	return err;
104a86c6181SAlex Tomas }
105a86c6181SAlex Tomas 
106f65e6fbaSAlex Tomas static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
107a86c6181SAlex Tomas 			      struct ext4_ext_path *path,
108725d26d3SAneesh Kumar K.V 			      ext4_lblk_t block)
109a86c6181SAlex Tomas {
110a86c6181SAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(inode);
111f65e6fbaSAlex Tomas 	ext4_fsblk_t bg_start;
11274d3487fSValerie Clement 	ext4_fsblk_t last_block;
113f65e6fbaSAlex Tomas 	ext4_grpblk_t colour;
114a4912123STheodore Ts'o 	ext4_group_t block_group;
115a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
116a86c6181SAlex Tomas 	int depth;
117a86c6181SAlex Tomas 
118a86c6181SAlex Tomas 	if (path) {
119a86c6181SAlex Tomas 		struct ext4_extent *ex;
120a86c6181SAlex Tomas 		depth = path->p_depth;
121a86c6181SAlex Tomas 
122ad4fb9caSKazuya Mio 		/*
123ad4fb9caSKazuya Mio 		 * Try to predict block placement assuming that we are
124ad4fb9caSKazuya Mio 		 * filling in a file which will eventually be
125ad4fb9caSKazuya Mio 		 * non-sparse --- i.e., in the case of libbfd writing
126ad4fb9caSKazuya Mio 		 * an ELF object sections out-of-order but in a way
127ad4fb9caSKazuya Mio 		 * the eventually results in a contiguous object or
128ad4fb9caSKazuya Mio 		 * executable file, or some database extending a table
129ad4fb9caSKazuya Mio 		 * space file.  However, this is actually somewhat
130ad4fb9caSKazuya Mio 		 * non-ideal if we are writing a sparse file such as
131ad4fb9caSKazuya Mio 		 * qemu or KVM writing a raw image file that is going
132ad4fb9caSKazuya Mio 		 * to stay fairly sparse, since it will end up
133ad4fb9caSKazuya Mio 		 * fragmenting the file system's free space.  Maybe we
134ad4fb9caSKazuya Mio 		 * should have some hueristics or some way to allow
135ad4fb9caSKazuya Mio 		 * userspace to pass a hint to file system,
136ad4fb9caSKazuya Mio 		 * especiially if the latter case turns out to be
137ad4fb9caSKazuya Mio 		 * common.
138ad4fb9caSKazuya Mio 		 */
1397e028976SAvantika Mathur 		ex = path[depth].p_ext;
140ad4fb9caSKazuya Mio 		if (ex) {
141ad4fb9caSKazuya Mio 			ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
142ad4fb9caSKazuya Mio 			ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
143ad4fb9caSKazuya Mio 
144ad4fb9caSKazuya Mio 			if (block > ext_block)
145ad4fb9caSKazuya Mio 				return ext_pblk + (block - ext_block);
146ad4fb9caSKazuya Mio 			else
147ad4fb9caSKazuya Mio 				return ext_pblk - (ext_block - block);
148ad4fb9caSKazuya Mio 		}
149a86c6181SAlex Tomas 
150d0d856e8SRandy Dunlap 		/* it looks like index is empty;
151d0d856e8SRandy Dunlap 		 * try to find starting block from index itself */
152a86c6181SAlex Tomas 		if (path[depth].p_bh)
153a86c6181SAlex Tomas 			return path[depth].p_bh->b_blocknr;
154a86c6181SAlex Tomas 	}
155a86c6181SAlex Tomas 
156a86c6181SAlex Tomas 	/* OK. use inode's group */
157a4912123STheodore Ts'o 	block_group = ei->i_block_group;
158a4912123STheodore Ts'o 	if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
159a4912123STheodore Ts'o 		/*
160a4912123STheodore Ts'o 		 * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
161a4912123STheodore Ts'o 		 * block groups per flexgroup, reserve the first block
162a4912123STheodore Ts'o 		 * group for directories and special files.  Regular
163a4912123STheodore Ts'o 		 * files will start at the second block group.  This
164a4912123STheodore Ts'o 		 * tends to speed up directory access and improves
165a4912123STheodore Ts'o 		 * fsck times.
166a4912123STheodore Ts'o 		 */
167a4912123STheodore Ts'o 		block_group &= ~(flex_size-1);
168a4912123STheodore Ts'o 		if (S_ISREG(inode->i_mode))
169a4912123STheodore Ts'o 			block_group++;
170a4912123STheodore Ts'o 	}
1715661bd68SAkinobu Mita 	bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
17274d3487fSValerie Clement 	last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
17374d3487fSValerie Clement 
174a4912123STheodore Ts'o 	/*
175a4912123STheodore Ts'o 	 * If we are doing delayed allocation, we don't need take
176a4912123STheodore Ts'o 	 * colour into account.
177a4912123STheodore Ts'o 	 */
178a4912123STheodore Ts'o 	if (test_opt(inode->i_sb, DELALLOC))
179a4912123STheodore Ts'o 		return bg_start;
180a4912123STheodore Ts'o 
18174d3487fSValerie Clement 	if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
182a86c6181SAlex Tomas 		colour = (current->pid % 16) *
183a86c6181SAlex Tomas 			(EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
18474d3487fSValerie Clement 	else
18574d3487fSValerie Clement 		colour = (current->pid % 16) * ((last_block - bg_start) / 16);
186a86c6181SAlex Tomas 	return bg_start + colour + block;
187a86c6181SAlex Tomas }
188a86c6181SAlex Tomas 
189654b4908SAneesh Kumar K.V /*
190654b4908SAneesh Kumar K.V  * Allocation for a meta data block
191654b4908SAneesh Kumar K.V  */
192f65e6fbaSAlex Tomas static ext4_fsblk_t
193654b4908SAneesh Kumar K.V ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
194a86c6181SAlex Tomas 			struct ext4_ext_path *path,
195a86c6181SAlex Tomas 			struct ext4_extent *ex, int *err)
196a86c6181SAlex Tomas {
197f65e6fbaSAlex Tomas 	ext4_fsblk_t goal, newblock;
198a86c6181SAlex Tomas 
199a86c6181SAlex Tomas 	goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
20097df5d15STheodore Ts'o 	newblock = ext4_new_meta_blocks(handle, inode, goal, NULL, err);
201a86c6181SAlex Tomas 	return newblock;
202a86c6181SAlex Tomas }
203a86c6181SAlex Tomas 
20455ad63bfSTheodore Ts'o static inline int ext4_ext_space_block(struct inode *inode, int check)
205a86c6181SAlex Tomas {
206a86c6181SAlex Tomas 	int size;
207a86c6181SAlex Tomas 
208a86c6181SAlex Tomas 	size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
209a86c6181SAlex Tomas 			/ sizeof(struct ext4_extent);
21055ad63bfSTheodore Ts'o 	if (!check) {
211bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
212a86c6181SAlex Tomas 		if (size > 6)
213a86c6181SAlex Tomas 			size = 6;
214a86c6181SAlex Tomas #endif
21555ad63bfSTheodore Ts'o 	}
216a86c6181SAlex Tomas 	return size;
217a86c6181SAlex Tomas }
218a86c6181SAlex Tomas 
21955ad63bfSTheodore Ts'o static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
220a86c6181SAlex Tomas {
221a86c6181SAlex Tomas 	int size;
222a86c6181SAlex Tomas 
223a86c6181SAlex Tomas 	size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
224a86c6181SAlex Tomas 			/ sizeof(struct ext4_extent_idx);
22555ad63bfSTheodore Ts'o 	if (!check) {
226bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
227a86c6181SAlex Tomas 		if (size > 5)
228a86c6181SAlex Tomas 			size = 5;
229a86c6181SAlex Tomas #endif
23055ad63bfSTheodore Ts'o 	}
231a86c6181SAlex Tomas 	return size;
232a86c6181SAlex Tomas }
233a86c6181SAlex Tomas 
23455ad63bfSTheodore Ts'o static inline int ext4_ext_space_root(struct inode *inode, int check)
235a86c6181SAlex Tomas {
236a86c6181SAlex Tomas 	int size;
237a86c6181SAlex Tomas 
238a86c6181SAlex Tomas 	size = sizeof(EXT4_I(inode)->i_data);
239a86c6181SAlex Tomas 	size -= sizeof(struct ext4_extent_header);
240a86c6181SAlex Tomas 	size /= sizeof(struct ext4_extent);
24155ad63bfSTheodore Ts'o 	if (!check) {
242bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
243a86c6181SAlex Tomas 		if (size > 3)
244a86c6181SAlex Tomas 			size = 3;
245a86c6181SAlex Tomas #endif
24655ad63bfSTheodore Ts'o 	}
247a86c6181SAlex Tomas 	return size;
248a86c6181SAlex Tomas }
249a86c6181SAlex Tomas 
25055ad63bfSTheodore Ts'o static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
251a86c6181SAlex Tomas {
252a86c6181SAlex Tomas 	int size;
253a86c6181SAlex Tomas 
254a86c6181SAlex Tomas 	size = sizeof(EXT4_I(inode)->i_data);
255a86c6181SAlex Tomas 	size -= sizeof(struct ext4_extent_header);
256a86c6181SAlex Tomas 	size /= sizeof(struct ext4_extent_idx);
25755ad63bfSTheodore Ts'o 	if (!check) {
258bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
259a86c6181SAlex Tomas 		if (size > 4)
260a86c6181SAlex Tomas 			size = 4;
261a86c6181SAlex Tomas #endif
26255ad63bfSTheodore Ts'o 	}
263a86c6181SAlex Tomas 	return size;
264a86c6181SAlex Tomas }
265a86c6181SAlex Tomas 
266d2a17637SMingming Cao /*
267d2a17637SMingming Cao  * Calculate the number of metadata blocks needed
268d2a17637SMingming Cao  * to allocate @blocks
269d2a17637SMingming Cao  * Worse case is one block per extent
270d2a17637SMingming Cao  */
27101f49d0bSTheodore Ts'o int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
272d2a17637SMingming Cao {
2739d0be502STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
2749d0be502STheodore Ts'o 	int idxs, num = 0;
275d2a17637SMingming Cao 
2769d0be502STheodore Ts'o 	idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
2779d0be502STheodore Ts'o 		/ sizeof(struct ext4_extent_idx));
278d2a17637SMingming Cao 
279d2a17637SMingming Cao 	/*
2809d0be502STheodore Ts'o 	 * If the new delayed allocation block is contiguous with the
2819d0be502STheodore Ts'o 	 * previous da block, it can share index blocks with the
2829d0be502STheodore Ts'o 	 * previous block, so we only need to allocate a new index
2839d0be502STheodore Ts'o 	 * block every idxs leaf blocks.  At ldxs**2 blocks, we need
2849d0be502STheodore Ts'o 	 * an additional index block, and at ldxs**3 blocks, yet
2859d0be502STheodore Ts'o 	 * another index blocks.
286d2a17637SMingming Cao 	 */
2879d0be502STheodore Ts'o 	if (ei->i_da_metadata_calc_len &&
2889d0be502STheodore Ts'o 	    ei->i_da_metadata_calc_last_lblock+1 == lblock) {
2899d0be502STheodore Ts'o 		if ((ei->i_da_metadata_calc_len % idxs) == 0)
2909d0be502STheodore Ts'o 			num++;
2919d0be502STheodore Ts'o 		if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
2929d0be502STheodore Ts'o 			num++;
2939d0be502STheodore Ts'o 		if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
2949d0be502STheodore Ts'o 			num++;
2959d0be502STheodore Ts'o 			ei->i_da_metadata_calc_len = 0;
2969d0be502STheodore Ts'o 		} else
2979d0be502STheodore Ts'o 			ei->i_da_metadata_calc_len++;
2989d0be502STheodore Ts'o 		ei->i_da_metadata_calc_last_lblock++;
299d2a17637SMingming Cao 		return num;
300d2a17637SMingming Cao 	}
301d2a17637SMingming Cao 
3029d0be502STheodore Ts'o 	/*
3039d0be502STheodore Ts'o 	 * In the worst case we need a new set of index blocks at
3049d0be502STheodore Ts'o 	 * every level of the inode's extent tree.
3059d0be502STheodore Ts'o 	 */
3069d0be502STheodore Ts'o 	ei->i_da_metadata_calc_len = 1;
3079d0be502STheodore Ts'o 	ei->i_da_metadata_calc_last_lblock = lblock;
3089d0be502STheodore Ts'o 	return ext_depth(inode) + 1;
3099d0be502STheodore Ts'o }
3109d0be502STheodore Ts'o 
311c29c0ae7SAlex Tomas static int
312c29c0ae7SAlex Tomas ext4_ext_max_entries(struct inode *inode, int depth)
313c29c0ae7SAlex Tomas {
314c29c0ae7SAlex Tomas 	int max;
315c29c0ae7SAlex Tomas 
316c29c0ae7SAlex Tomas 	if (depth == ext_depth(inode)) {
317c29c0ae7SAlex Tomas 		if (depth == 0)
31855ad63bfSTheodore Ts'o 			max = ext4_ext_space_root(inode, 1);
319c29c0ae7SAlex Tomas 		else
32055ad63bfSTheodore Ts'o 			max = ext4_ext_space_root_idx(inode, 1);
321c29c0ae7SAlex Tomas 	} else {
322c29c0ae7SAlex Tomas 		if (depth == 0)
32355ad63bfSTheodore Ts'o 			max = ext4_ext_space_block(inode, 1);
324c29c0ae7SAlex Tomas 		else
32555ad63bfSTheodore Ts'o 			max = ext4_ext_space_block_idx(inode, 1);
326c29c0ae7SAlex Tomas 	}
327c29c0ae7SAlex Tomas 
328c29c0ae7SAlex Tomas 	return max;
329c29c0ae7SAlex Tomas }
330c29c0ae7SAlex Tomas 
33156b19868SAneesh Kumar K.V static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
33256b19868SAneesh Kumar K.V {
333bf89d16fSTheodore Ts'o 	ext4_fsblk_t block = ext4_ext_pblock(ext);
33456b19868SAneesh Kumar K.V 	int len = ext4_ext_get_actual_len(ext);
335e84a26ceSTheodore Ts'o 
3366fd058f7STheodore Ts'o 	return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
33756b19868SAneesh Kumar K.V }
33856b19868SAneesh Kumar K.V 
33956b19868SAneesh Kumar K.V static int ext4_valid_extent_idx(struct inode *inode,
34056b19868SAneesh Kumar K.V 				struct ext4_extent_idx *ext_idx)
34156b19868SAneesh Kumar K.V {
342bf89d16fSTheodore Ts'o 	ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
343e84a26ceSTheodore Ts'o 
3446fd058f7STheodore Ts'o 	return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
34556b19868SAneesh Kumar K.V }
34656b19868SAneesh Kumar K.V 
34756b19868SAneesh Kumar K.V static int ext4_valid_extent_entries(struct inode *inode,
34856b19868SAneesh Kumar K.V 				struct ext4_extent_header *eh,
34956b19868SAneesh Kumar K.V 				int depth)
35056b19868SAneesh Kumar K.V {
35156b19868SAneesh Kumar K.V 	struct ext4_extent *ext;
35256b19868SAneesh Kumar K.V 	struct ext4_extent_idx *ext_idx;
35356b19868SAneesh Kumar K.V 	unsigned short entries;
35456b19868SAneesh Kumar K.V 	if (eh->eh_entries == 0)
35556b19868SAneesh Kumar K.V 		return 1;
35656b19868SAneesh Kumar K.V 
35756b19868SAneesh Kumar K.V 	entries = le16_to_cpu(eh->eh_entries);
35856b19868SAneesh Kumar K.V 
35956b19868SAneesh Kumar K.V 	if (depth == 0) {
36056b19868SAneesh Kumar K.V 		/* leaf entries */
36156b19868SAneesh Kumar K.V 		ext = EXT_FIRST_EXTENT(eh);
36256b19868SAneesh Kumar K.V 		while (entries) {
36356b19868SAneesh Kumar K.V 			if (!ext4_valid_extent(inode, ext))
36456b19868SAneesh Kumar K.V 				return 0;
36556b19868SAneesh Kumar K.V 			ext++;
36656b19868SAneesh Kumar K.V 			entries--;
36756b19868SAneesh Kumar K.V 		}
36856b19868SAneesh Kumar K.V 	} else {
36956b19868SAneesh Kumar K.V 		ext_idx = EXT_FIRST_INDEX(eh);
37056b19868SAneesh Kumar K.V 		while (entries) {
37156b19868SAneesh Kumar K.V 			if (!ext4_valid_extent_idx(inode, ext_idx))
37256b19868SAneesh Kumar K.V 				return 0;
37356b19868SAneesh Kumar K.V 			ext_idx++;
37456b19868SAneesh Kumar K.V 			entries--;
37556b19868SAneesh Kumar K.V 		}
37656b19868SAneesh Kumar K.V 	}
37756b19868SAneesh Kumar K.V 	return 1;
37856b19868SAneesh Kumar K.V }
37956b19868SAneesh Kumar K.V 
380c398eda0STheodore Ts'o static int __ext4_ext_check(const char *function, unsigned int line,
381c398eda0STheodore Ts'o 			    struct inode *inode, struct ext4_extent_header *eh,
382c29c0ae7SAlex Tomas 			    int depth)
383c29c0ae7SAlex Tomas {
384c29c0ae7SAlex Tomas 	const char *error_msg;
385c29c0ae7SAlex Tomas 	int max = 0;
386c29c0ae7SAlex Tomas 
387c29c0ae7SAlex Tomas 	if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
388c29c0ae7SAlex Tomas 		error_msg = "invalid magic";
389c29c0ae7SAlex Tomas 		goto corrupted;
390c29c0ae7SAlex Tomas 	}
391c29c0ae7SAlex Tomas 	if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
392c29c0ae7SAlex Tomas 		error_msg = "unexpected eh_depth";
393c29c0ae7SAlex Tomas 		goto corrupted;
394c29c0ae7SAlex Tomas 	}
395c29c0ae7SAlex Tomas 	if (unlikely(eh->eh_max == 0)) {
396c29c0ae7SAlex Tomas 		error_msg = "invalid eh_max";
397c29c0ae7SAlex Tomas 		goto corrupted;
398c29c0ae7SAlex Tomas 	}
399c29c0ae7SAlex Tomas 	max = ext4_ext_max_entries(inode, depth);
400c29c0ae7SAlex Tomas 	if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
401c29c0ae7SAlex Tomas 		error_msg = "too large eh_max";
402c29c0ae7SAlex Tomas 		goto corrupted;
403c29c0ae7SAlex Tomas 	}
404c29c0ae7SAlex Tomas 	if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
405c29c0ae7SAlex Tomas 		error_msg = "invalid eh_entries";
406c29c0ae7SAlex Tomas 		goto corrupted;
407c29c0ae7SAlex Tomas 	}
40856b19868SAneesh Kumar K.V 	if (!ext4_valid_extent_entries(inode, eh, depth)) {
40956b19868SAneesh Kumar K.V 		error_msg = "invalid extent entries";
41056b19868SAneesh Kumar K.V 		goto corrupted;
41156b19868SAneesh Kumar K.V 	}
412c29c0ae7SAlex Tomas 	return 0;
413c29c0ae7SAlex Tomas 
414c29c0ae7SAlex Tomas corrupted:
415c398eda0STheodore Ts'o 	ext4_error_inode(inode, function, line, 0,
41624676da4STheodore Ts'o 			"bad header/extent: %s - magic %x, "
417c29c0ae7SAlex Tomas 			"entries %u, max %u(%u), depth %u(%u)",
41824676da4STheodore Ts'o 			error_msg, le16_to_cpu(eh->eh_magic),
419c29c0ae7SAlex Tomas 			le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
420c29c0ae7SAlex Tomas 			max, le16_to_cpu(eh->eh_depth), depth);
421c29c0ae7SAlex Tomas 
422c29c0ae7SAlex Tomas 	return -EIO;
423c29c0ae7SAlex Tomas }
424c29c0ae7SAlex Tomas 
42556b19868SAneesh Kumar K.V #define ext4_ext_check(inode, eh, depth)	\
426c398eda0STheodore Ts'o 	__ext4_ext_check(__func__, __LINE__, inode, eh, depth)
427c29c0ae7SAlex Tomas 
4287a262f7cSAneesh Kumar K.V int ext4_ext_check_inode(struct inode *inode)
4297a262f7cSAneesh Kumar K.V {
4307a262f7cSAneesh Kumar K.V 	return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
4317a262f7cSAneesh Kumar K.V }
4327a262f7cSAneesh Kumar K.V 
433a86c6181SAlex Tomas #ifdef EXT_DEBUG
434a86c6181SAlex Tomas static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
435a86c6181SAlex Tomas {
436a86c6181SAlex Tomas 	int k, l = path->p_depth;
437a86c6181SAlex Tomas 
438a86c6181SAlex Tomas 	ext_debug("path:");
439a86c6181SAlex Tomas 	for (k = 0; k <= l; k++, path++) {
440a86c6181SAlex Tomas 		if (path->p_idx) {
4412ae02107SMingming Cao 		  ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
442bf89d16fSTheodore Ts'o 			    ext4_idx_pblock(path->p_idx));
443a86c6181SAlex Tomas 		} else if (path->p_ext) {
444553f9008SMingming 			ext_debug("  %d:[%d]%d:%llu ",
445a86c6181SAlex Tomas 				  le32_to_cpu(path->p_ext->ee_block),
446553f9008SMingming 				  ext4_ext_is_uninitialized(path->p_ext),
447a2df2a63SAmit Arora 				  ext4_ext_get_actual_len(path->p_ext),
448bf89d16fSTheodore Ts'o 				  ext4_ext_pblock(path->p_ext));
449a86c6181SAlex Tomas 		} else
450a86c6181SAlex Tomas 			ext_debug("  []");
451a86c6181SAlex Tomas 	}
452a86c6181SAlex Tomas 	ext_debug("\n");
453a86c6181SAlex Tomas }
454a86c6181SAlex Tomas 
455a86c6181SAlex Tomas static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
456a86c6181SAlex Tomas {
457a86c6181SAlex Tomas 	int depth = ext_depth(inode);
458a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
459a86c6181SAlex Tomas 	struct ext4_extent *ex;
460a86c6181SAlex Tomas 	int i;
461a86c6181SAlex Tomas 
462a86c6181SAlex Tomas 	if (!path)
463a86c6181SAlex Tomas 		return;
464a86c6181SAlex Tomas 
465a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
466a86c6181SAlex Tomas 	ex = EXT_FIRST_EXTENT(eh);
467a86c6181SAlex Tomas 
468553f9008SMingming 	ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
469553f9008SMingming 
470a86c6181SAlex Tomas 	for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
471553f9008SMingming 		ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
472553f9008SMingming 			  ext4_ext_is_uninitialized(ex),
473bf89d16fSTheodore Ts'o 			  ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
474a86c6181SAlex Tomas 	}
475a86c6181SAlex Tomas 	ext_debug("\n");
476a86c6181SAlex Tomas }
477a86c6181SAlex Tomas #else
478a86c6181SAlex Tomas #define ext4_ext_show_path(inode, path)
479a86c6181SAlex Tomas #define ext4_ext_show_leaf(inode, path)
480a86c6181SAlex Tomas #endif
481a86c6181SAlex Tomas 
482b35905c1SAneesh Kumar K.V void ext4_ext_drop_refs(struct ext4_ext_path *path)
483a86c6181SAlex Tomas {
484a86c6181SAlex Tomas 	int depth = path->p_depth;
485a86c6181SAlex Tomas 	int i;
486a86c6181SAlex Tomas 
487a86c6181SAlex Tomas 	for (i = 0; i <= depth; i++, path++)
488a86c6181SAlex Tomas 		if (path->p_bh) {
489a86c6181SAlex Tomas 			brelse(path->p_bh);
490a86c6181SAlex Tomas 			path->p_bh = NULL;
491a86c6181SAlex Tomas 		}
492a86c6181SAlex Tomas }
493a86c6181SAlex Tomas 
494a86c6181SAlex Tomas /*
495d0d856e8SRandy Dunlap  * ext4_ext_binsearch_idx:
496d0d856e8SRandy Dunlap  * binary search for the closest index of the given block
497c29c0ae7SAlex Tomas  * the header must be checked before calling this
498a86c6181SAlex Tomas  */
499a86c6181SAlex Tomas static void
500725d26d3SAneesh Kumar K.V ext4_ext_binsearch_idx(struct inode *inode,
501725d26d3SAneesh Kumar K.V 			struct ext4_ext_path *path, ext4_lblk_t block)
502a86c6181SAlex Tomas {
503a86c6181SAlex Tomas 	struct ext4_extent_header *eh = path->p_hdr;
504a86c6181SAlex Tomas 	struct ext4_extent_idx *r, *l, *m;
505a86c6181SAlex Tomas 
506a86c6181SAlex Tomas 
507bba90743SEric Sandeen 	ext_debug("binsearch for %u(idx):  ", block);
508a86c6181SAlex Tomas 
509a86c6181SAlex Tomas 	l = EXT_FIRST_INDEX(eh) + 1;
510e9f410b1SDmitry Monakhov 	r = EXT_LAST_INDEX(eh);
511a86c6181SAlex Tomas 	while (l <= r) {
512a86c6181SAlex Tomas 		m = l + (r - l) / 2;
513a86c6181SAlex Tomas 		if (block < le32_to_cpu(m->ei_block))
514a86c6181SAlex Tomas 			r = m - 1;
515a86c6181SAlex Tomas 		else
516a86c6181SAlex Tomas 			l = m + 1;
51726d535edSDmitry Monakhov 		ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
51826d535edSDmitry Monakhov 				m, le32_to_cpu(m->ei_block),
51926d535edSDmitry Monakhov 				r, le32_to_cpu(r->ei_block));
520a86c6181SAlex Tomas 	}
521a86c6181SAlex Tomas 
522a86c6181SAlex Tomas 	path->p_idx = l - 1;
523f65e6fbaSAlex Tomas 	ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
524bf89d16fSTheodore Ts'o 		  ext4_idx_pblock(path->p_idx));
525a86c6181SAlex Tomas 
526a86c6181SAlex Tomas #ifdef CHECK_BINSEARCH
527a86c6181SAlex Tomas 	{
528a86c6181SAlex Tomas 		struct ext4_extent_idx *chix, *ix;
529a86c6181SAlex Tomas 		int k;
530a86c6181SAlex Tomas 
531a86c6181SAlex Tomas 		chix = ix = EXT_FIRST_INDEX(eh);
532a86c6181SAlex Tomas 		for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
533a86c6181SAlex Tomas 		  if (k != 0 &&
534a86c6181SAlex Tomas 		      le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
5354776004fSTheodore Ts'o 				printk(KERN_DEBUG "k=%d, ix=0x%p, "
5364776004fSTheodore Ts'o 				       "first=0x%p\n", k,
537a86c6181SAlex Tomas 				       ix, EXT_FIRST_INDEX(eh));
5384776004fSTheodore Ts'o 				printk(KERN_DEBUG "%u <= %u\n",
539a86c6181SAlex Tomas 				       le32_to_cpu(ix->ei_block),
540a86c6181SAlex Tomas 				       le32_to_cpu(ix[-1].ei_block));
541a86c6181SAlex Tomas 			}
542a86c6181SAlex Tomas 			BUG_ON(k && le32_to_cpu(ix->ei_block)
543a86c6181SAlex Tomas 					   <= le32_to_cpu(ix[-1].ei_block));
544a86c6181SAlex Tomas 			if (block < le32_to_cpu(ix->ei_block))
545a86c6181SAlex Tomas 				break;
546a86c6181SAlex Tomas 			chix = ix;
547a86c6181SAlex Tomas 		}
548a86c6181SAlex Tomas 		BUG_ON(chix != path->p_idx);
549a86c6181SAlex Tomas 	}
550a86c6181SAlex Tomas #endif
551a86c6181SAlex Tomas 
552a86c6181SAlex Tomas }
553a86c6181SAlex Tomas 
554a86c6181SAlex Tomas /*
555d0d856e8SRandy Dunlap  * ext4_ext_binsearch:
556d0d856e8SRandy Dunlap  * binary search for closest extent of the given block
557c29c0ae7SAlex Tomas  * the header must be checked before calling this
558a86c6181SAlex Tomas  */
559a86c6181SAlex Tomas static void
560725d26d3SAneesh Kumar K.V ext4_ext_binsearch(struct inode *inode,
561725d26d3SAneesh Kumar K.V 		struct ext4_ext_path *path, ext4_lblk_t block)
562a86c6181SAlex Tomas {
563a86c6181SAlex Tomas 	struct ext4_extent_header *eh = path->p_hdr;
564a86c6181SAlex Tomas 	struct ext4_extent *r, *l, *m;
565a86c6181SAlex Tomas 
566a86c6181SAlex Tomas 	if (eh->eh_entries == 0) {
567a86c6181SAlex Tomas 		/*
568d0d856e8SRandy Dunlap 		 * this leaf is empty:
569a86c6181SAlex Tomas 		 * we get such a leaf in split/add case
570a86c6181SAlex Tomas 		 */
571a86c6181SAlex Tomas 		return;
572a86c6181SAlex Tomas 	}
573a86c6181SAlex Tomas 
574bba90743SEric Sandeen 	ext_debug("binsearch for %u:  ", block);
575a86c6181SAlex Tomas 
576a86c6181SAlex Tomas 	l = EXT_FIRST_EXTENT(eh) + 1;
577e9f410b1SDmitry Monakhov 	r = EXT_LAST_EXTENT(eh);
578a86c6181SAlex Tomas 
579a86c6181SAlex Tomas 	while (l <= r) {
580a86c6181SAlex Tomas 		m = l + (r - l) / 2;
581a86c6181SAlex Tomas 		if (block < le32_to_cpu(m->ee_block))
582a86c6181SAlex Tomas 			r = m - 1;
583a86c6181SAlex Tomas 		else
584a86c6181SAlex Tomas 			l = m + 1;
58526d535edSDmitry Monakhov 		ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
58626d535edSDmitry Monakhov 				m, le32_to_cpu(m->ee_block),
58726d535edSDmitry Monakhov 				r, le32_to_cpu(r->ee_block));
588a86c6181SAlex Tomas 	}
589a86c6181SAlex Tomas 
590a86c6181SAlex Tomas 	path->p_ext = l - 1;
591553f9008SMingming 	ext_debug("  -> %d:%llu:[%d]%d ",
592a86c6181SAlex Tomas 			le32_to_cpu(path->p_ext->ee_block),
593bf89d16fSTheodore Ts'o 			ext4_ext_pblock(path->p_ext),
594553f9008SMingming 			ext4_ext_is_uninitialized(path->p_ext),
595a2df2a63SAmit Arora 			ext4_ext_get_actual_len(path->p_ext));
596a86c6181SAlex Tomas 
597a86c6181SAlex Tomas #ifdef CHECK_BINSEARCH
598a86c6181SAlex Tomas 	{
599a86c6181SAlex Tomas 		struct ext4_extent *chex, *ex;
600a86c6181SAlex Tomas 		int k;
601a86c6181SAlex Tomas 
602a86c6181SAlex Tomas 		chex = ex = EXT_FIRST_EXTENT(eh);
603a86c6181SAlex Tomas 		for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
604a86c6181SAlex Tomas 			BUG_ON(k && le32_to_cpu(ex->ee_block)
605a86c6181SAlex Tomas 					  <= le32_to_cpu(ex[-1].ee_block));
606a86c6181SAlex Tomas 			if (block < le32_to_cpu(ex->ee_block))
607a86c6181SAlex Tomas 				break;
608a86c6181SAlex Tomas 			chex = ex;
609a86c6181SAlex Tomas 		}
610a86c6181SAlex Tomas 		BUG_ON(chex != path->p_ext);
611a86c6181SAlex Tomas 	}
612a86c6181SAlex Tomas #endif
613a86c6181SAlex Tomas 
614a86c6181SAlex Tomas }
615a86c6181SAlex Tomas 
616a86c6181SAlex Tomas int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
617a86c6181SAlex Tomas {
618a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
619a86c6181SAlex Tomas 
620a86c6181SAlex Tomas 	eh = ext_inode_hdr(inode);
621a86c6181SAlex Tomas 	eh->eh_depth = 0;
622a86c6181SAlex Tomas 	eh->eh_entries = 0;
623a86c6181SAlex Tomas 	eh->eh_magic = EXT4_EXT_MAGIC;
62455ad63bfSTheodore Ts'o 	eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
625a86c6181SAlex Tomas 	ext4_mark_inode_dirty(handle, inode);
626a86c6181SAlex Tomas 	ext4_ext_invalidate_cache(inode);
627a86c6181SAlex Tomas 	return 0;
628a86c6181SAlex Tomas }
629a86c6181SAlex Tomas 
630a86c6181SAlex Tomas struct ext4_ext_path *
631725d26d3SAneesh Kumar K.V ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
632725d26d3SAneesh Kumar K.V 					struct ext4_ext_path *path)
633a86c6181SAlex Tomas {
634a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
635a86c6181SAlex Tomas 	struct buffer_head *bh;
636a86c6181SAlex Tomas 	short int depth, i, ppos = 0, alloc = 0;
637a86c6181SAlex Tomas 
638a86c6181SAlex Tomas 	eh = ext_inode_hdr(inode);
639c29c0ae7SAlex Tomas 	depth = ext_depth(inode);
640a86c6181SAlex Tomas 
641a86c6181SAlex Tomas 	/* account possible depth increase */
642a86c6181SAlex Tomas 	if (!path) {
6435d4958f9SAvantika Mathur 		path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
644a86c6181SAlex Tomas 				GFP_NOFS);
645a86c6181SAlex Tomas 		if (!path)
646a86c6181SAlex Tomas 			return ERR_PTR(-ENOMEM);
647a86c6181SAlex Tomas 		alloc = 1;
648a86c6181SAlex Tomas 	}
649a86c6181SAlex Tomas 	path[0].p_hdr = eh;
6501973adcbSShen Feng 	path[0].p_bh = NULL;
651a86c6181SAlex Tomas 
652c29c0ae7SAlex Tomas 	i = depth;
653a86c6181SAlex Tomas 	/* walk through the tree */
654a86c6181SAlex Tomas 	while (i) {
6557a262f7cSAneesh Kumar K.V 		int need_to_validate = 0;
6567a262f7cSAneesh Kumar K.V 
657a86c6181SAlex Tomas 		ext_debug("depth %d: num %d, max %d\n",
658a86c6181SAlex Tomas 			  ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
659c29c0ae7SAlex Tomas 
660a86c6181SAlex Tomas 		ext4_ext_binsearch_idx(inode, path + ppos, block);
661bf89d16fSTheodore Ts'o 		path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
662a86c6181SAlex Tomas 		path[ppos].p_depth = i;
663a86c6181SAlex Tomas 		path[ppos].p_ext = NULL;
664a86c6181SAlex Tomas 
6657a262f7cSAneesh Kumar K.V 		bh = sb_getblk(inode->i_sb, path[ppos].p_block);
6667a262f7cSAneesh Kumar K.V 		if (unlikely(!bh))
667a86c6181SAlex Tomas 			goto err;
6687a262f7cSAneesh Kumar K.V 		if (!bh_uptodate_or_lock(bh)) {
669*0562e0baSJiaying Zhang 			trace_ext4_ext_load_extent(inode, block,
670*0562e0baSJiaying Zhang 						path[ppos].p_block);
6717a262f7cSAneesh Kumar K.V 			if (bh_submit_read(bh) < 0) {
6727a262f7cSAneesh Kumar K.V 				put_bh(bh);
6737a262f7cSAneesh Kumar K.V 				goto err;
6747a262f7cSAneesh Kumar K.V 			}
6757a262f7cSAneesh Kumar K.V 			/* validate the extent entries */
6767a262f7cSAneesh Kumar K.V 			need_to_validate = 1;
6777a262f7cSAneesh Kumar K.V 		}
678a86c6181SAlex Tomas 		eh = ext_block_hdr(bh);
679a86c6181SAlex Tomas 		ppos++;
680273df556SFrank Mayhar 		if (unlikely(ppos > depth)) {
681273df556SFrank Mayhar 			put_bh(bh);
682273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
683273df556SFrank Mayhar 					 "ppos %d > depth %d", ppos, depth);
684273df556SFrank Mayhar 			goto err;
685273df556SFrank Mayhar 		}
686a86c6181SAlex Tomas 		path[ppos].p_bh = bh;
687a86c6181SAlex Tomas 		path[ppos].p_hdr = eh;
688a86c6181SAlex Tomas 		i--;
689a86c6181SAlex Tomas 
6907a262f7cSAneesh Kumar K.V 		if (need_to_validate && ext4_ext_check(inode, eh, i))
691a86c6181SAlex Tomas 			goto err;
692a86c6181SAlex Tomas 	}
693a86c6181SAlex Tomas 
694a86c6181SAlex Tomas 	path[ppos].p_depth = i;
695a86c6181SAlex Tomas 	path[ppos].p_ext = NULL;
696a86c6181SAlex Tomas 	path[ppos].p_idx = NULL;
697a86c6181SAlex Tomas 
698a86c6181SAlex Tomas 	/* find extent */
699a86c6181SAlex Tomas 	ext4_ext_binsearch(inode, path + ppos, block);
7001973adcbSShen Feng 	/* if not an empty leaf */
7011973adcbSShen Feng 	if (path[ppos].p_ext)
702bf89d16fSTheodore Ts'o 		path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
703a86c6181SAlex Tomas 
704a86c6181SAlex Tomas 	ext4_ext_show_path(inode, path);
705a86c6181SAlex Tomas 
706a86c6181SAlex Tomas 	return path;
707a86c6181SAlex Tomas 
708a86c6181SAlex Tomas err:
709a86c6181SAlex Tomas 	ext4_ext_drop_refs(path);
710a86c6181SAlex Tomas 	if (alloc)
711a86c6181SAlex Tomas 		kfree(path);
712a86c6181SAlex Tomas 	return ERR_PTR(-EIO);
713a86c6181SAlex Tomas }
714a86c6181SAlex Tomas 
715a86c6181SAlex Tomas /*
716d0d856e8SRandy Dunlap  * ext4_ext_insert_index:
717d0d856e8SRandy Dunlap  * insert new index [@logical;@ptr] into the block at @curp;
718d0d856e8SRandy Dunlap  * check where to insert: before @curp or after @curp
719a86c6181SAlex Tomas  */
7201f109d5aSTheodore Ts'o static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
721a86c6181SAlex Tomas 				 struct ext4_ext_path *curp,
722f65e6fbaSAlex Tomas 				 int logical, ext4_fsblk_t ptr)
723a86c6181SAlex Tomas {
724a86c6181SAlex Tomas 	struct ext4_extent_idx *ix;
725a86c6181SAlex Tomas 	int len, err;
726a86c6181SAlex Tomas 
7277e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, curp);
7287e028976SAvantika Mathur 	if (err)
729a86c6181SAlex Tomas 		return err;
730a86c6181SAlex Tomas 
731273df556SFrank Mayhar 	if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
732273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
733273df556SFrank Mayhar 				 "logical %d == ei_block %d!",
734273df556SFrank Mayhar 				 logical, le32_to_cpu(curp->p_idx->ei_block));
735273df556SFrank Mayhar 		return -EIO;
736273df556SFrank Mayhar 	}
737a86c6181SAlex Tomas 	len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
738a86c6181SAlex Tomas 	if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
739a86c6181SAlex Tomas 		/* insert after */
740a86c6181SAlex Tomas 		if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
741a86c6181SAlex Tomas 			len = (len - 1) * sizeof(struct ext4_extent_idx);
742a86c6181SAlex Tomas 			len = len < 0 ? 0 : len;
74326d535edSDmitry Monakhov 			ext_debug("insert new index %d after: %llu. "
744a86c6181SAlex Tomas 					"move %d from 0x%p to 0x%p\n",
745a86c6181SAlex Tomas 					logical, ptr, len,
746a86c6181SAlex Tomas 					(curp->p_idx + 1), (curp->p_idx + 2));
747a86c6181SAlex Tomas 			memmove(curp->p_idx + 2, curp->p_idx + 1, len);
748a86c6181SAlex Tomas 		}
749a86c6181SAlex Tomas 		ix = curp->p_idx + 1;
750a86c6181SAlex Tomas 	} else {
751a86c6181SAlex Tomas 		/* insert before */
752a86c6181SAlex Tomas 		len = len * sizeof(struct ext4_extent_idx);
753a86c6181SAlex Tomas 		len = len < 0 ? 0 : len;
75426d535edSDmitry Monakhov 		ext_debug("insert new index %d before: %llu. "
755a86c6181SAlex Tomas 				"move %d from 0x%p to 0x%p\n",
756a86c6181SAlex Tomas 				logical, ptr, len,
757a86c6181SAlex Tomas 				curp->p_idx, (curp->p_idx + 1));
758a86c6181SAlex Tomas 		memmove(curp->p_idx + 1, curp->p_idx, len);
759a86c6181SAlex Tomas 		ix = curp->p_idx;
760a86c6181SAlex Tomas 	}
761a86c6181SAlex Tomas 
762a86c6181SAlex Tomas 	ix->ei_block = cpu_to_le32(logical);
763f65e6fbaSAlex Tomas 	ext4_idx_store_pblock(ix, ptr);
764e8546d06SMarcin Slusarz 	le16_add_cpu(&curp->p_hdr->eh_entries, 1);
765a86c6181SAlex Tomas 
766273df556SFrank Mayhar 	if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
767273df556SFrank Mayhar 			     > le16_to_cpu(curp->p_hdr->eh_max))) {
768273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
769273df556SFrank Mayhar 				 "logical %d == ei_block %d!",
770273df556SFrank Mayhar 				 logical, le32_to_cpu(curp->p_idx->ei_block));
771273df556SFrank Mayhar 		return -EIO;
772273df556SFrank Mayhar 	}
773273df556SFrank Mayhar 	if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
774273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
775273df556SFrank Mayhar 		return -EIO;
776273df556SFrank Mayhar 	}
777a86c6181SAlex Tomas 
778a86c6181SAlex Tomas 	err = ext4_ext_dirty(handle, inode, curp);
779a86c6181SAlex Tomas 	ext4_std_error(inode->i_sb, err);
780a86c6181SAlex Tomas 
781a86c6181SAlex Tomas 	return err;
782a86c6181SAlex Tomas }
783a86c6181SAlex Tomas 
784a86c6181SAlex Tomas /*
785d0d856e8SRandy Dunlap  * ext4_ext_split:
786d0d856e8SRandy Dunlap  * inserts new subtree into the path, using free index entry
787d0d856e8SRandy Dunlap  * at depth @at:
788a86c6181SAlex Tomas  * - allocates all needed blocks (new leaf and all intermediate index blocks)
789a86c6181SAlex Tomas  * - makes decision where to split
790d0d856e8SRandy Dunlap  * - moves remaining extents and index entries (right to the split point)
791a86c6181SAlex Tomas  *   into the newly allocated blocks
792d0d856e8SRandy Dunlap  * - initializes subtree
793a86c6181SAlex Tomas  */
794a86c6181SAlex Tomas static int ext4_ext_split(handle_t *handle, struct inode *inode,
795a86c6181SAlex Tomas 				struct ext4_ext_path *path,
796a86c6181SAlex Tomas 				struct ext4_extent *newext, int at)
797a86c6181SAlex Tomas {
798a86c6181SAlex Tomas 	struct buffer_head *bh = NULL;
799a86c6181SAlex Tomas 	int depth = ext_depth(inode);
800a86c6181SAlex Tomas 	struct ext4_extent_header *neh;
801a86c6181SAlex Tomas 	struct ext4_extent_idx *fidx;
802a86c6181SAlex Tomas 	struct ext4_extent *ex;
803a86c6181SAlex Tomas 	int i = at, k, m, a;
804f65e6fbaSAlex Tomas 	ext4_fsblk_t newblock, oldblock;
805a86c6181SAlex Tomas 	__le32 border;
806f65e6fbaSAlex Tomas 	ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
807a86c6181SAlex Tomas 	int err = 0;
808a86c6181SAlex Tomas 
809a86c6181SAlex Tomas 	/* make decision: where to split? */
810d0d856e8SRandy Dunlap 	/* FIXME: now decision is simplest: at current extent */
811a86c6181SAlex Tomas 
812d0d856e8SRandy Dunlap 	/* if current leaf will be split, then we should use
813a86c6181SAlex Tomas 	 * border from split point */
814273df556SFrank Mayhar 	if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
815273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
816273df556SFrank Mayhar 		return -EIO;
817273df556SFrank Mayhar 	}
818a86c6181SAlex Tomas 	if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
819a86c6181SAlex Tomas 		border = path[depth].p_ext[1].ee_block;
820d0d856e8SRandy Dunlap 		ext_debug("leaf will be split."
821a86c6181SAlex Tomas 				" next leaf starts at %d\n",
822a86c6181SAlex Tomas 				  le32_to_cpu(border));
823a86c6181SAlex Tomas 	} else {
824a86c6181SAlex Tomas 		border = newext->ee_block;
825a86c6181SAlex Tomas 		ext_debug("leaf will be added."
826a86c6181SAlex Tomas 				" next leaf starts at %d\n",
827a86c6181SAlex Tomas 				le32_to_cpu(border));
828a86c6181SAlex Tomas 	}
829a86c6181SAlex Tomas 
830a86c6181SAlex Tomas 	/*
831d0d856e8SRandy Dunlap 	 * If error occurs, then we break processing
832d0d856e8SRandy Dunlap 	 * and mark filesystem read-only. index won't
833a86c6181SAlex Tomas 	 * be inserted and tree will be in consistent
834d0d856e8SRandy Dunlap 	 * state. Next mount will repair buffers too.
835a86c6181SAlex Tomas 	 */
836a86c6181SAlex Tomas 
837a86c6181SAlex Tomas 	/*
838d0d856e8SRandy Dunlap 	 * Get array to track all allocated blocks.
839d0d856e8SRandy Dunlap 	 * We need this to handle errors and free blocks
840d0d856e8SRandy Dunlap 	 * upon them.
841a86c6181SAlex Tomas 	 */
8425d4958f9SAvantika Mathur 	ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
843a86c6181SAlex Tomas 	if (!ablocks)
844a86c6181SAlex Tomas 		return -ENOMEM;
845a86c6181SAlex Tomas 
846a86c6181SAlex Tomas 	/* allocate all needed blocks */
847a86c6181SAlex Tomas 	ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
848a86c6181SAlex Tomas 	for (a = 0; a < depth - at; a++) {
849654b4908SAneesh Kumar K.V 		newblock = ext4_ext_new_meta_block(handle, inode, path,
850654b4908SAneesh Kumar K.V 						   newext, &err);
851a86c6181SAlex Tomas 		if (newblock == 0)
852a86c6181SAlex Tomas 			goto cleanup;
853a86c6181SAlex Tomas 		ablocks[a] = newblock;
854a86c6181SAlex Tomas 	}
855a86c6181SAlex Tomas 
856a86c6181SAlex Tomas 	/* initialize new leaf */
857a86c6181SAlex Tomas 	newblock = ablocks[--a];
858273df556SFrank Mayhar 	if (unlikely(newblock == 0)) {
859273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "newblock == 0!");
860273df556SFrank Mayhar 		err = -EIO;
861273df556SFrank Mayhar 		goto cleanup;
862273df556SFrank Mayhar 	}
863a86c6181SAlex Tomas 	bh = sb_getblk(inode->i_sb, newblock);
864a86c6181SAlex Tomas 	if (!bh) {
865a86c6181SAlex Tomas 		err = -EIO;
866a86c6181SAlex Tomas 		goto cleanup;
867a86c6181SAlex Tomas 	}
868a86c6181SAlex Tomas 	lock_buffer(bh);
869a86c6181SAlex Tomas 
8707e028976SAvantika Mathur 	err = ext4_journal_get_create_access(handle, bh);
8717e028976SAvantika Mathur 	if (err)
872a86c6181SAlex Tomas 		goto cleanup;
873a86c6181SAlex Tomas 
874a86c6181SAlex Tomas 	neh = ext_block_hdr(bh);
875a86c6181SAlex Tomas 	neh->eh_entries = 0;
87655ad63bfSTheodore Ts'o 	neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
877a86c6181SAlex Tomas 	neh->eh_magic = EXT4_EXT_MAGIC;
878a86c6181SAlex Tomas 	neh->eh_depth = 0;
879a86c6181SAlex Tomas 	ex = EXT_FIRST_EXTENT(neh);
880a86c6181SAlex Tomas 
881d0d856e8SRandy Dunlap 	/* move remainder of path[depth] to the new leaf */
882273df556SFrank Mayhar 	if (unlikely(path[depth].p_hdr->eh_entries !=
883273df556SFrank Mayhar 		     path[depth].p_hdr->eh_max)) {
884273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
885273df556SFrank Mayhar 				 path[depth].p_hdr->eh_entries,
886273df556SFrank Mayhar 				 path[depth].p_hdr->eh_max);
887273df556SFrank Mayhar 		err = -EIO;
888273df556SFrank Mayhar 		goto cleanup;
889273df556SFrank Mayhar 	}
890a86c6181SAlex Tomas 	/* start copy from next extent */
891a86c6181SAlex Tomas 	/* TODO: we could do it by single memmove */
892a86c6181SAlex Tomas 	m = 0;
893a86c6181SAlex Tomas 	path[depth].p_ext++;
894a86c6181SAlex Tomas 	while (path[depth].p_ext <=
895a86c6181SAlex Tomas 			EXT_MAX_EXTENT(path[depth].p_hdr)) {
896553f9008SMingming 		ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
897a86c6181SAlex Tomas 				le32_to_cpu(path[depth].p_ext->ee_block),
898bf89d16fSTheodore Ts'o 				ext4_ext_pblock(path[depth].p_ext),
899553f9008SMingming 				ext4_ext_is_uninitialized(path[depth].p_ext),
900a2df2a63SAmit Arora 				ext4_ext_get_actual_len(path[depth].p_ext),
901a86c6181SAlex Tomas 				newblock);
902a86c6181SAlex Tomas 		/*memmove(ex++, path[depth].p_ext++,
903a86c6181SAlex Tomas 				sizeof(struct ext4_extent));
904a86c6181SAlex Tomas 		neh->eh_entries++;*/
905a86c6181SAlex Tomas 		path[depth].p_ext++;
906a86c6181SAlex Tomas 		m++;
907a86c6181SAlex Tomas 	}
908a86c6181SAlex Tomas 	if (m) {
909a86c6181SAlex Tomas 		memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
910e8546d06SMarcin Slusarz 		le16_add_cpu(&neh->eh_entries, m);
911a86c6181SAlex Tomas 	}
912a86c6181SAlex Tomas 
913a86c6181SAlex Tomas 	set_buffer_uptodate(bh);
914a86c6181SAlex Tomas 	unlock_buffer(bh);
915a86c6181SAlex Tomas 
9160390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, inode, bh);
9177e028976SAvantika Mathur 	if (err)
918a86c6181SAlex Tomas 		goto cleanup;
919a86c6181SAlex Tomas 	brelse(bh);
920a86c6181SAlex Tomas 	bh = NULL;
921a86c6181SAlex Tomas 
922a86c6181SAlex Tomas 	/* correct old leaf */
923a86c6181SAlex Tomas 	if (m) {
9247e028976SAvantika Mathur 		err = ext4_ext_get_access(handle, inode, path + depth);
9257e028976SAvantika Mathur 		if (err)
926a86c6181SAlex Tomas 			goto cleanup;
927e8546d06SMarcin Slusarz 		le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
9287e028976SAvantika Mathur 		err = ext4_ext_dirty(handle, inode, path + depth);
9297e028976SAvantika Mathur 		if (err)
930a86c6181SAlex Tomas 			goto cleanup;
931a86c6181SAlex Tomas 
932a86c6181SAlex Tomas 	}
933a86c6181SAlex Tomas 
934a86c6181SAlex Tomas 	/* create intermediate indexes */
935a86c6181SAlex Tomas 	k = depth - at - 1;
936273df556SFrank Mayhar 	if (unlikely(k < 0)) {
937273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "k %d < 0!", k);
938273df556SFrank Mayhar 		err = -EIO;
939273df556SFrank Mayhar 		goto cleanup;
940273df556SFrank Mayhar 	}
941a86c6181SAlex Tomas 	if (k)
942a86c6181SAlex Tomas 		ext_debug("create %d intermediate indices\n", k);
943a86c6181SAlex Tomas 	/* insert new index into current index block */
944a86c6181SAlex Tomas 	/* current depth stored in i var */
945a86c6181SAlex Tomas 	i = depth - 1;
946a86c6181SAlex Tomas 	while (k--) {
947a86c6181SAlex Tomas 		oldblock = newblock;
948a86c6181SAlex Tomas 		newblock = ablocks[--a];
949bba90743SEric Sandeen 		bh = sb_getblk(inode->i_sb, newblock);
950a86c6181SAlex Tomas 		if (!bh) {
951a86c6181SAlex Tomas 			err = -EIO;
952a86c6181SAlex Tomas 			goto cleanup;
953a86c6181SAlex Tomas 		}
954a86c6181SAlex Tomas 		lock_buffer(bh);
955a86c6181SAlex Tomas 
9567e028976SAvantika Mathur 		err = ext4_journal_get_create_access(handle, bh);
9577e028976SAvantika Mathur 		if (err)
958a86c6181SAlex Tomas 			goto cleanup;
959a86c6181SAlex Tomas 
960a86c6181SAlex Tomas 		neh = ext_block_hdr(bh);
961a86c6181SAlex Tomas 		neh->eh_entries = cpu_to_le16(1);
962a86c6181SAlex Tomas 		neh->eh_magic = EXT4_EXT_MAGIC;
96355ad63bfSTheodore Ts'o 		neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
964a86c6181SAlex Tomas 		neh->eh_depth = cpu_to_le16(depth - i);
965a86c6181SAlex Tomas 		fidx = EXT_FIRST_INDEX(neh);
966a86c6181SAlex Tomas 		fidx->ei_block = border;
967f65e6fbaSAlex Tomas 		ext4_idx_store_pblock(fidx, oldblock);
968a86c6181SAlex Tomas 
969bba90743SEric Sandeen 		ext_debug("int.index at %d (block %llu): %u -> %llu\n",
970bba90743SEric Sandeen 				i, newblock, le32_to_cpu(border), oldblock);
971a86c6181SAlex Tomas 		/* copy indexes */
972a86c6181SAlex Tomas 		m = 0;
973a86c6181SAlex Tomas 		path[i].p_idx++;
974a86c6181SAlex Tomas 
975a86c6181SAlex Tomas 		ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
976a86c6181SAlex Tomas 				EXT_MAX_INDEX(path[i].p_hdr));
977273df556SFrank Mayhar 		if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
978273df556SFrank Mayhar 					EXT_LAST_INDEX(path[i].p_hdr))) {
979273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
980273df556SFrank Mayhar 					 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
981273df556SFrank Mayhar 					 le32_to_cpu(path[i].p_ext->ee_block));
982273df556SFrank Mayhar 			err = -EIO;
983273df556SFrank Mayhar 			goto cleanup;
984273df556SFrank Mayhar 		}
985a86c6181SAlex Tomas 		while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
98626d535edSDmitry Monakhov 			ext_debug("%d: move %d:%llu in new index %llu\n", i,
987a86c6181SAlex Tomas 					le32_to_cpu(path[i].p_idx->ei_block),
988bf89d16fSTheodore Ts'o 					ext4_idx_pblock(path[i].p_idx),
989a86c6181SAlex Tomas 					newblock);
990a86c6181SAlex Tomas 			/*memmove(++fidx, path[i].p_idx++,
991a86c6181SAlex Tomas 					sizeof(struct ext4_extent_idx));
992a86c6181SAlex Tomas 			neh->eh_entries++;
993a86c6181SAlex Tomas 			BUG_ON(neh->eh_entries > neh->eh_max);*/
994a86c6181SAlex Tomas 			path[i].p_idx++;
995a86c6181SAlex Tomas 			m++;
996a86c6181SAlex Tomas 		}
997a86c6181SAlex Tomas 		if (m) {
998a86c6181SAlex Tomas 			memmove(++fidx, path[i].p_idx - m,
999a86c6181SAlex Tomas 				sizeof(struct ext4_extent_idx) * m);
1000e8546d06SMarcin Slusarz 			le16_add_cpu(&neh->eh_entries, m);
1001a86c6181SAlex Tomas 		}
1002a86c6181SAlex Tomas 		set_buffer_uptodate(bh);
1003a86c6181SAlex Tomas 		unlock_buffer(bh);
1004a86c6181SAlex Tomas 
10050390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
10067e028976SAvantika Mathur 		if (err)
1007a86c6181SAlex Tomas 			goto cleanup;
1008a86c6181SAlex Tomas 		brelse(bh);
1009a86c6181SAlex Tomas 		bh = NULL;
1010a86c6181SAlex Tomas 
1011a86c6181SAlex Tomas 		/* correct old index */
1012a86c6181SAlex Tomas 		if (m) {
1013a86c6181SAlex Tomas 			err = ext4_ext_get_access(handle, inode, path + i);
1014a86c6181SAlex Tomas 			if (err)
1015a86c6181SAlex Tomas 				goto cleanup;
1016e8546d06SMarcin Slusarz 			le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1017a86c6181SAlex Tomas 			err = ext4_ext_dirty(handle, inode, path + i);
1018a86c6181SAlex Tomas 			if (err)
1019a86c6181SAlex Tomas 				goto cleanup;
1020a86c6181SAlex Tomas 		}
1021a86c6181SAlex Tomas 
1022a86c6181SAlex Tomas 		i--;
1023a86c6181SAlex Tomas 	}
1024a86c6181SAlex Tomas 
1025a86c6181SAlex Tomas 	/* insert new index */
1026a86c6181SAlex Tomas 	err = ext4_ext_insert_index(handle, inode, path + at,
1027a86c6181SAlex Tomas 				    le32_to_cpu(border), newblock);
1028a86c6181SAlex Tomas 
1029a86c6181SAlex Tomas cleanup:
1030a86c6181SAlex Tomas 	if (bh) {
1031a86c6181SAlex Tomas 		if (buffer_locked(bh))
1032a86c6181SAlex Tomas 			unlock_buffer(bh);
1033a86c6181SAlex Tomas 		brelse(bh);
1034a86c6181SAlex Tomas 	}
1035a86c6181SAlex Tomas 
1036a86c6181SAlex Tomas 	if (err) {
1037a86c6181SAlex Tomas 		/* free all allocated blocks in error case */
1038a86c6181SAlex Tomas 		for (i = 0; i < depth; i++) {
1039a86c6181SAlex Tomas 			if (!ablocks[i])
1040a86c6181SAlex Tomas 				continue;
10417dc57615SPeter Huewe 			ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1042e6362609STheodore Ts'o 					 EXT4_FREE_BLOCKS_METADATA);
1043a86c6181SAlex Tomas 		}
1044a86c6181SAlex Tomas 	}
1045a86c6181SAlex Tomas 	kfree(ablocks);
1046a86c6181SAlex Tomas 
1047a86c6181SAlex Tomas 	return err;
1048a86c6181SAlex Tomas }
1049a86c6181SAlex Tomas 
1050a86c6181SAlex Tomas /*
1051d0d856e8SRandy Dunlap  * ext4_ext_grow_indepth:
1052d0d856e8SRandy Dunlap  * implements tree growing procedure:
1053a86c6181SAlex Tomas  * - allocates new block
1054a86c6181SAlex Tomas  * - moves top-level data (index block or leaf) into the new block
1055d0d856e8SRandy Dunlap  * - initializes new top-level, creating index that points to the
1056a86c6181SAlex Tomas  *   just created block
1057a86c6181SAlex Tomas  */
1058a86c6181SAlex Tomas static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1059a86c6181SAlex Tomas 					struct ext4_ext_path *path,
1060a86c6181SAlex Tomas 					struct ext4_extent *newext)
1061a86c6181SAlex Tomas {
1062a86c6181SAlex Tomas 	struct ext4_ext_path *curp = path;
1063a86c6181SAlex Tomas 	struct ext4_extent_header *neh;
1064a86c6181SAlex Tomas 	struct buffer_head *bh;
1065f65e6fbaSAlex Tomas 	ext4_fsblk_t newblock;
1066a86c6181SAlex Tomas 	int err = 0;
1067a86c6181SAlex Tomas 
1068654b4908SAneesh Kumar K.V 	newblock = ext4_ext_new_meta_block(handle, inode, path, newext, &err);
1069a86c6181SAlex Tomas 	if (newblock == 0)
1070a86c6181SAlex Tomas 		return err;
1071a86c6181SAlex Tomas 
1072a86c6181SAlex Tomas 	bh = sb_getblk(inode->i_sb, newblock);
1073a86c6181SAlex Tomas 	if (!bh) {
1074a86c6181SAlex Tomas 		err = -EIO;
1075a86c6181SAlex Tomas 		ext4_std_error(inode->i_sb, err);
1076a86c6181SAlex Tomas 		return err;
1077a86c6181SAlex Tomas 	}
1078a86c6181SAlex Tomas 	lock_buffer(bh);
1079a86c6181SAlex Tomas 
10807e028976SAvantika Mathur 	err = ext4_journal_get_create_access(handle, bh);
10817e028976SAvantika Mathur 	if (err) {
1082a86c6181SAlex Tomas 		unlock_buffer(bh);
1083a86c6181SAlex Tomas 		goto out;
1084a86c6181SAlex Tomas 	}
1085a86c6181SAlex Tomas 
1086a86c6181SAlex Tomas 	/* move top-level index/leaf into new block */
1087a86c6181SAlex Tomas 	memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
1088a86c6181SAlex Tomas 
1089a86c6181SAlex Tomas 	/* set size of new block */
1090a86c6181SAlex Tomas 	neh = ext_block_hdr(bh);
1091a86c6181SAlex Tomas 	/* old root could have indexes or leaves
1092a86c6181SAlex Tomas 	 * so calculate e_max right way */
1093a86c6181SAlex Tomas 	if (ext_depth(inode))
109455ad63bfSTheodore Ts'o 		neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1095a86c6181SAlex Tomas 	else
109655ad63bfSTheodore Ts'o 		neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1097a86c6181SAlex Tomas 	neh->eh_magic = EXT4_EXT_MAGIC;
1098a86c6181SAlex Tomas 	set_buffer_uptodate(bh);
1099a86c6181SAlex Tomas 	unlock_buffer(bh);
1100a86c6181SAlex Tomas 
11010390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, inode, bh);
11027e028976SAvantika Mathur 	if (err)
1103a86c6181SAlex Tomas 		goto out;
1104a86c6181SAlex Tomas 
1105a86c6181SAlex Tomas 	/* create index in new top-level index: num,max,pointer */
11067e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, curp);
11077e028976SAvantika Mathur 	if (err)
1108a86c6181SAlex Tomas 		goto out;
1109a86c6181SAlex Tomas 
1110a86c6181SAlex Tomas 	curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
111155ad63bfSTheodore Ts'o 	curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1112a86c6181SAlex Tomas 	curp->p_hdr->eh_entries = cpu_to_le16(1);
1113a86c6181SAlex Tomas 	curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
1114e9f410b1SDmitry Monakhov 
1115e9f410b1SDmitry Monakhov 	if (path[0].p_hdr->eh_depth)
1116e9f410b1SDmitry Monakhov 		curp->p_idx->ei_block =
1117e9f410b1SDmitry Monakhov 			EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
1118e9f410b1SDmitry Monakhov 	else
1119e9f410b1SDmitry Monakhov 		curp->p_idx->ei_block =
1120e9f410b1SDmitry Monakhov 			EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
1121f65e6fbaSAlex Tomas 	ext4_idx_store_pblock(curp->p_idx, newblock);
1122a86c6181SAlex Tomas 
1123a86c6181SAlex Tomas 	neh = ext_inode_hdr(inode);
11242ae02107SMingming Cao 	ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1125a86c6181SAlex Tomas 		  le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
11265a0790c2SAndi Kleen 		  le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1127bf89d16fSTheodore Ts'o 		  ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1128a86c6181SAlex Tomas 
1129a86c6181SAlex Tomas 	neh->eh_depth = cpu_to_le16(path->p_depth + 1);
1130a86c6181SAlex Tomas 	err = ext4_ext_dirty(handle, inode, curp);
1131a86c6181SAlex Tomas out:
1132a86c6181SAlex Tomas 	brelse(bh);
1133a86c6181SAlex Tomas 
1134a86c6181SAlex Tomas 	return err;
1135a86c6181SAlex Tomas }
1136a86c6181SAlex Tomas 
1137a86c6181SAlex Tomas /*
1138d0d856e8SRandy Dunlap  * ext4_ext_create_new_leaf:
1139d0d856e8SRandy Dunlap  * finds empty index and adds new leaf.
1140d0d856e8SRandy Dunlap  * if no free index is found, then it requests in-depth growing.
1141a86c6181SAlex Tomas  */
1142a86c6181SAlex Tomas static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1143a86c6181SAlex Tomas 					struct ext4_ext_path *path,
1144a86c6181SAlex Tomas 					struct ext4_extent *newext)
1145a86c6181SAlex Tomas {
1146a86c6181SAlex Tomas 	struct ext4_ext_path *curp;
1147a86c6181SAlex Tomas 	int depth, i, err = 0;
1148a86c6181SAlex Tomas 
1149a86c6181SAlex Tomas repeat:
1150a86c6181SAlex Tomas 	i = depth = ext_depth(inode);
1151a86c6181SAlex Tomas 
1152a86c6181SAlex Tomas 	/* walk up to the tree and look for free index entry */
1153a86c6181SAlex Tomas 	curp = path + depth;
1154a86c6181SAlex Tomas 	while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1155a86c6181SAlex Tomas 		i--;
1156a86c6181SAlex Tomas 		curp--;
1157a86c6181SAlex Tomas 	}
1158a86c6181SAlex Tomas 
1159d0d856e8SRandy Dunlap 	/* we use already allocated block for index block,
1160d0d856e8SRandy Dunlap 	 * so subsequent data blocks should be contiguous */
1161a86c6181SAlex Tomas 	if (EXT_HAS_FREE_INDEX(curp)) {
1162a86c6181SAlex Tomas 		/* if we found index with free entry, then use that
1163a86c6181SAlex Tomas 		 * entry: create all needed subtree and add new leaf */
1164a86c6181SAlex Tomas 		err = ext4_ext_split(handle, inode, path, newext, i);
1165787e0981SShen Feng 		if (err)
1166787e0981SShen Feng 			goto out;
1167a86c6181SAlex Tomas 
1168a86c6181SAlex Tomas 		/* refill path */
1169a86c6181SAlex Tomas 		ext4_ext_drop_refs(path);
1170a86c6181SAlex Tomas 		path = ext4_ext_find_extent(inode,
1171725d26d3SAneesh Kumar K.V 				    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1172a86c6181SAlex Tomas 				    path);
1173a86c6181SAlex Tomas 		if (IS_ERR(path))
1174a86c6181SAlex Tomas 			err = PTR_ERR(path);
1175a86c6181SAlex Tomas 	} else {
1176a86c6181SAlex Tomas 		/* tree is full, time to grow in depth */
1177a86c6181SAlex Tomas 		err = ext4_ext_grow_indepth(handle, inode, path, newext);
1178a86c6181SAlex Tomas 		if (err)
1179a86c6181SAlex Tomas 			goto out;
1180a86c6181SAlex Tomas 
1181a86c6181SAlex Tomas 		/* refill path */
1182a86c6181SAlex Tomas 		ext4_ext_drop_refs(path);
1183a86c6181SAlex Tomas 		path = ext4_ext_find_extent(inode,
1184725d26d3SAneesh Kumar K.V 				   (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1185a86c6181SAlex Tomas 				    path);
1186a86c6181SAlex Tomas 		if (IS_ERR(path)) {
1187a86c6181SAlex Tomas 			err = PTR_ERR(path);
1188a86c6181SAlex Tomas 			goto out;
1189a86c6181SAlex Tomas 		}
1190a86c6181SAlex Tomas 
1191a86c6181SAlex Tomas 		/*
1192d0d856e8SRandy Dunlap 		 * only first (depth 0 -> 1) produces free space;
1193d0d856e8SRandy Dunlap 		 * in all other cases we have to split the grown tree
1194a86c6181SAlex Tomas 		 */
1195a86c6181SAlex Tomas 		depth = ext_depth(inode);
1196a86c6181SAlex Tomas 		if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1197d0d856e8SRandy Dunlap 			/* now we need to split */
1198a86c6181SAlex Tomas 			goto repeat;
1199a86c6181SAlex Tomas 		}
1200a86c6181SAlex Tomas 	}
1201a86c6181SAlex Tomas 
1202a86c6181SAlex Tomas out:
1203a86c6181SAlex Tomas 	return err;
1204a86c6181SAlex Tomas }
1205a86c6181SAlex Tomas 
1206a86c6181SAlex Tomas /*
12071988b51eSAlex Tomas  * search the closest allocated block to the left for *logical
12081988b51eSAlex Tomas  * and returns it at @logical + it's physical address at @phys
12091988b51eSAlex Tomas  * if *logical is the smallest allocated block, the function
12101988b51eSAlex Tomas  * returns 0 at @phys
12111988b51eSAlex Tomas  * return value contains 0 (success) or error code
12121988b51eSAlex Tomas  */
12131f109d5aSTheodore Ts'o static int ext4_ext_search_left(struct inode *inode,
12141f109d5aSTheodore Ts'o 				struct ext4_ext_path *path,
12151988b51eSAlex Tomas 				ext4_lblk_t *logical, ext4_fsblk_t *phys)
12161988b51eSAlex Tomas {
12171988b51eSAlex Tomas 	struct ext4_extent_idx *ix;
12181988b51eSAlex Tomas 	struct ext4_extent *ex;
1219b939e376SAneesh Kumar K.V 	int depth, ee_len;
12201988b51eSAlex Tomas 
1221273df556SFrank Mayhar 	if (unlikely(path == NULL)) {
1222273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1223273df556SFrank Mayhar 		return -EIO;
1224273df556SFrank Mayhar 	}
12251988b51eSAlex Tomas 	depth = path->p_depth;
12261988b51eSAlex Tomas 	*phys = 0;
12271988b51eSAlex Tomas 
12281988b51eSAlex Tomas 	if (depth == 0 && path->p_ext == NULL)
12291988b51eSAlex Tomas 		return 0;
12301988b51eSAlex Tomas 
12311988b51eSAlex Tomas 	/* usually extent in the path covers blocks smaller
12321988b51eSAlex Tomas 	 * then *logical, but it can be that extent is the
12331988b51eSAlex Tomas 	 * first one in the file */
12341988b51eSAlex Tomas 
12351988b51eSAlex Tomas 	ex = path[depth].p_ext;
1236b939e376SAneesh Kumar K.V 	ee_len = ext4_ext_get_actual_len(ex);
12371988b51eSAlex Tomas 	if (*logical < le32_to_cpu(ex->ee_block)) {
1238273df556SFrank Mayhar 		if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1239273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
1240273df556SFrank Mayhar 					 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1241273df556SFrank Mayhar 					 *logical, le32_to_cpu(ex->ee_block));
1242273df556SFrank Mayhar 			return -EIO;
1243273df556SFrank Mayhar 		}
12441988b51eSAlex Tomas 		while (--depth >= 0) {
12451988b51eSAlex Tomas 			ix = path[depth].p_idx;
1246273df556SFrank Mayhar 			if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1247273df556SFrank Mayhar 				EXT4_ERROR_INODE(inode,
1248273df556SFrank Mayhar 				  "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1249273df556SFrank Mayhar 				  ix != NULL ? ix->ei_block : 0,
1250273df556SFrank Mayhar 				  EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1251273df556SFrank Mayhar 				    EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block : 0,
1252273df556SFrank Mayhar 				  depth);
1253273df556SFrank Mayhar 				return -EIO;
1254273df556SFrank Mayhar 			}
12551988b51eSAlex Tomas 		}
12561988b51eSAlex Tomas 		return 0;
12571988b51eSAlex Tomas 	}
12581988b51eSAlex Tomas 
1259273df556SFrank Mayhar 	if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1260273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
1261273df556SFrank Mayhar 				 "logical %d < ee_block %d + ee_len %d!",
1262273df556SFrank Mayhar 				 *logical, le32_to_cpu(ex->ee_block), ee_len);
1263273df556SFrank Mayhar 		return -EIO;
1264273df556SFrank Mayhar 	}
12651988b51eSAlex Tomas 
1266b939e376SAneesh Kumar K.V 	*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1267bf89d16fSTheodore Ts'o 	*phys = ext4_ext_pblock(ex) + ee_len - 1;
12681988b51eSAlex Tomas 	return 0;
12691988b51eSAlex Tomas }
12701988b51eSAlex Tomas 
12711988b51eSAlex Tomas /*
12721988b51eSAlex Tomas  * search the closest allocated block to the right for *logical
12731988b51eSAlex Tomas  * and returns it at @logical + it's physical address at @phys
12741988b51eSAlex Tomas  * if *logical is the smallest allocated block, the function
12751988b51eSAlex Tomas  * returns 0 at @phys
12761988b51eSAlex Tomas  * return value contains 0 (success) or error code
12771988b51eSAlex Tomas  */
12781f109d5aSTheodore Ts'o static int ext4_ext_search_right(struct inode *inode,
12791f109d5aSTheodore Ts'o 				 struct ext4_ext_path *path,
12801988b51eSAlex Tomas 				 ext4_lblk_t *logical, ext4_fsblk_t *phys)
12811988b51eSAlex Tomas {
12821988b51eSAlex Tomas 	struct buffer_head *bh = NULL;
12831988b51eSAlex Tomas 	struct ext4_extent_header *eh;
12841988b51eSAlex Tomas 	struct ext4_extent_idx *ix;
12851988b51eSAlex Tomas 	struct ext4_extent *ex;
12861988b51eSAlex Tomas 	ext4_fsblk_t block;
1287395a87bfSEric Sandeen 	int depth;	/* Note, NOT eh_depth; depth from top of tree */
1288395a87bfSEric Sandeen 	int ee_len;
12891988b51eSAlex Tomas 
1290273df556SFrank Mayhar 	if (unlikely(path == NULL)) {
1291273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1292273df556SFrank Mayhar 		return -EIO;
1293273df556SFrank Mayhar 	}
12941988b51eSAlex Tomas 	depth = path->p_depth;
12951988b51eSAlex Tomas 	*phys = 0;
12961988b51eSAlex Tomas 
12971988b51eSAlex Tomas 	if (depth == 0 && path->p_ext == NULL)
12981988b51eSAlex Tomas 		return 0;
12991988b51eSAlex Tomas 
13001988b51eSAlex Tomas 	/* usually extent in the path covers blocks smaller
13011988b51eSAlex Tomas 	 * then *logical, but it can be that extent is the
13021988b51eSAlex Tomas 	 * first one in the file */
13031988b51eSAlex Tomas 
13041988b51eSAlex Tomas 	ex = path[depth].p_ext;
1305b939e376SAneesh Kumar K.V 	ee_len = ext4_ext_get_actual_len(ex);
13061988b51eSAlex Tomas 	if (*logical < le32_to_cpu(ex->ee_block)) {
1307273df556SFrank Mayhar 		if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1308273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
1309273df556SFrank Mayhar 					 "first_extent(path[%d].p_hdr) != ex",
1310273df556SFrank Mayhar 					 depth);
1311273df556SFrank Mayhar 			return -EIO;
1312273df556SFrank Mayhar 		}
13131988b51eSAlex Tomas 		while (--depth >= 0) {
13141988b51eSAlex Tomas 			ix = path[depth].p_idx;
1315273df556SFrank Mayhar 			if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1316273df556SFrank Mayhar 				EXT4_ERROR_INODE(inode,
1317273df556SFrank Mayhar 						 "ix != EXT_FIRST_INDEX *logical %d!",
1318273df556SFrank Mayhar 						 *logical);
1319273df556SFrank Mayhar 				return -EIO;
1320273df556SFrank Mayhar 			}
13211988b51eSAlex Tomas 		}
13221988b51eSAlex Tomas 		*logical = le32_to_cpu(ex->ee_block);
1323bf89d16fSTheodore Ts'o 		*phys = ext4_ext_pblock(ex);
13241988b51eSAlex Tomas 		return 0;
13251988b51eSAlex Tomas 	}
13261988b51eSAlex Tomas 
1327273df556SFrank Mayhar 	if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1328273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
1329273df556SFrank Mayhar 				 "logical %d < ee_block %d + ee_len %d!",
1330273df556SFrank Mayhar 				 *logical, le32_to_cpu(ex->ee_block), ee_len);
1331273df556SFrank Mayhar 		return -EIO;
1332273df556SFrank Mayhar 	}
13331988b51eSAlex Tomas 
13341988b51eSAlex Tomas 	if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
13351988b51eSAlex Tomas 		/* next allocated block in this leaf */
13361988b51eSAlex Tomas 		ex++;
13371988b51eSAlex Tomas 		*logical = le32_to_cpu(ex->ee_block);
1338bf89d16fSTheodore Ts'o 		*phys = ext4_ext_pblock(ex);
13391988b51eSAlex Tomas 		return 0;
13401988b51eSAlex Tomas 	}
13411988b51eSAlex Tomas 
13421988b51eSAlex Tomas 	/* go up and search for index to the right */
13431988b51eSAlex Tomas 	while (--depth >= 0) {
13441988b51eSAlex Tomas 		ix = path[depth].p_idx;
13451988b51eSAlex Tomas 		if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
134625f1ee3aSWu Fengguang 			goto got_index;
13471988b51eSAlex Tomas 	}
13481988b51eSAlex Tomas 
134925f1ee3aSWu Fengguang 	/* we've gone up to the root and found no index to the right */
13501988b51eSAlex Tomas 	return 0;
13511988b51eSAlex Tomas 
135225f1ee3aSWu Fengguang got_index:
13531988b51eSAlex Tomas 	/* we've found index to the right, let's
13541988b51eSAlex Tomas 	 * follow it and find the closest allocated
13551988b51eSAlex Tomas 	 * block to the right */
13561988b51eSAlex Tomas 	ix++;
1357bf89d16fSTheodore Ts'o 	block = ext4_idx_pblock(ix);
13581988b51eSAlex Tomas 	while (++depth < path->p_depth) {
13591988b51eSAlex Tomas 		bh = sb_bread(inode->i_sb, block);
13601988b51eSAlex Tomas 		if (bh == NULL)
13611988b51eSAlex Tomas 			return -EIO;
13621988b51eSAlex Tomas 		eh = ext_block_hdr(bh);
1363395a87bfSEric Sandeen 		/* subtract from p_depth to get proper eh_depth */
136456b19868SAneesh Kumar K.V 		if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
13651988b51eSAlex Tomas 			put_bh(bh);
13661988b51eSAlex Tomas 			return -EIO;
13671988b51eSAlex Tomas 		}
13681988b51eSAlex Tomas 		ix = EXT_FIRST_INDEX(eh);
1369bf89d16fSTheodore Ts'o 		block = ext4_idx_pblock(ix);
13701988b51eSAlex Tomas 		put_bh(bh);
13711988b51eSAlex Tomas 	}
13721988b51eSAlex Tomas 
13731988b51eSAlex Tomas 	bh = sb_bread(inode->i_sb, block);
13741988b51eSAlex Tomas 	if (bh == NULL)
13751988b51eSAlex Tomas 		return -EIO;
13761988b51eSAlex Tomas 	eh = ext_block_hdr(bh);
137756b19868SAneesh Kumar K.V 	if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
13781988b51eSAlex Tomas 		put_bh(bh);
13791988b51eSAlex Tomas 		return -EIO;
13801988b51eSAlex Tomas 	}
13811988b51eSAlex Tomas 	ex = EXT_FIRST_EXTENT(eh);
13821988b51eSAlex Tomas 	*logical = le32_to_cpu(ex->ee_block);
1383bf89d16fSTheodore Ts'o 	*phys = ext4_ext_pblock(ex);
13841988b51eSAlex Tomas 	put_bh(bh);
13851988b51eSAlex Tomas 	return 0;
13861988b51eSAlex Tomas }
13871988b51eSAlex Tomas 
13881988b51eSAlex Tomas /*
1389d0d856e8SRandy Dunlap  * ext4_ext_next_allocated_block:
1390d0d856e8SRandy Dunlap  * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1391d0d856e8SRandy Dunlap  * NOTE: it considers block number from index entry as
1392d0d856e8SRandy Dunlap  * allocated block. Thus, index entries have to be consistent
1393d0d856e8SRandy Dunlap  * with leaves.
1394a86c6181SAlex Tomas  */
1395725d26d3SAneesh Kumar K.V static ext4_lblk_t
1396a86c6181SAlex Tomas ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1397a86c6181SAlex Tomas {
1398a86c6181SAlex Tomas 	int depth;
1399a86c6181SAlex Tomas 
1400a86c6181SAlex Tomas 	BUG_ON(path == NULL);
1401a86c6181SAlex Tomas 	depth = path->p_depth;
1402a86c6181SAlex Tomas 
1403a86c6181SAlex Tomas 	if (depth == 0 && path->p_ext == NULL)
1404a86c6181SAlex Tomas 		return EXT_MAX_BLOCK;
1405a86c6181SAlex Tomas 
1406a86c6181SAlex Tomas 	while (depth >= 0) {
1407a86c6181SAlex Tomas 		if (depth == path->p_depth) {
1408a86c6181SAlex Tomas 			/* leaf */
1409a86c6181SAlex Tomas 			if (path[depth].p_ext !=
1410a86c6181SAlex Tomas 					EXT_LAST_EXTENT(path[depth].p_hdr))
1411a86c6181SAlex Tomas 			  return le32_to_cpu(path[depth].p_ext[1].ee_block);
1412a86c6181SAlex Tomas 		} else {
1413a86c6181SAlex Tomas 			/* index */
1414a86c6181SAlex Tomas 			if (path[depth].p_idx !=
1415a86c6181SAlex Tomas 					EXT_LAST_INDEX(path[depth].p_hdr))
1416a86c6181SAlex Tomas 			  return le32_to_cpu(path[depth].p_idx[1].ei_block);
1417a86c6181SAlex Tomas 		}
1418a86c6181SAlex Tomas 		depth--;
1419a86c6181SAlex Tomas 	}
1420a86c6181SAlex Tomas 
1421a86c6181SAlex Tomas 	return EXT_MAX_BLOCK;
1422a86c6181SAlex Tomas }
1423a86c6181SAlex Tomas 
1424a86c6181SAlex Tomas /*
1425d0d856e8SRandy Dunlap  * ext4_ext_next_leaf_block:
1426a86c6181SAlex Tomas  * returns first allocated block from next leaf or EXT_MAX_BLOCK
1427a86c6181SAlex Tomas  */
1428725d26d3SAneesh Kumar K.V static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1429a86c6181SAlex Tomas 					struct ext4_ext_path *path)
1430a86c6181SAlex Tomas {
1431a86c6181SAlex Tomas 	int depth;
1432a86c6181SAlex Tomas 
1433a86c6181SAlex Tomas 	BUG_ON(path == NULL);
1434a86c6181SAlex Tomas 	depth = path->p_depth;
1435a86c6181SAlex Tomas 
1436a86c6181SAlex Tomas 	/* zero-tree has no leaf blocks at all */
1437a86c6181SAlex Tomas 	if (depth == 0)
1438a86c6181SAlex Tomas 		return EXT_MAX_BLOCK;
1439a86c6181SAlex Tomas 
1440a86c6181SAlex Tomas 	/* go to index block */
1441a86c6181SAlex Tomas 	depth--;
1442a86c6181SAlex Tomas 
1443a86c6181SAlex Tomas 	while (depth >= 0) {
1444a86c6181SAlex Tomas 		if (path[depth].p_idx !=
1445a86c6181SAlex Tomas 				EXT_LAST_INDEX(path[depth].p_hdr))
1446725d26d3SAneesh Kumar K.V 			return (ext4_lblk_t)
1447725d26d3SAneesh Kumar K.V 				le32_to_cpu(path[depth].p_idx[1].ei_block);
1448a86c6181SAlex Tomas 		depth--;
1449a86c6181SAlex Tomas 	}
1450a86c6181SAlex Tomas 
1451a86c6181SAlex Tomas 	return EXT_MAX_BLOCK;
1452a86c6181SAlex Tomas }
1453a86c6181SAlex Tomas 
1454a86c6181SAlex Tomas /*
1455d0d856e8SRandy Dunlap  * ext4_ext_correct_indexes:
1456d0d856e8SRandy Dunlap  * if leaf gets modified and modified extent is first in the leaf,
1457d0d856e8SRandy Dunlap  * then we have to correct all indexes above.
1458a86c6181SAlex Tomas  * TODO: do we need to correct tree in all cases?
1459a86c6181SAlex Tomas  */
14601d03ec98SAneesh Kumar K.V static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1461a86c6181SAlex Tomas 				struct ext4_ext_path *path)
1462a86c6181SAlex Tomas {
1463a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
1464a86c6181SAlex Tomas 	int depth = ext_depth(inode);
1465a86c6181SAlex Tomas 	struct ext4_extent *ex;
1466a86c6181SAlex Tomas 	__le32 border;
1467a86c6181SAlex Tomas 	int k, err = 0;
1468a86c6181SAlex Tomas 
1469a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
1470a86c6181SAlex Tomas 	ex = path[depth].p_ext;
1471273df556SFrank Mayhar 
1472273df556SFrank Mayhar 	if (unlikely(ex == NULL || eh == NULL)) {
1473273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
1474273df556SFrank Mayhar 				 "ex %p == NULL or eh %p == NULL", ex, eh);
1475273df556SFrank Mayhar 		return -EIO;
1476273df556SFrank Mayhar 	}
1477a86c6181SAlex Tomas 
1478a86c6181SAlex Tomas 	if (depth == 0) {
1479a86c6181SAlex Tomas 		/* there is no tree at all */
1480a86c6181SAlex Tomas 		return 0;
1481a86c6181SAlex Tomas 	}
1482a86c6181SAlex Tomas 
1483a86c6181SAlex Tomas 	if (ex != EXT_FIRST_EXTENT(eh)) {
1484a86c6181SAlex Tomas 		/* we correct tree if first leaf got modified only */
1485a86c6181SAlex Tomas 		return 0;
1486a86c6181SAlex Tomas 	}
1487a86c6181SAlex Tomas 
1488a86c6181SAlex Tomas 	/*
1489d0d856e8SRandy Dunlap 	 * TODO: we need correction if border is smaller than current one
1490a86c6181SAlex Tomas 	 */
1491a86c6181SAlex Tomas 	k = depth - 1;
1492a86c6181SAlex Tomas 	border = path[depth].p_ext->ee_block;
14937e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, path + k);
14947e028976SAvantika Mathur 	if (err)
1495a86c6181SAlex Tomas 		return err;
1496a86c6181SAlex Tomas 	path[k].p_idx->ei_block = border;
14977e028976SAvantika Mathur 	err = ext4_ext_dirty(handle, inode, path + k);
14987e028976SAvantika Mathur 	if (err)
1499a86c6181SAlex Tomas 		return err;
1500a86c6181SAlex Tomas 
1501a86c6181SAlex Tomas 	while (k--) {
1502a86c6181SAlex Tomas 		/* change all left-side indexes */
1503a86c6181SAlex Tomas 		if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1504a86c6181SAlex Tomas 			break;
15057e028976SAvantika Mathur 		err = ext4_ext_get_access(handle, inode, path + k);
15067e028976SAvantika Mathur 		if (err)
1507a86c6181SAlex Tomas 			break;
1508a86c6181SAlex Tomas 		path[k].p_idx->ei_block = border;
15097e028976SAvantika Mathur 		err = ext4_ext_dirty(handle, inode, path + k);
15107e028976SAvantika Mathur 		if (err)
1511a86c6181SAlex Tomas 			break;
1512a86c6181SAlex Tomas 	}
1513a86c6181SAlex Tomas 
1514a86c6181SAlex Tomas 	return err;
1515a86c6181SAlex Tomas }
1516a86c6181SAlex Tomas 
1517748de673SAkira Fujita int
1518a86c6181SAlex Tomas ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1519a86c6181SAlex Tomas 				struct ext4_extent *ex2)
1520a86c6181SAlex Tomas {
1521749269faSAmit Arora 	unsigned short ext1_ee_len, ext2_ee_len, max_len;
1522a2df2a63SAmit Arora 
1523a2df2a63SAmit Arora 	/*
1524a2df2a63SAmit Arora 	 * Make sure that either both extents are uninitialized, or
1525a2df2a63SAmit Arora 	 * both are _not_.
1526a2df2a63SAmit Arora 	 */
1527a2df2a63SAmit Arora 	if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1528a2df2a63SAmit Arora 		return 0;
1529a2df2a63SAmit Arora 
1530749269faSAmit Arora 	if (ext4_ext_is_uninitialized(ex1))
1531749269faSAmit Arora 		max_len = EXT_UNINIT_MAX_LEN;
1532749269faSAmit Arora 	else
1533749269faSAmit Arora 		max_len = EXT_INIT_MAX_LEN;
1534749269faSAmit Arora 
1535a2df2a63SAmit Arora 	ext1_ee_len = ext4_ext_get_actual_len(ex1);
1536a2df2a63SAmit Arora 	ext2_ee_len = ext4_ext_get_actual_len(ex2);
1537a2df2a63SAmit Arora 
1538a2df2a63SAmit Arora 	if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
153963f57933SAndrew Morton 			le32_to_cpu(ex2->ee_block))
1540a86c6181SAlex Tomas 		return 0;
1541a86c6181SAlex Tomas 
1542471d4011SSuparna Bhattacharya 	/*
1543471d4011SSuparna Bhattacharya 	 * To allow future support for preallocated extents to be added
1544471d4011SSuparna Bhattacharya 	 * as an RO_COMPAT feature, refuse to merge to extents if
1545d0d856e8SRandy Dunlap 	 * this can result in the top bit of ee_len being set.
1546471d4011SSuparna Bhattacharya 	 */
1547749269faSAmit Arora 	if (ext1_ee_len + ext2_ee_len > max_len)
1548471d4011SSuparna Bhattacharya 		return 0;
1549bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
1550b939e376SAneesh Kumar K.V 	if (ext1_ee_len >= 4)
1551a86c6181SAlex Tomas 		return 0;
1552a86c6181SAlex Tomas #endif
1553a86c6181SAlex Tomas 
1554bf89d16fSTheodore Ts'o 	if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1555a86c6181SAlex Tomas 		return 1;
1556a86c6181SAlex Tomas 	return 0;
1557a86c6181SAlex Tomas }
1558a86c6181SAlex Tomas 
1559a86c6181SAlex Tomas /*
156056055d3aSAmit Arora  * This function tries to merge the "ex" extent to the next extent in the tree.
156156055d3aSAmit Arora  * It always tries to merge towards right. If you want to merge towards
156256055d3aSAmit Arora  * left, pass "ex - 1" as argument instead of "ex".
156356055d3aSAmit Arora  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
156456055d3aSAmit Arora  * 1 if they got merged.
156556055d3aSAmit Arora  */
15661f109d5aSTheodore Ts'o static int ext4_ext_try_to_merge(struct inode *inode,
156756055d3aSAmit Arora 				 struct ext4_ext_path *path,
156856055d3aSAmit Arora 				 struct ext4_extent *ex)
156956055d3aSAmit Arora {
157056055d3aSAmit Arora 	struct ext4_extent_header *eh;
157156055d3aSAmit Arora 	unsigned int depth, len;
157256055d3aSAmit Arora 	int merge_done = 0;
157356055d3aSAmit Arora 	int uninitialized = 0;
157456055d3aSAmit Arora 
157556055d3aSAmit Arora 	depth = ext_depth(inode);
157656055d3aSAmit Arora 	BUG_ON(path[depth].p_hdr == NULL);
157756055d3aSAmit Arora 	eh = path[depth].p_hdr;
157856055d3aSAmit Arora 
157956055d3aSAmit Arora 	while (ex < EXT_LAST_EXTENT(eh)) {
158056055d3aSAmit Arora 		if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
158156055d3aSAmit Arora 			break;
158256055d3aSAmit Arora 		/* merge with next extent! */
158356055d3aSAmit Arora 		if (ext4_ext_is_uninitialized(ex))
158456055d3aSAmit Arora 			uninitialized = 1;
158556055d3aSAmit Arora 		ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
158656055d3aSAmit Arora 				+ ext4_ext_get_actual_len(ex + 1));
158756055d3aSAmit Arora 		if (uninitialized)
158856055d3aSAmit Arora 			ext4_ext_mark_uninitialized(ex);
158956055d3aSAmit Arora 
159056055d3aSAmit Arora 		if (ex + 1 < EXT_LAST_EXTENT(eh)) {
159156055d3aSAmit Arora 			len = (EXT_LAST_EXTENT(eh) - ex - 1)
159256055d3aSAmit Arora 				* sizeof(struct ext4_extent);
159356055d3aSAmit Arora 			memmove(ex + 1, ex + 2, len);
159456055d3aSAmit Arora 		}
1595e8546d06SMarcin Slusarz 		le16_add_cpu(&eh->eh_entries, -1);
159656055d3aSAmit Arora 		merge_done = 1;
159756055d3aSAmit Arora 		WARN_ON(eh->eh_entries == 0);
159856055d3aSAmit Arora 		if (!eh->eh_entries)
159924676da4STheodore Ts'o 			EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
160056055d3aSAmit Arora 	}
160156055d3aSAmit Arora 
160256055d3aSAmit Arora 	return merge_done;
160356055d3aSAmit Arora }
160456055d3aSAmit Arora 
160556055d3aSAmit Arora /*
160625d14f98SAmit Arora  * check if a portion of the "newext" extent overlaps with an
160725d14f98SAmit Arora  * existing extent.
160825d14f98SAmit Arora  *
160925d14f98SAmit Arora  * If there is an overlap discovered, it updates the length of the newext
161025d14f98SAmit Arora  * such that there will be no overlap, and then returns 1.
161125d14f98SAmit Arora  * If there is no overlap found, it returns 0.
161225d14f98SAmit Arora  */
16131f109d5aSTheodore Ts'o static unsigned int ext4_ext_check_overlap(struct inode *inode,
161425d14f98SAmit Arora 					   struct ext4_extent *newext,
161525d14f98SAmit Arora 					   struct ext4_ext_path *path)
161625d14f98SAmit Arora {
1617725d26d3SAneesh Kumar K.V 	ext4_lblk_t b1, b2;
161825d14f98SAmit Arora 	unsigned int depth, len1;
161925d14f98SAmit Arora 	unsigned int ret = 0;
162025d14f98SAmit Arora 
162125d14f98SAmit Arora 	b1 = le32_to_cpu(newext->ee_block);
1622a2df2a63SAmit Arora 	len1 = ext4_ext_get_actual_len(newext);
162325d14f98SAmit Arora 	depth = ext_depth(inode);
162425d14f98SAmit Arora 	if (!path[depth].p_ext)
162525d14f98SAmit Arora 		goto out;
162625d14f98SAmit Arora 	b2 = le32_to_cpu(path[depth].p_ext->ee_block);
162725d14f98SAmit Arora 
162825d14f98SAmit Arora 	/*
162925d14f98SAmit Arora 	 * get the next allocated block if the extent in the path
163025d14f98SAmit Arora 	 * is before the requested block(s)
163125d14f98SAmit Arora 	 */
163225d14f98SAmit Arora 	if (b2 < b1) {
163325d14f98SAmit Arora 		b2 = ext4_ext_next_allocated_block(path);
163425d14f98SAmit Arora 		if (b2 == EXT_MAX_BLOCK)
163525d14f98SAmit Arora 			goto out;
163625d14f98SAmit Arora 	}
163725d14f98SAmit Arora 
1638725d26d3SAneesh Kumar K.V 	/* check for wrap through zero on extent logical start block*/
163925d14f98SAmit Arora 	if (b1 + len1 < b1) {
164025d14f98SAmit Arora 		len1 = EXT_MAX_BLOCK - b1;
164125d14f98SAmit Arora 		newext->ee_len = cpu_to_le16(len1);
164225d14f98SAmit Arora 		ret = 1;
164325d14f98SAmit Arora 	}
164425d14f98SAmit Arora 
164525d14f98SAmit Arora 	/* check for overlap */
164625d14f98SAmit Arora 	if (b1 + len1 > b2) {
164725d14f98SAmit Arora 		newext->ee_len = cpu_to_le16(b2 - b1);
164825d14f98SAmit Arora 		ret = 1;
164925d14f98SAmit Arora 	}
165025d14f98SAmit Arora out:
165125d14f98SAmit Arora 	return ret;
165225d14f98SAmit Arora }
165325d14f98SAmit Arora 
165425d14f98SAmit Arora /*
1655d0d856e8SRandy Dunlap  * ext4_ext_insert_extent:
1656d0d856e8SRandy Dunlap  * tries to merge requsted extent into the existing extent or
1657d0d856e8SRandy Dunlap  * inserts requested extent as new one into the tree,
1658d0d856e8SRandy Dunlap  * creating new leaf in the no-space case.
1659a86c6181SAlex Tomas  */
1660a86c6181SAlex Tomas int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1661a86c6181SAlex Tomas 				struct ext4_ext_path *path,
16620031462bSMingming Cao 				struct ext4_extent *newext, int flag)
1663a86c6181SAlex Tomas {
1664a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
1665a86c6181SAlex Tomas 	struct ext4_extent *ex, *fex;
1666a86c6181SAlex Tomas 	struct ext4_extent *nearex; /* nearest extent */
1667a86c6181SAlex Tomas 	struct ext4_ext_path *npath = NULL;
1668725d26d3SAneesh Kumar K.V 	int depth, len, err;
1669725d26d3SAneesh Kumar K.V 	ext4_lblk_t next;
1670a2df2a63SAmit Arora 	unsigned uninitialized = 0;
1671a86c6181SAlex Tomas 
1672273df556SFrank Mayhar 	if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1673273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1674273df556SFrank Mayhar 		return -EIO;
1675273df556SFrank Mayhar 	}
1676a86c6181SAlex Tomas 	depth = ext_depth(inode);
1677a86c6181SAlex Tomas 	ex = path[depth].p_ext;
1678273df556SFrank Mayhar 	if (unlikely(path[depth].p_hdr == NULL)) {
1679273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1680273df556SFrank Mayhar 		return -EIO;
1681273df556SFrank Mayhar 	}
1682a86c6181SAlex Tomas 
1683a86c6181SAlex Tomas 	/* try to insert block into found extent and return */
1684744692dcSJiaying Zhang 	if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
16850031462bSMingming Cao 		&& ext4_can_extents_be_merged(inode, ex, newext)) {
1686553f9008SMingming 		ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
1687553f9008SMingming 			  ext4_ext_is_uninitialized(newext),
1688a2df2a63SAmit Arora 			  ext4_ext_get_actual_len(newext),
1689a86c6181SAlex Tomas 			  le32_to_cpu(ex->ee_block),
1690553f9008SMingming 			  ext4_ext_is_uninitialized(ex),
1691bf89d16fSTheodore Ts'o 			  ext4_ext_get_actual_len(ex),
1692bf89d16fSTheodore Ts'o 			  ext4_ext_pblock(ex));
16937e028976SAvantika Mathur 		err = ext4_ext_get_access(handle, inode, path + depth);
16947e028976SAvantika Mathur 		if (err)
1695a86c6181SAlex Tomas 			return err;
1696a2df2a63SAmit Arora 
1697a2df2a63SAmit Arora 		/*
1698a2df2a63SAmit Arora 		 * ext4_can_extents_be_merged should have checked that either
1699a2df2a63SAmit Arora 		 * both extents are uninitialized, or both aren't. Thus we
1700a2df2a63SAmit Arora 		 * need to check only one of them here.
1701a2df2a63SAmit Arora 		 */
1702a2df2a63SAmit Arora 		if (ext4_ext_is_uninitialized(ex))
1703a2df2a63SAmit Arora 			uninitialized = 1;
1704a2df2a63SAmit Arora 		ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1705a2df2a63SAmit Arora 					+ ext4_ext_get_actual_len(newext));
1706a2df2a63SAmit Arora 		if (uninitialized)
1707a2df2a63SAmit Arora 			ext4_ext_mark_uninitialized(ex);
1708a86c6181SAlex Tomas 		eh = path[depth].p_hdr;
1709a86c6181SAlex Tomas 		nearex = ex;
1710a86c6181SAlex Tomas 		goto merge;
1711a86c6181SAlex Tomas 	}
1712a86c6181SAlex Tomas 
1713a86c6181SAlex Tomas repeat:
1714a86c6181SAlex Tomas 	depth = ext_depth(inode);
1715a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
1716a86c6181SAlex Tomas 	if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1717a86c6181SAlex Tomas 		goto has_space;
1718a86c6181SAlex Tomas 
1719a86c6181SAlex Tomas 	/* probably next leaf has space for us? */
1720a86c6181SAlex Tomas 	fex = EXT_LAST_EXTENT(eh);
1721a86c6181SAlex Tomas 	next = ext4_ext_next_leaf_block(inode, path);
1722a86c6181SAlex Tomas 	if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1723a86c6181SAlex Tomas 	    && next != EXT_MAX_BLOCK) {
1724a86c6181SAlex Tomas 		ext_debug("next leaf block - %d\n", next);
1725a86c6181SAlex Tomas 		BUG_ON(npath != NULL);
1726a86c6181SAlex Tomas 		npath = ext4_ext_find_extent(inode, next, NULL);
1727a86c6181SAlex Tomas 		if (IS_ERR(npath))
1728a86c6181SAlex Tomas 			return PTR_ERR(npath);
1729a86c6181SAlex Tomas 		BUG_ON(npath->p_depth != path->p_depth);
1730a86c6181SAlex Tomas 		eh = npath[depth].p_hdr;
1731a86c6181SAlex Tomas 		if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1732a86c6181SAlex Tomas 			ext_debug("next leaf isnt full(%d)\n",
1733a86c6181SAlex Tomas 				  le16_to_cpu(eh->eh_entries));
1734a86c6181SAlex Tomas 			path = npath;
1735a86c6181SAlex Tomas 			goto repeat;
1736a86c6181SAlex Tomas 		}
1737a86c6181SAlex Tomas 		ext_debug("next leaf has no free space(%d,%d)\n",
1738a86c6181SAlex Tomas 			  le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1739a86c6181SAlex Tomas 	}
1740a86c6181SAlex Tomas 
1741a86c6181SAlex Tomas 	/*
1742d0d856e8SRandy Dunlap 	 * There is no free space in the found leaf.
1743d0d856e8SRandy Dunlap 	 * We're gonna add a new leaf in the tree.
1744a86c6181SAlex Tomas 	 */
1745a86c6181SAlex Tomas 	err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1746a86c6181SAlex Tomas 	if (err)
1747a86c6181SAlex Tomas 		goto cleanup;
1748a86c6181SAlex Tomas 	depth = ext_depth(inode);
1749a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
1750a86c6181SAlex Tomas 
1751a86c6181SAlex Tomas has_space:
1752a86c6181SAlex Tomas 	nearex = path[depth].p_ext;
1753a86c6181SAlex Tomas 
17547e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, path + depth);
17557e028976SAvantika Mathur 	if (err)
1756a86c6181SAlex Tomas 		goto cleanup;
1757a86c6181SAlex Tomas 
1758a86c6181SAlex Tomas 	if (!nearex) {
1759a86c6181SAlex Tomas 		/* there is no extent in this leaf, create first one */
1760553f9008SMingming 		ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
1761a86c6181SAlex Tomas 				le32_to_cpu(newext->ee_block),
1762bf89d16fSTheodore Ts'o 				ext4_ext_pblock(newext),
1763553f9008SMingming 				ext4_ext_is_uninitialized(newext),
1764a2df2a63SAmit Arora 				ext4_ext_get_actual_len(newext));
1765a86c6181SAlex Tomas 		path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1766a86c6181SAlex Tomas 	} else if (le32_to_cpu(newext->ee_block)
1767a86c6181SAlex Tomas 			   > le32_to_cpu(nearex->ee_block)) {
1768a86c6181SAlex Tomas /*		BUG_ON(newext->ee_block == nearex->ee_block); */
1769a86c6181SAlex Tomas 		if (nearex != EXT_LAST_EXTENT(eh)) {
1770a86c6181SAlex Tomas 			len = EXT_MAX_EXTENT(eh) - nearex;
1771a86c6181SAlex Tomas 			len = (len - 1) * sizeof(struct ext4_extent);
1772a86c6181SAlex Tomas 			len = len < 0 ? 0 : len;
1773553f9008SMingming 			ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
1774a86c6181SAlex Tomas 					"move %d from 0x%p to 0x%p\n",
1775a86c6181SAlex Tomas 					le32_to_cpu(newext->ee_block),
1776bf89d16fSTheodore Ts'o 					ext4_ext_pblock(newext),
1777553f9008SMingming 					ext4_ext_is_uninitialized(newext),
1778a2df2a63SAmit Arora 					ext4_ext_get_actual_len(newext),
1779a86c6181SAlex Tomas 					nearex, len, nearex + 1, nearex + 2);
1780a86c6181SAlex Tomas 			memmove(nearex + 2, nearex + 1, len);
1781a86c6181SAlex Tomas 		}
1782a86c6181SAlex Tomas 		path[depth].p_ext = nearex + 1;
1783a86c6181SAlex Tomas 	} else {
1784a86c6181SAlex Tomas 		BUG_ON(newext->ee_block == nearex->ee_block);
1785a86c6181SAlex Tomas 		len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1786a86c6181SAlex Tomas 		len = len < 0 ? 0 : len;
1787553f9008SMingming 		ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
1788a86c6181SAlex Tomas 				"move %d from 0x%p to 0x%p\n",
1789a86c6181SAlex Tomas 				le32_to_cpu(newext->ee_block),
1790bf89d16fSTheodore Ts'o 				ext4_ext_pblock(newext),
1791553f9008SMingming 				ext4_ext_is_uninitialized(newext),
1792a2df2a63SAmit Arora 				ext4_ext_get_actual_len(newext),
1793a86c6181SAlex Tomas 				nearex, len, nearex + 1, nearex + 2);
1794a86c6181SAlex Tomas 		memmove(nearex + 1, nearex, len);
1795a86c6181SAlex Tomas 		path[depth].p_ext = nearex;
1796a86c6181SAlex Tomas 	}
1797a86c6181SAlex Tomas 
1798e8546d06SMarcin Slusarz 	le16_add_cpu(&eh->eh_entries, 1);
1799a86c6181SAlex Tomas 	nearex = path[depth].p_ext;
1800a86c6181SAlex Tomas 	nearex->ee_block = newext->ee_block;
1801bf89d16fSTheodore Ts'o 	ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
1802a86c6181SAlex Tomas 	nearex->ee_len = newext->ee_len;
1803a86c6181SAlex Tomas 
1804a86c6181SAlex Tomas merge:
1805a86c6181SAlex Tomas 	/* try to merge extents to the right */
1806744692dcSJiaying Zhang 	if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
180756055d3aSAmit Arora 		ext4_ext_try_to_merge(inode, path, nearex);
1808a86c6181SAlex Tomas 
1809a86c6181SAlex Tomas 	/* try to merge extents to the left */
1810a86c6181SAlex Tomas 
1811a86c6181SAlex Tomas 	/* time to correct all indexes above */
1812a86c6181SAlex Tomas 	err = ext4_ext_correct_indexes(handle, inode, path);
1813a86c6181SAlex Tomas 	if (err)
1814a86c6181SAlex Tomas 		goto cleanup;
1815a86c6181SAlex Tomas 
1816a86c6181SAlex Tomas 	err = ext4_ext_dirty(handle, inode, path + depth);
1817a86c6181SAlex Tomas 
1818a86c6181SAlex Tomas cleanup:
1819a86c6181SAlex Tomas 	if (npath) {
1820a86c6181SAlex Tomas 		ext4_ext_drop_refs(npath);
1821a86c6181SAlex Tomas 		kfree(npath);
1822a86c6181SAlex Tomas 	}
1823a86c6181SAlex Tomas 	ext4_ext_invalidate_cache(inode);
1824a86c6181SAlex Tomas 	return err;
1825a86c6181SAlex Tomas }
1826a86c6181SAlex Tomas 
18271f109d5aSTheodore Ts'o static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
18286873fa0dSEric Sandeen 			       ext4_lblk_t num, ext_prepare_callback func,
18296873fa0dSEric Sandeen 			       void *cbdata)
18306873fa0dSEric Sandeen {
18316873fa0dSEric Sandeen 	struct ext4_ext_path *path = NULL;
18326873fa0dSEric Sandeen 	struct ext4_ext_cache cbex;
18336873fa0dSEric Sandeen 	struct ext4_extent *ex;
18346873fa0dSEric Sandeen 	ext4_lblk_t next, start = 0, end = 0;
18356873fa0dSEric Sandeen 	ext4_lblk_t last = block + num;
18366873fa0dSEric Sandeen 	int depth, exists, err = 0;
18376873fa0dSEric Sandeen 
18386873fa0dSEric Sandeen 	BUG_ON(func == NULL);
18396873fa0dSEric Sandeen 	BUG_ON(inode == NULL);
18406873fa0dSEric Sandeen 
18416873fa0dSEric Sandeen 	while (block < last && block != EXT_MAX_BLOCK) {
18426873fa0dSEric Sandeen 		num = last - block;
18436873fa0dSEric Sandeen 		/* find extent for this block */
1844fab3a549STheodore Ts'o 		down_read(&EXT4_I(inode)->i_data_sem);
18456873fa0dSEric Sandeen 		path = ext4_ext_find_extent(inode, block, path);
1846fab3a549STheodore Ts'o 		up_read(&EXT4_I(inode)->i_data_sem);
18476873fa0dSEric Sandeen 		if (IS_ERR(path)) {
18486873fa0dSEric Sandeen 			err = PTR_ERR(path);
18496873fa0dSEric Sandeen 			path = NULL;
18506873fa0dSEric Sandeen 			break;
18516873fa0dSEric Sandeen 		}
18526873fa0dSEric Sandeen 
18536873fa0dSEric Sandeen 		depth = ext_depth(inode);
1854273df556SFrank Mayhar 		if (unlikely(path[depth].p_hdr == NULL)) {
1855273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1856273df556SFrank Mayhar 			err = -EIO;
1857273df556SFrank Mayhar 			break;
1858273df556SFrank Mayhar 		}
18596873fa0dSEric Sandeen 		ex = path[depth].p_ext;
18606873fa0dSEric Sandeen 		next = ext4_ext_next_allocated_block(path);
18616873fa0dSEric Sandeen 
18626873fa0dSEric Sandeen 		exists = 0;
18636873fa0dSEric Sandeen 		if (!ex) {
18646873fa0dSEric Sandeen 			/* there is no extent yet, so try to allocate
18656873fa0dSEric Sandeen 			 * all requested space */
18666873fa0dSEric Sandeen 			start = block;
18676873fa0dSEric Sandeen 			end = block + num;
18686873fa0dSEric Sandeen 		} else if (le32_to_cpu(ex->ee_block) > block) {
18696873fa0dSEric Sandeen 			/* need to allocate space before found extent */
18706873fa0dSEric Sandeen 			start = block;
18716873fa0dSEric Sandeen 			end = le32_to_cpu(ex->ee_block);
18726873fa0dSEric Sandeen 			if (block + num < end)
18736873fa0dSEric Sandeen 				end = block + num;
18746873fa0dSEric Sandeen 		} else if (block >= le32_to_cpu(ex->ee_block)
18756873fa0dSEric Sandeen 					+ ext4_ext_get_actual_len(ex)) {
18766873fa0dSEric Sandeen 			/* need to allocate space after found extent */
18776873fa0dSEric Sandeen 			start = block;
18786873fa0dSEric Sandeen 			end = block + num;
18796873fa0dSEric Sandeen 			if (end >= next)
18806873fa0dSEric Sandeen 				end = next;
18816873fa0dSEric Sandeen 		} else if (block >= le32_to_cpu(ex->ee_block)) {
18826873fa0dSEric Sandeen 			/*
18836873fa0dSEric Sandeen 			 * some part of requested space is covered
18846873fa0dSEric Sandeen 			 * by found extent
18856873fa0dSEric Sandeen 			 */
18866873fa0dSEric Sandeen 			start = block;
18876873fa0dSEric Sandeen 			end = le32_to_cpu(ex->ee_block)
18886873fa0dSEric Sandeen 				+ ext4_ext_get_actual_len(ex);
18896873fa0dSEric Sandeen 			if (block + num < end)
18906873fa0dSEric Sandeen 				end = block + num;
18916873fa0dSEric Sandeen 			exists = 1;
18926873fa0dSEric Sandeen 		} else {
18936873fa0dSEric Sandeen 			BUG();
18946873fa0dSEric Sandeen 		}
18956873fa0dSEric Sandeen 		BUG_ON(end <= start);
18966873fa0dSEric Sandeen 
18976873fa0dSEric Sandeen 		if (!exists) {
18986873fa0dSEric Sandeen 			cbex.ec_block = start;
18996873fa0dSEric Sandeen 			cbex.ec_len = end - start;
19006873fa0dSEric Sandeen 			cbex.ec_start = 0;
19016873fa0dSEric Sandeen 		} else {
19026873fa0dSEric Sandeen 			cbex.ec_block = le32_to_cpu(ex->ee_block);
19036873fa0dSEric Sandeen 			cbex.ec_len = ext4_ext_get_actual_len(ex);
1904bf89d16fSTheodore Ts'o 			cbex.ec_start = ext4_ext_pblock(ex);
19056873fa0dSEric Sandeen 		}
19066873fa0dSEric Sandeen 
1907273df556SFrank Mayhar 		if (unlikely(cbex.ec_len == 0)) {
1908273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
1909273df556SFrank Mayhar 			err = -EIO;
1910273df556SFrank Mayhar 			break;
1911273df556SFrank Mayhar 		}
19126873fa0dSEric Sandeen 		err = func(inode, path, &cbex, ex, cbdata);
19136873fa0dSEric Sandeen 		ext4_ext_drop_refs(path);
19146873fa0dSEric Sandeen 
19156873fa0dSEric Sandeen 		if (err < 0)
19166873fa0dSEric Sandeen 			break;
19176873fa0dSEric Sandeen 
19186873fa0dSEric Sandeen 		if (err == EXT_REPEAT)
19196873fa0dSEric Sandeen 			continue;
19206873fa0dSEric Sandeen 		else if (err == EXT_BREAK) {
19216873fa0dSEric Sandeen 			err = 0;
19226873fa0dSEric Sandeen 			break;
19236873fa0dSEric Sandeen 		}
19246873fa0dSEric Sandeen 
19256873fa0dSEric Sandeen 		if (ext_depth(inode) != depth) {
19266873fa0dSEric Sandeen 			/* depth was changed. we have to realloc path */
19276873fa0dSEric Sandeen 			kfree(path);
19286873fa0dSEric Sandeen 			path = NULL;
19296873fa0dSEric Sandeen 		}
19306873fa0dSEric Sandeen 
19316873fa0dSEric Sandeen 		block = cbex.ec_block + cbex.ec_len;
19326873fa0dSEric Sandeen 	}
19336873fa0dSEric Sandeen 
19346873fa0dSEric Sandeen 	if (path) {
19356873fa0dSEric Sandeen 		ext4_ext_drop_refs(path);
19366873fa0dSEric Sandeen 		kfree(path);
19376873fa0dSEric Sandeen 	}
19386873fa0dSEric Sandeen 
19396873fa0dSEric Sandeen 	return err;
19406873fa0dSEric Sandeen }
19416873fa0dSEric Sandeen 
194209b88252SAvantika Mathur static void
1943725d26d3SAneesh Kumar K.V ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1944b05e6ae5STheodore Ts'o 			__u32 len, ext4_fsblk_t start)
1945a86c6181SAlex Tomas {
1946a86c6181SAlex Tomas 	struct ext4_ext_cache *cex;
1947a86c6181SAlex Tomas 	BUG_ON(len == 0);
19482ec0ae3aSTheodore Ts'o 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1949a86c6181SAlex Tomas 	cex = &EXT4_I(inode)->i_cached_extent;
1950a86c6181SAlex Tomas 	cex->ec_block = block;
1951a86c6181SAlex Tomas 	cex->ec_len = len;
1952a86c6181SAlex Tomas 	cex->ec_start = start;
19532ec0ae3aSTheodore Ts'o 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1954a86c6181SAlex Tomas }
1955a86c6181SAlex Tomas 
1956a86c6181SAlex Tomas /*
1957d0d856e8SRandy Dunlap  * ext4_ext_put_gap_in_cache:
1958d0d856e8SRandy Dunlap  * calculate boundaries of the gap that the requested block fits into
1959a86c6181SAlex Tomas  * and cache this gap
1960a86c6181SAlex Tomas  */
196109b88252SAvantika Mathur static void
1962a86c6181SAlex Tomas ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1963725d26d3SAneesh Kumar K.V 				ext4_lblk_t block)
1964a86c6181SAlex Tomas {
1965a86c6181SAlex Tomas 	int depth = ext_depth(inode);
1966725d26d3SAneesh Kumar K.V 	unsigned long len;
1967725d26d3SAneesh Kumar K.V 	ext4_lblk_t lblock;
1968a86c6181SAlex Tomas 	struct ext4_extent *ex;
1969a86c6181SAlex Tomas 
1970a86c6181SAlex Tomas 	ex = path[depth].p_ext;
1971a86c6181SAlex Tomas 	if (ex == NULL) {
1972a86c6181SAlex Tomas 		/* there is no extent yet, so gap is [0;-] */
1973a86c6181SAlex Tomas 		lblock = 0;
1974a86c6181SAlex Tomas 		len = EXT_MAX_BLOCK;
1975a86c6181SAlex Tomas 		ext_debug("cache gap(whole file):");
1976a86c6181SAlex Tomas 	} else if (block < le32_to_cpu(ex->ee_block)) {
1977a86c6181SAlex Tomas 		lblock = block;
1978a86c6181SAlex Tomas 		len = le32_to_cpu(ex->ee_block) - block;
1979bba90743SEric Sandeen 		ext_debug("cache gap(before): %u [%u:%u]",
1980bba90743SEric Sandeen 				block,
1981bba90743SEric Sandeen 				le32_to_cpu(ex->ee_block),
1982bba90743SEric Sandeen 				 ext4_ext_get_actual_len(ex));
1983a86c6181SAlex Tomas 	} else if (block >= le32_to_cpu(ex->ee_block)
1984a2df2a63SAmit Arora 			+ ext4_ext_get_actual_len(ex)) {
1985725d26d3SAneesh Kumar K.V 		ext4_lblk_t next;
1986a86c6181SAlex Tomas 		lblock = le32_to_cpu(ex->ee_block)
1987a2df2a63SAmit Arora 			+ ext4_ext_get_actual_len(ex);
1988725d26d3SAneesh Kumar K.V 
1989725d26d3SAneesh Kumar K.V 		next = ext4_ext_next_allocated_block(path);
1990bba90743SEric Sandeen 		ext_debug("cache gap(after): [%u:%u] %u",
1991bba90743SEric Sandeen 				le32_to_cpu(ex->ee_block),
1992bba90743SEric Sandeen 				ext4_ext_get_actual_len(ex),
1993bba90743SEric Sandeen 				block);
1994725d26d3SAneesh Kumar K.V 		BUG_ON(next == lblock);
1995725d26d3SAneesh Kumar K.V 		len = next - lblock;
1996a86c6181SAlex Tomas 	} else {
1997a86c6181SAlex Tomas 		lblock = len = 0;
1998a86c6181SAlex Tomas 		BUG();
1999a86c6181SAlex Tomas 	}
2000a86c6181SAlex Tomas 
2001bba90743SEric Sandeen 	ext_debug(" -> %u:%lu\n", lblock, len);
2002b05e6ae5STheodore Ts'o 	ext4_ext_put_in_cache(inode, lblock, len, 0);
2003a86c6181SAlex Tomas }
2004a86c6181SAlex Tomas 
2005b05e6ae5STheodore Ts'o /*
2006b05e6ae5STheodore Ts'o  * Return 0 if cache is invalid; 1 if the cache is valid
2007b05e6ae5STheodore Ts'o  */
200809b88252SAvantika Mathur static int
2009725d26d3SAneesh Kumar K.V ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
2010a86c6181SAlex Tomas 			struct ext4_extent *ex)
2011a86c6181SAlex Tomas {
2012a86c6181SAlex Tomas 	struct ext4_ext_cache *cex;
2013b05e6ae5STheodore Ts'o 	int ret = 0;
2014a86c6181SAlex Tomas 
20152ec0ae3aSTheodore Ts'o 	/*
20162ec0ae3aSTheodore Ts'o 	 * We borrow i_block_reservation_lock to protect i_cached_extent
20172ec0ae3aSTheodore Ts'o 	 */
20182ec0ae3aSTheodore Ts'o 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
2019a86c6181SAlex Tomas 	cex = &EXT4_I(inode)->i_cached_extent;
2020a86c6181SAlex Tomas 
2021a86c6181SAlex Tomas 	/* has cache valid data? */
2022b05e6ae5STheodore Ts'o 	if (cex->ec_len == 0)
20232ec0ae3aSTheodore Ts'o 		goto errout;
2024a86c6181SAlex Tomas 
2025731eb1a0SAkinobu Mita 	if (in_range(block, cex->ec_block, cex->ec_len)) {
2026a86c6181SAlex Tomas 		ex->ee_block = cpu_to_le32(cex->ec_block);
2027f65e6fbaSAlex Tomas 		ext4_ext_store_pblock(ex, cex->ec_start);
2028a86c6181SAlex Tomas 		ex->ee_len = cpu_to_le16(cex->ec_len);
2029bba90743SEric Sandeen 		ext_debug("%u cached by %u:%u:%llu\n",
2030bba90743SEric Sandeen 				block,
2031bba90743SEric Sandeen 				cex->ec_block, cex->ec_len, cex->ec_start);
2032b05e6ae5STheodore Ts'o 		ret = 1;
2033a86c6181SAlex Tomas 	}
20342ec0ae3aSTheodore Ts'o errout:
20352ec0ae3aSTheodore Ts'o 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
20362ec0ae3aSTheodore Ts'o 	return ret;
2037a86c6181SAlex Tomas }
2038a86c6181SAlex Tomas 
2039a86c6181SAlex Tomas /*
2040d0d856e8SRandy Dunlap  * ext4_ext_rm_idx:
2041d0d856e8SRandy Dunlap  * removes index from the index block.
2042d0d856e8SRandy Dunlap  * It's used in truncate case only, thus all requests are for
2043d0d856e8SRandy Dunlap  * last index in the block only.
2044a86c6181SAlex Tomas  */
20451d03ec98SAneesh Kumar K.V static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2046a86c6181SAlex Tomas 			struct ext4_ext_path *path)
2047a86c6181SAlex Tomas {
2048a86c6181SAlex Tomas 	int err;
2049f65e6fbaSAlex Tomas 	ext4_fsblk_t leaf;
2050a86c6181SAlex Tomas 
2051a86c6181SAlex Tomas 	/* free index block */
2052a86c6181SAlex Tomas 	path--;
2053bf89d16fSTheodore Ts'o 	leaf = ext4_idx_pblock(path->p_idx);
2054273df556SFrank Mayhar 	if (unlikely(path->p_hdr->eh_entries == 0)) {
2055273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2056273df556SFrank Mayhar 		return -EIO;
2057273df556SFrank Mayhar 	}
20587e028976SAvantika Mathur 	err = ext4_ext_get_access(handle, inode, path);
20597e028976SAvantika Mathur 	if (err)
2060a86c6181SAlex Tomas 		return err;
2061e8546d06SMarcin Slusarz 	le16_add_cpu(&path->p_hdr->eh_entries, -1);
20627e028976SAvantika Mathur 	err = ext4_ext_dirty(handle, inode, path);
20637e028976SAvantika Mathur 	if (err)
2064a86c6181SAlex Tomas 		return err;
20652ae02107SMingming Cao 	ext_debug("index is empty, remove it, free block %llu\n", leaf);
20667dc57615SPeter Huewe 	ext4_free_blocks(handle, inode, NULL, leaf, 1,
2067e6362609STheodore Ts'o 			 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2068a86c6181SAlex Tomas 	return err;
2069a86c6181SAlex Tomas }
2070a86c6181SAlex Tomas 
2071a86c6181SAlex Tomas /*
2072ee12b630SMingming Cao  * ext4_ext_calc_credits_for_single_extent:
2073ee12b630SMingming Cao  * This routine returns max. credits that needed to insert an extent
2074ee12b630SMingming Cao  * to the extent tree.
2075ee12b630SMingming Cao  * When pass the actual path, the caller should calculate credits
2076ee12b630SMingming Cao  * under i_data_sem.
2077a86c6181SAlex Tomas  */
2078525f4ed8SMingming Cao int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2079a86c6181SAlex Tomas 						struct ext4_ext_path *path)
2080a86c6181SAlex Tomas {
2081a86c6181SAlex Tomas 	if (path) {
2082ee12b630SMingming Cao 		int depth = ext_depth(inode);
2083f3bd1f3fSMingming Cao 		int ret = 0;
2084ee12b630SMingming Cao 
2085a86c6181SAlex Tomas 		/* probably there is space in leaf? */
2086a86c6181SAlex Tomas 		if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2087ee12b630SMingming Cao 				< le16_to_cpu(path[depth].p_hdr->eh_max)) {
2088ee12b630SMingming Cao 
2089ee12b630SMingming Cao 			/*
2090ee12b630SMingming Cao 			 *  There are some space in the leaf tree, no
2091ee12b630SMingming Cao 			 *  need to account for leaf block credit
2092ee12b630SMingming Cao 			 *
2093ee12b630SMingming Cao 			 *  bitmaps and block group descriptor blocks
2094ee12b630SMingming Cao 			 *  and other metadat blocks still need to be
2095ee12b630SMingming Cao 			 *  accounted.
2096ee12b630SMingming Cao 			 */
2097525f4ed8SMingming Cao 			/* 1 bitmap, 1 block group descriptor */
2098ee12b630SMingming Cao 			ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
20995887e98bSAneesh Kumar K.V 			return ret;
2100ee12b630SMingming Cao 		}
2101ee12b630SMingming Cao 	}
2102ee12b630SMingming Cao 
2103525f4ed8SMingming Cao 	return ext4_chunk_trans_blocks(inode, nrblocks);
2104a86c6181SAlex Tomas }
2105a86c6181SAlex Tomas 
2106a86c6181SAlex Tomas /*
2107ee12b630SMingming Cao  * How many index/leaf blocks need to change/allocate to modify nrblocks?
2108ee12b630SMingming Cao  *
2109ee12b630SMingming Cao  * if nrblocks are fit in a single extent (chunk flag is 1), then
2110ee12b630SMingming Cao  * in the worse case, each tree level index/leaf need to be changed
2111ee12b630SMingming Cao  * if the tree split due to insert a new extent, then the old tree
2112ee12b630SMingming Cao  * index/leaf need to be updated too
2113ee12b630SMingming Cao  *
2114ee12b630SMingming Cao  * If the nrblocks are discontiguous, they could cause
2115ee12b630SMingming Cao  * the whole tree split more than once, but this is really rare.
2116a86c6181SAlex Tomas  */
2117525f4ed8SMingming Cao int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2118ee12b630SMingming Cao {
2119ee12b630SMingming Cao 	int index;
2120ee12b630SMingming Cao 	int depth = ext_depth(inode);
2121a86c6181SAlex Tomas 
2122ee12b630SMingming Cao 	if (chunk)
2123ee12b630SMingming Cao 		index = depth * 2;
2124ee12b630SMingming Cao 	else
2125ee12b630SMingming Cao 		index = depth * 3;
2126a86c6181SAlex Tomas 
2127ee12b630SMingming Cao 	return index;
2128a86c6181SAlex Tomas }
2129a86c6181SAlex Tomas 
2130a86c6181SAlex Tomas static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2131a86c6181SAlex Tomas 				struct ext4_extent *ex,
2132725d26d3SAneesh Kumar K.V 				ext4_lblk_t from, ext4_lblk_t to)
2133a86c6181SAlex Tomas {
2134a2df2a63SAmit Arora 	unsigned short ee_len =  ext4_ext_get_actual_len(ex);
2135e6362609STheodore Ts'o 	int flags = EXT4_FREE_BLOCKS_FORGET;
2136a86c6181SAlex Tomas 
2137c9de560dSAlex Tomas 	if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2138e6362609STheodore Ts'o 		flags |= EXT4_FREE_BLOCKS_METADATA;
2139a86c6181SAlex Tomas #ifdef EXTENTS_STATS
2140a86c6181SAlex Tomas 	{
2141a86c6181SAlex Tomas 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2142a86c6181SAlex Tomas 		spin_lock(&sbi->s_ext_stats_lock);
2143a86c6181SAlex Tomas 		sbi->s_ext_blocks += ee_len;
2144a86c6181SAlex Tomas 		sbi->s_ext_extents++;
2145a86c6181SAlex Tomas 		if (ee_len < sbi->s_ext_min)
2146a86c6181SAlex Tomas 			sbi->s_ext_min = ee_len;
2147a86c6181SAlex Tomas 		if (ee_len > sbi->s_ext_max)
2148a86c6181SAlex Tomas 			sbi->s_ext_max = ee_len;
2149a86c6181SAlex Tomas 		if (ext_depth(inode) > sbi->s_depth_max)
2150a86c6181SAlex Tomas 			sbi->s_depth_max = ext_depth(inode);
2151a86c6181SAlex Tomas 		spin_unlock(&sbi->s_ext_stats_lock);
2152a86c6181SAlex Tomas 	}
2153a86c6181SAlex Tomas #endif
2154a86c6181SAlex Tomas 	if (from >= le32_to_cpu(ex->ee_block)
2155a2df2a63SAmit Arora 	    && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2156a86c6181SAlex Tomas 		/* tail removal */
2157725d26d3SAneesh Kumar K.V 		ext4_lblk_t num;
2158f65e6fbaSAlex Tomas 		ext4_fsblk_t start;
2159725d26d3SAneesh Kumar K.V 
2160a2df2a63SAmit Arora 		num = le32_to_cpu(ex->ee_block) + ee_len - from;
2161bf89d16fSTheodore Ts'o 		start = ext4_ext_pblock(ex) + ee_len - num;
2162725d26d3SAneesh Kumar K.V 		ext_debug("free last %u blocks starting %llu\n", num, start);
21637dc57615SPeter Huewe 		ext4_free_blocks(handle, inode, NULL, start, num, flags);
2164a86c6181SAlex Tomas 	} else if (from == le32_to_cpu(ex->ee_block)
2165a2df2a63SAmit Arora 		   && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2166725d26d3SAneesh Kumar K.V 		printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
2167a2df2a63SAmit Arora 			from, to, le32_to_cpu(ex->ee_block), ee_len);
2168a86c6181SAlex Tomas 	} else {
2169725d26d3SAneesh Kumar K.V 		printk(KERN_INFO "strange request: removal(2) "
2170725d26d3SAneesh Kumar K.V 				"%u-%u from %u:%u\n",
2171a2df2a63SAmit Arora 				from, to, le32_to_cpu(ex->ee_block), ee_len);
2172a86c6181SAlex Tomas 	}
2173a86c6181SAlex Tomas 	return 0;
2174a86c6181SAlex Tomas }
2175a86c6181SAlex Tomas 
2176a86c6181SAlex Tomas static int
2177a86c6181SAlex Tomas ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2178725d26d3SAneesh Kumar K.V 		struct ext4_ext_path *path, ext4_lblk_t start)
2179a86c6181SAlex Tomas {
2180a86c6181SAlex Tomas 	int err = 0, correct_index = 0;
2181a86c6181SAlex Tomas 	int depth = ext_depth(inode), credits;
2182a86c6181SAlex Tomas 	struct ext4_extent_header *eh;
2183725d26d3SAneesh Kumar K.V 	ext4_lblk_t a, b, block;
2184725d26d3SAneesh Kumar K.V 	unsigned num;
2185725d26d3SAneesh Kumar K.V 	ext4_lblk_t ex_ee_block;
2186a86c6181SAlex Tomas 	unsigned short ex_ee_len;
2187a2df2a63SAmit Arora 	unsigned uninitialized = 0;
2188a86c6181SAlex Tomas 	struct ext4_extent *ex;
2189a86c6181SAlex Tomas 
2190c29c0ae7SAlex Tomas 	/* the header must be checked already in ext4_ext_remove_space() */
2191725d26d3SAneesh Kumar K.V 	ext_debug("truncate since %u in leaf\n", start);
2192a86c6181SAlex Tomas 	if (!path[depth].p_hdr)
2193a86c6181SAlex Tomas 		path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2194a86c6181SAlex Tomas 	eh = path[depth].p_hdr;
2195273df556SFrank Mayhar 	if (unlikely(path[depth].p_hdr == NULL)) {
2196273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2197273df556SFrank Mayhar 		return -EIO;
2198273df556SFrank Mayhar 	}
2199a86c6181SAlex Tomas 	/* find where to start removing */
2200a86c6181SAlex Tomas 	ex = EXT_LAST_EXTENT(eh);
2201a86c6181SAlex Tomas 
2202a86c6181SAlex Tomas 	ex_ee_block = le32_to_cpu(ex->ee_block);
2203a2df2a63SAmit Arora 	ex_ee_len = ext4_ext_get_actual_len(ex);
2204a86c6181SAlex Tomas 
2205a86c6181SAlex Tomas 	while (ex >= EXT_FIRST_EXTENT(eh) &&
2206a86c6181SAlex Tomas 			ex_ee_block + ex_ee_len > start) {
2207a41f2071SAneesh Kumar K.V 
2208a41f2071SAneesh Kumar K.V 		if (ext4_ext_is_uninitialized(ex))
2209a41f2071SAneesh Kumar K.V 			uninitialized = 1;
2210a41f2071SAneesh Kumar K.V 		else
2211a41f2071SAneesh Kumar K.V 			uninitialized = 0;
2212a41f2071SAneesh Kumar K.V 
2213553f9008SMingming 		ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2214553f9008SMingming 			 uninitialized, ex_ee_len);
2215a86c6181SAlex Tomas 		path[depth].p_ext = ex;
2216a86c6181SAlex Tomas 
2217a86c6181SAlex Tomas 		a = ex_ee_block > start ? ex_ee_block : start;
2218a86c6181SAlex Tomas 		b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
2219a86c6181SAlex Tomas 			ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
2220a86c6181SAlex Tomas 
2221a86c6181SAlex Tomas 		ext_debug("  border %u:%u\n", a, b);
2222a86c6181SAlex Tomas 
2223a86c6181SAlex Tomas 		if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
2224a86c6181SAlex Tomas 			block = 0;
2225a86c6181SAlex Tomas 			num = 0;
2226a86c6181SAlex Tomas 			BUG();
2227a86c6181SAlex Tomas 		} else if (a != ex_ee_block) {
2228a86c6181SAlex Tomas 			/* remove tail of the extent */
2229a86c6181SAlex Tomas 			block = ex_ee_block;
2230a86c6181SAlex Tomas 			num = a - block;
2231a86c6181SAlex Tomas 		} else if (b != ex_ee_block + ex_ee_len - 1) {
2232a86c6181SAlex Tomas 			/* remove head of the extent */
2233a86c6181SAlex Tomas 			block = a;
2234a86c6181SAlex Tomas 			num = b - a;
2235a86c6181SAlex Tomas 			/* there is no "make a hole" API yet */
2236a86c6181SAlex Tomas 			BUG();
2237a86c6181SAlex Tomas 		} else {
2238a86c6181SAlex Tomas 			/* remove whole extent: excellent! */
2239a86c6181SAlex Tomas 			block = ex_ee_block;
2240a86c6181SAlex Tomas 			num = 0;
2241a86c6181SAlex Tomas 			BUG_ON(a != ex_ee_block);
2242a86c6181SAlex Tomas 			BUG_ON(b != ex_ee_block + ex_ee_len - 1);
2243a86c6181SAlex Tomas 		}
2244a86c6181SAlex Tomas 
224534071da7STheodore Ts'o 		/*
224634071da7STheodore Ts'o 		 * 3 for leaf, sb, and inode plus 2 (bmap and group
224734071da7STheodore Ts'o 		 * descriptor) for each block group; assume two block
224834071da7STheodore Ts'o 		 * groups plus ex_ee_len/blocks_per_block_group for
224934071da7STheodore Ts'o 		 * the worst case
225034071da7STheodore Ts'o 		 */
225134071da7STheodore Ts'o 		credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2252a86c6181SAlex Tomas 		if (ex == EXT_FIRST_EXTENT(eh)) {
2253a86c6181SAlex Tomas 			correct_index = 1;
2254a86c6181SAlex Tomas 			credits += (ext_depth(inode)) + 1;
2255a86c6181SAlex Tomas 		}
22565aca07ebSDmitry Monakhov 		credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2257a86c6181SAlex Tomas 
2258487caeefSJan Kara 		err = ext4_ext_truncate_extend_restart(handle, inode, credits);
22599102e4faSShen Feng 		if (err)
2260a86c6181SAlex Tomas 			goto out;
2261a86c6181SAlex Tomas 
2262a86c6181SAlex Tomas 		err = ext4_ext_get_access(handle, inode, path + depth);
2263a86c6181SAlex Tomas 		if (err)
2264a86c6181SAlex Tomas 			goto out;
2265a86c6181SAlex Tomas 
2266a86c6181SAlex Tomas 		err = ext4_remove_blocks(handle, inode, ex, a, b);
2267a86c6181SAlex Tomas 		if (err)
2268a86c6181SAlex Tomas 			goto out;
2269a86c6181SAlex Tomas 
2270a86c6181SAlex Tomas 		if (num == 0) {
2271d0d856e8SRandy Dunlap 			/* this extent is removed; mark slot entirely unused */
2272f65e6fbaSAlex Tomas 			ext4_ext_store_pblock(ex, 0);
2273e8546d06SMarcin Slusarz 			le16_add_cpu(&eh->eh_entries, -1);
2274a86c6181SAlex Tomas 		}
2275a86c6181SAlex Tomas 
2276a86c6181SAlex Tomas 		ex->ee_block = cpu_to_le32(block);
2277a86c6181SAlex Tomas 		ex->ee_len = cpu_to_le16(num);
2278749269faSAmit Arora 		/*
2279749269faSAmit Arora 		 * Do not mark uninitialized if all the blocks in the
2280749269faSAmit Arora 		 * extent have been removed.
2281749269faSAmit Arora 		 */
2282749269faSAmit Arora 		if (uninitialized && num)
2283a2df2a63SAmit Arora 			ext4_ext_mark_uninitialized(ex);
2284a86c6181SAlex Tomas 
2285a86c6181SAlex Tomas 		err = ext4_ext_dirty(handle, inode, path + depth);
2286a86c6181SAlex Tomas 		if (err)
2287a86c6181SAlex Tomas 			goto out;
2288a86c6181SAlex Tomas 
22892ae02107SMingming Cao 		ext_debug("new extent: %u:%u:%llu\n", block, num,
2290bf89d16fSTheodore Ts'o 				ext4_ext_pblock(ex));
2291a86c6181SAlex Tomas 		ex--;
2292a86c6181SAlex Tomas 		ex_ee_block = le32_to_cpu(ex->ee_block);
2293a2df2a63SAmit Arora 		ex_ee_len = ext4_ext_get_actual_len(ex);
2294a86c6181SAlex Tomas 	}
2295a86c6181SAlex Tomas 
2296a86c6181SAlex Tomas 	if (correct_index && eh->eh_entries)
2297a86c6181SAlex Tomas 		err = ext4_ext_correct_indexes(handle, inode, path);
2298a86c6181SAlex Tomas 
2299a86c6181SAlex Tomas 	/* if this leaf is free, then we should
2300a86c6181SAlex Tomas 	 * remove it from index block above */
2301a86c6181SAlex Tomas 	if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2302a86c6181SAlex Tomas 		err = ext4_ext_rm_idx(handle, inode, path + depth);
2303a86c6181SAlex Tomas 
2304a86c6181SAlex Tomas out:
2305a86c6181SAlex Tomas 	return err;
2306a86c6181SAlex Tomas }
2307a86c6181SAlex Tomas 
2308a86c6181SAlex Tomas /*
2309d0d856e8SRandy Dunlap  * ext4_ext_more_to_rm:
2310d0d856e8SRandy Dunlap  * returns 1 if current index has to be freed (even partial)
2311a86c6181SAlex Tomas  */
231209b88252SAvantika Mathur static int
2313a86c6181SAlex Tomas ext4_ext_more_to_rm(struct ext4_ext_path *path)
2314a86c6181SAlex Tomas {
2315a86c6181SAlex Tomas 	BUG_ON(path->p_idx == NULL);
2316a86c6181SAlex Tomas 
2317a86c6181SAlex Tomas 	if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2318a86c6181SAlex Tomas 		return 0;
2319a86c6181SAlex Tomas 
2320a86c6181SAlex Tomas 	/*
2321d0d856e8SRandy Dunlap 	 * if truncate on deeper level happened, it wasn't partial,
2322a86c6181SAlex Tomas 	 * so we have to consider current index for truncation
2323a86c6181SAlex Tomas 	 */
2324a86c6181SAlex Tomas 	if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2325a86c6181SAlex Tomas 		return 0;
2326a86c6181SAlex Tomas 	return 1;
2327a86c6181SAlex Tomas }
2328a86c6181SAlex Tomas 
23291d03ec98SAneesh Kumar K.V static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2330a86c6181SAlex Tomas {
2331a86c6181SAlex Tomas 	struct super_block *sb = inode->i_sb;
2332a86c6181SAlex Tomas 	int depth = ext_depth(inode);
2333a86c6181SAlex Tomas 	struct ext4_ext_path *path;
2334a86c6181SAlex Tomas 	handle_t *handle;
23350617b83fSDmitry Monakhov 	int i, err;
2336a86c6181SAlex Tomas 
2337725d26d3SAneesh Kumar K.V 	ext_debug("truncate since %u\n", start);
2338a86c6181SAlex Tomas 
2339a86c6181SAlex Tomas 	/* probably first extent we're gonna free will be last in block */
2340a86c6181SAlex Tomas 	handle = ext4_journal_start(inode, depth + 1);
2341a86c6181SAlex Tomas 	if (IS_ERR(handle))
2342a86c6181SAlex Tomas 		return PTR_ERR(handle);
2343a86c6181SAlex Tomas 
23440617b83fSDmitry Monakhov again:
2345a86c6181SAlex Tomas 	ext4_ext_invalidate_cache(inode);
2346a86c6181SAlex Tomas 
2347a86c6181SAlex Tomas 	/*
2348d0d856e8SRandy Dunlap 	 * We start scanning from right side, freeing all the blocks
2349d0d856e8SRandy Dunlap 	 * after i_size and walking into the tree depth-wise.
2350a86c6181SAlex Tomas 	 */
23510617b83fSDmitry Monakhov 	depth = ext_depth(inode);
2352216553c4SJosef Bacik 	path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2353a86c6181SAlex Tomas 	if (path == NULL) {
2354a86c6181SAlex Tomas 		ext4_journal_stop(handle);
2355a86c6181SAlex Tomas 		return -ENOMEM;
2356a86c6181SAlex Tomas 	}
23570617b83fSDmitry Monakhov 	path[0].p_depth = depth;
2358a86c6181SAlex Tomas 	path[0].p_hdr = ext_inode_hdr(inode);
235956b19868SAneesh Kumar K.V 	if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2360a86c6181SAlex Tomas 		err = -EIO;
2361a86c6181SAlex Tomas 		goto out;
2362a86c6181SAlex Tomas 	}
23630617b83fSDmitry Monakhov 	i = err = 0;
2364a86c6181SAlex Tomas 
2365a86c6181SAlex Tomas 	while (i >= 0 && err == 0) {
2366a86c6181SAlex Tomas 		if (i == depth) {
2367a86c6181SAlex Tomas 			/* this is leaf block */
2368a86c6181SAlex Tomas 			err = ext4_ext_rm_leaf(handle, inode, path, start);
2369d0d856e8SRandy Dunlap 			/* root level has p_bh == NULL, brelse() eats this */
2370a86c6181SAlex Tomas 			brelse(path[i].p_bh);
2371a86c6181SAlex Tomas 			path[i].p_bh = NULL;
2372a86c6181SAlex Tomas 			i--;
2373a86c6181SAlex Tomas 			continue;
2374a86c6181SAlex Tomas 		}
2375a86c6181SAlex Tomas 
2376a86c6181SAlex Tomas 		/* this is index block */
2377a86c6181SAlex Tomas 		if (!path[i].p_hdr) {
2378a86c6181SAlex Tomas 			ext_debug("initialize header\n");
2379a86c6181SAlex Tomas 			path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2380a86c6181SAlex Tomas 		}
2381a86c6181SAlex Tomas 
2382a86c6181SAlex Tomas 		if (!path[i].p_idx) {
2383d0d856e8SRandy Dunlap 			/* this level hasn't been touched yet */
2384a86c6181SAlex Tomas 			path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2385a86c6181SAlex Tomas 			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2386a86c6181SAlex Tomas 			ext_debug("init index ptr: hdr 0x%p, num %d\n",
2387a86c6181SAlex Tomas 				  path[i].p_hdr,
2388a86c6181SAlex Tomas 				  le16_to_cpu(path[i].p_hdr->eh_entries));
2389a86c6181SAlex Tomas 		} else {
2390d0d856e8SRandy Dunlap 			/* we were already here, see at next index */
2391a86c6181SAlex Tomas 			path[i].p_idx--;
2392a86c6181SAlex Tomas 		}
2393a86c6181SAlex Tomas 
2394a86c6181SAlex Tomas 		ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2395a86c6181SAlex Tomas 				i, EXT_FIRST_INDEX(path[i].p_hdr),
2396a86c6181SAlex Tomas 				path[i].p_idx);
2397a86c6181SAlex Tomas 		if (ext4_ext_more_to_rm(path + i)) {
2398c29c0ae7SAlex Tomas 			struct buffer_head *bh;
2399a86c6181SAlex Tomas 			/* go to the next level */
24002ae02107SMingming Cao 			ext_debug("move to level %d (block %llu)\n",
2401bf89d16fSTheodore Ts'o 				  i + 1, ext4_idx_pblock(path[i].p_idx));
2402a86c6181SAlex Tomas 			memset(path + i + 1, 0, sizeof(*path));
2403bf89d16fSTheodore Ts'o 			bh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));
2404c29c0ae7SAlex Tomas 			if (!bh) {
2405a86c6181SAlex Tomas 				/* should we reset i_size? */
2406a86c6181SAlex Tomas 				err = -EIO;
2407a86c6181SAlex Tomas 				break;
2408a86c6181SAlex Tomas 			}
2409c29c0ae7SAlex Tomas 			if (WARN_ON(i + 1 > depth)) {
2410c29c0ae7SAlex Tomas 				err = -EIO;
2411c29c0ae7SAlex Tomas 				break;
2412c29c0ae7SAlex Tomas 			}
241356b19868SAneesh Kumar K.V 			if (ext4_ext_check(inode, ext_block_hdr(bh),
2414c29c0ae7SAlex Tomas 							depth - i - 1)) {
2415c29c0ae7SAlex Tomas 				err = -EIO;
2416c29c0ae7SAlex Tomas 				break;
2417c29c0ae7SAlex Tomas 			}
2418c29c0ae7SAlex Tomas 			path[i + 1].p_bh = bh;
2419a86c6181SAlex Tomas 
2420d0d856e8SRandy Dunlap 			/* save actual number of indexes since this
2421d0d856e8SRandy Dunlap 			 * number is changed at the next iteration */
2422a86c6181SAlex Tomas 			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2423a86c6181SAlex Tomas 			i++;
2424a86c6181SAlex Tomas 		} else {
2425d0d856e8SRandy Dunlap 			/* we finished processing this index, go up */
2426a86c6181SAlex Tomas 			if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2427d0d856e8SRandy Dunlap 				/* index is empty, remove it;
2428a86c6181SAlex Tomas 				 * handle must be already prepared by the
2429a86c6181SAlex Tomas 				 * truncatei_leaf() */
2430a86c6181SAlex Tomas 				err = ext4_ext_rm_idx(handle, inode, path + i);
2431a86c6181SAlex Tomas 			}
2432d0d856e8SRandy Dunlap 			/* root level has p_bh == NULL, brelse() eats this */
2433a86c6181SAlex Tomas 			brelse(path[i].p_bh);
2434a86c6181SAlex Tomas 			path[i].p_bh = NULL;
2435a86c6181SAlex Tomas 			i--;
2436a86c6181SAlex Tomas 			ext_debug("return to level %d\n", i);
2437a86c6181SAlex Tomas 		}
2438a86c6181SAlex Tomas 	}
2439a86c6181SAlex Tomas 
2440a86c6181SAlex Tomas 	/* TODO: flexible tree reduction should be here */
2441a86c6181SAlex Tomas 	if (path->p_hdr->eh_entries == 0) {
2442a86c6181SAlex Tomas 		/*
2443d0d856e8SRandy Dunlap 		 * truncate to zero freed all the tree,
2444d0d856e8SRandy Dunlap 		 * so we need to correct eh_depth
2445a86c6181SAlex Tomas 		 */
2446a86c6181SAlex Tomas 		err = ext4_ext_get_access(handle, inode, path);
2447a86c6181SAlex Tomas 		if (err == 0) {
2448a86c6181SAlex Tomas 			ext_inode_hdr(inode)->eh_depth = 0;
2449a86c6181SAlex Tomas 			ext_inode_hdr(inode)->eh_max =
245055ad63bfSTheodore Ts'o 				cpu_to_le16(ext4_ext_space_root(inode, 0));
2451a86c6181SAlex Tomas 			err = ext4_ext_dirty(handle, inode, path);
2452a86c6181SAlex Tomas 		}
2453a86c6181SAlex Tomas 	}
2454a86c6181SAlex Tomas out:
2455a86c6181SAlex Tomas 	ext4_ext_drop_refs(path);
2456a86c6181SAlex Tomas 	kfree(path);
24570617b83fSDmitry Monakhov 	if (err == -EAGAIN)
24580617b83fSDmitry Monakhov 		goto again;
2459a86c6181SAlex Tomas 	ext4_journal_stop(handle);
2460a86c6181SAlex Tomas 
2461a86c6181SAlex Tomas 	return err;
2462a86c6181SAlex Tomas }
2463a86c6181SAlex Tomas 
2464a86c6181SAlex Tomas /*
2465a86c6181SAlex Tomas  * called at mount time
2466a86c6181SAlex Tomas  */
2467a86c6181SAlex Tomas void ext4_ext_init(struct super_block *sb)
2468a86c6181SAlex Tomas {
2469a86c6181SAlex Tomas 	/*
2470a86c6181SAlex Tomas 	 * possible initialization would be here
2471a86c6181SAlex Tomas 	 */
2472a86c6181SAlex Tomas 
247383982b6fSTheodore Ts'o 	if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
247490576c0bSTheodore Ts'o #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
24754776004fSTheodore Ts'o 		printk(KERN_INFO "EXT4-fs: file extents enabled");
2476bbf2f9fbSRobert P. J. Day #ifdef AGGRESSIVE_TEST
2477bbf2f9fbSRobert P. J. Day 		printk(", aggressive tests");
2478a86c6181SAlex Tomas #endif
2479a86c6181SAlex Tomas #ifdef CHECK_BINSEARCH
2480a86c6181SAlex Tomas 		printk(", check binsearch");
2481a86c6181SAlex Tomas #endif
2482a86c6181SAlex Tomas #ifdef EXTENTS_STATS
2483a86c6181SAlex Tomas 		printk(", stats");
2484a86c6181SAlex Tomas #endif
2485a86c6181SAlex Tomas 		printk("\n");
248690576c0bSTheodore Ts'o #endif
2487a86c6181SAlex Tomas #ifdef EXTENTS_STATS
2488a86c6181SAlex Tomas 		spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2489a86c6181SAlex Tomas 		EXT4_SB(sb)->s_ext_min = 1 << 30;
2490a86c6181SAlex Tomas 		EXT4_SB(sb)->s_ext_max = 0;
2491a86c6181SAlex Tomas #endif
2492a86c6181SAlex Tomas 	}
2493a86c6181SAlex Tomas }
2494a86c6181SAlex Tomas 
2495a86c6181SAlex Tomas /*
2496a86c6181SAlex Tomas  * called at umount time
2497a86c6181SAlex Tomas  */
2498a86c6181SAlex Tomas void ext4_ext_release(struct super_block *sb)
2499a86c6181SAlex Tomas {
250083982b6fSTheodore Ts'o 	if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2501a86c6181SAlex Tomas 		return;
2502a86c6181SAlex Tomas 
2503a86c6181SAlex Tomas #ifdef EXTENTS_STATS
2504a86c6181SAlex Tomas 	if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2505a86c6181SAlex Tomas 		struct ext4_sb_info *sbi = EXT4_SB(sb);
2506a86c6181SAlex Tomas 		printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2507a86c6181SAlex Tomas 			sbi->s_ext_blocks, sbi->s_ext_extents,
2508a86c6181SAlex Tomas 			sbi->s_ext_blocks / sbi->s_ext_extents);
2509a86c6181SAlex Tomas 		printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2510a86c6181SAlex Tomas 			sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2511a86c6181SAlex Tomas 	}
2512a86c6181SAlex Tomas #endif
2513a86c6181SAlex Tomas }
2514a86c6181SAlex Tomas 
2515093a088bSAneesh Kumar K.V /* FIXME!! we need to try to merge to left or right after zero-out  */
2516093a088bSAneesh Kumar K.V static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2517093a088bSAneesh Kumar K.V {
25182407518dSLukas Czerner 	ext4_fsblk_t ee_pblock;
25192407518dSLukas Czerner 	unsigned int ee_len;
2520b720303dSJing Zhang 	int ret;
2521093a088bSAneesh Kumar K.V 
2522093a088bSAneesh Kumar K.V 	ee_len    = ext4_ext_get_actual_len(ex);
2523bf89d16fSTheodore Ts'o 	ee_pblock = ext4_ext_pblock(ex);
2524093a088bSAneesh Kumar K.V 
2525a107e5a3STheodore Ts'o 	ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
25262407518dSLukas Czerner 	if (ret > 0)
25272407518dSLukas Czerner 		ret = 0;
2528093a088bSAneesh Kumar K.V 
25292407518dSLukas Czerner 	return ret;
2530093a088bSAneesh Kumar K.V }
2531093a088bSAneesh Kumar K.V 
25323977c965SAneesh Kumar K.V #define EXT4_EXT_ZERO_LEN 7
253356055d3aSAmit Arora /*
2534e35fd660STheodore Ts'o  * This function is called by ext4_ext_map_blocks() if someone tries to write
253556055d3aSAmit Arora  * to an uninitialized extent. It may result in splitting the uninitialized
253656055d3aSAmit Arora  * extent into multiple extents (upto three - one initialized and two
253756055d3aSAmit Arora  * uninitialized).
253856055d3aSAmit Arora  * There are three possibilities:
253956055d3aSAmit Arora  *   a> There is no split required: Entire extent should be initialized
254056055d3aSAmit Arora  *   b> Splits in two extents: Write is happening at either end of the extent
254156055d3aSAmit Arora  *   c> Splits in three extents: Somone is writing in middle of the extent
254256055d3aSAmit Arora  */
2543725d26d3SAneesh Kumar K.V static int ext4_ext_convert_to_initialized(handle_t *handle,
2544725d26d3SAneesh Kumar K.V 					   struct inode *inode,
2545e35fd660STheodore Ts'o 					   struct ext4_map_blocks *map,
2546e35fd660STheodore Ts'o 					   struct ext4_ext_path *path)
254756055d3aSAmit Arora {
254895c3889cSAneesh Kumar K.V 	struct ext4_extent *ex, newex, orig_ex;
254956055d3aSAmit Arora 	struct ext4_extent *ex1 = NULL;
255056055d3aSAmit Arora 	struct ext4_extent *ex2 = NULL;
255156055d3aSAmit Arora 	struct ext4_extent *ex3 = NULL;
255256055d3aSAmit Arora 	struct ext4_extent_header *eh;
255321ca087aSDmitry Monakhov 	ext4_lblk_t ee_block, eof_block;
2554725d26d3SAneesh Kumar K.V 	unsigned int allocated, ee_len, depth;
255556055d3aSAmit Arora 	ext4_fsblk_t newblock;
255656055d3aSAmit Arora 	int err = 0;
255756055d3aSAmit Arora 	int ret = 0;
255821ca087aSDmitry Monakhov 	int may_zeroout;
255921ca087aSDmitry Monakhov 
256021ca087aSDmitry Monakhov 	ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
256121ca087aSDmitry Monakhov 		"block %llu, max_blocks %u\n", inode->i_ino,
2562e35fd660STheodore Ts'o 		(unsigned long long)map->m_lblk, map->m_len);
256321ca087aSDmitry Monakhov 
256421ca087aSDmitry Monakhov 	eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
256521ca087aSDmitry Monakhov 		inode->i_sb->s_blocksize_bits;
2566e35fd660STheodore Ts'o 	if (eof_block < map->m_lblk + map->m_len)
2567e35fd660STheodore Ts'o 		eof_block = map->m_lblk + map->m_len;
256856055d3aSAmit Arora 
256956055d3aSAmit Arora 	depth = ext_depth(inode);
257056055d3aSAmit Arora 	eh = path[depth].p_hdr;
257156055d3aSAmit Arora 	ex = path[depth].p_ext;
257256055d3aSAmit Arora 	ee_block = le32_to_cpu(ex->ee_block);
257356055d3aSAmit Arora 	ee_len = ext4_ext_get_actual_len(ex);
2574e35fd660STheodore Ts'o 	allocated = ee_len - (map->m_lblk - ee_block);
2575bf89d16fSTheodore Ts'o 	newblock = map->m_lblk - ee_block + ext4_ext_pblock(ex);
257621ca087aSDmitry Monakhov 
257756055d3aSAmit Arora 	ex2 = ex;
257895c3889cSAneesh Kumar K.V 	orig_ex.ee_block = ex->ee_block;
257995c3889cSAneesh Kumar K.V 	orig_ex.ee_len   = cpu_to_le16(ee_len);
2580bf89d16fSTheodore Ts'o 	ext4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex));
258156055d3aSAmit Arora 
258221ca087aSDmitry Monakhov 	/*
258321ca087aSDmitry Monakhov 	 * It is safe to convert extent to initialized via explicit
258421ca087aSDmitry Monakhov 	 * zeroout only if extent is fully insde i_size or new_size.
258521ca087aSDmitry Monakhov 	 */
258621ca087aSDmitry Monakhov 	may_zeroout = ee_block + ee_len <= eof_block;
258721ca087aSDmitry Monakhov 
25889df5643aSAneesh Kumar K.V 	err = ext4_ext_get_access(handle, inode, path + depth);
25899df5643aSAneesh Kumar K.V 	if (err)
25909df5643aSAneesh Kumar K.V 		goto out;
25913977c965SAneesh Kumar K.V 	/* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
259221ca087aSDmitry Monakhov 	if (ee_len <= 2*EXT4_EXT_ZERO_LEN && may_zeroout) {
25933977c965SAneesh Kumar K.V 		err =  ext4_ext_zeroout(inode, &orig_ex);
25943977c965SAneesh Kumar K.V 		if (err)
25953977c965SAneesh Kumar K.V 			goto fix_extent_len;
25963977c965SAneesh Kumar K.V 		/* update the extent length and mark as initialized */
25973977c965SAneesh Kumar K.V 		ex->ee_block = orig_ex.ee_block;
25983977c965SAneesh Kumar K.V 		ex->ee_len   = orig_ex.ee_len;
2599bf89d16fSTheodore Ts'o 		ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
26003977c965SAneesh Kumar K.V 		ext4_ext_dirty(handle, inode, path + depth);
2601161e7b7cSAneesh Kumar K.V 		/* zeroed the full extent */
2602161e7b7cSAneesh Kumar K.V 		return allocated;
26033977c965SAneesh Kumar K.V 	}
26049df5643aSAneesh Kumar K.V 
2605e35fd660STheodore Ts'o 	/* ex1: ee_block to map->m_lblk - 1 : uninitialized */
2606e35fd660STheodore Ts'o 	if (map->m_lblk > ee_block) {
260756055d3aSAmit Arora 		ex1 = ex;
2608e35fd660STheodore Ts'o 		ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
260956055d3aSAmit Arora 		ext4_ext_mark_uninitialized(ex1);
261056055d3aSAmit Arora 		ex2 = &newex;
261156055d3aSAmit Arora 	}
261256055d3aSAmit Arora 	/*
261356055d3aSAmit Arora 	 * for sanity, update the length of the ex2 extent before
261456055d3aSAmit Arora 	 * we insert ex3, if ex1 is NULL. This is to avoid temporary
261556055d3aSAmit Arora 	 * overlap of blocks.
261656055d3aSAmit Arora 	 */
2617e35fd660STheodore Ts'o 	if (!ex1 && allocated > map->m_len)
2618e35fd660STheodore Ts'o 		ex2->ee_len = cpu_to_le16(map->m_len);
261956055d3aSAmit Arora 	/* ex3: to ee_block + ee_len : uninitialised */
2620e35fd660STheodore Ts'o 	if (allocated > map->m_len) {
262156055d3aSAmit Arora 		unsigned int newdepth;
26223977c965SAneesh Kumar K.V 		/* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
262321ca087aSDmitry Monakhov 		if (allocated <= EXT4_EXT_ZERO_LEN && may_zeroout) {
2624d03856bdSAneesh Kumar K.V 			/*
2625e35fd660STheodore Ts'o 			 * map->m_lblk == ee_block is handled by the zerouout
2626d03856bdSAneesh Kumar K.V 			 * at the beginning.
2627d03856bdSAneesh Kumar K.V 			 * Mark first half uninitialized.
26283977c965SAneesh Kumar K.V 			 * Mark second half initialized and zero out the
26293977c965SAneesh Kumar K.V 			 * initialized extent
26303977c965SAneesh Kumar K.V 			 */
26313977c965SAneesh Kumar K.V 			ex->ee_block = orig_ex.ee_block;
26323977c965SAneesh Kumar K.V 			ex->ee_len   = cpu_to_le16(ee_len - allocated);
26333977c965SAneesh Kumar K.V 			ext4_ext_mark_uninitialized(ex);
2634bf89d16fSTheodore Ts'o 			ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
26353977c965SAneesh Kumar K.V 			ext4_ext_dirty(handle, inode, path + depth);
26363977c965SAneesh Kumar K.V 
26373977c965SAneesh Kumar K.V 			ex3 = &newex;
2638e35fd660STheodore Ts'o 			ex3->ee_block = cpu_to_le32(map->m_lblk);
26393977c965SAneesh Kumar K.V 			ext4_ext_store_pblock(ex3, newblock);
26403977c965SAneesh Kumar K.V 			ex3->ee_len = cpu_to_le16(allocated);
26410031462bSMingming Cao 			err = ext4_ext_insert_extent(handle, inode, path,
26420031462bSMingming Cao 							ex3, 0);
26433977c965SAneesh Kumar K.V 			if (err == -ENOSPC) {
26443977c965SAneesh Kumar K.V 				err =  ext4_ext_zeroout(inode, &orig_ex);
26453977c965SAneesh Kumar K.V 				if (err)
26463977c965SAneesh Kumar K.V 					goto fix_extent_len;
26473977c965SAneesh Kumar K.V 				ex->ee_block = orig_ex.ee_block;
26483977c965SAneesh Kumar K.V 				ex->ee_len   = orig_ex.ee_len;
2649bf89d16fSTheodore Ts'o 				ext4_ext_store_pblock(ex,
2650bf89d16fSTheodore Ts'o 					ext4_ext_pblock(&orig_ex));
26513977c965SAneesh Kumar K.V 				ext4_ext_dirty(handle, inode, path + depth);
2652e35fd660STheodore Ts'o 				/* blocks available from map->m_lblk */
2653161e7b7cSAneesh Kumar K.V 				return allocated;
26543977c965SAneesh Kumar K.V 
26553977c965SAneesh Kumar K.V 			} else if (err)
26563977c965SAneesh Kumar K.V 				goto fix_extent_len;
26573977c965SAneesh Kumar K.V 
2658161e7b7cSAneesh Kumar K.V 			/*
2659161e7b7cSAneesh Kumar K.V 			 * We need to zero out the second half because
2660161e7b7cSAneesh Kumar K.V 			 * an fallocate request can update file size and
2661161e7b7cSAneesh Kumar K.V 			 * converting the second half to initialized extent
2662161e7b7cSAneesh Kumar K.V 			 * implies that we can leak some junk data to user
2663161e7b7cSAneesh Kumar K.V 			 * space.
2664161e7b7cSAneesh Kumar K.V 			 */
2665161e7b7cSAneesh Kumar K.V 			err =  ext4_ext_zeroout(inode, ex3);
2666161e7b7cSAneesh Kumar K.V 			if (err) {
2667161e7b7cSAneesh Kumar K.V 				/*
2668161e7b7cSAneesh Kumar K.V 				 * We should actually mark the
2669161e7b7cSAneesh Kumar K.V 				 * second half as uninit and return error
2670161e7b7cSAneesh Kumar K.V 				 * Insert would have changed the extent
2671161e7b7cSAneesh Kumar K.V 				 */
2672161e7b7cSAneesh Kumar K.V 				depth = ext_depth(inode);
2673161e7b7cSAneesh Kumar K.V 				ext4_ext_drop_refs(path);
2674e35fd660STheodore Ts'o 				path = ext4_ext_find_extent(inode, map->m_lblk,
2675e35fd660STheodore Ts'o 							    path);
2676161e7b7cSAneesh Kumar K.V 				if (IS_ERR(path)) {
2677161e7b7cSAneesh Kumar K.V 					err = PTR_ERR(path);
2678161e7b7cSAneesh Kumar K.V 					return err;
2679161e7b7cSAneesh Kumar K.V 				}
2680d03856bdSAneesh Kumar K.V 				/* get the second half extent details */
2681161e7b7cSAneesh Kumar K.V 				ex = path[depth].p_ext;
2682161e7b7cSAneesh Kumar K.V 				err = ext4_ext_get_access(handle, inode,
2683161e7b7cSAneesh Kumar K.V 								path + depth);
2684161e7b7cSAneesh Kumar K.V 				if (err)
2685161e7b7cSAneesh Kumar K.V 					return err;
2686161e7b7cSAneesh Kumar K.V 				ext4_ext_mark_uninitialized(ex);
2687161e7b7cSAneesh Kumar K.V 				ext4_ext_dirty(handle, inode, path + depth);
2688161e7b7cSAneesh Kumar K.V 				return err;
2689161e7b7cSAneesh Kumar K.V 			}
2690161e7b7cSAneesh Kumar K.V 
2691161e7b7cSAneesh Kumar K.V 			/* zeroed the second half */
26923977c965SAneesh Kumar K.V 			return allocated;
26933977c965SAneesh Kumar K.V 		}
269456055d3aSAmit Arora 		ex3 = &newex;
2695e35fd660STheodore Ts'o 		ex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len);
2696e35fd660STheodore Ts'o 		ext4_ext_store_pblock(ex3, newblock + map->m_len);
2697e35fd660STheodore Ts'o 		ex3->ee_len = cpu_to_le16(allocated - map->m_len);
269856055d3aSAmit Arora 		ext4_ext_mark_uninitialized(ex3);
26990031462bSMingming Cao 		err = ext4_ext_insert_extent(handle, inode, path, ex3, 0);
270021ca087aSDmitry Monakhov 		if (err == -ENOSPC && may_zeroout) {
2701093a088bSAneesh Kumar K.V 			err =  ext4_ext_zeroout(inode, &orig_ex);
2702093a088bSAneesh Kumar K.V 			if (err)
2703093a088bSAneesh Kumar K.V 				goto fix_extent_len;
2704093a088bSAneesh Kumar K.V 			/* update the extent length and mark as initialized */
270595c3889cSAneesh Kumar K.V 			ex->ee_block = orig_ex.ee_block;
270695c3889cSAneesh Kumar K.V 			ex->ee_len   = orig_ex.ee_len;
2707bf89d16fSTheodore Ts'o 			ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
270895c3889cSAneesh Kumar K.V 			ext4_ext_dirty(handle, inode, path + depth);
2709161e7b7cSAneesh Kumar K.V 			/* zeroed the full extent */
2710e35fd660STheodore Ts'o 			/* blocks available from map->m_lblk */
2711161e7b7cSAneesh Kumar K.V 			return allocated;
2712093a088bSAneesh Kumar K.V 
2713093a088bSAneesh Kumar K.V 		} else if (err)
2714093a088bSAneesh Kumar K.V 			goto fix_extent_len;
271556055d3aSAmit Arora 		/*
271656055d3aSAmit Arora 		 * The depth, and hence eh & ex might change
271756055d3aSAmit Arora 		 * as part of the insert above.
271856055d3aSAmit Arora 		 */
271956055d3aSAmit Arora 		newdepth = ext_depth(inode);
272095c3889cSAneesh Kumar K.V 		/*
272173ac36eaSColy Li 		 * update the extent length after successful insert of the
272295c3889cSAneesh Kumar K.V 		 * split extent
272395c3889cSAneesh Kumar K.V 		 */
272421ca087aSDmitry Monakhov 		ee_len -= ext4_ext_get_actual_len(ex3);
272521ca087aSDmitry Monakhov 		orig_ex.ee_len = cpu_to_le16(ee_len);
272621ca087aSDmitry Monakhov 		may_zeroout = ee_block + ee_len <= eof_block;
272721ca087aSDmitry Monakhov 
272856055d3aSAmit Arora 		depth = newdepth;
2729b35905c1SAneesh Kumar K.V 		ext4_ext_drop_refs(path);
2730e35fd660STheodore Ts'o 		path = ext4_ext_find_extent(inode, map->m_lblk, path);
273156055d3aSAmit Arora 		if (IS_ERR(path)) {
273256055d3aSAmit Arora 			err = PTR_ERR(path);
273356055d3aSAmit Arora 			goto out;
273456055d3aSAmit Arora 		}
273556055d3aSAmit Arora 		eh = path[depth].p_hdr;
273656055d3aSAmit Arora 		ex = path[depth].p_ext;
273756055d3aSAmit Arora 		if (ex2 != &newex)
273856055d3aSAmit Arora 			ex2 = ex;
27399df5643aSAneesh Kumar K.V 
27409df5643aSAneesh Kumar K.V 		err = ext4_ext_get_access(handle, inode, path + depth);
27419df5643aSAneesh Kumar K.V 		if (err)
27429df5643aSAneesh Kumar K.V 			goto out;
2743d03856bdSAneesh Kumar K.V 
2744e35fd660STheodore Ts'o 		allocated = map->m_len;
27453977c965SAneesh Kumar K.V 
27463977c965SAneesh Kumar K.V 		/* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
27473977c965SAneesh Kumar K.V 		 * to insert a extent in the middle zerout directly
27483977c965SAneesh Kumar K.V 		 * otherwise give the extent a chance to merge to left
27493977c965SAneesh Kumar K.V 		 */
27503977c965SAneesh Kumar K.V 		if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
2751e35fd660STheodore Ts'o 			map->m_lblk != ee_block && may_zeroout) {
27523977c965SAneesh Kumar K.V 			err =  ext4_ext_zeroout(inode, &orig_ex);
27533977c965SAneesh Kumar K.V 			if (err)
27543977c965SAneesh Kumar K.V 				goto fix_extent_len;
27553977c965SAneesh Kumar K.V 			/* update the extent length and mark as initialized */
27563977c965SAneesh Kumar K.V 			ex->ee_block = orig_ex.ee_block;
27573977c965SAneesh Kumar K.V 			ex->ee_len   = orig_ex.ee_len;
2758bf89d16fSTheodore Ts'o 			ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
27593977c965SAneesh Kumar K.V 			ext4_ext_dirty(handle, inode, path + depth);
2760161e7b7cSAneesh Kumar K.V 			/* zero out the first half */
2761e35fd660STheodore Ts'o 			/* blocks available from map->m_lblk */
2762161e7b7cSAneesh Kumar K.V 			return allocated;
27633977c965SAneesh Kumar K.V 		}
276456055d3aSAmit Arora 	}
276556055d3aSAmit Arora 	/*
276656055d3aSAmit Arora 	 * If there was a change of depth as part of the
276756055d3aSAmit Arora 	 * insertion of ex3 above, we need to update the length
276856055d3aSAmit Arora 	 * of the ex1 extent again here
276956055d3aSAmit Arora 	 */
277056055d3aSAmit Arora 	if (ex1 && ex1 != ex) {
277156055d3aSAmit Arora 		ex1 = ex;
2772e35fd660STheodore Ts'o 		ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
277356055d3aSAmit Arora 		ext4_ext_mark_uninitialized(ex1);
277456055d3aSAmit Arora 		ex2 = &newex;
277556055d3aSAmit Arora 	}
2776e35fd660STheodore Ts'o 	/* ex2: map->m_lblk to map->m_lblk + maxblocks-1 : initialised */
2777e35fd660STheodore Ts'o 	ex2->ee_block = cpu_to_le32(map->m_lblk);
277856055d3aSAmit Arora 	ext4_ext_store_pblock(ex2, newblock);
277956055d3aSAmit Arora 	ex2->ee_len = cpu_to_le16(allocated);
278056055d3aSAmit Arora 	if (ex2 != ex)
278156055d3aSAmit Arora 		goto insert;
278256055d3aSAmit Arora 	/*
278356055d3aSAmit Arora 	 * New (initialized) extent starts from the first block
278456055d3aSAmit Arora 	 * in the current extent. i.e., ex2 == ex
278556055d3aSAmit Arora 	 * We have to see if it can be merged with the extent
278656055d3aSAmit Arora 	 * on the left.
278756055d3aSAmit Arora 	 */
278856055d3aSAmit Arora 	if (ex2 > EXT_FIRST_EXTENT(eh)) {
278956055d3aSAmit Arora 		/*
279056055d3aSAmit Arora 		 * To merge left, pass "ex2 - 1" to try_to_merge(),
279156055d3aSAmit Arora 		 * since it merges towards right _only_.
279256055d3aSAmit Arora 		 */
279356055d3aSAmit Arora 		ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
279456055d3aSAmit Arora 		if (ret) {
279556055d3aSAmit Arora 			err = ext4_ext_correct_indexes(handle, inode, path);
279656055d3aSAmit Arora 			if (err)
279756055d3aSAmit Arora 				goto out;
279856055d3aSAmit Arora 			depth = ext_depth(inode);
279956055d3aSAmit Arora 			ex2--;
280056055d3aSAmit Arora 		}
280156055d3aSAmit Arora 	}
280256055d3aSAmit Arora 	/*
280356055d3aSAmit Arora 	 * Try to Merge towards right. This might be required
280456055d3aSAmit Arora 	 * only when the whole extent is being written to.
280556055d3aSAmit Arora 	 * i.e. ex2 == ex and ex3 == NULL.
280656055d3aSAmit Arora 	 */
280756055d3aSAmit Arora 	if (!ex3) {
280856055d3aSAmit Arora 		ret = ext4_ext_try_to_merge(inode, path, ex2);
280956055d3aSAmit Arora 		if (ret) {
281056055d3aSAmit Arora 			err = ext4_ext_correct_indexes(handle, inode, path);
281156055d3aSAmit Arora 			if (err)
281256055d3aSAmit Arora 				goto out;
281356055d3aSAmit Arora 		}
281456055d3aSAmit Arora 	}
281556055d3aSAmit Arora 	/* Mark modified extent as dirty */
281656055d3aSAmit Arora 	err = ext4_ext_dirty(handle, inode, path + depth);
281756055d3aSAmit Arora 	goto out;
281856055d3aSAmit Arora insert:
28190031462bSMingming Cao 	err = ext4_ext_insert_extent(handle, inode, path, &newex, 0);
282021ca087aSDmitry Monakhov 	if (err == -ENOSPC && may_zeroout) {
2821093a088bSAneesh Kumar K.V 		err =  ext4_ext_zeroout(inode, &orig_ex);
2822093a088bSAneesh Kumar K.V 		if (err)
2823093a088bSAneesh Kumar K.V 			goto fix_extent_len;
2824093a088bSAneesh Kumar K.V 		/* update the extent length and mark as initialized */
2825093a088bSAneesh Kumar K.V 		ex->ee_block = orig_ex.ee_block;
2826093a088bSAneesh Kumar K.V 		ex->ee_len   = orig_ex.ee_len;
2827bf89d16fSTheodore Ts'o 		ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
2828093a088bSAneesh Kumar K.V 		ext4_ext_dirty(handle, inode, path + depth);
2829161e7b7cSAneesh Kumar K.V 		/* zero out the first half */
2830161e7b7cSAneesh Kumar K.V 		return allocated;
2831093a088bSAneesh Kumar K.V 	} else if (err)
2832093a088bSAneesh Kumar K.V 		goto fix_extent_len;
2833093a088bSAneesh Kumar K.V out:
2834553f9008SMingming 	ext4_ext_show_leaf(inode, path);
2835093a088bSAneesh Kumar K.V 	return err ? err : allocated;
2836093a088bSAneesh Kumar K.V 
2837093a088bSAneesh Kumar K.V fix_extent_len:
283895c3889cSAneesh Kumar K.V 	ex->ee_block = orig_ex.ee_block;
283995c3889cSAneesh Kumar K.V 	ex->ee_len   = orig_ex.ee_len;
2840bf89d16fSTheodore Ts'o 	ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
284195c3889cSAneesh Kumar K.V 	ext4_ext_mark_uninitialized(ex);
284295c3889cSAneesh Kumar K.V 	ext4_ext_dirty(handle, inode, path + depth);
2843093a088bSAneesh Kumar K.V 	return err;
284456055d3aSAmit Arora }
284556055d3aSAmit Arora 
2846c278bfecSAneesh Kumar K.V /*
2847e35fd660STheodore Ts'o  * This function is called by ext4_ext_map_blocks() from
28480031462bSMingming Cao  * ext4_get_blocks_dio_write() when DIO to write
28490031462bSMingming Cao  * to an uninitialized extent.
28500031462bSMingming Cao  *
28510031462bSMingming Cao  * Writing to an uninitized extent may result in splitting the uninitialized
2852b595076aSUwe Kleine-König  * extent into multiple /initialized uninitialized extents (up to three)
28530031462bSMingming Cao  * There are three possibilities:
28540031462bSMingming Cao  *   a> There is no split required: Entire extent should be uninitialized
28550031462bSMingming Cao  *   b> Splits in two extents: Write is happening at either end of the extent
28560031462bSMingming Cao  *   c> Splits in three extents: Somone is writing in middle of the extent
28570031462bSMingming Cao  *
28580031462bSMingming Cao  * One of more index blocks maybe needed if the extent tree grow after
2859b595076aSUwe Kleine-König  * the uninitialized extent split. To prevent ENOSPC occur at the IO
28600031462bSMingming Cao  * complete, we need to split the uninitialized extent before DIO submit
2861421f91d2SUwe Kleine-König  * the IO. The uninitialized extent called at this time will be split
28620031462bSMingming Cao  * into three uninitialized extent(at most). After IO complete, the part
28630031462bSMingming Cao  * being filled will be convert to initialized by the end_io callback function
28640031462bSMingming Cao  * via ext4_convert_unwritten_extents().
2865ba230c3fSMingming  *
2866ba230c3fSMingming  * Returns the size of uninitialized extent to be written on success.
28670031462bSMingming Cao  */
28680031462bSMingming Cao static int ext4_split_unwritten_extents(handle_t *handle,
28690031462bSMingming Cao 					struct inode *inode,
2870e35fd660STheodore Ts'o 					struct ext4_map_blocks *map,
28710031462bSMingming Cao 					struct ext4_ext_path *path,
28720031462bSMingming Cao 					int flags)
28730031462bSMingming Cao {
28740031462bSMingming Cao 	struct ext4_extent *ex, newex, orig_ex;
28750031462bSMingming Cao 	struct ext4_extent *ex1 = NULL;
28760031462bSMingming Cao 	struct ext4_extent *ex2 = NULL;
28770031462bSMingming Cao 	struct ext4_extent *ex3 = NULL;
287821ca087aSDmitry Monakhov 	ext4_lblk_t ee_block, eof_block;
28790031462bSMingming Cao 	unsigned int allocated, ee_len, depth;
28800031462bSMingming Cao 	ext4_fsblk_t newblock;
28810031462bSMingming Cao 	int err = 0;
288221ca087aSDmitry Monakhov 	int may_zeroout;
28830031462bSMingming Cao 
288421ca087aSDmitry Monakhov 	ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
288521ca087aSDmitry Monakhov 		"block %llu, max_blocks %u\n", inode->i_ino,
2886e35fd660STheodore Ts'o 		(unsigned long long)map->m_lblk, map->m_len);
288721ca087aSDmitry Monakhov 
288821ca087aSDmitry Monakhov 	eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
288921ca087aSDmitry Monakhov 		inode->i_sb->s_blocksize_bits;
2890e35fd660STheodore Ts'o 	if (eof_block < map->m_lblk + map->m_len)
2891e35fd660STheodore Ts'o 		eof_block = map->m_lblk + map->m_len;
289221ca087aSDmitry Monakhov 
28930031462bSMingming Cao 	depth = ext_depth(inode);
28940031462bSMingming Cao 	ex = path[depth].p_ext;
28950031462bSMingming Cao 	ee_block = le32_to_cpu(ex->ee_block);
28960031462bSMingming Cao 	ee_len = ext4_ext_get_actual_len(ex);
2897e35fd660STheodore Ts'o 	allocated = ee_len - (map->m_lblk - ee_block);
2898bf89d16fSTheodore Ts'o 	newblock = map->m_lblk - ee_block + ext4_ext_pblock(ex);
289921ca087aSDmitry Monakhov 
29000031462bSMingming Cao 	ex2 = ex;
29010031462bSMingming Cao 	orig_ex.ee_block = ex->ee_block;
29020031462bSMingming Cao 	orig_ex.ee_len   = cpu_to_le16(ee_len);
2903bf89d16fSTheodore Ts'o 	ext4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex));
29040031462bSMingming Cao 
29050031462bSMingming Cao 	/*
290621ca087aSDmitry Monakhov 	 * It is safe to convert extent to initialized via explicit
290721ca087aSDmitry Monakhov 	 * zeroout only if extent is fully insde i_size or new_size.
290821ca087aSDmitry Monakhov 	 */
290921ca087aSDmitry Monakhov 	may_zeroout = ee_block + ee_len <= eof_block;
291021ca087aSDmitry Monakhov 
291121ca087aSDmitry Monakhov 	/*
2912ba230c3fSMingming  	 * If the uninitialized extent begins at the same logical
2913ba230c3fSMingming  	 * block where the write begins, and the write completely
2914ba230c3fSMingming  	 * covers the extent, then we don't need to split it.
29150031462bSMingming Cao  	 */
2916e35fd660STheodore Ts'o 	if ((map->m_lblk == ee_block) && (allocated <= map->m_len))
2917ba230c3fSMingming 		return allocated;
29180031462bSMingming Cao 
29190031462bSMingming Cao 	err = ext4_ext_get_access(handle, inode, path + depth);
29200031462bSMingming Cao 	if (err)
29210031462bSMingming Cao 		goto out;
2922e35fd660STheodore Ts'o 	/* ex1: ee_block to map->m_lblk - 1 : uninitialized */
2923e35fd660STheodore Ts'o 	if (map->m_lblk > ee_block) {
29240031462bSMingming Cao 		ex1 = ex;
2925e35fd660STheodore Ts'o 		ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
29260031462bSMingming Cao 		ext4_ext_mark_uninitialized(ex1);
29270031462bSMingming Cao 		ex2 = &newex;
29280031462bSMingming Cao 	}
29290031462bSMingming Cao 	/*
29300031462bSMingming Cao 	 * for sanity, update the length of the ex2 extent before
29310031462bSMingming Cao 	 * we insert ex3, if ex1 is NULL. This is to avoid temporary
29320031462bSMingming Cao 	 * overlap of blocks.
29330031462bSMingming Cao 	 */
2934e35fd660STheodore Ts'o 	if (!ex1 && allocated > map->m_len)
2935e35fd660STheodore Ts'o 		ex2->ee_len = cpu_to_le16(map->m_len);
29360031462bSMingming Cao 	/* ex3: to ee_block + ee_len : uninitialised */
2937e35fd660STheodore Ts'o 	if (allocated > map->m_len) {
29380031462bSMingming Cao 		unsigned int newdepth;
29390031462bSMingming Cao 		ex3 = &newex;
2940e35fd660STheodore Ts'o 		ex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len);
2941e35fd660STheodore Ts'o 		ext4_ext_store_pblock(ex3, newblock + map->m_len);
2942e35fd660STheodore Ts'o 		ex3->ee_len = cpu_to_le16(allocated - map->m_len);
29430031462bSMingming Cao 		ext4_ext_mark_uninitialized(ex3);
29440031462bSMingming Cao 		err = ext4_ext_insert_extent(handle, inode, path, ex3, flags);
294521ca087aSDmitry Monakhov 		if (err == -ENOSPC && may_zeroout) {
29460031462bSMingming Cao 			err =  ext4_ext_zeroout(inode, &orig_ex);
29470031462bSMingming Cao 			if (err)
29480031462bSMingming Cao 				goto fix_extent_len;
29490031462bSMingming Cao 			/* update the extent length and mark as initialized */
29500031462bSMingming Cao 			ex->ee_block = orig_ex.ee_block;
29510031462bSMingming Cao 			ex->ee_len   = orig_ex.ee_len;
2952bf89d16fSTheodore Ts'o 			ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
29530031462bSMingming Cao 			ext4_ext_dirty(handle, inode, path + depth);
29540031462bSMingming Cao 			/* zeroed the full extent */
2955e35fd660STheodore Ts'o 			/* blocks available from map->m_lblk */
29560031462bSMingming Cao 			return allocated;
29570031462bSMingming Cao 
29580031462bSMingming Cao 		} else if (err)
29590031462bSMingming Cao 			goto fix_extent_len;
29600031462bSMingming Cao 		/*
29610031462bSMingming Cao 		 * The depth, and hence eh & ex might change
29620031462bSMingming Cao 		 * as part of the insert above.
29630031462bSMingming Cao 		 */
29640031462bSMingming Cao 		newdepth = ext_depth(inode);
29650031462bSMingming Cao 		/*
29660031462bSMingming Cao 		 * update the extent length after successful insert of the
29670031462bSMingming Cao 		 * split extent
29680031462bSMingming Cao 		 */
296921ca087aSDmitry Monakhov 		ee_len -= ext4_ext_get_actual_len(ex3);
297021ca087aSDmitry Monakhov 		orig_ex.ee_len = cpu_to_le16(ee_len);
297121ca087aSDmitry Monakhov 		may_zeroout = ee_block + ee_len <= eof_block;
297221ca087aSDmitry Monakhov 
29730031462bSMingming Cao 		depth = newdepth;
29740031462bSMingming Cao 		ext4_ext_drop_refs(path);
2975e35fd660STheodore Ts'o 		path = ext4_ext_find_extent(inode, map->m_lblk, path);
29760031462bSMingming Cao 		if (IS_ERR(path)) {
29770031462bSMingming Cao 			err = PTR_ERR(path);
29780031462bSMingming Cao 			goto out;
29790031462bSMingming Cao 		}
29800031462bSMingming Cao 		ex = path[depth].p_ext;
29810031462bSMingming Cao 		if (ex2 != &newex)
29820031462bSMingming Cao 			ex2 = ex;
29830031462bSMingming Cao 
29840031462bSMingming Cao 		err = ext4_ext_get_access(handle, inode, path + depth);
29850031462bSMingming Cao 		if (err)
29860031462bSMingming Cao 			goto out;
29870031462bSMingming Cao 
2988e35fd660STheodore Ts'o 		allocated = map->m_len;
29890031462bSMingming Cao 	}
29900031462bSMingming Cao 	/*
29910031462bSMingming Cao 	 * If there was a change of depth as part of the
29920031462bSMingming Cao 	 * insertion of ex3 above, we need to update the length
29930031462bSMingming Cao 	 * of the ex1 extent again here
29940031462bSMingming Cao 	 */
29950031462bSMingming Cao 	if (ex1 && ex1 != ex) {
29960031462bSMingming Cao 		ex1 = ex;
2997e35fd660STheodore Ts'o 		ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
29980031462bSMingming Cao 		ext4_ext_mark_uninitialized(ex1);
29990031462bSMingming Cao 		ex2 = &newex;
30000031462bSMingming Cao 	}
30010031462bSMingming Cao 	/*
3002e35fd660STheodore Ts'o 	 * ex2: map->m_lblk to map->m_lblk + map->m_len-1 : to be written
3003e35fd660STheodore Ts'o 	 * using direct I/O, uninitialised still.
30040031462bSMingming Cao 	 */
3005e35fd660STheodore Ts'o 	ex2->ee_block = cpu_to_le32(map->m_lblk);
30060031462bSMingming Cao 	ext4_ext_store_pblock(ex2, newblock);
30070031462bSMingming Cao 	ex2->ee_len = cpu_to_le16(allocated);
30080031462bSMingming Cao 	ext4_ext_mark_uninitialized(ex2);
30090031462bSMingming Cao 	if (ex2 != ex)
30100031462bSMingming Cao 		goto insert;
30110031462bSMingming Cao 	/* Mark modified extent as dirty */
30120031462bSMingming Cao 	err = ext4_ext_dirty(handle, inode, path + depth);
30130031462bSMingming Cao 	ext_debug("out here\n");
30140031462bSMingming Cao 	goto out;
30150031462bSMingming Cao insert:
30160031462bSMingming Cao 	err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
301721ca087aSDmitry Monakhov 	if (err == -ENOSPC && may_zeroout) {
30180031462bSMingming Cao 		err =  ext4_ext_zeroout(inode, &orig_ex);
30190031462bSMingming Cao 		if (err)
30200031462bSMingming Cao 			goto fix_extent_len;
30210031462bSMingming Cao 		/* update the extent length and mark as initialized */
30220031462bSMingming Cao 		ex->ee_block = orig_ex.ee_block;
30230031462bSMingming Cao 		ex->ee_len   = orig_ex.ee_len;
3024bf89d16fSTheodore Ts'o 		ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
30250031462bSMingming Cao 		ext4_ext_dirty(handle, inode, path + depth);
30260031462bSMingming Cao 		/* zero out the first half */
30270031462bSMingming Cao 		return allocated;
30280031462bSMingming Cao 	} else if (err)
30290031462bSMingming Cao 		goto fix_extent_len;
30300031462bSMingming Cao out:
30310031462bSMingming Cao 	ext4_ext_show_leaf(inode, path);
30320031462bSMingming Cao 	return err ? err : allocated;
30330031462bSMingming Cao 
30340031462bSMingming Cao fix_extent_len:
30350031462bSMingming Cao 	ex->ee_block = orig_ex.ee_block;
30360031462bSMingming Cao 	ex->ee_len   = orig_ex.ee_len;
3037bf89d16fSTheodore Ts'o 	ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
30380031462bSMingming Cao 	ext4_ext_mark_uninitialized(ex);
30390031462bSMingming Cao 	ext4_ext_dirty(handle, inode, path + depth);
30400031462bSMingming Cao 	return err;
30410031462bSMingming Cao }
3042c7064ef1SJiaying Zhang static int ext4_convert_unwritten_extents_endio(handle_t *handle,
30430031462bSMingming Cao 					      struct inode *inode,
30440031462bSMingming Cao 					      struct ext4_ext_path *path)
30450031462bSMingming Cao {
30460031462bSMingming Cao 	struct ext4_extent *ex;
30470031462bSMingming Cao 	struct ext4_extent_header *eh;
30480031462bSMingming Cao 	int depth;
30490031462bSMingming Cao 	int err = 0;
30500031462bSMingming Cao 	int ret = 0;
30510031462bSMingming Cao 
30520031462bSMingming Cao 	depth = ext_depth(inode);
30530031462bSMingming Cao 	eh = path[depth].p_hdr;
30540031462bSMingming Cao 	ex = path[depth].p_ext;
30550031462bSMingming Cao 
30560031462bSMingming Cao 	err = ext4_ext_get_access(handle, inode, path + depth);
30570031462bSMingming Cao 	if (err)
30580031462bSMingming Cao 		goto out;
30590031462bSMingming Cao 	/* first mark the extent as initialized */
30600031462bSMingming Cao 	ext4_ext_mark_initialized(ex);
30610031462bSMingming Cao 
30620031462bSMingming Cao 	/*
30630031462bSMingming Cao 	 * We have to see if it can be merged with the extent
30640031462bSMingming Cao 	 * on the left.
30650031462bSMingming Cao 	 */
30660031462bSMingming Cao 	if (ex > EXT_FIRST_EXTENT(eh)) {
30670031462bSMingming Cao 		/*
30680031462bSMingming Cao 		 * To merge left, pass "ex - 1" to try_to_merge(),
30690031462bSMingming Cao 		 * since it merges towards right _only_.
30700031462bSMingming Cao 		 */
30710031462bSMingming Cao 		ret = ext4_ext_try_to_merge(inode, path, ex - 1);
30720031462bSMingming Cao 		if (ret) {
30730031462bSMingming Cao 			err = ext4_ext_correct_indexes(handle, inode, path);
30740031462bSMingming Cao 			if (err)
30750031462bSMingming Cao 				goto out;
30760031462bSMingming Cao 			depth = ext_depth(inode);
30770031462bSMingming Cao 			ex--;
30780031462bSMingming Cao 		}
30790031462bSMingming Cao 	}
30800031462bSMingming Cao 	/*
30810031462bSMingming Cao 	 * Try to Merge towards right.
30820031462bSMingming Cao 	 */
30830031462bSMingming Cao 	ret = ext4_ext_try_to_merge(inode, path, ex);
30840031462bSMingming Cao 	if (ret) {
30850031462bSMingming Cao 		err = ext4_ext_correct_indexes(handle, inode, path);
30860031462bSMingming Cao 		if (err)
30870031462bSMingming Cao 			goto out;
30880031462bSMingming Cao 		depth = ext_depth(inode);
30890031462bSMingming Cao 	}
30900031462bSMingming Cao 	/* Mark modified extent as dirty */
30910031462bSMingming Cao 	err = ext4_ext_dirty(handle, inode, path + depth);
30920031462bSMingming Cao out:
30930031462bSMingming Cao 	ext4_ext_show_leaf(inode, path);
30940031462bSMingming Cao 	return err;
30950031462bSMingming Cao }
30960031462bSMingming Cao 
3097515f41c3SAneesh Kumar K.V static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3098515f41c3SAneesh Kumar K.V 			sector_t block, int count)
3099515f41c3SAneesh Kumar K.V {
3100515f41c3SAneesh Kumar K.V 	int i;
3101515f41c3SAneesh Kumar K.V 	for (i = 0; i < count; i++)
3102515f41c3SAneesh Kumar K.V                 unmap_underlying_metadata(bdev, block + i);
3103515f41c3SAneesh Kumar K.V }
3104515f41c3SAneesh Kumar K.V 
310558590b06STheodore Ts'o /*
310658590b06STheodore Ts'o  * Handle EOFBLOCKS_FL flag, clearing it if necessary
310758590b06STheodore Ts'o  */
310858590b06STheodore Ts'o static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3109d002ebf1SEric Sandeen 			      ext4_lblk_t lblk,
311058590b06STheodore Ts'o 			      struct ext4_ext_path *path,
311158590b06STheodore Ts'o 			      unsigned int len)
311258590b06STheodore Ts'o {
311358590b06STheodore Ts'o 	int i, depth;
311458590b06STheodore Ts'o 	struct ext4_extent_header *eh;
311558590b06STheodore Ts'o 	struct ext4_extent *ex, *last_ex;
311658590b06STheodore Ts'o 
311758590b06STheodore Ts'o 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
311858590b06STheodore Ts'o 		return 0;
311958590b06STheodore Ts'o 
312058590b06STheodore Ts'o 	depth = ext_depth(inode);
312158590b06STheodore Ts'o 	eh = path[depth].p_hdr;
312258590b06STheodore Ts'o 	ex = path[depth].p_ext;
312358590b06STheodore Ts'o 
312458590b06STheodore Ts'o 	if (unlikely(!eh->eh_entries)) {
312558590b06STheodore Ts'o 		EXT4_ERROR_INODE(inode, "eh->eh_entries == 0 and "
312658590b06STheodore Ts'o 				 "EOFBLOCKS_FL set");
312758590b06STheodore Ts'o 		return -EIO;
312858590b06STheodore Ts'o 	}
312958590b06STheodore Ts'o 	last_ex = EXT_LAST_EXTENT(eh);
313058590b06STheodore Ts'o 	/*
313158590b06STheodore Ts'o 	 * We should clear the EOFBLOCKS_FL flag if we are writing the
313258590b06STheodore Ts'o 	 * last block in the last extent in the file.  We test this by
313358590b06STheodore Ts'o 	 * first checking to see if the caller to
313458590b06STheodore Ts'o 	 * ext4_ext_get_blocks() was interested in the last block (or
313558590b06STheodore Ts'o 	 * a block beyond the last block) in the current extent.  If
313658590b06STheodore Ts'o 	 * this turns out to be false, we can bail out from this
313758590b06STheodore Ts'o 	 * function immediately.
313858590b06STheodore Ts'o 	 */
3139d002ebf1SEric Sandeen 	if (lblk + len < le32_to_cpu(last_ex->ee_block) +
314058590b06STheodore Ts'o 	    ext4_ext_get_actual_len(last_ex))
314158590b06STheodore Ts'o 		return 0;
314258590b06STheodore Ts'o 	/*
314358590b06STheodore Ts'o 	 * If the caller does appear to be planning to write at or
314458590b06STheodore Ts'o 	 * beyond the end of the current extent, we then test to see
314558590b06STheodore Ts'o 	 * if the current extent is the last extent in the file, by
314658590b06STheodore Ts'o 	 * checking to make sure it was reached via the rightmost node
314758590b06STheodore Ts'o 	 * at each level of the tree.
314858590b06STheodore Ts'o 	 */
314958590b06STheodore Ts'o 	for (i = depth-1; i >= 0; i--)
315058590b06STheodore Ts'o 		if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
315158590b06STheodore Ts'o 			return 0;
315258590b06STheodore Ts'o 	ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
315358590b06STheodore Ts'o 	return ext4_mark_inode_dirty(handle, inode);
315458590b06STheodore Ts'o }
315558590b06STheodore Ts'o 
31560031462bSMingming Cao static int
31570031462bSMingming Cao ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
3158e35fd660STheodore Ts'o 			struct ext4_map_blocks *map,
31590031462bSMingming Cao 			struct ext4_ext_path *path, int flags,
3160e35fd660STheodore Ts'o 			unsigned int allocated, ext4_fsblk_t newblock)
31610031462bSMingming Cao {
31620031462bSMingming Cao 	int ret = 0;
31630031462bSMingming Cao 	int err = 0;
31648d5d02e6SMingming Cao 	ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
31650031462bSMingming Cao 
31660031462bSMingming Cao 	ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
31670031462bSMingming Cao 		  "block %llu, max_blocks %u, flags %d, allocated %u",
3168e35fd660STheodore Ts'o 		  inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
31690031462bSMingming Cao 		  flags, allocated);
31700031462bSMingming Cao 	ext4_ext_show_leaf(inode, path);
31710031462bSMingming Cao 
3172c7064ef1SJiaying Zhang 	/* get_block() before submit the IO, split the extent */
3173744692dcSJiaying Zhang 	if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3174e35fd660STheodore Ts'o 		ret = ext4_split_unwritten_extents(handle, inode, map,
3175e35fd660STheodore Ts'o 						   path, flags);
31765f524950SMingming 		/*
31775f524950SMingming 		 * Flag the inode(non aio case) or end_io struct (aio case)
31785f524950SMingming 		 * that this IO needs to convertion to written when IO is
31795f524950SMingming 		 * completed
31805f524950SMingming 		 */
3181e9e3bcecSEric Sandeen 		if (io && !(io->flag & EXT4_IO_END_UNWRITTEN)) {
3182bd2d0210STheodore Ts'o 			io->flag = EXT4_IO_END_UNWRITTEN;
3183e9e3bcecSEric Sandeen 			atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
3184e9e3bcecSEric Sandeen 		} else
318519f5fb7aSTheodore Ts'o 			ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3186744692dcSJiaying Zhang 		if (ext4_should_dioread_nolock(inode))
3187e35fd660STheodore Ts'o 			map->m_flags |= EXT4_MAP_UNINIT;
31880031462bSMingming Cao 		goto out;
31890031462bSMingming Cao 	}
3190c7064ef1SJiaying Zhang 	/* IO end_io complete, convert the filled extent to written */
3191744692dcSJiaying Zhang 	if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
3192c7064ef1SJiaying Zhang 		ret = ext4_convert_unwritten_extents_endio(handle, inode,
31930031462bSMingming Cao 							path);
319458590b06STheodore Ts'o 		if (ret >= 0) {
3195b436b9beSJan Kara 			ext4_update_inode_fsync_trans(handle, inode, 1);
3196d002ebf1SEric Sandeen 			err = check_eofblocks_fl(handle, inode, map->m_lblk,
3197d002ebf1SEric Sandeen 						 path, map->m_len);
319858590b06STheodore Ts'o 		} else
319958590b06STheodore Ts'o 			err = ret;
32000031462bSMingming Cao 		goto out2;
32010031462bSMingming Cao 	}
32020031462bSMingming Cao 	/* buffered IO case */
32030031462bSMingming Cao 	/*
32040031462bSMingming Cao 	 * repeat fallocate creation request
32050031462bSMingming Cao 	 * we already have an unwritten extent
32060031462bSMingming Cao 	 */
32070031462bSMingming Cao 	if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
32080031462bSMingming Cao 		goto map_out;
32090031462bSMingming Cao 
32100031462bSMingming Cao 	/* buffered READ or buffered write_begin() lookup */
32110031462bSMingming Cao 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
32120031462bSMingming Cao 		/*
32130031462bSMingming Cao 		 * We have blocks reserved already.  We
32140031462bSMingming Cao 		 * return allocated blocks so that delalloc
32150031462bSMingming Cao 		 * won't do block reservation for us.  But
32160031462bSMingming Cao 		 * the buffer head will be unmapped so that
32170031462bSMingming Cao 		 * a read from the block returns 0s.
32180031462bSMingming Cao 		 */
3219e35fd660STheodore Ts'o 		map->m_flags |= EXT4_MAP_UNWRITTEN;
32200031462bSMingming Cao 		goto out1;
32210031462bSMingming Cao 	}
32220031462bSMingming Cao 
32230031462bSMingming Cao 	/* buffered write, writepage time, convert*/
3224e35fd660STheodore Ts'o 	ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
322558590b06STheodore Ts'o 	if (ret >= 0) {
3226b436b9beSJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
3227d002ebf1SEric Sandeen 		err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
3228d002ebf1SEric Sandeen 					 map->m_len);
322958590b06STheodore Ts'o 		if (err < 0)
323058590b06STheodore Ts'o 			goto out2;
323158590b06STheodore Ts'o 	}
323258590b06STheodore Ts'o 
32330031462bSMingming Cao out:
32340031462bSMingming Cao 	if (ret <= 0) {
32350031462bSMingming Cao 		err = ret;
32360031462bSMingming Cao 		goto out2;
32370031462bSMingming Cao 	} else
32380031462bSMingming Cao 		allocated = ret;
3239e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_NEW;
3240515f41c3SAneesh Kumar K.V 	/*
3241515f41c3SAneesh Kumar K.V 	 * if we allocated more blocks than requested
3242515f41c3SAneesh Kumar K.V 	 * we need to make sure we unmap the extra block
3243515f41c3SAneesh Kumar K.V 	 * allocated. The actual needed block will get
3244515f41c3SAneesh Kumar K.V 	 * unmapped later when we find the buffer_head marked
3245515f41c3SAneesh Kumar K.V 	 * new.
3246515f41c3SAneesh Kumar K.V 	 */
3247e35fd660STheodore Ts'o 	if (allocated > map->m_len) {
3248515f41c3SAneesh Kumar K.V 		unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
3249e35fd660STheodore Ts'o 					newblock + map->m_len,
3250e35fd660STheodore Ts'o 					allocated - map->m_len);
3251e35fd660STheodore Ts'o 		allocated = map->m_len;
3252515f41c3SAneesh Kumar K.V 	}
32535f634d06SAneesh Kumar K.V 
32545f634d06SAneesh Kumar K.V 	/*
32555f634d06SAneesh Kumar K.V 	 * If we have done fallocate with the offset that is already
32565f634d06SAneesh Kumar K.V 	 * delayed allocated, we would have block reservation
32575f634d06SAneesh Kumar K.V 	 * and quota reservation done in the delayed write path.
32585f634d06SAneesh Kumar K.V 	 * But fallocate would have already updated quota and block
32595f634d06SAneesh Kumar K.V 	 * count for this offset. So cancel these reservation
32605f634d06SAneesh Kumar K.V 	 */
32611296cc85SAneesh Kumar K.V 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
32625f634d06SAneesh Kumar K.V 		ext4_da_update_reserve_space(inode, allocated, 0);
32635f634d06SAneesh Kumar K.V 
32640031462bSMingming Cao map_out:
3265e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_MAPPED;
32660031462bSMingming Cao out1:
3267e35fd660STheodore Ts'o 	if (allocated > map->m_len)
3268e35fd660STheodore Ts'o 		allocated = map->m_len;
32690031462bSMingming Cao 	ext4_ext_show_leaf(inode, path);
3270e35fd660STheodore Ts'o 	map->m_pblk = newblock;
3271e35fd660STheodore Ts'o 	map->m_len = allocated;
32720031462bSMingming Cao out2:
32730031462bSMingming Cao 	if (path) {
32740031462bSMingming Cao 		ext4_ext_drop_refs(path);
32750031462bSMingming Cao 		kfree(path);
32760031462bSMingming Cao 	}
32770031462bSMingming Cao 	return err ? err : allocated;
32780031462bSMingming Cao }
327958590b06STheodore Ts'o 
32800031462bSMingming Cao /*
3281f5ab0d1fSMingming Cao  * Block allocation/map/preallocation routine for extents based files
3282f5ab0d1fSMingming Cao  *
3283f5ab0d1fSMingming Cao  *
3284c278bfecSAneesh Kumar K.V  * Need to be called with
32850e855ac8SAneesh Kumar K.V  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
32860e855ac8SAneesh Kumar K.V  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
3287f5ab0d1fSMingming Cao  *
3288f5ab0d1fSMingming Cao  * return > 0, number of of blocks already mapped/allocated
3289f5ab0d1fSMingming Cao  *          if create == 0 and these are pre-allocated blocks
3290f5ab0d1fSMingming Cao  *          	buffer head is unmapped
3291f5ab0d1fSMingming Cao  *          otherwise blocks are mapped
3292f5ab0d1fSMingming Cao  *
3293f5ab0d1fSMingming Cao  * return = 0, if plain look up failed (blocks have not been allocated)
3294f5ab0d1fSMingming Cao  *          buffer head is unmapped
3295f5ab0d1fSMingming Cao  *
3296f5ab0d1fSMingming Cao  * return < 0, error case.
3297c278bfecSAneesh Kumar K.V  */
3298e35fd660STheodore Ts'o int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
3299e35fd660STheodore Ts'o 			struct ext4_map_blocks *map, int flags)
3300a86c6181SAlex Tomas {
3301a86c6181SAlex Tomas 	struct ext4_ext_path *path = NULL;
330256055d3aSAmit Arora 	struct ext4_extent_header *eh;
330358590b06STheodore Ts'o 	struct ext4_extent newex, *ex;
3304*0562e0baSJiaying Zhang 	ext4_fsblk_t newblock = 0;
3305b05e6ae5STheodore Ts'o 	int err = 0, depth, ret;
3306498e5f24STheodore Ts'o 	unsigned int allocated = 0;
3307c9de560dSAlex Tomas 	struct ext4_allocation_request ar;
33088d5d02e6SMingming Cao 	ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3309a86c6181SAlex Tomas 
331084fe3befSMingming 	ext_debug("blocks %u/%u requested for inode %lu\n",
3311e35fd660STheodore Ts'o 		  map->m_lblk, map->m_len, inode->i_ino);
3312*0562e0baSJiaying Zhang 	trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
3313a86c6181SAlex Tomas 
3314a86c6181SAlex Tomas 	/* check in cache */
3315b05e6ae5STheodore Ts'o 	if (ext4_ext_in_cache(inode, map->m_lblk, &newex)) {
3316b05e6ae5STheodore Ts'o 		if (!newex.ee_start_lo && !newex.ee_start_hi) {
3317c2177057STheodore Ts'o 			if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
331856055d3aSAmit Arora 				/*
331956055d3aSAmit Arora 				 * block isn't allocated yet and
332056055d3aSAmit Arora 				 * user doesn't want to allocate it
332156055d3aSAmit Arora 				 */
3322a86c6181SAlex Tomas 				goto out2;
3323a86c6181SAlex Tomas 			}
3324a86c6181SAlex Tomas 			/* we should allocate requested block */
3325b05e6ae5STheodore Ts'o 		} else {
3326a86c6181SAlex Tomas 			/* block is already allocated */
3327e35fd660STheodore Ts'o 			newblock = map->m_lblk
3328a86c6181SAlex Tomas 				   - le32_to_cpu(newex.ee_block)
3329bf89d16fSTheodore Ts'o 				   + ext4_ext_pblock(&newex);
3330d0d856e8SRandy Dunlap 			/* number of remaining blocks in the extent */
3331b939e376SAneesh Kumar K.V 			allocated = ext4_ext_get_actual_len(&newex) -
3332e35fd660STheodore Ts'o 				(map->m_lblk - le32_to_cpu(newex.ee_block));
3333a86c6181SAlex Tomas 			goto out;
3334a86c6181SAlex Tomas 		}
3335a86c6181SAlex Tomas 	}
3336a86c6181SAlex Tomas 
3337a86c6181SAlex Tomas 	/* find extent for this block */
3338e35fd660STheodore Ts'o 	path = ext4_ext_find_extent(inode, map->m_lblk, NULL);
3339a86c6181SAlex Tomas 	if (IS_ERR(path)) {
3340a86c6181SAlex Tomas 		err = PTR_ERR(path);
3341a86c6181SAlex Tomas 		path = NULL;
3342a86c6181SAlex Tomas 		goto out2;
3343a86c6181SAlex Tomas 	}
3344a86c6181SAlex Tomas 
3345a86c6181SAlex Tomas 	depth = ext_depth(inode);
3346a86c6181SAlex Tomas 
3347a86c6181SAlex Tomas 	/*
3348d0d856e8SRandy Dunlap 	 * consistent leaf must not be empty;
3349d0d856e8SRandy Dunlap 	 * this situation is possible, though, _during_ tree modification;
3350a86c6181SAlex Tomas 	 * this is why assert can't be put in ext4_ext_find_extent()
3351a86c6181SAlex Tomas 	 */
3352273df556SFrank Mayhar 	if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
3353273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode, "bad extent address "
3354f70f362bSTheodore Ts'o 				 "lblock: %lu, depth: %d pblock %lld",
3355f70f362bSTheodore Ts'o 				 (unsigned long) map->m_lblk, depth,
3356f70f362bSTheodore Ts'o 				 path[depth].p_block);
3357034fb4c9SSurbhi Palande 		err = -EIO;
3358034fb4c9SSurbhi Palande 		goto out2;
3359034fb4c9SSurbhi Palande 	}
336056055d3aSAmit Arora 	eh = path[depth].p_hdr;
3361a86c6181SAlex Tomas 
33627e028976SAvantika Mathur 	ex = path[depth].p_ext;
33637e028976SAvantika Mathur 	if (ex) {
3364725d26d3SAneesh Kumar K.V 		ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3365bf89d16fSTheodore Ts'o 		ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3366a2df2a63SAmit Arora 		unsigned short ee_len;
3367471d4011SSuparna Bhattacharya 
3368471d4011SSuparna Bhattacharya 		/*
3369471d4011SSuparna Bhattacharya 		 * Uninitialized extents are treated as holes, except that
337056055d3aSAmit Arora 		 * we split out initialized portions during a write.
3371471d4011SSuparna Bhattacharya 		 */
3372a2df2a63SAmit Arora 		ee_len = ext4_ext_get_actual_len(ex);
3373d0d856e8SRandy Dunlap 		/* if found extent covers block, simply return it */
3374e35fd660STheodore Ts'o 		if (in_range(map->m_lblk, ee_block, ee_len)) {
3375e35fd660STheodore Ts'o 			newblock = map->m_lblk - ee_block + ee_start;
3376d0d856e8SRandy Dunlap 			/* number of remaining blocks in the extent */
3377e35fd660STheodore Ts'o 			allocated = ee_len - (map->m_lblk - ee_block);
3378e35fd660STheodore Ts'o 			ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
3379a86c6181SAlex Tomas 				  ee_block, ee_len, newblock);
338056055d3aSAmit Arora 
3381a2df2a63SAmit Arora 			/* Do not put uninitialized extent in the cache */
338256055d3aSAmit Arora 			if (!ext4_ext_is_uninitialized(ex)) {
3383a2df2a63SAmit Arora 				ext4_ext_put_in_cache(inode, ee_block,
3384b05e6ae5STheodore Ts'o 							ee_len, ee_start);
3385a86c6181SAlex Tomas 				goto out;
3386a86c6181SAlex Tomas 			}
33870031462bSMingming Cao 			ret = ext4_ext_handle_uninitialized_extents(handle,
3388e35fd660STheodore Ts'o 					inode, map, path, flags, allocated,
3389e35fd660STheodore Ts'o 					newblock);
33900031462bSMingming Cao 			return ret;
339156055d3aSAmit Arora 		}
3392a86c6181SAlex Tomas 	}
3393a86c6181SAlex Tomas 
3394a86c6181SAlex Tomas 	/*
3395d0d856e8SRandy Dunlap 	 * requested block isn't allocated yet;
3396a86c6181SAlex Tomas 	 * we couldn't try to create block if create flag is zero
3397a86c6181SAlex Tomas 	 */
3398c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
339956055d3aSAmit Arora 		/*
340056055d3aSAmit Arora 		 * put just found gap into cache to speed up
340156055d3aSAmit Arora 		 * subsequent requests
340256055d3aSAmit Arora 		 */
3403e35fd660STheodore Ts'o 		ext4_ext_put_gap_in_cache(inode, path, map->m_lblk);
3404a86c6181SAlex Tomas 		goto out2;
3405a86c6181SAlex Tomas 	}
3406a86c6181SAlex Tomas 	/*
3407c2ea3fdeSTheodore Ts'o 	 * Okay, we need to do block allocation.
3408a86c6181SAlex Tomas 	 */
3409a86c6181SAlex Tomas 
3410c9de560dSAlex Tomas 	/* find neighbour allocated blocks */
3411e35fd660STheodore Ts'o 	ar.lleft = map->m_lblk;
3412c9de560dSAlex Tomas 	err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3413c9de560dSAlex Tomas 	if (err)
3414c9de560dSAlex Tomas 		goto out2;
3415e35fd660STheodore Ts'o 	ar.lright = map->m_lblk;
3416c9de560dSAlex Tomas 	err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
3417c9de560dSAlex Tomas 	if (err)
3418c9de560dSAlex Tomas 		goto out2;
341925d14f98SAmit Arora 
3420749269faSAmit Arora 	/*
3421749269faSAmit Arora 	 * See if request is beyond maximum number of blocks we can have in
3422749269faSAmit Arora 	 * a single extent. For an initialized extent this limit is
3423749269faSAmit Arora 	 * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
3424749269faSAmit Arora 	 * EXT_UNINIT_MAX_LEN.
3425749269faSAmit Arora 	 */
3426e35fd660STheodore Ts'o 	if (map->m_len > EXT_INIT_MAX_LEN &&
3427c2177057STheodore Ts'o 	    !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3428e35fd660STheodore Ts'o 		map->m_len = EXT_INIT_MAX_LEN;
3429e35fd660STheodore Ts'o 	else if (map->m_len > EXT_UNINIT_MAX_LEN &&
3430c2177057STheodore Ts'o 		 (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3431e35fd660STheodore Ts'o 		map->m_len = EXT_UNINIT_MAX_LEN;
3432749269faSAmit Arora 
3433e35fd660STheodore Ts'o 	/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
3434e35fd660STheodore Ts'o 	newex.ee_block = cpu_to_le32(map->m_lblk);
3435e35fd660STheodore Ts'o 	newex.ee_len = cpu_to_le16(map->m_len);
343625d14f98SAmit Arora 	err = ext4_ext_check_overlap(inode, &newex, path);
343725d14f98SAmit Arora 	if (err)
3438b939e376SAneesh Kumar K.V 		allocated = ext4_ext_get_actual_len(&newex);
343925d14f98SAmit Arora 	else
3440e35fd660STheodore Ts'o 		allocated = map->m_len;
3441c9de560dSAlex Tomas 
3442c9de560dSAlex Tomas 	/* allocate new block */
3443c9de560dSAlex Tomas 	ar.inode = inode;
3444e35fd660STheodore Ts'o 	ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
3445e35fd660STheodore Ts'o 	ar.logical = map->m_lblk;
3446c9de560dSAlex Tomas 	ar.len = allocated;
3447c9de560dSAlex Tomas 	if (S_ISREG(inode->i_mode))
3448c9de560dSAlex Tomas 		ar.flags = EXT4_MB_HINT_DATA;
3449c9de560dSAlex Tomas 	else
3450c9de560dSAlex Tomas 		/* disable in-core preallocation for non-regular files */
3451c9de560dSAlex Tomas 		ar.flags = 0;
3452c9de560dSAlex Tomas 	newblock = ext4_mb_new_blocks(handle, &ar, &err);
3453a86c6181SAlex Tomas 	if (!newblock)
3454a86c6181SAlex Tomas 		goto out2;
345584fe3befSMingming 	ext_debug("allocate new block: goal %llu, found %llu/%u\n",
3456498e5f24STheodore Ts'o 		  ar.goal, newblock, allocated);
3457a86c6181SAlex Tomas 
3458a86c6181SAlex Tomas 	/* try to insert new extent into found leaf and return */
3459f65e6fbaSAlex Tomas 	ext4_ext_store_pblock(&newex, newblock);
3460c9de560dSAlex Tomas 	newex.ee_len = cpu_to_le16(ar.len);
34618d5d02e6SMingming Cao 	/* Mark uninitialized */
34628d5d02e6SMingming Cao 	if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
3463a2df2a63SAmit Arora 		ext4_ext_mark_uninitialized(&newex);
34648d5d02e6SMingming Cao 		/*
3465744692dcSJiaying Zhang 		 * io_end structure was created for every IO write to an
3466744692dcSJiaying Zhang 		 * uninitialized extent. To avoid unecessary conversion,
3467744692dcSJiaying Zhang 		 * here we flag the IO that really needs the conversion.
34685f524950SMingming 		 * For non asycn direct IO case, flag the inode state
34695f524950SMingming 		 * that we need to perform convertion when IO is done.
34708d5d02e6SMingming Cao 		 */
3471744692dcSJiaying Zhang 		if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3472e9e3bcecSEric Sandeen 			if (io && !(io->flag & EXT4_IO_END_UNWRITTEN)) {
3473bd2d0210STheodore Ts'o 				io->flag = EXT4_IO_END_UNWRITTEN;
3474e9e3bcecSEric Sandeen 				atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
3475e9e3bcecSEric Sandeen 			} else
347619f5fb7aSTheodore Ts'o 				ext4_set_inode_state(inode,
347719f5fb7aSTheodore Ts'o 						     EXT4_STATE_DIO_UNWRITTEN);
34785f524950SMingming 		}
3479744692dcSJiaying Zhang 		if (ext4_should_dioread_nolock(inode))
3480e35fd660STheodore Ts'o 			map->m_flags |= EXT4_MAP_UNINIT;
34818d5d02e6SMingming Cao 	}
3482c8d46e41SJiaying Zhang 
3483d002ebf1SEric Sandeen 	err = check_eofblocks_fl(handle, inode, map->m_lblk, path, ar.len);
348458590b06STheodore Ts'o 	if (err)
3485273df556SFrank Mayhar 		goto out2;
348658590b06STheodore Ts'o 
34870031462bSMingming Cao 	err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
3488315054f0SAlex Tomas 	if (err) {
3489315054f0SAlex Tomas 		/* free data blocks we just allocated */
3490c9de560dSAlex Tomas 		/* not a good idea to call discard here directly,
3491c9de560dSAlex Tomas 		 * but otherwise we'd need to call it every free() */
3492c2ea3fdeSTheodore Ts'o 		ext4_discard_preallocations(inode);
34937dc57615SPeter Huewe 		ext4_free_blocks(handle, inode, NULL, ext4_ext_pblock(&newex),
3494b939e376SAneesh Kumar K.V 				 ext4_ext_get_actual_len(&newex), 0);
3495a86c6181SAlex Tomas 		goto out2;
3496315054f0SAlex Tomas 	}
3497a86c6181SAlex Tomas 
3498a86c6181SAlex Tomas 	/* previous routine could use block we allocated */
3499bf89d16fSTheodore Ts'o 	newblock = ext4_ext_pblock(&newex);
3500b939e376SAneesh Kumar K.V 	allocated = ext4_ext_get_actual_len(&newex);
3501e35fd660STheodore Ts'o 	if (allocated > map->m_len)
3502e35fd660STheodore Ts'o 		allocated = map->m_len;
3503e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_NEW;
3504a86c6181SAlex Tomas 
3505b436b9beSJan Kara 	/*
35065f634d06SAneesh Kumar K.V 	 * Update reserved blocks/metadata blocks after successful
35075f634d06SAneesh Kumar K.V 	 * block allocation which had been deferred till now.
35085f634d06SAneesh Kumar K.V 	 */
35091296cc85SAneesh Kumar K.V 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
35105f634d06SAneesh Kumar K.V 		ext4_da_update_reserve_space(inode, allocated, 1);
35115f634d06SAneesh Kumar K.V 
35125f634d06SAneesh Kumar K.V 	/*
3513b436b9beSJan Kara 	 * Cache the extent and update transaction to commit on fdatasync only
3514b436b9beSJan Kara 	 * when it is _not_ an uninitialized extent.
3515b436b9beSJan Kara 	 */
3516b436b9beSJan Kara 	if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
3517b05e6ae5STheodore Ts'o 		ext4_ext_put_in_cache(inode, map->m_lblk, allocated, newblock);
3518b436b9beSJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
3519b436b9beSJan Kara 	} else
3520b436b9beSJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 0);
3521a86c6181SAlex Tomas out:
3522e35fd660STheodore Ts'o 	if (allocated > map->m_len)
3523e35fd660STheodore Ts'o 		allocated = map->m_len;
3524a86c6181SAlex Tomas 	ext4_ext_show_leaf(inode, path);
3525e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_MAPPED;
3526e35fd660STheodore Ts'o 	map->m_pblk = newblock;
3527e35fd660STheodore Ts'o 	map->m_len = allocated;
3528a86c6181SAlex Tomas out2:
3529a86c6181SAlex Tomas 	if (path) {
3530a86c6181SAlex Tomas 		ext4_ext_drop_refs(path);
3531a86c6181SAlex Tomas 		kfree(path);
3532a86c6181SAlex Tomas 	}
3533*0562e0baSJiaying Zhang 	trace_ext4_ext_map_blocks_exit(inode, map->m_lblk,
3534*0562e0baSJiaying Zhang 		newblock, map->m_len, err ? err : allocated);
3535a86c6181SAlex Tomas 	return err ? err : allocated;
3536a86c6181SAlex Tomas }
3537a86c6181SAlex Tomas 
3538cf108bcaSJan Kara void ext4_ext_truncate(struct inode *inode)
3539a86c6181SAlex Tomas {
3540a86c6181SAlex Tomas 	struct address_space *mapping = inode->i_mapping;
3541a86c6181SAlex Tomas 	struct super_block *sb = inode->i_sb;
3542725d26d3SAneesh Kumar K.V 	ext4_lblk_t last_block;
3543a86c6181SAlex Tomas 	handle_t *handle;
3544a86c6181SAlex Tomas 	int err = 0;
3545a86c6181SAlex Tomas 
3546a86c6181SAlex Tomas 	/*
35473889fd57SJiaying Zhang 	 * finish any pending end_io work so we won't run the risk of
35483889fd57SJiaying Zhang 	 * converting any truncated blocks to initialized later
35493889fd57SJiaying Zhang 	 */
35503889fd57SJiaying Zhang 	ext4_flush_completed_IO(inode);
35513889fd57SJiaying Zhang 
35523889fd57SJiaying Zhang 	/*
3553a86c6181SAlex Tomas 	 * probably first extent we're gonna free will be last in block
3554a86c6181SAlex Tomas 	 */
3555f3bd1f3fSMingming Cao 	err = ext4_writepage_trans_blocks(inode);
3556a86c6181SAlex Tomas 	handle = ext4_journal_start(inode, err);
3557cf108bcaSJan Kara 	if (IS_ERR(handle))
3558a86c6181SAlex Tomas 		return;
3559a86c6181SAlex Tomas 
3560cf108bcaSJan Kara 	if (inode->i_size & (sb->s_blocksize - 1))
3561cf108bcaSJan Kara 		ext4_block_truncate_page(handle, mapping, inode->i_size);
3562a86c6181SAlex Tomas 
35639ddfc3dcSJan Kara 	if (ext4_orphan_add(handle, inode))
35649ddfc3dcSJan Kara 		goto out_stop;
35659ddfc3dcSJan Kara 
35660e855ac8SAneesh Kumar K.V 	down_write(&EXT4_I(inode)->i_data_sem);
3567a86c6181SAlex Tomas 	ext4_ext_invalidate_cache(inode);
3568a86c6181SAlex Tomas 
3569c2ea3fdeSTheodore Ts'o 	ext4_discard_preallocations(inode);
3570c9de560dSAlex Tomas 
3571a86c6181SAlex Tomas 	/*
3572d0d856e8SRandy Dunlap 	 * TODO: optimization is possible here.
3573d0d856e8SRandy Dunlap 	 * Probably we need not scan at all,
3574d0d856e8SRandy Dunlap 	 * because page truncation is enough.
3575a86c6181SAlex Tomas 	 */
3576a86c6181SAlex Tomas 
3577a86c6181SAlex Tomas 	/* we have to know where to truncate from in crash case */
3578a86c6181SAlex Tomas 	EXT4_I(inode)->i_disksize = inode->i_size;
3579a86c6181SAlex Tomas 	ext4_mark_inode_dirty(handle, inode);
3580a86c6181SAlex Tomas 
3581a86c6181SAlex Tomas 	last_block = (inode->i_size + sb->s_blocksize - 1)
3582a86c6181SAlex Tomas 			>> EXT4_BLOCK_SIZE_BITS(sb);
3583a86c6181SAlex Tomas 	err = ext4_ext_remove_space(inode, last_block);
3584a86c6181SAlex Tomas 
3585a86c6181SAlex Tomas 	/* In a multi-transaction truncate, we only make the final
358656055d3aSAmit Arora 	 * transaction synchronous.
358756055d3aSAmit Arora 	 */
3588a86c6181SAlex Tomas 	if (IS_SYNC(inode))
35890390131bSFrank Mayhar 		ext4_handle_sync(handle);
3590a86c6181SAlex Tomas 
3591a86c6181SAlex Tomas out_stop:
35929ddfc3dcSJan Kara 	up_write(&EXT4_I(inode)->i_data_sem);
3593a86c6181SAlex Tomas 	/*
3594d0d856e8SRandy Dunlap 	 * If this was a simple ftruncate() and the file will remain alive,
3595a86c6181SAlex Tomas 	 * then we need to clear up the orphan record which we created above.
3596a86c6181SAlex Tomas 	 * However, if this was a real unlink then we were called by
3597a86c6181SAlex Tomas 	 * ext4_delete_inode(), and we allow that function to clean up the
3598a86c6181SAlex Tomas 	 * orphan info for us.
3599a86c6181SAlex Tomas 	 */
3600a86c6181SAlex Tomas 	if (inode->i_nlink)
3601a86c6181SAlex Tomas 		ext4_orphan_del(handle, inode);
3602a86c6181SAlex Tomas 
3603ef737728SSolofo Ramangalahy 	inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3604ef737728SSolofo Ramangalahy 	ext4_mark_inode_dirty(handle, inode);
3605a86c6181SAlex Tomas 	ext4_journal_stop(handle);
3606a86c6181SAlex Tomas }
3607a86c6181SAlex Tomas 
3608fd28784aSAneesh Kumar K.V static void ext4_falloc_update_inode(struct inode *inode,
3609fd28784aSAneesh Kumar K.V 				int mode, loff_t new_size, int update_ctime)
3610fd28784aSAneesh Kumar K.V {
3611fd28784aSAneesh Kumar K.V 	struct timespec now;
3612fd28784aSAneesh Kumar K.V 
3613fd28784aSAneesh Kumar K.V 	if (update_ctime) {
3614fd28784aSAneesh Kumar K.V 		now = current_fs_time(inode->i_sb);
3615fd28784aSAneesh Kumar K.V 		if (!timespec_equal(&inode->i_ctime, &now))
3616fd28784aSAneesh Kumar K.V 			inode->i_ctime = now;
3617fd28784aSAneesh Kumar K.V 	}
3618fd28784aSAneesh Kumar K.V 	/*
3619fd28784aSAneesh Kumar K.V 	 * Update only when preallocation was requested beyond
3620fd28784aSAneesh Kumar K.V 	 * the file size.
3621fd28784aSAneesh Kumar K.V 	 */
3622cf17fea6SAneesh Kumar K.V 	if (!(mode & FALLOC_FL_KEEP_SIZE)) {
3623cf17fea6SAneesh Kumar K.V 		if (new_size > i_size_read(inode))
3624fd28784aSAneesh Kumar K.V 			i_size_write(inode, new_size);
3625cf17fea6SAneesh Kumar K.V 		if (new_size > EXT4_I(inode)->i_disksize)
3626cf17fea6SAneesh Kumar K.V 			ext4_update_i_disksize(inode, new_size);
3627c8d46e41SJiaying Zhang 	} else {
3628c8d46e41SJiaying Zhang 		/*
3629c8d46e41SJiaying Zhang 		 * Mark that we allocate beyond EOF so the subsequent truncate
3630c8d46e41SJiaying Zhang 		 * can proceed even if the new size is the same as i_size.
3631c8d46e41SJiaying Zhang 		 */
3632c8d46e41SJiaying Zhang 		if (new_size > i_size_read(inode))
363312e9b892SDmitry Monakhov 			ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3634fd28784aSAneesh Kumar K.V 	}
3635fd28784aSAneesh Kumar K.V 
3636fd28784aSAneesh Kumar K.V }
3637fd28784aSAneesh Kumar K.V 
3638a2df2a63SAmit Arora /*
36392fe17c10SChristoph Hellwig  * preallocate space for a file. This implements ext4's fallocate file
3640a2df2a63SAmit Arora  * operation, which gets called from sys_fallocate system call.
3641a2df2a63SAmit Arora  * For block-mapped files, posix_fallocate should fall back to the method
3642a2df2a63SAmit Arora  * of writing zeroes to the required new blocks (the same behavior which is
3643a2df2a63SAmit Arora  * expected for file systems which do not support fallocate() system call).
3644a2df2a63SAmit Arora  */
36452fe17c10SChristoph Hellwig long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
3646a2df2a63SAmit Arora {
36472fe17c10SChristoph Hellwig 	struct inode *inode = file->f_path.dentry->d_inode;
3648a2df2a63SAmit Arora 	handle_t *handle;
3649fd28784aSAneesh Kumar K.V 	loff_t new_size;
3650498e5f24STheodore Ts'o 	unsigned int max_blocks;
3651a2df2a63SAmit Arora 	int ret = 0;
3652a2df2a63SAmit Arora 	int ret2 = 0;
3653a2df2a63SAmit Arora 	int retries = 0;
36542ed88685STheodore Ts'o 	struct ext4_map_blocks map;
3655a2df2a63SAmit Arora 	unsigned int credits, blkbits = inode->i_blkbits;
3656a2df2a63SAmit Arora 
3657d6dc8462SJosef Bacik 	/* We only support the FALLOC_FL_KEEP_SIZE mode */
365864c23e86SChristoph Hellwig 	if (mode & ~FALLOC_FL_KEEP_SIZE)
3659d6dc8462SJosef Bacik 		return -EOPNOTSUPP;
3660d6dc8462SJosef Bacik 
3661a2df2a63SAmit Arora 	/*
3662a2df2a63SAmit Arora 	 * currently supporting (pre)allocate mode for extent-based
3663a2df2a63SAmit Arora 	 * files _only_
3664a2df2a63SAmit Arora 	 */
366512e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
3666a2df2a63SAmit Arora 		return -EOPNOTSUPP;
3667a2df2a63SAmit Arora 
3668*0562e0baSJiaying Zhang 	trace_ext4_fallocate_enter(inode, offset, len, mode);
36692ed88685STheodore Ts'o 	map.m_lblk = offset >> blkbits;
3670fd28784aSAneesh Kumar K.V 	/*
3671fd28784aSAneesh Kumar K.V 	 * We can't just convert len to max_blocks because
3672fd28784aSAneesh Kumar K.V 	 * If blocksize = 4096 offset = 3072 and len = 2048
3673fd28784aSAneesh Kumar K.V 	 */
3674a2df2a63SAmit Arora 	max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
36752ed88685STheodore Ts'o 		- map.m_lblk;
3676a2df2a63SAmit Arora 	/*
3677f3bd1f3fSMingming Cao 	 * credits to insert 1 extent into extent tree
3678a2df2a63SAmit Arora 	 */
3679f3bd1f3fSMingming Cao 	credits = ext4_chunk_trans_blocks(inode, max_blocks);
368055bd725aSAneesh Kumar K.V 	mutex_lock(&inode->i_mutex);
36816d19c42bSNikanth Karthikesan 	ret = inode_newsize_ok(inode, (len + offset));
36826d19c42bSNikanth Karthikesan 	if (ret) {
36836d19c42bSNikanth Karthikesan 		mutex_unlock(&inode->i_mutex);
3684*0562e0baSJiaying Zhang 		trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
36856d19c42bSNikanth Karthikesan 		return ret;
36866d19c42bSNikanth Karthikesan 	}
3687a2df2a63SAmit Arora retry:
3688a2df2a63SAmit Arora 	while (ret >= 0 && ret < max_blocks) {
36892ed88685STheodore Ts'o 		map.m_lblk = map.m_lblk + ret;
36902ed88685STheodore Ts'o 		map.m_len = max_blocks = max_blocks - ret;
3691a2df2a63SAmit Arora 		handle = ext4_journal_start(inode, credits);
3692a2df2a63SAmit Arora 		if (IS_ERR(handle)) {
3693a2df2a63SAmit Arora 			ret = PTR_ERR(handle);
3694a2df2a63SAmit Arora 			break;
3695a2df2a63SAmit Arora 		}
36962ed88685STheodore Ts'o 		ret = ext4_map_blocks(handle, inode, &map,
3697c2177057STheodore Ts'o 				      EXT4_GET_BLOCKS_CREATE_UNINIT_EXT);
3698221879c9SAneesh Kumar K.V 		if (ret <= 0) {
36992c98615dSAneesh Kumar K.V #ifdef EXT4FS_DEBUG
37002c98615dSAneesh Kumar K.V 			WARN_ON(ret <= 0);
3701e35fd660STheodore Ts'o 			printk(KERN_ERR "%s: ext4_ext_map_blocks "
37022c98615dSAneesh Kumar K.V 				    "returned error inode#%lu, block=%u, "
37039fd9784cSThadeu Lima de Souza Cascardo 				    "max_blocks=%u", __func__,
3704a6371b63SKazuya Mio 				    inode->i_ino, map.m_lblk, max_blocks);
37052c98615dSAneesh Kumar K.V #endif
3706a2df2a63SAmit Arora 			ext4_mark_inode_dirty(handle, inode);
3707a2df2a63SAmit Arora 			ret2 = ext4_journal_stop(handle);
3708a2df2a63SAmit Arora 			break;
3709a2df2a63SAmit Arora 		}
37102ed88685STheodore Ts'o 		if ((map.m_lblk + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
3711fd28784aSAneesh Kumar K.V 						blkbits) >> blkbits))
3712fd28784aSAneesh Kumar K.V 			new_size = offset + len;
3713fd28784aSAneesh Kumar K.V 		else
37142ed88685STheodore Ts'o 			new_size = (map.m_lblk + ret) << blkbits;
3715a2df2a63SAmit Arora 
3716fd28784aSAneesh Kumar K.V 		ext4_falloc_update_inode(inode, mode, new_size,
37172ed88685STheodore Ts'o 					 (map.m_flags & EXT4_MAP_NEW));
3718a2df2a63SAmit Arora 		ext4_mark_inode_dirty(handle, inode);
3719a2df2a63SAmit Arora 		ret2 = ext4_journal_stop(handle);
3720a2df2a63SAmit Arora 		if (ret2)
3721a2df2a63SAmit Arora 			break;
3722a2df2a63SAmit Arora 	}
3723fd28784aSAneesh Kumar K.V 	if (ret == -ENOSPC &&
3724fd28784aSAneesh Kumar K.V 			ext4_should_retry_alloc(inode->i_sb, &retries)) {
3725fd28784aSAneesh Kumar K.V 		ret = 0;
3726a2df2a63SAmit Arora 		goto retry;
3727a2df2a63SAmit Arora 	}
372855bd725aSAneesh Kumar K.V 	mutex_unlock(&inode->i_mutex);
3729*0562e0baSJiaying Zhang 	trace_ext4_fallocate_exit(inode, offset, max_blocks,
3730*0562e0baSJiaying Zhang 				ret > 0 ? ret2 : ret);
3731a2df2a63SAmit Arora 	return ret > 0 ? ret2 : ret;
3732a2df2a63SAmit Arora }
37336873fa0dSEric Sandeen 
37346873fa0dSEric Sandeen /*
37350031462bSMingming Cao  * This function convert a range of blocks to written extents
37360031462bSMingming Cao  * The caller of this function will pass the start offset and the size.
37370031462bSMingming Cao  * all unwritten extents within this range will be converted to
37380031462bSMingming Cao  * written extents.
37390031462bSMingming Cao  *
37400031462bSMingming Cao  * This function is called from the direct IO end io call back
37410031462bSMingming Cao  * function, to convert the fallocated extents after IO is completed.
3742109f5565SMingming  * Returns 0 on success.
37430031462bSMingming Cao  */
37440031462bSMingming Cao int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
3745a1de02dcSEric Sandeen 				    ssize_t len)
37460031462bSMingming Cao {
37470031462bSMingming Cao 	handle_t *handle;
37480031462bSMingming Cao 	unsigned int max_blocks;
37490031462bSMingming Cao 	int ret = 0;
37500031462bSMingming Cao 	int ret2 = 0;
37512ed88685STheodore Ts'o 	struct ext4_map_blocks map;
37520031462bSMingming Cao 	unsigned int credits, blkbits = inode->i_blkbits;
37530031462bSMingming Cao 
37542ed88685STheodore Ts'o 	map.m_lblk = offset >> blkbits;
37550031462bSMingming Cao 	/*
37560031462bSMingming Cao 	 * We can't just convert len to max_blocks because
37570031462bSMingming Cao 	 * If blocksize = 4096 offset = 3072 and len = 2048
37580031462bSMingming Cao 	 */
37592ed88685STheodore Ts'o 	max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
37602ed88685STheodore Ts'o 		      map.m_lblk);
37610031462bSMingming Cao 	/*
37620031462bSMingming Cao 	 * credits to insert 1 extent into extent tree
37630031462bSMingming Cao 	 */
37640031462bSMingming Cao 	credits = ext4_chunk_trans_blocks(inode, max_blocks);
37650031462bSMingming Cao 	while (ret >= 0 && ret < max_blocks) {
37662ed88685STheodore Ts'o 		map.m_lblk += ret;
37672ed88685STheodore Ts'o 		map.m_len = (max_blocks -= ret);
37680031462bSMingming Cao 		handle = ext4_journal_start(inode, credits);
37690031462bSMingming Cao 		if (IS_ERR(handle)) {
37700031462bSMingming Cao 			ret = PTR_ERR(handle);
37710031462bSMingming Cao 			break;
37720031462bSMingming Cao 		}
37732ed88685STheodore Ts'o 		ret = ext4_map_blocks(handle, inode, &map,
3774c7064ef1SJiaying Zhang 				      EXT4_GET_BLOCKS_IO_CONVERT_EXT);
37750031462bSMingming Cao 		if (ret <= 0) {
37760031462bSMingming Cao 			WARN_ON(ret <= 0);
3777e35fd660STheodore Ts'o 			printk(KERN_ERR "%s: ext4_ext_map_blocks "
37780031462bSMingming Cao 				    "returned error inode#%lu, block=%u, "
37790031462bSMingming Cao 				    "max_blocks=%u", __func__,
37802ed88685STheodore Ts'o 				    inode->i_ino, map.m_lblk, map.m_len);
37810031462bSMingming Cao 		}
37820031462bSMingming Cao 		ext4_mark_inode_dirty(handle, inode);
37830031462bSMingming Cao 		ret2 = ext4_journal_stop(handle);
37840031462bSMingming Cao 		if (ret <= 0 || ret2 )
37850031462bSMingming Cao 			break;
37860031462bSMingming Cao 	}
37870031462bSMingming Cao 	return ret > 0 ? ret2 : ret;
37880031462bSMingming Cao }
37896d9c85ebSYongqiang Yang 
37900031462bSMingming Cao /*
37916873fa0dSEric Sandeen  * Callback function called for each extent to gather FIEMAP information.
37926873fa0dSEric Sandeen  */
37933a06d778SAneesh Kumar K.V static int ext4_ext_fiemap_cb(struct inode *inode, struct ext4_ext_path *path,
37946873fa0dSEric Sandeen 		       struct ext4_ext_cache *newex, struct ext4_extent *ex,
37956873fa0dSEric Sandeen 		       void *data)
37966873fa0dSEric Sandeen {
37976873fa0dSEric Sandeen 	__u64	logical;
37986873fa0dSEric Sandeen 	__u64	physical;
37996873fa0dSEric Sandeen 	__u64	length;
38006d9c85ebSYongqiang Yang 	loff_t	size;
38016873fa0dSEric Sandeen 	__u32	flags = 0;
38026d9c85ebSYongqiang Yang 	int		ret = 0;
38036d9c85ebSYongqiang Yang 	struct fiemap_extent_info *fieinfo = data;
38046d9c85ebSYongqiang Yang 	unsigned char blksize_bits;
38056873fa0dSEric Sandeen 
38066d9c85ebSYongqiang Yang 	blksize_bits = inode->i_sb->s_blocksize_bits;
38076873fa0dSEric Sandeen 	logical = (__u64)newex->ec_block << blksize_bits;
38086873fa0dSEric Sandeen 
3809b05e6ae5STheodore Ts'o 	if (newex->ec_start == 0) {
38106d9c85ebSYongqiang Yang 		/*
38116d9c85ebSYongqiang Yang 		 * No extent in extent-tree contains block @newex->ec_start,
38126d9c85ebSYongqiang Yang 		 * then the block may stay in 1)a hole or 2)delayed-extent.
38136d9c85ebSYongqiang Yang 		 *
38146d9c85ebSYongqiang Yang 		 * Holes or delayed-extents are processed as follows.
38156d9c85ebSYongqiang Yang 		 * 1. lookup dirty pages with specified range in pagecache.
38166d9c85ebSYongqiang Yang 		 *    If no page is got, then there is no delayed-extent and
38176d9c85ebSYongqiang Yang 		 *    return with EXT_CONTINUE.
38186d9c85ebSYongqiang Yang 		 * 2. find the 1st mapped buffer,
38196d9c85ebSYongqiang Yang 		 * 3. check if the mapped buffer is both in the request range
38206d9c85ebSYongqiang Yang 		 *    and a delayed buffer. If not, there is no delayed-extent,
38216d9c85ebSYongqiang Yang 		 *    then return.
38226d9c85ebSYongqiang Yang 		 * 4. a delayed-extent is found, the extent will be collected.
38236d9c85ebSYongqiang Yang 		 */
38246d9c85ebSYongqiang Yang 		ext4_lblk_t	end = 0;
38256d9c85ebSYongqiang Yang 		pgoff_t		last_offset;
38266873fa0dSEric Sandeen 		pgoff_t		offset;
38276d9c85ebSYongqiang Yang 		pgoff_t		index;
38286d9c85ebSYongqiang Yang 		struct page	**pages = NULL;
38296873fa0dSEric Sandeen 		struct buffer_head *bh = NULL;
38306d9c85ebSYongqiang Yang 		struct buffer_head *head = NULL;
38316d9c85ebSYongqiang Yang 		unsigned int nr_pages = PAGE_SIZE / sizeof(struct page *);
38326d9c85ebSYongqiang Yang 
38336d9c85ebSYongqiang Yang 		pages = kmalloc(PAGE_SIZE, GFP_KERNEL);
38346d9c85ebSYongqiang Yang 		if (pages == NULL)
38356d9c85ebSYongqiang Yang 			return -ENOMEM;
38366873fa0dSEric Sandeen 
38376873fa0dSEric Sandeen 		offset = logical >> PAGE_SHIFT;
38386d9c85ebSYongqiang Yang repeat:
38396d9c85ebSYongqiang Yang 		last_offset = offset;
38406d9c85ebSYongqiang Yang 		head = NULL;
38416d9c85ebSYongqiang Yang 		ret = find_get_pages_tag(inode->i_mapping, &offset,
38426d9c85ebSYongqiang Yang 					PAGECACHE_TAG_DIRTY, nr_pages, pages);
38436873fa0dSEric Sandeen 
38446d9c85ebSYongqiang Yang 		if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
38456d9c85ebSYongqiang Yang 			/* First time, try to find a mapped buffer. */
38466d9c85ebSYongqiang Yang 			if (ret == 0) {
38476d9c85ebSYongqiang Yang out:
38486d9c85ebSYongqiang Yang 				for (index = 0; index < ret; index++)
38496d9c85ebSYongqiang Yang 					page_cache_release(pages[index]);
38506d9c85ebSYongqiang Yang 				/* just a hole. */
38516d9c85ebSYongqiang Yang 				kfree(pages);
38526873fa0dSEric Sandeen 				return EXT_CONTINUE;
38536873fa0dSEric Sandeen 			}
38546d9c85ebSYongqiang Yang 
38556d9c85ebSYongqiang Yang 			/* Try to find the 1st mapped buffer. */
38566d9c85ebSYongqiang Yang 			end = ((__u64)pages[0]->index << PAGE_SHIFT) >>
38576d9c85ebSYongqiang Yang 				  blksize_bits;
38586d9c85ebSYongqiang Yang 			if (!page_has_buffers(pages[0]))
38596d9c85ebSYongqiang Yang 				goto out;
38606d9c85ebSYongqiang Yang 			head = page_buffers(pages[0]);
38616d9c85ebSYongqiang Yang 			if (!head)
38626d9c85ebSYongqiang Yang 				goto out;
38636d9c85ebSYongqiang Yang 
38646d9c85ebSYongqiang Yang 			bh = head;
38656d9c85ebSYongqiang Yang 			do {
38666d9c85ebSYongqiang Yang 				if (buffer_mapped(bh)) {
38676d9c85ebSYongqiang Yang 					/* get the 1st mapped buffer. */
38686d9c85ebSYongqiang Yang 					if (end > newex->ec_block +
38696d9c85ebSYongqiang Yang 						newex->ec_len)
38706d9c85ebSYongqiang Yang 						/* The buffer is out of
38716d9c85ebSYongqiang Yang 						 * the request range.
38726d9c85ebSYongqiang Yang 						 */
38736d9c85ebSYongqiang Yang 						goto out;
38746d9c85ebSYongqiang Yang 					goto found_mapped_buffer;
38756d9c85ebSYongqiang Yang 				}
38766d9c85ebSYongqiang Yang 				bh = bh->b_this_page;
38776d9c85ebSYongqiang Yang 				end++;
38786d9c85ebSYongqiang Yang 			} while (bh != head);
38796d9c85ebSYongqiang Yang 
38806d9c85ebSYongqiang Yang 			/* No mapped buffer found. */
38816d9c85ebSYongqiang Yang 			goto out;
38826d9c85ebSYongqiang Yang 		} else {
38836d9c85ebSYongqiang Yang 			/*Find contiguous delayed buffers. */
38846d9c85ebSYongqiang Yang 			if (ret > 0 && pages[0]->index == last_offset)
38856d9c85ebSYongqiang Yang 				head = page_buffers(pages[0]);
38866d9c85ebSYongqiang Yang 			bh = head;
38876d9c85ebSYongqiang Yang 		}
38886d9c85ebSYongqiang Yang 
38896d9c85ebSYongqiang Yang found_mapped_buffer:
38906d9c85ebSYongqiang Yang 		if (bh != NULL && buffer_delay(bh)) {
38916d9c85ebSYongqiang Yang 			/* 1st or contiguous delayed buffer found. */
38926d9c85ebSYongqiang Yang 			if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
38936d9c85ebSYongqiang Yang 				/*
38946d9c85ebSYongqiang Yang 				 * 1st delayed buffer found, record
38956d9c85ebSYongqiang Yang 				 * the start of extent.
38966d9c85ebSYongqiang Yang 				 */
38976d9c85ebSYongqiang Yang 				flags |= FIEMAP_EXTENT_DELALLOC;
38986d9c85ebSYongqiang Yang 				newex->ec_block = end;
38996d9c85ebSYongqiang Yang 				logical = (__u64)end << blksize_bits;
39006d9c85ebSYongqiang Yang 			}
39016d9c85ebSYongqiang Yang 			/* Find contiguous delayed buffers. */
39026d9c85ebSYongqiang Yang 			do {
39036d9c85ebSYongqiang Yang 				if (!buffer_delay(bh))
39046d9c85ebSYongqiang Yang 					goto found_delayed_extent;
39056d9c85ebSYongqiang Yang 				bh = bh->b_this_page;
39066d9c85ebSYongqiang Yang 				end++;
39076d9c85ebSYongqiang Yang 			} while (bh != head);
39086d9c85ebSYongqiang Yang 
39096d9c85ebSYongqiang Yang 			for (index = 1; index < ret; index++) {
39106d9c85ebSYongqiang Yang 				if (!page_has_buffers(pages[index])) {
39116d9c85ebSYongqiang Yang 					bh = NULL;
39126d9c85ebSYongqiang Yang 					break;
39136d9c85ebSYongqiang Yang 				}
39146d9c85ebSYongqiang Yang 				head = page_buffers(pages[index]);
39156d9c85ebSYongqiang Yang 				if (!head) {
39166d9c85ebSYongqiang Yang 					bh = NULL;
39176d9c85ebSYongqiang Yang 					break;
39186d9c85ebSYongqiang Yang 				}
39196d9c85ebSYongqiang Yang 				if (pages[index]->index !=
39206d9c85ebSYongqiang Yang 					pages[0]->index + index) {
39216d9c85ebSYongqiang Yang 					/* Blocks are not contiguous. */
39226d9c85ebSYongqiang Yang 					bh = NULL;
39236d9c85ebSYongqiang Yang 					break;
39246d9c85ebSYongqiang Yang 				}
39256d9c85ebSYongqiang Yang 				bh = head;
39266d9c85ebSYongqiang Yang 				do {
39276d9c85ebSYongqiang Yang 					if (!buffer_delay(bh))
39286d9c85ebSYongqiang Yang 						/* Delayed-extent ends. */
39296d9c85ebSYongqiang Yang 						goto found_delayed_extent;
39306d9c85ebSYongqiang Yang 					bh = bh->b_this_page;
39316d9c85ebSYongqiang Yang 					end++;
39326d9c85ebSYongqiang Yang 				} while (bh != head);
39336d9c85ebSYongqiang Yang 			}
39346d9c85ebSYongqiang Yang 		} else if (!(flags & FIEMAP_EXTENT_DELALLOC))
39356d9c85ebSYongqiang Yang 			/* a hole found. */
39366d9c85ebSYongqiang Yang 			goto out;
39376d9c85ebSYongqiang Yang 
39386d9c85ebSYongqiang Yang found_delayed_extent:
39396d9c85ebSYongqiang Yang 		newex->ec_len = min(end - newex->ec_block,
39406d9c85ebSYongqiang Yang 						(ext4_lblk_t)EXT_INIT_MAX_LEN);
39416d9c85ebSYongqiang Yang 		if (ret == nr_pages && bh != NULL &&
39426d9c85ebSYongqiang Yang 			newex->ec_len < EXT_INIT_MAX_LEN &&
39436d9c85ebSYongqiang Yang 			buffer_delay(bh)) {
39446d9c85ebSYongqiang Yang 			/* Have not collected an extent and continue. */
39456d9c85ebSYongqiang Yang 			for (index = 0; index < ret; index++)
39466d9c85ebSYongqiang Yang 				page_cache_release(pages[index]);
39476d9c85ebSYongqiang Yang 			goto repeat;
39486d9c85ebSYongqiang Yang 		}
39496d9c85ebSYongqiang Yang 
39506d9c85ebSYongqiang Yang 		for (index = 0; index < ret; index++)
39516d9c85ebSYongqiang Yang 			page_cache_release(pages[index]);
39526d9c85ebSYongqiang Yang 		kfree(pages);
39536873fa0dSEric Sandeen 	}
39546873fa0dSEric Sandeen 
39556873fa0dSEric Sandeen 	physical = (__u64)newex->ec_start << blksize_bits;
39566873fa0dSEric Sandeen 	length =   (__u64)newex->ec_len << blksize_bits;
39576873fa0dSEric Sandeen 
39586873fa0dSEric Sandeen 	if (ex && ext4_ext_is_uninitialized(ex))
39596873fa0dSEric Sandeen 		flags |= FIEMAP_EXTENT_UNWRITTEN;
39606873fa0dSEric Sandeen 
39616d9c85ebSYongqiang Yang 	size = i_size_read(inode);
39626d9c85ebSYongqiang Yang 	if (logical + length >= size)
39636873fa0dSEric Sandeen 		flags |= FIEMAP_EXTENT_LAST;
39646873fa0dSEric Sandeen 
39656d9c85ebSYongqiang Yang 	ret = fiemap_fill_next_extent(fieinfo, logical, physical,
39666873fa0dSEric Sandeen 					length, flags);
39676d9c85ebSYongqiang Yang 	if (ret < 0)
39686d9c85ebSYongqiang Yang 		return ret;
39696d9c85ebSYongqiang Yang 	if (ret == 1)
39706873fa0dSEric Sandeen 		return EXT_BREAK;
39716873fa0dSEric Sandeen 	return EXT_CONTINUE;
39726873fa0dSEric Sandeen }
39736873fa0dSEric Sandeen 
39746873fa0dSEric Sandeen /* fiemap flags we can handle specified here */
39756873fa0dSEric Sandeen #define EXT4_FIEMAP_FLAGS	(FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
39766873fa0dSEric Sandeen 
39773a06d778SAneesh Kumar K.V static int ext4_xattr_fiemap(struct inode *inode,
39783a06d778SAneesh Kumar K.V 				struct fiemap_extent_info *fieinfo)
39796873fa0dSEric Sandeen {
39806873fa0dSEric Sandeen 	__u64 physical = 0;
39816873fa0dSEric Sandeen 	__u64 length;
39826873fa0dSEric Sandeen 	__u32 flags = FIEMAP_EXTENT_LAST;
39836873fa0dSEric Sandeen 	int blockbits = inode->i_sb->s_blocksize_bits;
39846873fa0dSEric Sandeen 	int error = 0;
39856873fa0dSEric Sandeen 
39866873fa0dSEric Sandeen 	/* in-inode? */
398719f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
39886873fa0dSEric Sandeen 		struct ext4_iloc iloc;
39896873fa0dSEric Sandeen 		int offset;	/* offset of xattr in inode */
39906873fa0dSEric Sandeen 
39916873fa0dSEric Sandeen 		error = ext4_get_inode_loc(inode, &iloc);
39926873fa0dSEric Sandeen 		if (error)
39936873fa0dSEric Sandeen 			return error;
39946873fa0dSEric Sandeen 		physical = iloc.bh->b_blocknr << blockbits;
39956873fa0dSEric Sandeen 		offset = EXT4_GOOD_OLD_INODE_SIZE +
39966873fa0dSEric Sandeen 				EXT4_I(inode)->i_extra_isize;
39976873fa0dSEric Sandeen 		physical += offset;
39986873fa0dSEric Sandeen 		length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
39996873fa0dSEric Sandeen 		flags |= FIEMAP_EXTENT_DATA_INLINE;
4000fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
40016873fa0dSEric Sandeen 	} else { /* external block */
40026873fa0dSEric Sandeen 		physical = EXT4_I(inode)->i_file_acl << blockbits;
40036873fa0dSEric Sandeen 		length = inode->i_sb->s_blocksize;
40046873fa0dSEric Sandeen 	}
40056873fa0dSEric Sandeen 
40066873fa0dSEric Sandeen 	if (physical)
40076873fa0dSEric Sandeen 		error = fiemap_fill_next_extent(fieinfo, 0, physical,
40086873fa0dSEric Sandeen 						length, flags);
40096873fa0dSEric Sandeen 	return (error < 0 ? error : 0);
40106873fa0dSEric Sandeen }
40116873fa0dSEric Sandeen 
40126873fa0dSEric Sandeen int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
40136873fa0dSEric Sandeen 		__u64 start, __u64 len)
40146873fa0dSEric Sandeen {
40156873fa0dSEric Sandeen 	ext4_lblk_t start_blk;
40166873fa0dSEric Sandeen 	int error = 0;
40176873fa0dSEric Sandeen 
40186873fa0dSEric Sandeen 	/* fallback to generic here if not in extents fmt */
401912e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
40206873fa0dSEric Sandeen 		return generic_block_fiemap(inode, fieinfo, start, len,
40216873fa0dSEric Sandeen 			ext4_get_block);
40226873fa0dSEric Sandeen 
40236873fa0dSEric Sandeen 	if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
40246873fa0dSEric Sandeen 		return -EBADR;
40256873fa0dSEric Sandeen 
40266873fa0dSEric Sandeen 	if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
40276873fa0dSEric Sandeen 		error = ext4_xattr_fiemap(inode, fieinfo);
40286873fa0dSEric Sandeen 	} else {
4029aca92ff6SLeonard Michlmayr 		ext4_lblk_t len_blks;
4030aca92ff6SLeonard Michlmayr 		__u64 last_blk;
4031aca92ff6SLeonard Michlmayr 
40326873fa0dSEric Sandeen 		start_blk = start >> inode->i_sb->s_blocksize_bits;
4033aca92ff6SLeonard Michlmayr 		last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
4034aca92ff6SLeonard Michlmayr 		if (last_blk >= EXT_MAX_BLOCK)
4035aca92ff6SLeonard Michlmayr 			last_blk = EXT_MAX_BLOCK-1;
4036aca92ff6SLeonard Michlmayr 		len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
40376873fa0dSEric Sandeen 
40386873fa0dSEric Sandeen 		/*
40396873fa0dSEric Sandeen 		 * Walk the extent tree gathering extent information.
40406873fa0dSEric Sandeen 		 * ext4_ext_fiemap_cb will push extents back to user.
40416873fa0dSEric Sandeen 		 */
40426873fa0dSEric Sandeen 		error = ext4_ext_walk_space(inode, start_blk, len_blks,
40436873fa0dSEric Sandeen 					  ext4_ext_fiemap_cb, fieinfo);
40446873fa0dSEric Sandeen 	}
40456873fa0dSEric Sandeen 
40466873fa0dSEric Sandeen 	return error;
40476873fa0dSEric Sandeen }
40486873fa0dSEric Sandeen 
4049