2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
5 * Architecture independence:
6 * Copyright (c) 2005, Bull S.A.
7 * Written by Pierre Peiffer <pierre.peiffer@bull.net>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
24 * Extents support for EXT4
27 * - ext4*_error() should be used in some situations
28 * - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29 * - smart tree reduction
33 #include <linux/time.h>
34 #include <linux/jbd2.h>
35 #include <linux/highuid.h>
36 #include <linux/pagemap.h>
37 #include <linux/quotaops.h>
38 #include <linux/string.h>
39 #include <linux/slab.h>
40 #include <linux/uaccess.h>
41 #include <linux/fiemap.h>
42 #include <linux/backing-dev.h>
43 #include "ext4_jbd2.h"
44 #include "ext4_extents.h"
47 #include <trace/events/ext4.h>
50 * used by extent splitting.
52 #define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
54 #define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
55 #define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
57 #define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
58 #define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
60 static __le32 ext4_extent_block_csum(struct inode *inode,
61 struct ext4_extent_header *eh)
63 struct ext4_inode_info *ei = EXT4_I(inode);
64 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
67 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
68 EXT4_EXTENT_TAIL_OFFSET(eh));
69 return cpu_to_le32(csum);
72 static int ext4_extent_block_csum_verify(struct inode *inode,
73 struct ext4_extent_header *eh)
75 struct ext4_extent_tail *et;
77 if (!ext4_has_metadata_csum(inode->i_sb))
80 et = find_ext4_extent_tail(eh);
81 if (et->et_checksum != ext4_extent_block_csum(inode, eh))
86 static void ext4_extent_block_csum_set(struct inode *inode,
87 struct ext4_extent_header *eh)
89 struct ext4_extent_tail *et;
91 if (!ext4_has_metadata_csum(inode->i_sb))
94 et = find_ext4_extent_tail(eh);
95 et->et_checksum = ext4_extent_block_csum(inode, eh);
98 static int ext4_split_extent(handle_t *handle,
100 struct ext4_ext_path **ppath,
101 struct ext4_map_blocks *map,
105 static int ext4_split_extent_at(handle_t *handle,
107 struct ext4_ext_path **ppath,
112 static int ext4_find_delayed_extent(struct inode *inode,
113 struct extent_status *newes);
115 static int ext4_ext_truncate_extend_restart(handle_t *handle,
121 if (!ext4_handle_valid(handle))
123 if (handle->h_buffer_credits >= needed)
126 * If we need to extend the journal get a few extra blocks
127 * while we're at it for efficiency's sake.
130 err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
133 err = ext4_truncate_restart_trans(handle, inode, needed);
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_inode_block_valid(inode, 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_inode_block_valid(inode, 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_error_inode(inode, function, line, 0,
496 "pblk %llu bad header/extent: %s - magic %x, "
497 "entries %u, max %u(%u), depth %u(%u)",
498 (unsigned long long) pblk, error_msg,
499 le16_to_cpu(eh->eh_magic),
500 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
501 max, le16_to_cpu(eh->eh_depth), depth);
505 #define ext4_ext_check(inode, eh, depth, pblk) \
506 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
508 int ext4_ext_check_inode(struct inode *inode)
510 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
513 static void ext4_cache_extents(struct inode *inode,
514 struct ext4_extent_header *eh)
516 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
517 ext4_lblk_t prev = 0;
520 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
521 unsigned int status = EXTENT_STATUS_WRITTEN;
522 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
523 int len = ext4_ext_get_actual_len(ex);
525 if (prev && (prev != lblk))
526 ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
529 if (ext4_ext_is_unwritten(ex))
530 status = EXTENT_STATUS_UNWRITTEN;
531 ext4_es_cache_extent(inode, lblk, len,
532 ext4_ext_pblock(ex), status);
537 static struct buffer_head *
538 __read_extent_tree_block(const char *function, unsigned int line,
539 struct inode *inode, ext4_fsblk_t pblk, int depth,
542 struct buffer_head *bh;
545 bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
547 return ERR_PTR(-ENOMEM);
549 if (!bh_uptodate_or_lock(bh)) {
550 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
551 err = bh_submit_read(bh);
555 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
557 err = __ext4_ext_check(function, line, inode,
558 ext_block_hdr(bh), depth, pblk);
561 set_buffer_verified(bh);
563 * If this is a leaf block, cache all of its entries
565 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
566 struct ext4_extent_header *eh = ext_block_hdr(bh);
567 ext4_cache_extents(inode, eh);
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 = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
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 eh->eh_generation = 0;
874 ext4_mark_inode_dirty(handle, inode);
878 struct ext4_ext_path *
879 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
880 struct ext4_ext_path **orig_path, int flags)
882 struct ext4_extent_header *eh;
883 struct buffer_head *bh;
884 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
885 short int depth, i, ppos = 0;
888 eh = ext_inode_hdr(inode);
889 depth = ext_depth(inode);
890 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
891 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
898 ext4_ext_drop_refs(path);
899 if (depth > path[0].p_maxdepth) {
901 *orig_path = path = NULL;
905 /* account possible depth increase */
906 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
909 return ERR_PTR(-ENOMEM);
910 path[0].p_maxdepth = depth + 1;
916 if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
917 ext4_cache_extents(inode, eh);
918 /* walk through the tree */
920 ext_debug("depth %d: num %d, max %d\n",
921 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
923 ext4_ext_binsearch_idx(inode, path + ppos, block);
924 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
925 path[ppos].p_depth = i;
926 path[ppos].p_ext = NULL;
928 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
935 eh = ext_block_hdr(bh);
937 path[ppos].p_bh = bh;
938 path[ppos].p_hdr = eh;
941 path[ppos].p_depth = i;
942 path[ppos].p_ext = NULL;
943 path[ppos].p_idx = NULL;
946 ext4_ext_binsearch(inode, path + ppos, block);
947 /* if not an empty leaf */
948 if (path[ppos].p_ext)
949 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
951 ext4_ext_show_path(inode, path);
956 ext4_ext_drop_refs(path);
964 * ext4_ext_insert_index:
965 * insert new index [@logical;@ptr] into the block at @curp;
966 * check where to insert: before @curp or after @curp
968 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
969 struct ext4_ext_path *curp,
970 int logical, ext4_fsblk_t ptr)
972 struct ext4_extent_idx *ix;
975 err = ext4_ext_get_access(handle, inode, curp);
979 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
980 EXT4_ERROR_INODE(inode,
981 "logical %d == ei_block %d!",
982 logical, le32_to_cpu(curp->p_idx->ei_block));
983 return -EFSCORRUPTED;
986 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
987 >= le16_to_cpu(curp->p_hdr->eh_max))) {
988 EXT4_ERROR_INODE(inode,
989 "eh_entries %d >= eh_max %d!",
990 le16_to_cpu(curp->p_hdr->eh_entries),
991 le16_to_cpu(curp->p_hdr->eh_max));
992 return -EFSCORRUPTED;
995 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
997 ext_debug("insert new index %d after: %llu\n", logical, ptr);
998 ix = curp->p_idx + 1;
1001 ext_debug("insert new index %d before: %llu\n", logical, ptr);
1005 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1008 ext_debug("insert new index %d: "
1009 "move %d indices from 0x%p to 0x%p\n",
1010 logical, len, ix, ix + 1);
1011 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1014 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1015 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1016 return -EFSCORRUPTED;
1019 ix->ei_block = cpu_to_le32(logical);
1020 ext4_idx_store_pblock(ix, ptr);
1021 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1023 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1024 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1025 return -EFSCORRUPTED;
1028 err = ext4_ext_dirty(handle, inode, curp);
1029 ext4_std_error(inode->i_sb, err);
1036 * inserts new subtree into the path, using free index entry
1038 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1039 * - makes decision where to split
1040 * - moves remaining extents and index entries (right to the split point)
1041 * into the newly allocated blocks
1042 * - initializes subtree
1044 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1046 struct ext4_ext_path *path,
1047 struct ext4_extent *newext, int at)
1049 struct buffer_head *bh = NULL;
1050 int depth = ext_depth(inode);
1051 struct ext4_extent_header *neh;
1052 struct ext4_extent_idx *fidx;
1053 int i = at, k, m, a;
1054 ext4_fsblk_t newblock, oldblock;
1056 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1058 size_t ext_size = 0;
1060 /* make decision: where to split? */
1061 /* FIXME: now decision is simplest: at current extent */
1063 /* if current leaf will be split, then we should use
1064 * border from split point */
1065 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1066 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1067 return -EFSCORRUPTED;
1069 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1070 border = path[depth].p_ext[1].ee_block;
1071 ext_debug("leaf will be split."
1072 " next leaf starts at %d\n",
1073 le32_to_cpu(border));
1075 border = newext->ee_block;
1076 ext_debug("leaf will be added."
1077 " next leaf starts at %d\n",
1078 le32_to_cpu(border));
1082 * If error occurs, then we break processing
1083 * and mark filesystem read-only. index won't
1084 * be inserted and tree will be in consistent
1085 * state. Next mount will repair buffers too.
1089 * Get array to track all allocated blocks.
1090 * We need this to handle errors and free blocks
1093 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
1097 /* allocate all needed blocks */
1098 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1099 for (a = 0; a < depth - at; a++) {
1100 newblock = ext4_ext_new_meta_block(handle, inode, path,
1101 newext, &err, flags);
1104 ablocks[a] = newblock;
1107 /* initialize new leaf */
1108 newblock = ablocks[--a];
1109 if (unlikely(newblock == 0)) {
1110 EXT4_ERROR_INODE(inode, "newblock == 0!");
1111 err = -EFSCORRUPTED;
1114 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1115 if (unlikely(!bh)) {
1121 err = ext4_journal_get_create_access(handle, bh);
1125 neh = ext_block_hdr(bh);
1126 neh->eh_entries = 0;
1127 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1128 neh->eh_magic = EXT4_EXT_MAGIC;
1130 neh->eh_generation = 0;
1132 /* move remainder of path[depth] to the new leaf */
1133 if (unlikely(path[depth].p_hdr->eh_entries !=
1134 path[depth].p_hdr->eh_max)) {
1135 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1136 path[depth].p_hdr->eh_entries,
1137 path[depth].p_hdr->eh_max);
1138 err = -EFSCORRUPTED;
1141 /* start copy from next extent */
1142 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1143 ext4_ext_show_move(inode, path, newblock, depth);
1145 struct ext4_extent *ex;
1146 ex = EXT_FIRST_EXTENT(neh);
1147 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1148 le16_add_cpu(&neh->eh_entries, m);
1151 /* zero out unused area in the extent block */
1152 ext_size = sizeof(struct ext4_extent_header) +
1153 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1154 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1155 ext4_extent_block_csum_set(inode, neh);
1156 set_buffer_uptodate(bh);
1159 err = ext4_handle_dirty_metadata(handle, inode, bh);
1165 /* correct old leaf */
1167 err = ext4_ext_get_access(handle, inode, path + depth);
1170 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1171 err = ext4_ext_dirty(handle, inode, path + depth);
1177 /* create intermediate indexes */
1179 if (unlikely(k < 0)) {
1180 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1181 err = -EFSCORRUPTED;
1185 ext_debug("create %d intermediate indices\n", k);
1186 /* insert new index into current index block */
1187 /* current depth stored in i var */
1190 oldblock = newblock;
1191 newblock = ablocks[--a];
1192 bh = sb_getblk(inode->i_sb, newblock);
1193 if (unlikely(!bh)) {
1199 err = ext4_journal_get_create_access(handle, bh);
1203 neh = ext_block_hdr(bh);
1204 neh->eh_entries = cpu_to_le16(1);
1205 neh->eh_magic = EXT4_EXT_MAGIC;
1206 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1207 neh->eh_depth = cpu_to_le16(depth - i);
1208 neh->eh_generation = 0;
1209 fidx = EXT_FIRST_INDEX(neh);
1210 fidx->ei_block = border;
1211 ext4_idx_store_pblock(fidx, oldblock);
1213 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1214 i, newblock, le32_to_cpu(border), oldblock);
1216 /* move remainder of path[i] to the new index block */
1217 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1218 EXT_LAST_INDEX(path[i].p_hdr))) {
1219 EXT4_ERROR_INODE(inode,
1220 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1221 le32_to_cpu(path[i].p_ext->ee_block));
1222 err = -EFSCORRUPTED;
1225 /* start copy indexes */
1226 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1227 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1228 EXT_MAX_INDEX(path[i].p_hdr));
1229 ext4_ext_show_move(inode, path, newblock, i);
1231 memmove(++fidx, path[i].p_idx,
1232 sizeof(struct ext4_extent_idx) * m);
1233 le16_add_cpu(&neh->eh_entries, m);
1235 /* zero out unused area in the extent block */
1236 ext_size = sizeof(struct ext4_extent_header) +
1237 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1238 memset(bh->b_data + ext_size, 0,
1239 inode->i_sb->s_blocksize - ext_size);
1240 ext4_extent_block_csum_set(inode, neh);
1241 set_buffer_uptodate(bh);
1244 err = ext4_handle_dirty_metadata(handle, inode, bh);
1250 /* correct old index */
1252 err = ext4_ext_get_access(handle, inode, path + i);
1255 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1256 err = ext4_ext_dirty(handle, inode, path + i);
1264 /* insert new index */
1265 err = ext4_ext_insert_index(handle, inode, path + at,
1266 le32_to_cpu(border), newblock);
1270 if (buffer_locked(bh))
1276 /* free all allocated blocks in error case */
1277 for (i = 0; i < depth; i++) {
1280 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1281 EXT4_FREE_BLOCKS_METADATA);
1290 * ext4_ext_grow_indepth:
1291 * implements tree growing procedure:
1292 * - allocates new block
1293 * - moves top-level data (index block or leaf) into the new block
1294 * - initializes new top-level, creating index that points to the
1295 * just created block
1297 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1300 struct ext4_extent_header *neh;
1301 struct buffer_head *bh;
1302 ext4_fsblk_t newblock, goal = 0;
1303 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1305 size_t ext_size = 0;
1307 /* Try to prepend new index to old one */
1308 if (ext_depth(inode))
1309 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1310 if (goal > le32_to_cpu(es->s_first_data_block)) {
1311 flags |= EXT4_MB_HINT_TRY_GOAL;
1314 goal = ext4_inode_to_goal_block(inode);
1315 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1320 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1325 err = ext4_journal_get_create_access(handle, bh);
1331 ext_size = sizeof(EXT4_I(inode)->i_data);
1332 /* move top-level index/leaf into new block */
1333 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1334 /* zero out unused area in the extent block */
1335 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1337 /* set size of new block */
1338 neh = ext_block_hdr(bh);
1339 /* old root could have indexes or leaves
1340 * so calculate e_max right way */
1341 if (ext_depth(inode))
1342 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1344 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1345 neh->eh_magic = EXT4_EXT_MAGIC;
1346 ext4_extent_block_csum_set(inode, neh);
1347 set_buffer_uptodate(bh);
1350 err = ext4_handle_dirty_metadata(handle, inode, bh);
1354 /* Update top-level index: num,max,pointer */
1355 neh = ext_inode_hdr(inode);
1356 neh->eh_entries = cpu_to_le16(1);
1357 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1358 if (neh->eh_depth == 0) {
1359 /* Root extent block becomes index block */
1360 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1361 EXT_FIRST_INDEX(neh)->ei_block =
1362 EXT_FIRST_EXTENT(neh)->ee_block;
1364 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1365 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1366 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1367 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1369 le16_add_cpu(&neh->eh_depth, 1);
1370 ext4_mark_inode_dirty(handle, inode);
1378 * ext4_ext_create_new_leaf:
1379 * finds empty index and adds new leaf.
1380 * if no free index is found, then it requests in-depth growing.
1382 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1383 unsigned int mb_flags,
1384 unsigned int gb_flags,
1385 struct ext4_ext_path **ppath,
1386 struct ext4_extent *newext)
1388 struct ext4_ext_path *path = *ppath;
1389 struct ext4_ext_path *curp;
1390 int depth, i, err = 0;
1393 i = depth = ext_depth(inode);
1395 /* walk up to the tree and look for free index entry */
1396 curp = path + depth;
1397 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1402 /* we use already allocated block for index block,
1403 * so subsequent data blocks should be contiguous */
1404 if (EXT_HAS_FREE_INDEX(curp)) {
1405 /* if we found index with free entry, then use that
1406 * entry: create all needed subtree and add new leaf */
1407 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1412 path = ext4_find_extent(inode,
1413 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1416 err = PTR_ERR(path);
1418 /* tree is full, time to grow in depth */
1419 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1424 path = ext4_find_extent(inode,
1425 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1428 err = PTR_ERR(path);
1433 * only first (depth 0 -> 1) produces free space;
1434 * in all other cases we have to split the grown tree
1436 depth = ext_depth(inode);
1437 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1438 /* now we need to split */
1448 * search the closest allocated block to the left for *logical
1449 * and returns it at @logical + it's physical address at @phys
1450 * if *logical is the smallest allocated block, the function
1451 * returns 0 at @phys
1452 * return value contains 0 (success) or error code
1454 static int ext4_ext_search_left(struct inode *inode,
1455 struct ext4_ext_path *path,
1456 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1458 struct ext4_extent_idx *ix;
1459 struct ext4_extent *ex;
1462 if (unlikely(path == NULL)) {
1463 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1464 return -EFSCORRUPTED;
1466 depth = path->p_depth;
1469 if (depth == 0 && path->p_ext == NULL)
1472 /* usually extent in the path covers blocks smaller
1473 * then *logical, but it can be that extent is the
1474 * first one in the file */
1476 ex = path[depth].p_ext;
1477 ee_len = ext4_ext_get_actual_len(ex);
1478 if (*logical < le32_to_cpu(ex->ee_block)) {
1479 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1480 EXT4_ERROR_INODE(inode,
1481 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1482 *logical, le32_to_cpu(ex->ee_block));
1483 return -EFSCORRUPTED;
1485 while (--depth >= 0) {
1486 ix = path[depth].p_idx;
1487 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1488 EXT4_ERROR_INODE(inode,
1489 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1490 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1491 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1492 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1494 return -EFSCORRUPTED;
1500 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1501 EXT4_ERROR_INODE(inode,
1502 "logical %d < ee_block %d + ee_len %d!",
1503 *logical, le32_to_cpu(ex->ee_block), ee_len);
1504 return -EFSCORRUPTED;
1507 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1508 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1513 * search the closest allocated block to the right for *logical
1514 * and returns it at @logical + it's physical address at @phys
1515 * if *logical is the largest allocated block, the function
1516 * returns 0 at @phys
1517 * return value contains 0 (success) or error code
1519 static int ext4_ext_search_right(struct inode *inode,
1520 struct ext4_ext_path *path,
1521 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1522 struct ext4_extent **ret_ex)
1524 struct buffer_head *bh = NULL;
1525 struct ext4_extent_header *eh;
1526 struct ext4_extent_idx *ix;
1527 struct ext4_extent *ex;
1529 int depth; /* Note, NOT eh_depth; depth from top of tree */
1532 if (unlikely(path == NULL)) {
1533 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1534 return -EFSCORRUPTED;
1536 depth = path->p_depth;
1539 if (depth == 0 && path->p_ext == NULL)
1542 /* usually extent in the path covers blocks smaller
1543 * then *logical, but it can be that extent is the
1544 * first one in the file */
1546 ex = path[depth].p_ext;
1547 ee_len = ext4_ext_get_actual_len(ex);
1548 if (*logical < le32_to_cpu(ex->ee_block)) {
1549 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1550 EXT4_ERROR_INODE(inode,
1551 "first_extent(path[%d].p_hdr) != ex",
1553 return -EFSCORRUPTED;
1555 while (--depth >= 0) {
1556 ix = path[depth].p_idx;
1557 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1558 EXT4_ERROR_INODE(inode,
1559 "ix != EXT_FIRST_INDEX *logical %d!",
1561 return -EFSCORRUPTED;
1567 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1568 EXT4_ERROR_INODE(inode,
1569 "logical %d < ee_block %d + ee_len %d!",
1570 *logical, le32_to_cpu(ex->ee_block), ee_len);
1571 return -EFSCORRUPTED;
1574 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1575 /* next allocated block in this leaf */
1580 /* go up and search for index to the right */
1581 while (--depth >= 0) {
1582 ix = path[depth].p_idx;
1583 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1587 /* we've gone up to the root and found no index to the right */
1591 /* we've found index to the right, let's
1592 * follow it and find the closest allocated
1593 * block to the right */
1595 block = ext4_idx_pblock(ix);
1596 while (++depth < path->p_depth) {
1597 /* subtract from p_depth to get proper eh_depth */
1598 bh = read_extent_tree_block(inode, block,
1599 path->p_depth - depth, 0);
1602 eh = ext_block_hdr(bh);
1603 ix = EXT_FIRST_INDEX(eh);
1604 block = ext4_idx_pblock(ix);
1608 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1611 eh = ext_block_hdr(bh);
1612 ex = EXT_FIRST_EXTENT(eh);
1614 *logical = le32_to_cpu(ex->ee_block);
1615 *phys = ext4_ext_pblock(ex);
1623 * ext4_ext_next_allocated_block:
1624 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1625 * NOTE: it considers block number from index entry as
1626 * allocated block. Thus, index entries have to be consistent
1630 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1634 BUG_ON(path == NULL);
1635 depth = path->p_depth;
1637 if (depth == 0 && path->p_ext == NULL)
1638 return EXT_MAX_BLOCKS;
1640 while (depth >= 0) {
1641 if (depth == path->p_depth) {
1643 if (path[depth].p_ext &&
1644 path[depth].p_ext !=
1645 EXT_LAST_EXTENT(path[depth].p_hdr))
1646 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1649 if (path[depth].p_idx !=
1650 EXT_LAST_INDEX(path[depth].p_hdr))
1651 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1656 return EXT_MAX_BLOCKS;
1660 * ext4_ext_next_leaf_block:
1661 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1663 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1667 BUG_ON(path == NULL);
1668 depth = path->p_depth;
1670 /* zero-tree has no leaf blocks at all */
1672 return EXT_MAX_BLOCKS;
1674 /* go to index block */
1677 while (depth >= 0) {
1678 if (path[depth].p_idx !=
1679 EXT_LAST_INDEX(path[depth].p_hdr))
1680 return (ext4_lblk_t)
1681 le32_to_cpu(path[depth].p_idx[1].ei_block);
1685 return EXT_MAX_BLOCKS;
1689 * ext4_ext_correct_indexes:
1690 * if leaf gets modified and modified extent is first in the leaf,
1691 * then we have to correct all indexes above.
1692 * TODO: do we need to correct tree in all cases?
1694 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1695 struct ext4_ext_path *path)
1697 struct ext4_extent_header *eh;
1698 int depth = ext_depth(inode);
1699 struct ext4_extent *ex;
1703 eh = path[depth].p_hdr;
1704 ex = path[depth].p_ext;
1706 if (unlikely(ex == NULL || eh == NULL)) {
1707 EXT4_ERROR_INODE(inode,
1708 "ex %p == NULL or eh %p == NULL", ex, eh);
1709 return -EFSCORRUPTED;
1713 /* there is no tree at all */
1717 if (ex != EXT_FIRST_EXTENT(eh)) {
1718 /* we correct tree if first leaf got modified only */
1723 * TODO: we need correction if border is smaller than current one
1726 border = path[depth].p_ext->ee_block;
1727 err = ext4_ext_get_access(handle, inode, path + k);
1730 path[k].p_idx->ei_block = border;
1731 err = ext4_ext_dirty(handle, inode, path + k);
1736 /* change all left-side indexes */
1737 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1739 err = ext4_ext_get_access(handle, inode, path + k);
1742 path[k].p_idx->ei_block = border;
1743 err = ext4_ext_dirty(handle, inode, path + k);
1752 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1753 struct ext4_extent *ex2)
1755 unsigned short ext1_ee_len, ext2_ee_len;
1757 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1760 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1761 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1763 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1764 le32_to_cpu(ex2->ee_block))
1768 * To allow future support for preallocated extents to be added
1769 * as an RO_COMPAT feature, refuse to merge to extents if
1770 * this can result in the top bit of ee_len being set.
1772 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1775 * The check for IO to unwritten extent is somewhat racy as we
1776 * increment i_unwritten / set EXT4_STATE_DIO_UNWRITTEN only after
1777 * dropping i_data_sem. But reserved blocks should save us in that
1780 if (ext4_ext_is_unwritten(ex1) &&
1781 (ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
1782 atomic_read(&EXT4_I(inode)->i_unwritten) ||
1783 (ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
1785 #ifdef AGGRESSIVE_TEST
1786 if (ext1_ee_len >= 4)
1790 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1796 * This function tries to merge the "ex" extent to the next extent in the tree.
1797 * It always tries to merge towards right. If you want to merge towards
1798 * left, pass "ex - 1" as argument instead of "ex".
1799 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1800 * 1 if they got merged.
1802 static int ext4_ext_try_to_merge_right(struct inode *inode,
1803 struct ext4_ext_path *path,
1804 struct ext4_extent *ex)
1806 struct ext4_extent_header *eh;
1807 unsigned int depth, len;
1808 int merge_done = 0, unwritten;
1810 depth = ext_depth(inode);
1811 BUG_ON(path[depth].p_hdr == NULL);
1812 eh = path[depth].p_hdr;
1814 while (ex < EXT_LAST_EXTENT(eh)) {
1815 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1817 /* merge with next extent! */
1818 unwritten = ext4_ext_is_unwritten(ex);
1819 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1820 + ext4_ext_get_actual_len(ex + 1));
1822 ext4_ext_mark_unwritten(ex);
1824 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1825 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1826 * sizeof(struct ext4_extent);
1827 memmove(ex + 1, ex + 2, len);
1829 le16_add_cpu(&eh->eh_entries, -1);
1831 WARN_ON(eh->eh_entries == 0);
1832 if (!eh->eh_entries)
1833 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1840 * This function does a very simple check to see if we can collapse
1841 * an extent tree with a single extent tree leaf block into the inode.
1843 static void ext4_ext_try_to_merge_up(handle_t *handle,
1844 struct inode *inode,
1845 struct ext4_ext_path *path)
1848 unsigned max_root = ext4_ext_space_root(inode, 0);
1851 if ((path[0].p_depth != 1) ||
1852 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1853 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1857 * We need to modify the block allocation bitmap and the block
1858 * group descriptor to release the extent tree block. If we
1859 * can't get the journal credits, give up.
1861 if (ext4_journal_extend(handle, 2))
1865 * Copy the extent data up to the inode
1867 blk = ext4_idx_pblock(path[0].p_idx);
1868 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1869 sizeof(struct ext4_extent_idx);
1870 s += sizeof(struct ext4_extent_header);
1872 path[1].p_maxdepth = path[0].p_maxdepth;
1873 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1874 path[0].p_depth = 0;
1875 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1876 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1877 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1879 brelse(path[1].p_bh);
1880 ext4_free_blocks(handle, inode, NULL, blk, 1,
1881 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1885 * This function tries to merge the @ex extent to neighbours in the tree.
1886 * return 1 if merge left else 0.
1888 static void ext4_ext_try_to_merge(handle_t *handle,
1889 struct inode *inode,
1890 struct ext4_ext_path *path,
1891 struct ext4_extent *ex) {
1892 struct ext4_extent_header *eh;
1896 depth = ext_depth(inode);
1897 BUG_ON(path[depth].p_hdr == NULL);
1898 eh = path[depth].p_hdr;
1900 if (ex > EXT_FIRST_EXTENT(eh))
1901 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1904 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1906 ext4_ext_try_to_merge_up(handle, inode, path);
1910 * check if a portion of the "newext" extent overlaps with an
1913 * If there is an overlap discovered, it updates the length of the newext
1914 * such that there will be no overlap, and then returns 1.
1915 * If there is no overlap found, it returns 0.
1917 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1918 struct inode *inode,
1919 struct ext4_extent *newext,
1920 struct ext4_ext_path *path)
1923 unsigned int depth, len1;
1924 unsigned int ret = 0;
1926 b1 = le32_to_cpu(newext->ee_block);
1927 len1 = ext4_ext_get_actual_len(newext);
1928 depth = ext_depth(inode);
1929 if (!path[depth].p_ext)
1931 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1934 * get the next allocated block if the extent in the path
1935 * is before the requested block(s)
1938 b2 = ext4_ext_next_allocated_block(path);
1939 if (b2 == EXT_MAX_BLOCKS)
1941 b2 = EXT4_LBLK_CMASK(sbi, b2);
1944 /* check for wrap through zero on extent logical start block*/
1945 if (b1 + len1 < b1) {
1946 len1 = EXT_MAX_BLOCKS - b1;
1947 newext->ee_len = cpu_to_le16(len1);
1951 /* check for overlap */
1952 if (b1 + len1 > b2) {
1953 newext->ee_len = cpu_to_le16(b2 - b1);
1961 * ext4_ext_insert_extent:
1962 * tries to merge requsted extent into the existing extent or
1963 * inserts requested extent as new one into the tree,
1964 * creating new leaf in the no-space case.
1966 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1967 struct ext4_ext_path **ppath,
1968 struct ext4_extent *newext, int gb_flags)
1970 struct ext4_ext_path *path = *ppath;
1971 struct ext4_extent_header *eh;
1972 struct ext4_extent *ex, *fex;
1973 struct ext4_extent *nearex; /* nearest extent */
1974 struct ext4_ext_path *npath = NULL;
1975 int depth, len, err;
1977 int mb_flags = 0, unwritten;
1979 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1980 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1981 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1982 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1983 return -EFSCORRUPTED;
1985 depth = ext_depth(inode);
1986 ex = path[depth].p_ext;
1987 eh = path[depth].p_hdr;
1988 if (unlikely(path[depth].p_hdr == NULL)) {
1989 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1990 return -EFSCORRUPTED;
1993 /* try to insert block into found extent and return */
1994 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1997 * Try to see whether we should rather test the extent on
1998 * right from ex, or from the left of ex. This is because
1999 * ext4_find_extent() can return either extent on the
2000 * left, or on the right from the searched position. This
2001 * will make merging more effective.
2003 if (ex < EXT_LAST_EXTENT(eh) &&
2004 (le32_to_cpu(ex->ee_block) +
2005 ext4_ext_get_actual_len(ex) <
2006 le32_to_cpu(newext->ee_block))) {
2009 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
2010 (le32_to_cpu(newext->ee_block) +
2011 ext4_ext_get_actual_len(newext) <
2012 le32_to_cpu(ex->ee_block)))
2015 /* Try to append newex to the ex */
2016 if (ext4_can_extents_be_merged(inode, ex, newext)) {
2017 ext_debug("append [%d]%d block to %u:[%d]%d"
2019 ext4_ext_is_unwritten(newext),
2020 ext4_ext_get_actual_len(newext),
2021 le32_to_cpu(ex->ee_block),
2022 ext4_ext_is_unwritten(ex),
2023 ext4_ext_get_actual_len(ex),
2024 ext4_ext_pblock(ex));
2025 err = ext4_ext_get_access(handle, inode,
2029 unwritten = ext4_ext_is_unwritten(ex);
2030 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2031 + ext4_ext_get_actual_len(newext));
2033 ext4_ext_mark_unwritten(ex);
2034 eh = path[depth].p_hdr;
2040 /* Try to prepend newex to the ex */
2041 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2042 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2044 le32_to_cpu(newext->ee_block),
2045 ext4_ext_is_unwritten(newext),
2046 ext4_ext_get_actual_len(newext),
2047 le32_to_cpu(ex->ee_block),
2048 ext4_ext_is_unwritten(ex),
2049 ext4_ext_get_actual_len(ex),
2050 ext4_ext_pblock(ex));
2051 err = ext4_ext_get_access(handle, inode,
2056 unwritten = ext4_ext_is_unwritten(ex);
2057 ex->ee_block = newext->ee_block;
2058 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2059 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2060 + ext4_ext_get_actual_len(newext));
2062 ext4_ext_mark_unwritten(ex);
2063 eh = path[depth].p_hdr;
2069 depth = ext_depth(inode);
2070 eh = path[depth].p_hdr;
2071 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2074 /* probably next leaf has space for us? */
2075 fex = EXT_LAST_EXTENT(eh);
2076 next = EXT_MAX_BLOCKS;
2077 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2078 next = ext4_ext_next_leaf_block(path);
2079 if (next != EXT_MAX_BLOCKS) {
2080 ext_debug("next leaf block - %u\n", next);
2081 BUG_ON(npath != NULL);
2082 npath = ext4_find_extent(inode, next, NULL, 0);
2084 return PTR_ERR(npath);
2085 BUG_ON(npath->p_depth != path->p_depth);
2086 eh = npath[depth].p_hdr;
2087 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2088 ext_debug("next leaf isn't full(%d)\n",
2089 le16_to_cpu(eh->eh_entries));
2093 ext_debug("next leaf has no free space(%d,%d)\n",
2094 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2098 * There is no free space in the found leaf.
2099 * We're gonna add a new leaf in the tree.
2101 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2102 mb_flags |= EXT4_MB_USE_RESERVED;
2103 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2107 depth = ext_depth(inode);
2108 eh = path[depth].p_hdr;
2111 nearex = path[depth].p_ext;
2113 err = ext4_ext_get_access(handle, inode, path + depth);
2118 /* there is no extent in this leaf, create first one */
2119 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
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));
2124 nearex = EXT_FIRST_EXTENT(eh);
2126 if (le32_to_cpu(newext->ee_block)
2127 > le32_to_cpu(nearex->ee_block)) {
2129 ext_debug("insert %u:%llu:[%d]%d before: "
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),
2139 BUG_ON(newext->ee_block == nearex->ee_block);
2140 ext_debug("insert %u:%llu:[%d]%d after: "
2142 le32_to_cpu(newext->ee_block),
2143 ext4_ext_pblock(newext),
2144 ext4_ext_is_unwritten(newext),
2145 ext4_ext_get_actual_len(newext),
2148 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2150 ext_debug("insert %u:%llu:[%d]%d: "
2151 "move %d extents from 0x%p to 0x%p\n",
2152 le32_to_cpu(newext->ee_block),
2153 ext4_ext_pblock(newext),
2154 ext4_ext_is_unwritten(newext),
2155 ext4_ext_get_actual_len(newext),
2156 len, nearex, nearex + 1);
2157 memmove(nearex + 1, nearex,
2158 len * sizeof(struct ext4_extent));
2162 le16_add_cpu(&eh->eh_entries, 1);
2163 path[depth].p_ext = nearex;
2164 nearex->ee_block = newext->ee_block;
2165 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2166 nearex->ee_len = newext->ee_len;
2169 /* try to merge extents */
2170 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2171 ext4_ext_try_to_merge(handle, inode, path, nearex);
2174 /* time to correct all indexes above */
2175 err = ext4_ext_correct_indexes(handle, inode, path);
2179 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2182 ext4_ext_drop_refs(npath);
2187 static int ext4_fill_fiemap_extents(struct inode *inode,
2188 ext4_lblk_t block, ext4_lblk_t num,
2189 struct fiemap_extent_info *fieinfo)
2191 struct ext4_ext_path *path = NULL;
2192 struct ext4_extent *ex;
2193 struct extent_status es;
2194 ext4_lblk_t next, next_del, start = 0, end = 0;
2195 ext4_lblk_t last = block + num;
2196 int exists, depth = 0, err = 0;
2197 unsigned int flags = 0;
2198 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2200 while (block < last && block != EXT_MAX_BLOCKS) {
2202 /* find extent for this block */
2203 down_read(&EXT4_I(inode)->i_data_sem);
2205 path = ext4_find_extent(inode, block, &path, 0);
2207 up_read(&EXT4_I(inode)->i_data_sem);
2208 err = PTR_ERR(path);
2213 depth = ext_depth(inode);
2214 if (unlikely(path[depth].p_hdr == NULL)) {
2215 up_read(&EXT4_I(inode)->i_data_sem);
2216 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2217 err = -EFSCORRUPTED;
2220 ex = path[depth].p_ext;
2221 next = ext4_ext_next_allocated_block(path);
2226 /* there is no extent yet, so try to allocate
2227 * all requested space */
2230 } else if (le32_to_cpu(ex->ee_block) > block) {
2231 /* need to allocate space before found extent */
2233 end = le32_to_cpu(ex->ee_block);
2234 if (block + num < end)
2236 } else if (block >= le32_to_cpu(ex->ee_block)
2237 + ext4_ext_get_actual_len(ex)) {
2238 /* need to allocate space after found extent */
2243 } else if (block >= le32_to_cpu(ex->ee_block)) {
2245 * some part of requested space is covered
2249 end = le32_to_cpu(ex->ee_block)
2250 + ext4_ext_get_actual_len(ex);
2251 if (block + num < end)
2257 BUG_ON(end <= start);
2261 es.es_len = end - start;
2264 es.es_lblk = le32_to_cpu(ex->ee_block);
2265 es.es_len = ext4_ext_get_actual_len(ex);
2266 es.es_pblk = ext4_ext_pblock(ex);
2267 if (ext4_ext_is_unwritten(ex))
2268 flags |= FIEMAP_EXTENT_UNWRITTEN;
2272 * Find delayed extent and update es accordingly. We call
2273 * it even in !exists case to find out whether es is the
2274 * last existing extent or not.
2276 next_del = ext4_find_delayed_extent(inode, &es);
2277 if (!exists && next_del) {
2279 flags |= (FIEMAP_EXTENT_DELALLOC |
2280 FIEMAP_EXTENT_UNKNOWN);
2282 up_read(&EXT4_I(inode)->i_data_sem);
2284 if (unlikely(es.es_len == 0)) {
2285 EXT4_ERROR_INODE(inode, "es.es_len == 0");
2286 err = -EFSCORRUPTED;
2291 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2292 * we need to check next == EXT_MAX_BLOCKS because it is
2293 * possible that an extent is with unwritten and delayed
2294 * status due to when an extent is delayed allocated and
2295 * is allocated by fallocate status tree will track both of
2298 * So we could return a unwritten and delayed extent, and
2299 * its block is equal to 'next'.
2301 if (next == next_del && next == EXT_MAX_BLOCKS) {
2302 flags |= FIEMAP_EXTENT_LAST;
2303 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2304 next != EXT_MAX_BLOCKS)) {
2305 EXT4_ERROR_INODE(inode,
2306 "next extent == %u, next "
2307 "delalloc extent = %u",
2309 err = -EFSCORRUPTED;
2315 err = fiemap_fill_next_extent(fieinfo,
2316 (__u64)es.es_lblk << blksize_bits,
2317 (__u64)es.es_pblk << blksize_bits,
2318 (__u64)es.es_len << blksize_bits,
2328 block = es.es_lblk + es.es_len;
2331 ext4_ext_drop_refs(path);
2337 * ext4_ext_determine_hole - determine hole around given block
2338 * @inode: inode we lookup in
2339 * @path: path in extent tree to @lblk
2340 * @lblk: pointer to logical block around which we want to determine hole
2342 * Determine hole length (and start if easily possible) around given logical
2343 * block. We don't try too hard to find the beginning of the hole but @path
2344 * actually points to extent before @lblk, we provide it.
2346 * The function returns the length of a hole starting at @lblk. We update @lblk
2347 * to the beginning of the hole if we managed to find it.
2349 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2350 struct ext4_ext_path *path,
2353 int depth = ext_depth(inode);
2354 struct ext4_extent *ex;
2357 ex = path[depth].p_ext;
2359 /* there is no extent yet, so gap is [0;-] */
2361 len = EXT_MAX_BLOCKS;
2362 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2363 len = le32_to_cpu(ex->ee_block) - *lblk;
2364 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2365 + ext4_ext_get_actual_len(ex)) {
2368 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2369 next = ext4_ext_next_allocated_block(path);
2370 BUG_ON(next == *lblk);
2379 * ext4_ext_put_gap_in_cache:
2380 * calculate boundaries of the gap that the requested block fits into
2381 * and cache this gap
2384 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2385 ext4_lblk_t hole_len)
2387 struct extent_status es;
2389 ext4_es_find_delayed_extent_range(inode, hole_start,
2390 hole_start + hole_len - 1, &es);
2392 /* There's delayed extent containing lblock? */
2393 if (es.es_lblk <= hole_start)
2395 hole_len = min(es.es_lblk - hole_start, hole_len);
2397 ext_debug(" -> %u:%u\n", hole_start, hole_len);
2398 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2399 EXTENT_STATUS_HOLE);
2404 * removes index from the index block.
2406 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2407 struct ext4_ext_path *path, int depth)
2412 /* free index block */
2414 path = path + depth;
2415 leaf = ext4_idx_pblock(path->p_idx);
2416 if (unlikely(path->p_hdr->eh_entries == 0)) {
2417 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2418 return -EFSCORRUPTED;
2420 err = ext4_ext_get_access(handle, inode, path);
2424 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2425 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2426 len *= sizeof(struct ext4_extent_idx);
2427 memmove(path->p_idx, path->p_idx + 1, len);
2430 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2431 err = ext4_ext_dirty(handle, inode, path);
2434 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2435 trace_ext4_ext_rm_idx(inode, leaf);
2437 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2438 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2440 while (--depth >= 0) {
2441 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2444 err = ext4_ext_get_access(handle, inode, path);
2447 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2448 err = ext4_ext_dirty(handle, inode, path);
2456 * ext4_ext_calc_credits_for_single_extent:
2457 * This routine returns max. credits that needed to insert an extent
2458 * to the extent tree.
2459 * When pass the actual path, the caller should calculate credits
2462 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2463 struct ext4_ext_path *path)
2466 int depth = ext_depth(inode);
2469 /* probably there is space in leaf? */
2470 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2471 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2474 * There are some space in the leaf tree, no
2475 * need to account for leaf block credit
2477 * bitmaps and block group descriptor blocks
2478 * and other metadata blocks still need to be
2481 /* 1 bitmap, 1 block group descriptor */
2482 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2487 return ext4_chunk_trans_blocks(inode, nrblocks);
2491 * How many index/leaf blocks need to change/allocate to add @extents extents?
2493 * If we add a single extent, then in the worse case, each tree level
2494 * index/leaf need to be changed in case of the tree split.
2496 * If more extents are inserted, they could cause the whole tree split more
2497 * than once, but this is really rare.
2499 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2504 /* If we are converting the inline data, only one is needed here. */
2505 if (ext4_has_inline_data(inode))
2508 depth = ext_depth(inode);
2518 static inline int get_default_free_blocks_flags(struct inode *inode)
2520 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2521 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2522 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2523 else if (ext4_should_journal_data(inode))
2524 return EXT4_FREE_BLOCKS_FORGET;
2528 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2529 struct ext4_extent *ex,
2530 long long *partial_cluster,
2531 ext4_lblk_t from, ext4_lblk_t to)
2533 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2534 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2536 int flags = get_default_free_blocks_flags(inode);
2539 * For bigalloc file systems, we never free a partial cluster
2540 * at the beginning of the extent. Instead, we make a note
2541 * that we tried freeing the cluster, and check to see if we
2542 * need to free it on a subsequent call to ext4_remove_blocks,
2543 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2545 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2547 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2549 * If we have a partial cluster, and it's different from the
2550 * cluster of the last block, we need to explicitly free the
2551 * partial cluster here.
2553 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2554 if (*partial_cluster > 0 &&
2555 *partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2556 ext4_free_blocks(handle, inode, NULL,
2557 EXT4_C2B(sbi, *partial_cluster),
2558 sbi->s_cluster_ratio, flags);
2559 *partial_cluster = 0;
2562 #ifdef EXTENTS_STATS
2564 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2565 spin_lock(&sbi->s_ext_stats_lock);
2566 sbi->s_ext_blocks += ee_len;
2567 sbi->s_ext_extents++;
2568 if (ee_len < sbi->s_ext_min)
2569 sbi->s_ext_min = ee_len;
2570 if (ee_len > sbi->s_ext_max)
2571 sbi->s_ext_max = ee_len;
2572 if (ext_depth(inode) > sbi->s_depth_max)
2573 sbi->s_depth_max = ext_depth(inode);
2574 spin_unlock(&sbi->s_ext_stats_lock);
2577 if (from >= le32_to_cpu(ex->ee_block)
2578 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2581 long long first_cluster;
2583 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2584 pblk = ext4_ext_pblock(ex) + ee_len - num;
2586 * Usually we want to free partial cluster at the end of the
2587 * extent, except for the situation when the cluster is still
2588 * used by any other extent (partial_cluster is negative).
2590 if (*partial_cluster < 0 &&
2591 *partial_cluster == -(long long) EXT4_B2C(sbi, pblk+num-1))
2592 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2594 ext_debug("free last %u blocks starting %llu partial %lld\n",
2595 num, pblk, *partial_cluster);
2596 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2598 * If the block range to be freed didn't start at the
2599 * beginning of a cluster, and we removed the entire
2600 * extent and the cluster is not used by any other extent,
2601 * save the partial cluster here, since we might need to
2602 * delete if we determine that the truncate or punch hole
2603 * operation has removed all of the blocks in the cluster.
2604 * If that cluster is used by another extent, preserve its
2605 * negative value so it isn't freed later on.
2607 * If the whole extent wasn't freed, we've reached the
2608 * start of the truncated/punched region and have finished
2609 * removing blocks. If there's a partial cluster here it's
2610 * shared with the remainder of the extent and is no longer
2611 * a candidate for removal.
2613 if (EXT4_PBLK_COFF(sbi, pblk) && ee_len == num) {
2614 first_cluster = (long long) EXT4_B2C(sbi, pblk);
2615 if (first_cluster != -*partial_cluster)
2616 *partial_cluster = first_cluster;
2618 *partial_cluster = 0;
2621 ext4_error(sbi->s_sb, "strange request: removal(2) "
2623 from, to, le32_to_cpu(ex->ee_block), ee_len);
2629 * ext4_ext_rm_leaf() Removes the extents associated with the
2630 * blocks appearing between "start" and "end". Both "start"
2631 * and "end" must appear in the same extent or EIO is returned.
2633 * @handle: The journal handle
2634 * @inode: The files inode
2635 * @path: The path to the leaf
2636 * @partial_cluster: The cluster which we'll have to free if all extents
2637 * has been released from it. However, if this value is
2638 * negative, it's a cluster just to the right of the
2639 * punched region and it must not be freed.
2640 * @start: The first block to remove
2641 * @end: The last block to remove
2644 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2645 struct ext4_ext_path *path,
2646 long long *partial_cluster,
2647 ext4_lblk_t start, ext4_lblk_t end)
2649 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2650 int err = 0, correct_index = 0;
2651 int depth = ext_depth(inode), credits;
2652 struct ext4_extent_header *eh;
2655 ext4_lblk_t ex_ee_block;
2656 unsigned short ex_ee_len;
2657 unsigned unwritten = 0;
2658 struct ext4_extent *ex;
2661 /* the header must be checked already in ext4_ext_remove_space() */
2662 ext_debug("truncate since %u in leaf to %u\n", start, end);
2663 if (!path[depth].p_hdr)
2664 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2665 eh = path[depth].p_hdr;
2666 if (unlikely(path[depth].p_hdr == NULL)) {
2667 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2668 return -EFSCORRUPTED;
2670 /* find where to start removing */
2671 ex = path[depth].p_ext;
2673 ex = EXT_LAST_EXTENT(eh);
2675 ex_ee_block = le32_to_cpu(ex->ee_block);
2676 ex_ee_len = ext4_ext_get_actual_len(ex);
2678 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2680 while (ex >= EXT_FIRST_EXTENT(eh) &&
2681 ex_ee_block + ex_ee_len > start) {
2683 if (ext4_ext_is_unwritten(ex))
2688 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2689 unwritten, ex_ee_len);
2690 path[depth].p_ext = ex;
2692 a = ex_ee_block > start ? ex_ee_block : start;
2693 b = ex_ee_block+ex_ee_len - 1 < end ?
2694 ex_ee_block+ex_ee_len - 1 : end;
2696 ext_debug(" border %u:%u\n", a, b);
2698 /* If this extent is beyond the end of the hole, skip it */
2699 if (end < ex_ee_block) {
2701 * We're going to skip this extent and move to another,
2702 * so note that its first cluster is in use to avoid
2703 * freeing it when removing blocks. Eventually, the
2704 * right edge of the truncated/punched region will
2705 * be just to the left.
2707 if (sbi->s_cluster_ratio > 1) {
2708 pblk = ext4_ext_pblock(ex);
2710 -(long long) EXT4_B2C(sbi, pblk);
2713 ex_ee_block = le32_to_cpu(ex->ee_block);
2714 ex_ee_len = ext4_ext_get_actual_len(ex);
2716 } else if (b != ex_ee_block + ex_ee_len - 1) {
2717 EXT4_ERROR_INODE(inode,
2718 "can not handle truncate %u:%u "
2720 start, end, ex_ee_block,
2721 ex_ee_block + ex_ee_len - 1);
2722 err = -EFSCORRUPTED;
2724 } else if (a != ex_ee_block) {
2725 /* remove tail of the extent */
2726 num = a - ex_ee_block;
2728 /* remove whole extent: excellent! */
2732 * 3 for leaf, sb, and inode plus 2 (bmap and group
2733 * descriptor) for each block group; assume two block
2734 * groups plus ex_ee_len/blocks_per_block_group for
2737 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2738 if (ex == EXT_FIRST_EXTENT(eh)) {
2740 credits += (ext_depth(inode)) + 1;
2742 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2744 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2748 err = ext4_ext_get_access(handle, inode, path + depth);
2752 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2758 /* this extent is removed; mark slot entirely unused */
2759 ext4_ext_store_pblock(ex, 0);
2761 ex->ee_len = cpu_to_le16(num);
2763 * Do not mark unwritten if all the blocks in the
2764 * extent have been removed.
2766 if (unwritten && num)
2767 ext4_ext_mark_unwritten(ex);
2769 * If the extent was completely released,
2770 * we need to remove it from the leaf
2773 if (end != EXT_MAX_BLOCKS - 1) {
2775 * For hole punching, we need to scoot all the
2776 * extents up when an extent is removed so that
2777 * we dont have blank extents in the middle
2779 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2780 sizeof(struct ext4_extent));
2782 /* Now get rid of the one at the end */
2783 memset(EXT_LAST_EXTENT(eh), 0,
2784 sizeof(struct ext4_extent));
2786 le16_add_cpu(&eh->eh_entries, -1);
2789 err = ext4_ext_dirty(handle, inode, path + depth);
2793 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2794 ext4_ext_pblock(ex));
2796 ex_ee_block = le32_to_cpu(ex->ee_block);
2797 ex_ee_len = ext4_ext_get_actual_len(ex);
2800 if (correct_index && eh->eh_entries)
2801 err = ext4_ext_correct_indexes(handle, inode, path);
2804 * If there's a partial cluster and at least one extent remains in
2805 * the leaf, free the partial cluster if it isn't shared with the
2806 * current extent. If it is shared with the current extent
2807 * we zero partial_cluster because we've reached the start of the
2808 * truncated/punched region and we're done removing blocks.
2810 if (*partial_cluster > 0 && ex >= EXT_FIRST_EXTENT(eh)) {
2811 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2812 if (*partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2813 ext4_free_blocks(handle, inode, NULL,
2814 EXT4_C2B(sbi, *partial_cluster),
2815 sbi->s_cluster_ratio,
2816 get_default_free_blocks_flags(inode));
2818 *partial_cluster = 0;
2821 /* if this leaf is free, then we should
2822 * remove it from index block above */
2823 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2824 err = ext4_ext_rm_idx(handle, inode, path, depth);
2831 * ext4_ext_more_to_rm:
2832 * returns 1 if current index has to be freed (even partial)
2835 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2837 BUG_ON(path->p_idx == NULL);
2839 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2843 * if truncate on deeper level happened, it wasn't partial,
2844 * so we have to consider current index for truncation
2846 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2851 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2854 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2855 int depth = ext_depth(inode);
2856 struct ext4_ext_path *path = NULL;
2857 long long partial_cluster = 0;
2861 ext_debug("truncate since %u to %u\n", start, end);
2863 /* probably first extent we're gonna free will be last in block */
2864 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
2866 return PTR_ERR(handle);
2869 trace_ext4_ext_remove_space(inode, start, end, depth);
2872 * Check if we are removing extents inside the extent tree. If that
2873 * is the case, we are going to punch a hole inside the extent tree
2874 * so we have to check whether we need to split the extent covering
2875 * the last block to remove so we can easily remove the part of it
2876 * in ext4_ext_rm_leaf().
2878 if (end < EXT_MAX_BLOCKS - 1) {
2879 struct ext4_extent *ex;
2880 ext4_lblk_t ee_block, ex_end, lblk;
2883 /* find extent for or closest extent to this block */
2884 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
2886 ext4_journal_stop(handle);
2887 return PTR_ERR(path);
2889 depth = ext_depth(inode);
2890 /* Leaf not may not exist only if inode has no blocks at all */
2891 ex = path[depth].p_ext;
2894 EXT4_ERROR_INODE(inode,
2895 "path[%d].p_hdr == NULL",
2897 err = -EFSCORRUPTED;
2902 ee_block = le32_to_cpu(ex->ee_block);
2903 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2906 * See if the last block is inside the extent, if so split
2907 * the extent at 'end' block so we can easily remove the
2908 * tail of the first part of the split extent in
2909 * ext4_ext_rm_leaf().
2911 if (end >= ee_block && end < ex_end) {
2914 * If we're going to split the extent, note that
2915 * the cluster containing the block after 'end' is
2916 * in use to avoid freeing it when removing blocks.
2918 if (sbi->s_cluster_ratio > 1) {
2919 pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
2921 -(long long) EXT4_B2C(sbi, pblk);
2925 * Split the extent in two so that 'end' is the last
2926 * block in the first new extent. Also we should not
2927 * fail removing space due to ENOSPC so try to use
2928 * reserved block if that happens.
2930 err = ext4_force_split_extent_at(handle, inode, &path,
2935 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end) {
2937 * If there's an extent to the right its first cluster
2938 * contains the immediate right boundary of the
2939 * truncated/punched region. Set partial_cluster to
2940 * its negative value so it won't be freed if shared
2941 * with the current extent. The end < ee_block case
2942 * is handled in ext4_ext_rm_leaf().
2945 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2951 -(long long) EXT4_B2C(sbi, pblk);
2955 * We start scanning from right side, freeing all the blocks
2956 * after i_size and walking into the tree depth-wise.
2958 depth = ext_depth(inode);
2963 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2965 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2968 ext4_journal_stop(handle);
2971 path[0].p_maxdepth = path[0].p_depth = depth;
2972 path[0].p_hdr = ext_inode_hdr(inode);
2975 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2976 err = -EFSCORRUPTED;
2982 while (i >= 0 && err == 0) {
2984 /* this is leaf block */
2985 err = ext4_ext_rm_leaf(handle, inode, path,
2986 &partial_cluster, start,
2988 /* root level has p_bh == NULL, brelse() eats this */
2989 brelse(path[i].p_bh);
2990 path[i].p_bh = NULL;
2995 /* this is index block */
2996 if (!path[i].p_hdr) {
2997 ext_debug("initialize header\n");
2998 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
3001 if (!path[i].p_idx) {
3002 /* this level hasn't been touched yet */
3003 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
3004 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
3005 ext_debug("init index ptr: hdr 0x%p, num %d\n",
3007 le16_to_cpu(path[i].p_hdr->eh_entries));
3009 /* we were already here, see at next index */
3013 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
3014 i, EXT_FIRST_INDEX(path[i].p_hdr),
3016 if (ext4_ext_more_to_rm(path + i)) {
3017 struct buffer_head *bh;
3018 /* go to the next level */
3019 ext_debug("move to level %d (block %llu)\n",
3020 i + 1, ext4_idx_pblock(path[i].p_idx));
3021 memset(path + i + 1, 0, sizeof(*path));
3022 bh = read_extent_tree_block(inode,
3023 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
3026 /* should we reset i_size? */
3030 /* Yield here to deal with large extent trees.
3031 * Should be a no-op if we did IO above. */
3033 if (WARN_ON(i + 1 > depth)) {
3034 err = -EFSCORRUPTED;
3037 path[i + 1].p_bh = bh;
3039 /* save actual number of indexes since this
3040 * number is changed at the next iteration */
3041 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3044 /* we finished processing this index, go up */
3045 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3046 /* index is empty, remove it;
3047 * handle must be already prepared by the
3048 * truncatei_leaf() */
3049 err = ext4_ext_rm_idx(handle, inode, path, i);
3051 /* root level has p_bh == NULL, brelse() eats this */
3052 brelse(path[i].p_bh);
3053 path[i].p_bh = NULL;
3055 ext_debug("return to level %d\n", i);
3059 trace_ext4_ext_remove_space_done(inode, start, end, depth,
3060 partial_cluster, path->p_hdr->eh_entries);
3063 * If we still have something in the partial cluster and we have removed
3064 * even the first extent, then we should free the blocks in the partial
3065 * cluster as well. (This code will only run when there are no leaves
3066 * to the immediate left of the truncated/punched region.)
3068 if (partial_cluster > 0 && err == 0) {
3069 /* don't zero partial_cluster since it's not used afterwards */
3070 ext4_free_blocks(handle, inode, NULL,
3071 EXT4_C2B(sbi, partial_cluster),
3072 sbi->s_cluster_ratio,
3073 get_default_free_blocks_flags(inode));
3076 /* TODO: flexible tree reduction should be here */
3077 if (path->p_hdr->eh_entries == 0) {
3079 * truncate to zero freed all the tree,
3080 * so we need to correct eh_depth
3082 err = ext4_ext_get_access(handle, inode, path);
3084 ext_inode_hdr(inode)->eh_depth = 0;
3085 ext_inode_hdr(inode)->eh_max =
3086 cpu_to_le16(ext4_ext_space_root(inode, 0));
3087 err = ext4_ext_dirty(handle, inode, path);
3091 ext4_ext_drop_refs(path);
3096 ext4_journal_stop(handle);
3102 * called at mount time
3104 void ext4_ext_init(struct super_block *sb)
3107 * possible initialization would be here
3110 if (ext4_has_feature_extents(sb)) {
3111 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3112 printk(KERN_INFO "EXT4-fs: file extents enabled"
3113 #ifdef AGGRESSIVE_TEST
3114 ", aggressive tests"
3116 #ifdef CHECK_BINSEARCH
3119 #ifdef EXTENTS_STATS
3124 #ifdef EXTENTS_STATS
3125 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3126 EXT4_SB(sb)->s_ext_min = 1 << 30;
3127 EXT4_SB(sb)->s_ext_max = 0;
3133 * called at umount time
3135 void ext4_ext_release(struct super_block *sb)
3137 if (!ext4_has_feature_extents(sb))
3140 #ifdef EXTENTS_STATS
3141 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3142 struct ext4_sb_info *sbi = EXT4_SB(sb);
3143 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3144 sbi->s_ext_blocks, sbi->s_ext_extents,
3145 sbi->s_ext_blocks / sbi->s_ext_extents);
3146 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3147 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3152 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3154 ext4_lblk_t ee_block;
3155 ext4_fsblk_t ee_pblock;
3156 unsigned int ee_len;
3158 ee_block = le32_to_cpu(ex->ee_block);
3159 ee_len = ext4_ext_get_actual_len(ex);
3160 ee_pblock = ext4_ext_pblock(ex);
3165 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3166 EXTENT_STATUS_WRITTEN);
3169 /* FIXME!! we need to try to merge to left or right after zero-out */
3170 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3172 ext4_fsblk_t ee_pblock;
3173 unsigned int ee_len;
3175 ee_len = ext4_ext_get_actual_len(ex);
3176 ee_pblock = ext4_ext_pblock(ex);
3177 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3182 * ext4_split_extent_at() splits an extent at given block.
3184 * @handle: the journal handle
3185 * @inode: the file inode
3186 * @path: the path to the extent
3187 * @split: the logical block where the extent is splitted.
3188 * @split_flags: indicates if the extent could be zeroout if split fails, and
3189 * the states(init or unwritten) of new extents.
3190 * @flags: flags used to insert new extent to extent tree.
3193 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3194 * of which are deterimined by split_flag.
3196 * There are two cases:
3197 * a> the extent are splitted into two extent.
3198 * b> split is not needed, and just mark the extent.
3200 * return 0 on success.
3202 static int ext4_split_extent_at(handle_t *handle,
3203 struct inode *inode,
3204 struct ext4_ext_path **ppath,
3209 struct ext4_ext_path *path = *ppath;
3210 ext4_fsblk_t newblock;
3211 ext4_lblk_t ee_block;
3212 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3213 struct ext4_extent *ex2 = NULL;
3214 unsigned int ee_len, depth;
3217 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3218 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3220 ext_debug("ext4_split_extents_at: inode %lu, logical"
3221 "block %llu\n", inode->i_ino, (unsigned long long)split);
3223 ext4_ext_show_leaf(inode, path);
3225 depth = ext_depth(inode);
3226 ex = path[depth].p_ext;
3227 ee_block = le32_to_cpu(ex->ee_block);
3228 ee_len = ext4_ext_get_actual_len(ex);
3229 newblock = split - ee_block + ext4_ext_pblock(ex);
3231 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3232 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3233 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3234 EXT4_EXT_MARK_UNWRIT1 |
3235 EXT4_EXT_MARK_UNWRIT2));
3237 err = ext4_ext_get_access(handle, inode, path + depth);
3241 if (split == ee_block) {
3243 * case b: block @split is the block that the extent begins with
3244 * then we just change the state of the extent, and splitting
3247 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3248 ext4_ext_mark_unwritten(ex);
3250 ext4_ext_mark_initialized(ex);
3252 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3253 ext4_ext_try_to_merge(handle, inode, path, ex);
3255 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3260 memcpy(&orig_ex, ex, sizeof(orig_ex));
3261 ex->ee_len = cpu_to_le16(split - ee_block);
3262 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3263 ext4_ext_mark_unwritten(ex);
3266 * path may lead to new leaf, not to original leaf any more
3267 * after ext4_ext_insert_extent() returns,
3269 err = ext4_ext_dirty(handle, inode, path + depth);
3271 goto fix_extent_len;
3274 ex2->ee_block = cpu_to_le32(split);
3275 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3276 ext4_ext_store_pblock(ex2, newblock);
3277 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3278 ext4_ext_mark_unwritten(ex2);
3280 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3281 if (err != -ENOSPC && err != -EDQUOT)
3284 if (EXT4_EXT_MAY_ZEROOUT & split_flag) {
3285 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3286 if (split_flag & EXT4_EXT_DATA_VALID1) {
3287 err = ext4_ext_zeroout(inode, ex2);
3288 zero_ex.ee_block = ex2->ee_block;
3289 zero_ex.ee_len = cpu_to_le16(
3290 ext4_ext_get_actual_len(ex2));
3291 ext4_ext_store_pblock(&zero_ex,
3292 ext4_ext_pblock(ex2));
3294 err = ext4_ext_zeroout(inode, ex);
3295 zero_ex.ee_block = ex->ee_block;
3296 zero_ex.ee_len = cpu_to_le16(
3297 ext4_ext_get_actual_len(ex));
3298 ext4_ext_store_pblock(&zero_ex,
3299 ext4_ext_pblock(ex));
3302 err = ext4_ext_zeroout(inode, &orig_ex);
3303 zero_ex.ee_block = orig_ex.ee_block;
3304 zero_ex.ee_len = cpu_to_le16(
3305 ext4_ext_get_actual_len(&orig_ex));
3306 ext4_ext_store_pblock(&zero_ex,
3307 ext4_ext_pblock(&orig_ex));
3311 /* update the extent length and mark as initialized */
3312 ex->ee_len = cpu_to_le16(ee_len);
3313 ext4_ext_try_to_merge(handle, inode, path, ex);
3314 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3316 /* update extent status tree */
3317 err = ext4_zeroout_es(inode, &zero_ex);
3318 /* If we failed at this point, we don't know in which
3319 * state the extent tree exactly is so don't try to fix
3320 * length of the original extent as it may do even more
3328 ex->ee_len = orig_ex.ee_len;
3329 ext4_ext_dirty(handle, inode, path + path->p_depth);
3332 ext4_ext_show_leaf(inode, path);
3337 * ext4_split_extents() splits an extent and mark extent which is covered
3338 * by @map as split_flags indicates
3340 * It may result in splitting the extent into multiple extents (up to three)
3341 * There are three possibilities:
3342 * a> There is no split required
3343 * b> Splits in two extents: Split is happening at either end of the extent
3344 * c> Splits in three extents: Somone is splitting in middle of the extent
3347 static int ext4_split_extent(handle_t *handle,
3348 struct inode *inode,
3349 struct ext4_ext_path **ppath,
3350 struct ext4_map_blocks *map,
3354 struct ext4_ext_path *path = *ppath;
3355 ext4_lblk_t ee_block;
3356 struct ext4_extent *ex;
3357 unsigned int ee_len, depth;
3360 int split_flag1, flags1;
3361 int allocated = map->m_len;
3363 depth = ext_depth(inode);
3364 ex = path[depth].p_ext;
3365 ee_block = le32_to_cpu(ex->ee_block);
3366 ee_len = ext4_ext_get_actual_len(ex);
3367 unwritten = ext4_ext_is_unwritten(ex);
3369 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3370 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3371 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3373 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3374 EXT4_EXT_MARK_UNWRIT2;
3375 if (split_flag & EXT4_EXT_DATA_VALID2)
3376 split_flag1 |= EXT4_EXT_DATA_VALID1;
3377 err = ext4_split_extent_at(handle, inode, ppath,
3378 map->m_lblk + map->m_len, split_flag1, flags1);
3382 allocated = ee_len - (map->m_lblk - ee_block);
3385 * Update path is required because previous ext4_split_extent_at() may
3386 * result in split of original leaf or extent zeroout.
3388 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3390 return PTR_ERR(path);
3391 depth = ext_depth(inode);
3392 ex = path[depth].p_ext;
3394 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3395 (unsigned long) map->m_lblk);
3396 return -EFSCORRUPTED;
3398 unwritten = ext4_ext_is_unwritten(ex);
3401 if (map->m_lblk >= ee_block) {
3402 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3404 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3405 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3406 EXT4_EXT_MARK_UNWRIT2);
3408 err = ext4_split_extent_at(handle, inode, ppath,
3409 map->m_lblk, split_flag1, flags);
3414 ext4_ext_show_leaf(inode, path);
3416 return err ? err : allocated;
3420 * This function is called by ext4_ext_map_blocks() if someone tries to write
3421 * to an unwritten extent. It may result in splitting the unwritten
3422 * extent into multiple extents (up to three - one initialized and two
3424 * There are three possibilities:
3425 * a> There is no split required: Entire extent should be initialized
3426 * b> Splits in two extents: Write is happening at either end of the extent
3427 * c> Splits in three extents: Somone is writing in middle of the extent
3430 * - The extent pointed to by 'path' is unwritten.
3431 * - The extent pointed to by 'path' contains a superset
3432 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3434 * Post-conditions on success:
3435 * - the returned value is the number of blocks beyond map->l_lblk
3436 * that are allocated and initialized.
3437 * It is guaranteed to be >= map->m_len.
3439 static int ext4_ext_convert_to_initialized(handle_t *handle,
3440 struct inode *inode,
3441 struct ext4_map_blocks *map,
3442 struct ext4_ext_path **ppath,
3445 struct ext4_ext_path *path = *ppath;
3446 struct ext4_sb_info *sbi;
3447 struct ext4_extent_header *eh;
3448 struct ext4_map_blocks split_map;
3449 struct ext4_extent zero_ex1, zero_ex2;
3450 struct ext4_extent *ex, *abut_ex;
3451 ext4_lblk_t ee_block, eof_block;
3452 unsigned int ee_len, depth, map_len = map->m_len;
3453 int allocated = 0, max_zeroout = 0;
3455 int split_flag = EXT4_EXT_DATA_VALID2;
3457 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3458 "block %llu, max_blocks %u\n", inode->i_ino,
3459 (unsigned long long)map->m_lblk, map_len);
3461 sbi = EXT4_SB(inode->i_sb);
3462 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3463 >> inode->i_sb->s_blocksize_bits;
3464 if (eof_block < map->m_lblk + map_len)
3465 eof_block = map->m_lblk + map_len;
3467 depth = ext_depth(inode);
3468 eh = path[depth].p_hdr;
3469 ex = path[depth].p_ext;
3470 ee_block = le32_to_cpu(ex->ee_block);
3471 ee_len = ext4_ext_get_actual_len(ex);
3472 zero_ex1.ee_len = 0;
3473 zero_ex2.ee_len = 0;
3475 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3477 /* Pre-conditions */
3478 BUG_ON(!ext4_ext_is_unwritten(ex));
3479 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3482 * Attempt to transfer newly initialized blocks from the currently
3483 * unwritten extent to its neighbor. This is much cheaper
3484 * than an insertion followed by a merge as those involve costly
3485 * memmove() calls. Transferring to the left is the common case in
3486 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3487 * followed by append writes.
3489 * Limitations of the current logic:
3490 * - L1: we do not deal with writes covering the whole extent.
3491 * This would require removing the extent if the transfer
3493 * - L2: we only attempt to merge with an extent stored in the
3494 * same extent tree node.
3496 if ((map->m_lblk == ee_block) &&
3497 /* See if we can merge left */
3498 (map_len < ee_len) && /*L1*/
3499 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3500 ext4_lblk_t prev_lblk;
3501 ext4_fsblk_t prev_pblk, ee_pblk;
3502 unsigned int prev_len;
3505 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3506 prev_len = ext4_ext_get_actual_len(abut_ex);
3507 prev_pblk = ext4_ext_pblock(abut_ex);
3508 ee_pblk = ext4_ext_pblock(ex);
3511 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3512 * upon those conditions:
3513 * - C1: abut_ex is initialized,
3514 * - C2: abut_ex is logically abutting ex,
3515 * - C3: abut_ex is physically abutting ex,
3516 * - C4: abut_ex can receive the additional blocks without
3517 * overflowing the (initialized) length limit.
3519 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3520 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3521 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3522 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3523 err = ext4_ext_get_access(handle, inode, path + depth);
3527 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3530 /* Shift the start of ex by 'map_len' blocks */
3531 ex->ee_block = cpu_to_le32(ee_block + map_len);
3532 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3533 ex->ee_len = cpu_to_le16(ee_len - map_len);
3534 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3536 /* Extend abut_ex by 'map_len' blocks */
3537 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3539 /* Result: number of initialized blocks past m_lblk */
3540 allocated = map_len;
3542 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3543 (map_len < ee_len) && /*L1*/
3544 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3545 /* See if we can merge right */
3546 ext4_lblk_t next_lblk;
3547 ext4_fsblk_t next_pblk, ee_pblk;
3548 unsigned int next_len;
3551 next_lblk = le32_to_cpu(abut_ex->ee_block);
3552 next_len = ext4_ext_get_actual_len(abut_ex);
3553 next_pblk = ext4_ext_pblock(abut_ex);
3554 ee_pblk = ext4_ext_pblock(ex);
3557 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3558 * upon those conditions:
3559 * - C1: abut_ex is initialized,
3560 * - C2: abut_ex is logically abutting ex,
3561 * - C3: abut_ex is physically abutting ex,
3562 * - C4: abut_ex can receive the additional blocks without
3563 * overflowing the (initialized) length limit.
3565 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3566 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3567 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3568 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3569 err = ext4_ext_get_access(handle, inode, path + depth);
3573 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3576 /* Shift the start of abut_ex by 'map_len' blocks */
3577 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3578 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3579 ex->ee_len = cpu_to_le16(ee_len - map_len);
3580 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3582 /* Extend abut_ex by 'map_len' blocks */
3583 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3585 /* Result: number of initialized blocks past m_lblk */
3586 allocated = map_len;
3590 /* Mark the block containing both extents as dirty */
3591 ext4_ext_dirty(handle, inode, path + depth);
3593 /* Update path to point to the right extent */
3594 path[depth].p_ext = abut_ex;
3597 allocated = ee_len - (map->m_lblk - ee_block);
3599 WARN_ON(map->m_lblk < ee_block);
3601 * It is safe to convert extent to initialized via explicit
3602 * zeroout only if extent is fully inside i_size or new_size.
3604 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3606 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3607 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3608 (inode->i_sb->s_blocksize_bits - 10);
3610 if (ext4_encrypted_inode(inode))
3615 * 1. split the extent into three extents.
3616 * 2. split the extent into two extents, zeroout the head of the first
3618 * 3. split the extent into two extents, zeroout the tail of the second
3620 * 4. split the extent into two extents with out zeroout.
3621 * 5. no splitting needed, just possibly zeroout the head and / or the
3622 * tail of the extent.
3624 split_map.m_lblk = map->m_lblk;
3625 split_map.m_len = map->m_len;
3627 if (max_zeroout && (allocated > split_map.m_len)) {
3628 if (allocated <= max_zeroout) {
3631 cpu_to_le32(split_map.m_lblk +
3634 cpu_to_le16(allocated - split_map.m_len);
3635 ext4_ext_store_pblock(&zero_ex1,
3636 ext4_ext_pblock(ex) + split_map.m_lblk +
3637 split_map.m_len - ee_block);
3638 err = ext4_ext_zeroout(inode, &zero_ex1);
3641 split_map.m_len = allocated;
3643 if (split_map.m_lblk - ee_block + split_map.m_len <
3646 if (split_map.m_lblk != ee_block) {
3647 zero_ex2.ee_block = ex->ee_block;
3648 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3650 ext4_ext_store_pblock(&zero_ex2,
3651 ext4_ext_pblock(ex));
3652 err = ext4_ext_zeroout(inode, &zero_ex2);
3657 split_map.m_len += split_map.m_lblk - ee_block;
3658 split_map.m_lblk = ee_block;
3659 allocated = map->m_len;
3663 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3668 /* If we have gotten a failure, don't zero out status tree */
3670 err = ext4_zeroout_es(inode, &zero_ex1);
3672 err = ext4_zeroout_es(inode, &zero_ex2);
3674 return err ? err : allocated;
3678 * This function is called by ext4_ext_map_blocks() from
3679 * ext4_get_blocks_dio_write() when DIO to write
3680 * to an unwritten extent.
3682 * Writing to an unwritten extent may result in splitting the unwritten
3683 * extent into multiple initialized/unwritten extents (up to three)
3684 * There are three possibilities:
3685 * a> There is no split required: Entire extent should be unwritten
3686 * b> Splits in two extents: Write is happening at either end of the extent
3687 * c> Splits in three extents: Somone is writing in middle of the extent
3689 * This works the same way in the case of initialized -> unwritten conversion.
3691 * One of more index blocks maybe needed if the extent tree grow after
3692 * the unwritten extent split. To prevent ENOSPC occur at the IO
3693 * complete, we need to split the unwritten extent before DIO submit
3694 * the IO. The unwritten extent called at this time will be split
3695 * into three unwritten extent(at most). After IO complete, the part
3696 * being filled will be convert to initialized by the end_io callback function
3697 * via ext4_convert_unwritten_extents().
3699 * Returns the size of unwritten extent to be written on success.
3701 static int ext4_split_convert_extents(handle_t *handle,
3702 struct inode *inode,
3703 struct ext4_map_blocks *map,
3704 struct ext4_ext_path **ppath,
3707 struct ext4_ext_path *path = *ppath;
3708 ext4_lblk_t eof_block;
3709 ext4_lblk_t ee_block;
3710 struct ext4_extent *ex;
3711 unsigned int ee_len;
3712 int split_flag = 0, depth;
3714 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3715 __func__, inode->i_ino,
3716 (unsigned long long)map->m_lblk, map->m_len);
3718 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3719 >> inode->i_sb->s_blocksize_bits;
3720 if (eof_block < map->m_lblk + map->m_len)
3721 eof_block = map->m_lblk + map->m_len;
3723 * It is safe to convert extent to initialized via explicit
3724 * zeroout only if extent is fully insde i_size or new_size.
3726 depth = ext_depth(inode);
3727 ex = path[depth].p_ext;
3728 ee_block = le32_to_cpu(ex->ee_block);
3729 ee_len = ext4_ext_get_actual_len(ex);
3731 /* Convert to unwritten */
3732 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3733 split_flag |= EXT4_EXT_DATA_VALID1;
3734 /* Convert to initialized */
3735 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3736 split_flag |= ee_block + ee_len <= eof_block ?
3737 EXT4_EXT_MAY_ZEROOUT : 0;
3738 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3740 flags |= EXT4_GET_BLOCKS_PRE_IO;
3741 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3744 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3745 struct inode *inode,
3746 struct ext4_map_blocks *map,
3747 struct ext4_ext_path **ppath)
3749 struct ext4_ext_path *path = *ppath;
3750 struct ext4_extent *ex;
3751 ext4_lblk_t ee_block;
3752 unsigned int ee_len;
3756 depth = ext_depth(inode);
3757 ex = path[depth].p_ext;
3758 ee_block = le32_to_cpu(ex->ee_block);
3759 ee_len = ext4_ext_get_actual_len(ex);
3761 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3762 "block %llu, max_blocks %u\n", inode->i_ino,
3763 (unsigned long long)ee_block, ee_len);
3765 /* If extent is larger than requested it is a clear sign that we still
3766 * have some extent state machine issues left. So extent_split is still
3768 * TODO: Once all related issues will be fixed this situation should be
3771 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3772 #ifdef CONFIG_EXT4_DEBUG
3773 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3774 " len %u; IO logical block %llu, len %u",
3775 inode->i_ino, (unsigned long long)ee_block, ee_len,
3776 (unsigned long long)map->m_lblk, map->m_len);
3778 err = ext4_split_convert_extents(handle, inode, map, ppath,
3779 EXT4_GET_BLOCKS_CONVERT);
3782 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3784 return PTR_ERR(path);
3785 depth = ext_depth(inode);
3786 ex = path[depth].p_ext;
3789 err = ext4_ext_get_access(handle, inode, path + depth);
3792 /* first mark the extent as initialized */
3793 ext4_ext_mark_initialized(ex);
3795 /* note: ext4_ext_correct_indexes() isn't needed here because
3796 * borders are not changed
3798 ext4_ext_try_to_merge(handle, inode, path, ex);
3800 /* Mark modified extent as dirty */
3801 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3803 ext4_ext_show_leaf(inode, path);
3808 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3810 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3812 struct ext4_ext_path *path,
3816 struct ext4_extent_header *eh;
3817 struct ext4_extent *last_ex;
3819 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3822 depth = ext_depth(inode);
3823 eh = path[depth].p_hdr;
3826 * We're going to remove EOFBLOCKS_FL entirely in future so we
3827 * do not care for this case anymore. Simply remove the flag
3828 * if there are no extents.
3830 if (unlikely(!eh->eh_entries))
3832 last_ex = EXT_LAST_EXTENT(eh);
3834 * We should clear the EOFBLOCKS_FL flag if we are writing the
3835 * last block in the last extent in the file. We test this by
3836 * first checking to see if the caller to
3837 * ext4_ext_get_blocks() was interested in the last block (or
3838 * a block beyond the last block) in the current extent. If
3839 * this turns out to be false, we can bail out from this
3840 * function immediately.
3842 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3843 ext4_ext_get_actual_len(last_ex))
3846 * If the caller does appear to be planning to write at or
3847 * beyond the end of the current extent, we then test to see
3848 * if the current extent is the last extent in the file, by
3849 * checking to make sure it was reached via the rightmost node
3850 * at each level of the tree.
3852 for (i = depth-1; i >= 0; i--)
3853 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3856 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3857 return ext4_mark_inode_dirty(handle, inode);
3861 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3863 * Return 1 if there is a delalloc block in the range, otherwise 0.
3865 int ext4_find_delalloc_range(struct inode *inode,
3866 ext4_lblk_t lblk_start,
3867 ext4_lblk_t lblk_end)
3869 struct extent_status es;
3871 ext4_es_find_delayed_extent_range(inode, lblk_start, lblk_end, &es);
3873 return 0; /* there is no delay extent in this tree */
3874 else if (es.es_lblk <= lblk_start &&
3875 lblk_start < es.es_lblk + es.es_len)
3877 else if (lblk_start <= es.es_lblk && es.es_lblk <= lblk_end)
3883 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk)
3885 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3886 ext4_lblk_t lblk_start, lblk_end;
3887 lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
3888 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3890 return ext4_find_delalloc_range(inode, lblk_start, lblk_end);
3894 * Determines how many complete clusters (out of those specified by the 'map')
3895 * are under delalloc and were reserved quota for.
3896 * This function is called when we are writing out the blocks that were
3897 * originally written with their allocation delayed, but then the space was
3898 * allocated using fallocate() before the delayed allocation could be resolved.
3899 * The cases to look for are:
3900 * ('=' indicated delayed allocated blocks
3901 * '-' indicates non-delayed allocated blocks)
3902 * (a) partial clusters towards beginning and/or end outside of allocated range
3903 * are not delalloc'ed.
3905 * |----c---=|====c====|====c====|===-c----|
3906 * |++++++ allocated ++++++|
3907 * ==> 4 complete clusters in above example
3909 * (b) partial cluster (outside of allocated range) towards either end is
3910 * marked for delayed allocation. In this case, we will exclude that
3913 * |----====c========|========c========|
3914 * |++++++ allocated ++++++|
3915 * ==> 1 complete clusters in above example
3918 * |================c================|
3919 * |++++++ allocated ++++++|
3920 * ==> 0 complete clusters in above example
3922 * The ext4_da_update_reserve_space will be called only if we
3923 * determine here that there were some "entire" clusters that span
3924 * this 'allocated' range.
3925 * In the non-bigalloc case, this function will just end up returning num_blks
3926 * without ever calling ext4_find_delalloc_range.
3929 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3930 unsigned int num_blks)
3932 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3933 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3934 ext4_lblk_t lblk_from, lblk_to, c_offset;
3935 unsigned int allocated_clusters = 0;
3937 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3938 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3940 /* max possible clusters for this allocation */
3941 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3943 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3945 /* Check towards left side */
3946 c_offset = EXT4_LBLK_COFF(sbi, lblk_start);
3948 lblk_from = EXT4_LBLK_CMASK(sbi, lblk_start);
3949 lblk_to = lblk_from + c_offset - 1;
3951 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3952 allocated_clusters--;
3955 /* Now check towards right. */
3956 c_offset = EXT4_LBLK_COFF(sbi, lblk_start + num_blks);
3957 if (allocated_clusters && c_offset) {
3958 lblk_from = lblk_start + num_blks;
3959 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3961 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3962 allocated_clusters--;
3965 return allocated_clusters;
3969 convert_initialized_extent(handle_t *handle, struct inode *inode,
3970 struct ext4_map_blocks *map,
3971 struct ext4_ext_path **ppath,
3972 unsigned int allocated)
3974 struct ext4_ext_path *path = *ppath;
3975 struct ext4_extent *ex;
3976 ext4_lblk_t ee_block;
3977 unsigned int ee_len;
3982 * Make sure that the extent is no bigger than we support with
3985 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3986 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3988 depth = ext_depth(inode);
3989 ex = path[depth].p_ext;
3990 ee_block = le32_to_cpu(ex->ee_block);
3991 ee_len = ext4_ext_get_actual_len(ex);
3993 ext_debug("%s: inode %lu, logical"
3994 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3995 (unsigned long long)ee_block, ee_len);
3997 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3998 err = ext4_split_convert_extents(handle, inode, map, ppath,
3999 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
4002 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
4004 return PTR_ERR(path);
4005 depth = ext_depth(inode);
4006 ex = path[depth].p_ext;
4008 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
4009 (unsigned long) map->m_lblk);
4010 return -EFSCORRUPTED;
4014 err = ext4_ext_get_access(handle, inode, path + depth);
4017 /* first mark the extent as unwritten */
4018 ext4_ext_mark_unwritten(ex);
4020 /* note: ext4_ext_correct_indexes() isn't needed here because
4021 * borders are not changed
4023 ext4_ext_try_to_merge(handle, inode, path, ex);
4025 /* Mark modified extent as dirty */
4026 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4029 ext4_ext_show_leaf(inode, path);
4031 ext4_update_inode_fsync_trans(handle, inode, 1);
4032 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4035 map->m_flags |= EXT4_MAP_UNWRITTEN;
4036 if (allocated > map->m_len)
4037 allocated = map->m_len;
4038 map->m_len = allocated;
4043 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4044 struct ext4_map_blocks *map,
4045 struct ext4_ext_path **ppath, int flags,
4046 unsigned int allocated, ext4_fsblk_t newblock)
4048 struct ext4_ext_path *path = *ppath;
4052 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4053 "block %llu, max_blocks %u, flags %x, allocated %u\n",
4054 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4056 ext4_ext_show_leaf(inode, path);
4059 * When writing into unwritten space, we should not fail to
4060 * allocate metadata blocks for the new extent block if needed.
4062 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4064 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4065 allocated, newblock);
4067 /* get_block() before submit the IO, split the extent */
4068 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4069 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4070 flags | EXT4_GET_BLOCKS_CONVERT);
4073 map->m_flags |= EXT4_MAP_UNWRITTEN;
4076 /* IO end_io complete, convert the filled extent to written */
4077 if (flags & EXT4_GET_BLOCKS_CONVERT) {
4078 if (flags & EXT4_GET_BLOCKS_ZERO) {
4079 if (allocated > map->m_len)
4080 allocated = map->m_len;
4081 err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4086 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4089 ext4_update_inode_fsync_trans(handle, inode, 1);
4090 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4094 map->m_flags |= EXT4_MAP_MAPPED;
4095 map->m_pblk = newblock;
4096 if (allocated > map->m_len)
4097 allocated = map->m_len;
4098 map->m_len = allocated;
4101 /* buffered IO case */
4103 * repeat fallocate creation request
4104 * we already have an unwritten extent
4106 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4107 map->m_flags |= EXT4_MAP_UNWRITTEN;
4111 /* buffered READ or buffered write_begin() lookup */
4112 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4114 * We have blocks reserved already. We
4115 * return allocated blocks so that delalloc
4116 * won't do block reservation for us. But
4117 * the buffer head will be unmapped so that
4118 * a read from the block returns 0s.
4120 map->m_flags |= EXT4_MAP_UNWRITTEN;
4124 /* buffered write, writepage time, convert*/
4125 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4127 ext4_update_inode_fsync_trans(handle, inode, 1);
4134 map->m_flags |= EXT4_MAP_NEW;
4136 * if we allocated more blocks than requested
4137 * we need to make sure we unmap the extra block
4138 * allocated. The actual needed block will get
4139 * unmapped later when we find the buffer_head marked
4142 if (allocated > map->m_len) {
4143 clean_bdev_aliases(inode->i_sb->s_bdev, newblock + map->m_len,
4144 allocated - map->m_len);
4145 allocated = map->m_len;
4147 map->m_len = allocated;
4150 * If we have done fallocate with the offset that is already
4151 * delayed allocated, we would have block reservation
4152 * and quota reservation done in the delayed write path.
4153 * But fallocate would have already updated quota and block
4154 * count for this offset. So cancel these reservation
4156 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4157 unsigned int reserved_clusters;
4158 reserved_clusters = get_reserved_cluster_alloc(inode,
4159 map->m_lblk, map->m_len);
4160 if (reserved_clusters)
4161 ext4_da_update_reserve_space(inode,
4167 map->m_flags |= EXT4_MAP_MAPPED;
4168 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4169 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4175 if (allocated > map->m_len)
4176 allocated = map->m_len;
4177 ext4_ext_show_leaf(inode, path);
4178 map->m_pblk = newblock;
4179 map->m_len = allocated;
4181 return err ? err : allocated;
4185 * get_implied_cluster_alloc - check to see if the requested
4186 * allocation (in the map structure) overlaps with a cluster already
4187 * allocated in an extent.
4188 * @sb The filesystem superblock structure
4189 * @map The requested lblk->pblk mapping
4190 * @ex The extent structure which might contain an implied
4191 * cluster allocation
4193 * This function is called by ext4_ext_map_blocks() after we failed to
4194 * find blocks that were already in the inode's extent tree. Hence,
4195 * we know that the beginning of the requested region cannot overlap
4196 * the extent from the inode's extent tree. There are three cases we
4197 * want to catch. The first is this case:
4199 * |--- cluster # N--|
4200 * |--- extent ---| |---- requested region ---|
4203 * The second case that we need to test for is this one:
4205 * |--------- cluster # N ----------------|
4206 * |--- requested region --| |------- extent ----|
4207 * |=======================|
4209 * The third case is when the requested region lies between two extents
4210 * within the same cluster:
4211 * |------------- cluster # N-------------|
4212 * |----- ex -----| |---- ex_right ----|
4213 * |------ requested region ------|
4214 * |================|
4216 * In each of the above cases, we need to set the map->m_pblk and
4217 * map->m_len so it corresponds to the return the extent labelled as
4218 * "|====|" from cluster #N, since it is already in use for data in
4219 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4220 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4221 * as a new "allocated" block region. Otherwise, we will return 0 and
4222 * ext4_ext_map_blocks() will then allocate one or more new clusters
4223 * by calling ext4_mb_new_blocks().
4225 static int get_implied_cluster_alloc(struct super_block *sb,
4226 struct ext4_map_blocks *map,
4227 struct ext4_extent *ex,
4228 struct ext4_ext_path *path)
4230 struct ext4_sb_info *sbi = EXT4_SB(sb);
4231 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4232 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4233 ext4_lblk_t rr_cluster_start;
4234 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4235 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4236 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4238 /* The extent passed in that we are trying to match */
4239 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4240 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4242 /* The requested region passed into ext4_map_blocks() */
4243 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4245 if ((rr_cluster_start == ex_cluster_end) ||
4246 (rr_cluster_start == ex_cluster_start)) {
4247 if (rr_cluster_start == ex_cluster_end)
4248 ee_start += ee_len - 1;
4249 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4250 map->m_len = min(map->m_len,
4251 (unsigned) sbi->s_cluster_ratio - c_offset);
4253 * Check for and handle this case:
4255 * |--------- cluster # N-------------|
4256 * |------- extent ----|
4257 * |--- requested region ---|
4261 if (map->m_lblk < ee_block)
4262 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4265 * Check for the case where there is already another allocated
4266 * block to the right of 'ex' but before the end of the cluster.
4268 * |------------- cluster # N-------------|
4269 * |----- ex -----| |---- ex_right ----|
4270 * |------ requested region ------|
4271 * |================|
4273 if (map->m_lblk > ee_block) {
4274 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4275 map->m_len = min(map->m_len, next - map->m_lblk);
4278 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4282 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4288 * Block allocation/map/preallocation routine for extents based files
4291 * Need to be called with
4292 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4293 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4295 * return > 0, number of of blocks already mapped/allocated
4296 * if create == 0 and these are pre-allocated blocks
4297 * buffer head is unmapped
4298 * otherwise blocks are mapped
4300 * return = 0, if plain look up failed (blocks have not been allocated)
4301 * buffer head is unmapped
4303 * return < 0, error case.
4305 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4306 struct ext4_map_blocks *map, int flags)
4308 struct ext4_ext_path *path = NULL;
4309 struct ext4_extent newex, *ex, *ex2;
4310 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4311 ext4_fsblk_t newblock = 0;
4312 int free_on_err = 0, err = 0, depth, ret;
4313 unsigned int allocated = 0, offset = 0;
4314 unsigned int allocated_clusters = 0;
4315 struct ext4_allocation_request ar;
4316 ext4_lblk_t cluster_offset;
4317 bool map_from_cluster = false;
4319 ext_debug("blocks %u/%u requested for inode %lu\n",
4320 map->m_lblk, map->m_len, inode->i_ino);
4321 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4323 /* find extent for this block */
4324 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4326 err = PTR_ERR(path);
4331 depth = ext_depth(inode);
4334 * consistent leaf must not be empty;
4335 * this situation is possible, though, _during_ tree modification;
4336 * this is why assert can't be put in ext4_find_extent()
4338 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4339 EXT4_ERROR_INODE(inode, "bad extent address "
4340 "lblock: %lu, depth: %d pblock %lld",
4341 (unsigned long) map->m_lblk, depth,
4342 path[depth].p_block);
4343 err = -EFSCORRUPTED;
4347 ex = path[depth].p_ext;
4349 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4350 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4351 unsigned short ee_len;
4355 * unwritten extents are treated as holes, except that
4356 * we split out initialized portions during a write.
4358 ee_len = ext4_ext_get_actual_len(ex);
4360 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4362 /* if found extent covers block, simply return it */
4363 if (in_range(map->m_lblk, ee_block, ee_len)) {
4364 newblock = map->m_lblk - ee_block + ee_start;
4365 /* number of remaining blocks in the extent */
4366 allocated = ee_len - (map->m_lblk - ee_block);
4367 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4368 ee_block, ee_len, newblock);
4371 * If the extent is initialized check whether the
4372 * caller wants to convert it to unwritten.
4374 if ((!ext4_ext_is_unwritten(ex)) &&
4375 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4376 allocated = convert_initialized_extent(
4377 handle, inode, map, &path,
4380 } else if (!ext4_ext_is_unwritten(ex))
4383 ret = ext4_ext_handle_unwritten_extents(
4384 handle, inode, map, &path, flags,
4385 allocated, newblock);
4395 * requested block isn't allocated yet;
4396 * we couldn't try to create block if create flag is zero
4398 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4399 ext4_lblk_t hole_start, hole_len;
4401 hole_start = map->m_lblk;
4402 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4404 * put just found gap into cache to speed up
4405 * subsequent requests
4407 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4409 /* Update hole_len to reflect hole size after map->m_lblk */
4410 if (hole_start != map->m_lblk)
4411 hole_len -= map->m_lblk - hole_start;
4413 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4419 * Okay, we need to do block allocation.
4421 newex.ee_block = cpu_to_le32(map->m_lblk);
4422 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4425 * If we are doing bigalloc, check to see if the extent returned
4426 * by ext4_find_extent() implies a cluster we can use.
4428 if (cluster_offset && ex &&
4429 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4430 ar.len = allocated = map->m_len;
4431 newblock = map->m_pblk;
4432 map_from_cluster = true;
4433 goto got_allocated_blocks;
4436 /* find neighbour allocated blocks */
4437 ar.lleft = map->m_lblk;
4438 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4441 ar.lright = map->m_lblk;
4443 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4447 /* Check if the extent after searching to the right implies a
4448 * cluster we can use. */
4449 if ((sbi->s_cluster_ratio > 1) && ex2 &&
4450 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4451 ar.len = allocated = map->m_len;
4452 newblock = map->m_pblk;
4453 map_from_cluster = true;
4454 goto got_allocated_blocks;
4458 * See if request is beyond maximum number of blocks we can have in
4459 * a single extent. For an initialized extent this limit is
4460 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4461 * EXT_UNWRITTEN_MAX_LEN.
4463 if (map->m_len > EXT_INIT_MAX_LEN &&
4464 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4465 map->m_len = EXT_INIT_MAX_LEN;
4466 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4467 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4468 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4470 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4471 newex.ee_len = cpu_to_le16(map->m_len);
4472 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4474 allocated = ext4_ext_get_actual_len(&newex);
4476 allocated = map->m_len;
4478 /* allocate new block */
4480 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4481 ar.logical = map->m_lblk;
4483 * We calculate the offset from the beginning of the cluster
4484 * for the logical block number, since when we allocate a
4485 * physical cluster, the physical block should start at the
4486 * same offset from the beginning of the cluster. This is
4487 * needed so that future calls to get_implied_cluster_alloc()
4490 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4491 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4493 ar.logical -= offset;
4494 if (S_ISREG(inode->i_mode))
4495 ar.flags = EXT4_MB_HINT_DATA;
4497 /* disable in-core preallocation for non-regular files */
4499 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4500 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4501 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4502 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4503 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4504 ar.flags |= EXT4_MB_USE_RESERVED;
4505 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4508 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4509 ar.goal, newblock, allocated);
4511 allocated_clusters = ar.len;
4512 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4513 if (ar.len > allocated)
4516 got_allocated_blocks:
4517 /* try to insert new extent into found leaf and return */
4518 ext4_ext_store_pblock(&newex, newblock + offset);
4519 newex.ee_len = cpu_to_le16(ar.len);
4520 /* Mark unwritten */
4521 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4522 ext4_ext_mark_unwritten(&newex);
4523 map->m_flags |= EXT4_MAP_UNWRITTEN;
4527 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4528 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4531 err = ext4_ext_insert_extent(handle, inode, &path,
4534 if (err && free_on_err) {
4535 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4536 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4537 /* free data blocks we just allocated */
4538 /* not a good idea to call discard here directly,
4539 * but otherwise we'd need to call it every free() */
4540 ext4_discard_preallocations(inode);
4541 ext4_free_blocks(handle, inode, NULL, newblock,
4542 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4546 /* previous routine could use block we allocated */
4547 newblock = ext4_ext_pblock(&newex);
4548 allocated = ext4_ext_get_actual_len(&newex);
4549 if (allocated > map->m_len)
4550 allocated = map->m_len;
4551 map->m_flags |= EXT4_MAP_NEW;
4554 * Update reserved blocks/metadata blocks after successful
4555 * block allocation which had been deferred till now.
4557 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4558 unsigned int reserved_clusters;
4560 * Check how many clusters we had reserved this allocated range
4562 reserved_clusters = get_reserved_cluster_alloc(inode,
4563 map->m_lblk, allocated);
4564 if (!map_from_cluster) {
4565 BUG_ON(allocated_clusters < reserved_clusters);
4566 if (reserved_clusters < allocated_clusters) {
4567 struct ext4_inode_info *ei = EXT4_I(inode);
4568 int reservation = allocated_clusters -
4571 * It seems we claimed few clusters outside of
4572 * the range of this allocation. We should give
4573 * it back to the reservation pool. This can
4574 * happen in the following case:
4576 * * Suppose s_cluster_ratio is 4 (i.e., each
4577 * cluster has 4 blocks. Thus, the clusters
4578 * are [0-3],[4-7],[8-11]...
4579 * * First comes delayed allocation write for
4580 * logical blocks 10 & 11. Since there were no
4581 * previous delayed allocated blocks in the
4582 * range [8-11], we would reserve 1 cluster
4584 * * Next comes write for logical blocks 3 to 8.
4585 * In this case, we will reserve 2 clusters
4586 * (for [0-3] and [4-7]; and not for [8-11] as
4587 * that range has a delayed allocated blocks.
4588 * Thus total reserved clusters now becomes 3.
4589 * * Now, during the delayed allocation writeout
4590 * time, we will first write blocks [3-8] and
4591 * allocate 3 clusters for writing these
4592 * blocks. Also, we would claim all these
4593 * three clusters above.
4594 * * Now when we come here to writeout the
4595 * blocks [10-11], we would expect to claim
4596 * the reservation of 1 cluster we had made
4597 * (and we would claim it since there are no
4598 * more delayed allocated blocks in the range
4599 * [8-11]. But our reserved cluster count had
4600 * already gone to 0.
4602 * Thus, at the step 4 above when we determine
4603 * that there are still some unwritten delayed
4604 * allocated blocks outside of our current
4605 * block range, we should increment the
4606 * reserved clusters count so that when the
4607 * remaining blocks finally gets written, we
4610 dquot_reserve_block(inode,
4611 EXT4_C2B(sbi, reservation));
4612 spin_lock(&ei->i_block_reservation_lock);
4613 ei->i_reserved_data_blocks += reservation;
4614 spin_unlock(&ei->i_block_reservation_lock);
4617 * We will claim quota for all newly allocated blocks.
4618 * We're updating the reserved space *after* the
4619 * correction above so we do not accidentally free
4620 * all the metadata reservation because we might
4621 * actually need it later on.
4623 ext4_da_update_reserve_space(inode, allocated_clusters,
4629 * Cache the extent and update transaction to commit on fdatasync only
4630 * when it is _not_ an unwritten extent.
4632 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4633 ext4_update_inode_fsync_trans(handle, inode, 1);
4635 ext4_update_inode_fsync_trans(handle, inode, 0);
4637 if (allocated > map->m_len)
4638 allocated = map->m_len;
4639 ext4_ext_show_leaf(inode, path);
4640 map->m_flags |= EXT4_MAP_MAPPED;
4641 map->m_pblk = newblock;
4642 map->m_len = allocated;
4644 ext4_ext_drop_refs(path);
4647 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4648 err ? err : allocated);
4649 return err ? err : allocated;
4652 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4654 struct super_block *sb = inode->i_sb;
4655 ext4_lblk_t last_block;
4659 * TODO: optimization is possible here.
4660 * Probably we need not scan at all,
4661 * because page truncation is enough.
4664 /* we have to know where to truncate from in crash case */
4665 EXT4_I(inode)->i_disksize = inode->i_size;
4666 err = ext4_mark_inode_dirty(handle, inode);
4670 last_block = (inode->i_size + sb->s_blocksize - 1)
4671 >> EXT4_BLOCK_SIZE_BITS(sb);
4673 err = ext4_es_remove_extent(inode, last_block,
4674 EXT_MAX_BLOCKS - last_block);
4675 if (err == -ENOMEM) {
4677 congestion_wait(BLK_RW_ASYNC, HZ/50);
4682 return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4685 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4686 ext4_lblk_t len, loff_t new_size,
4689 struct inode *inode = file_inode(file);
4695 struct ext4_map_blocks map;
4696 unsigned int credits;
4699 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4700 map.m_lblk = offset;
4703 * Don't normalize the request if it can fit in one extent so
4704 * that it doesn't get unnecessarily split into multiple
4707 if (len <= EXT_UNWRITTEN_MAX_LEN)
4708 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4711 * credits to insert 1 extent into extent tree
4713 credits = ext4_chunk_trans_blocks(inode, len);
4714 depth = ext_depth(inode);
4717 while (ret >= 0 && len) {
4719 * Recalculate credits when extent tree depth changes.
4721 if (depth != ext_depth(inode)) {
4722 credits = ext4_chunk_trans_blocks(inode, len);
4723 depth = ext_depth(inode);
4726 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4728 if (IS_ERR(handle)) {
4729 ret = PTR_ERR(handle);
4732 ret = ext4_map_blocks(handle, inode, &map, flags);
4734 ext4_debug("inode #%lu: block %u: len %u: "
4735 "ext4_ext_map_blocks returned %d",
4736 inode->i_ino, map.m_lblk,
4738 ext4_mark_inode_dirty(handle, inode);
4739 ret2 = ext4_journal_stop(handle);
4743 map.m_len = len = len - ret;
4744 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4745 inode->i_ctime = current_time(inode);
4747 if (epos > new_size)
4749 if (ext4_update_inode_size(inode, epos) & 0x1)
4750 inode->i_mtime = inode->i_ctime;
4752 if (epos > inode->i_size)
4753 ext4_set_inode_flag(inode,
4754 EXT4_INODE_EOFBLOCKS);
4756 ext4_mark_inode_dirty(handle, inode);
4757 ext4_update_inode_fsync_trans(handle, inode, 1);
4758 ret2 = ext4_journal_stop(handle);
4762 if (ret == -ENOSPC &&
4763 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4768 return ret > 0 ? ret2 : ret;
4771 static long ext4_zero_range(struct file *file, loff_t offset,
4772 loff_t len, int mode)
4774 struct inode *inode = file_inode(file);
4775 handle_t *handle = NULL;
4776 unsigned int max_blocks;
4777 loff_t new_size = 0;
4781 int partial_begin, partial_end;
4784 unsigned int blkbits = inode->i_blkbits;
4786 trace_ext4_zero_range(inode, offset, len, mode);
4788 if (!S_ISREG(inode->i_mode))
4791 /* Call ext4_force_commit to flush all data in case of data=journal. */
4792 if (ext4_should_journal_data(inode)) {
4793 ret = ext4_force_commit(inode->i_sb);
4799 * Round up offset. This is not fallocate, we neet to zero out
4800 * blocks, so convert interior block aligned part of the range to
4801 * unwritten and possibly manually zero out unaligned parts of the
4804 start = round_up(offset, 1 << blkbits);
4805 end = round_down((offset + len), 1 << blkbits);
4807 if (start < offset || end > offset + len)
4809 partial_begin = offset & ((1 << blkbits) - 1);
4810 partial_end = (offset + len) & ((1 << blkbits) - 1);
4812 lblk = start >> blkbits;
4813 max_blocks = (end >> blkbits);
4814 if (max_blocks < lblk)
4822 * Indirect files do not support unwritten extnets
4824 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4829 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4830 (offset + len > i_size_read(inode) ||
4831 offset + len > EXT4_I(inode)->i_disksize)) {
4832 new_size = offset + len;
4833 ret = inode_newsize_ok(inode, new_size);
4838 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4839 if (mode & FALLOC_FL_KEEP_SIZE)
4840 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4842 /* Wait all existing dio workers, newcomers will block on i_mutex */
4843 ext4_inode_block_unlocked_dio(inode);
4844 inode_dio_wait(inode);
4846 /* Preallocate the range including the unaligned edges */
4847 if (partial_begin || partial_end) {
4848 ret = ext4_alloc_file_blocks(file,
4849 round_down(offset, 1 << blkbits) >> blkbits,
4850 (round_up((offset + len), 1 << blkbits) -
4851 round_down(offset, 1 << blkbits)) >> blkbits,
4858 /* Zero range excluding the unaligned edges */
4859 if (max_blocks > 0) {
4860 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4864 * Prevent page faults from reinstantiating pages we have
4865 * released from page cache.
4867 down_write(&EXT4_I(inode)->i_mmap_sem);
4868 ret = ext4_update_disksize_before_punch(inode, offset, len);
4870 up_write(&EXT4_I(inode)->i_mmap_sem);
4873 /* Now release the pages and zero block aligned part of pages */
4874 truncate_pagecache_range(inode, start, end - 1);
4875 inode->i_mtime = inode->i_ctime = current_time(inode);
4877 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4879 up_write(&EXT4_I(inode)->i_mmap_sem);
4883 if (!partial_begin && !partial_end)
4887 * In worst case we have to writeout two nonadjacent unwritten
4888 * blocks and update the inode
4890 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4891 if (ext4_should_journal_data(inode))
4893 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4894 if (IS_ERR(handle)) {
4895 ret = PTR_ERR(handle);
4896 ext4_std_error(inode->i_sb, ret);
4900 inode->i_mtime = inode->i_ctime = current_time(inode);
4902 ext4_update_inode_size(inode, new_size);
4905 * Mark that we allocate beyond EOF so the subsequent truncate
4906 * can proceed even if the new size is the same as i_size.
4908 if ((offset + len) > i_size_read(inode))
4909 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4911 ext4_mark_inode_dirty(handle, inode);
4913 /* Zero out partial block at the edges of the range */
4914 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4916 ext4_update_inode_fsync_trans(handle, inode, 1);
4918 if (file->f_flags & O_SYNC)
4919 ext4_handle_sync(handle);
4921 ext4_journal_stop(handle);
4923 ext4_inode_resume_unlocked_dio(inode);
4925 inode_unlock(inode);
4930 * preallocate space for a file. This implements ext4's fallocate file
4931 * operation, which gets called from sys_fallocate system call.
4932 * For block-mapped files, posix_fallocate should fall back to the method
4933 * of writing zeroes to the required new blocks (the same behavior which is
4934 * expected for file systems which do not support fallocate() system call).
4936 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4938 struct inode *inode = file_inode(file);
4939 loff_t new_size = 0;
4940 unsigned int max_blocks;
4944 unsigned int blkbits = inode->i_blkbits;
4947 * Encrypted inodes can't handle collapse range or insert
4948 * range since we would need to re-encrypt blocks with a
4949 * different IV or XTS tweak (which are based on the logical
4952 * XXX It's not clear why zero range isn't working, but we'll
4953 * leave it disabled for encrypted inodes for now. This is a
4954 * bug we should fix....
4956 if (ext4_encrypted_inode(inode) &&
4957 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
4958 FALLOC_FL_ZERO_RANGE)))
4961 /* Return error if mode is not supported */
4962 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4963 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4964 FALLOC_FL_INSERT_RANGE))
4967 if (mode & FALLOC_FL_PUNCH_HOLE)
4968 return ext4_punch_hole(inode, offset, len);
4970 ret = ext4_convert_inline_data(inode);
4974 if (mode & FALLOC_FL_COLLAPSE_RANGE)
4975 return ext4_collapse_range(inode, offset, len);
4977 if (mode & FALLOC_FL_INSERT_RANGE)
4978 return ext4_insert_range(inode, offset, len);
4980 if (mode & FALLOC_FL_ZERO_RANGE)
4981 return ext4_zero_range(file, offset, len, mode);
4983 trace_ext4_fallocate_enter(inode, offset, len, mode);
4984 lblk = offset >> blkbits;
4986 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4987 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4988 if (mode & FALLOC_FL_KEEP_SIZE)
4989 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4994 * We only support preallocation for extent-based files only
4996 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5001 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
5002 (offset + len > i_size_read(inode) ||
5003 offset + len > EXT4_I(inode)->i_disksize)) {
5004 new_size = offset + len;
5005 ret = inode_newsize_ok(inode, new_size);
5010 /* Wait all existing dio workers, newcomers will block on i_mutex */
5011 ext4_inode_block_unlocked_dio(inode);
5012 inode_dio_wait(inode);
5014 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
5015 ext4_inode_resume_unlocked_dio(inode);
5019 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
5020 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5021 EXT4_I(inode)->i_sync_tid);
5024 inode_unlock(inode);
5025 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
5030 * This function convert a range of blocks to written extents
5031 * The caller of this function will pass the start offset and the size.
5032 * all unwritten extents within this range will be converted to
5035 * This function is called from the direct IO end io call back
5036 * function, to convert the fallocated extents after IO is completed.
5037 * Returns 0 on success.
5039 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
5040 loff_t offset, ssize_t len)
5042 unsigned int max_blocks;
5045 struct ext4_map_blocks map;
5046 unsigned int credits, blkbits = inode->i_blkbits;
5048 map.m_lblk = offset >> blkbits;
5049 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
5052 * This is somewhat ugly but the idea is clear: When transaction is
5053 * reserved, everything goes into it. Otherwise we rather start several
5054 * smaller transactions for conversion of each extent separately.
5057 handle = ext4_journal_start_reserved(handle,
5058 EXT4_HT_EXT_CONVERT);
5060 return PTR_ERR(handle);
5064 * credits to insert 1 extent into extent tree
5066 credits = ext4_chunk_trans_blocks(inode, max_blocks);
5068 while (ret >= 0 && ret < max_blocks) {
5070 map.m_len = (max_blocks -= ret);
5072 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5074 if (IS_ERR(handle)) {
5075 ret = PTR_ERR(handle);
5079 ret = ext4_map_blocks(handle, inode, &map,
5080 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5082 ext4_warning(inode->i_sb,
5083 "inode #%lu: block %u: len %u: "
5084 "ext4_ext_map_blocks returned %d",
5085 inode->i_ino, map.m_lblk,
5087 ext4_mark_inode_dirty(handle, inode);
5089 ret2 = ext4_journal_stop(handle);
5090 if (ret <= 0 || ret2)
5094 ret2 = ext4_journal_stop(handle);
5095 return ret > 0 ? ret2 : ret;
5099 * If newes is not existing extent (newes->ec_pblk equals zero) find
5100 * delayed extent at start of newes and update newes accordingly and
5101 * return start of the next delayed extent.
5103 * If newes is existing extent (newes->ec_pblk is not equal zero)
5104 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5105 * extent found. Leave newes unmodified.
5107 static int ext4_find_delayed_extent(struct inode *inode,
5108 struct extent_status *newes)
5110 struct extent_status es;
5111 ext4_lblk_t block, next_del;
5113 if (newes->es_pblk == 0) {
5114 ext4_es_find_delayed_extent_range(inode, newes->es_lblk,
5115 newes->es_lblk + newes->es_len - 1, &es);
5118 * No extent in extent-tree contains block @newes->es_pblk,
5119 * then the block may stay in 1)a hole or 2)delayed-extent.
5125 if (es.es_lblk > newes->es_lblk) {
5127 newes->es_len = min(es.es_lblk - newes->es_lblk,
5132 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5135 block = newes->es_lblk + newes->es_len;
5136 ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es);
5138 next_del = EXT_MAX_BLOCKS;
5140 next_del = es.es_lblk;
5144 /* fiemap flags we can handle specified here */
5145 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
5147 static int ext4_xattr_fiemap(struct inode *inode,
5148 struct fiemap_extent_info *fieinfo)
5152 __u32 flags = FIEMAP_EXTENT_LAST;
5153 int blockbits = inode->i_sb->s_blocksize_bits;
5157 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5158 struct ext4_iloc iloc;
5159 int offset; /* offset of xattr in inode */
5161 error = ext4_get_inode_loc(inode, &iloc);
5164 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5165 offset = EXT4_GOOD_OLD_INODE_SIZE +
5166 EXT4_I(inode)->i_extra_isize;
5168 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5169 flags |= FIEMAP_EXTENT_DATA_INLINE;
5171 } else { /* external block */
5172 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5173 length = inode->i_sb->s_blocksize;
5177 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5179 return (error < 0 ? error : 0);
5182 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5183 __u64 start, __u64 len)
5185 ext4_lblk_t start_blk;
5188 if (ext4_has_inline_data(inode)) {
5191 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5198 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5199 error = ext4_ext_precache(inode);
5204 /* fallback to generic here if not in extents fmt */
5205 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5206 return generic_block_fiemap(inode, fieinfo, start, len,
5209 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
5212 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5213 error = ext4_xattr_fiemap(inode, fieinfo);
5215 ext4_lblk_t len_blks;
5218 start_blk = start >> inode->i_sb->s_blocksize_bits;
5219 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5220 if (last_blk >= EXT_MAX_BLOCKS)
5221 last_blk = EXT_MAX_BLOCKS-1;
5222 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5225 * Walk the extent tree gathering extent information
5226 * and pushing extents back to the user.
5228 error = ext4_fill_fiemap_extents(inode, start_blk,
5236 * Function to access the path buffer for marking it dirty.
5237 * It also checks if there are sufficient credits left in the journal handle
5241 ext4_access_path(handle_t *handle, struct inode *inode,
5242 struct ext4_ext_path *path)
5246 if (!ext4_handle_valid(handle))
5250 * Check if need to extend journal credits
5251 * 3 for leaf, sb, and inode plus 2 (bmap and group
5252 * descriptor) for each block group; assume two block
5255 if (handle->h_buffer_credits < 7) {
5256 credits = ext4_writepage_trans_blocks(inode);
5257 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
5258 /* EAGAIN is success */
5259 if (err && err != -EAGAIN)
5263 err = ext4_ext_get_access(handle, inode, path);
5268 * ext4_ext_shift_path_extents:
5269 * Shift the extents of a path structure lying between path[depth].p_ext
5270 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5271 * if it is right shift or left shift operation.
5274 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5275 struct inode *inode, handle_t *handle,
5276 enum SHIFT_DIRECTION SHIFT)
5279 struct ext4_extent *ex_start, *ex_last;
5281 depth = path->p_depth;
5283 while (depth >= 0) {
5284 if (depth == path->p_depth) {
5285 ex_start = path[depth].p_ext;
5287 return -EFSCORRUPTED;
5289 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5291 err = ext4_access_path(handle, inode, path + depth);
5295 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5298 while (ex_start <= ex_last) {
5299 if (SHIFT == SHIFT_LEFT) {
5300 le32_add_cpu(&ex_start->ee_block,
5302 /* Try to merge to the left. */
5304 EXT_FIRST_EXTENT(path[depth].p_hdr))
5306 ext4_ext_try_to_merge_right(inode,
5307 path, ex_start - 1))
5312 le32_add_cpu(&ex_last->ee_block, shift);
5313 ext4_ext_try_to_merge_right(inode, path,
5318 err = ext4_ext_dirty(handle, inode, path + depth);
5322 if (--depth < 0 || !update)
5326 /* Update index too */
5327 err = ext4_access_path(handle, inode, path + depth);
5331 if (SHIFT == SHIFT_LEFT)
5332 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5334 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5335 err = ext4_ext_dirty(handle, inode, path + depth);
5339 /* we are done if current index is not a starting index */
5340 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5351 * ext4_ext_shift_extents:
5352 * All the extents which lies in the range from @start to the last allocated
5353 * block for the @inode are shifted either towards left or right (depending
5354 * upon @SHIFT) by @shift blocks.
5355 * On success, 0 is returned, error otherwise.
5358 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5359 ext4_lblk_t start, ext4_lblk_t shift,
5360 enum SHIFT_DIRECTION SHIFT)
5362 struct ext4_ext_path *path;
5364 struct ext4_extent *extent;
5365 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5367 /* Let path point to the last extent */
5368 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5371 return PTR_ERR(path);
5373 depth = path->p_depth;
5374 extent = path[depth].p_ext;
5378 stop = le32_to_cpu(extent->ee_block);
5381 * For left shifts, make sure the hole on the left is big enough to
5382 * accommodate the shift. For right shifts, make sure the last extent
5383 * won't be shifted beyond EXT_MAX_BLOCKS.
5385 if (SHIFT == SHIFT_LEFT) {
5386 path = ext4_find_extent(inode, start - 1, &path,
5389 return PTR_ERR(path);
5390 depth = path->p_depth;
5391 extent = path[depth].p_ext;
5393 ex_start = le32_to_cpu(extent->ee_block);
5394 ex_end = le32_to_cpu(extent->ee_block) +
5395 ext4_ext_get_actual_len(extent);
5401 if ((start == ex_start && shift > ex_start) ||
5402 (shift > start - ex_end)) {
5407 if (shift > EXT_MAX_BLOCKS -
5408 (stop + ext4_ext_get_actual_len(extent))) {
5415 * In case of left shift, iterator points to start and it is increased
5416 * till we reach stop. In case of right shift, iterator points to stop
5417 * and it is decreased till we reach start.
5419 if (SHIFT == SHIFT_LEFT)
5425 * Its safe to start updating extents. Start and stop are unsigned, so
5426 * in case of right shift if extent with 0 block is reached, iterator
5427 * becomes NULL to indicate the end of the loop.
5429 while (iterator && start <= stop) {
5430 path = ext4_find_extent(inode, *iterator, &path,
5433 return PTR_ERR(path);
5434 depth = path->p_depth;
5435 extent = path[depth].p_ext;
5437 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5438 (unsigned long) *iterator);
5439 return -EFSCORRUPTED;
5441 if (SHIFT == SHIFT_LEFT && *iterator >
5442 le32_to_cpu(extent->ee_block)) {
5443 /* Hole, move to the next extent */
5444 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5445 path[depth].p_ext++;
5447 *iterator = ext4_ext_next_allocated_block(path);
5452 if (SHIFT == SHIFT_LEFT) {
5453 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5454 *iterator = le32_to_cpu(extent->ee_block) +
5455 ext4_ext_get_actual_len(extent);
5457 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5458 if (le32_to_cpu(extent->ee_block) > 0)
5459 *iterator = le32_to_cpu(extent->ee_block) - 1;
5461 /* Beginning is reached, end of the loop */
5463 /* Update path extent in case we need to stop */
5464 while (le32_to_cpu(extent->ee_block) < start)
5466 path[depth].p_ext = extent;
5468 ret = ext4_ext_shift_path_extents(path, shift, inode,
5474 ext4_ext_drop_refs(path);
5480 * ext4_collapse_range:
5481 * This implements the fallocate's collapse range functionality for ext4
5482 * Returns: 0 and non-zero on error.
5484 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5486 struct super_block *sb = inode->i_sb;
5487 ext4_lblk_t punch_start, punch_stop;
5489 unsigned int credits;
5490 loff_t new_size, ioffset;
5494 * We need to test this early because xfstests assumes that a
5495 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5496 * system does not support collapse range.
5498 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5501 /* Collapse range works only on fs block size aligned offsets. */
5502 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5503 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5506 if (!S_ISREG(inode->i_mode))
5509 trace_ext4_collapse_range(inode, offset, len);
5511 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5512 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5514 /* Call ext4_force_commit to flush all data in case of data=journal. */
5515 if (ext4_should_journal_data(inode)) {
5516 ret = ext4_force_commit(inode->i_sb);
5523 * There is no need to overlap collapse range with EOF, in which case
5524 * it is effectively a truncate operation
5526 if (offset + len >= i_size_read(inode)) {
5531 /* Currently just for extent based files */
5532 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5537 /* Wait for existing dio to complete */
5538 ext4_inode_block_unlocked_dio(inode);
5539 inode_dio_wait(inode);
5542 * Prevent page faults from reinstantiating pages we have released from
5545 down_write(&EXT4_I(inode)->i_mmap_sem);
5547 * Need to round down offset to be aligned with page size boundary
5548 * for page size > block size.
5550 ioffset = round_down(offset, PAGE_SIZE);
5552 * Write tail of the last page before removed range since it will get
5553 * removed from the page cache below.
5555 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5559 * Write data that will be shifted to preserve them when discarding
5560 * page cache below. We are also protected from pages becoming dirty
5563 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5567 truncate_pagecache(inode, ioffset);
5569 credits = ext4_writepage_trans_blocks(inode);
5570 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5571 if (IS_ERR(handle)) {
5572 ret = PTR_ERR(handle);
5576 down_write(&EXT4_I(inode)->i_data_sem);
5577 ext4_discard_preallocations(inode);
5579 ret = ext4_es_remove_extent(inode, punch_start,
5580 EXT_MAX_BLOCKS - punch_start);
5582 up_write(&EXT4_I(inode)->i_data_sem);
5586 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5588 up_write(&EXT4_I(inode)->i_data_sem);
5591 ext4_discard_preallocations(inode);
5593 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5594 punch_stop - punch_start, SHIFT_LEFT);
5596 up_write(&EXT4_I(inode)->i_data_sem);
5600 new_size = i_size_read(inode) - len;
5601 i_size_write(inode, new_size);
5602 EXT4_I(inode)->i_disksize = new_size;
5604 up_write(&EXT4_I(inode)->i_data_sem);
5606 ext4_handle_sync(handle);
5607 inode->i_mtime = inode->i_ctime = current_time(inode);
5608 ext4_mark_inode_dirty(handle, inode);
5609 ext4_update_inode_fsync_trans(handle, inode, 1);
5612 ext4_journal_stop(handle);
5614 up_write(&EXT4_I(inode)->i_mmap_sem);
5615 ext4_inode_resume_unlocked_dio(inode);
5617 inode_unlock(inode);
5622 * ext4_insert_range:
5623 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5624 * The data blocks starting from @offset to the EOF are shifted by @len
5625 * towards right to create a hole in the @inode. Inode size is increased
5627 * Returns 0 on success, error otherwise.
5629 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5631 struct super_block *sb = inode->i_sb;
5633 struct ext4_ext_path *path;
5634 struct ext4_extent *extent;
5635 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5636 unsigned int credits, ee_len;
5637 int ret = 0, depth, split_flag = 0;
5641 * We need to test this early because xfstests assumes that an
5642 * insert range of (0, 1) will return EOPNOTSUPP if the file
5643 * system does not support insert range.
5645 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5648 /* Insert range works only on fs block size aligned offsets. */
5649 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5650 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5653 if (!S_ISREG(inode->i_mode))
5656 trace_ext4_insert_range(inode, offset, len);
5658 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5659 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5661 /* Call ext4_force_commit to flush all data in case of data=journal */
5662 if (ext4_should_journal_data(inode)) {
5663 ret = ext4_force_commit(inode->i_sb);
5669 /* Currently just for extent based files */
5670 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5675 /* Check for wrap through zero */
5676 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5681 /* Offset should be less than i_size */
5682 if (offset >= i_size_read(inode)) {
5687 /* Wait for existing dio to complete */
5688 ext4_inode_block_unlocked_dio(inode);
5689 inode_dio_wait(inode);
5692 * Prevent page faults from reinstantiating pages we have released from
5695 down_write(&EXT4_I(inode)->i_mmap_sem);
5697 * Need to round down to align start offset to page size boundary
5698 * for page size > block size.
5700 ioffset = round_down(offset, PAGE_SIZE);
5701 /* Write out all dirty pages */
5702 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5706 truncate_pagecache(inode, ioffset);
5708 credits = ext4_writepage_trans_blocks(inode);
5709 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5710 if (IS_ERR(handle)) {
5711 ret = PTR_ERR(handle);
5715 /* Expand file to avoid data loss if there is error while shifting */
5716 inode->i_size += len;
5717 EXT4_I(inode)->i_disksize += len;
5718 inode->i_mtime = inode->i_ctime = current_time(inode);
5719 ret = ext4_mark_inode_dirty(handle, inode);
5723 down_write(&EXT4_I(inode)->i_data_sem);
5724 ext4_discard_preallocations(inode);
5726 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5728 up_write(&EXT4_I(inode)->i_data_sem);
5732 depth = ext_depth(inode);
5733 extent = path[depth].p_ext;
5735 ee_start_lblk = le32_to_cpu(extent->ee_block);
5736 ee_len = ext4_ext_get_actual_len(extent);
5739 * If offset_lblk is not the starting block of extent, split
5740 * the extent @offset_lblk
5742 if ((offset_lblk > ee_start_lblk) &&
5743 (offset_lblk < (ee_start_lblk + ee_len))) {
5744 if (ext4_ext_is_unwritten(extent))
5745 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5746 EXT4_EXT_MARK_UNWRIT2;
5747 ret = ext4_split_extent_at(handle, inode, &path,
5748 offset_lblk, split_flag,
5750 EXT4_GET_BLOCKS_PRE_IO |
5751 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5754 ext4_ext_drop_refs(path);
5757 up_write(&EXT4_I(inode)->i_data_sem);
5761 ext4_ext_drop_refs(path);
5765 ret = ext4_es_remove_extent(inode, offset_lblk,
5766 EXT_MAX_BLOCKS - offset_lblk);
5768 up_write(&EXT4_I(inode)->i_data_sem);
5773 * if offset_lblk lies in a hole which is at start of file, use
5774 * ee_start_lblk to shift extents
5776 ret = ext4_ext_shift_extents(inode, handle,
5777 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5778 len_lblk, SHIFT_RIGHT);
5780 up_write(&EXT4_I(inode)->i_data_sem);
5782 ext4_handle_sync(handle);
5784 ext4_update_inode_fsync_trans(handle, inode, 1);
5787 ext4_journal_stop(handle);
5789 up_write(&EXT4_I(inode)->i_mmap_sem);
5790 ext4_inode_resume_unlocked_dio(inode);
5792 inode_unlock(inode);
5797 * ext4_swap_extents - Swap extents between two inodes
5799 * @inode1: First inode
5800 * @inode2: Second inode
5801 * @lblk1: Start block for first inode
5802 * @lblk2: Start block for second inode
5803 * @count: Number of blocks to swap
5804 * @mark_unwritten: Mark second inode's extents as unwritten after swap
5805 * @erp: Pointer to save error value
5807 * This helper routine does exactly what is promise "swap extents". All other
5808 * stuff such as page-cache locking consistency, bh mapping consistency or
5809 * extent's data copying must be performed by caller.
5811 * i_mutex is held for both inodes
5812 * i_data_sem is locked for write for both inodes
5814 * All pages from requested range are locked for both inodes
5817 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5818 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5819 ext4_lblk_t count, int unwritten, int *erp)
5821 struct ext4_ext_path *path1 = NULL;
5822 struct ext4_ext_path *path2 = NULL;
5823 int replaced_count = 0;
5825 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5826 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5827 BUG_ON(!inode_is_locked(inode1));
5828 BUG_ON(!inode_is_locked(inode2));
5830 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5833 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5838 struct ext4_extent *ex1, *ex2, tmp_ex;
5839 ext4_lblk_t e1_blk, e2_blk;
5840 int e1_len, e2_len, len;
5843 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5844 if (IS_ERR(path1)) {
5845 *erp = PTR_ERR(path1);
5851 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5852 if (IS_ERR(path2)) {
5853 *erp = PTR_ERR(path2);
5857 ex1 = path1[path1->p_depth].p_ext;
5858 ex2 = path2[path2->p_depth].p_ext;
5859 /* Do we have somthing to swap ? */
5860 if (unlikely(!ex2 || !ex1))
5863 e1_blk = le32_to_cpu(ex1->ee_block);
5864 e2_blk = le32_to_cpu(ex2->ee_block);
5865 e1_len = ext4_ext_get_actual_len(ex1);
5866 e2_len = ext4_ext_get_actual_len(ex2);
5869 if (!in_range(lblk1, e1_blk, e1_len) ||
5870 !in_range(lblk2, e2_blk, e2_len)) {
5871 ext4_lblk_t next1, next2;
5873 /* if hole after extent, then go to next extent */
5874 next1 = ext4_ext_next_allocated_block(path1);
5875 next2 = ext4_ext_next_allocated_block(path2);
5876 /* If hole before extent, then shift to that extent */
5881 /* Do we have something to swap */
5882 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5884 /* Move to the rightest boundary */
5885 len = next1 - lblk1;
5886 if (len < next2 - lblk2)
5887 len = next2 - lblk2;
5896 /* Prepare left boundary */
5897 if (e1_blk < lblk1) {
5899 *erp = ext4_force_split_extent_at(handle, inode1,
5904 if (e2_blk < lblk2) {
5906 *erp = ext4_force_split_extent_at(handle, inode2,
5911 /* ext4_split_extent_at() may result in leaf extent split,
5912 * path must to be revalidated. */
5916 /* Prepare right boundary */
5918 if (len > e1_blk + e1_len - lblk1)
5919 len = e1_blk + e1_len - lblk1;
5920 if (len > e2_blk + e2_len - lblk2)
5921 len = e2_blk + e2_len - lblk2;
5923 if (len != e1_len) {
5925 *erp = ext4_force_split_extent_at(handle, inode1,
5926 &path1, lblk1 + len, 0);
5930 if (len != e2_len) {
5932 *erp = ext4_force_split_extent_at(handle, inode2,
5933 &path2, lblk2 + len, 0);
5937 /* ext4_split_extent_at() may result in leaf extent split,
5938 * path must to be revalidated. */
5942 BUG_ON(e2_len != e1_len);
5943 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5946 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5950 /* Both extents are fully inside boundaries. Swap it now */
5952 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5953 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5954 ex1->ee_len = cpu_to_le16(e2_len);
5955 ex2->ee_len = cpu_to_le16(e1_len);
5957 ext4_ext_mark_unwritten(ex2);
5958 if (ext4_ext_is_unwritten(&tmp_ex))
5959 ext4_ext_mark_unwritten(ex1);
5961 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5962 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5963 *erp = ext4_ext_dirty(handle, inode2, path2 +
5967 *erp = ext4_ext_dirty(handle, inode1, path1 +
5970 * Looks scarry ah..? second inode already points to new blocks,
5971 * and it was successfully dirtied. But luckily error may happen
5972 * only due to journal error, so full transaction will be
5979 replaced_count += len;
5983 ext4_ext_drop_refs(path1);
5985 ext4_ext_drop_refs(path2);
5987 path1 = path2 = NULL;
5989 return replaced_count;