File Index
Files and directories
Sign in
FILE

extents.c

File preview with syntax highlighting.

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