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