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