arm64: kgdb: Fix single-step exception handling oops
[linux/fpc-iii.git] / fs / ext4 / extents.c
blobab19f61bd04bc21db1165ade1cc576450bc966f4
1 /*
2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
5 * Architecture independence:
6 * Copyright (c) 2005, Bull S.A.
7 * Written by Pierre Peiffer <pierre.peiffer@bull.net>
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.
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.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
24 * Extents support for EXT4
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
32 #include <linux/fs.h>
33 #include <linux/time.h>
34 #include <linux/jbd2.h>
35 #include <linux/highuid.h>
36 #include <linux/pagemap.h>
37 #include <linux/quotaops.h>
38 #include <linux/string.h>
39 #include <linux/slab.h>
40 #include <asm/uaccess.h>
41 #include <linux/fiemap.h>
42 #include <linux/backing-dev.h>
43 #include "ext4_jbd2.h"
44 #include "ext4_extents.h"
45 #include "xattr.h"
47 #include <trace/events/ext4.h>
50 * used by extent splitting.
52 #define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
53 due to ENOSPC */
54 #define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
55 #define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
57 #define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
58 #define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
60 static __le32 ext4_extent_block_csum(struct inode *inode,
61 struct ext4_extent_header *eh)
63 struct ext4_inode_info *ei = EXT4_I(inode);
64 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
65 __u32 csum;
67 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
68 EXT4_EXTENT_TAIL_OFFSET(eh));
69 return cpu_to_le32(csum);
72 static int ext4_extent_block_csum_verify(struct inode *inode,
73 struct ext4_extent_header *eh)
75 struct ext4_extent_tail *et;
77 if (!ext4_has_metadata_csum(inode->i_sb))
78 return 1;
80 et = find_ext4_extent_tail(eh);
81 if (et->et_checksum != ext4_extent_block_csum(inode, eh))
82 return 0;
83 return 1;
86 static void ext4_extent_block_csum_set(struct inode *inode,
87 struct ext4_extent_header *eh)
89 struct ext4_extent_tail *et;
91 if (!ext4_has_metadata_csum(inode->i_sb))
92 return;
94 et = find_ext4_extent_tail(eh);
95 et->et_checksum = ext4_extent_block_csum(inode, eh);
98 static int ext4_split_extent(handle_t *handle,
99 struct inode *inode,
100 struct ext4_ext_path **ppath,
101 struct ext4_map_blocks *map,
102 int split_flag,
103 int flags);
105 static int ext4_split_extent_at(handle_t *handle,
106 struct inode *inode,
107 struct ext4_ext_path **ppath,
108 ext4_lblk_t split,
109 int split_flag,
110 int flags);
112 static int ext4_find_delayed_extent(struct inode *inode,
113 struct extent_status *newes);
115 static int ext4_ext_truncate_extend_restart(handle_t *handle,
116 struct inode *inode,
117 int needed)
119 int err;
121 if (!ext4_handle_valid(handle))
122 return 0;
123 if (handle->h_buffer_credits >= needed)
124 return 0;
126 * If we need to extend the journal get a few extra blocks
127 * while we're at it for efficiency's sake.
129 needed += 3;
130 err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
131 if (err <= 0)
132 return err;
133 err = ext4_truncate_restart_trans(handle, inode, needed);
134 if (err == 0)
135 err = -EAGAIN;
137 return err;
141 * could return:
142 * - EROFS
143 * - ENOMEM
145 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
146 struct ext4_ext_path *path)
148 if (path->p_bh) {
149 /* path points to block */
150 BUFFER_TRACE(path->p_bh, "get_write_access");
151 return ext4_journal_get_write_access(handle, path->p_bh);
153 /* path points to leaf/index in inode body */
154 /* we use in-core data, no need to protect them */
155 return 0;
159 * could return:
160 * - EROFS
161 * - ENOMEM
162 * - EIO
164 int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
165 struct inode *inode, struct ext4_ext_path *path)
167 int err;
169 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
170 if (path->p_bh) {
171 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
172 /* path points to block */
173 err = __ext4_handle_dirty_metadata(where, line, handle,
174 inode, path->p_bh);
175 } else {
176 /* path points to leaf/index in inode body */
177 err = ext4_mark_inode_dirty(handle, inode);
179 return err;
182 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
183 struct ext4_ext_path *path,
184 ext4_lblk_t block)
186 if (path) {
187 int depth = path->p_depth;
188 struct ext4_extent *ex;
191 * Try to predict block placement assuming that we are
192 * filling in a file which will eventually be
193 * non-sparse --- i.e., in the case of libbfd writing
194 * an ELF object sections out-of-order but in a way
195 * the eventually results in a contiguous object or
196 * executable file, or some database extending a table
197 * space file. However, this is actually somewhat
198 * non-ideal if we are writing a sparse file such as
199 * qemu or KVM writing a raw image file that is going
200 * to stay fairly sparse, since it will end up
201 * fragmenting the file system's free space. Maybe we
202 * should have some hueristics or some way to allow
203 * userspace to pass a hint to file system,
204 * especially if the latter case turns out to be
205 * common.
207 ex = path[depth].p_ext;
208 if (ex) {
209 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
210 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
212 if (block > ext_block)
213 return ext_pblk + (block - ext_block);
214 else
215 return ext_pblk - (ext_block - block);
218 /* it looks like index is empty;
219 * try to find starting block from index itself */
220 if (path[depth].p_bh)
221 return path[depth].p_bh->b_blocknr;
224 /* OK. use inode's group */
225 return ext4_inode_to_goal_block(inode);
229 * Allocation for a meta data block
231 static ext4_fsblk_t
232 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
233 struct ext4_ext_path *path,
234 struct ext4_extent *ex, int *err, unsigned int flags)
236 ext4_fsblk_t goal, newblock;
238 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
239 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
240 NULL, err);
241 return newblock;
244 static inline int ext4_ext_space_block(struct inode *inode, int check)
246 int size;
248 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
249 / sizeof(struct ext4_extent);
250 #ifdef AGGRESSIVE_TEST
251 if (!check && size > 6)
252 size = 6;
253 #endif
254 return size;
257 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
259 int size;
261 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
262 / sizeof(struct ext4_extent_idx);
263 #ifdef AGGRESSIVE_TEST
264 if (!check && size > 5)
265 size = 5;
266 #endif
267 return size;
270 static inline int ext4_ext_space_root(struct inode *inode, int check)
272 int size;
274 size = sizeof(EXT4_I(inode)->i_data);
275 size -= sizeof(struct ext4_extent_header);
276 size /= sizeof(struct ext4_extent);
277 #ifdef AGGRESSIVE_TEST
278 if (!check && size > 3)
279 size = 3;
280 #endif
281 return size;
284 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
286 int size;
288 size = sizeof(EXT4_I(inode)->i_data);
289 size -= sizeof(struct ext4_extent_header);
290 size /= sizeof(struct ext4_extent_idx);
291 #ifdef AGGRESSIVE_TEST
292 if (!check && size > 4)
293 size = 4;
294 #endif
295 return size;
298 static inline int
299 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
300 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
301 int nofail)
303 struct ext4_ext_path *path = *ppath;
304 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
306 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
307 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
308 EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
309 (nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
313 * Calculate the number of metadata blocks needed
314 * to allocate @blocks
315 * Worse case is one block per extent
317 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
319 struct ext4_inode_info *ei = EXT4_I(inode);
320 int idxs;
322 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
323 / sizeof(struct ext4_extent_idx));
326 * If the new delayed allocation block is contiguous with the
327 * previous da block, it can share index blocks with the
328 * previous block, so we only need to allocate a new index
329 * block every idxs leaf blocks. At ldxs**2 blocks, we need
330 * an additional index block, and at ldxs**3 blocks, yet
331 * another index blocks.
333 if (ei->i_da_metadata_calc_len &&
334 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
335 int num = 0;
337 if ((ei->i_da_metadata_calc_len % idxs) == 0)
338 num++;
339 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
340 num++;
341 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
342 num++;
343 ei->i_da_metadata_calc_len = 0;
344 } else
345 ei->i_da_metadata_calc_len++;
346 ei->i_da_metadata_calc_last_lblock++;
347 return num;
351 * In the worst case we need a new set of index blocks at
352 * every level of the inode's extent tree.
354 ei->i_da_metadata_calc_len = 1;
355 ei->i_da_metadata_calc_last_lblock = lblock;
356 return ext_depth(inode) + 1;
359 static int
360 ext4_ext_max_entries(struct inode *inode, int depth)
362 int max;
364 if (depth == ext_depth(inode)) {
365 if (depth == 0)
366 max = ext4_ext_space_root(inode, 1);
367 else
368 max = ext4_ext_space_root_idx(inode, 1);
369 } else {
370 if (depth == 0)
371 max = ext4_ext_space_block(inode, 1);
372 else
373 max = ext4_ext_space_block_idx(inode, 1);
376 return max;
379 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
381 ext4_fsblk_t block = ext4_ext_pblock(ext);
382 int len = ext4_ext_get_actual_len(ext);
383 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
386 * We allow neither:
387 * - zero length
388 * - overflow/wrap-around
390 if (lblock + len <= lblock)
391 return 0;
392 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
395 static int ext4_valid_extent_idx(struct inode *inode,
396 struct ext4_extent_idx *ext_idx)
398 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
400 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
403 static int ext4_valid_extent_entries(struct inode *inode,
404 struct ext4_extent_header *eh,
405 int depth)
407 unsigned short entries;
408 if (eh->eh_entries == 0)
409 return 1;
411 entries = le16_to_cpu(eh->eh_entries);
413 if (depth == 0) {
414 /* leaf entries */
415 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
416 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
417 ext4_fsblk_t pblock = 0;
418 ext4_lblk_t lblock = 0;
419 ext4_lblk_t prev = 0;
420 int len = 0;
421 while (entries) {
422 if (!ext4_valid_extent(inode, ext))
423 return 0;
425 /* Check for overlapping extents */
426 lblock = le32_to_cpu(ext->ee_block);
427 len = ext4_ext_get_actual_len(ext);
428 if ((lblock <= prev) && prev) {
429 pblock = ext4_ext_pblock(ext);
430 es->s_last_error_block = cpu_to_le64(pblock);
431 return 0;
433 ext++;
434 entries--;
435 prev = lblock + len - 1;
437 } else {
438 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
439 while (entries) {
440 if (!ext4_valid_extent_idx(inode, ext_idx))
441 return 0;
442 ext_idx++;
443 entries--;
446 return 1;
449 static int __ext4_ext_check(const char *function, unsigned int line,
450 struct inode *inode, struct ext4_extent_header *eh,
451 int depth, ext4_fsblk_t pblk)
453 const char *error_msg;
454 int max = 0, err = -EFSCORRUPTED;
456 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
457 error_msg = "invalid magic";
458 goto corrupted;
460 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
461 error_msg = "unexpected eh_depth";
462 goto corrupted;
464 if (unlikely(eh->eh_max == 0)) {
465 error_msg = "invalid eh_max";
466 goto corrupted;
468 max = ext4_ext_max_entries(inode, depth);
469 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
470 error_msg = "too large eh_max";
471 goto corrupted;
473 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
474 error_msg = "invalid eh_entries";
475 goto corrupted;
477 if (!ext4_valid_extent_entries(inode, eh, depth)) {
478 error_msg = "invalid extent entries";
479 goto corrupted;
481 if (unlikely(depth > 32)) {
482 error_msg = "too large eh_depth";
483 goto corrupted;
485 /* Verify checksum on non-root extent tree nodes */
486 if (ext_depth(inode) != depth &&
487 !ext4_extent_block_csum_verify(inode, eh)) {
488 error_msg = "extent tree corrupted";
489 err = -EFSBADCRC;
490 goto corrupted;
492 return 0;
494 corrupted:
495 ext4_error_inode(inode, function, line, 0,
496 "pblk %llu bad header/extent: %s - magic %x, "
497 "entries %u, max %u(%u), depth %u(%u)",
498 (unsigned long long) pblk, error_msg,
499 le16_to_cpu(eh->eh_magic),
500 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
501 max, le16_to_cpu(eh->eh_depth), depth);
502 return err;
505 #define ext4_ext_check(inode, eh, depth, pblk) \
506 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
508 int ext4_ext_check_inode(struct inode *inode)
510 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
513 static void ext4_cache_extents(struct inode *inode,
514 struct ext4_extent_header *eh)
516 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
517 ext4_lblk_t prev = 0;
518 int i;
520 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
521 unsigned int status = EXTENT_STATUS_WRITTEN;
522 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
523 int len = ext4_ext_get_actual_len(ex);
525 if (prev && (prev != lblk))
526 ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
527 EXTENT_STATUS_HOLE);
529 if (ext4_ext_is_unwritten(ex))
530 status = EXTENT_STATUS_UNWRITTEN;
531 ext4_es_cache_extent(inode, lblk, len,
532 ext4_ext_pblock(ex), status);
533 prev = lblk + len;
537 static struct buffer_head *
538 __read_extent_tree_block(const char *function, unsigned int line,
539 struct inode *inode, ext4_fsblk_t pblk, int depth,
540 int flags)
542 struct buffer_head *bh;
543 int err;
545 bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
546 if (unlikely(!bh))
547 return ERR_PTR(-ENOMEM);
549 if (!bh_uptodate_or_lock(bh)) {
550 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
551 err = bh_submit_read(bh);
552 if (err < 0)
553 goto errout;
555 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
556 return bh;
557 if (!ext4_has_feature_journal(inode->i_sb) ||
558 (inode->i_ino !=
559 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum))) {
560 err = __ext4_ext_check(function, line, inode,
561 ext_block_hdr(bh), depth, pblk);
562 if (err)
563 goto errout;
565 set_buffer_verified(bh);
567 * If this is a leaf block, cache all of its entries
569 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
570 struct ext4_extent_header *eh = ext_block_hdr(bh);
571 ext4_cache_extents(inode, eh);
573 return bh;
574 errout:
575 put_bh(bh);
576 return ERR_PTR(err);
580 #define read_extent_tree_block(inode, pblk, depth, flags) \
581 __read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
582 (depth), (flags))
585 * This function is called to cache a file's extent information in the
586 * extent status tree
588 int ext4_ext_precache(struct inode *inode)
590 struct ext4_inode_info *ei = EXT4_I(inode);
591 struct ext4_ext_path *path = NULL;
592 struct buffer_head *bh;
593 int i = 0, depth, ret = 0;
595 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
596 return 0; /* not an extent-mapped inode */
598 down_read(&ei->i_data_sem);
599 depth = ext_depth(inode);
601 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
602 GFP_NOFS);
603 if (path == NULL) {
604 up_read(&ei->i_data_sem);
605 return -ENOMEM;
608 /* Don't cache anything if there are no external extent blocks */
609 if (depth == 0)
610 goto out;
611 path[0].p_hdr = ext_inode_hdr(inode);
612 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
613 if (ret)
614 goto out;
615 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
616 while (i >= 0) {
618 * If this is a leaf block or we've reached the end of
619 * the index block, go up
621 if ((i == depth) ||
622 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
623 brelse(path[i].p_bh);
624 path[i].p_bh = NULL;
625 i--;
626 continue;
628 bh = read_extent_tree_block(inode,
629 ext4_idx_pblock(path[i].p_idx++),
630 depth - i - 1,
631 EXT4_EX_FORCE_CACHE);
632 if (IS_ERR(bh)) {
633 ret = PTR_ERR(bh);
634 break;
636 i++;
637 path[i].p_bh = bh;
638 path[i].p_hdr = ext_block_hdr(bh);
639 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
641 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
642 out:
643 up_read(&ei->i_data_sem);
644 ext4_ext_drop_refs(path);
645 kfree(path);
646 return ret;
649 #ifdef EXT_DEBUG
650 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
652 int k, l = path->p_depth;
654 ext_debug("path:");
655 for (k = 0; k <= l; k++, path++) {
656 if (path->p_idx) {
657 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
658 ext4_idx_pblock(path->p_idx));
659 } else if (path->p_ext) {
660 ext_debug(" %d:[%d]%d:%llu ",
661 le32_to_cpu(path->p_ext->ee_block),
662 ext4_ext_is_unwritten(path->p_ext),
663 ext4_ext_get_actual_len(path->p_ext),
664 ext4_ext_pblock(path->p_ext));
665 } else
666 ext_debug(" []");
668 ext_debug("\n");
671 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
673 int depth = ext_depth(inode);
674 struct ext4_extent_header *eh;
675 struct ext4_extent *ex;
676 int i;
678 if (!path)
679 return;
681 eh = path[depth].p_hdr;
682 ex = EXT_FIRST_EXTENT(eh);
684 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
686 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
687 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
688 ext4_ext_is_unwritten(ex),
689 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
691 ext_debug("\n");
694 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
695 ext4_fsblk_t newblock, int level)
697 int depth = ext_depth(inode);
698 struct ext4_extent *ex;
700 if (depth != level) {
701 struct ext4_extent_idx *idx;
702 idx = path[level].p_idx;
703 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
704 ext_debug("%d: move %d:%llu in new index %llu\n", level,
705 le32_to_cpu(idx->ei_block),
706 ext4_idx_pblock(idx),
707 newblock);
708 idx++;
711 return;
714 ex = path[depth].p_ext;
715 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
716 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
717 le32_to_cpu(ex->ee_block),
718 ext4_ext_pblock(ex),
719 ext4_ext_is_unwritten(ex),
720 ext4_ext_get_actual_len(ex),
721 newblock);
722 ex++;
726 #else
727 #define ext4_ext_show_path(inode, path)
728 #define ext4_ext_show_leaf(inode, path)
729 #define ext4_ext_show_move(inode, path, newblock, level)
730 #endif
732 void ext4_ext_drop_refs(struct ext4_ext_path *path)
734 int depth, i;
736 if (!path)
737 return;
738 depth = path->p_depth;
739 for (i = 0; i <= depth; i++, path++)
740 if (path->p_bh) {
741 brelse(path->p_bh);
742 path->p_bh = NULL;
747 * ext4_ext_binsearch_idx:
748 * binary search for the closest index of the given block
749 * the header must be checked before calling this
751 static void
752 ext4_ext_binsearch_idx(struct inode *inode,
753 struct ext4_ext_path *path, ext4_lblk_t block)
755 struct ext4_extent_header *eh = path->p_hdr;
756 struct ext4_extent_idx *r, *l, *m;
759 ext_debug("binsearch for %u(idx): ", block);
761 l = EXT_FIRST_INDEX(eh) + 1;
762 r = EXT_LAST_INDEX(eh);
763 while (l <= r) {
764 m = l + (r - l) / 2;
765 if (block < le32_to_cpu(m->ei_block))
766 r = m - 1;
767 else
768 l = m + 1;
769 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
770 m, le32_to_cpu(m->ei_block),
771 r, le32_to_cpu(r->ei_block));
774 path->p_idx = l - 1;
775 ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
776 ext4_idx_pblock(path->p_idx));
778 #ifdef CHECK_BINSEARCH
780 struct ext4_extent_idx *chix, *ix;
781 int k;
783 chix = ix = EXT_FIRST_INDEX(eh);
784 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
785 if (k != 0 &&
786 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
787 printk(KERN_DEBUG "k=%d, ix=0x%p, "
788 "first=0x%p\n", k,
789 ix, EXT_FIRST_INDEX(eh));
790 printk(KERN_DEBUG "%u <= %u\n",
791 le32_to_cpu(ix->ei_block),
792 le32_to_cpu(ix[-1].ei_block));
794 BUG_ON(k && le32_to_cpu(ix->ei_block)
795 <= le32_to_cpu(ix[-1].ei_block));
796 if (block < le32_to_cpu(ix->ei_block))
797 break;
798 chix = ix;
800 BUG_ON(chix != path->p_idx);
802 #endif
807 * ext4_ext_binsearch:
808 * binary search for closest extent of the given block
809 * the header must be checked before calling this
811 static void
812 ext4_ext_binsearch(struct inode *inode,
813 struct ext4_ext_path *path, ext4_lblk_t block)
815 struct ext4_extent_header *eh = path->p_hdr;
816 struct ext4_extent *r, *l, *m;
818 if (eh->eh_entries == 0) {
820 * this leaf is empty:
821 * we get such a leaf in split/add case
823 return;
826 ext_debug("binsearch for %u: ", block);
828 l = EXT_FIRST_EXTENT(eh) + 1;
829 r = EXT_LAST_EXTENT(eh);
831 while (l <= r) {
832 m = l + (r - l) / 2;
833 if (block < le32_to_cpu(m->ee_block))
834 r = m - 1;
835 else
836 l = m + 1;
837 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
838 m, le32_to_cpu(m->ee_block),
839 r, le32_to_cpu(r->ee_block));
842 path->p_ext = l - 1;
843 ext_debug(" -> %d:%llu:[%d]%d ",
844 le32_to_cpu(path->p_ext->ee_block),
845 ext4_ext_pblock(path->p_ext),
846 ext4_ext_is_unwritten(path->p_ext),
847 ext4_ext_get_actual_len(path->p_ext));
849 #ifdef CHECK_BINSEARCH
851 struct ext4_extent *chex, *ex;
852 int k;
854 chex = ex = EXT_FIRST_EXTENT(eh);
855 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
856 BUG_ON(k && le32_to_cpu(ex->ee_block)
857 <= le32_to_cpu(ex[-1].ee_block));
858 if (block < le32_to_cpu(ex->ee_block))
859 break;
860 chex = ex;
862 BUG_ON(chex != path->p_ext);
864 #endif
868 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
870 struct ext4_extent_header *eh;
872 eh = ext_inode_hdr(inode);
873 eh->eh_depth = 0;
874 eh->eh_entries = 0;
875 eh->eh_magic = EXT4_EXT_MAGIC;
876 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
877 ext4_mark_inode_dirty(handle, inode);
878 return 0;
881 struct ext4_ext_path *
882 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
883 struct ext4_ext_path **orig_path, int flags)
885 struct ext4_extent_header *eh;
886 struct buffer_head *bh;
887 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
888 short int depth, i, ppos = 0;
889 int ret;
891 eh = ext_inode_hdr(inode);
892 depth = ext_depth(inode);
893 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
894 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
895 depth);
896 ret = -EFSCORRUPTED;
897 goto err;
900 if (path) {
901 ext4_ext_drop_refs(path);
902 if (depth > path[0].p_maxdepth) {
903 kfree(path);
904 *orig_path = path = NULL;
907 if (!path) {
908 /* account possible depth increase */
909 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
910 GFP_NOFS);
911 if (unlikely(!path))
912 return ERR_PTR(-ENOMEM);
913 path[0].p_maxdepth = depth + 1;
915 path[0].p_hdr = eh;
916 path[0].p_bh = NULL;
918 i = depth;
919 if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
920 ext4_cache_extents(inode, eh);
921 /* walk through the tree */
922 while (i) {
923 ext_debug("depth %d: num %d, max %d\n",
924 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
926 ext4_ext_binsearch_idx(inode, path + ppos, block);
927 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
928 path[ppos].p_depth = i;
929 path[ppos].p_ext = NULL;
931 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
932 flags);
933 if (IS_ERR(bh)) {
934 ret = PTR_ERR(bh);
935 goto err;
938 eh = ext_block_hdr(bh);
939 ppos++;
940 path[ppos].p_bh = bh;
941 path[ppos].p_hdr = eh;
944 path[ppos].p_depth = i;
945 path[ppos].p_ext = NULL;
946 path[ppos].p_idx = NULL;
948 /* find extent */
949 ext4_ext_binsearch(inode, path + ppos, block);
950 /* if not an empty leaf */
951 if (path[ppos].p_ext)
952 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
954 ext4_ext_show_path(inode, path);
956 return path;
958 err:
959 ext4_ext_drop_refs(path);
960 kfree(path);
961 if (orig_path)
962 *orig_path = NULL;
963 return ERR_PTR(ret);
967 * ext4_ext_insert_index:
968 * insert new index [@logical;@ptr] into the block at @curp;
969 * check where to insert: before @curp or after @curp
971 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
972 struct ext4_ext_path *curp,
973 int logical, ext4_fsblk_t ptr)
975 struct ext4_extent_idx *ix;
976 int len, err;
978 err = ext4_ext_get_access(handle, inode, curp);
979 if (err)
980 return err;
982 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
983 EXT4_ERROR_INODE(inode,
984 "logical %d == ei_block %d!",
985 logical, le32_to_cpu(curp->p_idx->ei_block));
986 return -EFSCORRUPTED;
989 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
990 >= le16_to_cpu(curp->p_hdr->eh_max))) {
991 EXT4_ERROR_INODE(inode,
992 "eh_entries %d >= eh_max %d!",
993 le16_to_cpu(curp->p_hdr->eh_entries),
994 le16_to_cpu(curp->p_hdr->eh_max));
995 return -EFSCORRUPTED;
998 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
999 /* insert after */
1000 ext_debug("insert new index %d after: %llu\n", logical, ptr);
1001 ix = curp->p_idx + 1;
1002 } else {
1003 /* insert before */
1004 ext_debug("insert new index %d before: %llu\n", logical, ptr);
1005 ix = curp->p_idx;
1008 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1009 BUG_ON(len < 0);
1010 if (len > 0) {
1011 ext_debug("insert new index %d: "
1012 "move %d indices from 0x%p to 0x%p\n",
1013 logical, len, ix, ix + 1);
1014 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1017 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1018 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1019 return -EFSCORRUPTED;
1022 ix->ei_block = cpu_to_le32(logical);
1023 ext4_idx_store_pblock(ix, ptr);
1024 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1026 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1027 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1028 return -EFSCORRUPTED;
1031 err = ext4_ext_dirty(handle, inode, curp);
1032 ext4_std_error(inode->i_sb, err);
1034 return err;
1038 * ext4_ext_split:
1039 * inserts new subtree into the path, using free index entry
1040 * at depth @at:
1041 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1042 * - makes decision where to split
1043 * - moves remaining extents and index entries (right to the split point)
1044 * into the newly allocated blocks
1045 * - initializes subtree
1047 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1048 unsigned int flags,
1049 struct ext4_ext_path *path,
1050 struct ext4_extent *newext, int at)
1052 struct buffer_head *bh = NULL;
1053 int depth = ext_depth(inode);
1054 struct ext4_extent_header *neh;
1055 struct ext4_extent_idx *fidx;
1056 int i = at, k, m, a;
1057 ext4_fsblk_t newblock, oldblock;
1058 __le32 border;
1059 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1060 int err = 0;
1061 size_t ext_size = 0;
1063 /* make decision: where to split? */
1064 /* FIXME: now decision is simplest: at current extent */
1066 /* if current leaf will be split, then we should use
1067 * border from split point */
1068 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1069 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1070 return -EFSCORRUPTED;
1072 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1073 border = path[depth].p_ext[1].ee_block;
1074 ext_debug("leaf will be split."
1075 " next leaf starts at %d\n",
1076 le32_to_cpu(border));
1077 } else {
1078 border = newext->ee_block;
1079 ext_debug("leaf will be added."
1080 " next leaf starts at %d\n",
1081 le32_to_cpu(border));
1085 * If error occurs, then we break processing
1086 * and mark filesystem read-only. index won't
1087 * be inserted and tree will be in consistent
1088 * state. Next mount will repair buffers too.
1092 * Get array to track all allocated blocks.
1093 * We need this to handle errors and free blocks
1094 * upon them.
1096 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
1097 if (!ablocks)
1098 return -ENOMEM;
1100 /* allocate all needed blocks */
1101 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1102 for (a = 0; a < depth - at; a++) {
1103 newblock = ext4_ext_new_meta_block(handle, inode, path,
1104 newext, &err, flags);
1105 if (newblock == 0)
1106 goto cleanup;
1107 ablocks[a] = newblock;
1110 /* initialize new leaf */
1111 newblock = ablocks[--a];
1112 if (unlikely(newblock == 0)) {
1113 EXT4_ERROR_INODE(inode, "newblock == 0!");
1114 err = -EFSCORRUPTED;
1115 goto cleanup;
1117 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1118 if (unlikely(!bh)) {
1119 err = -ENOMEM;
1120 goto cleanup;
1122 lock_buffer(bh);
1124 err = ext4_journal_get_create_access(handle, bh);
1125 if (err)
1126 goto cleanup;
1128 neh = ext_block_hdr(bh);
1129 neh->eh_entries = 0;
1130 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1131 neh->eh_magic = EXT4_EXT_MAGIC;
1132 neh->eh_depth = 0;
1134 /* move remainder of path[depth] to the new leaf */
1135 if (unlikely(path[depth].p_hdr->eh_entries !=
1136 path[depth].p_hdr->eh_max)) {
1137 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1138 path[depth].p_hdr->eh_entries,
1139 path[depth].p_hdr->eh_max);
1140 err = -EFSCORRUPTED;
1141 goto cleanup;
1143 /* start copy from next extent */
1144 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1145 ext4_ext_show_move(inode, path, newblock, depth);
1146 if (m) {
1147 struct ext4_extent *ex;
1148 ex = EXT_FIRST_EXTENT(neh);
1149 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1150 le16_add_cpu(&neh->eh_entries, m);
1153 /* zero out unused area in the extent block */
1154 ext_size = sizeof(struct ext4_extent_header) +
1155 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1156 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1157 ext4_extent_block_csum_set(inode, neh);
1158 set_buffer_uptodate(bh);
1159 unlock_buffer(bh);
1161 err = ext4_handle_dirty_metadata(handle, inode, bh);
1162 if (err)
1163 goto cleanup;
1164 brelse(bh);
1165 bh = NULL;
1167 /* correct old leaf */
1168 if (m) {
1169 err = ext4_ext_get_access(handle, inode, path + depth);
1170 if (err)
1171 goto cleanup;
1172 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1173 err = ext4_ext_dirty(handle, inode, path + depth);
1174 if (err)
1175 goto cleanup;
1179 /* create intermediate indexes */
1180 k = depth - at - 1;
1181 if (unlikely(k < 0)) {
1182 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1183 err = -EFSCORRUPTED;
1184 goto cleanup;
1186 if (k)
1187 ext_debug("create %d intermediate indices\n", k);
1188 /* insert new index into current index block */
1189 /* current depth stored in i var */
1190 i = depth - 1;
1191 while (k--) {
1192 oldblock = newblock;
1193 newblock = ablocks[--a];
1194 bh = sb_getblk(inode->i_sb, newblock);
1195 if (unlikely(!bh)) {
1196 err = -ENOMEM;
1197 goto cleanup;
1199 lock_buffer(bh);
1201 err = ext4_journal_get_create_access(handle, bh);
1202 if (err)
1203 goto cleanup;
1205 neh = ext_block_hdr(bh);
1206 neh->eh_entries = cpu_to_le16(1);
1207 neh->eh_magic = EXT4_EXT_MAGIC;
1208 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1209 neh->eh_depth = cpu_to_le16(depth - i);
1210 fidx = EXT_FIRST_INDEX(neh);
1211 fidx->ei_block = border;
1212 ext4_idx_store_pblock(fidx, oldblock);
1214 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1215 i, newblock, le32_to_cpu(border), oldblock);
1217 /* move remainder of path[i] to the new index block */
1218 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1219 EXT_LAST_INDEX(path[i].p_hdr))) {
1220 EXT4_ERROR_INODE(inode,
1221 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1222 le32_to_cpu(path[i].p_ext->ee_block));
1223 err = -EFSCORRUPTED;
1224 goto cleanup;
1226 /* start copy indexes */
1227 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1228 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1229 EXT_MAX_INDEX(path[i].p_hdr));
1230 ext4_ext_show_move(inode, path, newblock, i);
1231 if (m) {
1232 memmove(++fidx, path[i].p_idx,
1233 sizeof(struct ext4_extent_idx) * m);
1234 le16_add_cpu(&neh->eh_entries, m);
1236 /* zero out unused area in the extent block */
1237 ext_size = sizeof(struct ext4_extent_header) +
1238 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1239 memset(bh->b_data + ext_size, 0,
1240 inode->i_sb->s_blocksize - ext_size);
1241 ext4_extent_block_csum_set(inode, neh);
1242 set_buffer_uptodate(bh);
1243 unlock_buffer(bh);
1245 err = ext4_handle_dirty_metadata(handle, inode, bh);
1246 if (err)
1247 goto cleanup;
1248 brelse(bh);
1249 bh = NULL;
1251 /* correct old index */
1252 if (m) {
1253 err = ext4_ext_get_access(handle, inode, path + i);
1254 if (err)
1255 goto cleanup;
1256 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1257 err = ext4_ext_dirty(handle, inode, path + i);
1258 if (err)
1259 goto cleanup;
1262 i--;
1265 /* insert new index */
1266 err = ext4_ext_insert_index(handle, inode, path + at,
1267 le32_to_cpu(border), newblock);
1269 cleanup:
1270 if (bh) {
1271 if (buffer_locked(bh))
1272 unlock_buffer(bh);
1273 brelse(bh);
1276 if (err) {
1277 /* free all allocated blocks in error case */
1278 for (i = 0; i < depth; i++) {
1279 if (!ablocks[i])
1280 continue;
1281 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1282 EXT4_FREE_BLOCKS_METADATA);
1285 kfree(ablocks);
1287 return err;
1291 * ext4_ext_grow_indepth:
1292 * implements tree growing procedure:
1293 * - allocates new block
1294 * - moves top-level data (index block or leaf) into the new block
1295 * - initializes new top-level, creating index that points to the
1296 * just created block
1298 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1299 unsigned int flags)
1301 struct ext4_extent_header *neh;
1302 struct buffer_head *bh;
1303 ext4_fsblk_t newblock, goal = 0;
1304 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1305 int err = 0;
1306 size_t ext_size = 0;
1308 /* Try to prepend new index to old one */
1309 if (ext_depth(inode))
1310 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1311 if (goal > le32_to_cpu(es->s_first_data_block)) {
1312 flags |= EXT4_MB_HINT_TRY_GOAL;
1313 goal--;
1314 } else
1315 goal = ext4_inode_to_goal_block(inode);
1316 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1317 NULL, &err);
1318 if (newblock == 0)
1319 return err;
1321 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1322 if (unlikely(!bh))
1323 return -ENOMEM;
1324 lock_buffer(bh);
1326 err = ext4_journal_get_create_access(handle, bh);
1327 if (err) {
1328 unlock_buffer(bh);
1329 goto out;
1332 ext_size = sizeof(EXT4_I(inode)->i_data);
1333 /* move top-level index/leaf into new block */
1334 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1335 /* zero out unused area in the extent block */
1336 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1338 /* set size of new block */
1339 neh = ext_block_hdr(bh);
1340 /* old root could have indexes or leaves
1341 * so calculate e_max right way */
1342 if (ext_depth(inode))
1343 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1344 else
1345 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1346 neh->eh_magic = EXT4_EXT_MAGIC;
1347 ext4_extent_block_csum_set(inode, neh);
1348 set_buffer_uptodate(bh);
1349 unlock_buffer(bh);
1351 err = ext4_handle_dirty_metadata(handle, inode, bh);
1352 if (err)
1353 goto out;
1355 /* Update top-level index: num,max,pointer */
1356 neh = ext_inode_hdr(inode);
1357 neh->eh_entries = cpu_to_le16(1);
1358 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1359 if (neh->eh_depth == 0) {
1360 /* Root extent block becomes index block */
1361 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1362 EXT_FIRST_INDEX(neh)->ei_block =
1363 EXT_FIRST_EXTENT(neh)->ee_block;
1365 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1366 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1367 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1368 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1370 le16_add_cpu(&neh->eh_depth, 1);
1371 ext4_mark_inode_dirty(handle, inode);
1372 out:
1373 brelse(bh);
1375 return err;
1379 * ext4_ext_create_new_leaf:
1380 * finds empty index and adds new leaf.
1381 * if no free index is found, then it requests in-depth growing.
1383 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1384 unsigned int mb_flags,
1385 unsigned int gb_flags,
1386 struct ext4_ext_path **ppath,
1387 struct ext4_extent *newext)
1389 struct ext4_ext_path *path = *ppath;
1390 struct ext4_ext_path *curp;
1391 int depth, i, err = 0;
1393 repeat:
1394 i = depth = ext_depth(inode);
1396 /* walk up to the tree and look for free index entry */
1397 curp = path + depth;
1398 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1399 i--;
1400 curp--;
1403 /* we use already allocated block for index block,
1404 * so subsequent data blocks should be contiguous */
1405 if (EXT_HAS_FREE_INDEX(curp)) {
1406 /* if we found index with free entry, then use that
1407 * entry: create all needed subtree and add new leaf */
1408 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1409 if (err)
1410 goto out;
1412 /* refill path */
1413 path = ext4_find_extent(inode,
1414 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1415 ppath, gb_flags);
1416 if (IS_ERR(path))
1417 err = PTR_ERR(path);
1418 } else {
1419 /* tree is full, time to grow in depth */
1420 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1421 if (err)
1422 goto out;
1424 /* refill path */
1425 path = ext4_find_extent(inode,
1426 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1427 ppath, gb_flags);
1428 if (IS_ERR(path)) {
1429 err = PTR_ERR(path);
1430 goto out;
1434 * only first (depth 0 -> 1) produces free space;
1435 * in all other cases we have to split the grown tree
1437 depth = ext_depth(inode);
1438 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1439 /* now we need to split */
1440 goto repeat;
1444 out:
1445 return err;
1449 * search the closest allocated block to the left for *logical
1450 * and returns it at @logical + it's physical address at @phys
1451 * if *logical is the smallest allocated block, the function
1452 * returns 0 at @phys
1453 * return value contains 0 (success) or error code
1455 static int ext4_ext_search_left(struct inode *inode,
1456 struct ext4_ext_path *path,
1457 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1459 struct ext4_extent_idx *ix;
1460 struct ext4_extent *ex;
1461 int depth, ee_len;
1463 if (unlikely(path == NULL)) {
1464 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1465 return -EFSCORRUPTED;
1467 depth = path->p_depth;
1468 *phys = 0;
1470 if (depth == 0 && path->p_ext == NULL)
1471 return 0;
1473 /* usually extent in the path covers blocks smaller
1474 * then *logical, but it can be that extent is the
1475 * first one in the file */
1477 ex = path[depth].p_ext;
1478 ee_len = ext4_ext_get_actual_len(ex);
1479 if (*logical < le32_to_cpu(ex->ee_block)) {
1480 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1481 EXT4_ERROR_INODE(inode,
1482 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1483 *logical, le32_to_cpu(ex->ee_block));
1484 return -EFSCORRUPTED;
1486 while (--depth >= 0) {
1487 ix = path[depth].p_idx;
1488 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1489 EXT4_ERROR_INODE(inode,
1490 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1491 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1492 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1493 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1494 depth);
1495 return -EFSCORRUPTED;
1498 return 0;
1501 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1502 EXT4_ERROR_INODE(inode,
1503 "logical %d < ee_block %d + ee_len %d!",
1504 *logical, le32_to_cpu(ex->ee_block), ee_len);
1505 return -EFSCORRUPTED;
1508 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1509 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1510 return 0;
1514 * search the closest allocated block to the right for *logical
1515 * and returns it at @logical + it's physical address at @phys
1516 * if *logical is the largest allocated block, the function
1517 * returns 0 at @phys
1518 * return value contains 0 (success) or error code
1520 static int ext4_ext_search_right(struct inode *inode,
1521 struct ext4_ext_path *path,
1522 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1523 struct ext4_extent **ret_ex)
1525 struct buffer_head *bh = NULL;
1526 struct ext4_extent_header *eh;
1527 struct ext4_extent_idx *ix;
1528 struct ext4_extent *ex;
1529 ext4_fsblk_t block;
1530 int depth; /* Note, NOT eh_depth; depth from top of tree */
1531 int ee_len;
1533 if (unlikely(path == NULL)) {
1534 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1535 return -EFSCORRUPTED;
1537 depth = path->p_depth;
1538 *phys = 0;
1540 if (depth == 0 && path->p_ext == NULL)
1541 return 0;
1543 /* usually extent in the path covers blocks smaller
1544 * then *logical, but it can be that extent is the
1545 * first one in the file */
1547 ex = path[depth].p_ext;
1548 ee_len = ext4_ext_get_actual_len(ex);
1549 if (*logical < le32_to_cpu(ex->ee_block)) {
1550 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1551 EXT4_ERROR_INODE(inode,
1552 "first_extent(path[%d].p_hdr) != ex",
1553 depth);
1554 return -EFSCORRUPTED;
1556 while (--depth >= 0) {
1557 ix = path[depth].p_idx;
1558 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1559 EXT4_ERROR_INODE(inode,
1560 "ix != EXT_FIRST_INDEX *logical %d!",
1561 *logical);
1562 return -EFSCORRUPTED;
1565 goto found_extent;
1568 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1569 EXT4_ERROR_INODE(inode,
1570 "logical %d < ee_block %d + ee_len %d!",
1571 *logical, le32_to_cpu(ex->ee_block), ee_len);
1572 return -EFSCORRUPTED;
1575 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1576 /* next allocated block in this leaf */
1577 ex++;
1578 goto found_extent;
1581 /* go up and search for index to the right */
1582 while (--depth >= 0) {
1583 ix = path[depth].p_idx;
1584 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1585 goto got_index;
1588 /* we've gone up to the root and found no index to the right */
1589 return 0;
1591 got_index:
1592 /* we've found index to the right, let's
1593 * follow it and find the closest allocated
1594 * block to the right */
1595 ix++;
1596 block = ext4_idx_pblock(ix);
1597 while (++depth < path->p_depth) {
1598 /* subtract from p_depth to get proper eh_depth */
1599 bh = read_extent_tree_block(inode, block,
1600 path->p_depth - depth, 0);
1601 if (IS_ERR(bh))
1602 return PTR_ERR(bh);
1603 eh = ext_block_hdr(bh);
1604 ix = EXT_FIRST_INDEX(eh);
1605 block = ext4_idx_pblock(ix);
1606 put_bh(bh);
1609 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1610 if (IS_ERR(bh))
1611 return PTR_ERR(bh);
1612 eh = ext_block_hdr(bh);
1613 ex = EXT_FIRST_EXTENT(eh);
1614 found_extent:
1615 *logical = le32_to_cpu(ex->ee_block);
1616 *phys = ext4_ext_pblock(ex);
1617 *ret_ex = ex;
1618 if (bh)
1619 put_bh(bh);
1620 return 0;
1624 * ext4_ext_next_allocated_block:
1625 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1626 * NOTE: it considers block number from index entry as
1627 * allocated block. Thus, index entries have to be consistent
1628 * with leaves.
1630 ext4_lblk_t
1631 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1633 int depth;
1635 BUG_ON(path == NULL);
1636 depth = path->p_depth;
1638 if (depth == 0 && path->p_ext == NULL)
1639 return EXT_MAX_BLOCKS;
1641 while (depth >= 0) {
1642 if (depth == path->p_depth) {
1643 /* leaf */
1644 if (path[depth].p_ext &&
1645 path[depth].p_ext !=
1646 EXT_LAST_EXTENT(path[depth].p_hdr))
1647 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1648 } else {
1649 /* index */
1650 if (path[depth].p_idx !=
1651 EXT_LAST_INDEX(path[depth].p_hdr))
1652 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1654 depth--;
1657 return EXT_MAX_BLOCKS;
1661 * ext4_ext_next_leaf_block:
1662 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1664 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1666 int depth;
1668 BUG_ON(path == NULL);
1669 depth = path->p_depth;
1671 /* zero-tree has no leaf blocks at all */
1672 if (depth == 0)
1673 return EXT_MAX_BLOCKS;
1675 /* go to index block */
1676 depth--;
1678 while (depth >= 0) {
1679 if (path[depth].p_idx !=
1680 EXT_LAST_INDEX(path[depth].p_hdr))
1681 return (ext4_lblk_t)
1682 le32_to_cpu(path[depth].p_idx[1].ei_block);
1683 depth--;
1686 return EXT_MAX_BLOCKS;
1690 * ext4_ext_correct_indexes:
1691 * if leaf gets modified and modified extent is first in the leaf,
1692 * then we have to correct all indexes above.
1693 * TODO: do we need to correct tree in all cases?
1695 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1696 struct ext4_ext_path *path)
1698 struct ext4_extent_header *eh;
1699 int depth = ext_depth(inode);
1700 struct ext4_extent *ex;
1701 __le32 border;
1702 int k, err = 0;
1704 eh = path[depth].p_hdr;
1705 ex = path[depth].p_ext;
1707 if (unlikely(ex == NULL || eh == NULL)) {
1708 EXT4_ERROR_INODE(inode,
1709 "ex %p == NULL or eh %p == NULL", ex, eh);
1710 return -EFSCORRUPTED;
1713 if (depth == 0) {
1714 /* there is no tree at all */
1715 return 0;
1718 if (ex != EXT_FIRST_EXTENT(eh)) {
1719 /* we correct tree if first leaf got modified only */
1720 return 0;
1724 * TODO: we need correction if border is smaller than current one
1726 k = depth - 1;
1727 border = path[depth].p_ext->ee_block;
1728 err = ext4_ext_get_access(handle, inode, path + k);
1729 if (err)
1730 return err;
1731 path[k].p_idx->ei_block = border;
1732 err = ext4_ext_dirty(handle, inode, path + k);
1733 if (err)
1734 return err;
1736 while (k--) {
1737 /* change all left-side indexes */
1738 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1739 break;
1740 err = ext4_ext_get_access(handle, inode, path + k);
1741 if (err)
1742 break;
1743 path[k].p_idx->ei_block = border;
1744 err = ext4_ext_dirty(handle, inode, path + k);
1745 if (err)
1746 break;
1749 return err;
1753 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1754 struct ext4_extent *ex2)
1756 unsigned short ext1_ee_len, ext2_ee_len;
1758 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1759 return 0;
1761 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1762 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1764 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1765 le32_to_cpu(ex2->ee_block))
1766 return 0;
1769 * To allow future support for preallocated extents to be added
1770 * as an RO_COMPAT feature, refuse to merge to extents if
1771 * this can result in the top bit of ee_len being set.
1773 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1774 return 0;
1776 * The check for IO to unwritten extent is somewhat racy as we
1777 * increment i_unwritten / set EXT4_STATE_DIO_UNWRITTEN only after
1778 * dropping i_data_sem. But reserved blocks should save us in that
1779 * case.
1781 if (ext4_ext_is_unwritten(ex1) &&
1782 (ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
1783 atomic_read(&EXT4_I(inode)->i_unwritten) ||
1784 (ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
1785 return 0;
1786 #ifdef AGGRESSIVE_TEST
1787 if (ext1_ee_len >= 4)
1788 return 0;
1789 #endif
1791 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1792 return 1;
1793 return 0;
1797 * This function tries to merge the "ex" extent to the next extent in the tree.
1798 * It always tries to merge towards right. If you want to merge towards
1799 * left, pass "ex - 1" as argument instead of "ex".
1800 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1801 * 1 if they got merged.
1803 static int ext4_ext_try_to_merge_right(struct inode *inode,
1804 struct ext4_ext_path *path,
1805 struct ext4_extent *ex)
1807 struct ext4_extent_header *eh;
1808 unsigned int depth, len;
1809 int merge_done = 0, unwritten;
1811 depth = ext_depth(inode);
1812 BUG_ON(path[depth].p_hdr == NULL);
1813 eh = path[depth].p_hdr;
1815 while (ex < EXT_LAST_EXTENT(eh)) {
1816 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1817 break;
1818 /* merge with next extent! */
1819 unwritten = ext4_ext_is_unwritten(ex);
1820 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1821 + ext4_ext_get_actual_len(ex + 1));
1822 if (unwritten)
1823 ext4_ext_mark_unwritten(ex);
1825 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1826 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1827 * sizeof(struct ext4_extent);
1828 memmove(ex + 1, ex + 2, len);
1830 le16_add_cpu(&eh->eh_entries, -1);
1831 merge_done = 1;
1832 WARN_ON(eh->eh_entries == 0);
1833 if (!eh->eh_entries)
1834 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1837 return merge_done;
1841 * This function does a very simple check to see if we can collapse
1842 * an extent tree with a single extent tree leaf block into the inode.
1844 static void ext4_ext_try_to_merge_up(handle_t *handle,
1845 struct inode *inode,
1846 struct ext4_ext_path *path)
1848 size_t s;
1849 unsigned max_root = ext4_ext_space_root(inode, 0);
1850 ext4_fsblk_t blk;
1852 if ((path[0].p_depth != 1) ||
1853 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1854 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1855 return;
1858 * We need to modify the block allocation bitmap and the block
1859 * group descriptor to release the extent tree block. If we
1860 * can't get the journal credits, give up.
1862 if (ext4_journal_extend(handle, 2))
1863 return;
1866 * Copy the extent data up to the inode
1868 blk = ext4_idx_pblock(path[0].p_idx);
1869 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1870 sizeof(struct ext4_extent_idx);
1871 s += sizeof(struct ext4_extent_header);
1873 path[1].p_maxdepth = path[0].p_maxdepth;
1874 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1875 path[0].p_depth = 0;
1876 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1877 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1878 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1880 brelse(path[1].p_bh);
1881 ext4_free_blocks(handle, inode, NULL, blk, 1,
1882 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1886 * This function tries to merge the @ex extent to neighbours in the tree.
1887 * return 1 if merge left else 0.
1889 static void ext4_ext_try_to_merge(handle_t *handle,
1890 struct inode *inode,
1891 struct ext4_ext_path *path,
1892 struct ext4_extent *ex) {
1893 struct ext4_extent_header *eh;
1894 unsigned int depth;
1895 int merge_done = 0;
1897 depth = ext_depth(inode);
1898 BUG_ON(path[depth].p_hdr == NULL);
1899 eh = path[depth].p_hdr;
1901 if (ex > EXT_FIRST_EXTENT(eh))
1902 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1904 if (!merge_done)
1905 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1907 ext4_ext_try_to_merge_up(handle, inode, path);
1911 * check if a portion of the "newext" extent overlaps with an
1912 * existing extent.
1914 * If there is an overlap discovered, it updates the length of the newext
1915 * such that there will be no overlap, and then returns 1.
1916 * If there is no overlap found, it returns 0.
1918 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1919 struct inode *inode,
1920 struct ext4_extent *newext,
1921 struct ext4_ext_path *path)
1923 ext4_lblk_t b1, b2;
1924 unsigned int depth, len1;
1925 unsigned int ret = 0;
1927 b1 = le32_to_cpu(newext->ee_block);
1928 len1 = ext4_ext_get_actual_len(newext);
1929 depth = ext_depth(inode);
1930 if (!path[depth].p_ext)
1931 goto out;
1932 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1935 * get the next allocated block if the extent in the path
1936 * is before the requested block(s)
1938 if (b2 < b1) {
1939 b2 = ext4_ext_next_allocated_block(path);
1940 if (b2 == EXT_MAX_BLOCKS)
1941 goto out;
1942 b2 = EXT4_LBLK_CMASK(sbi, b2);
1945 /* check for wrap through zero on extent logical start block*/
1946 if (b1 + len1 < b1) {
1947 len1 = EXT_MAX_BLOCKS - b1;
1948 newext->ee_len = cpu_to_le16(len1);
1949 ret = 1;
1952 /* check for overlap */
1953 if (b1 + len1 > b2) {
1954 newext->ee_len = cpu_to_le16(b2 - b1);
1955 ret = 1;
1957 out:
1958 return ret;
1962 * ext4_ext_insert_extent:
1963 * tries to merge requsted extent into the existing extent or
1964 * inserts requested extent as new one into the tree,
1965 * creating new leaf in the no-space case.
1967 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1968 struct ext4_ext_path **ppath,
1969 struct ext4_extent *newext, int gb_flags)
1971 struct ext4_ext_path *path = *ppath;
1972 struct ext4_extent_header *eh;
1973 struct ext4_extent *ex, *fex;
1974 struct ext4_extent *nearex; /* nearest extent */
1975 struct ext4_ext_path *npath = NULL;
1976 int depth, len, err;
1977 ext4_lblk_t next;
1978 int mb_flags = 0, unwritten;
1980 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1981 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1982 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1983 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1984 return -EFSCORRUPTED;
1986 depth = ext_depth(inode);
1987 ex = path[depth].p_ext;
1988 eh = path[depth].p_hdr;
1989 if (unlikely(path[depth].p_hdr == NULL)) {
1990 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1991 return -EFSCORRUPTED;
1994 /* try to insert block into found extent and return */
1995 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1998 * Try to see whether we should rather test the extent on
1999 * right from ex, or from the left of ex. This is because
2000 * ext4_find_extent() can return either extent on the
2001 * left, or on the right from the searched position. This
2002 * will make merging more effective.
2004 if (ex < EXT_LAST_EXTENT(eh) &&
2005 (le32_to_cpu(ex->ee_block) +
2006 ext4_ext_get_actual_len(ex) <
2007 le32_to_cpu(newext->ee_block))) {
2008 ex += 1;
2009 goto prepend;
2010 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
2011 (le32_to_cpu(newext->ee_block) +
2012 ext4_ext_get_actual_len(newext) <
2013 le32_to_cpu(ex->ee_block)))
2014 ex -= 1;
2016 /* Try to append newex to the ex */
2017 if (ext4_can_extents_be_merged(inode, ex, newext)) {
2018 ext_debug("append [%d]%d block to %u:[%d]%d"
2019 "(from %llu)\n",
2020 ext4_ext_is_unwritten(newext),
2021 ext4_ext_get_actual_len(newext),
2022 le32_to_cpu(ex->ee_block),
2023 ext4_ext_is_unwritten(ex),
2024 ext4_ext_get_actual_len(ex),
2025 ext4_ext_pblock(ex));
2026 err = ext4_ext_get_access(handle, inode,
2027 path + depth);
2028 if (err)
2029 return err;
2030 unwritten = ext4_ext_is_unwritten(ex);
2031 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2032 + ext4_ext_get_actual_len(newext));
2033 if (unwritten)
2034 ext4_ext_mark_unwritten(ex);
2035 eh = path[depth].p_hdr;
2036 nearex = ex;
2037 goto merge;
2040 prepend:
2041 /* Try to prepend newex to the ex */
2042 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2043 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2044 "(from %llu)\n",
2045 le32_to_cpu(newext->ee_block),
2046 ext4_ext_is_unwritten(newext),
2047 ext4_ext_get_actual_len(newext),
2048 le32_to_cpu(ex->ee_block),
2049 ext4_ext_is_unwritten(ex),
2050 ext4_ext_get_actual_len(ex),
2051 ext4_ext_pblock(ex));
2052 err = ext4_ext_get_access(handle, inode,
2053 path + depth);
2054 if (err)
2055 return err;
2057 unwritten = ext4_ext_is_unwritten(ex);
2058 ex->ee_block = newext->ee_block;
2059 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2060 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2061 + ext4_ext_get_actual_len(newext));
2062 if (unwritten)
2063 ext4_ext_mark_unwritten(ex);
2064 eh = path[depth].p_hdr;
2065 nearex = ex;
2066 goto merge;
2070 depth = ext_depth(inode);
2071 eh = path[depth].p_hdr;
2072 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2073 goto has_space;
2075 /* probably next leaf has space for us? */
2076 fex = EXT_LAST_EXTENT(eh);
2077 next = EXT_MAX_BLOCKS;
2078 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2079 next = ext4_ext_next_leaf_block(path);
2080 if (next != EXT_MAX_BLOCKS) {
2081 ext_debug("next leaf block - %u\n", next);
2082 BUG_ON(npath != NULL);
2083 npath = ext4_find_extent(inode, next, NULL, 0);
2084 if (IS_ERR(npath))
2085 return PTR_ERR(npath);
2086 BUG_ON(npath->p_depth != path->p_depth);
2087 eh = npath[depth].p_hdr;
2088 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2089 ext_debug("next leaf isn't full(%d)\n",
2090 le16_to_cpu(eh->eh_entries));
2091 path = npath;
2092 goto has_space;
2094 ext_debug("next leaf has no free space(%d,%d)\n",
2095 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2099 * There is no free space in the found leaf.
2100 * We're gonna add a new leaf in the tree.
2102 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2103 mb_flags |= EXT4_MB_USE_RESERVED;
2104 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2105 ppath, newext);
2106 if (err)
2107 goto cleanup;
2108 depth = ext_depth(inode);
2109 eh = path[depth].p_hdr;
2111 has_space:
2112 nearex = path[depth].p_ext;
2114 err = ext4_ext_get_access(handle, inode, path + depth);
2115 if (err)
2116 goto cleanup;
2118 if (!nearex) {
2119 /* there is no extent in this leaf, create first one */
2120 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
2121 le32_to_cpu(newext->ee_block),
2122 ext4_ext_pblock(newext),
2123 ext4_ext_is_unwritten(newext),
2124 ext4_ext_get_actual_len(newext));
2125 nearex = EXT_FIRST_EXTENT(eh);
2126 } else {
2127 if (le32_to_cpu(newext->ee_block)
2128 > le32_to_cpu(nearex->ee_block)) {
2129 /* Insert after */
2130 ext_debug("insert %u:%llu:[%d]%d before: "
2131 "nearest %p\n",
2132 le32_to_cpu(newext->ee_block),
2133 ext4_ext_pblock(newext),
2134 ext4_ext_is_unwritten(newext),
2135 ext4_ext_get_actual_len(newext),
2136 nearex);
2137 nearex++;
2138 } else {
2139 /* Insert before */
2140 BUG_ON(newext->ee_block == nearex->ee_block);
2141 ext_debug("insert %u:%llu:[%d]%d after: "
2142 "nearest %p\n",
2143 le32_to_cpu(newext->ee_block),
2144 ext4_ext_pblock(newext),
2145 ext4_ext_is_unwritten(newext),
2146 ext4_ext_get_actual_len(newext),
2147 nearex);
2149 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2150 if (len > 0) {
2151 ext_debug("insert %u:%llu:[%d]%d: "
2152 "move %d extents from 0x%p to 0x%p\n",
2153 le32_to_cpu(newext->ee_block),
2154 ext4_ext_pblock(newext),
2155 ext4_ext_is_unwritten(newext),
2156 ext4_ext_get_actual_len(newext),
2157 len, nearex, nearex + 1);
2158 memmove(nearex + 1, nearex,
2159 len * sizeof(struct ext4_extent));
2163 le16_add_cpu(&eh->eh_entries, 1);
2164 path[depth].p_ext = nearex;
2165 nearex->ee_block = newext->ee_block;
2166 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2167 nearex->ee_len = newext->ee_len;
2169 merge:
2170 /* try to merge extents */
2171 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2172 ext4_ext_try_to_merge(handle, inode, path, nearex);
2175 /* time to correct all indexes above */
2176 err = ext4_ext_correct_indexes(handle, inode, path);
2177 if (err)
2178 goto cleanup;
2180 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2182 cleanup:
2183 ext4_ext_drop_refs(npath);
2184 kfree(npath);
2185 return err;
2188 static int ext4_fill_fiemap_extents(struct inode *inode,
2189 ext4_lblk_t block, ext4_lblk_t num,
2190 struct fiemap_extent_info *fieinfo)
2192 struct ext4_ext_path *path = NULL;
2193 struct ext4_extent *ex;
2194 struct extent_status es;
2195 ext4_lblk_t next, next_del, start = 0, end = 0;
2196 ext4_lblk_t last = block + num;
2197 int exists, depth = 0, err = 0;
2198 unsigned int flags = 0;
2199 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2201 while (block < last && block != EXT_MAX_BLOCKS) {
2202 num = last - block;
2203 /* find extent for this block */
2204 down_read(&EXT4_I(inode)->i_data_sem);
2206 path = ext4_find_extent(inode, block, &path, 0);
2207 if (IS_ERR(path)) {
2208 up_read(&EXT4_I(inode)->i_data_sem);
2209 err = PTR_ERR(path);
2210 path = NULL;
2211 break;
2214 depth = ext_depth(inode);
2215 if (unlikely(path[depth].p_hdr == NULL)) {
2216 up_read(&EXT4_I(inode)->i_data_sem);
2217 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2218 err = -EFSCORRUPTED;
2219 break;
2221 ex = path[depth].p_ext;
2222 next = ext4_ext_next_allocated_block(path);
2224 flags = 0;
2225 exists = 0;
2226 if (!ex) {
2227 /* there is no extent yet, so try to allocate
2228 * all requested space */
2229 start = block;
2230 end = block + num;
2231 } else if (le32_to_cpu(ex->ee_block) > block) {
2232 /* need to allocate space before found extent */
2233 start = block;
2234 end = le32_to_cpu(ex->ee_block);
2235 if (block + num < end)
2236 end = block + num;
2237 } else if (block >= le32_to_cpu(ex->ee_block)
2238 + ext4_ext_get_actual_len(ex)) {
2239 /* need to allocate space after found extent */
2240 start = block;
2241 end = block + num;
2242 if (end >= next)
2243 end = next;
2244 } else if (block >= le32_to_cpu(ex->ee_block)) {
2246 * some part of requested space is covered
2247 * by found extent
2249 start = block;
2250 end = le32_to_cpu(ex->ee_block)
2251 + ext4_ext_get_actual_len(ex);
2252 if (block + num < end)
2253 end = block + num;
2254 exists = 1;
2255 } else {
2256 BUG();
2258 BUG_ON(end <= start);
2260 if (!exists) {
2261 es.es_lblk = start;
2262 es.es_len = end - start;
2263 es.es_pblk = 0;
2264 } else {
2265 es.es_lblk = le32_to_cpu(ex->ee_block);
2266 es.es_len = ext4_ext_get_actual_len(ex);
2267 es.es_pblk = ext4_ext_pblock(ex);
2268 if (ext4_ext_is_unwritten(ex))
2269 flags |= FIEMAP_EXTENT_UNWRITTEN;
2273 * Find delayed extent and update es accordingly. We call
2274 * it even in !exists case to find out whether es is the
2275 * last existing extent or not.
2277 next_del = ext4_find_delayed_extent(inode, &es);
2278 if (!exists && next_del) {
2279 exists = 1;
2280 flags |= (FIEMAP_EXTENT_DELALLOC |
2281 FIEMAP_EXTENT_UNKNOWN);
2283 up_read(&EXT4_I(inode)->i_data_sem);
2285 if (unlikely(es.es_len == 0)) {
2286 EXT4_ERROR_INODE(inode, "es.es_len == 0");
2287 err = -EFSCORRUPTED;
2288 break;
2292 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2293 * we need to check next == EXT_MAX_BLOCKS because it is
2294 * possible that an extent is with unwritten and delayed
2295 * status due to when an extent is delayed allocated and
2296 * is allocated by fallocate status tree will track both of
2297 * them in a extent.
2299 * So we could return a unwritten and delayed extent, and
2300 * its block is equal to 'next'.
2302 if (next == next_del && next == EXT_MAX_BLOCKS) {
2303 flags |= FIEMAP_EXTENT_LAST;
2304 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2305 next != EXT_MAX_BLOCKS)) {
2306 EXT4_ERROR_INODE(inode,
2307 "next extent == %u, next "
2308 "delalloc extent = %u",
2309 next, next_del);
2310 err = -EFSCORRUPTED;
2311 break;
2315 if (exists) {
2316 err = fiemap_fill_next_extent(fieinfo,
2317 (__u64)es.es_lblk << blksize_bits,
2318 (__u64)es.es_pblk << blksize_bits,
2319 (__u64)es.es_len << blksize_bits,
2320 flags);
2321 if (err < 0)
2322 break;
2323 if (err == 1) {
2324 err = 0;
2325 break;
2329 block = es.es_lblk + es.es_len;
2332 ext4_ext_drop_refs(path);
2333 kfree(path);
2334 return err;
2338 * ext4_ext_determine_hole - determine hole around given block
2339 * @inode: inode we lookup in
2340 * @path: path in extent tree to @lblk
2341 * @lblk: pointer to logical block around which we want to determine hole
2343 * Determine hole length (and start if easily possible) around given logical
2344 * block. We don't try too hard to find the beginning of the hole but @path
2345 * actually points to extent before @lblk, we provide it.
2347 * The function returns the length of a hole starting at @lblk. We update @lblk
2348 * to the beginning of the hole if we managed to find it.
2350 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2351 struct ext4_ext_path *path,
2352 ext4_lblk_t *lblk)
2354 int depth = ext_depth(inode);
2355 struct ext4_extent *ex;
2356 ext4_lblk_t len;
2358 ex = path[depth].p_ext;
2359 if (ex == NULL) {
2360 /* there is no extent yet, so gap is [0;-] */
2361 *lblk = 0;
2362 len = EXT_MAX_BLOCKS;
2363 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2364 len = le32_to_cpu(ex->ee_block) - *lblk;
2365 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2366 + ext4_ext_get_actual_len(ex)) {
2367 ext4_lblk_t next;
2369 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2370 next = ext4_ext_next_allocated_block(path);
2371 BUG_ON(next == *lblk);
2372 len = next - *lblk;
2373 } else {
2374 BUG();
2376 return len;
2380 * ext4_ext_put_gap_in_cache:
2381 * calculate boundaries of the gap that the requested block fits into
2382 * and cache this gap
2384 static void
2385 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2386 ext4_lblk_t hole_len)
2388 struct extent_status es;
2390 ext4_es_find_delayed_extent_range(inode, hole_start,
2391 hole_start + hole_len - 1, &es);
2392 if (es.es_len) {
2393 /* There's delayed extent containing lblock? */
2394 if (es.es_lblk <= hole_start)
2395 return;
2396 hole_len = min(es.es_lblk - hole_start, hole_len);
2398 ext_debug(" -> %u:%u\n", hole_start, hole_len);
2399 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2400 EXTENT_STATUS_HOLE);
2404 * ext4_ext_rm_idx:
2405 * removes index from the index block.
2407 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2408 struct ext4_ext_path *path, int depth)
2410 int err;
2411 ext4_fsblk_t leaf;
2413 /* free index block */
2414 depth--;
2415 path = path + depth;
2416 leaf = ext4_idx_pblock(path->p_idx);
2417 if (unlikely(path->p_hdr->eh_entries == 0)) {
2418 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2419 return -EFSCORRUPTED;
2421 err = ext4_ext_get_access(handle, inode, path);
2422 if (err)
2423 return err;
2425 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2426 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2427 len *= sizeof(struct ext4_extent_idx);
2428 memmove(path->p_idx, path->p_idx + 1, len);
2431 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2432 err = ext4_ext_dirty(handle, inode, path);
2433 if (err)
2434 return err;
2435 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2436 trace_ext4_ext_rm_idx(inode, leaf);
2438 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2439 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2441 while (--depth >= 0) {
2442 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2443 break;
2444 path--;
2445 err = ext4_ext_get_access(handle, inode, path);
2446 if (err)
2447 break;
2448 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2449 err = ext4_ext_dirty(handle, inode, path);
2450 if (err)
2451 break;
2453 return err;
2457 * ext4_ext_calc_credits_for_single_extent:
2458 * This routine returns max. credits that needed to insert an extent
2459 * to the extent tree.
2460 * When pass the actual path, the caller should calculate credits
2461 * under i_data_sem.
2463 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2464 struct ext4_ext_path *path)
2466 if (path) {
2467 int depth = ext_depth(inode);
2468 int ret = 0;
2470 /* probably there is space in leaf? */
2471 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2472 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2475 * There are some space in the leaf tree, no
2476 * need to account for leaf block credit
2478 * bitmaps and block group descriptor blocks
2479 * and other metadata blocks still need to be
2480 * accounted.
2482 /* 1 bitmap, 1 block group descriptor */
2483 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2484 return ret;
2488 return ext4_chunk_trans_blocks(inode, nrblocks);
2492 * How many index/leaf blocks need to change/allocate to add @extents extents?
2494 * If we add a single extent, then in the worse case, each tree level
2495 * index/leaf need to be changed in case of the tree split.
2497 * If more extents are inserted, they could cause the whole tree split more
2498 * than once, but this is really rare.
2500 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2502 int index;
2503 int depth;
2505 /* If we are converting the inline data, only one is needed here. */
2506 if (ext4_has_inline_data(inode))
2507 return 1;
2509 depth = ext_depth(inode);
2511 if (extents <= 1)
2512 index = depth * 2;
2513 else
2514 index = depth * 3;
2516 return index;
2519 static inline int get_default_free_blocks_flags(struct inode *inode)
2521 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2522 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2523 else if (ext4_should_journal_data(inode))
2524 return EXT4_FREE_BLOCKS_FORGET;
2525 return 0;
2528 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2529 struct ext4_extent *ex,
2530 long long *partial_cluster,
2531 ext4_lblk_t from, ext4_lblk_t to)
2533 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2534 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2535 ext4_fsblk_t pblk;
2536 int flags = get_default_free_blocks_flags(inode);
2539 * For bigalloc file systems, we never free a partial cluster
2540 * at the beginning of the extent. Instead, we make a note
2541 * that we tried freeing the cluster, and check to see if we
2542 * need to free it on a subsequent call to ext4_remove_blocks,
2543 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2545 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2547 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2549 * If we have a partial cluster, and it's different from the
2550 * cluster of the last block, we need to explicitly free the
2551 * partial cluster here.
2553 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2554 if (*partial_cluster > 0 &&
2555 *partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2556 ext4_free_blocks(handle, inode, NULL,
2557 EXT4_C2B(sbi, *partial_cluster),
2558 sbi->s_cluster_ratio, flags);
2559 *partial_cluster = 0;
2562 #ifdef EXTENTS_STATS
2564 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2565 spin_lock(&sbi->s_ext_stats_lock);
2566 sbi->s_ext_blocks += ee_len;
2567 sbi->s_ext_extents++;
2568 if (ee_len < sbi->s_ext_min)
2569 sbi->s_ext_min = ee_len;
2570 if (ee_len > sbi->s_ext_max)
2571 sbi->s_ext_max = ee_len;
2572 if (ext_depth(inode) > sbi->s_depth_max)
2573 sbi->s_depth_max = ext_depth(inode);
2574 spin_unlock(&sbi->s_ext_stats_lock);
2576 #endif
2577 if (from >= le32_to_cpu(ex->ee_block)
2578 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2579 /* tail removal */
2580 ext4_lblk_t num;
2581 long long first_cluster;
2583 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2584 pblk = ext4_ext_pblock(ex) + ee_len - num;
2586 * Usually we want to free partial cluster at the end of the
2587 * extent, except for the situation when the cluster is still
2588 * used by any other extent (partial_cluster is negative).
2590 if (*partial_cluster < 0 &&
2591 *partial_cluster == -(long long) EXT4_B2C(sbi, pblk+num-1))
2592 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2594 ext_debug("free last %u blocks starting %llu partial %lld\n",
2595 num, pblk, *partial_cluster);
2596 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2598 * If the block range to be freed didn't start at the
2599 * beginning of a cluster, and we removed the entire
2600 * extent and the cluster is not used by any other extent,
2601 * save the partial cluster here, since we might need to
2602 * delete if we determine that the truncate or punch hole
2603 * operation has removed all of the blocks in the cluster.
2604 * If that cluster is used by another extent, preserve its
2605 * negative value so it isn't freed later on.
2607 * If the whole extent wasn't freed, we've reached the
2608 * start of the truncated/punched region and have finished
2609 * removing blocks. If there's a partial cluster here it's
2610 * shared with the remainder of the extent and is no longer
2611 * a candidate for removal.
2613 if (EXT4_PBLK_COFF(sbi, pblk) && ee_len == num) {
2614 first_cluster = (long long) EXT4_B2C(sbi, pblk);
2615 if (first_cluster != -*partial_cluster)
2616 *partial_cluster = first_cluster;
2617 } else {
2618 *partial_cluster = 0;
2620 } else
2621 ext4_error(sbi->s_sb, "strange request: removal(2) "
2622 "%u-%u from %u:%u",
2623 from, to, le32_to_cpu(ex->ee_block), ee_len);
2624 return 0;
2629 * ext4_ext_rm_leaf() Removes the extents associated with the
2630 * blocks appearing between "start" and "end". Both "start"
2631 * and "end" must appear in the same extent or EIO is returned.
2633 * @handle: The journal handle
2634 * @inode: The files inode
2635 * @path: The path to the leaf
2636 * @partial_cluster: The cluster which we'll have to free if all extents
2637 * has been released from it. However, if this value is
2638 * negative, it's a cluster just to the right of the
2639 * punched region and it must not be freed.
2640 * @start: The first block to remove
2641 * @end: The last block to remove
2643 static int
2644 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2645 struct ext4_ext_path *path,
2646 long long *partial_cluster,
2647 ext4_lblk_t start, ext4_lblk_t end)
2649 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2650 int err = 0, correct_index = 0;
2651 int depth = ext_depth(inode), credits;
2652 struct ext4_extent_header *eh;
2653 ext4_lblk_t a, b;
2654 unsigned num;
2655 ext4_lblk_t ex_ee_block;
2656 unsigned short ex_ee_len;
2657 unsigned unwritten = 0;
2658 struct ext4_extent *ex;
2659 ext4_fsblk_t pblk;
2661 /* the header must be checked already in ext4_ext_remove_space() */
2662 ext_debug("truncate since %u in leaf to %u\n", start, end);
2663 if (!path[depth].p_hdr)
2664 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2665 eh = path[depth].p_hdr;
2666 if (unlikely(path[depth].p_hdr == NULL)) {
2667 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2668 return -EFSCORRUPTED;
2670 /* find where to start removing */
2671 ex = path[depth].p_ext;
2672 if (!ex)
2673 ex = EXT_LAST_EXTENT(eh);
2675 ex_ee_block = le32_to_cpu(ex->ee_block);
2676 ex_ee_len = ext4_ext_get_actual_len(ex);
2678 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2680 while (ex >= EXT_FIRST_EXTENT(eh) &&
2681 ex_ee_block + ex_ee_len > start) {
2683 if (ext4_ext_is_unwritten(ex))
2684 unwritten = 1;
2685 else
2686 unwritten = 0;
2688 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2689 unwritten, ex_ee_len);
2690 path[depth].p_ext = ex;
2692 a = ex_ee_block > start ? ex_ee_block : start;
2693 b = ex_ee_block+ex_ee_len - 1 < end ?
2694 ex_ee_block+ex_ee_len - 1 : end;
2696 ext_debug(" border %u:%u\n", a, b);
2698 /* If this extent is beyond the end of the hole, skip it */
2699 if (end < ex_ee_block) {
2701 * We're going to skip this extent and move to another,
2702 * so note that its first cluster is in use to avoid
2703 * freeing it when removing blocks. Eventually, the
2704 * right edge of the truncated/punched region will
2705 * be just to the left.
2707 if (sbi->s_cluster_ratio > 1) {
2708 pblk = ext4_ext_pblock(ex);
2709 *partial_cluster =
2710 -(long long) EXT4_B2C(sbi, pblk);
2712 ex--;
2713 ex_ee_block = le32_to_cpu(ex->ee_block);
2714 ex_ee_len = ext4_ext_get_actual_len(ex);
2715 continue;
2716 } else if (b != ex_ee_block + ex_ee_len - 1) {
2717 EXT4_ERROR_INODE(inode,
2718 "can not handle truncate %u:%u "
2719 "on extent %u:%u",
2720 start, end, ex_ee_block,
2721 ex_ee_block + ex_ee_len - 1);
2722 err = -EFSCORRUPTED;
2723 goto out;
2724 } else if (a != ex_ee_block) {
2725 /* remove tail of the extent */
2726 num = a - ex_ee_block;
2727 } else {
2728 /* remove whole extent: excellent! */
2729 num = 0;
2732 * 3 for leaf, sb, and inode plus 2 (bmap and group
2733 * descriptor) for each block group; assume two block
2734 * groups plus ex_ee_len/blocks_per_block_group for
2735 * the worst case
2737 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2738 if (ex == EXT_FIRST_EXTENT(eh)) {
2739 correct_index = 1;
2740 credits += (ext_depth(inode)) + 1;
2742 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2744 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2745 if (err)
2746 goto out;
2748 err = ext4_ext_get_access(handle, inode, path + depth);
2749 if (err)
2750 goto out;
2752 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2753 a, b);
2754 if (err)
2755 goto out;
2757 if (num == 0)
2758 /* this extent is removed; mark slot entirely unused */
2759 ext4_ext_store_pblock(ex, 0);
2761 ex->ee_len = cpu_to_le16(num);
2763 * Do not mark unwritten if all the blocks in the
2764 * extent have been removed.
2766 if (unwritten && num)
2767 ext4_ext_mark_unwritten(ex);
2769 * If the extent was completely released,
2770 * we need to remove it from the leaf
2772 if (num == 0) {
2773 if (end != EXT_MAX_BLOCKS - 1) {
2775 * For hole punching, we need to scoot all the
2776 * extents up when an extent is removed so that
2777 * we dont have blank extents in the middle
2779 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2780 sizeof(struct ext4_extent));
2782 /* Now get rid of the one at the end */
2783 memset(EXT_LAST_EXTENT(eh), 0,
2784 sizeof(struct ext4_extent));
2786 le16_add_cpu(&eh->eh_entries, -1);
2789 err = ext4_ext_dirty(handle, inode, path + depth);
2790 if (err)
2791 goto out;
2793 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2794 ext4_ext_pblock(ex));
2795 ex--;
2796 ex_ee_block = le32_to_cpu(ex->ee_block);
2797 ex_ee_len = ext4_ext_get_actual_len(ex);
2800 if (correct_index && eh->eh_entries)
2801 err = ext4_ext_correct_indexes(handle, inode, path);
2804 * If there's a partial cluster and at least one extent remains in
2805 * the leaf, free the partial cluster if it isn't shared with the
2806 * current extent. If it is shared with the current extent
2807 * we zero partial_cluster because we've reached the start of the
2808 * truncated/punched region and we're done removing blocks.
2810 if (*partial_cluster > 0 && ex >= EXT_FIRST_EXTENT(eh)) {
2811 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2812 if (*partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2813 ext4_free_blocks(handle, inode, NULL,
2814 EXT4_C2B(sbi, *partial_cluster),
2815 sbi->s_cluster_ratio,
2816 get_default_free_blocks_flags(inode));
2818 *partial_cluster = 0;
2821 /* if this leaf is free, then we should
2822 * remove it from index block above */
2823 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2824 err = ext4_ext_rm_idx(handle, inode, path, depth);
2826 out:
2827 return err;
2831 * ext4_ext_more_to_rm:
2832 * returns 1 if current index has to be freed (even partial)
2834 static int
2835 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2837 BUG_ON(path->p_idx == NULL);
2839 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2840 return 0;
2843 * if truncate on deeper level happened, it wasn't partial,
2844 * so we have to consider current index for truncation
2846 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2847 return 0;
2848 return 1;
2851 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2852 ext4_lblk_t end)
2854 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2855 int depth = ext_depth(inode);
2856 struct ext4_ext_path *path = NULL;
2857 long long partial_cluster = 0;
2858 handle_t *handle;
2859 int i = 0, err = 0;
2861 ext_debug("truncate since %u to %u\n", start, end);
2863 /* probably first extent we're gonna free will be last in block */
2864 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
2865 if (IS_ERR(handle))
2866 return PTR_ERR(handle);
2868 again:
2869 trace_ext4_ext_remove_space(inode, start, end, depth);
2872 * Check if we are removing extents inside the extent tree. If that
2873 * is the case, we are going to punch a hole inside the extent tree
2874 * so we have to check whether we need to split the extent covering
2875 * the last block to remove so we can easily remove the part of it
2876 * in ext4_ext_rm_leaf().
2878 if (end < EXT_MAX_BLOCKS - 1) {
2879 struct ext4_extent *ex;
2880 ext4_lblk_t ee_block, ex_end, lblk;
2881 ext4_fsblk_t pblk;
2883 /* find extent for or closest extent to this block */
2884 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
2885 if (IS_ERR(path)) {
2886 ext4_journal_stop(handle);
2887 return PTR_ERR(path);
2889 depth = ext_depth(inode);
2890 /* Leaf not may not exist only if inode has no blocks at all */
2891 ex = path[depth].p_ext;
2892 if (!ex) {
2893 if (depth) {
2894 EXT4_ERROR_INODE(inode,
2895 "path[%d].p_hdr == NULL",
2896 depth);
2897 err = -EFSCORRUPTED;
2899 goto out;
2902 ee_block = le32_to_cpu(ex->ee_block);
2903 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2906 * See if the last block is inside the extent, if so split
2907 * the extent at 'end' block so we can easily remove the
2908 * tail of the first part of the split extent in
2909 * ext4_ext_rm_leaf().
2911 if (end >= ee_block && end < ex_end) {
2914 * If we're going to split the extent, note that
2915 * the cluster containing the block after 'end' is
2916 * in use to avoid freeing it when removing blocks.
2918 if (sbi->s_cluster_ratio > 1) {
2919 pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
2920 partial_cluster =
2921 -(long long) EXT4_B2C(sbi, pblk);
2925 * Split the extent in two so that 'end' is the last
2926 * block in the first new extent. Also we should not
2927 * fail removing space due to ENOSPC so try to use
2928 * reserved block if that happens.
2930 err = ext4_force_split_extent_at(handle, inode, &path,
2931 end + 1, 1);
2932 if (err < 0)
2933 goto out;
2935 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end) {
2937 * If there's an extent to the right its first cluster
2938 * contains the immediate right boundary of the
2939 * truncated/punched region. Set partial_cluster to
2940 * its negative value so it won't be freed if shared
2941 * with the current extent. The end < ee_block case
2942 * is handled in ext4_ext_rm_leaf().
2944 lblk = ex_end + 1;
2945 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2946 &ex);
2947 if (err)
2948 goto out;
2949 if (pblk)
2950 partial_cluster =
2951 -(long long) EXT4_B2C(sbi, pblk);
2955 * We start scanning from right side, freeing all the blocks
2956 * after i_size and walking into the tree depth-wise.
2958 depth = ext_depth(inode);
2959 if (path) {
2960 int k = i = depth;
2961 while (--k > 0)
2962 path[k].p_block =
2963 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2964 } else {
2965 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2966 GFP_NOFS);
2967 if (path == NULL) {
2968 ext4_journal_stop(handle);
2969 return -ENOMEM;
2971 path[0].p_maxdepth = path[0].p_depth = depth;
2972 path[0].p_hdr = ext_inode_hdr(inode);
2973 i = 0;
2975 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2976 err = -EFSCORRUPTED;
2977 goto out;
2980 err = 0;
2982 while (i >= 0 && err == 0) {
2983 if (i == depth) {
2984 /* this is leaf block */
2985 err = ext4_ext_rm_leaf(handle, inode, path,
2986 &partial_cluster, start,
2987 end);
2988 /* root level has p_bh == NULL, brelse() eats this */
2989 brelse(path[i].p_bh);
2990 path[i].p_bh = NULL;
2991 i--;
2992 continue;
2995 /* this is index block */
2996 if (!path[i].p_hdr) {
2997 ext_debug("initialize header\n");
2998 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
3001 if (!path[i].p_idx) {
3002 /* this level hasn't been touched yet */
3003 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
3004 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
3005 ext_debug("init index ptr: hdr 0x%p, num %d\n",
3006 path[i].p_hdr,
3007 le16_to_cpu(path[i].p_hdr->eh_entries));
3008 } else {
3009 /* we were already here, see at next index */
3010 path[i].p_idx--;
3013 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
3014 i, EXT_FIRST_INDEX(path[i].p_hdr),
3015 path[i].p_idx);
3016 if (ext4_ext_more_to_rm(path + i)) {
3017 struct buffer_head *bh;
3018 /* go to the next level */
3019 ext_debug("move to level %d (block %llu)\n",
3020 i + 1, ext4_idx_pblock(path[i].p_idx));
3021 memset(path + i + 1, 0, sizeof(*path));
3022 bh = read_extent_tree_block(inode,
3023 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
3024 EXT4_EX_NOCACHE);
3025 if (IS_ERR(bh)) {
3026 /* should we reset i_size? */
3027 err = PTR_ERR(bh);
3028 break;
3030 /* Yield here to deal with large extent trees.
3031 * Should be a no-op if we did IO above. */
3032 cond_resched();
3033 if (WARN_ON(i + 1 > depth)) {
3034 err = -EFSCORRUPTED;
3035 break;
3037 path[i + 1].p_bh = bh;
3039 /* save actual number of indexes since this
3040 * number is changed at the next iteration */
3041 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3042 i++;
3043 } else {
3044 /* we finished processing this index, go up */
3045 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3046 /* index is empty, remove it;
3047 * handle must be already prepared by the
3048 * truncatei_leaf() */
3049 err = ext4_ext_rm_idx(handle, inode, path, i);
3051 /* root level has p_bh == NULL, brelse() eats this */
3052 brelse(path[i].p_bh);
3053 path[i].p_bh = NULL;
3054 i--;
3055 ext_debug("return to level %d\n", i);
3059 trace_ext4_ext_remove_space_done(inode, start, end, depth,
3060 partial_cluster, path->p_hdr->eh_entries);
3063 * If we still have something in the partial cluster and we have removed
3064 * even the first extent, then we should free the blocks in the partial
3065 * cluster as well. (This code will only run when there are no leaves
3066 * to the immediate left of the truncated/punched region.)
3068 if (partial_cluster > 0 && err == 0) {
3069 /* don't zero partial_cluster since it's not used afterwards */
3070 ext4_free_blocks(handle, inode, NULL,
3071 EXT4_C2B(sbi, partial_cluster),
3072 sbi->s_cluster_ratio,
3073 get_default_free_blocks_flags(inode));
3076 /* TODO: flexible tree reduction should be here */
3077 if (path->p_hdr->eh_entries == 0) {
3079 * truncate to zero freed all the tree,
3080 * so we need to correct eh_depth
3082 err = ext4_ext_get_access(handle, inode, path);
3083 if (err == 0) {
3084 ext_inode_hdr(inode)->eh_depth = 0;
3085 ext_inode_hdr(inode)->eh_max =
3086 cpu_to_le16(ext4_ext_space_root(inode, 0));
3087 err = ext4_ext_dirty(handle, inode, path);
3090 out:
3091 ext4_ext_drop_refs(path);
3092 kfree(path);
3093 path = NULL;
3094 if (err == -EAGAIN)
3095 goto again;
3096 ext4_journal_stop(handle);
3098 return err;
3102 * called at mount time
3104 void ext4_ext_init(struct super_block *sb)
3107 * possible initialization would be here
3110 if (ext4_has_feature_extents(sb)) {
3111 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3112 printk(KERN_INFO "EXT4-fs: file extents enabled"
3113 #ifdef AGGRESSIVE_TEST
3114 ", aggressive tests"
3115 #endif
3116 #ifdef CHECK_BINSEARCH
3117 ", check binsearch"
3118 #endif
3119 #ifdef EXTENTS_STATS
3120 ", stats"
3121 #endif
3122 "\n");
3123 #endif
3124 #ifdef EXTENTS_STATS
3125 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3126 EXT4_SB(sb)->s_ext_min = 1 << 30;
3127 EXT4_SB(sb)->s_ext_max = 0;
3128 #endif
3133 * called at umount time
3135 void ext4_ext_release(struct super_block *sb)
3137 if (!ext4_has_feature_extents(sb))
3138 return;
3140 #ifdef EXTENTS_STATS
3141 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3142 struct ext4_sb_info *sbi = EXT4_SB(sb);
3143 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3144 sbi->s_ext_blocks, sbi->s_ext_extents,
3145 sbi->s_ext_blocks / sbi->s_ext_extents);
3146 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3147 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3149 #endif
3152 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3154 ext4_lblk_t ee_block;
3155 ext4_fsblk_t ee_pblock;
3156 unsigned int ee_len;
3158 ee_block = le32_to_cpu(ex->ee_block);
3159 ee_len = ext4_ext_get_actual_len(ex);
3160 ee_pblock = ext4_ext_pblock(ex);
3162 if (ee_len == 0)
3163 return 0;
3165 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3166 EXTENT_STATUS_WRITTEN);
3169 /* FIXME!! we need to try to merge to left or right after zero-out */
3170 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3172 ext4_fsblk_t ee_pblock;
3173 unsigned int ee_len;
3175 ee_len = ext4_ext_get_actual_len(ex);
3176 ee_pblock = ext4_ext_pblock(ex);
3177 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3178 ee_len);
3182 * ext4_split_extent_at() splits an extent at given block.
3184 * @handle: the journal handle
3185 * @inode: the file inode
3186 * @path: the path to the extent
3187 * @split: the logical block where the extent is splitted.
3188 * @split_flags: indicates if the extent could be zeroout if split fails, and
3189 * the states(init or unwritten) of new extents.
3190 * @flags: flags used to insert new extent to extent tree.
3193 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3194 * of which are deterimined by split_flag.
3196 * There are two cases:
3197 * a> the extent are splitted into two extent.
3198 * b> split is not needed, and just mark the extent.
3200 * return 0 on success.
3202 static int ext4_split_extent_at(handle_t *handle,
3203 struct inode *inode,
3204 struct ext4_ext_path **ppath,
3205 ext4_lblk_t split,
3206 int split_flag,
3207 int flags)
3209 struct ext4_ext_path *path = *ppath;
3210 ext4_fsblk_t newblock;
3211 ext4_lblk_t ee_block;
3212 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3213 struct ext4_extent *ex2 = NULL;
3214 unsigned int ee_len, depth;
3215 int err = 0;
3217 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3218 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3220 ext_debug("ext4_split_extents_at: inode %lu, logical"
3221 "block %llu\n", inode->i_ino, (unsigned long long)split);
3223 ext4_ext_show_leaf(inode, path);
3225 depth = ext_depth(inode);
3226 ex = path[depth].p_ext;
3227 ee_block = le32_to_cpu(ex->ee_block);
3228 ee_len = ext4_ext_get_actual_len(ex);
3229 newblock = split - ee_block + ext4_ext_pblock(ex);
3231 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3232 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3233 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3234 EXT4_EXT_MARK_UNWRIT1 |
3235 EXT4_EXT_MARK_UNWRIT2));
3237 err = ext4_ext_get_access(handle, inode, path + depth);
3238 if (err)
3239 goto out;
3241 if (split == ee_block) {
3243 * case b: block @split is the block that the extent begins with
3244 * then we just change the state of the extent, and splitting
3245 * is not needed.
3247 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3248 ext4_ext_mark_unwritten(ex);
3249 else
3250 ext4_ext_mark_initialized(ex);
3252 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3253 ext4_ext_try_to_merge(handle, inode, path, ex);
3255 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3256 goto out;
3259 /* case a */
3260 memcpy(&orig_ex, ex, sizeof(orig_ex));
3261 ex->ee_len = cpu_to_le16(split - ee_block);
3262 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3263 ext4_ext_mark_unwritten(ex);
3266 * path may lead to new leaf, not to original leaf any more
3267 * after ext4_ext_insert_extent() returns,
3269 err = ext4_ext_dirty(handle, inode, path + depth);
3270 if (err)
3271 goto fix_extent_len;
3273 ex2 = &newex;
3274 ex2->ee_block = cpu_to_le32(split);
3275 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3276 ext4_ext_store_pblock(ex2, newblock);
3277 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3278 ext4_ext_mark_unwritten(ex2);
3280 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3281 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3282 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3283 if (split_flag & EXT4_EXT_DATA_VALID1) {
3284 err = ext4_ext_zeroout(inode, ex2);
3285 zero_ex.ee_block = ex2->ee_block;
3286 zero_ex.ee_len = cpu_to_le16(
3287 ext4_ext_get_actual_len(ex2));
3288 ext4_ext_store_pblock(&zero_ex,
3289 ext4_ext_pblock(ex2));
3290 } else {
3291 err = ext4_ext_zeroout(inode, ex);
3292 zero_ex.ee_block = ex->ee_block;
3293 zero_ex.ee_len = cpu_to_le16(
3294 ext4_ext_get_actual_len(ex));
3295 ext4_ext_store_pblock(&zero_ex,
3296 ext4_ext_pblock(ex));
3298 } else {
3299 err = ext4_ext_zeroout(inode, &orig_ex);
3300 zero_ex.ee_block = orig_ex.ee_block;
3301 zero_ex.ee_len = cpu_to_le16(
3302 ext4_ext_get_actual_len(&orig_ex));
3303 ext4_ext_store_pblock(&zero_ex,
3304 ext4_ext_pblock(&orig_ex));
3307 if (err)
3308 goto fix_extent_len;
3309 /* update the extent length and mark as initialized */
3310 ex->ee_len = cpu_to_le16(ee_len);
3311 ext4_ext_try_to_merge(handle, inode, path, ex);
3312 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3313 if (err)
3314 goto fix_extent_len;
3316 /* update extent status tree */
3317 err = ext4_zeroout_es(inode, &zero_ex);
3319 goto out;
3320 } else if (err)
3321 goto fix_extent_len;
3323 out:
3324 ext4_ext_show_leaf(inode, path);
3325 return err;
3327 fix_extent_len:
3328 ex->ee_len = orig_ex.ee_len;
3329 ext4_ext_dirty(handle, inode, path + path->p_depth);
3330 return err;
3334 * ext4_split_extents() splits an extent and mark extent which is covered
3335 * by @map as split_flags indicates
3337 * It may result in splitting the extent into multiple extents (up to three)
3338 * There are three possibilities:
3339 * a> There is no split required
3340 * b> Splits in two extents: Split is happening at either end of the extent
3341 * c> Splits in three extents: Somone is splitting in middle of the extent
3344 static int ext4_split_extent(handle_t *handle,
3345 struct inode *inode,
3346 struct ext4_ext_path **ppath,
3347 struct ext4_map_blocks *map,
3348 int split_flag,
3349 int flags)
3351 struct ext4_ext_path *path = *ppath;
3352 ext4_lblk_t ee_block;
3353 struct ext4_extent *ex;
3354 unsigned int ee_len, depth;
3355 int err = 0;
3356 int unwritten;
3357 int split_flag1, flags1;
3358 int allocated = map->m_len;
3360 depth = ext_depth(inode);
3361 ex = path[depth].p_ext;
3362 ee_block = le32_to_cpu(ex->ee_block);
3363 ee_len = ext4_ext_get_actual_len(ex);
3364 unwritten = ext4_ext_is_unwritten(ex);
3366 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3367 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3368 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3369 if (unwritten)
3370 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3371 EXT4_EXT_MARK_UNWRIT2;
3372 if (split_flag & EXT4_EXT_DATA_VALID2)
3373 split_flag1 |= EXT4_EXT_DATA_VALID1;
3374 err = ext4_split_extent_at(handle, inode, ppath,
3375 map->m_lblk + map->m_len, split_flag1, flags1);
3376 if (err)
3377 goto out;
3378 } else {
3379 allocated = ee_len - (map->m_lblk - ee_block);
3382 * Update path is required because previous ext4_split_extent_at() may
3383 * result in split of original leaf or extent zeroout.
3385 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3386 if (IS_ERR(path))
3387 return PTR_ERR(path);
3388 depth = ext_depth(inode);
3389 ex = path[depth].p_ext;
3390 if (!ex) {
3391 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3392 (unsigned long) map->m_lblk);
3393 return -EFSCORRUPTED;
3395 unwritten = ext4_ext_is_unwritten(ex);
3396 split_flag1 = 0;
3398 if (map->m_lblk >= ee_block) {
3399 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3400 if (unwritten) {
3401 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3402 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3403 EXT4_EXT_MARK_UNWRIT2);
3405 err = ext4_split_extent_at(handle, inode, ppath,
3406 map->m_lblk, split_flag1, flags);
3407 if (err)
3408 goto out;
3411 ext4_ext_show_leaf(inode, path);
3412 out:
3413 return err ? err : allocated;
3417 * This function is called by ext4_ext_map_blocks() if someone tries to write
3418 * to an unwritten extent. It may result in splitting the unwritten
3419 * extent into multiple extents (up to three - one initialized and two
3420 * unwritten).
3421 * There are three possibilities:
3422 * a> There is no split required: Entire extent should be initialized
3423 * b> Splits in two extents: Write is happening at either end of the extent
3424 * c> Splits in three extents: Somone is writing in middle of the extent
3426 * Pre-conditions:
3427 * - The extent pointed to by 'path' is unwritten.
3428 * - The extent pointed to by 'path' contains a superset
3429 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3431 * Post-conditions on success:
3432 * - the returned value is the number of blocks beyond map->l_lblk
3433 * that are allocated and initialized.
3434 * It is guaranteed to be >= map->m_len.
3436 static int ext4_ext_convert_to_initialized(handle_t *handle,
3437 struct inode *inode,
3438 struct ext4_map_blocks *map,
3439 struct ext4_ext_path **ppath,
3440 int flags)
3442 struct ext4_ext_path *path = *ppath;
3443 struct ext4_sb_info *sbi;
3444 struct ext4_extent_header *eh;
3445 struct ext4_map_blocks split_map;
3446 struct ext4_extent zero_ex1, zero_ex2;
3447 struct ext4_extent *ex, *abut_ex;
3448 ext4_lblk_t ee_block, eof_block;
3449 unsigned int ee_len, depth, map_len = map->m_len;
3450 int allocated = 0, max_zeroout = 0;
3451 int err = 0;
3452 int split_flag = EXT4_EXT_DATA_VALID2;
3454 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3455 "block %llu, max_blocks %u\n", inode->i_ino,
3456 (unsigned long long)map->m_lblk, map_len);
3458 sbi = EXT4_SB(inode->i_sb);
3459 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3460 >> inode->i_sb->s_blocksize_bits;
3461 if (eof_block < map->m_lblk + map_len)
3462 eof_block = map->m_lblk + map_len;
3464 depth = ext_depth(inode);
3465 eh = path[depth].p_hdr;
3466 ex = path[depth].p_ext;
3467 ee_block = le32_to_cpu(ex->ee_block);
3468 ee_len = ext4_ext_get_actual_len(ex);
3469 zero_ex1.ee_len = 0;
3470 zero_ex2.ee_len = 0;
3472 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3474 /* Pre-conditions */
3475 BUG_ON(!ext4_ext_is_unwritten(ex));
3476 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3479 * Attempt to transfer newly initialized blocks from the currently
3480 * unwritten extent to its neighbor. This is much cheaper
3481 * than an insertion followed by a merge as those involve costly
3482 * memmove() calls. Transferring to the left is the common case in
3483 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3484 * followed by append writes.
3486 * Limitations of the current logic:
3487 * - L1: we do not deal with writes covering the whole extent.
3488 * This would require removing the extent if the transfer
3489 * is possible.
3490 * - L2: we only attempt to merge with an extent stored in the
3491 * same extent tree node.
3493 if ((map->m_lblk == ee_block) &&
3494 /* See if we can merge left */
3495 (map_len < ee_len) && /*L1*/
3496 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3497 ext4_lblk_t prev_lblk;
3498 ext4_fsblk_t prev_pblk, ee_pblk;
3499 unsigned int prev_len;
3501 abut_ex = ex - 1;
3502 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3503 prev_len = ext4_ext_get_actual_len(abut_ex);
3504 prev_pblk = ext4_ext_pblock(abut_ex);
3505 ee_pblk = ext4_ext_pblock(ex);
3508 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3509 * upon those conditions:
3510 * - C1: abut_ex is initialized,
3511 * - C2: abut_ex is logically abutting ex,
3512 * - C3: abut_ex is physically abutting ex,
3513 * - C4: abut_ex can receive the additional blocks without
3514 * overflowing the (initialized) length limit.
3516 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3517 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3518 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3519 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3520 err = ext4_ext_get_access(handle, inode, path + depth);
3521 if (err)
3522 goto out;
3524 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3525 map, ex, abut_ex);
3527 /* Shift the start of ex by 'map_len' blocks */
3528 ex->ee_block = cpu_to_le32(ee_block + map_len);
3529 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3530 ex->ee_len = cpu_to_le16(ee_len - map_len);
3531 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3533 /* Extend abut_ex by 'map_len' blocks */
3534 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3536 /* Result: number of initialized blocks past m_lblk */
3537 allocated = map_len;
3539 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3540 (map_len < ee_len) && /*L1*/
3541 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3542 /* See if we can merge right */
3543 ext4_lblk_t next_lblk;
3544 ext4_fsblk_t next_pblk, ee_pblk;
3545 unsigned int next_len;
3547 abut_ex = ex + 1;
3548 next_lblk = le32_to_cpu(abut_ex->ee_block);
3549 next_len = ext4_ext_get_actual_len(abut_ex);
3550 next_pblk = ext4_ext_pblock(abut_ex);
3551 ee_pblk = ext4_ext_pblock(ex);
3554 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3555 * upon those conditions:
3556 * - C1: abut_ex is initialized,
3557 * - C2: abut_ex is logically abutting ex,
3558 * - C3: abut_ex is physically abutting ex,
3559 * - C4: abut_ex can receive the additional blocks without
3560 * overflowing the (initialized) length limit.
3562 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3563 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3564 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3565 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3566 err = ext4_ext_get_access(handle, inode, path + depth);
3567 if (err)
3568 goto out;
3570 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3571 map, ex, abut_ex);
3573 /* Shift the start of abut_ex by 'map_len' blocks */
3574 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3575 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3576 ex->ee_len = cpu_to_le16(ee_len - map_len);
3577 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3579 /* Extend abut_ex by 'map_len' blocks */
3580 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3582 /* Result: number of initialized blocks past m_lblk */
3583 allocated = map_len;
3586 if (allocated) {
3587 /* Mark the block containing both extents as dirty */
3588 ext4_ext_dirty(handle, inode, path + depth);
3590 /* Update path to point to the right extent */
3591 path[depth].p_ext = abut_ex;
3592 goto out;
3593 } else
3594 allocated = ee_len - (map->m_lblk - ee_block);
3596 WARN_ON(map->m_lblk < ee_block);
3598 * It is safe to convert extent to initialized via explicit
3599 * zeroout only if extent is fully inside i_size or new_size.
3601 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3603 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3604 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3605 (inode->i_sb->s_blocksize_bits - 10);
3607 if (ext4_encrypted_inode(inode))
3608 max_zeroout = 0;
3611 * five cases:
3612 * 1. split the extent into three extents.
3613 * 2. split the extent into two extents, zeroout the head of the first
3614 * extent.
3615 * 3. split the extent into two extents, zeroout the tail of the second
3616 * extent.
3617 * 4. split the extent into two extents with out zeroout.
3618 * 5. no splitting needed, just possibly zeroout the head and / or the
3619 * tail of the extent.
3621 split_map.m_lblk = map->m_lblk;
3622 split_map.m_len = map->m_len;
3624 if (max_zeroout && (allocated > split_map.m_len)) {
3625 if (allocated <= max_zeroout) {
3626 /* case 3 or 5 */
3627 zero_ex1.ee_block =
3628 cpu_to_le32(split_map.m_lblk +
3629 split_map.m_len);
3630 zero_ex1.ee_len =
3631 cpu_to_le16(allocated - split_map.m_len);
3632 ext4_ext_store_pblock(&zero_ex1,
3633 ext4_ext_pblock(ex) + split_map.m_lblk +
3634 split_map.m_len - ee_block);
3635 err = ext4_ext_zeroout(inode, &zero_ex1);
3636 if (err)
3637 goto out;
3638 split_map.m_len = allocated;
3640 if (split_map.m_lblk - ee_block + split_map.m_len <
3641 max_zeroout) {
3642 /* case 2 or 5 */
3643 if (split_map.m_lblk != ee_block) {
3644 zero_ex2.ee_block = ex->ee_block;
3645 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3646 ee_block);
3647 ext4_ext_store_pblock(&zero_ex2,
3648 ext4_ext_pblock(ex));
3649 err = ext4_ext_zeroout(inode, &zero_ex2);
3650 if (err)
3651 goto out;
3654 split_map.m_len += split_map.m_lblk - ee_block;
3655 split_map.m_lblk = ee_block;
3656 allocated = map->m_len;
3660 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3661 flags);
3662 if (err > 0)
3663 err = 0;
3664 out:
3665 /* If we have gotten a failure, don't zero out status tree */
3666 if (!err) {
3667 err = ext4_zeroout_es(inode, &zero_ex1);
3668 if (!err)
3669 err = ext4_zeroout_es(inode, &zero_ex2);
3671 return err ? err : allocated;
3675 * This function is called by ext4_ext_map_blocks() from
3676 * ext4_get_blocks_dio_write() when DIO to write
3677 * to an unwritten extent.
3679 * Writing to an unwritten extent may result in splitting the unwritten
3680 * extent into multiple initialized/unwritten extents (up to three)
3681 * There are three possibilities:
3682 * a> There is no split required: Entire extent should be unwritten
3683 * b> Splits in two extents: Write is happening at either end of the extent
3684 * c> Splits in three extents: Somone is writing in middle of the extent
3686 * This works the same way in the case of initialized -> unwritten conversion.
3688 * One of more index blocks maybe needed if the extent tree grow after
3689 * the unwritten extent split. To prevent ENOSPC occur at the IO
3690 * complete, we need to split the unwritten extent before DIO submit
3691 * the IO. The unwritten extent called at this time will be split
3692 * into three unwritten extent(at most). After IO complete, the part
3693 * being filled will be convert to initialized by the end_io callback function
3694 * via ext4_convert_unwritten_extents().
3696 * Returns the size of unwritten extent to be written on success.
3698 static int ext4_split_convert_extents(handle_t *handle,
3699 struct inode *inode,
3700 struct ext4_map_blocks *map,
3701 struct ext4_ext_path **ppath,
3702 int flags)
3704 struct ext4_ext_path *path = *ppath;
3705 ext4_lblk_t eof_block;
3706 ext4_lblk_t ee_block;
3707 struct ext4_extent *ex;
3708 unsigned int ee_len;
3709 int split_flag = 0, depth;
3711 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3712 __func__, inode->i_ino,
3713 (unsigned long long)map->m_lblk, map->m_len);
3715 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3716 >> inode->i_sb->s_blocksize_bits;
3717 if (eof_block < map->m_lblk + map->m_len)
3718 eof_block = map->m_lblk + map->m_len;
3720 * It is safe to convert extent to initialized via explicit
3721 * zeroout only if extent is fully insde i_size or new_size.
3723 depth = ext_depth(inode);
3724 ex = path[depth].p_ext;
3725 ee_block = le32_to_cpu(ex->ee_block);
3726 ee_len = ext4_ext_get_actual_len(ex);
3728 /* Convert to unwritten */
3729 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3730 split_flag |= EXT4_EXT_DATA_VALID1;
3731 /* Convert to initialized */
3732 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3733 split_flag |= ee_block + ee_len <= eof_block ?
3734 EXT4_EXT_MAY_ZEROOUT : 0;
3735 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3737 flags |= EXT4_GET_BLOCKS_PRE_IO;
3738 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3741 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3742 struct inode *inode,
3743 struct ext4_map_blocks *map,
3744 struct ext4_ext_path **ppath)
3746 struct ext4_ext_path *path = *ppath;
3747 struct ext4_extent *ex;
3748 ext4_lblk_t ee_block;
3749 unsigned int ee_len;
3750 int depth;
3751 int err = 0;
3753 depth = ext_depth(inode);
3754 ex = path[depth].p_ext;
3755 ee_block = le32_to_cpu(ex->ee_block);
3756 ee_len = ext4_ext_get_actual_len(ex);
3758 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3759 "block %llu, max_blocks %u\n", inode->i_ino,
3760 (unsigned long long)ee_block, ee_len);
3762 /* If extent is larger than requested it is a clear sign that we still
3763 * have some extent state machine issues left. So extent_split is still
3764 * required.
3765 * TODO: Once all related issues will be fixed this situation should be
3766 * illegal.
3768 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3769 #ifdef CONFIG_EXT4_DEBUG
3770 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3771 " len %u; IO logical block %llu, len %u",
3772 inode->i_ino, (unsigned long long)ee_block, ee_len,
3773 (unsigned long long)map->m_lblk, map->m_len);
3774 #endif
3775 err = ext4_split_convert_extents(handle, inode, map, ppath,
3776 EXT4_GET_BLOCKS_CONVERT);
3777 if (err < 0)
3778 return err;
3779 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3780 if (IS_ERR(path))
3781 return PTR_ERR(path);
3782 depth = ext_depth(inode);
3783 ex = path[depth].p_ext;
3786 err = ext4_ext_get_access(handle, inode, path + depth);
3787 if (err)
3788 goto out;
3789 /* first mark the extent as initialized */
3790 ext4_ext_mark_initialized(ex);
3792 /* note: ext4_ext_correct_indexes() isn't needed here because
3793 * borders are not changed
3795 ext4_ext_try_to_merge(handle, inode, path, ex);
3797 /* Mark modified extent as dirty */
3798 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3799 out:
3800 ext4_ext_show_leaf(inode, path);
3801 return err;
3804 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3805 sector_t block, int count)
3807 int i;
3808 for (i = 0; i < count; i++)
3809 unmap_underlying_metadata(bdev, block + i);
3813 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3815 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3816 ext4_lblk_t lblk,
3817 struct ext4_ext_path *path,
3818 unsigned int len)
3820 int i, depth;
3821 struct ext4_extent_header *eh;
3822 struct ext4_extent *last_ex;
3824 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3825 return 0;
3827 depth = ext_depth(inode);
3828 eh = path[depth].p_hdr;
3831 * We're going to remove EOFBLOCKS_FL entirely in future so we
3832 * do not care for this case anymore. Simply remove the flag
3833 * if there are no extents.
3835 if (unlikely(!eh->eh_entries))
3836 goto out;
3837 last_ex = EXT_LAST_EXTENT(eh);
3839 * We should clear the EOFBLOCKS_FL flag if we are writing the
3840 * last block in the last extent in the file. We test this by
3841 * first checking to see if the caller to
3842 * ext4_ext_get_blocks() was interested in the last block (or
3843 * a block beyond the last block) in the current extent. If
3844 * this turns out to be false, we can bail out from this
3845 * function immediately.
3847 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3848 ext4_ext_get_actual_len(last_ex))
3849 return 0;
3851 * If the caller does appear to be planning to write at or
3852 * beyond the end of the current extent, we then test to see
3853 * if the current extent is the last extent in the file, by
3854 * checking to make sure it was reached via the rightmost node
3855 * at each level of the tree.
3857 for (i = depth-1; i >= 0; i--)
3858 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3859 return 0;
3860 out:
3861 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3862 return ext4_mark_inode_dirty(handle, inode);
3866 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3868 * Return 1 if there is a delalloc block in the range, otherwise 0.
3870 int ext4_find_delalloc_range(struct inode *inode,
3871 ext4_lblk_t lblk_start,
3872 ext4_lblk_t lblk_end)
3874 struct extent_status es;
3876 ext4_es_find_delayed_extent_range(inode, lblk_start, lblk_end, &es);
3877 if (es.es_len == 0)
3878 return 0; /* there is no delay extent in this tree */
3879 else if (es.es_lblk <= lblk_start &&
3880 lblk_start < es.es_lblk + es.es_len)
3881 return 1;
3882 else if (lblk_start <= es.es_lblk && es.es_lblk <= lblk_end)
3883 return 1;
3884 else
3885 return 0;
3888 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk)
3890 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3891 ext4_lblk_t lblk_start, lblk_end;
3892 lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
3893 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3895 return ext4_find_delalloc_range(inode, lblk_start, lblk_end);
3899 * Determines how many complete clusters (out of those specified by the 'map')
3900 * are under delalloc and were reserved quota for.
3901 * This function is called when we are writing out the blocks that were
3902 * originally written with their allocation delayed, but then the space was
3903 * allocated using fallocate() before the delayed allocation could be resolved.
3904 * The cases to look for are:
3905 * ('=' indicated delayed allocated blocks
3906 * '-' indicates non-delayed allocated blocks)
3907 * (a) partial clusters towards beginning and/or end outside of allocated range
3908 * are not delalloc'ed.
3909 * Ex:
3910 * |----c---=|====c====|====c====|===-c----|
3911 * |++++++ allocated ++++++|
3912 * ==> 4 complete clusters in above example
3914 * (b) partial cluster (outside of allocated range) towards either end is
3915 * marked for delayed allocation. In this case, we will exclude that
3916 * cluster.
3917 * Ex:
3918 * |----====c========|========c========|
3919 * |++++++ allocated ++++++|
3920 * ==> 1 complete clusters in above example
3922 * Ex:
3923 * |================c================|
3924 * |++++++ allocated ++++++|
3925 * ==> 0 complete clusters in above example
3927 * The ext4_da_update_reserve_space will be called only if we
3928 * determine here that there were some "entire" clusters that span
3929 * this 'allocated' range.
3930 * In the non-bigalloc case, this function will just end up returning num_blks
3931 * without ever calling ext4_find_delalloc_range.
3933 static unsigned int
3934 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3935 unsigned int num_blks)
3937 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3938 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3939 ext4_lblk_t lblk_from, lblk_to, c_offset;
3940 unsigned int allocated_clusters = 0;
3942 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3943 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3945 /* max possible clusters for this allocation */
3946 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3948 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3950 /* Check towards left side */
3951 c_offset = EXT4_LBLK_COFF(sbi, lblk_start);
3952 if (c_offset) {
3953 lblk_from = EXT4_LBLK_CMASK(sbi, lblk_start);
3954 lblk_to = lblk_from + c_offset - 1;
3956 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3957 allocated_clusters--;
3960 /* Now check towards right. */
3961 c_offset = EXT4_LBLK_COFF(sbi, lblk_start + num_blks);
3962 if (allocated_clusters && c_offset) {
3963 lblk_from = lblk_start + num_blks;
3964 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3966 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3967 allocated_clusters--;
3970 return allocated_clusters;
3973 static int
3974 convert_initialized_extent(handle_t *handle, struct inode *inode,
3975 struct ext4_map_blocks *map,
3976 struct ext4_ext_path **ppath,
3977 unsigned int allocated)
3979 struct ext4_ext_path *path = *ppath;
3980 struct ext4_extent *ex;
3981 ext4_lblk_t ee_block;
3982 unsigned int ee_len;
3983 int depth;
3984 int err = 0;
3987 * Make sure that the extent is no bigger than we support with
3988 * unwritten extent
3990 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3991 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3993 depth = ext_depth(inode);
3994 ex = path[depth].p_ext;
3995 ee_block = le32_to_cpu(ex->ee_block);
3996 ee_len = ext4_ext_get_actual_len(ex);
3998 ext_debug("%s: inode %lu, logical"
3999 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
4000 (unsigned long long)ee_block, ee_len);
4002 if (ee_block != map->m_lblk || ee_len > map->m_len) {
4003 err = ext4_split_convert_extents(handle, inode, map, ppath,
4004 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
4005 if (err < 0)
4006 return err;
4007 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
4008 if (IS_ERR(path))
4009 return PTR_ERR(path);
4010 depth = ext_depth(inode);
4011 ex = path[depth].p_ext;
4012 if (!ex) {
4013 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
4014 (unsigned long) map->m_lblk);
4015 return -EFSCORRUPTED;
4019 err = ext4_ext_get_access(handle, inode, path + depth);
4020 if (err)
4021 return err;
4022 /* first mark the extent as unwritten */
4023 ext4_ext_mark_unwritten(ex);
4025 /* note: ext4_ext_correct_indexes() isn't needed here because
4026 * borders are not changed
4028 ext4_ext_try_to_merge(handle, inode, path, ex);
4030 /* Mark modified extent as dirty */
4031 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4032 if (err)
4033 return err;
4034 ext4_ext_show_leaf(inode, path);
4036 ext4_update_inode_fsync_trans(handle, inode, 1);
4037 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4038 if (err)
4039 return err;
4040 map->m_flags |= EXT4_MAP_UNWRITTEN;
4041 if (allocated > map->m_len)
4042 allocated = map->m_len;
4043 map->m_len = allocated;
4044 return allocated;
4047 static int
4048 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4049 struct ext4_map_blocks *map,
4050 struct ext4_ext_path **ppath, int flags,
4051 unsigned int allocated, ext4_fsblk_t newblock)
4053 struct ext4_ext_path *path = *ppath;
4054 int ret = 0;
4055 int err = 0;
4057 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4058 "block %llu, max_blocks %u, flags %x, allocated %u\n",
4059 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4060 flags, allocated);
4061 ext4_ext_show_leaf(inode, path);
4064 * When writing into unwritten space, we should not fail to
4065 * allocate metadata blocks for the new extent block if needed.
4067 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4069 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4070 allocated, newblock);
4072 /* get_block() before submit the IO, split the extent */
4073 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4074 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4075 flags | EXT4_GET_BLOCKS_CONVERT);
4076 if (ret <= 0)
4077 goto out;
4078 map->m_flags |= EXT4_MAP_UNWRITTEN;
4079 goto out;
4081 /* IO end_io complete, convert the filled extent to written */
4082 if (flags & EXT4_GET_BLOCKS_CONVERT) {
4083 if (flags & EXT4_GET_BLOCKS_ZERO) {
4084 if (allocated > map->m_len)
4085 allocated = map->m_len;
4086 err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4087 allocated);
4088 if (err < 0)
4089 goto out2;
4091 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4092 ppath);
4093 if (ret >= 0) {
4094 ext4_update_inode_fsync_trans(handle, inode, 1);
4095 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4096 path, map->m_len);
4097 } else
4098 err = ret;
4099 map->m_flags |= EXT4_MAP_MAPPED;
4100 map->m_pblk = newblock;
4101 if (allocated > map->m_len)
4102 allocated = map->m_len;
4103 map->m_len = allocated;
4104 goto out2;
4106 /* buffered IO case */
4108 * repeat fallocate creation request
4109 * we already have an unwritten extent
4111 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4112 map->m_flags |= EXT4_MAP_UNWRITTEN;
4113 goto map_out;
4116 /* buffered READ or buffered write_begin() lookup */
4117 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4119 * We have blocks reserved already. We
4120 * return allocated blocks so that delalloc
4121 * won't do block reservation for us. But
4122 * the buffer head will be unmapped so that
4123 * a read from the block returns 0s.
4125 map->m_flags |= EXT4_MAP_UNWRITTEN;
4126 goto out1;
4129 /* buffered write, writepage time, convert*/
4130 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4131 if (ret >= 0)
4132 ext4_update_inode_fsync_trans(handle, inode, 1);
4133 out:
4134 if (ret <= 0) {
4135 err = ret;
4136 goto out2;
4137 } else
4138 allocated = ret;
4139 map->m_flags |= EXT4_MAP_NEW;
4141 * if we allocated more blocks than requested
4142 * we need to make sure we unmap the extra block
4143 * allocated. The actual needed block will get
4144 * unmapped later when we find the buffer_head marked
4145 * new.
4147 if (allocated > map->m_len) {
4148 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
4149 newblock + map->m_len,
4150 allocated - map->m_len);
4151 allocated = map->m_len;
4153 map->m_len = allocated;
4156 * If we have done fallocate with the offset that is already
4157 * delayed allocated, we would have block reservation
4158 * and quota reservation done in the delayed write path.
4159 * But fallocate would have already updated quota and block
4160 * count for this offset. So cancel these reservation
4162 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4163 unsigned int reserved_clusters;
4164 reserved_clusters = get_reserved_cluster_alloc(inode,
4165 map->m_lblk, map->m_len);
4166 if (reserved_clusters)
4167 ext4_da_update_reserve_space(inode,
4168 reserved_clusters,
4172 map_out:
4173 map->m_flags |= EXT4_MAP_MAPPED;
4174 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4175 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4176 map->m_len);
4177 if (err < 0)
4178 goto out2;
4180 out1:
4181 if (allocated > map->m_len)
4182 allocated = map->m_len;
4183 ext4_ext_show_leaf(inode, path);
4184 map->m_pblk = newblock;
4185 map->m_len = allocated;
4186 out2:
4187 return err ? err : allocated;
4191 * get_implied_cluster_alloc - check to see if the requested
4192 * allocation (in the map structure) overlaps with a cluster already
4193 * allocated in an extent.
4194 * @sb The filesystem superblock structure
4195 * @map The requested lblk->pblk mapping
4196 * @ex The extent structure which might contain an implied
4197 * cluster allocation
4199 * This function is called by ext4_ext_map_blocks() after we failed to
4200 * find blocks that were already in the inode's extent tree. Hence,
4201 * we know that the beginning of the requested region cannot overlap
4202 * the extent from the inode's extent tree. There are three cases we
4203 * want to catch. The first is this case:
4205 * |--- cluster # N--|
4206 * |--- extent ---| |---- requested region ---|
4207 * |==========|
4209 * The second case that we need to test for is this one:
4211 * |--------- cluster # N ----------------|
4212 * |--- requested region --| |------- extent ----|
4213 * |=======================|
4215 * The third case is when the requested region lies between two extents
4216 * within the same cluster:
4217 * |------------- cluster # N-------------|
4218 * |----- ex -----| |---- ex_right ----|
4219 * |------ requested region ------|
4220 * |================|
4222 * In each of the above cases, we need to set the map->m_pblk and
4223 * map->m_len so it corresponds to the return the extent labelled as
4224 * "|====|" from cluster #N, since it is already in use for data in
4225 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4226 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4227 * as a new "allocated" block region. Otherwise, we will return 0 and
4228 * ext4_ext_map_blocks() will then allocate one or more new clusters
4229 * by calling ext4_mb_new_blocks().
4231 static int get_implied_cluster_alloc(struct super_block *sb,
4232 struct ext4_map_blocks *map,
4233 struct ext4_extent *ex,
4234 struct ext4_ext_path *path)
4236 struct ext4_sb_info *sbi = EXT4_SB(sb);
4237 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4238 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4239 ext4_lblk_t rr_cluster_start;
4240 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4241 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4242 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4244 /* The extent passed in that we are trying to match */
4245 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4246 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4248 /* The requested region passed into ext4_map_blocks() */
4249 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4251 if ((rr_cluster_start == ex_cluster_end) ||
4252 (rr_cluster_start == ex_cluster_start)) {
4253 if (rr_cluster_start == ex_cluster_end)
4254 ee_start += ee_len - 1;
4255 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4256 map->m_len = min(map->m_len,
4257 (unsigned) sbi->s_cluster_ratio - c_offset);
4259 * Check for and handle this case:
4261 * |--------- cluster # N-------------|
4262 * |------- extent ----|
4263 * |--- requested region ---|
4264 * |===========|
4267 if (map->m_lblk < ee_block)
4268 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4271 * Check for the case where there is already another allocated
4272 * block to the right of 'ex' but before the end of the cluster.
4274 * |------------- cluster # N-------------|
4275 * |----- ex -----| |---- ex_right ----|
4276 * |------ requested region ------|
4277 * |================|
4279 if (map->m_lblk > ee_block) {
4280 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4281 map->m_len = min(map->m_len, next - map->m_lblk);
4284 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4285 return 1;
4288 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4289 return 0;
4294 * Block allocation/map/preallocation routine for extents based files
4297 * Need to be called with
4298 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4299 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4301 * return > 0, number of of blocks already mapped/allocated
4302 * if create == 0 and these are pre-allocated blocks
4303 * buffer head is unmapped
4304 * otherwise blocks are mapped
4306 * return = 0, if plain look up failed (blocks have not been allocated)
4307 * buffer head is unmapped
4309 * return < 0, error case.
4311 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4312 struct ext4_map_blocks *map, int flags)
4314 struct ext4_ext_path *path = NULL;
4315 struct ext4_extent newex, *ex, *ex2;
4316 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4317 ext4_fsblk_t newblock = 0;
4318 int free_on_err = 0, err = 0, depth, ret;
4319 unsigned int allocated = 0, offset = 0;
4320 unsigned int allocated_clusters = 0;
4321 struct ext4_allocation_request ar;
4322 ext4_lblk_t cluster_offset;
4323 bool map_from_cluster = false;
4325 ext_debug("blocks %u/%u requested for inode %lu\n",
4326 map->m_lblk, map->m_len, inode->i_ino);
4327 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4329 /* find extent for this block */
4330 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4331 if (IS_ERR(path)) {
4332 err = PTR_ERR(path);
4333 path = NULL;
4334 goto out2;
4337 depth = ext_depth(inode);
4340 * consistent leaf must not be empty;
4341 * this situation is possible, though, _during_ tree modification;
4342 * this is why assert can't be put in ext4_find_extent()
4344 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4345 EXT4_ERROR_INODE(inode, "bad extent address "
4346 "lblock: %lu, depth: %d pblock %lld",
4347 (unsigned long) map->m_lblk, depth,
4348 path[depth].p_block);
4349 err = -EFSCORRUPTED;
4350 goto out2;
4353 ex = path[depth].p_ext;
4354 if (ex) {
4355 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4356 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4357 unsigned short ee_len;
4361 * unwritten extents are treated as holes, except that
4362 * we split out initialized portions during a write.
4364 ee_len = ext4_ext_get_actual_len(ex);
4366 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4368 /* if found extent covers block, simply return it */
4369 if (in_range(map->m_lblk, ee_block, ee_len)) {
4370 newblock = map->m_lblk - ee_block + ee_start;
4371 /* number of remaining blocks in the extent */
4372 allocated = ee_len - (map->m_lblk - ee_block);
4373 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4374 ee_block, ee_len, newblock);
4377 * If the extent is initialized check whether the
4378 * caller wants to convert it to unwritten.
4380 if ((!ext4_ext_is_unwritten(ex)) &&
4381 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4382 allocated = convert_initialized_extent(
4383 handle, inode, map, &path,
4384 allocated);
4385 goto out2;
4386 } else if (!ext4_ext_is_unwritten(ex))
4387 goto out;
4389 ret = ext4_ext_handle_unwritten_extents(
4390 handle, inode, map, &path, flags,
4391 allocated, newblock);
4392 if (ret < 0)
4393 err = ret;
4394 else
4395 allocated = ret;
4396 goto out2;
4401 * requested block isn't allocated yet;
4402 * we couldn't try to create block if create flag is zero
4404 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4405 ext4_lblk_t hole_start, hole_len;
4407 hole_start = map->m_lblk;
4408 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4410 * put just found gap into cache to speed up
4411 * subsequent requests
4413 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4415 /* Update hole_len to reflect hole size after map->m_lblk */
4416 if (hole_start != map->m_lblk)
4417 hole_len -= map->m_lblk - hole_start;
4418 map->m_pblk = 0;
4419 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4421 goto out2;
4425 * Okay, we need to do block allocation.
4427 newex.ee_block = cpu_to_le32(map->m_lblk);
4428 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4431 * If we are doing bigalloc, check to see if the extent returned
4432 * by ext4_find_extent() implies a cluster we can use.
4434 if (cluster_offset && ex &&
4435 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4436 ar.len = allocated = map->m_len;
4437 newblock = map->m_pblk;
4438 map_from_cluster = true;
4439 goto got_allocated_blocks;
4442 /* find neighbour allocated blocks */
4443 ar.lleft = map->m_lblk;
4444 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4445 if (err)
4446 goto out2;
4447 ar.lright = map->m_lblk;
4448 ex2 = NULL;
4449 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4450 if (err)
4451 goto out2;
4453 /* Check if the extent after searching to the right implies a
4454 * cluster we can use. */
4455 if ((sbi->s_cluster_ratio > 1) && ex2 &&
4456 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4457 ar.len = allocated = map->m_len;
4458 newblock = map->m_pblk;
4459 map_from_cluster = true;
4460 goto got_allocated_blocks;
4464 * See if request is beyond maximum number of blocks we can have in
4465 * a single extent. For an initialized extent this limit is
4466 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4467 * EXT_UNWRITTEN_MAX_LEN.
4469 if (map->m_len > EXT_INIT_MAX_LEN &&
4470 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4471 map->m_len = EXT_INIT_MAX_LEN;
4472 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4473 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4474 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4476 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4477 newex.ee_len = cpu_to_le16(map->m_len);
4478 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4479 if (err)
4480 allocated = ext4_ext_get_actual_len(&newex);
4481 else
4482 allocated = map->m_len;
4484 /* allocate new block */
4485 ar.inode = inode;
4486 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4487 ar.logical = map->m_lblk;
4489 * We calculate the offset from the beginning of the cluster
4490 * for the logical block number, since when we allocate a
4491 * physical cluster, the physical block should start at the
4492 * same offset from the beginning of the cluster. This is
4493 * needed so that future calls to get_implied_cluster_alloc()
4494 * work correctly.
4496 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4497 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4498 ar.goal -= offset;
4499 ar.logical -= offset;
4500 if (S_ISREG(inode->i_mode))
4501 ar.flags = EXT4_MB_HINT_DATA;
4502 else
4503 /* disable in-core preallocation for non-regular files */
4504 ar.flags = 0;
4505 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4506 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4507 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4508 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4509 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4510 ar.flags |= EXT4_MB_USE_RESERVED;
4511 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4512 if (!newblock)
4513 goto out2;
4514 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4515 ar.goal, newblock, allocated);
4516 free_on_err = 1;
4517 allocated_clusters = ar.len;
4518 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4519 if (ar.len > allocated)
4520 ar.len = allocated;
4522 got_allocated_blocks:
4523 /* try to insert new extent into found leaf and return */
4524 ext4_ext_store_pblock(&newex, newblock + offset);
4525 newex.ee_len = cpu_to_le16(ar.len);
4526 /* Mark unwritten */
4527 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4528 ext4_ext_mark_unwritten(&newex);
4529 map->m_flags |= EXT4_MAP_UNWRITTEN;
4532 err = 0;
4533 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4534 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4535 path, ar.len);
4536 if (!err)
4537 err = ext4_ext_insert_extent(handle, inode, &path,
4538 &newex, flags);
4540 if (err && free_on_err) {
4541 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4542 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4543 /* free data blocks we just allocated */
4544 /* not a good idea to call discard here directly,
4545 * but otherwise we'd need to call it every free() */
4546 ext4_discard_preallocations(inode);
4547 ext4_free_blocks(handle, inode, NULL, newblock,
4548 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4549 goto out2;
4552 /* previous routine could use block we allocated */
4553 newblock = ext4_ext_pblock(&newex);
4554 allocated = ext4_ext_get_actual_len(&newex);
4555 if (allocated > map->m_len)
4556 allocated = map->m_len;
4557 map->m_flags |= EXT4_MAP_NEW;
4560 * Update reserved blocks/metadata blocks after successful
4561 * block allocation which had been deferred till now.
4563 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4564 unsigned int reserved_clusters;
4566 * Check how many clusters we had reserved this allocated range
4568 reserved_clusters = get_reserved_cluster_alloc(inode,
4569 map->m_lblk, allocated);
4570 if (!map_from_cluster) {
4571 BUG_ON(allocated_clusters < reserved_clusters);
4572 if (reserved_clusters < allocated_clusters) {
4573 struct ext4_inode_info *ei = EXT4_I(inode);
4574 int reservation = allocated_clusters -
4575 reserved_clusters;
4577 * It seems we claimed few clusters outside of
4578 * the range of this allocation. We should give
4579 * it back to the reservation pool. This can
4580 * happen in the following case:
4582 * * Suppose s_cluster_ratio is 4 (i.e., each
4583 * cluster has 4 blocks. Thus, the clusters
4584 * are [0-3],[4-7],[8-11]...
4585 * * First comes delayed allocation write for
4586 * logical blocks 10 & 11. Since there were no
4587 * previous delayed allocated blocks in the
4588 * range [8-11], we would reserve 1 cluster
4589 * for this write.
4590 * * Next comes write for logical blocks 3 to 8.
4591 * In this case, we will reserve 2 clusters
4592 * (for [0-3] and [4-7]; and not for [8-11] as
4593 * that range has a delayed allocated blocks.
4594 * Thus total reserved clusters now becomes 3.
4595 * * Now, during the delayed allocation writeout
4596 * time, we will first write blocks [3-8] and
4597 * allocate 3 clusters for writing these
4598 * blocks. Also, we would claim all these
4599 * three clusters above.
4600 * * Now when we come here to writeout the
4601 * blocks [10-11], we would expect to claim
4602 * the reservation of 1 cluster we had made
4603 * (and we would claim it since there are no
4604 * more delayed allocated blocks in the range
4605 * [8-11]. But our reserved cluster count had
4606 * already gone to 0.
4608 * Thus, at the step 4 above when we determine
4609 * that there are still some unwritten delayed
4610 * allocated blocks outside of our current
4611 * block range, we should increment the
4612 * reserved clusters count so that when the
4613 * remaining blocks finally gets written, we
4614 * could claim them.
4616 dquot_reserve_block(inode,
4617 EXT4_C2B(sbi, reservation));
4618 spin_lock(&ei->i_block_reservation_lock);
4619 ei->i_reserved_data_blocks += reservation;
4620 spin_unlock(&ei->i_block_reservation_lock);
4623 * We will claim quota for all newly allocated blocks.
4624 * We're updating the reserved space *after* the
4625 * correction above so we do not accidentally free
4626 * all the metadata reservation because we might
4627 * actually need it later on.
4629 ext4_da_update_reserve_space(inode, allocated_clusters,
4635 * Cache the extent and update transaction to commit on fdatasync only
4636 * when it is _not_ an unwritten extent.
4638 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4639 ext4_update_inode_fsync_trans(handle, inode, 1);
4640 else
4641 ext4_update_inode_fsync_trans(handle, inode, 0);
4642 out:
4643 if (allocated > map->m_len)
4644 allocated = map->m_len;
4645 ext4_ext_show_leaf(inode, path);
4646 map->m_flags |= EXT4_MAP_MAPPED;
4647 map->m_pblk = newblock;
4648 map->m_len = allocated;
4649 out2:
4650 ext4_ext_drop_refs(path);
4651 kfree(path);
4653 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4654 err ? err : allocated);
4655 return err ? err : allocated;
4658 void ext4_ext_truncate(handle_t *handle, struct inode *inode)
4660 struct super_block *sb = inode->i_sb;
4661 ext4_lblk_t last_block;
4662 int err = 0;
4665 * TODO: optimization is possible here.
4666 * Probably we need not scan at all,
4667 * because page truncation is enough.
4670 /* we have to know where to truncate from in crash case */
4671 EXT4_I(inode)->i_disksize = inode->i_size;
4672 ext4_mark_inode_dirty(handle, inode);
4674 last_block = (inode->i_size + sb->s_blocksize - 1)
4675 >> EXT4_BLOCK_SIZE_BITS(sb);
4676 retry:
4677 err = ext4_es_remove_extent(inode, last_block,
4678 EXT_MAX_BLOCKS - last_block);
4679 if (err == -ENOMEM) {
4680 cond_resched();
4681 congestion_wait(BLK_RW_ASYNC, HZ/50);
4682 goto retry;
4684 if (err) {
4685 ext4_std_error(inode->i_sb, err);
4686 return;
4688 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4689 ext4_std_error(inode->i_sb, err);
4692 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4693 ext4_lblk_t len, loff_t new_size,
4694 int flags, int mode)
4696 struct inode *inode = file_inode(file);
4697 handle_t *handle;
4698 int ret = 0;
4699 int ret2 = 0;
4700 int retries = 0;
4701 int depth = 0;
4702 struct ext4_map_blocks map;
4703 unsigned int credits;
4704 loff_t epos;
4706 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4707 map.m_lblk = offset;
4708 map.m_len = len;
4710 * Don't normalize the request if it can fit in one extent so
4711 * that it doesn't get unnecessarily split into multiple
4712 * extents.
4714 if (len <= EXT_UNWRITTEN_MAX_LEN)
4715 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4718 * credits to insert 1 extent into extent tree
4720 credits = ext4_chunk_trans_blocks(inode, len);
4721 depth = ext_depth(inode);
4723 retry:
4724 while (ret >= 0 && len) {
4726 * Recalculate credits when extent tree depth changes.
4728 if (depth >= 0 && depth != ext_depth(inode)) {
4729 credits = ext4_chunk_trans_blocks(inode, len);
4730 depth = ext_depth(inode);
4733 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4734 credits);
4735 if (IS_ERR(handle)) {
4736 ret = PTR_ERR(handle);
4737 break;
4739 ret = ext4_map_blocks(handle, inode, &map, flags);
4740 if (ret <= 0) {
4741 ext4_debug("inode #%lu: block %u: len %u: "
4742 "ext4_ext_map_blocks returned %d",
4743 inode->i_ino, map.m_lblk,
4744 map.m_len, ret);
4745 ext4_mark_inode_dirty(handle, inode);
4746 ret2 = ext4_journal_stop(handle);
4747 break;
4749 map.m_lblk += ret;
4750 map.m_len = len = len - ret;
4751 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4752 inode->i_ctime = ext4_current_time(inode);
4753 if (new_size) {
4754 if (epos > new_size)
4755 epos = new_size;
4756 if (ext4_update_inode_size(inode, epos) & 0x1)
4757 inode->i_mtime = inode->i_ctime;
4758 } else {
4759 if (epos > inode->i_size)
4760 ext4_set_inode_flag(inode,
4761 EXT4_INODE_EOFBLOCKS);
4763 ext4_mark_inode_dirty(handle, inode);
4764 ext4_update_inode_fsync_trans(handle, inode, 1);
4765 ret2 = ext4_journal_stop(handle);
4766 if (ret2)
4767 break;
4769 if (ret == -ENOSPC &&
4770 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4771 ret = 0;
4772 goto retry;
4775 return ret > 0 ? ret2 : ret;
4778 static long ext4_zero_range(struct file *file, loff_t offset,
4779 loff_t len, int mode)
4781 struct inode *inode = file_inode(file);
4782 handle_t *handle = NULL;
4783 unsigned int max_blocks;
4784 loff_t new_size = 0;
4785 int ret = 0;
4786 int flags;
4787 int credits;
4788 int partial_begin, partial_end;
4789 loff_t start, end;
4790 ext4_lblk_t lblk;
4791 unsigned int blkbits = inode->i_blkbits;
4793 trace_ext4_zero_range(inode, offset, len, mode);
4795 if (!S_ISREG(inode->i_mode))
4796 return -EINVAL;
4798 /* Call ext4_force_commit to flush all data in case of data=journal. */
4799 if (ext4_should_journal_data(inode)) {
4800 ret = ext4_force_commit(inode->i_sb);
4801 if (ret)
4802 return ret;
4806 * Round up offset. This is not fallocate, we neet to zero out
4807 * blocks, so convert interior block aligned part of the range to
4808 * unwritten and possibly manually zero out unaligned parts of the
4809 * range.
4811 start = round_up(offset, 1 << blkbits);
4812 end = round_down((offset + len), 1 << blkbits);
4814 if (start < offset || end > offset + len)
4815 return -EINVAL;
4816 partial_begin = offset & ((1 << blkbits) - 1);
4817 partial_end = (offset + len) & ((1 << blkbits) - 1);
4819 lblk = start >> blkbits;
4820 max_blocks = (end >> blkbits);
4821 if (max_blocks < lblk)
4822 max_blocks = 0;
4823 else
4824 max_blocks -= lblk;
4826 inode_lock(inode);
4829 * Indirect files do not support unwritten extnets
4831 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4832 ret = -EOPNOTSUPP;
4833 goto out_mutex;
4836 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4837 (offset + len > i_size_read(inode) ||
4838 offset + len > EXT4_I(inode)->i_disksize)) {
4839 new_size = offset + len;
4840 ret = inode_newsize_ok(inode, new_size);
4841 if (ret)
4842 goto out_mutex;
4845 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4846 if (mode & FALLOC_FL_KEEP_SIZE)
4847 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4849 /* Wait all existing dio workers, newcomers will block on i_mutex */
4850 ext4_inode_block_unlocked_dio(inode);
4851 inode_dio_wait(inode);
4853 /* Preallocate the range including the unaligned edges */
4854 if (partial_begin || partial_end) {
4855 ret = ext4_alloc_file_blocks(file,
4856 round_down(offset, 1 << blkbits) >> blkbits,
4857 (round_up((offset + len), 1 << blkbits) -
4858 round_down(offset, 1 << blkbits)) >> blkbits,
4859 new_size, flags, mode);
4860 if (ret)
4861 goto out_dio;
4865 /* Zero range excluding the unaligned edges */
4866 if (max_blocks > 0) {
4867 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4868 EXT4_EX_NOCACHE);
4871 * Prevent page faults from reinstantiating pages we have
4872 * released from page cache.
4874 down_write(&EXT4_I(inode)->i_mmap_sem);
4875 ret = ext4_update_disksize_before_punch(inode, offset, len);
4876 if (ret) {
4877 up_write(&EXT4_I(inode)->i_mmap_sem);
4878 goto out_dio;
4880 /* Now release the pages and zero block aligned part of pages */
4881 truncate_pagecache_range(inode, start, end - 1);
4882 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4884 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4885 flags, mode);
4886 up_write(&EXT4_I(inode)->i_mmap_sem);
4887 if (ret)
4888 goto out_dio;
4890 if (!partial_begin && !partial_end)
4891 goto out_dio;
4894 * In worst case we have to writeout two nonadjacent unwritten
4895 * blocks and update the inode
4897 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4898 if (ext4_should_journal_data(inode))
4899 credits += 2;
4900 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4901 if (IS_ERR(handle)) {
4902 ret = PTR_ERR(handle);
4903 ext4_std_error(inode->i_sb, ret);
4904 goto out_dio;
4907 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4908 if (new_size) {
4909 ext4_update_inode_size(inode, new_size);
4910 } else {
4912 * Mark that we allocate beyond EOF so the subsequent truncate
4913 * can proceed even if the new size is the same as i_size.
4915 if ((offset + len) > i_size_read(inode))
4916 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4918 ext4_mark_inode_dirty(handle, inode);
4920 /* Zero out partial block at the edges of the range */
4921 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4922 if (ret >= 0)
4923 ext4_update_inode_fsync_trans(handle, inode, 1);
4925 if (file->f_flags & O_SYNC)
4926 ext4_handle_sync(handle);
4928 ext4_journal_stop(handle);
4929 out_dio:
4930 ext4_inode_resume_unlocked_dio(inode);
4931 out_mutex:
4932 inode_unlock(inode);
4933 return ret;
4937 * preallocate space for a file. This implements ext4's fallocate file
4938 * operation, which gets called from sys_fallocate system call.
4939 * For block-mapped files, posix_fallocate should fall back to the method
4940 * of writing zeroes to the required new blocks (the same behavior which is
4941 * expected for file systems which do not support fallocate() system call).
4943 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4945 struct inode *inode = file_inode(file);
4946 loff_t new_size = 0;
4947 unsigned int max_blocks;
4948 int ret = 0;
4949 int flags;
4950 ext4_lblk_t lblk;
4951 unsigned int blkbits = inode->i_blkbits;
4954 * Encrypted inodes can't handle collapse range or insert
4955 * range since we would need to re-encrypt blocks with a
4956 * different IV or XTS tweak (which are based on the logical
4957 * block number).
4959 * XXX It's not clear why zero range isn't working, but we'll
4960 * leave it disabled for encrypted inodes for now. This is a
4961 * bug we should fix....
4963 if (ext4_encrypted_inode(inode) &&
4964 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
4965 FALLOC_FL_ZERO_RANGE)))
4966 return -EOPNOTSUPP;
4968 /* Return error if mode is not supported */
4969 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4970 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4971 FALLOC_FL_INSERT_RANGE))
4972 return -EOPNOTSUPP;
4974 if (mode & FALLOC_FL_PUNCH_HOLE)
4975 return ext4_punch_hole(inode, offset, len);
4977 ret = ext4_convert_inline_data(inode);
4978 if (ret)
4979 return ret;
4981 if (mode & FALLOC_FL_COLLAPSE_RANGE)
4982 return ext4_collapse_range(inode, offset, len);
4984 if (mode & FALLOC_FL_INSERT_RANGE)
4985 return ext4_insert_range(inode, offset, len);
4987 if (mode & FALLOC_FL_ZERO_RANGE)
4988 return ext4_zero_range(file, offset, len, mode);
4990 trace_ext4_fallocate_enter(inode, offset, len, mode);
4991 lblk = offset >> blkbits;
4993 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4994 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4995 if (mode & FALLOC_FL_KEEP_SIZE)
4996 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4998 inode_lock(inode);
5001 * We only support preallocation for extent-based files only
5003 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5004 ret = -EOPNOTSUPP;
5005 goto out;
5008 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
5009 (offset + len > i_size_read(inode) ||
5010 offset + len > EXT4_I(inode)->i_disksize)) {
5011 new_size = offset + len;
5012 ret = inode_newsize_ok(inode, new_size);
5013 if (ret)
5014 goto out;
5017 /* Wait all existing dio workers, newcomers will block on i_mutex */
5018 ext4_inode_block_unlocked_dio(inode);
5019 inode_dio_wait(inode);
5021 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
5022 flags, mode);
5023 ext4_inode_resume_unlocked_dio(inode);
5024 if (ret)
5025 goto out;
5027 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
5028 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5029 EXT4_I(inode)->i_sync_tid);
5031 out:
5032 inode_unlock(inode);
5033 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
5034 return ret;
5038 * This function convert a range of blocks to written extents
5039 * The caller of this function will pass the start offset and the size.
5040 * all unwritten extents within this range will be converted to
5041 * written extents.
5043 * This function is called from the direct IO end io call back
5044 * function, to convert the fallocated extents after IO is completed.
5045 * Returns 0 on success.
5047 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
5048 loff_t offset, ssize_t len)
5050 unsigned int max_blocks;
5051 int ret = 0;
5052 int ret2 = 0;
5053 struct ext4_map_blocks map;
5054 unsigned int credits, blkbits = inode->i_blkbits;
5056 map.m_lblk = offset >> blkbits;
5057 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
5060 * This is somewhat ugly but the idea is clear: When transaction is
5061 * reserved, everything goes into it. Otherwise we rather start several
5062 * smaller transactions for conversion of each extent separately.
5064 if (handle) {
5065 handle = ext4_journal_start_reserved(handle,
5066 EXT4_HT_EXT_CONVERT);
5067 if (IS_ERR(handle))
5068 return PTR_ERR(handle);
5069 credits = 0;
5070 } else {
5072 * credits to insert 1 extent into extent tree
5074 credits = ext4_chunk_trans_blocks(inode, max_blocks);
5076 while (ret >= 0 && ret < max_blocks) {
5077 map.m_lblk += ret;
5078 map.m_len = (max_blocks -= ret);
5079 if (credits) {
5080 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5081 credits);
5082 if (IS_ERR(handle)) {
5083 ret = PTR_ERR(handle);
5084 break;
5087 ret = ext4_map_blocks(handle, inode, &map,
5088 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5089 if (ret <= 0)
5090 ext4_warning(inode->i_sb,
5091 "inode #%lu: block %u: len %u: "
5092 "ext4_ext_map_blocks returned %d",
5093 inode->i_ino, map.m_lblk,
5094 map.m_len, ret);
5095 ext4_mark_inode_dirty(handle, inode);
5096 if (credits)
5097 ret2 = ext4_journal_stop(handle);
5098 if (ret <= 0 || ret2)
5099 break;
5101 if (!credits)
5102 ret2 = ext4_journal_stop(handle);
5103 return ret > 0 ? ret2 : ret;
5107 * If newes is not existing extent (newes->ec_pblk equals zero) find
5108 * delayed extent at start of newes and update newes accordingly and
5109 * return start of the next delayed extent.
5111 * If newes is existing extent (newes->ec_pblk is not equal zero)
5112 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5113 * extent found. Leave newes unmodified.
5115 static int ext4_find_delayed_extent(struct inode *inode,
5116 struct extent_status *newes)
5118 struct extent_status es;
5119 ext4_lblk_t block, next_del;
5121 if (newes->es_pblk == 0) {
5122 ext4_es_find_delayed_extent_range(inode, newes->es_lblk,
5123 newes->es_lblk + newes->es_len - 1, &es);
5126 * No extent in extent-tree contains block @newes->es_pblk,
5127 * then the block may stay in 1)a hole or 2)delayed-extent.
5129 if (es.es_len == 0)
5130 /* A hole found. */
5131 return 0;
5133 if (es.es_lblk > newes->es_lblk) {
5134 /* A hole found. */
5135 newes->es_len = min(es.es_lblk - newes->es_lblk,
5136 newes->es_len);
5137 return 0;
5140 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5143 block = newes->es_lblk + newes->es_len;
5144 ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es);
5145 if (es.es_len == 0)
5146 next_del = EXT_MAX_BLOCKS;
5147 else
5148 next_del = es.es_lblk;
5150 return next_del;
5152 /* fiemap flags we can handle specified here */
5153 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
5155 static int ext4_xattr_fiemap(struct inode *inode,
5156 struct fiemap_extent_info *fieinfo)
5158 __u64 physical = 0;
5159 __u64 length;
5160 __u32 flags = FIEMAP_EXTENT_LAST;
5161 int blockbits = inode->i_sb->s_blocksize_bits;
5162 int error = 0;
5164 /* in-inode? */
5165 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5166 struct ext4_iloc iloc;
5167 int offset; /* offset of xattr in inode */
5169 error = ext4_get_inode_loc(inode, &iloc);
5170 if (error)
5171 return error;
5172 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5173 offset = EXT4_GOOD_OLD_INODE_SIZE +
5174 EXT4_I(inode)->i_extra_isize;
5175 physical += offset;
5176 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5177 flags |= FIEMAP_EXTENT_DATA_INLINE;
5178 brelse(iloc.bh);
5179 } else { /* external block */
5180 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5181 length = inode->i_sb->s_blocksize;
5184 if (physical)
5185 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5186 length, flags);
5187 return (error < 0 ? error : 0);
5190 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5191 __u64 start, __u64 len)
5193 ext4_lblk_t start_blk;
5194 int error = 0;
5196 if (ext4_has_inline_data(inode)) {
5197 int has_inline = 1;
5199 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5200 start, len);
5202 if (has_inline)
5203 return error;
5206 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5207 error = ext4_ext_precache(inode);
5208 if (error)
5209 return error;
5212 /* fallback to generic here if not in extents fmt */
5213 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5214 return generic_block_fiemap(inode, fieinfo, start, len,
5215 ext4_get_block);
5217 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
5218 return -EBADR;
5220 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5221 error = ext4_xattr_fiemap(inode, fieinfo);
5222 } else {
5223 ext4_lblk_t len_blks;
5224 __u64 last_blk;
5226 start_blk = start >> inode->i_sb->s_blocksize_bits;
5227 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5228 if (last_blk >= EXT_MAX_BLOCKS)
5229 last_blk = EXT_MAX_BLOCKS-1;
5230 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5233 * Walk the extent tree gathering extent information
5234 * and pushing extents back to the user.
5236 error = ext4_fill_fiemap_extents(inode, start_blk,
5237 len_blks, fieinfo);
5239 return error;
5243 * ext4_access_path:
5244 * Function to access the path buffer for marking it dirty.
5245 * It also checks if there are sufficient credits left in the journal handle
5246 * to update path.
5248 static int
5249 ext4_access_path(handle_t *handle, struct inode *inode,
5250 struct ext4_ext_path *path)
5252 int credits, err;
5254 if (!ext4_handle_valid(handle))
5255 return 0;
5258 * Check if need to extend journal credits
5259 * 3 for leaf, sb, and inode plus 2 (bmap and group
5260 * descriptor) for each block group; assume two block
5261 * groups
5263 if (handle->h_buffer_credits < 7) {
5264 credits = ext4_writepage_trans_blocks(inode);
5265 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
5266 /* EAGAIN is success */
5267 if (err && err != -EAGAIN)
5268 return err;
5271 err = ext4_ext_get_access(handle, inode, path);
5272 return err;
5276 * ext4_ext_shift_path_extents:
5277 * Shift the extents of a path structure lying between path[depth].p_ext
5278 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5279 * if it is right shift or left shift operation.
5281 static int
5282 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5283 struct inode *inode, handle_t *handle,
5284 enum SHIFT_DIRECTION SHIFT)
5286 int depth, err = 0;
5287 struct ext4_extent *ex_start, *ex_last;
5288 bool update = 0;
5289 depth = path->p_depth;
5291 while (depth >= 0) {
5292 if (depth == path->p_depth) {
5293 ex_start = path[depth].p_ext;
5294 if (!ex_start)
5295 return -EFSCORRUPTED;
5297 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5299 err = ext4_access_path(handle, inode, path + depth);
5300 if (err)
5301 goto out;
5303 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5304 update = 1;
5306 while (ex_start <= ex_last) {
5307 if (SHIFT == SHIFT_LEFT) {
5308 le32_add_cpu(&ex_start->ee_block,
5309 -shift);
5310 /* Try to merge to the left. */
5311 if ((ex_start >
5312 EXT_FIRST_EXTENT(path[depth].p_hdr))
5314 ext4_ext_try_to_merge_right(inode,
5315 path, ex_start - 1))
5316 ex_last--;
5317 else
5318 ex_start++;
5319 } else {
5320 le32_add_cpu(&ex_last->ee_block, shift);
5321 ext4_ext_try_to_merge_right(inode, path,
5322 ex_last);
5323 ex_last--;
5326 err = ext4_ext_dirty(handle, inode, path + depth);
5327 if (err)
5328 goto out;
5330 if (--depth < 0 || !update)
5331 break;
5334 /* Update index too */
5335 err = ext4_access_path(handle, inode, path + depth);
5336 if (err)
5337 goto out;
5339 if (SHIFT == SHIFT_LEFT)
5340 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5341 else
5342 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5343 err = ext4_ext_dirty(handle, inode, path + depth);
5344 if (err)
5345 goto out;
5347 /* we are done if current index is not a starting index */
5348 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5349 break;
5351 depth--;
5354 out:
5355 return err;
5359 * ext4_ext_shift_extents:
5360 * All the extents which lies in the range from @start to the last allocated
5361 * block for the @inode are shifted either towards left or right (depending
5362 * upon @SHIFT) by @shift blocks.
5363 * On success, 0 is returned, error otherwise.
5365 static int
5366 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5367 ext4_lblk_t start, ext4_lblk_t shift,
5368 enum SHIFT_DIRECTION SHIFT)
5370 struct ext4_ext_path *path;
5371 int ret = 0, depth;
5372 struct ext4_extent *extent;
5373 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5375 /* Let path point to the last extent */
5376 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5377 EXT4_EX_NOCACHE);
5378 if (IS_ERR(path))
5379 return PTR_ERR(path);
5381 depth = path->p_depth;
5382 extent = path[depth].p_ext;
5383 if (!extent)
5384 goto out;
5386 stop = le32_to_cpu(extent->ee_block);
5389 * For left shifts, make sure the hole on the left is big enough to
5390 * accommodate the shift. For right shifts, make sure the last extent
5391 * won't be shifted beyond EXT_MAX_BLOCKS.
5393 if (SHIFT == SHIFT_LEFT) {
5394 path = ext4_find_extent(inode, start - 1, &path,
5395 EXT4_EX_NOCACHE);
5396 if (IS_ERR(path))
5397 return PTR_ERR(path);
5398 depth = path->p_depth;
5399 extent = path[depth].p_ext;
5400 if (extent) {
5401 ex_start = le32_to_cpu(extent->ee_block);
5402 ex_end = le32_to_cpu(extent->ee_block) +
5403 ext4_ext_get_actual_len(extent);
5404 } else {
5405 ex_start = 0;
5406 ex_end = 0;
5409 if ((start == ex_start && shift > ex_start) ||
5410 (shift > start - ex_end)) {
5411 ret = -EINVAL;
5412 goto out;
5414 } else {
5415 if (shift > EXT_MAX_BLOCKS -
5416 (stop + ext4_ext_get_actual_len(extent))) {
5417 ret = -EINVAL;
5418 goto out;
5423 * In case of left shift, iterator points to start and it is increased
5424 * till we reach stop. In case of right shift, iterator points to stop
5425 * and it is decreased till we reach start.
5427 if (SHIFT == SHIFT_LEFT)
5428 iterator = &start;
5429 else
5430 iterator = &stop;
5433 * Its safe to start updating extents. Start and stop are unsigned, so
5434 * in case of right shift if extent with 0 block is reached, iterator
5435 * becomes NULL to indicate the end of the loop.
5437 while (iterator && start <= stop) {
5438 path = ext4_find_extent(inode, *iterator, &path,
5439 EXT4_EX_NOCACHE);
5440 if (IS_ERR(path))
5441 return PTR_ERR(path);
5442 depth = path->p_depth;
5443 extent = path[depth].p_ext;
5444 if (!extent) {
5445 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5446 (unsigned long) *iterator);
5447 return -EFSCORRUPTED;
5449 if (SHIFT == SHIFT_LEFT && *iterator >
5450 le32_to_cpu(extent->ee_block)) {
5451 /* Hole, move to the next extent */
5452 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5453 path[depth].p_ext++;
5454 } else {
5455 *iterator = ext4_ext_next_allocated_block(path);
5456 continue;
5460 if (SHIFT == SHIFT_LEFT) {
5461 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5462 *iterator = le32_to_cpu(extent->ee_block) +
5463 ext4_ext_get_actual_len(extent);
5464 } else {
5465 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5466 if (le32_to_cpu(extent->ee_block) > 0)
5467 *iterator = le32_to_cpu(extent->ee_block) - 1;
5468 else
5469 /* Beginning is reached, end of the loop */
5470 iterator = NULL;
5471 /* Update path extent in case we need to stop */
5472 while (le32_to_cpu(extent->ee_block) < start)
5473 extent++;
5474 path[depth].p_ext = extent;
5476 ret = ext4_ext_shift_path_extents(path, shift, inode,
5477 handle, SHIFT);
5478 if (ret)
5479 break;
5481 out:
5482 ext4_ext_drop_refs(path);
5483 kfree(path);
5484 return ret;
5488 * ext4_collapse_range:
5489 * This implements the fallocate's collapse range functionality for ext4
5490 * Returns: 0 and non-zero on error.
5492 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5494 struct super_block *sb = inode->i_sb;
5495 ext4_lblk_t punch_start, punch_stop;
5496 handle_t *handle;
5497 unsigned int credits;
5498 loff_t new_size, ioffset;
5499 int ret;
5502 * We need to test this early because xfstests assumes that a
5503 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5504 * system does not support collapse range.
5506 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5507 return -EOPNOTSUPP;
5509 /* Collapse range works only on fs block size aligned offsets. */
5510 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5511 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5512 return -EINVAL;
5514 if (!S_ISREG(inode->i_mode))
5515 return -EINVAL;
5517 trace_ext4_collapse_range(inode, offset, len);
5519 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5520 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5522 /* Call ext4_force_commit to flush all data in case of data=journal. */
5523 if (ext4_should_journal_data(inode)) {
5524 ret = ext4_force_commit(inode->i_sb);
5525 if (ret)
5526 return ret;
5529 inode_lock(inode);
5531 * There is no need to overlap collapse range with EOF, in which case
5532 * it is effectively a truncate operation
5534 if (offset + len >= i_size_read(inode)) {
5535 ret = -EINVAL;
5536 goto out_mutex;
5539 /* Currently just for extent based files */
5540 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5541 ret = -EOPNOTSUPP;
5542 goto out_mutex;
5545 /* Wait for existing dio to complete */
5546 ext4_inode_block_unlocked_dio(inode);
5547 inode_dio_wait(inode);
5550 * Prevent page faults from reinstantiating pages we have released from
5551 * page cache.
5553 down_write(&EXT4_I(inode)->i_mmap_sem);
5555 * Need to round down offset to be aligned with page size boundary
5556 * for page size > block size.
5558 ioffset = round_down(offset, PAGE_SIZE);
5560 * Write tail of the last page before removed range since it will get
5561 * removed from the page cache below.
5563 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5564 if (ret)
5565 goto out_mmap;
5567 * Write data that will be shifted to preserve them when discarding
5568 * page cache below. We are also protected from pages becoming dirty
5569 * by i_mmap_sem.
5571 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5572 LLONG_MAX);
5573 if (ret)
5574 goto out_mmap;
5575 truncate_pagecache(inode, ioffset);
5577 credits = ext4_writepage_trans_blocks(inode);
5578 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5579 if (IS_ERR(handle)) {
5580 ret = PTR_ERR(handle);
5581 goto out_mmap;
5584 down_write(&EXT4_I(inode)->i_data_sem);
5585 ext4_discard_preallocations(inode);
5587 ret = ext4_es_remove_extent(inode, punch_start,
5588 EXT_MAX_BLOCKS - punch_start);
5589 if (ret) {
5590 up_write(&EXT4_I(inode)->i_data_sem);
5591 goto out_stop;
5594 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5595 if (ret) {
5596 up_write(&EXT4_I(inode)->i_data_sem);
5597 goto out_stop;
5599 ext4_discard_preallocations(inode);
5601 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5602 punch_stop - punch_start, SHIFT_LEFT);
5603 if (ret) {
5604 up_write(&EXT4_I(inode)->i_data_sem);
5605 goto out_stop;
5608 new_size = i_size_read(inode) - len;
5609 i_size_write(inode, new_size);
5610 EXT4_I(inode)->i_disksize = new_size;
5612 up_write(&EXT4_I(inode)->i_data_sem);
5613 if (IS_SYNC(inode))
5614 ext4_handle_sync(handle);
5615 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5616 ext4_mark_inode_dirty(handle, inode);
5617 ext4_update_inode_fsync_trans(handle, inode, 1);
5619 out_stop:
5620 ext4_journal_stop(handle);
5621 out_mmap:
5622 up_write(&EXT4_I(inode)->i_mmap_sem);
5623 ext4_inode_resume_unlocked_dio(inode);
5624 out_mutex:
5625 inode_unlock(inode);
5626 return ret;
5630 * ext4_insert_range:
5631 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5632 * The data blocks starting from @offset to the EOF are shifted by @len
5633 * towards right to create a hole in the @inode. Inode size is increased
5634 * by len bytes.
5635 * Returns 0 on success, error otherwise.
5637 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5639 struct super_block *sb = inode->i_sb;
5640 handle_t *handle;
5641 struct ext4_ext_path *path;
5642 struct ext4_extent *extent;
5643 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5644 unsigned int credits, ee_len;
5645 int ret = 0, depth, split_flag = 0;
5646 loff_t ioffset;
5649 * We need to test this early because xfstests assumes that an
5650 * insert range of (0, 1) will return EOPNOTSUPP if the file
5651 * system does not support insert range.
5653 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5654 return -EOPNOTSUPP;
5656 /* Insert range works only on fs block size aligned offsets. */
5657 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5658 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5659 return -EINVAL;
5661 if (!S_ISREG(inode->i_mode))
5662 return -EOPNOTSUPP;
5664 trace_ext4_insert_range(inode, offset, len);
5666 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5667 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5669 /* Call ext4_force_commit to flush all data in case of data=journal */
5670 if (ext4_should_journal_data(inode)) {
5671 ret = ext4_force_commit(inode->i_sb);
5672 if (ret)
5673 return ret;
5676 inode_lock(inode);
5677 /* Currently just for extent based files */
5678 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5679 ret = -EOPNOTSUPP;
5680 goto out_mutex;
5683 /* Check for wrap through zero */
5684 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5685 ret = -EFBIG;
5686 goto out_mutex;
5689 /* Offset should be less than i_size */
5690 if (offset >= i_size_read(inode)) {
5691 ret = -EINVAL;
5692 goto out_mutex;
5695 /* Wait for existing dio to complete */
5696 ext4_inode_block_unlocked_dio(inode);
5697 inode_dio_wait(inode);
5700 * Prevent page faults from reinstantiating pages we have released from
5701 * page cache.
5703 down_write(&EXT4_I(inode)->i_mmap_sem);
5705 * Need to round down to align start offset to page size boundary
5706 * for page size > block size.
5708 ioffset = round_down(offset, PAGE_SIZE);
5709 /* Write out all dirty pages */
5710 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5711 LLONG_MAX);
5712 if (ret)
5713 goto out_mmap;
5714 truncate_pagecache(inode, ioffset);
5716 credits = ext4_writepage_trans_blocks(inode);
5717 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5718 if (IS_ERR(handle)) {
5719 ret = PTR_ERR(handle);
5720 goto out_mmap;
5723 /* Expand file to avoid data loss if there is error while shifting */
5724 inode->i_size += len;
5725 EXT4_I(inode)->i_disksize += len;
5726 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5727 ret = ext4_mark_inode_dirty(handle, inode);
5728 if (ret)
5729 goto out_stop;
5731 down_write(&EXT4_I(inode)->i_data_sem);
5732 ext4_discard_preallocations(inode);
5734 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5735 if (IS_ERR(path)) {
5736 up_write(&EXT4_I(inode)->i_data_sem);
5737 goto out_stop;
5740 depth = ext_depth(inode);
5741 extent = path[depth].p_ext;
5742 if (extent) {
5743 ee_start_lblk = le32_to_cpu(extent->ee_block);
5744 ee_len = ext4_ext_get_actual_len(extent);
5747 * If offset_lblk is not the starting block of extent, split
5748 * the extent @offset_lblk
5750 if ((offset_lblk > ee_start_lblk) &&
5751 (offset_lblk < (ee_start_lblk + ee_len))) {
5752 if (ext4_ext_is_unwritten(extent))
5753 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5754 EXT4_EXT_MARK_UNWRIT2;
5755 ret = ext4_split_extent_at(handle, inode, &path,
5756 offset_lblk, split_flag,
5757 EXT4_EX_NOCACHE |
5758 EXT4_GET_BLOCKS_PRE_IO |
5759 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5762 ext4_ext_drop_refs(path);
5763 kfree(path);
5764 if (ret < 0) {
5765 up_write(&EXT4_I(inode)->i_data_sem);
5766 goto out_stop;
5768 } else {
5769 ext4_ext_drop_refs(path);
5770 kfree(path);
5773 ret = ext4_es_remove_extent(inode, offset_lblk,
5774 EXT_MAX_BLOCKS - offset_lblk);
5775 if (ret) {
5776 up_write(&EXT4_I(inode)->i_data_sem);
5777 goto out_stop;
5781 * if offset_lblk lies in a hole which is at start of file, use
5782 * ee_start_lblk to shift extents
5784 ret = ext4_ext_shift_extents(inode, handle,
5785 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5786 len_lblk, SHIFT_RIGHT);
5788 up_write(&EXT4_I(inode)->i_data_sem);
5789 if (IS_SYNC(inode))
5790 ext4_handle_sync(handle);
5791 if (ret >= 0)
5792 ext4_update_inode_fsync_trans(handle, inode, 1);
5794 out_stop:
5795 ext4_journal_stop(handle);
5796 out_mmap:
5797 up_write(&EXT4_I(inode)->i_mmap_sem);
5798 ext4_inode_resume_unlocked_dio(inode);
5799 out_mutex:
5800 inode_unlock(inode);
5801 return ret;
5805 * ext4_swap_extents - Swap extents between two inodes
5807 * @inode1: First inode
5808 * @inode2: Second inode
5809 * @lblk1: Start block for first inode
5810 * @lblk2: Start block for second inode
5811 * @count: Number of blocks to swap
5812 * @mark_unwritten: Mark second inode's extents as unwritten after swap
5813 * @erp: Pointer to save error value
5815 * This helper routine does exactly what is promise "swap extents". All other
5816 * stuff such as page-cache locking consistency, bh mapping consistency or
5817 * extent's data copying must be performed by caller.
5818 * Locking:
5819 * i_mutex is held for both inodes
5820 * i_data_sem is locked for write for both inodes
5821 * Assumptions:
5822 * All pages from requested range are locked for both inodes
5825 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5826 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5827 ext4_lblk_t count, int unwritten, int *erp)
5829 struct ext4_ext_path *path1 = NULL;
5830 struct ext4_ext_path *path2 = NULL;
5831 int replaced_count = 0;
5833 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5834 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5835 BUG_ON(!inode_is_locked(inode1));
5836 BUG_ON(!inode_is_locked(inode2));
5838 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5839 if (unlikely(*erp))
5840 return 0;
5841 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5842 if (unlikely(*erp))
5843 return 0;
5845 while (count) {
5846 struct ext4_extent *ex1, *ex2, tmp_ex;
5847 ext4_lblk_t e1_blk, e2_blk;
5848 int e1_len, e2_len, len;
5849 int split = 0;
5851 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5852 if (IS_ERR(path1)) {
5853 *erp = PTR_ERR(path1);
5854 path1 = NULL;
5855 finish:
5856 count = 0;
5857 goto repeat;
5859 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5860 if (IS_ERR(path2)) {
5861 *erp = PTR_ERR(path2);
5862 path2 = NULL;
5863 goto finish;
5865 ex1 = path1[path1->p_depth].p_ext;
5866 ex2 = path2[path2->p_depth].p_ext;
5867 /* Do we have somthing to swap ? */
5868 if (unlikely(!ex2 || !ex1))
5869 goto finish;
5871 e1_blk = le32_to_cpu(ex1->ee_block);
5872 e2_blk = le32_to_cpu(ex2->ee_block);
5873 e1_len = ext4_ext_get_actual_len(ex1);
5874 e2_len = ext4_ext_get_actual_len(ex2);
5876 /* Hole handling */
5877 if (!in_range(lblk1, e1_blk, e1_len) ||
5878 !in_range(lblk2, e2_blk, e2_len)) {
5879 ext4_lblk_t next1, next2;
5881 /* if hole after extent, then go to next extent */
5882 next1 = ext4_ext_next_allocated_block(path1);
5883 next2 = ext4_ext_next_allocated_block(path2);
5884 /* If hole before extent, then shift to that extent */
5885 if (e1_blk > lblk1)
5886 next1 = e1_blk;
5887 if (e2_blk > lblk2)
5888 next2 = e1_blk;
5889 /* Do we have something to swap */
5890 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5891 goto finish;
5892 /* Move to the rightest boundary */
5893 len = next1 - lblk1;
5894 if (len < next2 - lblk2)
5895 len = next2 - lblk2;
5896 if (len > count)
5897 len = count;
5898 lblk1 += len;
5899 lblk2 += len;
5900 count -= len;
5901 goto repeat;
5904 /* Prepare left boundary */
5905 if (e1_blk < lblk1) {
5906 split = 1;
5907 *erp = ext4_force_split_extent_at(handle, inode1,
5908 &path1, lblk1, 0);
5909 if (unlikely(*erp))
5910 goto finish;
5912 if (e2_blk < lblk2) {
5913 split = 1;
5914 *erp = ext4_force_split_extent_at(handle, inode2,
5915 &path2, lblk2, 0);
5916 if (unlikely(*erp))
5917 goto finish;
5919 /* ext4_split_extent_at() may result in leaf extent split,
5920 * path must to be revalidated. */
5921 if (split)
5922 goto repeat;
5924 /* Prepare right boundary */
5925 len = count;
5926 if (len > e1_blk + e1_len - lblk1)
5927 len = e1_blk + e1_len - lblk1;
5928 if (len > e2_blk + e2_len - lblk2)
5929 len = e2_blk + e2_len - lblk2;
5931 if (len != e1_len) {
5932 split = 1;
5933 *erp = ext4_force_split_extent_at(handle, inode1,
5934 &path1, lblk1 + len, 0);
5935 if (unlikely(*erp))
5936 goto finish;
5938 if (len != e2_len) {
5939 split = 1;
5940 *erp = ext4_force_split_extent_at(handle, inode2,
5941 &path2, lblk2 + len, 0);
5942 if (*erp)
5943 goto finish;
5945 /* ext4_split_extent_at() may result in leaf extent split,
5946 * path must to be revalidated. */
5947 if (split)
5948 goto repeat;
5950 BUG_ON(e2_len != e1_len);
5951 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5952 if (unlikely(*erp))
5953 goto finish;
5954 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5955 if (unlikely(*erp))
5956 goto finish;
5958 /* Both extents are fully inside boundaries. Swap it now */
5959 tmp_ex = *ex1;
5960 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5961 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5962 ex1->ee_len = cpu_to_le16(e2_len);
5963 ex2->ee_len = cpu_to_le16(e1_len);
5964 if (unwritten)
5965 ext4_ext_mark_unwritten(ex2);
5966 if (ext4_ext_is_unwritten(&tmp_ex))
5967 ext4_ext_mark_unwritten(ex1);
5969 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5970 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5971 *erp = ext4_ext_dirty(handle, inode2, path2 +
5972 path2->p_depth);
5973 if (unlikely(*erp))
5974 goto finish;
5975 *erp = ext4_ext_dirty(handle, inode1, path1 +
5976 path1->p_depth);
5978 * Looks scarry ah..? second inode already points to new blocks,
5979 * and it was successfully dirtied. But luckily error may happen
5980 * only due to journal error, so full transaction will be
5981 * aborted anyway.
5983 if (unlikely(*erp))
5984 goto finish;
5985 lblk1 += len;
5986 lblk2 += len;
5987 replaced_count += len;
5988 count -= len;
5990 repeat:
5991 ext4_ext_drop_refs(path1);
5992 kfree(path1);
5993 ext4_ext_drop_refs(path2);
5994 kfree(path2);
5995 path1 = path2 = NULL;
5997 return replaced_count;