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)
140 /* path points to block */
141 BUFFER_TRACE(path->p_bh, "get_write_access");
142 return ext4_journal_get_write_access(handle, path->p_bh);
144 /* path points to leaf/index in inode body */
145 /* we use in-core data, no need to protect them */
155 static int __ext4_ext_dirty(const char *where, unsigned int line,
156 handle_t *handle, struct inode *inode,
157 struct ext4_ext_path *path)
161 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
163 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
164 /* path points to block */
165 err = __ext4_handle_dirty_metadata(where, line, handle,
168 /* path points to leaf/index in inode body */
169 err = ext4_mark_inode_dirty(handle, inode);
174 #define ext4_ext_dirty(handle, inode, path) \
175 __ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
177 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
178 struct ext4_ext_path *path,
182 int depth = path->p_depth;
183 struct ext4_extent *ex;
186 * Try to predict block placement assuming that we are
187 * filling in a file which will eventually be
188 * non-sparse --- i.e., in the case of libbfd writing
189 * an ELF object sections out-of-order but in a way
190 * the eventually results in a contiguous object or
191 * executable file, or some database extending a table
192 * space file. However, this is actually somewhat
193 * non-ideal if we are writing a sparse file such as
194 * qemu or KVM writing a raw image file that is going
195 * to stay fairly sparse, since it will end up
196 * fragmenting the file system's free space. Maybe we
197 * should have some hueristics or some way to allow
198 * userspace to pass a hint to file system,
199 * especially if the latter case turns out to be
202 ex = path[depth].p_ext;
204 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
205 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
207 if (block > ext_block)
208 return ext_pblk + (block - ext_block);
210 return ext_pblk - (ext_block - block);
213 /* it looks like index is empty;
214 * try to find starting block from index itself */
215 if (path[depth].p_bh)
216 return path[depth].p_bh->b_blocknr;
219 /* OK. use inode's group */
220 return ext4_inode_to_goal_block(inode);
224 * Allocation for a meta data block
227 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
228 struct ext4_ext_path *path,
229 struct ext4_extent *ex, int *err, unsigned int flags)
231 ext4_fsblk_t goal, newblock;
233 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
234 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
239 static inline int ext4_ext_space_block(struct inode *inode, int check)
243 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
244 / sizeof(struct ext4_extent);
245 #ifdef AGGRESSIVE_TEST
246 if (!check && size > 6)
252 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
256 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
257 / sizeof(struct ext4_extent_idx);
258 #ifdef AGGRESSIVE_TEST
259 if (!check && size > 5)
265 static inline int ext4_ext_space_root(struct inode *inode, int check)
269 size = sizeof(EXT4_I(inode)->i_data);
270 size -= sizeof(struct ext4_extent_header);
271 size /= sizeof(struct ext4_extent);
272 #ifdef AGGRESSIVE_TEST
273 if (!check && size > 3)
279 static inline int ext4_ext_space_root_idx(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_idx);
286 #ifdef AGGRESSIVE_TEST
287 if (!check && size > 4)
294 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
295 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
298 struct ext4_ext_path *path = *ppath;
299 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
300 int flags = EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO;
303 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL | EXT4_EX_NOFAIL;
305 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
306 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
311 ext4_ext_max_entries(struct inode *inode, int depth)
315 if (depth == ext_depth(inode)) {
317 max = ext4_ext_space_root(inode, 1);
319 max = ext4_ext_space_root_idx(inode, 1);
322 max = ext4_ext_space_block(inode, 1);
324 max = ext4_ext_space_block_idx(inode, 1);
330 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
332 ext4_fsblk_t block = ext4_ext_pblock(ext);
333 int len = ext4_ext_get_actual_len(ext);
334 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
339 * - overflow/wrap-around
341 if (lblock + len <= lblock)
343 return ext4_inode_block_valid(inode, block, len);
346 static int ext4_valid_extent_idx(struct inode *inode,
347 struct ext4_extent_idx *ext_idx)
349 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
351 return ext4_inode_block_valid(inode, block, 1);
354 static int ext4_valid_extent_entries(struct inode *inode,
355 struct ext4_extent_header *eh,
356 ext4_fsblk_t *pblk, int depth)
358 unsigned short entries;
359 if (eh->eh_entries == 0)
362 entries = le16_to_cpu(eh->eh_entries);
366 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
367 ext4_lblk_t lblock = 0;
368 ext4_lblk_t prev = 0;
371 if (!ext4_valid_extent(inode, ext))
374 /* Check for overlapping extents */
375 lblock = le32_to_cpu(ext->ee_block);
376 len = ext4_ext_get_actual_len(ext);
377 if ((lblock <= prev) && prev) {
378 *pblk = ext4_ext_pblock(ext);
383 prev = lblock + len - 1;
386 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
388 if (!ext4_valid_extent_idx(inode, ext_idx))
397 static int __ext4_ext_check(const char *function, unsigned int line,
398 struct inode *inode, struct ext4_extent_header *eh,
399 int depth, ext4_fsblk_t pblk)
401 const char *error_msg;
402 int max = 0, err = -EFSCORRUPTED;
404 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
405 error_msg = "invalid magic";
408 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
409 error_msg = "unexpected eh_depth";
412 if (unlikely(eh->eh_max == 0)) {
413 error_msg = "invalid eh_max";
416 max = ext4_ext_max_entries(inode, depth);
417 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
418 error_msg = "too large eh_max";
421 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
422 error_msg = "invalid eh_entries";
425 if (!ext4_valid_extent_entries(inode, eh, &pblk, depth)) {
426 error_msg = "invalid extent entries";
429 if (unlikely(depth > 32)) {
430 error_msg = "too large eh_depth";
433 /* Verify checksum on non-root extent tree nodes */
434 if (ext_depth(inode) != depth &&
435 !ext4_extent_block_csum_verify(inode, eh)) {
436 error_msg = "extent tree corrupted";
443 ext4_error_inode_err(inode, function, line, 0, -err,
444 "pblk %llu bad header/extent: %s - magic %x, "
445 "entries %u, max %u(%u), depth %u(%u)",
446 (unsigned long long) pblk, error_msg,
447 le16_to_cpu(eh->eh_magic),
448 le16_to_cpu(eh->eh_entries),
449 le16_to_cpu(eh->eh_max),
450 max, le16_to_cpu(eh->eh_depth), depth);
454 #define ext4_ext_check(inode, eh, depth, pblk) \
455 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
457 int ext4_ext_check_inode(struct inode *inode)
459 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
462 static void ext4_cache_extents(struct inode *inode,
463 struct ext4_extent_header *eh)
465 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
466 ext4_lblk_t prev = 0;
469 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
470 unsigned int status = EXTENT_STATUS_WRITTEN;
471 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
472 int len = ext4_ext_get_actual_len(ex);
474 if (prev && (prev != lblk))
475 ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
478 if (ext4_ext_is_unwritten(ex))
479 status = EXTENT_STATUS_UNWRITTEN;
480 ext4_es_cache_extent(inode, lblk, len,
481 ext4_ext_pblock(ex), status);
486 static struct buffer_head *
487 __read_extent_tree_block(const char *function, unsigned int line,
488 struct inode *inode, ext4_fsblk_t pblk, int depth,
491 struct buffer_head *bh;
493 gfp_t gfp_flags = __GFP_MOVABLE | GFP_NOFS;
495 if (flags & EXT4_EX_NOFAIL)
496 gfp_flags |= __GFP_NOFAIL;
498 bh = sb_getblk_gfp(inode->i_sb, pblk, gfp_flags);
500 return ERR_PTR(-ENOMEM);
502 if (!bh_uptodate_or_lock(bh)) {
503 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
504 err = ext4_read_bh(bh, 0, NULL);
508 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
510 err = __ext4_ext_check(function, line, inode,
511 ext_block_hdr(bh), depth, pblk);
514 set_buffer_verified(bh);
516 * If this is a leaf block, cache all of its entries
518 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
519 struct ext4_extent_header *eh = ext_block_hdr(bh);
520 ext4_cache_extents(inode, eh);
529 #define read_extent_tree_block(inode, pblk, depth, flags) \
530 __read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
534 * This function is called to cache a file's extent information in the
537 int ext4_ext_precache(struct inode *inode)
539 struct ext4_inode_info *ei = EXT4_I(inode);
540 struct ext4_ext_path *path = NULL;
541 struct buffer_head *bh;
542 int i = 0, depth, ret = 0;
544 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
545 return 0; /* not an extent-mapped inode */
547 down_read(&ei->i_data_sem);
548 depth = ext_depth(inode);
550 /* Don't cache anything if there are no external extent blocks */
552 up_read(&ei->i_data_sem);
556 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
559 up_read(&ei->i_data_sem);
563 path[0].p_hdr = ext_inode_hdr(inode);
564 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
567 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
570 * If this is a leaf block or we've reached the end of
571 * the index block, go up
574 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
575 brelse(path[i].p_bh);
580 bh = read_extent_tree_block(inode,
581 ext4_idx_pblock(path[i].p_idx++),
583 EXT4_EX_FORCE_CACHE);
590 path[i].p_hdr = ext_block_hdr(bh);
591 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
593 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
595 up_read(&ei->i_data_sem);
596 ext4_ext_drop_refs(path);
602 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
604 int k, l = path->p_depth;
606 ext_debug(inode, "path:");
607 for (k = 0; k <= l; k++, path++) {
609 ext_debug(inode, " %d->%llu",
610 le32_to_cpu(path->p_idx->ei_block),
611 ext4_idx_pblock(path->p_idx));
612 } else if (path->p_ext) {
613 ext_debug(inode, " %d:[%d]%d:%llu ",
614 le32_to_cpu(path->p_ext->ee_block),
615 ext4_ext_is_unwritten(path->p_ext),
616 ext4_ext_get_actual_len(path->p_ext),
617 ext4_ext_pblock(path->p_ext));
619 ext_debug(inode, " []");
621 ext_debug(inode, "\n");
624 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
626 int depth = ext_depth(inode);
627 struct ext4_extent_header *eh;
628 struct ext4_extent *ex;
634 eh = path[depth].p_hdr;
635 ex = EXT_FIRST_EXTENT(eh);
637 ext_debug(inode, "Displaying leaf extents\n");
639 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
640 ext_debug(inode, "%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
641 ext4_ext_is_unwritten(ex),
642 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
644 ext_debug(inode, "\n");
647 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
648 ext4_fsblk_t newblock, int level)
650 int depth = ext_depth(inode);
651 struct ext4_extent *ex;
653 if (depth != level) {
654 struct ext4_extent_idx *idx;
655 idx = path[level].p_idx;
656 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
657 ext_debug(inode, "%d: move %d:%llu in new index %llu\n",
658 level, le32_to_cpu(idx->ei_block),
659 ext4_idx_pblock(idx), newblock);
666 ex = path[depth].p_ext;
667 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
668 ext_debug(inode, "move %d:%llu:[%d]%d in new leaf %llu\n",
669 le32_to_cpu(ex->ee_block),
671 ext4_ext_is_unwritten(ex),
672 ext4_ext_get_actual_len(ex),
679 #define ext4_ext_show_path(inode, path)
680 #define ext4_ext_show_leaf(inode, path)
681 #define ext4_ext_show_move(inode, path, newblock, level)
684 void ext4_ext_drop_refs(struct ext4_ext_path *path)
690 depth = path->p_depth;
691 for (i = 0; i <= depth; i++, path++) {
698 * ext4_ext_binsearch_idx:
699 * binary search for the closest index of the given block
700 * the header must be checked before calling this
703 ext4_ext_binsearch_idx(struct inode *inode,
704 struct ext4_ext_path *path, ext4_lblk_t block)
706 struct ext4_extent_header *eh = path->p_hdr;
707 struct ext4_extent_idx *r, *l, *m;
710 ext_debug(inode, "binsearch for %u(idx): ", block);
712 l = EXT_FIRST_INDEX(eh) + 1;
713 r = EXT_LAST_INDEX(eh);
716 if (block < le32_to_cpu(m->ei_block))
720 ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
721 le32_to_cpu(l->ei_block), m, le32_to_cpu(m->ei_block),
722 r, le32_to_cpu(r->ei_block));
726 ext_debug(inode, " -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
727 ext4_idx_pblock(path->p_idx));
729 #ifdef CHECK_BINSEARCH
731 struct ext4_extent_idx *chix, *ix;
734 chix = ix = EXT_FIRST_INDEX(eh);
735 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
736 if (k != 0 && le32_to_cpu(ix->ei_block) <=
737 le32_to_cpu(ix[-1].ei_block)) {
738 printk(KERN_DEBUG "k=%d, ix=0x%p, "
740 ix, EXT_FIRST_INDEX(eh));
741 printk(KERN_DEBUG "%u <= %u\n",
742 le32_to_cpu(ix->ei_block),
743 le32_to_cpu(ix[-1].ei_block));
745 BUG_ON(k && le32_to_cpu(ix->ei_block)
746 <= le32_to_cpu(ix[-1].ei_block));
747 if (block < le32_to_cpu(ix->ei_block))
751 BUG_ON(chix != path->p_idx);
758 * ext4_ext_binsearch:
759 * binary search for closest extent of the given block
760 * the header must be checked before calling this
763 ext4_ext_binsearch(struct inode *inode,
764 struct ext4_ext_path *path, ext4_lblk_t block)
766 struct ext4_extent_header *eh = path->p_hdr;
767 struct ext4_extent *r, *l, *m;
769 if (eh->eh_entries == 0) {
771 * this leaf is empty:
772 * we get such a leaf in split/add case
777 ext_debug(inode, "binsearch for %u: ", block);
779 l = EXT_FIRST_EXTENT(eh) + 1;
780 r = EXT_LAST_EXTENT(eh);
784 if (block < le32_to_cpu(m->ee_block))
788 ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
789 le32_to_cpu(l->ee_block), m, le32_to_cpu(m->ee_block),
790 r, le32_to_cpu(r->ee_block));
794 ext_debug(inode, " -> %d:%llu:[%d]%d ",
795 le32_to_cpu(path->p_ext->ee_block),
796 ext4_ext_pblock(path->p_ext),
797 ext4_ext_is_unwritten(path->p_ext),
798 ext4_ext_get_actual_len(path->p_ext));
800 #ifdef CHECK_BINSEARCH
802 struct ext4_extent *chex, *ex;
805 chex = ex = EXT_FIRST_EXTENT(eh);
806 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
807 BUG_ON(k && le32_to_cpu(ex->ee_block)
808 <= le32_to_cpu(ex[-1].ee_block));
809 if (block < le32_to_cpu(ex->ee_block))
813 BUG_ON(chex != path->p_ext);
819 void ext4_ext_tree_init(handle_t *handle, struct inode *inode)
821 struct ext4_extent_header *eh;
823 eh = ext_inode_hdr(inode);
826 eh->eh_magic = EXT4_EXT_MAGIC;
827 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
828 eh->eh_generation = 0;
829 ext4_mark_inode_dirty(handle, inode);
832 struct ext4_ext_path *
833 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
834 struct ext4_ext_path **orig_path, int flags)
836 struct ext4_extent_header *eh;
837 struct buffer_head *bh;
838 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
839 short int depth, i, ppos = 0;
841 gfp_t gfp_flags = GFP_NOFS;
843 if (flags & EXT4_EX_NOFAIL)
844 gfp_flags |= __GFP_NOFAIL;
846 eh = ext_inode_hdr(inode);
847 depth = ext_depth(inode);
848 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
849 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
856 ext4_ext_drop_refs(path);
857 if (depth > path[0].p_maxdepth) {
859 *orig_path = path = NULL;
863 /* account possible depth increase */
864 path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
867 return ERR_PTR(-ENOMEM);
868 path[0].p_maxdepth = depth + 1;
874 if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
875 ext4_cache_extents(inode, eh);
876 /* walk through the tree */
878 ext_debug(inode, "depth %d: num %d, max %d\n",
879 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
881 ext4_ext_binsearch_idx(inode, path + ppos, block);
882 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
883 path[ppos].p_depth = i;
884 path[ppos].p_ext = NULL;
886 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
893 eh = ext_block_hdr(bh);
895 path[ppos].p_bh = bh;
896 path[ppos].p_hdr = eh;
899 path[ppos].p_depth = i;
900 path[ppos].p_ext = NULL;
901 path[ppos].p_idx = NULL;
904 ext4_ext_binsearch(inode, path + ppos, block);
905 /* if not an empty leaf */
906 if (path[ppos].p_ext)
907 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
909 ext4_ext_show_path(inode, path);
914 ext4_ext_drop_refs(path);
922 * ext4_ext_insert_index:
923 * insert new index [@logical;@ptr] into the block at @curp;
924 * check where to insert: before @curp or after @curp
926 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
927 struct ext4_ext_path *curp,
928 int logical, ext4_fsblk_t ptr)
930 struct ext4_extent_idx *ix;
933 err = ext4_ext_get_access(handle, inode, curp);
937 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
938 EXT4_ERROR_INODE(inode,
939 "logical %d == ei_block %d!",
940 logical, le32_to_cpu(curp->p_idx->ei_block));
941 return -EFSCORRUPTED;
944 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
945 >= le16_to_cpu(curp->p_hdr->eh_max))) {
946 EXT4_ERROR_INODE(inode,
947 "eh_entries %d >= eh_max %d!",
948 le16_to_cpu(curp->p_hdr->eh_entries),
949 le16_to_cpu(curp->p_hdr->eh_max));
950 return -EFSCORRUPTED;
953 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
955 ext_debug(inode, "insert new index %d after: %llu\n",
957 ix = curp->p_idx + 1;
960 ext_debug(inode, "insert new index %d before: %llu\n",
965 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
968 ext_debug(inode, "insert new index %d: "
969 "move %d indices from 0x%p to 0x%p\n",
970 logical, len, ix, ix + 1);
971 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
974 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
975 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
976 return -EFSCORRUPTED;
979 ix->ei_block = cpu_to_le32(logical);
980 ext4_idx_store_pblock(ix, ptr);
981 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
983 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
984 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
985 return -EFSCORRUPTED;
988 err = ext4_ext_dirty(handle, inode, curp);
989 ext4_std_error(inode->i_sb, err);
996 * inserts new subtree into the path, using free index entry
998 * - allocates all needed blocks (new leaf and all intermediate index blocks)
999 * - makes decision where to split
1000 * - moves remaining extents and index entries (right to the split point)
1001 * into the newly allocated blocks
1002 * - initializes subtree
1004 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1006 struct ext4_ext_path *path,
1007 struct ext4_extent *newext, int at)
1009 struct buffer_head *bh = NULL;
1010 int depth = ext_depth(inode);
1011 struct ext4_extent_header *neh;
1012 struct ext4_extent_idx *fidx;
1013 int i = at, k, m, a;
1014 ext4_fsblk_t newblock, oldblock;
1016 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1017 gfp_t gfp_flags = GFP_NOFS;
1019 size_t ext_size = 0;
1021 if (flags & EXT4_EX_NOFAIL)
1022 gfp_flags |= __GFP_NOFAIL;
1024 /* make decision: where to split? */
1025 /* FIXME: now decision is simplest: at current extent */
1027 /* if current leaf will be split, then we should use
1028 * border from split point */
1029 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1030 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1031 return -EFSCORRUPTED;
1033 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1034 border = path[depth].p_ext[1].ee_block;
1035 ext_debug(inode, "leaf will be split."
1036 " next leaf starts at %d\n",
1037 le32_to_cpu(border));
1039 border = newext->ee_block;
1040 ext_debug(inode, "leaf will be added."
1041 " next leaf starts at %d\n",
1042 le32_to_cpu(border));
1046 * If error occurs, then we break processing
1047 * and mark filesystem read-only. index won't
1048 * be inserted and tree will be in consistent
1049 * state. Next mount will repair buffers too.
1053 * Get array to track all allocated blocks.
1054 * We need this to handle errors and free blocks
1057 ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), gfp_flags);
1061 /* allocate all needed blocks */
1062 ext_debug(inode, "allocate %d blocks for indexes/leaf\n", depth - at);
1063 for (a = 0; a < depth - at; a++) {
1064 newblock = ext4_ext_new_meta_block(handle, inode, path,
1065 newext, &err, flags);
1068 ablocks[a] = newblock;
1071 /* initialize new leaf */
1072 newblock = ablocks[--a];
1073 if (unlikely(newblock == 0)) {
1074 EXT4_ERROR_INODE(inode, "newblock == 0!");
1075 err = -EFSCORRUPTED;
1078 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1079 if (unlikely(!bh)) {
1085 err = ext4_journal_get_create_access(handle, bh);
1089 neh = ext_block_hdr(bh);
1090 neh->eh_entries = 0;
1091 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1092 neh->eh_magic = EXT4_EXT_MAGIC;
1094 neh->eh_generation = 0;
1096 /* move remainder of path[depth] to the new leaf */
1097 if (unlikely(path[depth].p_hdr->eh_entries !=
1098 path[depth].p_hdr->eh_max)) {
1099 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1100 path[depth].p_hdr->eh_entries,
1101 path[depth].p_hdr->eh_max);
1102 err = -EFSCORRUPTED;
1105 /* start copy from next extent */
1106 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1107 ext4_ext_show_move(inode, path, newblock, depth);
1109 struct ext4_extent *ex;
1110 ex = EXT_FIRST_EXTENT(neh);
1111 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1112 le16_add_cpu(&neh->eh_entries, m);
1115 /* zero out unused area in the extent block */
1116 ext_size = sizeof(struct ext4_extent_header) +
1117 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1118 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1119 ext4_extent_block_csum_set(inode, neh);
1120 set_buffer_uptodate(bh);
1123 err = ext4_handle_dirty_metadata(handle, inode, bh);
1129 /* correct old leaf */
1131 err = ext4_ext_get_access(handle, inode, path + depth);
1134 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1135 err = ext4_ext_dirty(handle, inode, path + depth);
1141 /* create intermediate indexes */
1143 if (unlikely(k < 0)) {
1144 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1145 err = -EFSCORRUPTED;
1149 ext_debug(inode, "create %d intermediate indices\n", k);
1150 /* insert new index into current index block */
1151 /* current depth stored in i var */
1154 oldblock = newblock;
1155 newblock = ablocks[--a];
1156 bh = sb_getblk(inode->i_sb, newblock);
1157 if (unlikely(!bh)) {
1163 err = ext4_journal_get_create_access(handle, bh);
1167 neh = ext_block_hdr(bh);
1168 neh->eh_entries = cpu_to_le16(1);
1169 neh->eh_magic = EXT4_EXT_MAGIC;
1170 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1171 neh->eh_depth = cpu_to_le16(depth - i);
1172 neh->eh_generation = 0;
1173 fidx = EXT_FIRST_INDEX(neh);
1174 fidx->ei_block = border;
1175 ext4_idx_store_pblock(fidx, oldblock);
1177 ext_debug(inode, "int.index at %d (block %llu): %u -> %llu\n",
1178 i, newblock, le32_to_cpu(border), oldblock);
1180 /* move remainder of path[i] to the new index block */
1181 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1182 EXT_LAST_INDEX(path[i].p_hdr))) {
1183 EXT4_ERROR_INODE(inode,
1184 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1185 le32_to_cpu(path[i].p_ext->ee_block));
1186 err = -EFSCORRUPTED;
1189 /* start copy indexes */
1190 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1191 ext_debug(inode, "cur 0x%p, last 0x%p\n", path[i].p_idx,
1192 EXT_MAX_INDEX(path[i].p_hdr));
1193 ext4_ext_show_move(inode, path, newblock, i);
1195 memmove(++fidx, path[i].p_idx,
1196 sizeof(struct ext4_extent_idx) * m);
1197 le16_add_cpu(&neh->eh_entries, m);
1199 /* zero out unused area in the extent block */
1200 ext_size = sizeof(struct ext4_extent_header) +
1201 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1202 memset(bh->b_data + ext_size, 0,
1203 inode->i_sb->s_blocksize - ext_size);
1204 ext4_extent_block_csum_set(inode, neh);
1205 set_buffer_uptodate(bh);
1208 err = ext4_handle_dirty_metadata(handle, inode, bh);
1214 /* correct old index */
1216 err = ext4_ext_get_access(handle, inode, path + i);
1219 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1220 err = ext4_ext_dirty(handle, inode, path + i);
1228 /* insert new index */
1229 err = ext4_ext_insert_index(handle, inode, path + at,
1230 le32_to_cpu(border), newblock);
1234 if (buffer_locked(bh))
1240 /* free all allocated blocks in error case */
1241 for (i = 0; i < depth; i++) {
1244 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1245 EXT4_FREE_BLOCKS_METADATA);
1254 * ext4_ext_grow_indepth:
1255 * implements tree growing procedure:
1256 * - allocates new block
1257 * - moves top-level data (index block or leaf) into the new block
1258 * - initializes new top-level, creating index that points to the
1259 * just created block
1261 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1264 struct ext4_extent_header *neh;
1265 struct buffer_head *bh;
1266 ext4_fsblk_t newblock, goal = 0;
1267 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1269 size_t ext_size = 0;
1271 /* Try to prepend new index to old one */
1272 if (ext_depth(inode))
1273 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1274 if (goal > le32_to_cpu(es->s_first_data_block)) {
1275 flags |= EXT4_MB_HINT_TRY_GOAL;
1278 goal = ext4_inode_to_goal_block(inode);
1279 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1284 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1289 err = ext4_journal_get_create_access(handle, bh);
1295 ext_size = sizeof(EXT4_I(inode)->i_data);
1296 /* move top-level index/leaf into new block */
1297 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1298 /* zero out unused area in the extent block */
1299 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1301 /* set size of new block */
1302 neh = ext_block_hdr(bh);
1303 /* old root could have indexes or leaves
1304 * so calculate e_max right way */
1305 if (ext_depth(inode))
1306 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1308 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1309 neh->eh_magic = EXT4_EXT_MAGIC;
1310 ext4_extent_block_csum_set(inode, neh);
1311 set_buffer_uptodate(bh);
1314 err = ext4_handle_dirty_metadata(handle, inode, bh);
1318 /* Update top-level index: num,max,pointer */
1319 neh = ext_inode_hdr(inode);
1320 neh->eh_entries = cpu_to_le16(1);
1321 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1322 if (neh->eh_depth == 0) {
1323 /* Root extent block becomes index block */
1324 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1325 EXT_FIRST_INDEX(neh)->ei_block =
1326 EXT_FIRST_EXTENT(neh)->ee_block;
1328 ext_debug(inode, "new root: num %d(%d), lblock %d, ptr %llu\n",
1329 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1330 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1331 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1333 le16_add_cpu(&neh->eh_depth, 1);
1334 err = ext4_mark_inode_dirty(handle, inode);
1342 * ext4_ext_create_new_leaf:
1343 * finds empty index and adds new leaf.
1344 * if no free index is found, then it requests in-depth growing.
1346 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1347 unsigned int mb_flags,
1348 unsigned int gb_flags,
1349 struct ext4_ext_path **ppath,
1350 struct ext4_extent *newext)
1352 struct ext4_ext_path *path = *ppath;
1353 struct ext4_ext_path *curp;
1354 int depth, i, err = 0;
1357 i = depth = ext_depth(inode);
1359 /* walk up to the tree and look for free index entry */
1360 curp = path + depth;
1361 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1366 /* we use already allocated block for index block,
1367 * so subsequent data blocks should be contiguous */
1368 if (EXT_HAS_FREE_INDEX(curp)) {
1369 /* if we found index with free entry, then use that
1370 * entry: create all needed subtree and add new leaf */
1371 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1376 path = ext4_find_extent(inode,
1377 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1380 err = PTR_ERR(path);
1382 /* tree is full, time to grow in depth */
1383 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1388 path = ext4_find_extent(inode,
1389 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1392 err = PTR_ERR(path);
1397 * only first (depth 0 -> 1) produces free space;
1398 * in all other cases we have to split the grown tree
1400 depth = ext_depth(inode);
1401 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1402 /* now we need to split */
1412 * search the closest allocated block to the left for *logical
1413 * and returns it at @logical + it's physical address at @phys
1414 * if *logical is the smallest allocated block, the function
1415 * returns 0 at @phys
1416 * return value contains 0 (success) or error code
1418 static int ext4_ext_search_left(struct inode *inode,
1419 struct ext4_ext_path *path,
1420 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1422 struct ext4_extent_idx *ix;
1423 struct ext4_extent *ex;
1426 if (unlikely(path == NULL)) {
1427 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1428 return -EFSCORRUPTED;
1430 depth = path->p_depth;
1433 if (depth == 0 && path->p_ext == NULL)
1436 /* usually extent in the path covers blocks smaller
1437 * then *logical, but it can be that extent is the
1438 * first one in the file */
1440 ex = path[depth].p_ext;
1441 ee_len = ext4_ext_get_actual_len(ex);
1442 if (*logical < le32_to_cpu(ex->ee_block)) {
1443 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1444 EXT4_ERROR_INODE(inode,
1445 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1446 *logical, le32_to_cpu(ex->ee_block));
1447 return -EFSCORRUPTED;
1449 while (--depth >= 0) {
1450 ix = path[depth].p_idx;
1451 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1452 EXT4_ERROR_INODE(inode,
1453 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1454 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1455 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1456 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1458 return -EFSCORRUPTED;
1464 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1465 EXT4_ERROR_INODE(inode,
1466 "logical %d < ee_block %d + ee_len %d!",
1467 *logical, le32_to_cpu(ex->ee_block), ee_len);
1468 return -EFSCORRUPTED;
1471 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1472 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1477 * Search the closest allocated block to the right for *logical
1478 * and returns it at @logical + it's physical address at @phys.
1479 * If not exists, return 0 and @phys is set to 0. We will return
1480 * 1 which means we found an allocated block and ret_ex is valid.
1481 * Or return a (< 0) error code.
1483 static int ext4_ext_search_right(struct inode *inode,
1484 struct ext4_ext_path *path,
1485 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1486 struct ext4_extent *ret_ex)
1488 struct buffer_head *bh = NULL;
1489 struct ext4_extent_header *eh;
1490 struct ext4_extent_idx *ix;
1491 struct ext4_extent *ex;
1493 int depth; /* Note, NOT eh_depth; depth from top of tree */
1496 if (unlikely(path == NULL)) {
1497 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1498 return -EFSCORRUPTED;
1500 depth = path->p_depth;
1503 if (depth == 0 && path->p_ext == NULL)
1506 /* usually extent in the path covers blocks smaller
1507 * then *logical, but it can be that extent is the
1508 * first one in the file */
1510 ex = path[depth].p_ext;
1511 ee_len = ext4_ext_get_actual_len(ex);
1512 if (*logical < le32_to_cpu(ex->ee_block)) {
1513 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1514 EXT4_ERROR_INODE(inode,
1515 "first_extent(path[%d].p_hdr) != ex",
1517 return -EFSCORRUPTED;
1519 while (--depth >= 0) {
1520 ix = path[depth].p_idx;
1521 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1522 EXT4_ERROR_INODE(inode,
1523 "ix != EXT_FIRST_INDEX *logical %d!",
1525 return -EFSCORRUPTED;
1531 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1532 EXT4_ERROR_INODE(inode,
1533 "logical %d < ee_block %d + ee_len %d!",
1534 *logical, le32_to_cpu(ex->ee_block), ee_len);
1535 return -EFSCORRUPTED;
1538 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1539 /* next allocated block in this leaf */
1544 /* go up and search for index to the right */
1545 while (--depth >= 0) {
1546 ix = path[depth].p_idx;
1547 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1551 /* we've gone up to the root and found no index to the right */
1555 /* we've found index to the right, let's
1556 * follow it and find the closest allocated
1557 * block to the right */
1559 block = ext4_idx_pblock(ix);
1560 while (++depth < path->p_depth) {
1561 /* subtract from p_depth to get proper eh_depth */
1562 bh = read_extent_tree_block(inode, block,
1563 path->p_depth - depth, 0);
1566 eh = ext_block_hdr(bh);
1567 ix = EXT_FIRST_INDEX(eh);
1568 block = ext4_idx_pblock(ix);
1572 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1575 eh = ext_block_hdr(bh);
1576 ex = EXT_FIRST_EXTENT(eh);
1578 *logical = le32_to_cpu(ex->ee_block);
1579 *phys = ext4_ext_pblock(ex);
1588 * ext4_ext_next_allocated_block:
1589 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1590 * NOTE: it considers block number from index entry as
1591 * allocated block. Thus, index entries have to be consistent
1595 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1599 BUG_ON(path == NULL);
1600 depth = path->p_depth;
1602 if (depth == 0 && path->p_ext == NULL)
1603 return EXT_MAX_BLOCKS;
1605 while (depth >= 0) {
1606 struct ext4_ext_path *p = &path[depth];
1608 if (depth == path->p_depth) {
1610 if (p->p_ext && p->p_ext != EXT_LAST_EXTENT(p->p_hdr))
1611 return le32_to_cpu(p->p_ext[1].ee_block);
1614 if (p->p_idx != EXT_LAST_INDEX(p->p_hdr))
1615 return le32_to_cpu(p->p_idx[1].ei_block);
1620 return EXT_MAX_BLOCKS;
1624 * ext4_ext_next_leaf_block:
1625 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1627 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1631 BUG_ON(path == NULL);
1632 depth = path->p_depth;
1634 /* zero-tree has no leaf blocks at all */
1636 return EXT_MAX_BLOCKS;
1638 /* go to index block */
1641 while (depth >= 0) {
1642 if (path[depth].p_idx !=
1643 EXT_LAST_INDEX(path[depth].p_hdr))
1644 return (ext4_lblk_t)
1645 le32_to_cpu(path[depth].p_idx[1].ei_block);
1649 return EXT_MAX_BLOCKS;
1653 * ext4_ext_correct_indexes:
1654 * if leaf gets modified and modified extent is first in the leaf,
1655 * then we have to correct all indexes above.
1656 * TODO: do we need to correct tree in all cases?
1658 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1659 struct ext4_ext_path *path)
1661 struct ext4_extent_header *eh;
1662 int depth = ext_depth(inode);
1663 struct ext4_extent *ex;
1667 eh = path[depth].p_hdr;
1668 ex = path[depth].p_ext;
1670 if (unlikely(ex == NULL || eh == NULL)) {
1671 EXT4_ERROR_INODE(inode,
1672 "ex %p == NULL or eh %p == NULL", ex, eh);
1673 return -EFSCORRUPTED;
1677 /* there is no tree at all */
1681 if (ex != EXT_FIRST_EXTENT(eh)) {
1682 /* we correct tree if first leaf got modified only */
1687 * TODO: we need correction if border is smaller than current one
1690 border = path[depth].p_ext->ee_block;
1691 err = ext4_ext_get_access(handle, inode, path + k);
1694 path[k].p_idx->ei_block = border;
1695 err = ext4_ext_dirty(handle, inode, path + k);
1700 /* change all left-side indexes */
1701 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1703 err = ext4_ext_get_access(handle, inode, path + k);
1706 path[k].p_idx->ei_block = border;
1707 err = ext4_ext_dirty(handle, inode, path + k);
1715 static int ext4_can_extents_be_merged(struct inode *inode,
1716 struct ext4_extent *ex1,
1717 struct ext4_extent *ex2)
1719 unsigned short ext1_ee_len, ext2_ee_len;
1721 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1724 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1725 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1727 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1728 le32_to_cpu(ex2->ee_block))
1731 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1734 if (ext4_ext_is_unwritten(ex1) &&
1735 ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)
1737 #ifdef AGGRESSIVE_TEST
1738 if (ext1_ee_len >= 4)
1742 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1748 * This function tries to merge the "ex" extent to the next extent in the tree.
1749 * It always tries to merge towards right. If you want to merge towards
1750 * left, pass "ex - 1" as argument instead of "ex".
1751 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1752 * 1 if they got merged.
1754 static int ext4_ext_try_to_merge_right(struct inode *inode,
1755 struct ext4_ext_path *path,
1756 struct ext4_extent *ex)
1758 struct ext4_extent_header *eh;
1759 unsigned int depth, len;
1760 int merge_done = 0, unwritten;
1762 depth = ext_depth(inode);
1763 BUG_ON(path[depth].p_hdr == NULL);
1764 eh = path[depth].p_hdr;
1766 while (ex < EXT_LAST_EXTENT(eh)) {
1767 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1769 /* merge with next extent! */
1770 unwritten = ext4_ext_is_unwritten(ex);
1771 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1772 + ext4_ext_get_actual_len(ex + 1));
1774 ext4_ext_mark_unwritten(ex);
1776 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1777 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1778 * sizeof(struct ext4_extent);
1779 memmove(ex + 1, ex + 2, len);
1781 le16_add_cpu(&eh->eh_entries, -1);
1783 WARN_ON(eh->eh_entries == 0);
1784 if (!eh->eh_entries)
1785 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1792 * This function does a very simple check to see if we can collapse
1793 * an extent tree with a single extent tree leaf block into the inode.
1795 static void ext4_ext_try_to_merge_up(handle_t *handle,
1796 struct inode *inode,
1797 struct ext4_ext_path *path)
1800 unsigned max_root = ext4_ext_space_root(inode, 0);
1803 if ((path[0].p_depth != 1) ||
1804 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1805 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1809 * We need to modify the block allocation bitmap and the block
1810 * group descriptor to release the extent tree block. If we
1811 * can't get the journal credits, give up.
1813 if (ext4_journal_extend(handle, 2,
1814 ext4_free_metadata_revoke_credits(inode->i_sb, 1)))
1818 * Copy the extent data up to the inode
1820 blk = ext4_idx_pblock(path[0].p_idx);
1821 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1822 sizeof(struct ext4_extent_idx);
1823 s += sizeof(struct ext4_extent_header);
1825 path[1].p_maxdepth = path[0].p_maxdepth;
1826 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1827 path[0].p_depth = 0;
1828 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1829 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1830 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1832 brelse(path[1].p_bh);
1833 ext4_free_blocks(handle, inode, NULL, blk, 1,
1834 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1838 * This function tries to merge the @ex extent to neighbours in the tree, then
1839 * tries to collapse the extent tree into the inode.
1841 static void ext4_ext_try_to_merge(handle_t *handle,
1842 struct inode *inode,
1843 struct ext4_ext_path *path,
1844 struct ext4_extent *ex)
1846 struct ext4_extent_header *eh;
1850 depth = ext_depth(inode);
1851 BUG_ON(path[depth].p_hdr == NULL);
1852 eh = path[depth].p_hdr;
1854 if (ex > EXT_FIRST_EXTENT(eh))
1855 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1858 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1860 ext4_ext_try_to_merge_up(handle, inode, path);
1864 * check if a portion of the "newext" extent overlaps with an
1867 * If there is an overlap discovered, it updates the length of the newext
1868 * such that there will be no overlap, and then returns 1.
1869 * If there is no overlap found, it returns 0.
1871 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1872 struct inode *inode,
1873 struct ext4_extent *newext,
1874 struct ext4_ext_path *path)
1877 unsigned int depth, len1;
1878 unsigned int ret = 0;
1880 b1 = le32_to_cpu(newext->ee_block);
1881 len1 = ext4_ext_get_actual_len(newext);
1882 depth = ext_depth(inode);
1883 if (!path[depth].p_ext)
1885 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1888 * get the next allocated block if the extent in the path
1889 * is before the requested block(s)
1892 b2 = ext4_ext_next_allocated_block(path);
1893 if (b2 == EXT_MAX_BLOCKS)
1895 b2 = EXT4_LBLK_CMASK(sbi, b2);
1898 /* check for wrap through zero on extent logical start block*/
1899 if (b1 + len1 < b1) {
1900 len1 = EXT_MAX_BLOCKS - b1;
1901 newext->ee_len = cpu_to_le16(len1);
1905 /* check for overlap */
1906 if (b1 + len1 > b2) {
1907 newext->ee_len = cpu_to_le16(b2 - b1);
1915 * ext4_ext_insert_extent:
1916 * tries to merge requested extent into the existing extent or
1917 * inserts requested extent as new one into the tree,
1918 * creating new leaf in the no-space case.
1920 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1921 struct ext4_ext_path **ppath,
1922 struct ext4_extent *newext, int gb_flags)
1924 struct ext4_ext_path *path = *ppath;
1925 struct ext4_extent_header *eh;
1926 struct ext4_extent *ex, *fex;
1927 struct ext4_extent *nearex; /* nearest extent */
1928 struct ext4_ext_path *npath = NULL;
1929 int depth, len, err;
1931 int mb_flags = 0, unwritten;
1933 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1934 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1935 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1936 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1937 return -EFSCORRUPTED;
1939 depth = ext_depth(inode);
1940 ex = path[depth].p_ext;
1941 eh = path[depth].p_hdr;
1942 if (unlikely(path[depth].p_hdr == NULL)) {
1943 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1944 return -EFSCORRUPTED;
1947 /* try to insert block into found extent and return */
1948 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1951 * Try to see whether we should rather test the extent on
1952 * right from ex, or from the left of ex. This is because
1953 * ext4_find_extent() can return either extent on the
1954 * left, or on the right from the searched position. This
1955 * will make merging more effective.
1957 if (ex < EXT_LAST_EXTENT(eh) &&
1958 (le32_to_cpu(ex->ee_block) +
1959 ext4_ext_get_actual_len(ex) <
1960 le32_to_cpu(newext->ee_block))) {
1963 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
1964 (le32_to_cpu(newext->ee_block) +
1965 ext4_ext_get_actual_len(newext) <
1966 le32_to_cpu(ex->ee_block)))
1969 /* Try to append newex to the ex */
1970 if (ext4_can_extents_be_merged(inode, ex, newext)) {
1971 ext_debug(inode, "append [%d]%d block to %u:[%d]%d"
1973 ext4_ext_is_unwritten(newext),
1974 ext4_ext_get_actual_len(newext),
1975 le32_to_cpu(ex->ee_block),
1976 ext4_ext_is_unwritten(ex),
1977 ext4_ext_get_actual_len(ex),
1978 ext4_ext_pblock(ex));
1979 err = ext4_ext_get_access(handle, inode,
1983 unwritten = ext4_ext_is_unwritten(ex);
1984 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1985 + ext4_ext_get_actual_len(newext));
1987 ext4_ext_mark_unwritten(ex);
1988 eh = path[depth].p_hdr;
1994 /* Try to prepend newex to the ex */
1995 if (ext4_can_extents_be_merged(inode, newext, ex)) {
1996 ext_debug(inode, "prepend %u[%d]%d block to %u:[%d]%d"
1998 le32_to_cpu(newext->ee_block),
1999 ext4_ext_is_unwritten(newext),
2000 ext4_ext_get_actual_len(newext),
2001 le32_to_cpu(ex->ee_block),
2002 ext4_ext_is_unwritten(ex),
2003 ext4_ext_get_actual_len(ex),
2004 ext4_ext_pblock(ex));
2005 err = ext4_ext_get_access(handle, inode,
2010 unwritten = ext4_ext_is_unwritten(ex);
2011 ex->ee_block = newext->ee_block;
2012 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2013 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2014 + ext4_ext_get_actual_len(newext));
2016 ext4_ext_mark_unwritten(ex);
2017 eh = path[depth].p_hdr;
2023 depth = ext_depth(inode);
2024 eh = path[depth].p_hdr;
2025 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2028 /* probably next leaf has space for us? */
2029 fex = EXT_LAST_EXTENT(eh);
2030 next = EXT_MAX_BLOCKS;
2031 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2032 next = ext4_ext_next_leaf_block(path);
2033 if (next != EXT_MAX_BLOCKS) {
2034 ext_debug(inode, "next leaf block - %u\n", next);
2035 BUG_ON(npath != NULL);
2036 npath = ext4_find_extent(inode, next, NULL, gb_flags);
2038 return PTR_ERR(npath);
2039 BUG_ON(npath->p_depth != path->p_depth);
2040 eh = npath[depth].p_hdr;
2041 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2042 ext_debug(inode, "next leaf isn't full(%d)\n",
2043 le16_to_cpu(eh->eh_entries));
2047 ext_debug(inode, "next leaf has no free space(%d,%d)\n",
2048 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2052 * There is no free space in the found leaf.
2053 * We're gonna add a new leaf in the tree.
2055 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2056 mb_flags |= EXT4_MB_USE_RESERVED;
2057 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2061 depth = ext_depth(inode);
2062 eh = path[depth].p_hdr;
2065 nearex = path[depth].p_ext;
2067 err = ext4_ext_get_access(handle, inode, path + depth);
2072 /* there is no extent in this leaf, create first one */
2073 ext_debug(inode, "first extent in the leaf: %u:%llu:[%d]%d\n",
2074 le32_to_cpu(newext->ee_block),
2075 ext4_ext_pblock(newext),
2076 ext4_ext_is_unwritten(newext),
2077 ext4_ext_get_actual_len(newext));
2078 nearex = EXT_FIRST_EXTENT(eh);
2080 if (le32_to_cpu(newext->ee_block)
2081 > le32_to_cpu(nearex->ee_block)) {
2083 ext_debug(inode, "insert %u:%llu:[%d]%d before: "
2085 le32_to_cpu(newext->ee_block),
2086 ext4_ext_pblock(newext),
2087 ext4_ext_is_unwritten(newext),
2088 ext4_ext_get_actual_len(newext),
2093 BUG_ON(newext->ee_block == nearex->ee_block);
2094 ext_debug(inode, "insert %u:%llu:[%d]%d after: "
2096 le32_to_cpu(newext->ee_block),
2097 ext4_ext_pblock(newext),
2098 ext4_ext_is_unwritten(newext),
2099 ext4_ext_get_actual_len(newext),
2102 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2104 ext_debug(inode, "insert %u:%llu:[%d]%d: "
2105 "move %d extents from 0x%p to 0x%p\n",
2106 le32_to_cpu(newext->ee_block),
2107 ext4_ext_pblock(newext),
2108 ext4_ext_is_unwritten(newext),
2109 ext4_ext_get_actual_len(newext),
2110 len, nearex, nearex + 1);
2111 memmove(nearex + 1, nearex,
2112 len * sizeof(struct ext4_extent));
2116 le16_add_cpu(&eh->eh_entries, 1);
2117 path[depth].p_ext = nearex;
2118 nearex->ee_block = newext->ee_block;
2119 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2120 nearex->ee_len = newext->ee_len;
2123 /* try to merge extents */
2124 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2125 ext4_ext_try_to_merge(handle, inode, path, nearex);
2128 /* time to correct all indexes above */
2129 err = ext4_ext_correct_indexes(handle, inode, path);
2133 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2136 ext4_ext_drop_refs(npath);
2141 static int ext4_fill_es_cache_info(struct inode *inode,
2142 ext4_lblk_t block, ext4_lblk_t num,
2143 struct fiemap_extent_info *fieinfo)
2145 ext4_lblk_t next, end = block + num - 1;
2146 struct extent_status es;
2147 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2151 while (block <= end) {
2154 if (!ext4_es_lookup_extent(inode, block, &next, &es))
2156 if (ext4_es_is_unwritten(&es))
2157 flags |= FIEMAP_EXTENT_UNWRITTEN;
2158 if (ext4_es_is_delayed(&es))
2159 flags |= (FIEMAP_EXTENT_DELALLOC |
2160 FIEMAP_EXTENT_UNKNOWN);
2161 if (ext4_es_is_hole(&es))
2162 flags |= EXT4_FIEMAP_EXTENT_HOLE;
2164 flags |= FIEMAP_EXTENT_LAST;
2165 if (flags & (FIEMAP_EXTENT_DELALLOC|
2166 EXT4_FIEMAP_EXTENT_HOLE))
2169 es.es_pblk = ext4_es_pblock(&es);
2170 err = fiemap_fill_next_extent(fieinfo,
2171 (__u64)es.es_lblk << blksize_bits,
2172 (__u64)es.es_pblk << blksize_bits,
2173 (__u64)es.es_len << blksize_bits,
2188 * ext4_ext_determine_hole - determine hole around given block
2189 * @inode: inode we lookup in
2190 * @path: path in extent tree to @lblk
2191 * @lblk: pointer to logical block around which we want to determine hole
2193 * Determine hole length (and start if easily possible) around given logical
2194 * block. We don't try too hard to find the beginning of the hole but @path
2195 * actually points to extent before @lblk, we provide it.
2197 * The function returns the length of a hole starting at @lblk. We update @lblk
2198 * to the beginning of the hole if we managed to find it.
2200 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2201 struct ext4_ext_path *path,
2204 int depth = ext_depth(inode);
2205 struct ext4_extent *ex;
2208 ex = path[depth].p_ext;
2210 /* there is no extent yet, so gap is [0;-] */
2212 len = EXT_MAX_BLOCKS;
2213 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2214 len = le32_to_cpu(ex->ee_block) - *lblk;
2215 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2216 + ext4_ext_get_actual_len(ex)) {
2219 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2220 next = ext4_ext_next_allocated_block(path);
2221 BUG_ON(next == *lblk);
2230 * ext4_ext_put_gap_in_cache:
2231 * calculate boundaries of the gap that the requested block fits into
2232 * and cache this gap
2235 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2236 ext4_lblk_t hole_len)
2238 struct extent_status es;
2240 ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
2241 hole_start + hole_len - 1, &es);
2243 /* There's delayed extent containing lblock? */
2244 if (es.es_lblk <= hole_start)
2246 hole_len = min(es.es_lblk - hole_start, hole_len);
2248 ext_debug(inode, " -> %u:%u\n", hole_start, hole_len);
2249 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2250 EXTENT_STATUS_HOLE);
2255 * removes index from the index block.
2257 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2258 struct ext4_ext_path *path, int depth)
2263 /* free index block */
2265 path = path + depth;
2266 leaf = ext4_idx_pblock(path->p_idx);
2267 if (unlikely(path->p_hdr->eh_entries == 0)) {
2268 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2269 return -EFSCORRUPTED;
2271 err = ext4_ext_get_access(handle, inode, path);
2275 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2276 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2277 len *= sizeof(struct ext4_extent_idx);
2278 memmove(path->p_idx, path->p_idx + 1, len);
2281 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2282 err = ext4_ext_dirty(handle, inode, path);
2285 ext_debug(inode, "index is empty, remove it, free block %llu\n", leaf);
2286 trace_ext4_ext_rm_idx(inode, leaf);
2288 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2289 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2291 while (--depth >= 0) {
2292 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2295 err = ext4_ext_get_access(handle, inode, path);
2298 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2299 err = ext4_ext_dirty(handle, inode, path);
2307 * ext4_ext_calc_credits_for_single_extent:
2308 * This routine returns max. credits that needed to insert an extent
2309 * to the extent tree.
2310 * When pass the actual path, the caller should calculate credits
2313 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2314 struct ext4_ext_path *path)
2317 int depth = ext_depth(inode);
2320 /* probably there is space in leaf? */
2321 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2322 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2325 * There are some space in the leaf tree, no
2326 * need to account for leaf block credit
2328 * bitmaps and block group descriptor blocks
2329 * and other metadata blocks still need to be
2332 /* 1 bitmap, 1 block group descriptor */
2333 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2338 return ext4_chunk_trans_blocks(inode, nrblocks);
2342 * How many index/leaf blocks need to change/allocate to add @extents extents?
2344 * If we add a single extent, then in the worse case, each tree level
2345 * index/leaf need to be changed in case of the tree split.
2347 * If more extents are inserted, they could cause the whole tree split more
2348 * than once, but this is really rare.
2350 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2355 /* If we are converting the inline data, only one is needed here. */
2356 if (ext4_has_inline_data(inode))
2359 depth = ext_depth(inode);
2369 static inline int get_default_free_blocks_flags(struct inode *inode)
2371 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2372 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2373 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2374 else if (ext4_should_journal_data(inode))
2375 return EXT4_FREE_BLOCKS_FORGET;
2380 * ext4_rereserve_cluster - increment the reserved cluster count when
2381 * freeing a cluster with a pending reservation
2383 * @inode - file containing the cluster
2384 * @lblk - logical block in cluster to be reserved
2386 * Increments the reserved cluster count and adjusts quota in a bigalloc
2387 * file system when freeing a partial cluster containing at least one
2388 * delayed and unwritten block. A partial cluster meeting that
2389 * requirement will have a pending reservation. If so, the
2390 * RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
2391 * defer reserved and allocated space accounting to a subsequent call
2394 static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
2396 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2397 struct ext4_inode_info *ei = EXT4_I(inode);
2399 dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
2401 spin_lock(&ei->i_block_reservation_lock);
2402 ei->i_reserved_data_blocks++;
2403 percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
2404 spin_unlock(&ei->i_block_reservation_lock);
2406 percpu_counter_add(&sbi->s_freeclusters_counter, 1);
2407 ext4_remove_pending(inode, lblk);
2410 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2411 struct ext4_extent *ex,
2412 struct partial_cluster *partial,
2413 ext4_lblk_t from, ext4_lblk_t to)
2415 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2416 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2417 ext4_fsblk_t last_pblk, pblk;
2421 /* only extent tail removal is allowed */
2422 if (from < le32_to_cpu(ex->ee_block) ||
2423 to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
2424 ext4_error(sbi->s_sb,
2425 "strange request: removal(2) %u-%u from %u:%u",
2426 from, to, le32_to_cpu(ex->ee_block), ee_len);
2430 #ifdef EXTENTS_STATS
2431 spin_lock(&sbi->s_ext_stats_lock);
2432 sbi->s_ext_blocks += ee_len;
2433 sbi->s_ext_extents++;
2434 if (ee_len < sbi->s_ext_min)
2435 sbi->s_ext_min = ee_len;
2436 if (ee_len > sbi->s_ext_max)
2437 sbi->s_ext_max = ee_len;
2438 if (ext_depth(inode) > sbi->s_depth_max)
2439 sbi->s_depth_max = ext_depth(inode);
2440 spin_unlock(&sbi->s_ext_stats_lock);
2443 trace_ext4_remove_blocks(inode, ex, from, to, partial);
2446 * if we have a partial cluster, and it's different from the
2447 * cluster of the last block in the extent, we free it
2449 last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
2451 if (partial->state != initial &&
2452 partial->pclu != EXT4_B2C(sbi, last_pblk)) {
2453 if (partial->state == tofree) {
2454 flags = get_default_free_blocks_flags(inode);
2455 if (ext4_is_pending(inode, partial->lblk))
2456 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2457 ext4_free_blocks(handle, inode, NULL,
2458 EXT4_C2B(sbi, partial->pclu),
2459 sbi->s_cluster_ratio, flags);
2460 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2461 ext4_rereserve_cluster(inode, partial->lblk);
2463 partial->state = initial;
2466 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2467 pblk = ext4_ext_pblock(ex) + ee_len - num;
2470 * We free the partial cluster at the end of the extent (if any),
2471 * unless the cluster is used by another extent (partial_cluster
2472 * state is nofree). If a partial cluster exists here, it must be
2473 * shared with the last block in the extent.
2475 flags = get_default_free_blocks_flags(inode);
2477 /* partial, left end cluster aligned, right end unaligned */
2478 if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
2479 (EXT4_LBLK_CMASK(sbi, to) >= from) &&
2480 (partial->state != nofree)) {
2481 if (ext4_is_pending(inode, to))
2482 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2483 ext4_free_blocks(handle, inode, NULL,
2484 EXT4_PBLK_CMASK(sbi, last_pblk),
2485 sbi->s_cluster_ratio, flags);
2486 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2487 ext4_rereserve_cluster(inode, to);
2488 partial->state = initial;
2489 flags = get_default_free_blocks_flags(inode);
2492 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2495 * For bigalloc file systems, we never free a partial cluster
2496 * at the beginning of the extent. Instead, we check to see if we
2497 * need to free it on a subsequent call to ext4_remove_blocks,
2498 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2500 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2501 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2503 /* reset the partial cluster if we've freed past it */
2504 if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
2505 partial->state = initial;
2508 * If we've freed the entire extent but the beginning is not left
2509 * cluster aligned and is not marked as ineligible for freeing we
2510 * record the partial cluster at the beginning of the extent. It
2511 * wasn't freed by the preceding ext4_free_blocks() call, and we
2512 * need to look farther to the left to determine if it's to be freed
2513 * (not shared with another extent). Else, reset the partial
2514 * cluster - we're either done freeing or the beginning of the
2515 * extent is left cluster aligned.
2517 if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
2518 if (partial->state == initial) {
2519 partial->pclu = EXT4_B2C(sbi, pblk);
2520 partial->lblk = from;
2521 partial->state = tofree;
2524 partial->state = initial;
2531 * ext4_ext_rm_leaf() Removes the extents associated with the
2532 * blocks appearing between "start" and "end". Both "start"
2533 * and "end" must appear in the same extent or EIO is returned.
2535 * @handle: The journal handle
2536 * @inode: The files inode
2537 * @path: The path to the leaf
2538 * @partial_cluster: The cluster which we'll have to free if all extents
2539 * has been released from it. However, if this value is
2540 * negative, it's a cluster just to the right of the
2541 * punched region and it must not be freed.
2542 * @start: The first block to remove
2543 * @end: The last block to remove
2546 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2547 struct ext4_ext_path *path,
2548 struct partial_cluster *partial,
2549 ext4_lblk_t start, ext4_lblk_t end)
2551 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2552 int err = 0, correct_index = 0;
2553 int depth = ext_depth(inode), credits, revoke_credits;
2554 struct ext4_extent_header *eh;
2557 ext4_lblk_t ex_ee_block;
2558 unsigned short ex_ee_len;
2559 unsigned unwritten = 0;
2560 struct ext4_extent *ex;
2563 /* the header must be checked already in ext4_ext_remove_space() */
2564 ext_debug(inode, "truncate since %u in leaf to %u\n", start, end);
2565 if (!path[depth].p_hdr)
2566 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2567 eh = path[depth].p_hdr;
2568 if (unlikely(path[depth].p_hdr == NULL)) {
2569 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2570 return -EFSCORRUPTED;
2572 /* find where to start removing */
2573 ex = path[depth].p_ext;
2575 ex = EXT_LAST_EXTENT(eh);
2577 ex_ee_block = le32_to_cpu(ex->ee_block);
2578 ex_ee_len = ext4_ext_get_actual_len(ex);
2580 trace_ext4_ext_rm_leaf(inode, start, ex, partial);
2582 while (ex >= EXT_FIRST_EXTENT(eh) &&
2583 ex_ee_block + ex_ee_len > start) {
2585 if (ext4_ext_is_unwritten(ex))
2590 ext_debug(inode, "remove ext %u:[%d]%d\n", ex_ee_block,
2591 unwritten, ex_ee_len);
2592 path[depth].p_ext = ex;
2594 a = ex_ee_block > start ? ex_ee_block : start;
2595 b = ex_ee_block+ex_ee_len - 1 < end ?
2596 ex_ee_block+ex_ee_len - 1 : end;
2598 ext_debug(inode, " border %u:%u\n", a, b);
2600 /* If this extent is beyond the end of the hole, skip it */
2601 if (end < ex_ee_block) {
2603 * We're going to skip this extent and move to another,
2604 * so note that its first cluster is in use to avoid
2605 * freeing it when removing blocks. Eventually, the
2606 * right edge of the truncated/punched region will
2607 * be just to the left.
2609 if (sbi->s_cluster_ratio > 1) {
2610 pblk = ext4_ext_pblock(ex);
2611 partial->pclu = EXT4_B2C(sbi, pblk);
2612 partial->state = nofree;
2615 ex_ee_block = le32_to_cpu(ex->ee_block);
2616 ex_ee_len = ext4_ext_get_actual_len(ex);
2618 } else if (b != ex_ee_block + ex_ee_len - 1) {
2619 EXT4_ERROR_INODE(inode,
2620 "can not handle truncate %u:%u "
2622 start, end, ex_ee_block,
2623 ex_ee_block + ex_ee_len - 1);
2624 err = -EFSCORRUPTED;
2626 } else if (a != ex_ee_block) {
2627 /* remove tail of the extent */
2628 num = a - ex_ee_block;
2630 /* remove whole extent: excellent! */
2634 * 3 for leaf, sb, and inode plus 2 (bmap and group
2635 * descriptor) for each block group; assume two block
2636 * groups plus ex_ee_len/blocks_per_block_group for
2639 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2640 if (ex == EXT_FIRST_EXTENT(eh)) {
2642 credits += (ext_depth(inode)) + 1;
2644 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2646 * We may end up freeing some index blocks and data from the
2647 * punched range. Note that partial clusters are accounted for
2648 * by ext4_free_data_revoke_credits().
2651 ext4_free_metadata_revoke_credits(inode->i_sb,
2653 ext4_free_data_revoke_credits(inode, b - a + 1);
2655 err = ext4_datasem_ensure_credits(handle, inode, credits,
2656 credits, revoke_credits);
2663 err = ext4_ext_get_access(handle, inode, path + depth);
2667 err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
2672 /* this extent is removed; mark slot entirely unused */
2673 ext4_ext_store_pblock(ex, 0);
2675 ex->ee_len = cpu_to_le16(num);
2677 * Do not mark unwritten if all the blocks in the
2678 * extent have been removed.
2680 if (unwritten && num)
2681 ext4_ext_mark_unwritten(ex);
2683 * If the extent was completely released,
2684 * we need to remove it from the leaf
2687 if (end != EXT_MAX_BLOCKS - 1) {
2689 * For hole punching, we need to scoot all the
2690 * extents up when an extent is removed so that
2691 * we dont have blank extents in the middle
2693 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2694 sizeof(struct ext4_extent));
2696 /* Now get rid of the one at the end */
2697 memset(EXT_LAST_EXTENT(eh), 0,
2698 sizeof(struct ext4_extent));
2700 le16_add_cpu(&eh->eh_entries, -1);
2703 err = ext4_ext_dirty(handle, inode, path + depth);
2707 ext_debug(inode, "new extent: %u:%u:%llu\n", ex_ee_block, num,
2708 ext4_ext_pblock(ex));
2710 ex_ee_block = le32_to_cpu(ex->ee_block);
2711 ex_ee_len = ext4_ext_get_actual_len(ex);
2714 if (correct_index && eh->eh_entries)
2715 err = ext4_ext_correct_indexes(handle, inode, path);
2718 * If there's a partial cluster and at least one extent remains in
2719 * the leaf, free the partial cluster if it isn't shared with the
2720 * current extent. If it is shared with the current extent
2721 * we reset the partial cluster because we've reached the start of the
2722 * truncated/punched region and we're done removing blocks.
2724 if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
2725 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2726 if (partial->pclu != EXT4_B2C(sbi, pblk)) {
2727 int flags = get_default_free_blocks_flags(inode);
2729 if (ext4_is_pending(inode, partial->lblk))
2730 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2731 ext4_free_blocks(handle, inode, NULL,
2732 EXT4_C2B(sbi, partial->pclu),
2733 sbi->s_cluster_ratio, flags);
2734 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2735 ext4_rereserve_cluster(inode, partial->lblk);
2737 partial->state = initial;
2740 /* if this leaf is free, then we should
2741 * remove it from index block above */
2742 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2743 err = ext4_ext_rm_idx(handle, inode, path, depth);
2750 * ext4_ext_more_to_rm:
2751 * returns 1 if current index has to be freed (even partial)
2754 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2756 BUG_ON(path->p_idx == NULL);
2758 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2762 * if truncate on deeper level happened, it wasn't partial,
2763 * so we have to consider current index for truncation
2765 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2770 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2773 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2774 int depth = ext_depth(inode);
2775 struct ext4_ext_path *path = NULL;
2776 struct partial_cluster partial;
2782 partial.state = initial;
2784 ext_debug(inode, "truncate since %u to %u\n", start, end);
2786 /* probably first extent we're gonna free will be last in block */
2787 handle = ext4_journal_start_with_revoke(inode, EXT4_HT_TRUNCATE,
2789 ext4_free_metadata_revoke_credits(inode->i_sb, depth));
2791 return PTR_ERR(handle);
2794 trace_ext4_ext_remove_space(inode, start, end, depth);
2797 * Check if we are removing extents inside the extent tree. If that
2798 * is the case, we are going to punch a hole inside the extent tree
2799 * so we have to check whether we need to split the extent covering
2800 * the last block to remove so we can easily remove the part of it
2801 * in ext4_ext_rm_leaf().
2803 if (end < EXT_MAX_BLOCKS - 1) {
2804 struct ext4_extent *ex;
2805 ext4_lblk_t ee_block, ex_end, lblk;
2808 /* find extent for or closest extent to this block */
2809 path = ext4_find_extent(inode, end, NULL,
2810 EXT4_EX_NOCACHE | EXT4_EX_NOFAIL);
2812 ext4_journal_stop(handle);
2813 return PTR_ERR(path);
2815 depth = ext_depth(inode);
2816 /* Leaf not may not exist only if inode has no blocks at all */
2817 ex = path[depth].p_ext;
2820 EXT4_ERROR_INODE(inode,
2821 "path[%d].p_hdr == NULL",
2823 err = -EFSCORRUPTED;
2828 ee_block = le32_to_cpu(ex->ee_block);
2829 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2832 * See if the last block is inside the extent, if so split
2833 * the extent at 'end' block so we can easily remove the
2834 * tail of the first part of the split extent in
2835 * ext4_ext_rm_leaf().
2837 if (end >= ee_block && end < ex_end) {
2840 * If we're going to split the extent, note that
2841 * the cluster containing the block after 'end' is
2842 * in use to avoid freeing it when removing blocks.
2844 if (sbi->s_cluster_ratio > 1) {
2845 pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
2846 partial.pclu = EXT4_B2C(sbi, pblk);
2847 partial.state = nofree;
2851 * Split the extent in two so that 'end' is the last
2852 * block in the first new extent. Also we should not
2853 * fail removing space due to ENOSPC so try to use
2854 * reserved block if that happens.
2856 err = ext4_force_split_extent_at(handle, inode, &path,
2861 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
2862 partial.state == initial) {
2864 * If we're punching, there's an extent to the right.
2865 * If the partial cluster hasn't been set, set it to
2866 * that extent's first cluster and its state to nofree
2867 * so it won't be freed should it contain blocks to be
2868 * removed. If it's already set (tofree/nofree), we're
2869 * retrying and keep the original partial cluster info
2870 * so a cluster marked tofree as a result of earlier
2871 * extent removal is not lost.
2874 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2879 partial.pclu = EXT4_B2C(sbi, pblk);
2880 partial.state = nofree;
2885 * We start scanning from right side, freeing all the blocks
2886 * after i_size and walking into the tree depth-wise.
2888 depth = ext_depth(inode);
2893 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2895 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
2896 GFP_NOFS | __GFP_NOFAIL);
2898 ext4_journal_stop(handle);
2901 path[0].p_maxdepth = path[0].p_depth = depth;
2902 path[0].p_hdr = ext_inode_hdr(inode);
2905 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2906 err = -EFSCORRUPTED;
2912 while (i >= 0 && err == 0) {
2914 /* this is leaf block */
2915 err = ext4_ext_rm_leaf(handle, inode, path,
2916 &partial, start, end);
2917 /* root level has p_bh == NULL, brelse() eats this */
2918 brelse(path[i].p_bh);
2919 path[i].p_bh = NULL;
2924 /* this is index block */
2925 if (!path[i].p_hdr) {
2926 ext_debug(inode, "initialize header\n");
2927 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2930 if (!path[i].p_idx) {
2931 /* this level hasn't been touched yet */
2932 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2933 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2934 ext_debug(inode, "init index ptr: hdr 0x%p, num %d\n",
2936 le16_to_cpu(path[i].p_hdr->eh_entries));
2938 /* we were already here, see at next index */
2942 ext_debug(inode, "level %d - index, first 0x%p, cur 0x%p\n",
2943 i, EXT_FIRST_INDEX(path[i].p_hdr),
2945 if (ext4_ext_more_to_rm(path + i)) {
2946 struct buffer_head *bh;
2947 /* go to the next level */
2948 ext_debug(inode, "move to level %d (block %llu)\n",
2949 i + 1, ext4_idx_pblock(path[i].p_idx));
2950 memset(path + i + 1, 0, sizeof(*path));
2951 bh = read_extent_tree_block(inode,
2952 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
2955 /* should we reset i_size? */
2959 /* Yield here to deal with large extent trees.
2960 * Should be a no-op if we did IO above. */
2962 if (WARN_ON(i + 1 > depth)) {
2963 err = -EFSCORRUPTED;
2966 path[i + 1].p_bh = bh;
2968 /* save actual number of indexes since this
2969 * number is changed at the next iteration */
2970 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2973 /* we finished processing this index, go up */
2974 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2975 /* index is empty, remove it;
2976 * handle must be already prepared by the
2977 * truncatei_leaf() */
2978 err = ext4_ext_rm_idx(handle, inode, path, i);
2980 /* root level has p_bh == NULL, brelse() eats this */
2981 brelse(path[i].p_bh);
2982 path[i].p_bh = NULL;
2984 ext_debug(inode, "return to level %d\n", i);
2988 trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
2989 path->p_hdr->eh_entries);
2992 * if there's a partial cluster and we have removed the first extent
2993 * in the file, then we also free the partial cluster, if any
2995 if (partial.state == tofree && err == 0) {
2996 int flags = get_default_free_blocks_flags(inode);
2998 if (ext4_is_pending(inode, partial.lblk))
2999 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
3000 ext4_free_blocks(handle, inode, NULL,
3001 EXT4_C2B(sbi, partial.pclu),
3002 sbi->s_cluster_ratio, flags);
3003 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
3004 ext4_rereserve_cluster(inode, partial.lblk);
3005 partial.state = initial;
3008 /* TODO: flexible tree reduction should be here */
3009 if (path->p_hdr->eh_entries == 0) {
3011 * truncate to zero freed all the tree,
3012 * so we need to correct eh_depth
3014 err = ext4_ext_get_access(handle, inode, path);
3016 ext_inode_hdr(inode)->eh_depth = 0;
3017 ext_inode_hdr(inode)->eh_max =
3018 cpu_to_le16(ext4_ext_space_root(inode, 0));
3019 err = ext4_ext_dirty(handle, inode, path);
3023 ext4_ext_drop_refs(path);
3028 ext4_journal_stop(handle);
3034 * called at mount time
3036 void ext4_ext_init(struct super_block *sb)
3039 * possible initialization would be here
3042 if (ext4_has_feature_extents(sb)) {
3043 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3044 printk(KERN_INFO "EXT4-fs: file extents enabled"
3045 #ifdef AGGRESSIVE_TEST
3046 ", aggressive tests"
3048 #ifdef CHECK_BINSEARCH
3051 #ifdef EXTENTS_STATS
3056 #ifdef EXTENTS_STATS
3057 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3058 EXT4_SB(sb)->s_ext_min = 1 << 30;
3059 EXT4_SB(sb)->s_ext_max = 0;
3065 * called at umount time
3067 void ext4_ext_release(struct super_block *sb)
3069 if (!ext4_has_feature_extents(sb))
3072 #ifdef EXTENTS_STATS
3073 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3074 struct ext4_sb_info *sbi = EXT4_SB(sb);
3075 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3076 sbi->s_ext_blocks, sbi->s_ext_extents,
3077 sbi->s_ext_blocks / sbi->s_ext_extents);
3078 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3079 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3084 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3086 ext4_lblk_t ee_block;
3087 ext4_fsblk_t ee_pblock;
3088 unsigned int ee_len;
3090 ee_block = le32_to_cpu(ex->ee_block);
3091 ee_len = ext4_ext_get_actual_len(ex);
3092 ee_pblock = ext4_ext_pblock(ex);
3097 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3098 EXTENT_STATUS_WRITTEN);
3101 /* FIXME!! we need to try to merge to left or right after zero-out */
3102 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3104 ext4_fsblk_t ee_pblock;
3105 unsigned int ee_len;
3107 ee_len = ext4_ext_get_actual_len(ex);
3108 ee_pblock = ext4_ext_pblock(ex);
3109 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3114 * ext4_split_extent_at() splits an extent at given block.
3116 * @handle: the journal handle
3117 * @inode: the file inode
3118 * @path: the path to the extent
3119 * @split: the logical block where the extent is splitted.
3120 * @split_flags: indicates if the extent could be zeroout if split fails, and
3121 * the states(init or unwritten) of new extents.
3122 * @flags: flags used to insert new extent to extent tree.
3125 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3126 * of which are determined by split_flag.
3128 * There are two cases:
3129 * a> the extent are splitted into two extent.
3130 * b> split is not needed, and just mark the extent.
3132 * return 0 on success.
3134 static int ext4_split_extent_at(handle_t *handle,
3135 struct inode *inode,
3136 struct ext4_ext_path **ppath,
3141 struct ext4_ext_path *path = *ppath;
3142 ext4_fsblk_t newblock;
3143 ext4_lblk_t ee_block;
3144 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3145 struct ext4_extent *ex2 = NULL;
3146 unsigned int ee_len, depth;
3149 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3150 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3152 ext_debug(inode, "logical block %llu\n", (unsigned long long)split);
3154 ext4_ext_show_leaf(inode, path);
3156 depth = ext_depth(inode);
3157 ex = path[depth].p_ext;
3158 ee_block = le32_to_cpu(ex->ee_block);
3159 ee_len = ext4_ext_get_actual_len(ex);
3160 newblock = split - ee_block + ext4_ext_pblock(ex);
3162 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3163 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3164 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3165 EXT4_EXT_MARK_UNWRIT1 |
3166 EXT4_EXT_MARK_UNWRIT2));
3168 err = ext4_ext_get_access(handle, inode, path + depth);
3172 if (split == ee_block) {
3174 * case b: block @split is the block that the extent begins with
3175 * then we just change the state of the extent, and splitting
3178 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3179 ext4_ext_mark_unwritten(ex);
3181 ext4_ext_mark_initialized(ex);
3183 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3184 ext4_ext_try_to_merge(handle, inode, path, ex);
3186 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3191 memcpy(&orig_ex, ex, sizeof(orig_ex));
3192 ex->ee_len = cpu_to_le16(split - ee_block);
3193 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3194 ext4_ext_mark_unwritten(ex);
3197 * path may lead to new leaf, not to original leaf any more
3198 * after ext4_ext_insert_extent() returns,
3200 err = ext4_ext_dirty(handle, inode, path + depth);
3202 goto fix_extent_len;
3205 ex2->ee_block = cpu_to_le32(split);
3206 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3207 ext4_ext_store_pblock(ex2, newblock);
3208 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3209 ext4_ext_mark_unwritten(ex2);
3211 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3212 if (err != -ENOSPC && err != -EDQUOT)
3215 if (EXT4_EXT_MAY_ZEROOUT & split_flag) {
3216 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3217 if (split_flag & EXT4_EXT_DATA_VALID1) {
3218 err = ext4_ext_zeroout(inode, ex2);
3219 zero_ex.ee_block = ex2->ee_block;
3220 zero_ex.ee_len = cpu_to_le16(
3221 ext4_ext_get_actual_len(ex2));
3222 ext4_ext_store_pblock(&zero_ex,
3223 ext4_ext_pblock(ex2));
3225 err = ext4_ext_zeroout(inode, ex);
3226 zero_ex.ee_block = ex->ee_block;
3227 zero_ex.ee_len = cpu_to_le16(
3228 ext4_ext_get_actual_len(ex));
3229 ext4_ext_store_pblock(&zero_ex,
3230 ext4_ext_pblock(ex));
3233 err = ext4_ext_zeroout(inode, &orig_ex);
3234 zero_ex.ee_block = orig_ex.ee_block;
3235 zero_ex.ee_len = cpu_to_le16(
3236 ext4_ext_get_actual_len(&orig_ex));
3237 ext4_ext_store_pblock(&zero_ex,
3238 ext4_ext_pblock(&orig_ex));
3242 /* update the extent length and mark as initialized */
3243 ex->ee_len = cpu_to_le16(ee_len);
3244 ext4_ext_try_to_merge(handle, inode, path, ex);
3245 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3247 /* update extent status tree */
3248 err = ext4_zeroout_es(inode, &zero_ex);
3249 /* If we failed at this point, we don't know in which
3250 * state the extent tree exactly is so don't try to fix
3251 * length of the original extent as it may do even more
3259 ex->ee_len = orig_ex.ee_len;
3261 * Ignore ext4_ext_dirty return value since we are already in error path
3262 * and err is a non-zero error code.
3264 ext4_ext_dirty(handle, inode, path + path->p_depth);
3267 ext4_ext_show_leaf(inode, path);
3272 * ext4_split_extents() splits an extent and mark extent which is covered
3273 * by @map as split_flags indicates
3275 * It may result in splitting the extent into multiple extents (up to three)
3276 * There are three possibilities:
3277 * a> There is no split required
3278 * b> Splits in two extents: Split is happening at either end of the extent
3279 * c> Splits in three extents: Somone is splitting in middle of the extent
3282 static int ext4_split_extent(handle_t *handle,
3283 struct inode *inode,
3284 struct ext4_ext_path **ppath,
3285 struct ext4_map_blocks *map,
3289 struct ext4_ext_path *path = *ppath;
3290 ext4_lblk_t ee_block;
3291 struct ext4_extent *ex;
3292 unsigned int ee_len, depth;
3295 int split_flag1, flags1;
3296 int allocated = map->m_len;
3298 depth = ext_depth(inode);
3299 ex = path[depth].p_ext;
3300 ee_block = le32_to_cpu(ex->ee_block);
3301 ee_len = ext4_ext_get_actual_len(ex);
3302 unwritten = ext4_ext_is_unwritten(ex);
3304 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3305 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3306 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3308 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3309 EXT4_EXT_MARK_UNWRIT2;
3310 if (split_flag & EXT4_EXT_DATA_VALID2)
3311 split_flag1 |= EXT4_EXT_DATA_VALID1;
3312 err = ext4_split_extent_at(handle, inode, ppath,
3313 map->m_lblk + map->m_len, split_flag1, flags1);
3317 allocated = ee_len - (map->m_lblk - ee_block);
3320 * Update path is required because previous ext4_split_extent_at() may
3321 * result in split of original leaf or extent zeroout.
3323 path = ext4_find_extent(inode, map->m_lblk, ppath, flags);
3325 return PTR_ERR(path);
3326 depth = ext_depth(inode);
3327 ex = path[depth].p_ext;
3329 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3330 (unsigned long) map->m_lblk);
3331 return -EFSCORRUPTED;
3333 unwritten = ext4_ext_is_unwritten(ex);
3336 if (map->m_lblk >= ee_block) {
3337 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3339 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3340 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3341 EXT4_EXT_MARK_UNWRIT2);
3343 err = ext4_split_extent_at(handle, inode, ppath,
3344 map->m_lblk, split_flag1, flags);
3349 ext4_ext_show_leaf(inode, path);
3351 return err ? err : allocated;
3355 * This function is called by ext4_ext_map_blocks() if someone tries to write
3356 * to an unwritten extent. It may result in splitting the unwritten
3357 * extent into multiple extents (up to three - one initialized and two
3359 * There are three possibilities:
3360 * a> There is no split required: Entire extent should be initialized
3361 * b> Splits in two extents: Write is happening at either end of the extent
3362 * c> Splits in three extents: Somone is writing in middle of the extent
3365 * - The extent pointed to by 'path' is unwritten.
3366 * - The extent pointed to by 'path' contains a superset
3367 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3369 * Post-conditions on success:
3370 * - the returned value is the number of blocks beyond map->l_lblk
3371 * that are allocated and initialized.
3372 * It is guaranteed to be >= map->m_len.
3374 static int ext4_ext_convert_to_initialized(handle_t *handle,
3375 struct inode *inode,
3376 struct ext4_map_blocks *map,
3377 struct ext4_ext_path **ppath,
3380 struct ext4_ext_path *path = *ppath;
3381 struct ext4_sb_info *sbi;
3382 struct ext4_extent_header *eh;
3383 struct ext4_map_blocks split_map;
3384 struct ext4_extent zero_ex1, zero_ex2;
3385 struct ext4_extent *ex, *abut_ex;
3386 ext4_lblk_t ee_block, eof_block;
3387 unsigned int ee_len, depth, map_len = map->m_len;
3388 int allocated = 0, max_zeroout = 0;
3390 int split_flag = EXT4_EXT_DATA_VALID2;
3392 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3393 (unsigned long long)map->m_lblk, map_len);
3395 sbi = EXT4_SB(inode->i_sb);
3396 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3397 >> inode->i_sb->s_blocksize_bits;
3398 if (eof_block < map->m_lblk + map_len)
3399 eof_block = map->m_lblk + map_len;
3401 depth = ext_depth(inode);
3402 eh = path[depth].p_hdr;
3403 ex = path[depth].p_ext;
3404 ee_block = le32_to_cpu(ex->ee_block);
3405 ee_len = ext4_ext_get_actual_len(ex);
3406 zero_ex1.ee_len = 0;
3407 zero_ex2.ee_len = 0;
3409 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3411 /* Pre-conditions */
3412 BUG_ON(!ext4_ext_is_unwritten(ex));
3413 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3416 * Attempt to transfer newly initialized blocks from the currently
3417 * unwritten extent to its neighbor. This is much cheaper
3418 * than an insertion followed by a merge as those involve costly
3419 * memmove() calls. Transferring to the left is the common case in
3420 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3421 * followed by append writes.
3423 * Limitations of the current logic:
3424 * - L1: we do not deal with writes covering the whole extent.
3425 * This would require removing the extent if the transfer
3427 * - L2: we only attempt to merge with an extent stored in the
3428 * same extent tree node.
3430 if ((map->m_lblk == ee_block) &&
3431 /* See if we can merge left */
3432 (map_len < ee_len) && /*L1*/
3433 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3434 ext4_lblk_t prev_lblk;
3435 ext4_fsblk_t prev_pblk, ee_pblk;
3436 unsigned int prev_len;
3439 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3440 prev_len = ext4_ext_get_actual_len(abut_ex);
3441 prev_pblk = ext4_ext_pblock(abut_ex);
3442 ee_pblk = ext4_ext_pblock(ex);
3445 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3446 * upon those conditions:
3447 * - C1: abut_ex is initialized,
3448 * - C2: abut_ex is logically abutting ex,
3449 * - C3: abut_ex is physically abutting ex,
3450 * - C4: abut_ex can receive the additional blocks without
3451 * overflowing the (initialized) length limit.
3453 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3454 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3455 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3456 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3457 err = ext4_ext_get_access(handle, inode, path + depth);
3461 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3464 /* Shift the start of ex by 'map_len' blocks */
3465 ex->ee_block = cpu_to_le32(ee_block + map_len);
3466 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3467 ex->ee_len = cpu_to_le16(ee_len - map_len);
3468 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3470 /* Extend abut_ex by 'map_len' blocks */
3471 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3473 /* Result: number of initialized blocks past m_lblk */
3474 allocated = map_len;
3476 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3477 (map_len < ee_len) && /*L1*/
3478 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3479 /* See if we can merge right */
3480 ext4_lblk_t next_lblk;
3481 ext4_fsblk_t next_pblk, ee_pblk;
3482 unsigned int next_len;
3485 next_lblk = le32_to_cpu(abut_ex->ee_block);
3486 next_len = ext4_ext_get_actual_len(abut_ex);
3487 next_pblk = ext4_ext_pblock(abut_ex);
3488 ee_pblk = ext4_ext_pblock(ex);
3491 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3492 * upon those conditions:
3493 * - C1: abut_ex is initialized,
3494 * - C2: abut_ex is logically abutting ex,
3495 * - C3: abut_ex is physically abutting ex,
3496 * - C4: abut_ex can receive the additional blocks without
3497 * overflowing the (initialized) length limit.
3499 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3500 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3501 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3502 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3503 err = ext4_ext_get_access(handle, inode, path + depth);
3507 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3510 /* Shift the start of abut_ex by 'map_len' blocks */
3511 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3512 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3513 ex->ee_len = cpu_to_le16(ee_len - map_len);
3514 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3516 /* Extend abut_ex by 'map_len' blocks */
3517 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3519 /* Result: number of initialized blocks past m_lblk */
3520 allocated = map_len;
3524 /* Mark the block containing both extents as dirty */
3525 err = ext4_ext_dirty(handle, inode, path + depth);
3527 /* Update path to point to the right extent */
3528 path[depth].p_ext = abut_ex;
3531 allocated = ee_len - (map->m_lblk - ee_block);
3533 WARN_ON(map->m_lblk < ee_block);
3535 * It is safe to convert extent to initialized via explicit
3536 * zeroout only if extent is fully inside i_size or new_size.
3538 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3540 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3541 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3542 (inode->i_sb->s_blocksize_bits - 10);
3546 * 1. split the extent into three extents.
3547 * 2. split the extent into two extents, zeroout the head of the first
3549 * 3. split the extent into two extents, zeroout the tail of the second
3551 * 4. split the extent into two extents with out zeroout.
3552 * 5. no splitting needed, just possibly zeroout the head and / or the
3553 * tail of the extent.
3555 split_map.m_lblk = map->m_lblk;
3556 split_map.m_len = map->m_len;
3558 if (max_zeroout && (allocated > split_map.m_len)) {
3559 if (allocated <= max_zeroout) {
3562 cpu_to_le32(split_map.m_lblk +
3565 cpu_to_le16(allocated - split_map.m_len);
3566 ext4_ext_store_pblock(&zero_ex1,
3567 ext4_ext_pblock(ex) + split_map.m_lblk +
3568 split_map.m_len - ee_block);
3569 err = ext4_ext_zeroout(inode, &zero_ex1);
3572 split_map.m_len = allocated;
3574 if (split_map.m_lblk - ee_block + split_map.m_len <
3577 if (split_map.m_lblk != ee_block) {
3578 zero_ex2.ee_block = ex->ee_block;
3579 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3581 ext4_ext_store_pblock(&zero_ex2,
3582 ext4_ext_pblock(ex));
3583 err = ext4_ext_zeroout(inode, &zero_ex2);
3588 split_map.m_len += split_map.m_lblk - ee_block;
3589 split_map.m_lblk = ee_block;
3590 allocated = map->m_len;
3594 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3599 /* If we have gotten a failure, don't zero out status tree */
3601 err = ext4_zeroout_es(inode, &zero_ex1);
3603 err = ext4_zeroout_es(inode, &zero_ex2);
3605 return err ? err : allocated;
3609 * This function is called by ext4_ext_map_blocks() from
3610 * ext4_get_blocks_dio_write() when DIO to write
3611 * to an unwritten extent.
3613 * Writing to an unwritten extent may result in splitting the unwritten
3614 * extent into multiple initialized/unwritten extents (up to three)
3615 * There are three possibilities:
3616 * a> There is no split required: Entire extent should be unwritten
3617 * b> Splits in two extents: Write is happening at either end of the extent
3618 * c> Splits in three extents: Somone is writing in middle of the extent
3620 * This works the same way in the case of initialized -> unwritten conversion.
3622 * One of more index blocks maybe needed if the extent tree grow after
3623 * the unwritten extent split. To prevent ENOSPC occur at the IO
3624 * complete, we need to split the unwritten extent before DIO submit
3625 * the IO. The unwritten extent called at this time will be split
3626 * into three unwritten extent(at most). After IO complete, the part
3627 * being filled will be convert to initialized by the end_io callback function
3628 * via ext4_convert_unwritten_extents().
3630 * Returns the size of unwritten extent to be written on success.
3632 static int ext4_split_convert_extents(handle_t *handle,
3633 struct inode *inode,
3634 struct ext4_map_blocks *map,
3635 struct ext4_ext_path **ppath,
3638 struct ext4_ext_path *path = *ppath;
3639 ext4_lblk_t eof_block;
3640 ext4_lblk_t ee_block;
3641 struct ext4_extent *ex;
3642 unsigned int ee_len;
3643 int split_flag = 0, depth;
3645 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3646 (unsigned long long)map->m_lblk, map->m_len);
3648 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3649 >> inode->i_sb->s_blocksize_bits;
3650 if (eof_block < map->m_lblk + map->m_len)
3651 eof_block = map->m_lblk + map->m_len;
3653 * It is safe to convert extent to initialized via explicit
3654 * zeroout only if extent is fully inside i_size or new_size.
3656 depth = ext_depth(inode);
3657 ex = path[depth].p_ext;
3658 ee_block = le32_to_cpu(ex->ee_block);
3659 ee_len = ext4_ext_get_actual_len(ex);
3661 /* Convert to unwritten */
3662 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3663 split_flag |= EXT4_EXT_DATA_VALID1;
3664 /* Convert to initialized */
3665 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3666 split_flag |= ee_block + ee_len <= eof_block ?
3667 EXT4_EXT_MAY_ZEROOUT : 0;
3668 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3670 flags |= EXT4_GET_BLOCKS_PRE_IO;
3671 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3674 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3675 struct inode *inode,
3676 struct ext4_map_blocks *map,
3677 struct ext4_ext_path **ppath)
3679 struct ext4_ext_path *path = *ppath;
3680 struct ext4_extent *ex;
3681 ext4_lblk_t ee_block;
3682 unsigned int ee_len;
3686 depth = ext_depth(inode);
3687 ex = path[depth].p_ext;
3688 ee_block = le32_to_cpu(ex->ee_block);
3689 ee_len = ext4_ext_get_actual_len(ex);
3691 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3692 (unsigned long long)ee_block, ee_len);
3694 /* If extent is larger than requested it is a clear sign that we still
3695 * have some extent state machine issues left. So extent_split is still
3697 * TODO: Once all related issues will be fixed this situation should be
3700 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3701 #ifdef CONFIG_EXT4_DEBUG
3702 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3703 " len %u; IO logical block %llu, len %u",
3704 inode->i_ino, (unsigned long long)ee_block, ee_len,
3705 (unsigned long long)map->m_lblk, map->m_len);
3707 err = ext4_split_convert_extents(handle, inode, map, ppath,
3708 EXT4_GET_BLOCKS_CONVERT);
3711 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3713 return PTR_ERR(path);
3714 depth = ext_depth(inode);
3715 ex = path[depth].p_ext;
3718 err = ext4_ext_get_access(handle, inode, path + depth);
3721 /* first mark the extent as initialized */
3722 ext4_ext_mark_initialized(ex);
3724 /* note: ext4_ext_correct_indexes() isn't needed here because
3725 * borders are not changed
3727 ext4_ext_try_to_merge(handle, inode, path, ex);
3729 /* Mark modified extent as dirty */
3730 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3732 ext4_ext_show_leaf(inode, path);
3737 convert_initialized_extent(handle_t *handle, struct inode *inode,
3738 struct ext4_map_blocks *map,
3739 struct ext4_ext_path **ppath,
3740 unsigned int *allocated)
3742 struct ext4_ext_path *path = *ppath;
3743 struct ext4_extent *ex;
3744 ext4_lblk_t ee_block;
3745 unsigned int ee_len;
3750 * Make sure that the extent is no bigger than we support with
3753 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3754 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3756 depth = ext_depth(inode);
3757 ex = path[depth].p_ext;
3758 ee_block = le32_to_cpu(ex->ee_block);
3759 ee_len = ext4_ext_get_actual_len(ex);
3761 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3762 (unsigned long long)ee_block, ee_len);
3764 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3765 err = ext4_split_convert_extents(handle, inode, map, ppath,
3766 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3769 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3771 return PTR_ERR(path);
3772 depth = ext_depth(inode);
3773 ex = path[depth].p_ext;
3775 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3776 (unsigned long) map->m_lblk);
3777 return -EFSCORRUPTED;
3781 err = ext4_ext_get_access(handle, inode, path + depth);
3784 /* first mark the extent as unwritten */
3785 ext4_ext_mark_unwritten(ex);
3787 /* note: ext4_ext_correct_indexes() isn't needed here because
3788 * borders are not changed
3790 ext4_ext_try_to_merge(handle, inode, path, ex);
3792 /* Mark modified extent as dirty */
3793 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3796 ext4_ext_show_leaf(inode, path);
3798 ext4_update_inode_fsync_trans(handle, inode, 1);
3800 map->m_flags |= EXT4_MAP_UNWRITTEN;
3801 if (*allocated > map->m_len)
3802 *allocated = map->m_len;
3803 map->m_len = *allocated;
3808 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
3809 struct ext4_map_blocks *map,
3810 struct ext4_ext_path **ppath, int flags,
3811 unsigned int allocated, ext4_fsblk_t newblock)
3813 struct ext4_ext_path __maybe_unused *path = *ppath;
3817 ext_debug(inode, "logical block %llu, max_blocks %u, flags 0x%x, allocated %u\n",
3818 (unsigned long long)map->m_lblk, map->m_len, flags,
3820 ext4_ext_show_leaf(inode, path);
3823 * When writing into unwritten space, we should not fail to
3824 * allocate metadata blocks for the new extent block if needed.
3826 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
3828 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
3829 allocated, newblock);
3831 /* get_block() before submitting IO, split the extent */
3832 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
3833 ret = ext4_split_convert_extents(handle, inode, map, ppath,
3834 flags | EXT4_GET_BLOCKS_CONVERT);
3840 * shouldn't get a 0 return when splitting an extent unless
3841 * m_len is 0 (bug) or extent has been corrupted
3843 if (unlikely(ret == 0)) {
3844 EXT4_ERROR_INODE(inode,
3845 "unexpected ret == 0, m_len = %u",
3847 err = -EFSCORRUPTED;
3850 map->m_flags |= EXT4_MAP_UNWRITTEN;
3853 /* IO end_io complete, convert the filled extent to written */
3854 if (flags & EXT4_GET_BLOCKS_CONVERT) {
3855 err = ext4_convert_unwritten_extents_endio(handle, inode, map,
3859 ext4_update_inode_fsync_trans(handle, inode, 1);
3862 /* buffered IO cases */
3864 * repeat fallocate creation request
3865 * we already have an unwritten extent
3867 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
3868 map->m_flags |= EXT4_MAP_UNWRITTEN;
3872 /* buffered READ or buffered write_begin() lookup */
3873 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3875 * We have blocks reserved already. We
3876 * return allocated blocks so that delalloc
3877 * won't do block reservation for us. But
3878 * the buffer head will be unmapped so that
3879 * a read from the block returns 0s.
3881 map->m_flags |= EXT4_MAP_UNWRITTEN;
3886 * Default case when (flags & EXT4_GET_BLOCKS_CREATE) == 1.
3887 * For buffered writes, at writepage time, etc. Convert a
3888 * discovered unwritten extent to written.
3890 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
3895 ext4_update_inode_fsync_trans(handle, inode, 1);
3897 * shouldn't get a 0 return when converting an unwritten extent
3898 * unless m_len is 0 (bug) or extent has been corrupted
3900 if (unlikely(ret == 0)) {
3901 EXT4_ERROR_INODE(inode, "unexpected ret == 0, m_len = %u",
3903 err = -EFSCORRUPTED;
3909 map->m_flags |= EXT4_MAP_NEW;
3911 map->m_flags |= EXT4_MAP_MAPPED;
3913 map->m_pblk = newblock;
3914 if (allocated > map->m_len)
3915 allocated = map->m_len;
3916 map->m_len = allocated;
3917 ext4_ext_show_leaf(inode, path);
3919 return err ? err : allocated;
3923 * get_implied_cluster_alloc - check to see if the requested
3924 * allocation (in the map structure) overlaps with a cluster already
3925 * allocated in an extent.
3926 * @sb The filesystem superblock structure
3927 * @map The requested lblk->pblk mapping
3928 * @ex The extent structure which might contain an implied
3929 * cluster allocation
3931 * This function is called by ext4_ext_map_blocks() after we failed to
3932 * find blocks that were already in the inode's extent tree. Hence,
3933 * we know that the beginning of the requested region cannot overlap
3934 * the extent from the inode's extent tree. There are three cases we
3935 * want to catch. The first is this case:
3937 * |--- cluster # N--|
3938 * |--- extent ---| |---- requested region ---|
3941 * The second case that we need to test for is this one:
3943 * |--------- cluster # N ----------------|
3944 * |--- requested region --| |------- extent ----|
3945 * |=======================|
3947 * The third case is when the requested region lies between two extents
3948 * within the same cluster:
3949 * |------------- cluster # N-------------|
3950 * |----- ex -----| |---- ex_right ----|
3951 * |------ requested region ------|
3952 * |================|
3954 * In each of the above cases, we need to set the map->m_pblk and
3955 * map->m_len so it corresponds to the return the extent labelled as
3956 * "|====|" from cluster #N, since it is already in use for data in
3957 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
3958 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
3959 * as a new "allocated" block region. Otherwise, we will return 0 and
3960 * ext4_ext_map_blocks() will then allocate one or more new clusters
3961 * by calling ext4_mb_new_blocks().
3963 static int get_implied_cluster_alloc(struct super_block *sb,
3964 struct ext4_map_blocks *map,
3965 struct ext4_extent *ex,
3966 struct ext4_ext_path *path)
3968 struct ext4_sb_info *sbi = EXT4_SB(sb);
3969 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
3970 ext4_lblk_t ex_cluster_start, ex_cluster_end;
3971 ext4_lblk_t rr_cluster_start;
3972 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3973 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3974 unsigned short ee_len = ext4_ext_get_actual_len(ex);
3976 /* The extent passed in that we are trying to match */
3977 ex_cluster_start = EXT4_B2C(sbi, ee_block);
3978 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
3980 /* The requested region passed into ext4_map_blocks() */
3981 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
3983 if ((rr_cluster_start == ex_cluster_end) ||
3984 (rr_cluster_start == ex_cluster_start)) {
3985 if (rr_cluster_start == ex_cluster_end)
3986 ee_start += ee_len - 1;
3987 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
3988 map->m_len = min(map->m_len,
3989 (unsigned) sbi->s_cluster_ratio - c_offset);
3991 * Check for and handle this case:
3993 * |--------- cluster # N-------------|
3994 * |------- extent ----|
3995 * |--- requested region ---|
3999 if (map->m_lblk < ee_block)
4000 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4003 * Check for the case where there is already another allocated
4004 * block to the right of 'ex' but before the end of the cluster.
4006 * |------------- cluster # N-------------|
4007 * |----- ex -----| |---- ex_right ----|
4008 * |------ requested region ------|
4009 * |================|
4011 if (map->m_lblk > ee_block) {
4012 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4013 map->m_len = min(map->m_len, next - map->m_lblk);
4016 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4020 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4026 * Block allocation/map/preallocation routine for extents based files
4029 * Need to be called with
4030 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4031 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4033 * return > 0, number of blocks already mapped/allocated
4034 * if create == 0 and these are pre-allocated blocks
4035 * buffer head is unmapped
4036 * otherwise blocks are mapped
4038 * return = 0, if plain look up failed (blocks have not been allocated)
4039 * buffer head is unmapped
4041 * return < 0, error case.
4043 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4044 struct ext4_map_blocks *map, int flags)
4046 struct ext4_ext_path *path = NULL;
4047 struct ext4_extent newex, *ex, ex2;
4048 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4049 ext4_fsblk_t newblock = 0, pblk;
4050 int err = 0, depth, ret;
4051 unsigned int allocated = 0, offset = 0;
4052 unsigned int allocated_clusters = 0;
4053 struct ext4_allocation_request ar;
4054 ext4_lblk_t cluster_offset;
4056 ext_debug(inode, "blocks %u/%u requested\n", map->m_lblk, map->m_len);
4057 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4059 /* find extent for this block */
4060 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4062 err = PTR_ERR(path);
4067 depth = ext_depth(inode);
4070 * consistent leaf must not be empty;
4071 * this situation is possible, though, _during_ tree modification;
4072 * this is why assert can't be put in ext4_find_extent()
4074 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4075 EXT4_ERROR_INODE(inode, "bad extent address "
4076 "lblock: %lu, depth: %d pblock %lld",
4077 (unsigned long) map->m_lblk, depth,
4078 path[depth].p_block);
4079 err = -EFSCORRUPTED;
4083 ex = path[depth].p_ext;
4085 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4086 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4087 unsigned short ee_len;
4091 * unwritten extents are treated as holes, except that
4092 * we split out initialized portions during a write.
4094 ee_len = ext4_ext_get_actual_len(ex);
4096 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4098 /* if found extent covers block, simply return it */
4099 if (in_range(map->m_lblk, ee_block, ee_len)) {
4100 newblock = map->m_lblk - ee_block + ee_start;
4101 /* number of remaining blocks in the extent */
4102 allocated = ee_len - (map->m_lblk - ee_block);
4103 ext_debug(inode, "%u fit into %u:%d -> %llu\n",
4104 map->m_lblk, ee_block, ee_len, newblock);
4107 * If the extent is initialized check whether the
4108 * caller wants to convert it to unwritten.
4110 if ((!ext4_ext_is_unwritten(ex)) &&
4111 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4112 err = convert_initialized_extent(handle,
4113 inode, map, &path, &allocated);
4115 } else if (!ext4_ext_is_unwritten(ex)) {
4116 map->m_flags |= EXT4_MAP_MAPPED;
4117 map->m_pblk = newblock;
4118 if (allocated > map->m_len)
4119 allocated = map->m_len;
4120 map->m_len = allocated;
4121 ext4_ext_show_leaf(inode, path);
4125 ret = ext4_ext_handle_unwritten_extents(
4126 handle, inode, map, &path, flags,
4127 allocated, newblock);
4137 * requested block isn't allocated yet;
4138 * we couldn't try to create block if create flag is zero
4140 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4141 ext4_lblk_t hole_start, hole_len;
4143 hole_start = map->m_lblk;
4144 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4146 * put just found gap into cache to speed up
4147 * subsequent requests
4149 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4151 /* Update hole_len to reflect hole size after map->m_lblk */
4152 if (hole_start != map->m_lblk)
4153 hole_len -= map->m_lblk - hole_start;
4155 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4161 * Okay, we need to do block allocation.
4163 newex.ee_block = cpu_to_le32(map->m_lblk);
4164 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4167 * If we are doing bigalloc, check to see if the extent returned
4168 * by ext4_find_extent() implies a cluster we can use.
4170 if (cluster_offset && ex &&
4171 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4172 ar.len = allocated = map->m_len;
4173 newblock = map->m_pblk;
4174 goto got_allocated_blocks;
4177 /* find neighbour allocated blocks */
4178 ar.lleft = map->m_lblk;
4179 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4182 ar.lright = map->m_lblk;
4183 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4187 /* Check if the extent after searching to the right implies a
4188 * cluster we can use. */
4189 if ((sbi->s_cluster_ratio > 1) && err &&
4190 get_implied_cluster_alloc(inode->i_sb, map, &ex2, path)) {
4191 ar.len = allocated = map->m_len;
4192 newblock = map->m_pblk;
4193 goto got_allocated_blocks;
4197 * See if request is beyond maximum number of blocks we can have in
4198 * a single extent. For an initialized extent this limit is
4199 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4200 * EXT_UNWRITTEN_MAX_LEN.
4202 if (map->m_len > EXT_INIT_MAX_LEN &&
4203 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4204 map->m_len = EXT_INIT_MAX_LEN;
4205 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4206 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4207 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4209 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4210 newex.ee_len = cpu_to_le16(map->m_len);
4211 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4213 allocated = ext4_ext_get_actual_len(&newex);
4215 allocated = map->m_len;
4217 /* allocate new block */
4219 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4220 ar.logical = map->m_lblk;
4222 * We calculate the offset from the beginning of the cluster
4223 * for the logical block number, since when we allocate a
4224 * physical cluster, the physical block should start at the
4225 * same offset from the beginning of the cluster. This is
4226 * needed so that future calls to get_implied_cluster_alloc()
4229 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4230 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4232 ar.logical -= offset;
4233 if (S_ISREG(inode->i_mode))
4234 ar.flags = EXT4_MB_HINT_DATA;
4236 /* disable in-core preallocation for non-regular files */
4238 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4239 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4240 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4241 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4242 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4243 ar.flags |= EXT4_MB_USE_RESERVED;
4244 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4247 allocated_clusters = ar.len;
4248 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4249 ext_debug(inode, "allocate new block: goal %llu, found %llu/%u, requested %u\n",
4250 ar.goal, newblock, ar.len, allocated);
4251 if (ar.len > allocated)
4254 got_allocated_blocks:
4255 /* try to insert new extent into found leaf and return */
4256 pblk = newblock + offset;
4257 ext4_ext_store_pblock(&newex, pblk);
4258 newex.ee_len = cpu_to_le16(ar.len);
4259 /* Mark unwritten */
4260 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4261 ext4_ext_mark_unwritten(&newex);
4262 map->m_flags |= EXT4_MAP_UNWRITTEN;
4265 err = ext4_ext_insert_extent(handle, inode, &path, &newex, flags);
4267 if (allocated_clusters) {
4271 * free data blocks we just allocated.
4272 * not a good idea to call discard here directly,
4273 * but otherwise we'd need to call it every free().
4275 ext4_discard_preallocations(inode, 0);
4276 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4277 fb_flags = EXT4_FREE_BLOCKS_NO_QUOT_UPDATE;
4278 ext4_free_blocks(handle, inode, NULL, newblock,
4279 EXT4_C2B(sbi, allocated_clusters),
4286 * Reduce the reserved cluster count to reflect successful deferred
4287 * allocation of delayed allocated clusters or direct allocation of
4288 * clusters discovered to be delayed allocated. Once allocated, a
4289 * cluster is not included in the reserved count.
4291 if (test_opt(inode->i_sb, DELALLOC) && allocated_clusters) {
4292 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4294 * When allocating delayed allocated clusters, simply
4295 * reduce the reserved cluster count and claim quota
4297 ext4_da_update_reserve_space(inode, allocated_clusters,
4300 ext4_lblk_t lblk, len;
4304 * When allocating non-delayed allocated clusters
4305 * (from fallocate, filemap, DIO, or clusters
4306 * allocated when delalloc has been disabled by
4307 * ext4_nonda_switch), reduce the reserved cluster
4308 * count by the number of allocated clusters that
4309 * have previously been delayed allocated. Quota
4310 * has been claimed by ext4_mb_new_blocks() above,
4311 * so release the quota reservations made for any
4312 * previously delayed allocated clusters.
4314 lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
4315 len = allocated_clusters << sbi->s_cluster_bits;
4316 n = ext4_es_delayed_clu(inode, lblk, len);
4318 ext4_da_update_reserve_space(inode, (int) n, 0);
4323 * Cache the extent and update transaction to commit on fdatasync only
4324 * when it is _not_ an unwritten extent.
4326 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4327 ext4_update_inode_fsync_trans(handle, inode, 1);
4329 ext4_update_inode_fsync_trans(handle, inode, 0);
4331 map->m_flags |= (EXT4_MAP_NEW | EXT4_MAP_MAPPED);
4333 map->m_len = ar.len;
4334 allocated = map->m_len;
4335 ext4_ext_show_leaf(inode, path);
4337 ext4_ext_drop_refs(path);
4340 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4341 err ? err : allocated);
4342 return err ? err : allocated;
4345 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4347 struct super_block *sb = inode->i_sb;
4348 ext4_lblk_t last_block;
4352 * TODO: optimization is possible here.
4353 * Probably we need not scan at all,
4354 * because page truncation is enough.
4357 /* we have to know where to truncate from in crash case */
4358 EXT4_I(inode)->i_disksize = inode->i_size;
4359 err = ext4_mark_inode_dirty(handle, inode);
4363 last_block = (inode->i_size + sb->s_blocksize - 1)
4364 >> EXT4_BLOCK_SIZE_BITS(sb);
4366 err = ext4_es_remove_extent(inode, last_block,
4367 EXT_MAX_BLOCKS - last_block);
4368 if (err == -ENOMEM) {
4370 congestion_wait(BLK_RW_ASYNC, HZ/50);
4376 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4377 if (err == -ENOMEM) {
4379 congestion_wait(BLK_RW_ASYNC, HZ/50);
4380 goto retry_remove_space;
4385 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4386 ext4_lblk_t len, loff_t new_size,
4389 struct inode *inode = file_inode(file);
4391 int ret = 0, ret2 = 0, ret3 = 0;
4394 struct ext4_map_blocks map;
4395 unsigned int credits;
4398 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4399 map.m_lblk = offset;
4402 * Don't normalize the request if it can fit in one extent so
4403 * that it doesn't get unnecessarily split into multiple
4406 if (len <= EXT_UNWRITTEN_MAX_LEN)
4407 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4410 * credits to insert 1 extent into extent tree
4412 credits = ext4_chunk_trans_blocks(inode, len);
4413 depth = ext_depth(inode);
4418 * Recalculate credits when extent tree depth changes.
4420 if (depth != ext_depth(inode)) {
4421 credits = ext4_chunk_trans_blocks(inode, len);
4422 depth = ext_depth(inode);
4425 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4427 if (IS_ERR(handle)) {
4428 ret = PTR_ERR(handle);
4431 ret = ext4_map_blocks(handle, inode, &map, flags);
4433 ext4_debug("inode #%lu: block %u: len %u: "
4434 "ext4_ext_map_blocks returned %d",
4435 inode->i_ino, map.m_lblk,
4437 ext4_mark_inode_dirty(handle, inode);
4438 ext4_journal_stop(handle);
4442 * allow a full retry cycle for any remaining allocations
4446 map.m_len = len = len - ret;
4447 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4448 inode->i_ctime = current_time(inode);
4450 if (epos > new_size)
4452 if (ext4_update_inode_size(inode, epos) & 0x1)
4453 inode->i_mtime = inode->i_ctime;
4455 ret2 = ext4_mark_inode_dirty(handle, inode);
4456 ext4_update_inode_fsync_trans(handle, inode, 1);
4457 ret3 = ext4_journal_stop(handle);
4458 ret2 = ret3 ? ret3 : ret2;
4462 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4465 return ret > 0 ? ret2 : ret;
4468 static int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len);
4470 static int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len);
4472 static long ext4_zero_range(struct file *file, loff_t offset,
4473 loff_t len, int mode)
4475 struct inode *inode = file_inode(file);
4476 handle_t *handle = NULL;
4477 unsigned int max_blocks;
4478 loff_t new_size = 0;
4482 int partial_begin, partial_end;
4485 unsigned int blkbits = inode->i_blkbits;
4487 trace_ext4_zero_range(inode, offset, len, mode);
4489 /* Call ext4_force_commit to flush all data in case of data=journal. */
4490 if (ext4_should_journal_data(inode)) {
4491 ret = ext4_force_commit(inode->i_sb);
4497 * Round up offset. This is not fallocate, we need to zero out
4498 * blocks, so convert interior block aligned part of the range to
4499 * unwritten and possibly manually zero out unaligned parts of the
4502 start = round_up(offset, 1 << blkbits);
4503 end = round_down((offset + len), 1 << blkbits);
4505 if (start < offset || end > offset + len)
4507 partial_begin = offset & ((1 << blkbits) - 1);
4508 partial_end = (offset + len) & ((1 << blkbits) - 1);
4510 lblk = start >> blkbits;
4511 max_blocks = (end >> blkbits);
4512 if (max_blocks < lblk)
4520 * Indirect files do not support unwritten extents
4522 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4527 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4528 (offset + len > inode->i_size ||
4529 offset + len > EXT4_I(inode)->i_disksize)) {
4530 new_size = offset + len;
4531 ret = inode_newsize_ok(inode, new_size);
4536 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4538 /* Wait all existing dio workers, newcomers will block on i_mutex */
4539 inode_dio_wait(inode);
4541 /* Preallocate the range including the unaligned edges */
4542 if (partial_begin || partial_end) {
4543 ret = ext4_alloc_file_blocks(file,
4544 round_down(offset, 1 << blkbits) >> blkbits,
4545 (round_up((offset + len), 1 << blkbits) -
4546 round_down(offset, 1 << blkbits)) >> blkbits,
4553 /* Zero range excluding the unaligned edges */
4554 if (max_blocks > 0) {
4555 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4559 * Prevent page faults from reinstantiating pages we have
4560 * released from page cache.
4562 down_write(&EXT4_I(inode)->i_mmap_sem);
4564 ret = ext4_break_layouts(inode);
4566 up_write(&EXT4_I(inode)->i_mmap_sem);
4570 ret = ext4_update_disksize_before_punch(inode, offset, len);
4572 up_write(&EXT4_I(inode)->i_mmap_sem);
4575 /* Now release the pages and zero block aligned part of pages */
4576 truncate_pagecache_range(inode, start, end - 1);
4577 inode->i_mtime = inode->i_ctime = current_time(inode);
4579 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4581 up_write(&EXT4_I(inode)->i_mmap_sem);
4585 if (!partial_begin && !partial_end)
4589 * In worst case we have to writeout two nonadjacent unwritten
4590 * blocks and update the inode
4592 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4593 if (ext4_should_journal_data(inode))
4595 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4596 if (IS_ERR(handle)) {
4597 ret = PTR_ERR(handle);
4598 ext4_std_error(inode->i_sb, ret);
4602 inode->i_mtime = inode->i_ctime = current_time(inode);
4604 ext4_update_inode_size(inode, new_size);
4605 ret = ext4_mark_inode_dirty(handle, inode);
4608 ext4_fc_track_range(handle, inode, offset >> inode->i_sb->s_blocksize_bits,
4609 (offset + len - 1) >> inode->i_sb->s_blocksize_bits);
4610 /* Zero out partial block at the edges of the range */
4611 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4613 ext4_update_inode_fsync_trans(handle, inode, 1);
4615 if (file->f_flags & O_SYNC)
4616 ext4_handle_sync(handle);
4619 ext4_journal_stop(handle);
4621 inode_unlock(inode);
4626 * preallocate space for a file. This implements ext4's fallocate file
4627 * operation, which gets called from sys_fallocate system call.
4628 * For block-mapped files, posix_fallocate should fall back to the method
4629 * of writing zeroes to the required new blocks (the same behavior which is
4630 * expected for file systems which do not support fallocate() system call).
4632 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4634 struct inode *inode = file_inode(file);
4635 loff_t new_size = 0;
4636 unsigned int max_blocks;
4640 unsigned int blkbits = inode->i_blkbits;
4643 * Encrypted inodes can't handle collapse range or insert
4644 * range since we would need to re-encrypt blocks with a
4645 * different IV or XTS tweak (which are based on the logical
4648 if (IS_ENCRYPTED(inode) &&
4649 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
4652 /* Return error if mode is not supported */
4653 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4654 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4655 FALLOC_FL_INSERT_RANGE))
4658 ext4_fc_start_update(inode);
4660 if (mode & FALLOC_FL_PUNCH_HOLE) {
4661 ret = ext4_punch_hole(inode, offset, len);
4665 ret = ext4_convert_inline_data(inode);
4669 if (mode & FALLOC_FL_COLLAPSE_RANGE) {
4670 ret = ext4_collapse_range(inode, offset, len);
4674 if (mode & FALLOC_FL_INSERT_RANGE) {
4675 ret = ext4_insert_range(inode, offset, len);
4679 if (mode & FALLOC_FL_ZERO_RANGE) {
4680 ret = ext4_zero_range(file, offset, len, mode);
4683 trace_ext4_fallocate_enter(inode, offset, len, mode);
4684 lblk = offset >> blkbits;
4686 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4687 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4692 * We only support preallocation for extent-based files only
4694 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4699 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4700 (offset + len > inode->i_size ||
4701 offset + len > EXT4_I(inode)->i_disksize)) {
4702 new_size = offset + len;
4703 ret = inode_newsize_ok(inode, new_size);
4708 /* Wait all existing dio workers, newcomers will block on i_mutex */
4709 inode_dio_wait(inode);
4711 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
4715 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
4716 ret = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
4717 EXT4_I(inode)->i_sync_tid);
4720 inode_unlock(inode);
4721 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
4723 ext4_fc_stop_update(inode);
4728 * This function convert a range of blocks to written extents
4729 * The caller of this function will pass the start offset and the size.
4730 * all unwritten extents within this range will be converted to
4733 * This function is called from the direct IO end io call back
4734 * function, to convert the fallocated extents after IO is completed.
4735 * Returns 0 on success.
4737 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
4738 loff_t offset, ssize_t len)
4740 unsigned int max_blocks;
4741 int ret = 0, ret2 = 0, ret3 = 0;
4742 struct ext4_map_blocks map;
4743 unsigned int blkbits = inode->i_blkbits;
4744 unsigned int credits = 0;
4746 map.m_lblk = offset >> blkbits;
4747 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4751 * credits to insert 1 extent into extent tree
4753 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4755 while (ret >= 0 && ret < max_blocks) {
4757 map.m_len = (max_blocks -= ret);
4759 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4761 if (IS_ERR(handle)) {
4762 ret = PTR_ERR(handle);
4766 ret = ext4_map_blocks(handle, inode, &map,
4767 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
4769 ext4_warning(inode->i_sb,
4770 "inode #%lu: block %u: len %u: "
4771 "ext4_ext_map_blocks returned %d",
4772 inode->i_ino, map.m_lblk,
4774 ret2 = ext4_mark_inode_dirty(handle, inode);
4776 ret3 = ext4_journal_stop(handle);
4781 if (ret <= 0 || ret2)
4784 return ret > 0 ? ret2 : ret;
4787 int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
4789 int ret = 0, err = 0;
4790 struct ext4_io_end_vec *io_end_vec;
4793 * This is somewhat ugly but the idea is clear: When transaction is
4794 * reserved, everything goes into it. Otherwise we rather start several
4795 * smaller transactions for conversion of each extent separately.
4798 handle = ext4_journal_start_reserved(handle,
4799 EXT4_HT_EXT_CONVERT);
4801 return PTR_ERR(handle);
4804 list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
4805 ret = ext4_convert_unwritten_extents(handle, io_end->inode,
4813 err = ext4_journal_stop(handle);
4815 return ret < 0 ? ret : err;
4818 static int ext4_iomap_xattr_fiemap(struct inode *inode, struct iomap *iomap)
4822 int blockbits = inode->i_sb->s_blocksize_bits;
4827 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4828 struct ext4_iloc iloc;
4829 int offset; /* offset of xattr in inode */
4831 error = ext4_get_inode_loc(inode, &iloc);
4834 physical = (__u64)iloc.bh->b_blocknr << blockbits;
4835 offset = EXT4_GOOD_OLD_INODE_SIZE +
4836 EXT4_I(inode)->i_extra_isize;
4838 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
4840 iomap_type = IOMAP_INLINE;
4841 } else if (EXT4_I(inode)->i_file_acl) { /* external block */
4842 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
4843 length = inode->i_sb->s_blocksize;
4844 iomap_type = IOMAP_MAPPED;
4846 /* no in-inode or external block for xattr, so return -ENOENT */
4851 iomap->addr = physical;
4853 iomap->length = length;
4854 iomap->type = iomap_type;
4860 static int ext4_iomap_xattr_begin(struct inode *inode, loff_t offset,
4861 loff_t length, unsigned flags,
4862 struct iomap *iomap, struct iomap *srcmap)
4866 error = ext4_iomap_xattr_fiemap(inode, iomap);
4867 if (error == 0 && (offset >= iomap->length))
4872 static const struct iomap_ops ext4_iomap_xattr_ops = {
4873 .iomap_begin = ext4_iomap_xattr_begin,
4876 static int ext4_fiemap_check_ranges(struct inode *inode, u64 start, u64 *len)
4880 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4881 maxbytes = inode->i_sb->s_maxbytes;
4883 maxbytes = EXT4_SB(inode->i_sb)->s_bitmap_maxbytes;
4887 if (start > maxbytes)
4891 * Shrink request scope to what the fs can actually handle.
4893 if (*len > maxbytes || (maxbytes - *len) < start)
4894 *len = maxbytes - start;
4898 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4903 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4904 error = ext4_ext_precache(inode);
4907 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
4911 * For bitmap files the maximum size limit could be smaller than
4912 * s_maxbytes, so check len here manually instead of just relying on the
4915 error = ext4_fiemap_check_ranges(inode, start, &len);
4919 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
4920 fieinfo->fi_flags &= ~FIEMAP_FLAG_XATTR;
4921 return iomap_fiemap(inode, fieinfo, start, len,
4922 &ext4_iomap_xattr_ops);
4925 return iomap_fiemap(inode, fieinfo, start, len, &ext4_iomap_report_ops);
4928 int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
4929 __u64 start, __u64 len)
4931 ext4_lblk_t start_blk, len_blks;
4935 if (ext4_has_inline_data(inode)) {
4938 down_read(&EXT4_I(inode)->xattr_sem);
4939 has_inline = ext4_has_inline_data(inode);
4940 up_read(&EXT4_I(inode)->xattr_sem);
4945 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4946 error = ext4_ext_precache(inode);
4949 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
4952 error = fiemap_prep(inode, fieinfo, start, &len, 0);
4956 error = ext4_fiemap_check_ranges(inode, start, &len);
4960 start_blk = start >> inode->i_sb->s_blocksize_bits;
4961 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
4962 if (last_blk >= EXT_MAX_BLOCKS)
4963 last_blk = EXT_MAX_BLOCKS-1;
4964 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
4967 * Walk the extent tree gathering extent information
4968 * and pushing extents back to the user.
4970 return ext4_fill_es_cache_info(inode, start_blk, len_blks, fieinfo);
4975 * Function to access the path buffer for marking it dirty.
4976 * It also checks if there are sufficient credits left in the journal handle
4980 ext4_access_path(handle_t *handle, struct inode *inode,
4981 struct ext4_ext_path *path)
4985 if (!ext4_handle_valid(handle))
4989 * Check if need to extend journal credits
4990 * 3 for leaf, sb, and inode plus 2 (bmap and group
4991 * descriptor) for each block group; assume two block
4994 credits = ext4_writepage_trans_blocks(inode);
4995 err = ext4_datasem_ensure_credits(handle, inode, 7, credits, 0);
4999 err = ext4_ext_get_access(handle, inode, path);
5004 * ext4_ext_shift_path_extents:
5005 * Shift the extents of a path structure lying between path[depth].p_ext
5006 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5007 * if it is right shift or left shift operation.
5010 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5011 struct inode *inode, handle_t *handle,
5012 enum SHIFT_DIRECTION SHIFT)
5015 struct ext4_extent *ex_start, *ex_last;
5016 bool update = false;
5017 depth = path->p_depth;
5019 while (depth >= 0) {
5020 if (depth == path->p_depth) {
5021 ex_start = path[depth].p_ext;
5023 return -EFSCORRUPTED;
5025 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5027 err = ext4_access_path(handle, inode, path + depth);
5031 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5034 while (ex_start <= ex_last) {
5035 if (SHIFT == SHIFT_LEFT) {
5036 le32_add_cpu(&ex_start->ee_block,
5038 /* Try to merge to the left. */
5040 EXT_FIRST_EXTENT(path[depth].p_hdr))
5042 ext4_ext_try_to_merge_right(inode,
5043 path, ex_start - 1))
5048 le32_add_cpu(&ex_last->ee_block, shift);
5049 ext4_ext_try_to_merge_right(inode, path,
5054 err = ext4_ext_dirty(handle, inode, path + depth);
5058 if (--depth < 0 || !update)
5062 /* Update index too */
5063 err = ext4_access_path(handle, inode, path + depth);
5067 if (SHIFT == SHIFT_LEFT)
5068 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5070 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5071 err = ext4_ext_dirty(handle, inode, path + depth);
5075 /* we are done if current index is not a starting index */
5076 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5087 * ext4_ext_shift_extents:
5088 * All the extents which lies in the range from @start to the last allocated
5089 * block for the @inode are shifted either towards left or right (depending
5090 * upon @SHIFT) by @shift blocks.
5091 * On success, 0 is returned, error otherwise.
5094 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5095 ext4_lblk_t start, ext4_lblk_t shift,
5096 enum SHIFT_DIRECTION SHIFT)
5098 struct ext4_ext_path *path;
5100 struct ext4_extent *extent;
5101 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5103 /* Let path point to the last extent */
5104 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5107 return PTR_ERR(path);
5109 depth = path->p_depth;
5110 extent = path[depth].p_ext;
5114 stop = le32_to_cpu(extent->ee_block);
5117 * For left shifts, make sure the hole on the left is big enough to
5118 * accommodate the shift. For right shifts, make sure the last extent
5119 * won't be shifted beyond EXT_MAX_BLOCKS.
5121 if (SHIFT == SHIFT_LEFT) {
5122 path = ext4_find_extent(inode, start - 1, &path,
5125 return PTR_ERR(path);
5126 depth = path->p_depth;
5127 extent = path[depth].p_ext;
5129 ex_start = le32_to_cpu(extent->ee_block);
5130 ex_end = le32_to_cpu(extent->ee_block) +
5131 ext4_ext_get_actual_len(extent);
5137 if ((start == ex_start && shift > ex_start) ||
5138 (shift > start - ex_end)) {
5143 if (shift > EXT_MAX_BLOCKS -
5144 (stop + ext4_ext_get_actual_len(extent))) {
5151 * In case of left shift, iterator points to start and it is increased
5152 * till we reach stop. In case of right shift, iterator points to stop
5153 * and it is decreased till we reach start.
5155 if (SHIFT == SHIFT_LEFT)
5161 * Its safe to start updating extents. Start and stop are unsigned, so
5162 * in case of right shift if extent with 0 block is reached, iterator
5163 * becomes NULL to indicate the end of the loop.
5165 while (iterator && start <= stop) {
5166 path = ext4_find_extent(inode, *iterator, &path,
5169 return PTR_ERR(path);
5170 depth = path->p_depth;
5171 extent = path[depth].p_ext;
5173 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5174 (unsigned long) *iterator);
5175 return -EFSCORRUPTED;
5177 if (SHIFT == SHIFT_LEFT && *iterator >
5178 le32_to_cpu(extent->ee_block)) {
5179 /* Hole, move to the next extent */
5180 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5181 path[depth].p_ext++;
5183 *iterator = ext4_ext_next_allocated_block(path);
5188 if (SHIFT == SHIFT_LEFT) {
5189 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5190 *iterator = le32_to_cpu(extent->ee_block) +
5191 ext4_ext_get_actual_len(extent);
5193 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5194 if (le32_to_cpu(extent->ee_block) > 0)
5195 *iterator = le32_to_cpu(extent->ee_block) - 1;
5197 /* Beginning is reached, end of the loop */
5199 /* Update path extent in case we need to stop */
5200 while (le32_to_cpu(extent->ee_block) < start)
5202 path[depth].p_ext = extent;
5204 ret = ext4_ext_shift_path_extents(path, shift, inode,
5210 ext4_ext_drop_refs(path);
5216 * ext4_collapse_range:
5217 * This implements the fallocate's collapse range functionality for ext4
5218 * Returns: 0 and non-zero on error.
5220 static int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5222 struct super_block *sb = inode->i_sb;
5223 ext4_lblk_t punch_start, punch_stop;
5225 unsigned int credits;
5226 loff_t new_size, ioffset;
5230 * We need to test this early because xfstests assumes that a
5231 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5232 * system does not support collapse range.
5234 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5237 /* Collapse range works only on fs cluster size aligned regions. */
5238 if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
5241 trace_ext4_collapse_range(inode, offset, len);
5243 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5244 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5246 /* Call ext4_force_commit to flush all data in case of data=journal. */
5247 if (ext4_should_journal_data(inode)) {
5248 ret = ext4_force_commit(inode->i_sb);
5255 * There is no need to overlap collapse range with EOF, in which case
5256 * it is effectively a truncate operation
5258 if (offset + len >= inode->i_size) {
5263 /* Currently just for extent based files */
5264 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5269 /* Wait for existing dio to complete */
5270 inode_dio_wait(inode);
5273 * Prevent page faults from reinstantiating pages we have released from
5276 down_write(&EXT4_I(inode)->i_mmap_sem);
5278 ret = ext4_break_layouts(inode);
5283 * Need to round down offset to be aligned with page size boundary
5284 * for page size > block size.
5286 ioffset = round_down(offset, PAGE_SIZE);
5288 * Write tail of the last page before removed range since it will get
5289 * removed from the page cache below.
5291 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5295 * Write data that will be shifted to preserve them when discarding
5296 * page cache below. We are also protected from pages becoming dirty
5299 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5303 truncate_pagecache(inode, ioffset);
5305 credits = ext4_writepage_trans_blocks(inode);
5306 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5307 if (IS_ERR(handle)) {
5308 ret = PTR_ERR(handle);
5311 ext4_fc_start_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE);
5313 down_write(&EXT4_I(inode)->i_data_sem);
5314 ext4_discard_preallocations(inode, 0);
5316 ret = ext4_es_remove_extent(inode, punch_start,
5317 EXT_MAX_BLOCKS - punch_start);
5319 up_write(&EXT4_I(inode)->i_data_sem);
5323 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5325 up_write(&EXT4_I(inode)->i_data_sem);
5328 ext4_discard_preallocations(inode, 0);
5330 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5331 punch_stop - punch_start, SHIFT_LEFT);
5333 up_write(&EXT4_I(inode)->i_data_sem);
5337 new_size = inode->i_size - len;
5338 i_size_write(inode, new_size);
5339 EXT4_I(inode)->i_disksize = new_size;
5341 up_write(&EXT4_I(inode)->i_data_sem);
5343 ext4_handle_sync(handle);
5344 inode->i_mtime = inode->i_ctime = current_time(inode);
5345 ret = ext4_mark_inode_dirty(handle, inode);
5346 ext4_update_inode_fsync_trans(handle, inode, 1);
5349 ext4_journal_stop(handle);
5350 ext4_fc_stop_ineligible(sb);
5352 up_write(&EXT4_I(inode)->i_mmap_sem);
5354 inode_unlock(inode);
5359 * ext4_insert_range:
5360 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5361 * The data blocks starting from @offset to the EOF are shifted by @len
5362 * towards right to create a hole in the @inode. Inode size is increased
5364 * Returns 0 on success, error otherwise.
5366 static int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5368 struct super_block *sb = inode->i_sb;
5370 struct ext4_ext_path *path;
5371 struct ext4_extent *extent;
5372 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5373 unsigned int credits, ee_len;
5374 int ret = 0, depth, split_flag = 0;
5378 * We need to test this early because xfstests assumes that an
5379 * insert range of (0, 1) will return EOPNOTSUPP if the file
5380 * system does not support insert range.
5382 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5385 /* Insert range works only on fs cluster size aligned regions. */
5386 if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
5389 trace_ext4_insert_range(inode, offset, len);
5391 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5392 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5394 /* Call ext4_force_commit to flush all data in case of data=journal */
5395 if (ext4_should_journal_data(inode)) {
5396 ret = ext4_force_commit(inode->i_sb);
5402 /* Currently just for extent based files */
5403 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5408 /* Check whether the maximum file size would be exceeded */
5409 if (len > inode->i_sb->s_maxbytes - inode->i_size) {
5414 /* Offset must be less than i_size */
5415 if (offset >= inode->i_size) {
5420 /* Wait for existing dio to complete */
5421 inode_dio_wait(inode);
5424 * Prevent page faults from reinstantiating pages we have released from
5427 down_write(&EXT4_I(inode)->i_mmap_sem);
5429 ret = ext4_break_layouts(inode);
5434 * Need to round down to align start offset to page size boundary
5435 * for page size > block size.
5437 ioffset = round_down(offset, PAGE_SIZE);
5438 /* Write out all dirty pages */
5439 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5443 truncate_pagecache(inode, ioffset);
5445 credits = ext4_writepage_trans_blocks(inode);
5446 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5447 if (IS_ERR(handle)) {
5448 ret = PTR_ERR(handle);
5451 ext4_fc_start_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE);
5453 /* Expand file to avoid data loss if there is error while shifting */
5454 inode->i_size += len;
5455 EXT4_I(inode)->i_disksize += len;
5456 inode->i_mtime = inode->i_ctime = current_time(inode);
5457 ret = ext4_mark_inode_dirty(handle, inode);
5461 down_write(&EXT4_I(inode)->i_data_sem);
5462 ext4_discard_preallocations(inode, 0);
5464 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5466 up_write(&EXT4_I(inode)->i_data_sem);
5470 depth = ext_depth(inode);
5471 extent = path[depth].p_ext;
5473 ee_start_lblk = le32_to_cpu(extent->ee_block);
5474 ee_len = ext4_ext_get_actual_len(extent);
5477 * If offset_lblk is not the starting block of extent, split
5478 * the extent @offset_lblk
5480 if ((offset_lblk > ee_start_lblk) &&
5481 (offset_lblk < (ee_start_lblk + ee_len))) {
5482 if (ext4_ext_is_unwritten(extent))
5483 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5484 EXT4_EXT_MARK_UNWRIT2;
5485 ret = ext4_split_extent_at(handle, inode, &path,
5486 offset_lblk, split_flag,
5488 EXT4_GET_BLOCKS_PRE_IO |
5489 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5492 ext4_ext_drop_refs(path);
5495 up_write(&EXT4_I(inode)->i_data_sem);
5499 ext4_ext_drop_refs(path);
5503 ret = ext4_es_remove_extent(inode, offset_lblk,
5504 EXT_MAX_BLOCKS - offset_lblk);
5506 up_write(&EXT4_I(inode)->i_data_sem);
5511 * if offset_lblk lies in a hole which is at start of file, use
5512 * ee_start_lblk to shift extents
5514 ret = ext4_ext_shift_extents(inode, handle,
5515 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5516 len_lblk, SHIFT_RIGHT);
5518 up_write(&EXT4_I(inode)->i_data_sem);
5520 ext4_handle_sync(handle);
5522 ext4_update_inode_fsync_trans(handle, inode, 1);
5525 ext4_journal_stop(handle);
5526 ext4_fc_stop_ineligible(sb);
5528 up_write(&EXT4_I(inode)->i_mmap_sem);
5530 inode_unlock(inode);
5535 * ext4_swap_extents() - Swap extents between two inodes
5536 * @handle: handle for this transaction
5537 * @inode1: First inode
5538 * @inode2: Second inode
5539 * @lblk1: Start block for first inode
5540 * @lblk2: Start block for second inode
5541 * @count: Number of blocks to swap
5542 * @unwritten: Mark second inode's extents as unwritten after swap
5543 * @erp: Pointer to save error value
5545 * This helper routine does exactly what is promise "swap extents". All other
5546 * stuff such as page-cache locking consistency, bh mapping consistency or
5547 * extent's data copying must be performed by caller.
5549 * i_mutex is held for both inodes
5550 * i_data_sem is locked for write for both inodes
5552 * All pages from requested range are locked for both inodes
5555 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5556 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5557 ext4_lblk_t count, int unwritten, int *erp)
5559 struct ext4_ext_path *path1 = NULL;
5560 struct ext4_ext_path *path2 = NULL;
5561 int replaced_count = 0;
5563 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5564 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5565 BUG_ON(!inode_is_locked(inode1));
5566 BUG_ON(!inode_is_locked(inode2));
5568 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5571 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5576 struct ext4_extent *ex1, *ex2, tmp_ex;
5577 ext4_lblk_t e1_blk, e2_blk;
5578 int e1_len, e2_len, len;
5581 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5582 if (IS_ERR(path1)) {
5583 *erp = PTR_ERR(path1);
5589 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5590 if (IS_ERR(path2)) {
5591 *erp = PTR_ERR(path2);
5595 ex1 = path1[path1->p_depth].p_ext;
5596 ex2 = path2[path2->p_depth].p_ext;
5597 /* Do we have something to swap ? */
5598 if (unlikely(!ex2 || !ex1))
5601 e1_blk = le32_to_cpu(ex1->ee_block);
5602 e2_blk = le32_to_cpu(ex2->ee_block);
5603 e1_len = ext4_ext_get_actual_len(ex1);
5604 e2_len = ext4_ext_get_actual_len(ex2);
5607 if (!in_range(lblk1, e1_blk, e1_len) ||
5608 !in_range(lblk2, e2_blk, e2_len)) {
5609 ext4_lblk_t next1, next2;
5611 /* if hole after extent, then go to next extent */
5612 next1 = ext4_ext_next_allocated_block(path1);
5613 next2 = ext4_ext_next_allocated_block(path2);
5614 /* If hole before extent, then shift to that extent */
5619 /* Do we have something to swap */
5620 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5622 /* Move to the rightest boundary */
5623 len = next1 - lblk1;
5624 if (len < next2 - lblk2)
5625 len = next2 - lblk2;
5634 /* Prepare left boundary */
5635 if (e1_blk < lblk1) {
5637 *erp = ext4_force_split_extent_at(handle, inode1,
5642 if (e2_blk < lblk2) {
5644 *erp = ext4_force_split_extent_at(handle, inode2,
5649 /* ext4_split_extent_at() may result in leaf extent split,
5650 * path must to be revalidated. */
5654 /* Prepare right boundary */
5656 if (len > e1_blk + e1_len - lblk1)
5657 len = e1_blk + e1_len - lblk1;
5658 if (len > e2_blk + e2_len - lblk2)
5659 len = e2_blk + e2_len - lblk2;
5661 if (len != e1_len) {
5663 *erp = ext4_force_split_extent_at(handle, inode1,
5664 &path1, lblk1 + len, 0);
5668 if (len != e2_len) {
5670 *erp = ext4_force_split_extent_at(handle, inode2,
5671 &path2, lblk2 + len, 0);
5675 /* ext4_split_extent_at() may result in leaf extent split,
5676 * path must to be revalidated. */
5680 BUG_ON(e2_len != e1_len);
5681 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5684 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5688 /* Both extents are fully inside boundaries. Swap it now */
5690 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5691 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5692 ex1->ee_len = cpu_to_le16(e2_len);
5693 ex2->ee_len = cpu_to_le16(e1_len);
5695 ext4_ext_mark_unwritten(ex2);
5696 if (ext4_ext_is_unwritten(&tmp_ex))
5697 ext4_ext_mark_unwritten(ex1);
5699 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5700 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5701 *erp = ext4_ext_dirty(handle, inode2, path2 +
5705 *erp = ext4_ext_dirty(handle, inode1, path1 +
5708 * Looks scarry ah..? second inode already points to new blocks,
5709 * and it was successfully dirtied. But luckily error may happen
5710 * only due to journal error, so full transaction will be
5717 replaced_count += len;
5721 ext4_ext_drop_refs(path1);
5723 ext4_ext_drop_refs(path2);
5725 path1 = path2 = NULL;
5727 return replaced_count;
5731 * ext4_clu_mapped - determine whether any block in a logical cluster has
5732 * been mapped to a physical cluster
5734 * @inode - file containing the logical cluster
5735 * @lclu - logical cluster of interest
5737 * Returns 1 if any block in the logical cluster is mapped, signifying
5738 * that a physical cluster has been allocated for it. Otherwise,
5739 * returns 0. Can also return negative error codes. Derived from
5740 * ext4_ext_map_blocks().
5742 int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
5744 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5745 struct ext4_ext_path *path;
5746 int depth, mapped = 0, err = 0;
5747 struct ext4_extent *extent;
5748 ext4_lblk_t first_lblk, first_lclu, last_lclu;
5750 /* search for the extent closest to the first block in the cluster */
5751 path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
5753 err = PTR_ERR(path);
5758 depth = ext_depth(inode);
5761 * A consistent leaf must not be empty. This situation is possible,
5762 * though, _during_ tree modification, and it's why an assert can't
5763 * be put in ext4_find_extent().
5765 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
5766 EXT4_ERROR_INODE(inode,
5767 "bad extent address - lblock: %lu, depth: %d, pblock: %lld",
5768 (unsigned long) EXT4_C2B(sbi, lclu),
5769 depth, path[depth].p_block);
5770 err = -EFSCORRUPTED;
5774 extent = path[depth].p_ext;
5776 /* can't be mapped if the extent tree is empty */
5780 first_lblk = le32_to_cpu(extent->ee_block);
5781 first_lclu = EXT4_B2C(sbi, first_lblk);
5784 * Three possible outcomes at this point - found extent spanning
5785 * the target cluster, to the left of the target cluster, or to the
5786 * right of the target cluster. The first two cases are handled here.
5787 * The last case indicates the target cluster is not mapped.
5789 if (lclu >= first_lclu) {
5790 last_lclu = EXT4_B2C(sbi, first_lblk +
5791 ext4_ext_get_actual_len(extent) - 1);
5792 if (lclu <= last_lclu) {
5795 first_lblk = ext4_ext_next_allocated_block(path);
5796 first_lclu = EXT4_B2C(sbi, first_lblk);
5797 if (lclu == first_lclu)
5803 ext4_ext_drop_refs(path);
5806 return err ? err : mapped;
5810 * Updates physical block address and unwritten status of extent
5811 * starting at lblk start and of len. If such an extent doesn't exist,
5812 * this function splits the extent tree appropriately to create an
5813 * extent like this. This function is called in the fast commit
5814 * replay path. Returns 0 on success and error on failure.
5816 int ext4_ext_replay_update_ex(struct inode *inode, ext4_lblk_t start,
5817 int len, int unwritten, ext4_fsblk_t pblk)
5819 struct ext4_ext_path *path = NULL, *ppath;
5820 struct ext4_extent *ex;
5823 path = ext4_find_extent(inode, start, NULL, 0);
5825 return PTR_ERR(path);
5826 ex = path[path->p_depth].p_ext;
5828 ret = -EFSCORRUPTED;
5832 if (le32_to_cpu(ex->ee_block) != start ||
5833 ext4_ext_get_actual_len(ex) != len) {
5834 /* We need to split this extent to match our extent first */
5836 down_write(&EXT4_I(inode)->i_data_sem);
5837 ret = ext4_force_split_extent_at(NULL, inode, &ppath, start, 1);
5838 up_write(&EXT4_I(inode)->i_data_sem);
5842 path = ext4_find_extent(inode, start, NULL, 0);
5846 ex = path[path->p_depth].p_ext;
5847 WARN_ON(le32_to_cpu(ex->ee_block) != start);
5848 if (ext4_ext_get_actual_len(ex) != len) {
5849 down_write(&EXT4_I(inode)->i_data_sem);
5850 ret = ext4_force_split_extent_at(NULL, inode, &ppath,
5852 up_write(&EXT4_I(inode)->i_data_sem);
5856 path = ext4_find_extent(inode, start, NULL, 0);
5859 ex = path[path->p_depth].p_ext;
5863 ext4_ext_mark_unwritten(ex);
5865 ext4_ext_mark_initialized(ex);
5866 ext4_ext_store_pblock(ex, pblk);
5867 down_write(&EXT4_I(inode)->i_data_sem);
5868 ret = ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
5869 up_write(&EXT4_I(inode)->i_data_sem);
5871 ext4_ext_drop_refs(path);
5873 ext4_mark_inode_dirty(NULL, inode);
5877 /* Try to shrink the extent tree */
5878 void ext4_ext_replay_shrink_inode(struct inode *inode, ext4_lblk_t end)
5880 struct ext4_ext_path *path = NULL;
5881 struct ext4_extent *ex;
5882 ext4_lblk_t old_cur, cur = 0;
5885 path = ext4_find_extent(inode, cur, NULL, 0);
5888 ex = path[path->p_depth].p_ext;
5890 ext4_ext_drop_refs(path);
5892 ext4_mark_inode_dirty(NULL, inode);
5896 cur = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
5899 ext4_ext_try_to_merge(NULL, inode, path, ex);
5900 down_write(&EXT4_I(inode)->i_data_sem);
5901 ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
5902 up_write(&EXT4_I(inode)->i_data_sem);
5903 ext4_mark_inode_dirty(NULL, inode);
5904 ext4_ext_drop_refs(path);
5909 /* Check if *cur is a hole and if it is, skip it */
5910 static void skip_hole(struct inode *inode, ext4_lblk_t *cur)
5913 struct ext4_map_blocks map;
5916 map.m_len = ((inode->i_size) >> inode->i_sb->s_blocksize_bits) - *cur;
5918 ret = ext4_map_blocks(NULL, inode, &map, 0);
5921 *cur = *cur + map.m_len;
5924 /* Count number of blocks used by this inode and update i_blocks */
5925 int ext4_ext_replay_set_iblocks(struct inode *inode)
5927 struct ext4_ext_path *path = NULL, *path2 = NULL;
5928 struct ext4_extent *ex;
5929 ext4_lblk_t cur = 0, end;
5930 int numblks = 0, i, ret = 0;
5931 ext4_fsblk_t cmp1, cmp2;
5932 struct ext4_map_blocks map;
5934 /* Determin the size of the file first */
5935 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5938 return PTR_ERR(path);
5939 ex = path[path->p_depth].p_ext;
5941 ext4_ext_drop_refs(path);
5945 end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
5946 ext4_ext_drop_refs(path);
5949 /* Count the number of data blocks */
5953 map.m_len = end - cur;
5954 ret = ext4_map_blocks(NULL, inode, &map, 0);
5959 cur = cur + map.m_len;
5963 * Count the number of extent tree blocks. We do it by looking up
5964 * two successive extents and determining the difference between
5965 * their paths. When path is different for 2 successive extents
5966 * we compare the blocks in the path at each level and increment
5967 * iblocks by total number of differences found.
5970 skip_hole(inode, &cur);
5971 path = ext4_find_extent(inode, cur, NULL, 0);
5974 numblks += path->p_depth;
5975 ext4_ext_drop_refs(path);
5978 path = ext4_find_extent(inode, cur, NULL, 0);
5981 ex = path[path->p_depth].p_ext;
5983 ext4_ext_drop_refs(path);
5987 cur = max(cur + 1, le32_to_cpu(ex->ee_block) +
5988 ext4_ext_get_actual_len(ex));
5989 skip_hole(inode, &cur);
5991 path2 = ext4_find_extent(inode, cur, NULL, 0);
5992 if (IS_ERR(path2)) {
5993 ext4_ext_drop_refs(path);
5997 for (i = 0; i <= max(path->p_depth, path2->p_depth); i++) {
5999 if (i <= path->p_depth)
6000 cmp1 = path[i].p_bh ?
6001 path[i].p_bh->b_blocknr : 0;
6002 if (i <= path2->p_depth)
6003 cmp2 = path2[i].p_bh ?
6004 path2[i].p_bh->b_blocknr : 0;
6005 if (cmp1 != cmp2 && cmp2 != 0)
6008 ext4_ext_drop_refs(path);
6009 ext4_ext_drop_refs(path2);
6015 inode->i_blocks = numblks << (inode->i_sb->s_blocksize_bits - 9);
6016 ext4_mark_inode_dirty(NULL, inode);
6020 int ext4_ext_clear_bb(struct inode *inode)
6022 struct ext4_ext_path *path = NULL;
6023 struct ext4_extent *ex;
6024 ext4_lblk_t cur = 0, end;
6026 struct ext4_map_blocks map;
6028 /* Determin the size of the file first */
6029 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
6032 return PTR_ERR(path);
6033 ex = path[path->p_depth].p_ext;
6035 ext4_ext_drop_refs(path);
6039 end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
6040 ext4_ext_drop_refs(path);
6046 map.m_len = end - cur;
6047 ret = ext4_map_blocks(NULL, inode, &map, 0);
6051 path = ext4_find_extent(inode, map.m_lblk, NULL, 0);
6052 if (!IS_ERR_OR_NULL(path)) {
6053 for (j = 0; j < path->p_depth; j++) {
6055 ext4_mb_mark_bb(inode->i_sb,
6056 path[j].p_block, 1, 0);
6058 ext4_ext_drop_refs(path);
6061 ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, 0);
6063 cur = cur + map.m_len;