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