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