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 "ext4_jbd2.h"
32 #include "ext4_extents.h"
35 #include <trace/events/ext4.h>
38 * used by extent splitting.
40 #define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
42 #define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
43 #define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
45 #define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
46 #define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
48 static __le32 ext4_extent_block_csum(struct inode *inode,
49 struct ext4_extent_header *eh)
51 struct ext4_inode_info *ei = EXT4_I(inode);
52 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
55 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
56 EXT4_EXTENT_TAIL_OFFSET(eh));
57 return cpu_to_le32(csum);
60 static int ext4_extent_block_csum_verify(struct inode *inode,
61 struct ext4_extent_header *eh)
63 struct ext4_extent_tail *et;
65 if (!ext4_has_metadata_csum(inode->i_sb))
68 et = find_ext4_extent_tail(eh);
69 if (et->et_checksum != ext4_extent_block_csum(inode, eh))
74 static void ext4_extent_block_csum_set(struct inode *inode,
75 struct ext4_extent_header *eh)
77 struct ext4_extent_tail *et;
79 if (!ext4_has_metadata_csum(inode->i_sb))
82 et = find_ext4_extent_tail(eh);
83 et->et_checksum = ext4_extent_block_csum(inode, eh);
86 static int ext4_split_extent(handle_t *handle,
88 struct ext4_ext_path **ppath,
89 struct ext4_map_blocks *map,
93 static int ext4_split_extent_at(handle_t *handle,
95 struct ext4_ext_path **ppath,
100 static int ext4_find_delayed_extent(struct inode *inode,
101 struct extent_status *newes);
103 static int ext4_ext_trunc_restart_fn(struct inode *inode, int *dropped)
106 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
107 * moment, get_block can be called only for blocks inside i_size since
108 * page cache has been already dropped and writes are blocked by
109 * i_mutex. So we can safely drop the i_data_sem here.
111 BUG_ON(EXT4_JOURNAL(inode) == NULL);
112 ext4_discard_preallocations(inode);
113 up_write(&EXT4_I(inode)->i_data_sem);
119 * Make sure 'handle' has at least 'check_cred' credits. If not, restart
120 * transaction with 'restart_cred' credits. The function drops i_data_sem
121 * when restarting transaction and gets it after transaction is restarted.
123 * The function returns 0 on success, 1 if transaction had to be restarted,
124 * and < 0 in case of fatal error.
126 int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode,
127 int check_cred, int restart_cred,
133 ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred,
134 revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped));
136 down_write(&EXT4_I(inode)->i_data_sem);
145 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
146 struct ext4_ext_path *path)
149 /* path points to block */
150 BUFFER_TRACE(path->p_bh, "get_write_access");
151 return ext4_journal_get_write_access(handle, path->p_bh);
153 /* path points to leaf/index in inode body */
154 /* we use in-core data, no need to protect them */
164 int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
165 struct inode *inode, struct ext4_ext_path *path)
169 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
171 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
172 /* path points to block */
173 err = __ext4_handle_dirty_metadata(where, line, handle,
176 /* path points to leaf/index in inode body */
177 err = ext4_mark_inode_dirty(handle, inode);
182 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
183 struct ext4_ext_path *path,
187 int depth = path->p_depth;
188 struct ext4_extent *ex;
191 * Try to predict block placement assuming that we are
192 * filling in a file which will eventually be
193 * non-sparse --- i.e., in the case of libbfd writing
194 * an ELF object sections out-of-order but in a way
195 * the eventually results in a contiguous object or
196 * executable file, or some database extending a table
197 * space file. However, this is actually somewhat
198 * non-ideal if we are writing a sparse file such as
199 * qemu or KVM writing a raw image file that is going
200 * to stay fairly sparse, since it will end up
201 * fragmenting the file system's free space. Maybe we
202 * should have some hueristics or some way to allow
203 * userspace to pass a hint to file system,
204 * especially if the latter case turns out to be
207 ex = path[depth].p_ext;
209 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
210 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
212 if (block > ext_block)
213 return ext_pblk + (block - ext_block);
215 return ext_pblk - (ext_block - block);
218 /* it looks like index is empty;
219 * try to find starting block from index itself */
220 if (path[depth].p_bh)
221 return path[depth].p_bh->b_blocknr;
224 /* OK. use inode's group */
225 return ext4_inode_to_goal_block(inode);
229 * Allocation for a meta data block
232 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
233 struct ext4_ext_path *path,
234 struct ext4_extent *ex, int *err, unsigned int flags)
236 ext4_fsblk_t goal, newblock;
238 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
239 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
244 static inline int ext4_ext_space_block(struct inode *inode, int check)
248 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
249 / sizeof(struct ext4_extent);
250 #ifdef AGGRESSIVE_TEST
251 if (!check && size > 6)
257 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
261 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
262 / sizeof(struct ext4_extent_idx);
263 #ifdef AGGRESSIVE_TEST
264 if (!check && size > 5)
270 static inline int ext4_ext_space_root(struct inode *inode, int check)
274 size = sizeof(EXT4_I(inode)->i_data);
275 size -= sizeof(struct ext4_extent_header);
276 size /= sizeof(struct ext4_extent);
277 #ifdef AGGRESSIVE_TEST
278 if (!check && size > 3)
284 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
288 size = sizeof(EXT4_I(inode)->i_data);
289 size -= sizeof(struct ext4_extent_header);
290 size /= sizeof(struct ext4_extent_idx);
291 #ifdef AGGRESSIVE_TEST
292 if (!check && size > 4)
299 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
300 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
303 struct ext4_ext_path *path = *ppath;
304 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
306 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
307 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
308 EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
309 (nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
313 * Calculate the number of metadata blocks needed
314 * to allocate @blocks
315 * Worse case is one block per extent
317 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
319 struct ext4_inode_info *ei = EXT4_I(inode);
322 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
323 / sizeof(struct ext4_extent_idx));
326 * If the new delayed allocation block is contiguous with the
327 * previous da block, it can share index blocks with the
328 * previous block, so we only need to allocate a new index
329 * block every idxs leaf blocks. At ldxs**2 blocks, we need
330 * an additional index block, and at ldxs**3 blocks, yet
331 * another index blocks.
333 if (ei->i_da_metadata_calc_len &&
334 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
337 if ((ei->i_da_metadata_calc_len % idxs) == 0)
339 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
341 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
343 ei->i_da_metadata_calc_len = 0;
345 ei->i_da_metadata_calc_len++;
346 ei->i_da_metadata_calc_last_lblock++;
351 * In the worst case we need a new set of index blocks at
352 * every level of the inode's extent tree.
354 ei->i_da_metadata_calc_len = 1;
355 ei->i_da_metadata_calc_last_lblock = lblock;
356 return ext_depth(inode) + 1;
360 ext4_ext_max_entries(struct inode *inode, int depth)
364 if (depth == ext_depth(inode)) {
366 max = ext4_ext_space_root(inode, 1);
368 max = ext4_ext_space_root_idx(inode, 1);
371 max = ext4_ext_space_block(inode, 1);
373 max = ext4_ext_space_block_idx(inode, 1);
379 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
381 ext4_fsblk_t block = ext4_ext_pblock(ext);
382 int len = ext4_ext_get_actual_len(ext);
383 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
388 * - overflow/wrap-around
390 if (lblock + len <= lblock)
392 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
395 static int ext4_valid_extent_idx(struct inode *inode,
396 struct ext4_extent_idx *ext_idx)
398 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
400 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
403 static int ext4_valid_extent_entries(struct inode *inode,
404 struct ext4_extent_header *eh,
407 unsigned short entries;
408 if (eh->eh_entries == 0)
411 entries = le16_to_cpu(eh->eh_entries);
415 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
416 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
417 ext4_fsblk_t pblock = 0;
418 ext4_lblk_t lblock = 0;
419 ext4_lblk_t prev = 0;
422 if (!ext4_valid_extent(inode, ext))
425 /* Check for overlapping extents */
426 lblock = le32_to_cpu(ext->ee_block);
427 len = ext4_ext_get_actual_len(ext);
428 if ((lblock <= prev) && prev) {
429 pblock = ext4_ext_pblock(ext);
430 es->s_last_error_block = cpu_to_le64(pblock);
435 prev = lblock + len - 1;
438 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
440 if (!ext4_valid_extent_idx(inode, ext_idx))
449 static int __ext4_ext_check(const char *function, unsigned int line,
450 struct inode *inode, struct ext4_extent_header *eh,
451 int depth, ext4_fsblk_t pblk)
453 const char *error_msg;
454 int max = 0, err = -EFSCORRUPTED;
456 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
457 error_msg = "invalid magic";
460 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
461 error_msg = "unexpected eh_depth";
464 if (unlikely(eh->eh_max == 0)) {
465 error_msg = "invalid eh_max";
468 max = ext4_ext_max_entries(inode, depth);
469 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
470 error_msg = "too large eh_max";
473 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
474 error_msg = "invalid eh_entries";
477 if (!ext4_valid_extent_entries(inode, eh, depth)) {
478 error_msg = "invalid extent entries";
481 if (unlikely(depth > 32)) {
482 error_msg = "too large eh_depth";
485 /* Verify checksum on non-root extent tree nodes */
486 if (ext_depth(inode) != depth &&
487 !ext4_extent_block_csum_verify(inode, eh)) {
488 error_msg = "extent tree corrupted";
495 ext4_set_errno(inode->i_sb, -err);
496 ext4_error_inode(inode, function, line, 0,
497 "pblk %llu bad header/extent: %s - magic %x, "
498 "entries %u, max %u(%u), depth %u(%u)",
499 (unsigned long long) pblk, error_msg,
500 le16_to_cpu(eh->eh_magic),
501 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
502 max, le16_to_cpu(eh->eh_depth), depth);
506 #define ext4_ext_check(inode, eh, depth, pblk) \
507 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
509 int ext4_ext_check_inode(struct inode *inode)
511 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
514 static struct buffer_head *
515 __read_extent_tree_block(const char *function, unsigned int line,
516 struct inode *inode, ext4_fsblk_t pblk, int depth,
519 struct buffer_head *bh;
522 bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
524 return ERR_PTR(-ENOMEM);
526 if (!bh_uptodate_or_lock(bh)) {
527 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
528 err = bh_submit_read(bh);
532 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
534 if (!ext4_has_feature_journal(inode->i_sb) ||
536 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum))) {
537 err = __ext4_ext_check(function, line, inode,
538 ext_block_hdr(bh), depth, pblk);
542 set_buffer_verified(bh);
544 * If this is a leaf block, cache all of its entries
546 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
547 struct ext4_extent_header *eh = ext_block_hdr(bh);
548 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
549 ext4_lblk_t prev = 0;
552 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
553 unsigned int status = EXTENT_STATUS_WRITTEN;
554 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
555 int len = ext4_ext_get_actual_len(ex);
557 if (prev && (prev != lblk))
558 ext4_es_cache_extent(inode, prev,
562 if (ext4_ext_is_unwritten(ex))
563 status = EXTENT_STATUS_UNWRITTEN;
564 ext4_es_cache_extent(inode, lblk, len,
565 ext4_ext_pblock(ex), status);
576 #define read_extent_tree_block(inode, pblk, depth, flags) \
577 __read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
581 * This function is called to cache a file's extent information in the
584 int ext4_ext_precache(struct inode *inode)
586 struct ext4_inode_info *ei = EXT4_I(inode);
587 struct ext4_ext_path *path = NULL;
588 struct buffer_head *bh;
589 int i = 0, depth, ret = 0;
591 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
592 return 0; /* not an extent-mapped inode */
594 down_read(&ei->i_data_sem);
595 depth = ext_depth(inode);
597 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
600 up_read(&ei->i_data_sem);
604 /* Don't cache anything if there are no external extent blocks */
607 path[0].p_hdr = ext_inode_hdr(inode);
608 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
611 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
614 * If this is a leaf block or we've reached the end of
615 * the index block, go up
618 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
619 brelse(path[i].p_bh);
624 bh = read_extent_tree_block(inode,
625 ext4_idx_pblock(path[i].p_idx++),
627 EXT4_EX_FORCE_CACHE);
634 path[i].p_hdr = ext_block_hdr(bh);
635 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
637 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
639 up_read(&ei->i_data_sem);
640 ext4_ext_drop_refs(path);
646 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
648 int k, l = path->p_depth;
651 for (k = 0; k <= l; k++, path++) {
653 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
654 ext4_idx_pblock(path->p_idx));
655 } else if (path->p_ext) {
656 ext_debug(" %d:[%d]%d:%llu ",
657 le32_to_cpu(path->p_ext->ee_block),
658 ext4_ext_is_unwritten(path->p_ext),
659 ext4_ext_get_actual_len(path->p_ext),
660 ext4_ext_pblock(path->p_ext));
667 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
669 int depth = ext_depth(inode);
670 struct ext4_extent_header *eh;
671 struct ext4_extent *ex;
677 eh = path[depth].p_hdr;
678 ex = EXT_FIRST_EXTENT(eh);
680 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
682 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
683 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
684 ext4_ext_is_unwritten(ex),
685 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
690 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
691 ext4_fsblk_t newblock, int level)
693 int depth = ext_depth(inode);
694 struct ext4_extent *ex;
696 if (depth != level) {
697 struct ext4_extent_idx *idx;
698 idx = path[level].p_idx;
699 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
700 ext_debug("%d: move %d:%llu in new index %llu\n", level,
701 le32_to_cpu(idx->ei_block),
702 ext4_idx_pblock(idx),
710 ex = path[depth].p_ext;
711 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
712 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
713 le32_to_cpu(ex->ee_block),
715 ext4_ext_is_unwritten(ex),
716 ext4_ext_get_actual_len(ex),
723 #define ext4_ext_show_path(inode, path)
724 #define ext4_ext_show_leaf(inode, path)
725 #define ext4_ext_show_move(inode, path, newblock, level)
728 void ext4_ext_drop_refs(struct ext4_ext_path *path)
734 depth = path->p_depth;
735 for (i = 0; i <= depth; i++, path++)
743 * ext4_ext_binsearch_idx:
744 * binary search for the closest index of the given block
745 * the header must be checked before calling this
748 ext4_ext_binsearch_idx(struct inode *inode,
749 struct ext4_ext_path *path, ext4_lblk_t block)
751 struct ext4_extent_header *eh = path->p_hdr;
752 struct ext4_extent_idx *r, *l, *m;
755 ext_debug("binsearch for %u(idx): ", block);
757 l = EXT_FIRST_INDEX(eh) + 1;
758 r = EXT_LAST_INDEX(eh);
761 if (block < le32_to_cpu(m->ei_block))
765 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
766 m, le32_to_cpu(m->ei_block),
767 r, le32_to_cpu(r->ei_block));
771 ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
772 ext4_idx_pblock(path->p_idx));
774 #ifdef CHECK_BINSEARCH
776 struct ext4_extent_idx *chix, *ix;
779 chix = ix = EXT_FIRST_INDEX(eh);
780 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
782 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
783 printk(KERN_DEBUG "k=%d, ix=0x%p, "
785 ix, EXT_FIRST_INDEX(eh));
786 printk(KERN_DEBUG "%u <= %u\n",
787 le32_to_cpu(ix->ei_block),
788 le32_to_cpu(ix[-1].ei_block));
790 BUG_ON(k && le32_to_cpu(ix->ei_block)
791 <= le32_to_cpu(ix[-1].ei_block));
792 if (block < le32_to_cpu(ix->ei_block))
796 BUG_ON(chix != path->p_idx);
803 * ext4_ext_binsearch:
804 * binary search for closest extent of the given block
805 * the header must be checked before calling this
808 ext4_ext_binsearch(struct inode *inode,
809 struct ext4_ext_path *path, ext4_lblk_t block)
811 struct ext4_extent_header *eh = path->p_hdr;
812 struct ext4_extent *r, *l, *m;
814 if (eh->eh_entries == 0) {
816 * this leaf is empty:
817 * we get such a leaf in split/add case
822 ext_debug("binsearch for %u: ", block);
824 l = EXT_FIRST_EXTENT(eh) + 1;
825 r = EXT_LAST_EXTENT(eh);
829 if (block < le32_to_cpu(m->ee_block))
833 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
834 m, le32_to_cpu(m->ee_block),
835 r, le32_to_cpu(r->ee_block));
839 ext_debug(" -> %d:%llu:[%d]%d ",
840 le32_to_cpu(path->p_ext->ee_block),
841 ext4_ext_pblock(path->p_ext),
842 ext4_ext_is_unwritten(path->p_ext),
843 ext4_ext_get_actual_len(path->p_ext));
845 #ifdef CHECK_BINSEARCH
847 struct ext4_extent *chex, *ex;
850 chex = ex = EXT_FIRST_EXTENT(eh);
851 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
852 BUG_ON(k && le32_to_cpu(ex->ee_block)
853 <= le32_to_cpu(ex[-1].ee_block));
854 if (block < le32_to_cpu(ex->ee_block))
858 BUG_ON(chex != path->p_ext);
864 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
866 struct ext4_extent_header *eh;
868 eh = ext_inode_hdr(inode);
871 eh->eh_magic = EXT4_EXT_MAGIC;
872 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
873 ext4_mark_inode_dirty(handle, inode);
877 struct ext4_ext_path *
878 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
879 struct ext4_ext_path **orig_path, int flags)
881 struct ext4_extent_header *eh;
882 struct buffer_head *bh;
883 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
884 short int depth, i, ppos = 0;
887 eh = ext_inode_hdr(inode);
888 depth = ext_depth(inode);
889 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
890 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
897 ext4_ext_drop_refs(path);
898 if (depth > path[0].p_maxdepth) {
900 *orig_path = path = NULL;
904 /* account possible depth increase */
905 path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
908 return ERR_PTR(-ENOMEM);
909 path[0].p_maxdepth = depth + 1;
915 /* walk through the tree */
917 ext_debug("depth %d: num %d, max %d\n",
918 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
920 ext4_ext_binsearch_idx(inode, path + ppos, block);
921 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
922 path[ppos].p_depth = i;
923 path[ppos].p_ext = NULL;
925 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
932 eh = ext_block_hdr(bh);
934 path[ppos].p_bh = bh;
935 path[ppos].p_hdr = eh;
938 path[ppos].p_depth = i;
939 path[ppos].p_ext = NULL;
940 path[ppos].p_idx = NULL;
943 ext4_ext_binsearch(inode, path + ppos, block);
944 /* if not an empty leaf */
945 if (path[ppos].p_ext)
946 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
948 ext4_ext_show_path(inode, path);
953 ext4_ext_drop_refs(path);
961 * ext4_ext_insert_index:
962 * insert new index [@logical;@ptr] into the block at @curp;
963 * check where to insert: before @curp or after @curp
965 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
966 struct ext4_ext_path *curp,
967 int logical, ext4_fsblk_t ptr)
969 struct ext4_extent_idx *ix;
972 err = ext4_ext_get_access(handle, inode, curp);
976 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
977 EXT4_ERROR_INODE(inode,
978 "logical %d == ei_block %d!",
979 logical, le32_to_cpu(curp->p_idx->ei_block));
980 return -EFSCORRUPTED;
983 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
984 >= le16_to_cpu(curp->p_hdr->eh_max))) {
985 EXT4_ERROR_INODE(inode,
986 "eh_entries %d >= eh_max %d!",
987 le16_to_cpu(curp->p_hdr->eh_entries),
988 le16_to_cpu(curp->p_hdr->eh_max));
989 return -EFSCORRUPTED;
992 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
994 ext_debug("insert new index %d after: %llu\n", logical, ptr);
995 ix = curp->p_idx + 1;
998 ext_debug("insert new index %d before: %llu\n", logical, ptr);
1002 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1005 ext_debug("insert new index %d: "
1006 "move %d indices from 0x%p to 0x%p\n",
1007 logical, len, ix, ix + 1);
1008 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1011 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1012 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1013 return -EFSCORRUPTED;
1016 ix->ei_block = cpu_to_le32(logical);
1017 ext4_idx_store_pblock(ix, ptr);
1018 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1020 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1021 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1022 return -EFSCORRUPTED;
1025 err = ext4_ext_dirty(handle, inode, curp);
1026 ext4_std_error(inode->i_sb, err);
1033 * inserts new subtree into the path, using free index entry
1035 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1036 * - makes decision where to split
1037 * - moves remaining extents and index entries (right to the split point)
1038 * into the newly allocated blocks
1039 * - initializes subtree
1041 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1043 struct ext4_ext_path *path,
1044 struct ext4_extent *newext, int at)
1046 struct buffer_head *bh = NULL;
1047 int depth = ext_depth(inode);
1048 struct ext4_extent_header *neh;
1049 struct ext4_extent_idx *fidx;
1050 int i = at, k, m, a;
1051 ext4_fsblk_t newblock, oldblock;
1053 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1055 size_t ext_size = 0;
1057 /* make decision: where to split? */
1058 /* FIXME: now decision is simplest: at current extent */
1060 /* if current leaf will be split, then we should use
1061 * border from split point */
1062 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1063 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1064 return -EFSCORRUPTED;
1066 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1067 border = path[depth].p_ext[1].ee_block;
1068 ext_debug("leaf will be split."
1069 " next leaf starts at %d\n",
1070 le32_to_cpu(border));
1072 border = newext->ee_block;
1073 ext_debug("leaf will be added."
1074 " next leaf starts at %d\n",
1075 le32_to_cpu(border));
1079 * If error occurs, then we break processing
1080 * and mark filesystem read-only. index won't
1081 * be inserted and tree will be in consistent
1082 * state. Next mount will repair buffers too.
1086 * Get array to track all allocated blocks.
1087 * We need this to handle errors and free blocks
1090 ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), GFP_NOFS);
1094 /* allocate all needed blocks */
1095 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1096 for (a = 0; a < depth - at; a++) {
1097 newblock = ext4_ext_new_meta_block(handle, inode, path,
1098 newext, &err, flags);
1101 ablocks[a] = newblock;
1104 /* initialize new leaf */
1105 newblock = ablocks[--a];
1106 if (unlikely(newblock == 0)) {
1107 EXT4_ERROR_INODE(inode, "newblock == 0!");
1108 err = -EFSCORRUPTED;
1111 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1112 if (unlikely(!bh)) {
1118 err = ext4_journal_get_create_access(handle, bh);
1122 neh = ext_block_hdr(bh);
1123 neh->eh_entries = 0;
1124 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1125 neh->eh_magic = EXT4_EXT_MAGIC;
1128 /* move remainder of path[depth] to the new leaf */
1129 if (unlikely(path[depth].p_hdr->eh_entries !=
1130 path[depth].p_hdr->eh_max)) {
1131 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1132 path[depth].p_hdr->eh_entries,
1133 path[depth].p_hdr->eh_max);
1134 err = -EFSCORRUPTED;
1137 /* start copy from next extent */
1138 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1139 ext4_ext_show_move(inode, path, newblock, depth);
1141 struct ext4_extent *ex;
1142 ex = EXT_FIRST_EXTENT(neh);
1143 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1144 le16_add_cpu(&neh->eh_entries, m);
1147 /* zero out unused area in the extent block */
1148 ext_size = sizeof(struct ext4_extent_header) +
1149 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1150 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1151 ext4_extent_block_csum_set(inode, neh);
1152 set_buffer_uptodate(bh);
1155 err = ext4_handle_dirty_metadata(handle, inode, bh);
1161 /* correct old leaf */
1163 err = ext4_ext_get_access(handle, inode, path + depth);
1166 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1167 err = ext4_ext_dirty(handle, inode, path + depth);
1173 /* create intermediate indexes */
1175 if (unlikely(k < 0)) {
1176 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1177 err = -EFSCORRUPTED;
1181 ext_debug("create %d intermediate indices\n", k);
1182 /* insert new index into current index block */
1183 /* current depth stored in i var */
1186 oldblock = newblock;
1187 newblock = ablocks[--a];
1188 bh = sb_getblk(inode->i_sb, newblock);
1189 if (unlikely(!bh)) {
1195 err = ext4_journal_get_create_access(handle, bh);
1199 neh = ext_block_hdr(bh);
1200 neh->eh_entries = cpu_to_le16(1);
1201 neh->eh_magic = EXT4_EXT_MAGIC;
1202 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1203 neh->eh_depth = cpu_to_le16(depth - i);
1204 fidx = EXT_FIRST_INDEX(neh);
1205 fidx->ei_block = border;
1206 ext4_idx_store_pblock(fidx, oldblock);
1208 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1209 i, newblock, le32_to_cpu(border), oldblock);
1211 /* move remainder of path[i] to the new index block */
1212 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1213 EXT_LAST_INDEX(path[i].p_hdr))) {
1214 EXT4_ERROR_INODE(inode,
1215 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1216 le32_to_cpu(path[i].p_ext->ee_block));
1217 err = -EFSCORRUPTED;
1220 /* start copy indexes */
1221 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1222 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1223 EXT_MAX_INDEX(path[i].p_hdr));
1224 ext4_ext_show_move(inode, path, newblock, i);
1226 memmove(++fidx, path[i].p_idx,
1227 sizeof(struct ext4_extent_idx) * m);
1228 le16_add_cpu(&neh->eh_entries, m);
1230 /* zero out unused area in the extent block */
1231 ext_size = sizeof(struct ext4_extent_header) +
1232 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1233 memset(bh->b_data + ext_size, 0,
1234 inode->i_sb->s_blocksize - ext_size);
1235 ext4_extent_block_csum_set(inode, neh);
1236 set_buffer_uptodate(bh);
1239 err = ext4_handle_dirty_metadata(handle, inode, bh);
1245 /* correct old index */
1247 err = ext4_ext_get_access(handle, inode, path + i);
1250 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1251 err = ext4_ext_dirty(handle, inode, path + i);
1259 /* insert new index */
1260 err = ext4_ext_insert_index(handle, inode, path + at,
1261 le32_to_cpu(border), newblock);
1265 if (buffer_locked(bh))
1271 /* free all allocated blocks in error case */
1272 for (i = 0; i < depth; i++) {
1275 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1276 EXT4_FREE_BLOCKS_METADATA);
1285 * ext4_ext_grow_indepth:
1286 * implements tree growing procedure:
1287 * - allocates new block
1288 * - moves top-level data (index block or leaf) into the new block
1289 * - initializes new top-level, creating index that points to the
1290 * just created block
1292 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1295 struct ext4_extent_header *neh;
1296 struct buffer_head *bh;
1297 ext4_fsblk_t newblock, goal = 0;
1298 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1300 size_t ext_size = 0;
1302 /* Try to prepend new index to old one */
1303 if (ext_depth(inode))
1304 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1305 if (goal > le32_to_cpu(es->s_first_data_block)) {
1306 flags |= EXT4_MB_HINT_TRY_GOAL;
1309 goal = ext4_inode_to_goal_block(inode);
1310 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1315 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1320 err = ext4_journal_get_create_access(handle, bh);
1326 ext_size = sizeof(EXT4_I(inode)->i_data);
1327 /* move top-level index/leaf into new block */
1328 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1329 /* zero out unused area in the extent block */
1330 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1332 /* set size of new block */
1333 neh = ext_block_hdr(bh);
1334 /* old root could have indexes or leaves
1335 * so calculate e_max right way */
1336 if (ext_depth(inode))
1337 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1339 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1340 neh->eh_magic = EXT4_EXT_MAGIC;
1341 ext4_extent_block_csum_set(inode, neh);
1342 set_buffer_uptodate(bh);
1345 err = ext4_handle_dirty_metadata(handle, inode, bh);
1349 /* Update top-level index: num,max,pointer */
1350 neh = ext_inode_hdr(inode);
1351 neh->eh_entries = cpu_to_le16(1);
1352 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1353 if (neh->eh_depth == 0) {
1354 /* Root extent block becomes index block */
1355 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1356 EXT_FIRST_INDEX(neh)->ei_block =
1357 EXT_FIRST_EXTENT(neh)->ee_block;
1359 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1360 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1361 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1362 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1364 le16_add_cpu(&neh->eh_depth, 1);
1365 ext4_mark_inode_dirty(handle, inode);
1373 * ext4_ext_create_new_leaf:
1374 * finds empty index and adds new leaf.
1375 * if no free index is found, then it requests in-depth growing.
1377 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1378 unsigned int mb_flags,
1379 unsigned int gb_flags,
1380 struct ext4_ext_path **ppath,
1381 struct ext4_extent *newext)
1383 struct ext4_ext_path *path = *ppath;
1384 struct ext4_ext_path *curp;
1385 int depth, i, err = 0;
1388 i = depth = ext_depth(inode);
1390 /* walk up to the tree and look for free index entry */
1391 curp = path + depth;
1392 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1397 /* we use already allocated block for index block,
1398 * so subsequent data blocks should be contiguous */
1399 if (EXT_HAS_FREE_INDEX(curp)) {
1400 /* if we found index with free entry, then use that
1401 * entry: create all needed subtree and add new leaf */
1402 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1407 path = ext4_find_extent(inode,
1408 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1411 err = PTR_ERR(path);
1413 /* tree is full, time to grow in depth */
1414 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1419 path = ext4_find_extent(inode,
1420 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1423 err = PTR_ERR(path);
1428 * only first (depth 0 -> 1) produces free space;
1429 * in all other cases we have to split the grown tree
1431 depth = ext_depth(inode);
1432 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1433 /* now we need to split */
1443 * search the closest allocated block to the left for *logical
1444 * and returns it at @logical + it's physical address at @phys
1445 * if *logical is the smallest allocated block, the function
1446 * returns 0 at @phys
1447 * return value contains 0 (success) or error code
1449 static int ext4_ext_search_left(struct inode *inode,
1450 struct ext4_ext_path *path,
1451 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1453 struct ext4_extent_idx *ix;
1454 struct ext4_extent *ex;
1457 if (unlikely(path == NULL)) {
1458 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1459 return -EFSCORRUPTED;
1461 depth = path->p_depth;
1464 if (depth == 0 && path->p_ext == NULL)
1467 /* usually extent in the path covers blocks smaller
1468 * then *logical, but it can be that extent is the
1469 * first one in the file */
1471 ex = path[depth].p_ext;
1472 ee_len = ext4_ext_get_actual_len(ex);
1473 if (*logical < le32_to_cpu(ex->ee_block)) {
1474 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1475 EXT4_ERROR_INODE(inode,
1476 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1477 *logical, le32_to_cpu(ex->ee_block));
1478 return -EFSCORRUPTED;
1480 while (--depth >= 0) {
1481 ix = path[depth].p_idx;
1482 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1483 EXT4_ERROR_INODE(inode,
1484 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1485 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1486 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1487 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1489 return -EFSCORRUPTED;
1495 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1496 EXT4_ERROR_INODE(inode,
1497 "logical %d < ee_block %d + ee_len %d!",
1498 *logical, le32_to_cpu(ex->ee_block), ee_len);
1499 return -EFSCORRUPTED;
1502 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1503 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1508 * search the closest allocated block to the right for *logical
1509 * and returns it at @logical + it's physical address at @phys
1510 * if *logical is the largest allocated block, the function
1511 * returns 0 at @phys
1512 * return value contains 0 (success) or error code
1514 static int ext4_ext_search_right(struct inode *inode,
1515 struct ext4_ext_path *path,
1516 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1517 struct ext4_extent **ret_ex)
1519 struct buffer_head *bh = NULL;
1520 struct ext4_extent_header *eh;
1521 struct ext4_extent_idx *ix;
1522 struct ext4_extent *ex;
1524 int depth; /* Note, NOT eh_depth; depth from top of tree */
1527 if (unlikely(path == NULL)) {
1528 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1529 return -EFSCORRUPTED;
1531 depth = path->p_depth;
1534 if (depth == 0 && path->p_ext == NULL)
1537 /* usually extent in the path covers blocks smaller
1538 * then *logical, but it can be that extent is the
1539 * first one in the file */
1541 ex = path[depth].p_ext;
1542 ee_len = ext4_ext_get_actual_len(ex);
1543 if (*logical < le32_to_cpu(ex->ee_block)) {
1544 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1545 EXT4_ERROR_INODE(inode,
1546 "first_extent(path[%d].p_hdr) != ex",
1548 return -EFSCORRUPTED;
1550 while (--depth >= 0) {
1551 ix = path[depth].p_idx;
1552 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1553 EXT4_ERROR_INODE(inode,
1554 "ix != EXT_FIRST_INDEX *logical %d!",
1556 return -EFSCORRUPTED;
1562 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1563 EXT4_ERROR_INODE(inode,
1564 "logical %d < ee_block %d + ee_len %d!",
1565 *logical, le32_to_cpu(ex->ee_block), ee_len);
1566 return -EFSCORRUPTED;
1569 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1570 /* next allocated block in this leaf */
1575 /* go up and search for index to the right */
1576 while (--depth >= 0) {
1577 ix = path[depth].p_idx;
1578 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1582 /* we've gone up to the root and found no index to the right */
1586 /* we've found index to the right, let's
1587 * follow it and find the closest allocated
1588 * block to the right */
1590 block = ext4_idx_pblock(ix);
1591 while (++depth < path->p_depth) {
1592 /* subtract from p_depth to get proper eh_depth */
1593 bh = read_extent_tree_block(inode, block,
1594 path->p_depth - depth, 0);
1597 eh = ext_block_hdr(bh);
1598 ix = EXT_FIRST_INDEX(eh);
1599 block = ext4_idx_pblock(ix);
1603 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1606 eh = ext_block_hdr(bh);
1607 ex = EXT_FIRST_EXTENT(eh);
1609 *logical = le32_to_cpu(ex->ee_block);
1610 *phys = ext4_ext_pblock(ex);
1618 * ext4_ext_next_allocated_block:
1619 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1620 * NOTE: it considers block number from index entry as
1621 * allocated block. Thus, index entries have to be consistent
1625 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1629 BUG_ON(path == NULL);
1630 depth = path->p_depth;
1632 if (depth == 0 && path->p_ext == NULL)
1633 return EXT_MAX_BLOCKS;
1635 while (depth >= 0) {
1636 if (depth == path->p_depth) {
1638 if (path[depth].p_ext &&
1639 path[depth].p_ext !=
1640 EXT_LAST_EXTENT(path[depth].p_hdr))
1641 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1644 if (path[depth].p_idx !=
1645 EXT_LAST_INDEX(path[depth].p_hdr))
1646 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1651 return EXT_MAX_BLOCKS;
1655 * ext4_ext_next_leaf_block:
1656 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1658 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1662 BUG_ON(path == NULL);
1663 depth = path->p_depth;
1665 /* zero-tree has no leaf blocks at all */
1667 return EXT_MAX_BLOCKS;
1669 /* go to index block */
1672 while (depth >= 0) {
1673 if (path[depth].p_idx !=
1674 EXT_LAST_INDEX(path[depth].p_hdr))
1675 return (ext4_lblk_t)
1676 le32_to_cpu(path[depth].p_idx[1].ei_block);
1680 return EXT_MAX_BLOCKS;
1684 * ext4_ext_correct_indexes:
1685 * if leaf gets modified and modified extent is first in the leaf,
1686 * then we have to correct all indexes above.
1687 * TODO: do we need to correct tree in all cases?
1689 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1690 struct ext4_ext_path *path)
1692 struct ext4_extent_header *eh;
1693 int depth = ext_depth(inode);
1694 struct ext4_extent *ex;
1698 eh = path[depth].p_hdr;
1699 ex = path[depth].p_ext;
1701 if (unlikely(ex == NULL || eh == NULL)) {
1702 EXT4_ERROR_INODE(inode,
1703 "ex %p == NULL or eh %p == NULL", ex, eh);
1704 return -EFSCORRUPTED;
1708 /* there is no tree at all */
1712 if (ex != EXT_FIRST_EXTENT(eh)) {
1713 /* we correct tree if first leaf got modified only */
1718 * TODO: we need correction if border is smaller than current one
1721 border = path[depth].p_ext->ee_block;
1722 err = ext4_ext_get_access(handle, inode, path + k);
1725 path[k].p_idx->ei_block = border;
1726 err = ext4_ext_dirty(handle, inode, path + k);
1731 /* change all left-side indexes */
1732 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1734 err = ext4_ext_get_access(handle, inode, path + k);
1737 path[k].p_idx->ei_block = border;
1738 err = ext4_ext_dirty(handle, inode, path + k);
1747 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1748 struct ext4_extent *ex2)
1750 unsigned short ext1_ee_len, ext2_ee_len;
1752 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1755 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1756 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1758 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1759 le32_to_cpu(ex2->ee_block))
1763 * To allow future support for preallocated extents to be added
1764 * as an RO_COMPAT feature, refuse to merge to extents if
1765 * this can result in the top bit of ee_len being set.
1767 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1770 if (ext4_ext_is_unwritten(ex1) &&
1771 ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)
1773 #ifdef AGGRESSIVE_TEST
1774 if (ext1_ee_len >= 4)
1778 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1784 * This function tries to merge the "ex" extent to the next extent in the tree.
1785 * It always tries to merge towards right. If you want to merge towards
1786 * left, pass "ex - 1" as argument instead of "ex".
1787 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1788 * 1 if they got merged.
1790 static int ext4_ext_try_to_merge_right(struct inode *inode,
1791 struct ext4_ext_path *path,
1792 struct ext4_extent *ex)
1794 struct ext4_extent_header *eh;
1795 unsigned int depth, len;
1796 int merge_done = 0, unwritten;
1798 depth = ext_depth(inode);
1799 BUG_ON(path[depth].p_hdr == NULL);
1800 eh = path[depth].p_hdr;
1802 while (ex < EXT_LAST_EXTENT(eh)) {
1803 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1805 /* merge with next extent! */
1806 unwritten = ext4_ext_is_unwritten(ex);
1807 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1808 + ext4_ext_get_actual_len(ex + 1));
1810 ext4_ext_mark_unwritten(ex);
1812 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1813 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1814 * sizeof(struct ext4_extent);
1815 memmove(ex + 1, ex + 2, len);
1817 le16_add_cpu(&eh->eh_entries, -1);
1819 WARN_ON(eh->eh_entries == 0);
1820 if (!eh->eh_entries)
1821 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1828 * This function does a very simple check to see if we can collapse
1829 * an extent tree with a single extent tree leaf block into the inode.
1831 static void ext4_ext_try_to_merge_up(handle_t *handle,
1832 struct inode *inode,
1833 struct ext4_ext_path *path)
1836 unsigned max_root = ext4_ext_space_root(inode, 0);
1839 if ((path[0].p_depth != 1) ||
1840 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1841 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1845 * We need to modify the block allocation bitmap and the block
1846 * group descriptor to release the extent tree block. If we
1847 * can't get the journal credits, give up.
1849 if (ext4_journal_extend(handle, 2,
1850 ext4_free_metadata_revoke_credits(inode->i_sb, 1)))
1854 * Copy the extent data up to the inode
1856 blk = ext4_idx_pblock(path[0].p_idx);
1857 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1858 sizeof(struct ext4_extent_idx);
1859 s += sizeof(struct ext4_extent_header);
1861 path[1].p_maxdepth = path[0].p_maxdepth;
1862 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1863 path[0].p_depth = 0;
1864 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1865 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1866 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1868 brelse(path[1].p_bh);
1869 ext4_free_blocks(handle, inode, NULL, blk, 1,
1870 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1874 * This function tries to merge the @ex extent to neighbours in the tree.
1875 * return 1 if merge left else 0.
1877 static void ext4_ext_try_to_merge(handle_t *handle,
1878 struct inode *inode,
1879 struct ext4_ext_path *path,
1880 struct ext4_extent *ex) {
1881 struct ext4_extent_header *eh;
1885 depth = ext_depth(inode);
1886 BUG_ON(path[depth].p_hdr == NULL);
1887 eh = path[depth].p_hdr;
1889 if (ex > EXT_FIRST_EXTENT(eh))
1890 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1893 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1895 ext4_ext_try_to_merge_up(handle, inode, path);
1899 * check if a portion of the "newext" extent overlaps with an
1902 * If there is an overlap discovered, it updates the length of the newext
1903 * such that there will be no overlap, and then returns 1.
1904 * If there is no overlap found, it returns 0.
1906 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1907 struct inode *inode,
1908 struct ext4_extent *newext,
1909 struct ext4_ext_path *path)
1912 unsigned int depth, len1;
1913 unsigned int ret = 0;
1915 b1 = le32_to_cpu(newext->ee_block);
1916 len1 = ext4_ext_get_actual_len(newext);
1917 depth = ext_depth(inode);
1918 if (!path[depth].p_ext)
1920 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1923 * get the next allocated block if the extent in the path
1924 * is before the requested block(s)
1927 b2 = ext4_ext_next_allocated_block(path);
1928 if (b2 == EXT_MAX_BLOCKS)
1930 b2 = EXT4_LBLK_CMASK(sbi, b2);
1933 /* check for wrap through zero on extent logical start block*/
1934 if (b1 + len1 < b1) {
1935 len1 = EXT_MAX_BLOCKS - b1;
1936 newext->ee_len = cpu_to_le16(len1);
1940 /* check for overlap */
1941 if (b1 + len1 > b2) {
1942 newext->ee_len = cpu_to_le16(b2 - b1);
1950 * ext4_ext_insert_extent:
1951 * tries to merge requsted extent into the existing extent or
1952 * inserts requested extent as new one into the tree,
1953 * creating new leaf in the no-space case.
1955 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1956 struct ext4_ext_path **ppath,
1957 struct ext4_extent *newext, int gb_flags)
1959 struct ext4_ext_path *path = *ppath;
1960 struct ext4_extent_header *eh;
1961 struct ext4_extent *ex, *fex;
1962 struct ext4_extent *nearex; /* nearest extent */
1963 struct ext4_ext_path *npath = NULL;
1964 int depth, len, err;
1966 int mb_flags = 0, unwritten;
1968 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1969 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1970 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1971 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1972 return -EFSCORRUPTED;
1974 depth = ext_depth(inode);
1975 ex = path[depth].p_ext;
1976 eh = path[depth].p_hdr;
1977 if (unlikely(path[depth].p_hdr == NULL)) {
1978 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1979 return -EFSCORRUPTED;
1982 /* try to insert block into found extent and return */
1983 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1986 * Try to see whether we should rather test the extent on
1987 * right from ex, or from the left of ex. This is because
1988 * ext4_find_extent() can return either extent on the
1989 * left, or on the right from the searched position. This
1990 * will make merging more effective.
1992 if (ex < EXT_LAST_EXTENT(eh) &&
1993 (le32_to_cpu(ex->ee_block) +
1994 ext4_ext_get_actual_len(ex) <
1995 le32_to_cpu(newext->ee_block))) {
1998 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
1999 (le32_to_cpu(newext->ee_block) +
2000 ext4_ext_get_actual_len(newext) <
2001 le32_to_cpu(ex->ee_block)))
2004 /* Try to append newex to the ex */
2005 if (ext4_can_extents_be_merged(inode, ex, newext)) {
2006 ext_debug("append [%d]%d block to %u:[%d]%d"
2008 ext4_ext_is_unwritten(newext),
2009 ext4_ext_get_actual_len(newext),
2010 le32_to_cpu(ex->ee_block),
2011 ext4_ext_is_unwritten(ex),
2012 ext4_ext_get_actual_len(ex),
2013 ext4_ext_pblock(ex));
2014 err = ext4_ext_get_access(handle, inode,
2018 unwritten = ext4_ext_is_unwritten(ex);
2019 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2020 + ext4_ext_get_actual_len(newext));
2022 ext4_ext_mark_unwritten(ex);
2023 eh = path[depth].p_hdr;
2029 /* Try to prepend newex to the ex */
2030 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2031 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2033 le32_to_cpu(newext->ee_block),
2034 ext4_ext_is_unwritten(newext),
2035 ext4_ext_get_actual_len(newext),
2036 le32_to_cpu(ex->ee_block),
2037 ext4_ext_is_unwritten(ex),
2038 ext4_ext_get_actual_len(ex),
2039 ext4_ext_pblock(ex));
2040 err = ext4_ext_get_access(handle, inode,
2045 unwritten = ext4_ext_is_unwritten(ex);
2046 ex->ee_block = newext->ee_block;
2047 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2048 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2049 + ext4_ext_get_actual_len(newext));
2051 ext4_ext_mark_unwritten(ex);
2052 eh = path[depth].p_hdr;
2058 depth = ext_depth(inode);
2059 eh = path[depth].p_hdr;
2060 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2063 /* probably next leaf has space for us? */
2064 fex = EXT_LAST_EXTENT(eh);
2065 next = EXT_MAX_BLOCKS;
2066 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2067 next = ext4_ext_next_leaf_block(path);
2068 if (next != EXT_MAX_BLOCKS) {
2069 ext_debug("next leaf block - %u\n", next);
2070 BUG_ON(npath != NULL);
2071 npath = ext4_find_extent(inode, next, NULL, 0);
2073 return PTR_ERR(npath);
2074 BUG_ON(npath->p_depth != path->p_depth);
2075 eh = npath[depth].p_hdr;
2076 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2077 ext_debug("next leaf isn't full(%d)\n",
2078 le16_to_cpu(eh->eh_entries));
2082 ext_debug("next leaf has no free space(%d,%d)\n",
2083 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2087 * There is no free space in the found leaf.
2088 * We're gonna add a new leaf in the tree.
2090 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2091 mb_flags |= EXT4_MB_USE_RESERVED;
2092 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2096 depth = ext_depth(inode);
2097 eh = path[depth].p_hdr;
2100 nearex = path[depth].p_ext;
2102 err = ext4_ext_get_access(handle, inode, path + depth);
2107 /* there is no extent in this leaf, create first one */
2108 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
2109 le32_to_cpu(newext->ee_block),
2110 ext4_ext_pblock(newext),
2111 ext4_ext_is_unwritten(newext),
2112 ext4_ext_get_actual_len(newext));
2113 nearex = EXT_FIRST_EXTENT(eh);
2115 if (le32_to_cpu(newext->ee_block)
2116 > le32_to_cpu(nearex->ee_block)) {
2118 ext_debug("insert %u:%llu:[%d]%d before: "
2120 le32_to_cpu(newext->ee_block),
2121 ext4_ext_pblock(newext),
2122 ext4_ext_is_unwritten(newext),
2123 ext4_ext_get_actual_len(newext),
2128 BUG_ON(newext->ee_block == nearex->ee_block);
2129 ext_debug("insert %u:%llu:[%d]%d after: "
2131 le32_to_cpu(newext->ee_block),
2132 ext4_ext_pblock(newext),
2133 ext4_ext_is_unwritten(newext),
2134 ext4_ext_get_actual_len(newext),
2137 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2139 ext_debug("insert %u:%llu:[%d]%d: "
2140 "move %d extents from 0x%p to 0x%p\n",
2141 le32_to_cpu(newext->ee_block),
2142 ext4_ext_pblock(newext),
2143 ext4_ext_is_unwritten(newext),
2144 ext4_ext_get_actual_len(newext),
2145 len, nearex, nearex + 1);
2146 memmove(nearex + 1, nearex,
2147 len * sizeof(struct ext4_extent));
2151 le16_add_cpu(&eh->eh_entries, 1);
2152 path[depth].p_ext = nearex;
2153 nearex->ee_block = newext->ee_block;
2154 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2155 nearex->ee_len = newext->ee_len;
2158 /* try to merge extents */
2159 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2160 ext4_ext_try_to_merge(handle, inode, path, nearex);
2163 /* time to correct all indexes above */
2164 err = ext4_ext_correct_indexes(handle, inode, path);
2168 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2171 ext4_ext_drop_refs(npath);
2176 static int ext4_fill_fiemap_extents(struct inode *inode,
2177 ext4_lblk_t block, ext4_lblk_t num,
2178 struct fiemap_extent_info *fieinfo)
2180 struct ext4_ext_path *path = NULL;
2181 struct ext4_extent *ex;
2182 struct extent_status es;
2183 ext4_lblk_t next, next_del, start = 0, end = 0;
2184 ext4_lblk_t last = block + num;
2185 int exists, depth = 0, err = 0;
2186 unsigned int flags = 0;
2187 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2189 while (block < last && block != EXT_MAX_BLOCKS) {
2191 /* find extent for this block */
2192 down_read(&EXT4_I(inode)->i_data_sem);
2194 path = ext4_find_extent(inode, block, &path, 0);
2196 up_read(&EXT4_I(inode)->i_data_sem);
2197 err = PTR_ERR(path);
2202 depth = ext_depth(inode);
2203 if (unlikely(path[depth].p_hdr == NULL)) {
2204 up_read(&EXT4_I(inode)->i_data_sem);
2205 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2206 err = -EFSCORRUPTED;
2209 ex = path[depth].p_ext;
2210 next = ext4_ext_next_allocated_block(path);
2215 /* there is no extent yet, so try to allocate
2216 * all requested space */
2219 } else if (le32_to_cpu(ex->ee_block) > block) {
2220 /* need to allocate space before found extent */
2222 end = le32_to_cpu(ex->ee_block);
2223 if (block + num < end)
2225 } else if (block >= le32_to_cpu(ex->ee_block)
2226 + ext4_ext_get_actual_len(ex)) {
2227 /* need to allocate space after found extent */
2232 } else if (block >= le32_to_cpu(ex->ee_block)) {
2234 * some part of requested space is covered
2238 end = le32_to_cpu(ex->ee_block)
2239 + ext4_ext_get_actual_len(ex);
2240 if (block + num < end)
2246 BUG_ON(end <= start);
2250 es.es_len = end - start;
2253 es.es_lblk = le32_to_cpu(ex->ee_block);
2254 es.es_len = ext4_ext_get_actual_len(ex);
2255 es.es_pblk = ext4_ext_pblock(ex);
2256 if (ext4_ext_is_unwritten(ex))
2257 flags |= FIEMAP_EXTENT_UNWRITTEN;
2261 * Find delayed extent and update es accordingly. We call
2262 * it even in !exists case to find out whether es is the
2263 * last existing extent or not.
2265 next_del = ext4_find_delayed_extent(inode, &es);
2266 if (!exists && next_del) {
2268 flags |= (FIEMAP_EXTENT_DELALLOC |
2269 FIEMAP_EXTENT_UNKNOWN);
2271 up_read(&EXT4_I(inode)->i_data_sem);
2273 if (unlikely(es.es_len == 0)) {
2274 EXT4_ERROR_INODE(inode, "es.es_len == 0");
2275 err = -EFSCORRUPTED;
2280 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2281 * we need to check next == EXT_MAX_BLOCKS because it is
2282 * possible that an extent is with unwritten and delayed
2283 * status due to when an extent is delayed allocated and
2284 * is allocated by fallocate status tree will track both of
2287 * So we could return a unwritten and delayed extent, and
2288 * its block is equal to 'next'.
2290 if (next == next_del && next == EXT_MAX_BLOCKS) {
2291 flags |= FIEMAP_EXTENT_LAST;
2292 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2293 next != EXT_MAX_BLOCKS)) {
2294 EXT4_ERROR_INODE(inode,
2295 "next extent == %u, next "
2296 "delalloc extent = %u",
2298 err = -EFSCORRUPTED;
2304 err = fiemap_fill_next_extent(fieinfo,
2305 (__u64)es.es_lblk << blksize_bits,
2306 (__u64)es.es_pblk << blksize_bits,
2307 (__u64)es.es_len << blksize_bits,
2317 block = es.es_lblk + es.es_len;
2320 ext4_ext_drop_refs(path);
2325 static int ext4_fill_es_cache_info(struct inode *inode,
2326 ext4_lblk_t block, ext4_lblk_t num,
2327 struct fiemap_extent_info *fieinfo)
2329 ext4_lblk_t next, end = block + num - 1;
2330 struct extent_status es;
2331 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2335 while (block <= end) {
2338 if (!ext4_es_lookup_extent(inode, block, &next, &es))
2340 if (ext4_es_is_unwritten(&es))
2341 flags |= FIEMAP_EXTENT_UNWRITTEN;
2342 if (ext4_es_is_delayed(&es))
2343 flags |= (FIEMAP_EXTENT_DELALLOC |
2344 FIEMAP_EXTENT_UNKNOWN);
2345 if (ext4_es_is_hole(&es))
2346 flags |= EXT4_FIEMAP_EXTENT_HOLE;
2348 flags |= FIEMAP_EXTENT_LAST;
2349 if (flags & (FIEMAP_EXTENT_DELALLOC|
2350 EXT4_FIEMAP_EXTENT_HOLE))
2353 es.es_pblk = ext4_es_pblock(&es);
2354 err = fiemap_fill_next_extent(fieinfo,
2355 (__u64)es.es_lblk << blksize_bits,
2356 (__u64)es.es_pblk << blksize_bits,
2357 (__u64)es.es_len << blksize_bits,
2372 * ext4_ext_determine_hole - determine hole around given block
2373 * @inode: inode we lookup in
2374 * @path: path in extent tree to @lblk
2375 * @lblk: pointer to logical block around which we want to determine hole
2377 * Determine hole length (and start if easily possible) around given logical
2378 * block. We don't try too hard to find the beginning of the hole but @path
2379 * actually points to extent before @lblk, we provide it.
2381 * The function returns the length of a hole starting at @lblk. We update @lblk
2382 * to the beginning of the hole if we managed to find it.
2384 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2385 struct ext4_ext_path *path,
2388 int depth = ext_depth(inode);
2389 struct ext4_extent *ex;
2392 ex = path[depth].p_ext;
2394 /* there is no extent yet, so gap is [0;-] */
2396 len = EXT_MAX_BLOCKS;
2397 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2398 len = le32_to_cpu(ex->ee_block) - *lblk;
2399 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2400 + ext4_ext_get_actual_len(ex)) {
2403 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2404 next = ext4_ext_next_allocated_block(path);
2405 BUG_ON(next == *lblk);
2414 * ext4_ext_put_gap_in_cache:
2415 * calculate boundaries of the gap that the requested block fits into
2416 * and cache this gap
2419 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2420 ext4_lblk_t hole_len)
2422 struct extent_status es;
2424 ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
2425 hole_start + hole_len - 1, &es);
2427 /* There's delayed extent containing lblock? */
2428 if (es.es_lblk <= hole_start)
2430 hole_len = min(es.es_lblk - hole_start, hole_len);
2432 ext_debug(" -> %u:%u\n", hole_start, hole_len);
2433 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2434 EXTENT_STATUS_HOLE);
2439 * removes index from the index block.
2441 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2442 struct ext4_ext_path *path, int depth)
2447 /* free index block */
2449 path = path + depth;
2450 leaf = ext4_idx_pblock(path->p_idx);
2451 if (unlikely(path->p_hdr->eh_entries == 0)) {
2452 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2453 return -EFSCORRUPTED;
2455 err = ext4_ext_get_access(handle, inode, path);
2459 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2460 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2461 len *= sizeof(struct ext4_extent_idx);
2462 memmove(path->p_idx, path->p_idx + 1, len);
2465 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2466 err = ext4_ext_dirty(handle, inode, path);
2469 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2470 trace_ext4_ext_rm_idx(inode, leaf);
2472 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2473 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2475 while (--depth >= 0) {
2476 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2479 err = ext4_ext_get_access(handle, inode, path);
2482 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2483 err = ext4_ext_dirty(handle, inode, path);
2491 * ext4_ext_calc_credits_for_single_extent:
2492 * This routine returns max. credits that needed to insert an extent
2493 * to the extent tree.
2494 * When pass the actual path, the caller should calculate credits
2497 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2498 struct ext4_ext_path *path)
2501 int depth = ext_depth(inode);
2504 /* probably there is space in leaf? */
2505 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2506 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2509 * There are some space in the leaf tree, no
2510 * need to account for leaf block credit
2512 * bitmaps and block group descriptor blocks
2513 * and other metadata blocks still need to be
2516 /* 1 bitmap, 1 block group descriptor */
2517 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2522 return ext4_chunk_trans_blocks(inode, nrblocks);
2526 * How many index/leaf blocks need to change/allocate to add @extents extents?
2528 * If we add a single extent, then in the worse case, each tree level
2529 * index/leaf need to be changed in case of the tree split.
2531 * If more extents are inserted, they could cause the whole tree split more
2532 * than once, but this is really rare.
2534 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2539 /* If we are converting the inline data, only one is needed here. */
2540 if (ext4_has_inline_data(inode))
2543 depth = ext_depth(inode);
2553 static inline int get_default_free_blocks_flags(struct inode *inode)
2555 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2556 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2557 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2558 else if (ext4_should_journal_data(inode))
2559 return EXT4_FREE_BLOCKS_FORGET;
2564 * ext4_rereserve_cluster - increment the reserved cluster count when
2565 * freeing a cluster with a pending reservation
2567 * @inode - file containing the cluster
2568 * @lblk - logical block in cluster to be reserved
2570 * Increments the reserved cluster count and adjusts quota in a bigalloc
2571 * file system when freeing a partial cluster containing at least one
2572 * delayed and unwritten block. A partial cluster meeting that
2573 * requirement will have a pending reservation. If so, the
2574 * RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
2575 * defer reserved and allocated space accounting to a subsequent call
2578 static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
2580 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2581 struct ext4_inode_info *ei = EXT4_I(inode);
2583 dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
2585 spin_lock(&ei->i_block_reservation_lock);
2586 ei->i_reserved_data_blocks++;
2587 percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
2588 spin_unlock(&ei->i_block_reservation_lock);
2590 percpu_counter_add(&sbi->s_freeclusters_counter, 1);
2591 ext4_remove_pending(inode, lblk);
2594 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2595 struct ext4_extent *ex,
2596 struct partial_cluster *partial,
2597 ext4_lblk_t from, ext4_lblk_t to)
2599 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2600 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2601 ext4_fsblk_t last_pblk, pblk;
2605 /* only extent tail removal is allowed */
2606 if (from < le32_to_cpu(ex->ee_block) ||
2607 to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
2608 ext4_error(sbi->s_sb,
2609 "strange request: removal(2) %u-%u from %u:%u",
2610 from, to, le32_to_cpu(ex->ee_block), ee_len);
2614 #ifdef EXTENTS_STATS
2615 spin_lock(&sbi->s_ext_stats_lock);
2616 sbi->s_ext_blocks += ee_len;
2617 sbi->s_ext_extents++;
2618 if (ee_len < sbi->s_ext_min)
2619 sbi->s_ext_min = ee_len;
2620 if (ee_len > sbi->s_ext_max)
2621 sbi->s_ext_max = ee_len;
2622 if (ext_depth(inode) > sbi->s_depth_max)
2623 sbi->s_depth_max = ext_depth(inode);
2624 spin_unlock(&sbi->s_ext_stats_lock);
2627 trace_ext4_remove_blocks(inode, ex, from, to, partial);
2630 * if we have a partial cluster, and it's different from the
2631 * cluster of the last block in the extent, we free it
2633 last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
2635 if (partial->state != initial &&
2636 partial->pclu != EXT4_B2C(sbi, last_pblk)) {
2637 if (partial->state == tofree) {
2638 flags = get_default_free_blocks_flags(inode);
2639 if (ext4_is_pending(inode, partial->lblk))
2640 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2641 ext4_free_blocks(handle, inode, NULL,
2642 EXT4_C2B(sbi, partial->pclu),
2643 sbi->s_cluster_ratio, flags);
2644 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2645 ext4_rereserve_cluster(inode, partial->lblk);
2647 partial->state = initial;
2650 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2651 pblk = ext4_ext_pblock(ex) + ee_len - num;
2654 * We free the partial cluster at the end of the extent (if any),
2655 * unless the cluster is used by another extent (partial_cluster
2656 * state is nofree). If a partial cluster exists here, it must be
2657 * shared with the last block in the extent.
2659 flags = get_default_free_blocks_flags(inode);
2661 /* partial, left end cluster aligned, right end unaligned */
2662 if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
2663 (EXT4_LBLK_CMASK(sbi, to) >= from) &&
2664 (partial->state != nofree)) {
2665 if (ext4_is_pending(inode, to))
2666 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2667 ext4_free_blocks(handle, inode, NULL,
2668 EXT4_PBLK_CMASK(sbi, last_pblk),
2669 sbi->s_cluster_ratio, flags);
2670 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2671 ext4_rereserve_cluster(inode, to);
2672 partial->state = initial;
2673 flags = get_default_free_blocks_flags(inode);
2676 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2679 * For bigalloc file systems, we never free a partial cluster
2680 * at the beginning of the extent. Instead, we check to see if we
2681 * need to free it on a subsequent call to ext4_remove_blocks,
2682 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2684 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2685 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2687 /* reset the partial cluster if we've freed past it */
2688 if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
2689 partial->state = initial;
2692 * If we've freed the entire extent but the beginning is not left
2693 * cluster aligned and is not marked as ineligible for freeing we
2694 * record the partial cluster at the beginning of the extent. It
2695 * wasn't freed by the preceding ext4_free_blocks() call, and we
2696 * need to look farther to the left to determine if it's to be freed
2697 * (not shared with another extent). Else, reset the partial
2698 * cluster - we're either done freeing or the beginning of the
2699 * extent is left cluster aligned.
2701 if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
2702 if (partial->state == initial) {
2703 partial->pclu = EXT4_B2C(sbi, pblk);
2704 partial->lblk = from;
2705 partial->state = tofree;
2708 partial->state = initial;
2715 * ext4_ext_rm_leaf() Removes the extents associated with the
2716 * blocks appearing between "start" and "end". Both "start"
2717 * and "end" must appear in the same extent or EIO is returned.
2719 * @handle: The journal handle
2720 * @inode: The files inode
2721 * @path: The path to the leaf
2722 * @partial_cluster: The cluster which we'll have to free if all extents
2723 * has been released from it. However, if this value is
2724 * negative, it's a cluster just to the right of the
2725 * punched region and it must not be freed.
2726 * @start: The first block to remove
2727 * @end: The last block to remove
2730 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2731 struct ext4_ext_path *path,
2732 struct partial_cluster *partial,
2733 ext4_lblk_t start, ext4_lblk_t end)
2735 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2736 int err = 0, correct_index = 0;
2737 int depth = ext_depth(inode), credits, revoke_credits;
2738 struct ext4_extent_header *eh;
2741 ext4_lblk_t ex_ee_block;
2742 unsigned short ex_ee_len;
2743 unsigned unwritten = 0;
2744 struct ext4_extent *ex;
2747 /* the header must be checked already in ext4_ext_remove_space() */
2748 ext_debug("truncate since %u in leaf to %u\n", start, end);
2749 if (!path[depth].p_hdr)
2750 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2751 eh = path[depth].p_hdr;
2752 if (unlikely(path[depth].p_hdr == NULL)) {
2753 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2754 return -EFSCORRUPTED;
2756 /* find where to start removing */
2757 ex = path[depth].p_ext;
2759 ex = EXT_LAST_EXTENT(eh);
2761 ex_ee_block = le32_to_cpu(ex->ee_block);
2762 ex_ee_len = ext4_ext_get_actual_len(ex);
2764 trace_ext4_ext_rm_leaf(inode, start, ex, partial);
2766 while (ex >= EXT_FIRST_EXTENT(eh) &&
2767 ex_ee_block + ex_ee_len > start) {
2769 if (ext4_ext_is_unwritten(ex))
2774 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2775 unwritten, ex_ee_len);
2776 path[depth].p_ext = ex;
2778 a = ex_ee_block > start ? ex_ee_block : start;
2779 b = ex_ee_block+ex_ee_len - 1 < end ?
2780 ex_ee_block+ex_ee_len - 1 : end;
2782 ext_debug(" border %u:%u\n", a, b);
2784 /* If this extent is beyond the end of the hole, skip it */
2785 if (end < ex_ee_block) {
2787 * We're going to skip this extent and move to another,
2788 * so note that its first cluster is in use to avoid
2789 * freeing it when removing blocks. Eventually, the
2790 * right edge of the truncated/punched region will
2791 * be just to the left.
2793 if (sbi->s_cluster_ratio > 1) {
2794 pblk = ext4_ext_pblock(ex);
2795 partial->pclu = EXT4_B2C(sbi, pblk);
2796 partial->state = nofree;
2799 ex_ee_block = le32_to_cpu(ex->ee_block);
2800 ex_ee_len = ext4_ext_get_actual_len(ex);
2802 } else if (b != ex_ee_block + ex_ee_len - 1) {
2803 EXT4_ERROR_INODE(inode,
2804 "can not handle truncate %u:%u "
2806 start, end, ex_ee_block,
2807 ex_ee_block + ex_ee_len - 1);
2808 err = -EFSCORRUPTED;
2810 } else if (a != ex_ee_block) {
2811 /* remove tail of the extent */
2812 num = a - ex_ee_block;
2814 /* remove whole extent: excellent! */
2818 * 3 for leaf, sb, and inode plus 2 (bmap and group
2819 * descriptor) for each block group; assume two block
2820 * groups plus ex_ee_len/blocks_per_block_group for
2823 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2824 if (ex == EXT_FIRST_EXTENT(eh)) {
2826 credits += (ext_depth(inode)) + 1;
2828 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2830 * We may end up freeing some index blocks and data from the
2831 * punched range. Note that partial clusters are accounted for
2832 * by ext4_free_data_revoke_credits().
2835 ext4_free_metadata_revoke_credits(inode->i_sb,
2837 ext4_free_data_revoke_credits(inode, b - a + 1);
2839 err = ext4_datasem_ensure_credits(handle, inode, credits,
2840 credits, revoke_credits);
2847 err = ext4_ext_get_access(handle, inode, path + depth);
2851 err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
2856 /* this extent is removed; mark slot entirely unused */
2857 ext4_ext_store_pblock(ex, 0);
2859 ex->ee_len = cpu_to_le16(num);
2861 * Do not mark unwritten if all the blocks in the
2862 * extent have been removed.
2864 if (unwritten && num)
2865 ext4_ext_mark_unwritten(ex);
2867 * If the extent was completely released,
2868 * we need to remove it from the leaf
2871 if (end != EXT_MAX_BLOCKS - 1) {
2873 * For hole punching, we need to scoot all the
2874 * extents up when an extent is removed so that
2875 * we dont have blank extents in the middle
2877 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2878 sizeof(struct ext4_extent));
2880 /* Now get rid of the one at the end */
2881 memset(EXT_LAST_EXTENT(eh), 0,
2882 sizeof(struct ext4_extent));
2884 le16_add_cpu(&eh->eh_entries, -1);
2887 err = ext4_ext_dirty(handle, inode, path + depth);
2891 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2892 ext4_ext_pblock(ex));
2894 ex_ee_block = le32_to_cpu(ex->ee_block);
2895 ex_ee_len = ext4_ext_get_actual_len(ex);
2898 if (correct_index && eh->eh_entries)
2899 err = ext4_ext_correct_indexes(handle, inode, path);
2902 * If there's a partial cluster and at least one extent remains in
2903 * the leaf, free the partial cluster if it isn't shared with the
2904 * current extent. If it is shared with the current extent
2905 * we reset the partial cluster because we've reached the start of the
2906 * truncated/punched region and we're done removing blocks.
2908 if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
2909 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2910 if (partial->pclu != EXT4_B2C(sbi, pblk)) {
2911 int flags = get_default_free_blocks_flags(inode);
2913 if (ext4_is_pending(inode, partial->lblk))
2914 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2915 ext4_free_blocks(handle, inode, NULL,
2916 EXT4_C2B(sbi, partial->pclu),
2917 sbi->s_cluster_ratio, flags);
2918 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2919 ext4_rereserve_cluster(inode, partial->lblk);
2921 partial->state = initial;
2924 /* if this leaf is free, then we should
2925 * remove it from index block above */
2926 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2927 err = ext4_ext_rm_idx(handle, inode, path, depth);
2934 * ext4_ext_more_to_rm:
2935 * returns 1 if current index has to be freed (even partial)
2938 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2940 BUG_ON(path->p_idx == NULL);
2942 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2946 * if truncate on deeper level happened, it wasn't partial,
2947 * so we have to consider current index for truncation
2949 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2954 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2957 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2958 int depth = ext_depth(inode);
2959 struct ext4_ext_path *path = NULL;
2960 struct partial_cluster partial;
2966 partial.state = initial;
2968 ext_debug("truncate since %u to %u\n", start, end);
2970 /* probably first extent we're gonna free will be last in block */
2971 handle = ext4_journal_start_with_revoke(inode, EXT4_HT_TRUNCATE,
2973 ext4_free_metadata_revoke_credits(inode->i_sb, depth));
2975 return PTR_ERR(handle);
2978 trace_ext4_ext_remove_space(inode, start, end, depth);
2981 * Check if we are removing extents inside the extent tree. If that
2982 * is the case, we are going to punch a hole inside the extent tree
2983 * so we have to check whether we need to split the extent covering
2984 * the last block to remove so we can easily remove the part of it
2985 * in ext4_ext_rm_leaf().
2987 if (end < EXT_MAX_BLOCKS - 1) {
2988 struct ext4_extent *ex;
2989 ext4_lblk_t ee_block, ex_end, lblk;
2992 /* find extent for or closest extent to this block */
2993 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
2995 ext4_journal_stop(handle);
2996 return PTR_ERR(path);
2998 depth = ext_depth(inode);
2999 /* Leaf not may not exist only if inode has no blocks at all */
3000 ex = path[depth].p_ext;
3003 EXT4_ERROR_INODE(inode,
3004 "path[%d].p_hdr == NULL",
3006 err = -EFSCORRUPTED;
3011 ee_block = le32_to_cpu(ex->ee_block);
3012 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
3015 * See if the last block is inside the extent, if so split
3016 * the extent at 'end' block so we can easily remove the
3017 * tail of the first part of the split extent in
3018 * ext4_ext_rm_leaf().
3020 if (end >= ee_block && end < ex_end) {
3023 * If we're going to split the extent, note that
3024 * the cluster containing the block after 'end' is
3025 * in use to avoid freeing it when removing blocks.
3027 if (sbi->s_cluster_ratio > 1) {
3028 pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
3029 partial.pclu = EXT4_B2C(sbi, pblk);
3030 partial.state = nofree;
3034 * Split the extent in two so that 'end' is the last
3035 * block in the first new extent. Also we should not
3036 * fail removing space due to ENOSPC so try to use
3037 * reserved block if that happens.
3039 err = ext4_force_split_extent_at(handle, inode, &path,
3044 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
3045 partial.state == initial) {
3047 * If we're punching, there's an extent to the right.
3048 * If the partial cluster hasn't been set, set it to
3049 * that extent's first cluster and its state to nofree
3050 * so it won't be freed should it contain blocks to be
3051 * removed. If it's already set (tofree/nofree), we're
3052 * retrying and keep the original partial cluster info
3053 * so a cluster marked tofree as a result of earlier
3054 * extent removal is not lost.
3057 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
3062 partial.pclu = EXT4_B2C(sbi, pblk);
3063 partial.state = nofree;
3068 * We start scanning from right side, freeing all the blocks
3069 * after i_size and walking into the tree depth-wise.
3071 depth = ext_depth(inode);
3076 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
3078 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
3081 ext4_journal_stop(handle);
3084 path[0].p_maxdepth = path[0].p_depth = depth;
3085 path[0].p_hdr = ext_inode_hdr(inode);
3088 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
3089 err = -EFSCORRUPTED;
3095 while (i >= 0 && err == 0) {
3097 /* this is leaf block */
3098 err = ext4_ext_rm_leaf(handle, inode, path,
3099 &partial, start, end);
3100 /* root level has p_bh == NULL, brelse() eats this */
3101 brelse(path[i].p_bh);
3102 path[i].p_bh = NULL;
3107 /* this is index block */
3108 if (!path[i].p_hdr) {
3109 ext_debug("initialize header\n");
3110 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
3113 if (!path[i].p_idx) {
3114 /* this level hasn't been touched yet */
3115 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
3116 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
3117 ext_debug("init index ptr: hdr 0x%p, num %d\n",
3119 le16_to_cpu(path[i].p_hdr->eh_entries));
3121 /* we were already here, see at next index */
3125 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
3126 i, EXT_FIRST_INDEX(path[i].p_hdr),
3128 if (ext4_ext_more_to_rm(path + i)) {
3129 struct buffer_head *bh;
3130 /* go to the next level */
3131 ext_debug("move to level %d (block %llu)\n",
3132 i + 1, ext4_idx_pblock(path[i].p_idx));
3133 memset(path + i + 1, 0, sizeof(*path));
3134 bh = read_extent_tree_block(inode,
3135 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
3138 /* should we reset i_size? */
3142 /* Yield here to deal with large extent trees.
3143 * Should be a no-op if we did IO above. */
3145 if (WARN_ON(i + 1 > depth)) {
3146 err = -EFSCORRUPTED;
3149 path[i + 1].p_bh = bh;
3151 /* save actual number of indexes since this
3152 * number is changed at the next iteration */
3153 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3156 /* we finished processing this index, go up */
3157 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3158 /* index is empty, remove it;
3159 * handle must be already prepared by the
3160 * truncatei_leaf() */
3161 err = ext4_ext_rm_idx(handle, inode, path, i);
3163 /* root level has p_bh == NULL, brelse() eats this */
3164 brelse(path[i].p_bh);
3165 path[i].p_bh = NULL;
3167 ext_debug("return to level %d\n", i);
3171 trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
3172 path->p_hdr->eh_entries);
3175 * if there's a partial cluster and we have removed the first extent
3176 * in the file, then we also free the partial cluster, if any
3178 if (partial.state == tofree && err == 0) {
3179 int flags = get_default_free_blocks_flags(inode);
3181 if (ext4_is_pending(inode, partial.lblk))
3182 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
3183 ext4_free_blocks(handle, inode, NULL,
3184 EXT4_C2B(sbi, partial.pclu),
3185 sbi->s_cluster_ratio, flags);
3186 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
3187 ext4_rereserve_cluster(inode, partial.lblk);
3188 partial.state = initial;
3191 /* TODO: flexible tree reduction should be here */
3192 if (path->p_hdr->eh_entries == 0) {
3194 * truncate to zero freed all the tree,
3195 * so we need to correct eh_depth
3197 err = ext4_ext_get_access(handle, inode, path);
3199 ext_inode_hdr(inode)->eh_depth = 0;
3200 ext_inode_hdr(inode)->eh_max =
3201 cpu_to_le16(ext4_ext_space_root(inode, 0));
3202 err = ext4_ext_dirty(handle, inode, path);
3206 ext4_ext_drop_refs(path);
3211 ext4_journal_stop(handle);
3217 * called at mount time
3219 void ext4_ext_init(struct super_block *sb)
3222 * possible initialization would be here
3225 if (ext4_has_feature_extents(sb)) {
3226 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3227 printk(KERN_INFO "EXT4-fs: file extents enabled"
3228 #ifdef AGGRESSIVE_TEST
3229 ", aggressive tests"
3231 #ifdef CHECK_BINSEARCH
3234 #ifdef EXTENTS_STATS
3239 #ifdef EXTENTS_STATS
3240 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3241 EXT4_SB(sb)->s_ext_min = 1 << 30;
3242 EXT4_SB(sb)->s_ext_max = 0;
3248 * called at umount time
3250 void ext4_ext_release(struct super_block *sb)
3252 if (!ext4_has_feature_extents(sb))
3255 #ifdef EXTENTS_STATS
3256 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3257 struct ext4_sb_info *sbi = EXT4_SB(sb);
3258 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3259 sbi->s_ext_blocks, sbi->s_ext_extents,
3260 sbi->s_ext_blocks / sbi->s_ext_extents);
3261 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3262 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3267 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3269 ext4_lblk_t ee_block;
3270 ext4_fsblk_t ee_pblock;
3271 unsigned int ee_len;
3273 ee_block = le32_to_cpu(ex->ee_block);
3274 ee_len = ext4_ext_get_actual_len(ex);
3275 ee_pblock = ext4_ext_pblock(ex);
3280 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3281 EXTENT_STATUS_WRITTEN);
3284 /* FIXME!! we need to try to merge to left or right after zero-out */
3285 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3287 ext4_fsblk_t ee_pblock;
3288 unsigned int ee_len;
3290 ee_len = ext4_ext_get_actual_len(ex);
3291 ee_pblock = ext4_ext_pblock(ex);
3292 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3297 * ext4_split_extent_at() splits an extent at given block.
3299 * @handle: the journal handle
3300 * @inode: the file inode
3301 * @path: the path to the extent
3302 * @split: the logical block where the extent is splitted.
3303 * @split_flags: indicates if the extent could be zeroout if split fails, and
3304 * the states(init or unwritten) of new extents.
3305 * @flags: flags used to insert new extent to extent tree.
3308 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3309 * of which are deterimined by split_flag.
3311 * There are two cases:
3312 * a> the extent are splitted into two extent.
3313 * b> split is not needed, and just mark the extent.
3315 * return 0 on success.
3317 static int ext4_split_extent_at(handle_t *handle,
3318 struct inode *inode,
3319 struct ext4_ext_path **ppath,
3324 struct ext4_ext_path *path = *ppath;
3325 ext4_fsblk_t newblock;
3326 ext4_lblk_t ee_block;
3327 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3328 struct ext4_extent *ex2 = NULL;
3329 unsigned int ee_len, depth;
3332 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3333 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3335 ext_debug("ext4_split_extents_at: inode %lu, logical"
3336 "block %llu\n", inode->i_ino, (unsigned long long)split);
3338 ext4_ext_show_leaf(inode, path);
3340 depth = ext_depth(inode);
3341 ex = path[depth].p_ext;
3342 ee_block = le32_to_cpu(ex->ee_block);
3343 ee_len = ext4_ext_get_actual_len(ex);
3344 newblock = split - ee_block + ext4_ext_pblock(ex);
3346 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3347 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3348 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3349 EXT4_EXT_MARK_UNWRIT1 |
3350 EXT4_EXT_MARK_UNWRIT2));
3352 err = ext4_ext_get_access(handle, inode, path + depth);
3356 if (split == ee_block) {
3358 * case b: block @split is the block that the extent begins with
3359 * then we just change the state of the extent, and splitting
3362 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3363 ext4_ext_mark_unwritten(ex);
3365 ext4_ext_mark_initialized(ex);
3367 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3368 ext4_ext_try_to_merge(handle, inode, path, ex);
3370 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3375 memcpy(&orig_ex, ex, sizeof(orig_ex));
3376 ex->ee_len = cpu_to_le16(split - ee_block);
3377 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3378 ext4_ext_mark_unwritten(ex);
3381 * path may lead to new leaf, not to original leaf any more
3382 * after ext4_ext_insert_extent() returns,
3384 err = ext4_ext_dirty(handle, inode, path + depth);
3386 goto fix_extent_len;
3389 ex2->ee_block = cpu_to_le32(split);
3390 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3391 ext4_ext_store_pblock(ex2, newblock);
3392 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3393 ext4_ext_mark_unwritten(ex2);
3395 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3396 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3397 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3398 if (split_flag & EXT4_EXT_DATA_VALID1) {
3399 err = ext4_ext_zeroout(inode, ex2);
3400 zero_ex.ee_block = ex2->ee_block;
3401 zero_ex.ee_len = cpu_to_le16(
3402 ext4_ext_get_actual_len(ex2));
3403 ext4_ext_store_pblock(&zero_ex,
3404 ext4_ext_pblock(ex2));
3406 err = ext4_ext_zeroout(inode, ex);
3407 zero_ex.ee_block = ex->ee_block;
3408 zero_ex.ee_len = cpu_to_le16(
3409 ext4_ext_get_actual_len(ex));
3410 ext4_ext_store_pblock(&zero_ex,
3411 ext4_ext_pblock(ex));
3414 err = ext4_ext_zeroout(inode, &orig_ex);
3415 zero_ex.ee_block = orig_ex.ee_block;
3416 zero_ex.ee_len = cpu_to_le16(
3417 ext4_ext_get_actual_len(&orig_ex));
3418 ext4_ext_store_pblock(&zero_ex,
3419 ext4_ext_pblock(&orig_ex));
3423 goto fix_extent_len;
3424 /* update the extent length and mark as initialized */
3425 ex->ee_len = cpu_to_le16(ee_len);
3426 ext4_ext_try_to_merge(handle, inode, path, ex);
3427 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3429 goto fix_extent_len;
3431 /* update extent status tree */
3432 err = ext4_zeroout_es(inode, &zero_ex);
3436 goto fix_extent_len;
3439 ext4_ext_show_leaf(inode, path);
3443 ex->ee_len = orig_ex.ee_len;
3444 ext4_ext_dirty(handle, inode, path + path->p_depth);
3449 * ext4_split_extents() splits an extent and mark extent which is covered
3450 * by @map as split_flags indicates
3452 * It may result in splitting the extent into multiple extents (up to three)
3453 * There are three possibilities:
3454 * a> There is no split required
3455 * b> Splits in two extents: Split is happening at either end of the extent
3456 * c> Splits in three extents: Somone is splitting in middle of the extent
3459 static int ext4_split_extent(handle_t *handle,
3460 struct inode *inode,
3461 struct ext4_ext_path **ppath,
3462 struct ext4_map_blocks *map,
3466 struct ext4_ext_path *path = *ppath;
3467 ext4_lblk_t ee_block;
3468 struct ext4_extent *ex;
3469 unsigned int ee_len, depth;
3472 int split_flag1, flags1;
3473 int allocated = map->m_len;
3475 depth = ext_depth(inode);
3476 ex = path[depth].p_ext;
3477 ee_block = le32_to_cpu(ex->ee_block);
3478 ee_len = ext4_ext_get_actual_len(ex);
3479 unwritten = ext4_ext_is_unwritten(ex);
3481 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3482 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3483 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3485 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3486 EXT4_EXT_MARK_UNWRIT2;
3487 if (split_flag & EXT4_EXT_DATA_VALID2)
3488 split_flag1 |= EXT4_EXT_DATA_VALID1;
3489 err = ext4_split_extent_at(handle, inode, ppath,
3490 map->m_lblk + map->m_len, split_flag1, flags1);
3494 allocated = ee_len - (map->m_lblk - ee_block);
3497 * Update path is required because previous ext4_split_extent_at() may
3498 * result in split of original leaf or extent zeroout.
3500 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3502 return PTR_ERR(path);
3503 depth = ext_depth(inode);
3504 ex = path[depth].p_ext;
3506 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3507 (unsigned long) map->m_lblk);
3508 return -EFSCORRUPTED;
3510 unwritten = ext4_ext_is_unwritten(ex);
3513 if (map->m_lblk >= ee_block) {
3514 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3516 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3517 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3518 EXT4_EXT_MARK_UNWRIT2);
3520 err = ext4_split_extent_at(handle, inode, ppath,
3521 map->m_lblk, split_flag1, flags);
3526 ext4_ext_show_leaf(inode, path);
3528 return err ? err : allocated;
3532 * This function is called by ext4_ext_map_blocks() if someone tries to write
3533 * to an unwritten extent. It may result in splitting the unwritten
3534 * extent into multiple extents (up to three - one initialized and two
3536 * There are three possibilities:
3537 * a> There is no split required: Entire extent should be initialized
3538 * b> Splits in two extents: Write is happening at either end of the extent
3539 * c> Splits in three extents: Somone is writing in middle of the extent
3542 * - The extent pointed to by 'path' is unwritten.
3543 * - The extent pointed to by 'path' contains a superset
3544 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3546 * Post-conditions on success:
3547 * - the returned value is the number of blocks beyond map->l_lblk
3548 * that are allocated and initialized.
3549 * It is guaranteed to be >= map->m_len.
3551 static int ext4_ext_convert_to_initialized(handle_t *handle,
3552 struct inode *inode,
3553 struct ext4_map_blocks *map,
3554 struct ext4_ext_path **ppath,
3557 struct ext4_ext_path *path = *ppath;
3558 struct ext4_sb_info *sbi;
3559 struct ext4_extent_header *eh;
3560 struct ext4_map_blocks split_map;
3561 struct ext4_extent zero_ex1, zero_ex2;
3562 struct ext4_extent *ex, *abut_ex;
3563 ext4_lblk_t ee_block, eof_block;
3564 unsigned int ee_len, depth, map_len = map->m_len;
3565 int allocated = 0, max_zeroout = 0;
3567 int split_flag = EXT4_EXT_DATA_VALID2;
3569 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3570 "block %llu, max_blocks %u\n", inode->i_ino,
3571 (unsigned long long)map->m_lblk, map_len);
3573 sbi = EXT4_SB(inode->i_sb);
3574 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3575 inode->i_sb->s_blocksize_bits;
3576 if (eof_block < map->m_lblk + map_len)
3577 eof_block = map->m_lblk + map_len;
3579 depth = ext_depth(inode);
3580 eh = path[depth].p_hdr;
3581 ex = path[depth].p_ext;
3582 ee_block = le32_to_cpu(ex->ee_block);
3583 ee_len = ext4_ext_get_actual_len(ex);
3584 zero_ex1.ee_len = 0;
3585 zero_ex2.ee_len = 0;
3587 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3589 /* Pre-conditions */
3590 BUG_ON(!ext4_ext_is_unwritten(ex));
3591 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3594 * Attempt to transfer newly initialized blocks from the currently
3595 * unwritten extent to its neighbor. This is much cheaper
3596 * than an insertion followed by a merge as those involve costly
3597 * memmove() calls. Transferring to the left is the common case in
3598 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3599 * followed by append writes.
3601 * Limitations of the current logic:
3602 * - L1: we do not deal with writes covering the whole extent.
3603 * This would require removing the extent if the transfer
3605 * - L2: we only attempt to merge with an extent stored in the
3606 * same extent tree node.
3608 if ((map->m_lblk == ee_block) &&
3609 /* See if we can merge left */
3610 (map_len < ee_len) && /*L1*/
3611 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3612 ext4_lblk_t prev_lblk;
3613 ext4_fsblk_t prev_pblk, ee_pblk;
3614 unsigned int prev_len;
3617 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3618 prev_len = ext4_ext_get_actual_len(abut_ex);
3619 prev_pblk = ext4_ext_pblock(abut_ex);
3620 ee_pblk = ext4_ext_pblock(ex);
3623 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3624 * upon those conditions:
3625 * - C1: abut_ex is initialized,
3626 * - C2: abut_ex is logically abutting ex,
3627 * - C3: abut_ex is physically abutting ex,
3628 * - C4: abut_ex can receive the additional blocks without
3629 * overflowing the (initialized) length limit.
3631 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3632 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3633 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3634 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3635 err = ext4_ext_get_access(handle, inode, path + depth);
3639 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3642 /* Shift the start of ex by 'map_len' blocks */
3643 ex->ee_block = cpu_to_le32(ee_block + map_len);
3644 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3645 ex->ee_len = cpu_to_le16(ee_len - map_len);
3646 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3648 /* Extend abut_ex by 'map_len' blocks */
3649 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3651 /* Result: number of initialized blocks past m_lblk */
3652 allocated = map_len;
3654 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3655 (map_len < ee_len) && /*L1*/
3656 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3657 /* See if we can merge right */
3658 ext4_lblk_t next_lblk;
3659 ext4_fsblk_t next_pblk, ee_pblk;
3660 unsigned int next_len;
3663 next_lblk = le32_to_cpu(abut_ex->ee_block);
3664 next_len = ext4_ext_get_actual_len(abut_ex);
3665 next_pblk = ext4_ext_pblock(abut_ex);
3666 ee_pblk = ext4_ext_pblock(ex);
3669 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3670 * upon those conditions:
3671 * - C1: abut_ex is initialized,
3672 * - C2: abut_ex is logically abutting ex,
3673 * - C3: abut_ex is physically abutting ex,
3674 * - C4: abut_ex can receive the additional blocks without
3675 * overflowing the (initialized) length limit.
3677 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3678 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3679 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3680 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3681 err = ext4_ext_get_access(handle, inode, path + depth);
3685 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3688 /* Shift the start of abut_ex by 'map_len' blocks */
3689 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3690 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3691 ex->ee_len = cpu_to_le16(ee_len - map_len);
3692 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3694 /* Extend abut_ex by 'map_len' blocks */
3695 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3697 /* Result: number of initialized blocks past m_lblk */
3698 allocated = map_len;
3702 /* Mark the block containing both extents as dirty */
3703 ext4_ext_dirty(handle, inode, path + depth);
3705 /* Update path to point to the right extent */
3706 path[depth].p_ext = abut_ex;
3709 allocated = ee_len - (map->m_lblk - ee_block);
3711 WARN_ON(map->m_lblk < ee_block);
3713 * It is safe to convert extent to initialized via explicit
3714 * zeroout only if extent is fully inside i_size or new_size.
3716 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3718 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3719 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3720 (inode->i_sb->s_blocksize_bits - 10);
3722 if (IS_ENCRYPTED(inode))
3727 * 1. split the extent into three extents.
3728 * 2. split the extent into two extents, zeroout the head of the first
3730 * 3. split the extent into two extents, zeroout the tail of the second
3732 * 4. split the extent into two extents with out zeroout.
3733 * 5. no splitting needed, just possibly zeroout the head and / or the
3734 * tail of the extent.
3736 split_map.m_lblk = map->m_lblk;
3737 split_map.m_len = map->m_len;
3739 if (max_zeroout && (allocated > split_map.m_len)) {
3740 if (allocated <= max_zeroout) {
3743 cpu_to_le32(split_map.m_lblk +
3746 cpu_to_le16(allocated - split_map.m_len);
3747 ext4_ext_store_pblock(&zero_ex1,
3748 ext4_ext_pblock(ex) + split_map.m_lblk +
3749 split_map.m_len - ee_block);
3750 err = ext4_ext_zeroout(inode, &zero_ex1);
3753 split_map.m_len = allocated;
3755 if (split_map.m_lblk - ee_block + split_map.m_len <
3758 if (split_map.m_lblk != ee_block) {
3759 zero_ex2.ee_block = ex->ee_block;
3760 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3762 ext4_ext_store_pblock(&zero_ex2,
3763 ext4_ext_pblock(ex));
3764 err = ext4_ext_zeroout(inode, &zero_ex2);
3769 split_map.m_len += split_map.m_lblk - ee_block;
3770 split_map.m_lblk = ee_block;
3771 allocated = map->m_len;
3775 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3780 /* If we have gotten a failure, don't zero out status tree */
3782 err = ext4_zeroout_es(inode, &zero_ex1);
3784 err = ext4_zeroout_es(inode, &zero_ex2);
3786 return err ? err : allocated;
3790 * This function is called by ext4_ext_map_blocks() from
3791 * ext4_get_blocks_dio_write() when DIO to write
3792 * to an unwritten extent.
3794 * Writing to an unwritten extent may result in splitting the unwritten
3795 * extent into multiple initialized/unwritten extents (up to three)
3796 * There are three possibilities:
3797 * a> There is no split required: Entire extent should be unwritten
3798 * b> Splits in two extents: Write is happening at either end of the extent
3799 * c> Splits in three extents: Somone is writing in middle of the extent
3801 * This works the same way in the case of initialized -> unwritten conversion.
3803 * One of more index blocks maybe needed if the extent tree grow after
3804 * the unwritten extent split. To prevent ENOSPC occur at the IO
3805 * complete, we need to split the unwritten extent before DIO submit
3806 * the IO. The unwritten extent called at this time will be split
3807 * into three unwritten extent(at most). After IO complete, the part
3808 * being filled will be convert to initialized by the end_io callback function
3809 * via ext4_convert_unwritten_extents().
3811 * Returns the size of unwritten extent to be written on success.
3813 static int ext4_split_convert_extents(handle_t *handle,
3814 struct inode *inode,
3815 struct ext4_map_blocks *map,
3816 struct ext4_ext_path **ppath,
3819 struct ext4_ext_path *path = *ppath;
3820 ext4_lblk_t eof_block;
3821 ext4_lblk_t ee_block;
3822 struct ext4_extent *ex;
3823 unsigned int ee_len;
3824 int split_flag = 0, depth;
3826 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3827 __func__, inode->i_ino,
3828 (unsigned long long)map->m_lblk, map->m_len);
3830 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3831 inode->i_sb->s_blocksize_bits;
3832 if (eof_block < map->m_lblk + map->m_len)
3833 eof_block = map->m_lblk + map->m_len;
3835 * It is safe to convert extent to initialized via explicit
3836 * zeroout only if extent is fully insde i_size or new_size.
3838 depth = ext_depth(inode);
3839 ex = path[depth].p_ext;
3840 ee_block = le32_to_cpu(ex->ee_block);
3841 ee_len = ext4_ext_get_actual_len(ex);
3843 /* Convert to unwritten */
3844 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3845 split_flag |= EXT4_EXT_DATA_VALID1;
3846 /* Convert to initialized */
3847 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3848 split_flag |= ee_block + ee_len <= eof_block ?
3849 EXT4_EXT_MAY_ZEROOUT : 0;
3850 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3852 flags |= EXT4_GET_BLOCKS_PRE_IO;
3853 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3856 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3857 struct inode *inode,
3858 struct ext4_map_blocks *map,
3859 struct ext4_ext_path **ppath)
3861 struct ext4_ext_path *path = *ppath;
3862 struct ext4_extent *ex;
3863 ext4_lblk_t ee_block;
3864 unsigned int ee_len;
3868 depth = ext_depth(inode);
3869 ex = path[depth].p_ext;
3870 ee_block = le32_to_cpu(ex->ee_block);
3871 ee_len = ext4_ext_get_actual_len(ex);
3873 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3874 "block %llu, max_blocks %u\n", inode->i_ino,
3875 (unsigned long long)ee_block, ee_len);
3877 /* If extent is larger than requested it is a clear sign that we still
3878 * have some extent state machine issues left. So extent_split is still
3880 * TODO: Once all related issues will be fixed this situation should be
3883 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3884 #ifdef CONFIG_EXT4_DEBUG
3885 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3886 " len %u; IO logical block %llu, len %u",
3887 inode->i_ino, (unsigned long long)ee_block, ee_len,
3888 (unsigned long long)map->m_lblk, map->m_len);
3890 err = ext4_split_convert_extents(handle, inode, map, ppath,
3891 EXT4_GET_BLOCKS_CONVERT);
3894 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3896 return PTR_ERR(path);
3897 depth = ext_depth(inode);
3898 ex = path[depth].p_ext;
3901 err = ext4_ext_get_access(handle, inode, path + depth);
3904 /* first mark the extent as initialized */
3905 ext4_ext_mark_initialized(ex);
3907 /* note: ext4_ext_correct_indexes() isn't needed here because
3908 * borders are not changed
3910 ext4_ext_try_to_merge(handle, inode, path, ex);
3912 /* Mark modified extent as dirty */
3913 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3915 ext4_ext_show_leaf(inode, path);
3920 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3922 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3924 struct ext4_ext_path *path,
3928 struct ext4_extent_header *eh;
3929 struct ext4_extent *last_ex;
3931 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3934 depth = ext_depth(inode);
3935 eh = path[depth].p_hdr;
3938 * We're going to remove EOFBLOCKS_FL entirely in future so we
3939 * do not care for this case anymore. Simply remove the flag
3940 * if there are no extents.
3942 if (unlikely(!eh->eh_entries))
3944 last_ex = EXT_LAST_EXTENT(eh);
3946 * We should clear the EOFBLOCKS_FL flag if we are writing the
3947 * last block in the last extent in the file. We test this by
3948 * first checking to see if the caller to
3949 * ext4_ext_get_blocks() was interested in the last block (or
3950 * a block beyond the last block) in the current extent. If
3951 * this turns out to be false, we can bail out from this
3952 * function immediately.
3954 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3955 ext4_ext_get_actual_len(last_ex))
3958 * If the caller does appear to be planning to write at or
3959 * beyond the end of the current extent, we then test to see
3960 * if the current extent is the last extent in the file, by
3961 * checking to make sure it was reached via the rightmost node
3962 * at each level of the tree.
3964 for (i = depth-1; i >= 0; i--)
3965 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3968 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3969 return ext4_mark_inode_dirty(handle, inode);
3973 convert_initialized_extent(handle_t *handle, struct inode *inode,
3974 struct ext4_map_blocks *map,
3975 struct ext4_ext_path **ppath,
3976 unsigned int allocated)
3978 struct ext4_ext_path *path = *ppath;
3979 struct ext4_extent *ex;
3980 ext4_lblk_t ee_block;
3981 unsigned int ee_len;
3986 * Make sure that the extent is no bigger than we support with
3989 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3990 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3992 depth = ext_depth(inode);
3993 ex = path[depth].p_ext;
3994 ee_block = le32_to_cpu(ex->ee_block);
3995 ee_len = ext4_ext_get_actual_len(ex);
3997 ext_debug("%s: inode %lu, logical"
3998 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3999 (unsigned long long)ee_block, ee_len);
4001 if (ee_block != map->m_lblk || ee_len > map->m_len) {
4002 err = ext4_split_convert_extents(handle, inode, map, ppath,
4003 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
4006 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
4008 return PTR_ERR(path);
4009 depth = ext_depth(inode);
4010 ex = path[depth].p_ext;
4012 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
4013 (unsigned long) map->m_lblk);
4014 return -EFSCORRUPTED;
4018 err = ext4_ext_get_access(handle, inode, path + depth);
4021 /* first mark the extent as unwritten */
4022 ext4_ext_mark_unwritten(ex);
4024 /* note: ext4_ext_correct_indexes() isn't needed here because
4025 * borders are not changed
4027 ext4_ext_try_to_merge(handle, inode, path, ex);
4029 /* Mark modified extent as dirty */
4030 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4033 ext4_ext_show_leaf(inode, path);
4035 ext4_update_inode_fsync_trans(handle, inode, 1);
4036 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4039 map->m_flags |= EXT4_MAP_UNWRITTEN;
4040 if (allocated > map->m_len)
4041 allocated = map->m_len;
4042 map->m_len = allocated;
4047 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4048 struct ext4_map_blocks *map,
4049 struct ext4_ext_path **ppath, int flags,
4050 unsigned int allocated, ext4_fsblk_t newblock)
4052 struct ext4_ext_path *path = *ppath;
4056 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4057 "block %llu, max_blocks %u, flags %x, allocated %u\n",
4058 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4060 ext4_ext_show_leaf(inode, path);
4063 * When writing into unwritten space, we should not fail to
4064 * allocate metadata blocks for the new extent block if needed.
4066 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4068 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4069 allocated, newblock);
4071 /* get_block() before submit the IO, split the extent */
4072 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4073 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4074 flags | EXT4_GET_BLOCKS_CONVERT);
4077 map->m_flags |= EXT4_MAP_UNWRITTEN;
4080 /* IO end_io complete, convert the filled extent to written */
4081 if (flags & EXT4_GET_BLOCKS_CONVERT) {
4082 if (flags & EXT4_GET_BLOCKS_ZERO) {
4083 if (allocated > map->m_len)
4084 allocated = map->m_len;
4085 err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4090 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4093 ext4_update_inode_fsync_trans(handle, inode, 1);
4094 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4098 map->m_flags |= EXT4_MAP_MAPPED;
4099 map->m_pblk = newblock;
4100 if (allocated > map->m_len)
4101 allocated = map->m_len;
4102 map->m_len = allocated;
4105 /* buffered IO case */
4107 * repeat fallocate creation request
4108 * we already have an unwritten extent
4110 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4111 map->m_flags |= EXT4_MAP_UNWRITTEN;
4115 /* buffered READ or buffered write_begin() lookup */
4116 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4118 * We have blocks reserved already. We
4119 * return allocated blocks so that delalloc
4120 * won't do block reservation for us. But
4121 * the buffer head will be unmapped so that
4122 * a read from the block returns 0s.
4124 map->m_flags |= EXT4_MAP_UNWRITTEN;
4128 /* buffered write, writepage time, convert*/
4129 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4131 ext4_update_inode_fsync_trans(handle, inode, 1);
4138 map->m_flags |= EXT4_MAP_NEW;
4139 if (allocated > map->m_len)
4140 allocated = map->m_len;
4141 map->m_len = allocated;
4144 map->m_flags |= EXT4_MAP_MAPPED;
4145 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4146 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4152 if (allocated > map->m_len)
4153 allocated = map->m_len;
4154 ext4_ext_show_leaf(inode, path);
4155 map->m_pblk = newblock;
4156 map->m_len = allocated;
4158 return err ? err : allocated;
4162 * get_implied_cluster_alloc - check to see if the requested
4163 * allocation (in the map structure) overlaps with a cluster already
4164 * allocated in an extent.
4165 * @sb The filesystem superblock structure
4166 * @map The requested lblk->pblk mapping
4167 * @ex The extent structure which might contain an implied
4168 * cluster allocation
4170 * This function is called by ext4_ext_map_blocks() after we failed to
4171 * find blocks that were already in the inode's extent tree. Hence,
4172 * we know that the beginning of the requested region cannot overlap
4173 * the extent from the inode's extent tree. There are three cases we
4174 * want to catch. The first is this case:
4176 * |--- cluster # N--|
4177 * |--- extent ---| |---- requested region ---|
4180 * The second case that we need to test for is this one:
4182 * |--------- cluster # N ----------------|
4183 * |--- requested region --| |------- extent ----|
4184 * |=======================|
4186 * The third case is when the requested region lies between two extents
4187 * within the same cluster:
4188 * |------------- cluster # N-------------|
4189 * |----- ex -----| |---- ex_right ----|
4190 * |------ requested region ------|
4191 * |================|
4193 * In each of the above cases, we need to set the map->m_pblk and
4194 * map->m_len so it corresponds to the return the extent labelled as
4195 * "|====|" from cluster #N, since it is already in use for data in
4196 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4197 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4198 * as a new "allocated" block region. Otherwise, we will return 0 and
4199 * ext4_ext_map_blocks() will then allocate one or more new clusters
4200 * by calling ext4_mb_new_blocks().
4202 static int get_implied_cluster_alloc(struct super_block *sb,
4203 struct ext4_map_blocks *map,
4204 struct ext4_extent *ex,
4205 struct ext4_ext_path *path)
4207 struct ext4_sb_info *sbi = EXT4_SB(sb);
4208 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4209 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4210 ext4_lblk_t rr_cluster_start;
4211 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4212 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4213 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4215 /* The extent passed in that we are trying to match */
4216 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4217 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4219 /* The requested region passed into ext4_map_blocks() */
4220 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4222 if ((rr_cluster_start == ex_cluster_end) ||
4223 (rr_cluster_start == ex_cluster_start)) {
4224 if (rr_cluster_start == ex_cluster_end)
4225 ee_start += ee_len - 1;
4226 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4227 map->m_len = min(map->m_len,
4228 (unsigned) sbi->s_cluster_ratio - c_offset);
4230 * Check for and handle this case:
4232 * |--------- cluster # N-------------|
4233 * |------- extent ----|
4234 * |--- requested region ---|
4238 if (map->m_lblk < ee_block)
4239 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4242 * Check for the case where there is already another allocated
4243 * block to the right of 'ex' but before the end of the cluster.
4245 * |------------- cluster # N-------------|
4246 * |----- ex -----| |---- ex_right ----|
4247 * |------ requested region ------|
4248 * |================|
4250 if (map->m_lblk > ee_block) {
4251 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4252 map->m_len = min(map->m_len, next - map->m_lblk);
4255 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4259 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4265 * Block allocation/map/preallocation routine for extents based files
4268 * Need to be called with
4269 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4270 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4272 * return > 0, number of of blocks already mapped/allocated
4273 * if create == 0 and these are pre-allocated blocks
4274 * buffer head is unmapped
4275 * otherwise blocks are mapped
4277 * return = 0, if plain look up failed (blocks have not been allocated)
4278 * buffer head is unmapped
4280 * return < 0, error case.
4282 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4283 struct ext4_map_blocks *map, int flags)
4285 struct ext4_ext_path *path = NULL;
4286 struct ext4_extent newex, *ex, *ex2;
4287 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4288 ext4_fsblk_t newblock = 0;
4289 int free_on_err = 0, err = 0, depth, ret;
4290 unsigned int allocated = 0, offset = 0;
4291 unsigned int allocated_clusters = 0;
4292 struct ext4_allocation_request ar;
4293 ext4_lblk_t cluster_offset;
4294 bool map_from_cluster = false;
4296 ext_debug("blocks %u/%u requested for inode %lu\n",
4297 map->m_lblk, map->m_len, inode->i_ino);
4298 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4300 /* find extent for this block */
4301 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4303 err = PTR_ERR(path);
4308 depth = ext_depth(inode);
4311 * consistent leaf must not be empty;
4312 * this situation is possible, though, _during_ tree modification;
4313 * this is why assert can't be put in ext4_find_extent()
4315 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4316 EXT4_ERROR_INODE(inode, "bad extent address "
4317 "lblock: %lu, depth: %d pblock %lld",
4318 (unsigned long) map->m_lblk, depth,
4319 path[depth].p_block);
4320 err = -EFSCORRUPTED;
4324 ex = path[depth].p_ext;
4326 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4327 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4328 unsigned short ee_len;
4332 * unwritten extents are treated as holes, except that
4333 * we split out initialized portions during a write.
4335 ee_len = ext4_ext_get_actual_len(ex);
4337 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4339 /* if found extent covers block, simply return it */
4340 if (in_range(map->m_lblk, ee_block, ee_len)) {
4341 newblock = map->m_lblk - ee_block + ee_start;
4342 /* number of remaining blocks in the extent */
4343 allocated = ee_len - (map->m_lblk - ee_block);
4344 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4345 ee_block, ee_len, newblock);
4348 * If the extent is initialized check whether the
4349 * caller wants to convert it to unwritten.
4351 if ((!ext4_ext_is_unwritten(ex)) &&
4352 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4353 allocated = convert_initialized_extent(
4354 handle, inode, map, &path,
4357 } else if (!ext4_ext_is_unwritten(ex))
4360 ret = ext4_ext_handle_unwritten_extents(
4361 handle, inode, map, &path, flags,
4362 allocated, newblock);
4372 * requested block isn't allocated yet;
4373 * we couldn't try to create block if create flag is zero
4375 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4376 ext4_lblk_t hole_start, hole_len;
4378 hole_start = map->m_lblk;
4379 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4381 * put just found gap into cache to speed up
4382 * subsequent requests
4384 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4386 /* Update hole_len to reflect hole size after map->m_lblk */
4387 if (hole_start != map->m_lblk)
4388 hole_len -= map->m_lblk - hole_start;
4390 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4396 * Okay, we need to do block allocation.
4398 newex.ee_block = cpu_to_le32(map->m_lblk);
4399 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4402 * If we are doing bigalloc, check to see if the extent returned
4403 * by ext4_find_extent() implies a cluster we can use.
4405 if (cluster_offset && ex &&
4406 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4407 ar.len = allocated = map->m_len;
4408 newblock = map->m_pblk;
4409 map_from_cluster = true;
4410 goto got_allocated_blocks;
4413 /* find neighbour allocated blocks */
4414 ar.lleft = map->m_lblk;
4415 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4418 ar.lright = map->m_lblk;
4420 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4424 /* Check if the extent after searching to the right implies a
4425 * cluster we can use. */
4426 if ((sbi->s_cluster_ratio > 1) && ex2 &&
4427 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4428 ar.len = allocated = map->m_len;
4429 newblock = map->m_pblk;
4430 map_from_cluster = true;
4431 goto got_allocated_blocks;
4435 * See if request is beyond maximum number of blocks we can have in
4436 * a single extent. For an initialized extent this limit is
4437 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4438 * EXT_UNWRITTEN_MAX_LEN.
4440 if (map->m_len > EXT_INIT_MAX_LEN &&
4441 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4442 map->m_len = EXT_INIT_MAX_LEN;
4443 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4444 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4445 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4447 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4448 newex.ee_len = cpu_to_le16(map->m_len);
4449 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4451 allocated = ext4_ext_get_actual_len(&newex);
4453 allocated = map->m_len;
4455 /* allocate new block */
4457 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4458 ar.logical = map->m_lblk;
4460 * We calculate the offset from the beginning of the cluster
4461 * for the logical block number, since when we allocate a
4462 * physical cluster, the physical block should start at the
4463 * same offset from the beginning of the cluster. This is
4464 * needed so that future calls to get_implied_cluster_alloc()
4467 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4468 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4470 ar.logical -= offset;
4471 if (S_ISREG(inode->i_mode))
4472 ar.flags = EXT4_MB_HINT_DATA;
4474 /* disable in-core preallocation for non-regular files */
4476 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4477 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4478 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4479 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4480 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4481 ar.flags |= EXT4_MB_USE_RESERVED;
4482 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4485 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4486 ar.goal, newblock, allocated);
4488 allocated_clusters = ar.len;
4489 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4490 if (ar.len > allocated)
4493 got_allocated_blocks:
4494 /* try to insert new extent into found leaf and return */
4495 ext4_ext_store_pblock(&newex, newblock + offset);
4496 newex.ee_len = cpu_to_le16(ar.len);
4497 /* Mark unwritten */
4498 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4499 ext4_ext_mark_unwritten(&newex);
4500 map->m_flags |= EXT4_MAP_UNWRITTEN;
4504 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4505 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4508 err = ext4_ext_insert_extent(handle, inode, &path,
4511 if (err && free_on_err) {
4512 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4513 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4514 /* free data blocks we just allocated */
4515 /* not a good idea to call discard here directly,
4516 * but otherwise we'd need to call it every free() */
4517 ext4_discard_preallocations(inode);
4518 ext4_free_blocks(handle, inode, NULL, newblock,
4519 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4523 /* previous routine could use block we allocated */
4524 newblock = ext4_ext_pblock(&newex);
4525 allocated = ext4_ext_get_actual_len(&newex);
4526 if (allocated > map->m_len)
4527 allocated = map->m_len;
4528 map->m_flags |= EXT4_MAP_NEW;
4531 * Reduce the reserved cluster count to reflect successful deferred
4532 * allocation of delayed allocated clusters or direct allocation of
4533 * clusters discovered to be delayed allocated. Once allocated, a
4534 * cluster is not included in the reserved count.
4536 if (test_opt(inode->i_sb, DELALLOC) && !map_from_cluster) {
4537 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4539 * When allocating delayed allocated clusters, simply
4540 * reduce the reserved cluster count and claim quota
4542 ext4_da_update_reserve_space(inode, allocated_clusters,
4545 ext4_lblk_t lblk, len;
4549 * When allocating non-delayed allocated clusters
4550 * (from fallocate, filemap, DIO, or clusters
4551 * allocated when delalloc has been disabled by
4552 * ext4_nonda_switch), reduce the reserved cluster
4553 * count by the number of allocated clusters that
4554 * have previously been delayed allocated. Quota
4555 * has been claimed by ext4_mb_new_blocks() above,
4556 * so release the quota reservations made for any
4557 * previously delayed allocated clusters.
4559 lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
4560 len = allocated_clusters << sbi->s_cluster_bits;
4561 n = ext4_es_delayed_clu(inode, lblk, len);
4563 ext4_da_update_reserve_space(inode, (int) n, 0);
4568 * Cache the extent and update transaction to commit on fdatasync only
4569 * when it is _not_ an unwritten extent.
4571 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4572 ext4_update_inode_fsync_trans(handle, inode, 1);
4574 ext4_update_inode_fsync_trans(handle, inode, 0);
4576 if (allocated > map->m_len)
4577 allocated = map->m_len;
4578 ext4_ext_show_leaf(inode, path);
4579 map->m_flags |= EXT4_MAP_MAPPED;
4580 map->m_pblk = newblock;
4581 map->m_len = allocated;
4583 ext4_ext_drop_refs(path);
4586 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4587 err ? err : allocated);
4588 return err ? err : allocated;
4591 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4593 struct super_block *sb = inode->i_sb;
4594 ext4_lblk_t last_block;
4598 * TODO: optimization is possible here.
4599 * Probably we need not scan at all,
4600 * because page truncation is enough.
4603 /* we have to know where to truncate from in crash case */
4604 EXT4_I(inode)->i_disksize = inode->i_size;
4605 err = ext4_mark_inode_dirty(handle, inode);
4609 last_block = (inode->i_size + sb->s_blocksize - 1)
4610 >> EXT4_BLOCK_SIZE_BITS(sb);
4612 err = ext4_es_remove_extent(inode, last_block,
4613 EXT_MAX_BLOCKS - last_block);
4614 if (err == -ENOMEM) {
4616 congestion_wait(BLK_RW_ASYNC, HZ/50);
4621 return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4624 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4625 ext4_lblk_t len, loff_t new_size,
4628 struct inode *inode = file_inode(file);
4634 struct ext4_map_blocks map;
4635 unsigned int credits;
4638 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4639 map.m_lblk = offset;
4642 * Don't normalize the request if it can fit in one extent so
4643 * that it doesn't get unnecessarily split into multiple
4646 if (len <= EXT_UNWRITTEN_MAX_LEN)
4647 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4650 * credits to insert 1 extent into extent tree
4652 credits = ext4_chunk_trans_blocks(inode, len);
4653 depth = ext_depth(inode);
4656 while (ret >= 0 && len) {
4658 * Recalculate credits when extent tree depth changes.
4660 if (depth != ext_depth(inode)) {
4661 credits = ext4_chunk_trans_blocks(inode, len);
4662 depth = ext_depth(inode);
4665 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4667 if (IS_ERR(handle)) {
4668 ret = PTR_ERR(handle);
4671 ret = ext4_map_blocks(handle, inode, &map, flags);
4673 ext4_debug("inode #%lu: block %u: len %u: "
4674 "ext4_ext_map_blocks returned %d",
4675 inode->i_ino, map.m_lblk,
4677 ext4_mark_inode_dirty(handle, inode);
4678 ret2 = ext4_journal_stop(handle);
4682 map.m_len = len = len - ret;
4683 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4684 inode->i_ctime = current_time(inode);
4686 if (epos > new_size)
4688 if (ext4_update_inode_size(inode, epos) & 0x1)
4689 inode->i_mtime = inode->i_ctime;
4691 if (epos > inode->i_size)
4692 ext4_set_inode_flag(inode,
4693 EXT4_INODE_EOFBLOCKS);
4695 ext4_mark_inode_dirty(handle, inode);
4696 ext4_update_inode_fsync_trans(handle, inode, 1);
4697 ret2 = ext4_journal_stop(handle);
4701 if (ret == -ENOSPC &&
4702 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4707 return ret > 0 ? ret2 : ret;
4710 static long ext4_zero_range(struct file *file, loff_t offset,
4711 loff_t len, int mode)
4713 struct inode *inode = file_inode(file);
4714 handle_t *handle = NULL;
4715 unsigned int max_blocks;
4716 loff_t new_size = 0;
4720 int partial_begin, partial_end;
4723 unsigned int blkbits = inode->i_blkbits;
4725 trace_ext4_zero_range(inode, offset, len, mode);
4727 if (!S_ISREG(inode->i_mode))
4730 /* Call ext4_force_commit to flush all data in case of data=journal. */
4731 if (ext4_should_journal_data(inode)) {
4732 ret = ext4_force_commit(inode->i_sb);
4738 * Round up offset. This is not fallocate, we neet to zero out
4739 * blocks, so convert interior block aligned part of the range to
4740 * unwritten and possibly manually zero out unaligned parts of the
4743 start = round_up(offset, 1 << blkbits);
4744 end = round_down((offset + len), 1 << blkbits);
4746 if (start < offset || end > offset + len)
4748 partial_begin = offset & ((1 << blkbits) - 1);
4749 partial_end = (offset + len) & ((1 << blkbits) - 1);
4751 lblk = start >> blkbits;
4752 max_blocks = (end >> blkbits);
4753 if (max_blocks < lblk)
4761 * Indirect files do not support unwritten extnets
4763 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4768 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4769 (offset + len > i_size_read(inode) ||
4770 offset + len > EXT4_I(inode)->i_disksize)) {
4771 new_size = offset + len;
4772 ret = inode_newsize_ok(inode, new_size);
4777 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4778 if (mode & FALLOC_FL_KEEP_SIZE)
4779 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4781 /* Wait all existing dio workers, newcomers will block on i_mutex */
4782 inode_dio_wait(inode);
4784 /* Preallocate the range including the unaligned edges */
4785 if (partial_begin || partial_end) {
4786 ret = ext4_alloc_file_blocks(file,
4787 round_down(offset, 1 << blkbits) >> blkbits,
4788 (round_up((offset + len), 1 << blkbits) -
4789 round_down(offset, 1 << blkbits)) >> blkbits,
4796 /* Zero range excluding the unaligned edges */
4797 if (max_blocks > 0) {
4798 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4802 * Prevent page faults from reinstantiating pages we have
4803 * released from page cache.
4805 down_write(&EXT4_I(inode)->i_mmap_sem);
4807 ret = ext4_break_layouts(inode);
4809 up_write(&EXT4_I(inode)->i_mmap_sem);
4813 ret = ext4_update_disksize_before_punch(inode, offset, len);
4815 up_write(&EXT4_I(inode)->i_mmap_sem);
4818 /* Now release the pages and zero block aligned part of pages */
4819 truncate_pagecache_range(inode, start, end - 1);
4820 inode->i_mtime = inode->i_ctime = current_time(inode);
4822 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4824 up_write(&EXT4_I(inode)->i_mmap_sem);
4828 if (!partial_begin && !partial_end)
4832 * In worst case we have to writeout two nonadjacent unwritten
4833 * blocks and update the inode
4835 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4836 if (ext4_should_journal_data(inode))
4838 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4839 if (IS_ERR(handle)) {
4840 ret = PTR_ERR(handle);
4841 ext4_std_error(inode->i_sb, ret);
4845 inode->i_mtime = inode->i_ctime = current_time(inode);
4847 ext4_update_inode_size(inode, new_size);
4850 * Mark that we allocate beyond EOF so the subsequent truncate
4851 * can proceed even if the new size is the same as i_size.
4853 if ((offset + len) > i_size_read(inode))
4854 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4856 ext4_mark_inode_dirty(handle, inode);
4858 /* Zero out partial block at the edges of the range */
4859 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4861 ext4_update_inode_fsync_trans(handle, inode, 1);
4863 if (file->f_flags & O_SYNC)
4864 ext4_handle_sync(handle);
4866 ext4_journal_stop(handle);
4868 inode_unlock(inode);
4873 * preallocate space for a file. This implements ext4's fallocate file
4874 * operation, which gets called from sys_fallocate system call.
4875 * For block-mapped files, posix_fallocate should fall back to the method
4876 * of writing zeroes to the required new blocks (the same behavior which is
4877 * expected for file systems which do not support fallocate() system call).
4879 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4881 struct inode *inode = file_inode(file);
4882 loff_t new_size = 0;
4883 unsigned int max_blocks;
4887 unsigned int blkbits = inode->i_blkbits;
4890 * Encrypted inodes can't handle collapse range or insert
4891 * range since we would need to re-encrypt blocks with a
4892 * different IV or XTS tweak (which are based on the logical
4895 if (IS_ENCRYPTED(inode) &&
4896 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
4899 /* Return error if mode is not supported */
4900 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4901 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4902 FALLOC_FL_INSERT_RANGE))
4905 if (mode & FALLOC_FL_PUNCH_HOLE)
4906 return ext4_punch_hole(inode, offset, len);
4908 ret = ext4_convert_inline_data(inode);
4912 if (mode & FALLOC_FL_COLLAPSE_RANGE)
4913 return ext4_collapse_range(inode, offset, len);
4915 if (mode & FALLOC_FL_INSERT_RANGE)
4916 return ext4_insert_range(inode, offset, len);
4918 if (mode & FALLOC_FL_ZERO_RANGE)
4919 return ext4_zero_range(file, offset, len, mode);
4921 trace_ext4_fallocate_enter(inode, offset, len, mode);
4922 lblk = offset >> blkbits;
4924 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4925 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4926 if (mode & FALLOC_FL_KEEP_SIZE)
4927 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4932 * We only support preallocation for extent-based files only
4934 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4939 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4940 (offset + len > i_size_read(inode) ||
4941 offset + len > EXT4_I(inode)->i_disksize)) {
4942 new_size = offset + len;
4943 ret = inode_newsize_ok(inode, new_size);
4948 /* Wait all existing dio workers, newcomers will block on i_mutex */
4949 inode_dio_wait(inode);
4951 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
4955 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
4956 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
4957 EXT4_I(inode)->i_sync_tid);
4960 inode_unlock(inode);
4961 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
4966 * This function convert a range of blocks to written extents
4967 * The caller of this function will pass the start offset and the size.
4968 * all unwritten extents within this range will be converted to
4971 * This function is called from the direct IO end io call back
4972 * function, to convert the fallocated extents after IO is completed.
4973 * Returns 0 on success.
4975 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
4976 loff_t offset, ssize_t len)
4978 unsigned int max_blocks;
4981 struct ext4_map_blocks map;
4982 unsigned int blkbits = inode->i_blkbits;
4983 unsigned int credits = 0;
4985 map.m_lblk = offset >> blkbits;
4986 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4990 * credits to insert 1 extent into extent tree
4992 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4994 while (ret >= 0 && ret < max_blocks) {
4996 map.m_len = (max_blocks -= ret);
4998 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5000 if (IS_ERR(handle)) {
5001 ret = PTR_ERR(handle);
5005 ret = ext4_map_blocks(handle, inode, &map,
5006 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5008 ext4_warning(inode->i_sb,
5009 "inode #%lu: block %u: len %u: "
5010 "ext4_ext_map_blocks returned %d",
5011 inode->i_ino, map.m_lblk,
5013 ext4_mark_inode_dirty(handle, inode);
5015 ret2 = ext4_journal_stop(handle);
5016 if (ret <= 0 || ret2)
5019 return ret > 0 ? ret2 : ret;
5022 int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
5025 struct ext4_io_end_vec *io_end_vec;
5028 * This is somewhat ugly but the idea is clear: When transaction is
5029 * reserved, everything goes into it. Otherwise we rather start several
5030 * smaller transactions for conversion of each extent separately.
5033 handle = ext4_journal_start_reserved(handle,
5034 EXT4_HT_EXT_CONVERT);
5036 return PTR_ERR(handle);
5039 list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
5040 ret = ext4_convert_unwritten_extents(handle, io_end->inode,
5048 err = ext4_journal_stop(handle);
5050 return ret < 0 ? ret : err;
5054 * If newes is not existing extent (newes->ec_pblk equals zero) find
5055 * delayed extent at start of newes and update newes accordingly and
5056 * return start of the next delayed extent.
5058 * If newes is existing extent (newes->ec_pblk is not equal zero)
5059 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5060 * extent found. Leave newes unmodified.
5062 static int ext4_find_delayed_extent(struct inode *inode,
5063 struct extent_status *newes)
5065 struct extent_status es;
5066 ext4_lblk_t block, next_del;
5068 if (newes->es_pblk == 0) {
5069 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
5071 newes->es_lblk + newes->es_len - 1,
5075 * No extent in extent-tree contains block @newes->es_pblk,
5076 * then the block may stay in 1)a hole or 2)delayed-extent.
5082 if (es.es_lblk > newes->es_lblk) {
5084 newes->es_len = min(es.es_lblk - newes->es_lblk,
5089 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5092 block = newes->es_lblk + newes->es_len;
5093 ext4_es_find_extent_range(inode, &ext4_es_is_delayed, block,
5094 EXT_MAX_BLOCKS, &es);
5096 next_del = EXT_MAX_BLOCKS;
5098 next_del = es.es_lblk;
5103 static int ext4_xattr_fiemap(struct inode *inode,
5104 struct fiemap_extent_info *fieinfo)
5108 __u32 flags = FIEMAP_EXTENT_LAST;
5109 int blockbits = inode->i_sb->s_blocksize_bits;
5113 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5114 struct ext4_iloc iloc;
5115 int offset; /* offset of xattr in inode */
5117 error = ext4_get_inode_loc(inode, &iloc);
5120 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5121 offset = EXT4_GOOD_OLD_INODE_SIZE +
5122 EXT4_I(inode)->i_extra_isize;
5124 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5125 flags |= FIEMAP_EXTENT_DATA_INLINE;
5127 } else { /* external block */
5128 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5129 length = inode->i_sb->s_blocksize;
5133 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5135 return (error < 0 ? error : 0);
5138 static int _ext4_fiemap(struct inode *inode,
5139 struct fiemap_extent_info *fieinfo,
5140 __u64 start, __u64 len,
5141 int (*fill)(struct inode *, ext4_lblk_t,
5143 struct fiemap_extent_info *))
5145 ext4_lblk_t start_blk;
5146 u32 ext4_fiemap_flags = FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR;
5150 if (ext4_has_inline_data(inode)) {
5153 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5160 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5161 error = ext4_ext_precache(inode);
5164 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
5167 /* fallback to generic here if not in extents fmt */
5168 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
5169 fill == ext4_fill_fiemap_extents)
5170 return generic_block_fiemap(inode, fieinfo, start, len,
5173 if (fill == ext4_fill_es_cache_info)
5174 ext4_fiemap_flags &= FIEMAP_FLAG_XATTR;
5175 if (fiemap_check_flags(fieinfo, ext4_fiemap_flags))
5178 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5179 error = ext4_xattr_fiemap(inode, fieinfo);
5181 ext4_lblk_t len_blks;
5184 start_blk = start >> inode->i_sb->s_blocksize_bits;
5185 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5186 if (last_blk >= EXT_MAX_BLOCKS)
5187 last_blk = EXT_MAX_BLOCKS-1;
5188 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5191 * Walk the extent tree gathering extent information
5192 * and pushing extents back to the user.
5194 error = fill(inode, start_blk, len_blks, fieinfo);
5199 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5200 __u64 start, __u64 len)
5202 return _ext4_fiemap(inode, fieinfo, start, len,
5203 ext4_fill_fiemap_extents);
5206 int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
5207 __u64 start, __u64 len)
5209 if (ext4_has_inline_data(inode)) {
5212 down_read(&EXT4_I(inode)->xattr_sem);
5213 has_inline = ext4_has_inline_data(inode);
5214 up_read(&EXT4_I(inode)->xattr_sem);
5219 return _ext4_fiemap(inode, fieinfo, start, len,
5220 ext4_fill_es_cache_info);
5226 * Function to access the path buffer for marking it dirty.
5227 * It also checks if there are sufficient credits left in the journal handle
5231 ext4_access_path(handle_t *handle, struct inode *inode,
5232 struct ext4_ext_path *path)
5236 if (!ext4_handle_valid(handle))
5240 * Check if need to extend journal credits
5241 * 3 for leaf, sb, and inode plus 2 (bmap and group
5242 * descriptor) for each block group; assume two block
5245 credits = ext4_writepage_trans_blocks(inode);
5246 err = ext4_datasem_ensure_credits(handle, inode, 7, credits, 0);
5250 err = ext4_ext_get_access(handle, inode, path);
5255 * ext4_ext_shift_path_extents:
5256 * Shift the extents of a path structure lying between path[depth].p_ext
5257 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5258 * if it is right shift or left shift operation.
5261 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5262 struct inode *inode, handle_t *handle,
5263 enum SHIFT_DIRECTION SHIFT)
5266 struct ext4_extent *ex_start, *ex_last;
5267 bool update = false;
5268 depth = path->p_depth;
5270 while (depth >= 0) {
5271 if (depth == path->p_depth) {
5272 ex_start = path[depth].p_ext;
5274 return -EFSCORRUPTED;
5276 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5278 err = ext4_access_path(handle, inode, path + depth);
5282 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5285 while (ex_start <= ex_last) {
5286 if (SHIFT == SHIFT_LEFT) {
5287 le32_add_cpu(&ex_start->ee_block,
5289 /* Try to merge to the left. */
5291 EXT_FIRST_EXTENT(path[depth].p_hdr))
5293 ext4_ext_try_to_merge_right(inode,
5294 path, ex_start - 1))
5299 le32_add_cpu(&ex_last->ee_block, shift);
5300 ext4_ext_try_to_merge_right(inode, path,
5305 err = ext4_ext_dirty(handle, inode, path + depth);
5309 if (--depth < 0 || !update)
5313 /* Update index too */
5314 err = ext4_access_path(handle, inode, path + depth);
5318 if (SHIFT == SHIFT_LEFT)
5319 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5321 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5322 err = ext4_ext_dirty(handle, inode, path + depth);
5326 /* we are done if current index is not a starting index */
5327 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5338 * ext4_ext_shift_extents:
5339 * All the extents which lies in the range from @start to the last allocated
5340 * block for the @inode are shifted either towards left or right (depending
5341 * upon @SHIFT) by @shift blocks.
5342 * On success, 0 is returned, error otherwise.
5345 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5346 ext4_lblk_t start, ext4_lblk_t shift,
5347 enum SHIFT_DIRECTION SHIFT)
5349 struct ext4_ext_path *path;
5351 struct ext4_extent *extent;
5352 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5354 /* Let path point to the last extent */
5355 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5358 return PTR_ERR(path);
5360 depth = path->p_depth;
5361 extent = path[depth].p_ext;
5365 stop = le32_to_cpu(extent->ee_block);
5368 * For left shifts, make sure the hole on the left is big enough to
5369 * accommodate the shift. For right shifts, make sure the last extent
5370 * won't be shifted beyond EXT_MAX_BLOCKS.
5372 if (SHIFT == SHIFT_LEFT) {
5373 path = ext4_find_extent(inode, start - 1, &path,
5376 return PTR_ERR(path);
5377 depth = path->p_depth;
5378 extent = path[depth].p_ext;
5380 ex_start = le32_to_cpu(extent->ee_block);
5381 ex_end = le32_to_cpu(extent->ee_block) +
5382 ext4_ext_get_actual_len(extent);
5388 if ((start == ex_start && shift > ex_start) ||
5389 (shift > start - ex_end)) {
5394 if (shift > EXT_MAX_BLOCKS -
5395 (stop + ext4_ext_get_actual_len(extent))) {
5402 * In case of left shift, iterator points to start and it is increased
5403 * till we reach stop. In case of right shift, iterator points to stop
5404 * and it is decreased till we reach start.
5406 if (SHIFT == SHIFT_LEFT)
5412 * Its safe to start updating extents. Start and stop are unsigned, so
5413 * in case of right shift if extent with 0 block is reached, iterator
5414 * becomes NULL to indicate the end of the loop.
5416 while (iterator && start <= stop) {
5417 path = ext4_find_extent(inode, *iterator, &path,
5420 return PTR_ERR(path);
5421 depth = path->p_depth;
5422 extent = path[depth].p_ext;
5424 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5425 (unsigned long) *iterator);
5426 return -EFSCORRUPTED;
5428 if (SHIFT == SHIFT_LEFT && *iterator >
5429 le32_to_cpu(extent->ee_block)) {
5430 /* Hole, move to the next extent */
5431 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5432 path[depth].p_ext++;
5434 *iterator = ext4_ext_next_allocated_block(path);
5439 if (SHIFT == SHIFT_LEFT) {
5440 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5441 *iterator = le32_to_cpu(extent->ee_block) +
5442 ext4_ext_get_actual_len(extent);
5444 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5445 if (le32_to_cpu(extent->ee_block) > 0)
5446 *iterator = le32_to_cpu(extent->ee_block) - 1;
5448 /* Beginning is reached, end of the loop */
5450 /* Update path extent in case we need to stop */
5451 while (le32_to_cpu(extent->ee_block) < start)
5453 path[depth].p_ext = extent;
5455 ret = ext4_ext_shift_path_extents(path, shift, inode,
5461 ext4_ext_drop_refs(path);
5467 * ext4_collapse_range:
5468 * This implements the fallocate's collapse range functionality for ext4
5469 * Returns: 0 and non-zero on error.
5471 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5473 struct super_block *sb = inode->i_sb;
5474 ext4_lblk_t punch_start, punch_stop;
5476 unsigned int credits;
5477 loff_t new_size, ioffset;
5481 * We need to test this early because xfstests assumes that a
5482 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5483 * system does not support collapse range.
5485 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5488 /* Collapse range works only on fs block size aligned offsets. */
5489 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5490 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5493 if (!S_ISREG(inode->i_mode))
5496 trace_ext4_collapse_range(inode, offset, len);
5498 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5499 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5501 /* Call ext4_force_commit to flush all data in case of data=journal. */
5502 if (ext4_should_journal_data(inode)) {
5503 ret = ext4_force_commit(inode->i_sb);
5510 * There is no need to overlap collapse range with EOF, in which case
5511 * it is effectively a truncate operation
5513 if (offset + len >= i_size_read(inode)) {
5518 /* Currently just for extent based files */
5519 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5524 /* Wait for existing dio to complete */
5525 inode_dio_wait(inode);
5528 * Prevent page faults from reinstantiating pages we have released from
5531 down_write(&EXT4_I(inode)->i_mmap_sem);
5533 ret = ext4_break_layouts(inode);
5538 * Need to round down offset to be aligned with page size boundary
5539 * for page size > block size.
5541 ioffset = round_down(offset, PAGE_SIZE);
5543 * Write tail of the last page before removed range since it will get
5544 * removed from the page cache below.
5546 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5550 * Write data that will be shifted to preserve them when discarding
5551 * page cache below. We are also protected from pages becoming dirty
5554 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5558 truncate_pagecache(inode, ioffset);
5560 credits = ext4_writepage_trans_blocks(inode);
5561 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5562 if (IS_ERR(handle)) {
5563 ret = PTR_ERR(handle);
5567 down_write(&EXT4_I(inode)->i_data_sem);
5568 ext4_discard_preallocations(inode);
5570 ret = ext4_es_remove_extent(inode, punch_start,
5571 EXT_MAX_BLOCKS - punch_start);
5573 up_write(&EXT4_I(inode)->i_data_sem);
5577 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5579 up_write(&EXT4_I(inode)->i_data_sem);
5582 ext4_discard_preallocations(inode);
5584 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5585 punch_stop - punch_start, SHIFT_LEFT);
5587 up_write(&EXT4_I(inode)->i_data_sem);
5591 new_size = i_size_read(inode) - len;
5592 i_size_write(inode, new_size);
5593 EXT4_I(inode)->i_disksize = new_size;
5595 up_write(&EXT4_I(inode)->i_data_sem);
5597 ext4_handle_sync(handle);
5598 inode->i_mtime = inode->i_ctime = current_time(inode);
5599 ext4_mark_inode_dirty(handle, inode);
5600 ext4_update_inode_fsync_trans(handle, inode, 1);
5603 ext4_journal_stop(handle);
5605 up_write(&EXT4_I(inode)->i_mmap_sem);
5607 inode_unlock(inode);
5612 * ext4_insert_range:
5613 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5614 * The data blocks starting from @offset to the EOF are shifted by @len
5615 * towards right to create a hole in the @inode. Inode size is increased
5617 * Returns 0 on success, error otherwise.
5619 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5621 struct super_block *sb = inode->i_sb;
5623 struct ext4_ext_path *path;
5624 struct ext4_extent *extent;
5625 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5626 unsigned int credits, ee_len;
5627 int ret = 0, depth, split_flag = 0;
5631 * We need to test this early because xfstests assumes that an
5632 * insert range of (0, 1) will return EOPNOTSUPP if the file
5633 * system does not support insert range.
5635 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5638 /* Insert range works only on fs block size aligned offsets. */
5639 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5640 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5643 if (!S_ISREG(inode->i_mode))
5646 trace_ext4_insert_range(inode, offset, len);
5648 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5649 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5651 /* Call ext4_force_commit to flush all data in case of data=journal */
5652 if (ext4_should_journal_data(inode)) {
5653 ret = ext4_force_commit(inode->i_sb);
5659 /* Currently just for extent based files */
5660 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5665 /* Check for wrap through zero */
5666 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5671 /* Offset should be less than i_size */
5672 if (offset >= i_size_read(inode)) {
5677 /* Wait for existing dio to complete */
5678 inode_dio_wait(inode);
5681 * Prevent page faults from reinstantiating pages we have released from
5684 down_write(&EXT4_I(inode)->i_mmap_sem);
5686 ret = ext4_break_layouts(inode);
5691 * Need to round down to align start offset to page size boundary
5692 * for page size > block size.
5694 ioffset = round_down(offset, PAGE_SIZE);
5695 /* Write out all dirty pages */
5696 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5700 truncate_pagecache(inode, ioffset);
5702 credits = ext4_writepage_trans_blocks(inode);
5703 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5704 if (IS_ERR(handle)) {
5705 ret = PTR_ERR(handle);
5709 /* Expand file to avoid data loss if there is error while shifting */
5710 inode->i_size += len;
5711 EXT4_I(inode)->i_disksize += len;
5712 inode->i_mtime = inode->i_ctime = current_time(inode);
5713 ret = ext4_mark_inode_dirty(handle, inode);
5717 down_write(&EXT4_I(inode)->i_data_sem);
5718 ext4_discard_preallocations(inode);
5720 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5722 up_write(&EXT4_I(inode)->i_data_sem);
5726 depth = ext_depth(inode);
5727 extent = path[depth].p_ext;
5729 ee_start_lblk = le32_to_cpu(extent->ee_block);
5730 ee_len = ext4_ext_get_actual_len(extent);
5733 * If offset_lblk is not the starting block of extent, split
5734 * the extent @offset_lblk
5736 if ((offset_lblk > ee_start_lblk) &&
5737 (offset_lblk < (ee_start_lblk + ee_len))) {
5738 if (ext4_ext_is_unwritten(extent))
5739 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5740 EXT4_EXT_MARK_UNWRIT2;
5741 ret = ext4_split_extent_at(handle, inode, &path,
5742 offset_lblk, split_flag,
5744 EXT4_GET_BLOCKS_PRE_IO |
5745 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5748 ext4_ext_drop_refs(path);
5751 up_write(&EXT4_I(inode)->i_data_sem);
5755 ext4_ext_drop_refs(path);
5759 ret = ext4_es_remove_extent(inode, offset_lblk,
5760 EXT_MAX_BLOCKS - offset_lblk);
5762 up_write(&EXT4_I(inode)->i_data_sem);
5767 * if offset_lblk lies in a hole which is at start of file, use
5768 * ee_start_lblk to shift extents
5770 ret = ext4_ext_shift_extents(inode, handle,
5771 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5772 len_lblk, SHIFT_RIGHT);
5774 up_write(&EXT4_I(inode)->i_data_sem);
5776 ext4_handle_sync(handle);
5778 ext4_update_inode_fsync_trans(handle, inode, 1);
5781 ext4_journal_stop(handle);
5783 up_write(&EXT4_I(inode)->i_mmap_sem);
5785 inode_unlock(inode);
5790 * ext4_swap_extents() - Swap extents between two inodes
5791 * @handle: handle for this transaction
5792 * @inode1: First inode
5793 * @inode2: Second inode
5794 * @lblk1: Start block for first inode
5795 * @lblk2: Start block for second inode
5796 * @count: Number of blocks to swap
5797 * @unwritten: Mark second inode's extents as unwritten after swap
5798 * @erp: Pointer to save error value
5800 * This helper routine does exactly what is promise "swap extents". All other
5801 * stuff such as page-cache locking consistency, bh mapping consistency or
5802 * extent's data copying must be performed by caller.
5804 * i_mutex is held for both inodes
5805 * i_data_sem is locked for write for both inodes
5807 * All pages from requested range are locked for both inodes
5810 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5811 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5812 ext4_lblk_t count, int unwritten, int *erp)
5814 struct ext4_ext_path *path1 = NULL;
5815 struct ext4_ext_path *path2 = NULL;
5816 int replaced_count = 0;
5818 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5819 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5820 BUG_ON(!inode_is_locked(inode1));
5821 BUG_ON(!inode_is_locked(inode2));
5823 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5826 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5831 struct ext4_extent *ex1, *ex2, tmp_ex;
5832 ext4_lblk_t e1_blk, e2_blk;
5833 int e1_len, e2_len, len;
5836 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5837 if (IS_ERR(path1)) {
5838 *erp = PTR_ERR(path1);
5844 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5845 if (IS_ERR(path2)) {
5846 *erp = PTR_ERR(path2);
5850 ex1 = path1[path1->p_depth].p_ext;
5851 ex2 = path2[path2->p_depth].p_ext;
5852 /* Do we have somthing to swap ? */
5853 if (unlikely(!ex2 || !ex1))
5856 e1_blk = le32_to_cpu(ex1->ee_block);
5857 e2_blk = le32_to_cpu(ex2->ee_block);
5858 e1_len = ext4_ext_get_actual_len(ex1);
5859 e2_len = ext4_ext_get_actual_len(ex2);
5862 if (!in_range(lblk1, e1_blk, e1_len) ||
5863 !in_range(lblk2, e2_blk, e2_len)) {
5864 ext4_lblk_t next1, next2;
5866 /* if hole after extent, then go to next extent */
5867 next1 = ext4_ext_next_allocated_block(path1);
5868 next2 = ext4_ext_next_allocated_block(path2);
5869 /* If hole before extent, then shift to that extent */
5874 /* Do we have something to swap */
5875 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5877 /* Move to the rightest boundary */
5878 len = next1 - lblk1;
5879 if (len < next2 - lblk2)
5880 len = next2 - lblk2;
5889 /* Prepare left boundary */
5890 if (e1_blk < lblk1) {
5892 *erp = ext4_force_split_extent_at(handle, inode1,
5897 if (e2_blk < lblk2) {
5899 *erp = ext4_force_split_extent_at(handle, inode2,
5904 /* ext4_split_extent_at() may result in leaf extent split,
5905 * path must to be revalidated. */
5909 /* Prepare right boundary */
5911 if (len > e1_blk + e1_len - lblk1)
5912 len = e1_blk + e1_len - lblk1;
5913 if (len > e2_blk + e2_len - lblk2)
5914 len = e2_blk + e2_len - lblk2;
5916 if (len != e1_len) {
5918 *erp = ext4_force_split_extent_at(handle, inode1,
5919 &path1, lblk1 + len, 0);
5923 if (len != e2_len) {
5925 *erp = ext4_force_split_extent_at(handle, inode2,
5926 &path2, lblk2 + len, 0);
5930 /* ext4_split_extent_at() may result in leaf extent split,
5931 * path must to be revalidated. */
5935 BUG_ON(e2_len != e1_len);
5936 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5939 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5943 /* Both extents are fully inside boundaries. Swap it now */
5945 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5946 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5947 ex1->ee_len = cpu_to_le16(e2_len);
5948 ex2->ee_len = cpu_to_le16(e1_len);
5950 ext4_ext_mark_unwritten(ex2);
5951 if (ext4_ext_is_unwritten(&tmp_ex))
5952 ext4_ext_mark_unwritten(ex1);
5954 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5955 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5956 *erp = ext4_ext_dirty(handle, inode2, path2 +
5960 *erp = ext4_ext_dirty(handle, inode1, path1 +
5963 * Looks scarry ah..? second inode already points to new blocks,
5964 * and it was successfully dirtied. But luckily error may happen
5965 * only due to journal error, so full transaction will be
5972 replaced_count += len;
5976 ext4_ext_drop_refs(path1);
5978 ext4_ext_drop_refs(path2);
5980 path1 = path2 = NULL;
5982 return replaced_count;
5986 * ext4_clu_mapped - determine whether any block in a logical cluster has
5987 * been mapped to a physical cluster
5989 * @inode - file containing the logical cluster
5990 * @lclu - logical cluster of interest
5992 * Returns 1 if any block in the logical cluster is mapped, signifying
5993 * that a physical cluster has been allocated for it. Otherwise,
5994 * returns 0. Can also return negative error codes. Derived from
5995 * ext4_ext_map_blocks().
5997 int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
5999 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6000 struct ext4_ext_path *path;
6001 int depth, mapped = 0, err = 0;
6002 struct ext4_extent *extent;
6003 ext4_lblk_t first_lblk, first_lclu, last_lclu;
6005 /* search for the extent closest to the first block in the cluster */
6006 path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
6008 err = PTR_ERR(path);
6013 depth = ext_depth(inode);
6016 * A consistent leaf must not be empty. This situation is possible,
6017 * though, _during_ tree modification, and it's why an assert can't
6018 * be put in ext4_find_extent().
6020 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
6021 EXT4_ERROR_INODE(inode,
6022 "bad extent address - lblock: %lu, depth: %d, pblock: %lld",
6023 (unsigned long) EXT4_C2B(sbi, lclu),
6024 depth, path[depth].p_block);
6025 err = -EFSCORRUPTED;
6029 extent = path[depth].p_ext;
6031 /* can't be mapped if the extent tree is empty */
6035 first_lblk = le32_to_cpu(extent->ee_block);
6036 first_lclu = EXT4_B2C(sbi, first_lblk);
6039 * Three possible outcomes at this point - found extent spanning
6040 * the target cluster, to the left of the target cluster, or to the
6041 * right of the target cluster. The first two cases are handled here.
6042 * The last case indicates the target cluster is not mapped.
6044 if (lclu >= first_lclu) {
6045 last_lclu = EXT4_B2C(sbi, first_lblk +
6046 ext4_ext_get_actual_len(extent) - 1);
6047 if (lclu <= last_lclu) {
6050 first_lblk = ext4_ext_next_allocated_block(path);
6051 first_lclu = EXT4_B2C(sbi, first_lblk);
6052 if (lclu == first_lclu)
6058 ext4_ext_drop_refs(path);
6061 return err ? err : mapped;