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