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