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 Licens
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
32 #include <linux/module.h>
34 #include <linux/time.h>
35 #include <linux/jbd2.h>
36 #include <linux/highuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/quotaops.h>
39 #include <linux/string.h>
40 #include <linux/slab.h>
41 #include <linux/falloc.h>
42 #include <asm/uaccess.h>
43 #include <linux/fiemap.h>
44 #include "ext4_jbd2.h"
46 #include <trace/events/ext4.h>
48 static int ext4_split_extent(handle_t *handle,
50 struct ext4_ext_path *path,
51 struct ext4_map_blocks *map,
55 static int ext4_ext_truncate_extend_restart(handle_t *handle,
61 if (!ext4_handle_valid(handle))
63 if (handle->h_buffer_credits > needed)
65 err = ext4_journal_extend(handle, needed);
68 err = ext4_truncate_restart_trans(handle, inode, needed);
80 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
81 struct ext4_ext_path *path)
84 /* path points to block */
85 return ext4_journal_get_write_access(handle, path->p_bh);
87 /* path points to leaf/index in inode body */
88 /* we use in-core data, no need to protect them */
98 #define ext4_ext_dirty(handle, inode, path) \
99 __ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
100 static int __ext4_ext_dirty(const char *where, unsigned int line,
101 handle_t *handle, struct inode *inode,
102 struct ext4_ext_path *path)
106 /* path points to block */
107 err = __ext4_handle_dirty_metadata(where, line, handle,
110 /* path points to leaf/index in inode body */
111 err = ext4_mark_inode_dirty(handle, inode);
116 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
117 struct ext4_ext_path *path,
121 int depth = path->p_depth;
122 struct ext4_extent *ex;
125 * Try to predict block placement assuming that we are
126 * filling in a file which will eventually be
127 * non-sparse --- i.e., in the case of libbfd writing
128 * an ELF object sections out-of-order but in a way
129 * the eventually results in a contiguous object or
130 * executable file, or some database extending a table
131 * space file. However, this is actually somewhat
132 * non-ideal if we are writing a sparse file such as
133 * qemu or KVM writing a raw image file that is going
134 * to stay fairly sparse, since it will end up
135 * fragmenting the file system's free space. Maybe we
136 * should have some hueristics or some way to allow
137 * userspace to pass a hint to file system,
138 * especially if the latter case turns out to be
141 ex = path[depth].p_ext;
143 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
144 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
146 if (block > ext_block)
147 return ext_pblk + (block - ext_block);
149 return ext_pblk - (ext_block - block);
152 /* it looks like index is empty;
153 * try to find starting block from index itself */
154 if (path[depth].p_bh)
155 return path[depth].p_bh->b_blocknr;
158 /* OK. use inode's group */
159 return ext4_inode_to_goal_block(inode);
163 * Allocation for a meta data block
166 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
167 struct ext4_ext_path *path,
168 struct ext4_extent *ex, int *err, unsigned int flags)
170 ext4_fsblk_t goal, newblock;
172 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
173 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
178 static inline int ext4_ext_space_block(struct inode *inode, int check)
182 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
183 / sizeof(struct ext4_extent);
184 #ifdef AGGRESSIVE_TEST
185 if (!check && size > 6)
191 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
195 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
196 / sizeof(struct ext4_extent_idx);
197 #ifdef AGGRESSIVE_TEST
198 if (!check && size > 5)
204 static inline int ext4_ext_space_root(struct inode *inode, int check)
208 size = sizeof(EXT4_I(inode)->i_data);
209 size -= sizeof(struct ext4_extent_header);
210 size /= sizeof(struct ext4_extent);
211 #ifdef AGGRESSIVE_TEST
212 if (!check && size > 3)
218 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
222 size = sizeof(EXT4_I(inode)->i_data);
223 size -= sizeof(struct ext4_extent_header);
224 size /= sizeof(struct ext4_extent_idx);
225 #ifdef AGGRESSIVE_TEST
226 if (!check && size > 4)
233 * Calculate the number of metadata blocks needed
234 * to allocate @blocks
235 * Worse case is one block per extent
237 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
239 struct ext4_inode_info *ei = EXT4_I(inode);
242 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
243 / sizeof(struct ext4_extent_idx));
246 * If the new delayed allocation block is contiguous with the
247 * previous da block, it can share index blocks with the
248 * previous block, so we only need to allocate a new index
249 * block every idxs leaf blocks. At ldxs**2 blocks, we need
250 * an additional index block, and at ldxs**3 blocks, yet
251 * another index blocks.
253 if (ei->i_da_metadata_calc_len &&
254 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
257 if ((ei->i_da_metadata_calc_len % idxs) == 0)
259 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
261 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
263 ei->i_da_metadata_calc_len = 0;
265 ei->i_da_metadata_calc_len++;
266 ei->i_da_metadata_calc_last_lblock++;
271 * In the worst case we need a new set of index blocks at
272 * every level of the inode's extent tree.
274 ei->i_da_metadata_calc_len = 1;
275 ei->i_da_metadata_calc_last_lblock = lblock;
276 return ext_depth(inode) + 1;
280 ext4_ext_max_entries(struct inode *inode, int depth)
284 if (depth == ext_depth(inode)) {
286 max = ext4_ext_space_root(inode, 1);
288 max = ext4_ext_space_root_idx(inode, 1);
291 max = ext4_ext_space_block(inode, 1);
293 max = ext4_ext_space_block_idx(inode, 1);
299 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
301 ext4_fsblk_t block = ext4_ext_pblock(ext);
302 int len = ext4_ext_get_actual_len(ext);
306 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
309 static int ext4_valid_extent_idx(struct inode *inode,
310 struct ext4_extent_idx *ext_idx)
312 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
314 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
317 static int ext4_valid_extent_entries(struct inode *inode,
318 struct ext4_extent_header *eh,
321 unsigned short entries;
322 if (eh->eh_entries == 0)
325 entries = le16_to_cpu(eh->eh_entries);
329 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
331 if (!ext4_valid_extent(inode, ext))
337 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
339 if (!ext4_valid_extent_idx(inode, ext_idx))
348 static int __ext4_ext_check(const char *function, unsigned int line,
349 struct inode *inode, struct ext4_extent_header *eh,
352 const char *error_msg;
355 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
356 error_msg = "invalid magic";
359 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
360 error_msg = "unexpected eh_depth";
363 if (unlikely(eh->eh_max == 0)) {
364 error_msg = "invalid eh_max";
367 max = ext4_ext_max_entries(inode, depth);
368 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
369 error_msg = "too large eh_max";
372 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
373 error_msg = "invalid eh_entries";
376 if (!ext4_valid_extent_entries(inode, eh, depth)) {
377 error_msg = "invalid extent entries";
383 ext4_error_inode(inode, function, line, 0,
384 "bad header/extent: %s - magic %x, "
385 "entries %u, max %u(%u), depth %u(%u)",
386 error_msg, le16_to_cpu(eh->eh_magic),
387 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
388 max, le16_to_cpu(eh->eh_depth), depth);
393 #define ext4_ext_check(inode, eh, depth) \
394 __ext4_ext_check(__func__, __LINE__, inode, eh, depth)
396 int ext4_ext_check_inode(struct inode *inode)
398 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
402 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
404 int k, l = path->p_depth;
407 for (k = 0; k <= l; k++, path++) {
409 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
410 ext4_idx_pblock(path->p_idx));
411 } else if (path->p_ext) {
412 ext_debug(" %d:[%d]%d:%llu ",
413 le32_to_cpu(path->p_ext->ee_block),
414 ext4_ext_is_uninitialized(path->p_ext),
415 ext4_ext_get_actual_len(path->p_ext),
416 ext4_ext_pblock(path->p_ext));
423 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
425 int depth = ext_depth(inode);
426 struct ext4_extent_header *eh;
427 struct ext4_extent *ex;
433 eh = path[depth].p_hdr;
434 ex = EXT_FIRST_EXTENT(eh);
436 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
438 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
439 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
440 ext4_ext_is_uninitialized(ex),
441 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
446 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
447 ext4_fsblk_t newblock, int level)
449 int depth = ext_depth(inode);
450 struct ext4_extent *ex;
452 if (depth != level) {
453 struct ext4_extent_idx *idx;
454 idx = path[level].p_idx;
455 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
456 ext_debug("%d: move %d:%llu in new index %llu\n", level,
457 le32_to_cpu(idx->ei_block),
458 ext4_idx_pblock(idx),
466 ex = path[depth].p_ext;
467 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
468 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
469 le32_to_cpu(ex->ee_block),
471 ext4_ext_is_uninitialized(ex),
472 ext4_ext_get_actual_len(ex),
479 #define ext4_ext_show_path(inode, path)
480 #define ext4_ext_show_leaf(inode, path)
481 #define ext4_ext_show_move(inode, path, newblock, level)
484 void ext4_ext_drop_refs(struct ext4_ext_path *path)
486 int depth = path->p_depth;
489 for (i = 0; i <= depth; i++, path++)
497 * ext4_ext_binsearch_idx:
498 * binary search for the closest index of the given block
499 * the header must be checked before calling this
502 ext4_ext_binsearch_idx(struct inode *inode,
503 struct ext4_ext_path *path, ext4_lblk_t block)
505 struct ext4_extent_header *eh = path->p_hdr;
506 struct ext4_extent_idx *r, *l, *m;
509 ext_debug("binsearch for %u(idx): ", block);
511 l = EXT_FIRST_INDEX(eh) + 1;
512 r = EXT_LAST_INDEX(eh);
515 if (block < le32_to_cpu(m->ei_block))
519 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
520 m, le32_to_cpu(m->ei_block),
521 r, le32_to_cpu(r->ei_block));
525 ext_debug(" -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
526 ext4_idx_pblock(path->p_idx));
528 #ifdef CHECK_BINSEARCH
530 struct ext4_extent_idx *chix, *ix;
533 chix = ix = EXT_FIRST_INDEX(eh);
534 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
536 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
537 printk(KERN_DEBUG "k=%d, ix=0x%p, "
539 ix, EXT_FIRST_INDEX(eh));
540 printk(KERN_DEBUG "%u <= %u\n",
541 le32_to_cpu(ix->ei_block),
542 le32_to_cpu(ix[-1].ei_block));
544 BUG_ON(k && le32_to_cpu(ix->ei_block)
545 <= le32_to_cpu(ix[-1].ei_block));
546 if (block < le32_to_cpu(ix->ei_block))
550 BUG_ON(chix != path->p_idx);
557 * ext4_ext_binsearch:
558 * binary search for closest extent of the given block
559 * the header must be checked before calling this
562 ext4_ext_binsearch(struct inode *inode,
563 struct ext4_ext_path *path, ext4_lblk_t block)
565 struct ext4_extent_header *eh = path->p_hdr;
566 struct ext4_extent *r, *l, *m;
568 if (eh->eh_entries == 0) {
570 * this leaf is empty:
571 * we get such a leaf in split/add case
576 ext_debug("binsearch for %u: ", block);
578 l = EXT_FIRST_EXTENT(eh) + 1;
579 r = EXT_LAST_EXTENT(eh);
583 if (block < le32_to_cpu(m->ee_block))
587 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
588 m, le32_to_cpu(m->ee_block),
589 r, le32_to_cpu(r->ee_block));
593 ext_debug(" -> %d:%llu:[%d]%d ",
594 le32_to_cpu(path->p_ext->ee_block),
595 ext4_ext_pblock(path->p_ext),
596 ext4_ext_is_uninitialized(path->p_ext),
597 ext4_ext_get_actual_len(path->p_ext));
599 #ifdef CHECK_BINSEARCH
601 struct ext4_extent *chex, *ex;
604 chex = ex = EXT_FIRST_EXTENT(eh);
605 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
606 BUG_ON(k && le32_to_cpu(ex->ee_block)
607 <= le32_to_cpu(ex[-1].ee_block));
608 if (block < le32_to_cpu(ex->ee_block))
612 BUG_ON(chex != path->p_ext);
618 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
620 struct ext4_extent_header *eh;
622 eh = ext_inode_hdr(inode);
625 eh->eh_magic = EXT4_EXT_MAGIC;
626 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
627 ext4_mark_inode_dirty(handle, inode);
628 ext4_ext_invalidate_cache(inode);
632 struct ext4_ext_path *
633 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
634 struct ext4_ext_path *path)
636 struct ext4_extent_header *eh;
637 struct buffer_head *bh;
638 short int depth, i, ppos = 0, alloc = 0;
640 eh = ext_inode_hdr(inode);
641 depth = ext_depth(inode);
643 /* account possible depth increase */
645 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
648 return ERR_PTR(-ENOMEM);
655 /* walk through the tree */
657 int need_to_validate = 0;
659 ext_debug("depth %d: num %d, max %d\n",
660 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
662 ext4_ext_binsearch_idx(inode, path + ppos, block);
663 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
664 path[ppos].p_depth = i;
665 path[ppos].p_ext = NULL;
667 bh = sb_getblk(inode->i_sb, path[ppos].p_block);
670 if (!bh_uptodate_or_lock(bh)) {
671 trace_ext4_ext_load_extent(inode, block,
673 if (bh_submit_read(bh) < 0) {
677 /* validate the extent entries */
678 need_to_validate = 1;
680 eh = ext_block_hdr(bh);
682 if (unlikely(ppos > depth)) {
684 EXT4_ERROR_INODE(inode,
685 "ppos %d > depth %d", ppos, depth);
688 path[ppos].p_bh = bh;
689 path[ppos].p_hdr = eh;
692 if (need_to_validate && ext4_ext_check(inode, eh, i))
696 path[ppos].p_depth = i;
697 path[ppos].p_ext = NULL;
698 path[ppos].p_idx = NULL;
701 ext4_ext_binsearch(inode, path + ppos, block);
702 /* if not an empty leaf */
703 if (path[ppos].p_ext)
704 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
706 ext4_ext_show_path(inode, path);
711 ext4_ext_drop_refs(path);
714 return ERR_PTR(-EIO);
718 * ext4_ext_insert_index:
719 * insert new index [@logical;@ptr] into the block at @curp;
720 * check where to insert: before @curp or after @curp
722 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
723 struct ext4_ext_path *curp,
724 int logical, ext4_fsblk_t ptr)
726 struct ext4_extent_idx *ix;
729 err = ext4_ext_get_access(handle, inode, curp);
733 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
734 EXT4_ERROR_INODE(inode,
735 "logical %d == ei_block %d!",
736 logical, le32_to_cpu(curp->p_idx->ei_block));
740 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
741 >= le16_to_cpu(curp->p_hdr->eh_max))) {
742 EXT4_ERROR_INODE(inode,
743 "eh_entries %d >= eh_max %d!",
744 le16_to_cpu(curp->p_hdr->eh_entries),
745 le16_to_cpu(curp->p_hdr->eh_max));
749 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
751 ext_debug("insert new index %d after: %llu\n", logical, ptr);
752 ix = curp->p_idx + 1;
755 ext_debug("insert new index %d before: %llu\n", logical, ptr);
759 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
762 ext_debug("insert new index %d: "
763 "move %d indices from 0x%p to 0x%p\n",
764 logical, len, ix, ix + 1);
765 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
768 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
769 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
773 ix->ei_block = cpu_to_le32(logical);
774 ext4_idx_store_pblock(ix, ptr);
775 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
777 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
778 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
782 err = ext4_ext_dirty(handle, inode, curp);
783 ext4_std_error(inode->i_sb, err);
790 * inserts new subtree into the path, using free index entry
792 * - allocates all needed blocks (new leaf and all intermediate index blocks)
793 * - makes decision where to split
794 * - moves remaining extents and index entries (right to the split point)
795 * into the newly allocated blocks
796 * - initializes subtree
798 static int ext4_ext_split(handle_t *handle, struct inode *inode,
800 struct ext4_ext_path *path,
801 struct ext4_extent *newext, int at)
803 struct buffer_head *bh = NULL;
804 int depth = ext_depth(inode);
805 struct ext4_extent_header *neh;
806 struct ext4_extent_idx *fidx;
808 ext4_fsblk_t newblock, oldblock;
810 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
813 /* make decision: where to split? */
814 /* FIXME: now decision is simplest: at current extent */
816 /* if current leaf will be split, then we should use
817 * border from split point */
818 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
819 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
822 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
823 border = path[depth].p_ext[1].ee_block;
824 ext_debug("leaf will be split."
825 " next leaf starts at %d\n",
826 le32_to_cpu(border));
828 border = newext->ee_block;
829 ext_debug("leaf will be added."
830 " next leaf starts at %d\n",
831 le32_to_cpu(border));
835 * If error occurs, then we break processing
836 * and mark filesystem read-only. index won't
837 * be inserted and tree will be in consistent
838 * state. Next mount will repair buffers too.
842 * Get array to track all allocated blocks.
843 * We need this to handle errors and free blocks
846 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
850 /* allocate all needed blocks */
851 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
852 for (a = 0; a < depth - at; a++) {
853 newblock = ext4_ext_new_meta_block(handle, inode, path,
854 newext, &err, flags);
857 ablocks[a] = newblock;
860 /* initialize new leaf */
861 newblock = ablocks[--a];
862 if (unlikely(newblock == 0)) {
863 EXT4_ERROR_INODE(inode, "newblock == 0!");
867 bh = sb_getblk(inode->i_sb, newblock);
874 err = ext4_journal_get_create_access(handle, bh);
878 neh = ext_block_hdr(bh);
880 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
881 neh->eh_magic = EXT4_EXT_MAGIC;
884 /* move remainder of path[depth] to the new leaf */
885 if (unlikely(path[depth].p_hdr->eh_entries !=
886 path[depth].p_hdr->eh_max)) {
887 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
888 path[depth].p_hdr->eh_entries,
889 path[depth].p_hdr->eh_max);
893 /* start copy from next extent */
894 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
895 ext4_ext_show_move(inode, path, newblock, depth);
897 struct ext4_extent *ex;
898 ex = EXT_FIRST_EXTENT(neh);
899 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
900 le16_add_cpu(&neh->eh_entries, m);
903 set_buffer_uptodate(bh);
906 err = ext4_handle_dirty_metadata(handle, inode, bh);
912 /* correct old leaf */
914 err = ext4_ext_get_access(handle, inode, path + depth);
917 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
918 err = ext4_ext_dirty(handle, inode, path + depth);
924 /* create intermediate indexes */
926 if (unlikely(k < 0)) {
927 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
932 ext_debug("create %d intermediate indices\n", k);
933 /* insert new index into current index block */
934 /* current depth stored in i var */
938 newblock = ablocks[--a];
939 bh = sb_getblk(inode->i_sb, newblock);
946 err = ext4_journal_get_create_access(handle, bh);
950 neh = ext_block_hdr(bh);
951 neh->eh_entries = cpu_to_le16(1);
952 neh->eh_magic = EXT4_EXT_MAGIC;
953 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
954 neh->eh_depth = cpu_to_le16(depth - i);
955 fidx = EXT_FIRST_INDEX(neh);
956 fidx->ei_block = border;
957 ext4_idx_store_pblock(fidx, oldblock);
959 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
960 i, newblock, le32_to_cpu(border), oldblock);
962 /* move remainder of path[i] to the new index block */
963 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
964 EXT_LAST_INDEX(path[i].p_hdr))) {
965 EXT4_ERROR_INODE(inode,
966 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
967 le32_to_cpu(path[i].p_ext->ee_block));
971 /* start copy indexes */
972 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
973 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
974 EXT_MAX_INDEX(path[i].p_hdr));
975 ext4_ext_show_move(inode, path, newblock, i);
977 memmove(++fidx, path[i].p_idx,
978 sizeof(struct ext4_extent_idx) * m);
979 le16_add_cpu(&neh->eh_entries, m);
981 set_buffer_uptodate(bh);
984 err = ext4_handle_dirty_metadata(handle, inode, bh);
990 /* correct old index */
992 err = ext4_ext_get_access(handle, inode, path + i);
995 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
996 err = ext4_ext_dirty(handle, inode, path + i);
1004 /* insert new index */
1005 err = ext4_ext_insert_index(handle, inode, path + at,
1006 le32_to_cpu(border), newblock);
1010 if (buffer_locked(bh))
1016 /* free all allocated blocks in error case */
1017 for (i = 0; i < depth; i++) {
1020 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1021 EXT4_FREE_BLOCKS_METADATA);
1030 * ext4_ext_grow_indepth:
1031 * implements tree growing procedure:
1032 * - allocates new block
1033 * - moves top-level data (index block or leaf) into the new block
1034 * - initializes new top-level, creating index that points to the
1035 * just created block
1037 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1039 struct ext4_extent *newext)
1041 struct ext4_extent_header *neh;
1042 struct buffer_head *bh;
1043 ext4_fsblk_t newblock;
1046 newblock = ext4_ext_new_meta_block(handle, inode, NULL,
1047 newext, &err, flags);
1051 bh = sb_getblk(inode->i_sb, newblock);
1054 ext4_std_error(inode->i_sb, err);
1059 err = ext4_journal_get_create_access(handle, bh);
1065 /* move top-level index/leaf into new block */
1066 memmove(bh->b_data, EXT4_I(inode)->i_data,
1067 sizeof(EXT4_I(inode)->i_data));
1069 /* set size of new block */
1070 neh = ext_block_hdr(bh);
1071 /* old root could have indexes or leaves
1072 * so calculate e_max right way */
1073 if (ext_depth(inode))
1074 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1076 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1077 neh->eh_magic = EXT4_EXT_MAGIC;
1078 set_buffer_uptodate(bh);
1081 err = ext4_handle_dirty_metadata(handle, inode, bh);
1085 /* Update top-level index: num,max,pointer */
1086 neh = ext_inode_hdr(inode);
1087 neh->eh_entries = cpu_to_le16(1);
1088 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1089 if (neh->eh_depth == 0) {
1090 /* Root extent block becomes index block */
1091 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1092 EXT_FIRST_INDEX(neh)->ei_block =
1093 EXT_FIRST_EXTENT(neh)->ee_block;
1095 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1096 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1097 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1098 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1100 neh->eh_depth = cpu_to_le16(le16_to_cpu(neh->eh_depth) + 1);
1101 ext4_mark_inode_dirty(handle, inode);
1109 * ext4_ext_create_new_leaf:
1110 * finds empty index and adds new leaf.
1111 * if no free index is found, then it requests in-depth growing.
1113 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1115 struct ext4_ext_path *path,
1116 struct ext4_extent *newext)
1118 struct ext4_ext_path *curp;
1119 int depth, i, err = 0;
1122 i = depth = ext_depth(inode);
1124 /* walk up to the tree and look for free index entry */
1125 curp = path + depth;
1126 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1131 /* we use already allocated block for index block,
1132 * so subsequent data blocks should be contiguous */
1133 if (EXT_HAS_FREE_INDEX(curp)) {
1134 /* if we found index with free entry, then use that
1135 * entry: create all needed subtree and add new leaf */
1136 err = ext4_ext_split(handle, inode, flags, path, newext, i);
1141 ext4_ext_drop_refs(path);
1142 path = ext4_ext_find_extent(inode,
1143 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1146 err = PTR_ERR(path);
1148 /* tree is full, time to grow in depth */
1149 err = ext4_ext_grow_indepth(handle, inode, flags, newext);
1154 ext4_ext_drop_refs(path);
1155 path = ext4_ext_find_extent(inode,
1156 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1159 err = PTR_ERR(path);
1164 * only first (depth 0 -> 1) produces free space;
1165 * in all other cases we have to split the grown tree
1167 depth = ext_depth(inode);
1168 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1169 /* now we need to split */
1179 * search the closest allocated block to the left for *logical
1180 * and returns it at @logical + it's physical address at @phys
1181 * if *logical is the smallest allocated block, the function
1182 * returns 0 at @phys
1183 * return value contains 0 (success) or error code
1185 static int ext4_ext_search_left(struct inode *inode,
1186 struct ext4_ext_path *path,
1187 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1189 struct ext4_extent_idx *ix;
1190 struct ext4_extent *ex;
1193 if (unlikely(path == NULL)) {
1194 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1197 depth = path->p_depth;
1200 if (depth == 0 && path->p_ext == NULL)
1203 /* usually extent in the path covers blocks smaller
1204 * then *logical, but it can be that extent is the
1205 * first one in the file */
1207 ex = path[depth].p_ext;
1208 ee_len = ext4_ext_get_actual_len(ex);
1209 if (*logical < le32_to_cpu(ex->ee_block)) {
1210 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1211 EXT4_ERROR_INODE(inode,
1212 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1213 *logical, le32_to_cpu(ex->ee_block));
1216 while (--depth >= 0) {
1217 ix = path[depth].p_idx;
1218 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1219 EXT4_ERROR_INODE(inode,
1220 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1221 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1222 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1223 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1231 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1232 EXT4_ERROR_INODE(inode,
1233 "logical %d < ee_block %d + ee_len %d!",
1234 *logical, le32_to_cpu(ex->ee_block), ee_len);
1238 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1239 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1244 * search the closest allocated block to the right for *logical
1245 * and returns it at @logical + it's physical address at @phys
1246 * if *logical is the largest allocated block, the function
1247 * returns 0 at @phys
1248 * return value contains 0 (success) or error code
1250 static int ext4_ext_search_right(struct inode *inode,
1251 struct ext4_ext_path *path,
1252 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1253 struct ext4_extent **ret_ex)
1255 struct buffer_head *bh = NULL;
1256 struct ext4_extent_header *eh;
1257 struct ext4_extent_idx *ix;
1258 struct ext4_extent *ex;
1260 int depth; /* Note, NOT eh_depth; depth from top of tree */
1263 if (unlikely(path == NULL)) {
1264 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1267 depth = path->p_depth;
1270 if (depth == 0 && path->p_ext == NULL)
1273 /* usually extent in the path covers blocks smaller
1274 * then *logical, but it can be that extent is the
1275 * first one in the file */
1277 ex = path[depth].p_ext;
1278 ee_len = ext4_ext_get_actual_len(ex);
1279 if (*logical < le32_to_cpu(ex->ee_block)) {
1280 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1281 EXT4_ERROR_INODE(inode,
1282 "first_extent(path[%d].p_hdr) != ex",
1286 while (--depth >= 0) {
1287 ix = path[depth].p_idx;
1288 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1289 EXT4_ERROR_INODE(inode,
1290 "ix != EXT_FIRST_INDEX *logical %d!",
1298 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1299 EXT4_ERROR_INODE(inode,
1300 "logical %d < ee_block %d + ee_len %d!",
1301 *logical, le32_to_cpu(ex->ee_block), ee_len);
1305 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1306 /* next allocated block in this leaf */
1311 /* go up and search for index to the right */
1312 while (--depth >= 0) {
1313 ix = path[depth].p_idx;
1314 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1318 /* we've gone up to the root and found no index to the right */
1322 /* we've found index to the right, let's
1323 * follow it and find the closest allocated
1324 * block to the right */
1326 block = ext4_idx_pblock(ix);
1327 while (++depth < path->p_depth) {
1328 bh = sb_bread(inode->i_sb, block);
1331 eh = ext_block_hdr(bh);
1332 /* subtract from p_depth to get proper eh_depth */
1333 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1337 ix = EXT_FIRST_INDEX(eh);
1338 block = ext4_idx_pblock(ix);
1342 bh = sb_bread(inode->i_sb, block);
1345 eh = ext_block_hdr(bh);
1346 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1350 ex = EXT_FIRST_EXTENT(eh);
1352 *logical = le32_to_cpu(ex->ee_block);
1353 *phys = ext4_ext_pblock(ex);
1361 * ext4_ext_next_allocated_block:
1362 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1363 * NOTE: it considers block number from index entry as
1364 * allocated block. Thus, index entries have to be consistent
1368 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1372 BUG_ON(path == NULL);
1373 depth = path->p_depth;
1375 if (depth == 0 && path->p_ext == NULL)
1376 return EXT_MAX_BLOCKS;
1378 while (depth >= 0) {
1379 if (depth == path->p_depth) {
1381 if (path[depth].p_ext &&
1382 path[depth].p_ext !=
1383 EXT_LAST_EXTENT(path[depth].p_hdr))
1384 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1387 if (path[depth].p_idx !=
1388 EXT_LAST_INDEX(path[depth].p_hdr))
1389 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1394 return EXT_MAX_BLOCKS;
1398 * ext4_ext_next_leaf_block:
1399 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1401 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1405 BUG_ON(path == NULL);
1406 depth = path->p_depth;
1408 /* zero-tree has no leaf blocks at all */
1410 return EXT_MAX_BLOCKS;
1412 /* go to index block */
1415 while (depth >= 0) {
1416 if (path[depth].p_idx !=
1417 EXT_LAST_INDEX(path[depth].p_hdr))
1418 return (ext4_lblk_t)
1419 le32_to_cpu(path[depth].p_idx[1].ei_block);
1423 return EXT_MAX_BLOCKS;
1427 * ext4_ext_correct_indexes:
1428 * if leaf gets modified and modified extent is first in the leaf,
1429 * then we have to correct all indexes above.
1430 * TODO: do we need to correct tree in all cases?
1432 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1433 struct ext4_ext_path *path)
1435 struct ext4_extent_header *eh;
1436 int depth = ext_depth(inode);
1437 struct ext4_extent *ex;
1441 eh = path[depth].p_hdr;
1442 ex = path[depth].p_ext;
1444 if (unlikely(ex == NULL || eh == NULL)) {
1445 EXT4_ERROR_INODE(inode,
1446 "ex %p == NULL or eh %p == NULL", ex, eh);
1451 /* there is no tree at all */
1455 if (ex != EXT_FIRST_EXTENT(eh)) {
1456 /* we correct tree if first leaf got modified only */
1461 * TODO: we need correction if border is smaller than current one
1464 border = path[depth].p_ext->ee_block;
1465 err = ext4_ext_get_access(handle, inode, path + k);
1468 path[k].p_idx->ei_block = border;
1469 err = ext4_ext_dirty(handle, inode, path + k);
1474 /* change all left-side indexes */
1475 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1477 err = ext4_ext_get_access(handle, inode, path + k);
1480 path[k].p_idx->ei_block = border;
1481 err = ext4_ext_dirty(handle, inode, path + k);
1490 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1491 struct ext4_extent *ex2)
1493 unsigned short ext1_ee_len, ext2_ee_len, max_len;
1496 * Make sure that either both extents are uninitialized, or
1499 if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1502 if (ext4_ext_is_uninitialized(ex1))
1503 max_len = EXT_UNINIT_MAX_LEN;
1505 max_len = EXT_INIT_MAX_LEN;
1507 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1508 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1510 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1511 le32_to_cpu(ex2->ee_block))
1515 * To allow future support for preallocated extents to be added
1516 * as an RO_COMPAT feature, refuse to merge to extents if
1517 * this can result in the top bit of ee_len being set.
1519 if (ext1_ee_len + ext2_ee_len > max_len)
1521 #ifdef AGGRESSIVE_TEST
1522 if (ext1_ee_len >= 4)
1526 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1532 * This function tries to merge the "ex" extent to the next extent in the tree.
1533 * It always tries to merge towards right. If you want to merge towards
1534 * left, pass "ex - 1" as argument instead of "ex".
1535 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1536 * 1 if they got merged.
1538 static int ext4_ext_try_to_merge_right(struct inode *inode,
1539 struct ext4_ext_path *path,
1540 struct ext4_extent *ex)
1542 struct ext4_extent_header *eh;
1543 unsigned int depth, len;
1545 int uninitialized = 0;
1547 depth = ext_depth(inode);
1548 BUG_ON(path[depth].p_hdr == NULL);
1549 eh = path[depth].p_hdr;
1551 while (ex < EXT_LAST_EXTENT(eh)) {
1552 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1554 /* merge with next extent! */
1555 if (ext4_ext_is_uninitialized(ex))
1557 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1558 + ext4_ext_get_actual_len(ex + 1));
1560 ext4_ext_mark_uninitialized(ex);
1562 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1563 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1564 * sizeof(struct ext4_extent);
1565 memmove(ex + 1, ex + 2, len);
1567 le16_add_cpu(&eh->eh_entries, -1);
1569 WARN_ON(eh->eh_entries == 0);
1570 if (!eh->eh_entries)
1571 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1578 * This function tries to merge the @ex extent to neighbours in the tree.
1579 * return 1 if merge left else 0.
1581 static int ext4_ext_try_to_merge(struct inode *inode,
1582 struct ext4_ext_path *path,
1583 struct ext4_extent *ex) {
1584 struct ext4_extent_header *eh;
1589 depth = ext_depth(inode);
1590 BUG_ON(path[depth].p_hdr == NULL);
1591 eh = path[depth].p_hdr;
1593 if (ex > EXT_FIRST_EXTENT(eh))
1594 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1597 ret = ext4_ext_try_to_merge_right(inode, path, ex);
1603 * check if a portion of the "newext" extent overlaps with an
1606 * If there is an overlap discovered, it updates the length of the newext
1607 * such that there will be no overlap, and then returns 1.
1608 * If there is no overlap found, it returns 0.
1610 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1611 struct inode *inode,
1612 struct ext4_extent *newext,
1613 struct ext4_ext_path *path)
1616 unsigned int depth, len1;
1617 unsigned int ret = 0;
1619 b1 = le32_to_cpu(newext->ee_block);
1620 len1 = ext4_ext_get_actual_len(newext);
1621 depth = ext_depth(inode);
1622 if (!path[depth].p_ext)
1624 b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1625 b2 &= ~(sbi->s_cluster_ratio - 1);
1628 * get the next allocated block if the extent in the path
1629 * is before the requested block(s)
1632 b2 = ext4_ext_next_allocated_block(path);
1633 if (b2 == EXT_MAX_BLOCKS)
1635 b2 &= ~(sbi->s_cluster_ratio - 1);
1638 /* check for wrap through zero on extent logical start block*/
1639 if (b1 + len1 < b1) {
1640 len1 = EXT_MAX_BLOCKS - b1;
1641 newext->ee_len = cpu_to_le16(len1);
1645 /* check for overlap */
1646 if (b1 + len1 > b2) {
1647 newext->ee_len = cpu_to_le16(b2 - b1);
1655 * ext4_ext_insert_extent:
1656 * tries to merge requsted extent into the existing extent or
1657 * inserts requested extent as new one into the tree,
1658 * creating new leaf in the no-space case.
1660 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1661 struct ext4_ext_path *path,
1662 struct ext4_extent *newext, int flag)
1664 struct ext4_extent_header *eh;
1665 struct ext4_extent *ex, *fex;
1666 struct ext4_extent *nearex; /* nearest extent */
1667 struct ext4_ext_path *npath = NULL;
1668 int depth, len, err;
1670 unsigned uninitialized = 0;
1673 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1674 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1677 depth = ext_depth(inode);
1678 ex = path[depth].p_ext;
1679 if (unlikely(path[depth].p_hdr == NULL)) {
1680 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1684 /* try to insert block into found extent and return */
1685 if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
1686 && ext4_can_extents_be_merged(inode, ex, newext)) {
1687 ext_debug("append [%d]%d block to %u:[%d]%d (from %llu)\n",
1688 ext4_ext_is_uninitialized(newext),
1689 ext4_ext_get_actual_len(newext),
1690 le32_to_cpu(ex->ee_block),
1691 ext4_ext_is_uninitialized(ex),
1692 ext4_ext_get_actual_len(ex),
1693 ext4_ext_pblock(ex));
1694 err = ext4_ext_get_access(handle, inode, path + depth);
1699 * ext4_can_extents_be_merged should have checked that either
1700 * both extents are uninitialized, or both aren't. Thus we
1701 * need to check only one of them here.
1703 if (ext4_ext_is_uninitialized(ex))
1705 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1706 + ext4_ext_get_actual_len(newext));
1708 ext4_ext_mark_uninitialized(ex);
1709 eh = path[depth].p_hdr;
1714 depth = ext_depth(inode);
1715 eh = path[depth].p_hdr;
1716 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1719 /* probably next leaf has space for us? */
1720 fex = EXT_LAST_EXTENT(eh);
1721 next = EXT_MAX_BLOCKS;
1722 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
1723 next = ext4_ext_next_leaf_block(path);
1724 if (next != EXT_MAX_BLOCKS) {
1725 ext_debug("next leaf block - %u\n", next);
1726 BUG_ON(npath != NULL);
1727 npath = ext4_ext_find_extent(inode, next, NULL);
1729 return PTR_ERR(npath);
1730 BUG_ON(npath->p_depth != path->p_depth);
1731 eh = npath[depth].p_hdr;
1732 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1733 ext_debug("next leaf isn't full(%d)\n",
1734 le16_to_cpu(eh->eh_entries));
1738 ext_debug("next leaf has no free space(%d,%d)\n",
1739 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1743 * There is no free space in the found leaf.
1744 * We're gonna add a new leaf in the tree.
1746 if (flag & EXT4_GET_BLOCKS_PUNCH_OUT_EXT)
1747 flags = EXT4_MB_USE_ROOT_BLOCKS;
1748 err = ext4_ext_create_new_leaf(handle, inode, flags, path, newext);
1751 depth = ext_depth(inode);
1752 eh = path[depth].p_hdr;
1755 nearex = path[depth].p_ext;
1757 err = ext4_ext_get_access(handle, inode, path + depth);
1762 /* there is no extent in this leaf, create first one */
1763 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
1764 le32_to_cpu(newext->ee_block),
1765 ext4_ext_pblock(newext),
1766 ext4_ext_is_uninitialized(newext),
1767 ext4_ext_get_actual_len(newext));
1768 nearex = EXT_FIRST_EXTENT(eh);
1770 if (le32_to_cpu(newext->ee_block)
1771 > le32_to_cpu(nearex->ee_block)) {
1773 ext_debug("insert %u:%llu:[%d]%d before: "
1775 le32_to_cpu(newext->ee_block),
1776 ext4_ext_pblock(newext),
1777 ext4_ext_is_uninitialized(newext),
1778 ext4_ext_get_actual_len(newext),
1783 BUG_ON(newext->ee_block == nearex->ee_block);
1784 ext_debug("insert %u:%llu:[%d]%d after: "
1786 le32_to_cpu(newext->ee_block),
1787 ext4_ext_pblock(newext),
1788 ext4_ext_is_uninitialized(newext),
1789 ext4_ext_get_actual_len(newext),
1792 len = EXT_LAST_EXTENT(eh) - nearex + 1;
1794 ext_debug("insert %u:%llu:[%d]%d: "
1795 "move %d extents from 0x%p to 0x%p\n",
1796 le32_to_cpu(newext->ee_block),
1797 ext4_ext_pblock(newext),
1798 ext4_ext_is_uninitialized(newext),
1799 ext4_ext_get_actual_len(newext),
1800 len, nearex, nearex + 1);
1801 memmove(nearex + 1, nearex,
1802 len * sizeof(struct ext4_extent));
1806 le16_add_cpu(&eh->eh_entries, 1);
1807 path[depth].p_ext = nearex;
1808 nearex->ee_block = newext->ee_block;
1809 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
1810 nearex->ee_len = newext->ee_len;
1813 /* try to merge extents to the right */
1814 if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
1815 ext4_ext_try_to_merge(inode, path, nearex);
1817 /* try to merge extents to the left */
1819 /* time to correct all indexes above */
1820 err = ext4_ext_correct_indexes(handle, inode, path);
1824 err = ext4_ext_dirty(handle, inode, path + depth);
1828 ext4_ext_drop_refs(npath);
1831 ext4_ext_invalidate_cache(inode);
1835 static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1836 ext4_lblk_t num, ext_prepare_callback func,
1839 struct ext4_ext_path *path = NULL;
1840 struct ext4_ext_cache cbex;
1841 struct ext4_extent *ex;
1842 ext4_lblk_t next, start = 0, end = 0;
1843 ext4_lblk_t last = block + num;
1844 int depth, exists, err = 0;
1846 BUG_ON(func == NULL);
1847 BUG_ON(inode == NULL);
1849 while (block < last && block != EXT_MAX_BLOCKS) {
1851 /* find extent for this block */
1852 down_read(&EXT4_I(inode)->i_data_sem);
1853 path = ext4_ext_find_extent(inode, block, path);
1854 up_read(&EXT4_I(inode)->i_data_sem);
1856 err = PTR_ERR(path);
1861 depth = ext_depth(inode);
1862 if (unlikely(path[depth].p_hdr == NULL)) {
1863 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1867 ex = path[depth].p_ext;
1868 next = ext4_ext_next_allocated_block(path);
1872 /* there is no extent yet, so try to allocate
1873 * all requested space */
1876 } else if (le32_to_cpu(ex->ee_block) > block) {
1877 /* need to allocate space before found extent */
1879 end = le32_to_cpu(ex->ee_block);
1880 if (block + num < end)
1882 } else if (block >= le32_to_cpu(ex->ee_block)
1883 + ext4_ext_get_actual_len(ex)) {
1884 /* need to allocate space after found extent */
1889 } else if (block >= le32_to_cpu(ex->ee_block)) {
1891 * some part of requested space is covered
1895 end = le32_to_cpu(ex->ee_block)
1896 + ext4_ext_get_actual_len(ex);
1897 if (block + num < end)
1903 BUG_ON(end <= start);
1906 cbex.ec_block = start;
1907 cbex.ec_len = end - start;
1910 cbex.ec_block = le32_to_cpu(ex->ee_block);
1911 cbex.ec_len = ext4_ext_get_actual_len(ex);
1912 cbex.ec_start = ext4_ext_pblock(ex);
1915 if (unlikely(cbex.ec_len == 0)) {
1916 EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
1920 err = func(inode, next, &cbex, ex, cbdata);
1921 ext4_ext_drop_refs(path);
1926 if (err == EXT_REPEAT)
1928 else if (err == EXT_BREAK) {
1933 if (ext_depth(inode) != depth) {
1934 /* depth was changed. we have to realloc path */
1939 block = cbex.ec_block + cbex.ec_len;
1943 ext4_ext_drop_refs(path);
1951 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1952 __u32 len, ext4_fsblk_t start)
1954 struct ext4_ext_cache *cex;
1956 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1957 trace_ext4_ext_put_in_cache(inode, block, len, start);
1958 cex = &EXT4_I(inode)->i_cached_extent;
1959 cex->ec_block = block;
1961 cex->ec_start = start;
1962 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1966 * ext4_ext_put_gap_in_cache:
1967 * calculate boundaries of the gap that the requested block fits into
1968 * and cache this gap
1971 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1974 int depth = ext_depth(inode);
1977 struct ext4_extent *ex;
1979 ex = path[depth].p_ext;
1981 /* there is no extent yet, so gap is [0;-] */
1983 len = EXT_MAX_BLOCKS;
1984 ext_debug("cache gap(whole file):");
1985 } else if (block < le32_to_cpu(ex->ee_block)) {
1987 len = le32_to_cpu(ex->ee_block) - block;
1988 ext_debug("cache gap(before): %u [%u:%u]",
1990 le32_to_cpu(ex->ee_block),
1991 ext4_ext_get_actual_len(ex));
1992 } else if (block >= le32_to_cpu(ex->ee_block)
1993 + ext4_ext_get_actual_len(ex)) {
1995 lblock = le32_to_cpu(ex->ee_block)
1996 + ext4_ext_get_actual_len(ex);
1998 next = ext4_ext_next_allocated_block(path);
1999 ext_debug("cache gap(after): [%u:%u] %u",
2000 le32_to_cpu(ex->ee_block),
2001 ext4_ext_get_actual_len(ex),
2003 BUG_ON(next == lblock);
2004 len = next - lblock;
2010 ext_debug(" -> %u:%lu\n", lblock, len);
2011 ext4_ext_put_in_cache(inode, lblock, len, 0);
2015 * ext4_ext_check_cache()
2016 * Checks to see if the given block is in the cache.
2017 * If it is, the cached extent is stored in the given
2018 * cache extent pointer. If the cached extent is a hole,
2019 * this routine should be used instead of
2020 * ext4_ext_in_cache if the calling function needs to
2021 * know the size of the hole.
2023 * @inode: The files inode
2024 * @block: The block to look for in the cache
2025 * @ex: Pointer where the cached extent will be stored
2026 * if it contains block
2028 * Return 0 if cache is invalid; 1 if the cache is valid
2030 static int ext4_ext_check_cache(struct inode *inode, ext4_lblk_t block,
2031 struct ext4_ext_cache *ex){
2032 struct ext4_ext_cache *cex;
2033 struct ext4_sb_info *sbi;
2037 * We borrow i_block_reservation_lock to protect i_cached_extent
2039 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
2040 cex = &EXT4_I(inode)->i_cached_extent;
2041 sbi = EXT4_SB(inode->i_sb);
2043 /* has cache valid data? */
2044 if (cex->ec_len == 0)
2047 if (in_range(block, cex->ec_block, cex->ec_len)) {
2048 memcpy(ex, cex, sizeof(struct ext4_ext_cache));
2049 ext_debug("%u cached by %u:%u:%llu\n",
2051 cex->ec_block, cex->ec_len, cex->ec_start);
2055 trace_ext4_ext_in_cache(inode, block, ret);
2056 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2061 * ext4_ext_in_cache()
2062 * Checks to see if the given block is in the cache.
2063 * If it is, the cached extent is stored in the given
2066 * @inode: The files inode
2067 * @block: The block to look for in the cache
2068 * @ex: Pointer where the cached extent will be stored
2069 * if it contains block
2071 * Return 0 if cache is invalid; 1 if the cache is valid
2074 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
2075 struct ext4_extent *ex)
2077 struct ext4_ext_cache cex;
2080 if (ext4_ext_check_cache(inode, block, &cex)) {
2081 ex->ee_block = cpu_to_le32(cex.ec_block);
2082 ext4_ext_store_pblock(ex, cex.ec_start);
2083 ex->ee_len = cpu_to_le16(cex.ec_len);
2093 * removes index from the index block.
2095 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2096 struct ext4_ext_path *path, int depth)
2101 /* free index block */
2103 path = path + depth;
2104 leaf = ext4_idx_pblock(path->p_idx);
2105 if (unlikely(path->p_hdr->eh_entries == 0)) {
2106 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2109 err = ext4_ext_get_access(handle, inode, path);
2113 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2114 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2115 len *= sizeof(struct ext4_extent_idx);
2116 memmove(path->p_idx, path->p_idx + 1, len);
2119 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2120 err = ext4_ext_dirty(handle, inode, path);
2123 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2124 trace_ext4_ext_rm_idx(inode, leaf);
2126 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2127 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2129 while (--depth >= 0) {
2130 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2133 err = ext4_ext_get_access(handle, inode, path);
2136 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2137 err = ext4_ext_dirty(handle, inode, path);
2145 * ext4_ext_calc_credits_for_single_extent:
2146 * This routine returns max. credits that needed to insert an extent
2147 * to the extent tree.
2148 * When pass the actual path, the caller should calculate credits
2151 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2152 struct ext4_ext_path *path)
2155 int depth = ext_depth(inode);
2158 /* probably there is space in leaf? */
2159 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2160 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2163 * There are some space in the leaf tree, no
2164 * need to account for leaf block credit
2166 * bitmaps and block group descriptor blocks
2167 * and other metadata blocks still need to be
2170 /* 1 bitmap, 1 block group descriptor */
2171 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2176 return ext4_chunk_trans_blocks(inode, nrblocks);
2180 * How many index/leaf blocks need to change/allocate to modify nrblocks?
2182 * if nrblocks are fit in a single extent (chunk flag is 1), then
2183 * in the worse case, each tree level index/leaf need to be changed
2184 * if the tree split due to insert a new extent, then the old tree
2185 * index/leaf need to be updated too
2187 * If the nrblocks are discontiguous, they could cause
2188 * the whole tree split more than once, but this is really rare.
2190 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2193 int depth = ext_depth(inode);
2203 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2204 struct ext4_extent *ex,
2205 ext4_fsblk_t *partial_cluster,
2206 ext4_lblk_t from, ext4_lblk_t to)
2208 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2209 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2211 int flags = EXT4_FREE_BLOCKS_FORGET;
2213 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2214 flags |= EXT4_FREE_BLOCKS_METADATA;
2216 * For bigalloc file systems, we never free a partial cluster
2217 * at the beginning of the extent. Instead, we make a note
2218 * that we tried freeing the cluster, and check to see if we
2219 * need to free it on a subsequent call to ext4_remove_blocks,
2220 * or at the end of the ext4_truncate() operation.
2222 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2224 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2226 * If we have a partial cluster, and it's different from the
2227 * cluster of the last block, we need to explicitly free the
2228 * partial cluster here.
2230 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2231 if (*partial_cluster && (EXT4_B2C(sbi, pblk) != *partial_cluster)) {
2232 ext4_free_blocks(handle, inode, NULL,
2233 EXT4_C2B(sbi, *partial_cluster),
2234 sbi->s_cluster_ratio, flags);
2235 *partial_cluster = 0;
2238 #ifdef EXTENTS_STATS
2240 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2241 spin_lock(&sbi->s_ext_stats_lock);
2242 sbi->s_ext_blocks += ee_len;
2243 sbi->s_ext_extents++;
2244 if (ee_len < sbi->s_ext_min)
2245 sbi->s_ext_min = ee_len;
2246 if (ee_len > sbi->s_ext_max)
2247 sbi->s_ext_max = ee_len;
2248 if (ext_depth(inode) > sbi->s_depth_max)
2249 sbi->s_depth_max = ext_depth(inode);
2250 spin_unlock(&sbi->s_ext_stats_lock);
2253 if (from >= le32_to_cpu(ex->ee_block)
2254 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2258 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2259 pblk = ext4_ext_pblock(ex) + ee_len - num;
2260 ext_debug("free last %u blocks starting %llu\n", num, pblk);
2261 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2263 * If the block range to be freed didn't start at the
2264 * beginning of a cluster, and we removed the entire
2265 * extent, save the partial cluster here, since we
2266 * might need to delete if we determine that the
2267 * truncate operation has removed all of the blocks in
2270 if (pblk & (sbi->s_cluster_ratio - 1) &&
2272 *partial_cluster = EXT4_B2C(sbi, pblk);
2274 *partial_cluster = 0;
2275 } else if (from == le32_to_cpu(ex->ee_block)
2276 && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2282 start = ext4_ext_pblock(ex);
2284 ext_debug("free first %u blocks starting %llu\n", num, start);
2285 ext4_free_blocks(handle, inode, NULL, start, num, flags);
2288 printk(KERN_INFO "strange request: removal(2) "
2289 "%u-%u from %u:%u\n",
2290 from, to, le32_to_cpu(ex->ee_block), ee_len);
2297 * ext4_ext_rm_leaf() Removes the extents associated with the
2298 * blocks appearing between "start" and "end", and splits the extents
2299 * if "start" and "end" appear in the same extent
2301 * @handle: The journal handle
2302 * @inode: The files inode
2303 * @path: The path to the leaf
2304 * @start: The first block to remove
2305 * @end: The last block to remove
2308 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2309 struct ext4_ext_path *path, ext4_fsblk_t *partial_cluster,
2310 ext4_lblk_t start, ext4_lblk_t end)
2312 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2313 int err = 0, correct_index = 0;
2314 int depth = ext_depth(inode), credits;
2315 struct ext4_extent_header *eh;
2318 ext4_lblk_t ex_ee_block;
2319 unsigned short ex_ee_len;
2320 unsigned uninitialized = 0;
2321 struct ext4_extent *ex;
2323 /* the header must be checked already in ext4_ext_remove_space() */
2324 ext_debug("truncate since %u in leaf\n", start);
2325 if (!path[depth].p_hdr)
2326 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2327 eh = path[depth].p_hdr;
2328 if (unlikely(path[depth].p_hdr == NULL)) {
2329 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2332 /* find where to start removing */
2333 ex = EXT_LAST_EXTENT(eh);
2335 ex_ee_block = le32_to_cpu(ex->ee_block);
2336 ex_ee_len = ext4_ext_get_actual_len(ex);
2338 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2340 while (ex >= EXT_FIRST_EXTENT(eh) &&
2341 ex_ee_block + ex_ee_len > start) {
2343 if (ext4_ext_is_uninitialized(ex))
2348 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2349 uninitialized, ex_ee_len);
2350 path[depth].p_ext = ex;
2352 a = ex_ee_block > start ? ex_ee_block : start;
2353 b = ex_ee_block+ex_ee_len - 1 < end ?
2354 ex_ee_block+ex_ee_len - 1 : end;
2356 ext_debug(" border %u:%u\n", a, b);
2358 /* If this extent is beyond the end of the hole, skip it */
2359 if (end <= ex_ee_block) {
2361 ex_ee_block = le32_to_cpu(ex->ee_block);
2362 ex_ee_len = ext4_ext_get_actual_len(ex);
2364 } else if (b != ex_ee_block + ex_ee_len - 1) {
2365 EXT4_ERROR_INODE(inode," bad truncate %u:%u\n",
2369 } else if (a != ex_ee_block) {
2370 /* remove tail of the extent */
2371 num = a - ex_ee_block;
2373 /* remove whole extent: excellent! */
2377 * 3 for leaf, sb, and inode plus 2 (bmap and group
2378 * descriptor) for each block group; assume two block
2379 * groups plus ex_ee_len/blocks_per_block_group for
2382 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2383 if (ex == EXT_FIRST_EXTENT(eh)) {
2385 credits += (ext_depth(inode)) + 1;
2387 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2389 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2393 err = ext4_ext_get_access(handle, inode, path + depth);
2397 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2403 /* this extent is removed; mark slot entirely unused */
2404 ext4_ext_store_pblock(ex, 0);
2406 ex->ee_len = cpu_to_le16(num);
2408 * Do not mark uninitialized if all the blocks in the
2409 * extent have been removed.
2411 if (uninitialized && num)
2412 ext4_ext_mark_uninitialized(ex);
2414 * If the extent was completely released,
2415 * we need to remove it from the leaf
2418 if (end != EXT_MAX_BLOCKS - 1) {
2420 * For hole punching, we need to scoot all the
2421 * extents up when an extent is removed so that
2422 * we dont have blank extents in the middle
2424 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2425 sizeof(struct ext4_extent));
2427 /* Now get rid of the one at the end */
2428 memset(EXT_LAST_EXTENT(eh), 0,
2429 sizeof(struct ext4_extent));
2431 le16_add_cpu(&eh->eh_entries, -1);
2433 *partial_cluster = 0;
2435 err = ext4_ext_dirty(handle, inode, path + depth);
2439 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2440 ext4_ext_pblock(ex));
2442 ex_ee_block = le32_to_cpu(ex->ee_block);
2443 ex_ee_len = ext4_ext_get_actual_len(ex);
2446 if (correct_index && eh->eh_entries)
2447 err = ext4_ext_correct_indexes(handle, inode, path);
2450 * If there is still a entry in the leaf node, check to see if
2451 * it references the partial cluster. This is the only place
2452 * where it could; if it doesn't, we can free the cluster.
2454 if (*partial_cluster && ex >= EXT_FIRST_EXTENT(eh) &&
2455 (EXT4_B2C(sbi, ext4_ext_pblock(ex) + ex_ee_len - 1) !=
2456 *partial_cluster)) {
2457 int flags = EXT4_FREE_BLOCKS_FORGET;
2459 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2460 flags |= EXT4_FREE_BLOCKS_METADATA;
2462 ext4_free_blocks(handle, inode, NULL,
2463 EXT4_C2B(sbi, *partial_cluster),
2464 sbi->s_cluster_ratio, flags);
2465 *partial_cluster = 0;
2468 /* if this leaf is free, then we should
2469 * remove it from index block above */
2470 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2471 err = ext4_ext_rm_idx(handle, inode, path, depth);
2478 * ext4_ext_more_to_rm:
2479 * returns 1 if current index has to be freed (even partial)
2482 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2484 BUG_ON(path->p_idx == NULL);
2486 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2490 * if truncate on deeper level happened, it wasn't partial,
2491 * so we have to consider current index for truncation
2493 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2498 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2500 struct super_block *sb = inode->i_sb;
2501 int depth = ext_depth(inode);
2502 struct ext4_ext_path *path;
2503 ext4_fsblk_t partial_cluster = 0;
2507 ext_debug("truncate since %u\n", start);
2509 /* probably first extent we're gonna free will be last in block */
2510 handle = ext4_journal_start(inode, depth + 1);
2512 return PTR_ERR(handle);
2515 ext4_ext_invalidate_cache(inode);
2517 trace_ext4_ext_remove_space(inode, start, depth);
2520 * We start scanning from right side, freeing all the blocks
2521 * after i_size and walking into the tree depth-wise.
2523 depth = ext_depth(inode);
2524 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2526 ext4_journal_stop(handle);
2529 path[0].p_depth = depth;
2530 path[0].p_hdr = ext_inode_hdr(inode);
2531 if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2537 while (i >= 0 && err == 0) {
2539 /* this is leaf block */
2540 err = ext4_ext_rm_leaf(handle, inode, path,
2541 &partial_cluster, start,
2542 EXT_MAX_BLOCKS - 1);
2543 /* root level has p_bh == NULL, brelse() eats this */
2544 brelse(path[i].p_bh);
2545 path[i].p_bh = NULL;
2550 /* this is index block */
2551 if (!path[i].p_hdr) {
2552 ext_debug("initialize header\n");
2553 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2556 if (!path[i].p_idx) {
2557 /* this level hasn't been touched yet */
2558 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2559 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2560 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2562 le16_to_cpu(path[i].p_hdr->eh_entries));
2564 /* we were already here, see at next index */
2568 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2569 i, EXT_FIRST_INDEX(path[i].p_hdr),
2571 if (ext4_ext_more_to_rm(path + i)) {
2572 struct buffer_head *bh;
2573 /* go to the next level */
2574 ext_debug("move to level %d (block %llu)\n",
2575 i + 1, ext4_idx_pblock(path[i].p_idx));
2576 memset(path + i + 1, 0, sizeof(*path));
2577 bh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));
2579 /* should we reset i_size? */
2583 if (WARN_ON(i + 1 > depth)) {
2587 if (ext4_ext_check(inode, ext_block_hdr(bh),
2592 path[i + 1].p_bh = bh;
2594 /* save actual number of indexes since this
2595 * number is changed at the next iteration */
2596 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2599 /* we finished processing this index, go up */
2600 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2601 /* index is empty, remove it;
2602 * handle must be already prepared by the
2603 * truncatei_leaf() */
2604 err = ext4_ext_rm_idx(handle, inode, path, i);
2606 /* root level has p_bh == NULL, brelse() eats this */
2607 brelse(path[i].p_bh);
2608 path[i].p_bh = NULL;
2610 ext_debug("return to level %d\n", i);
2614 trace_ext4_ext_remove_space_done(inode, start, depth, partial_cluster,
2615 path->p_hdr->eh_entries);
2617 /* If we still have something in the partial cluster and we have removed
2618 * even the first extent, then we should free the blocks in the partial
2619 * cluster as well. */
2620 if (partial_cluster && path->p_hdr->eh_entries == 0) {
2621 int flags = EXT4_FREE_BLOCKS_FORGET;
2623 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2624 flags |= EXT4_FREE_BLOCKS_METADATA;
2626 ext4_free_blocks(handle, inode, NULL,
2627 EXT4_C2B(EXT4_SB(sb), partial_cluster),
2628 EXT4_SB(sb)->s_cluster_ratio, flags);
2629 partial_cluster = 0;
2632 /* TODO: flexible tree reduction should be here */
2633 if (path->p_hdr->eh_entries == 0) {
2635 * truncate to zero freed all the tree,
2636 * so we need to correct eh_depth
2638 err = ext4_ext_get_access(handle, inode, path);
2640 ext_inode_hdr(inode)->eh_depth = 0;
2641 ext_inode_hdr(inode)->eh_max =
2642 cpu_to_le16(ext4_ext_space_root(inode, 0));
2643 err = ext4_ext_dirty(handle, inode, path);
2647 ext4_ext_drop_refs(path);
2651 ext4_journal_stop(handle);
2657 * called at mount time
2659 void ext4_ext_init(struct super_block *sb)
2662 * possible initialization would be here
2665 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2666 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
2667 printk(KERN_INFO "EXT4-fs: file extents enabled");
2668 #ifdef AGGRESSIVE_TEST
2669 printk(", aggressive tests");
2671 #ifdef CHECK_BINSEARCH
2672 printk(", check binsearch");
2674 #ifdef EXTENTS_STATS
2679 #ifdef EXTENTS_STATS
2680 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2681 EXT4_SB(sb)->s_ext_min = 1 << 30;
2682 EXT4_SB(sb)->s_ext_max = 0;
2688 * called at umount time
2690 void ext4_ext_release(struct super_block *sb)
2692 if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2695 #ifdef EXTENTS_STATS
2696 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2697 struct ext4_sb_info *sbi = EXT4_SB(sb);
2698 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2699 sbi->s_ext_blocks, sbi->s_ext_extents,
2700 sbi->s_ext_blocks / sbi->s_ext_extents);
2701 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2702 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2707 /* FIXME!! we need to try to merge to left or right after zero-out */
2708 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2710 ext4_fsblk_t ee_pblock;
2711 unsigned int ee_len;
2714 ee_len = ext4_ext_get_actual_len(ex);
2715 ee_pblock = ext4_ext_pblock(ex);
2717 ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
2725 * used by extent splitting.
2727 #define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
2729 #define EXT4_EXT_MARK_UNINIT1 0x2 /* mark first half uninitialized */
2730 #define EXT4_EXT_MARK_UNINIT2 0x4 /* mark second half uninitialized */
2732 #define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
2733 #define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
2736 * ext4_split_extent_at() splits an extent at given block.
2738 * @handle: the journal handle
2739 * @inode: the file inode
2740 * @path: the path to the extent
2741 * @split: the logical block where the extent is splitted.
2742 * @split_flags: indicates if the extent could be zeroout if split fails, and
2743 * the states(init or uninit) of new extents.
2744 * @flags: flags used to insert new extent to extent tree.
2747 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
2748 * of which are deterimined by split_flag.
2750 * There are two cases:
2751 * a> the extent are splitted into two extent.
2752 * b> split is not needed, and just mark the extent.
2754 * return 0 on success.
2756 static int ext4_split_extent_at(handle_t *handle,
2757 struct inode *inode,
2758 struct ext4_ext_path *path,
2763 ext4_fsblk_t newblock;
2764 ext4_lblk_t ee_block;
2765 struct ext4_extent *ex, newex, orig_ex;
2766 struct ext4_extent *ex2 = NULL;
2767 unsigned int ee_len, depth;
2770 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
2771 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
2773 ext_debug("ext4_split_extents_at: inode %lu, logical"
2774 "block %llu\n", inode->i_ino, (unsigned long long)split);
2776 ext4_ext_show_leaf(inode, path);
2778 depth = ext_depth(inode);
2779 ex = path[depth].p_ext;
2780 ee_block = le32_to_cpu(ex->ee_block);
2781 ee_len = ext4_ext_get_actual_len(ex);
2782 newblock = split - ee_block + ext4_ext_pblock(ex);
2784 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
2786 err = ext4_ext_get_access(handle, inode, path + depth);
2790 if (split == ee_block) {
2792 * case b: block @split is the block that the extent begins with
2793 * then we just change the state of the extent, and splitting
2796 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2797 ext4_ext_mark_uninitialized(ex);
2799 ext4_ext_mark_initialized(ex);
2801 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
2802 ext4_ext_try_to_merge(inode, path, ex);
2804 err = ext4_ext_dirty(handle, inode, path + depth);
2809 memcpy(&orig_ex, ex, sizeof(orig_ex));
2810 ex->ee_len = cpu_to_le16(split - ee_block);
2811 if (split_flag & EXT4_EXT_MARK_UNINIT1)
2812 ext4_ext_mark_uninitialized(ex);
2815 * path may lead to new leaf, not to original leaf any more
2816 * after ext4_ext_insert_extent() returns,
2818 err = ext4_ext_dirty(handle, inode, path + depth);
2820 goto fix_extent_len;
2823 ex2->ee_block = cpu_to_le32(split);
2824 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
2825 ext4_ext_store_pblock(ex2, newblock);
2826 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2827 ext4_ext_mark_uninitialized(ex2);
2829 err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
2830 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
2831 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
2832 if (split_flag & EXT4_EXT_DATA_VALID1)
2833 err = ext4_ext_zeroout(inode, ex2);
2835 err = ext4_ext_zeroout(inode, ex);
2837 err = ext4_ext_zeroout(inode, &orig_ex);
2840 goto fix_extent_len;
2841 /* update the extent length and mark as initialized */
2842 ex->ee_len = cpu_to_le16(ee_len);
2843 ext4_ext_try_to_merge(inode, path, ex);
2844 err = ext4_ext_dirty(handle, inode, path + depth);
2847 goto fix_extent_len;
2850 ext4_ext_show_leaf(inode, path);
2854 ex->ee_len = orig_ex.ee_len;
2855 ext4_ext_dirty(handle, inode, path + depth);
2860 * ext4_split_extents() splits an extent and mark extent which is covered
2861 * by @map as split_flags indicates
2863 * It may result in splitting the extent into multiple extents (upto three)
2864 * There are three possibilities:
2865 * a> There is no split required
2866 * b> Splits in two extents: Split is happening at either end of the extent
2867 * c> Splits in three extents: Somone is splitting in middle of the extent
2870 static int ext4_split_extent(handle_t *handle,
2871 struct inode *inode,
2872 struct ext4_ext_path *path,
2873 struct ext4_map_blocks *map,
2877 ext4_lblk_t ee_block;
2878 struct ext4_extent *ex;
2879 unsigned int ee_len, depth;
2882 int split_flag1, flags1;
2884 depth = ext_depth(inode);
2885 ex = path[depth].p_ext;
2886 ee_block = le32_to_cpu(ex->ee_block);
2887 ee_len = ext4_ext_get_actual_len(ex);
2888 uninitialized = ext4_ext_is_uninitialized(ex);
2890 if (map->m_lblk + map->m_len < ee_block + ee_len) {
2891 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
2892 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
2894 split_flag1 |= EXT4_EXT_MARK_UNINIT1 |
2895 EXT4_EXT_MARK_UNINIT2;
2896 if (split_flag & EXT4_EXT_DATA_VALID2)
2897 split_flag1 |= EXT4_EXT_DATA_VALID1;
2898 err = ext4_split_extent_at(handle, inode, path,
2899 map->m_lblk + map->m_len, split_flag1, flags1);
2904 ext4_ext_drop_refs(path);
2905 path = ext4_ext_find_extent(inode, map->m_lblk, path);
2907 return PTR_ERR(path);
2909 if (map->m_lblk >= ee_block) {
2910 split_flag1 = split_flag & (EXT4_EXT_MAY_ZEROOUT |
2911 EXT4_EXT_DATA_VALID2);
2913 split_flag1 |= EXT4_EXT_MARK_UNINIT1;
2914 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2915 split_flag1 |= EXT4_EXT_MARK_UNINIT2;
2916 err = ext4_split_extent_at(handle, inode, path,
2917 map->m_lblk, split_flag1, flags);
2922 ext4_ext_show_leaf(inode, path);
2924 return err ? err : map->m_len;
2927 #define EXT4_EXT_ZERO_LEN 7
2929 * This function is called by ext4_ext_map_blocks() if someone tries to write
2930 * to an uninitialized extent. It may result in splitting the uninitialized
2931 * extent into multiple extents (up to three - one initialized and two
2933 * There are three possibilities:
2934 * a> There is no split required: Entire extent should be initialized
2935 * b> Splits in two extents: Write is happening at either end of the extent
2936 * c> Splits in three extents: Somone is writing in middle of the extent
2939 * - The extent pointed to by 'path' is uninitialized.
2940 * - The extent pointed to by 'path' contains a superset
2941 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
2943 * Post-conditions on success:
2944 * - the returned value is the number of blocks beyond map->l_lblk
2945 * that are allocated and initialized.
2946 * It is guaranteed to be >= map->m_len.
2948 static int ext4_ext_convert_to_initialized(handle_t *handle,
2949 struct inode *inode,
2950 struct ext4_map_blocks *map,
2951 struct ext4_ext_path *path)
2953 struct ext4_extent_header *eh;
2954 struct ext4_map_blocks split_map;
2955 struct ext4_extent zero_ex;
2956 struct ext4_extent *ex;
2957 ext4_lblk_t ee_block, eof_block;
2958 unsigned int ee_len, depth;
2963 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
2964 "block %llu, max_blocks %u\n", inode->i_ino,
2965 (unsigned long long)map->m_lblk, map->m_len);
2967 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2968 inode->i_sb->s_blocksize_bits;
2969 if (eof_block < map->m_lblk + map->m_len)
2970 eof_block = map->m_lblk + map->m_len;
2972 depth = ext_depth(inode);
2973 eh = path[depth].p_hdr;
2974 ex = path[depth].p_ext;
2975 ee_block = le32_to_cpu(ex->ee_block);
2976 ee_len = ext4_ext_get_actual_len(ex);
2977 allocated = ee_len - (map->m_lblk - ee_block);
2979 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
2981 /* Pre-conditions */
2982 BUG_ON(!ext4_ext_is_uninitialized(ex));
2983 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
2986 * Attempt to transfer newly initialized blocks from the currently
2987 * uninitialized extent to its left neighbor. This is much cheaper
2988 * than an insertion followed by a merge as those involve costly
2989 * memmove() calls. This is the common case in steady state for
2990 * workloads doing fallocate(FALLOC_FL_KEEP_SIZE) followed by append
2993 * Limitations of the current logic:
2994 * - L1: we only deal with writes at the start of the extent.
2995 * The approach could be extended to writes at the end
2996 * of the extent but this scenario was deemed less common.
2997 * - L2: we do not deal with writes covering the whole extent.
2998 * This would require removing the extent if the transfer
3000 * - L3: we only attempt to merge with an extent stored in the
3001 * same extent tree node.
3003 if ((map->m_lblk == ee_block) && /*L1*/
3004 (map->m_len < ee_len) && /*L2*/
3005 (ex > EXT_FIRST_EXTENT(eh))) { /*L3*/
3006 struct ext4_extent *prev_ex;
3007 ext4_lblk_t prev_lblk;
3008 ext4_fsblk_t prev_pblk, ee_pblk;
3009 unsigned int prev_len, write_len;
3012 prev_lblk = le32_to_cpu(prev_ex->ee_block);
3013 prev_len = ext4_ext_get_actual_len(prev_ex);
3014 prev_pblk = ext4_ext_pblock(prev_ex);
3015 ee_pblk = ext4_ext_pblock(ex);
3016 write_len = map->m_len;
3019 * A transfer of blocks from 'ex' to 'prev_ex' is allowed
3020 * upon those conditions:
3021 * - C1: prev_ex is initialized,
3022 * - C2: prev_ex is logically abutting ex,
3023 * - C3: prev_ex is physically abutting ex,
3024 * - C4: prev_ex can receive the additional blocks without
3025 * overflowing the (initialized) length limit.
3027 if ((!ext4_ext_is_uninitialized(prev_ex)) && /*C1*/
3028 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3029 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3030 (prev_len < (EXT_INIT_MAX_LEN - write_len))) { /*C4*/
3031 err = ext4_ext_get_access(handle, inode, path + depth);
3035 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3038 /* Shift the start of ex by 'write_len' blocks */
3039 ex->ee_block = cpu_to_le32(ee_block + write_len);
3040 ext4_ext_store_pblock(ex, ee_pblk + write_len);
3041 ex->ee_len = cpu_to_le16(ee_len - write_len);
3042 ext4_ext_mark_uninitialized(ex); /* Restore the flag */
3044 /* Extend prev_ex by 'write_len' blocks */
3045 prev_ex->ee_len = cpu_to_le16(prev_len + write_len);
3047 /* Mark the block containing both extents as dirty */
3048 ext4_ext_dirty(handle, inode, path + depth);
3050 /* Update path to point to the right extent */
3051 path[depth].p_ext = prev_ex;
3053 /* Result: number of initialized blocks past m_lblk */
3054 allocated = write_len;
3059 WARN_ON(map->m_lblk < ee_block);
3061 * It is safe to convert extent to initialized via explicit
3062 * zeroout only if extent is fully insde i_size or new_size.
3064 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3066 /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
3067 if (ee_len <= 2*EXT4_EXT_ZERO_LEN &&
3068 (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3069 err = ext4_ext_zeroout(inode, ex);
3073 err = ext4_ext_get_access(handle, inode, path + depth);
3076 ext4_ext_mark_initialized(ex);
3077 ext4_ext_try_to_merge(inode, path, ex);
3078 err = ext4_ext_dirty(handle, inode, path + depth);
3084 * 1. split the extent into three extents.
3085 * 2. split the extent into two extents, zeroout the first half.
3086 * 3. split the extent into two extents, zeroout the second half.
3087 * 4. split the extent into two extents with out zeroout.
3089 split_map.m_lblk = map->m_lblk;
3090 split_map.m_len = map->m_len;
3092 if (allocated > map->m_len) {
3093 if (allocated <= EXT4_EXT_ZERO_LEN &&
3094 (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3097 cpu_to_le32(map->m_lblk);
3098 zero_ex.ee_len = cpu_to_le16(allocated);
3099 ext4_ext_store_pblock(&zero_ex,
3100 ext4_ext_pblock(ex) + map->m_lblk - ee_block);
3101 err = ext4_ext_zeroout(inode, &zero_ex);
3104 split_map.m_lblk = map->m_lblk;
3105 split_map.m_len = allocated;
3106 } else if ((map->m_lblk - ee_block + map->m_len <
3107 EXT4_EXT_ZERO_LEN) &&
3108 (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3110 if (map->m_lblk != ee_block) {
3111 zero_ex.ee_block = ex->ee_block;
3112 zero_ex.ee_len = cpu_to_le16(map->m_lblk -
3114 ext4_ext_store_pblock(&zero_ex,
3115 ext4_ext_pblock(ex));
3116 err = ext4_ext_zeroout(inode, &zero_ex);
3121 split_map.m_lblk = ee_block;
3122 split_map.m_len = map->m_lblk - ee_block + map->m_len;
3123 allocated = map->m_len;
3127 allocated = ext4_split_extent(handle, inode, path,
3128 &split_map, split_flag, 0);
3133 return err ? err : allocated;
3137 * This function is called by ext4_ext_map_blocks() from
3138 * ext4_get_blocks_dio_write() when DIO to write
3139 * to an uninitialized extent.
3141 * Writing to an uninitialized extent may result in splitting the uninitialized
3142 * extent into multiple /initialized uninitialized extents (up to three)
3143 * There are three possibilities:
3144 * a> There is no split required: Entire extent should be uninitialized
3145 * b> Splits in two extents: Write is happening at either end of the extent
3146 * c> Splits in three extents: Somone is writing in middle of the extent
3148 * One of more index blocks maybe needed if the extent tree grow after
3149 * the uninitialized extent split. To prevent ENOSPC occur at the IO
3150 * complete, we need to split the uninitialized extent before DIO submit
3151 * the IO. The uninitialized extent called at this time will be split
3152 * into three uninitialized extent(at most). After IO complete, the part
3153 * being filled will be convert to initialized by the end_io callback function
3154 * via ext4_convert_unwritten_extents().
3156 * Returns the size of uninitialized extent to be written on success.
3158 static int ext4_split_unwritten_extents(handle_t *handle,
3159 struct inode *inode,
3160 struct ext4_map_blocks *map,
3161 struct ext4_ext_path *path,
3164 ext4_lblk_t eof_block;
3165 ext4_lblk_t ee_block;
3166 struct ext4_extent *ex;
3167 unsigned int ee_len;
3168 int split_flag = 0, depth;
3170 ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
3171 "block %llu, max_blocks %u\n", inode->i_ino,
3172 (unsigned long long)map->m_lblk, map->m_len);
3174 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3175 inode->i_sb->s_blocksize_bits;
3176 if (eof_block < map->m_lblk + map->m_len)
3177 eof_block = map->m_lblk + map->m_len;
3179 * It is safe to convert extent to initialized via explicit
3180 * zeroout only if extent is fully insde i_size or new_size.
3182 depth = ext_depth(inode);
3183 ex = path[depth].p_ext;
3184 ee_block = le32_to_cpu(ex->ee_block);
3185 ee_len = ext4_ext_get_actual_len(ex);
3187 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3188 split_flag |= EXT4_EXT_MARK_UNINIT2;
3189 if (flags & EXT4_GET_BLOCKS_CONVERT)
3190 split_flag |= EXT4_EXT_DATA_VALID2;
3191 flags |= EXT4_GET_BLOCKS_PRE_IO;
3192 return ext4_split_extent(handle, inode, path, map, split_flag, flags);
3195 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3196 struct inode *inode,
3197 struct ext4_map_blocks *map,
3198 struct ext4_ext_path *path)
3200 struct ext4_extent *ex;
3201 ext4_lblk_t ee_block;
3202 unsigned int ee_len;
3206 depth = ext_depth(inode);
3207 ex = path[depth].p_ext;
3208 ee_block = le32_to_cpu(ex->ee_block);
3209 ee_len = ext4_ext_get_actual_len(ex);
3211 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3212 "block %llu, max_blocks %u\n", inode->i_ino,
3213 (unsigned long long)ee_block, ee_len);
3215 /* If extent is larger than requested then split is required */
3216 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3217 err = ext4_split_unwritten_extents(handle, inode, map, path,
3218 EXT4_GET_BLOCKS_CONVERT);
3221 ext4_ext_drop_refs(path);
3222 path = ext4_ext_find_extent(inode, map->m_lblk, path);
3224 err = PTR_ERR(path);
3227 depth = ext_depth(inode);
3228 ex = path[depth].p_ext;
3231 err = ext4_ext_get_access(handle, inode, path + depth);
3234 /* first mark the extent as initialized */
3235 ext4_ext_mark_initialized(ex);
3237 /* note: ext4_ext_correct_indexes() isn't needed here because
3238 * borders are not changed
3240 ext4_ext_try_to_merge(inode, path, ex);
3242 /* Mark modified extent as dirty */
3243 err = ext4_ext_dirty(handle, inode, path + depth);
3245 ext4_ext_show_leaf(inode, path);
3249 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3250 sector_t block, int count)
3253 for (i = 0; i < count; i++)
3254 unmap_underlying_metadata(bdev, block + i);
3258 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3260 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3262 struct ext4_ext_path *path,
3266 struct ext4_extent_header *eh;
3267 struct ext4_extent *last_ex;
3269 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3272 depth = ext_depth(inode);
3273 eh = path[depth].p_hdr;
3275 if (unlikely(!eh->eh_entries)) {
3276 EXT4_ERROR_INODE(inode, "eh->eh_entries == 0 and "
3277 "EOFBLOCKS_FL set");
3280 last_ex = EXT_LAST_EXTENT(eh);
3282 * We should clear the EOFBLOCKS_FL flag if we are writing the
3283 * last block in the last extent in the file. We test this by
3284 * first checking to see if the caller to
3285 * ext4_ext_get_blocks() was interested in the last block (or
3286 * a block beyond the last block) in the current extent. If
3287 * this turns out to be false, we can bail out from this
3288 * function immediately.
3290 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3291 ext4_ext_get_actual_len(last_ex))
3294 * If the caller does appear to be planning to write at or
3295 * beyond the end of the current extent, we then test to see
3296 * if the current extent is the last extent in the file, by
3297 * checking to make sure it was reached via the rightmost node
3298 * at each level of the tree.
3300 for (i = depth-1; i >= 0; i--)
3301 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3303 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3304 return ext4_mark_inode_dirty(handle, inode);
3308 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3310 * Goes through the buffer heads in the range [lblk_start, lblk_end] and returns
3311 * whether there are any buffers marked for delayed allocation. It returns '1'
3312 * on the first delalloc'ed buffer head found. If no buffer head in the given
3313 * range is marked for delalloc, it returns 0.
3314 * lblk_start should always be <= lblk_end.
3315 * search_hint_reverse is to indicate that searching in reverse from lblk_end to
3316 * lblk_start might be more efficient (i.e., we will likely hit the delalloc'ed
3317 * block sooner). This is useful when blocks are truncated sequentially from
3318 * lblk_start towards lblk_end.
3320 static int ext4_find_delalloc_range(struct inode *inode,
3321 ext4_lblk_t lblk_start,
3322 ext4_lblk_t lblk_end,
3323 int search_hint_reverse)
3325 struct address_space *mapping = inode->i_mapping;
3326 struct buffer_head *head, *bh = NULL;
3328 ext4_lblk_t i, pg_lblk;
3331 /* reverse search wont work if fs block size is less than page size */
3332 if (inode->i_blkbits < PAGE_CACHE_SHIFT)
3333 search_hint_reverse = 0;
3335 if (search_hint_reverse)
3340 index = i >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
3342 while ((i >= lblk_start) && (i <= lblk_end)) {
3343 page = find_get_page(mapping, index);
3347 if (!page_has_buffers(page))
3350 head = page_buffers(page);
3355 pg_lblk = index << (PAGE_CACHE_SHIFT -
3358 if (unlikely(pg_lblk < lblk_start)) {
3360 * This is possible when fs block size is less
3361 * than page size and our cluster starts/ends in
3362 * middle of the page. So we need to skip the
3363 * initial few blocks till we reach the 'lblk'
3369 /* Check if the buffer is delayed allocated and that it
3370 * is not yet mapped. (when da-buffers are mapped during
3371 * their writeout, their da_mapped bit is set.)
3373 if (buffer_delay(bh) && !buffer_da_mapped(bh)) {
3374 page_cache_release(page);
3375 trace_ext4_find_delalloc_range(inode,
3376 lblk_start, lblk_end,
3377 search_hint_reverse,
3381 if (search_hint_reverse)
3385 } while ((i >= lblk_start) && (i <= lblk_end) &&
3386 ((bh = bh->b_this_page) != head));
3389 page_cache_release(page);
3391 * Move to next page. 'i' will be the first lblk in the next
3394 if (search_hint_reverse)
3398 i = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
3401 trace_ext4_find_delalloc_range(inode, lblk_start, lblk_end,
3402 search_hint_reverse, 0, 0);
3406 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk,
3407 int search_hint_reverse)
3409 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3410 ext4_lblk_t lblk_start, lblk_end;
3411 lblk_start = lblk & (~(sbi->s_cluster_ratio - 1));
3412 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3414 return ext4_find_delalloc_range(inode, lblk_start, lblk_end,
3415 search_hint_reverse);
3419 * Determines how many complete clusters (out of those specified by the 'map')
3420 * are under delalloc and were reserved quota for.
3421 * This function is called when we are writing out the blocks that were
3422 * originally written with their allocation delayed, but then the space was
3423 * allocated using fallocate() before the delayed allocation could be resolved.
3424 * The cases to look for are:
3425 * ('=' indicated delayed allocated blocks
3426 * '-' indicates non-delayed allocated blocks)
3427 * (a) partial clusters towards beginning and/or end outside of allocated range
3428 * are not delalloc'ed.
3430 * |----c---=|====c====|====c====|===-c----|
3431 * |++++++ allocated ++++++|
3432 * ==> 4 complete clusters in above example
3434 * (b) partial cluster (outside of allocated range) towards either end is
3435 * marked for delayed allocation. In this case, we will exclude that
3438 * |----====c========|========c========|
3439 * |++++++ allocated ++++++|
3440 * ==> 1 complete clusters in above example
3443 * |================c================|
3444 * |++++++ allocated ++++++|
3445 * ==> 0 complete clusters in above example
3447 * The ext4_da_update_reserve_space will be called only if we
3448 * determine here that there were some "entire" clusters that span
3449 * this 'allocated' range.
3450 * In the non-bigalloc case, this function will just end up returning num_blks
3451 * without ever calling ext4_find_delalloc_range.
3454 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3455 unsigned int num_blks)
3457 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3458 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3459 ext4_lblk_t lblk_from, lblk_to, c_offset;
3460 unsigned int allocated_clusters = 0;
3462 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3463 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3465 /* max possible clusters for this allocation */
3466 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3468 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3470 /* Check towards left side */
3471 c_offset = lblk_start & (sbi->s_cluster_ratio - 1);
3473 lblk_from = lblk_start & (~(sbi->s_cluster_ratio - 1));
3474 lblk_to = lblk_from + c_offset - 1;
3476 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))
3477 allocated_clusters--;
3480 /* Now check towards right. */
3481 c_offset = (lblk_start + num_blks) & (sbi->s_cluster_ratio - 1);
3482 if (allocated_clusters && c_offset) {
3483 lblk_from = lblk_start + num_blks;
3484 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3486 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))
3487 allocated_clusters--;
3490 return allocated_clusters;
3494 ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
3495 struct ext4_map_blocks *map,
3496 struct ext4_ext_path *path, int flags,
3497 unsigned int allocated, ext4_fsblk_t newblock)
3501 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3503 ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
3504 "block %llu, max_blocks %u, flags %d, allocated %u",
3505 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
3507 ext4_ext_show_leaf(inode, path);
3509 trace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,
3512 /* get_block() before submit the IO, split the extent */
3513 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3514 ret = ext4_split_unwritten_extents(handle, inode, map,
3517 * Flag the inode(non aio case) or end_io struct (aio case)
3518 * that this IO needs to conversion to written when IO is
3522 ext4_set_io_unwritten_flag(inode, io);
3524 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3525 if (ext4_should_dioread_nolock(inode))
3526 map->m_flags |= EXT4_MAP_UNINIT;
3529 /* IO end_io complete, convert the filled extent to written */
3530 if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
3531 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
3534 ext4_update_inode_fsync_trans(handle, inode, 1);
3535 err = check_eofblocks_fl(handle, inode, map->m_lblk,
3541 /* buffered IO case */
3543 * repeat fallocate creation request
3544 * we already have an unwritten extent
3546 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
3549 /* buffered READ or buffered write_begin() lookup */
3550 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3552 * We have blocks reserved already. We
3553 * return allocated blocks so that delalloc
3554 * won't do block reservation for us. But
3555 * the buffer head will be unmapped so that
3556 * a read from the block returns 0s.
3558 map->m_flags |= EXT4_MAP_UNWRITTEN;
3562 /* buffered write, writepage time, convert*/
3563 ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
3565 ext4_update_inode_fsync_trans(handle, inode, 1);
3572 map->m_flags |= EXT4_MAP_NEW;
3574 * if we allocated more blocks than requested
3575 * we need to make sure we unmap the extra block
3576 * allocated. The actual needed block will get
3577 * unmapped later when we find the buffer_head marked
3580 if (allocated > map->m_len) {
3581 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
3582 newblock + map->m_len,
3583 allocated - map->m_len);
3584 allocated = map->m_len;
3588 * If we have done fallocate with the offset that is already
3589 * delayed allocated, we would have block reservation
3590 * and quota reservation done in the delayed write path.
3591 * But fallocate would have already updated quota and block
3592 * count for this offset. So cancel these reservation
3594 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
3595 unsigned int reserved_clusters;
3596 reserved_clusters = get_reserved_cluster_alloc(inode,
3597 map->m_lblk, map->m_len);
3598 if (reserved_clusters)
3599 ext4_da_update_reserve_space(inode,
3605 map->m_flags |= EXT4_MAP_MAPPED;
3606 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
3607 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
3613 if (allocated > map->m_len)
3614 allocated = map->m_len;
3615 ext4_ext_show_leaf(inode, path);
3616 map->m_pblk = newblock;
3617 map->m_len = allocated;
3620 ext4_ext_drop_refs(path);
3623 return err ? err : allocated;
3627 * get_implied_cluster_alloc - check to see if the requested
3628 * allocation (in the map structure) overlaps with a cluster already
3629 * allocated in an extent.
3630 * @sb The filesystem superblock structure
3631 * @map The requested lblk->pblk mapping
3632 * @ex The extent structure which might contain an implied
3633 * cluster allocation
3635 * This function is called by ext4_ext_map_blocks() after we failed to
3636 * find blocks that were already in the inode's extent tree. Hence,
3637 * we know that the beginning of the requested region cannot overlap
3638 * the extent from the inode's extent tree. There are three cases we
3639 * want to catch. The first is this case:
3641 * |--- cluster # N--|
3642 * |--- extent ---| |---- requested region ---|
3645 * The second case that we need to test for is this one:
3647 * |--------- cluster # N ----------------|
3648 * |--- requested region --| |------- extent ----|
3649 * |=======================|
3651 * The third case is when the requested region lies between two extents
3652 * within the same cluster:
3653 * |------------- cluster # N-------------|
3654 * |----- ex -----| |---- ex_right ----|
3655 * |------ requested region ------|
3656 * |================|
3658 * In each of the above cases, we need to set the map->m_pblk and
3659 * map->m_len so it corresponds to the return the extent labelled as
3660 * "|====|" from cluster #N, since it is already in use for data in
3661 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
3662 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
3663 * as a new "allocated" block region. Otherwise, we will return 0 and
3664 * ext4_ext_map_blocks() will then allocate one or more new clusters
3665 * by calling ext4_mb_new_blocks().
3667 static int get_implied_cluster_alloc(struct super_block *sb,
3668 struct ext4_map_blocks *map,
3669 struct ext4_extent *ex,
3670 struct ext4_ext_path *path)
3672 struct ext4_sb_info *sbi = EXT4_SB(sb);
3673 ext4_lblk_t c_offset = map->m_lblk & (sbi->s_cluster_ratio-1);
3674 ext4_lblk_t ex_cluster_start, ex_cluster_end;
3675 ext4_lblk_t rr_cluster_start, rr_cluster_end;
3676 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3677 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3678 unsigned short ee_len = ext4_ext_get_actual_len(ex);
3680 /* The extent passed in that we are trying to match */
3681 ex_cluster_start = EXT4_B2C(sbi, ee_block);
3682 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
3684 /* The requested region passed into ext4_map_blocks() */
3685 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
3686 rr_cluster_end = EXT4_B2C(sbi, map->m_lblk + map->m_len - 1);
3688 if ((rr_cluster_start == ex_cluster_end) ||
3689 (rr_cluster_start == ex_cluster_start)) {
3690 if (rr_cluster_start == ex_cluster_end)
3691 ee_start += ee_len - 1;
3692 map->m_pblk = (ee_start & ~(sbi->s_cluster_ratio - 1)) +
3694 map->m_len = min(map->m_len,
3695 (unsigned) sbi->s_cluster_ratio - c_offset);
3697 * Check for and handle this case:
3699 * |--------- cluster # N-------------|
3700 * |------- extent ----|
3701 * |--- requested region ---|
3705 if (map->m_lblk < ee_block)
3706 map->m_len = min(map->m_len, ee_block - map->m_lblk);
3709 * Check for the case where there is already another allocated
3710 * block to the right of 'ex' but before the end of the cluster.
3712 * |------------- cluster # N-------------|
3713 * |----- ex -----| |---- ex_right ----|
3714 * |------ requested region ------|
3715 * |================|
3717 if (map->m_lblk > ee_block) {
3718 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
3719 map->m_len = min(map->m_len, next - map->m_lblk);
3722 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
3726 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
3732 * Block allocation/map/preallocation routine for extents based files
3735 * Need to be called with
3736 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
3737 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
3739 * return > 0, number of of blocks already mapped/allocated
3740 * if create == 0 and these are pre-allocated blocks
3741 * buffer head is unmapped
3742 * otherwise blocks are mapped
3744 * return = 0, if plain look up failed (blocks have not been allocated)
3745 * buffer head is unmapped
3747 * return < 0, error case.
3749 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
3750 struct ext4_map_blocks *map, int flags)
3752 struct ext4_ext_path *path = NULL;
3753 struct ext4_extent newex, *ex, *ex2;
3754 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3755 ext4_fsblk_t newblock = 0;
3756 int free_on_err = 0, err = 0, depth, ret;
3757 unsigned int allocated = 0, offset = 0;
3758 unsigned int allocated_clusters = 0;
3759 unsigned int punched_out = 0;
3760 unsigned int result = 0;
3761 struct ext4_allocation_request ar;
3762 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3763 ext4_lblk_t cluster_offset;
3765 ext_debug("blocks %u/%u requested for inode %lu\n",
3766 map->m_lblk, map->m_len, inode->i_ino);
3767 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
3769 /* check in cache */
3770 if (!(flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) &&
3771 ext4_ext_in_cache(inode, map->m_lblk, &newex)) {
3772 if (!newex.ee_start_lo && !newex.ee_start_hi) {
3773 if ((sbi->s_cluster_ratio > 1) &&
3774 ext4_find_delalloc_cluster(inode, map->m_lblk, 0))
3775 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3777 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3779 * block isn't allocated yet and
3780 * user doesn't want to allocate it
3784 /* we should allocate requested block */
3786 /* block is already allocated */
3787 if (sbi->s_cluster_ratio > 1)
3788 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3789 newblock = map->m_lblk
3790 - le32_to_cpu(newex.ee_block)
3791 + ext4_ext_pblock(&newex);
3792 /* number of remaining blocks in the extent */
3793 allocated = ext4_ext_get_actual_len(&newex) -
3794 (map->m_lblk - le32_to_cpu(newex.ee_block));
3799 /* find extent for this block */
3800 path = ext4_ext_find_extent(inode, map->m_lblk, NULL);
3802 err = PTR_ERR(path);
3807 depth = ext_depth(inode);
3810 * consistent leaf must not be empty;
3811 * this situation is possible, though, _during_ tree modification;
3812 * this is why assert can't be put in ext4_ext_find_extent()
3814 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
3815 EXT4_ERROR_INODE(inode, "bad extent address "
3816 "lblock: %lu, depth: %d pblock %lld",
3817 (unsigned long) map->m_lblk, depth,
3818 path[depth].p_block);
3823 ex = path[depth].p_ext;
3825 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3826 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3827 unsigned short ee_len;
3830 * Uninitialized extents are treated as holes, except that
3831 * we split out initialized portions during a write.
3833 ee_len = ext4_ext_get_actual_len(ex);
3835 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
3837 /* if found extent covers block, simply return it */
3838 if (in_range(map->m_lblk, ee_block, ee_len)) {
3839 struct ext4_map_blocks punch_map;
3840 ext4_fsblk_t partial_cluster = 0;
3842 newblock = map->m_lblk - ee_block + ee_start;
3843 /* number of remaining blocks in the extent */
3844 allocated = ee_len - (map->m_lblk - ee_block);
3845 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
3846 ee_block, ee_len, newblock);
3848 if ((flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) == 0) {
3850 * Do not put uninitialized extent
3853 if (!ext4_ext_is_uninitialized(ex)) {
3854 ext4_ext_put_in_cache(inode, ee_block,
3858 ret = ext4_ext_handle_uninitialized_extents(
3859 handle, inode, map, path, flags,
3860 allocated, newblock);
3865 * Punch out the map length, but only to the
3868 punched_out = allocated < map->m_len ?
3869 allocated : map->m_len;
3872 * Sense extents need to be converted to
3873 * uninitialized, they must fit in an
3874 * uninitialized extent
3876 if (punched_out > EXT_UNINIT_MAX_LEN)
3877 punched_out = EXT_UNINIT_MAX_LEN;
3879 punch_map.m_lblk = map->m_lblk;
3880 punch_map.m_pblk = newblock;
3881 punch_map.m_len = punched_out;
3882 punch_map.m_flags = 0;
3884 /* Check to see if the extent needs to be split */
3885 if (punch_map.m_len != ee_len ||
3886 punch_map.m_lblk != ee_block) {
3888 ret = ext4_split_extent(handle, inode,
3889 path, &punch_map, 0,
3890 EXT4_GET_BLOCKS_PUNCH_OUT_EXT |
3891 EXT4_GET_BLOCKS_PRE_IO);
3898 * find extent for the block at
3899 * the start of the hole
3901 ext4_ext_drop_refs(path);
3904 path = ext4_ext_find_extent(inode,
3907 err = PTR_ERR(path);
3912 depth = ext_depth(inode);
3913 ex = path[depth].p_ext;
3914 ee_len = ext4_ext_get_actual_len(ex);
3915 ee_block = le32_to_cpu(ex->ee_block);
3916 ee_start = ext4_ext_pblock(ex);
3920 ext4_ext_mark_uninitialized(ex);
3922 ext4_ext_invalidate_cache(inode);
3924 err = ext4_ext_rm_leaf(handle, inode, path,
3925 &partial_cluster, map->m_lblk,
3926 map->m_lblk + punched_out);
3928 if (!err && path->p_hdr->eh_entries == 0) {
3930 * Punch hole freed all of this sub tree,
3931 * so we need to correct eh_depth
3933 err = ext4_ext_get_access(handle, inode, path);
3935 ext_inode_hdr(inode)->eh_depth = 0;
3936 ext_inode_hdr(inode)->eh_max =
3937 cpu_to_le16(ext4_ext_space_root(
3940 err = ext4_ext_dirty(
3941 handle, inode, path);
3949 if ((sbi->s_cluster_ratio > 1) &&
3950 ext4_find_delalloc_cluster(inode, map->m_lblk, 0))
3951 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3954 * requested block isn't allocated yet;
3955 * we couldn't try to create block if create flag is zero
3957 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3959 * put just found gap into cache to speed up
3960 * subsequent requests
3962 ext4_ext_put_gap_in_cache(inode, path, map->m_lblk);
3967 * Okay, we need to do block allocation.
3969 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
3970 newex.ee_block = cpu_to_le32(map->m_lblk);
3971 cluster_offset = map->m_lblk & (sbi->s_cluster_ratio-1);
3974 * If we are doing bigalloc, check to see if the extent returned
3975 * by ext4_ext_find_extent() implies a cluster we can use.
3977 if (cluster_offset && ex &&
3978 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
3979 ar.len = allocated = map->m_len;
3980 newblock = map->m_pblk;
3981 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3982 goto got_allocated_blocks;
3985 /* find neighbour allocated blocks */
3986 ar.lleft = map->m_lblk;
3987 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3990 ar.lright = map->m_lblk;
3992 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
3996 /* Check if the extent after searching to the right implies a
3997 * cluster we can use. */
3998 if ((sbi->s_cluster_ratio > 1) && ex2 &&
3999 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4000 ar.len = allocated = map->m_len;
4001 newblock = map->m_pblk;
4002 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
4003 goto got_allocated_blocks;
4007 * See if request is beyond maximum number of blocks we can have in
4008 * a single extent. For an initialized extent this limit is
4009 * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
4010 * EXT_UNINIT_MAX_LEN.
4012 if (map->m_len > EXT_INIT_MAX_LEN &&
4013 !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
4014 map->m_len = EXT_INIT_MAX_LEN;
4015 else if (map->m_len > EXT_UNINIT_MAX_LEN &&
4016 (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
4017 map->m_len = EXT_UNINIT_MAX_LEN;
4019 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4020 newex.ee_len = cpu_to_le16(map->m_len);
4021 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4023 allocated = ext4_ext_get_actual_len(&newex);
4025 allocated = map->m_len;
4027 /* allocate new block */
4029 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4030 ar.logical = map->m_lblk;
4032 * We calculate the offset from the beginning of the cluster
4033 * for the logical block number, since when we allocate a
4034 * physical cluster, the physical block should start at the
4035 * same offset from the beginning of the cluster. This is
4036 * needed so that future calls to get_implied_cluster_alloc()
4039 offset = map->m_lblk & (sbi->s_cluster_ratio - 1);
4040 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4042 ar.logical -= offset;
4043 if (S_ISREG(inode->i_mode))
4044 ar.flags = EXT4_MB_HINT_DATA;
4046 /* disable in-core preallocation for non-regular files */
4048 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4049 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4050 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4053 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4054 ar.goal, newblock, allocated);
4056 allocated_clusters = ar.len;
4057 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4058 if (ar.len > allocated)
4061 got_allocated_blocks:
4062 /* try to insert new extent into found leaf and return */
4063 ext4_ext_store_pblock(&newex, newblock + offset);
4064 newex.ee_len = cpu_to_le16(ar.len);
4065 /* Mark uninitialized */
4066 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
4067 ext4_ext_mark_uninitialized(&newex);
4069 * io_end structure was created for every IO write to an
4070 * uninitialized extent. To avoid unnecessary conversion,
4071 * here we flag the IO that really needs the conversion.
4072 * For non asycn direct IO case, flag the inode state
4073 * that we need to perform conversion when IO is done.
4075 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
4077 ext4_set_io_unwritten_flag(inode, io);
4079 ext4_set_inode_state(inode,
4080 EXT4_STATE_DIO_UNWRITTEN);
4082 if (ext4_should_dioread_nolock(inode))
4083 map->m_flags |= EXT4_MAP_UNINIT;
4087 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4088 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4091 err = ext4_ext_insert_extent(handle, inode, path,
4093 if (err && free_on_err) {
4094 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4095 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4096 /* free data blocks we just allocated */
4097 /* not a good idea to call discard here directly,
4098 * but otherwise we'd need to call it every free() */
4099 ext4_discard_preallocations(inode);
4100 ext4_free_blocks(handle, inode, NULL, ext4_ext_pblock(&newex),
4101 ext4_ext_get_actual_len(&newex), fb_flags);
4105 /* previous routine could use block we allocated */
4106 newblock = ext4_ext_pblock(&newex);
4107 allocated = ext4_ext_get_actual_len(&newex);
4108 if (allocated > map->m_len)
4109 allocated = map->m_len;
4110 map->m_flags |= EXT4_MAP_NEW;
4113 * Update reserved blocks/metadata blocks after successful
4114 * block allocation which had been deferred till now.
4116 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4117 unsigned int reserved_clusters;
4119 * Check how many clusters we had reserved this allocated range
4121 reserved_clusters = get_reserved_cluster_alloc(inode,
4122 map->m_lblk, allocated);
4123 if (map->m_flags & EXT4_MAP_FROM_CLUSTER) {
4124 if (reserved_clusters) {
4126 * We have clusters reserved for this range.
4127 * But since we are not doing actual allocation
4128 * and are simply using blocks from previously
4129 * allocated cluster, we should release the
4130 * reservation and not claim quota.
4132 ext4_da_update_reserve_space(inode,
4133 reserved_clusters, 0);
4136 BUG_ON(allocated_clusters < reserved_clusters);
4137 /* We will claim quota for all newly allocated blocks.*/
4138 ext4_da_update_reserve_space(inode, allocated_clusters,
4140 if (reserved_clusters < allocated_clusters) {
4141 struct ext4_inode_info *ei = EXT4_I(inode);
4142 int reservation = allocated_clusters -
4145 * It seems we claimed few clusters outside of
4146 * the range of this allocation. We should give
4147 * it back to the reservation pool. This can
4148 * happen in the following case:
4150 * * Suppose s_cluster_ratio is 4 (i.e., each
4151 * cluster has 4 blocks. Thus, the clusters
4152 * are [0-3],[4-7],[8-11]...
4153 * * First comes delayed allocation write for
4154 * logical blocks 10 & 11. Since there were no
4155 * previous delayed allocated blocks in the
4156 * range [8-11], we would reserve 1 cluster
4158 * * Next comes write for logical blocks 3 to 8.
4159 * In this case, we will reserve 2 clusters
4160 * (for [0-3] and [4-7]; and not for [8-11] as
4161 * that range has a delayed allocated blocks.
4162 * Thus total reserved clusters now becomes 3.
4163 * * Now, during the delayed allocation writeout
4164 * time, we will first write blocks [3-8] and
4165 * allocate 3 clusters for writing these
4166 * blocks. Also, we would claim all these
4167 * three clusters above.
4168 * * Now when we come here to writeout the
4169 * blocks [10-11], we would expect to claim
4170 * the reservation of 1 cluster we had made
4171 * (and we would claim it since there are no
4172 * more delayed allocated blocks in the range
4173 * [8-11]. But our reserved cluster count had
4174 * already gone to 0.
4176 * Thus, at the step 4 above when we determine
4177 * that there are still some unwritten delayed
4178 * allocated blocks outside of our current
4179 * block range, we should increment the
4180 * reserved clusters count so that when the
4181 * remaining blocks finally gets written, we
4184 dquot_reserve_block(inode,
4185 EXT4_C2B(sbi, reservation));
4186 spin_lock(&ei->i_block_reservation_lock);
4187 ei->i_reserved_data_blocks += reservation;
4188 spin_unlock(&ei->i_block_reservation_lock);
4194 * Cache the extent and update transaction to commit on fdatasync only
4195 * when it is _not_ an uninitialized extent.
4197 if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
4198 ext4_ext_put_in_cache(inode, map->m_lblk, allocated, newblock);
4199 ext4_update_inode_fsync_trans(handle, inode, 1);
4201 ext4_update_inode_fsync_trans(handle, inode, 0);
4203 if (allocated > map->m_len)
4204 allocated = map->m_len;
4205 ext4_ext_show_leaf(inode, path);
4206 map->m_flags |= EXT4_MAP_MAPPED;
4207 map->m_pblk = newblock;
4208 map->m_len = allocated;
4211 ext4_ext_drop_refs(path);
4214 result = (flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) ?
4215 punched_out : allocated;
4217 trace_ext4_ext_map_blocks_exit(inode, map->m_lblk,
4218 newblock, map->m_len, err ? err : result);
4220 return err ? err : result;
4223 void ext4_ext_truncate(struct inode *inode)
4225 struct address_space *mapping = inode->i_mapping;
4226 struct super_block *sb = inode->i_sb;
4227 ext4_lblk_t last_block;
4233 * finish any pending end_io work so we won't run the risk of
4234 * converting any truncated blocks to initialized later
4236 ext4_flush_completed_IO(inode);
4239 * probably first extent we're gonna free will be last in block
4241 err = ext4_writepage_trans_blocks(inode);
4242 handle = ext4_journal_start(inode, err);
4246 if (inode->i_size % PAGE_CACHE_SIZE != 0) {
4247 page_len = PAGE_CACHE_SIZE -
4248 (inode->i_size & (PAGE_CACHE_SIZE - 1));
4250 err = ext4_discard_partial_page_buffers(handle,
4251 mapping, inode->i_size, page_len, 0);
4257 if (ext4_orphan_add(handle, inode))
4260 down_write(&EXT4_I(inode)->i_data_sem);
4261 ext4_ext_invalidate_cache(inode);
4263 ext4_discard_preallocations(inode);
4266 * TODO: optimization is possible here.
4267 * Probably we need not scan at all,
4268 * because page truncation is enough.
4271 /* we have to know where to truncate from in crash case */
4272 EXT4_I(inode)->i_disksize = inode->i_size;
4273 ext4_mark_inode_dirty(handle, inode);
4275 last_block = (inode->i_size + sb->s_blocksize - 1)
4276 >> EXT4_BLOCK_SIZE_BITS(sb);
4277 err = ext4_ext_remove_space(inode, last_block);
4279 /* In a multi-transaction truncate, we only make the final
4280 * transaction synchronous.
4283 ext4_handle_sync(handle);
4285 up_write(&EXT4_I(inode)->i_data_sem);
4289 * If this was a simple ftruncate() and the file will remain alive,
4290 * then we need to clear up the orphan record which we created above.
4291 * However, if this was a real unlink then we were called by
4292 * ext4_delete_inode(), and we allow that function to clean up the
4293 * orphan info for us.
4296 ext4_orphan_del(handle, inode);
4298 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4299 ext4_mark_inode_dirty(handle, inode);
4300 ext4_journal_stop(handle);
4303 static void ext4_falloc_update_inode(struct inode *inode,
4304 int mode, loff_t new_size, int update_ctime)
4306 struct timespec now;
4309 now = current_fs_time(inode->i_sb);
4310 if (!timespec_equal(&inode->i_ctime, &now))
4311 inode->i_ctime = now;
4314 * Update only when preallocation was requested beyond
4317 if (!(mode & FALLOC_FL_KEEP_SIZE)) {
4318 if (new_size > i_size_read(inode))
4319 i_size_write(inode, new_size);
4320 if (new_size > EXT4_I(inode)->i_disksize)
4321 ext4_update_i_disksize(inode, new_size);
4324 * Mark that we allocate beyond EOF so the subsequent truncate
4325 * can proceed even if the new size is the same as i_size.
4327 if (new_size > i_size_read(inode))
4328 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4334 * preallocate space for a file. This implements ext4's fallocate file
4335 * operation, which gets called from sys_fallocate system call.
4336 * For block-mapped files, posix_fallocate should fall back to the method
4337 * of writing zeroes to the required new blocks (the same behavior which is
4338 * expected for file systems which do not support fallocate() system call).
4340 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4342 struct inode *inode = file->f_path.dentry->d_inode;
4345 unsigned int max_blocks;
4350 struct ext4_map_blocks map;
4351 unsigned int credits, blkbits = inode->i_blkbits;
4354 * currently supporting (pre)allocate mode for extent-based
4357 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4360 /* Return error if mode is not supported */
4361 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
4364 if (mode & FALLOC_FL_PUNCH_HOLE)
4365 return ext4_punch_hole(file, offset, len);
4367 trace_ext4_fallocate_enter(inode, offset, len, mode);
4368 map.m_lblk = offset >> blkbits;
4370 * We can't just convert len to max_blocks because
4371 * If blocksize = 4096 offset = 3072 and len = 2048
4373 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
4376 * credits to insert 1 extent into extent tree
4378 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4379 mutex_lock(&inode->i_mutex);
4380 ret = inode_newsize_ok(inode, (len + offset));
4382 mutex_unlock(&inode->i_mutex);
4383 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
4386 flags = EXT4_GET_BLOCKS_CREATE_UNINIT_EXT;
4387 if (mode & FALLOC_FL_KEEP_SIZE)
4388 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4390 * Don't normalize the request if it can fit in one extent so
4391 * that it doesn't get unnecessarily split into multiple
4394 if (len <= EXT_UNINIT_MAX_LEN << blkbits)
4395 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4397 while (ret >= 0 && ret < max_blocks) {
4398 map.m_lblk = map.m_lblk + ret;
4399 map.m_len = max_blocks = max_blocks - ret;
4400 handle = ext4_journal_start(inode, credits);
4401 if (IS_ERR(handle)) {
4402 ret = PTR_ERR(handle);
4405 ret = ext4_map_blocks(handle, inode, &map, flags);
4409 printk(KERN_ERR "%s: ext4_ext_map_blocks "
4410 "returned error inode#%lu, block=%u, "
4411 "max_blocks=%u", __func__,
4412 inode->i_ino, map.m_lblk, max_blocks);
4414 ext4_mark_inode_dirty(handle, inode);
4415 ret2 = ext4_journal_stop(handle);
4418 if ((map.m_lblk + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
4419 blkbits) >> blkbits))
4420 new_size = offset + len;
4422 new_size = ((loff_t) map.m_lblk + ret) << blkbits;
4424 ext4_falloc_update_inode(inode, mode, new_size,
4425 (map.m_flags & EXT4_MAP_NEW));
4426 ext4_mark_inode_dirty(handle, inode);
4427 ret2 = ext4_journal_stop(handle);
4431 if (ret == -ENOSPC &&
4432 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4436 mutex_unlock(&inode->i_mutex);
4437 trace_ext4_fallocate_exit(inode, offset, max_blocks,
4438 ret > 0 ? ret2 : ret);
4439 return ret > 0 ? ret2 : ret;
4443 * This function convert a range of blocks to written extents
4444 * The caller of this function will pass the start offset and the size.
4445 * all unwritten extents within this range will be converted to
4448 * This function is called from the direct IO end io call back
4449 * function, to convert the fallocated extents after IO is completed.
4450 * Returns 0 on success.
4452 int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
4456 unsigned int max_blocks;
4459 struct ext4_map_blocks map;
4460 unsigned int credits, blkbits = inode->i_blkbits;
4462 map.m_lblk = offset >> blkbits;
4464 * We can't just convert len to max_blocks because
4465 * If blocksize = 4096 offset = 3072 and len = 2048
4467 max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
4470 * credits to insert 1 extent into extent tree
4472 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4473 while (ret >= 0 && ret < max_blocks) {
4475 map.m_len = (max_blocks -= ret);
4476 handle = ext4_journal_start(inode, credits);
4477 if (IS_ERR(handle)) {
4478 ret = PTR_ERR(handle);
4481 ret = ext4_map_blocks(handle, inode, &map,
4482 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
4485 printk(KERN_ERR "%s: ext4_ext_map_blocks "
4486 "returned error inode#%lu, block=%u, "
4487 "max_blocks=%u", __func__,
4488 inode->i_ino, map.m_lblk, map.m_len);
4490 ext4_mark_inode_dirty(handle, inode);
4491 ret2 = ext4_journal_stop(handle);
4492 if (ret <= 0 || ret2 )
4495 return ret > 0 ? ret2 : ret;
4499 * Callback function called for each extent to gather FIEMAP information.
4501 static int ext4_ext_fiemap_cb(struct inode *inode, ext4_lblk_t next,
4502 struct ext4_ext_cache *newex, struct ext4_extent *ex,
4510 struct fiemap_extent_info *fieinfo = data;
4511 unsigned char blksize_bits;
4513 blksize_bits = inode->i_sb->s_blocksize_bits;
4514 logical = (__u64)newex->ec_block << blksize_bits;
4516 if (newex->ec_start == 0) {
4518 * No extent in extent-tree contains block @newex->ec_start,
4519 * then the block may stay in 1)a hole or 2)delayed-extent.
4521 * Holes or delayed-extents are processed as follows.
4522 * 1. lookup dirty pages with specified range in pagecache.
4523 * If no page is got, then there is no delayed-extent and
4524 * return with EXT_CONTINUE.
4525 * 2. find the 1st mapped buffer,
4526 * 3. check if the mapped buffer is both in the request range
4527 * and a delayed buffer. If not, there is no delayed-extent,
4529 * 4. a delayed-extent is found, the extent will be collected.
4531 ext4_lblk_t end = 0;
4532 pgoff_t last_offset;
4535 pgoff_t start_index = 0;
4536 struct page **pages = NULL;
4537 struct buffer_head *bh = NULL;
4538 struct buffer_head *head = NULL;
4539 unsigned int nr_pages = PAGE_SIZE / sizeof(struct page *);
4541 pages = kmalloc(PAGE_SIZE, GFP_KERNEL);
4545 offset = logical >> PAGE_SHIFT;
4547 last_offset = offset;
4549 ret = find_get_pages_tag(inode->i_mapping, &offset,
4550 PAGECACHE_TAG_DIRTY, nr_pages, pages);
4552 if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
4553 /* First time, try to find a mapped buffer. */
4556 for (index = 0; index < ret; index++)
4557 page_cache_release(pages[index]);
4560 return EXT_CONTINUE;
4565 /* Try to find the 1st mapped buffer. */
4566 end = ((__u64)pages[index]->index << PAGE_SHIFT) >>
4568 if (!page_has_buffers(pages[index]))
4570 head = page_buffers(pages[index]);
4577 if (end >= newex->ec_block +
4579 /* The buffer is out of
4580 * the request range.
4584 if (buffer_mapped(bh) &&
4585 end >= newex->ec_block) {
4586 start_index = index - 1;
4587 /* get the 1st mapped buffer. */
4588 goto found_mapped_buffer;
4591 bh = bh->b_this_page;
4593 } while (bh != head);
4595 /* No mapped buffer in the range found in this page,
4596 * We need to look up next page.
4599 /* There is no page left, but we need to limit
4602 newex->ec_len = end - newex->ec_block;
4607 /*Find contiguous delayed buffers. */
4608 if (ret > 0 && pages[0]->index == last_offset)
4609 head = page_buffers(pages[0]);
4615 found_mapped_buffer:
4616 if (bh != NULL && buffer_delay(bh)) {
4617 /* 1st or contiguous delayed buffer found. */
4618 if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
4620 * 1st delayed buffer found, record
4621 * the start of extent.
4623 flags |= FIEMAP_EXTENT_DELALLOC;
4624 newex->ec_block = end;
4625 logical = (__u64)end << blksize_bits;
4627 /* Find contiguous delayed buffers. */
4629 if (!buffer_delay(bh))
4630 goto found_delayed_extent;
4631 bh = bh->b_this_page;
4633 } while (bh != head);
4635 for (; index < ret; index++) {
4636 if (!page_has_buffers(pages[index])) {
4640 head = page_buffers(pages[index]);
4646 if (pages[index]->index !=
4647 pages[start_index]->index + index
4649 /* Blocks are not contiguous. */
4655 if (!buffer_delay(bh))
4656 /* Delayed-extent ends. */
4657 goto found_delayed_extent;
4658 bh = bh->b_this_page;
4660 } while (bh != head);
4662 } else if (!(flags & FIEMAP_EXTENT_DELALLOC))
4666 found_delayed_extent:
4667 newex->ec_len = min(end - newex->ec_block,
4668 (ext4_lblk_t)EXT_INIT_MAX_LEN);
4669 if (ret == nr_pages && bh != NULL &&
4670 newex->ec_len < EXT_INIT_MAX_LEN &&
4672 /* Have not collected an extent and continue. */
4673 for (index = 0; index < ret; index++)
4674 page_cache_release(pages[index]);
4678 for (index = 0; index < ret; index++)
4679 page_cache_release(pages[index]);
4683 physical = (__u64)newex->ec_start << blksize_bits;
4684 length = (__u64)newex->ec_len << blksize_bits;
4686 if (ex && ext4_ext_is_uninitialized(ex))
4687 flags |= FIEMAP_EXTENT_UNWRITTEN;
4689 if (next == EXT_MAX_BLOCKS)
4690 flags |= FIEMAP_EXTENT_LAST;
4692 ret = fiemap_fill_next_extent(fieinfo, logical, physical,
4698 return EXT_CONTINUE;
4700 /* fiemap flags we can handle specified here */
4701 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
4703 static int ext4_xattr_fiemap(struct inode *inode,
4704 struct fiemap_extent_info *fieinfo)
4708 __u32 flags = FIEMAP_EXTENT_LAST;
4709 int blockbits = inode->i_sb->s_blocksize_bits;
4713 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4714 struct ext4_iloc iloc;
4715 int offset; /* offset of xattr in inode */
4717 error = ext4_get_inode_loc(inode, &iloc);
4720 physical = iloc.bh->b_blocknr << blockbits;
4721 offset = EXT4_GOOD_OLD_INODE_SIZE +
4722 EXT4_I(inode)->i_extra_isize;
4724 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
4725 flags |= FIEMAP_EXTENT_DATA_INLINE;
4727 } else { /* external block */
4728 physical = EXT4_I(inode)->i_file_acl << blockbits;
4729 length = inode->i_sb->s_blocksize;
4733 error = fiemap_fill_next_extent(fieinfo, 0, physical,
4735 return (error < 0 ? error : 0);
4739 * ext4_ext_punch_hole
4741 * Punches a hole of "length" bytes in a file starting
4744 * @inode: The inode of the file to punch a hole in
4745 * @offset: The starting byte offset of the hole
4746 * @length: The length of the hole
4748 * Returns the number of blocks removed or negative on err
4750 int ext4_ext_punch_hole(struct file *file, loff_t offset, loff_t length)
4752 struct inode *inode = file->f_path.dentry->d_inode;
4753 struct super_block *sb = inode->i_sb;
4754 struct ext4_ext_cache cache_ex;
4755 ext4_lblk_t first_block, last_block, num_blocks, iblock, max_blocks;
4756 struct address_space *mapping = inode->i_mapping;
4757 struct ext4_map_blocks map;
4759 loff_t first_page, last_page, page_len;
4760 loff_t first_page_offset, last_page_offset;
4761 int ret, credits, blocks_released, err = 0;
4763 /* No need to punch hole beyond i_size */
4764 if (offset >= inode->i_size)
4768 * If the hole extends beyond i_size, set the hole
4769 * to end after the page that contains i_size
4771 if (offset + length > inode->i_size) {
4772 length = inode->i_size +
4773 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
4777 first_block = (offset + sb->s_blocksize - 1) >>
4778 EXT4_BLOCK_SIZE_BITS(sb);
4779 last_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4781 first_page = (offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
4782 last_page = (offset + length) >> PAGE_CACHE_SHIFT;
4784 first_page_offset = first_page << PAGE_CACHE_SHIFT;
4785 last_page_offset = last_page << PAGE_CACHE_SHIFT;
4788 * Write out all dirty pages to avoid race conditions
4789 * Then release them.
4791 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4792 err = filemap_write_and_wait_range(mapping,
4793 offset, offset + length - 1);
4799 /* Now release the pages */
4800 if (last_page_offset > first_page_offset) {
4801 truncate_inode_pages_range(mapping, first_page_offset,
4802 last_page_offset-1);
4805 /* finish any pending end_io work */
4806 ext4_flush_completed_IO(inode);
4808 credits = ext4_writepage_trans_blocks(inode);
4809 handle = ext4_journal_start(inode, credits);
4811 return PTR_ERR(handle);
4813 err = ext4_orphan_add(handle, inode);
4818 * Now we need to zero out the non-page-aligned data in the
4819 * pages at the start and tail of the hole, and unmap the buffer
4820 * heads for the block aligned regions of the page that were
4821 * completely zeroed.
4823 if (first_page > last_page) {
4825 * If the file space being truncated is contained within a page
4826 * just zero out and unmap the middle of that page
4828 err = ext4_discard_partial_page_buffers(handle,
4829 mapping, offset, length, 0);
4835 * zero out and unmap the partial page that contains
4836 * the start of the hole
4838 page_len = first_page_offset - offset;
4840 err = ext4_discard_partial_page_buffers(handle, mapping,
4841 offset, page_len, 0);
4847 * zero out and unmap the partial page that contains
4848 * the end of the hole
4850 page_len = offset + length - last_page_offset;
4852 err = ext4_discard_partial_page_buffers(handle, mapping,
4853 last_page_offset, page_len, 0);
4861 * If i_size is contained in the last page, we need to
4862 * unmap and zero the partial page after i_size
4864 if (inode->i_size >> PAGE_CACHE_SHIFT == last_page &&
4865 inode->i_size % PAGE_CACHE_SIZE != 0) {
4867 page_len = PAGE_CACHE_SIZE -
4868 (inode->i_size & (PAGE_CACHE_SIZE - 1));
4871 err = ext4_discard_partial_page_buffers(handle,
4872 mapping, inode->i_size, page_len, 0);
4879 /* If there are no blocks to remove, return now */
4880 if (first_block >= last_block)
4883 down_write(&EXT4_I(inode)->i_data_sem);
4884 ext4_ext_invalidate_cache(inode);
4885 ext4_discard_preallocations(inode);
4888 * Loop over all the blocks and identify blocks
4889 * that need to be punched out
4891 iblock = first_block;
4892 blocks_released = 0;
4893 while (iblock < last_block) {
4894 max_blocks = last_block - iblock;
4896 memset(&map, 0, sizeof(map));
4897 map.m_lblk = iblock;
4898 map.m_len = max_blocks;
4899 ret = ext4_ext_map_blocks(handle, inode, &map,
4900 EXT4_GET_BLOCKS_PUNCH_OUT_EXT);
4903 blocks_released += ret;
4905 } else if (ret == 0) {
4907 * If map blocks could not find the block,
4908 * then it is in a hole. If the hole was
4909 * not already cached, then map blocks should
4910 * put it in the cache. So we can get the hole
4913 memset(&cache_ex, 0, sizeof(cache_ex));
4914 if ((ext4_ext_check_cache(inode, iblock, &cache_ex)) &&
4915 !cache_ex.ec_start) {
4917 /* The hole is cached */
4918 num_blocks = cache_ex.ec_block +
4919 cache_ex.ec_len - iblock;
4922 /* The block could not be identified */
4927 /* Map blocks error */
4932 if (num_blocks == 0) {
4933 /* This condition should never happen */
4934 ext_debug("Block lookup failed");
4939 iblock += num_blocks;
4942 if (blocks_released > 0) {
4943 ext4_ext_invalidate_cache(inode);
4944 ext4_discard_preallocations(inode);
4948 ext4_handle_sync(handle);
4950 up_write(&EXT4_I(inode)->i_data_sem);
4953 ext4_orphan_del(handle, inode);
4954 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4955 ext4_mark_inode_dirty(handle, inode);
4956 ext4_journal_stop(handle);
4959 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4960 __u64 start, __u64 len)
4962 ext4_lblk_t start_blk;
4965 /* fallback to generic here if not in extents fmt */
4966 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4967 return generic_block_fiemap(inode, fieinfo, start, len,
4970 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
4973 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
4974 error = ext4_xattr_fiemap(inode, fieinfo);
4976 ext4_lblk_t len_blks;
4979 start_blk = start >> inode->i_sb->s_blocksize_bits;
4980 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
4981 if (last_blk >= EXT_MAX_BLOCKS)
4982 last_blk = EXT_MAX_BLOCKS-1;
4983 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
4986 * Walk the extent tree gathering extent information.
4987 * ext4_ext_fiemap_cb will push extents back to user.
4989 error = ext4_ext_walk_space(inode, start_blk, len_blks,
4990 ext4_ext_fiemap_cb, fieinfo);