1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4 * Written by Alex Tomas <alex@clusterfs.com>
6 * Architecture independence:
7 * Copyright (c) 2005, Bull S.A.
8 * Written by Pierre Peiffer <pierre.peiffer@bull.net>
12 * Extents support for EXT4
15 * - ext4*_error() should be used in some situations
16 * - analyze all BUG()/BUG_ON(), use -EIO where appropriate
17 * - smart tree reduction
21 #include <linux/time.h>
22 #include <linux/jbd2.h>
23 #include <linux/highuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/quotaops.h>
26 #include <linux/string.h>
27 #include <linux/slab.h>
28 #include <linux/uaccess.h>
29 #include <linux/fiemap.h>
30 #include <linux/backing-dev.h>
31 #include <linux/iomap.h>
32 #include "ext4_jbd2.h"
33 #include "ext4_extents.h"
36 #include <trace/events/ext4.h>
39 * used by extent splitting.
41 #define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
43 #define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
44 #define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
46 #define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
47 #define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
49 static __le32 ext4_extent_block_csum(struct inode *inode,
50 struct ext4_extent_header *eh)
52 struct ext4_inode_info *ei = EXT4_I(inode);
53 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
57 EXT4_EXTENT_TAIL_OFFSET(eh));
58 return cpu_to_le32(csum);
61 static int ext4_extent_block_csum_verify(struct inode *inode,
62 struct ext4_extent_header *eh)
64 struct ext4_extent_tail *et;
66 if (!ext4_has_metadata_csum(inode->i_sb))
69 et = find_ext4_extent_tail(eh);
70 if (et->et_checksum != ext4_extent_block_csum(inode, eh))
75 static void ext4_extent_block_csum_set(struct inode *inode,
76 struct ext4_extent_header *eh)
78 struct ext4_extent_tail *et;
80 if (!ext4_has_metadata_csum(inode->i_sb))
83 et = find_ext4_extent_tail(eh);
84 et->et_checksum = ext4_extent_block_csum(inode, eh);
87 static int ext4_split_extent_at(handle_t *handle,
89 struct ext4_ext_path **ppath,
94 static int ext4_ext_trunc_restart_fn(struct inode *inode, int *dropped)
97 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
98 * moment, get_block can be called only for blocks inside i_size since
99 * page cache has been already dropped and writes are blocked by
100 * i_mutex. So we can safely drop the i_data_sem here.
102 BUG_ON(EXT4_JOURNAL(inode) == NULL);
103 ext4_discard_preallocations(inode, 0);
104 up_write(&EXT4_I(inode)->i_data_sem);
110 * Make sure 'handle' has at least 'check_cred' credits. If not, restart
111 * transaction with 'restart_cred' credits. The function drops i_data_sem
112 * when restarting transaction and gets it after transaction is restarted.
114 * The function returns 0 on success, 1 if transaction had to be restarted,
115 * and < 0 in case of fatal error.
117 int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode,
118 int check_cred, int restart_cred,
124 ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred,
125 revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped));
127 down_write(&EXT4_I(inode)->i_data_sem);
136 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
137 struct ext4_ext_path *path)
142 /* path points to block */
143 BUFFER_TRACE(path->p_bh, "get_write_access");
144 err = ext4_journal_get_write_access(handle, inode->i_sb,
145 path->p_bh, EXT4_JTR_NONE);
147 * The extent buffer's verified bit will be set again in
148 * __ext4_ext_dirty(). We could leave an inconsistent
149 * buffer if the extents updating procudure break off du
150 * to some error happens, force to check it again.
153 clear_buffer_verified(path->p_bh);
155 /* path points to leaf/index in inode body */
156 /* we use in-core data, no need to protect them */
166 static int __ext4_ext_dirty(const char *where, unsigned int line,
167 handle_t *handle, struct inode *inode,
168 struct ext4_ext_path *path)
172 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
174 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
175 /* path points to block */
176 err = __ext4_handle_dirty_metadata(where, line, handle,
178 /* Extents updating done, re-set verified flag */
180 set_buffer_verified(path->p_bh);
182 /* path points to leaf/index in inode body */
183 err = ext4_mark_inode_dirty(handle, inode);
188 #define ext4_ext_dirty(handle, inode, path) \
189 __ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
191 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
192 struct ext4_ext_path *path,
196 int depth = path->p_depth;
197 struct ext4_extent *ex;
200 * Try to predict block placement assuming that we are
201 * filling in a file which will eventually be
202 * non-sparse --- i.e., in the case of libbfd writing
203 * an ELF object sections out-of-order but in a way
204 * the eventually results in a contiguous object or
205 * executable file, or some database extending a table
206 * space file. However, this is actually somewhat
207 * non-ideal if we are writing a sparse file such as
208 * qemu or KVM writing a raw image file that is going
209 * to stay fairly sparse, since it will end up
210 * fragmenting the file system's free space. Maybe we
211 * should have some hueristics or some way to allow
212 * userspace to pass a hint to file system,
213 * especially if the latter case turns out to be
216 ex = path[depth].p_ext;
218 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
219 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
221 if (block > ext_block)
222 return ext_pblk + (block - ext_block);
224 return ext_pblk - (ext_block - block);
227 /* it looks like index is empty;
228 * try to find starting block from index itself */
229 if (path[depth].p_bh)
230 return path[depth].p_bh->b_blocknr;
233 /* OK. use inode's group */
234 return ext4_inode_to_goal_block(inode);
238 * Allocation for a meta data block
241 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
242 struct ext4_ext_path *path,
243 struct ext4_extent *ex, int *err, unsigned int flags)
245 ext4_fsblk_t goal, newblock;
247 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
248 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
253 static inline int ext4_ext_space_block(struct inode *inode, int check)
257 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
258 / sizeof(struct ext4_extent);
259 #ifdef AGGRESSIVE_TEST
260 if (!check && size > 6)
266 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
270 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
271 / sizeof(struct ext4_extent_idx);
272 #ifdef AGGRESSIVE_TEST
273 if (!check && size > 5)
279 static inline int ext4_ext_space_root(struct inode *inode, int check)
283 size = sizeof(EXT4_I(inode)->i_data);
284 size -= sizeof(struct ext4_extent_header);
285 size /= sizeof(struct ext4_extent);
286 #ifdef AGGRESSIVE_TEST
287 if (!check && size > 3)
293 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
297 size = sizeof(EXT4_I(inode)->i_data);
298 size -= sizeof(struct ext4_extent_header);
299 size /= sizeof(struct ext4_extent_idx);
300 #ifdef AGGRESSIVE_TEST
301 if (!check && size > 4)
308 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
309 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
312 struct ext4_ext_path *path = *ppath;
313 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
314 int flags = EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO;
317 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL | EXT4_EX_NOFAIL;
319 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
320 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
325 ext4_ext_max_entries(struct inode *inode, int depth)
329 if (depth == ext_depth(inode)) {
331 max = ext4_ext_space_root(inode, 1);
333 max = ext4_ext_space_root_idx(inode, 1);
336 max = ext4_ext_space_block(inode, 1);
338 max = ext4_ext_space_block_idx(inode, 1);
344 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
346 ext4_fsblk_t block = ext4_ext_pblock(ext);
347 int len = ext4_ext_get_actual_len(ext);
348 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
353 * - overflow/wrap-around
355 if (lblock + len <= lblock)
357 return ext4_inode_block_valid(inode, block, len);
360 static int ext4_valid_extent_idx(struct inode *inode,
361 struct ext4_extent_idx *ext_idx)
363 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
365 return ext4_inode_block_valid(inode, block, 1);
368 static int ext4_valid_extent_entries(struct inode *inode,
369 struct ext4_extent_header *eh,
370 ext4_lblk_t lblk, ext4_fsblk_t *pblk,
373 unsigned short entries;
374 ext4_lblk_t lblock = 0;
377 if (eh->eh_entries == 0)
380 entries = le16_to_cpu(eh->eh_entries);
384 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
387 * The logical block in the first entry should equal to
388 * the number in the index block.
390 if (depth != ext_depth(inode) &&
391 lblk != le32_to_cpu(ext->ee_block))
394 if (!ext4_valid_extent(inode, ext))
397 /* Check for overlapping extents */
398 lblock = le32_to_cpu(ext->ee_block);
400 *pblk = ext4_ext_pblock(ext);
403 cur = lblock + ext4_ext_get_actual_len(ext);
408 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
411 * The logical block in the first entry should equal to
412 * the number in the parent index block.
414 if (depth != ext_depth(inode) &&
415 lblk != le32_to_cpu(ext_idx->ei_block))
418 if (!ext4_valid_extent_idx(inode, ext_idx))
421 /* Check for overlapping index extents */
422 lblock = le32_to_cpu(ext_idx->ei_block);
424 *pblk = ext4_idx_pblock(ext_idx);
435 static int __ext4_ext_check(const char *function, unsigned int line,
436 struct inode *inode, struct ext4_extent_header *eh,
437 int depth, ext4_fsblk_t pblk, ext4_lblk_t lblk)
439 const char *error_msg;
440 int max = 0, err = -EFSCORRUPTED;
442 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
443 error_msg = "invalid magic";
446 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
447 error_msg = "unexpected eh_depth";
450 if (unlikely(eh->eh_max == 0)) {
451 error_msg = "invalid eh_max";
454 max = ext4_ext_max_entries(inode, depth);
455 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
456 error_msg = "too large eh_max";
459 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
460 error_msg = "invalid eh_entries";
463 if (unlikely((eh->eh_entries == 0) && (depth > 0))) {
464 error_msg = "eh_entries is 0 but eh_depth is > 0";
467 if (!ext4_valid_extent_entries(inode, eh, lblk, &pblk, depth)) {
468 error_msg = "invalid extent entries";
471 if (unlikely(depth > 32)) {
472 error_msg = "too large eh_depth";
475 /* Verify checksum on non-root extent tree nodes */
476 if (ext_depth(inode) != depth &&
477 !ext4_extent_block_csum_verify(inode, eh)) {
478 error_msg = "extent tree corrupted";
485 ext4_error_inode_err(inode, function, line, 0, -err,
486 "pblk %llu bad header/extent: %s - magic %x, "
487 "entries %u, max %u(%u), depth %u(%u)",
488 (unsigned long long) pblk, error_msg,
489 le16_to_cpu(eh->eh_magic),
490 le16_to_cpu(eh->eh_entries),
491 le16_to_cpu(eh->eh_max),
492 max, le16_to_cpu(eh->eh_depth), depth);
496 #define ext4_ext_check(inode, eh, depth, pblk) \
497 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk), 0)
499 int ext4_ext_check_inode(struct inode *inode)
501 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
504 static void ext4_cache_extents(struct inode *inode,
505 struct ext4_extent_header *eh)
507 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
508 ext4_lblk_t prev = 0;
511 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
512 unsigned int status = EXTENT_STATUS_WRITTEN;
513 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
514 int len = ext4_ext_get_actual_len(ex);
516 if (prev && (prev != lblk))
517 ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
520 if (ext4_ext_is_unwritten(ex))
521 status = EXTENT_STATUS_UNWRITTEN;
522 ext4_es_cache_extent(inode, lblk, len,
523 ext4_ext_pblock(ex), status);
528 static struct buffer_head *
529 __read_extent_tree_block(const char *function, unsigned int line,
530 struct inode *inode, struct ext4_extent_idx *idx,
531 int depth, int flags)
533 struct buffer_head *bh;
535 gfp_t gfp_flags = __GFP_MOVABLE | GFP_NOFS;
538 if (flags & EXT4_EX_NOFAIL)
539 gfp_flags |= __GFP_NOFAIL;
541 pblk = ext4_idx_pblock(idx);
542 bh = sb_getblk_gfp(inode->i_sb, pblk, gfp_flags);
544 return ERR_PTR(-ENOMEM);
546 if (!bh_uptodate_or_lock(bh)) {
547 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
548 err = ext4_read_bh(bh, 0, NULL);
552 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
554 err = __ext4_ext_check(function, line, inode, ext_block_hdr(bh),
555 depth, pblk, le32_to_cpu(idx->ei_block));
558 set_buffer_verified(bh);
560 * If this is a leaf block, cache all of its entries
562 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
563 struct ext4_extent_header *eh = ext_block_hdr(bh);
564 ext4_cache_extents(inode, eh);
573 #define read_extent_tree_block(inode, idx, depth, flags) \
574 __read_extent_tree_block(__func__, __LINE__, (inode), (idx), \
578 * This function is called to cache a file's extent information in the
581 int ext4_ext_precache(struct inode *inode)
583 struct ext4_inode_info *ei = EXT4_I(inode);
584 struct ext4_ext_path *path = NULL;
585 struct buffer_head *bh;
586 int i = 0, depth, ret = 0;
588 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
589 return 0; /* not an extent-mapped inode */
591 down_read(&ei->i_data_sem);
592 depth = ext_depth(inode);
594 /* Don't cache anything if there are no external extent blocks */
596 up_read(&ei->i_data_sem);
600 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
603 up_read(&ei->i_data_sem);
607 path[0].p_hdr = ext_inode_hdr(inode);
608 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
611 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
614 * If this is a leaf block or we've reached the end of
615 * the index block, go up
618 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
619 brelse(path[i].p_bh);
624 bh = read_extent_tree_block(inode, path[i].p_idx++,
626 EXT4_EX_FORCE_CACHE);
633 path[i].p_hdr = ext_block_hdr(bh);
634 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
636 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
638 up_read(&ei->i_data_sem);
639 ext4_ext_drop_refs(path);
645 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
647 int k, l = path->p_depth;
649 ext_debug(inode, "path:");
650 for (k = 0; k <= l; k++, path++) {
652 ext_debug(inode, " %d->%llu",
653 le32_to_cpu(path->p_idx->ei_block),
654 ext4_idx_pblock(path->p_idx));
655 } else if (path->p_ext) {
656 ext_debug(inode, " %d:[%d]%d:%llu ",
657 le32_to_cpu(path->p_ext->ee_block),
658 ext4_ext_is_unwritten(path->p_ext),
659 ext4_ext_get_actual_len(path->p_ext),
660 ext4_ext_pblock(path->p_ext));
662 ext_debug(inode, " []");
664 ext_debug(inode, "\n");
667 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
669 int depth = ext_depth(inode);
670 struct ext4_extent_header *eh;
671 struct ext4_extent *ex;
677 eh = path[depth].p_hdr;
678 ex = EXT_FIRST_EXTENT(eh);
680 ext_debug(inode, "Displaying leaf extents\n");
682 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
683 ext_debug(inode, "%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
684 ext4_ext_is_unwritten(ex),
685 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
687 ext_debug(inode, "\n");
690 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
691 ext4_fsblk_t newblock, int level)
693 int depth = ext_depth(inode);
694 struct ext4_extent *ex;
696 if (depth != level) {
697 struct ext4_extent_idx *idx;
698 idx = path[level].p_idx;
699 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
700 ext_debug(inode, "%d: move %d:%llu in new index %llu\n",
701 level, le32_to_cpu(idx->ei_block),
702 ext4_idx_pblock(idx), newblock);
709 ex = path[depth].p_ext;
710 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
711 ext_debug(inode, "move %d:%llu:[%d]%d in new leaf %llu\n",
712 le32_to_cpu(ex->ee_block),
714 ext4_ext_is_unwritten(ex),
715 ext4_ext_get_actual_len(ex),
722 #define ext4_ext_show_path(inode, path)
723 #define ext4_ext_show_leaf(inode, path)
724 #define ext4_ext_show_move(inode, path, newblock, level)
727 void ext4_ext_drop_refs(struct ext4_ext_path *path)
733 depth = path->p_depth;
734 for (i = 0; i <= depth; i++, path++) {
741 * ext4_ext_binsearch_idx:
742 * binary search for the closest index of the given block
743 * the header must be checked before calling this
746 ext4_ext_binsearch_idx(struct inode *inode,
747 struct ext4_ext_path *path, ext4_lblk_t block)
749 struct ext4_extent_header *eh = path->p_hdr;
750 struct ext4_extent_idx *r, *l, *m;
753 ext_debug(inode, "binsearch for %u(idx): ", block);
755 l = EXT_FIRST_INDEX(eh) + 1;
756 r = EXT_LAST_INDEX(eh);
759 if (block < le32_to_cpu(m->ei_block))
763 ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
764 le32_to_cpu(l->ei_block), m, le32_to_cpu(m->ei_block),
765 r, le32_to_cpu(r->ei_block));
769 ext_debug(inode, " -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
770 ext4_idx_pblock(path->p_idx));
772 #ifdef CHECK_BINSEARCH
774 struct ext4_extent_idx *chix, *ix;
777 chix = ix = EXT_FIRST_INDEX(eh);
778 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
779 if (k != 0 && le32_to_cpu(ix->ei_block) <=
780 le32_to_cpu(ix[-1].ei_block)) {
781 printk(KERN_DEBUG "k=%d, ix=0x%p, "
783 ix, EXT_FIRST_INDEX(eh));
784 printk(KERN_DEBUG "%u <= %u\n",
785 le32_to_cpu(ix->ei_block),
786 le32_to_cpu(ix[-1].ei_block));
788 BUG_ON(k && le32_to_cpu(ix->ei_block)
789 <= le32_to_cpu(ix[-1].ei_block));
790 if (block < le32_to_cpu(ix->ei_block))
794 BUG_ON(chix != path->p_idx);
801 * ext4_ext_binsearch:
802 * binary search for closest extent of the given block
803 * the header must be checked before calling this
806 ext4_ext_binsearch(struct inode *inode,
807 struct ext4_ext_path *path, ext4_lblk_t block)
809 struct ext4_extent_header *eh = path->p_hdr;
810 struct ext4_extent *r, *l, *m;
812 if (eh->eh_entries == 0) {
814 * this leaf is empty:
815 * we get such a leaf in split/add case
820 ext_debug(inode, "binsearch for %u: ", block);
822 l = EXT_FIRST_EXTENT(eh) + 1;
823 r = EXT_LAST_EXTENT(eh);
827 if (block < le32_to_cpu(m->ee_block))
831 ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
832 le32_to_cpu(l->ee_block), m, le32_to_cpu(m->ee_block),
833 r, le32_to_cpu(r->ee_block));
837 ext_debug(inode, " -> %d:%llu:[%d]%d ",
838 le32_to_cpu(path->p_ext->ee_block),
839 ext4_ext_pblock(path->p_ext),
840 ext4_ext_is_unwritten(path->p_ext),
841 ext4_ext_get_actual_len(path->p_ext));
843 #ifdef CHECK_BINSEARCH
845 struct ext4_extent *chex, *ex;
848 chex = ex = EXT_FIRST_EXTENT(eh);
849 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
850 BUG_ON(k && le32_to_cpu(ex->ee_block)
851 <= le32_to_cpu(ex[-1].ee_block));
852 if (block < le32_to_cpu(ex->ee_block))
856 BUG_ON(chex != path->p_ext);
862 void ext4_ext_tree_init(handle_t *handle, struct inode *inode)
864 struct ext4_extent_header *eh;
866 eh = ext_inode_hdr(inode);
869 eh->eh_magic = EXT4_EXT_MAGIC;
870 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
871 eh->eh_generation = 0;
872 ext4_mark_inode_dirty(handle, inode);
875 struct ext4_ext_path *
876 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
877 struct ext4_ext_path **orig_path, int flags)
879 struct ext4_extent_header *eh;
880 struct buffer_head *bh;
881 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
882 short int depth, i, ppos = 0;
884 gfp_t gfp_flags = GFP_NOFS;
886 if (flags & EXT4_EX_NOFAIL)
887 gfp_flags |= __GFP_NOFAIL;
889 eh = ext_inode_hdr(inode);
890 depth = ext_depth(inode);
891 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
892 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
899 ext4_ext_drop_refs(path);
900 if (depth > path[0].p_maxdepth) {
902 *orig_path = path = NULL;
906 /* account possible depth increase */
907 path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
910 return ERR_PTR(-ENOMEM);
911 path[0].p_maxdepth = depth + 1;
917 if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
918 ext4_cache_extents(inode, eh);
919 /* walk through the tree */
921 ext_debug(inode, "depth %d: num %d, max %d\n",
922 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
924 ext4_ext_binsearch_idx(inode, path + ppos, block);
925 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
926 path[ppos].p_depth = i;
927 path[ppos].p_ext = NULL;
929 bh = read_extent_tree_block(inode, path[ppos].p_idx, --i, flags);
935 eh = ext_block_hdr(bh);
937 path[ppos].p_bh = bh;
938 path[ppos].p_hdr = eh;
941 path[ppos].p_depth = i;
942 path[ppos].p_ext = NULL;
943 path[ppos].p_idx = NULL;
946 ext4_ext_binsearch(inode, path + ppos, block);
947 /* if not an empty leaf */
948 if (path[ppos].p_ext)
949 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
951 ext4_ext_show_path(inode, path);
956 ext4_ext_drop_refs(path);
964 * ext4_ext_insert_index:
965 * insert new index [@logical;@ptr] into the block at @curp;
966 * check where to insert: before @curp or after @curp
968 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
969 struct ext4_ext_path *curp,
970 int logical, ext4_fsblk_t ptr)
972 struct ext4_extent_idx *ix;
975 err = ext4_ext_get_access(handle, inode, curp);
979 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
980 EXT4_ERROR_INODE(inode,
981 "logical %d == ei_block %d!",
982 logical, le32_to_cpu(curp->p_idx->ei_block));
983 return -EFSCORRUPTED;
986 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
987 >= le16_to_cpu(curp->p_hdr->eh_max))) {
988 EXT4_ERROR_INODE(inode,
989 "eh_entries %d >= eh_max %d!",
990 le16_to_cpu(curp->p_hdr->eh_entries),
991 le16_to_cpu(curp->p_hdr->eh_max));
992 return -EFSCORRUPTED;
995 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
997 ext_debug(inode, "insert new index %d after: %llu\n",
999 ix = curp->p_idx + 1;
1002 ext_debug(inode, "insert new index %d before: %llu\n",
1007 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1010 ext_debug(inode, "insert new index %d: "
1011 "move %d indices from 0x%p to 0x%p\n",
1012 logical, len, ix, ix + 1);
1013 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1016 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1017 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1018 return -EFSCORRUPTED;
1021 ix->ei_block = cpu_to_le32(logical);
1022 ext4_idx_store_pblock(ix, ptr);
1023 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1025 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1026 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1027 return -EFSCORRUPTED;
1030 err = ext4_ext_dirty(handle, inode, curp);
1031 ext4_std_error(inode->i_sb, err);
1038 * inserts new subtree into the path, using free index entry
1040 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1041 * - makes decision where to split
1042 * - moves remaining extents and index entries (right to the split point)
1043 * into the newly allocated blocks
1044 * - initializes subtree
1046 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1048 struct ext4_ext_path *path,
1049 struct ext4_extent *newext, int at)
1051 struct buffer_head *bh = NULL;
1052 int depth = ext_depth(inode);
1053 struct ext4_extent_header *neh;
1054 struct ext4_extent_idx *fidx;
1055 int i = at, k, m, a;
1056 ext4_fsblk_t newblock, oldblock;
1058 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1059 gfp_t gfp_flags = GFP_NOFS;
1061 size_t ext_size = 0;
1063 if (flags & EXT4_EX_NOFAIL)
1064 gfp_flags |= __GFP_NOFAIL;
1066 /* make decision: where to split? */
1067 /* FIXME: now decision is simplest: at current extent */
1069 /* if current leaf will be split, then we should use
1070 * border from split point */
1071 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1072 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1073 return -EFSCORRUPTED;
1075 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1076 border = path[depth].p_ext[1].ee_block;
1077 ext_debug(inode, "leaf will be split."
1078 " next leaf starts at %d\n",
1079 le32_to_cpu(border));
1081 border = newext->ee_block;
1082 ext_debug(inode, "leaf will be added."
1083 " next leaf starts at %d\n",
1084 le32_to_cpu(border));
1088 * If error occurs, then we break processing
1089 * and mark filesystem read-only. index won't
1090 * be inserted and tree will be in consistent
1091 * state. Next mount will repair buffers too.
1095 * Get array to track all allocated blocks.
1096 * We need this to handle errors and free blocks
1099 ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), gfp_flags);
1103 /* allocate all needed blocks */
1104 ext_debug(inode, "allocate %d blocks for indexes/leaf\n", depth - at);
1105 for (a = 0; a < depth - at; a++) {
1106 newblock = ext4_ext_new_meta_block(handle, inode, path,
1107 newext, &err, flags);
1110 ablocks[a] = newblock;
1113 /* initialize new leaf */
1114 newblock = ablocks[--a];
1115 if (unlikely(newblock == 0)) {
1116 EXT4_ERROR_INODE(inode, "newblock == 0!");
1117 err = -EFSCORRUPTED;
1120 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1121 if (unlikely(!bh)) {
1127 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
1132 neh = ext_block_hdr(bh);
1133 neh->eh_entries = 0;
1134 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1135 neh->eh_magic = EXT4_EXT_MAGIC;
1137 neh->eh_generation = 0;
1139 /* move remainder of path[depth] to the new leaf */
1140 if (unlikely(path[depth].p_hdr->eh_entries !=
1141 path[depth].p_hdr->eh_max)) {
1142 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1143 path[depth].p_hdr->eh_entries,
1144 path[depth].p_hdr->eh_max);
1145 err = -EFSCORRUPTED;
1148 /* start copy from next extent */
1149 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1150 ext4_ext_show_move(inode, path, newblock, depth);
1152 struct ext4_extent *ex;
1153 ex = EXT_FIRST_EXTENT(neh);
1154 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1155 le16_add_cpu(&neh->eh_entries, m);
1158 /* zero out unused area in the extent block */
1159 ext_size = sizeof(struct ext4_extent_header) +
1160 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1161 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1162 ext4_extent_block_csum_set(inode, neh);
1163 set_buffer_uptodate(bh);
1166 err = ext4_handle_dirty_metadata(handle, inode, bh);
1172 /* correct old leaf */
1174 err = ext4_ext_get_access(handle, inode, path + depth);
1177 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1178 err = ext4_ext_dirty(handle, inode, path + depth);
1184 /* create intermediate indexes */
1186 if (unlikely(k < 0)) {
1187 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1188 err = -EFSCORRUPTED;
1192 ext_debug(inode, "create %d intermediate indices\n", k);
1193 /* insert new index into current index block */
1194 /* current depth stored in i var */
1197 oldblock = newblock;
1198 newblock = ablocks[--a];
1199 bh = sb_getblk(inode->i_sb, newblock);
1200 if (unlikely(!bh)) {
1206 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
1211 neh = ext_block_hdr(bh);
1212 neh->eh_entries = cpu_to_le16(1);
1213 neh->eh_magic = EXT4_EXT_MAGIC;
1214 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1215 neh->eh_depth = cpu_to_le16(depth - i);
1216 neh->eh_generation = 0;
1217 fidx = EXT_FIRST_INDEX(neh);
1218 fidx->ei_block = border;
1219 ext4_idx_store_pblock(fidx, oldblock);
1221 ext_debug(inode, "int.index at %d (block %llu): %u -> %llu\n",
1222 i, newblock, le32_to_cpu(border), oldblock);
1224 /* move remainder of path[i] to the new index block */
1225 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1226 EXT_LAST_INDEX(path[i].p_hdr))) {
1227 EXT4_ERROR_INODE(inode,
1228 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1229 le32_to_cpu(path[i].p_ext->ee_block));
1230 err = -EFSCORRUPTED;
1233 /* start copy indexes */
1234 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1235 ext_debug(inode, "cur 0x%p, last 0x%p\n", path[i].p_idx,
1236 EXT_MAX_INDEX(path[i].p_hdr));
1237 ext4_ext_show_move(inode, path, newblock, i);
1239 memmove(++fidx, path[i].p_idx,
1240 sizeof(struct ext4_extent_idx) * m);
1241 le16_add_cpu(&neh->eh_entries, m);
1243 /* zero out unused area in the extent block */
1244 ext_size = sizeof(struct ext4_extent_header) +
1245 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1246 memset(bh->b_data + ext_size, 0,
1247 inode->i_sb->s_blocksize - ext_size);
1248 ext4_extent_block_csum_set(inode, neh);
1249 set_buffer_uptodate(bh);
1252 err = ext4_handle_dirty_metadata(handle, inode, bh);
1258 /* correct old index */
1260 err = ext4_ext_get_access(handle, inode, path + i);
1263 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1264 err = ext4_ext_dirty(handle, inode, path + i);
1272 /* insert new index */
1273 err = ext4_ext_insert_index(handle, inode, path + at,
1274 le32_to_cpu(border), newblock);
1278 if (buffer_locked(bh))
1284 /* free all allocated blocks in error case */
1285 for (i = 0; i < depth; i++) {
1288 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1289 EXT4_FREE_BLOCKS_METADATA);
1298 * ext4_ext_grow_indepth:
1299 * implements tree growing procedure:
1300 * - allocates new block
1301 * - moves top-level data (index block or leaf) into the new block
1302 * - initializes new top-level, creating index that points to the
1303 * just created block
1305 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1308 struct ext4_extent_header *neh;
1309 struct buffer_head *bh;
1310 ext4_fsblk_t newblock, goal = 0;
1311 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1313 size_t ext_size = 0;
1315 /* Try to prepend new index to old one */
1316 if (ext_depth(inode))
1317 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1318 if (goal > le32_to_cpu(es->s_first_data_block)) {
1319 flags |= EXT4_MB_HINT_TRY_GOAL;
1322 goal = ext4_inode_to_goal_block(inode);
1323 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1328 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1333 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
1340 ext_size = sizeof(EXT4_I(inode)->i_data);
1341 /* move top-level index/leaf into new block */
1342 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1343 /* zero out unused area in the extent block */
1344 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1346 /* set size of new block */
1347 neh = ext_block_hdr(bh);
1348 /* old root could have indexes or leaves
1349 * so calculate e_max right way */
1350 if (ext_depth(inode))
1351 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1353 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1354 neh->eh_magic = EXT4_EXT_MAGIC;
1355 ext4_extent_block_csum_set(inode, neh);
1356 set_buffer_uptodate(bh);
1357 set_buffer_verified(bh);
1360 err = ext4_handle_dirty_metadata(handle, inode, bh);
1364 /* Update top-level index: num,max,pointer */
1365 neh = ext_inode_hdr(inode);
1366 neh->eh_entries = cpu_to_le16(1);
1367 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1368 if (neh->eh_depth == 0) {
1369 /* Root extent block becomes index block */
1370 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1371 EXT_FIRST_INDEX(neh)->ei_block =
1372 EXT_FIRST_EXTENT(neh)->ee_block;
1374 ext_debug(inode, "new root: num %d(%d), lblock %d, ptr %llu\n",
1375 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1376 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1377 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1379 le16_add_cpu(&neh->eh_depth, 1);
1380 err = ext4_mark_inode_dirty(handle, inode);
1388 * ext4_ext_create_new_leaf:
1389 * finds empty index and adds new leaf.
1390 * if no free index is found, then it requests in-depth growing.
1392 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1393 unsigned int mb_flags,
1394 unsigned int gb_flags,
1395 struct ext4_ext_path **ppath,
1396 struct ext4_extent *newext)
1398 struct ext4_ext_path *path = *ppath;
1399 struct ext4_ext_path *curp;
1400 int depth, i, err = 0;
1403 i = depth = ext_depth(inode);
1405 /* walk up to the tree and look for free index entry */
1406 curp = path + depth;
1407 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1412 /* we use already allocated block for index block,
1413 * so subsequent data blocks should be contiguous */
1414 if (EXT_HAS_FREE_INDEX(curp)) {
1415 /* if we found index with free entry, then use that
1416 * entry: create all needed subtree and add new leaf */
1417 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1422 path = ext4_find_extent(inode,
1423 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1426 err = PTR_ERR(path);
1428 /* tree is full, time to grow in depth */
1429 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1434 path = ext4_find_extent(inode,
1435 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1438 err = PTR_ERR(path);
1443 * only first (depth 0 -> 1) produces free space;
1444 * in all other cases we have to split the grown tree
1446 depth = ext_depth(inode);
1447 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1448 /* now we need to split */
1458 * search the closest allocated block to the left for *logical
1459 * and returns it at @logical + it's physical address at @phys
1460 * if *logical is the smallest allocated block, the function
1461 * returns 0 at @phys
1462 * return value contains 0 (success) or error code
1464 static int ext4_ext_search_left(struct inode *inode,
1465 struct ext4_ext_path *path,
1466 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1468 struct ext4_extent_idx *ix;
1469 struct ext4_extent *ex;
1472 if (unlikely(path == NULL)) {
1473 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1474 return -EFSCORRUPTED;
1476 depth = path->p_depth;
1479 if (depth == 0 && path->p_ext == NULL)
1482 /* usually extent in the path covers blocks smaller
1483 * then *logical, but it can be that extent is the
1484 * first one in the file */
1486 ex = path[depth].p_ext;
1487 ee_len = ext4_ext_get_actual_len(ex);
1488 if (*logical < le32_to_cpu(ex->ee_block)) {
1489 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1490 EXT4_ERROR_INODE(inode,
1491 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1492 *logical, le32_to_cpu(ex->ee_block));
1493 return -EFSCORRUPTED;
1495 while (--depth >= 0) {
1496 ix = path[depth].p_idx;
1497 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1498 EXT4_ERROR_INODE(inode,
1499 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1500 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1501 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1502 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1504 return -EFSCORRUPTED;
1510 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1511 EXT4_ERROR_INODE(inode,
1512 "logical %d < ee_block %d + ee_len %d!",
1513 *logical, le32_to_cpu(ex->ee_block), ee_len);
1514 return -EFSCORRUPTED;
1517 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1518 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1523 * Search the closest allocated block to the right for *logical
1524 * and returns it at @logical + it's physical address at @phys.
1525 * If not exists, return 0 and @phys is set to 0. We will return
1526 * 1 which means we found an allocated block and ret_ex is valid.
1527 * Or return a (< 0) error code.
1529 static int ext4_ext_search_right(struct inode *inode,
1530 struct ext4_ext_path *path,
1531 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1532 struct ext4_extent *ret_ex)
1534 struct buffer_head *bh = NULL;
1535 struct ext4_extent_header *eh;
1536 struct ext4_extent_idx *ix;
1537 struct ext4_extent *ex;
1538 int depth; /* Note, NOT eh_depth; depth from top of tree */
1541 if (unlikely(path == NULL)) {
1542 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1543 return -EFSCORRUPTED;
1545 depth = path->p_depth;
1548 if (depth == 0 && path->p_ext == NULL)
1551 /* usually extent in the path covers blocks smaller
1552 * then *logical, but it can be that extent is the
1553 * first one in the file */
1555 ex = path[depth].p_ext;
1556 ee_len = ext4_ext_get_actual_len(ex);
1557 if (*logical < le32_to_cpu(ex->ee_block)) {
1558 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1559 EXT4_ERROR_INODE(inode,
1560 "first_extent(path[%d].p_hdr) != ex",
1562 return -EFSCORRUPTED;
1564 while (--depth >= 0) {
1565 ix = path[depth].p_idx;
1566 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1567 EXT4_ERROR_INODE(inode,
1568 "ix != EXT_FIRST_INDEX *logical %d!",
1570 return -EFSCORRUPTED;
1576 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1577 EXT4_ERROR_INODE(inode,
1578 "logical %d < ee_block %d + ee_len %d!",
1579 *logical, le32_to_cpu(ex->ee_block), ee_len);
1580 return -EFSCORRUPTED;
1583 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1584 /* next allocated block in this leaf */
1589 /* go up and search for index to the right */
1590 while (--depth >= 0) {
1591 ix = path[depth].p_idx;
1592 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1596 /* we've gone up to the root and found no index to the right */
1600 /* we've found index to the right, let's
1601 * follow it and find the closest allocated
1602 * block to the right */
1604 while (++depth < path->p_depth) {
1605 /* subtract from p_depth to get proper eh_depth */
1606 bh = read_extent_tree_block(inode, ix, path->p_depth - depth, 0);
1609 eh = ext_block_hdr(bh);
1610 ix = EXT_FIRST_INDEX(eh);
1614 bh = read_extent_tree_block(inode, ix, path->p_depth - depth, 0);
1617 eh = ext_block_hdr(bh);
1618 ex = EXT_FIRST_EXTENT(eh);
1620 *logical = le32_to_cpu(ex->ee_block);
1621 *phys = ext4_ext_pblock(ex);
1630 * ext4_ext_next_allocated_block:
1631 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1632 * NOTE: it considers block number from index entry as
1633 * allocated block. Thus, index entries have to be consistent
1637 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1641 BUG_ON(path == NULL);
1642 depth = path->p_depth;
1644 if (depth == 0 && path->p_ext == NULL)
1645 return EXT_MAX_BLOCKS;
1647 while (depth >= 0) {
1648 struct ext4_ext_path *p = &path[depth];
1650 if (depth == path->p_depth) {
1652 if (p->p_ext && p->p_ext != EXT_LAST_EXTENT(p->p_hdr))
1653 return le32_to_cpu(p->p_ext[1].ee_block);
1656 if (p->p_idx != EXT_LAST_INDEX(p->p_hdr))
1657 return le32_to_cpu(p->p_idx[1].ei_block);
1662 return EXT_MAX_BLOCKS;
1666 * ext4_ext_next_leaf_block:
1667 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1669 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1673 BUG_ON(path == NULL);
1674 depth = path->p_depth;
1676 /* zero-tree has no leaf blocks at all */
1678 return EXT_MAX_BLOCKS;
1680 /* go to index block */
1683 while (depth >= 0) {
1684 if (path[depth].p_idx !=
1685 EXT_LAST_INDEX(path[depth].p_hdr))
1686 return (ext4_lblk_t)
1687 le32_to_cpu(path[depth].p_idx[1].ei_block);
1691 return EXT_MAX_BLOCKS;
1695 * ext4_ext_correct_indexes:
1696 * if leaf gets modified and modified extent is first in the leaf,
1697 * then we have to correct all indexes above.
1698 * TODO: do we need to correct tree in all cases?
1700 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1701 struct ext4_ext_path *path)
1703 struct ext4_extent_header *eh;
1704 int depth = ext_depth(inode);
1705 struct ext4_extent *ex;
1709 eh = path[depth].p_hdr;
1710 ex = path[depth].p_ext;
1712 if (unlikely(ex == NULL || eh == NULL)) {
1713 EXT4_ERROR_INODE(inode,
1714 "ex %p == NULL or eh %p == NULL", ex, eh);
1715 return -EFSCORRUPTED;
1719 /* there is no tree at all */
1723 if (ex != EXT_FIRST_EXTENT(eh)) {
1724 /* we correct tree if first leaf got modified only */
1729 * TODO: we need correction if border is smaller than current one
1732 border = path[depth].p_ext->ee_block;
1733 err = ext4_ext_get_access(handle, inode, path + k);
1736 path[k].p_idx->ei_block = border;
1737 err = ext4_ext_dirty(handle, inode, path + k);
1742 /* change all left-side indexes */
1743 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1745 err = ext4_ext_get_access(handle, inode, path + k);
1748 path[k].p_idx->ei_block = border;
1749 err = ext4_ext_dirty(handle, inode, path + k);
1757 static int ext4_can_extents_be_merged(struct inode *inode,
1758 struct ext4_extent *ex1,
1759 struct ext4_extent *ex2)
1761 unsigned short ext1_ee_len, ext2_ee_len;
1763 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1766 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1767 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1769 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1770 le32_to_cpu(ex2->ee_block))
1773 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1776 if (ext4_ext_is_unwritten(ex1) &&
1777 ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)
1779 #ifdef AGGRESSIVE_TEST
1780 if (ext1_ee_len >= 4)
1784 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1790 * This function tries to merge the "ex" extent to the next extent in the tree.
1791 * It always tries to merge towards right. If you want to merge towards
1792 * left, pass "ex - 1" as argument instead of "ex".
1793 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1794 * 1 if they got merged.
1796 static int ext4_ext_try_to_merge_right(struct inode *inode,
1797 struct ext4_ext_path *path,
1798 struct ext4_extent *ex)
1800 struct ext4_extent_header *eh;
1801 unsigned int depth, len;
1802 int merge_done = 0, unwritten;
1804 depth = ext_depth(inode);
1805 BUG_ON(path[depth].p_hdr == NULL);
1806 eh = path[depth].p_hdr;
1808 while (ex < EXT_LAST_EXTENT(eh)) {
1809 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1811 /* merge with next extent! */
1812 unwritten = ext4_ext_is_unwritten(ex);
1813 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1814 + ext4_ext_get_actual_len(ex + 1));
1816 ext4_ext_mark_unwritten(ex);
1818 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1819 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1820 * sizeof(struct ext4_extent);
1821 memmove(ex + 1, ex + 2, len);
1823 le16_add_cpu(&eh->eh_entries, -1);
1825 WARN_ON(eh->eh_entries == 0);
1826 if (!eh->eh_entries)
1827 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1834 * This function does a very simple check to see if we can collapse
1835 * an extent tree with a single extent tree leaf block into the inode.
1837 static void ext4_ext_try_to_merge_up(handle_t *handle,
1838 struct inode *inode,
1839 struct ext4_ext_path *path)
1842 unsigned max_root = ext4_ext_space_root(inode, 0);
1845 if ((path[0].p_depth != 1) ||
1846 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1847 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1851 * We need to modify the block allocation bitmap and the block
1852 * group descriptor to release the extent tree block. If we
1853 * can't get the journal credits, give up.
1855 if (ext4_journal_extend(handle, 2,
1856 ext4_free_metadata_revoke_credits(inode->i_sb, 1)))
1860 * Copy the extent data up to the inode
1862 blk = ext4_idx_pblock(path[0].p_idx);
1863 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1864 sizeof(struct ext4_extent_idx);
1865 s += sizeof(struct ext4_extent_header);
1867 path[1].p_maxdepth = path[0].p_maxdepth;
1868 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1869 path[0].p_depth = 0;
1870 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1871 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1872 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1874 brelse(path[1].p_bh);
1875 ext4_free_blocks(handle, inode, NULL, blk, 1,
1876 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1880 * This function tries to merge the @ex extent to neighbours in the tree, then
1881 * tries to collapse the extent tree into the inode.
1883 static void ext4_ext_try_to_merge(handle_t *handle,
1884 struct inode *inode,
1885 struct ext4_ext_path *path,
1886 struct ext4_extent *ex)
1888 struct ext4_extent_header *eh;
1892 depth = ext_depth(inode);
1893 BUG_ON(path[depth].p_hdr == NULL);
1894 eh = path[depth].p_hdr;
1896 if (ex > EXT_FIRST_EXTENT(eh))
1897 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1900 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1902 ext4_ext_try_to_merge_up(handle, inode, path);
1906 * check if a portion of the "newext" extent overlaps with an
1909 * If there is an overlap discovered, it updates the length of the newext
1910 * such that there will be no overlap, and then returns 1.
1911 * If there is no overlap found, it returns 0.
1913 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1914 struct inode *inode,
1915 struct ext4_extent *newext,
1916 struct ext4_ext_path *path)
1919 unsigned int depth, len1;
1920 unsigned int ret = 0;
1922 b1 = le32_to_cpu(newext->ee_block);
1923 len1 = ext4_ext_get_actual_len(newext);
1924 depth = ext_depth(inode);
1925 if (!path[depth].p_ext)
1927 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1930 * get the next allocated block if the extent in the path
1931 * is before the requested block(s)
1934 b2 = ext4_ext_next_allocated_block(path);
1935 if (b2 == EXT_MAX_BLOCKS)
1937 b2 = EXT4_LBLK_CMASK(sbi, b2);
1940 /* check for wrap through zero on extent logical start block*/
1941 if (b1 + len1 < b1) {
1942 len1 = EXT_MAX_BLOCKS - b1;
1943 newext->ee_len = cpu_to_le16(len1);
1947 /* check for overlap */
1948 if (b1 + len1 > b2) {
1949 newext->ee_len = cpu_to_le16(b2 - b1);
1957 * ext4_ext_insert_extent:
1958 * tries to merge requested extent into the existing extent or
1959 * inserts requested extent as new one into the tree,
1960 * creating new leaf in the no-space case.
1962 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1963 struct ext4_ext_path **ppath,
1964 struct ext4_extent *newext, int gb_flags)
1966 struct ext4_ext_path *path = *ppath;
1967 struct ext4_extent_header *eh;
1968 struct ext4_extent *ex, *fex;
1969 struct ext4_extent *nearex; /* nearest extent */
1970 struct ext4_ext_path *npath = NULL;
1971 int depth, len, err;
1973 int mb_flags = 0, unwritten;
1975 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1976 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1977 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1978 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1979 return -EFSCORRUPTED;
1981 depth = ext_depth(inode);
1982 ex = path[depth].p_ext;
1983 eh = path[depth].p_hdr;
1984 if (unlikely(path[depth].p_hdr == NULL)) {
1985 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1986 return -EFSCORRUPTED;
1989 /* try to insert block into found extent and return */
1990 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1993 * Try to see whether we should rather test the extent on
1994 * right from ex, or from the left of ex. This is because
1995 * ext4_find_extent() can return either extent on the
1996 * left, or on the right from the searched position. This
1997 * will make merging more effective.
1999 if (ex < EXT_LAST_EXTENT(eh) &&
2000 (le32_to_cpu(ex->ee_block) +
2001 ext4_ext_get_actual_len(ex) <
2002 le32_to_cpu(newext->ee_block))) {
2005 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
2006 (le32_to_cpu(newext->ee_block) +
2007 ext4_ext_get_actual_len(newext) <
2008 le32_to_cpu(ex->ee_block)))
2011 /* Try to append newex to the ex */
2012 if (ext4_can_extents_be_merged(inode, ex, newext)) {
2013 ext_debug(inode, "append [%d]%d block to %u:[%d]%d"
2015 ext4_ext_is_unwritten(newext),
2016 ext4_ext_get_actual_len(newext),
2017 le32_to_cpu(ex->ee_block),
2018 ext4_ext_is_unwritten(ex),
2019 ext4_ext_get_actual_len(ex),
2020 ext4_ext_pblock(ex));
2021 err = ext4_ext_get_access(handle, inode,
2025 unwritten = ext4_ext_is_unwritten(ex);
2026 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2027 + ext4_ext_get_actual_len(newext));
2029 ext4_ext_mark_unwritten(ex);
2030 eh = path[depth].p_hdr;
2036 /* Try to prepend newex to the ex */
2037 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2038 ext_debug(inode, "prepend %u[%d]%d block to %u:[%d]%d"
2040 le32_to_cpu(newext->ee_block),
2041 ext4_ext_is_unwritten(newext),
2042 ext4_ext_get_actual_len(newext),
2043 le32_to_cpu(ex->ee_block),
2044 ext4_ext_is_unwritten(ex),
2045 ext4_ext_get_actual_len(ex),
2046 ext4_ext_pblock(ex));
2047 err = ext4_ext_get_access(handle, inode,
2052 unwritten = ext4_ext_is_unwritten(ex);
2053 ex->ee_block = newext->ee_block;
2054 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2055 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2056 + ext4_ext_get_actual_len(newext));
2058 ext4_ext_mark_unwritten(ex);
2059 eh = path[depth].p_hdr;
2065 depth = ext_depth(inode);
2066 eh = path[depth].p_hdr;
2067 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2070 /* probably next leaf has space for us? */
2071 fex = EXT_LAST_EXTENT(eh);
2072 next = EXT_MAX_BLOCKS;
2073 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2074 next = ext4_ext_next_leaf_block(path);
2075 if (next != EXT_MAX_BLOCKS) {
2076 ext_debug(inode, "next leaf block - %u\n", next);
2077 BUG_ON(npath != NULL);
2078 npath = ext4_find_extent(inode, next, NULL, gb_flags);
2080 return PTR_ERR(npath);
2081 BUG_ON(npath->p_depth != path->p_depth);
2082 eh = npath[depth].p_hdr;
2083 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2084 ext_debug(inode, "next leaf isn't full(%d)\n",
2085 le16_to_cpu(eh->eh_entries));
2089 ext_debug(inode, "next leaf has no free space(%d,%d)\n",
2090 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2094 * There is no free space in the found leaf.
2095 * We're gonna add a new leaf in the tree.
2097 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2098 mb_flags |= EXT4_MB_USE_RESERVED;
2099 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2103 depth = ext_depth(inode);
2104 eh = path[depth].p_hdr;
2107 nearex = path[depth].p_ext;
2109 err = ext4_ext_get_access(handle, inode, path + depth);
2114 /* there is no extent in this leaf, create first one */
2115 ext_debug(inode, "first extent in the leaf: %u:%llu:[%d]%d\n",
2116 le32_to_cpu(newext->ee_block),
2117 ext4_ext_pblock(newext),
2118 ext4_ext_is_unwritten(newext),
2119 ext4_ext_get_actual_len(newext));
2120 nearex = EXT_FIRST_EXTENT(eh);
2122 if (le32_to_cpu(newext->ee_block)
2123 > le32_to_cpu(nearex->ee_block)) {
2125 ext_debug(inode, "insert %u:%llu:[%d]%d before: "
2127 le32_to_cpu(newext->ee_block),
2128 ext4_ext_pblock(newext),
2129 ext4_ext_is_unwritten(newext),
2130 ext4_ext_get_actual_len(newext),
2135 BUG_ON(newext->ee_block == nearex->ee_block);
2136 ext_debug(inode, "insert %u:%llu:[%d]%d after: "
2138 le32_to_cpu(newext->ee_block),
2139 ext4_ext_pblock(newext),
2140 ext4_ext_is_unwritten(newext),
2141 ext4_ext_get_actual_len(newext),
2144 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2146 ext_debug(inode, "insert %u:%llu:[%d]%d: "
2147 "move %d extents from 0x%p to 0x%p\n",
2148 le32_to_cpu(newext->ee_block),
2149 ext4_ext_pblock(newext),
2150 ext4_ext_is_unwritten(newext),
2151 ext4_ext_get_actual_len(newext),
2152 len, nearex, nearex + 1);
2153 memmove(nearex + 1, nearex,
2154 len * sizeof(struct ext4_extent));
2158 le16_add_cpu(&eh->eh_entries, 1);
2159 path[depth].p_ext = nearex;
2160 nearex->ee_block = newext->ee_block;
2161 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2162 nearex->ee_len = newext->ee_len;
2165 /* try to merge extents */
2166 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2167 ext4_ext_try_to_merge(handle, inode, path, nearex);
2170 /* time to correct all indexes above */
2171 err = ext4_ext_correct_indexes(handle, inode, path);
2175 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2178 ext4_ext_drop_refs(npath);
2183 static int ext4_fill_es_cache_info(struct inode *inode,
2184 ext4_lblk_t block, ext4_lblk_t num,
2185 struct fiemap_extent_info *fieinfo)
2187 ext4_lblk_t next, end = block + num - 1;
2188 struct extent_status es;
2189 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2193 while (block <= end) {
2196 if (!ext4_es_lookup_extent(inode, block, &next, &es))
2198 if (ext4_es_is_unwritten(&es))
2199 flags |= FIEMAP_EXTENT_UNWRITTEN;
2200 if (ext4_es_is_delayed(&es))
2201 flags |= (FIEMAP_EXTENT_DELALLOC |
2202 FIEMAP_EXTENT_UNKNOWN);
2203 if (ext4_es_is_hole(&es))
2204 flags |= EXT4_FIEMAP_EXTENT_HOLE;
2206 flags |= FIEMAP_EXTENT_LAST;
2207 if (flags & (FIEMAP_EXTENT_DELALLOC|
2208 EXT4_FIEMAP_EXTENT_HOLE))
2211 es.es_pblk = ext4_es_pblock(&es);
2212 err = fiemap_fill_next_extent(fieinfo,
2213 (__u64)es.es_lblk << blksize_bits,
2214 (__u64)es.es_pblk << blksize_bits,
2215 (__u64)es.es_len << blksize_bits,
2230 * ext4_ext_determine_hole - determine hole around given block
2231 * @inode: inode we lookup in
2232 * @path: path in extent tree to @lblk
2233 * @lblk: pointer to logical block around which we want to determine hole
2235 * Determine hole length (and start if easily possible) around given logical
2236 * block. We don't try too hard to find the beginning of the hole but @path
2237 * actually points to extent before @lblk, we provide it.
2239 * The function returns the length of a hole starting at @lblk. We update @lblk
2240 * to the beginning of the hole if we managed to find it.
2242 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2243 struct ext4_ext_path *path,
2246 int depth = ext_depth(inode);
2247 struct ext4_extent *ex;
2250 ex = path[depth].p_ext;
2252 /* there is no extent yet, so gap is [0;-] */
2254 len = EXT_MAX_BLOCKS;
2255 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2256 len = le32_to_cpu(ex->ee_block) - *lblk;
2257 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2258 + ext4_ext_get_actual_len(ex)) {
2261 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2262 next = ext4_ext_next_allocated_block(path);
2263 BUG_ON(next == *lblk);
2272 * ext4_ext_put_gap_in_cache:
2273 * calculate boundaries of the gap that the requested block fits into
2274 * and cache this gap
2277 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2278 ext4_lblk_t hole_len)
2280 struct extent_status es;
2282 ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
2283 hole_start + hole_len - 1, &es);
2285 /* There's delayed extent containing lblock? */
2286 if (es.es_lblk <= hole_start)
2288 hole_len = min(es.es_lblk - hole_start, hole_len);
2290 ext_debug(inode, " -> %u:%u\n", hole_start, hole_len);
2291 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2292 EXTENT_STATUS_HOLE);
2297 * removes index from the index block.
2299 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2300 struct ext4_ext_path *path, int depth)
2305 /* free index block */
2307 path = path + depth;
2308 leaf = ext4_idx_pblock(path->p_idx);
2309 if (unlikely(path->p_hdr->eh_entries == 0)) {
2310 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2311 return -EFSCORRUPTED;
2313 err = ext4_ext_get_access(handle, inode, path);
2317 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2318 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2319 len *= sizeof(struct ext4_extent_idx);
2320 memmove(path->p_idx, path->p_idx + 1, len);
2323 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2324 err = ext4_ext_dirty(handle, inode, path);
2327 ext_debug(inode, "index is empty, remove it, free block %llu\n", leaf);
2328 trace_ext4_ext_rm_idx(inode, leaf);
2330 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2331 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2333 while (--depth >= 0) {
2334 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2337 err = ext4_ext_get_access(handle, inode, path);
2340 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2341 err = ext4_ext_dirty(handle, inode, path);
2349 * ext4_ext_calc_credits_for_single_extent:
2350 * This routine returns max. credits that needed to insert an extent
2351 * to the extent tree.
2352 * When pass the actual path, the caller should calculate credits
2355 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2356 struct ext4_ext_path *path)
2359 int depth = ext_depth(inode);
2362 /* probably there is space in leaf? */
2363 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2364 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2367 * There are some space in the leaf tree, no
2368 * need to account for leaf block credit
2370 * bitmaps and block group descriptor blocks
2371 * and other metadata blocks still need to be
2374 /* 1 bitmap, 1 block group descriptor */
2375 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2380 return ext4_chunk_trans_blocks(inode, nrblocks);
2384 * How many index/leaf blocks need to change/allocate to add @extents extents?
2386 * If we add a single extent, then in the worse case, each tree level
2387 * index/leaf need to be changed in case of the tree split.
2389 * If more extents are inserted, they could cause the whole tree split more
2390 * than once, but this is really rare.
2392 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2397 /* If we are converting the inline data, only one is needed here. */
2398 if (ext4_has_inline_data(inode))
2401 depth = ext_depth(inode);
2411 static inline int get_default_free_blocks_flags(struct inode *inode)
2413 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2414 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2415 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2416 else if (ext4_should_journal_data(inode))
2417 return EXT4_FREE_BLOCKS_FORGET;
2422 * ext4_rereserve_cluster - increment the reserved cluster count when
2423 * freeing a cluster with a pending reservation
2425 * @inode - file containing the cluster
2426 * @lblk - logical block in cluster to be reserved
2428 * Increments the reserved cluster count and adjusts quota in a bigalloc
2429 * file system when freeing a partial cluster containing at least one
2430 * delayed and unwritten block. A partial cluster meeting that
2431 * requirement will have a pending reservation. If so, the
2432 * RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
2433 * defer reserved and allocated space accounting to a subsequent call
2436 static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
2438 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2439 struct ext4_inode_info *ei = EXT4_I(inode);
2441 dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
2443 spin_lock(&ei->i_block_reservation_lock);
2444 ei->i_reserved_data_blocks++;
2445 percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
2446 spin_unlock(&ei->i_block_reservation_lock);
2448 percpu_counter_add(&sbi->s_freeclusters_counter, 1);
2449 ext4_remove_pending(inode, lblk);
2452 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2453 struct ext4_extent *ex,
2454 struct partial_cluster *partial,
2455 ext4_lblk_t from, ext4_lblk_t to)
2457 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2458 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2459 ext4_fsblk_t last_pblk, pblk;
2463 /* only extent tail removal is allowed */
2464 if (from < le32_to_cpu(ex->ee_block) ||
2465 to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
2466 ext4_error(sbi->s_sb,
2467 "strange request: removal(2) %u-%u from %u:%u",
2468 from, to, le32_to_cpu(ex->ee_block), ee_len);
2472 #ifdef EXTENTS_STATS
2473 spin_lock(&sbi->s_ext_stats_lock);
2474 sbi->s_ext_blocks += ee_len;
2475 sbi->s_ext_extents++;
2476 if (ee_len < sbi->s_ext_min)
2477 sbi->s_ext_min = ee_len;
2478 if (ee_len > sbi->s_ext_max)
2479 sbi->s_ext_max = ee_len;
2480 if (ext_depth(inode) > sbi->s_depth_max)
2481 sbi->s_depth_max = ext_depth(inode);
2482 spin_unlock(&sbi->s_ext_stats_lock);
2485 trace_ext4_remove_blocks(inode, ex, from, to, partial);
2488 * if we have a partial cluster, and it's different from the
2489 * cluster of the last block in the extent, we free it
2491 last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
2493 if (partial->state != initial &&
2494 partial->pclu != EXT4_B2C(sbi, last_pblk)) {
2495 if (partial->state == tofree) {
2496 flags = get_default_free_blocks_flags(inode);
2497 if (ext4_is_pending(inode, partial->lblk))
2498 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2499 ext4_free_blocks(handle, inode, NULL,
2500 EXT4_C2B(sbi, partial->pclu),
2501 sbi->s_cluster_ratio, flags);
2502 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2503 ext4_rereserve_cluster(inode, partial->lblk);
2505 partial->state = initial;
2508 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2509 pblk = ext4_ext_pblock(ex) + ee_len - num;
2512 * We free the partial cluster at the end of the extent (if any),
2513 * unless the cluster is used by another extent (partial_cluster
2514 * state is nofree). If a partial cluster exists here, it must be
2515 * shared with the last block in the extent.
2517 flags = get_default_free_blocks_flags(inode);
2519 /* partial, left end cluster aligned, right end unaligned */
2520 if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
2521 (EXT4_LBLK_CMASK(sbi, to) >= from) &&
2522 (partial->state != nofree)) {
2523 if (ext4_is_pending(inode, to))
2524 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2525 ext4_free_blocks(handle, inode, NULL,
2526 EXT4_PBLK_CMASK(sbi, last_pblk),
2527 sbi->s_cluster_ratio, flags);
2528 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2529 ext4_rereserve_cluster(inode, to);
2530 partial->state = initial;
2531 flags = get_default_free_blocks_flags(inode);
2534 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2537 * For bigalloc file systems, we never free a partial cluster
2538 * at the beginning of the extent. Instead, we check to see if we
2539 * need to free it on a subsequent call to ext4_remove_blocks,
2540 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2542 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2543 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2545 /* reset the partial cluster if we've freed past it */
2546 if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
2547 partial->state = initial;
2550 * If we've freed the entire extent but the beginning is not left
2551 * cluster aligned and is not marked as ineligible for freeing we
2552 * record the partial cluster at the beginning of the extent. It
2553 * wasn't freed by the preceding ext4_free_blocks() call, and we
2554 * need to look farther to the left to determine if it's to be freed
2555 * (not shared with another extent). Else, reset the partial
2556 * cluster - we're either done freeing or the beginning of the
2557 * extent is left cluster aligned.
2559 if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
2560 if (partial->state == initial) {
2561 partial->pclu = EXT4_B2C(sbi, pblk);
2562 partial->lblk = from;
2563 partial->state = tofree;
2566 partial->state = initial;
2573 * ext4_ext_rm_leaf() Removes the extents associated with the
2574 * blocks appearing between "start" and "end". Both "start"
2575 * and "end" must appear in the same extent or EIO is returned.
2577 * @handle: The journal handle
2578 * @inode: The files inode
2579 * @path: The path to the leaf
2580 * @partial_cluster: The cluster which we'll have to free if all extents
2581 * has been released from it. However, if this value is
2582 * negative, it's a cluster just to the right of the
2583 * punched region and it must not be freed.
2584 * @start: The first block to remove
2585 * @end: The last block to remove
2588 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2589 struct ext4_ext_path *path,
2590 struct partial_cluster *partial,
2591 ext4_lblk_t start, ext4_lblk_t end)
2593 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2594 int err = 0, correct_index = 0;
2595 int depth = ext_depth(inode), credits, revoke_credits;
2596 struct ext4_extent_header *eh;
2599 ext4_lblk_t ex_ee_block;
2600 unsigned short ex_ee_len;
2601 unsigned unwritten = 0;
2602 struct ext4_extent *ex;
2605 /* the header must be checked already in ext4_ext_remove_space() */
2606 ext_debug(inode, "truncate since %u in leaf to %u\n", start, end);
2607 if (!path[depth].p_hdr)
2608 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2609 eh = path[depth].p_hdr;
2610 if (unlikely(path[depth].p_hdr == NULL)) {
2611 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2612 return -EFSCORRUPTED;
2614 /* find where to start removing */
2615 ex = path[depth].p_ext;
2617 ex = EXT_LAST_EXTENT(eh);
2619 ex_ee_block = le32_to_cpu(ex->ee_block);
2620 ex_ee_len = ext4_ext_get_actual_len(ex);
2622 trace_ext4_ext_rm_leaf(inode, start, ex, partial);
2624 while (ex >= EXT_FIRST_EXTENT(eh) &&
2625 ex_ee_block + ex_ee_len > start) {
2627 if (ext4_ext_is_unwritten(ex))
2632 ext_debug(inode, "remove ext %u:[%d]%d\n", ex_ee_block,
2633 unwritten, ex_ee_len);
2634 path[depth].p_ext = ex;
2636 a = ex_ee_block > start ? ex_ee_block : start;
2637 b = ex_ee_block+ex_ee_len - 1 < end ?
2638 ex_ee_block+ex_ee_len - 1 : end;
2640 ext_debug(inode, " border %u:%u\n", a, b);
2642 /* If this extent is beyond the end of the hole, skip it */
2643 if (end < ex_ee_block) {
2645 * We're going to skip this extent and move to another,
2646 * so note that its first cluster is in use to avoid
2647 * freeing it when removing blocks. Eventually, the
2648 * right edge of the truncated/punched region will
2649 * be just to the left.
2651 if (sbi->s_cluster_ratio > 1) {
2652 pblk = ext4_ext_pblock(ex);
2653 partial->pclu = EXT4_B2C(sbi, pblk);
2654 partial->state = nofree;
2657 ex_ee_block = le32_to_cpu(ex->ee_block);
2658 ex_ee_len = ext4_ext_get_actual_len(ex);
2660 } else if (b != ex_ee_block + ex_ee_len - 1) {
2661 EXT4_ERROR_INODE(inode,
2662 "can not handle truncate %u:%u "
2664 start, end, ex_ee_block,
2665 ex_ee_block + ex_ee_len - 1);
2666 err = -EFSCORRUPTED;
2668 } else if (a != ex_ee_block) {
2669 /* remove tail of the extent */
2670 num = a - ex_ee_block;
2672 /* remove whole extent: excellent! */
2676 * 3 for leaf, sb, and inode plus 2 (bmap and group
2677 * descriptor) for each block group; assume two block
2678 * groups plus ex_ee_len/blocks_per_block_group for
2681 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2682 if (ex == EXT_FIRST_EXTENT(eh)) {
2684 credits += (ext_depth(inode)) + 1;
2686 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2688 * We may end up freeing some index blocks and data from the
2689 * punched range. Note that partial clusters are accounted for
2690 * by ext4_free_data_revoke_credits().
2693 ext4_free_metadata_revoke_credits(inode->i_sb,
2695 ext4_free_data_revoke_credits(inode, b - a + 1);
2697 err = ext4_datasem_ensure_credits(handle, inode, credits,
2698 credits, revoke_credits);
2705 err = ext4_ext_get_access(handle, inode, path + depth);
2709 err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
2714 /* this extent is removed; mark slot entirely unused */
2715 ext4_ext_store_pblock(ex, 0);
2717 ex->ee_len = cpu_to_le16(num);
2719 * Do not mark unwritten if all the blocks in the
2720 * extent have been removed.
2722 if (unwritten && num)
2723 ext4_ext_mark_unwritten(ex);
2725 * If the extent was completely released,
2726 * we need to remove it from the leaf
2729 if (end != EXT_MAX_BLOCKS - 1) {
2731 * For hole punching, we need to scoot all the
2732 * extents up when an extent is removed so that
2733 * we dont have blank extents in the middle
2735 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2736 sizeof(struct ext4_extent));
2738 /* Now get rid of the one at the end */
2739 memset(EXT_LAST_EXTENT(eh), 0,
2740 sizeof(struct ext4_extent));
2742 le16_add_cpu(&eh->eh_entries, -1);
2745 err = ext4_ext_dirty(handle, inode, path + depth);
2749 ext_debug(inode, "new extent: %u:%u:%llu\n", ex_ee_block, num,
2750 ext4_ext_pblock(ex));
2752 ex_ee_block = le32_to_cpu(ex->ee_block);
2753 ex_ee_len = ext4_ext_get_actual_len(ex);
2756 if (correct_index && eh->eh_entries)
2757 err = ext4_ext_correct_indexes(handle, inode, path);
2760 * If there's a partial cluster and at least one extent remains in
2761 * the leaf, free the partial cluster if it isn't shared with the
2762 * current extent. If it is shared with the current extent
2763 * we reset the partial cluster because we've reached the start of the
2764 * truncated/punched region and we're done removing blocks.
2766 if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
2767 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2768 if (partial->pclu != EXT4_B2C(sbi, pblk)) {
2769 int flags = get_default_free_blocks_flags(inode);
2771 if (ext4_is_pending(inode, partial->lblk))
2772 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2773 ext4_free_blocks(handle, inode, NULL,
2774 EXT4_C2B(sbi, partial->pclu),
2775 sbi->s_cluster_ratio, flags);
2776 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2777 ext4_rereserve_cluster(inode, partial->lblk);
2779 partial->state = initial;
2782 /* if this leaf is free, then we should
2783 * remove it from index block above */
2784 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2785 err = ext4_ext_rm_idx(handle, inode, path, depth);
2792 * ext4_ext_more_to_rm:
2793 * returns 1 if current index has to be freed (even partial)
2796 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2798 BUG_ON(path->p_idx == NULL);
2800 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2804 * if truncate on deeper level happened, it wasn't partial,
2805 * so we have to consider current index for truncation
2807 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2812 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2815 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2816 int depth = ext_depth(inode);
2817 struct ext4_ext_path *path = NULL;
2818 struct partial_cluster partial;
2824 partial.state = initial;
2826 ext_debug(inode, "truncate since %u to %u\n", start, end);
2828 /* probably first extent we're gonna free will be last in block */
2829 handle = ext4_journal_start_with_revoke(inode, EXT4_HT_TRUNCATE,
2831 ext4_free_metadata_revoke_credits(inode->i_sb, depth));
2833 return PTR_ERR(handle);
2836 trace_ext4_ext_remove_space(inode, start, end, depth);
2839 * Check if we are removing extents inside the extent tree. If that
2840 * is the case, we are going to punch a hole inside the extent tree
2841 * so we have to check whether we need to split the extent covering
2842 * the last block to remove so we can easily remove the part of it
2843 * in ext4_ext_rm_leaf().
2845 if (end < EXT_MAX_BLOCKS - 1) {
2846 struct ext4_extent *ex;
2847 ext4_lblk_t ee_block, ex_end, lblk;
2850 /* find extent for or closest extent to this block */
2851 path = ext4_find_extent(inode, end, NULL,
2852 EXT4_EX_NOCACHE | EXT4_EX_NOFAIL);
2854 ext4_journal_stop(handle);
2855 return PTR_ERR(path);
2857 depth = ext_depth(inode);
2858 /* Leaf not may not exist only if inode has no blocks at all */
2859 ex = path[depth].p_ext;
2862 EXT4_ERROR_INODE(inode,
2863 "path[%d].p_hdr == NULL",
2865 err = -EFSCORRUPTED;
2870 ee_block = le32_to_cpu(ex->ee_block);
2871 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2874 * See if the last block is inside the extent, if so split
2875 * the extent at 'end' block so we can easily remove the
2876 * tail of the first part of the split extent in
2877 * ext4_ext_rm_leaf().
2879 if (end >= ee_block && end < ex_end) {
2882 * If we're going to split the extent, note that
2883 * the cluster containing the block after 'end' is
2884 * in use to avoid freeing it when removing blocks.
2886 if (sbi->s_cluster_ratio > 1) {
2887 pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
2888 partial.pclu = EXT4_B2C(sbi, pblk);
2889 partial.state = nofree;
2893 * Split the extent in two so that 'end' is the last
2894 * block in the first new extent. Also we should not
2895 * fail removing space due to ENOSPC so try to use
2896 * reserved block if that happens.
2898 err = ext4_force_split_extent_at(handle, inode, &path,
2903 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
2904 partial.state == initial) {
2906 * If we're punching, there's an extent to the right.
2907 * If the partial cluster hasn't been set, set it to
2908 * that extent's first cluster and its state to nofree
2909 * so it won't be freed should it contain blocks to be
2910 * removed. If it's already set (tofree/nofree), we're
2911 * retrying and keep the original partial cluster info
2912 * so a cluster marked tofree as a result of earlier
2913 * extent removal is not lost.
2916 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2921 partial.pclu = EXT4_B2C(sbi, pblk);
2922 partial.state = nofree;
2927 * We start scanning from right side, freeing all the blocks
2928 * after i_size and walking into the tree depth-wise.
2930 depth = ext_depth(inode);
2935 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2937 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
2938 GFP_NOFS | __GFP_NOFAIL);
2940 ext4_journal_stop(handle);
2943 path[0].p_maxdepth = path[0].p_depth = depth;
2944 path[0].p_hdr = ext_inode_hdr(inode);
2947 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2948 err = -EFSCORRUPTED;
2954 while (i >= 0 && err == 0) {
2956 /* this is leaf block */
2957 err = ext4_ext_rm_leaf(handle, inode, path,
2958 &partial, start, end);
2959 /* root level has p_bh == NULL, brelse() eats this */
2960 brelse(path[i].p_bh);
2961 path[i].p_bh = NULL;
2966 /* this is index block */
2967 if (!path[i].p_hdr) {
2968 ext_debug(inode, "initialize header\n");
2969 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2972 if (!path[i].p_idx) {
2973 /* this level hasn't been touched yet */
2974 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2975 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2976 ext_debug(inode, "init index ptr: hdr 0x%p, num %d\n",
2978 le16_to_cpu(path[i].p_hdr->eh_entries));
2980 /* we were already here, see at next index */
2984 ext_debug(inode, "level %d - index, first 0x%p, cur 0x%p\n",
2985 i, EXT_FIRST_INDEX(path[i].p_hdr),
2987 if (ext4_ext_more_to_rm(path + i)) {
2988 struct buffer_head *bh;
2989 /* go to the next level */
2990 ext_debug(inode, "move to level %d (block %llu)\n",
2991 i + 1, ext4_idx_pblock(path[i].p_idx));
2992 memset(path + i + 1, 0, sizeof(*path));
2993 bh = read_extent_tree_block(inode, path[i].p_idx,
2997 /* should we reset i_size? */
3001 /* Yield here to deal with large extent trees.
3002 * Should be a no-op if we did IO above. */
3004 if (WARN_ON(i + 1 > depth)) {
3005 err = -EFSCORRUPTED;
3008 path[i + 1].p_bh = bh;
3010 /* save actual number of indexes since this
3011 * number is changed at the next iteration */
3012 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3015 /* we finished processing this index, go up */
3016 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3017 /* index is empty, remove it;
3018 * handle must be already prepared by the
3019 * truncatei_leaf() */
3020 err = ext4_ext_rm_idx(handle, inode, path, i);
3022 /* root level has p_bh == NULL, brelse() eats this */
3023 brelse(path[i].p_bh);
3024 path[i].p_bh = NULL;
3026 ext_debug(inode, "return to level %d\n", i);
3030 trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
3031 path->p_hdr->eh_entries);
3034 * if there's a partial cluster and we have removed the first extent
3035 * in the file, then we also free the partial cluster, if any
3037 if (partial.state == tofree && err == 0) {
3038 int flags = get_default_free_blocks_flags(inode);
3040 if (ext4_is_pending(inode, partial.lblk))
3041 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
3042 ext4_free_blocks(handle, inode, NULL,
3043 EXT4_C2B(sbi, partial.pclu),
3044 sbi->s_cluster_ratio, flags);
3045 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
3046 ext4_rereserve_cluster(inode, partial.lblk);
3047 partial.state = initial;
3050 /* TODO: flexible tree reduction should be here */
3051 if (path->p_hdr->eh_entries == 0) {
3053 * truncate to zero freed all the tree,
3054 * so we need to correct eh_depth
3056 err = ext4_ext_get_access(handle, inode, path);
3058 ext_inode_hdr(inode)->eh_depth = 0;
3059 ext_inode_hdr(inode)->eh_max =
3060 cpu_to_le16(ext4_ext_space_root(inode, 0));
3061 err = ext4_ext_dirty(handle, inode, path);
3065 ext4_ext_drop_refs(path);
3070 ext4_journal_stop(handle);
3076 * called at mount time
3078 void ext4_ext_init(struct super_block *sb)
3081 * possible initialization would be here
3084 if (ext4_has_feature_extents(sb)) {
3085 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3086 printk(KERN_INFO "EXT4-fs: file extents enabled"
3087 #ifdef AGGRESSIVE_TEST
3088 ", aggressive tests"
3090 #ifdef CHECK_BINSEARCH
3093 #ifdef EXTENTS_STATS
3098 #ifdef EXTENTS_STATS
3099 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3100 EXT4_SB(sb)->s_ext_min = 1 << 30;
3101 EXT4_SB(sb)->s_ext_max = 0;
3107 * called at umount time
3109 void ext4_ext_release(struct super_block *sb)
3111 if (!ext4_has_feature_extents(sb))
3114 #ifdef EXTENTS_STATS
3115 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3116 struct ext4_sb_info *sbi = EXT4_SB(sb);
3117 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3118 sbi->s_ext_blocks, sbi->s_ext_extents,
3119 sbi->s_ext_blocks / sbi->s_ext_extents);
3120 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3121 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3126 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3128 ext4_lblk_t ee_block;
3129 ext4_fsblk_t ee_pblock;
3130 unsigned int ee_len;
3132 ee_block = le32_to_cpu(ex->ee_block);
3133 ee_len = ext4_ext_get_actual_len(ex);
3134 ee_pblock = ext4_ext_pblock(ex);
3139 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3140 EXTENT_STATUS_WRITTEN);
3143 /* FIXME!! we need to try to merge to left or right after zero-out */
3144 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3146 ext4_fsblk_t ee_pblock;
3147 unsigned int ee_len;
3149 ee_len = ext4_ext_get_actual_len(ex);
3150 ee_pblock = ext4_ext_pblock(ex);
3151 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3156 * ext4_split_extent_at() splits an extent at given block.
3158 * @handle: the journal handle
3159 * @inode: the file inode
3160 * @path: the path to the extent
3161 * @split: the logical block where the extent is splitted.
3162 * @split_flags: indicates if the extent could be zeroout if split fails, and
3163 * the states(init or unwritten) of new extents.
3164 * @flags: flags used to insert new extent to extent tree.
3167 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3168 * of which are determined by split_flag.
3170 * There are two cases:
3171 * a> the extent are splitted into two extent.
3172 * b> split is not needed, and just mark the extent.
3174 * return 0 on success.
3176 static int ext4_split_extent_at(handle_t *handle,
3177 struct inode *inode,
3178 struct ext4_ext_path **ppath,
3183 struct ext4_ext_path *path = *ppath;
3184 ext4_fsblk_t newblock;
3185 ext4_lblk_t ee_block;
3186 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3187 struct ext4_extent *ex2 = NULL;
3188 unsigned int ee_len, depth;
3191 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3192 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3194 ext_debug(inode, "logical block %llu\n", (unsigned long long)split);
3196 ext4_ext_show_leaf(inode, path);
3198 depth = ext_depth(inode);
3199 ex = path[depth].p_ext;
3200 ee_block = le32_to_cpu(ex->ee_block);
3201 ee_len = ext4_ext_get_actual_len(ex);
3202 newblock = split - ee_block + ext4_ext_pblock(ex);
3204 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3205 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3206 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3207 EXT4_EXT_MARK_UNWRIT1 |
3208 EXT4_EXT_MARK_UNWRIT2));
3210 err = ext4_ext_get_access(handle, inode, path + depth);
3214 if (split == ee_block) {
3216 * case b: block @split is the block that the extent begins with
3217 * then we just change the state of the extent, and splitting
3220 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3221 ext4_ext_mark_unwritten(ex);
3223 ext4_ext_mark_initialized(ex);
3225 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3226 ext4_ext_try_to_merge(handle, inode, path, ex);
3228 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3233 memcpy(&orig_ex, ex, sizeof(orig_ex));
3234 ex->ee_len = cpu_to_le16(split - ee_block);
3235 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3236 ext4_ext_mark_unwritten(ex);
3239 * path may lead to new leaf, not to original leaf any more
3240 * after ext4_ext_insert_extent() returns,
3242 err = ext4_ext_dirty(handle, inode, path + depth);
3244 goto fix_extent_len;
3247 ex2->ee_block = cpu_to_le32(split);
3248 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3249 ext4_ext_store_pblock(ex2, newblock);
3250 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3251 ext4_ext_mark_unwritten(ex2);
3253 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3254 if (err != -ENOSPC && err != -EDQUOT)
3257 if (EXT4_EXT_MAY_ZEROOUT & split_flag) {
3258 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3259 if (split_flag & EXT4_EXT_DATA_VALID1) {
3260 err = ext4_ext_zeroout(inode, ex2);
3261 zero_ex.ee_block = ex2->ee_block;
3262 zero_ex.ee_len = cpu_to_le16(
3263 ext4_ext_get_actual_len(ex2));
3264 ext4_ext_store_pblock(&zero_ex,
3265 ext4_ext_pblock(ex2));
3267 err = ext4_ext_zeroout(inode, ex);
3268 zero_ex.ee_block = ex->ee_block;
3269 zero_ex.ee_len = cpu_to_le16(
3270 ext4_ext_get_actual_len(ex));
3271 ext4_ext_store_pblock(&zero_ex,
3272 ext4_ext_pblock(ex));
3275 err = ext4_ext_zeroout(inode, &orig_ex);
3276 zero_ex.ee_block = orig_ex.ee_block;
3277 zero_ex.ee_len = cpu_to_le16(
3278 ext4_ext_get_actual_len(&orig_ex));
3279 ext4_ext_store_pblock(&zero_ex,
3280 ext4_ext_pblock(&orig_ex));
3284 /* update the extent length and mark as initialized */
3285 ex->ee_len = cpu_to_le16(ee_len);
3286 ext4_ext_try_to_merge(handle, inode, path, ex);
3287 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3289 /* update extent status tree */
3290 err = ext4_zeroout_es(inode, &zero_ex);
3291 /* If we failed at this point, we don't know in which
3292 * state the extent tree exactly is so don't try to fix
3293 * length of the original extent as it may do even more
3301 ex->ee_len = orig_ex.ee_len;
3303 * Ignore ext4_ext_dirty return value since we are already in error path
3304 * and err is a non-zero error code.
3306 ext4_ext_dirty(handle, inode, path + path->p_depth);
3309 ext4_ext_show_leaf(inode, path);
3314 * ext4_split_extents() splits an extent and mark extent which is covered
3315 * by @map as split_flags indicates
3317 * It may result in splitting the extent into multiple extents (up to three)
3318 * There are three possibilities:
3319 * a> There is no split required
3320 * b> Splits in two extents: Split is happening at either end of the extent
3321 * c> Splits in three extents: Somone is splitting in middle of the extent
3324 static int ext4_split_extent(handle_t *handle,
3325 struct inode *inode,
3326 struct ext4_ext_path **ppath,
3327 struct ext4_map_blocks *map,
3331 struct ext4_ext_path *path = *ppath;
3332 ext4_lblk_t ee_block;
3333 struct ext4_extent *ex;
3334 unsigned int ee_len, depth;
3337 int split_flag1, flags1;
3338 int allocated = map->m_len;
3340 depth = ext_depth(inode);
3341 ex = path[depth].p_ext;
3342 ee_block = le32_to_cpu(ex->ee_block);
3343 ee_len = ext4_ext_get_actual_len(ex);
3344 unwritten = ext4_ext_is_unwritten(ex);
3346 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3347 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3348 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3350 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3351 EXT4_EXT_MARK_UNWRIT2;
3352 if (split_flag & EXT4_EXT_DATA_VALID2)
3353 split_flag1 |= EXT4_EXT_DATA_VALID1;
3354 err = ext4_split_extent_at(handle, inode, ppath,
3355 map->m_lblk + map->m_len, split_flag1, flags1);
3359 allocated = ee_len - (map->m_lblk - ee_block);
3362 * Update path is required because previous ext4_split_extent_at() may
3363 * result in split of original leaf or extent zeroout.
3365 path = ext4_find_extent(inode, map->m_lblk, ppath, flags);
3367 return PTR_ERR(path);
3368 depth = ext_depth(inode);
3369 ex = path[depth].p_ext;
3371 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3372 (unsigned long) map->m_lblk);
3373 return -EFSCORRUPTED;
3375 unwritten = ext4_ext_is_unwritten(ex);
3378 if (map->m_lblk >= ee_block) {
3379 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3381 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3382 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3383 EXT4_EXT_MARK_UNWRIT2);
3385 err = ext4_split_extent_at(handle, inode, ppath,
3386 map->m_lblk, split_flag1, flags);
3391 ext4_ext_show_leaf(inode, path);
3393 return err ? err : allocated;
3397 * This function is called by ext4_ext_map_blocks() if someone tries to write
3398 * to an unwritten extent. It may result in splitting the unwritten
3399 * extent into multiple extents (up to three - one initialized and two
3401 * There are three possibilities:
3402 * a> There is no split required: Entire extent should be initialized
3403 * b> Splits in two extents: Write is happening at either end of the extent
3404 * c> Splits in three extents: Somone is writing in middle of the extent
3407 * - The extent pointed to by 'path' is unwritten.
3408 * - The extent pointed to by 'path' contains a superset
3409 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3411 * Post-conditions on success:
3412 * - the returned value is the number of blocks beyond map->l_lblk
3413 * that are allocated and initialized.
3414 * It is guaranteed to be >= map->m_len.
3416 static int ext4_ext_convert_to_initialized(handle_t *handle,
3417 struct inode *inode,
3418 struct ext4_map_blocks *map,
3419 struct ext4_ext_path **ppath,
3422 struct ext4_ext_path *path = *ppath;
3423 struct ext4_sb_info *sbi;
3424 struct ext4_extent_header *eh;
3425 struct ext4_map_blocks split_map;
3426 struct ext4_extent zero_ex1, zero_ex2;
3427 struct ext4_extent *ex, *abut_ex;
3428 ext4_lblk_t ee_block, eof_block;
3429 unsigned int ee_len, depth, map_len = map->m_len;
3430 int allocated = 0, max_zeroout = 0;
3432 int split_flag = EXT4_EXT_DATA_VALID2;
3434 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3435 (unsigned long long)map->m_lblk, map_len);
3437 sbi = EXT4_SB(inode->i_sb);
3438 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3439 >> inode->i_sb->s_blocksize_bits;
3440 if (eof_block < map->m_lblk + map_len)
3441 eof_block = map->m_lblk + map_len;
3443 depth = ext_depth(inode);
3444 eh = path[depth].p_hdr;
3445 ex = path[depth].p_ext;
3446 ee_block = le32_to_cpu(ex->ee_block);
3447 ee_len = ext4_ext_get_actual_len(ex);
3448 zero_ex1.ee_len = 0;
3449 zero_ex2.ee_len = 0;
3451 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3453 /* Pre-conditions */
3454 BUG_ON(!ext4_ext_is_unwritten(ex));
3455 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3458 * Attempt to transfer newly initialized blocks from the currently
3459 * unwritten extent to its neighbor. This is much cheaper
3460 * than an insertion followed by a merge as those involve costly
3461 * memmove() calls. Transferring to the left is the common case in
3462 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3463 * followed by append writes.
3465 * Limitations of the current logic:
3466 * - L1: we do not deal with writes covering the whole extent.
3467 * This would require removing the extent if the transfer
3469 * - L2: we only attempt to merge with an extent stored in the
3470 * same extent tree node.
3472 if ((map->m_lblk == ee_block) &&
3473 /* See if we can merge left */
3474 (map_len < ee_len) && /*L1*/
3475 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3476 ext4_lblk_t prev_lblk;
3477 ext4_fsblk_t prev_pblk, ee_pblk;
3478 unsigned int prev_len;
3481 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3482 prev_len = ext4_ext_get_actual_len(abut_ex);
3483 prev_pblk = ext4_ext_pblock(abut_ex);
3484 ee_pblk = ext4_ext_pblock(ex);
3487 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3488 * upon those conditions:
3489 * - C1: abut_ex is initialized,
3490 * - C2: abut_ex is logically abutting ex,
3491 * - C3: abut_ex is physically abutting ex,
3492 * - C4: abut_ex can receive the additional blocks without
3493 * overflowing the (initialized) length limit.
3495 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3496 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3497 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3498 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3499 err = ext4_ext_get_access(handle, inode, path + depth);
3503 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3506 /* Shift the start of ex by 'map_len' blocks */
3507 ex->ee_block = cpu_to_le32(ee_block + map_len);
3508 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3509 ex->ee_len = cpu_to_le16(ee_len - map_len);
3510 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3512 /* Extend abut_ex by 'map_len' blocks */
3513 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3515 /* Result: number of initialized blocks past m_lblk */
3516 allocated = map_len;
3518 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3519 (map_len < ee_len) && /*L1*/
3520 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3521 /* See if we can merge right */
3522 ext4_lblk_t next_lblk;
3523 ext4_fsblk_t next_pblk, ee_pblk;
3524 unsigned int next_len;
3527 next_lblk = le32_to_cpu(abut_ex->ee_block);
3528 next_len = ext4_ext_get_actual_len(abut_ex);
3529 next_pblk = ext4_ext_pblock(abut_ex);
3530 ee_pblk = ext4_ext_pblock(ex);
3533 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3534 * upon those conditions:
3535 * - C1: abut_ex is initialized,
3536 * - C2: abut_ex is logically abutting ex,
3537 * - C3: abut_ex is physically abutting ex,
3538 * - C4: abut_ex can receive the additional blocks without
3539 * overflowing the (initialized) length limit.
3541 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3542 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3543 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3544 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3545 err = ext4_ext_get_access(handle, inode, path + depth);
3549 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3552 /* Shift the start of abut_ex by 'map_len' blocks */
3553 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3554 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3555 ex->ee_len = cpu_to_le16(ee_len - map_len);
3556 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3558 /* Extend abut_ex by 'map_len' blocks */
3559 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3561 /* Result: number of initialized blocks past m_lblk */
3562 allocated = map_len;
3566 /* Mark the block containing both extents as dirty */
3567 err = ext4_ext_dirty(handle, inode, path + depth);
3569 /* Update path to point to the right extent */
3570 path[depth].p_ext = abut_ex;
3573 allocated = ee_len - (map->m_lblk - ee_block);
3575 WARN_ON(map->m_lblk < ee_block);
3577 * It is safe to convert extent to initialized via explicit
3578 * zeroout only if extent is fully inside i_size or new_size.
3580 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3582 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3583 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3584 (inode->i_sb->s_blocksize_bits - 10);
3588 * 1. split the extent into three extents.
3589 * 2. split the extent into two extents, zeroout the head of the first
3591 * 3. split the extent into two extents, zeroout the tail of the second
3593 * 4. split the extent into two extents with out zeroout.
3594 * 5. no splitting needed, just possibly zeroout the head and / or the
3595 * tail of the extent.
3597 split_map.m_lblk = map->m_lblk;
3598 split_map.m_len = map->m_len;
3600 if (max_zeroout && (allocated > split_map.m_len)) {
3601 if (allocated <= max_zeroout) {
3604 cpu_to_le32(split_map.m_lblk +
3607 cpu_to_le16(allocated - split_map.m_len);
3608 ext4_ext_store_pblock(&zero_ex1,
3609 ext4_ext_pblock(ex) + split_map.m_lblk +
3610 split_map.m_len - ee_block);
3611 err = ext4_ext_zeroout(inode, &zero_ex1);
3614 split_map.m_len = allocated;
3616 if (split_map.m_lblk - ee_block + split_map.m_len <
3619 if (split_map.m_lblk != ee_block) {
3620 zero_ex2.ee_block = ex->ee_block;
3621 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3623 ext4_ext_store_pblock(&zero_ex2,
3624 ext4_ext_pblock(ex));
3625 err = ext4_ext_zeroout(inode, &zero_ex2);
3630 split_map.m_len += split_map.m_lblk - ee_block;
3631 split_map.m_lblk = ee_block;
3632 allocated = map->m_len;
3637 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3642 /* If we have gotten a failure, don't zero out status tree */
3644 err = ext4_zeroout_es(inode, &zero_ex1);
3646 err = ext4_zeroout_es(inode, &zero_ex2);
3648 return err ? err : allocated;
3652 * This function is called by ext4_ext_map_blocks() from
3653 * ext4_get_blocks_dio_write() when DIO to write
3654 * to an unwritten extent.
3656 * Writing to an unwritten extent may result in splitting the unwritten
3657 * extent into multiple initialized/unwritten extents (up to three)
3658 * There are three possibilities:
3659 * a> There is no split required: Entire extent should be unwritten
3660 * b> Splits in two extents: Write is happening at either end of the extent
3661 * c> Splits in three extents: Somone is writing in middle of the extent
3663 * This works the same way in the case of initialized -> unwritten conversion.
3665 * One of more index blocks maybe needed if the extent tree grow after
3666 * the unwritten extent split. To prevent ENOSPC occur at the IO
3667 * complete, we need to split the unwritten extent before DIO submit
3668 * the IO. The unwritten extent called at this time will be split
3669 * into three unwritten extent(at most). After IO complete, the part
3670 * being filled will be convert to initialized by the end_io callback function
3671 * via ext4_convert_unwritten_extents().
3673 * Returns the size of unwritten extent to be written on success.
3675 static int ext4_split_convert_extents(handle_t *handle,
3676 struct inode *inode,
3677 struct ext4_map_blocks *map,
3678 struct ext4_ext_path **ppath,
3681 struct ext4_ext_path *path = *ppath;
3682 ext4_lblk_t eof_block;
3683 ext4_lblk_t ee_block;
3684 struct ext4_extent *ex;
3685 unsigned int ee_len;
3686 int split_flag = 0, depth;
3688 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3689 (unsigned long long)map->m_lblk, map->m_len);
3691 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3692 >> inode->i_sb->s_blocksize_bits;
3693 if (eof_block < map->m_lblk + map->m_len)
3694 eof_block = map->m_lblk + map->m_len;
3696 * It is safe to convert extent to initialized via explicit
3697 * zeroout only if extent is fully inside i_size or new_size.
3699 depth = ext_depth(inode);
3700 ex = path[depth].p_ext;
3701 ee_block = le32_to_cpu(ex->ee_block);
3702 ee_len = ext4_ext_get_actual_len(ex);
3704 /* Convert to unwritten */
3705 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3706 split_flag |= EXT4_EXT_DATA_VALID1;
3707 /* Convert to initialized */
3708 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3709 split_flag |= ee_block + ee_len <= eof_block ?
3710 EXT4_EXT_MAY_ZEROOUT : 0;
3711 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3713 flags |= EXT4_GET_BLOCKS_PRE_IO;
3714 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3717 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3718 struct inode *inode,
3719 struct ext4_map_blocks *map,
3720 struct ext4_ext_path **ppath)
3722 struct ext4_ext_path *path = *ppath;
3723 struct ext4_extent *ex;
3724 ext4_lblk_t ee_block;
3725 unsigned int ee_len;
3729 depth = ext_depth(inode);
3730 ex = path[depth].p_ext;
3731 ee_block = le32_to_cpu(ex->ee_block);
3732 ee_len = ext4_ext_get_actual_len(ex);
3734 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3735 (unsigned long long)ee_block, ee_len);
3737 /* If extent is larger than requested it is a clear sign that we still
3738 * have some extent state machine issues left. So extent_split is still
3740 * TODO: Once all related issues will be fixed this situation should be
3743 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3744 #ifdef CONFIG_EXT4_DEBUG
3745 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3746 " len %u; IO logical block %llu, len %u",
3747 inode->i_ino, (unsigned long long)ee_block, ee_len,
3748 (unsigned long long)map->m_lblk, map->m_len);
3750 err = ext4_split_convert_extents(handle, inode, map, ppath,
3751 EXT4_GET_BLOCKS_CONVERT);
3754 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3756 return PTR_ERR(path);
3757 depth = ext_depth(inode);
3758 ex = path[depth].p_ext;
3761 err = ext4_ext_get_access(handle, inode, path + depth);
3764 /* first mark the extent as initialized */
3765 ext4_ext_mark_initialized(ex);
3767 /* note: ext4_ext_correct_indexes() isn't needed here because
3768 * borders are not changed
3770 ext4_ext_try_to_merge(handle, inode, path, ex);
3772 /* Mark modified extent as dirty */
3773 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3775 ext4_ext_show_leaf(inode, path);
3780 convert_initialized_extent(handle_t *handle, struct inode *inode,
3781 struct ext4_map_blocks *map,
3782 struct ext4_ext_path **ppath,
3783 unsigned int *allocated)
3785 struct ext4_ext_path *path = *ppath;
3786 struct ext4_extent *ex;
3787 ext4_lblk_t ee_block;
3788 unsigned int ee_len;
3793 * Make sure that the extent is no bigger than we support with
3796 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3797 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3799 depth = ext_depth(inode);
3800 ex = path[depth].p_ext;
3801 ee_block = le32_to_cpu(ex->ee_block);
3802 ee_len = ext4_ext_get_actual_len(ex);
3804 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3805 (unsigned long long)ee_block, ee_len);
3807 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3808 err = ext4_split_convert_extents(handle, inode, map, ppath,
3809 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3812 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3814 return PTR_ERR(path);
3815 depth = ext_depth(inode);
3816 ex = path[depth].p_ext;
3818 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3819 (unsigned long) map->m_lblk);
3820 return -EFSCORRUPTED;
3824 err = ext4_ext_get_access(handle, inode, path + depth);
3827 /* first mark the extent as unwritten */
3828 ext4_ext_mark_unwritten(ex);
3830 /* note: ext4_ext_correct_indexes() isn't needed here because
3831 * borders are not changed
3833 ext4_ext_try_to_merge(handle, inode, path, ex);
3835 /* Mark modified extent as dirty */
3836 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3839 ext4_ext_show_leaf(inode, path);
3841 ext4_update_inode_fsync_trans(handle, inode, 1);
3843 map->m_flags |= EXT4_MAP_UNWRITTEN;
3844 if (*allocated > map->m_len)
3845 *allocated = map->m_len;
3846 map->m_len = *allocated;
3851 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
3852 struct ext4_map_blocks *map,
3853 struct ext4_ext_path **ppath, int flags,
3854 unsigned int allocated, ext4_fsblk_t newblock)
3856 struct ext4_ext_path __maybe_unused *path = *ppath;
3860 ext_debug(inode, "logical block %llu, max_blocks %u, flags 0x%x, allocated %u\n",
3861 (unsigned long long)map->m_lblk, map->m_len, flags,
3863 ext4_ext_show_leaf(inode, path);
3866 * When writing into unwritten space, we should not fail to
3867 * allocate metadata blocks for the new extent block if needed.
3869 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
3871 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
3872 allocated, newblock);
3874 /* get_block() before submitting IO, split the extent */
3875 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
3876 ret = ext4_split_convert_extents(handle, inode, map, ppath,
3877 flags | EXT4_GET_BLOCKS_CONVERT);
3883 * shouldn't get a 0 return when splitting an extent unless
3884 * m_len is 0 (bug) or extent has been corrupted
3886 if (unlikely(ret == 0)) {
3887 EXT4_ERROR_INODE(inode,
3888 "unexpected ret == 0, m_len = %u",
3890 err = -EFSCORRUPTED;
3893 map->m_flags |= EXT4_MAP_UNWRITTEN;
3896 /* IO end_io complete, convert the filled extent to written */
3897 if (flags & EXT4_GET_BLOCKS_CONVERT) {
3898 err = ext4_convert_unwritten_extents_endio(handle, inode, map,
3902 ext4_update_inode_fsync_trans(handle, inode, 1);
3905 /* buffered IO cases */
3907 * repeat fallocate creation request
3908 * we already have an unwritten extent
3910 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
3911 map->m_flags |= EXT4_MAP_UNWRITTEN;
3915 /* buffered READ or buffered write_begin() lookup */
3916 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3918 * We have blocks reserved already. We
3919 * return allocated blocks so that delalloc
3920 * won't do block reservation for us. But
3921 * the buffer head will be unmapped so that
3922 * a read from the block returns 0s.
3924 map->m_flags |= EXT4_MAP_UNWRITTEN;
3929 * Default case when (flags & EXT4_GET_BLOCKS_CREATE) == 1.
3930 * For buffered writes, at writepage time, etc. Convert a
3931 * discovered unwritten extent to written.
3933 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
3938 ext4_update_inode_fsync_trans(handle, inode, 1);
3940 * shouldn't get a 0 return when converting an unwritten extent
3941 * unless m_len is 0 (bug) or extent has been corrupted
3943 if (unlikely(ret == 0)) {
3944 EXT4_ERROR_INODE(inode, "unexpected ret == 0, m_len = %u",
3946 err = -EFSCORRUPTED;
3952 map->m_flags |= EXT4_MAP_NEW;
3954 map->m_flags |= EXT4_MAP_MAPPED;
3956 map->m_pblk = newblock;
3957 if (allocated > map->m_len)
3958 allocated = map->m_len;
3959 map->m_len = allocated;
3960 ext4_ext_show_leaf(inode, path);
3962 return err ? err : allocated;
3966 * get_implied_cluster_alloc - check to see if the requested
3967 * allocation (in the map structure) overlaps with a cluster already
3968 * allocated in an extent.
3969 * @sb The filesystem superblock structure
3970 * @map The requested lblk->pblk mapping
3971 * @ex The extent structure which might contain an implied
3972 * cluster allocation
3974 * This function is called by ext4_ext_map_blocks() after we failed to
3975 * find blocks that were already in the inode's extent tree. Hence,
3976 * we know that the beginning of the requested region cannot overlap
3977 * the extent from the inode's extent tree. There are three cases we
3978 * want to catch. The first is this case:
3980 * |--- cluster # N--|
3981 * |--- extent ---| |---- requested region ---|
3984 * The second case that we need to test for is this one:
3986 * |--------- cluster # N ----------------|
3987 * |--- requested region --| |------- extent ----|
3988 * |=======================|
3990 * The third case is when the requested region lies between two extents
3991 * within the same cluster:
3992 * |------------- cluster # N-------------|
3993 * |----- ex -----| |---- ex_right ----|
3994 * |------ requested region ------|
3995 * |================|
3997 * In each of the above cases, we need to set the map->m_pblk and
3998 * map->m_len so it corresponds to the return the extent labelled as
3999 * "|====|" from cluster #N, since it is already in use for data in
4000 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4001 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4002 * as a new "allocated" block region. Otherwise, we will return 0 and
4003 * ext4_ext_map_blocks() will then allocate one or more new clusters
4004 * by calling ext4_mb_new_blocks().
4006 static int get_implied_cluster_alloc(struct super_block *sb,
4007 struct ext4_map_blocks *map,
4008 struct ext4_extent *ex,
4009 struct ext4_ext_path *path)
4011 struct ext4_sb_info *sbi = EXT4_SB(sb);
4012 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4013 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4014 ext4_lblk_t rr_cluster_start;
4015 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4016 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4017 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4019 /* The extent passed in that we are trying to match */
4020 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4021 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4023 /* The requested region passed into ext4_map_blocks() */
4024 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4026 if ((rr_cluster_start == ex_cluster_end) ||
4027 (rr_cluster_start == ex_cluster_start)) {
4028 if (rr_cluster_start == ex_cluster_end)
4029 ee_start += ee_len - 1;
4030 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4031 map->m_len = min(map->m_len,
4032 (unsigned) sbi->s_cluster_ratio - c_offset);
4034 * Check for and handle this case:
4036 * |--------- cluster # N-------------|
4037 * |------- extent ----|
4038 * |--- requested region ---|
4042 if (map->m_lblk < ee_block)
4043 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4046 * Check for the case where there is already another allocated
4047 * block to the right of 'ex' but before the end of the cluster.
4049 * |------------- cluster # N-------------|
4050 * |----- ex -----| |---- ex_right ----|
4051 * |------ requested region ------|
4052 * |================|
4054 if (map->m_lblk > ee_block) {
4055 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4056 map->m_len = min(map->m_len, next - map->m_lblk);
4059 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4063 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4069 * Block allocation/map/preallocation routine for extents based files
4072 * Need to be called with
4073 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4074 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4076 * return > 0, number of blocks already mapped/allocated
4077 * if create == 0 and these are pre-allocated blocks
4078 * buffer head is unmapped
4079 * otherwise blocks are mapped
4081 * return = 0, if plain look up failed (blocks have not been allocated)
4082 * buffer head is unmapped
4084 * return < 0, error case.
4086 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4087 struct ext4_map_blocks *map, int flags)
4089 struct ext4_ext_path *path = NULL;
4090 struct ext4_extent newex, *ex, ex2;
4091 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4092 ext4_fsblk_t newblock = 0, pblk;
4093 int err = 0, depth, ret;
4094 unsigned int allocated = 0, offset = 0;
4095 unsigned int allocated_clusters = 0;
4096 struct ext4_allocation_request ar;
4097 ext4_lblk_t cluster_offset;
4099 ext_debug(inode, "blocks %u/%u requested\n", map->m_lblk, map->m_len);
4100 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4102 /* find extent for this block */
4103 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4105 err = PTR_ERR(path);
4110 depth = ext_depth(inode);
4113 * consistent leaf must not be empty;
4114 * this situation is possible, though, _during_ tree modification;
4115 * this is why assert can't be put in ext4_find_extent()
4117 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4118 EXT4_ERROR_INODE(inode, "bad extent address "
4119 "lblock: %lu, depth: %d pblock %lld",
4120 (unsigned long) map->m_lblk, depth,
4121 path[depth].p_block);
4122 err = -EFSCORRUPTED;
4126 ex = path[depth].p_ext;
4128 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4129 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4130 unsigned short ee_len;
4134 * unwritten extents are treated as holes, except that
4135 * we split out initialized portions during a write.
4137 ee_len = ext4_ext_get_actual_len(ex);
4139 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4141 /* if found extent covers block, simply return it */
4142 if (in_range(map->m_lblk, ee_block, ee_len)) {
4143 newblock = map->m_lblk - ee_block + ee_start;
4144 /* number of remaining blocks in the extent */
4145 allocated = ee_len - (map->m_lblk - ee_block);
4146 ext_debug(inode, "%u fit into %u:%d -> %llu\n",
4147 map->m_lblk, ee_block, ee_len, newblock);
4150 * If the extent is initialized check whether the
4151 * caller wants to convert it to unwritten.
4153 if ((!ext4_ext_is_unwritten(ex)) &&
4154 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4155 err = convert_initialized_extent(handle,
4156 inode, map, &path, &allocated);
4158 } else if (!ext4_ext_is_unwritten(ex)) {
4159 map->m_flags |= EXT4_MAP_MAPPED;
4160 map->m_pblk = newblock;
4161 if (allocated > map->m_len)
4162 allocated = map->m_len;
4163 map->m_len = allocated;
4164 ext4_ext_show_leaf(inode, path);
4168 ret = ext4_ext_handle_unwritten_extents(
4169 handle, inode, map, &path, flags,
4170 allocated, newblock);
4180 * requested block isn't allocated yet;
4181 * we couldn't try to create block if create flag is zero
4183 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4184 ext4_lblk_t hole_start, hole_len;
4186 hole_start = map->m_lblk;
4187 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4189 * put just found gap into cache to speed up
4190 * subsequent requests
4192 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4194 /* Update hole_len to reflect hole size after map->m_lblk */
4195 if (hole_start != map->m_lblk)
4196 hole_len -= map->m_lblk - hole_start;
4198 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4204 * Okay, we need to do block allocation.
4206 newex.ee_block = cpu_to_le32(map->m_lblk);
4207 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4210 * If we are doing bigalloc, check to see if the extent returned
4211 * by ext4_find_extent() implies a cluster we can use.
4213 if (cluster_offset && ex &&
4214 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4215 ar.len = allocated = map->m_len;
4216 newblock = map->m_pblk;
4217 goto got_allocated_blocks;
4220 /* find neighbour allocated blocks */
4221 ar.lleft = map->m_lblk;
4222 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4225 ar.lright = map->m_lblk;
4226 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4230 /* Check if the extent after searching to the right implies a
4231 * cluster we can use. */
4232 if ((sbi->s_cluster_ratio > 1) && err &&
4233 get_implied_cluster_alloc(inode->i_sb, map, &ex2, path)) {
4234 ar.len = allocated = map->m_len;
4235 newblock = map->m_pblk;
4236 goto got_allocated_blocks;
4240 * See if request is beyond maximum number of blocks we can have in
4241 * a single extent. For an initialized extent this limit is
4242 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4243 * EXT_UNWRITTEN_MAX_LEN.
4245 if (map->m_len > EXT_INIT_MAX_LEN &&
4246 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4247 map->m_len = EXT_INIT_MAX_LEN;
4248 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4249 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4250 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4252 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4253 newex.ee_len = cpu_to_le16(map->m_len);
4254 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4256 allocated = ext4_ext_get_actual_len(&newex);
4258 allocated = map->m_len;
4260 /* allocate new block */
4262 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4263 ar.logical = map->m_lblk;
4265 * We calculate the offset from the beginning of the cluster
4266 * for the logical block number, since when we allocate a
4267 * physical cluster, the physical block should start at the
4268 * same offset from the beginning of the cluster. This is
4269 * needed so that future calls to get_implied_cluster_alloc()
4272 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4273 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4275 ar.logical -= offset;
4276 if (S_ISREG(inode->i_mode))
4277 ar.flags = EXT4_MB_HINT_DATA;
4279 /* disable in-core preallocation for non-regular files */
4281 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4282 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4283 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4284 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4285 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4286 ar.flags |= EXT4_MB_USE_RESERVED;
4287 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4290 allocated_clusters = ar.len;
4291 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4292 ext_debug(inode, "allocate new block: goal %llu, found %llu/%u, requested %u\n",
4293 ar.goal, newblock, ar.len, allocated);
4294 if (ar.len > allocated)
4297 got_allocated_blocks:
4298 /* try to insert new extent into found leaf and return */
4299 pblk = newblock + offset;
4300 ext4_ext_store_pblock(&newex, pblk);
4301 newex.ee_len = cpu_to_le16(ar.len);
4302 /* Mark unwritten */
4303 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4304 ext4_ext_mark_unwritten(&newex);
4305 map->m_flags |= EXT4_MAP_UNWRITTEN;
4308 err = ext4_ext_insert_extent(handle, inode, &path, &newex, flags);
4310 if (allocated_clusters) {
4314 * free data blocks we just allocated.
4315 * not a good idea to call discard here directly,
4316 * but otherwise we'd need to call it every free().
4318 ext4_discard_preallocations(inode, 0);
4319 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4320 fb_flags = EXT4_FREE_BLOCKS_NO_QUOT_UPDATE;
4321 ext4_free_blocks(handle, inode, NULL, newblock,
4322 EXT4_C2B(sbi, allocated_clusters),
4329 * Reduce the reserved cluster count to reflect successful deferred
4330 * allocation of delayed allocated clusters or direct allocation of
4331 * clusters discovered to be delayed allocated. Once allocated, a
4332 * cluster is not included in the reserved count.
4334 if (test_opt(inode->i_sb, DELALLOC) && allocated_clusters) {
4335 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4337 * When allocating delayed allocated clusters, simply
4338 * reduce the reserved cluster count and claim quota
4340 ext4_da_update_reserve_space(inode, allocated_clusters,
4343 ext4_lblk_t lblk, len;
4347 * When allocating non-delayed allocated clusters
4348 * (from fallocate, filemap, DIO, or clusters
4349 * allocated when delalloc has been disabled by
4350 * ext4_nonda_switch), reduce the reserved cluster
4351 * count by the number of allocated clusters that
4352 * have previously been delayed allocated. Quota
4353 * has been claimed by ext4_mb_new_blocks() above,
4354 * so release the quota reservations made for any
4355 * previously delayed allocated clusters.
4357 lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
4358 len = allocated_clusters << sbi->s_cluster_bits;
4359 n = ext4_es_delayed_clu(inode, lblk, len);
4361 ext4_da_update_reserve_space(inode, (int) n, 0);
4366 * Cache the extent and update transaction to commit on fdatasync only
4367 * when it is _not_ an unwritten extent.
4369 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4370 ext4_update_inode_fsync_trans(handle, inode, 1);
4372 ext4_update_inode_fsync_trans(handle, inode, 0);
4374 map->m_flags |= (EXT4_MAP_NEW | EXT4_MAP_MAPPED);
4376 map->m_len = ar.len;
4377 allocated = map->m_len;
4378 ext4_ext_show_leaf(inode, path);
4380 ext4_ext_drop_refs(path);
4383 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4384 err ? err : allocated);
4385 return err ? err : allocated;
4388 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4390 struct super_block *sb = inode->i_sb;
4391 ext4_lblk_t last_block;
4395 * TODO: optimization is possible here.
4396 * Probably we need not scan at all,
4397 * because page truncation is enough.
4400 /* we have to know where to truncate from in crash case */
4401 EXT4_I(inode)->i_disksize = inode->i_size;
4402 err = ext4_mark_inode_dirty(handle, inode);
4406 last_block = (inode->i_size + sb->s_blocksize - 1)
4407 >> EXT4_BLOCK_SIZE_BITS(sb);
4409 err = ext4_es_remove_extent(inode, last_block,
4410 EXT_MAX_BLOCKS - last_block);
4411 if (err == -ENOMEM) {
4413 congestion_wait(BLK_RW_ASYNC, HZ/50);
4419 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4420 if (err == -ENOMEM) {
4422 congestion_wait(BLK_RW_ASYNC, HZ/50);
4423 goto retry_remove_space;
4428 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4429 ext4_lblk_t len, loff_t new_size,
4432 struct inode *inode = file_inode(file);
4434 int ret = 0, ret2 = 0, ret3 = 0;
4437 struct ext4_map_blocks map;
4438 unsigned int credits;
4441 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4442 map.m_lblk = offset;
4445 * Don't normalize the request if it can fit in one extent so
4446 * that it doesn't get unnecessarily split into multiple
4449 if (len <= EXT_UNWRITTEN_MAX_LEN)
4450 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4453 * credits to insert 1 extent into extent tree
4455 credits = ext4_chunk_trans_blocks(inode, len);
4456 depth = ext_depth(inode);
4461 * Recalculate credits when extent tree depth changes.
4463 if (depth != ext_depth(inode)) {
4464 credits = ext4_chunk_trans_blocks(inode, len);
4465 depth = ext_depth(inode);
4468 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4470 if (IS_ERR(handle)) {
4471 ret = PTR_ERR(handle);
4474 ret = ext4_map_blocks(handle, inode, &map, flags);
4476 ext4_debug("inode #%lu: block %u: len %u: "
4477 "ext4_ext_map_blocks returned %d",
4478 inode->i_ino, map.m_lblk,
4480 ext4_mark_inode_dirty(handle, inode);
4481 ext4_journal_stop(handle);
4485 * allow a full retry cycle for any remaining allocations
4489 map.m_len = len = len - ret;
4490 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4491 inode->i_ctime = current_time(inode);
4493 if (epos > new_size)
4495 if (ext4_update_inode_size(inode, epos) & 0x1)
4496 inode->i_mtime = inode->i_ctime;
4498 ret2 = ext4_mark_inode_dirty(handle, inode);
4499 ext4_update_inode_fsync_trans(handle, inode, 1);
4500 ret3 = ext4_journal_stop(handle);
4501 ret2 = ret3 ? ret3 : ret2;
4505 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4508 return ret > 0 ? ret2 : ret;
4511 static int ext4_collapse_range(struct file *file, loff_t offset, loff_t len);
4513 static int ext4_insert_range(struct file *file, loff_t offset, loff_t len);
4515 static long ext4_zero_range(struct file *file, loff_t offset,
4516 loff_t len, int mode)
4518 struct inode *inode = file_inode(file);
4519 struct address_space *mapping = file->f_mapping;
4520 handle_t *handle = NULL;
4521 unsigned int max_blocks;
4522 loff_t new_size = 0;
4526 int partial_begin, partial_end;
4529 unsigned int blkbits = inode->i_blkbits;
4531 trace_ext4_zero_range(inode, offset, len, mode);
4533 /* Call ext4_force_commit to flush all data in case of data=journal. */
4534 if (ext4_should_journal_data(inode)) {
4535 ret = ext4_force_commit(inode->i_sb);
4541 * Round up offset. This is not fallocate, we need to zero out
4542 * blocks, so convert interior block aligned part of the range to
4543 * unwritten and possibly manually zero out unaligned parts of the
4546 start = round_up(offset, 1 << blkbits);
4547 end = round_down((offset + len), 1 << blkbits);
4549 if (start < offset || end > offset + len)
4551 partial_begin = offset & ((1 << blkbits) - 1);
4552 partial_end = (offset + len) & ((1 << blkbits) - 1);
4554 lblk = start >> blkbits;
4555 max_blocks = (end >> blkbits);
4556 if (max_blocks < lblk)
4564 * Indirect files do not support unwritten extents
4566 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4571 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4572 (offset + len > inode->i_size ||
4573 offset + len > EXT4_I(inode)->i_disksize)) {
4574 new_size = offset + len;
4575 ret = inode_newsize_ok(inode, new_size);
4580 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4582 /* Wait all existing dio workers, newcomers will block on i_mutex */
4583 inode_dio_wait(inode);
4585 ret = file_modified(file);
4589 /* Preallocate the range including the unaligned edges */
4590 if (partial_begin || partial_end) {
4591 ret = ext4_alloc_file_blocks(file,
4592 round_down(offset, 1 << blkbits) >> blkbits,
4593 (round_up((offset + len), 1 << blkbits) -
4594 round_down(offset, 1 << blkbits)) >> blkbits,
4601 /* Zero range excluding the unaligned edges */
4602 if (max_blocks > 0) {
4603 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4607 * Prevent page faults from reinstantiating pages we have
4608 * released from page cache.
4610 filemap_invalidate_lock(mapping);
4612 ret = ext4_break_layouts(inode);
4614 filemap_invalidate_unlock(mapping);
4618 ret = ext4_update_disksize_before_punch(inode, offset, len);
4620 filemap_invalidate_unlock(mapping);
4623 /* Now release the pages and zero block aligned part of pages */
4624 truncate_pagecache_range(inode, start, end - 1);
4625 inode->i_mtime = inode->i_ctime = current_time(inode);
4627 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4629 filemap_invalidate_unlock(mapping);
4633 if (!partial_begin && !partial_end)
4637 * In worst case we have to writeout two nonadjacent unwritten
4638 * blocks and update the inode
4640 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4641 if (ext4_should_journal_data(inode))
4643 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4644 if (IS_ERR(handle)) {
4645 ret = PTR_ERR(handle);
4646 ext4_std_error(inode->i_sb, ret);
4650 inode->i_mtime = inode->i_ctime = current_time(inode);
4652 ext4_update_inode_size(inode, new_size);
4653 ret = ext4_mark_inode_dirty(handle, inode);
4656 /* Zero out partial block at the edges of the range */
4657 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4659 ext4_update_inode_fsync_trans(handle, inode, 1);
4661 if (file->f_flags & O_SYNC)
4662 ext4_handle_sync(handle);
4665 ext4_journal_stop(handle);
4667 inode_unlock(inode);
4672 * preallocate space for a file. This implements ext4's fallocate file
4673 * operation, which gets called from sys_fallocate system call.
4674 * For block-mapped files, posix_fallocate should fall back to the method
4675 * of writing zeroes to the required new blocks (the same behavior which is
4676 * expected for file systems which do not support fallocate() system call).
4678 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4680 struct inode *inode = file_inode(file);
4681 loff_t new_size = 0;
4682 unsigned int max_blocks;
4686 unsigned int blkbits = inode->i_blkbits;
4689 * Encrypted inodes can't handle collapse range or insert
4690 * range since we would need to re-encrypt blocks with a
4691 * different IV or XTS tweak (which are based on the logical
4694 if (IS_ENCRYPTED(inode) &&
4695 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
4698 /* Return error if mode is not supported */
4699 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4700 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4701 FALLOC_FL_INSERT_RANGE))
4705 ret = ext4_convert_inline_data(inode);
4706 inode_unlock(inode);
4710 if (mode & FALLOC_FL_PUNCH_HOLE) {
4711 ret = ext4_punch_hole(file, offset, len);
4715 if (mode & FALLOC_FL_COLLAPSE_RANGE) {
4716 ret = ext4_collapse_range(file, offset, len);
4720 if (mode & FALLOC_FL_INSERT_RANGE) {
4721 ret = ext4_insert_range(file, offset, len);
4725 if (mode & FALLOC_FL_ZERO_RANGE) {
4726 ret = ext4_zero_range(file, offset, len, mode);
4729 trace_ext4_fallocate_enter(inode, offset, len, mode);
4730 lblk = offset >> blkbits;
4732 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4733 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4738 * We only support preallocation for extent-based files only
4740 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4745 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4746 (offset + len > inode->i_size ||
4747 offset + len > EXT4_I(inode)->i_disksize)) {
4748 new_size = offset + len;
4749 ret = inode_newsize_ok(inode, new_size);
4754 /* Wait all existing dio workers, newcomers will block on i_mutex */
4755 inode_dio_wait(inode);
4757 ret = file_modified(file);
4761 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
4765 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
4766 ret = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
4767 EXT4_I(inode)->i_sync_tid);
4770 inode_unlock(inode);
4771 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
4777 * This function convert a range of blocks to written extents
4778 * The caller of this function will pass the start offset and the size.
4779 * all unwritten extents within this range will be converted to
4782 * This function is called from the direct IO end io call back
4783 * function, to convert the fallocated extents after IO is completed.
4784 * Returns 0 on success.
4786 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
4787 loff_t offset, ssize_t len)
4789 unsigned int max_blocks;
4790 int ret = 0, ret2 = 0, ret3 = 0;
4791 struct ext4_map_blocks map;
4792 unsigned int blkbits = inode->i_blkbits;
4793 unsigned int credits = 0;
4795 map.m_lblk = offset >> blkbits;
4796 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4800 * credits to insert 1 extent into extent tree
4802 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4804 while (ret >= 0 && ret < max_blocks) {
4806 map.m_len = (max_blocks -= ret);
4808 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4810 if (IS_ERR(handle)) {
4811 ret = PTR_ERR(handle);
4815 ret = ext4_map_blocks(handle, inode, &map,
4816 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
4818 ext4_warning(inode->i_sb,
4819 "inode #%lu: block %u: len %u: "
4820 "ext4_ext_map_blocks returned %d",
4821 inode->i_ino, map.m_lblk,
4823 ret2 = ext4_mark_inode_dirty(handle, inode);
4825 ret3 = ext4_journal_stop(handle);
4830 if (ret <= 0 || ret2)
4833 return ret > 0 ? ret2 : ret;
4836 int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
4838 int ret = 0, err = 0;
4839 struct ext4_io_end_vec *io_end_vec;
4842 * This is somewhat ugly but the idea is clear: When transaction is
4843 * reserved, everything goes into it. Otherwise we rather start several
4844 * smaller transactions for conversion of each extent separately.
4847 handle = ext4_journal_start_reserved(handle,
4848 EXT4_HT_EXT_CONVERT);
4850 return PTR_ERR(handle);
4853 list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
4854 ret = ext4_convert_unwritten_extents(handle, io_end->inode,
4862 err = ext4_journal_stop(handle);
4864 return ret < 0 ? ret : err;
4867 static int ext4_iomap_xattr_fiemap(struct inode *inode, struct iomap *iomap)
4871 int blockbits = inode->i_sb->s_blocksize_bits;
4876 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4877 struct ext4_iloc iloc;
4878 int offset; /* offset of xattr in inode */
4880 error = ext4_get_inode_loc(inode, &iloc);
4883 physical = (__u64)iloc.bh->b_blocknr << blockbits;
4884 offset = EXT4_GOOD_OLD_INODE_SIZE +
4885 EXT4_I(inode)->i_extra_isize;
4887 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
4889 iomap_type = IOMAP_INLINE;
4890 } else if (EXT4_I(inode)->i_file_acl) { /* external block */
4891 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
4892 length = inode->i_sb->s_blocksize;
4893 iomap_type = IOMAP_MAPPED;
4895 /* no in-inode or external block for xattr, so return -ENOENT */
4900 iomap->addr = physical;
4902 iomap->length = length;
4903 iomap->type = iomap_type;
4909 static int ext4_iomap_xattr_begin(struct inode *inode, loff_t offset,
4910 loff_t length, unsigned flags,
4911 struct iomap *iomap, struct iomap *srcmap)
4915 error = ext4_iomap_xattr_fiemap(inode, iomap);
4916 if (error == 0 && (offset >= iomap->length))
4921 static const struct iomap_ops ext4_iomap_xattr_ops = {
4922 .iomap_begin = ext4_iomap_xattr_begin,
4925 static int ext4_fiemap_check_ranges(struct inode *inode, u64 start, u64 *len)
4929 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4930 maxbytes = inode->i_sb->s_maxbytes;
4932 maxbytes = EXT4_SB(inode->i_sb)->s_bitmap_maxbytes;
4936 if (start > maxbytes)
4940 * Shrink request scope to what the fs can actually handle.
4942 if (*len > maxbytes || (maxbytes - *len) < start)
4943 *len = maxbytes - start;
4947 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4952 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4953 error = ext4_ext_precache(inode);
4956 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
4960 * For bitmap files the maximum size limit could be smaller than
4961 * s_maxbytes, so check len here manually instead of just relying on the
4964 error = ext4_fiemap_check_ranges(inode, start, &len);
4968 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
4969 fieinfo->fi_flags &= ~FIEMAP_FLAG_XATTR;
4970 return iomap_fiemap(inode, fieinfo, start, len,
4971 &ext4_iomap_xattr_ops);
4974 return iomap_fiemap(inode, fieinfo, start, len, &ext4_iomap_report_ops);
4977 int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
4978 __u64 start, __u64 len)
4980 ext4_lblk_t start_blk, len_blks;
4984 if (ext4_has_inline_data(inode)) {
4987 down_read(&EXT4_I(inode)->xattr_sem);
4988 has_inline = ext4_has_inline_data(inode);
4989 up_read(&EXT4_I(inode)->xattr_sem);
4994 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4995 error = ext4_ext_precache(inode);
4998 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
5001 error = fiemap_prep(inode, fieinfo, start, &len, 0);
5005 error = ext4_fiemap_check_ranges(inode, start, &len);
5009 start_blk = start >> inode->i_sb->s_blocksize_bits;
5010 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5011 if (last_blk >= EXT_MAX_BLOCKS)
5012 last_blk = EXT_MAX_BLOCKS-1;
5013 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5016 * Walk the extent tree gathering extent information
5017 * and pushing extents back to the user.
5019 return ext4_fill_es_cache_info(inode, start_blk, len_blks, fieinfo);
5023 * ext4_ext_shift_path_extents:
5024 * Shift the extents of a path structure lying between path[depth].p_ext
5025 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5026 * if it is right shift or left shift operation.
5029 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5030 struct inode *inode, handle_t *handle,
5031 enum SHIFT_DIRECTION SHIFT)
5034 struct ext4_extent *ex_start, *ex_last;
5035 bool update = false;
5036 int credits, restart_credits;
5037 depth = path->p_depth;
5039 while (depth >= 0) {
5040 if (depth == path->p_depth) {
5041 ex_start = path[depth].p_ext;
5043 return -EFSCORRUPTED;
5045 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5046 /* leaf + sb + inode */
5048 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr)) {
5050 /* extent tree + sb + inode */
5051 credits = depth + 2;
5054 restart_credits = ext4_writepage_trans_blocks(inode);
5055 err = ext4_datasem_ensure_credits(handle, inode, credits,
5056 restart_credits, 0);
5063 err = ext4_ext_get_access(handle, inode, path + depth);
5067 while (ex_start <= ex_last) {
5068 if (SHIFT == SHIFT_LEFT) {
5069 le32_add_cpu(&ex_start->ee_block,
5071 /* Try to merge to the left. */
5073 EXT_FIRST_EXTENT(path[depth].p_hdr))
5075 ext4_ext_try_to_merge_right(inode,
5076 path, ex_start - 1))
5081 le32_add_cpu(&ex_last->ee_block, shift);
5082 ext4_ext_try_to_merge_right(inode, path,
5087 err = ext4_ext_dirty(handle, inode, path + depth);
5091 if (--depth < 0 || !update)
5095 /* Update index too */
5096 err = ext4_ext_get_access(handle, inode, path + depth);
5100 if (SHIFT == SHIFT_LEFT)
5101 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5103 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5104 err = ext4_ext_dirty(handle, inode, path + depth);
5108 /* we are done if current index is not a starting index */
5109 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5120 * ext4_ext_shift_extents:
5121 * All the extents which lies in the range from @start to the last allocated
5122 * block for the @inode are shifted either towards left or right (depending
5123 * upon @SHIFT) by @shift blocks.
5124 * On success, 0 is returned, error otherwise.
5127 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5128 ext4_lblk_t start, ext4_lblk_t shift,
5129 enum SHIFT_DIRECTION SHIFT)
5131 struct ext4_ext_path *path;
5133 struct ext4_extent *extent;
5134 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5135 ext4_lblk_t tmp = EXT_MAX_BLOCKS;
5137 /* Let path point to the last extent */
5138 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5141 return PTR_ERR(path);
5143 depth = path->p_depth;
5144 extent = path[depth].p_ext;
5148 stop = le32_to_cpu(extent->ee_block);
5151 * For left shifts, make sure the hole on the left is big enough to
5152 * accommodate the shift. For right shifts, make sure the last extent
5153 * won't be shifted beyond EXT_MAX_BLOCKS.
5155 if (SHIFT == SHIFT_LEFT) {
5156 path = ext4_find_extent(inode, start - 1, &path,
5159 return PTR_ERR(path);
5160 depth = path->p_depth;
5161 extent = path[depth].p_ext;
5163 ex_start = le32_to_cpu(extent->ee_block);
5164 ex_end = le32_to_cpu(extent->ee_block) +
5165 ext4_ext_get_actual_len(extent);
5171 if ((start == ex_start && shift > ex_start) ||
5172 (shift > start - ex_end)) {
5177 if (shift > EXT_MAX_BLOCKS -
5178 (stop + ext4_ext_get_actual_len(extent))) {
5185 * In case of left shift, iterator points to start and it is increased
5186 * till we reach stop. In case of right shift, iterator points to stop
5187 * and it is decreased till we reach start.
5191 if (SHIFT == SHIFT_LEFT)
5196 if (tmp != EXT_MAX_BLOCKS)
5200 * Its safe to start updating extents. Start and stop are unsigned, so
5201 * in case of right shift if extent with 0 block is reached, iterator
5202 * becomes NULL to indicate the end of the loop.
5204 while (iterator && start <= stop) {
5205 path = ext4_find_extent(inode, *iterator, &path,
5208 return PTR_ERR(path);
5209 depth = path->p_depth;
5210 extent = path[depth].p_ext;
5212 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5213 (unsigned long) *iterator);
5214 return -EFSCORRUPTED;
5216 if (SHIFT == SHIFT_LEFT && *iterator >
5217 le32_to_cpu(extent->ee_block)) {
5218 /* Hole, move to the next extent */
5219 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5220 path[depth].p_ext++;
5222 *iterator = ext4_ext_next_allocated_block(path);
5228 if (SHIFT == SHIFT_LEFT) {
5229 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5230 *iterator = le32_to_cpu(extent->ee_block) +
5231 ext4_ext_get_actual_len(extent);
5233 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5234 if (le32_to_cpu(extent->ee_block) > start)
5235 *iterator = le32_to_cpu(extent->ee_block) - 1;
5236 else if (le32_to_cpu(extent->ee_block) == start)
5239 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5240 while (le32_to_cpu(extent->ee_block) >= start)
5243 if (extent == EXT_LAST_EXTENT(path[depth].p_hdr))
5249 path[depth].p_ext = extent;
5251 ret = ext4_ext_shift_path_extents(path, shift, inode,
5253 /* iterator can be NULL which means we should break */
5260 ext4_ext_drop_refs(path);
5266 * ext4_collapse_range:
5267 * This implements the fallocate's collapse range functionality for ext4
5268 * Returns: 0 and non-zero on error.
5270 static int ext4_collapse_range(struct file *file, loff_t offset, loff_t len)
5272 struct inode *inode = file_inode(file);
5273 struct super_block *sb = inode->i_sb;
5274 struct address_space *mapping = inode->i_mapping;
5275 ext4_lblk_t punch_start, punch_stop;
5277 unsigned int credits;
5278 loff_t new_size, ioffset;
5282 * We need to test this early because xfstests assumes that a
5283 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5284 * system does not support collapse range.
5286 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5289 /* Collapse range works only on fs cluster size aligned regions. */
5290 if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
5293 trace_ext4_collapse_range(inode, offset, len);
5295 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5296 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5298 /* Call ext4_force_commit to flush all data in case of data=journal. */
5299 if (ext4_should_journal_data(inode)) {
5300 ret = ext4_force_commit(inode->i_sb);
5307 * There is no need to overlap collapse range with EOF, in which case
5308 * it is effectively a truncate operation
5310 if (offset + len >= inode->i_size) {
5315 /* Currently just for extent based files */
5316 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5321 /* Wait for existing dio to complete */
5322 inode_dio_wait(inode);
5324 ret = file_modified(file);
5329 * Prevent page faults from reinstantiating pages we have released from
5332 filemap_invalidate_lock(mapping);
5334 ret = ext4_break_layouts(inode);
5339 * Need to round down offset to be aligned with page size boundary
5340 * for page size > block size.
5342 ioffset = round_down(offset, PAGE_SIZE);
5344 * Write tail of the last page before removed range since it will get
5345 * removed from the page cache below.
5347 ret = filemap_write_and_wait_range(mapping, ioffset, offset);
5351 * Write data that will be shifted to preserve them when discarding
5352 * page cache below. We are also protected from pages becoming dirty
5353 * by i_rwsem and invalidate_lock.
5355 ret = filemap_write_and_wait_range(mapping, offset + len,
5359 truncate_pagecache(inode, ioffset);
5361 credits = ext4_writepage_trans_blocks(inode);
5362 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5363 if (IS_ERR(handle)) {
5364 ret = PTR_ERR(handle);
5367 ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE, handle);
5369 down_write(&EXT4_I(inode)->i_data_sem);
5370 ext4_discard_preallocations(inode, 0);
5372 ret = ext4_es_remove_extent(inode, punch_start,
5373 EXT_MAX_BLOCKS - punch_start);
5375 up_write(&EXT4_I(inode)->i_data_sem);
5379 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5381 up_write(&EXT4_I(inode)->i_data_sem);
5384 ext4_discard_preallocations(inode, 0);
5386 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5387 punch_stop - punch_start, SHIFT_LEFT);
5389 up_write(&EXT4_I(inode)->i_data_sem);
5393 new_size = inode->i_size - len;
5394 i_size_write(inode, new_size);
5395 EXT4_I(inode)->i_disksize = new_size;
5397 up_write(&EXT4_I(inode)->i_data_sem);
5399 ext4_handle_sync(handle);
5400 inode->i_mtime = inode->i_ctime = current_time(inode);
5401 ret = ext4_mark_inode_dirty(handle, inode);
5402 ext4_update_inode_fsync_trans(handle, inode, 1);
5405 ext4_journal_stop(handle);
5407 filemap_invalidate_unlock(mapping);
5409 inode_unlock(inode);
5414 * ext4_insert_range:
5415 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5416 * The data blocks starting from @offset to the EOF are shifted by @len
5417 * towards right to create a hole in the @inode. Inode size is increased
5419 * Returns 0 on success, error otherwise.
5421 static int ext4_insert_range(struct file *file, loff_t offset, loff_t len)
5423 struct inode *inode = file_inode(file);
5424 struct super_block *sb = inode->i_sb;
5425 struct address_space *mapping = inode->i_mapping;
5427 struct ext4_ext_path *path;
5428 struct ext4_extent *extent;
5429 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5430 unsigned int credits, ee_len;
5431 int ret = 0, depth, split_flag = 0;
5435 * We need to test this early because xfstests assumes that an
5436 * insert range of (0, 1) will return EOPNOTSUPP if the file
5437 * system does not support insert range.
5439 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5442 /* Insert range works only on fs cluster size aligned regions. */
5443 if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
5446 trace_ext4_insert_range(inode, offset, len);
5448 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5449 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5451 /* Call ext4_force_commit to flush all data in case of data=journal */
5452 if (ext4_should_journal_data(inode)) {
5453 ret = ext4_force_commit(inode->i_sb);
5459 /* Currently just for extent based files */
5460 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5465 /* Check whether the maximum file size would be exceeded */
5466 if (len > inode->i_sb->s_maxbytes - inode->i_size) {
5471 /* Offset must be less than i_size */
5472 if (offset >= inode->i_size) {
5477 /* Wait for existing dio to complete */
5478 inode_dio_wait(inode);
5480 ret = file_modified(file);
5485 * Prevent page faults from reinstantiating pages we have released from
5488 filemap_invalidate_lock(mapping);
5490 ret = ext4_break_layouts(inode);
5495 * Need to round down to align start offset to page size boundary
5496 * for page size > block size.
5498 ioffset = round_down(offset, PAGE_SIZE);
5499 /* Write out all dirty pages */
5500 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5504 truncate_pagecache(inode, ioffset);
5506 credits = ext4_writepage_trans_blocks(inode);
5507 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5508 if (IS_ERR(handle)) {
5509 ret = PTR_ERR(handle);
5512 ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE, handle);
5514 /* Expand file to avoid data loss if there is error while shifting */
5515 inode->i_size += len;
5516 EXT4_I(inode)->i_disksize += len;
5517 inode->i_mtime = inode->i_ctime = current_time(inode);
5518 ret = ext4_mark_inode_dirty(handle, inode);
5522 down_write(&EXT4_I(inode)->i_data_sem);
5523 ext4_discard_preallocations(inode, 0);
5525 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5527 up_write(&EXT4_I(inode)->i_data_sem);
5531 depth = ext_depth(inode);
5532 extent = path[depth].p_ext;
5534 ee_start_lblk = le32_to_cpu(extent->ee_block);
5535 ee_len = ext4_ext_get_actual_len(extent);
5538 * If offset_lblk is not the starting block of extent, split
5539 * the extent @offset_lblk
5541 if ((offset_lblk > ee_start_lblk) &&
5542 (offset_lblk < (ee_start_lblk + ee_len))) {
5543 if (ext4_ext_is_unwritten(extent))
5544 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5545 EXT4_EXT_MARK_UNWRIT2;
5546 ret = ext4_split_extent_at(handle, inode, &path,
5547 offset_lblk, split_flag,
5549 EXT4_GET_BLOCKS_PRE_IO |
5550 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5553 ext4_ext_drop_refs(path);
5556 up_write(&EXT4_I(inode)->i_data_sem);
5560 ext4_ext_drop_refs(path);
5564 ret = ext4_es_remove_extent(inode, offset_lblk,
5565 EXT_MAX_BLOCKS - offset_lblk);
5567 up_write(&EXT4_I(inode)->i_data_sem);
5572 * if offset_lblk lies in a hole which is at start of file, use
5573 * ee_start_lblk to shift extents
5575 ret = ext4_ext_shift_extents(inode, handle,
5576 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5577 len_lblk, SHIFT_RIGHT);
5579 up_write(&EXT4_I(inode)->i_data_sem);
5581 ext4_handle_sync(handle);
5583 ext4_update_inode_fsync_trans(handle, inode, 1);
5586 ext4_journal_stop(handle);
5588 filemap_invalidate_unlock(mapping);
5590 inode_unlock(inode);
5595 * ext4_swap_extents() - Swap extents between two inodes
5596 * @handle: handle for this transaction
5597 * @inode1: First inode
5598 * @inode2: Second inode
5599 * @lblk1: Start block for first inode
5600 * @lblk2: Start block for second inode
5601 * @count: Number of blocks to swap
5602 * @unwritten: Mark second inode's extents as unwritten after swap
5603 * @erp: Pointer to save error value
5605 * This helper routine does exactly what is promise "swap extents". All other
5606 * stuff such as page-cache locking consistency, bh mapping consistency or
5607 * extent's data copying must be performed by caller.
5609 * i_mutex is held for both inodes
5610 * i_data_sem is locked for write for both inodes
5612 * All pages from requested range are locked for both inodes
5615 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5616 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5617 ext4_lblk_t count, int unwritten, int *erp)
5619 struct ext4_ext_path *path1 = NULL;
5620 struct ext4_ext_path *path2 = NULL;
5621 int replaced_count = 0;
5623 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5624 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5625 BUG_ON(!inode_is_locked(inode1));
5626 BUG_ON(!inode_is_locked(inode2));
5628 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5631 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5636 struct ext4_extent *ex1, *ex2, tmp_ex;
5637 ext4_lblk_t e1_blk, e2_blk;
5638 int e1_len, e2_len, len;
5641 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5642 if (IS_ERR(path1)) {
5643 *erp = PTR_ERR(path1);
5649 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5650 if (IS_ERR(path2)) {
5651 *erp = PTR_ERR(path2);
5655 ex1 = path1[path1->p_depth].p_ext;
5656 ex2 = path2[path2->p_depth].p_ext;
5657 /* Do we have something to swap ? */
5658 if (unlikely(!ex2 || !ex1))
5661 e1_blk = le32_to_cpu(ex1->ee_block);
5662 e2_blk = le32_to_cpu(ex2->ee_block);
5663 e1_len = ext4_ext_get_actual_len(ex1);
5664 e2_len = ext4_ext_get_actual_len(ex2);
5667 if (!in_range(lblk1, e1_blk, e1_len) ||
5668 !in_range(lblk2, e2_blk, e2_len)) {
5669 ext4_lblk_t next1, next2;
5671 /* if hole after extent, then go to next extent */
5672 next1 = ext4_ext_next_allocated_block(path1);
5673 next2 = ext4_ext_next_allocated_block(path2);
5674 /* If hole before extent, then shift to that extent */
5679 /* Do we have something to swap */
5680 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5682 /* Move to the rightest boundary */
5683 len = next1 - lblk1;
5684 if (len < next2 - lblk2)
5685 len = next2 - lblk2;
5694 /* Prepare left boundary */
5695 if (e1_blk < lblk1) {
5697 *erp = ext4_force_split_extent_at(handle, inode1,
5702 if (e2_blk < lblk2) {
5704 *erp = ext4_force_split_extent_at(handle, inode2,
5709 /* ext4_split_extent_at() may result in leaf extent split,
5710 * path must to be revalidated. */
5714 /* Prepare right boundary */
5716 if (len > e1_blk + e1_len - lblk1)
5717 len = e1_blk + e1_len - lblk1;
5718 if (len > e2_blk + e2_len - lblk2)
5719 len = e2_blk + e2_len - lblk2;
5721 if (len != e1_len) {
5723 *erp = ext4_force_split_extent_at(handle, inode1,
5724 &path1, lblk1 + len, 0);
5728 if (len != e2_len) {
5730 *erp = ext4_force_split_extent_at(handle, inode2,
5731 &path2, lblk2 + len, 0);
5735 /* ext4_split_extent_at() may result in leaf extent split,
5736 * path must to be revalidated. */
5740 BUG_ON(e2_len != e1_len);
5741 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5744 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5748 /* Both extents are fully inside boundaries. Swap it now */
5750 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5751 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5752 ex1->ee_len = cpu_to_le16(e2_len);
5753 ex2->ee_len = cpu_to_le16(e1_len);
5755 ext4_ext_mark_unwritten(ex2);
5756 if (ext4_ext_is_unwritten(&tmp_ex))
5757 ext4_ext_mark_unwritten(ex1);
5759 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5760 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5761 *erp = ext4_ext_dirty(handle, inode2, path2 +
5765 *erp = ext4_ext_dirty(handle, inode1, path1 +
5768 * Looks scarry ah..? second inode already points to new blocks,
5769 * and it was successfully dirtied. But luckily error may happen
5770 * only due to journal error, so full transaction will be
5777 replaced_count += len;
5781 ext4_ext_drop_refs(path1);
5783 ext4_ext_drop_refs(path2);
5785 path1 = path2 = NULL;
5787 return replaced_count;
5791 * ext4_clu_mapped - determine whether any block in a logical cluster has
5792 * been mapped to a physical cluster
5794 * @inode - file containing the logical cluster
5795 * @lclu - logical cluster of interest
5797 * Returns 1 if any block in the logical cluster is mapped, signifying
5798 * that a physical cluster has been allocated for it. Otherwise,
5799 * returns 0. Can also return negative error codes. Derived from
5800 * ext4_ext_map_blocks().
5802 int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
5804 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5805 struct ext4_ext_path *path;
5806 int depth, mapped = 0, err = 0;
5807 struct ext4_extent *extent;
5808 ext4_lblk_t first_lblk, first_lclu, last_lclu;
5811 * if data can be stored inline, the logical cluster isn't
5812 * mapped - no physical clusters have been allocated, and the
5813 * file has no extents
5815 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) ||
5816 ext4_has_inline_data(inode))
5819 /* search for the extent closest to the first block in the cluster */
5820 path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
5822 err = PTR_ERR(path);
5827 depth = ext_depth(inode);
5830 * A consistent leaf must not be empty. This situation is possible,
5831 * though, _during_ tree modification, and it's why an assert can't
5832 * be put in ext4_find_extent().
5834 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
5835 EXT4_ERROR_INODE(inode,
5836 "bad extent address - lblock: %lu, depth: %d, pblock: %lld",
5837 (unsigned long) EXT4_C2B(sbi, lclu),
5838 depth, path[depth].p_block);
5839 err = -EFSCORRUPTED;
5843 extent = path[depth].p_ext;
5845 /* can't be mapped if the extent tree is empty */
5849 first_lblk = le32_to_cpu(extent->ee_block);
5850 first_lclu = EXT4_B2C(sbi, first_lblk);
5853 * Three possible outcomes at this point - found extent spanning
5854 * the target cluster, to the left of the target cluster, or to the
5855 * right of the target cluster. The first two cases are handled here.
5856 * The last case indicates the target cluster is not mapped.
5858 if (lclu >= first_lclu) {
5859 last_lclu = EXT4_B2C(sbi, first_lblk +
5860 ext4_ext_get_actual_len(extent) - 1);
5861 if (lclu <= last_lclu) {
5864 first_lblk = ext4_ext_next_allocated_block(path);
5865 first_lclu = EXT4_B2C(sbi, first_lblk);
5866 if (lclu == first_lclu)
5872 ext4_ext_drop_refs(path);
5875 return err ? err : mapped;
5879 * Updates physical block address and unwritten status of extent
5880 * starting at lblk start and of len. If such an extent doesn't exist,
5881 * this function splits the extent tree appropriately to create an
5882 * extent like this. This function is called in the fast commit
5883 * replay path. Returns 0 on success and error on failure.
5885 int ext4_ext_replay_update_ex(struct inode *inode, ext4_lblk_t start,
5886 int len, int unwritten, ext4_fsblk_t pblk)
5888 struct ext4_ext_path *path = NULL, *ppath;
5889 struct ext4_extent *ex;
5892 path = ext4_find_extent(inode, start, NULL, 0);
5894 return PTR_ERR(path);
5895 ex = path[path->p_depth].p_ext;
5897 ret = -EFSCORRUPTED;
5901 if (le32_to_cpu(ex->ee_block) != start ||
5902 ext4_ext_get_actual_len(ex) != len) {
5903 /* We need to split this extent to match our extent first */
5905 down_write(&EXT4_I(inode)->i_data_sem);
5906 ret = ext4_force_split_extent_at(NULL, inode, &ppath, start, 1);
5907 up_write(&EXT4_I(inode)->i_data_sem);
5911 path = ext4_find_extent(inode, start, NULL, 0);
5915 ex = path[path->p_depth].p_ext;
5916 WARN_ON(le32_to_cpu(ex->ee_block) != start);
5917 if (ext4_ext_get_actual_len(ex) != len) {
5918 down_write(&EXT4_I(inode)->i_data_sem);
5919 ret = ext4_force_split_extent_at(NULL, inode, &ppath,
5921 up_write(&EXT4_I(inode)->i_data_sem);
5925 path = ext4_find_extent(inode, start, NULL, 0);
5928 ex = path[path->p_depth].p_ext;
5932 ext4_ext_mark_unwritten(ex);
5934 ext4_ext_mark_initialized(ex);
5935 ext4_ext_store_pblock(ex, pblk);
5936 down_write(&EXT4_I(inode)->i_data_sem);
5937 ret = ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
5938 up_write(&EXT4_I(inode)->i_data_sem);
5940 ext4_ext_drop_refs(path);
5942 ext4_mark_inode_dirty(NULL, inode);
5946 /* Try to shrink the extent tree */
5947 void ext4_ext_replay_shrink_inode(struct inode *inode, ext4_lblk_t end)
5949 struct ext4_ext_path *path = NULL;
5950 struct ext4_extent *ex;
5951 ext4_lblk_t old_cur, cur = 0;
5954 path = ext4_find_extent(inode, cur, NULL, 0);
5957 ex = path[path->p_depth].p_ext;
5959 ext4_ext_drop_refs(path);
5961 ext4_mark_inode_dirty(NULL, inode);
5965 cur = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
5968 ext4_ext_try_to_merge(NULL, inode, path, ex);
5969 down_write(&EXT4_I(inode)->i_data_sem);
5970 ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
5971 up_write(&EXT4_I(inode)->i_data_sem);
5972 ext4_mark_inode_dirty(NULL, inode);
5973 ext4_ext_drop_refs(path);
5978 /* Check if *cur is a hole and if it is, skip it */
5979 static int skip_hole(struct inode *inode, ext4_lblk_t *cur)
5982 struct ext4_map_blocks map;
5985 map.m_len = ((inode->i_size) >> inode->i_sb->s_blocksize_bits) - *cur;
5987 ret = ext4_map_blocks(NULL, inode, &map, 0);
5992 *cur = *cur + map.m_len;
5996 /* Count number of blocks used by this inode and update i_blocks */
5997 int ext4_ext_replay_set_iblocks(struct inode *inode)
5999 struct ext4_ext_path *path = NULL, *path2 = NULL;
6000 struct ext4_extent *ex;
6001 ext4_lblk_t cur = 0, end;
6002 int numblks = 0, i, ret = 0;
6003 ext4_fsblk_t cmp1, cmp2;
6004 struct ext4_map_blocks map;
6006 /* Determin the size of the file first */
6007 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
6010 return PTR_ERR(path);
6011 ex = path[path->p_depth].p_ext;
6013 ext4_ext_drop_refs(path);
6017 end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
6018 ext4_ext_drop_refs(path);
6021 /* Count the number of data blocks */
6025 map.m_len = end - cur;
6026 ret = ext4_map_blocks(NULL, inode, &map, 0);
6031 cur = cur + map.m_len;
6035 * Count the number of extent tree blocks. We do it by looking up
6036 * two successive extents and determining the difference between
6037 * their paths. When path is different for 2 successive extents
6038 * we compare the blocks in the path at each level and increment
6039 * iblocks by total number of differences found.
6042 ret = skip_hole(inode, &cur);
6045 path = ext4_find_extent(inode, cur, NULL, 0);
6048 numblks += path->p_depth;
6049 ext4_ext_drop_refs(path);
6052 path = ext4_find_extent(inode, cur, NULL, 0);
6055 ex = path[path->p_depth].p_ext;
6057 ext4_ext_drop_refs(path);
6061 cur = max(cur + 1, le32_to_cpu(ex->ee_block) +
6062 ext4_ext_get_actual_len(ex));
6063 ret = skip_hole(inode, &cur);
6065 ext4_ext_drop_refs(path);
6069 path2 = ext4_find_extent(inode, cur, NULL, 0);
6070 if (IS_ERR(path2)) {
6071 ext4_ext_drop_refs(path);
6075 for (i = 0; i <= max(path->p_depth, path2->p_depth); i++) {
6077 if (i <= path->p_depth)
6078 cmp1 = path[i].p_bh ?
6079 path[i].p_bh->b_blocknr : 0;
6080 if (i <= path2->p_depth)
6081 cmp2 = path2[i].p_bh ?
6082 path2[i].p_bh->b_blocknr : 0;
6083 if (cmp1 != cmp2 && cmp2 != 0)
6086 ext4_ext_drop_refs(path);
6087 ext4_ext_drop_refs(path2);
6093 inode->i_blocks = numblks << (inode->i_sb->s_blocksize_bits - 9);
6094 ext4_mark_inode_dirty(NULL, inode);
6098 int ext4_ext_clear_bb(struct inode *inode)
6100 struct ext4_ext_path *path = NULL;
6101 struct ext4_extent *ex;
6102 ext4_lblk_t cur = 0, end;
6104 struct ext4_map_blocks map;
6106 /* Determin the size of the file first */
6107 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
6110 return PTR_ERR(path);
6111 ex = path[path->p_depth].p_ext;
6113 ext4_ext_drop_refs(path);
6117 end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
6118 ext4_ext_drop_refs(path);
6124 map.m_len = end - cur;
6125 ret = ext4_map_blocks(NULL, inode, &map, 0);
6129 path = ext4_find_extent(inode, map.m_lblk, NULL, 0);
6130 if (!IS_ERR_OR_NULL(path)) {
6131 for (j = 0; j < path->p_depth; j++) {
6133 ext4_mb_mark_bb(inode->i_sb,
6134 path[j].p_block, 1, 0);
6135 ext4_fc_record_regions(inode->i_sb, inode->i_ino,
6136 0, path[j].p_block, 1, 1);
6138 ext4_ext_drop_refs(path);
6141 ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, 0);
6142 ext4_fc_record_regions(inode->i_sb, inode->i_ino,
6143 map.m_lblk, map.m_pblk, map.m_len, 1);
6145 cur = cur + map.m_len;