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