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