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