xref: /openbmc/linux/fs/ext4/extents.c (revision 68d8904b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4  * Written by Alex Tomas <alex@clusterfs.com>
5  *
6  * Architecture independence:
7  *   Copyright (c) 2005, Bull S.A.
8  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
9  */
10 
11 /*
12  * Extents support for EXT4
13  *
14  * TODO:
15  *   - ext4*_error() should be used in some situations
16  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
17  *   - smart tree reduction
18  */
19 
20 #include <linux/fs.h>
21 #include <linux/time.h>
22 #include <linux/jbd2.h>
23 #include <linux/highuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/quotaops.h>
26 #include <linux/string.h>
27 #include <linux/slab.h>
28 #include <linux/uaccess.h>
29 #include <linux/fiemap.h>
30 #include <linux/backing-dev.h>
31 #include <linux/iomap.h>
32 #include "ext4_jbd2.h"
33 #include "ext4_extents.h"
34 #include "xattr.h"
35 
36 #include <trace/events/ext4.h>
37 
38 /*
39  * used by extent splitting.
40  */
41 #define EXT4_EXT_MAY_ZEROOUT	0x1  /* safe to zeroout if split fails \
42 					due to ENOSPC */
43 #define EXT4_EXT_MARK_UNWRIT1	0x2  /* mark first half unwritten */
44 #define EXT4_EXT_MARK_UNWRIT2	0x4  /* mark second half unwritten */
45 
46 #define EXT4_EXT_DATA_VALID1	0x8  /* first half contains valid data */
47 #define EXT4_EXT_DATA_VALID2	0x10 /* second half contains valid data */
48 
49 static __le32 ext4_extent_block_csum(struct inode *inode,
50 				     struct ext4_extent_header *eh)
51 {
52 	struct ext4_inode_info *ei = EXT4_I(inode);
53 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
54 	__u32 csum;
55 
56 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
57 			   EXT4_EXTENT_TAIL_OFFSET(eh));
58 	return cpu_to_le32(csum);
59 }
60 
61 static int ext4_extent_block_csum_verify(struct inode *inode,
62 					 struct ext4_extent_header *eh)
63 {
64 	struct ext4_extent_tail *et;
65 
66 	if (!ext4_has_metadata_csum(inode->i_sb))
67 		return 1;
68 
69 	et = find_ext4_extent_tail(eh);
70 	if (et->et_checksum != ext4_extent_block_csum(inode, eh))
71 		return 0;
72 	return 1;
73 }
74 
75 static void ext4_extent_block_csum_set(struct inode *inode,
76 				       struct ext4_extent_header *eh)
77 {
78 	struct ext4_extent_tail *et;
79 
80 	if (!ext4_has_metadata_csum(inode->i_sb))
81 		return;
82 
83 	et = find_ext4_extent_tail(eh);
84 	et->et_checksum = ext4_extent_block_csum(inode, eh);
85 }
86 
87 static int ext4_split_extent_at(handle_t *handle,
88 			     struct inode *inode,
89 			     struct ext4_ext_path **ppath,
90 			     ext4_lblk_t split,
91 			     int split_flag,
92 			     int flags);
93 
94 static int ext4_ext_trunc_restart_fn(struct inode *inode, int *dropped)
95 {
96 	/*
97 	 * Drop i_data_sem to avoid deadlock with ext4_map_blocks.  At this
98 	 * moment, get_block can be called only for blocks inside i_size since
99 	 * page cache has been already dropped and writes are blocked by
100 	 * i_mutex. So we can safely drop the i_data_sem here.
101 	 */
102 	BUG_ON(EXT4_JOURNAL(inode) == NULL);
103 	ext4_discard_preallocations(inode);
104 	up_write(&EXT4_I(inode)->i_data_sem);
105 	*dropped = 1;
106 	return 0;
107 }
108 
109 /*
110  * Make sure 'handle' has at least 'check_cred' credits. If not, restart
111  * transaction with 'restart_cred' credits. The function drops i_data_sem
112  * when restarting transaction and gets it after transaction is restarted.
113  *
114  * The function returns 0 on success, 1 if transaction had to be restarted,
115  * and < 0 in case of fatal error.
116  */
117 int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode,
118 				int check_cred, int restart_cred,
119 				int revoke_cred)
120 {
121 	int ret;
122 	int dropped = 0;
123 
124 	ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred,
125 		revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped));
126 	if (dropped)
127 		down_write(&EXT4_I(inode)->i_data_sem);
128 	return ret;
129 }
130 
131 /*
132  * could return:
133  *  - EROFS
134  *  - ENOMEM
135  */
136 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
137 				struct ext4_ext_path *path)
138 {
139 	if (path->p_bh) {
140 		/* path points to block */
141 		BUFFER_TRACE(path->p_bh, "get_write_access");
142 		return ext4_journal_get_write_access(handle, path->p_bh);
143 	}
144 	/* path points to leaf/index in inode body */
145 	/* we use in-core data, no need to protect them */
146 	return 0;
147 }
148 
149 /*
150  * could return:
151  *  - EROFS
152  *  - ENOMEM
153  *  - EIO
154  */
155 static int __ext4_ext_dirty(const char *where, unsigned int line,
156 			    handle_t *handle, struct inode *inode,
157 			    struct ext4_ext_path *path)
158 {
159 	int err;
160 
161 	WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
162 	if (path->p_bh) {
163 		ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
164 		/* path points to block */
165 		err = __ext4_handle_dirty_metadata(where, line, handle,
166 						   inode, path->p_bh);
167 	} else {
168 		/* path points to leaf/index in inode body */
169 		err = ext4_mark_inode_dirty(handle, inode);
170 	}
171 	return err;
172 }
173 
174 #define ext4_ext_dirty(handle, inode, path) \
175 		__ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
176 
177 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
178 			      struct ext4_ext_path *path,
179 			      ext4_lblk_t block)
180 {
181 	if (path) {
182 		int depth = path->p_depth;
183 		struct ext4_extent *ex;
184 
185 		/*
186 		 * Try to predict block placement assuming that we are
187 		 * filling in a file which will eventually be
188 		 * non-sparse --- i.e., in the case of libbfd writing
189 		 * an ELF object sections out-of-order but in a way
190 		 * the eventually results in a contiguous object or
191 		 * executable file, or some database extending a table
192 		 * space file.  However, this is actually somewhat
193 		 * non-ideal if we are writing a sparse file such as
194 		 * qemu or KVM writing a raw image file that is going
195 		 * to stay fairly sparse, since it will end up
196 		 * fragmenting the file system's free space.  Maybe we
197 		 * should have some hueristics or some way to allow
198 		 * userspace to pass a hint to file system,
199 		 * especially if the latter case turns out to be
200 		 * common.
201 		 */
202 		ex = path[depth].p_ext;
203 		if (ex) {
204 			ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
205 			ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
206 
207 			if (block > ext_block)
208 				return ext_pblk + (block - ext_block);
209 			else
210 				return ext_pblk - (ext_block - block);
211 		}
212 
213 		/* it looks like index is empty;
214 		 * try to find starting block from index itself */
215 		if (path[depth].p_bh)
216 			return path[depth].p_bh->b_blocknr;
217 	}
218 
219 	/* OK. use inode's group */
220 	return ext4_inode_to_goal_block(inode);
221 }
222 
223 /*
224  * Allocation for a meta data block
225  */
226 static ext4_fsblk_t
227 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
228 			struct ext4_ext_path *path,
229 			struct ext4_extent *ex, int *err, unsigned int flags)
230 {
231 	ext4_fsblk_t goal, newblock;
232 
233 	goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
234 	newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
235 					NULL, err);
236 	return newblock;
237 }
238 
239 static inline int ext4_ext_space_block(struct inode *inode, int check)
240 {
241 	int size;
242 
243 	size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
244 			/ sizeof(struct ext4_extent);
245 #ifdef AGGRESSIVE_TEST
246 	if (!check && size > 6)
247 		size = 6;
248 #endif
249 	return size;
250 }
251 
252 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
253 {
254 	int size;
255 
256 	size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
257 			/ sizeof(struct ext4_extent_idx);
258 #ifdef AGGRESSIVE_TEST
259 	if (!check && size > 5)
260 		size = 5;
261 #endif
262 	return size;
263 }
264 
265 static inline int ext4_ext_space_root(struct inode *inode, int check)
266 {
267 	int size;
268 
269 	size = sizeof(EXT4_I(inode)->i_data);
270 	size -= sizeof(struct ext4_extent_header);
271 	size /= sizeof(struct ext4_extent);
272 #ifdef AGGRESSIVE_TEST
273 	if (!check && size > 3)
274 		size = 3;
275 #endif
276 	return size;
277 }
278 
279 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
280 {
281 	int size;
282 
283 	size = sizeof(EXT4_I(inode)->i_data);
284 	size -= sizeof(struct ext4_extent_header);
285 	size /= sizeof(struct ext4_extent_idx);
286 #ifdef AGGRESSIVE_TEST
287 	if (!check && size > 4)
288 		size = 4;
289 #endif
290 	return size;
291 }
292 
293 static inline int
294 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
295 			   struct ext4_ext_path **ppath, ext4_lblk_t lblk,
296 			   int nofail)
297 {
298 	struct ext4_ext_path *path = *ppath;
299 	int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
300 	int flags = EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO;
301 
302 	if (nofail)
303 		flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL | EXT4_EX_NOFAIL;
304 
305 	return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
306 			EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
307 			flags);
308 }
309 
310 static int
311 ext4_ext_max_entries(struct inode *inode, int depth)
312 {
313 	int max;
314 
315 	if (depth == ext_depth(inode)) {
316 		if (depth == 0)
317 			max = ext4_ext_space_root(inode, 1);
318 		else
319 			max = ext4_ext_space_root_idx(inode, 1);
320 	} else {
321 		if (depth == 0)
322 			max = ext4_ext_space_block(inode, 1);
323 		else
324 			max = ext4_ext_space_block_idx(inode, 1);
325 	}
326 
327 	return max;
328 }
329 
330 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
331 {
332 	ext4_fsblk_t block = ext4_ext_pblock(ext);
333 	int len = ext4_ext_get_actual_len(ext);
334 	ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
335 
336 	/*
337 	 * We allow neither:
338 	 *  - zero length
339 	 *  - overflow/wrap-around
340 	 */
341 	if (lblock + len <= lblock)
342 		return 0;
343 	return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
344 }
345 
346 static int ext4_valid_extent_idx(struct inode *inode,
347 				struct ext4_extent_idx *ext_idx)
348 {
349 	ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
350 
351 	return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
352 }
353 
354 static int ext4_valid_extent_entries(struct inode *inode,
355 				     struct ext4_extent_header *eh,
356 				     ext4_fsblk_t *pblk, int depth)
357 {
358 	unsigned short entries;
359 	if (eh->eh_entries == 0)
360 		return 1;
361 
362 	entries = le16_to_cpu(eh->eh_entries);
363 
364 	if (depth == 0) {
365 		/* leaf entries */
366 		struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
367 		ext4_lblk_t lblock = 0;
368 		ext4_lblk_t prev = 0;
369 		int len = 0;
370 		while (entries) {
371 			if (!ext4_valid_extent(inode, ext))
372 				return 0;
373 
374 			/* Check for overlapping extents */
375 			lblock = le32_to_cpu(ext->ee_block);
376 			len = ext4_ext_get_actual_len(ext);
377 			if ((lblock <= prev) && prev) {
378 				*pblk = ext4_ext_pblock(ext);
379 				return 0;
380 			}
381 			ext++;
382 			entries--;
383 			prev = lblock + len - 1;
384 		}
385 	} else {
386 		struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
387 		while (entries) {
388 			if (!ext4_valid_extent_idx(inode, ext_idx))
389 				return 0;
390 			ext_idx++;
391 			entries--;
392 		}
393 	}
394 	return 1;
395 }
396 
397 static int __ext4_ext_check(const char *function, unsigned int line,
398 			    struct inode *inode, struct ext4_extent_header *eh,
399 			    int depth, ext4_fsblk_t pblk)
400 {
401 	const char *error_msg;
402 	int max = 0, err = -EFSCORRUPTED;
403 
404 	if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
405 		error_msg = "invalid magic";
406 		goto corrupted;
407 	}
408 	if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
409 		error_msg = "unexpected eh_depth";
410 		goto corrupted;
411 	}
412 	if (unlikely(eh->eh_max == 0)) {
413 		error_msg = "invalid eh_max";
414 		goto corrupted;
415 	}
416 	max = ext4_ext_max_entries(inode, depth);
417 	if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
418 		error_msg = "too large eh_max";
419 		goto corrupted;
420 	}
421 	if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
422 		error_msg = "invalid eh_entries";
423 		goto corrupted;
424 	}
425 	if (!ext4_valid_extent_entries(inode, eh, &pblk, depth)) {
426 		error_msg = "invalid extent entries";
427 		goto corrupted;
428 	}
429 	if (unlikely(depth > 32)) {
430 		error_msg = "too large eh_depth";
431 		goto corrupted;
432 	}
433 	/* Verify checksum on non-root extent tree nodes */
434 	if (ext_depth(inode) != depth &&
435 	    !ext4_extent_block_csum_verify(inode, eh)) {
436 		error_msg = "extent tree corrupted";
437 		err = -EFSBADCRC;
438 		goto corrupted;
439 	}
440 	return 0;
441 
442 corrupted:
443 	ext4_error_inode_err(inode, function, line, 0, -err,
444 			     "pblk %llu bad header/extent: %s - magic %x, "
445 			     "entries %u, max %u(%u), depth %u(%u)",
446 			     (unsigned long long) pblk, error_msg,
447 			     le16_to_cpu(eh->eh_magic),
448 			     le16_to_cpu(eh->eh_entries),
449 			     le16_to_cpu(eh->eh_max),
450 			     max, le16_to_cpu(eh->eh_depth), depth);
451 	return err;
452 }
453 
454 #define ext4_ext_check(inode, eh, depth, pblk)			\
455 	__ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
456 
457 int ext4_ext_check_inode(struct inode *inode)
458 {
459 	return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
460 }
461 
462 static void ext4_cache_extents(struct inode *inode,
463 			       struct ext4_extent_header *eh)
464 {
465 	struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
466 	ext4_lblk_t prev = 0;
467 	int i;
468 
469 	for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
470 		unsigned int status = EXTENT_STATUS_WRITTEN;
471 		ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
472 		int len = ext4_ext_get_actual_len(ex);
473 
474 		if (prev && (prev != lblk))
475 			ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
476 					     EXTENT_STATUS_HOLE);
477 
478 		if (ext4_ext_is_unwritten(ex))
479 			status = EXTENT_STATUS_UNWRITTEN;
480 		ext4_es_cache_extent(inode, lblk, len,
481 				     ext4_ext_pblock(ex), status);
482 		prev = lblk + len;
483 	}
484 }
485 
486 static struct buffer_head *
487 __read_extent_tree_block(const char *function, unsigned int line,
488 			 struct inode *inode, ext4_fsblk_t pblk, int depth,
489 			 int flags)
490 {
491 	struct buffer_head		*bh;
492 	int				err;
493 	gfp_t				gfp_flags = __GFP_MOVABLE | GFP_NOFS;
494 
495 	if (flags & EXT4_EX_NOFAIL)
496 		gfp_flags |= __GFP_NOFAIL;
497 
498 	bh = sb_getblk_gfp(inode->i_sb, pblk, gfp_flags);
499 	if (unlikely(!bh))
500 		return ERR_PTR(-ENOMEM);
501 
502 	if (!bh_uptodate_or_lock(bh)) {
503 		trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
504 		err = bh_submit_read(bh);
505 		if (err < 0)
506 			goto errout;
507 	}
508 	if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
509 		return bh;
510 	if (!ext4_has_feature_journal(inode->i_sb) ||
511 	    (inode->i_ino !=
512 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum))) {
513 		err = __ext4_ext_check(function, line, inode,
514 				       ext_block_hdr(bh), depth, pblk);
515 		if (err)
516 			goto errout;
517 	}
518 	set_buffer_verified(bh);
519 	/*
520 	 * If this is a leaf block, cache all of its entries
521 	 */
522 	if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
523 		struct ext4_extent_header *eh = ext_block_hdr(bh);
524 		ext4_cache_extents(inode, eh);
525 	}
526 	return bh;
527 errout:
528 	put_bh(bh);
529 	return ERR_PTR(err);
530 
531 }
532 
533 #define read_extent_tree_block(inode, pblk, depth, flags)		\
534 	__read_extent_tree_block(__func__, __LINE__, (inode), (pblk),   \
535 				 (depth), (flags))
536 
537 /*
538  * This function is called to cache a file's extent information in the
539  * extent status tree
540  */
541 int ext4_ext_precache(struct inode *inode)
542 {
543 	struct ext4_inode_info *ei = EXT4_I(inode);
544 	struct ext4_ext_path *path = NULL;
545 	struct buffer_head *bh;
546 	int i = 0, depth, ret = 0;
547 
548 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
549 		return 0;	/* not an extent-mapped inode */
550 
551 	down_read(&ei->i_data_sem);
552 	depth = ext_depth(inode);
553 
554 	/* Don't cache anything if there are no external extent blocks */
555 	if (!depth) {
556 		up_read(&ei->i_data_sem);
557 		return ret;
558 	}
559 
560 	path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
561 		       GFP_NOFS);
562 	if (path == NULL) {
563 		up_read(&ei->i_data_sem);
564 		return -ENOMEM;
565 	}
566 
567 	path[0].p_hdr = ext_inode_hdr(inode);
568 	ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
569 	if (ret)
570 		goto out;
571 	path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
572 	while (i >= 0) {
573 		/*
574 		 * If this is a leaf block or we've reached the end of
575 		 * the index block, go up
576 		 */
577 		if ((i == depth) ||
578 		    path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
579 			brelse(path[i].p_bh);
580 			path[i].p_bh = NULL;
581 			i--;
582 			continue;
583 		}
584 		bh = read_extent_tree_block(inode,
585 					    ext4_idx_pblock(path[i].p_idx++),
586 					    depth - i - 1,
587 					    EXT4_EX_FORCE_CACHE);
588 		if (IS_ERR(bh)) {
589 			ret = PTR_ERR(bh);
590 			break;
591 		}
592 		i++;
593 		path[i].p_bh = bh;
594 		path[i].p_hdr = ext_block_hdr(bh);
595 		path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
596 	}
597 	ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
598 out:
599 	up_read(&ei->i_data_sem);
600 	ext4_ext_drop_refs(path);
601 	kfree(path);
602 	return ret;
603 }
604 
605 #ifdef EXT_DEBUG
606 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
607 {
608 	int k, l = path->p_depth;
609 
610 	ext_debug(inode, "path:");
611 	for (k = 0; k <= l; k++, path++) {
612 		if (path->p_idx) {
613 			ext_debug(inode, "  %d->%llu",
614 				  le32_to_cpu(path->p_idx->ei_block),
615 				  ext4_idx_pblock(path->p_idx));
616 		} else if (path->p_ext) {
617 			ext_debug(inode, "  %d:[%d]%d:%llu ",
618 				  le32_to_cpu(path->p_ext->ee_block),
619 				  ext4_ext_is_unwritten(path->p_ext),
620 				  ext4_ext_get_actual_len(path->p_ext),
621 				  ext4_ext_pblock(path->p_ext));
622 		} else
623 			ext_debug(inode, "  []");
624 	}
625 	ext_debug(inode, "\n");
626 }
627 
628 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
629 {
630 	int depth = ext_depth(inode);
631 	struct ext4_extent_header *eh;
632 	struct ext4_extent *ex;
633 	int i;
634 
635 	if (!path)
636 		return;
637 
638 	eh = path[depth].p_hdr;
639 	ex = EXT_FIRST_EXTENT(eh);
640 
641 	ext_debug(inode, "Displaying leaf extents\n");
642 
643 	for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
644 		ext_debug(inode, "%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
645 			  ext4_ext_is_unwritten(ex),
646 			  ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
647 	}
648 	ext_debug(inode, "\n");
649 }
650 
651 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
652 			ext4_fsblk_t newblock, int level)
653 {
654 	int depth = ext_depth(inode);
655 	struct ext4_extent *ex;
656 
657 	if (depth != level) {
658 		struct ext4_extent_idx *idx;
659 		idx = path[level].p_idx;
660 		while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
661 			ext_debug(inode, "%d: move %d:%llu in new index %llu\n",
662 				  level, le32_to_cpu(idx->ei_block),
663 				  ext4_idx_pblock(idx), newblock);
664 			idx++;
665 		}
666 
667 		return;
668 	}
669 
670 	ex = path[depth].p_ext;
671 	while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
672 		ext_debug(inode, "move %d:%llu:[%d]%d in new leaf %llu\n",
673 				le32_to_cpu(ex->ee_block),
674 				ext4_ext_pblock(ex),
675 				ext4_ext_is_unwritten(ex),
676 				ext4_ext_get_actual_len(ex),
677 				newblock);
678 		ex++;
679 	}
680 }
681 
682 #else
683 #define ext4_ext_show_path(inode, path)
684 #define ext4_ext_show_leaf(inode, path)
685 #define ext4_ext_show_move(inode, path, newblock, level)
686 #endif
687 
688 void ext4_ext_drop_refs(struct ext4_ext_path *path)
689 {
690 	int depth, i;
691 
692 	if (!path)
693 		return;
694 	depth = path->p_depth;
695 	for (i = 0; i <= depth; i++, path++) {
696 		if (path->p_bh) {
697 			brelse(path->p_bh);
698 			path->p_bh = NULL;
699 		}
700 	}
701 }
702 
703 /*
704  * ext4_ext_binsearch_idx:
705  * binary search for the closest index of the given block
706  * the header must be checked before calling this
707  */
708 static void
709 ext4_ext_binsearch_idx(struct inode *inode,
710 			struct ext4_ext_path *path, ext4_lblk_t block)
711 {
712 	struct ext4_extent_header *eh = path->p_hdr;
713 	struct ext4_extent_idx *r, *l, *m;
714 
715 
716 	ext_debug(inode, "binsearch for %u(idx):  ", block);
717 
718 	l = EXT_FIRST_INDEX(eh) + 1;
719 	r = EXT_LAST_INDEX(eh);
720 	while (l <= r) {
721 		m = l + (r - l) / 2;
722 		if (block < le32_to_cpu(m->ei_block))
723 			r = m - 1;
724 		else
725 			l = m + 1;
726 		ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
727 			  le32_to_cpu(l->ei_block), m, le32_to_cpu(m->ei_block),
728 			  r, le32_to_cpu(r->ei_block));
729 	}
730 
731 	path->p_idx = l - 1;
732 	ext_debug(inode, "  -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
733 		  ext4_idx_pblock(path->p_idx));
734 
735 #ifdef CHECK_BINSEARCH
736 	{
737 		struct ext4_extent_idx *chix, *ix;
738 		int k;
739 
740 		chix = ix = EXT_FIRST_INDEX(eh);
741 		for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
742 			if (k != 0 && le32_to_cpu(ix->ei_block) <=
743 			    le32_to_cpu(ix[-1].ei_block)) {
744 				printk(KERN_DEBUG "k=%d, ix=0x%p, "
745 				       "first=0x%p\n", k,
746 				       ix, EXT_FIRST_INDEX(eh));
747 				printk(KERN_DEBUG "%u <= %u\n",
748 				       le32_to_cpu(ix->ei_block),
749 				       le32_to_cpu(ix[-1].ei_block));
750 			}
751 			BUG_ON(k && le32_to_cpu(ix->ei_block)
752 					   <= le32_to_cpu(ix[-1].ei_block));
753 			if (block < le32_to_cpu(ix->ei_block))
754 				break;
755 			chix = ix;
756 		}
757 		BUG_ON(chix != path->p_idx);
758 	}
759 #endif
760 
761 }
762 
763 /*
764  * ext4_ext_binsearch:
765  * binary search for closest extent of the given block
766  * the header must be checked before calling this
767  */
768 static void
769 ext4_ext_binsearch(struct inode *inode,
770 		struct ext4_ext_path *path, ext4_lblk_t block)
771 {
772 	struct ext4_extent_header *eh = path->p_hdr;
773 	struct ext4_extent *r, *l, *m;
774 
775 	if (eh->eh_entries == 0) {
776 		/*
777 		 * this leaf is empty:
778 		 * we get such a leaf in split/add case
779 		 */
780 		return;
781 	}
782 
783 	ext_debug(inode, "binsearch for %u:  ", block);
784 
785 	l = EXT_FIRST_EXTENT(eh) + 1;
786 	r = EXT_LAST_EXTENT(eh);
787 
788 	while (l <= r) {
789 		m = l + (r - l) / 2;
790 		if (block < le32_to_cpu(m->ee_block))
791 			r = m - 1;
792 		else
793 			l = m + 1;
794 		ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
795 			  le32_to_cpu(l->ee_block), m, le32_to_cpu(m->ee_block),
796 			  r, le32_to_cpu(r->ee_block));
797 	}
798 
799 	path->p_ext = l - 1;
800 	ext_debug(inode, "  -> %d:%llu:[%d]%d ",
801 			le32_to_cpu(path->p_ext->ee_block),
802 			ext4_ext_pblock(path->p_ext),
803 			ext4_ext_is_unwritten(path->p_ext),
804 			ext4_ext_get_actual_len(path->p_ext));
805 
806 #ifdef CHECK_BINSEARCH
807 	{
808 		struct ext4_extent *chex, *ex;
809 		int k;
810 
811 		chex = ex = EXT_FIRST_EXTENT(eh);
812 		for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
813 			BUG_ON(k && le32_to_cpu(ex->ee_block)
814 					  <= le32_to_cpu(ex[-1].ee_block));
815 			if (block < le32_to_cpu(ex->ee_block))
816 				break;
817 			chex = ex;
818 		}
819 		BUG_ON(chex != path->p_ext);
820 	}
821 #endif
822 
823 }
824 
825 void ext4_ext_tree_init(handle_t *handle, struct inode *inode)
826 {
827 	struct ext4_extent_header *eh;
828 
829 	eh = ext_inode_hdr(inode);
830 	eh->eh_depth = 0;
831 	eh->eh_entries = 0;
832 	eh->eh_magic = EXT4_EXT_MAGIC;
833 	eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
834 	ext4_mark_inode_dirty(handle, inode);
835 }
836 
837 struct ext4_ext_path *
838 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
839 		 struct ext4_ext_path **orig_path, int flags)
840 {
841 	struct ext4_extent_header *eh;
842 	struct buffer_head *bh;
843 	struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
844 	short int depth, i, ppos = 0;
845 	int ret;
846 	gfp_t gfp_flags = GFP_NOFS;
847 
848 	if (flags & EXT4_EX_NOFAIL)
849 		gfp_flags |= __GFP_NOFAIL;
850 
851 	eh = ext_inode_hdr(inode);
852 	depth = ext_depth(inode);
853 	if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
854 		EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
855 				 depth);
856 		ret = -EFSCORRUPTED;
857 		goto err;
858 	}
859 
860 	if (path) {
861 		ext4_ext_drop_refs(path);
862 		if (depth > path[0].p_maxdepth) {
863 			kfree(path);
864 			*orig_path = path = NULL;
865 		}
866 	}
867 	if (!path) {
868 		/* account possible depth increase */
869 		path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
870 				gfp_flags);
871 		if (unlikely(!path))
872 			return ERR_PTR(-ENOMEM);
873 		path[0].p_maxdepth = depth + 1;
874 	}
875 	path[0].p_hdr = eh;
876 	path[0].p_bh = NULL;
877 
878 	i = depth;
879 	if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
880 		ext4_cache_extents(inode, eh);
881 	/* walk through the tree */
882 	while (i) {
883 		ext_debug(inode, "depth %d: num %d, max %d\n",
884 			  ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
885 
886 		ext4_ext_binsearch_idx(inode, path + ppos, block);
887 		path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
888 		path[ppos].p_depth = i;
889 		path[ppos].p_ext = NULL;
890 
891 		bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
892 					    flags);
893 		if (IS_ERR(bh)) {
894 			ret = PTR_ERR(bh);
895 			goto err;
896 		}
897 
898 		eh = ext_block_hdr(bh);
899 		ppos++;
900 		path[ppos].p_bh = bh;
901 		path[ppos].p_hdr = eh;
902 	}
903 
904 	path[ppos].p_depth = i;
905 	path[ppos].p_ext = NULL;
906 	path[ppos].p_idx = NULL;
907 
908 	/* find extent */
909 	ext4_ext_binsearch(inode, path + ppos, block);
910 	/* if not an empty leaf */
911 	if (path[ppos].p_ext)
912 		path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
913 
914 	ext4_ext_show_path(inode, path);
915 
916 	return path;
917 
918 err:
919 	ext4_ext_drop_refs(path);
920 	kfree(path);
921 	if (orig_path)
922 		*orig_path = NULL;
923 	return ERR_PTR(ret);
924 }
925 
926 /*
927  * ext4_ext_insert_index:
928  * insert new index [@logical;@ptr] into the block at @curp;
929  * check where to insert: before @curp or after @curp
930  */
931 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
932 				 struct ext4_ext_path *curp,
933 				 int logical, ext4_fsblk_t ptr)
934 {
935 	struct ext4_extent_idx *ix;
936 	int len, err;
937 
938 	err = ext4_ext_get_access(handle, inode, curp);
939 	if (err)
940 		return err;
941 
942 	if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
943 		EXT4_ERROR_INODE(inode,
944 				 "logical %d == ei_block %d!",
945 				 logical, le32_to_cpu(curp->p_idx->ei_block));
946 		return -EFSCORRUPTED;
947 	}
948 
949 	if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
950 			     >= le16_to_cpu(curp->p_hdr->eh_max))) {
951 		EXT4_ERROR_INODE(inode,
952 				 "eh_entries %d >= eh_max %d!",
953 				 le16_to_cpu(curp->p_hdr->eh_entries),
954 				 le16_to_cpu(curp->p_hdr->eh_max));
955 		return -EFSCORRUPTED;
956 	}
957 
958 	if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
959 		/* insert after */
960 		ext_debug(inode, "insert new index %d after: %llu\n",
961 			  logical, ptr);
962 		ix = curp->p_idx + 1;
963 	} else {
964 		/* insert before */
965 		ext_debug(inode, "insert new index %d before: %llu\n",
966 			  logical, ptr);
967 		ix = curp->p_idx;
968 	}
969 
970 	len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
971 	BUG_ON(len < 0);
972 	if (len > 0) {
973 		ext_debug(inode, "insert new index %d: "
974 				"move %d indices from 0x%p to 0x%p\n",
975 				logical, len, ix, ix + 1);
976 		memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
977 	}
978 
979 	if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
980 		EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
981 		return -EFSCORRUPTED;
982 	}
983 
984 	ix->ei_block = cpu_to_le32(logical);
985 	ext4_idx_store_pblock(ix, ptr);
986 	le16_add_cpu(&curp->p_hdr->eh_entries, 1);
987 
988 	if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
989 		EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
990 		return -EFSCORRUPTED;
991 	}
992 
993 	err = ext4_ext_dirty(handle, inode, curp);
994 	ext4_std_error(inode->i_sb, err);
995 
996 	return err;
997 }
998 
999 /*
1000  * ext4_ext_split:
1001  * inserts new subtree into the path, using free index entry
1002  * at depth @at:
1003  * - allocates all needed blocks (new leaf and all intermediate index blocks)
1004  * - makes decision where to split
1005  * - moves remaining extents and index entries (right to the split point)
1006  *   into the newly allocated blocks
1007  * - initializes subtree
1008  */
1009 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1010 			  unsigned int flags,
1011 			  struct ext4_ext_path *path,
1012 			  struct ext4_extent *newext, int at)
1013 {
1014 	struct buffer_head *bh = NULL;
1015 	int depth = ext_depth(inode);
1016 	struct ext4_extent_header *neh;
1017 	struct ext4_extent_idx *fidx;
1018 	int i = at, k, m, a;
1019 	ext4_fsblk_t newblock, oldblock;
1020 	__le32 border;
1021 	ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1022 	gfp_t gfp_flags = GFP_NOFS;
1023 	int err = 0;
1024 	size_t ext_size = 0;
1025 
1026 	if (flags & EXT4_EX_NOFAIL)
1027 		gfp_flags |= __GFP_NOFAIL;
1028 
1029 	/* make decision: where to split? */
1030 	/* FIXME: now decision is simplest: at current extent */
1031 
1032 	/* if current leaf will be split, then we should use
1033 	 * border from split point */
1034 	if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1035 		EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1036 		return -EFSCORRUPTED;
1037 	}
1038 	if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1039 		border = path[depth].p_ext[1].ee_block;
1040 		ext_debug(inode, "leaf will be split."
1041 				" next leaf starts at %d\n",
1042 				  le32_to_cpu(border));
1043 	} else {
1044 		border = newext->ee_block;
1045 		ext_debug(inode, "leaf will be added."
1046 				" next leaf starts at %d\n",
1047 				le32_to_cpu(border));
1048 	}
1049 
1050 	/*
1051 	 * If error occurs, then we break processing
1052 	 * and mark filesystem read-only. index won't
1053 	 * be inserted and tree will be in consistent
1054 	 * state. Next mount will repair buffers too.
1055 	 */
1056 
1057 	/*
1058 	 * Get array to track all allocated blocks.
1059 	 * We need this to handle errors and free blocks
1060 	 * upon them.
1061 	 */
1062 	ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), gfp_flags);
1063 	if (!ablocks)
1064 		return -ENOMEM;
1065 
1066 	/* allocate all needed blocks */
1067 	ext_debug(inode, "allocate %d blocks for indexes/leaf\n", depth - at);
1068 	for (a = 0; a < depth - at; a++) {
1069 		newblock = ext4_ext_new_meta_block(handle, inode, path,
1070 						   newext, &err, flags);
1071 		if (newblock == 0)
1072 			goto cleanup;
1073 		ablocks[a] = newblock;
1074 	}
1075 
1076 	/* initialize new leaf */
1077 	newblock = ablocks[--a];
1078 	if (unlikely(newblock == 0)) {
1079 		EXT4_ERROR_INODE(inode, "newblock == 0!");
1080 		err = -EFSCORRUPTED;
1081 		goto cleanup;
1082 	}
1083 	bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1084 	if (unlikely(!bh)) {
1085 		err = -ENOMEM;
1086 		goto cleanup;
1087 	}
1088 	lock_buffer(bh);
1089 
1090 	err = ext4_journal_get_create_access(handle, bh);
1091 	if (err)
1092 		goto cleanup;
1093 
1094 	neh = ext_block_hdr(bh);
1095 	neh->eh_entries = 0;
1096 	neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1097 	neh->eh_magic = EXT4_EXT_MAGIC;
1098 	neh->eh_depth = 0;
1099 
1100 	/* move remainder of path[depth] to the new leaf */
1101 	if (unlikely(path[depth].p_hdr->eh_entries !=
1102 		     path[depth].p_hdr->eh_max)) {
1103 		EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1104 				 path[depth].p_hdr->eh_entries,
1105 				 path[depth].p_hdr->eh_max);
1106 		err = -EFSCORRUPTED;
1107 		goto cleanup;
1108 	}
1109 	/* start copy from next extent */
1110 	m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1111 	ext4_ext_show_move(inode, path, newblock, depth);
1112 	if (m) {
1113 		struct ext4_extent *ex;
1114 		ex = EXT_FIRST_EXTENT(neh);
1115 		memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1116 		le16_add_cpu(&neh->eh_entries, m);
1117 	}
1118 
1119 	/* zero out unused area in the extent block */
1120 	ext_size = sizeof(struct ext4_extent_header) +
1121 		sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1122 	memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1123 	ext4_extent_block_csum_set(inode, neh);
1124 	set_buffer_uptodate(bh);
1125 	unlock_buffer(bh);
1126 
1127 	err = ext4_handle_dirty_metadata(handle, inode, bh);
1128 	if (err)
1129 		goto cleanup;
1130 	brelse(bh);
1131 	bh = NULL;
1132 
1133 	/* correct old leaf */
1134 	if (m) {
1135 		err = ext4_ext_get_access(handle, inode, path + depth);
1136 		if (err)
1137 			goto cleanup;
1138 		le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1139 		err = ext4_ext_dirty(handle, inode, path + depth);
1140 		if (err)
1141 			goto cleanup;
1142 
1143 	}
1144 
1145 	/* create intermediate indexes */
1146 	k = depth - at - 1;
1147 	if (unlikely(k < 0)) {
1148 		EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1149 		err = -EFSCORRUPTED;
1150 		goto cleanup;
1151 	}
1152 	if (k)
1153 		ext_debug(inode, "create %d intermediate indices\n", k);
1154 	/* insert new index into current index block */
1155 	/* current depth stored in i var */
1156 	i = depth - 1;
1157 	while (k--) {
1158 		oldblock = newblock;
1159 		newblock = ablocks[--a];
1160 		bh = sb_getblk(inode->i_sb, newblock);
1161 		if (unlikely(!bh)) {
1162 			err = -ENOMEM;
1163 			goto cleanup;
1164 		}
1165 		lock_buffer(bh);
1166 
1167 		err = ext4_journal_get_create_access(handle, bh);
1168 		if (err)
1169 			goto cleanup;
1170 
1171 		neh = ext_block_hdr(bh);
1172 		neh->eh_entries = cpu_to_le16(1);
1173 		neh->eh_magic = EXT4_EXT_MAGIC;
1174 		neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1175 		neh->eh_depth = cpu_to_le16(depth - i);
1176 		fidx = EXT_FIRST_INDEX(neh);
1177 		fidx->ei_block = border;
1178 		ext4_idx_store_pblock(fidx, oldblock);
1179 
1180 		ext_debug(inode, "int.index at %d (block %llu): %u -> %llu\n",
1181 				i, newblock, le32_to_cpu(border), oldblock);
1182 
1183 		/* move remainder of path[i] to the new index block */
1184 		if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1185 					EXT_LAST_INDEX(path[i].p_hdr))) {
1186 			EXT4_ERROR_INODE(inode,
1187 					 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1188 					 le32_to_cpu(path[i].p_ext->ee_block));
1189 			err = -EFSCORRUPTED;
1190 			goto cleanup;
1191 		}
1192 		/* start copy indexes */
1193 		m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1194 		ext_debug(inode, "cur 0x%p, last 0x%p\n", path[i].p_idx,
1195 				EXT_MAX_INDEX(path[i].p_hdr));
1196 		ext4_ext_show_move(inode, path, newblock, i);
1197 		if (m) {
1198 			memmove(++fidx, path[i].p_idx,
1199 				sizeof(struct ext4_extent_idx) * m);
1200 			le16_add_cpu(&neh->eh_entries, m);
1201 		}
1202 		/* zero out unused area in the extent block */
1203 		ext_size = sizeof(struct ext4_extent_header) +
1204 		   (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1205 		memset(bh->b_data + ext_size, 0,
1206 			inode->i_sb->s_blocksize - ext_size);
1207 		ext4_extent_block_csum_set(inode, neh);
1208 		set_buffer_uptodate(bh);
1209 		unlock_buffer(bh);
1210 
1211 		err = ext4_handle_dirty_metadata(handle, inode, bh);
1212 		if (err)
1213 			goto cleanup;
1214 		brelse(bh);
1215 		bh = NULL;
1216 
1217 		/* correct old index */
1218 		if (m) {
1219 			err = ext4_ext_get_access(handle, inode, path + i);
1220 			if (err)
1221 				goto cleanup;
1222 			le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1223 			err = ext4_ext_dirty(handle, inode, path + i);
1224 			if (err)
1225 				goto cleanup;
1226 		}
1227 
1228 		i--;
1229 	}
1230 
1231 	/* insert new index */
1232 	err = ext4_ext_insert_index(handle, inode, path + at,
1233 				    le32_to_cpu(border), newblock);
1234 
1235 cleanup:
1236 	if (bh) {
1237 		if (buffer_locked(bh))
1238 			unlock_buffer(bh);
1239 		brelse(bh);
1240 	}
1241 
1242 	if (err) {
1243 		/* free all allocated blocks in error case */
1244 		for (i = 0; i < depth; i++) {
1245 			if (!ablocks[i])
1246 				continue;
1247 			ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1248 					 EXT4_FREE_BLOCKS_METADATA);
1249 		}
1250 	}
1251 	kfree(ablocks);
1252 
1253 	return err;
1254 }
1255 
1256 /*
1257  * ext4_ext_grow_indepth:
1258  * implements tree growing procedure:
1259  * - allocates new block
1260  * - moves top-level data (index block or leaf) into the new block
1261  * - initializes new top-level, creating index that points to the
1262  *   just created block
1263  */
1264 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1265 				 unsigned int flags)
1266 {
1267 	struct ext4_extent_header *neh;
1268 	struct buffer_head *bh;
1269 	ext4_fsblk_t newblock, goal = 0;
1270 	struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1271 	int err = 0;
1272 	size_t ext_size = 0;
1273 
1274 	/* Try to prepend new index to old one */
1275 	if (ext_depth(inode))
1276 		goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1277 	if (goal > le32_to_cpu(es->s_first_data_block)) {
1278 		flags |= EXT4_MB_HINT_TRY_GOAL;
1279 		goal--;
1280 	} else
1281 		goal = ext4_inode_to_goal_block(inode);
1282 	newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1283 					NULL, &err);
1284 	if (newblock == 0)
1285 		return err;
1286 
1287 	bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1288 	if (unlikely(!bh))
1289 		return -ENOMEM;
1290 	lock_buffer(bh);
1291 
1292 	err = ext4_journal_get_create_access(handle, bh);
1293 	if (err) {
1294 		unlock_buffer(bh);
1295 		goto out;
1296 	}
1297 
1298 	ext_size = sizeof(EXT4_I(inode)->i_data);
1299 	/* move top-level index/leaf into new block */
1300 	memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1301 	/* zero out unused area in the extent block */
1302 	memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1303 
1304 	/* set size of new block */
1305 	neh = ext_block_hdr(bh);
1306 	/* old root could have indexes or leaves
1307 	 * so calculate e_max right way */
1308 	if (ext_depth(inode))
1309 		neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1310 	else
1311 		neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1312 	neh->eh_magic = EXT4_EXT_MAGIC;
1313 	ext4_extent_block_csum_set(inode, neh);
1314 	set_buffer_uptodate(bh);
1315 	unlock_buffer(bh);
1316 
1317 	err = ext4_handle_dirty_metadata(handle, inode, bh);
1318 	if (err)
1319 		goto out;
1320 
1321 	/* Update top-level index: num,max,pointer */
1322 	neh = ext_inode_hdr(inode);
1323 	neh->eh_entries = cpu_to_le16(1);
1324 	ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1325 	if (neh->eh_depth == 0) {
1326 		/* Root extent block becomes index block */
1327 		neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1328 		EXT_FIRST_INDEX(neh)->ei_block =
1329 			EXT_FIRST_EXTENT(neh)->ee_block;
1330 	}
1331 	ext_debug(inode, "new root: num %d(%d), lblock %d, ptr %llu\n",
1332 		  le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1333 		  le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1334 		  ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1335 
1336 	le16_add_cpu(&neh->eh_depth, 1);
1337 	err = ext4_mark_inode_dirty(handle, inode);
1338 out:
1339 	brelse(bh);
1340 
1341 	return err;
1342 }
1343 
1344 /*
1345  * ext4_ext_create_new_leaf:
1346  * finds empty index and adds new leaf.
1347  * if no free index is found, then it requests in-depth growing.
1348  */
1349 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1350 				    unsigned int mb_flags,
1351 				    unsigned int gb_flags,
1352 				    struct ext4_ext_path **ppath,
1353 				    struct ext4_extent *newext)
1354 {
1355 	struct ext4_ext_path *path = *ppath;
1356 	struct ext4_ext_path *curp;
1357 	int depth, i, err = 0;
1358 
1359 repeat:
1360 	i = depth = ext_depth(inode);
1361 
1362 	/* walk up to the tree and look for free index entry */
1363 	curp = path + depth;
1364 	while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1365 		i--;
1366 		curp--;
1367 	}
1368 
1369 	/* we use already allocated block for index block,
1370 	 * so subsequent data blocks should be contiguous */
1371 	if (EXT_HAS_FREE_INDEX(curp)) {
1372 		/* if we found index with free entry, then use that
1373 		 * entry: create all needed subtree and add new leaf */
1374 		err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1375 		if (err)
1376 			goto out;
1377 
1378 		/* refill path */
1379 		path = ext4_find_extent(inode,
1380 				    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1381 				    ppath, gb_flags);
1382 		if (IS_ERR(path))
1383 			err = PTR_ERR(path);
1384 	} else {
1385 		/* tree is full, time to grow in depth */
1386 		err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1387 		if (err)
1388 			goto out;
1389 
1390 		/* refill path */
1391 		path = ext4_find_extent(inode,
1392 				   (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1393 				    ppath, gb_flags);
1394 		if (IS_ERR(path)) {
1395 			err = PTR_ERR(path);
1396 			goto out;
1397 		}
1398 
1399 		/*
1400 		 * only first (depth 0 -> 1) produces free space;
1401 		 * in all other cases we have to split the grown tree
1402 		 */
1403 		depth = ext_depth(inode);
1404 		if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1405 			/* now we need to split */
1406 			goto repeat;
1407 		}
1408 	}
1409 
1410 out:
1411 	return err;
1412 }
1413 
1414 /*
1415  * search the closest allocated block to the left for *logical
1416  * and returns it at @logical + it's physical address at @phys
1417  * if *logical is the smallest allocated block, the function
1418  * returns 0 at @phys
1419  * return value contains 0 (success) or error code
1420  */
1421 static int ext4_ext_search_left(struct inode *inode,
1422 				struct ext4_ext_path *path,
1423 				ext4_lblk_t *logical, ext4_fsblk_t *phys)
1424 {
1425 	struct ext4_extent_idx *ix;
1426 	struct ext4_extent *ex;
1427 	int depth, ee_len;
1428 
1429 	if (unlikely(path == NULL)) {
1430 		EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1431 		return -EFSCORRUPTED;
1432 	}
1433 	depth = path->p_depth;
1434 	*phys = 0;
1435 
1436 	if (depth == 0 && path->p_ext == NULL)
1437 		return 0;
1438 
1439 	/* usually extent in the path covers blocks smaller
1440 	 * then *logical, but it can be that extent is the
1441 	 * first one in the file */
1442 
1443 	ex = path[depth].p_ext;
1444 	ee_len = ext4_ext_get_actual_len(ex);
1445 	if (*logical < le32_to_cpu(ex->ee_block)) {
1446 		if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1447 			EXT4_ERROR_INODE(inode,
1448 					 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1449 					 *logical, le32_to_cpu(ex->ee_block));
1450 			return -EFSCORRUPTED;
1451 		}
1452 		while (--depth >= 0) {
1453 			ix = path[depth].p_idx;
1454 			if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1455 				EXT4_ERROR_INODE(inode,
1456 				  "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1457 				  ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1458 				  EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1459 		le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1460 				  depth);
1461 				return -EFSCORRUPTED;
1462 			}
1463 		}
1464 		return 0;
1465 	}
1466 
1467 	if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1468 		EXT4_ERROR_INODE(inode,
1469 				 "logical %d < ee_block %d + ee_len %d!",
1470 				 *logical, le32_to_cpu(ex->ee_block), ee_len);
1471 		return -EFSCORRUPTED;
1472 	}
1473 
1474 	*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1475 	*phys = ext4_ext_pblock(ex) + ee_len - 1;
1476 	return 0;
1477 }
1478 
1479 /*
1480  * search the closest allocated block to the right for *logical
1481  * and returns it at @logical + it's physical address at @phys
1482  * if *logical is the largest allocated block, the function
1483  * returns 0 at @phys
1484  * return value contains 0 (success) or error code
1485  */
1486 static int ext4_ext_search_right(struct inode *inode,
1487 				 struct ext4_ext_path *path,
1488 				 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1489 				 struct ext4_extent **ret_ex)
1490 {
1491 	struct buffer_head *bh = NULL;
1492 	struct ext4_extent_header *eh;
1493 	struct ext4_extent_idx *ix;
1494 	struct ext4_extent *ex;
1495 	ext4_fsblk_t block;
1496 	int depth;	/* Note, NOT eh_depth; depth from top of tree */
1497 	int ee_len;
1498 
1499 	if (unlikely(path == NULL)) {
1500 		EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1501 		return -EFSCORRUPTED;
1502 	}
1503 	depth = path->p_depth;
1504 	*phys = 0;
1505 
1506 	if (depth == 0 && path->p_ext == NULL)
1507 		return 0;
1508 
1509 	/* usually extent in the path covers blocks smaller
1510 	 * then *logical, but it can be that extent is the
1511 	 * first one in the file */
1512 
1513 	ex = path[depth].p_ext;
1514 	ee_len = ext4_ext_get_actual_len(ex);
1515 	if (*logical < le32_to_cpu(ex->ee_block)) {
1516 		if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1517 			EXT4_ERROR_INODE(inode,
1518 					 "first_extent(path[%d].p_hdr) != ex",
1519 					 depth);
1520 			return -EFSCORRUPTED;
1521 		}
1522 		while (--depth >= 0) {
1523 			ix = path[depth].p_idx;
1524 			if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1525 				EXT4_ERROR_INODE(inode,
1526 						 "ix != EXT_FIRST_INDEX *logical %d!",
1527 						 *logical);
1528 				return -EFSCORRUPTED;
1529 			}
1530 		}
1531 		goto found_extent;
1532 	}
1533 
1534 	if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1535 		EXT4_ERROR_INODE(inode,
1536 				 "logical %d < ee_block %d + ee_len %d!",
1537 				 *logical, le32_to_cpu(ex->ee_block), ee_len);
1538 		return -EFSCORRUPTED;
1539 	}
1540 
1541 	if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1542 		/* next allocated block in this leaf */
1543 		ex++;
1544 		goto found_extent;
1545 	}
1546 
1547 	/* go up and search for index to the right */
1548 	while (--depth >= 0) {
1549 		ix = path[depth].p_idx;
1550 		if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1551 			goto got_index;
1552 	}
1553 
1554 	/* we've gone up to the root and found no index to the right */
1555 	return 0;
1556 
1557 got_index:
1558 	/* we've found index to the right, let's
1559 	 * follow it and find the closest allocated
1560 	 * block to the right */
1561 	ix++;
1562 	block = ext4_idx_pblock(ix);
1563 	while (++depth < path->p_depth) {
1564 		/* subtract from p_depth to get proper eh_depth */
1565 		bh = read_extent_tree_block(inode, block,
1566 					    path->p_depth - depth, 0);
1567 		if (IS_ERR(bh))
1568 			return PTR_ERR(bh);
1569 		eh = ext_block_hdr(bh);
1570 		ix = EXT_FIRST_INDEX(eh);
1571 		block = ext4_idx_pblock(ix);
1572 		put_bh(bh);
1573 	}
1574 
1575 	bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1576 	if (IS_ERR(bh))
1577 		return PTR_ERR(bh);
1578 	eh = ext_block_hdr(bh);
1579 	ex = EXT_FIRST_EXTENT(eh);
1580 found_extent:
1581 	*logical = le32_to_cpu(ex->ee_block);
1582 	*phys = ext4_ext_pblock(ex);
1583 	*ret_ex = ex;
1584 	if (bh)
1585 		put_bh(bh);
1586 	return 0;
1587 }
1588 
1589 /*
1590  * ext4_ext_next_allocated_block:
1591  * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1592  * NOTE: it considers block number from index entry as
1593  * allocated block. Thus, index entries have to be consistent
1594  * with leaves.
1595  */
1596 ext4_lblk_t
1597 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1598 {
1599 	int depth;
1600 
1601 	BUG_ON(path == NULL);
1602 	depth = path->p_depth;
1603 
1604 	if (depth == 0 && path->p_ext == NULL)
1605 		return EXT_MAX_BLOCKS;
1606 
1607 	while (depth >= 0) {
1608 		struct ext4_ext_path *p = &path[depth];
1609 
1610 		if (depth == path->p_depth) {
1611 			/* leaf */
1612 			if (p->p_ext && p->p_ext != EXT_LAST_EXTENT(p->p_hdr))
1613 				return le32_to_cpu(p->p_ext[1].ee_block);
1614 		} else {
1615 			/* index */
1616 			if (p->p_idx != EXT_LAST_INDEX(p->p_hdr))
1617 				return le32_to_cpu(p->p_idx[1].ei_block);
1618 		}
1619 		depth--;
1620 	}
1621 
1622 	return EXT_MAX_BLOCKS;
1623 }
1624 
1625 /*
1626  * ext4_ext_next_leaf_block:
1627  * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1628  */
1629 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1630 {
1631 	int depth;
1632 
1633 	BUG_ON(path == NULL);
1634 	depth = path->p_depth;
1635 
1636 	/* zero-tree has no leaf blocks at all */
1637 	if (depth == 0)
1638 		return EXT_MAX_BLOCKS;
1639 
1640 	/* go to index block */
1641 	depth--;
1642 
1643 	while (depth >= 0) {
1644 		if (path[depth].p_idx !=
1645 				EXT_LAST_INDEX(path[depth].p_hdr))
1646 			return (ext4_lblk_t)
1647 				le32_to_cpu(path[depth].p_idx[1].ei_block);
1648 		depth--;
1649 	}
1650 
1651 	return EXT_MAX_BLOCKS;
1652 }
1653 
1654 /*
1655  * ext4_ext_correct_indexes:
1656  * if leaf gets modified and modified extent is first in the leaf,
1657  * then we have to correct all indexes above.
1658  * TODO: do we need to correct tree in all cases?
1659  */
1660 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1661 				struct ext4_ext_path *path)
1662 {
1663 	struct ext4_extent_header *eh;
1664 	int depth = ext_depth(inode);
1665 	struct ext4_extent *ex;
1666 	__le32 border;
1667 	int k, err = 0;
1668 
1669 	eh = path[depth].p_hdr;
1670 	ex = path[depth].p_ext;
1671 
1672 	if (unlikely(ex == NULL || eh == NULL)) {
1673 		EXT4_ERROR_INODE(inode,
1674 				 "ex %p == NULL or eh %p == NULL", ex, eh);
1675 		return -EFSCORRUPTED;
1676 	}
1677 
1678 	if (depth == 0) {
1679 		/* there is no tree at all */
1680 		return 0;
1681 	}
1682 
1683 	if (ex != EXT_FIRST_EXTENT(eh)) {
1684 		/* we correct tree if first leaf got modified only */
1685 		return 0;
1686 	}
1687 
1688 	/*
1689 	 * TODO: we need correction if border is smaller than current one
1690 	 */
1691 	k = depth - 1;
1692 	border = path[depth].p_ext->ee_block;
1693 	err = ext4_ext_get_access(handle, inode, path + k);
1694 	if (err)
1695 		return err;
1696 	path[k].p_idx->ei_block = border;
1697 	err = ext4_ext_dirty(handle, inode, path + k);
1698 	if (err)
1699 		return err;
1700 
1701 	while (k--) {
1702 		/* change all left-side indexes */
1703 		if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1704 			break;
1705 		err = ext4_ext_get_access(handle, inode, path + k);
1706 		if (err)
1707 			break;
1708 		path[k].p_idx->ei_block = border;
1709 		err = ext4_ext_dirty(handle, inode, path + k);
1710 		if (err)
1711 			break;
1712 	}
1713 
1714 	return err;
1715 }
1716 
1717 static int ext4_can_extents_be_merged(struct inode *inode,
1718 				      struct ext4_extent *ex1,
1719 				      struct ext4_extent *ex2)
1720 {
1721 	unsigned short ext1_ee_len, ext2_ee_len;
1722 
1723 	if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1724 		return 0;
1725 
1726 	ext1_ee_len = ext4_ext_get_actual_len(ex1);
1727 	ext2_ee_len = ext4_ext_get_actual_len(ex2);
1728 
1729 	if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1730 			le32_to_cpu(ex2->ee_block))
1731 		return 0;
1732 
1733 	if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1734 		return 0;
1735 
1736 	if (ext4_ext_is_unwritten(ex1) &&
1737 	    ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)
1738 		return 0;
1739 #ifdef AGGRESSIVE_TEST
1740 	if (ext1_ee_len >= 4)
1741 		return 0;
1742 #endif
1743 
1744 	if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1745 		return 1;
1746 	return 0;
1747 }
1748 
1749 /*
1750  * This function tries to merge the "ex" extent to the next extent in the tree.
1751  * It always tries to merge towards right. If you want to merge towards
1752  * left, pass "ex - 1" as argument instead of "ex".
1753  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1754  * 1 if they got merged.
1755  */
1756 static int ext4_ext_try_to_merge_right(struct inode *inode,
1757 				 struct ext4_ext_path *path,
1758 				 struct ext4_extent *ex)
1759 {
1760 	struct ext4_extent_header *eh;
1761 	unsigned int depth, len;
1762 	int merge_done = 0, unwritten;
1763 
1764 	depth = ext_depth(inode);
1765 	BUG_ON(path[depth].p_hdr == NULL);
1766 	eh = path[depth].p_hdr;
1767 
1768 	while (ex < EXT_LAST_EXTENT(eh)) {
1769 		if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1770 			break;
1771 		/* merge with next extent! */
1772 		unwritten = ext4_ext_is_unwritten(ex);
1773 		ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1774 				+ ext4_ext_get_actual_len(ex + 1));
1775 		if (unwritten)
1776 			ext4_ext_mark_unwritten(ex);
1777 
1778 		if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1779 			len = (EXT_LAST_EXTENT(eh) - ex - 1)
1780 				* sizeof(struct ext4_extent);
1781 			memmove(ex + 1, ex + 2, len);
1782 		}
1783 		le16_add_cpu(&eh->eh_entries, -1);
1784 		merge_done = 1;
1785 		WARN_ON(eh->eh_entries == 0);
1786 		if (!eh->eh_entries)
1787 			EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1788 	}
1789 
1790 	return merge_done;
1791 }
1792 
1793 /*
1794  * This function does a very simple check to see if we can collapse
1795  * an extent tree with a single extent tree leaf block into the inode.
1796  */
1797 static void ext4_ext_try_to_merge_up(handle_t *handle,
1798 				     struct inode *inode,
1799 				     struct ext4_ext_path *path)
1800 {
1801 	size_t s;
1802 	unsigned max_root = ext4_ext_space_root(inode, 0);
1803 	ext4_fsblk_t blk;
1804 
1805 	if ((path[0].p_depth != 1) ||
1806 	    (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1807 	    (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1808 		return;
1809 
1810 	/*
1811 	 * We need to modify the block allocation bitmap and the block
1812 	 * group descriptor to release the extent tree block.  If we
1813 	 * can't get the journal credits, give up.
1814 	 */
1815 	if (ext4_journal_extend(handle, 2,
1816 			ext4_free_metadata_revoke_credits(inode->i_sb, 1)))
1817 		return;
1818 
1819 	/*
1820 	 * Copy the extent data up to the inode
1821 	 */
1822 	blk = ext4_idx_pblock(path[0].p_idx);
1823 	s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1824 		sizeof(struct ext4_extent_idx);
1825 	s += sizeof(struct ext4_extent_header);
1826 
1827 	path[1].p_maxdepth = path[0].p_maxdepth;
1828 	memcpy(path[0].p_hdr, path[1].p_hdr, s);
1829 	path[0].p_depth = 0;
1830 	path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1831 		(path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1832 	path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1833 
1834 	brelse(path[1].p_bh);
1835 	ext4_free_blocks(handle, inode, NULL, blk, 1,
1836 			 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1837 }
1838 
1839 /*
1840  * This function tries to merge the @ex extent to neighbours in the tree, then
1841  * tries to collapse the extent tree into the inode.
1842  */
1843 static void ext4_ext_try_to_merge(handle_t *handle,
1844 				  struct inode *inode,
1845 				  struct ext4_ext_path *path,
1846 				  struct ext4_extent *ex)
1847 {
1848 	struct ext4_extent_header *eh;
1849 	unsigned int depth;
1850 	int merge_done = 0;
1851 
1852 	depth = ext_depth(inode);
1853 	BUG_ON(path[depth].p_hdr == NULL);
1854 	eh = path[depth].p_hdr;
1855 
1856 	if (ex > EXT_FIRST_EXTENT(eh))
1857 		merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1858 
1859 	if (!merge_done)
1860 		(void) ext4_ext_try_to_merge_right(inode, path, ex);
1861 
1862 	ext4_ext_try_to_merge_up(handle, inode, path);
1863 }
1864 
1865 /*
1866  * check if a portion of the "newext" extent overlaps with an
1867  * existing extent.
1868  *
1869  * If there is an overlap discovered, it updates the length of the newext
1870  * such that there will be no overlap, and then returns 1.
1871  * If there is no overlap found, it returns 0.
1872  */
1873 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1874 					   struct inode *inode,
1875 					   struct ext4_extent *newext,
1876 					   struct ext4_ext_path *path)
1877 {
1878 	ext4_lblk_t b1, b2;
1879 	unsigned int depth, len1;
1880 	unsigned int ret = 0;
1881 
1882 	b1 = le32_to_cpu(newext->ee_block);
1883 	len1 = ext4_ext_get_actual_len(newext);
1884 	depth = ext_depth(inode);
1885 	if (!path[depth].p_ext)
1886 		goto out;
1887 	b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1888 
1889 	/*
1890 	 * get the next allocated block if the extent in the path
1891 	 * is before the requested block(s)
1892 	 */
1893 	if (b2 < b1) {
1894 		b2 = ext4_ext_next_allocated_block(path);
1895 		if (b2 == EXT_MAX_BLOCKS)
1896 			goto out;
1897 		b2 = EXT4_LBLK_CMASK(sbi, b2);
1898 	}
1899 
1900 	/* check for wrap through zero on extent logical start block*/
1901 	if (b1 + len1 < b1) {
1902 		len1 = EXT_MAX_BLOCKS - b1;
1903 		newext->ee_len = cpu_to_le16(len1);
1904 		ret = 1;
1905 	}
1906 
1907 	/* check for overlap */
1908 	if (b1 + len1 > b2) {
1909 		newext->ee_len = cpu_to_le16(b2 - b1);
1910 		ret = 1;
1911 	}
1912 out:
1913 	return ret;
1914 }
1915 
1916 /*
1917  * ext4_ext_insert_extent:
1918  * tries to merge requsted extent into the existing extent or
1919  * inserts requested extent as new one into the tree,
1920  * creating new leaf in the no-space case.
1921  */
1922 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1923 				struct ext4_ext_path **ppath,
1924 				struct ext4_extent *newext, int gb_flags)
1925 {
1926 	struct ext4_ext_path *path = *ppath;
1927 	struct ext4_extent_header *eh;
1928 	struct ext4_extent *ex, *fex;
1929 	struct ext4_extent *nearex; /* nearest extent */
1930 	struct ext4_ext_path *npath = NULL;
1931 	int depth, len, err;
1932 	ext4_lblk_t next;
1933 	int mb_flags = 0, unwritten;
1934 
1935 	if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1936 		mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1937 	if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1938 		EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1939 		return -EFSCORRUPTED;
1940 	}
1941 	depth = ext_depth(inode);
1942 	ex = path[depth].p_ext;
1943 	eh = path[depth].p_hdr;
1944 	if (unlikely(path[depth].p_hdr == NULL)) {
1945 		EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1946 		return -EFSCORRUPTED;
1947 	}
1948 
1949 	/* try to insert block into found extent and return */
1950 	if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1951 
1952 		/*
1953 		 * Try to see whether we should rather test the extent on
1954 		 * right from ex, or from the left of ex. This is because
1955 		 * ext4_find_extent() can return either extent on the
1956 		 * left, or on the right from the searched position. This
1957 		 * will make merging more effective.
1958 		 */
1959 		if (ex < EXT_LAST_EXTENT(eh) &&
1960 		    (le32_to_cpu(ex->ee_block) +
1961 		    ext4_ext_get_actual_len(ex) <
1962 		    le32_to_cpu(newext->ee_block))) {
1963 			ex += 1;
1964 			goto prepend;
1965 		} else if ((ex > EXT_FIRST_EXTENT(eh)) &&
1966 			   (le32_to_cpu(newext->ee_block) +
1967 			   ext4_ext_get_actual_len(newext) <
1968 			   le32_to_cpu(ex->ee_block)))
1969 			ex -= 1;
1970 
1971 		/* Try to append newex to the ex */
1972 		if (ext4_can_extents_be_merged(inode, ex, newext)) {
1973 			ext_debug(inode, "append [%d]%d block to %u:[%d]%d"
1974 				  "(from %llu)\n",
1975 				  ext4_ext_is_unwritten(newext),
1976 				  ext4_ext_get_actual_len(newext),
1977 				  le32_to_cpu(ex->ee_block),
1978 				  ext4_ext_is_unwritten(ex),
1979 				  ext4_ext_get_actual_len(ex),
1980 				  ext4_ext_pblock(ex));
1981 			err = ext4_ext_get_access(handle, inode,
1982 						  path + depth);
1983 			if (err)
1984 				return err;
1985 			unwritten = ext4_ext_is_unwritten(ex);
1986 			ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1987 					+ ext4_ext_get_actual_len(newext));
1988 			if (unwritten)
1989 				ext4_ext_mark_unwritten(ex);
1990 			eh = path[depth].p_hdr;
1991 			nearex = ex;
1992 			goto merge;
1993 		}
1994 
1995 prepend:
1996 		/* Try to prepend newex to the ex */
1997 		if (ext4_can_extents_be_merged(inode, newext, ex)) {
1998 			ext_debug(inode, "prepend %u[%d]%d block to %u:[%d]%d"
1999 				  "(from %llu)\n",
2000 				  le32_to_cpu(newext->ee_block),
2001 				  ext4_ext_is_unwritten(newext),
2002 				  ext4_ext_get_actual_len(newext),
2003 				  le32_to_cpu(ex->ee_block),
2004 				  ext4_ext_is_unwritten(ex),
2005 				  ext4_ext_get_actual_len(ex),
2006 				  ext4_ext_pblock(ex));
2007 			err = ext4_ext_get_access(handle, inode,
2008 						  path + depth);
2009 			if (err)
2010 				return err;
2011 
2012 			unwritten = ext4_ext_is_unwritten(ex);
2013 			ex->ee_block = newext->ee_block;
2014 			ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2015 			ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2016 					+ ext4_ext_get_actual_len(newext));
2017 			if (unwritten)
2018 				ext4_ext_mark_unwritten(ex);
2019 			eh = path[depth].p_hdr;
2020 			nearex = ex;
2021 			goto merge;
2022 		}
2023 	}
2024 
2025 	depth = ext_depth(inode);
2026 	eh = path[depth].p_hdr;
2027 	if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2028 		goto has_space;
2029 
2030 	/* probably next leaf has space for us? */
2031 	fex = EXT_LAST_EXTENT(eh);
2032 	next = EXT_MAX_BLOCKS;
2033 	if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2034 		next = ext4_ext_next_leaf_block(path);
2035 	if (next != EXT_MAX_BLOCKS) {
2036 		ext_debug(inode, "next leaf block - %u\n", next);
2037 		BUG_ON(npath != NULL);
2038 		npath = ext4_find_extent(inode, next, NULL, gb_flags);
2039 		if (IS_ERR(npath))
2040 			return PTR_ERR(npath);
2041 		BUG_ON(npath->p_depth != path->p_depth);
2042 		eh = npath[depth].p_hdr;
2043 		if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2044 			ext_debug(inode, "next leaf isn't full(%d)\n",
2045 				  le16_to_cpu(eh->eh_entries));
2046 			path = npath;
2047 			goto has_space;
2048 		}
2049 		ext_debug(inode, "next leaf has no free space(%d,%d)\n",
2050 			  le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2051 	}
2052 
2053 	/*
2054 	 * There is no free space in the found leaf.
2055 	 * We're gonna add a new leaf in the tree.
2056 	 */
2057 	if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2058 		mb_flags |= EXT4_MB_USE_RESERVED;
2059 	err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2060 				       ppath, newext);
2061 	if (err)
2062 		goto cleanup;
2063 	depth = ext_depth(inode);
2064 	eh = path[depth].p_hdr;
2065 
2066 has_space:
2067 	nearex = path[depth].p_ext;
2068 
2069 	err = ext4_ext_get_access(handle, inode, path + depth);
2070 	if (err)
2071 		goto cleanup;
2072 
2073 	if (!nearex) {
2074 		/* there is no extent in this leaf, create first one */
2075 		ext_debug(inode, "first extent in the leaf: %u:%llu:[%d]%d\n",
2076 				le32_to_cpu(newext->ee_block),
2077 				ext4_ext_pblock(newext),
2078 				ext4_ext_is_unwritten(newext),
2079 				ext4_ext_get_actual_len(newext));
2080 		nearex = EXT_FIRST_EXTENT(eh);
2081 	} else {
2082 		if (le32_to_cpu(newext->ee_block)
2083 			   > le32_to_cpu(nearex->ee_block)) {
2084 			/* Insert after */
2085 			ext_debug(inode, "insert %u:%llu:[%d]%d before: "
2086 					"nearest %p\n",
2087 					le32_to_cpu(newext->ee_block),
2088 					ext4_ext_pblock(newext),
2089 					ext4_ext_is_unwritten(newext),
2090 					ext4_ext_get_actual_len(newext),
2091 					nearex);
2092 			nearex++;
2093 		} else {
2094 			/* Insert before */
2095 			BUG_ON(newext->ee_block == nearex->ee_block);
2096 			ext_debug(inode, "insert %u:%llu:[%d]%d after: "
2097 					"nearest %p\n",
2098 					le32_to_cpu(newext->ee_block),
2099 					ext4_ext_pblock(newext),
2100 					ext4_ext_is_unwritten(newext),
2101 					ext4_ext_get_actual_len(newext),
2102 					nearex);
2103 		}
2104 		len = EXT_LAST_EXTENT(eh) - nearex + 1;
2105 		if (len > 0) {
2106 			ext_debug(inode, "insert %u:%llu:[%d]%d: "
2107 					"move %d extents from 0x%p to 0x%p\n",
2108 					le32_to_cpu(newext->ee_block),
2109 					ext4_ext_pblock(newext),
2110 					ext4_ext_is_unwritten(newext),
2111 					ext4_ext_get_actual_len(newext),
2112 					len, nearex, nearex + 1);
2113 			memmove(nearex + 1, nearex,
2114 				len * sizeof(struct ext4_extent));
2115 		}
2116 	}
2117 
2118 	le16_add_cpu(&eh->eh_entries, 1);
2119 	path[depth].p_ext = nearex;
2120 	nearex->ee_block = newext->ee_block;
2121 	ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2122 	nearex->ee_len = newext->ee_len;
2123 
2124 merge:
2125 	/* try to merge extents */
2126 	if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2127 		ext4_ext_try_to_merge(handle, inode, path, nearex);
2128 
2129 
2130 	/* time to correct all indexes above */
2131 	err = ext4_ext_correct_indexes(handle, inode, path);
2132 	if (err)
2133 		goto cleanup;
2134 
2135 	err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2136 
2137 cleanup:
2138 	ext4_ext_drop_refs(npath);
2139 	kfree(npath);
2140 	return err;
2141 }
2142 
2143 static int ext4_fill_es_cache_info(struct inode *inode,
2144 				   ext4_lblk_t block, ext4_lblk_t num,
2145 				   struct fiemap_extent_info *fieinfo)
2146 {
2147 	ext4_lblk_t next, end = block + num - 1;
2148 	struct extent_status es;
2149 	unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2150 	unsigned int flags;
2151 	int err;
2152 
2153 	while (block <= end) {
2154 		next = 0;
2155 		flags = 0;
2156 		if (!ext4_es_lookup_extent(inode, block, &next, &es))
2157 			break;
2158 		if (ext4_es_is_unwritten(&es))
2159 			flags |= FIEMAP_EXTENT_UNWRITTEN;
2160 		if (ext4_es_is_delayed(&es))
2161 			flags |= (FIEMAP_EXTENT_DELALLOC |
2162 				  FIEMAP_EXTENT_UNKNOWN);
2163 		if (ext4_es_is_hole(&es))
2164 			flags |= EXT4_FIEMAP_EXTENT_HOLE;
2165 		if (next == 0)
2166 			flags |= FIEMAP_EXTENT_LAST;
2167 		if (flags & (FIEMAP_EXTENT_DELALLOC|
2168 			     EXT4_FIEMAP_EXTENT_HOLE))
2169 			es.es_pblk = 0;
2170 		else
2171 			es.es_pblk = ext4_es_pblock(&es);
2172 		err = fiemap_fill_next_extent(fieinfo,
2173 				(__u64)es.es_lblk << blksize_bits,
2174 				(__u64)es.es_pblk << blksize_bits,
2175 				(__u64)es.es_len << blksize_bits,
2176 				flags);
2177 		if (next == 0)
2178 			break;
2179 		block = next;
2180 		if (err < 0)
2181 			return err;
2182 		if (err == 1)
2183 			return 0;
2184 	}
2185 	return 0;
2186 }
2187 
2188 
2189 /*
2190  * ext4_ext_determine_hole - determine hole around given block
2191  * @inode:	inode we lookup in
2192  * @path:	path in extent tree to @lblk
2193  * @lblk:	pointer to logical block around which we want to determine hole
2194  *
2195  * Determine hole length (and start if easily possible) around given logical
2196  * block. We don't try too hard to find the beginning of the hole but @path
2197  * actually points to extent before @lblk, we provide it.
2198  *
2199  * The function returns the length of a hole starting at @lblk. We update @lblk
2200  * to the beginning of the hole if we managed to find it.
2201  */
2202 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2203 					   struct ext4_ext_path *path,
2204 					   ext4_lblk_t *lblk)
2205 {
2206 	int depth = ext_depth(inode);
2207 	struct ext4_extent *ex;
2208 	ext4_lblk_t len;
2209 
2210 	ex = path[depth].p_ext;
2211 	if (ex == NULL) {
2212 		/* there is no extent yet, so gap is [0;-] */
2213 		*lblk = 0;
2214 		len = EXT_MAX_BLOCKS;
2215 	} else if (*lblk < le32_to_cpu(ex->ee_block)) {
2216 		len = le32_to_cpu(ex->ee_block) - *lblk;
2217 	} else if (*lblk >= le32_to_cpu(ex->ee_block)
2218 			+ ext4_ext_get_actual_len(ex)) {
2219 		ext4_lblk_t next;
2220 
2221 		*lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2222 		next = ext4_ext_next_allocated_block(path);
2223 		BUG_ON(next == *lblk);
2224 		len = next - *lblk;
2225 	} else {
2226 		BUG();
2227 	}
2228 	return len;
2229 }
2230 
2231 /*
2232  * ext4_ext_put_gap_in_cache:
2233  * calculate boundaries of the gap that the requested block fits into
2234  * and cache this gap
2235  */
2236 static void
2237 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2238 			  ext4_lblk_t hole_len)
2239 {
2240 	struct extent_status es;
2241 
2242 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
2243 				  hole_start + hole_len - 1, &es);
2244 	if (es.es_len) {
2245 		/* There's delayed extent containing lblock? */
2246 		if (es.es_lblk <= hole_start)
2247 			return;
2248 		hole_len = min(es.es_lblk - hole_start, hole_len);
2249 	}
2250 	ext_debug(inode, " -> %u:%u\n", hole_start, hole_len);
2251 	ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2252 			      EXTENT_STATUS_HOLE);
2253 }
2254 
2255 /*
2256  * ext4_ext_rm_idx:
2257  * removes index from the index block.
2258  */
2259 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2260 			struct ext4_ext_path *path, int depth)
2261 {
2262 	int err;
2263 	ext4_fsblk_t leaf;
2264 
2265 	/* free index block */
2266 	depth--;
2267 	path = path + depth;
2268 	leaf = ext4_idx_pblock(path->p_idx);
2269 	if (unlikely(path->p_hdr->eh_entries == 0)) {
2270 		EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2271 		return -EFSCORRUPTED;
2272 	}
2273 	err = ext4_ext_get_access(handle, inode, path);
2274 	if (err)
2275 		return err;
2276 
2277 	if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2278 		int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2279 		len *= sizeof(struct ext4_extent_idx);
2280 		memmove(path->p_idx, path->p_idx + 1, len);
2281 	}
2282 
2283 	le16_add_cpu(&path->p_hdr->eh_entries, -1);
2284 	err = ext4_ext_dirty(handle, inode, path);
2285 	if (err)
2286 		return err;
2287 	ext_debug(inode, "index is empty, remove it, free block %llu\n", leaf);
2288 	trace_ext4_ext_rm_idx(inode, leaf);
2289 
2290 	ext4_free_blocks(handle, inode, NULL, leaf, 1,
2291 			 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2292 
2293 	while (--depth >= 0) {
2294 		if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2295 			break;
2296 		path--;
2297 		err = ext4_ext_get_access(handle, inode, path);
2298 		if (err)
2299 			break;
2300 		path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2301 		err = ext4_ext_dirty(handle, inode, path);
2302 		if (err)
2303 			break;
2304 	}
2305 	return err;
2306 }
2307 
2308 /*
2309  * ext4_ext_calc_credits_for_single_extent:
2310  * This routine returns max. credits that needed to insert an extent
2311  * to the extent tree.
2312  * When pass the actual path, the caller should calculate credits
2313  * under i_data_sem.
2314  */
2315 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2316 						struct ext4_ext_path *path)
2317 {
2318 	if (path) {
2319 		int depth = ext_depth(inode);
2320 		int ret = 0;
2321 
2322 		/* probably there is space in leaf? */
2323 		if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2324 				< le16_to_cpu(path[depth].p_hdr->eh_max)) {
2325 
2326 			/*
2327 			 *  There are some space in the leaf tree, no
2328 			 *  need to account for leaf block credit
2329 			 *
2330 			 *  bitmaps and block group descriptor blocks
2331 			 *  and other metadata blocks still need to be
2332 			 *  accounted.
2333 			 */
2334 			/* 1 bitmap, 1 block group descriptor */
2335 			ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2336 			return ret;
2337 		}
2338 	}
2339 
2340 	return ext4_chunk_trans_blocks(inode, nrblocks);
2341 }
2342 
2343 /*
2344  * How many index/leaf blocks need to change/allocate to add @extents extents?
2345  *
2346  * If we add a single extent, then in the worse case, each tree level
2347  * index/leaf need to be changed in case of the tree split.
2348  *
2349  * If more extents are inserted, they could cause the whole tree split more
2350  * than once, but this is really rare.
2351  */
2352 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2353 {
2354 	int index;
2355 	int depth;
2356 
2357 	/* If we are converting the inline data, only one is needed here. */
2358 	if (ext4_has_inline_data(inode))
2359 		return 1;
2360 
2361 	depth = ext_depth(inode);
2362 
2363 	if (extents <= 1)
2364 		index = depth * 2;
2365 	else
2366 		index = depth * 3;
2367 
2368 	return index;
2369 }
2370 
2371 static inline int get_default_free_blocks_flags(struct inode *inode)
2372 {
2373 	if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2374 	    ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2375 		return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2376 	else if (ext4_should_journal_data(inode))
2377 		return EXT4_FREE_BLOCKS_FORGET;
2378 	return 0;
2379 }
2380 
2381 /*
2382  * ext4_rereserve_cluster - increment the reserved cluster count when
2383  *                          freeing a cluster with a pending reservation
2384  *
2385  * @inode - file containing the cluster
2386  * @lblk - logical block in cluster to be reserved
2387  *
2388  * Increments the reserved cluster count and adjusts quota in a bigalloc
2389  * file system when freeing a partial cluster containing at least one
2390  * delayed and unwritten block.  A partial cluster meeting that
2391  * requirement will have a pending reservation.  If so, the
2392  * RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
2393  * defer reserved and allocated space accounting to a subsequent call
2394  * to this function.
2395  */
2396 static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
2397 {
2398 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2399 	struct ext4_inode_info *ei = EXT4_I(inode);
2400 
2401 	dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
2402 
2403 	spin_lock(&ei->i_block_reservation_lock);
2404 	ei->i_reserved_data_blocks++;
2405 	percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
2406 	spin_unlock(&ei->i_block_reservation_lock);
2407 
2408 	percpu_counter_add(&sbi->s_freeclusters_counter, 1);
2409 	ext4_remove_pending(inode, lblk);
2410 }
2411 
2412 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2413 			      struct ext4_extent *ex,
2414 			      struct partial_cluster *partial,
2415 			      ext4_lblk_t from, ext4_lblk_t to)
2416 {
2417 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2418 	unsigned short ee_len = ext4_ext_get_actual_len(ex);
2419 	ext4_fsblk_t last_pblk, pblk;
2420 	ext4_lblk_t num;
2421 	int flags;
2422 
2423 	/* only extent tail removal is allowed */
2424 	if (from < le32_to_cpu(ex->ee_block) ||
2425 	    to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
2426 		ext4_error(sbi->s_sb,
2427 			   "strange request: removal(2) %u-%u from %u:%u",
2428 			   from, to, le32_to_cpu(ex->ee_block), ee_len);
2429 		return 0;
2430 	}
2431 
2432 #ifdef EXTENTS_STATS
2433 	spin_lock(&sbi->s_ext_stats_lock);
2434 	sbi->s_ext_blocks += ee_len;
2435 	sbi->s_ext_extents++;
2436 	if (ee_len < sbi->s_ext_min)
2437 		sbi->s_ext_min = ee_len;
2438 	if (ee_len > sbi->s_ext_max)
2439 		sbi->s_ext_max = ee_len;
2440 	if (ext_depth(inode) > sbi->s_depth_max)
2441 		sbi->s_depth_max = ext_depth(inode);
2442 	spin_unlock(&sbi->s_ext_stats_lock);
2443 #endif
2444 
2445 	trace_ext4_remove_blocks(inode, ex, from, to, partial);
2446 
2447 	/*
2448 	 * if we have a partial cluster, and it's different from the
2449 	 * cluster of the last block in the extent, we free it
2450 	 */
2451 	last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
2452 
2453 	if (partial->state != initial &&
2454 	    partial->pclu != EXT4_B2C(sbi, last_pblk)) {
2455 		if (partial->state == tofree) {
2456 			flags = get_default_free_blocks_flags(inode);
2457 			if (ext4_is_pending(inode, partial->lblk))
2458 				flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2459 			ext4_free_blocks(handle, inode, NULL,
2460 					 EXT4_C2B(sbi, partial->pclu),
2461 					 sbi->s_cluster_ratio, flags);
2462 			if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2463 				ext4_rereserve_cluster(inode, partial->lblk);
2464 		}
2465 		partial->state = initial;
2466 	}
2467 
2468 	num = le32_to_cpu(ex->ee_block) + ee_len - from;
2469 	pblk = ext4_ext_pblock(ex) + ee_len - num;
2470 
2471 	/*
2472 	 * We free the partial cluster at the end of the extent (if any),
2473 	 * unless the cluster is used by another extent (partial_cluster
2474 	 * state is nofree).  If a partial cluster exists here, it must be
2475 	 * shared with the last block in the extent.
2476 	 */
2477 	flags = get_default_free_blocks_flags(inode);
2478 
2479 	/* partial, left end cluster aligned, right end unaligned */
2480 	if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
2481 	    (EXT4_LBLK_CMASK(sbi, to) >= from) &&
2482 	    (partial->state != nofree)) {
2483 		if (ext4_is_pending(inode, to))
2484 			flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2485 		ext4_free_blocks(handle, inode, NULL,
2486 				 EXT4_PBLK_CMASK(sbi, last_pblk),
2487 				 sbi->s_cluster_ratio, flags);
2488 		if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2489 			ext4_rereserve_cluster(inode, to);
2490 		partial->state = initial;
2491 		flags = get_default_free_blocks_flags(inode);
2492 	}
2493 
2494 	flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2495 
2496 	/*
2497 	 * For bigalloc file systems, we never free a partial cluster
2498 	 * at the beginning of the extent.  Instead, we check to see if we
2499 	 * need to free it on a subsequent call to ext4_remove_blocks,
2500 	 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2501 	 */
2502 	flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2503 	ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2504 
2505 	/* reset the partial cluster if we've freed past it */
2506 	if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
2507 		partial->state = initial;
2508 
2509 	/*
2510 	 * If we've freed the entire extent but the beginning is not left
2511 	 * cluster aligned and is not marked as ineligible for freeing we
2512 	 * record the partial cluster at the beginning of the extent.  It
2513 	 * wasn't freed by the preceding ext4_free_blocks() call, and we
2514 	 * need to look farther to the left to determine if it's to be freed
2515 	 * (not shared with another extent). Else, reset the partial
2516 	 * cluster - we're either  done freeing or the beginning of the
2517 	 * extent is left cluster aligned.
2518 	 */
2519 	if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
2520 		if (partial->state == initial) {
2521 			partial->pclu = EXT4_B2C(sbi, pblk);
2522 			partial->lblk = from;
2523 			partial->state = tofree;
2524 		}
2525 	} else {
2526 		partial->state = initial;
2527 	}
2528 
2529 	return 0;
2530 }
2531 
2532 /*
2533  * ext4_ext_rm_leaf() Removes the extents associated with the
2534  * blocks appearing between "start" and "end".  Both "start"
2535  * and "end" must appear in the same extent or EIO is returned.
2536  *
2537  * @handle: The journal handle
2538  * @inode:  The files inode
2539  * @path:   The path to the leaf
2540  * @partial_cluster: The cluster which we'll have to free if all extents
2541  *                   has been released from it.  However, if this value is
2542  *                   negative, it's a cluster just to the right of the
2543  *                   punched region and it must not be freed.
2544  * @start:  The first block to remove
2545  * @end:   The last block to remove
2546  */
2547 static int
2548 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2549 		 struct ext4_ext_path *path,
2550 		 struct partial_cluster *partial,
2551 		 ext4_lblk_t start, ext4_lblk_t end)
2552 {
2553 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2554 	int err = 0, correct_index = 0;
2555 	int depth = ext_depth(inode), credits, revoke_credits;
2556 	struct ext4_extent_header *eh;
2557 	ext4_lblk_t a, b;
2558 	unsigned num;
2559 	ext4_lblk_t ex_ee_block;
2560 	unsigned short ex_ee_len;
2561 	unsigned unwritten = 0;
2562 	struct ext4_extent *ex;
2563 	ext4_fsblk_t pblk;
2564 
2565 	/* the header must be checked already in ext4_ext_remove_space() */
2566 	ext_debug(inode, "truncate since %u in leaf to %u\n", start, end);
2567 	if (!path[depth].p_hdr)
2568 		path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2569 	eh = path[depth].p_hdr;
2570 	if (unlikely(path[depth].p_hdr == NULL)) {
2571 		EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2572 		return -EFSCORRUPTED;
2573 	}
2574 	/* find where to start removing */
2575 	ex = path[depth].p_ext;
2576 	if (!ex)
2577 		ex = EXT_LAST_EXTENT(eh);
2578 
2579 	ex_ee_block = le32_to_cpu(ex->ee_block);
2580 	ex_ee_len = ext4_ext_get_actual_len(ex);
2581 
2582 	trace_ext4_ext_rm_leaf(inode, start, ex, partial);
2583 
2584 	while (ex >= EXT_FIRST_EXTENT(eh) &&
2585 			ex_ee_block + ex_ee_len > start) {
2586 
2587 		if (ext4_ext_is_unwritten(ex))
2588 			unwritten = 1;
2589 		else
2590 			unwritten = 0;
2591 
2592 		ext_debug(inode, "remove ext %u:[%d]%d\n", ex_ee_block,
2593 			  unwritten, ex_ee_len);
2594 		path[depth].p_ext = ex;
2595 
2596 		a = ex_ee_block > start ? ex_ee_block : start;
2597 		b = ex_ee_block+ex_ee_len - 1 < end ?
2598 			ex_ee_block+ex_ee_len - 1 : end;
2599 
2600 		ext_debug(inode, "  border %u:%u\n", a, b);
2601 
2602 		/* If this extent is beyond the end of the hole, skip it */
2603 		if (end < ex_ee_block) {
2604 			/*
2605 			 * We're going to skip this extent and move to another,
2606 			 * so note that its first cluster is in use to avoid
2607 			 * freeing it when removing blocks.  Eventually, the
2608 			 * right edge of the truncated/punched region will
2609 			 * be just to the left.
2610 			 */
2611 			if (sbi->s_cluster_ratio > 1) {
2612 				pblk = ext4_ext_pblock(ex);
2613 				partial->pclu = EXT4_B2C(sbi, pblk);
2614 				partial->state = nofree;
2615 			}
2616 			ex--;
2617 			ex_ee_block = le32_to_cpu(ex->ee_block);
2618 			ex_ee_len = ext4_ext_get_actual_len(ex);
2619 			continue;
2620 		} else if (b != ex_ee_block + ex_ee_len - 1) {
2621 			EXT4_ERROR_INODE(inode,
2622 					 "can not handle truncate %u:%u "
2623 					 "on extent %u:%u",
2624 					 start, end, ex_ee_block,
2625 					 ex_ee_block + ex_ee_len - 1);
2626 			err = -EFSCORRUPTED;
2627 			goto out;
2628 		} else if (a != ex_ee_block) {
2629 			/* remove tail of the extent */
2630 			num = a - ex_ee_block;
2631 		} else {
2632 			/* remove whole extent: excellent! */
2633 			num = 0;
2634 		}
2635 		/*
2636 		 * 3 for leaf, sb, and inode plus 2 (bmap and group
2637 		 * descriptor) for each block group; assume two block
2638 		 * groups plus ex_ee_len/blocks_per_block_group for
2639 		 * the worst case
2640 		 */
2641 		credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2642 		if (ex == EXT_FIRST_EXTENT(eh)) {
2643 			correct_index = 1;
2644 			credits += (ext_depth(inode)) + 1;
2645 		}
2646 		credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2647 		/*
2648 		 * We may end up freeing some index blocks and data from the
2649 		 * punched range. Note that partial clusters are accounted for
2650 		 * by ext4_free_data_revoke_credits().
2651 		 */
2652 		revoke_credits =
2653 			ext4_free_metadata_revoke_credits(inode->i_sb,
2654 							  ext_depth(inode)) +
2655 			ext4_free_data_revoke_credits(inode, b - a + 1);
2656 
2657 		err = ext4_datasem_ensure_credits(handle, inode, credits,
2658 						  credits, revoke_credits);
2659 		if (err) {
2660 			if (err > 0)
2661 				err = -EAGAIN;
2662 			goto out;
2663 		}
2664 
2665 		err = ext4_ext_get_access(handle, inode, path + depth);
2666 		if (err)
2667 			goto out;
2668 
2669 		err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
2670 		if (err)
2671 			goto out;
2672 
2673 		if (num == 0)
2674 			/* this extent is removed; mark slot entirely unused */
2675 			ext4_ext_store_pblock(ex, 0);
2676 
2677 		ex->ee_len = cpu_to_le16(num);
2678 		/*
2679 		 * Do not mark unwritten if all the blocks in the
2680 		 * extent have been removed.
2681 		 */
2682 		if (unwritten && num)
2683 			ext4_ext_mark_unwritten(ex);
2684 		/*
2685 		 * If the extent was completely released,
2686 		 * we need to remove it from the leaf
2687 		 */
2688 		if (num == 0) {
2689 			if (end != EXT_MAX_BLOCKS - 1) {
2690 				/*
2691 				 * For hole punching, we need to scoot all the
2692 				 * extents up when an extent is removed so that
2693 				 * we dont have blank extents in the middle
2694 				 */
2695 				memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2696 					sizeof(struct ext4_extent));
2697 
2698 				/* Now get rid of the one at the end */
2699 				memset(EXT_LAST_EXTENT(eh), 0,
2700 					sizeof(struct ext4_extent));
2701 			}
2702 			le16_add_cpu(&eh->eh_entries, -1);
2703 		}
2704 
2705 		err = ext4_ext_dirty(handle, inode, path + depth);
2706 		if (err)
2707 			goto out;
2708 
2709 		ext_debug(inode, "new extent: %u:%u:%llu\n", ex_ee_block, num,
2710 				ext4_ext_pblock(ex));
2711 		ex--;
2712 		ex_ee_block = le32_to_cpu(ex->ee_block);
2713 		ex_ee_len = ext4_ext_get_actual_len(ex);
2714 	}
2715 
2716 	if (correct_index && eh->eh_entries)
2717 		err = ext4_ext_correct_indexes(handle, inode, path);
2718 
2719 	/*
2720 	 * If there's a partial cluster and at least one extent remains in
2721 	 * the leaf, free the partial cluster if it isn't shared with the
2722 	 * current extent.  If it is shared with the current extent
2723 	 * we reset the partial cluster because we've reached the start of the
2724 	 * truncated/punched region and we're done removing blocks.
2725 	 */
2726 	if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
2727 		pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2728 		if (partial->pclu != EXT4_B2C(sbi, pblk)) {
2729 			int flags = get_default_free_blocks_flags(inode);
2730 
2731 			if (ext4_is_pending(inode, partial->lblk))
2732 				flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2733 			ext4_free_blocks(handle, inode, NULL,
2734 					 EXT4_C2B(sbi, partial->pclu),
2735 					 sbi->s_cluster_ratio, flags);
2736 			if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2737 				ext4_rereserve_cluster(inode, partial->lblk);
2738 		}
2739 		partial->state = initial;
2740 	}
2741 
2742 	/* if this leaf is free, then we should
2743 	 * remove it from index block above */
2744 	if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2745 		err = ext4_ext_rm_idx(handle, inode, path, depth);
2746 
2747 out:
2748 	return err;
2749 }
2750 
2751 /*
2752  * ext4_ext_more_to_rm:
2753  * returns 1 if current index has to be freed (even partial)
2754  */
2755 static int
2756 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2757 {
2758 	BUG_ON(path->p_idx == NULL);
2759 
2760 	if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2761 		return 0;
2762 
2763 	/*
2764 	 * if truncate on deeper level happened, it wasn't partial,
2765 	 * so we have to consider current index for truncation
2766 	 */
2767 	if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2768 		return 0;
2769 	return 1;
2770 }
2771 
2772 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2773 			  ext4_lblk_t end)
2774 {
2775 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2776 	int depth = ext_depth(inode);
2777 	struct ext4_ext_path *path = NULL;
2778 	struct partial_cluster partial;
2779 	handle_t *handle;
2780 	int i = 0, err = 0;
2781 
2782 	partial.pclu = 0;
2783 	partial.lblk = 0;
2784 	partial.state = initial;
2785 
2786 	ext_debug(inode, "truncate since %u to %u\n", start, end);
2787 
2788 	/* probably first extent we're gonna free will be last in block */
2789 	handle = ext4_journal_start_with_revoke(inode, EXT4_HT_TRUNCATE,
2790 			depth + 1,
2791 			ext4_free_metadata_revoke_credits(inode->i_sb, depth));
2792 	if (IS_ERR(handle))
2793 		return PTR_ERR(handle);
2794 
2795 again:
2796 	trace_ext4_ext_remove_space(inode, start, end, depth);
2797 
2798 	/*
2799 	 * Check if we are removing extents inside the extent tree. If that
2800 	 * is the case, we are going to punch a hole inside the extent tree
2801 	 * so we have to check whether we need to split the extent covering
2802 	 * the last block to remove so we can easily remove the part of it
2803 	 * in ext4_ext_rm_leaf().
2804 	 */
2805 	if (end < EXT_MAX_BLOCKS - 1) {
2806 		struct ext4_extent *ex;
2807 		ext4_lblk_t ee_block, ex_end, lblk;
2808 		ext4_fsblk_t pblk;
2809 
2810 		/* find extent for or closest extent to this block */
2811 		path = ext4_find_extent(inode, end, NULL,
2812 					EXT4_EX_NOCACHE | EXT4_EX_NOFAIL);
2813 		if (IS_ERR(path)) {
2814 			ext4_journal_stop(handle);
2815 			return PTR_ERR(path);
2816 		}
2817 		depth = ext_depth(inode);
2818 		/* Leaf not may not exist only if inode has no blocks at all */
2819 		ex = path[depth].p_ext;
2820 		if (!ex) {
2821 			if (depth) {
2822 				EXT4_ERROR_INODE(inode,
2823 						 "path[%d].p_hdr == NULL",
2824 						 depth);
2825 				err = -EFSCORRUPTED;
2826 			}
2827 			goto out;
2828 		}
2829 
2830 		ee_block = le32_to_cpu(ex->ee_block);
2831 		ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2832 
2833 		/*
2834 		 * See if the last block is inside the extent, if so split
2835 		 * the extent at 'end' block so we can easily remove the
2836 		 * tail of the first part of the split extent in
2837 		 * ext4_ext_rm_leaf().
2838 		 */
2839 		if (end >= ee_block && end < ex_end) {
2840 
2841 			/*
2842 			 * If we're going to split the extent, note that
2843 			 * the cluster containing the block after 'end' is
2844 			 * in use to avoid freeing it when removing blocks.
2845 			 */
2846 			if (sbi->s_cluster_ratio > 1) {
2847 				pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
2848 				partial.pclu = EXT4_B2C(sbi, pblk);
2849 				partial.state = nofree;
2850 			}
2851 
2852 			/*
2853 			 * Split the extent in two so that 'end' is the last
2854 			 * block in the first new extent. Also we should not
2855 			 * fail removing space due to ENOSPC so try to use
2856 			 * reserved block if that happens.
2857 			 */
2858 			err = ext4_force_split_extent_at(handle, inode, &path,
2859 							 end + 1, 1);
2860 			if (err < 0)
2861 				goto out;
2862 
2863 		} else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
2864 			   partial.state == initial) {
2865 			/*
2866 			 * If we're punching, there's an extent to the right.
2867 			 * If the partial cluster hasn't been set, set it to
2868 			 * that extent's first cluster and its state to nofree
2869 			 * so it won't be freed should it contain blocks to be
2870 			 * removed. If it's already set (tofree/nofree), we're
2871 			 * retrying and keep the original partial cluster info
2872 			 * so a cluster marked tofree as a result of earlier
2873 			 * extent removal is not lost.
2874 			 */
2875 			lblk = ex_end + 1;
2876 			err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2877 						    &ex);
2878 			if (err)
2879 				goto out;
2880 			if (pblk) {
2881 				partial.pclu = EXT4_B2C(sbi, pblk);
2882 				partial.state = nofree;
2883 			}
2884 		}
2885 	}
2886 	/*
2887 	 * We start scanning from right side, freeing all the blocks
2888 	 * after i_size and walking into the tree depth-wise.
2889 	 */
2890 	depth = ext_depth(inode);
2891 	if (path) {
2892 		int k = i = depth;
2893 		while (--k > 0)
2894 			path[k].p_block =
2895 				le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2896 	} else {
2897 		path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
2898 			       GFP_NOFS | __GFP_NOFAIL);
2899 		if (path == NULL) {
2900 			ext4_journal_stop(handle);
2901 			return -ENOMEM;
2902 		}
2903 		path[0].p_maxdepth = path[0].p_depth = depth;
2904 		path[0].p_hdr = ext_inode_hdr(inode);
2905 		i = 0;
2906 
2907 		if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2908 			err = -EFSCORRUPTED;
2909 			goto out;
2910 		}
2911 	}
2912 	err = 0;
2913 
2914 	while (i >= 0 && err == 0) {
2915 		if (i == depth) {
2916 			/* this is leaf block */
2917 			err = ext4_ext_rm_leaf(handle, inode, path,
2918 					       &partial, start, end);
2919 			/* root level has p_bh == NULL, brelse() eats this */
2920 			brelse(path[i].p_bh);
2921 			path[i].p_bh = NULL;
2922 			i--;
2923 			continue;
2924 		}
2925 
2926 		/* this is index block */
2927 		if (!path[i].p_hdr) {
2928 			ext_debug(inode, "initialize header\n");
2929 			path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2930 		}
2931 
2932 		if (!path[i].p_idx) {
2933 			/* this level hasn't been touched yet */
2934 			path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2935 			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2936 			ext_debug(inode, "init index ptr: hdr 0x%p, num %d\n",
2937 				  path[i].p_hdr,
2938 				  le16_to_cpu(path[i].p_hdr->eh_entries));
2939 		} else {
2940 			/* we were already here, see at next index */
2941 			path[i].p_idx--;
2942 		}
2943 
2944 		ext_debug(inode, "level %d - index, first 0x%p, cur 0x%p\n",
2945 				i, EXT_FIRST_INDEX(path[i].p_hdr),
2946 				path[i].p_idx);
2947 		if (ext4_ext_more_to_rm(path + i)) {
2948 			struct buffer_head *bh;
2949 			/* go to the next level */
2950 			ext_debug(inode, "move to level %d (block %llu)\n",
2951 				  i + 1, ext4_idx_pblock(path[i].p_idx));
2952 			memset(path + i + 1, 0, sizeof(*path));
2953 			bh = read_extent_tree_block(inode,
2954 				ext4_idx_pblock(path[i].p_idx), depth - i - 1,
2955 				EXT4_EX_NOCACHE);
2956 			if (IS_ERR(bh)) {
2957 				/* should we reset i_size? */
2958 				err = PTR_ERR(bh);
2959 				break;
2960 			}
2961 			/* Yield here to deal with large extent trees.
2962 			 * Should be a no-op if we did IO above. */
2963 			cond_resched();
2964 			if (WARN_ON(i + 1 > depth)) {
2965 				err = -EFSCORRUPTED;
2966 				break;
2967 			}
2968 			path[i + 1].p_bh = bh;
2969 
2970 			/* save actual number of indexes since this
2971 			 * number is changed at the next iteration */
2972 			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2973 			i++;
2974 		} else {
2975 			/* we finished processing this index, go up */
2976 			if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2977 				/* index is empty, remove it;
2978 				 * handle must be already prepared by the
2979 				 * truncatei_leaf() */
2980 				err = ext4_ext_rm_idx(handle, inode, path, i);
2981 			}
2982 			/* root level has p_bh == NULL, brelse() eats this */
2983 			brelse(path[i].p_bh);
2984 			path[i].p_bh = NULL;
2985 			i--;
2986 			ext_debug(inode, "return to level %d\n", i);
2987 		}
2988 	}
2989 
2990 	trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
2991 					 path->p_hdr->eh_entries);
2992 
2993 	/*
2994 	 * if there's a partial cluster and we have removed the first extent
2995 	 * in the file, then we also free the partial cluster, if any
2996 	 */
2997 	if (partial.state == tofree && err == 0) {
2998 		int flags = get_default_free_blocks_flags(inode);
2999 
3000 		if (ext4_is_pending(inode, partial.lblk))
3001 			flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
3002 		ext4_free_blocks(handle, inode, NULL,
3003 				 EXT4_C2B(sbi, partial.pclu),
3004 				 sbi->s_cluster_ratio, flags);
3005 		if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
3006 			ext4_rereserve_cluster(inode, partial.lblk);
3007 		partial.state = initial;
3008 	}
3009 
3010 	/* TODO: flexible tree reduction should be here */
3011 	if (path->p_hdr->eh_entries == 0) {
3012 		/*
3013 		 * truncate to zero freed all the tree,
3014 		 * so we need to correct eh_depth
3015 		 */
3016 		err = ext4_ext_get_access(handle, inode, path);
3017 		if (err == 0) {
3018 			ext_inode_hdr(inode)->eh_depth = 0;
3019 			ext_inode_hdr(inode)->eh_max =
3020 				cpu_to_le16(ext4_ext_space_root(inode, 0));
3021 			err = ext4_ext_dirty(handle, inode, path);
3022 		}
3023 	}
3024 out:
3025 	ext4_ext_drop_refs(path);
3026 	kfree(path);
3027 	path = NULL;
3028 	if (err == -EAGAIN)
3029 		goto again;
3030 	ext4_journal_stop(handle);
3031 
3032 	return err;
3033 }
3034 
3035 /*
3036  * called at mount time
3037  */
3038 void ext4_ext_init(struct super_block *sb)
3039 {
3040 	/*
3041 	 * possible initialization would be here
3042 	 */
3043 
3044 	if (ext4_has_feature_extents(sb)) {
3045 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3046 		printk(KERN_INFO "EXT4-fs: file extents enabled"
3047 #ifdef AGGRESSIVE_TEST
3048 		       ", aggressive tests"
3049 #endif
3050 #ifdef CHECK_BINSEARCH
3051 		       ", check binsearch"
3052 #endif
3053 #ifdef EXTENTS_STATS
3054 		       ", stats"
3055 #endif
3056 		       "\n");
3057 #endif
3058 #ifdef EXTENTS_STATS
3059 		spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3060 		EXT4_SB(sb)->s_ext_min = 1 << 30;
3061 		EXT4_SB(sb)->s_ext_max = 0;
3062 #endif
3063 	}
3064 }
3065 
3066 /*
3067  * called at umount time
3068  */
3069 void ext4_ext_release(struct super_block *sb)
3070 {
3071 	if (!ext4_has_feature_extents(sb))
3072 		return;
3073 
3074 #ifdef EXTENTS_STATS
3075 	if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3076 		struct ext4_sb_info *sbi = EXT4_SB(sb);
3077 		printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3078 			sbi->s_ext_blocks, sbi->s_ext_extents,
3079 			sbi->s_ext_blocks / sbi->s_ext_extents);
3080 		printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3081 			sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3082 	}
3083 #endif
3084 }
3085 
3086 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3087 {
3088 	ext4_lblk_t  ee_block;
3089 	ext4_fsblk_t ee_pblock;
3090 	unsigned int ee_len;
3091 
3092 	ee_block  = le32_to_cpu(ex->ee_block);
3093 	ee_len    = ext4_ext_get_actual_len(ex);
3094 	ee_pblock = ext4_ext_pblock(ex);
3095 
3096 	if (ee_len == 0)
3097 		return 0;
3098 
3099 	return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3100 				     EXTENT_STATUS_WRITTEN);
3101 }
3102 
3103 /* FIXME!! we need to try to merge to left or right after zero-out  */
3104 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3105 {
3106 	ext4_fsblk_t ee_pblock;
3107 	unsigned int ee_len;
3108 
3109 	ee_len    = ext4_ext_get_actual_len(ex);
3110 	ee_pblock = ext4_ext_pblock(ex);
3111 	return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3112 				  ee_len);
3113 }
3114 
3115 /*
3116  * ext4_split_extent_at() splits an extent at given block.
3117  *
3118  * @handle: the journal handle
3119  * @inode: the file inode
3120  * @path: the path to the extent
3121  * @split: the logical block where the extent is splitted.
3122  * @split_flags: indicates if the extent could be zeroout if split fails, and
3123  *		 the states(init or unwritten) of new extents.
3124  * @flags: flags used to insert new extent to extent tree.
3125  *
3126  *
3127  * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3128  * of which are deterimined by split_flag.
3129  *
3130  * There are two cases:
3131  *  a> the extent are splitted into two extent.
3132  *  b> split is not needed, and just mark the extent.
3133  *
3134  * return 0 on success.
3135  */
3136 static int ext4_split_extent_at(handle_t *handle,
3137 			     struct inode *inode,
3138 			     struct ext4_ext_path **ppath,
3139 			     ext4_lblk_t split,
3140 			     int split_flag,
3141 			     int flags)
3142 {
3143 	struct ext4_ext_path *path = *ppath;
3144 	ext4_fsblk_t newblock;
3145 	ext4_lblk_t ee_block;
3146 	struct ext4_extent *ex, newex, orig_ex, zero_ex;
3147 	struct ext4_extent *ex2 = NULL;
3148 	unsigned int ee_len, depth;
3149 	int err = 0;
3150 
3151 	BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3152 	       (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3153 
3154 	ext_debug(inode, "logical block %llu\n", (unsigned long long)split);
3155 
3156 	ext4_ext_show_leaf(inode, path);
3157 
3158 	depth = ext_depth(inode);
3159 	ex = path[depth].p_ext;
3160 	ee_block = le32_to_cpu(ex->ee_block);
3161 	ee_len = ext4_ext_get_actual_len(ex);
3162 	newblock = split - ee_block + ext4_ext_pblock(ex);
3163 
3164 	BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3165 	BUG_ON(!ext4_ext_is_unwritten(ex) &&
3166 	       split_flag & (EXT4_EXT_MAY_ZEROOUT |
3167 			     EXT4_EXT_MARK_UNWRIT1 |
3168 			     EXT4_EXT_MARK_UNWRIT2));
3169 
3170 	err = ext4_ext_get_access(handle, inode, path + depth);
3171 	if (err)
3172 		goto out;
3173 
3174 	if (split == ee_block) {
3175 		/*
3176 		 * case b: block @split is the block that the extent begins with
3177 		 * then we just change the state of the extent, and splitting
3178 		 * is not needed.
3179 		 */
3180 		if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3181 			ext4_ext_mark_unwritten(ex);
3182 		else
3183 			ext4_ext_mark_initialized(ex);
3184 
3185 		if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3186 			ext4_ext_try_to_merge(handle, inode, path, ex);
3187 
3188 		err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3189 		goto out;
3190 	}
3191 
3192 	/* case a */
3193 	memcpy(&orig_ex, ex, sizeof(orig_ex));
3194 	ex->ee_len = cpu_to_le16(split - ee_block);
3195 	if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3196 		ext4_ext_mark_unwritten(ex);
3197 
3198 	/*
3199 	 * path may lead to new leaf, not to original leaf any more
3200 	 * after ext4_ext_insert_extent() returns,
3201 	 */
3202 	err = ext4_ext_dirty(handle, inode, path + depth);
3203 	if (err)
3204 		goto fix_extent_len;
3205 
3206 	ex2 = &newex;
3207 	ex2->ee_block = cpu_to_le32(split);
3208 	ex2->ee_len   = cpu_to_le16(ee_len - (split - ee_block));
3209 	ext4_ext_store_pblock(ex2, newblock);
3210 	if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3211 		ext4_ext_mark_unwritten(ex2);
3212 
3213 	err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3214 	if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3215 		if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3216 			if (split_flag & EXT4_EXT_DATA_VALID1) {
3217 				err = ext4_ext_zeroout(inode, ex2);
3218 				zero_ex.ee_block = ex2->ee_block;
3219 				zero_ex.ee_len = cpu_to_le16(
3220 						ext4_ext_get_actual_len(ex2));
3221 				ext4_ext_store_pblock(&zero_ex,
3222 						      ext4_ext_pblock(ex2));
3223 			} else {
3224 				err = ext4_ext_zeroout(inode, ex);
3225 				zero_ex.ee_block = ex->ee_block;
3226 				zero_ex.ee_len = cpu_to_le16(
3227 						ext4_ext_get_actual_len(ex));
3228 				ext4_ext_store_pblock(&zero_ex,
3229 						      ext4_ext_pblock(ex));
3230 			}
3231 		} else {
3232 			err = ext4_ext_zeroout(inode, &orig_ex);
3233 			zero_ex.ee_block = orig_ex.ee_block;
3234 			zero_ex.ee_len = cpu_to_le16(
3235 						ext4_ext_get_actual_len(&orig_ex));
3236 			ext4_ext_store_pblock(&zero_ex,
3237 					      ext4_ext_pblock(&orig_ex));
3238 		}
3239 
3240 		if (err)
3241 			goto fix_extent_len;
3242 		/* update the extent length and mark as initialized */
3243 		ex->ee_len = cpu_to_le16(ee_len);
3244 		ext4_ext_try_to_merge(handle, inode, path, ex);
3245 		err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3246 		if (err)
3247 			goto fix_extent_len;
3248 
3249 		/* update extent status tree */
3250 		err = ext4_zeroout_es(inode, &zero_ex);
3251 
3252 		goto out;
3253 	} else if (err)
3254 		goto fix_extent_len;
3255 
3256 out:
3257 	ext4_ext_show_leaf(inode, path);
3258 	return err;
3259 
3260 fix_extent_len:
3261 	ex->ee_len = orig_ex.ee_len;
3262 	/*
3263 	 * Ignore ext4_ext_dirty return value since we are already in error path
3264 	 * and err is a non-zero error code.
3265 	 */
3266 	ext4_ext_dirty(handle, inode, path + path->p_depth);
3267 	return err;
3268 }
3269 
3270 /*
3271  * ext4_split_extents() splits an extent and mark extent which is covered
3272  * by @map as split_flags indicates
3273  *
3274  * It may result in splitting the extent into multiple extents (up to three)
3275  * There are three possibilities:
3276  *   a> There is no split required
3277  *   b> Splits in two extents: Split is happening at either end of the extent
3278  *   c> Splits in three extents: Somone is splitting in middle of the extent
3279  *
3280  */
3281 static int ext4_split_extent(handle_t *handle,
3282 			      struct inode *inode,
3283 			      struct ext4_ext_path **ppath,
3284 			      struct ext4_map_blocks *map,
3285 			      int split_flag,
3286 			      int flags)
3287 {
3288 	struct ext4_ext_path *path = *ppath;
3289 	ext4_lblk_t ee_block;
3290 	struct ext4_extent *ex;
3291 	unsigned int ee_len, depth;
3292 	int err = 0;
3293 	int unwritten;
3294 	int split_flag1, flags1;
3295 	int allocated = map->m_len;
3296 
3297 	depth = ext_depth(inode);
3298 	ex = path[depth].p_ext;
3299 	ee_block = le32_to_cpu(ex->ee_block);
3300 	ee_len = ext4_ext_get_actual_len(ex);
3301 	unwritten = ext4_ext_is_unwritten(ex);
3302 
3303 	if (map->m_lblk + map->m_len < ee_block + ee_len) {
3304 		split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3305 		flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3306 		if (unwritten)
3307 			split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3308 				       EXT4_EXT_MARK_UNWRIT2;
3309 		if (split_flag & EXT4_EXT_DATA_VALID2)
3310 			split_flag1 |= EXT4_EXT_DATA_VALID1;
3311 		err = ext4_split_extent_at(handle, inode, ppath,
3312 				map->m_lblk + map->m_len, split_flag1, flags1);
3313 		if (err)
3314 			goto out;
3315 	} else {
3316 		allocated = ee_len - (map->m_lblk - ee_block);
3317 	}
3318 	/*
3319 	 * Update path is required because previous ext4_split_extent_at() may
3320 	 * result in split of original leaf or extent zeroout.
3321 	 */
3322 	path = ext4_find_extent(inode, map->m_lblk, ppath, flags);
3323 	if (IS_ERR(path))
3324 		return PTR_ERR(path);
3325 	depth = ext_depth(inode);
3326 	ex = path[depth].p_ext;
3327 	if (!ex) {
3328 		EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3329 				 (unsigned long) map->m_lblk);
3330 		return -EFSCORRUPTED;
3331 	}
3332 	unwritten = ext4_ext_is_unwritten(ex);
3333 	split_flag1 = 0;
3334 
3335 	if (map->m_lblk >= ee_block) {
3336 		split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3337 		if (unwritten) {
3338 			split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3339 			split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3340 						     EXT4_EXT_MARK_UNWRIT2);
3341 		}
3342 		err = ext4_split_extent_at(handle, inode, ppath,
3343 				map->m_lblk, split_flag1, flags);
3344 		if (err)
3345 			goto out;
3346 	}
3347 
3348 	ext4_ext_show_leaf(inode, path);
3349 out:
3350 	return err ? err : allocated;
3351 }
3352 
3353 /*
3354  * This function is called by ext4_ext_map_blocks() if someone tries to write
3355  * to an unwritten extent. It may result in splitting the unwritten
3356  * extent into multiple extents (up to three - one initialized and two
3357  * unwritten).
3358  * There are three possibilities:
3359  *   a> There is no split required: Entire extent should be initialized
3360  *   b> Splits in two extents: Write is happening at either end of the extent
3361  *   c> Splits in three extents: Somone is writing in middle of the extent
3362  *
3363  * Pre-conditions:
3364  *  - The extent pointed to by 'path' is unwritten.
3365  *  - The extent pointed to by 'path' contains a superset
3366  *    of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3367  *
3368  * Post-conditions on success:
3369  *  - the returned value is the number of blocks beyond map->l_lblk
3370  *    that are allocated and initialized.
3371  *    It is guaranteed to be >= map->m_len.
3372  */
3373 static int ext4_ext_convert_to_initialized(handle_t *handle,
3374 					   struct inode *inode,
3375 					   struct ext4_map_blocks *map,
3376 					   struct ext4_ext_path **ppath,
3377 					   int flags)
3378 {
3379 	struct ext4_ext_path *path = *ppath;
3380 	struct ext4_sb_info *sbi;
3381 	struct ext4_extent_header *eh;
3382 	struct ext4_map_blocks split_map;
3383 	struct ext4_extent zero_ex1, zero_ex2;
3384 	struct ext4_extent *ex, *abut_ex;
3385 	ext4_lblk_t ee_block, eof_block;
3386 	unsigned int ee_len, depth, map_len = map->m_len;
3387 	int allocated = 0, max_zeroout = 0;
3388 	int err = 0;
3389 	int split_flag = EXT4_EXT_DATA_VALID2;
3390 
3391 	ext_debug(inode, "logical block %llu, max_blocks %u\n",
3392 		  (unsigned long long)map->m_lblk, map_len);
3393 
3394 	sbi = EXT4_SB(inode->i_sb);
3395 	eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3396 			>> inode->i_sb->s_blocksize_bits;
3397 	if (eof_block < map->m_lblk + map_len)
3398 		eof_block = map->m_lblk + map_len;
3399 
3400 	depth = ext_depth(inode);
3401 	eh = path[depth].p_hdr;
3402 	ex = path[depth].p_ext;
3403 	ee_block = le32_to_cpu(ex->ee_block);
3404 	ee_len = ext4_ext_get_actual_len(ex);
3405 	zero_ex1.ee_len = 0;
3406 	zero_ex2.ee_len = 0;
3407 
3408 	trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3409 
3410 	/* Pre-conditions */
3411 	BUG_ON(!ext4_ext_is_unwritten(ex));
3412 	BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3413 
3414 	/*
3415 	 * Attempt to transfer newly initialized blocks from the currently
3416 	 * unwritten extent to its neighbor. This is much cheaper
3417 	 * than an insertion followed by a merge as those involve costly
3418 	 * memmove() calls. Transferring to the left is the common case in
3419 	 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3420 	 * followed by append writes.
3421 	 *
3422 	 * Limitations of the current logic:
3423 	 *  - L1: we do not deal with writes covering the whole extent.
3424 	 *    This would require removing the extent if the transfer
3425 	 *    is possible.
3426 	 *  - L2: we only attempt to merge with an extent stored in the
3427 	 *    same extent tree node.
3428 	 */
3429 	if ((map->m_lblk == ee_block) &&
3430 		/* See if we can merge left */
3431 		(map_len < ee_len) &&		/*L1*/
3432 		(ex > EXT_FIRST_EXTENT(eh))) {	/*L2*/
3433 		ext4_lblk_t prev_lblk;
3434 		ext4_fsblk_t prev_pblk, ee_pblk;
3435 		unsigned int prev_len;
3436 
3437 		abut_ex = ex - 1;
3438 		prev_lblk = le32_to_cpu(abut_ex->ee_block);
3439 		prev_len = ext4_ext_get_actual_len(abut_ex);
3440 		prev_pblk = ext4_ext_pblock(abut_ex);
3441 		ee_pblk = ext4_ext_pblock(ex);
3442 
3443 		/*
3444 		 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3445 		 * upon those conditions:
3446 		 * - C1: abut_ex is initialized,
3447 		 * - C2: abut_ex is logically abutting ex,
3448 		 * - C3: abut_ex is physically abutting ex,
3449 		 * - C4: abut_ex can receive the additional blocks without
3450 		 *   overflowing the (initialized) length limit.
3451 		 */
3452 		if ((!ext4_ext_is_unwritten(abut_ex)) &&		/*C1*/
3453 			((prev_lblk + prev_len) == ee_block) &&		/*C2*/
3454 			((prev_pblk + prev_len) == ee_pblk) &&		/*C3*/
3455 			(prev_len < (EXT_INIT_MAX_LEN - map_len))) {	/*C4*/
3456 			err = ext4_ext_get_access(handle, inode, path + depth);
3457 			if (err)
3458 				goto out;
3459 
3460 			trace_ext4_ext_convert_to_initialized_fastpath(inode,
3461 				map, ex, abut_ex);
3462 
3463 			/* Shift the start of ex by 'map_len' blocks */
3464 			ex->ee_block = cpu_to_le32(ee_block + map_len);
3465 			ext4_ext_store_pblock(ex, ee_pblk + map_len);
3466 			ex->ee_len = cpu_to_le16(ee_len - map_len);
3467 			ext4_ext_mark_unwritten(ex); /* Restore the flag */
3468 
3469 			/* Extend abut_ex by 'map_len' blocks */
3470 			abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3471 
3472 			/* Result: number of initialized blocks past m_lblk */
3473 			allocated = map_len;
3474 		}
3475 	} else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3476 		   (map_len < ee_len) &&	/*L1*/
3477 		   ex < EXT_LAST_EXTENT(eh)) {	/*L2*/
3478 		/* See if we can merge right */
3479 		ext4_lblk_t next_lblk;
3480 		ext4_fsblk_t next_pblk, ee_pblk;
3481 		unsigned int next_len;
3482 
3483 		abut_ex = ex + 1;
3484 		next_lblk = le32_to_cpu(abut_ex->ee_block);
3485 		next_len = ext4_ext_get_actual_len(abut_ex);
3486 		next_pblk = ext4_ext_pblock(abut_ex);
3487 		ee_pblk = ext4_ext_pblock(ex);
3488 
3489 		/*
3490 		 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3491 		 * upon those conditions:
3492 		 * - C1: abut_ex is initialized,
3493 		 * - C2: abut_ex is logically abutting ex,
3494 		 * - C3: abut_ex is physically abutting ex,
3495 		 * - C4: abut_ex can receive the additional blocks without
3496 		 *   overflowing the (initialized) length limit.
3497 		 */
3498 		if ((!ext4_ext_is_unwritten(abut_ex)) &&		/*C1*/
3499 		    ((map->m_lblk + map_len) == next_lblk) &&		/*C2*/
3500 		    ((ee_pblk + ee_len) == next_pblk) &&		/*C3*/
3501 		    (next_len < (EXT_INIT_MAX_LEN - map_len))) {	/*C4*/
3502 			err = ext4_ext_get_access(handle, inode, path + depth);
3503 			if (err)
3504 				goto out;
3505 
3506 			trace_ext4_ext_convert_to_initialized_fastpath(inode,
3507 				map, ex, abut_ex);
3508 
3509 			/* Shift the start of abut_ex by 'map_len' blocks */
3510 			abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3511 			ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3512 			ex->ee_len = cpu_to_le16(ee_len - map_len);
3513 			ext4_ext_mark_unwritten(ex); /* Restore the flag */
3514 
3515 			/* Extend abut_ex by 'map_len' blocks */
3516 			abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3517 
3518 			/* Result: number of initialized blocks past m_lblk */
3519 			allocated = map_len;
3520 		}
3521 	}
3522 	if (allocated) {
3523 		/* Mark the block containing both extents as dirty */
3524 		err = ext4_ext_dirty(handle, inode, path + depth);
3525 
3526 		/* Update path to point to the right extent */
3527 		path[depth].p_ext = abut_ex;
3528 		goto out;
3529 	} else
3530 		allocated = ee_len - (map->m_lblk - ee_block);
3531 
3532 	WARN_ON(map->m_lblk < ee_block);
3533 	/*
3534 	 * It is safe to convert extent to initialized via explicit
3535 	 * zeroout only if extent is fully inside i_size or new_size.
3536 	 */
3537 	split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3538 
3539 	if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3540 		max_zeroout = sbi->s_extent_max_zeroout_kb >>
3541 			(inode->i_sb->s_blocksize_bits - 10);
3542 
3543 	/*
3544 	 * five cases:
3545 	 * 1. split the extent into three extents.
3546 	 * 2. split the extent into two extents, zeroout the head of the first
3547 	 *    extent.
3548 	 * 3. split the extent into two extents, zeroout the tail of the second
3549 	 *    extent.
3550 	 * 4. split the extent into two extents with out zeroout.
3551 	 * 5. no splitting needed, just possibly zeroout the head and / or the
3552 	 *    tail of the extent.
3553 	 */
3554 	split_map.m_lblk = map->m_lblk;
3555 	split_map.m_len = map->m_len;
3556 
3557 	if (max_zeroout && (allocated > split_map.m_len)) {
3558 		if (allocated <= max_zeroout) {
3559 			/* case 3 or 5 */
3560 			zero_ex1.ee_block =
3561 				 cpu_to_le32(split_map.m_lblk +
3562 					     split_map.m_len);
3563 			zero_ex1.ee_len =
3564 				cpu_to_le16(allocated - split_map.m_len);
3565 			ext4_ext_store_pblock(&zero_ex1,
3566 				ext4_ext_pblock(ex) + split_map.m_lblk +
3567 				split_map.m_len - ee_block);
3568 			err = ext4_ext_zeroout(inode, &zero_ex1);
3569 			if (err)
3570 				goto out;
3571 			split_map.m_len = allocated;
3572 		}
3573 		if (split_map.m_lblk - ee_block + split_map.m_len <
3574 								max_zeroout) {
3575 			/* case 2 or 5 */
3576 			if (split_map.m_lblk != ee_block) {
3577 				zero_ex2.ee_block = ex->ee_block;
3578 				zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3579 							ee_block);
3580 				ext4_ext_store_pblock(&zero_ex2,
3581 						      ext4_ext_pblock(ex));
3582 				err = ext4_ext_zeroout(inode, &zero_ex2);
3583 				if (err)
3584 					goto out;
3585 			}
3586 
3587 			split_map.m_len += split_map.m_lblk - ee_block;
3588 			split_map.m_lblk = ee_block;
3589 			allocated = map->m_len;
3590 		}
3591 	}
3592 
3593 	err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3594 				flags);
3595 	if (err > 0)
3596 		err = 0;
3597 out:
3598 	/* If we have gotten a failure, don't zero out status tree */
3599 	if (!err) {
3600 		err = ext4_zeroout_es(inode, &zero_ex1);
3601 		if (!err)
3602 			err = ext4_zeroout_es(inode, &zero_ex2);
3603 	}
3604 	return err ? err : allocated;
3605 }
3606 
3607 /*
3608  * This function is called by ext4_ext_map_blocks() from
3609  * ext4_get_blocks_dio_write() when DIO to write
3610  * to an unwritten extent.
3611  *
3612  * Writing to an unwritten extent may result in splitting the unwritten
3613  * extent into multiple initialized/unwritten extents (up to three)
3614  * There are three possibilities:
3615  *   a> There is no split required: Entire extent should be unwritten
3616  *   b> Splits in two extents: Write is happening at either end of the extent
3617  *   c> Splits in three extents: Somone is writing in middle of the extent
3618  *
3619  * This works the same way in the case of initialized -> unwritten conversion.
3620  *
3621  * One of more index blocks maybe needed if the extent tree grow after
3622  * the unwritten extent split. To prevent ENOSPC occur at the IO
3623  * complete, we need to split the unwritten extent before DIO submit
3624  * the IO. The unwritten extent called at this time will be split
3625  * into three unwritten extent(at most). After IO complete, the part
3626  * being filled will be convert to initialized by the end_io callback function
3627  * via ext4_convert_unwritten_extents().
3628  *
3629  * Returns the size of unwritten extent to be written on success.
3630  */
3631 static int ext4_split_convert_extents(handle_t *handle,
3632 					struct inode *inode,
3633 					struct ext4_map_blocks *map,
3634 					struct ext4_ext_path **ppath,
3635 					int flags)
3636 {
3637 	struct ext4_ext_path *path = *ppath;
3638 	ext4_lblk_t eof_block;
3639 	ext4_lblk_t ee_block;
3640 	struct ext4_extent *ex;
3641 	unsigned int ee_len;
3642 	int split_flag = 0, depth;
3643 
3644 	ext_debug(inode, "logical block %llu, max_blocks %u\n",
3645 		  (unsigned long long)map->m_lblk, map->m_len);
3646 
3647 	eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3648 			>> inode->i_sb->s_blocksize_bits;
3649 	if (eof_block < map->m_lblk + map->m_len)
3650 		eof_block = map->m_lblk + map->m_len;
3651 	/*
3652 	 * It is safe to convert extent to initialized via explicit
3653 	 * zeroout only if extent is fully insde i_size or new_size.
3654 	 */
3655 	depth = ext_depth(inode);
3656 	ex = path[depth].p_ext;
3657 	ee_block = le32_to_cpu(ex->ee_block);
3658 	ee_len = ext4_ext_get_actual_len(ex);
3659 
3660 	/* Convert to unwritten */
3661 	if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3662 		split_flag |= EXT4_EXT_DATA_VALID1;
3663 	/* Convert to initialized */
3664 	} else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3665 		split_flag |= ee_block + ee_len <= eof_block ?
3666 			      EXT4_EXT_MAY_ZEROOUT : 0;
3667 		split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3668 	}
3669 	flags |= EXT4_GET_BLOCKS_PRE_IO;
3670 	return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3671 }
3672 
3673 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3674 						struct inode *inode,
3675 						struct ext4_map_blocks *map,
3676 						struct ext4_ext_path **ppath)
3677 {
3678 	struct ext4_ext_path *path = *ppath;
3679 	struct ext4_extent *ex;
3680 	ext4_lblk_t ee_block;
3681 	unsigned int ee_len;
3682 	int depth;
3683 	int err = 0;
3684 
3685 	depth = ext_depth(inode);
3686 	ex = path[depth].p_ext;
3687 	ee_block = le32_to_cpu(ex->ee_block);
3688 	ee_len = ext4_ext_get_actual_len(ex);
3689 
3690 	ext_debug(inode, "logical block %llu, max_blocks %u\n",
3691 		  (unsigned long long)ee_block, ee_len);
3692 
3693 	/* If extent is larger than requested it is a clear sign that we still
3694 	 * have some extent state machine issues left. So extent_split is still
3695 	 * required.
3696 	 * TODO: Once all related issues will be fixed this situation should be
3697 	 * illegal.
3698 	 */
3699 	if (ee_block != map->m_lblk || ee_len > map->m_len) {
3700 #ifdef CONFIG_EXT4_DEBUG
3701 		ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3702 			     " len %u; IO logical block %llu, len %u",
3703 			     inode->i_ino, (unsigned long long)ee_block, ee_len,
3704 			     (unsigned long long)map->m_lblk, map->m_len);
3705 #endif
3706 		err = ext4_split_convert_extents(handle, inode, map, ppath,
3707 						 EXT4_GET_BLOCKS_CONVERT);
3708 		if (err < 0)
3709 			return err;
3710 		path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3711 		if (IS_ERR(path))
3712 			return PTR_ERR(path);
3713 		depth = ext_depth(inode);
3714 		ex = path[depth].p_ext;
3715 	}
3716 
3717 	err = ext4_ext_get_access(handle, inode, path + depth);
3718 	if (err)
3719 		goto out;
3720 	/* first mark the extent as initialized */
3721 	ext4_ext_mark_initialized(ex);
3722 
3723 	/* note: ext4_ext_correct_indexes() isn't needed here because
3724 	 * borders are not changed
3725 	 */
3726 	ext4_ext_try_to_merge(handle, inode, path, ex);
3727 
3728 	/* Mark modified extent as dirty */
3729 	err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3730 out:
3731 	ext4_ext_show_leaf(inode, path);
3732 	return err;
3733 }
3734 
3735 static int
3736 convert_initialized_extent(handle_t *handle, struct inode *inode,
3737 			   struct ext4_map_blocks *map,
3738 			   struct ext4_ext_path **ppath,
3739 			   unsigned int *allocated)
3740 {
3741 	struct ext4_ext_path *path = *ppath;
3742 	struct ext4_extent *ex;
3743 	ext4_lblk_t ee_block;
3744 	unsigned int ee_len;
3745 	int depth;
3746 	int err = 0;
3747 
3748 	/*
3749 	 * Make sure that the extent is no bigger than we support with
3750 	 * unwritten extent
3751 	 */
3752 	if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3753 		map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3754 
3755 	depth = ext_depth(inode);
3756 	ex = path[depth].p_ext;
3757 	ee_block = le32_to_cpu(ex->ee_block);
3758 	ee_len = ext4_ext_get_actual_len(ex);
3759 
3760 	ext_debug(inode, "logical block %llu, max_blocks %u\n",
3761 		  (unsigned long long)ee_block, ee_len);
3762 
3763 	if (ee_block != map->m_lblk || ee_len > map->m_len) {
3764 		err = ext4_split_convert_extents(handle, inode, map, ppath,
3765 				EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3766 		if (err < 0)
3767 			return err;
3768 		path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3769 		if (IS_ERR(path))
3770 			return PTR_ERR(path);
3771 		depth = ext_depth(inode);
3772 		ex = path[depth].p_ext;
3773 		if (!ex) {
3774 			EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3775 					 (unsigned long) map->m_lblk);
3776 			return -EFSCORRUPTED;
3777 		}
3778 	}
3779 
3780 	err = ext4_ext_get_access(handle, inode, path + depth);
3781 	if (err)
3782 		return err;
3783 	/* first mark the extent as unwritten */
3784 	ext4_ext_mark_unwritten(ex);
3785 
3786 	/* note: ext4_ext_correct_indexes() isn't needed here because
3787 	 * borders are not changed
3788 	 */
3789 	ext4_ext_try_to_merge(handle, inode, path, ex);
3790 
3791 	/* Mark modified extent as dirty */
3792 	err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3793 	if (err)
3794 		return err;
3795 	ext4_ext_show_leaf(inode, path);
3796 
3797 	ext4_update_inode_fsync_trans(handle, inode, 1);
3798 
3799 	map->m_flags |= EXT4_MAP_UNWRITTEN;
3800 	if (*allocated > map->m_len)
3801 		*allocated = map->m_len;
3802 	map->m_len = *allocated;
3803 	return 0;
3804 }
3805 
3806 static int
3807 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
3808 			struct ext4_map_blocks *map,
3809 			struct ext4_ext_path **ppath, int flags,
3810 			unsigned int allocated, ext4_fsblk_t newblock)
3811 {
3812 	struct ext4_ext_path __maybe_unused *path = *ppath;
3813 	int ret = 0;
3814 	int err = 0;
3815 
3816 	ext_debug(inode, "logical block %llu, max_blocks %u, flags 0x%x, allocated %u\n",
3817 		  (unsigned long long)map->m_lblk, map->m_len, flags,
3818 		  allocated);
3819 	ext4_ext_show_leaf(inode, path);
3820 
3821 	/*
3822 	 * When writing into unwritten space, we should not fail to
3823 	 * allocate metadata blocks for the new extent block if needed.
3824 	 */
3825 	flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
3826 
3827 	trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
3828 						    allocated, newblock);
3829 
3830 	/* get_block() before submitting IO, split the extent */
3831 	if (flags & EXT4_GET_BLOCKS_PRE_IO) {
3832 		ret = ext4_split_convert_extents(handle, inode, map, ppath,
3833 					 flags | EXT4_GET_BLOCKS_CONVERT);
3834 		if (ret < 0) {
3835 			err = ret;
3836 			goto out2;
3837 		}
3838 		/*
3839 		 * shouldn't get a 0 return when splitting an extent unless
3840 		 * m_len is 0 (bug) or extent has been corrupted
3841 		 */
3842 		if (unlikely(ret == 0)) {
3843 			EXT4_ERROR_INODE(inode,
3844 					 "unexpected ret == 0, m_len = %u",
3845 					 map->m_len);
3846 			err = -EFSCORRUPTED;
3847 			goto out2;
3848 		}
3849 		map->m_flags |= EXT4_MAP_UNWRITTEN;
3850 		goto out;
3851 	}
3852 	/* IO end_io complete, convert the filled extent to written */
3853 	if (flags & EXT4_GET_BLOCKS_CONVERT) {
3854 		err = ext4_convert_unwritten_extents_endio(handle, inode, map,
3855 							   ppath);
3856 		if (err < 0)
3857 			goto out2;
3858 		ext4_update_inode_fsync_trans(handle, inode, 1);
3859 		goto map_out;
3860 	}
3861 	/* buffered IO cases */
3862 	/*
3863 	 * repeat fallocate creation request
3864 	 * we already have an unwritten extent
3865 	 */
3866 	if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
3867 		map->m_flags |= EXT4_MAP_UNWRITTEN;
3868 		goto map_out;
3869 	}
3870 
3871 	/* buffered READ or buffered write_begin() lookup */
3872 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3873 		/*
3874 		 * We have blocks reserved already.  We
3875 		 * return allocated blocks so that delalloc
3876 		 * won't do block reservation for us.  But
3877 		 * the buffer head will be unmapped so that
3878 		 * a read from the block returns 0s.
3879 		 */
3880 		map->m_flags |= EXT4_MAP_UNWRITTEN;
3881 		goto out1;
3882 	}
3883 
3884 	/*
3885 	 * Default case when (flags & EXT4_GET_BLOCKS_CREATE) == 1.
3886 	 * For buffered writes, at writepage time, etc.  Convert a
3887 	 * discovered unwritten extent to written.
3888 	 */
3889 	ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
3890 	if (ret < 0) {
3891 		err = ret;
3892 		goto out2;
3893 	}
3894 	ext4_update_inode_fsync_trans(handle, inode, 1);
3895 	/*
3896 	 * shouldn't get a 0 return when converting an unwritten extent
3897 	 * unless m_len is 0 (bug) or extent has been corrupted
3898 	 */
3899 	if (unlikely(ret == 0)) {
3900 		EXT4_ERROR_INODE(inode, "unexpected ret == 0, m_len = %u",
3901 				 map->m_len);
3902 		err = -EFSCORRUPTED;
3903 		goto out2;
3904 	}
3905 
3906 out:
3907 	allocated = ret;
3908 	map->m_flags |= EXT4_MAP_NEW;
3909 map_out:
3910 	map->m_flags |= EXT4_MAP_MAPPED;
3911 out1:
3912 	map->m_pblk = newblock;
3913 	if (allocated > map->m_len)
3914 		allocated = map->m_len;
3915 	map->m_len = allocated;
3916 	ext4_ext_show_leaf(inode, path);
3917 out2:
3918 	return err ? err : allocated;
3919 }
3920 
3921 /*
3922  * get_implied_cluster_alloc - check to see if the requested
3923  * allocation (in the map structure) overlaps with a cluster already
3924  * allocated in an extent.
3925  *	@sb	The filesystem superblock structure
3926  *	@map	The requested lblk->pblk mapping
3927  *	@ex	The extent structure which might contain an implied
3928  *			cluster allocation
3929  *
3930  * This function is called by ext4_ext_map_blocks() after we failed to
3931  * find blocks that were already in the inode's extent tree.  Hence,
3932  * we know that the beginning of the requested region cannot overlap
3933  * the extent from the inode's extent tree.  There are three cases we
3934  * want to catch.  The first is this case:
3935  *
3936  *		 |--- cluster # N--|
3937  *    |--- extent ---|	|---- requested region ---|
3938  *			|==========|
3939  *
3940  * The second case that we need to test for is this one:
3941  *
3942  *   |--------- cluster # N ----------------|
3943  *	   |--- requested region --|   |------- extent ----|
3944  *	   |=======================|
3945  *
3946  * The third case is when the requested region lies between two extents
3947  * within the same cluster:
3948  *          |------------- cluster # N-------------|
3949  * |----- ex -----|                  |---- ex_right ----|
3950  *                  |------ requested region ------|
3951  *                  |================|
3952  *
3953  * In each of the above cases, we need to set the map->m_pblk and
3954  * map->m_len so it corresponds to the return the extent labelled as
3955  * "|====|" from cluster #N, since it is already in use for data in
3956  * cluster EXT4_B2C(sbi, map->m_lblk).	We will then return 1 to
3957  * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
3958  * as a new "allocated" block region.  Otherwise, we will return 0 and
3959  * ext4_ext_map_blocks() will then allocate one or more new clusters
3960  * by calling ext4_mb_new_blocks().
3961  */
3962 static int get_implied_cluster_alloc(struct super_block *sb,
3963 				     struct ext4_map_blocks *map,
3964 				     struct ext4_extent *ex,
3965 				     struct ext4_ext_path *path)
3966 {
3967 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3968 	ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
3969 	ext4_lblk_t ex_cluster_start, ex_cluster_end;
3970 	ext4_lblk_t rr_cluster_start;
3971 	ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3972 	ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3973 	unsigned short ee_len = ext4_ext_get_actual_len(ex);
3974 
3975 	/* The extent passed in that we are trying to match */
3976 	ex_cluster_start = EXT4_B2C(sbi, ee_block);
3977 	ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
3978 
3979 	/* The requested region passed into ext4_map_blocks() */
3980 	rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
3981 
3982 	if ((rr_cluster_start == ex_cluster_end) ||
3983 	    (rr_cluster_start == ex_cluster_start)) {
3984 		if (rr_cluster_start == ex_cluster_end)
3985 			ee_start += ee_len - 1;
3986 		map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
3987 		map->m_len = min(map->m_len,
3988 				 (unsigned) sbi->s_cluster_ratio - c_offset);
3989 		/*
3990 		 * Check for and handle this case:
3991 		 *
3992 		 *   |--------- cluster # N-------------|
3993 		 *		       |------- extent ----|
3994 		 *	   |--- requested region ---|
3995 		 *	   |===========|
3996 		 */
3997 
3998 		if (map->m_lblk < ee_block)
3999 			map->m_len = min(map->m_len, ee_block - map->m_lblk);
4000 
4001 		/*
4002 		 * Check for the case where there is already another allocated
4003 		 * block to the right of 'ex' but before the end of the cluster.
4004 		 *
4005 		 *          |------------- cluster # N-------------|
4006 		 * |----- ex -----|                  |---- ex_right ----|
4007 		 *                  |------ requested region ------|
4008 		 *                  |================|
4009 		 */
4010 		if (map->m_lblk > ee_block) {
4011 			ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4012 			map->m_len = min(map->m_len, next - map->m_lblk);
4013 		}
4014 
4015 		trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4016 		return 1;
4017 	}
4018 
4019 	trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4020 	return 0;
4021 }
4022 
4023 
4024 /*
4025  * Block allocation/map/preallocation routine for extents based files
4026  *
4027  *
4028  * Need to be called with
4029  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4030  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4031  *
4032  * return > 0, number of of blocks already mapped/allocated
4033  *          if create == 0 and these are pre-allocated blocks
4034  *          	buffer head is unmapped
4035  *          otherwise blocks are mapped
4036  *
4037  * return = 0, if plain look up failed (blocks have not been allocated)
4038  *          buffer head is unmapped
4039  *
4040  * return < 0, error case.
4041  */
4042 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4043 			struct ext4_map_blocks *map, int flags)
4044 {
4045 	struct ext4_ext_path *path = NULL;
4046 	struct ext4_extent newex, *ex, *ex2;
4047 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4048 	ext4_fsblk_t newblock = 0, pblk;
4049 	int err = 0, depth, ret;
4050 	unsigned int allocated = 0, offset = 0;
4051 	unsigned int allocated_clusters = 0;
4052 	struct ext4_allocation_request ar;
4053 	ext4_lblk_t cluster_offset;
4054 
4055 	ext_debug(inode, "blocks %u/%u requested\n", map->m_lblk, map->m_len);
4056 	trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4057 
4058 	/* find extent for this block */
4059 	path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4060 	if (IS_ERR(path)) {
4061 		err = PTR_ERR(path);
4062 		path = NULL;
4063 		goto out;
4064 	}
4065 
4066 	depth = ext_depth(inode);
4067 
4068 	/*
4069 	 * consistent leaf must not be empty;
4070 	 * this situation is possible, though, _during_ tree modification;
4071 	 * this is why assert can't be put in ext4_find_extent()
4072 	 */
4073 	if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4074 		EXT4_ERROR_INODE(inode, "bad extent address "
4075 				 "lblock: %lu, depth: %d pblock %lld",
4076 				 (unsigned long) map->m_lblk, depth,
4077 				 path[depth].p_block);
4078 		err = -EFSCORRUPTED;
4079 		goto out;
4080 	}
4081 
4082 	ex = path[depth].p_ext;
4083 	if (ex) {
4084 		ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4085 		ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4086 		unsigned short ee_len;
4087 
4088 
4089 		/*
4090 		 * unwritten extents are treated as holes, except that
4091 		 * we split out initialized portions during a write.
4092 		 */
4093 		ee_len = ext4_ext_get_actual_len(ex);
4094 
4095 		trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4096 
4097 		/* if found extent covers block, simply return it */
4098 		if (in_range(map->m_lblk, ee_block, ee_len)) {
4099 			newblock = map->m_lblk - ee_block + ee_start;
4100 			/* number of remaining blocks in the extent */
4101 			allocated = ee_len - (map->m_lblk - ee_block);
4102 			ext_debug(inode, "%u fit into %u:%d -> %llu\n",
4103 				  map->m_lblk, ee_block, ee_len, newblock);
4104 
4105 			/*
4106 			 * If the extent is initialized check whether the
4107 			 * caller wants to convert it to unwritten.
4108 			 */
4109 			if ((!ext4_ext_is_unwritten(ex)) &&
4110 			    (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4111 				err = convert_initialized_extent(handle,
4112 					inode, map, &path, &allocated);
4113 				goto out;
4114 			} else if (!ext4_ext_is_unwritten(ex)) {
4115 				map->m_flags |= EXT4_MAP_MAPPED;
4116 				map->m_pblk = newblock;
4117 				if (allocated > map->m_len)
4118 					allocated = map->m_len;
4119 				map->m_len = allocated;
4120 				ext4_ext_show_leaf(inode, path);
4121 				goto out;
4122 			}
4123 
4124 			ret = ext4_ext_handle_unwritten_extents(
4125 				handle, inode, map, &path, flags,
4126 				allocated, newblock);
4127 			if (ret < 0)
4128 				err = ret;
4129 			else
4130 				allocated = ret;
4131 			goto out;
4132 		}
4133 	}
4134 
4135 	/*
4136 	 * requested block isn't allocated yet;
4137 	 * we couldn't try to create block if create flag is zero
4138 	 */
4139 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4140 		ext4_lblk_t hole_start, hole_len;
4141 
4142 		hole_start = map->m_lblk;
4143 		hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4144 		/*
4145 		 * put just found gap into cache to speed up
4146 		 * subsequent requests
4147 		 */
4148 		ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4149 
4150 		/* Update hole_len to reflect hole size after map->m_lblk */
4151 		if (hole_start != map->m_lblk)
4152 			hole_len -= map->m_lblk - hole_start;
4153 		map->m_pblk = 0;
4154 		map->m_len = min_t(unsigned int, map->m_len, hole_len);
4155 
4156 		goto out;
4157 	}
4158 
4159 	/*
4160 	 * Okay, we need to do block allocation.
4161 	 */
4162 	newex.ee_block = cpu_to_le32(map->m_lblk);
4163 	cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4164 
4165 	/*
4166 	 * If we are doing bigalloc, check to see if the extent returned
4167 	 * by ext4_find_extent() implies a cluster we can use.
4168 	 */
4169 	if (cluster_offset && ex &&
4170 	    get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4171 		ar.len = allocated = map->m_len;
4172 		newblock = map->m_pblk;
4173 		goto got_allocated_blocks;
4174 	}
4175 
4176 	/* find neighbour allocated blocks */
4177 	ar.lleft = map->m_lblk;
4178 	err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4179 	if (err)
4180 		goto out;
4181 	ar.lright = map->m_lblk;
4182 	ex2 = NULL;
4183 	err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4184 	if (err)
4185 		goto out;
4186 
4187 	/* Check if the extent after searching to the right implies a
4188 	 * cluster we can use. */
4189 	if ((sbi->s_cluster_ratio > 1) && ex2 &&
4190 	    get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4191 		ar.len = allocated = map->m_len;
4192 		newblock = map->m_pblk;
4193 		goto got_allocated_blocks;
4194 	}
4195 
4196 	/*
4197 	 * See if request is beyond maximum number of blocks we can have in
4198 	 * a single extent. For an initialized extent this limit is
4199 	 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4200 	 * EXT_UNWRITTEN_MAX_LEN.
4201 	 */
4202 	if (map->m_len > EXT_INIT_MAX_LEN &&
4203 	    !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4204 		map->m_len = EXT_INIT_MAX_LEN;
4205 	else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4206 		 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4207 		map->m_len = EXT_UNWRITTEN_MAX_LEN;
4208 
4209 	/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4210 	newex.ee_len = cpu_to_le16(map->m_len);
4211 	err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4212 	if (err)
4213 		allocated = ext4_ext_get_actual_len(&newex);
4214 	else
4215 		allocated = map->m_len;
4216 
4217 	/* allocate new block */
4218 	ar.inode = inode;
4219 	ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4220 	ar.logical = map->m_lblk;
4221 	/*
4222 	 * We calculate the offset from the beginning of the cluster
4223 	 * for the logical block number, since when we allocate a
4224 	 * physical cluster, the physical block should start at the
4225 	 * same offset from the beginning of the cluster.  This is
4226 	 * needed so that future calls to get_implied_cluster_alloc()
4227 	 * work correctly.
4228 	 */
4229 	offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4230 	ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4231 	ar.goal -= offset;
4232 	ar.logical -= offset;
4233 	if (S_ISREG(inode->i_mode))
4234 		ar.flags = EXT4_MB_HINT_DATA;
4235 	else
4236 		/* disable in-core preallocation for non-regular files */
4237 		ar.flags = 0;
4238 	if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4239 		ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4240 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4241 		ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4242 	if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4243 		ar.flags |= EXT4_MB_USE_RESERVED;
4244 	newblock = ext4_mb_new_blocks(handle, &ar, &err);
4245 	if (!newblock)
4246 		goto out;
4247 	allocated_clusters = ar.len;
4248 	ar.len = EXT4_C2B(sbi, ar.len) - offset;
4249 	ext_debug(inode, "allocate new block: goal %llu, found %llu/%u, requested %u\n",
4250 		  ar.goal, newblock, ar.len, allocated);
4251 	if (ar.len > allocated)
4252 		ar.len = allocated;
4253 
4254 got_allocated_blocks:
4255 	/* try to insert new extent into found leaf and return */
4256 	pblk = newblock + offset;
4257 	ext4_ext_store_pblock(&newex, pblk);
4258 	newex.ee_len = cpu_to_le16(ar.len);
4259 	/* Mark unwritten */
4260 	if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4261 		ext4_ext_mark_unwritten(&newex);
4262 		map->m_flags |= EXT4_MAP_UNWRITTEN;
4263 	}
4264 
4265 	err = ext4_ext_insert_extent(handle, inode, &path, &newex, flags);
4266 	if (err) {
4267 		if (allocated_clusters) {
4268 			int fb_flags = 0;
4269 
4270 			/*
4271 			 * free data blocks we just allocated.
4272 			 * not a good idea to call discard here directly,
4273 			 * but otherwise we'd need to call it every free().
4274 			 */
4275 			ext4_discard_preallocations(inode);
4276 			if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4277 				fb_flags = EXT4_FREE_BLOCKS_NO_QUOT_UPDATE;
4278 			ext4_free_blocks(handle, inode, NULL, newblock,
4279 					 EXT4_C2B(sbi, allocated_clusters),
4280 					 fb_flags);
4281 		}
4282 		goto out;
4283 	}
4284 
4285 	/*
4286 	 * Reduce the reserved cluster count to reflect successful deferred
4287 	 * allocation of delayed allocated clusters or direct allocation of
4288 	 * clusters discovered to be delayed allocated.  Once allocated, a
4289 	 * cluster is not included in the reserved count.
4290 	 */
4291 	if (test_opt(inode->i_sb, DELALLOC) && allocated_clusters) {
4292 		if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4293 			/*
4294 			 * When allocating delayed allocated clusters, simply
4295 			 * reduce the reserved cluster count and claim quota
4296 			 */
4297 			ext4_da_update_reserve_space(inode, allocated_clusters,
4298 							1);
4299 		} else {
4300 			ext4_lblk_t lblk, len;
4301 			unsigned int n;
4302 
4303 			/*
4304 			 * When allocating non-delayed allocated clusters
4305 			 * (from fallocate, filemap, DIO, or clusters
4306 			 * allocated when delalloc has been disabled by
4307 			 * ext4_nonda_switch), reduce the reserved cluster
4308 			 * count by the number of allocated clusters that
4309 			 * have previously been delayed allocated.  Quota
4310 			 * has been claimed by ext4_mb_new_blocks() above,
4311 			 * so release the quota reservations made for any
4312 			 * previously delayed allocated clusters.
4313 			 */
4314 			lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
4315 			len = allocated_clusters << sbi->s_cluster_bits;
4316 			n = ext4_es_delayed_clu(inode, lblk, len);
4317 			if (n > 0)
4318 				ext4_da_update_reserve_space(inode, (int) n, 0);
4319 		}
4320 	}
4321 
4322 	/*
4323 	 * Cache the extent and update transaction to commit on fdatasync only
4324 	 * when it is _not_ an unwritten extent.
4325 	 */
4326 	if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4327 		ext4_update_inode_fsync_trans(handle, inode, 1);
4328 	else
4329 		ext4_update_inode_fsync_trans(handle, inode, 0);
4330 
4331 	map->m_flags |= (EXT4_MAP_NEW | EXT4_MAP_MAPPED);
4332 	map->m_pblk = pblk;
4333 	map->m_len = ar.len;
4334 	allocated = map->m_len;
4335 	ext4_ext_show_leaf(inode, path);
4336 
4337 out:
4338 	ext4_ext_drop_refs(path);
4339 	kfree(path);
4340 
4341 	trace_ext4_ext_map_blocks_exit(inode, flags, map,
4342 				       err ? err : allocated);
4343 	return err ? err : allocated;
4344 }
4345 
4346 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4347 {
4348 	struct super_block *sb = inode->i_sb;
4349 	ext4_lblk_t last_block;
4350 	int err = 0;
4351 
4352 	/*
4353 	 * TODO: optimization is possible here.
4354 	 * Probably we need not scan at all,
4355 	 * because page truncation is enough.
4356 	 */
4357 
4358 	/* we have to know where to truncate from in crash case */
4359 	EXT4_I(inode)->i_disksize = inode->i_size;
4360 	err = ext4_mark_inode_dirty(handle, inode);
4361 	if (err)
4362 		return err;
4363 
4364 	last_block = (inode->i_size + sb->s_blocksize - 1)
4365 			>> EXT4_BLOCK_SIZE_BITS(sb);
4366 retry:
4367 	err = ext4_es_remove_extent(inode, last_block,
4368 				    EXT_MAX_BLOCKS - last_block);
4369 	if (err == -ENOMEM) {
4370 		cond_resched();
4371 		congestion_wait(BLK_RW_ASYNC, HZ/50);
4372 		goto retry;
4373 	}
4374 	if (err)
4375 		return err;
4376 retry_remove_space:
4377 	err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4378 	if (err == -ENOMEM) {
4379 		cond_resched();
4380 		congestion_wait(BLK_RW_ASYNC, HZ/50);
4381 		goto retry_remove_space;
4382 	}
4383 	return err;
4384 }
4385 
4386 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4387 				  ext4_lblk_t len, loff_t new_size,
4388 				  int flags)
4389 {
4390 	struct inode *inode = file_inode(file);
4391 	handle_t *handle;
4392 	int ret = 0;
4393 	int ret2 = 0, ret3 = 0;
4394 	int retries = 0;
4395 	int depth = 0;
4396 	struct ext4_map_blocks map;
4397 	unsigned int credits;
4398 	loff_t epos;
4399 
4400 	BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4401 	map.m_lblk = offset;
4402 	map.m_len = len;
4403 	/*
4404 	 * Don't normalize the request if it can fit in one extent so
4405 	 * that it doesn't get unnecessarily split into multiple
4406 	 * extents.
4407 	 */
4408 	if (len <= EXT_UNWRITTEN_MAX_LEN)
4409 		flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4410 
4411 	/*
4412 	 * credits to insert 1 extent into extent tree
4413 	 */
4414 	credits = ext4_chunk_trans_blocks(inode, len);
4415 	depth = ext_depth(inode);
4416 
4417 retry:
4418 	while (ret >= 0 && len) {
4419 		/*
4420 		 * Recalculate credits when extent tree depth changes.
4421 		 */
4422 		if (depth != ext_depth(inode)) {
4423 			credits = ext4_chunk_trans_blocks(inode, len);
4424 			depth = ext_depth(inode);
4425 		}
4426 
4427 		handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4428 					    credits);
4429 		if (IS_ERR(handle)) {
4430 			ret = PTR_ERR(handle);
4431 			break;
4432 		}
4433 		ret = ext4_map_blocks(handle, inode, &map, flags);
4434 		if (ret <= 0) {
4435 			ext4_debug("inode #%lu: block %u: len %u: "
4436 				   "ext4_ext_map_blocks returned %d",
4437 				   inode->i_ino, map.m_lblk,
4438 				   map.m_len, ret);
4439 			ext4_mark_inode_dirty(handle, inode);
4440 			ret2 = ext4_journal_stop(handle);
4441 			break;
4442 		}
4443 		map.m_lblk += ret;
4444 		map.m_len = len = len - ret;
4445 		epos = (loff_t)map.m_lblk << inode->i_blkbits;
4446 		inode->i_ctime = current_time(inode);
4447 		if (new_size) {
4448 			if (epos > new_size)
4449 				epos = new_size;
4450 			if (ext4_update_inode_size(inode, epos) & 0x1)
4451 				inode->i_mtime = inode->i_ctime;
4452 		}
4453 		ret2 = ext4_mark_inode_dirty(handle, inode);
4454 		ext4_update_inode_fsync_trans(handle, inode, 1);
4455 		ret3 = ext4_journal_stop(handle);
4456 		ret2 = ret3 ? ret3 : ret2;
4457 		if (unlikely(ret2))
4458 			break;
4459 	}
4460 	if (ret == -ENOSPC &&
4461 			ext4_should_retry_alloc(inode->i_sb, &retries)) {
4462 		ret = 0;
4463 		goto retry;
4464 	}
4465 
4466 	return ret > 0 ? ret2 : ret;
4467 }
4468 
4469 static int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len);
4470 
4471 static int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len);
4472 
4473 static long ext4_zero_range(struct file *file, loff_t offset,
4474 			    loff_t len, int mode)
4475 {
4476 	struct inode *inode = file_inode(file);
4477 	handle_t *handle = NULL;
4478 	unsigned int max_blocks;
4479 	loff_t new_size = 0;
4480 	int ret = 0;
4481 	int flags;
4482 	int credits;
4483 	int partial_begin, partial_end;
4484 	loff_t start, end;
4485 	ext4_lblk_t lblk;
4486 	unsigned int blkbits = inode->i_blkbits;
4487 
4488 	trace_ext4_zero_range(inode, offset, len, mode);
4489 
4490 	/* Call ext4_force_commit to flush all data in case of data=journal. */
4491 	if (ext4_should_journal_data(inode)) {
4492 		ret = ext4_force_commit(inode->i_sb);
4493 		if (ret)
4494 			return ret;
4495 	}
4496 
4497 	/*
4498 	 * Round up offset. This is not fallocate, we neet to zero out
4499 	 * blocks, so convert interior block aligned part of the range to
4500 	 * unwritten and possibly manually zero out unaligned parts of the
4501 	 * range.
4502 	 */
4503 	start = round_up(offset, 1 << blkbits);
4504 	end = round_down((offset + len), 1 << blkbits);
4505 
4506 	if (start < offset || end > offset + len)
4507 		return -EINVAL;
4508 	partial_begin = offset & ((1 << blkbits) - 1);
4509 	partial_end = (offset + len) & ((1 << blkbits) - 1);
4510 
4511 	lblk = start >> blkbits;
4512 	max_blocks = (end >> blkbits);
4513 	if (max_blocks < lblk)
4514 		max_blocks = 0;
4515 	else
4516 		max_blocks -= lblk;
4517 
4518 	inode_lock(inode);
4519 
4520 	/*
4521 	 * Indirect files do not support unwritten extents
4522 	 */
4523 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4524 		ret = -EOPNOTSUPP;
4525 		goto out_mutex;
4526 	}
4527 
4528 	if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4529 	    (offset + len > inode->i_size ||
4530 	     offset + len > EXT4_I(inode)->i_disksize)) {
4531 		new_size = offset + len;
4532 		ret = inode_newsize_ok(inode, new_size);
4533 		if (ret)
4534 			goto out_mutex;
4535 	}
4536 
4537 	flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4538 
4539 	/* Wait all existing dio workers, newcomers will block on i_mutex */
4540 	inode_dio_wait(inode);
4541 
4542 	/* Preallocate the range including the unaligned edges */
4543 	if (partial_begin || partial_end) {
4544 		ret = ext4_alloc_file_blocks(file,
4545 				round_down(offset, 1 << blkbits) >> blkbits,
4546 				(round_up((offset + len), 1 << blkbits) -
4547 				 round_down(offset, 1 << blkbits)) >> blkbits,
4548 				new_size, flags);
4549 		if (ret)
4550 			goto out_mutex;
4551 
4552 	}
4553 
4554 	/* Zero range excluding the unaligned edges */
4555 	if (max_blocks > 0) {
4556 		flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4557 			  EXT4_EX_NOCACHE);
4558 
4559 		/*
4560 		 * Prevent page faults from reinstantiating pages we have
4561 		 * released from page cache.
4562 		 */
4563 		down_write(&EXT4_I(inode)->i_mmap_sem);
4564 
4565 		ret = ext4_break_layouts(inode);
4566 		if (ret) {
4567 			up_write(&EXT4_I(inode)->i_mmap_sem);
4568 			goto out_mutex;
4569 		}
4570 
4571 		ret = ext4_update_disksize_before_punch(inode, offset, len);
4572 		if (ret) {
4573 			up_write(&EXT4_I(inode)->i_mmap_sem);
4574 			goto out_mutex;
4575 		}
4576 		/* Now release the pages and zero block aligned part of pages */
4577 		truncate_pagecache_range(inode, start, end - 1);
4578 		inode->i_mtime = inode->i_ctime = current_time(inode);
4579 
4580 		ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4581 					     flags);
4582 		up_write(&EXT4_I(inode)->i_mmap_sem);
4583 		if (ret)
4584 			goto out_mutex;
4585 	}
4586 	if (!partial_begin && !partial_end)
4587 		goto out_mutex;
4588 
4589 	/*
4590 	 * In worst case we have to writeout two nonadjacent unwritten
4591 	 * blocks and update the inode
4592 	 */
4593 	credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4594 	if (ext4_should_journal_data(inode))
4595 		credits += 2;
4596 	handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4597 	if (IS_ERR(handle)) {
4598 		ret = PTR_ERR(handle);
4599 		ext4_std_error(inode->i_sb, ret);
4600 		goto out_mutex;
4601 	}
4602 
4603 	inode->i_mtime = inode->i_ctime = current_time(inode);
4604 	if (new_size)
4605 		ext4_update_inode_size(inode, new_size);
4606 	ret = ext4_mark_inode_dirty(handle, inode);
4607 	if (unlikely(ret))
4608 		goto out_handle;
4609 
4610 	/* Zero out partial block at the edges of the range */
4611 	ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4612 	if (ret >= 0)
4613 		ext4_update_inode_fsync_trans(handle, inode, 1);
4614 
4615 	if (file->f_flags & O_SYNC)
4616 		ext4_handle_sync(handle);
4617 
4618 out_handle:
4619 	ext4_journal_stop(handle);
4620 out_mutex:
4621 	inode_unlock(inode);
4622 	return ret;
4623 }
4624 
4625 /*
4626  * preallocate space for a file. This implements ext4's fallocate file
4627  * operation, which gets called from sys_fallocate system call.
4628  * For block-mapped files, posix_fallocate should fall back to the method
4629  * of writing zeroes to the required new blocks (the same behavior which is
4630  * expected for file systems which do not support fallocate() system call).
4631  */
4632 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4633 {
4634 	struct inode *inode = file_inode(file);
4635 	loff_t new_size = 0;
4636 	unsigned int max_blocks;
4637 	int ret = 0;
4638 	int flags;
4639 	ext4_lblk_t lblk;
4640 	unsigned int blkbits = inode->i_blkbits;
4641 
4642 	/*
4643 	 * Encrypted inodes can't handle collapse range or insert
4644 	 * range since we would need to re-encrypt blocks with a
4645 	 * different IV or XTS tweak (which are based on the logical
4646 	 * block number).
4647 	 */
4648 	if (IS_ENCRYPTED(inode) &&
4649 	    (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
4650 		return -EOPNOTSUPP;
4651 
4652 	/* Return error if mode is not supported */
4653 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4654 		     FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4655 		     FALLOC_FL_INSERT_RANGE))
4656 		return -EOPNOTSUPP;
4657 
4658 	if (mode & FALLOC_FL_PUNCH_HOLE)
4659 		return ext4_punch_hole(inode, offset, len);
4660 
4661 	ret = ext4_convert_inline_data(inode);
4662 	if (ret)
4663 		return ret;
4664 
4665 	if (mode & FALLOC_FL_COLLAPSE_RANGE)
4666 		return ext4_collapse_range(inode, offset, len);
4667 
4668 	if (mode & FALLOC_FL_INSERT_RANGE)
4669 		return ext4_insert_range(inode, offset, len);
4670 
4671 	if (mode & FALLOC_FL_ZERO_RANGE)
4672 		return ext4_zero_range(file, offset, len, mode);
4673 
4674 	trace_ext4_fallocate_enter(inode, offset, len, mode);
4675 	lblk = offset >> blkbits;
4676 
4677 	max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4678 	flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4679 
4680 	inode_lock(inode);
4681 
4682 	/*
4683 	 * We only support preallocation for extent-based files only
4684 	 */
4685 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4686 		ret = -EOPNOTSUPP;
4687 		goto out;
4688 	}
4689 
4690 	if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4691 	    (offset + len > inode->i_size ||
4692 	     offset + len > EXT4_I(inode)->i_disksize)) {
4693 		new_size = offset + len;
4694 		ret = inode_newsize_ok(inode, new_size);
4695 		if (ret)
4696 			goto out;
4697 	}
4698 
4699 	/* Wait all existing dio workers, newcomers will block on i_mutex */
4700 	inode_dio_wait(inode);
4701 
4702 	ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
4703 	if (ret)
4704 		goto out;
4705 
4706 	if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
4707 		ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
4708 						EXT4_I(inode)->i_sync_tid);
4709 	}
4710 out:
4711 	inode_unlock(inode);
4712 	trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
4713 	return ret;
4714 }
4715 
4716 /*
4717  * This function convert a range of blocks to written extents
4718  * The caller of this function will pass the start offset and the size.
4719  * all unwritten extents within this range will be converted to
4720  * written extents.
4721  *
4722  * This function is called from the direct IO end io call back
4723  * function, to convert the fallocated extents after IO is completed.
4724  * Returns 0 on success.
4725  */
4726 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
4727 				   loff_t offset, ssize_t len)
4728 {
4729 	unsigned int max_blocks;
4730 	int ret = 0, ret2 = 0, ret3 = 0;
4731 	struct ext4_map_blocks map;
4732 	unsigned int blkbits = inode->i_blkbits;
4733 	unsigned int credits = 0;
4734 
4735 	map.m_lblk = offset >> blkbits;
4736 	max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4737 
4738 	if (!handle) {
4739 		/*
4740 		 * credits to insert 1 extent into extent tree
4741 		 */
4742 		credits = ext4_chunk_trans_blocks(inode, max_blocks);
4743 	}
4744 	while (ret >= 0 && ret < max_blocks) {
4745 		map.m_lblk += ret;
4746 		map.m_len = (max_blocks -= ret);
4747 		if (credits) {
4748 			handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4749 						    credits);
4750 			if (IS_ERR(handle)) {
4751 				ret = PTR_ERR(handle);
4752 				break;
4753 			}
4754 		}
4755 		ret = ext4_map_blocks(handle, inode, &map,
4756 				      EXT4_GET_BLOCKS_IO_CONVERT_EXT);
4757 		if (ret <= 0)
4758 			ext4_warning(inode->i_sb,
4759 				     "inode #%lu: block %u: len %u: "
4760 				     "ext4_ext_map_blocks returned %d",
4761 				     inode->i_ino, map.m_lblk,
4762 				     map.m_len, ret);
4763 		ret2 = ext4_mark_inode_dirty(handle, inode);
4764 		if (credits) {
4765 			ret3 = ext4_journal_stop(handle);
4766 			if (unlikely(ret3))
4767 				ret2 = ret3;
4768 		}
4769 
4770 		if (ret <= 0 || ret2)
4771 			break;
4772 	}
4773 	return ret > 0 ? ret2 : ret;
4774 }
4775 
4776 int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
4777 {
4778 	int ret, err = 0;
4779 	struct ext4_io_end_vec *io_end_vec;
4780 
4781 	/*
4782 	 * This is somewhat ugly but the idea is clear: When transaction is
4783 	 * reserved, everything goes into it. Otherwise we rather start several
4784 	 * smaller transactions for conversion of each extent separately.
4785 	 */
4786 	if (handle) {
4787 		handle = ext4_journal_start_reserved(handle,
4788 						     EXT4_HT_EXT_CONVERT);
4789 		if (IS_ERR(handle))
4790 			return PTR_ERR(handle);
4791 	}
4792 
4793 	list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
4794 		ret = ext4_convert_unwritten_extents(handle, io_end->inode,
4795 						     io_end_vec->offset,
4796 						     io_end_vec->size);
4797 		if (ret)
4798 			break;
4799 	}
4800 
4801 	if (handle)
4802 		err = ext4_journal_stop(handle);
4803 
4804 	return ret < 0 ? ret : err;
4805 }
4806 
4807 static int ext4_iomap_xattr_fiemap(struct inode *inode, struct iomap *iomap)
4808 {
4809 	__u64 physical = 0;
4810 	__u64 length = 0;
4811 	int blockbits = inode->i_sb->s_blocksize_bits;
4812 	int error = 0;
4813 	u16 iomap_type;
4814 
4815 	/* in-inode? */
4816 	if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4817 		struct ext4_iloc iloc;
4818 		int offset;	/* offset of xattr in inode */
4819 
4820 		error = ext4_get_inode_loc(inode, &iloc);
4821 		if (error)
4822 			return error;
4823 		physical = (__u64)iloc.bh->b_blocknr << blockbits;
4824 		offset = EXT4_GOOD_OLD_INODE_SIZE +
4825 				EXT4_I(inode)->i_extra_isize;
4826 		physical += offset;
4827 		length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
4828 		brelse(iloc.bh);
4829 		iomap_type = IOMAP_INLINE;
4830 	} else if (EXT4_I(inode)->i_file_acl) { /* external block */
4831 		physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
4832 		length = inode->i_sb->s_blocksize;
4833 		iomap_type = IOMAP_MAPPED;
4834 	} else {
4835 		/* no in-inode or external block for xattr, so return -ENOENT */
4836 		error = -ENOENT;
4837 		goto out;
4838 	}
4839 
4840 	iomap->addr = physical;
4841 	iomap->offset = 0;
4842 	iomap->length = length;
4843 	iomap->type = iomap_type;
4844 	iomap->flags = 0;
4845 out:
4846 	return error;
4847 }
4848 
4849 static int ext4_iomap_xattr_begin(struct inode *inode, loff_t offset,
4850 				  loff_t length, unsigned flags,
4851 				  struct iomap *iomap, struct iomap *srcmap)
4852 {
4853 	int error;
4854 
4855 	error = ext4_iomap_xattr_fiemap(inode, iomap);
4856 	if (error == 0 && (offset >= iomap->length))
4857 		error = -ENOENT;
4858 	return error;
4859 }
4860 
4861 static const struct iomap_ops ext4_iomap_xattr_ops = {
4862 	.iomap_begin		= ext4_iomap_xattr_begin,
4863 };
4864 
4865 static int ext4_fiemap_check_ranges(struct inode *inode, u64 start, u64 *len)
4866 {
4867 	u64 maxbytes;
4868 
4869 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4870 		maxbytes = inode->i_sb->s_maxbytes;
4871 	else
4872 		maxbytes = EXT4_SB(inode->i_sb)->s_bitmap_maxbytes;
4873 
4874 	if (*len == 0)
4875 		return -EINVAL;
4876 	if (start > maxbytes)
4877 		return -EFBIG;
4878 
4879 	/*
4880 	 * Shrink request scope to what the fs can actually handle.
4881 	 */
4882 	if (*len > maxbytes || (maxbytes - *len) < start)
4883 		*len = maxbytes - start;
4884 	return 0;
4885 }
4886 
4887 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4888 		u64 start, u64 len)
4889 {
4890 	int error = 0;
4891 
4892 	if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4893 		error = ext4_ext_precache(inode);
4894 		if (error)
4895 			return error;
4896 		fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
4897 	}
4898 
4899 	/*
4900 	 * For bitmap files the maximum size limit could be smaller than
4901 	 * s_maxbytes, so check len here manually instead of just relying on the
4902 	 * generic check.
4903 	 */
4904 	error = ext4_fiemap_check_ranges(inode, start, &len);
4905 	if (error)
4906 		return error;
4907 
4908 	if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
4909 		fieinfo->fi_flags &= ~FIEMAP_FLAG_XATTR;
4910 		return iomap_fiemap(inode, fieinfo, start, len,
4911 				    &ext4_iomap_xattr_ops);
4912 	}
4913 
4914 	return iomap_fiemap(inode, fieinfo, start, len, &ext4_iomap_report_ops);
4915 }
4916 
4917 int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
4918 		      __u64 start, __u64 len)
4919 {
4920 	ext4_lblk_t start_blk, len_blks;
4921 	__u64 last_blk;
4922 	int error = 0;
4923 
4924 	if (ext4_has_inline_data(inode)) {
4925 		int has_inline;
4926 
4927 		down_read(&EXT4_I(inode)->xattr_sem);
4928 		has_inline = ext4_has_inline_data(inode);
4929 		up_read(&EXT4_I(inode)->xattr_sem);
4930 		if (has_inline)
4931 			return 0;
4932 	}
4933 
4934 	if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4935 		error = ext4_ext_precache(inode);
4936 		if (error)
4937 			return error;
4938 		fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
4939 	}
4940 
4941 	error = fiemap_prep(inode, fieinfo, start, &len, 0);
4942 	if (error)
4943 		return error;
4944 
4945 	error = ext4_fiemap_check_ranges(inode, start, &len);
4946 	if (error)
4947 		return error;
4948 
4949 	start_blk = start >> inode->i_sb->s_blocksize_bits;
4950 	last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
4951 	if (last_blk >= EXT_MAX_BLOCKS)
4952 		last_blk = EXT_MAX_BLOCKS-1;
4953 	len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
4954 
4955 	/*
4956 	 * Walk the extent tree gathering extent information
4957 	 * and pushing extents back to the user.
4958 	 */
4959 	return ext4_fill_es_cache_info(inode, start_blk, len_blks, fieinfo);
4960 }
4961 
4962 /*
4963  * ext4_access_path:
4964  * Function to access the path buffer for marking it dirty.
4965  * It also checks if there are sufficient credits left in the journal handle
4966  * to update path.
4967  */
4968 static int
4969 ext4_access_path(handle_t *handle, struct inode *inode,
4970 		struct ext4_ext_path *path)
4971 {
4972 	int credits, err;
4973 
4974 	if (!ext4_handle_valid(handle))
4975 		return 0;
4976 
4977 	/*
4978 	 * Check if need to extend journal credits
4979 	 * 3 for leaf, sb, and inode plus 2 (bmap and group
4980 	 * descriptor) for each block group; assume two block
4981 	 * groups
4982 	 */
4983 	credits = ext4_writepage_trans_blocks(inode);
4984 	err = ext4_datasem_ensure_credits(handle, inode, 7, credits, 0);
4985 	if (err < 0)
4986 		return err;
4987 
4988 	err = ext4_ext_get_access(handle, inode, path);
4989 	return err;
4990 }
4991 
4992 /*
4993  * ext4_ext_shift_path_extents:
4994  * Shift the extents of a path structure lying between path[depth].p_ext
4995  * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
4996  * if it is right shift or left shift operation.
4997  */
4998 static int
4999 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5000 			    struct inode *inode, handle_t *handle,
5001 			    enum SHIFT_DIRECTION SHIFT)
5002 {
5003 	int depth, err = 0;
5004 	struct ext4_extent *ex_start, *ex_last;
5005 	bool update = false;
5006 	depth = path->p_depth;
5007 
5008 	while (depth >= 0) {
5009 		if (depth == path->p_depth) {
5010 			ex_start = path[depth].p_ext;
5011 			if (!ex_start)
5012 				return -EFSCORRUPTED;
5013 
5014 			ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5015 
5016 			err = ext4_access_path(handle, inode, path + depth);
5017 			if (err)
5018 				goto out;
5019 
5020 			if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5021 				update = true;
5022 
5023 			while (ex_start <= ex_last) {
5024 				if (SHIFT == SHIFT_LEFT) {
5025 					le32_add_cpu(&ex_start->ee_block,
5026 						-shift);
5027 					/* Try to merge to the left. */
5028 					if ((ex_start >
5029 					    EXT_FIRST_EXTENT(path[depth].p_hdr))
5030 					    &&
5031 					    ext4_ext_try_to_merge_right(inode,
5032 					    path, ex_start - 1))
5033 						ex_last--;
5034 					else
5035 						ex_start++;
5036 				} else {
5037 					le32_add_cpu(&ex_last->ee_block, shift);
5038 					ext4_ext_try_to_merge_right(inode, path,
5039 						ex_last);
5040 					ex_last--;
5041 				}
5042 			}
5043 			err = ext4_ext_dirty(handle, inode, path + depth);
5044 			if (err)
5045 				goto out;
5046 
5047 			if (--depth < 0 || !update)
5048 				break;
5049 		}
5050 
5051 		/* Update index too */
5052 		err = ext4_access_path(handle, inode, path + depth);
5053 		if (err)
5054 			goto out;
5055 
5056 		if (SHIFT == SHIFT_LEFT)
5057 			le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5058 		else
5059 			le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5060 		err = ext4_ext_dirty(handle, inode, path + depth);
5061 		if (err)
5062 			goto out;
5063 
5064 		/* we are done if current index is not a starting index */
5065 		if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5066 			break;
5067 
5068 		depth--;
5069 	}
5070 
5071 out:
5072 	return err;
5073 }
5074 
5075 /*
5076  * ext4_ext_shift_extents:
5077  * All the extents which lies in the range from @start to the last allocated
5078  * block for the @inode are shifted either towards left or right (depending
5079  * upon @SHIFT) by @shift blocks.
5080  * On success, 0 is returned, error otherwise.
5081  */
5082 static int
5083 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5084 		       ext4_lblk_t start, ext4_lblk_t shift,
5085 		       enum SHIFT_DIRECTION SHIFT)
5086 {
5087 	struct ext4_ext_path *path;
5088 	int ret = 0, depth;
5089 	struct ext4_extent *extent;
5090 	ext4_lblk_t stop, *iterator, ex_start, ex_end;
5091 
5092 	/* Let path point to the last extent */
5093 	path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5094 				EXT4_EX_NOCACHE);
5095 	if (IS_ERR(path))
5096 		return PTR_ERR(path);
5097 
5098 	depth = path->p_depth;
5099 	extent = path[depth].p_ext;
5100 	if (!extent)
5101 		goto out;
5102 
5103 	stop = le32_to_cpu(extent->ee_block);
5104 
5105        /*
5106 	* For left shifts, make sure the hole on the left is big enough to
5107 	* accommodate the shift.  For right shifts, make sure the last extent
5108 	* won't be shifted beyond EXT_MAX_BLOCKS.
5109 	*/
5110 	if (SHIFT == SHIFT_LEFT) {
5111 		path = ext4_find_extent(inode, start - 1, &path,
5112 					EXT4_EX_NOCACHE);
5113 		if (IS_ERR(path))
5114 			return PTR_ERR(path);
5115 		depth = path->p_depth;
5116 		extent =  path[depth].p_ext;
5117 		if (extent) {
5118 			ex_start = le32_to_cpu(extent->ee_block);
5119 			ex_end = le32_to_cpu(extent->ee_block) +
5120 				ext4_ext_get_actual_len(extent);
5121 		} else {
5122 			ex_start = 0;
5123 			ex_end = 0;
5124 		}
5125 
5126 		if ((start == ex_start && shift > ex_start) ||
5127 		    (shift > start - ex_end)) {
5128 			ret = -EINVAL;
5129 			goto out;
5130 		}
5131 	} else {
5132 		if (shift > EXT_MAX_BLOCKS -
5133 		    (stop + ext4_ext_get_actual_len(extent))) {
5134 			ret = -EINVAL;
5135 			goto out;
5136 		}
5137 	}
5138 
5139 	/*
5140 	 * In case of left shift, iterator points to start and it is increased
5141 	 * till we reach stop. In case of right shift, iterator points to stop
5142 	 * and it is decreased till we reach start.
5143 	 */
5144 	if (SHIFT == SHIFT_LEFT)
5145 		iterator = &start;
5146 	else
5147 		iterator = &stop;
5148 
5149 	/*
5150 	 * Its safe to start updating extents.  Start and stop are unsigned, so
5151 	 * in case of right shift if extent with 0 block is reached, iterator
5152 	 * becomes NULL to indicate the end of the loop.
5153 	 */
5154 	while (iterator && start <= stop) {
5155 		path = ext4_find_extent(inode, *iterator, &path,
5156 					EXT4_EX_NOCACHE);
5157 		if (IS_ERR(path))
5158 			return PTR_ERR(path);
5159 		depth = path->p_depth;
5160 		extent = path[depth].p_ext;
5161 		if (!extent) {
5162 			EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5163 					 (unsigned long) *iterator);
5164 			return -EFSCORRUPTED;
5165 		}
5166 		if (SHIFT == SHIFT_LEFT && *iterator >
5167 		    le32_to_cpu(extent->ee_block)) {
5168 			/* Hole, move to the next extent */
5169 			if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5170 				path[depth].p_ext++;
5171 			} else {
5172 				*iterator = ext4_ext_next_allocated_block(path);
5173 				continue;
5174 			}
5175 		}
5176 
5177 		if (SHIFT == SHIFT_LEFT) {
5178 			extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5179 			*iterator = le32_to_cpu(extent->ee_block) +
5180 					ext4_ext_get_actual_len(extent);
5181 		} else {
5182 			extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5183 			if (le32_to_cpu(extent->ee_block) > 0)
5184 				*iterator = le32_to_cpu(extent->ee_block) - 1;
5185 			else
5186 				/* Beginning is reached, end of the loop */
5187 				iterator = NULL;
5188 			/* Update path extent in case we need to stop */
5189 			while (le32_to_cpu(extent->ee_block) < start)
5190 				extent++;
5191 			path[depth].p_ext = extent;
5192 		}
5193 		ret = ext4_ext_shift_path_extents(path, shift, inode,
5194 				handle, SHIFT);
5195 		if (ret)
5196 			break;
5197 	}
5198 out:
5199 	ext4_ext_drop_refs(path);
5200 	kfree(path);
5201 	return ret;
5202 }
5203 
5204 /*
5205  * ext4_collapse_range:
5206  * This implements the fallocate's collapse range functionality for ext4
5207  * Returns: 0 and non-zero on error.
5208  */
5209 static int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5210 {
5211 	struct super_block *sb = inode->i_sb;
5212 	ext4_lblk_t punch_start, punch_stop;
5213 	handle_t *handle;
5214 	unsigned int credits;
5215 	loff_t new_size, ioffset;
5216 	int ret;
5217 
5218 	/*
5219 	 * We need to test this early because xfstests assumes that a
5220 	 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5221 	 * system does not support collapse range.
5222 	 */
5223 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5224 		return -EOPNOTSUPP;
5225 
5226 	/* Collapse range works only on fs cluster size aligned regions. */
5227 	if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
5228 		return -EINVAL;
5229 
5230 	trace_ext4_collapse_range(inode, offset, len);
5231 
5232 	punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5233 	punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5234 
5235 	/* Call ext4_force_commit to flush all data in case of data=journal. */
5236 	if (ext4_should_journal_data(inode)) {
5237 		ret = ext4_force_commit(inode->i_sb);
5238 		if (ret)
5239 			return ret;
5240 	}
5241 
5242 	inode_lock(inode);
5243 	/*
5244 	 * There is no need to overlap collapse range with EOF, in which case
5245 	 * it is effectively a truncate operation
5246 	 */
5247 	if (offset + len >= inode->i_size) {
5248 		ret = -EINVAL;
5249 		goto out_mutex;
5250 	}
5251 
5252 	/* Currently just for extent based files */
5253 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5254 		ret = -EOPNOTSUPP;
5255 		goto out_mutex;
5256 	}
5257 
5258 	/* Wait for existing dio to complete */
5259 	inode_dio_wait(inode);
5260 
5261 	/*
5262 	 * Prevent page faults from reinstantiating pages we have released from
5263 	 * page cache.
5264 	 */
5265 	down_write(&EXT4_I(inode)->i_mmap_sem);
5266 
5267 	ret = ext4_break_layouts(inode);
5268 	if (ret)
5269 		goto out_mmap;
5270 
5271 	/*
5272 	 * Need to round down offset to be aligned with page size boundary
5273 	 * for page size > block size.
5274 	 */
5275 	ioffset = round_down(offset, PAGE_SIZE);
5276 	/*
5277 	 * Write tail of the last page before removed range since it will get
5278 	 * removed from the page cache below.
5279 	 */
5280 	ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5281 	if (ret)
5282 		goto out_mmap;
5283 	/*
5284 	 * Write data that will be shifted to preserve them when discarding
5285 	 * page cache below. We are also protected from pages becoming dirty
5286 	 * by i_mmap_sem.
5287 	 */
5288 	ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5289 					   LLONG_MAX);
5290 	if (ret)
5291 		goto out_mmap;
5292 	truncate_pagecache(inode, ioffset);
5293 
5294 	credits = ext4_writepage_trans_blocks(inode);
5295 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5296 	if (IS_ERR(handle)) {
5297 		ret = PTR_ERR(handle);
5298 		goto out_mmap;
5299 	}
5300 
5301 	down_write(&EXT4_I(inode)->i_data_sem);
5302 	ext4_discard_preallocations(inode);
5303 
5304 	ret = ext4_es_remove_extent(inode, punch_start,
5305 				    EXT_MAX_BLOCKS - punch_start);
5306 	if (ret) {
5307 		up_write(&EXT4_I(inode)->i_data_sem);
5308 		goto out_stop;
5309 	}
5310 
5311 	ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5312 	if (ret) {
5313 		up_write(&EXT4_I(inode)->i_data_sem);
5314 		goto out_stop;
5315 	}
5316 	ext4_discard_preallocations(inode);
5317 
5318 	ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5319 				     punch_stop - punch_start, SHIFT_LEFT);
5320 	if (ret) {
5321 		up_write(&EXT4_I(inode)->i_data_sem);
5322 		goto out_stop;
5323 	}
5324 
5325 	new_size = inode->i_size - len;
5326 	i_size_write(inode, new_size);
5327 	EXT4_I(inode)->i_disksize = new_size;
5328 
5329 	up_write(&EXT4_I(inode)->i_data_sem);
5330 	if (IS_SYNC(inode))
5331 		ext4_handle_sync(handle);
5332 	inode->i_mtime = inode->i_ctime = current_time(inode);
5333 	ret = ext4_mark_inode_dirty(handle, inode);
5334 	ext4_update_inode_fsync_trans(handle, inode, 1);
5335 
5336 out_stop:
5337 	ext4_journal_stop(handle);
5338 out_mmap:
5339 	up_write(&EXT4_I(inode)->i_mmap_sem);
5340 out_mutex:
5341 	inode_unlock(inode);
5342 	return ret;
5343 }
5344 
5345 /*
5346  * ext4_insert_range:
5347  * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5348  * The data blocks starting from @offset to the EOF are shifted by @len
5349  * towards right to create a hole in the @inode. Inode size is increased
5350  * by len bytes.
5351  * Returns 0 on success, error otherwise.
5352  */
5353 static int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5354 {
5355 	struct super_block *sb = inode->i_sb;
5356 	handle_t *handle;
5357 	struct ext4_ext_path *path;
5358 	struct ext4_extent *extent;
5359 	ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5360 	unsigned int credits, ee_len;
5361 	int ret = 0, depth, split_flag = 0;
5362 	loff_t ioffset;
5363 
5364 	/*
5365 	 * We need to test this early because xfstests assumes that an
5366 	 * insert range of (0, 1) will return EOPNOTSUPP if the file
5367 	 * system does not support insert range.
5368 	 */
5369 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5370 		return -EOPNOTSUPP;
5371 
5372 	/* Insert range works only on fs cluster size aligned regions. */
5373 	if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
5374 		return -EINVAL;
5375 
5376 	trace_ext4_insert_range(inode, offset, len);
5377 
5378 	offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5379 	len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5380 
5381 	/* Call ext4_force_commit to flush all data in case of data=journal */
5382 	if (ext4_should_journal_data(inode)) {
5383 		ret = ext4_force_commit(inode->i_sb);
5384 		if (ret)
5385 			return ret;
5386 	}
5387 
5388 	inode_lock(inode);
5389 	/* Currently just for extent based files */
5390 	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5391 		ret = -EOPNOTSUPP;
5392 		goto out_mutex;
5393 	}
5394 
5395 	/* Check whether the maximum file size would be exceeded */
5396 	if (len > inode->i_sb->s_maxbytes - inode->i_size) {
5397 		ret = -EFBIG;
5398 		goto out_mutex;
5399 	}
5400 
5401 	/* Offset must be less than i_size */
5402 	if (offset >= inode->i_size) {
5403 		ret = -EINVAL;
5404 		goto out_mutex;
5405 	}
5406 
5407 	/* Wait for existing dio to complete */
5408 	inode_dio_wait(inode);
5409 
5410 	/*
5411 	 * Prevent page faults from reinstantiating pages we have released from
5412 	 * page cache.
5413 	 */
5414 	down_write(&EXT4_I(inode)->i_mmap_sem);
5415 
5416 	ret = ext4_break_layouts(inode);
5417 	if (ret)
5418 		goto out_mmap;
5419 
5420 	/*
5421 	 * Need to round down to align start offset to page size boundary
5422 	 * for page size > block size.
5423 	 */
5424 	ioffset = round_down(offset, PAGE_SIZE);
5425 	/* Write out all dirty pages */
5426 	ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5427 			LLONG_MAX);
5428 	if (ret)
5429 		goto out_mmap;
5430 	truncate_pagecache(inode, ioffset);
5431 
5432 	credits = ext4_writepage_trans_blocks(inode);
5433 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5434 	if (IS_ERR(handle)) {
5435 		ret = PTR_ERR(handle);
5436 		goto out_mmap;
5437 	}
5438 
5439 	/* Expand file to avoid data loss if there is error while shifting */
5440 	inode->i_size += len;
5441 	EXT4_I(inode)->i_disksize += len;
5442 	inode->i_mtime = inode->i_ctime = current_time(inode);
5443 	ret = ext4_mark_inode_dirty(handle, inode);
5444 	if (ret)
5445 		goto out_stop;
5446 
5447 	down_write(&EXT4_I(inode)->i_data_sem);
5448 	ext4_discard_preallocations(inode);
5449 
5450 	path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5451 	if (IS_ERR(path)) {
5452 		up_write(&EXT4_I(inode)->i_data_sem);
5453 		goto out_stop;
5454 	}
5455 
5456 	depth = ext_depth(inode);
5457 	extent = path[depth].p_ext;
5458 	if (extent) {
5459 		ee_start_lblk = le32_to_cpu(extent->ee_block);
5460 		ee_len = ext4_ext_get_actual_len(extent);
5461 
5462 		/*
5463 		 * If offset_lblk is not the starting block of extent, split
5464 		 * the extent @offset_lblk
5465 		 */
5466 		if ((offset_lblk > ee_start_lblk) &&
5467 				(offset_lblk < (ee_start_lblk + ee_len))) {
5468 			if (ext4_ext_is_unwritten(extent))
5469 				split_flag = EXT4_EXT_MARK_UNWRIT1 |
5470 					EXT4_EXT_MARK_UNWRIT2;
5471 			ret = ext4_split_extent_at(handle, inode, &path,
5472 					offset_lblk, split_flag,
5473 					EXT4_EX_NOCACHE |
5474 					EXT4_GET_BLOCKS_PRE_IO |
5475 					EXT4_GET_BLOCKS_METADATA_NOFAIL);
5476 		}
5477 
5478 		ext4_ext_drop_refs(path);
5479 		kfree(path);
5480 		if (ret < 0) {
5481 			up_write(&EXT4_I(inode)->i_data_sem);
5482 			goto out_stop;
5483 		}
5484 	} else {
5485 		ext4_ext_drop_refs(path);
5486 		kfree(path);
5487 	}
5488 
5489 	ret = ext4_es_remove_extent(inode, offset_lblk,
5490 			EXT_MAX_BLOCKS - offset_lblk);
5491 	if (ret) {
5492 		up_write(&EXT4_I(inode)->i_data_sem);
5493 		goto out_stop;
5494 	}
5495 
5496 	/*
5497 	 * if offset_lblk lies in a hole which is at start of file, use
5498 	 * ee_start_lblk to shift extents
5499 	 */
5500 	ret = ext4_ext_shift_extents(inode, handle,
5501 		ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5502 		len_lblk, SHIFT_RIGHT);
5503 
5504 	up_write(&EXT4_I(inode)->i_data_sem);
5505 	if (IS_SYNC(inode))
5506 		ext4_handle_sync(handle);
5507 	if (ret >= 0)
5508 		ext4_update_inode_fsync_trans(handle, inode, 1);
5509 
5510 out_stop:
5511 	ext4_journal_stop(handle);
5512 out_mmap:
5513 	up_write(&EXT4_I(inode)->i_mmap_sem);
5514 out_mutex:
5515 	inode_unlock(inode);
5516 	return ret;
5517 }
5518 
5519 /**
5520  * ext4_swap_extents() - Swap extents between two inodes
5521  * @handle: handle for this transaction
5522  * @inode1:	First inode
5523  * @inode2:	Second inode
5524  * @lblk1:	Start block for first inode
5525  * @lblk2:	Start block for second inode
5526  * @count:	Number of blocks to swap
5527  * @unwritten: Mark second inode's extents as unwritten after swap
5528  * @erp:	Pointer to save error value
5529  *
5530  * This helper routine does exactly what is promise "swap extents". All other
5531  * stuff such as page-cache locking consistency, bh mapping consistency or
5532  * extent's data copying must be performed by caller.
5533  * Locking:
5534  * 		i_mutex is held for both inodes
5535  * 		i_data_sem is locked for write for both inodes
5536  * Assumptions:
5537  *		All pages from requested range are locked for both inodes
5538  */
5539 int
5540 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5541 		  struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5542 		  ext4_lblk_t count, int unwritten, int *erp)
5543 {
5544 	struct ext4_ext_path *path1 = NULL;
5545 	struct ext4_ext_path *path2 = NULL;
5546 	int replaced_count = 0;
5547 
5548 	BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5549 	BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5550 	BUG_ON(!inode_is_locked(inode1));
5551 	BUG_ON(!inode_is_locked(inode2));
5552 
5553 	*erp = ext4_es_remove_extent(inode1, lblk1, count);
5554 	if (unlikely(*erp))
5555 		return 0;
5556 	*erp = ext4_es_remove_extent(inode2, lblk2, count);
5557 	if (unlikely(*erp))
5558 		return 0;
5559 
5560 	while (count) {
5561 		struct ext4_extent *ex1, *ex2, tmp_ex;
5562 		ext4_lblk_t e1_blk, e2_blk;
5563 		int e1_len, e2_len, len;
5564 		int split = 0;
5565 
5566 		path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5567 		if (IS_ERR(path1)) {
5568 			*erp = PTR_ERR(path1);
5569 			path1 = NULL;
5570 		finish:
5571 			count = 0;
5572 			goto repeat;
5573 		}
5574 		path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5575 		if (IS_ERR(path2)) {
5576 			*erp = PTR_ERR(path2);
5577 			path2 = NULL;
5578 			goto finish;
5579 		}
5580 		ex1 = path1[path1->p_depth].p_ext;
5581 		ex2 = path2[path2->p_depth].p_ext;
5582 		/* Do we have somthing to swap ? */
5583 		if (unlikely(!ex2 || !ex1))
5584 			goto finish;
5585 
5586 		e1_blk = le32_to_cpu(ex1->ee_block);
5587 		e2_blk = le32_to_cpu(ex2->ee_block);
5588 		e1_len = ext4_ext_get_actual_len(ex1);
5589 		e2_len = ext4_ext_get_actual_len(ex2);
5590 
5591 		/* Hole handling */
5592 		if (!in_range(lblk1, e1_blk, e1_len) ||
5593 		    !in_range(lblk2, e2_blk, e2_len)) {
5594 			ext4_lblk_t next1, next2;
5595 
5596 			/* if hole after extent, then go to next extent */
5597 			next1 = ext4_ext_next_allocated_block(path1);
5598 			next2 = ext4_ext_next_allocated_block(path2);
5599 			/* If hole before extent, then shift to that extent */
5600 			if (e1_blk > lblk1)
5601 				next1 = e1_blk;
5602 			if (e2_blk > lblk2)
5603 				next2 = e2_blk;
5604 			/* Do we have something to swap */
5605 			if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5606 				goto finish;
5607 			/* Move to the rightest boundary */
5608 			len = next1 - lblk1;
5609 			if (len < next2 - lblk2)
5610 				len = next2 - lblk2;
5611 			if (len > count)
5612 				len = count;
5613 			lblk1 += len;
5614 			lblk2 += len;
5615 			count -= len;
5616 			goto repeat;
5617 		}
5618 
5619 		/* Prepare left boundary */
5620 		if (e1_blk < lblk1) {
5621 			split = 1;
5622 			*erp = ext4_force_split_extent_at(handle, inode1,
5623 						&path1, lblk1, 0);
5624 			if (unlikely(*erp))
5625 				goto finish;
5626 		}
5627 		if (e2_blk < lblk2) {
5628 			split = 1;
5629 			*erp = ext4_force_split_extent_at(handle, inode2,
5630 						&path2,  lblk2, 0);
5631 			if (unlikely(*erp))
5632 				goto finish;
5633 		}
5634 		/* ext4_split_extent_at() may result in leaf extent split,
5635 		 * path must to be revalidated. */
5636 		if (split)
5637 			goto repeat;
5638 
5639 		/* Prepare right boundary */
5640 		len = count;
5641 		if (len > e1_blk + e1_len - lblk1)
5642 			len = e1_blk + e1_len - lblk1;
5643 		if (len > e2_blk + e2_len - lblk2)
5644 			len = e2_blk + e2_len - lblk2;
5645 
5646 		if (len != e1_len) {
5647 			split = 1;
5648 			*erp = ext4_force_split_extent_at(handle, inode1,
5649 						&path1, lblk1 + len, 0);
5650 			if (unlikely(*erp))
5651 				goto finish;
5652 		}
5653 		if (len != e2_len) {
5654 			split = 1;
5655 			*erp = ext4_force_split_extent_at(handle, inode2,
5656 						&path2, lblk2 + len, 0);
5657 			if (*erp)
5658 				goto finish;
5659 		}
5660 		/* ext4_split_extent_at() may result in leaf extent split,
5661 		 * path must to be revalidated. */
5662 		if (split)
5663 			goto repeat;
5664 
5665 		BUG_ON(e2_len != e1_len);
5666 		*erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5667 		if (unlikely(*erp))
5668 			goto finish;
5669 		*erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5670 		if (unlikely(*erp))
5671 			goto finish;
5672 
5673 		/* Both extents are fully inside boundaries. Swap it now */
5674 		tmp_ex = *ex1;
5675 		ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5676 		ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5677 		ex1->ee_len = cpu_to_le16(e2_len);
5678 		ex2->ee_len = cpu_to_le16(e1_len);
5679 		if (unwritten)
5680 			ext4_ext_mark_unwritten(ex2);
5681 		if (ext4_ext_is_unwritten(&tmp_ex))
5682 			ext4_ext_mark_unwritten(ex1);
5683 
5684 		ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5685 		ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5686 		*erp = ext4_ext_dirty(handle, inode2, path2 +
5687 				      path2->p_depth);
5688 		if (unlikely(*erp))
5689 			goto finish;
5690 		*erp = ext4_ext_dirty(handle, inode1, path1 +
5691 				      path1->p_depth);
5692 		/*
5693 		 * Looks scarry ah..? second inode already points to new blocks,
5694 		 * and it was successfully dirtied. But luckily error may happen
5695 		 * only due to journal error, so full transaction will be
5696 		 * aborted anyway.
5697 		 */
5698 		if (unlikely(*erp))
5699 			goto finish;
5700 		lblk1 += len;
5701 		lblk2 += len;
5702 		replaced_count += len;
5703 		count -= len;
5704 
5705 	repeat:
5706 		ext4_ext_drop_refs(path1);
5707 		kfree(path1);
5708 		ext4_ext_drop_refs(path2);
5709 		kfree(path2);
5710 		path1 = path2 = NULL;
5711 	}
5712 	return replaced_count;
5713 }
5714 
5715 /*
5716  * ext4_clu_mapped - determine whether any block in a logical cluster has
5717  *                   been mapped to a physical cluster
5718  *
5719  * @inode - file containing the logical cluster
5720  * @lclu - logical cluster of interest
5721  *
5722  * Returns 1 if any block in the logical cluster is mapped, signifying
5723  * that a physical cluster has been allocated for it.  Otherwise,
5724  * returns 0.  Can also return negative error codes.  Derived from
5725  * ext4_ext_map_blocks().
5726  */
5727 int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
5728 {
5729 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5730 	struct ext4_ext_path *path;
5731 	int depth, mapped = 0, err = 0;
5732 	struct ext4_extent *extent;
5733 	ext4_lblk_t first_lblk, first_lclu, last_lclu;
5734 
5735 	/* search for the extent closest to the first block in the cluster */
5736 	path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
5737 	if (IS_ERR(path)) {
5738 		err = PTR_ERR(path);
5739 		path = NULL;
5740 		goto out;
5741 	}
5742 
5743 	depth = ext_depth(inode);
5744 
5745 	/*
5746 	 * A consistent leaf must not be empty.  This situation is possible,
5747 	 * though, _during_ tree modification, and it's why an assert can't
5748 	 * be put in ext4_find_extent().
5749 	 */
5750 	if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
5751 		EXT4_ERROR_INODE(inode,
5752 		    "bad extent address - lblock: %lu, depth: %d, pblock: %lld",
5753 				 (unsigned long) EXT4_C2B(sbi, lclu),
5754 				 depth, path[depth].p_block);
5755 		err = -EFSCORRUPTED;
5756 		goto out;
5757 	}
5758 
5759 	extent = path[depth].p_ext;
5760 
5761 	/* can't be mapped if the extent tree is empty */
5762 	if (extent == NULL)
5763 		goto out;
5764 
5765 	first_lblk = le32_to_cpu(extent->ee_block);
5766 	first_lclu = EXT4_B2C(sbi, first_lblk);
5767 
5768 	/*
5769 	 * Three possible outcomes at this point - found extent spanning
5770 	 * the target cluster, to the left of the target cluster, or to the
5771 	 * right of the target cluster.  The first two cases are handled here.
5772 	 * The last case indicates the target cluster is not mapped.
5773 	 */
5774 	if (lclu >= first_lclu) {
5775 		last_lclu = EXT4_B2C(sbi, first_lblk +
5776 				     ext4_ext_get_actual_len(extent) - 1);
5777 		if (lclu <= last_lclu) {
5778 			mapped = 1;
5779 		} else {
5780 			first_lblk = ext4_ext_next_allocated_block(path);
5781 			first_lclu = EXT4_B2C(sbi, first_lblk);
5782 			if (lclu == first_lclu)
5783 				mapped = 1;
5784 		}
5785 	}
5786 
5787 out:
5788 	ext4_ext_drop_refs(path);
5789 	kfree(path);
5790 
5791 	return err ? err : mapped;
5792 }
5793