1/*
2 *  linux/fs/ext4/indirect.c
3 *
4 *  from
5 *
6 *  linux/fs/ext4/inode.c
7 *
8 * Copyright (C) 1992, 1993, 1994, 1995
9 * Remy Card (card@masi.ibp.fr)
10 * Laboratoire MASI - Institut Blaise Pascal
11 * Universite Pierre et Marie Curie (Paris VI)
12 *
13 *  from
14 *
15 *  linux/fs/minix/inode.c
16 *
17 *  Copyright (C) 1991, 1992  Linus Torvalds
18 *
19 *  Goal-directed block allocation by Stephen Tweedie
20 *	(sct@redhat.com), 1993, 1998
21 */
22
23#include "ext4_jbd2.h"
24#include "truncate.h"
25#include <linux/uio.h>
26
27#include <trace/events/ext4.h>
28
29typedef struct {
30	__le32	*p;
31	__le32	key;
32	struct buffer_head *bh;
33} Indirect;
34
35static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
36{
37	p->key = *(p->p = v);
38	p->bh = bh;
39}
40
41/**
42 *	ext4_block_to_path - parse the block number into array of offsets
43 *	@inode: inode in question (we are only interested in its superblock)
44 *	@i_block: block number to be parsed
45 *	@offsets: array to store the offsets in
46 *	@boundary: set this non-zero if the referred-to block is likely to be
47 *	       followed (on disk) by an indirect block.
48 *
49 *	To store the locations of file's data ext4 uses a data structure common
50 *	for UNIX filesystems - tree of pointers anchored in the inode, with
51 *	data blocks at leaves and indirect blocks in intermediate nodes.
52 *	This function translates the block number into path in that tree -
53 *	return value is the path length and @offsets[n] is the offset of
54 *	pointer to (n+1)th node in the nth one. If @block is out of range
55 *	(negative or too large) warning is printed and zero returned.
56 *
57 *	Note: function doesn't find node addresses, so no IO is needed. All
58 *	we need to know is the capacity of indirect blocks (taken from the
59 *	inode->i_sb).
60 */
61
62/*
63 * Portability note: the last comparison (check that we fit into triple
64 * indirect block) is spelled differently, because otherwise on an
65 * architecture with 32-bit longs and 8Kb pages we might get into trouble
66 * if our filesystem had 8Kb blocks. We might use long long, but that would
67 * kill us on x86. Oh, well, at least the sign propagation does not matter -
68 * i_block would have to be negative in the very beginning, so we would not
69 * get there at all.
70 */
71
72static int ext4_block_to_path(struct inode *inode,
73			      ext4_lblk_t i_block,
74			      ext4_lblk_t offsets[4], int *boundary)
75{
76	int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
77	int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
78	const long direct_blocks = EXT4_NDIR_BLOCKS,
79		indirect_blocks = ptrs,
80		double_blocks = (1 << (ptrs_bits * 2));
81	int n = 0;
82	int final = 0;
83
84	if (i_block < direct_blocks) {
85		offsets[n++] = i_block;
86		final = direct_blocks;
87	} else if ((i_block -= direct_blocks) < indirect_blocks) {
88		offsets[n++] = EXT4_IND_BLOCK;
89		offsets[n++] = i_block;
90		final = ptrs;
91	} else if ((i_block -= indirect_blocks) < double_blocks) {
92		offsets[n++] = EXT4_DIND_BLOCK;
93		offsets[n++] = i_block >> ptrs_bits;
94		offsets[n++] = i_block & (ptrs - 1);
95		final = ptrs;
96	} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
97		offsets[n++] = EXT4_TIND_BLOCK;
98		offsets[n++] = i_block >> (ptrs_bits * 2);
99		offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
100		offsets[n++] = i_block & (ptrs - 1);
101		final = ptrs;
102	} else {
103		ext4_warning(inode->i_sb, "block %lu > max in inode %lu",
104			     i_block + direct_blocks +
105			     indirect_blocks + double_blocks, inode->i_ino);
106	}
107	if (boundary)
108		*boundary = final - 1 - (i_block & (ptrs - 1));
109	return n;
110}
111
112/**
113 *	ext4_get_branch - read the chain of indirect blocks leading to data
114 *	@inode: inode in question
115 *	@depth: depth of the chain (1 - direct pointer, etc.)
116 *	@offsets: offsets of pointers in inode/indirect blocks
117 *	@chain: place to store the result
118 *	@err: here we store the error value
119 *
120 *	Function fills the array of triples <key, p, bh> and returns %NULL
121 *	if everything went OK or the pointer to the last filled triple
122 *	(incomplete one) otherwise. Upon the return chain[i].key contains
123 *	the number of (i+1)-th block in the chain (as it is stored in memory,
124 *	i.e. little-endian 32-bit), chain[i].p contains the address of that
125 *	number (it points into struct inode for i==0 and into the bh->b_data
126 *	for i>0) and chain[i].bh points to the buffer_head of i-th indirect
127 *	block for i>0 and NULL for i==0. In other words, it holds the block
128 *	numbers of the chain, addresses they were taken from (and where we can
129 *	verify that chain did not change) and buffer_heads hosting these
130 *	numbers.
131 *
132 *	Function stops when it stumbles upon zero pointer (absent block)
133 *		(pointer to last triple returned, *@err == 0)
134 *	or when it gets an IO error reading an indirect block
135 *		(ditto, *@err == -EIO)
136 *	or when it reads all @depth-1 indirect blocks successfully and finds
137 *	the whole chain, all way to the data (returns %NULL, *err == 0).
138 *
139 *      Need to be called with
140 *      down_read(&EXT4_I(inode)->i_data_sem)
141 */
142static Indirect *ext4_get_branch(struct inode *inode, int depth,
143				 ext4_lblk_t  *offsets,
144				 Indirect chain[4], int *err)
145{
146	struct super_block *sb = inode->i_sb;
147	Indirect *p = chain;
148	struct buffer_head *bh;
149	int ret = -EIO;
150
151	*err = 0;
152	/* i_data is not going away, no lock needed */
153	add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
154	if (!p->key)
155		goto no_block;
156	while (--depth) {
157		bh = sb_getblk(sb, le32_to_cpu(p->key));
158		if (unlikely(!bh)) {
159			ret = -ENOMEM;
160			goto failure;
161		}
162
163		if (!bh_uptodate_or_lock(bh)) {
164			if (bh_submit_read(bh) < 0) {
165				put_bh(bh);
166				goto failure;
167			}
168			/* validate block references */
169			if (ext4_check_indirect_blockref(inode, bh)) {
170				put_bh(bh);
171				goto failure;
172			}
173		}
174
175		add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
176		/* Reader: end */
177		if (!p->key)
178			goto no_block;
179	}
180	return NULL;
181
182failure:
183	*err = ret;
184no_block:
185	return p;
186}
187
188/**
189 *	ext4_find_near - find a place for allocation with sufficient locality
190 *	@inode: owner
191 *	@ind: descriptor of indirect block.
192 *
193 *	This function returns the preferred place for block allocation.
194 *	It is used when heuristic for sequential allocation fails.
195 *	Rules are:
196 *	  + if there is a block to the left of our position - allocate near it.
197 *	  + if pointer will live in indirect block - allocate near that block.
198 *	  + if pointer will live in inode - allocate in the same
199 *	    cylinder group.
200 *
201 * In the latter case we colour the starting block by the callers PID to
202 * prevent it from clashing with concurrent allocations for a different inode
203 * in the same block group.   The PID is used here so that functionally related
204 * files will be close-by on-disk.
205 *
206 *	Caller must make sure that @ind is valid and will stay that way.
207 */
208static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
209{
210	struct ext4_inode_info *ei = EXT4_I(inode);
211	__le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
212	__le32 *p;
213
214	/* Try to find previous block */
215	for (p = ind->p - 1; p >= start; p--) {
216		if (*p)
217			return le32_to_cpu(*p);
218	}
219
220	/* No such thing, so let's try location of indirect block */
221	if (ind->bh)
222		return ind->bh->b_blocknr;
223
224	/*
225	 * It is going to be referred to from the inode itself? OK, just put it
226	 * into the same cylinder group then.
227	 */
228	return ext4_inode_to_goal_block(inode);
229}
230
231/**
232 *	ext4_find_goal - find a preferred place for allocation.
233 *	@inode: owner
234 *	@block:  block we want
235 *	@partial: pointer to the last triple within a chain
236 *
237 *	Normally this function find the preferred place for block allocation,
238 *	returns it.
239 *	Because this is only used for non-extent files, we limit the block nr
240 *	to 32 bits.
241 */
242static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
243				   Indirect *partial)
244{
245	ext4_fsblk_t goal;
246
247	/*
248	 * XXX need to get goal block from mballoc's data structures
249	 */
250
251	goal = ext4_find_near(inode, partial);
252	goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
253	return goal;
254}
255
256/**
257 *	ext4_blks_to_allocate - Look up the block map and count the number
258 *	of direct blocks need to be allocated for the given branch.
259 *
260 *	@branch: chain of indirect blocks
261 *	@k: number of blocks need for indirect blocks
262 *	@blks: number of data blocks to be mapped.
263 *	@blocks_to_boundary:  the offset in the indirect block
264 *
265 *	return the total number of blocks to be allocate, including the
266 *	direct and indirect blocks.
267 */
268static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
269				 int blocks_to_boundary)
270{
271	unsigned int count = 0;
272
273	/*
274	 * Simple case, [t,d]Indirect block(s) has not allocated yet
275	 * then it's clear blocks on that path have not allocated
276	 */
277	if (k > 0) {
278		/* right now we don't handle cross boundary allocation */
279		if (blks < blocks_to_boundary + 1)
280			count += blks;
281		else
282			count += blocks_to_boundary + 1;
283		return count;
284	}
285
286	count++;
287	while (count < blks && count <= blocks_to_boundary &&
288		le32_to_cpu(*(branch[0].p + count)) == 0) {
289		count++;
290	}
291	return count;
292}
293
294/**
295 *	ext4_alloc_branch - allocate and set up a chain of blocks.
296 *	@handle: handle for this transaction
297 *	@inode: owner
298 *	@indirect_blks: number of allocated indirect blocks
299 *	@blks: number of allocated direct blocks
300 *	@goal: preferred place for allocation
301 *	@offsets: offsets (in the blocks) to store the pointers to next.
302 *	@branch: place to store the chain in.
303 *
304 *	This function allocates blocks, zeroes out all but the last one,
305 *	links them into chain and (if we are synchronous) writes them to disk.
306 *	In other words, it prepares a branch that can be spliced onto the
307 *	inode. It stores the information about that chain in the branch[], in
308 *	the same format as ext4_get_branch() would do. We are calling it after
309 *	we had read the existing part of chain and partial points to the last
310 *	triple of that (one with zero ->key). Upon the exit we have the same
311 *	picture as after the successful ext4_get_block(), except that in one
312 *	place chain is disconnected - *branch->p is still zero (we did not
313 *	set the last link), but branch->key contains the number that should
314 *	be placed into *branch->p to fill that gap.
315 *
316 *	If allocation fails we free all blocks we've allocated (and forget
317 *	their buffer_heads) and return the error value the from failed
318 *	ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
319 *	as described above and return 0.
320 */
321static int ext4_alloc_branch(handle_t *handle,
322			     struct ext4_allocation_request *ar,
323			     int indirect_blks, ext4_lblk_t *offsets,
324			     Indirect *branch)
325{
326	struct buffer_head *		bh;
327	ext4_fsblk_t			b, new_blocks[4];
328	__le32				*p;
329	int				i, j, err, len = 1;
330
331	for (i = 0; i <= indirect_blks; i++) {
332		if (i == indirect_blks) {
333			new_blocks[i] = ext4_mb_new_blocks(handle, ar, &err);
334		} else
335			ar->goal = new_blocks[i] = ext4_new_meta_blocks(handle,
336					ar->inode, ar->goal,
337					ar->flags & EXT4_MB_DELALLOC_RESERVED,
338					NULL, &err);
339		if (err) {
340			i--;
341			goto failed;
342		}
343		branch[i].key = cpu_to_le32(new_blocks[i]);
344		if (i == 0)
345			continue;
346
347		bh = branch[i].bh = sb_getblk(ar->inode->i_sb, new_blocks[i-1]);
348		if (unlikely(!bh)) {
349			err = -ENOMEM;
350			goto failed;
351		}
352		lock_buffer(bh);
353		BUFFER_TRACE(bh, "call get_create_access");
354		err = ext4_journal_get_create_access(handle, bh);
355		if (err) {
356			unlock_buffer(bh);
357			goto failed;
358		}
359
360		memset(bh->b_data, 0, bh->b_size);
361		p = branch[i].p = (__le32 *) bh->b_data + offsets[i];
362		b = new_blocks[i];
363
364		if (i == indirect_blks)
365			len = ar->len;
366		for (j = 0; j < len; j++)
367			*p++ = cpu_to_le32(b++);
368
369		BUFFER_TRACE(bh, "marking uptodate");
370		set_buffer_uptodate(bh);
371		unlock_buffer(bh);
372
373		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
374		err = ext4_handle_dirty_metadata(handle, ar->inode, bh);
375		if (err)
376			goto failed;
377	}
378	return 0;
379failed:
380	for (; i >= 0; i--) {
381		/*
382		 * We want to ext4_forget() only freshly allocated indirect
383		 * blocks.  Buffer for new_blocks[i-1] is at branch[i].bh and
384		 * buffer at branch[0].bh is indirect block / inode already
385		 * existing before ext4_alloc_branch() was called.
386		 */
387		if (i > 0 && i != indirect_blks && branch[i].bh)
388			ext4_forget(handle, 1, ar->inode, branch[i].bh,
389				    branch[i].bh->b_blocknr);
390		ext4_free_blocks(handle, ar->inode, NULL, new_blocks[i],
391				 (i == indirect_blks) ? ar->len : 1, 0);
392	}
393	return err;
394}
395
396/**
397 * ext4_splice_branch - splice the allocated branch onto inode.
398 * @handle: handle for this transaction
399 * @inode: owner
400 * @block: (logical) number of block we are adding
401 * @chain: chain of indirect blocks (with a missing link - see
402 *	ext4_alloc_branch)
403 * @where: location of missing link
404 * @num:   number of indirect blocks we are adding
405 * @blks:  number of direct blocks we are adding
406 *
407 * This function fills the missing link and does all housekeeping needed in
408 * inode (->i_blocks, etc.). In case of success we end up with the full
409 * chain to new block and return 0.
410 */
411static int ext4_splice_branch(handle_t *handle,
412			      struct ext4_allocation_request *ar,
413			      Indirect *where, int num)
414{
415	int i;
416	int err = 0;
417	ext4_fsblk_t current_block;
418
419	/*
420	 * If we're splicing into a [td]indirect block (as opposed to the
421	 * inode) then we need to get write access to the [td]indirect block
422	 * before the splice.
423	 */
424	if (where->bh) {
425		BUFFER_TRACE(where->bh, "get_write_access");
426		err = ext4_journal_get_write_access(handle, where->bh);
427		if (err)
428			goto err_out;
429	}
430	/* That's it */
431
432	*where->p = where->key;
433
434	/*
435	 * Update the host buffer_head or inode to point to more just allocated
436	 * direct blocks blocks
437	 */
438	if (num == 0 && ar->len > 1) {
439		current_block = le32_to_cpu(where->key) + 1;
440		for (i = 1; i < ar->len; i++)
441			*(where->p + i) = cpu_to_le32(current_block++);
442	}
443
444	/* We are done with atomic stuff, now do the rest of housekeeping */
445	/* had we spliced it onto indirect block? */
446	if (where->bh) {
447		/*
448		 * If we spliced it onto an indirect block, we haven't
449		 * altered the inode.  Note however that if it is being spliced
450		 * onto an indirect block at the very end of the file (the
451		 * file is growing) then we *will* alter the inode to reflect
452		 * the new i_size.  But that is not done here - it is done in
453		 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
454		 */
455		jbd_debug(5, "splicing indirect only\n");
456		BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
457		err = ext4_handle_dirty_metadata(handle, ar->inode, where->bh);
458		if (err)
459			goto err_out;
460	} else {
461		/*
462		 * OK, we spliced it into the inode itself on a direct block.
463		 */
464		ext4_mark_inode_dirty(handle, ar->inode);
465		jbd_debug(5, "splicing direct\n");
466	}
467	return err;
468
469err_out:
470	for (i = 1; i <= num; i++) {
471		/*
472		 * branch[i].bh is newly allocated, so there is no
473		 * need to revoke the block, which is why we don't
474		 * need to set EXT4_FREE_BLOCKS_METADATA.
475		 */
476		ext4_free_blocks(handle, ar->inode, where[i].bh, 0, 1,
477				 EXT4_FREE_BLOCKS_FORGET);
478	}
479	ext4_free_blocks(handle, ar->inode, NULL, le32_to_cpu(where[num].key),
480			 ar->len, 0);
481
482	return err;
483}
484
485/*
486 * The ext4_ind_map_blocks() function handles non-extents inodes
487 * (i.e., using the traditional indirect/double-indirect i_blocks
488 * scheme) for ext4_map_blocks().
489 *
490 * Allocation strategy is simple: if we have to allocate something, we will
491 * have to go the whole way to leaf. So let's do it before attaching anything
492 * to tree, set linkage between the newborn blocks, write them if sync is
493 * required, recheck the path, free and repeat if check fails, otherwise
494 * set the last missing link (that will protect us from any truncate-generated
495 * removals - all blocks on the path are immune now) and possibly force the
496 * write on the parent block.
497 * That has a nice additional property: no special recovery from the failed
498 * allocations is needed - we simply release blocks and do not touch anything
499 * reachable from inode.
500 *
501 * `handle' can be NULL if create == 0.
502 *
503 * return > 0, # of blocks mapped or allocated.
504 * return = 0, if plain lookup failed.
505 * return < 0, error case.
506 *
507 * The ext4_ind_get_blocks() function should be called with
508 * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
509 * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
510 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
511 * blocks.
512 */
513int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
514			struct ext4_map_blocks *map,
515			int flags)
516{
517	struct ext4_allocation_request ar;
518	int err = -EIO;
519	ext4_lblk_t offsets[4];
520	Indirect chain[4];
521	Indirect *partial;
522	int indirect_blks;
523	int blocks_to_boundary = 0;
524	int depth;
525	int count = 0;
526	ext4_fsblk_t first_block = 0;
527
528	trace_ext4_ind_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
529	J_ASSERT(!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)));
530	J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
531	depth = ext4_block_to_path(inode, map->m_lblk, offsets,
532				   &blocks_to_boundary);
533
534	if (depth == 0)
535		goto out;
536
537	partial = ext4_get_branch(inode, depth, offsets, chain, &err);
538
539	/* Simplest case - block found, no allocation needed */
540	if (!partial) {
541		first_block = le32_to_cpu(chain[depth - 1].key);
542		count++;
543		/*map more blocks*/
544		while (count < map->m_len && count <= blocks_to_boundary) {
545			ext4_fsblk_t blk;
546
547			blk = le32_to_cpu(*(chain[depth-1].p + count));
548
549			if (blk == first_block + count)
550				count++;
551			else
552				break;
553		}
554		goto got_it;
555	}
556
557	/* Next simple case - plain lookup or failed read of indirect block */
558	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
559		goto cleanup;
560
561	/*
562	 * Okay, we need to do block allocation.
563	*/
564	if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
565				       EXT4_FEATURE_RO_COMPAT_BIGALLOC)) {
566		EXT4_ERROR_INODE(inode, "Can't allocate blocks for "
567				 "non-extent mapped inodes with bigalloc");
568		return -EUCLEAN;
569	}
570
571	/* Set up for the direct block allocation */
572	memset(&ar, 0, sizeof(ar));
573	ar.inode = inode;
574	ar.logical = map->m_lblk;
575	if (S_ISREG(inode->i_mode))
576		ar.flags = EXT4_MB_HINT_DATA;
577	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
578		ar.flags |= EXT4_MB_DELALLOC_RESERVED;
579
580	ar.goal = ext4_find_goal(inode, map->m_lblk, partial);
581
582	/* the number of blocks need to allocate for [d,t]indirect blocks */
583	indirect_blks = (chain + depth) - partial - 1;
584
585	/*
586	 * Next look up the indirect map to count the totoal number of
587	 * direct blocks to allocate for this branch.
588	 */
589	ar.len = ext4_blks_to_allocate(partial, indirect_blks,
590				       map->m_len, blocks_to_boundary);
591
592	/*
593	 * Block out ext4_truncate while we alter the tree
594	 */
595	err = ext4_alloc_branch(handle, &ar, indirect_blks,
596				offsets + (partial - chain), partial);
597
598	/*
599	 * The ext4_splice_branch call will free and forget any buffers
600	 * on the new chain if there is a failure, but that risks using
601	 * up transaction credits, especially for bitmaps where the
602	 * credits cannot be returned.  Can we handle this somehow?  We
603	 * may need to return -EAGAIN upwards in the worst case.  --sct
604	 */
605	if (!err)
606		err = ext4_splice_branch(handle, &ar, partial, indirect_blks);
607	if (err)
608		goto cleanup;
609
610	map->m_flags |= EXT4_MAP_NEW;
611
612	ext4_update_inode_fsync_trans(handle, inode, 1);
613	count = ar.len;
614got_it:
615	map->m_flags |= EXT4_MAP_MAPPED;
616	map->m_pblk = le32_to_cpu(chain[depth-1].key);
617	map->m_len = count;
618	if (count > blocks_to_boundary)
619		map->m_flags |= EXT4_MAP_BOUNDARY;
620	err = count;
621	/* Clean up and exit */
622	partial = chain + depth - 1;	/* the whole chain */
623cleanup:
624	while (partial > chain) {
625		BUFFER_TRACE(partial->bh, "call brelse");
626		brelse(partial->bh);
627		partial--;
628	}
629out:
630	trace_ext4_ind_map_blocks_exit(inode, flags, map, err);
631	return err;
632}
633
634/*
635 * O_DIRECT for ext3 (or indirect map) based files
636 *
637 * If the O_DIRECT write will extend the file then add this inode to the
638 * orphan list.  So recovery will truncate it back to the original size
639 * if the machine crashes during the write.
640 *
641 * If the O_DIRECT write is intantiating holes inside i_size and the machine
642 * crashes then stale disk data _may_ be exposed inside the file. But current
643 * VFS code falls back into buffered path in that case so we are safe.
644 */
645ssize_t ext4_ind_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
646			   loff_t offset)
647{
648	struct file *file = iocb->ki_filp;
649	struct inode *inode = file->f_mapping->host;
650	struct ext4_inode_info *ei = EXT4_I(inode);
651	handle_t *handle;
652	ssize_t ret;
653	int orphan = 0;
654	size_t count = iov_iter_count(iter);
655	int retries = 0;
656
657	if (iov_iter_rw(iter) == WRITE) {
658		loff_t final_size = offset + count;
659
660		if (final_size > inode->i_size) {
661			/* Credits for sb + inode write */
662			handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
663			if (IS_ERR(handle)) {
664				ret = PTR_ERR(handle);
665				goto out;
666			}
667			ret = ext4_orphan_add(handle, inode);
668			if (ret) {
669				ext4_journal_stop(handle);
670				goto out;
671			}
672			orphan = 1;
673			ei->i_disksize = inode->i_size;
674			ext4_journal_stop(handle);
675		}
676	}
677
678retry:
679	if (iov_iter_rw(iter) == READ && ext4_should_dioread_nolock(inode)) {
680		/*
681		 * Nolock dioread optimization may be dynamically disabled
682		 * via ext4_inode_block_unlocked_dio(). Check inode's state
683		 * while holding extra i_dio_count ref.
684		 */
685		inode_dio_begin(inode);
686		smp_mb();
687		if (unlikely(ext4_test_inode_state(inode,
688						    EXT4_STATE_DIOREAD_LOCK))) {
689			inode_dio_end(inode);
690			goto locked;
691		}
692		if (IS_DAX(inode))
693			ret = dax_do_io(iocb, inode, iter, offset,
694					ext4_get_block, NULL, 0);
695		else
696			ret = __blockdev_direct_IO(iocb, inode,
697						   inode->i_sb->s_bdev, iter,
698						   offset, ext4_get_block, NULL,
699						   NULL, 0);
700		inode_dio_end(inode);
701	} else {
702locked:
703		if (IS_DAX(inode))
704			ret = dax_do_io(iocb, inode, iter, offset,
705					ext4_get_block, NULL, DIO_LOCKING);
706		else
707			ret = blockdev_direct_IO(iocb, inode, iter, offset,
708						 ext4_get_block);
709
710		if (unlikely(iov_iter_rw(iter) == WRITE && ret < 0)) {
711			loff_t isize = i_size_read(inode);
712			loff_t end = offset + count;
713
714			if (end > isize)
715				ext4_truncate_failed_write(inode);
716		}
717	}
718	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
719		goto retry;
720
721	if (orphan) {
722		int err;
723
724		/* Credits for sb + inode write */
725		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
726		if (IS_ERR(handle)) {
727			/* This is really bad luck. We've written the data
728			 * but cannot extend i_size. Bail out and pretend
729			 * the write failed... */
730			ret = PTR_ERR(handle);
731			if (inode->i_nlink)
732				ext4_orphan_del(NULL, inode);
733
734			goto out;
735		}
736		if (inode->i_nlink)
737			ext4_orphan_del(handle, inode);
738		if (ret > 0) {
739			loff_t end = offset + ret;
740			if (end > inode->i_size) {
741				ei->i_disksize = end;
742				i_size_write(inode, end);
743				/*
744				 * We're going to return a positive `ret'
745				 * here due to non-zero-length I/O, so there's
746				 * no way of reporting error returns from
747				 * ext4_mark_inode_dirty() to userspace.  So
748				 * ignore it.
749				 */
750				ext4_mark_inode_dirty(handle, inode);
751			}
752		}
753		err = ext4_journal_stop(handle);
754		if (ret == 0)
755			ret = err;
756	}
757out:
758	return ret;
759}
760
761/*
762 * Calculate the number of metadata blocks need to reserve
763 * to allocate a new block at @lblocks for non extent file based file
764 */
765int ext4_ind_calc_metadata_amount(struct inode *inode, sector_t lblock)
766{
767	struct ext4_inode_info *ei = EXT4_I(inode);
768	sector_t dind_mask = ~((sector_t)EXT4_ADDR_PER_BLOCK(inode->i_sb) - 1);
769	int blk_bits;
770
771	if (lblock < EXT4_NDIR_BLOCKS)
772		return 0;
773
774	lblock -= EXT4_NDIR_BLOCKS;
775
776	if (ei->i_da_metadata_calc_len &&
777	    (lblock & dind_mask) == ei->i_da_metadata_calc_last_lblock) {
778		ei->i_da_metadata_calc_len++;
779		return 0;
780	}
781	ei->i_da_metadata_calc_last_lblock = lblock & dind_mask;
782	ei->i_da_metadata_calc_len = 1;
783	blk_bits = order_base_2(lblock);
784	return (blk_bits / EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb)) + 1;
785}
786
787/*
788 * Calculate number of indirect blocks touched by mapping @nrblocks logically
789 * contiguous blocks
790 */
791int ext4_ind_trans_blocks(struct inode *inode, int nrblocks)
792{
793	/*
794	 * With N contiguous data blocks, we need at most
795	 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) + 1 indirect blocks,
796	 * 2 dindirect blocks, and 1 tindirect block
797	 */
798	return DIV_ROUND_UP(nrblocks, EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4;
799}
800
801/*
802 * Truncate transactions can be complex and absolutely huge.  So we need to
803 * be able to restart the transaction at a conventient checkpoint to make
804 * sure we don't overflow the journal.
805 *
806 * Try to extend this transaction for the purposes of truncation.  If
807 * extend fails, we need to propagate the failure up and restart the
808 * transaction in the top-level truncate loop. --sct
809 *
810 * Returns 0 if we managed to create more room.  If we can't create more
811 * room, and the transaction must be restarted we return 1.
812 */
813static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
814{
815	if (!ext4_handle_valid(handle))
816		return 0;
817	if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
818		return 0;
819	if (!ext4_journal_extend(handle, ext4_blocks_for_truncate(inode)))
820		return 0;
821	return 1;
822}
823
824/*
825 * Probably it should be a library function... search for first non-zero word
826 * or memcmp with zero_page, whatever is better for particular architecture.
827 * Linus?
828 */
829static inline int all_zeroes(__le32 *p, __le32 *q)
830{
831	while (p < q)
832		if (*p++)
833			return 0;
834	return 1;
835}
836
837/**
838 *	ext4_find_shared - find the indirect blocks for partial truncation.
839 *	@inode:	  inode in question
840 *	@depth:	  depth of the affected branch
841 *	@offsets: offsets of pointers in that branch (see ext4_block_to_path)
842 *	@chain:	  place to store the pointers to partial indirect blocks
843 *	@top:	  place to the (detached) top of branch
844 *
845 *	This is a helper function used by ext4_truncate().
846 *
847 *	When we do truncate() we may have to clean the ends of several
848 *	indirect blocks but leave the blocks themselves alive. Block is
849 *	partially truncated if some data below the new i_size is referred
850 *	from it (and it is on the path to the first completely truncated
851 *	data block, indeed).  We have to free the top of that path along
852 *	with everything to the right of the path. Since no allocation
853 *	past the truncation point is possible until ext4_truncate()
854 *	finishes, we may safely do the latter, but top of branch may
855 *	require special attention - pageout below the truncation point
856 *	might try to populate it.
857 *
858 *	We atomically detach the top of branch from the tree, store the
859 *	block number of its root in *@top, pointers to buffer_heads of
860 *	partially truncated blocks - in @chain[].bh and pointers to
861 *	their last elements that should not be removed - in
862 *	@chain[].p. Return value is the pointer to last filled element
863 *	of @chain.
864 *
865 *	The work left to caller to do the actual freeing of subtrees:
866 *		a) free the subtree starting from *@top
867 *		b) free the subtrees whose roots are stored in
868 *			(@chain[i].p+1 .. end of @chain[i].bh->b_data)
869 *		c) free the subtrees growing from the inode past the @chain[0].
870 *			(no partially truncated stuff there).  */
871
872static Indirect *ext4_find_shared(struct inode *inode, int depth,
873				  ext4_lblk_t offsets[4], Indirect chain[4],
874				  __le32 *top)
875{
876	Indirect *partial, *p;
877	int k, err;
878
879	*top = 0;
880	/* Make k index the deepest non-null offset + 1 */
881	for (k = depth; k > 1 && !offsets[k-1]; k--)
882		;
883	partial = ext4_get_branch(inode, k, offsets, chain, &err);
884	/* Writer: pointers */
885	if (!partial)
886		partial = chain + k-1;
887	/*
888	 * If the branch acquired continuation since we've looked at it -
889	 * fine, it should all survive and (new) top doesn't belong to us.
890	 */
891	if (!partial->key && *partial->p)
892		/* Writer: end */
893		goto no_top;
894	for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
895		;
896	/*
897	 * OK, we've found the last block that must survive. The rest of our
898	 * branch should be detached before unlocking. However, if that rest
899	 * of branch is all ours and does not grow immediately from the inode
900	 * it's easier to cheat and just decrement partial->p.
901	 */
902	if (p == chain + k - 1 && p > chain) {
903		p->p--;
904	} else {
905		*top = *p->p;
906		/* Nope, don't do this in ext4.  Must leave the tree intact */
907#if 0
908		*p->p = 0;
909#endif
910	}
911	/* Writer: end */
912
913	while (partial > p) {
914		brelse(partial->bh);
915		partial--;
916	}
917no_top:
918	return partial;
919}
920
921/*
922 * Zero a number of block pointers in either an inode or an indirect block.
923 * If we restart the transaction we must again get write access to the
924 * indirect block for further modification.
925 *
926 * We release `count' blocks on disk, but (last - first) may be greater
927 * than `count' because there can be holes in there.
928 *
929 * Return 0 on success, 1 on invalid block range
930 * and < 0 on fatal error.
931 */
932static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
933			     struct buffer_head *bh,
934			     ext4_fsblk_t block_to_free,
935			     unsigned long count, __le32 *first,
936			     __le32 *last)
937{
938	__le32 *p;
939	int	flags = EXT4_FREE_BLOCKS_VALIDATED;
940	int	err;
941
942	if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
943		flags |= EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_METADATA;
944	else if (ext4_should_journal_data(inode))
945		flags |= EXT4_FREE_BLOCKS_FORGET;
946
947	if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
948				   count)) {
949		EXT4_ERROR_INODE(inode, "attempt to clear invalid "
950				 "blocks %llu len %lu",
951				 (unsigned long long) block_to_free, count);
952		return 1;
953	}
954
955	if (try_to_extend_transaction(handle, inode)) {
956		if (bh) {
957			BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
958			err = ext4_handle_dirty_metadata(handle, inode, bh);
959			if (unlikely(err))
960				goto out_err;
961		}
962		err = ext4_mark_inode_dirty(handle, inode);
963		if (unlikely(err))
964			goto out_err;
965		err = ext4_truncate_restart_trans(handle, inode,
966					ext4_blocks_for_truncate(inode));
967		if (unlikely(err))
968			goto out_err;
969		if (bh) {
970			BUFFER_TRACE(bh, "retaking write access");
971			err = ext4_journal_get_write_access(handle, bh);
972			if (unlikely(err))
973				goto out_err;
974		}
975	}
976
977	for (p = first; p < last; p++)
978		*p = 0;
979
980	ext4_free_blocks(handle, inode, NULL, block_to_free, count, flags);
981	return 0;
982out_err:
983	ext4_std_error(inode->i_sb, err);
984	return err;
985}
986
987/**
988 * ext4_free_data - free a list of data blocks
989 * @handle:	handle for this transaction
990 * @inode:	inode we are dealing with
991 * @this_bh:	indirect buffer_head which contains *@first and *@last
992 * @first:	array of block numbers
993 * @last:	points immediately past the end of array
994 *
995 * We are freeing all blocks referred from that array (numbers are stored as
996 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
997 *
998 * We accumulate contiguous runs of blocks to free.  Conveniently, if these
999 * blocks are contiguous then releasing them at one time will only affect one
1000 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
1001 * actually use a lot of journal space.
1002 *
1003 * @this_bh will be %NULL if @first and @last point into the inode's direct
1004 * block pointers.
1005 */
1006static void ext4_free_data(handle_t *handle, struct inode *inode,
1007			   struct buffer_head *this_bh,
1008			   __le32 *first, __le32 *last)
1009{
1010	ext4_fsblk_t block_to_free = 0;    /* Starting block # of a run */
1011	unsigned long count = 0;	    /* Number of blocks in the run */
1012	__le32 *block_to_free_p = NULL;	    /* Pointer into inode/ind
1013					       corresponding to
1014					       block_to_free */
1015	ext4_fsblk_t nr;		    /* Current block # */
1016	__le32 *p;			    /* Pointer into inode/ind
1017					       for current block */
1018	int err = 0;
1019
1020	if (this_bh) {				/* For indirect block */
1021		BUFFER_TRACE(this_bh, "get_write_access");
1022		err = ext4_journal_get_write_access(handle, this_bh);
1023		/* Important: if we can't update the indirect pointers
1024		 * to the blocks, we can't free them. */
1025		if (err)
1026			return;
1027	}
1028
1029	for (p = first; p < last; p++) {
1030		nr = le32_to_cpu(*p);
1031		if (nr) {
1032			/* accumulate blocks to free if they're contiguous */
1033			if (count == 0) {
1034				block_to_free = nr;
1035				block_to_free_p = p;
1036				count = 1;
1037			} else if (nr == block_to_free + count) {
1038				count++;
1039			} else {
1040				err = ext4_clear_blocks(handle, inode, this_bh,
1041						        block_to_free, count,
1042						        block_to_free_p, p);
1043				if (err)
1044					break;
1045				block_to_free = nr;
1046				block_to_free_p = p;
1047				count = 1;
1048			}
1049		}
1050	}
1051
1052	if (!err && count > 0)
1053		err = ext4_clear_blocks(handle, inode, this_bh, block_to_free,
1054					count, block_to_free_p, p);
1055	if (err < 0)
1056		/* fatal error */
1057		return;
1058
1059	if (this_bh) {
1060		BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
1061
1062		/*
1063		 * The buffer head should have an attached journal head at this
1064		 * point. However, if the data is corrupted and an indirect
1065		 * block pointed to itself, it would have been detached when
1066		 * the block was cleared. Check for this instead of OOPSing.
1067		 */
1068		if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
1069			ext4_handle_dirty_metadata(handle, inode, this_bh);
1070		else
1071			EXT4_ERROR_INODE(inode,
1072					 "circular indirect block detected at "
1073					 "block %llu",
1074				(unsigned long long) this_bh->b_blocknr);
1075	}
1076}
1077
1078/**
1079 *	ext4_free_branches - free an array of branches
1080 *	@handle: JBD handle for this transaction
1081 *	@inode:	inode we are dealing with
1082 *	@parent_bh: the buffer_head which contains *@first and *@last
1083 *	@first:	array of block numbers
1084 *	@last:	pointer immediately past the end of array
1085 *	@depth:	depth of the branches to free
1086 *
1087 *	We are freeing all blocks referred from these branches (numbers are
1088 *	stored as little-endian 32-bit) and updating @inode->i_blocks
1089 *	appropriately.
1090 */
1091static void ext4_free_branches(handle_t *handle, struct inode *inode,
1092			       struct buffer_head *parent_bh,
1093			       __le32 *first, __le32 *last, int depth)
1094{
1095	ext4_fsblk_t nr;
1096	__le32 *p;
1097
1098	if (ext4_handle_is_aborted(handle))
1099		return;
1100
1101	if (depth--) {
1102		struct buffer_head *bh;
1103		int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
1104		p = last;
1105		while (--p >= first) {
1106			nr = le32_to_cpu(*p);
1107			if (!nr)
1108				continue;		/* A hole */
1109
1110			if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
1111						   nr, 1)) {
1112				EXT4_ERROR_INODE(inode,
1113						 "invalid indirect mapped "
1114						 "block %lu (level %d)",
1115						 (unsigned long) nr, depth);
1116				break;
1117			}
1118
1119			/* Go read the buffer for the next level down */
1120			bh = sb_bread(inode->i_sb, nr);
1121
1122			/*
1123			 * A read failure? Report error and clear slot
1124			 * (should be rare).
1125			 */
1126			if (!bh) {
1127				EXT4_ERROR_INODE_BLOCK(inode, nr,
1128						       "Read failure");
1129				continue;
1130			}
1131
1132			/* This zaps the entire block.  Bottom up. */
1133			BUFFER_TRACE(bh, "free child branches");
1134			ext4_free_branches(handle, inode, bh,
1135					(__le32 *) bh->b_data,
1136					(__le32 *) bh->b_data + addr_per_block,
1137					depth);
1138			brelse(bh);
1139
1140			/*
1141			 * Everything below this this pointer has been
1142			 * released.  Now let this top-of-subtree go.
1143			 *
1144			 * We want the freeing of this indirect block to be
1145			 * atomic in the journal with the updating of the
1146			 * bitmap block which owns it.  So make some room in
1147			 * the journal.
1148			 *
1149			 * We zero the parent pointer *after* freeing its
1150			 * pointee in the bitmaps, so if extend_transaction()
1151			 * for some reason fails to put the bitmap changes and
1152			 * the release into the same transaction, recovery
1153			 * will merely complain about releasing a free block,
1154			 * rather than leaking blocks.
1155			 */
1156			if (ext4_handle_is_aborted(handle))
1157				return;
1158			if (try_to_extend_transaction(handle, inode)) {
1159				ext4_mark_inode_dirty(handle, inode);
1160				ext4_truncate_restart_trans(handle, inode,
1161					    ext4_blocks_for_truncate(inode));
1162			}
1163
1164			/*
1165			 * The forget flag here is critical because if
1166			 * we are journaling (and not doing data
1167			 * journaling), we have to make sure a revoke
1168			 * record is written to prevent the journal
1169			 * replay from overwriting the (former)
1170			 * indirect block if it gets reallocated as a
1171			 * data block.  This must happen in the same
1172			 * transaction where the data blocks are
1173			 * actually freed.
1174			 */
1175			ext4_free_blocks(handle, inode, NULL, nr, 1,
1176					 EXT4_FREE_BLOCKS_METADATA|
1177					 EXT4_FREE_BLOCKS_FORGET);
1178
1179			if (parent_bh) {
1180				/*
1181				 * The block which we have just freed is
1182				 * pointed to by an indirect block: journal it
1183				 */
1184				BUFFER_TRACE(parent_bh, "get_write_access");
1185				if (!ext4_journal_get_write_access(handle,
1186								   parent_bh)){
1187					*p = 0;
1188					BUFFER_TRACE(parent_bh,
1189					"call ext4_handle_dirty_metadata");
1190					ext4_handle_dirty_metadata(handle,
1191								   inode,
1192								   parent_bh);
1193				}
1194			}
1195		}
1196	} else {
1197		/* We have reached the bottom of the tree. */
1198		BUFFER_TRACE(parent_bh, "free data blocks");
1199		ext4_free_data(handle, inode, parent_bh, first, last);
1200	}
1201}
1202
1203void ext4_ind_truncate(handle_t *handle, struct inode *inode)
1204{
1205	struct ext4_inode_info *ei = EXT4_I(inode);
1206	__le32 *i_data = ei->i_data;
1207	int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
1208	ext4_lblk_t offsets[4];
1209	Indirect chain[4];
1210	Indirect *partial;
1211	__le32 nr = 0;
1212	int n = 0;
1213	ext4_lblk_t last_block, max_block;
1214	unsigned blocksize = inode->i_sb->s_blocksize;
1215
1216	last_block = (inode->i_size + blocksize-1)
1217					>> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
1218	max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
1219					>> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
1220
1221	if (last_block != max_block) {
1222		n = ext4_block_to_path(inode, last_block, offsets, NULL);
1223		if (n == 0)
1224			return;
1225	}
1226
1227	ext4_es_remove_extent(inode, last_block, EXT_MAX_BLOCKS - last_block);
1228
1229	/*
1230	 * The orphan list entry will now protect us from any crash which
1231	 * occurs before the truncate completes, so it is now safe to propagate
1232	 * the new, shorter inode size (held for now in i_size) into the
1233	 * on-disk inode. We do this via i_disksize, which is the value which
1234	 * ext4 *really* writes onto the disk inode.
1235	 */
1236	ei->i_disksize = inode->i_size;
1237
1238	if (last_block == max_block) {
1239		/*
1240		 * It is unnecessary to free any data blocks if last_block is
1241		 * equal to the indirect block limit.
1242		 */
1243		return;
1244	} else if (n == 1) {		/* direct blocks */
1245		ext4_free_data(handle, inode, NULL, i_data+offsets[0],
1246			       i_data + EXT4_NDIR_BLOCKS);
1247		goto do_indirects;
1248	}
1249
1250	partial = ext4_find_shared(inode, n, offsets, chain, &nr);
1251	/* Kill the top of shared branch (not detached) */
1252	if (nr) {
1253		if (partial == chain) {
1254			/* Shared branch grows from the inode */
1255			ext4_free_branches(handle, inode, NULL,
1256					   &nr, &nr+1, (chain+n-1) - partial);
1257			*partial->p = 0;
1258			/*
1259			 * We mark the inode dirty prior to restart,
1260			 * and prior to stop.  No need for it here.
1261			 */
1262		} else {
1263			/* Shared branch grows from an indirect block */
1264			BUFFER_TRACE(partial->bh, "get_write_access");
1265			ext4_free_branches(handle, inode, partial->bh,
1266					partial->p,
1267					partial->p+1, (chain+n-1) - partial);
1268		}
1269	}
1270	/* Clear the ends of indirect blocks on the shared branch */
1271	while (partial > chain) {
1272		ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
1273				   (__le32*)partial->bh->b_data+addr_per_block,
1274				   (chain+n-1) - partial);
1275		BUFFER_TRACE(partial->bh, "call brelse");
1276		brelse(partial->bh);
1277		partial--;
1278	}
1279do_indirects:
1280	/* Kill the remaining (whole) subtrees */
1281	switch (offsets[0]) {
1282	default:
1283		nr = i_data[EXT4_IND_BLOCK];
1284		if (nr) {
1285			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
1286			i_data[EXT4_IND_BLOCK] = 0;
1287		}
1288	case EXT4_IND_BLOCK:
1289		nr = i_data[EXT4_DIND_BLOCK];
1290		if (nr) {
1291			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
1292			i_data[EXT4_DIND_BLOCK] = 0;
1293		}
1294	case EXT4_DIND_BLOCK:
1295		nr = i_data[EXT4_TIND_BLOCK];
1296		if (nr) {
1297			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
1298			i_data[EXT4_TIND_BLOCK] = 0;
1299		}
1300	case EXT4_TIND_BLOCK:
1301		;
1302	}
1303}
1304
1305/**
1306 *	ext4_ind_remove_space - remove space from the range
1307 *	@handle: JBD handle for this transaction
1308 *	@inode:	inode we are dealing with
1309 *	@start:	First block to remove
1310 *	@end:	One block after the last block to remove (exclusive)
1311 *
1312 *	Free the blocks in the defined range (end is exclusive endpoint of
1313 *	range). This is used by ext4_punch_hole().
1314 */
1315int ext4_ind_remove_space(handle_t *handle, struct inode *inode,
1316			  ext4_lblk_t start, ext4_lblk_t end)
1317{
1318	struct ext4_inode_info *ei = EXT4_I(inode);
1319	__le32 *i_data = ei->i_data;
1320	int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
1321	ext4_lblk_t offsets[4], offsets2[4];
1322	Indirect chain[4], chain2[4];
1323	Indirect *partial, *partial2;
1324	ext4_lblk_t max_block;
1325	__le32 nr = 0, nr2 = 0;
1326	int n = 0, n2 = 0;
1327	unsigned blocksize = inode->i_sb->s_blocksize;
1328
1329	max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
1330					>> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
1331	if (end >= max_block)
1332		end = max_block;
1333	if ((start >= end) || (start > max_block))
1334		return 0;
1335
1336	n = ext4_block_to_path(inode, start, offsets, NULL);
1337	n2 = ext4_block_to_path(inode, end, offsets2, NULL);
1338
1339	BUG_ON(n > n2);
1340
1341	if ((n == 1) && (n == n2)) {
1342		/* We're punching only within direct block range */
1343		ext4_free_data(handle, inode, NULL, i_data + offsets[0],
1344			       i_data + offsets2[0]);
1345		return 0;
1346	} else if (n2 > n) {
1347		/*
1348		 * Start and end are on a different levels so we're going to
1349		 * free partial block at start, and partial block at end of
1350		 * the range. If there are some levels in between then
1351		 * do_indirects label will take care of that.
1352		 */
1353
1354		if (n == 1) {
1355			/*
1356			 * Start is at the direct block level, free
1357			 * everything to the end of the level.
1358			 */
1359			ext4_free_data(handle, inode, NULL, i_data + offsets[0],
1360				       i_data + EXT4_NDIR_BLOCKS);
1361			goto end_range;
1362		}
1363
1364
1365		partial = ext4_find_shared(inode, n, offsets, chain, &nr);
1366		if (nr) {
1367			if (partial == chain) {
1368				/* Shared branch grows from the inode */
1369				ext4_free_branches(handle, inode, NULL,
1370					   &nr, &nr+1, (chain+n-1) - partial);
1371				*partial->p = 0;
1372			} else {
1373				/* Shared branch grows from an indirect block */
1374				BUFFER_TRACE(partial->bh, "get_write_access");
1375				ext4_free_branches(handle, inode, partial->bh,
1376					partial->p,
1377					partial->p+1, (chain+n-1) - partial);
1378			}
1379		}
1380
1381		/*
1382		 * Clear the ends of indirect blocks on the shared branch
1383		 * at the start of the range
1384		 */
1385		while (partial > chain) {
1386			ext4_free_branches(handle, inode, partial->bh,
1387				partial->p + 1,
1388				(__le32 *)partial->bh->b_data+addr_per_block,
1389				(chain+n-1) - partial);
1390			BUFFER_TRACE(partial->bh, "call brelse");
1391			brelse(partial->bh);
1392			partial--;
1393		}
1394
1395end_range:
1396		partial2 = ext4_find_shared(inode, n2, offsets2, chain2, &nr2);
1397		if (nr2) {
1398			if (partial2 == chain2) {
1399				/*
1400				 * Remember, end is exclusive so here we're at
1401				 * the start of the next level we're not going
1402				 * to free. Everything was covered by the start
1403				 * of the range.
1404				 */
1405				goto do_indirects;
1406			}
1407		} else {
1408			/*
1409			 * ext4_find_shared returns Indirect structure which
1410			 * points to the last element which should not be
1411			 * removed by truncate. But this is end of the range
1412			 * in punch_hole so we need to point to the next element
1413			 */
1414			partial2->p++;
1415		}
1416
1417		/*
1418		 * Clear the ends of indirect blocks on the shared branch
1419		 * at the end of the range
1420		 */
1421		while (partial2 > chain2) {
1422			ext4_free_branches(handle, inode, partial2->bh,
1423					   (__le32 *)partial2->bh->b_data,
1424					   partial2->p,
1425					   (chain2+n2-1) - partial2);
1426			BUFFER_TRACE(partial2->bh, "call brelse");
1427			brelse(partial2->bh);
1428			partial2--;
1429		}
1430		goto do_indirects;
1431	}
1432
1433	/* Punch happened within the same level (n == n2) */
1434	partial = ext4_find_shared(inode, n, offsets, chain, &nr);
1435	partial2 = ext4_find_shared(inode, n2, offsets2, chain2, &nr2);
1436
1437	/* Free top, but only if partial2 isn't its subtree. */
1438	if (nr) {
1439		int level = min(partial - chain, partial2 - chain2);
1440		int i;
1441		int subtree = 1;
1442
1443		for (i = 0; i <= level; i++) {
1444			if (offsets[i] != offsets2[i]) {
1445				subtree = 0;
1446				break;
1447			}
1448		}
1449
1450		if (!subtree) {
1451			if (partial == chain) {
1452				/* Shared branch grows from the inode */
1453				ext4_free_branches(handle, inode, NULL,
1454						   &nr, &nr+1,
1455						   (chain+n-1) - partial);
1456				*partial->p = 0;
1457			} else {
1458				/* Shared branch grows from an indirect block */
1459				BUFFER_TRACE(partial->bh, "get_write_access");
1460				ext4_free_branches(handle, inode, partial->bh,
1461						   partial->p,
1462						   partial->p+1,
1463						   (chain+n-1) - partial);
1464			}
1465		}
1466	}
1467
1468	if (!nr2) {
1469		/*
1470		 * ext4_find_shared returns Indirect structure which
1471		 * points to the last element which should not be
1472		 * removed by truncate. But this is end of the range
1473		 * in punch_hole so we need to point to the next element
1474		 */
1475		partial2->p++;
1476	}
1477
1478	while (partial > chain || partial2 > chain2) {
1479		int depth = (chain+n-1) - partial;
1480		int depth2 = (chain2+n2-1) - partial2;
1481
1482		if (partial > chain && partial2 > chain2 &&
1483		    partial->bh->b_blocknr == partial2->bh->b_blocknr) {
1484			/*
1485			 * We've converged on the same block. Clear the range,
1486			 * then we're done.
1487			 */
1488			ext4_free_branches(handle, inode, partial->bh,
1489					   partial->p + 1,
1490					   partial2->p,
1491					   (chain+n-1) - partial);
1492			BUFFER_TRACE(partial->bh, "call brelse");
1493			brelse(partial->bh);
1494			BUFFER_TRACE(partial2->bh, "call brelse");
1495			brelse(partial2->bh);
1496			return 0;
1497		}
1498
1499		/*
1500		 * The start and end partial branches may not be at the same
1501		 * level even though the punch happened within one level. So, we
1502		 * give them a chance to arrive at the same level, then walk
1503		 * them in step with each other until we converge on the same
1504		 * block.
1505		 */
1506		if (partial > chain && depth <= depth2) {
1507			ext4_free_branches(handle, inode, partial->bh,
1508					   partial->p + 1,
1509					   (__le32 *)partial->bh->b_data+addr_per_block,
1510					   (chain+n-1) - partial);
1511			BUFFER_TRACE(partial->bh, "call brelse");
1512			brelse(partial->bh);
1513			partial--;
1514		}
1515		if (partial2 > chain2 && depth2 <= depth) {
1516			ext4_free_branches(handle, inode, partial2->bh,
1517					   (__le32 *)partial2->bh->b_data,
1518					   partial2->p,
1519					   (chain2+n2-1) - partial2);
1520			BUFFER_TRACE(partial2->bh, "call brelse");
1521			brelse(partial2->bh);
1522			partial2--;
1523		}
1524	}
1525	return 0;
1526
1527do_indirects:
1528	/* Kill the remaining (whole) subtrees */
1529	switch (offsets[0]) {
1530	default:
1531		if (++n >= n2)
1532			return 0;
1533		nr = i_data[EXT4_IND_BLOCK];
1534		if (nr) {
1535			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
1536			i_data[EXT4_IND_BLOCK] = 0;
1537		}
1538	case EXT4_IND_BLOCK:
1539		if (++n >= n2)
1540			return 0;
1541		nr = i_data[EXT4_DIND_BLOCK];
1542		if (nr) {
1543			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
1544			i_data[EXT4_DIND_BLOCK] = 0;
1545		}
1546	case EXT4_DIND_BLOCK:
1547		if (++n >= n2)
1548			return 0;
1549		nr = i_data[EXT4_TIND_BLOCK];
1550		if (nr) {
1551			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
1552			i_data[EXT4_TIND_BLOCK] = 0;
1553		}
1554	case EXT4_TIND_BLOCK:
1555		;
1556	}
1557	return 0;
1558}
1559