ext4: Do not zero out uninitialized extents beyond i_size
[linux-2.6.git] / fs / ext4 / extents.c
blobee611daf07486547651290e53d478ab51cb9451e
1 /*
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
26 * TODO:
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>
33 #include <linux/fs.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"
45 #include "ext4_extents.h"
49 * ext_pblock:
50 * combine low and high parts of physical block number into ext4_fsblk_t
52 ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
54 ext4_fsblk_t block;
56 block = le32_to_cpu(ex->ee_start_lo);
57 block |= ((ext4_fsblk_t) le16_to_cpu(ex->ee_start_hi) << 31) << 1;
58 return block;
62 * idx_pblock:
63 * combine low and high parts of a leaf physical block number into ext4_fsblk_t
65 ext4_fsblk_t idx_pblock(struct ext4_extent_idx *ix)
67 ext4_fsblk_t block;
69 block = le32_to_cpu(ix->ei_leaf_lo);
70 block |= ((ext4_fsblk_t) le16_to_cpu(ix->ei_leaf_hi) << 31) << 1;
71 return block;
75 * ext4_ext_store_pblock:
76 * stores a large physical block number into an extent struct,
77 * breaking it into parts
79 void ext4_ext_store_pblock(struct ext4_extent *ex, ext4_fsblk_t pb)
81 ex->ee_start_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
82 ex->ee_start_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
86 * ext4_idx_store_pblock:
87 * stores a large physical block number into an index struct,
88 * breaking it into parts
90 static void ext4_idx_store_pblock(struct ext4_extent_idx *ix, ext4_fsblk_t pb)
92 ix->ei_leaf_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
93 ix->ei_leaf_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
96 static int ext4_ext_truncate_extend_restart(handle_t *handle,
97 struct inode *inode,
98 int needed)
100 int err;
102 if (!ext4_handle_valid(handle))
103 return 0;
104 if (handle->h_buffer_credits > needed)
105 return 0;
106 err = ext4_journal_extend(handle, needed);
107 if (err <= 0)
108 return err;
109 err = ext4_truncate_restart_trans(handle, inode, needed);
111 * We have dropped i_data_sem so someone might have cached again
112 * an extent we are going to truncate.
114 ext4_ext_invalidate_cache(inode);
116 return err;
120 * could return:
121 * - EROFS
122 * - ENOMEM
124 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
125 struct ext4_ext_path *path)
127 if (path->p_bh) {
128 /* path points to block */
129 return ext4_journal_get_write_access(handle, path->p_bh);
131 /* path points to leaf/index in inode body */
132 /* we use in-core data, no need to protect them */
133 return 0;
137 * could return:
138 * - EROFS
139 * - ENOMEM
140 * - EIO
142 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
143 struct ext4_ext_path *path)
145 int err;
146 if (path->p_bh) {
147 /* path points to block */
148 err = ext4_handle_dirty_metadata(handle, inode, path->p_bh);
149 } else {
150 /* path points to leaf/index in inode body */
151 err = ext4_mark_inode_dirty(handle, inode);
153 return err;
156 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
157 struct ext4_ext_path *path,
158 ext4_lblk_t block)
160 struct ext4_inode_info *ei = EXT4_I(inode);
161 ext4_fsblk_t bg_start;
162 ext4_fsblk_t last_block;
163 ext4_grpblk_t colour;
164 ext4_group_t block_group;
165 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
166 int depth;
168 if (path) {
169 struct ext4_extent *ex;
170 depth = path->p_depth;
172 /* try to predict block placement */
173 ex = path[depth].p_ext;
174 if (ex)
175 return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
177 /* it looks like index is empty;
178 * try to find starting block from index itself */
179 if (path[depth].p_bh)
180 return path[depth].p_bh->b_blocknr;
183 /* OK. use inode's group */
184 block_group = ei->i_block_group;
185 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
187 * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
188 * block groups per flexgroup, reserve the first block
189 * group for directories and special files. Regular
190 * files will start at the second block group. This
191 * tends to speed up directory access and improves
192 * fsck times.
194 block_group &= ~(flex_size-1);
195 if (S_ISREG(inode->i_mode))
196 block_group++;
198 bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
199 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
202 * If we are doing delayed allocation, we don't need take
203 * colour into account.
205 if (test_opt(inode->i_sb, DELALLOC))
206 return bg_start;
208 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
209 colour = (current->pid % 16) *
210 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
211 else
212 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
213 return bg_start + colour + block;
217 * Allocation for a meta data block
219 static ext4_fsblk_t
220 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
221 struct ext4_ext_path *path,
222 struct ext4_extent *ex, int *err)
224 ext4_fsblk_t goal, newblock;
226 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
227 newblock = ext4_new_meta_blocks(handle, inode, goal, NULL, err);
228 return newblock;
231 static inline int ext4_ext_space_block(struct inode *inode, int check)
233 int size;
235 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
236 / sizeof(struct ext4_extent);
237 if (!check) {
238 #ifdef AGGRESSIVE_TEST
239 if (size > 6)
240 size = 6;
241 #endif
243 return size;
246 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
248 int size;
250 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
251 / sizeof(struct ext4_extent_idx);
252 if (!check) {
253 #ifdef AGGRESSIVE_TEST
254 if (size > 5)
255 size = 5;
256 #endif
258 return size;
261 static inline int ext4_ext_space_root(struct inode *inode, int check)
263 int size;
265 size = sizeof(EXT4_I(inode)->i_data);
266 size -= sizeof(struct ext4_extent_header);
267 size /= sizeof(struct ext4_extent);
268 if (!check) {
269 #ifdef AGGRESSIVE_TEST
270 if (size > 3)
271 size = 3;
272 #endif
274 return size;
277 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
279 int size;
281 size = sizeof(EXT4_I(inode)->i_data);
282 size -= sizeof(struct ext4_extent_header);
283 size /= sizeof(struct ext4_extent_idx);
284 if (!check) {
285 #ifdef AGGRESSIVE_TEST
286 if (size > 4)
287 size = 4;
288 #endif
290 return size;
294 * Calculate the number of metadata blocks needed
295 * to allocate @blocks
296 * Worse case is one block per extent
298 int ext4_ext_calc_metadata_amount(struct inode *inode, sector_t lblock)
300 struct ext4_inode_info *ei = EXT4_I(inode);
301 int idxs, num = 0;
303 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
304 / sizeof(struct ext4_extent_idx));
307 * If the new delayed allocation block is contiguous with the
308 * previous da block, it can share index blocks with the
309 * previous block, so we only need to allocate a new index
310 * block every idxs leaf blocks. At ldxs**2 blocks, we need
311 * an additional index block, and at ldxs**3 blocks, yet
312 * another index blocks.
314 if (ei->i_da_metadata_calc_len &&
315 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
316 if ((ei->i_da_metadata_calc_len % idxs) == 0)
317 num++;
318 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
319 num++;
320 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
321 num++;
322 ei->i_da_metadata_calc_len = 0;
323 } else
324 ei->i_da_metadata_calc_len++;
325 ei->i_da_metadata_calc_last_lblock++;
326 return num;
330 * In the worst case we need a new set of index blocks at
331 * every level of the inode's extent tree.
333 ei->i_da_metadata_calc_len = 1;
334 ei->i_da_metadata_calc_last_lblock = lblock;
335 return ext_depth(inode) + 1;
338 static int
339 ext4_ext_max_entries(struct inode *inode, int depth)
341 int max;
343 if (depth == ext_depth(inode)) {
344 if (depth == 0)
345 max = ext4_ext_space_root(inode, 1);
346 else
347 max = ext4_ext_space_root_idx(inode, 1);
348 } else {
349 if (depth == 0)
350 max = ext4_ext_space_block(inode, 1);
351 else
352 max = ext4_ext_space_block_idx(inode, 1);
355 return max;
358 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
360 ext4_fsblk_t block = ext_pblock(ext);
361 int len = ext4_ext_get_actual_len(ext);
363 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
366 static int ext4_valid_extent_idx(struct inode *inode,
367 struct ext4_extent_idx *ext_idx)
369 ext4_fsblk_t block = idx_pblock(ext_idx);
371 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
374 static int ext4_valid_extent_entries(struct inode *inode,
375 struct ext4_extent_header *eh,
376 int depth)
378 struct ext4_extent *ext;
379 struct ext4_extent_idx *ext_idx;
380 unsigned short entries;
381 if (eh->eh_entries == 0)
382 return 1;
384 entries = le16_to_cpu(eh->eh_entries);
386 if (depth == 0) {
387 /* leaf entries */
388 ext = EXT_FIRST_EXTENT(eh);
389 while (entries) {
390 if (!ext4_valid_extent(inode, ext))
391 return 0;
392 ext++;
393 entries--;
395 } else {
396 ext_idx = EXT_FIRST_INDEX(eh);
397 while (entries) {
398 if (!ext4_valid_extent_idx(inode, ext_idx))
399 return 0;
400 ext_idx++;
401 entries--;
404 return 1;
407 static int __ext4_ext_check(const char *function, struct inode *inode,
408 struct ext4_extent_header *eh,
409 int depth)
411 const char *error_msg;
412 int max = 0;
414 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
415 error_msg = "invalid magic";
416 goto corrupted;
418 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
419 error_msg = "unexpected eh_depth";
420 goto corrupted;
422 if (unlikely(eh->eh_max == 0)) {
423 error_msg = "invalid eh_max";
424 goto corrupted;
426 max = ext4_ext_max_entries(inode, depth);
427 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
428 error_msg = "too large eh_max";
429 goto corrupted;
431 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
432 error_msg = "invalid eh_entries";
433 goto corrupted;
435 if (!ext4_valid_extent_entries(inode, eh, depth)) {
436 error_msg = "invalid extent entries";
437 goto corrupted;
439 return 0;
441 corrupted:
442 __ext4_error(inode->i_sb, function,
443 "bad header/extent in inode #%lu: %s - magic %x, "
444 "entries %u, max %u(%u), depth %u(%u)",
445 inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
446 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
447 max, le16_to_cpu(eh->eh_depth), depth);
449 return -EIO;
452 #define ext4_ext_check(inode, eh, depth) \
453 __ext4_ext_check(__func__, inode, eh, depth)
455 int ext4_ext_check_inode(struct inode *inode)
457 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
460 #ifdef EXT_DEBUG
461 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
463 int k, l = path->p_depth;
465 ext_debug("path:");
466 for (k = 0; k <= l; k++, path++) {
467 if (path->p_idx) {
468 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
469 idx_pblock(path->p_idx));
470 } else if (path->p_ext) {
471 ext_debug(" %d:[%d]%d:%llu ",
472 le32_to_cpu(path->p_ext->ee_block),
473 ext4_ext_is_uninitialized(path->p_ext),
474 ext4_ext_get_actual_len(path->p_ext),
475 ext_pblock(path->p_ext));
476 } else
477 ext_debug(" []");
479 ext_debug("\n");
482 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
484 int depth = ext_depth(inode);
485 struct ext4_extent_header *eh;
486 struct ext4_extent *ex;
487 int i;
489 if (!path)
490 return;
492 eh = path[depth].p_hdr;
493 ex = EXT_FIRST_EXTENT(eh);
495 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
497 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
498 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
499 ext4_ext_is_uninitialized(ex),
500 ext4_ext_get_actual_len(ex), ext_pblock(ex));
502 ext_debug("\n");
504 #else
505 #define ext4_ext_show_path(inode, path)
506 #define ext4_ext_show_leaf(inode, path)
507 #endif
509 void ext4_ext_drop_refs(struct ext4_ext_path *path)
511 int depth = path->p_depth;
512 int i;
514 for (i = 0; i <= depth; i++, path++)
515 if (path->p_bh) {
516 brelse(path->p_bh);
517 path->p_bh = NULL;
522 * ext4_ext_binsearch_idx:
523 * binary search for the closest index of the given block
524 * the header must be checked before calling this
526 static void
527 ext4_ext_binsearch_idx(struct inode *inode,
528 struct ext4_ext_path *path, ext4_lblk_t block)
530 struct ext4_extent_header *eh = path->p_hdr;
531 struct ext4_extent_idx *r, *l, *m;
534 ext_debug("binsearch for %u(idx): ", block);
536 l = EXT_FIRST_INDEX(eh) + 1;
537 r = EXT_LAST_INDEX(eh);
538 while (l <= r) {
539 m = l + (r - l) / 2;
540 if (block < le32_to_cpu(m->ei_block))
541 r = m - 1;
542 else
543 l = m + 1;
544 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
545 m, le32_to_cpu(m->ei_block),
546 r, le32_to_cpu(r->ei_block));
549 path->p_idx = l - 1;
550 ext_debug(" -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
551 idx_pblock(path->p_idx));
553 #ifdef CHECK_BINSEARCH
555 struct ext4_extent_idx *chix, *ix;
556 int k;
558 chix = ix = EXT_FIRST_INDEX(eh);
559 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
560 if (k != 0 &&
561 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
562 printk(KERN_DEBUG "k=%d, ix=0x%p, "
563 "first=0x%p\n", k,
564 ix, EXT_FIRST_INDEX(eh));
565 printk(KERN_DEBUG "%u <= %u\n",
566 le32_to_cpu(ix->ei_block),
567 le32_to_cpu(ix[-1].ei_block));
569 BUG_ON(k && le32_to_cpu(ix->ei_block)
570 <= le32_to_cpu(ix[-1].ei_block));
571 if (block < le32_to_cpu(ix->ei_block))
572 break;
573 chix = ix;
575 BUG_ON(chix != path->p_idx);
577 #endif
582 * ext4_ext_binsearch:
583 * binary search for closest extent of the given block
584 * the header must be checked before calling this
586 static void
587 ext4_ext_binsearch(struct inode *inode,
588 struct ext4_ext_path *path, ext4_lblk_t block)
590 struct ext4_extent_header *eh = path->p_hdr;
591 struct ext4_extent *r, *l, *m;
593 if (eh->eh_entries == 0) {
595 * this leaf is empty:
596 * we get such a leaf in split/add case
598 return;
601 ext_debug("binsearch for %u: ", block);
603 l = EXT_FIRST_EXTENT(eh) + 1;
604 r = EXT_LAST_EXTENT(eh);
606 while (l <= r) {
607 m = l + (r - l) / 2;
608 if (block < le32_to_cpu(m->ee_block))
609 r = m - 1;
610 else
611 l = m + 1;
612 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
613 m, le32_to_cpu(m->ee_block),
614 r, le32_to_cpu(r->ee_block));
617 path->p_ext = l - 1;
618 ext_debug(" -> %d:%llu:[%d]%d ",
619 le32_to_cpu(path->p_ext->ee_block),
620 ext_pblock(path->p_ext),
621 ext4_ext_is_uninitialized(path->p_ext),
622 ext4_ext_get_actual_len(path->p_ext));
624 #ifdef CHECK_BINSEARCH
626 struct ext4_extent *chex, *ex;
627 int k;
629 chex = ex = EXT_FIRST_EXTENT(eh);
630 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
631 BUG_ON(k && le32_to_cpu(ex->ee_block)
632 <= le32_to_cpu(ex[-1].ee_block));
633 if (block < le32_to_cpu(ex->ee_block))
634 break;
635 chex = ex;
637 BUG_ON(chex != path->p_ext);
639 #endif
643 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
645 struct ext4_extent_header *eh;
647 eh = ext_inode_hdr(inode);
648 eh->eh_depth = 0;
649 eh->eh_entries = 0;
650 eh->eh_magic = EXT4_EXT_MAGIC;
651 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
652 ext4_mark_inode_dirty(handle, inode);
653 ext4_ext_invalidate_cache(inode);
654 return 0;
657 struct ext4_ext_path *
658 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
659 struct ext4_ext_path *path)
661 struct ext4_extent_header *eh;
662 struct buffer_head *bh;
663 short int depth, i, ppos = 0, alloc = 0;
665 eh = ext_inode_hdr(inode);
666 depth = ext_depth(inode);
668 /* account possible depth increase */
669 if (!path) {
670 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
671 GFP_NOFS);
672 if (!path)
673 return ERR_PTR(-ENOMEM);
674 alloc = 1;
676 path[0].p_hdr = eh;
677 path[0].p_bh = NULL;
679 i = depth;
680 /* walk through the tree */
681 while (i) {
682 int need_to_validate = 0;
684 ext_debug("depth %d: num %d, max %d\n",
685 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
687 ext4_ext_binsearch_idx(inode, path + ppos, block);
688 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
689 path[ppos].p_depth = i;
690 path[ppos].p_ext = NULL;
692 bh = sb_getblk(inode->i_sb, path[ppos].p_block);
693 if (unlikely(!bh))
694 goto err;
695 if (!bh_uptodate_or_lock(bh)) {
696 if (bh_submit_read(bh) < 0) {
697 put_bh(bh);
698 goto err;
700 /* validate the extent entries */
701 need_to_validate = 1;
703 eh = ext_block_hdr(bh);
704 ppos++;
705 if (unlikely(ppos > depth)) {
706 put_bh(bh);
707 EXT4_ERROR_INODE(inode,
708 "ppos %d > depth %d", ppos, depth);
709 goto err;
711 path[ppos].p_bh = bh;
712 path[ppos].p_hdr = eh;
713 i--;
715 if (need_to_validate && ext4_ext_check(inode, eh, i))
716 goto err;
719 path[ppos].p_depth = i;
720 path[ppos].p_ext = NULL;
721 path[ppos].p_idx = NULL;
723 /* find extent */
724 ext4_ext_binsearch(inode, path + ppos, block);
725 /* if not an empty leaf */
726 if (path[ppos].p_ext)
727 path[ppos].p_block = ext_pblock(path[ppos].p_ext);
729 ext4_ext_show_path(inode, path);
731 return path;
733 err:
734 ext4_ext_drop_refs(path);
735 if (alloc)
736 kfree(path);
737 return ERR_PTR(-EIO);
741 * ext4_ext_insert_index:
742 * insert new index [@logical;@ptr] into the block at @curp;
743 * check where to insert: before @curp or after @curp
745 int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
746 struct ext4_ext_path *curp,
747 int logical, ext4_fsblk_t ptr)
749 struct ext4_extent_idx *ix;
750 int len, err;
752 err = ext4_ext_get_access(handle, inode, curp);
753 if (err)
754 return err;
756 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
757 EXT4_ERROR_INODE(inode,
758 "logical %d == ei_block %d!",
759 logical, le32_to_cpu(curp->p_idx->ei_block));
760 return -EIO;
762 len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
763 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
764 /* insert after */
765 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
766 len = (len - 1) * sizeof(struct ext4_extent_idx);
767 len = len < 0 ? 0 : len;
768 ext_debug("insert new index %d after: %llu. "
769 "move %d from 0x%p to 0x%p\n",
770 logical, ptr, len,
771 (curp->p_idx + 1), (curp->p_idx + 2));
772 memmove(curp->p_idx + 2, curp->p_idx + 1, len);
774 ix = curp->p_idx + 1;
775 } else {
776 /* insert before */
777 len = len * sizeof(struct ext4_extent_idx);
778 len = len < 0 ? 0 : len;
779 ext_debug("insert new index %d before: %llu. "
780 "move %d from 0x%p to 0x%p\n",
781 logical, ptr, len,
782 curp->p_idx, (curp->p_idx + 1));
783 memmove(curp->p_idx + 1, curp->p_idx, len);
784 ix = curp->p_idx;
787 ix->ei_block = cpu_to_le32(logical);
788 ext4_idx_store_pblock(ix, ptr);
789 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
791 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
792 > le16_to_cpu(curp->p_hdr->eh_max))) {
793 EXT4_ERROR_INODE(inode,
794 "logical %d == ei_block %d!",
795 logical, le32_to_cpu(curp->p_idx->ei_block));
796 return -EIO;
798 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
799 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
800 return -EIO;
803 err = ext4_ext_dirty(handle, inode, curp);
804 ext4_std_error(inode->i_sb, err);
806 return err;
810 * ext4_ext_split:
811 * inserts new subtree into the path, using free index entry
812 * at depth @at:
813 * - allocates all needed blocks (new leaf and all intermediate index blocks)
814 * - makes decision where to split
815 * - moves remaining extents and index entries (right to the split point)
816 * into the newly allocated blocks
817 * - initializes subtree
819 static int ext4_ext_split(handle_t *handle, struct inode *inode,
820 struct ext4_ext_path *path,
821 struct ext4_extent *newext, int at)
823 struct buffer_head *bh = NULL;
824 int depth = ext_depth(inode);
825 struct ext4_extent_header *neh;
826 struct ext4_extent_idx *fidx;
827 struct ext4_extent *ex;
828 int i = at, k, m, a;
829 ext4_fsblk_t newblock, oldblock;
830 __le32 border;
831 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
832 int err = 0;
834 /* make decision: where to split? */
835 /* FIXME: now decision is simplest: at current extent */
837 /* if current leaf will be split, then we should use
838 * border from split point */
839 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
840 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
841 return -EIO;
843 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
844 border = path[depth].p_ext[1].ee_block;
845 ext_debug("leaf will be split."
846 " next leaf starts at %d\n",
847 le32_to_cpu(border));
848 } else {
849 border = newext->ee_block;
850 ext_debug("leaf will be added."
851 " next leaf starts at %d\n",
852 le32_to_cpu(border));
856 * If error occurs, then we break processing
857 * and mark filesystem read-only. index won't
858 * be inserted and tree will be in consistent
859 * state. Next mount will repair buffers too.
863 * Get array to track all allocated blocks.
864 * We need this to handle errors and free blocks
865 * upon them.
867 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
868 if (!ablocks)
869 return -ENOMEM;
871 /* allocate all needed blocks */
872 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
873 for (a = 0; a < depth - at; a++) {
874 newblock = ext4_ext_new_meta_block(handle, inode, path,
875 newext, &err);
876 if (newblock == 0)
877 goto cleanup;
878 ablocks[a] = newblock;
881 /* initialize new leaf */
882 newblock = ablocks[--a];
883 if (unlikely(newblock == 0)) {
884 EXT4_ERROR_INODE(inode, "newblock == 0!");
885 err = -EIO;
886 goto cleanup;
888 bh = sb_getblk(inode->i_sb, newblock);
889 if (!bh) {
890 err = -EIO;
891 goto cleanup;
893 lock_buffer(bh);
895 err = ext4_journal_get_create_access(handle, bh);
896 if (err)
897 goto cleanup;
899 neh = ext_block_hdr(bh);
900 neh->eh_entries = 0;
901 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
902 neh->eh_magic = EXT4_EXT_MAGIC;
903 neh->eh_depth = 0;
904 ex = EXT_FIRST_EXTENT(neh);
906 /* move remainder of path[depth] to the new leaf */
907 if (unlikely(path[depth].p_hdr->eh_entries !=
908 path[depth].p_hdr->eh_max)) {
909 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
910 path[depth].p_hdr->eh_entries,
911 path[depth].p_hdr->eh_max);
912 err = -EIO;
913 goto cleanup;
915 /* start copy from next extent */
916 /* TODO: we could do it by single memmove */
917 m = 0;
918 path[depth].p_ext++;
919 while (path[depth].p_ext <=
920 EXT_MAX_EXTENT(path[depth].p_hdr)) {
921 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
922 le32_to_cpu(path[depth].p_ext->ee_block),
923 ext_pblock(path[depth].p_ext),
924 ext4_ext_is_uninitialized(path[depth].p_ext),
925 ext4_ext_get_actual_len(path[depth].p_ext),
926 newblock);
927 /*memmove(ex++, path[depth].p_ext++,
928 sizeof(struct ext4_extent));
929 neh->eh_entries++;*/
930 path[depth].p_ext++;
931 m++;
933 if (m) {
934 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
935 le16_add_cpu(&neh->eh_entries, m);
938 set_buffer_uptodate(bh);
939 unlock_buffer(bh);
941 err = ext4_handle_dirty_metadata(handle, inode, bh);
942 if (err)
943 goto cleanup;
944 brelse(bh);
945 bh = NULL;
947 /* correct old leaf */
948 if (m) {
949 err = ext4_ext_get_access(handle, inode, path + depth);
950 if (err)
951 goto cleanup;
952 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
953 err = ext4_ext_dirty(handle, inode, path + depth);
954 if (err)
955 goto cleanup;
959 /* create intermediate indexes */
960 k = depth - at - 1;
961 if (unlikely(k < 0)) {
962 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
963 err = -EIO;
964 goto cleanup;
966 if (k)
967 ext_debug("create %d intermediate indices\n", k);
968 /* insert new index into current index block */
969 /* current depth stored in i var */
970 i = depth - 1;
971 while (k--) {
972 oldblock = newblock;
973 newblock = ablocks[--a];
974 bh = sb_getblk(inode->i_sb, newblock);
975 if (!bh) {
976 err = -EIO;
977 goto cleanup;
979 lock_buffer(bh);
981 err = ext4_journal_get_create_access(handle, bh);
982 if (err)
983 goto cleanup;
985 neh = ext_block_hdr(bh);
986 neh->eh_entries = cpu_to_le16(1);
987 neh->eh_magic = EXT4_EXT_MAGIC;
988 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
989 neh->eh_depth = cpu_to_le16(depth - i);
990 fidx = EXT_FIRST_INDEX(neh);
991 fidx->ei_block = border;
992 ext4_idx_store_pblock(fidx, oldblock);
994 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
995 i, newblock, le32_to_cpu(border), oldblock);
996 /* copy indexes */
997 m = 0;
998 path[i].p_idx++;
1000 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1001 EXT_MAX_INDEX(path[i].p_hdr));
1002 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1003 EXT_LAST_INDEX(path[i].p_hdr))) {
1004 EXT4_ERROR_INODE(inode,
1005 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1006 le32_to_cpu(path[i].p_ext->ee_block));
1007 err = -EIO;
1008 goto cleanup;
1010 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
1011 ext_debug("%d: move %d:%llu in new index %llu\n", i,
1012 le32_to_cpu(path[i].p_idx->ei_block),
1013 idx_pblock(path[i].p_idx),
1014 newblock);
1015 /*memmove(++fidx, path[i].p_idx++,
1016 sizeof(struct ext4_extent_idx));
1017 neh->eh_entries++;
1018 BUG_ON(neh->eh_entries > neh->eh_max);*/
1019 path[i].p_idx++;
1020 m++;
1022 if (m) {
1023 memmove(++fidx, path[i].p_idx - m,
1024 sizeof(struct ext4_extent_idx) * m);
1025 le16_add_cpu(&neh->eh_entries, m);
1027 set_buffer_uptodate(bh);
1028 unlock_buffer(bh);
1030 err = ext4_handle_dirty_metadata(handle, inode, bh);
1031 if (err)
1032 goto cleanup;
1033 brelse(bh);
1034 bh = NULL;
1036 /* correct old index */
1037 if (m) {
1038 err = ext4_ext_get_access(handle, inode, path + i);
1039 if (err)
1040 goto cleanup;
1041 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1042 err = ext4_ext_dirty(handle, inode, path + i);
1043 if (err)
1044 goto cleanup;
1047 i--;
1050 /* insert new index */
1051 err = ext4_ext_insert_index(handle, inode, path + at,
1052 le32_to_cpu(border), newblock);
1054 cleanup:
1055 if (bh) {
1056 if (buffer_locked(bh))
1057 unlock_buffer(bh);
1058 brelse(bh);
1061 if (err) {
1062 /* free all allocated blocks in error case */
1063 for (i = 0; i < depth; i++) {
1064 if (!ablocks[i])
1065 continue;
1066 ext4_free_blocks(handle, inode, 0, ablocks[i], 1,
1067 EXT4_FREE_BLOCKS_METADATA);
1070 kfree(ablocks);
1072 return err;
1076 * ext4_ext_grow_indepth:
1077 * implements tree growing procedure:
1078 * - allocates new block
1079 * - moves top-level data (index block or leaf) into the new block
1080 * - initializes new top-level, creating index that points to the
1081 * just created block
1083 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1084 struct ext4_ext_path *path,
1085 struct ext4_extent *newext)
1087 struct ext4_ext_path *curp = path;
1088 struct ext4_extent_header *neh;
1089 struct ext4_extent_idx *fidx;
1090 struct buffer_head *bh;
1091 ext4_fsblk_t newblock;
1092 int err = 0;
1094 newblock = ext4_ext_new_meta_block(handle, inode, path, newext, &err);
1095 if (newblock == 0)
1096 return err;
1098 bh = sb_getblk(inode->i_sb, newblock);
1099 if (!bh) {
1100 err = -EIO;
1101 ext4_std_error(inode->i_sb, err);
1102 return err;
1104 lock_buffer(bh);
1106 err = ext4_journal_get_create_access(handle, bh);
1107 if (err) {
1108 unlock_buffer(bh);
1109 goto out;
1112 /* move top-level index/leaf into new block */
1113 memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
1115 /* set size of new block */
1116 neh = ext_block_hdr(bh);
1117 /* old root could have indexes or leaves
1118 * so calculate e_max right way */
1119 if (ext_depth(inode))
1120 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1121 else
1122 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1123 neh->eh_magic = EXT4_EXT_MAGIC;
1124 set_buffer_uptodate(bh);
1125 unlock_buffer(bh);
1127 err = ext4_handle_dirty_metadata(handle, inode, bh);
1128 if (err)
1129 goto out;
1131 /* create index in new top-level index: num,max,pointer */
1132 err = ext4_ext_get_access(handle, inode, curp);
1133 if (err)
1134 goto out;
1136 curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
1137 curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1138 curp->p_hdr->eh_entries = cpu_to_le16(1);
1139 curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
1141 if (path[0].p_hdr->eh_depth)
1142 curp->p_idx->ei_block =
1143 EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
1144 else
1145 curp->p_idx->ei_block =
1146 EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
1147 ext4_idx_store_pblock(curp->p_idx, newblock);
1149 neh = ext_inode_hdr(inode);
1150 fidx = EXT_FIRST_INDEX(neh);
1151 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1152 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1153 le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
1155 neh->eh_depth = cpu_to_le16(path->p_depth + 1);
1156 err = ext4_ext_dirty(handle, inode, curp);
1157 out:
1158 brelse(bh);
1160 return err;
1164 * ext4_ext_create_new_leaf:
1165 * finds empty index and adds new leaf.
1166 * if no free index is found, then it requests in-depth growing.
1168 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1169 struct ext4_ext_path *path,
1170 struct ext4_extent *newext)
1172 struct ext4_ext_path *curp;
1173 int depth, i, err = 0;
1175 repeat:
1176 i = depth = ext_depth(inode);
1178 /* walk up to the tree and look for free index entry */
1179 curp = path + depth;
1180 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1181 i--;
1182 curp--;
1185 /* we use already allocated block for index block,
1186 * so subsequent data blocks should be contiguous */
1187 if (EXT_HAS_FREE_INDEX(curp)) {
1188 /* if we found index with free entry, then use that
1189 * entry: create all needed subtree and add new leaf */
1190 err = ext4_ext_split(handle, inode, path, newext, i);
1191 if (err)
1192 goto out;
1194 /* refill path */
1195 ext4_ext_drop_refs(path);
1196 path = ext4_ext_find_extent(inode,
1197 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1198 path);
1199 if (IS_ERR(path))
1200 err = PTR_ERR(path);
1201 } else {
1202 /* tree is full, time to grow in depth */
1203 err = ext4_ext_grow_indepth(handle, inode, path, newext);
1204 if (err)
1205 goto out;
1207 /* refill path */
1208 ext4_ext_drop_refs(path);
1209 path = ext4_ext_find_extent(inode,
1210 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1211 path);
1212 if (IS_ERR(path)) {
1213 err = PTR_ERR(path);
1214 goto out;
1218 * only first (depth 0 -> 1) produces free space;
1219 * in all other cases we have to split the grown tree
1221 depth = ext_depth(inode);
1222 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1223 /* now we need to split */
1224 goto repeat;
1228 out:
1229 return err;
1233 * search the closest allocated block to the left for *logical
1234 * and returns it at @logical + it's physical address at @phys
1235 * if *logical is the smallest allocated block, the function
1236 * returns 0 at @phys
1237 * return value contains 0 (success) or error code
1240 ext4_ext_search_left(struct inode *inode, struct ext4_ext_path *path,
1241 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1243 struct ext4_extent_idx *ix;
1244 struct ext4_extent *ex;
1245 int depth, ee_len;
1247 if (unlikely(path == NULL)) {
1248 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1249 return -EIO;
1251 depth = path->p_depth;
1252 *phys = 0;
1254 if (depth == 0 && path->p_ext == NULL)
1255 return 0;
1257 /* usually extent in the path covers blocks smaller
1258 * then *logical, but it can be that extent is the
1259 * first one in the file */
1261 ex = path[depth].p_ext;
1262 ee_len = ext4_ext_get_actual_len(ex);
1263 if (*logical < le32_to_cpu(ex->ee_block)) {
1264 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1265 EXT4_ERROR_INODE(inode,
1266 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1267 *logical, le32_to_cpu(ex->ee_block));
1268 return -EIO;
1270 while (--depth >= 0) {
1271 ix = path[depth].p_idx;
1272 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1273 EXT4_ERROR_INODE(inode,
1274 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1275 ix != NULL ? ix->ei_block : 0,
1276 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1277 EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block : 0,
1278 depth);
1279 return -EIO;
1282 return 0;
1285 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1286 EXT4_ERROR_INODE(inode,
1287 "logical %d < ee_block %d + ee_len %d!",
1288 *logical, le32_to_cpu(ex->ee_block), ee_len);
1289 return -EIO;
1292 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1293 *phys = ext_pblock(ex) + ee_len - 1;
1294 return 0;
1298 * search the closest allocated block to the right for *logical
1299 * and returns it at @logical + it's physical address at @phys
1300 * if *logical is the smallest allocated block, the function
1301 * returns 0 at @phys
1302 * return value contains 0 (success) or error code
1305 ext4_ext_search_right(struct inode *inode, struct ext4_ext_path *path,
1306 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1308 struct buffer_head *bh = NULL;
1309 struct ext4_extent_header *eh;
1310 struct ext4_extent_idx *ix;
1311 struct ext4_extent *ex;
1312 ext4_fsblk_t block;
1313 int depth; /* Note, NOT eh_depth; depth from top of tree */
1314 int ee_len;
1316 if (unlikely(path == NULL)) {
1317 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1318 return -EIO;
1320 depth = path->p_depth;
1321 *phys = 0;
1323 if (depth == 0 && path->p_ext == NULL)
1324 return 0;
1326 /* usually extent in the path covers blocks smaller
1327 * then *logical, but it can be that extent is the
1328 * first one in the file */
1330 ex = path[depth].p_ext;
1331 ee_len = ext4_ext_get_actual_len(ex);
1332 if (*logical < le32_to_cpu(ex->ee_block)) {
1333 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1334 EXT4_ERROR_INODE(inode,
1335 "first_extent(path[%d].p_hdr) != ex",
1336 depth);
1337 return -EIO;
1339 while (--depth >= 0) {
1340 ix = path[depth].p_idx;
1341 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1342 EXT4_ERROR_INODE(inode,
1343 "ix != EXT_FIRST_INDEX *logical %d!",
1344 *logical);
1345 return -EIO;
1348 *logical = le32_to_cpu(ex->ee_block);
1349 *phys = ext_pblock(ex);
1350 return 0;
1353 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1354 EXT4_ERROR_INODE(inode,
1355 "logical %d < ee_block %d + ee_len %d!",
1356 *logical, le32_to_cpu(ex->ee_block), ee_len);
1357 return -EIO;
1360 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1361 /* next allocated block in this leaf */
1362 ex++;
1363 *logical = le32_to_cpu(ex->ee_block);
1364 *phys = ext_pblock(ex);
1365 return 0;
1368 /* go up and search for index to the right */
1369 while (--depth >= 0) {
1370 ix = path[depth].p_idx;
1371 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1372 goto got_index;
1375 /* we've gone up to the root and found no index to the right */
1376 return 0;
1378 got_index:
1379 /* we've found index to the right, let's
1380 * follow it and find the closest allocated
1381 * block to the right */
1382 ix++;
1383 block = idx_pblock(ix);
1384 while (++depth < path->p_depth) {
1385 bh = sb_bread(inode->i_sb, block);
1386 if (bh == NULL)
1387 return -EIO;
1388 eh = ext_block_hdr(bh);
1389 /* subtract from p_depth to get proper eh_depth */
1390 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1391 put_bh(bh);
1392 return -EIO;
1394 ix = EXT_FIRST_INDEX(eh);
1395 block = idx_pblock(ix);
1396 put_bh(bh);
1399 bh = sb_bread(inode->i_sb, block);
1400 if (bh == NULL)
1401 return -EIO;
1402 eh = ext_block_hdr(bh);
1403 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1404 put_bh(bh);
1405 return -EIO;
1407 ex = EXT_FIRST_EXTENT(eh);
1408 *logical = le32_to_cpu(ex->ee_block);
1409 *phys = ext_pblock(ex);
1410 put_bh(bh);
1411 return 0;
1415 * ext4_ext_next_allocated_block:
1416 * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1417 * NOTE: it considers block number from index entry as
1418 * allocated block. Thus, index entries have to be consistent
1419 * with leaves.
1421 static ext4_lblk_t
1422 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1424 int depth;
1426 BUG_ON(path == NULL);
1427 depth = path->p_depth;
1429 if (depth == 0 && path->p_ext == NULL)
1430 return EXT_MAX_BLOCK;
1432 while (depth >= 0) {
1433 if (depth == path->p_depth) {
1434 /* leaf */
1435 if (path[depth].p_ext !=
1436 EXT_LAST_EXTENT(path[depth].p_hdr))
1437 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1438 } else {
1439 /* index */
1440 if (path[depth].p_idx !=
1441 EXT_LAST_INDEX(path[depth].p_hdr))
1442 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1444 depth--;
1447 return EXT_MAX_BLOCK;
1451 * ext4_ext_next_leaf_block:
1452 * returns first allocated block from next leaf or EXT_MAX_BLOCK
1454 static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1455 struct ext4_ext_path *path)
1457 int depth;
1459 BUG_ON(path == NULL);
1460 depth = path->p_depth;
1462 /* zero-tree has no leaf blocks at all */
1463 if (depth == 0)
1464 return EXT_MAX_BLOCK;
1466 /* go to index block */
1467 depth--;
1469 while (depth >= 0) {
1470 if (path[depth].p_idx !=
1471 EXT_LAST_INDEX(path[depth].p_hdr))
1472 return (ext4_lblk_t)
1473 le32_to_cpu(path[depth].p_idx[1].ei_block);
1474 depth--;
1477 return EXT_MAX_BLOCK;
1481 * ext4_ext_correct_indexes:
1482 * if leaf gets modified and modified extent is first in the leaf,
1483 * then we have to correct all indexes above.
1484 * TODO: do we need to correct tree in all cases?
1486 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1487 struct ext4_ext_path *path)
1489 struct ext4_extent_header *eh;
1490 int depth = ext_depth(inode);
1491 struct ext4_extent *ex;
1492 __le32 border;
1493 int k, err = 0;
1495 eh = path[depth].p_hdr;
1496 ex = path[depth].p_ext;
1498 if (unlikely(ex == NULL || eh == NULL)) {
1499 EXT4_ERROR_INODE(inode,
1500 "ex %p == NULL or eh %p == NULL", ex, eh);
1501 return -EIO;
1504 if (depth == 0) {
1505 /* there is no tree at all */
1506 return 0;
1509 if (ex != EXT_FIRST_EXTENT(eh)) {
1510 /* we correct tree if first leaf got modified only */
1511 return 0;
1515 * TODO: we need correction if border is smaller than current one
1517 k = depth - 1;
1518 border = path[depth].p_ext->ee_block;
1519 err = ext4_ext_get_access(handle, inode, path + k);
1520 if (err)
1521 return err;
1522 path[k].p_idx->ei_block = border;
1523 err = ext4_ext_dirty(handle, inode, path + k);
1524 if (err)
1525 return err;
1527 while (k--) {
1528 /* change all left-side indexes */
1529 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1530 break;
1531 err = ext4_ext_get_access(handle, inode, path + k);
1532 if (err)
1533 break;
1534 path[k].p_idx->ei_block = border;
1535 err = ext4_ext_dirty(handle, inode, path + k);
1536 if (err)
1537 break;
1540 return err;
1544 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1545 struct ext4_extent *ex2)
1547 unsigned short ext1_ee_len, ext2_ee_len, max_len;
1550 * Make sure that either both extents are uninitialized, or
1551 * both are _not_.
1553 if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1554 return 0;
1556 if (ext4_ext_is_uninitialized(ex1))
1557 max_len = EXT_UNINIT_MAX_LEN;
1558 else
1559 max_len = EXT_INIT_MAX_LEN;
1561 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1562 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1564 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1565 le32_to_cpu(ex2->ee_block))
1566 return 0;
1569 * To allow future support for preallocated extents to be added
1570 * as an RO_COMPAT feature, refuse to merge to extents if
1571 * this can result in the top bit of ee_len being set.
1573 if (ext1_ee_len + ext2_ee_len > max_len)
1574 return 0;
1575 #ifdef AGGRESSIVE_TEST
1576 if (ext1_ee_len >= 4)
1577 return 0;
1578 #endif
1580 if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1581 return 1;
1582 return 0;
1586 * This function tries to merge the "ex" extent to the next extent in the tree.
1587 * It always tries to merge towards right. If you want to merge towards
1588 * left, pass "ex - 1" as argument instead of "ex".
1589 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1590 * 1 if they got merged.
1592 int ext4_ext_try_to_merge(struct inode *inode,
1593 struct ext4_ext_path *path,
1594 struct ext4_extent *ex)
1596 struct ext4_extent_header *eh;
1597 unsigned int depth, len;
1598 int merge_done = 0;
1599 int uninitialized = 0;
1601 depth = ext_depth(inode);
1602 BUG_ON(path[depth].p_hdr == NULL);
1603 eh = path[depth].p_hdr;
1605 while (ex < EXT_LAST_EXTENT(eh)) {
1606 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1607 break;
1608 /* merge with next extent! */
1609 if (ext4_ext_is_uninitialized(ex))
1610 uninitialized = 1;
1611 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1612 + ext4_ext_get_actual_len(ex + 1));
1613 if (uninitialized)
1614 ext4_ext_mark_uninitialized(ex);
1616 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1617 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1618 * sizeof(struct ext4_extent);
1619 memmove(ex + 1, ex + 2, len);
1621 le16_add_cpu(&eh->eh_entries, -1);
1622 merge_done = 1;
1623 WARN_ON(eh->eh_entries == 0);
1624 if (!eh->eh_entries)
1625 ext4_error(inode->i_sb,
1626 "inode#%lu, eh->eh_entries = 0!",
1627 inode->i_ino);
1630 return merge_done;
1634 * check if a portion of the "newext" extent overlaps with an
1635 * existing extent.
1637 * If there is an overlap discovered, it updates the length of the newext
1638 * such that there will be no overlap, and then returns 1.
1639 * If there is no overlap found, it returns 0.
1641 unsigned int ext4_ext_check_overlap(struct inode *inode,
1642 struct ext4_extent *newext,
1643 struct ext4_ext_path *path)
1645 ext4_lblk_t b1, b2;
1646 unsigned int depth, len1;
1647 unsigned int ret = 0;
1649 b1 = le32_to_cpu(newext->ee_block);
1650 len1 = ext4_ext_get_actual_len(newext);
1651 depth = ext_depth(inode);
1652 if (!path[depth].p_ext)
1653 goto out;
1654 b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1657 * get the next allocated block if the extent in the path
1658 * is before the requested block(s)
1660 if (b2 < b1) {
1661 b2 = ext4_ext_next_allocated_block(path);
1662 if (b2 == EXT_MAX_BLOCK)
1663 goto out;
1666 /* check for wrap through zero on extent logical start block*/
1667 if (b1 + len1 < b1) {
1668 len1 = EXT_MAX_BLOCK - b1;
1669 newext->ee_len = cpu_to_le16(len1);
1670 ret = 1;
1673 /* check for overlap */
1674 if (b1 + len1 > b2) {
1675 newext->ee_len = cpu_to_le16(b2 - b1);
1676 ret = 1;
1678 out:
1679 return ret;
1683 * ext4_ext_insert_extent:
1684 * tries to merge requsted extent into the existing extent or
1685 * inserts requested extent as new one into the tree,
1686 * creating new leaf in the no-space case.
1688 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1689 struct ext4_ext_path *path,
1690 struct ext4_extent *newext, int flag)
1692 struct ext4_extent_header *eh;
1693 struct ext4_extent *ex, *fex;
1694 struct ext4_extent *nearex; /* nearest extent */
1695 struct ext4_ext_path *npath = NULL;
1696 int depth, len, err;
1697 ext4_lblk_t next;
1698 unsigned uninitialized = 0;
1700 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1701 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1702 return -EIO;
1704 depth = ext_depth(inode);
1705 ex = path[depth].p_ext;
1706 if (unlikely(path[depth].p_hdr == NULL)) {
1707 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1708 return -EIO;
1711 /* try to insert block into found extent and return */
1712 if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
1713 && ext4_can_extents_be_merged(inode, ex, newext)) {
1714 ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
1715 ext4_ext_is_uninitialized(newext),
1716 ext4_ext_get_actual_len(newext),
1717 le32_to_cpu(ex->ee_block),
1718 ext4_ext_is_uninitialized(ex),
1719 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1720 err = ext4_ext_get_access(handle, inode, path + depth);
1721 if (err)
1722 return err;
1725 * ext4_can_extents_be_merged should have checked that either
1726 * both extents are uninitialized, or both aren't. Thus we
1727 * need to check only one of them here.
1729 if (ext4_ext_is_uninitialized(ex))
1730 uninitialized = 1;
1731 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1732 + ext4_ext_get_actual_len(newext));
1733 if (uninitialized)
1734 ext4_ext_mark_uninitialized(ex);
1735 eh = path[depth].p_hdr;
1736 nearex = ex;
1737 goto merge;
1740 repeat:
1741 depth = ext_depth(inode);
1742 eh = path[depth].p_hdr;
1743 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1744 goto has_space;
1746 /* probably next leaf has space for us? */
1747 fex = EXT_LAST_EXTENT(eh);
1748 next = ext4_ext_next_leaf_block(inode, path);
1749 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1750 && next != EXT_MAX_BLOCK) {
1751 ext_debug("next leaf block - %d\n", next);
1752 BUG_ON(npath != NULL);
1753 npath = ext4_ext_find_extent(inode, next, NULL);
1754 if (IS_ERR(npath))
1755 return PTR_ERR(npath);
1756 BUG_ON(npath->p_depth != path->p_depth);
1757 eh = npath[depth].p_hdr;
1758 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1759 ext_debug("next leaf isnt full(%d)\n",
1760 le16_to_cpu(eh->eh_entries));
1761 path = npath;
1762 goto repeat;
1764 ext_debug("next leaf has no free space(%d,%d)\n",
1765 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1769 * There is no free space in the found leaf.
1770 * We're gonna add a new leaf in the tree.
1772 err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1773 if (err)
1774 goto cleanup;
1775 depth = ext_depth(inode);
1776 eh = path[depth].p_hdr;
1778 has_space:
1779 nearex = path[depth].p_ext;
1781 err = ext4_ext_get_access(handle, inode, path + depth);
1782 if (err)
1783 goto cleanup;
1785 if (!nearex) {
1786 /* there is no extent in this leaf, create first one */
1787 ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
1788 le32_to_cpu(newext->ee_block),
1789 ext_pblock(newext),
1790 ext4_ext_is_uninitialized(newext),
1791 ext4_ext_get_actual_len(newext));
1792 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1793 } else if (le32_to_cpu(newext->ee_block)
1794 > le32_to_cpu(nearex->ee_block)) {
1795 /* BUG_ON(newext->ee_block == nearex->ee_block); */
1796 if (nearex != EXT_LAST_EXTENT(eh)) {
1797 len = EXT_MAX_EXTENT(eh) - nearex;
1798 len = (len - 1) * sizeof(struct ext4_extent);
1799 len = len < 0 ? 0 : len;
1800 ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
1801 "move %d from 0x%p to 0x%p\n",
1802 le32_to_cpu(newext->ee_block),
1803 ext_pblock(newext),
1804 ext4_ext_is_uninitialized(newext),
1805 ext4_ext_get_actual_len(newext),
1806 nearex, len, nearex + 1, nearex + 2);
1807 memmove(nearex + 2, nearex + 1, len);
1809 path[depth].p_ext = nearex + 1;
1810 } else {
1811 BUG_ON(newext->ee_block == nearex->ee_block);
1812 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1813 len = len < 0 ? 0 : len;
1814 ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
1815 "move %d from 0x%p to 0x%p\n",
1816 le32_to_cpu(newext->ee_block),
1817 ext_pblock(newext),
1818 ext4_ext_is_uninitialized(newext),
1819 ext4_ext_get_actual_len(newext),
1820 nearex, len, nearex + 1, nearex + 2);
1821 memmove(nearex + 1, nearex, len);
1822 path[depth].p_ext = nearex;
1825 le16_add_cpu(&eh->eh_entries, 1);
1826 nearex = path[depth].p_ext;
1827 nearex->ee_block = newext->ee_block;
1828 ext4_ext_store_pblock(nearex, ext_pblock(newext));
1829 nearex->ee_len = newext->ee_len;
1831 merge:
1832 /* try to merge extents to the right */
1833 if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
1834 ext4_ext_try_to_merge(inode, path, nearex);
1836 /* try to merge extents to the left */
1838 /* time to correct all indexes above */
1839 err = ext4_ext_correct_indexes(handle, inode, path);
1840 if (err)
1841 goto cleanup;
1843 err = ext4_ext_dirty(handle, inode, path + depth);
1845 cleanup:
1846 if (npath) {
1847 ext4_ext_drop_refs(npath);
1848 kfree(npath);
1850 ext4_ext_invalidate_cache(inode);
1851 return err;
1854 int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1855 ext4_lblk_t num, ext_prepare_callback func,
1856 void *cbdata)
1858 struct ext4_ext_path *path = NULL;
1859 struct ext4_ext_cache cbex;
1860 struct ext4_extent *ex;
1861 ext4_lblk_t next, start = 0, end = 0;
1862 ext4_lblk_t last = block + num;
1863 int depth, exists, err = 0;
1865 BUG_ON(func == NULL);
1866 BUG_ON(inode == NULL);
1868 while (block < last && block != EXT_MAX_BLOCK) {
1869 num = last - block;
1870 /* find extent for this block */
1871 down_read(&EXT4_I(inode)->i_data_sem);
1872 path = ext4_ext_find_extent(inode, block, path);
1873 up_read(&EXT4_I(inode)->i_data_sem);
1874 if (IS_ERR(path)) {
1875 err = PTR_ERR(path);
1876 path = NULL;
1877 break;
1880 depth = ext_depth(inode);
1881 if (unlikely(path[depth].p_hdr == NULL)) {
1882 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1883 err = -EIO;
1884 break;
1886 ex = path[depth].p_ext;
1887 next = ext4_ext_next_allocated_block(path);
1889 exists = 0;
1890 if (!ex) {
1891 /* there is no extent yet, so try to allocate
1892 * all requested space */
1893 start = block;
1894 end = block + num;
1895 } else if (le32_to_cpu(ex->ee_block) > block) {
1896 /* need to allocate space before found extent */
1897 start = block;
1898 end = le32_to_cpu(ex->ee_block);
1899 if (block + num < end)
1900 end = block + num;
1901 } else if (block >= le32_to_cpu(ex->ee_block)
1902 + ext4_ext_get_actual_len(ex)) {
1903 /* need to allocate space after found extent */
1904 start = block;
1905 end = block + num;
1906 if (end >= next)
1907 end = next;
1908 } else if (block >= le32_to_cpu(ex->ee_block)) {
1910 * some part of requested space is covered
1911 * by found extent
1913 start = block;
1914 end = le32_to_cpu(ex->ee_block)
1915 + ext4_ext_get_actual_len(ex);
1916 if (block + num < end)
1917 end = block + num;
1918 exists = 1;
1919 } else {
1920 BUG();
1922 BUG_ON(end <= start);
1924 if (!exists) {
1925 cbex.ec_block = start;
1926 cbex.ec_len = end - start;
1927 cbex.ec_start = 0;
1928 cbex.ec_type = EXT4_EXT_CACHE_GAP;
1929 } else {
1930 cbex.ec_block = le32_to_cpu(ex->ee_block);
1931 cbex.ec_len = ext4_ext_get_actual_len(ex);
1932 cbex.ec_start = ext_pblock(ex);
1933 cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1936 if (unlikely(cbex.ec_len == 0)) {
1937 EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
1938 err = -EIO;
1939 break;
1941 err = func(inode, path, &cbex, ex, cbdata);
1942 ext4_ext_drop_refs(path);
1944 if (err < 0)
1945 break;
1947 if (err == EXT_REPEAT)
1948 continue;
1949 else if (err == EXT_BREAK) {
1950 err = 0;
1951 break;
1954 if (ext_depth(inode) != depth) {
1955 /* depth was changed. we have to realloc path */
1956 kfree(path);
1957 path = NULL;
1960 block = cbex.ec_block + cbex.ec_len;
1963 if (path) {
1964 ext4_ext_drop_refs(path);
1965 kfree(path);
1968 return err;
1971 static void
1972 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1973 __u32 len, ext4_fsblk_t start, int type)
1975 struct ext4_ext_cache *cex;
1976 BUG_ON(len == 0);
1977 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1978 cex = &EXT4_I(inode)->i_cached_extent;
1979 cex->ec_type = type;
1980 cex->ec_block = block;
1981 cex->ec_len = len;
1982 cex->ec_start = start;
1983 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1987 * ext4_ext_put_gap_in_cache:
1988 * calculate boundaries of the gap that the requested block fits into
1989 * and cache this gap
1991 static void
1992 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1993 ext4_lblk_t block)
1995 int depth = ext_depth(inode);
1996 unsigned long len;
1997 ext4_lblk_t lblock;
1998 struct ext4_extent *ex;
2000 ex = path[depth].p_ext;
2001 if (ex == NULL) {
2002 /* there is no extent yet, so gap is [0;-] */
2003 lblock = 0;
2004 len = EXT_MAX_BLOCK;
2005 ext_debug("cache gap(whole file):");
2006 } else if (block < le32_to_cpu(ex->ee_block)) {
2007 lblock = block;
2008 len = le32_to_cpu(ex->ee_block) - block;
2009 ext_debug("cache gap(before): %u [%u:%u]",
2010 block,
2011 le32_to_cpu(ex->ee_block),
2012 ext4_ext_get_actual_len(ex));
2013 } else if (block >= le32_to_cpu(ex->ee_block)
2014 + ext4_ext_get_actual_len(ex)) {
2015 ext4_lblk_t next;
2016 lblock = le32_to_cpu(ex->ee_block)
2017 + ext4_ext_get_actual_len(ex);
2019 next = ext4_ext_next_allocated_block(path);
2020 ext_debug("cache gap(after): [%u:%u] %u",
2021 le32_to_cpu(ex->ee_block),
2022 ext4_ext_get_actual_len(ex),
2023 block);
2024 BUG_ON(next == lblock);
2025 len = next - lblock;
2026 } else {
2027 lblock = len = 0;
2028 BUG();
2031 ext_debug(" -> %u:%lu\n", lblock, len);
2032 ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
2035 static int
2036 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
2037 struct ext4_extent *ex)
2039 struct ext4_ext_cache *cex;
2040 int ret = EXT4_EXT_CACHE_NO;
2043 * We borrow i_block_reservation_lock to protect i_cached_extent
2045 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
2046 cex = &EXT4_I(inode)->i_cached_extent;
2048 /* has cache valid data? */
2049 if (cex->ec_type == EXT4_EXT_CACHE_NO)
2050 goto errout;
2052 BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
2053 cex->ec_type != EXT4_EXT_CACHE_EXTENT);
2054 if (in_range(block, cex->ec_block, cex->ec_len)) {
2055 ex->ee_block = cpu_to_le32(cex->ec_block);
2056 ext4_ext_store_pblock(ex, cex->ec_start);
2057 ex->ee_len = cpu_to_le16(cex->ec_len);
2058 ext_debug("%u cached by %u:%u:%llu\n",
2059 block,
2060 cex->ec_block, cex->ec_len, cex->ec_start);
2061 ret = cex->ec_type;
2063 errout:
2064 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2065 return ret;
2069 * ext4_ext_rm_idx:
2070 * removes index from the index block.
2071 * It's used in truncate case only, thus all requests are for
2072 * last index in the block only.
2074 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2075 struct ext4_ext_path *path)
2077 int err;
2078 ext4_fsblk_t leaf;
2080 /* free index block */
2081 path--;
2082 leaf = idx_pblock(path->p_idx);
2083 if (unlikely(path->p_hdr->eh_entries == 0)) {
2084 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2085 return -EIO;
2087 err = ext4_ext_get_access(handle, inode, path);
2088 if (err)
2089 return err;
2090 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2091 err = ext4_ext_dirty(handle, inode, path);
2092 if (err)
2093 return err;
2094 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2095 ext4_free_blocks(handle, inode, 0, leaf, 1,
2096 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2097 return err;
2101 * ext4_ext_calc_credits_for_single_extent:
2102 * This routine returns max. credits that needed to insert an extent
2103 * to the extent tree.
2104 * When pass the actual path, the caller should calculate credits
2105 * under i_data_sem.
2107 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2108 struct ext4_ext_path *path)
2110 if (path) {
2111 int depth = ext_depth(inode);
2112 int ret = 0;
2114 /* probably there is space in leaf? */
2115 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2116 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2119 * There are some space in the leaf tree, no
2120 * need to account for leaf block credit
2122 * bitmaps and block group descriptor blocks
2123 * and other metadat blocks still need to be
2124 * accounted.
2126 /* 1 bitmap, 1 block group descriptor */
2127 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2128 return ret;
2132 return ext4_chunk_trans_blocks(inode, nrblocks);
2136 * How many index/leaf blocks need to change/allocate to modify nrblocks?
2138 * if nrblocks are fit in a single extent (chunk flag is 1), then
2139 * in the worse case, each tree level index/leaf need to be changed
2140 * if the tree split due to insert a new extent, then the old tree
2141 * index/leaf need to be updated too
2143 * If the nrblocks are discontiguous, they could cause
2144 * the whole tree split more than once, but this is really rare.
2146 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2148 int index;
2149 int depth = ext_depth(inode);
2151 if (chunk)
2152 index = depth * 2;
2153 else
2154 index = depth * 3;
2156 return index;
2159 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2160 struct ext4_extent *ex,
2161 ext4_lblk_t from, ext4_lblk_t to)
2163 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2164 int flags = EXT4_FREE_BLOCKS_FORGET;
2166 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2167 flags |= EXT4_FREE_BLOCKS_METADATA;
2168 #ifdef EXTENTS_STATS
2170 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2171 spin_lock(&sbi->s_ext_stats_lock);
2172 sbi->s_ext_blocks += ee_len;
2173 sbi->s_ext_extents++;
2174 if (ee_len < sbi->s_ext_min)
2175 sbi->s_ext_min = ee_len;
2176 if (ee_len > sbi->s_ext_max)
2177 sbi->s_ext_max = ee_len;
2178 if (ext_depth(inode) > sbi->s_depth_max)
2179 sbi->s_depth_max = ext_depth(inode);
2180 spin_unlock(&sbi->s_ext_stats_lock);
2182 #endif
2183 if (from >= le32_to_cpu(ex->ee_block)
2184 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2185 /* tail removal */
2186 ext4_lblk_t num;
2187 ext4_fsblk_t start;
2189 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2190 start = ext_pblock(ex) + ee_len - num;
2191 ext_debug("free last %u blocks starting %llu\n", num, start);
2192 ext4_free_blocks(handle, inode, 0, start, num, flags);
2193 } else if (from == le32_to_cpu(ex->ee_block)
2194 && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2195 printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
2196 from, to, le32_to_cpu(ex->ee_block), ee_len);
2197 } else {
2198 printk(KERN_INFO "strange request: removal(2) "
2199 "%u-%u from %u:%u\n",
2200 from, to, le32_to_cpu(ex->ee_block), ee_len);
2202 return 0;
2205 static int
2206 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2207 struct ext4_ext_path *path, ext4_lblk_t start)
2209 int err = 0, correct_index = 0;
2210 int depth = ext_depth(inode), credits;
2211 struct ext4_extent_header *eh;
2212 ext4_lblk_t a, b, block;
2213 unsigned num;
2214 ext4_lblk_t ex_ee_block;
2215 unsigned short ex_ee_len;
2216 unsigned uninitialized = 0;
2217 struct ext4_extent *ex;
2219 /* the header must be checked already in ext4_ext_remove_space() */
2220 ext_debug("truncate since %u in leaf\n", start);
2221 if (!path[depth].p_hdr)
2222 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2223 eh = path[depth].p_hdr;
2224 if (unlikely(path[depth].p_hdr == NULL)) {
2225 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2226 return -EIO;
2228 /* find where to start removing */
2229 ex = EXT_LAST_EXTENT(eh);
2231 ex_ee_block = le32_to_cpu(ex->ee_block);
2232 ex_ee_len = ext4_ext_get_actual_len(ex);
2234 while (ex >= EXT_FIRST_EXTENT(eh) &&
2235 ex_ee_block + ex_ee_len > start) {
2237 if (ext4_ext_is_uninitialized(ex))
2238 uninitialized = 1;
2239 else
2240 uninitialized = 0;
2242 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2243 uninitialized, ex_ee_len);
2244 path[depth].p_ext = ex;
2246 a = ex_ee_block > start ? ex_ee_block : start;
2247 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
2248 ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
2250 ext_debug(" border %u:%u\n", a, b);
2252 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
2253 block = 0;
2254 num = 0;
2255 BUG();
2256 } else if (a != ex_ee_block) {
2257 /* remove tail of the extent */
2258 block = ex_ee_block;
2259 num = a - block;
2260 } else if (b != ex_ee_block + ex_ee_len - 1) {
2261 /* remove head of the extent */
2262 block = a;
2263 num = b - a;
2264 /* there is no "make a hole" API yet */
2265 BUG();
2266 } else {
2267 /* remove whole extent: excellent! */
2268 block = ex_ee_block;
2269 num = 0;
2270 BUG_ON(a != ex_ee_block);
2271 BUG_ON(b != ex_ee_block + ex_ee_len - 1);
2275 * 3 for leaf, sb, and inode plus 2 (bmap and group
2276 * descriptor) for each block group; assume two block
2277 * groups plus ex_ee_len/blocks_per_block_group for
2278 * the worst case
2280 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2281 if (ex == EXT_FIRST_EXTENT(eh)) {
2282 correct_index = 1;
2283 credits += (ext_depth(inode)) + 1;
2285 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2287 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2288 if (err)
2289 goto out;
2291 err = ext4_ext_get_access(handle, inode, path + depth);
2292 if (err)
2293 goto out;
2295 err = ext4_remove_blocks(handle, inode, ex, a, b);
2296 if (err)
2297 goto out;
2299 if (num == 0) {
2300 /* this extent is removed; mark slot entirely unused */
2301 ext4_ext_store_pblock(ex, 0);
2302 le16_add_cpu(&eh->eh_entries, -1);
2305 ex->ee_block = cpu_to_le32(block);
2306 ex->ee_len = cpu_to_le16(num);
2308 * Do not mark uninitialized if all the blocks in the
2309 * extent have been removed.
2311 if (uninitialized && num)
2312 ext4_ext_mark_uninitialized(ex);
2314 err = ext4_ext_dirty(handle, inode, path + depth);
2315 if (err)
2316 goto out;
2318 ext_debug("new extent: %u:%u:%llu\n", block, num,
2319 ext_pblock(ex));
2320 ex--;
2321 ex_ee_block = le32_to_cpu(ex->ee_block);
2322 ex_ee_len = ext4_ext_get_actual_len(ex);
2325 if (correct_index && eh->eh_entries)
2326 err = ext4_ext_correct_indexes(handle, inode, path);
2328 /* if this leaf is free, then we should
2329 * remove it from index block above */
2330 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2331 err = ext4_ext_rm_idx(handle, inode, path + depth);
2333 out:
2334 return err;
2338 * ext4_ext_more_to_rm:
2339 * returns 1 if current index has to be freed (even partial)
2341 static int
2342 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2344 BUG_ON(path->p_idx == NULL);
2346 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2347 return 0;
2350 * if truncate on deeper level happened, it wasn't partial,
2351 * so we have to consider current index for truncation
2353 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2354 return 0;
2355 return 1;
2358 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2360 struct super_block *sb = inode->i_sb;
2361 int depth = ext_depth(inode);
2362 struct ext4_ext_path *path;
2363 handle_t *handle;
2364 int i = 0, err = 0;
2366 ext_debug("truncate since %u\n", start);
2368 /* probably first extent we're gonna free will be last in block */
2369 handle = ext4_journal_start(inode, depth + 1);
2370 if (IS_ERR(handle))
2371 return PTR_ERR(handle);
2373 ext4_ext_invalidate_cache(inode);
2376 * We start scanning from right side, freeing all the blocks
2377 * after i_size and walking into the tree depth-wise.
2379 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2380 if (path == NULL) {
2381 ext4_journal_stop(handle);
2382 return -ENOMEM;
2384 path[0].p_hdr = ext_inode_hdr(inode);
2385 if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2386 err = -EIO;
2387 goto out;
2389 path[0].p_depth = depth;
2391 while (i >= 0 && err == 0) {
2392 if (i == depth) {
2393 /* this is leaf block */
2394 err = ext4_ext_rm_leaf(handle, inode, path, start);
2395 /* root level has p_bh == NULL, brelse() eats this */
2396 brelse(path[i].p_bh);
2397 path[i].p_bh = NULL;
2398 i--;
2399 continue;
2402 /* this is index block */
2403 if (!path[i].p_hdr) {
2404 ext_debug("initialize header\n");
2405 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2408 if (!path[i].p_idx) {
2409 /* this level hasn't been touched yet */
2410 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2411 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2412 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2413 path[i].p_hdr,
2414 le16_to_cpu(path[i].p_hdr->eh_entries));
2415 } else {
2416 /* we were already here, see at next index */
2417 path[i].p_idx--;
2420 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2421 i, EXT_FIRST_INDEX(path[i].p_hdr),
2422 path[i].p_idx);
2423 if (ext4_ext_more_to_rm(path + i)) {
2424 struct buffer_head *bh;
2425 /* go to the next level */
2426 ext_debug("move to level %d (block %llu)\n",
2427 i + 1, idx_pblock(path[i].p_idx));
2428 memset(path + i + 1, 0, sizeof(*path));
2429 bh = sb_bread(sb, idx_pblock(path[i].p_idx));
2430 if (!bh) {
2431 /* should we reset i_size? */
2432 err = -EIO;
2433 break;
2435 if (WARN_ON(i + 1 > depth)) {
2436 err = -EIO;
2437 break;
2439 if (ext4_ext_check(inode, ext_block_hdr(bh),
2440 depth - i - 1)) {
2441 err = -EIO;
2442 break;
2444 path[i + 1].p_bh = bh;
2446 /* save actual number of indexes since this
2447 * number is changed at the next iteration */
2448 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2449 i++;
2450 } else {
2451 /* we finished processing this index, go up */
2452 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2453 /* index is empty, remove it;
2454 * handle must be already prepared by the
2455 * truncatei_leaf() */
2456 err = ext4_ext_rm_idx(handle, inode, path + i);
2458 /* root level has p_bh == NULL, brelse() eats this */
2459 brelse(path[i].p_bh);
2460 path[i].p_bh = NULL;
2461 i--;
2462 ext_debug("return to level %d\n", i);
2466 /* TODO: flexible tree reduction should be here */
2467 if (path->p_hdr->eh_entries == 0) {
2469 * truncate to zero freed all the tree,
2470 * so we need to correct eh_depth
2472 err = ext4_ext_get_access(handle, inode, path);
2473 if (err == 0) {
2474 ext_inode_hdr(inode)->eh_depth = 0;
2475 ext_inode_hdr(inode)->eh_max =
2476 cpu_to_le16(ext4_ext_space_root(inode, 0));
2477 err = ext4_ext_dirty(handle, inode, path);
2480 out:
2481 ext4_ext_drop_refs(path);
2482 kfree(path);
2483 ext4_journal_stop(handle);
2485 return err;
2489 * called at mount time
2491 void ext4_ext_init(struct super_block *sb)
2494 * possible initialization would be here
2497 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2498 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
2499 printk(KERN_INFO "EXT4-fs: file extents enabled");
2500 #ifdef AGGRESSIVE_TEST
2501 printk(", aggressive tests");
2502 #endif
2503 #ifdef CHECK_BINSEARCH
2504 printk(", check binsearch");
2505 #endif
2506 #ifdef EXTENTS_STATS
2507 printk(", stats");
2508 #endif
2509 printk("\n");
2510 #endif
2511 #ifdef EXTENTS_STATS
2512 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2513 EXT4_SB(sb)->s_ext_min = 1 << 30;
2514 EXT4_SB(sb)->s_ext_max = 0;
2515 #endif
2520 * called at umount time
2522 void ext4_ext_release(struct super_block *sb)
2524 if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2525 return;
2527 #ifdef EXTENTS_STATS
2528 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2529 struct ext4_sb_info *sbi = EXT4_SB(sb);
2530 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2531 sbi->s_ext_blocks, sbi->s_ext_extents,
2532 sbi->s_ext_blocks / sbi->s_ext_extents);
2533 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2534 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2536 #endif
2539 static void bi_complete(struct bio *bio, int error)
2541 complete((struct completion *)bio->bi_private);
2544 /* FIXME!! we need to try to merge to left or right after zero-out */
2545 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2547 int ret;
2548 struct bio *bio;
2549 int blkbits, blocksize;
2550 sector_t ee_pblock;
2551 struct completion event;
2552 unsigned int ee_len, len, done, offset;
2555 blkbits = inode->i_blkbits;
2556 blocksize = inode->i_sb->s_blocksize;
2557 ee_len = ext4_ext_get_actual_len(ex);
2558 ee_pblock = ext_pblock(ex);
2560 /* convert ee_pblock to 512 byte sectors */
2561 ee_pblock = ee_pblock << (blkbits - 9);
2563 while (ee_len > 0) {
2565 if (ee_len > BIO_MAX_PAGES)
2566 len = BIO_MAX_PAGES;
2567 else
2568 len = ee_len;
2570 bio = bio_alloc(GFP_NOIO, len);
2571 if (!bio)
2572 return -ENOMEM;
2574 bio->bi_sector = ee_pblock;
2575 bio->bi_bdev = inode->i_sb->s_bdev;
2577 done = 0;
2578 offset = 0;
2579 while (done < len) {
2580 ret = bio_add_page(bio, ZERO_PAGE(0),
2581 blocksize, offset);
2582 if (ret != blocksize) {
2584 * We can't add any more pages because of
2585 * hardware limitations. Start a new bio.
2587 break;
2589 done++;
2590 offset += blocksize;
2591 if (offset >= PAGE_CACHE_SIZE)
2592 offset = 0;
2595 init_completion(&event);
2596 bio->bi_private = &event;
2597 bio->bi_end_io = bi_complete;
2598 submit_bio(WRITE, bio);
2599 wait_for_completion(&event);
2601 if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) {
2602 bio_put(bio);
2603 return -EIO;
2605 bio_put(bio);
2606 ee_len -= done;
2607 ee_pblock += done << (blkbits - 9);
2609 return 0;
2612 #define EXT4_EXT_ZERO_LEN 7
2614 * This function is called by ext4_ext_get_blocks() if someone tries to write
2615 * to an uninitialized extent. It may result in splitting the uninitialized
2616 * extent into multiple extents (upto three - one initialized and two
2617 * uninitialized).
2618 * There are three possibilities:
2619 * a> There is no split required: Entire extent should be initialized
2620 * b> Splits in two extents: Write is happening at either end of the extent
2621 * c> Splits in three extents: Somone is writing in middle of the extent
2623 static int ext4_ext_convert_to_initialized(handle_t *handle,
2624 struct inode *inode,
2625 struct ext4_ext_path *path,
2626 ext4_lblk_t iblock,
2627 unsigned int max_blocks)
2629 struct ext4_extent *ex, newex, orig_ex;
2630 struct ext4_extent *ex1 = NULL;
2631 struct ext4_extent *ex2 = NULL;
2632 struct ext4_extent *ex3 = NULL;
2633 struct ext4_extent_header *eh;
2634 ext4_lblk_t ee_block, eof_block;
2635 unsigned int allocated, ee_len, depth;
2636 ext4_fsblk_t newblock;
2637 int err = 0;
2638 int ret = 0;
2639 int may_zeroout;
2641 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
2642 "block %llu, max_blocks %u\n", inode->i_ino,
2643 (unsigned long long)iblock, max_blocks);
2645 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2646 inode->i_sb->s_blocksize_bits;
2647 if (eof_block < iblock + max_blocks)
2648 eof_block = iblock + max_blocks;
2650 depth = ext_depth(inode);
2651 eh = path[depth].p_hdr;
2652 ex = path[depth].p_ext;
2653 ee_block = le32_to_cpu(ex->ee_block);
2654 ee_len = ext4_ext_get_actual_len(ex);
2655 allocated = ee_len - (iblock - ee_block);
2656 newblock = iblock - ee_block + ext_pblock(ex);
2658 ex2 = ex;
2659 orig_ex.ee_block = ex->ee_block;
2660 orig_ex.ee_len = cpu_to_le16(ee_len);
2661 ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2664 * It is safe to convert extent to initialized via explicit
2665 * zeroout only if extent is fully insde i_size or new_size.
2667 may_zeroout = ee_block + ee_len <= eof_block;
2669 err = ext4_ext_get_access(handle, inode, path + depth);
2670 if (err)
2671 goto out;
2672 /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
2673 if (ee_len <= 2*EXT4_EXT_ZERO_LEN && may_zeroout) {
2674 err = ext4_ext_zeroout(inode, &orig_ex);
2675 if (err)
2676 goto fix_extent_len;
2677 /* update the extent length and mark as initialized */
2678 ex->ee_block = orig_ex.ee_block;
2679 ex->ee_len = orig_ex.ee_len;
2680 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2681 ext4_ext_dirty(handle, inode, path + depth);
2682 /* zeroed the full extent */
2683 return allocated;
2686 /* ex1: ee_block to iblock - 1 : uninitialized */
2687 if (iblock > ee_block) {
2688 ex1 = ex;
2689 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2690 ext4_ext_mark_uninitialized(ex1);
2691 ex2 = &newex;
2694 * for sanity, update the length of the ex2 extent before
2695 * we insert ex3, if ex1 is NULL. This is to avoid temporary
2696 * overlap of blocks.
2698 if (!ex1 && allocated > max_blocks)
2699 ex2->ee_len = cpu_to_le16(max_blocks);
2700 /* ex3: to ee_block + ee_len : uninitialised */
2701 if (allocated > max_blocks) {
2702 unsigned int newdepth;
2703 /* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
2704 if (allocated <= EXT4_EXT_ZERO_LEN && may_zeroout) {
2706 * iblock == ee_block is handled by the zerouout
2707 * at the beginning.
2708 * Mark first half uninitialized.
2709 * Mark second half initialized and zero out the
2710 * initialized extent
2712 ex->ee_block = orig_ex.ee_block;
2713 ex->ee_len = cpu_to_le16(ee_len - allocated);
2714 ext4_ext_mark_uninitialized(ex);
2715 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2716 ext4_ext_dirty(handle, inode, path + depth);
2718 ex3 = &newex;
2719 ex3->ee_block = cpu_to_le32(iblock);
2720 ext4_ext_store_pblock(ex3, newblock);
2721 ex3->ee_len = cpu_to_le16(allocated);
2722 err = ext4_ext_insert_extent(handle, inode, path,
2723 ex3, 0);
2724 if (err == -ENOSPC) {
2725 err = ext4_ext_zeroout(inode, &orig_ex);
2726 if (err)
2727 goto fix_extent_len;
2728 ex->ee_block = orig_ex.ee_block;
2729 ex->ee_len = orig_ex.ee_len;
2730 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2731 ext4_ext_dirty(handle, inode, path + depth);
2732 /* blocks available from iblock */
2733 return allocated;
2735 } else if (err)
2736 goto fix_extent_len;
2739 * We need to zero out the second half because
2740 * an fallocate request can update file size and
2741 * converting the second half to initialized extent
2742 * implies that we can leak some junk data to user
2743 * space.
2745 err = ext4_ext_zeroout(inode, ex3);
2746 if (err) {
2748 * We should actually mark the
2749 * second half as uninit and return error
2750 * Insert would have changed the extent
2752 depth = ext_depth(inode);
2753 ext4_ext_drop_refs(path);
2754 path = ext4_ext_find_extent(inode,
2755 iblock, path);
2756 if (IS_ERR(path)) {
2757 err = PTR_ERR(path);
2758 return err;
2760 /* get the second half extent details */
2761 ex = path[depth].p_ext;
2762 err = ext4_ext_get_access(handle, inode,
2763 path + depth);
2764 if (err)
2765 return err;
2766 ext4_ext_mark_uninitialized(ex);
2767 ext4_ext_dirty(handle, inode, path + depth);
2768 return err;
2771 /* zeroed the second half */
2772 return allocated;
2774 ex3 = &newex;
2775 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2776 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2777 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2778 ext4_ext_mark_uninitialized(ex3);
2779 err = ext4_ext_insert_extent(handle, inode, path, ex3, 0);
2780 if (err == -ENOSPC && may_zeroout) {
2781 err = ext4_ext_zeroout(inode, &orig_ex);
2782 if (err)
2783 goto fix_extent_len;
2784 /* update the extent length and mark as initialized */
2785 ex->ee_block = orig_ex.ee_block;
2786 ex->ee_len = orig_ex.ee_len;
2787 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2788 ext4_ext_dirty(handle, inode, path + depth);
2789 /* zeroed the full extent */
2790 /* blocks available from iblock */
2791 return allocated;
2793 } else if (err)
2794 goto fix_extent_len;
2796 * The depth, and hence eh & ex might change
2797 * as part of the insert above.
2799 newdepth = ext_depth(inode);
2801 * update the extent length after successful insert of the
2802 * split extent
2804 ee_len -= ext4_ext_get_actual_len(ex3);
2805 orig_ex.ee_len = cpu_to_le16(ee_len);
2806 may_zeroout = ee_block + ee_len <= eof_block;
2808 depth = newdepth;
2809 ext4_ext_drop_refs(path);
2810 path = ext4_ext_find_extent(inode, iblock, path);
2811 if (IS_ERR(path)) {
2812 err = PTR_ERR(path);
2813 goto out;
2815 eh = path[depth].p_hdr;
2816 ex = path[depth].p_ext;
2817 if (ex2 != &newex)
2818 ex2 = ex;
2820 err = ext4_ext_get_access(handle, inode, path + depth);
2821 if (err)
2822 goto out;
2824 allocated = max_blocks;
2826 /* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
2827 * to insert a extent in the middle zerout directly
2828 * otherwise give the extent a chance to merge to left
2830 if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
2831 iblock != ee_block && may_zeroout) {
2832 err = ext4_ext_zeroout(inode, &orig_ex);
2833 if (err)
2834 goto fix_extent_len;
2835 /* update the extent length and mark as initialized */
2836 ex->ee_block = orig_ex.ee_block;
2837 ex->ee_len = orig_ex.ee_len;
2838 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2839 ext4_ext_dirty(handle, inode, path + depth);
2840 /* zero out the first half */
2841 /* blocks available from iblock */
2842 return allocated;
2846 * If there was a change of depth as part of the
2847 * insertion of ex3 above, we need to update the length
2848 * of the ex1 extent again here
2850 if (ex1 && ex1 != ex) {
2851 ex1 = ex;
2852 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2853 ext4_ext_mark_uninitialized(ex1);
2854 ex2 = &newex;
2856 /* ex2: iblock to iblock + maxblocks-1 : initialised */
2857 ex2->ee_block = cpu_to_le32(iblock);
2858 ext4_ext_store_pblock(ex2, newblock);
2859 ex2->ee_len = cpu_to_le16(allocated);
2860 if (ex2 != ex)
2861 goto insert;
2863 * New (initialized) extent starts from the first block
2864 * in the current extent. i.e., ex2 == ex
2865 * We have to see if it can be merged with the extent
2866 * on the left.
2868 if (ex2 > EXT_FIRST_EXTENT(eh)) {
2870 * To merge left, pass "ex2 - 1" to try_to_merge(),
2871 * since it merges towards right _only_.
2873 ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
2874 if (ret) {
2875 err = ext4_ext_correct_indexes(handle, inode, path);
2876 if (err)
2877 goto out;
2878 depth = ext_depth(inode);
2879 ex2--;
2883 * Try to Merge towards right. This might be required
2884 * only when the whole extent is being written to.
2885 * i.e. ex2 == ex and ex3 == NULL.
2887 if (!ex3) {
2888 ret = ext4_ext_try_to_merge(inode, path, ex2);
2889 if (ret) {
2890 err = ext4_ext_correct_indexes(handle, inode, path);
2891 if (err)
2892 goto out;
2895 /* Mark modified extent as dirty */
2896 err = ext4_ext_dirty(handle, inode, path + depth);
2897 goto out;
2898 insert:
2899 err = ext4_ext_insert_extent(handle, inode, path, &newex, 0);
2900 if (err == -ENOSPC && may_zeroout) {
2901 err = ext4_ext_zeroout(inode, &orig_ex);
2902 if (err)
2903 goto fix_extent_len;
2904 /* update the extent length and mark as initialized */
2905 ex->ee_block = orig_ex.ee_block;
2906 ex->ee_len = orig_ex.ee_len;
2907 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2908 ext4_ext_dirty(handle, inode, path + depth);
2909 /* zero out the first half */
2910 return allocated;
2911 } else if (err)
2912 goto fix_extent_len;
2913 out:
2914 ext4_ext_show_leaf(inode, path);
2915 return err ? err : allocated;
2917 fix_extent_len:
2918 ex->ee_block = orig_ex.ee_block;
2919 ex->ee_len = orig_ex.ee_len;
2920 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2921 ext4_ext_mark_uninitialized(ex);
2922 ext4_ext_dirty(handle, inode, path + depth);
2923 return err;
2927 * This function is called by ext4_ext_get_blocks() from
2928 * ext4_get_blocks_dio_write() when DIO to write
2929 * to an uninitialized extent.
2931 * Writing to an uninitized extent may result in splitting the uninitialized
2932 * extent into multiple /intialized unintialized extents (up to three)
2933 * There are three possibilities:
2934 * a> There is no split required: Entire extent should be uninitialized
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
2938 * One of more index blocks maybe needed if the extent tree grow after
2939 * the unintialized extent split. To prevent ENOSPC occur at the IO
2940 * complete, we need to split the uninitialized extent before DIO submit
2941 * the IO. The uninitilized extent called at this time will be split
2942 * into three uninitialized extent(at most). After IO complete, the part
2943 * being filled will be convert to initialized by the end_io callback function
2944 * via ext4_convert_unwritten_extents().
2946 * Returns the size of uninitialized extent to be written on success.
2948 static int ext4_split_unwritten_extents(handle_t *handle,
2949 struct inode *inode,
2950 struct ext4_ext_path *path,
2951 ext4_lblk_t iblock,
2952 unsigned int max_blocks,
2953 int flags)
2955 struct ext4_extent *ex, newex, orig_ex;
2956 struct ext4_extent *ex1 = NULL;
2957 struct ext4_extent *ex2 = NULL;
2958 struct ext4_extent *ex3 = NULL;
2959 struct ext4_extent_header *eh;
2960 ext4_lblk_t ee_block, eof_block;
2961 unsigned int allocated, ee_len, depth;
2962 ext4_fsblk_t newblock;
2963 int err = 0;
2964 int may_zeroout;
2966 ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
2967 "block %llu, max_blocks %u\n", inode->i_ino,
2968 (unsigned long long)iblock, max_blocks);
2970 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2971 inode->i_sb->s_blocksize_bits;
2972 if (eof_block < iblock + max_blocks)
2973 eof_block = iblock + max_blocks;
2975 depth = ext_depth(inode);
2976 eh = path[depth].p_hdr;
2977 ex = path[depth].p_ext;
2978 ee_block = le32_to_cpu(ex->ee_block);
2979 ee_len = ext4_ext_get_actual_len(ex);
2980 allocated = ee_len - (iblock - ee_block);
2981 newblock = iblock - ee_block + ext_pblock(ex);
2983 ex2 = ex;
2984 orig_ex.ee_block = ex->ee_block;
2985 orig_ex.ee_len = cpu_to_le16(ee_len);
2986 ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2989 * It is safe to convert extent to initialized via explicit
2990 * zeroout only if extent is fully insde i_size or new_size.
2992 may_zeroout = ee_block + ee_len <= eof_block;
2995 * If the uninitialized extent begins at the same logical
2996 * block where the write begins, and the write completely
2997 * covers the extent, then we don't need to split it.
2999 if ((iblock == ee_block) && (allocated <= max_blocks))
3000 return allocated;
3002 err = ext4_ext_get_access(handle, inode, path + depth);
3003 if (err)
3004 goto out;
3005 /* ex1: ee_block to iblock - 1 : uninitialized */
3006 if (iblock > ee_block) {
3007 ex1 = ex;
3008 ex1->ee_len = cpu_to_le16(iblock - ee_block);
3009 ext4_ext_mark_uninitialized(ex1);
3010 ex2 = &newex;
3013 * for sanity, update the length of the ex2 extent before
3014 * we insert ex3, if ex1 is NULL. This is to avoid temporary
3015 * overlap of blocks.
3017 if (!ex1 && allocated > max_blocks)
3018 ex2->ee_len = cpu_to_le16(max_blocks);
3019 /* ex3: to ee_block + ee_len : uninitialised */
3020 if (allocated > max_blocks) {
3021 unsigned int newdepth;
3022 ex3 = &newex;
3023 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
3024 ext4_ext_store_pblock(ex3, newblock + max_blocks);
3025 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
3026 ext4_ext_mark_uninitialized(ex3);
3027 err = ext4_ext_insert_extent(handle, inode, path, ex3, flags);
3028 if (err == -ENOSPC && may_zeroout) {
3029 err = ext4_ext_zeroout(inode, &orig_ex);
3030 if (err)
3031 goto fix_extent_len;
3032 /* update the extent length and mark as initialized */
3033 ex->ee_block = orig_ex.ee_block;
3034 ex->ee_len = orig_ex.ee_len;
3035 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
3036 ext4_ext_dirty(handle, inode, path + depth);
3037 /* zeroed the full extent */
3038 /* blocks available from iblock */
3039 return allocated;
3041 } else if (err)
3042 goto fix_extent_len;
3044 * The depth, and hence eh & ex might change
3045 * as part of the insert above.
3047 newdepth = ext_depth(inode);
3049 * update the extent length after successful insert of the
3050 * split extent
3052 ee_len -= ext4_ext_get_actual_len(ex3);
3053 orig_ex.ee_len = cpu_to_le16(ee_len);
3054 may_zeroout = ee_block + ee_len <= eof_block;
3056 depth = newdepth;
3057 ext4_ext_drop_refs(path);
3058 path = ext4_ext_find_extent(inode, iblock, path);
3059 if (IS_ERR(path)) {
3060 err = PTR_ERR(path);
3061 goto out;
3063 eh = path[depth].p_hdr;
3064 ex = path[depth].p_ext;
3065 if (ex2 != &newex)
3066 ex2 = ex;
3068 err = ext4_ext_get_access(handle, inode, path + depth);
3069 if (err)
3070 goto out;
3072 allocated = max_blocks;
3075 * If there was a change of depth as part of the
3076 * insertion of ex3 above, we need to update the length
3077 * of the ex1 extent again here
3079 if (ex1 && ex1 != ex) {
3080 ex1 = ex;
3081 ex1->ee_len = cpu_to_le16(iblock - ee_block);
3082 ext4_ext_mark_uninitialized(ex1);
3083 ex2 = &newex;
3086 * ex2: iblock to iblock + maxblocks-1 : to be direct IO written,
3087 * uninitialised still.
3089 ex2->ee_block = cpu_to_le32(iblock);
3090 ext4_ext_store_pblock(ex2, newblock);
3091 ex2->ee_len = cpu_to_le16(allocated);
3092 ext4_ext_mark_uninitialized(ex2);
3093 if (ex2 != ex)
3094 goto insert;
3095 /* Mark modified extent as dirty */
3096 err = ext4_ext_dirty(handle, inode, path + depth);
3097 ext_debug("out here\n");
3098 goto out;
3099 insert:
3100 err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
3101 if (err == -ENOSPC && may_zeroout) {
3102 err = ext4_ext_zeroout(inode, &orig_ex);
3103 if (err)
3104 goto fix_extent_len;
3105 /* update the extent length and mark as initialized */
3106 ex->ee_block = orig_ex.ee_block;
3107 ex->ee_len = orig_ex.ee_len;
3108 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
3109 ext4_ext_dirty(handle, inode, path + depth);
3110 /* zero out the first half */
3111 return allocated;
3112 } else if (err)
3113 goto fix_extent_len;
3114 out:
3115 ext4_ext_show_leaf(inode, path);
3116 return err ? err : allocated;
3118 fix_extent_len:
3119 ex->ee_block = orig_ex.ee_block;
3120 ex->ee_len = orig_ex.ee_len;
3121 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
3122 ext4_ext_mark_uninitialized(ex);
3123 ext4_ext_dirty(handle, inode, path + depth);
3124 return err;
3126 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3127 struct inode *inode,
3128 struct ext4_ext_path *path)
3130 struct ext4_extent *ex;
3131 struct ext4_extent_header *eh;
3132 int depth;
3133 int err = 0;
3134 int ret = 0;
3136 depth = ext_depth(inode);
3137 eh = path[depth].p_hdr;
3138 ex = path[depth].p_ext;
3140 err = ext4_ext_get_access(handle, inode, path + depth);
3141 if (err)
3142 goto out;
3143 /* first mark the extent as initialized */
3144 ext4_ext_mark_initialized(ex);
3147 * We have to see if it can be merged with the extent
3148 * on the left.
3150 if (ex > EXT_FIRST_EXTENT(eh)) {
3152 * To merge left, pass "ex - 1" to try_to_merge(),
3153 * since it merges towards right _only_.
3155 ret = ext4_ext_try_to_merge(inode, path, ex - 1);
3156 if (ret) {
3157 err = ext4_ext_correct_indexes(handle, inode, path);
3158 if (err)
3159 goto out;
3160 depth = ext_depth(inode);
3161 ex--;
3165 * Try to Merge towards right.
3167 ret = ext4_ext_try_to_merge(inode, path, ex);
3168 if (ret) {
3169 err = ext4_ext_correct_indexes(handle, inode, path);
3170 if (err)
3171 goto out;
3172 depth = ext_depth(inode);
3174 /* Mark modified extent as dirty */
3175 err = ext4_ext_dirty(handle, inode, path + depth);
3176 out:
3177 ext4_ext_show_leaf(inode, path);
3178 return err;
3181 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3182 sector_t block, int count)
3184 int i;
3185 for (i = 0; i < count; i++)
3186 unmap_underlying_metadata(bdev, block + i);
3189 static int
3190 ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
3191 ext4_lblk_t iblock, unsigned int max_blocks,
3192 struct ext4_ext_path *path, int flags,
3193 unsigned int allocated, struct buffer_head *bh_result,
3194 ext4_fsblk_t newblock)
3196 int ret = 0;
3197 int err = 0;
3198 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3200 ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
3201 "block %llu, max_blocks %u, flags %d, allocated %u",
3202 inode->i_ino, (unsigned long long)iblock, max_blocks,
3203 flags, allocated);
3204 ext4_ext_show_leaf(inode, path);
3206 /* get_block() before submit the IO, split the extent */
3207 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3208 ret = ext4_split_unwritten_extents(handle,
3209 inode, path, iblock,
3210 max_blocks, flags);
3212 * Flag the inode(non aio case) or end_io struct (aio case)
3213 * that this IO needs to convertion to written when IO is
3214 * completed
3216 if (io)
3217 io->flag = EXT4_IO_UNWRITTEN;
3218 else
3219 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3220 if (ext4_should_dioread_nolock(inode))
3221 set_buffer_uninit(bh_result);
3222 goto out;
3224 /* IO end_io complete, convert the filled extent to written */
3225 if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
3226 ret = ext4_convert_unwritten_extents_endio(handle, inode,
3227 path);
3228 if (ret >= 0)
3229 ext4_update_inode_fsync_trans(handle, inode, 1);
3230 goto out2;
3232 /* buffered IO case */
3234 * repeat fallocate creation request
3235 * we already have an unwritten extent
3237 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
3238 goto map_out;
3240 /* buffered READ or buffered write_begin() lookup */
3241 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3243 * We have blocks reserved already. We
3244 * return allocated blocks so that delalloc
3245 * won't do block reservation for us. But
3246 * the buffer head will be unmapped so that
3247 * a read from the block returns 0s.
3249 set_buffer_unwritten(bh_result);
3250 goto out1;
3253 /* buffered write, writepage time, convert*/
3254 ret = ext4_ext_convert_to_initialized(handle, inode,
3255 path, iblock,
3256 max_blocks);
3257 if (ret >= 0)
3258 ext4_update_inode_fsync_trans(handle, inode, 1);
3259 out:
3260 if (ret <= 0) {
3261 err = ret;
3262 goto out2;
3263 } else
3264 allocated = ret;
3265 set_buffer_new(bh_result);
3267 * if we allocated more blocks than requested
3268 * we need to make sure we unmap the extra block
3269 * allocated. The actual needed block will get
3270 * unmapped later when we find the buffer_head marked
3271 * new.
3273 if (allocated > max_blocks) {
3274 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
3275 newblock + max_blocks,
3276 allocated - max_blocks);
3277 allocated = max_blocks;
3281 * If we have done fallocate with the offset that is already
3282 * delayed allocated, we would have block reservation
3283 * and quota reservation done in the delayed write path.
3284 * But fallocate would have already updated quota and block
3285 * count for this offset. So cancel these reservation
3287 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3288 ext4_da_update_reserve_space(inode, allocated, 0);
3290 map_out:
3291 set_buffer_mapped(bh_result);
3292 out1:
3293 if (allocated > max_blocks)
3294 allocated = max_blocks;
3295 ext4_ext_show_leaf(inode, path);
3296 bh_result->b_bdev = inode->i_sb->s_bdev;
3297 bh_result->b_blocknr = newblock;
3298 out2:
3299 if (path) {
3300 ext4_ext_drop_refs(path);
3301 kfree(path);
3303 return err ? err : allocated;
3306 * Block allocation/map/preallocation routine for extents based files
3309 * Need to be called with
3310 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
3311 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
3313 * return > 0, number of of blocks already mapped/allocated
3314 * if create == 0 and these are pre-allocated blocks
3315 * buffer head is unmapped
3316 * otherwise blocks are mapped
3318 * return = 0, if plain look up failed (blocks have not been allocated)
3319 * buffer head is unmapped
3321 * return < 0, error case.
3323 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
3324 ext4_lblk_t iblock,
3325 unsigned int max_blocks, struct buffer_head *bh_result,
3326 int flags)
3328 struct ext4_ext_path *path = NULL;
3329 struct ext4_extent_header *eh;
3330 struct ext4_extent newex, *ex, *last_ex;
3331 ext4_fsblk_t newblock;
3332 int err = 0, depth, ret, cache_type;
3333 unsigned int allocated = 0;
3334 struct ext4_allocation_request ar;
3335 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3337 __clear_bit(BH_New, &bh_result->b_state);
3338 ext_debug("blocks %u/%u requested for inode %lu\n",
3339 iblock, max_blocks, inode->i_ino);
3341 /* check in cache */
3342 cache_type = ext4_ext_in_cache(inode, iblock, &newex);
3343 if (cache_type) {
3344 if (cache_type == EXT4_EXT_CACHE_GAP) {
3345 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3347 * block isn't allocated yet and
3348 * user doesn't want to allocate it
3350 goto out2;
3352 /* we should allocate requested block */
3353 } else if (cache_type == EXT4_EXT_CACHE_EXTENT) {
3354 /* block is already allocated */
3355 newblock = iblock
3356 - le32_to_cpu(newex.ee_block)
3357 + ext_pblock(&newex);
3358 /* number of remaining blocks in the extent */
3359 allocated = ext4_ext_get_actual_len(&newex) -
3360 (iblock - le32_to_cpu(newex.ee_block));
3361 goto out;
3362 } else {
3363 BUG();
3367 /* find extent for this block */
3368 path = ext4_ext_find_extent(inode, iblock, NULL);
3369 if (IS_ERR(path)) {
3370 err = PTR_ERR(path);
3371 path = NULL;
3372 goto out2;
3375 depth = ext_depth(inode);
3378 * consistent leaf must not be empty;
3379 * this situation is possible, though, _during_ tree modification;
3380 * this is why assert can't be put in ext4_ext_find_extent()
3382 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
3383 EXT4_ERROR_INODE(inode, "bad extent address "
3384 "iblock: %d, depth: %d pblock %lld",
3385 iblock, depth, path[depth].p_block);
3386 err = -EIO;
3387 goto out2;
3389 eh = path[depth].p_hdr;
3391 ex = path[depth].p_ext;
3392 if (ex) {
3393 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3394 ext4_fsblk_t ee_start = ext_pblock(ex);
3395 unsigned short ee_len;
3398 * Uninitialized extents are treated as holes, except that
3399 * we split out initialized portions during a write.
3401 ee_len = ext4_ext_get_actual_len(ex);
3402 /* if found extent covers block, simply return it */
3403 if (in_range(iblock, ee_block, ee_len)) {
3404 newblock = iblock - ee_block + ee_start;
3405 /* number of remaining blocks in the extent */
3406 allocated = ee_len - (iblock - ee_block);
3407 ext_debug("%u fit into %u:%d -> %llu\n", iblock,
3408 ee_block, ee_len, newblock);
3410 /* Do not put uninitialized extent in the cache */
3411 if (!ext4_ext_is_uninitialized(ex)) {
3412 ext4_ext_put_in_cache(inode, ee_block,
3413 ee_len, ee_start,
3414 EXT4_EXT_CACHE_EXTENT);
3415 goto out;
3417 ret = ext4_ext_handle_uninitialized_extents(handle,
3418 inode, iblock, max_blocks, path,
3419 flags, allocated, bh_result, newblock);
3420 return ret;
3425 * requested block isn't allocated yet;
3426 * we couldn't try to create block if create flag is zero
3428 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3430 * put just found gap into cache to speed up
3431 * subsequent requests
3433 ext4_ext_put_gap_in_cache(inode, path, iblock);
3434 goto out2;
3437 * Okay, we need to do block allocation.
3440 /* find neighbour allocated blocks */
3441 ar.lleft = iblock;
3442 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3443 if (err)
3444 goto out2;
3445 ar.lright = iblock;
3446 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
3447 if (err)
3448 goto out2;
3451 * See if request is beyond maximum number of blocks we can have in
3452 * a single extent. For an initialized extent this limit is
3453 * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
3454 * EXT_UNINIT_MAX_LEN.
3456 if (max_blocks > EXT_INIT_MAX_LEN &&
3457 !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3458 max_blocks = EXT_INIT_MAX_LEN;
3459 else if (max_blocks > EXT_UNINIT_MAX_LEN &&
3460 (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3461 max_blocks = EXT_UNINIT_MAX_LEN;
3463 /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
3464 newex.ee_block = cpu_to_le32(iblock);
3465 newex.ee_len = cpu_to_le16(max_blocks);
3466 err = ext4_ext_check_overlap(inode, &newex, path);
3467 if (err)
3468 allocated = ext4_ext_get_actual_len(&newex);
3469 else
3470 allocated = max_blocks;
3472 /* allocate new block */
3473 ar.inode = inode;
3474 ar.goal = ext4_ext_find_goal(inode, path, iblock);
3475 ar.logical = iblock;
3476 ar.len = allocated;
3477 if (S_ISREG(inode->i_mode))
3478 ar.flags = EXT4_MB_HINT_DATA;
3479 else
3480 /* disable in-core preallocation for non-regular files */
3481 ar.flags = 0;
3482 newblock = ext4_mb_new_blocks(handle, &ar, &err);
3483 if (!newblock)
3484 goto out2;
3485 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
3486 ar.goal, newblock, allocated);
3488 /* try to insert new extent into found leaf and return */
3489 ext4_ext_store_pblock(&newex, newblock);
3490 newex.ee_len = cpu_to_le16(ar.len);
3491 /* Mark uninitialized */
3492 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
3493 ext4_ext_mark_uninitialized(&newex);
3495 * io_end structure was created for every IO write to an
3496 * uninitialized extent. To avoid unecessary conversion,
3497 * here we flag the IO that really needs the conversion.
3498 * For non asycn direct IO case, flag the inode state
3499 * that we need to perform convertion when IO is done.
3501 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3502 if (io)
3503 io->flag = EXT4_IO_UNWRITTEN;
3504 else
3505 ext4_set_inode_state(inode,
3506 EXT4_STATE_DIO_UNWRITTEN);
3508 if (ext4_should_dioread_nolock(inode))
3509 set_buffer_uninit(bh_result);
3512 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EOFBLOCKS_FL)) {
3513 if (unlikely(!eh->eh_entries)) {
3514 EXT4_ERROR_INODE(inode,
3515 "eh->eh_entries == 0 ee_block %d",
3516 ex->ee_block);
3517 err = -EIO;
3518 goto out2;
3520 last_ex = EXT_LAST_EXTENT(eh);
3521 if (iblock + ar.len > le32_to_cpu(last_ex->ee_block)
3522 + ext4_ext_get_actual_len(last_ex))
3523 EXT4_I(inode)->i_flags &= ~EXT4_EOFBLOCKS_FL;
3525 err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
3526 if (err) {
3527 /* free data blocks we just allocated */
3528 /* not a good idea to call discard here directly,
3529 * but otherwise we'd need to call it every free() */
3530 ext4_discard_preallocations(inode);
3531 ext4_free_blocks(handle, inode, 0, ext_pblock(&newex),
3532 ext4_ext_get_actual_len(&newex), 0);
3533 goto out2;
3536 /* previous routine could use block we allocated */
3537 newblock = ext_pblock(&newex);
3538 allocated = ext4_ext_get_actual_len(&newex);
3539 if (allocated > max_blocks)
3540 allocated = max_blocks;
3541 set_buffer_new(bh_result);
3544 * Update reserved blocks/metadata blocks after successful
3545 * block allocation which had been deferred till now.
3547 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3548 ext4_da_update_reserve_space(inode, allocated, 1);
3551 * Cache the extent and update transaction to commit on fdatasync only
3552 * when it is _not_ an uninitialized extent.
3554 if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
3555 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
3556 EXT4_EXT_CACHE_EXTENT);
3557 ext4_update_inode_fsync_trans(handle, inode, 1);
3558 } else
3559 ext4_update_inode_fsync_trans(handle, inode, 0);
3560 out:
3561 if (allocated > max_blocks)
3562 allocated = max_blocks;
3563 ext4_ext_show_leaf(inode, path);
3564 set_buffer_mapped(bh_result);
3565 bh_result->b_bdev = inode->i_sb->s_bdev;
3566 bh_result->b_blocknr = newblock;
3567 out2:
3568 if (path) {
3569 ext4_ext_drop_refs(path);
3570 kfree(path);
3572 return err ? err : allocated;
3575 void ext4_ext_truncate(struct inode *inode)
3577 struct address_space *mapping = inode->i_mapping;
3578 struct super_block *sb = inode->i_sb;
3579 ext4_lblk_t last_block;
3580 handle_t *handle;
3581 int err = 0;
3584 * probably first extent we're gonna free will be last in block
3586 err = ext4_writepage_trans_blocks(inode);
3587 handle = ext4_journal_start(inode, err);
3588 if (IS_ERR(handle))
3589 return;
3591 if (inode->i_size & (sb->s_blocksize - 1))
3592 ext4_block_truncate_page(handle, mapping, inode->i_size);
3594 if (ext4_orphan_add(handle, inode))
3595 goto out_stop;
3597 down_write(&EXT4_I(inode)->i_data_sem);
3598 ext4_ext_invalidate_cache(inode);
3600 ext4_discard_preallocations(inode);
3603 * TODO: optimization is possible here.
3604 * Probably we need not scan at all,
3605 * because page truncation is enough.
3608 /* we have to know where to truncate from in crash case */
3609 EXT4_I(inode)->i_disksize = inode->i_size;
3610 ext4_mark_inode_dirty(handle, inode);
3612 last_block = (inode->i_size + sb->s_blocksize - 1)
3613 >> EXT4_BLOCK_SIZE_BITS(sb);
3614 err = ext4_ext_remove_space(inode, last_block);
3616 /* In a multi-transaction truncate, we only make the final
3617 * transaction synchronous.
3619 if (IS_SYNC(inode))
3620 ext4_handle_sync(handle);
3622 out_stop:
3623 up_write(&EXT4_I(inode)->i_data_sem);
3625 * If this was a simple ftruncate() and the file will remain alive,
3626 * then we need to clear up the orphan record which we created above.
3627 * However, if this was a real unlink then we were called by
3628 * ext4_delete_inode(), and we allow that function to clean up the
3629 * orphan info for us.
3631 if (inode->i_nlink)
3632 ext4_orphan_del(handle, inode);
3634 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3635 ext4_mark_inode_dirty(handle, inode);
3636 ext4_journal_stop(handle);
3639 static void ext4_falloc_update_inode(struct inode *inode,
3640 int mode, loff_t new_size, int update_ctime)
3642 struct timespec now;
3644 if (update_ctime) {
3645 now = current_fs_time(inode->i_sb);
3646 if (!timespec_equal(&inode->i_ctime, &now))
3647 inode->i_ctime = now;
3650 * Update only when preallocation was requested beyond
3651 * the file size.
3653 if (!(mode & FALLOC_FL_KEEP_SIZE)) {
3654 if (new_size > i_size_read(inode))
3655 i_size_write(inode, new_size);
3656 if (new_size > EXT4_I(inode)->i_disksize)
3657 ext4_update_i_disksize(inode, new_size);
3658 } else {
3660 * Mark that we allocate beyond EOF so the subsequent truncate
3661 * can proceed even if the new size is the same as i_size.
3663 if (new_size > i_size_read(inode))
3664 EXT4_I(inode)->i_flags |= EXT4_EOFBLOCKS_FL;
3670 * preallocate space for a file. This implements ext4's fallocate inode
3671 * operation, which gets called from sys_fallocate system call.
3672 * For block-mapped files, posix_fallocate should fall back to the method
3673 * of writing zeroes to the required new blocks (the same behavior which is
3674 * expected for file systems which do not support fallocate() system call).
3676 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
3678 handle_t *handle;
3679 ext4_lblk_t block;
3680 loff_t new_size;
3681 unsigned int max_blocks;
3682 int ret = 0;
3683 int ret2 = 0;
3684 int retries = 0;
3685 struct buffer_head map_bh;
3686 unsigned int credits, blkbits = inode->i_blkbits;
3689 * currently supporting (pre)allocate mode for extent-based
3690 * files _only_
3692 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
3693 return -EOPNOTSUPP;
3695 /* preallocation to directories is currently not supported */
3696 if (S_ISDIR(inode->i_mode))
3697 return -ENODEV;
3699 block = offset >> blkbits;
3701 * We can't just convert len to max_blocks because
3702 * If blocksize = 4096 offset = 3072 and len = 2048
3704 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3705 - block;
3707 * credits to insert 1 extent into extent tree
3709 credits = ext4_chunk_trans_blocks(inode, max_blocks);
3710 mutex_lock(&inode->i_mutex);
3711 retry:
3712 while (ret >= 0 && ret < max_blocks) {
3713 block = block + ret;
3714 max_blocks = max_blocks - ret;
3715 handle = ext4_journal_start(inode, credits);
3716 if (IS_ERR(handle)) {
3717 ret = PTR_ERR(handle);
3718 break;
3720 map_bh.b_state = 0;
3721 ret = ext4_get_blocks(handle, inode, block,
3722 max_blocks, &map_bh,
3723 EXT4_GET_BLOCKS_CREATE_UNINIT_EXT);
3724 if (ret <= 0) {
3725 #ifdef EXT4FS_DEBUG
3726 WARN_ON(ret <= 0);
3727 printk(KERN_ERR "%s: ext4_ext_get_blocks "
3728 "returned error inode#%lu, block=%u, "
3729 "max_blocks=%u", __func__,
3730 inode->i_ino, block, max_blocks);
3731 #endif
3732 ext4_mark_inode_dirty(handle, inode);
3733 ret2 = ext4_journal_stop(handle);
3734 break;
3736 if ((block + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
3737 blkbits) >> blkbits))
3738 new_size = offset + len;
3739 else
3740 new_size = (block + ret) << blkbits;
3742 ext4_falloc_update_inode(inode, mode, new_size,
3743 buffer_new(&map_bh));
3744 ext4_mark_inode_dirty(handle, inode);
3745 ret2 = ext4_journal_stop(handle);
3746 if (ret2)
3747 break;
3749 if (ret == -ENOSPC &&
3750 ext4_should_retry_alloc(inode->i_sb, &retries)) {
3751 ret = 0;
3752 goto retry;
3754 mutex_unlock(&inode->i_mutex);
3755 return ret > 0 ? ret2 : ret;
3759 * This function convert a range of blocks to written extents
3760 * The caller of this function will pass the start offset and the size.
3761 * all unwritten extents within this range will be converted to
3762 * written extents.
3764 * This function is called from the direct IO end io call back
3765 * function, to convert the fallocated extents after IO is completed.
3766 * Returns 0 on success.
3768 int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
3769 ssize_t len)
3771 handle_t *handle;
3772 ext4_lblk_t block;
3773 unsigned int max_blocks;
3774 int ret = 0;
3775 int ret2 = 0;
3776 struct buffer_head map_bh;
3777 unsigned int credits, blkbits = inode->i_blkbits;
3779 block = offset >> blkbits;
3781 * We can't just convert len to max_blocks because
3782 * If blocksize = 4096 offset = 3072 and len = 2048
3784 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3785 - block;
3787 * credits to insert 1 extent into extent tree
3789 credits = ext4_chunk_trans_blocks(inode, max_blocks);
3790 while (ret >= 0 && ret < max_blocks) {
3791 block = block + ret;
3792 max_blocks = max_blocks - ret;
3793 handle = ext4_journal_start(inode, credits);
3794 if (IS_ERR(handle)) {
3795 ret = PTR_ERR(handle);
3796 break;
3798 map_bh.b_state = 0;
3799 ret = ext4_get_blocks(handle, inode, block,
3800 max_blocks, &map_bh,
3801 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
3802 if (ret <= 0) {
3803 WARN_ON(ret <= 0);
3804 printk(KERN_ERR "%s: ext4_ext_get_blocks "
3805 "returned error inode#%lu, block=%u, "
3806 "max_blocks=%u", __func__,
3807 inode->i_ino, block, max_blocks);
3809 ext4_mark_inode_dirty(handle, inode);
3810 ret2 = ext4_journal_stop(handle);
3811 if (ret <= 0 || ret2 )
3812 break;
3814 return ret > 0 ? ret2 : ret;
3817 * Callback function called for each extent to gather FIEMAP information.
3819 static int ext4_ext_fiemap_cb(struct inode *inode, struct ext4_ext_path *path,
3820 struct ext4_ext_cache *newex, struct ext4_extent *ex,
3821 void *data)
3823 struct fiemap_extent_info *fieinfo = data;
3824 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
3825 __u64 logical;
3826 __u64 physical;
3827 __u64 length;
3828 __u32 flags = 0;
3829 int error;
3831 logical = (__u64)newex->ec_block << blksize_bits;
3833 if (newex->ec_type == EXT4_EXT_CACHE_GAP) {
3834 pgoff_t offset;
3835 struct page *page;
3836 struct buffer_head *bh = NULL;
3838 offset = logical >> PAGE_SHIFT;
3839 page = find_get_page(inode->i_mapping, offset);
3840 if (!page || !page_has_buffers(page))
3841 return EXT_CONTINUE;
3843 bh = page_buffers(page);
3845 if (!bh)
3846 return EXT_CONTINUE;
3848 if (buffer_delay(bh)) {
3849 flags |= FIEMAP_EXTENT_DELALLOC;
3850 page_cache_release(page);
3851 } else {
3852 page_cache_release(page);
3853 return EXT_CONTINUE;
3857 physical = (__u64)newex->ec_start << blksize_bits;
3858 length = (__u64)newex->ec_len << blksize_bits;
3860 if (ex && ext4_ext_is_uninitialized(ex))
3861 flags |= FIEMAP_EXTENT_UNWRITTEN;
3864 * If this extent reaches EXT_MAX_BLOCK, it must be last.
3866 * Or if ext4_ext_next_allocated_block is EXT_MAX_BLOCK,
3867 * this also indicates no more allocated blocks.
3869 * XXX this might miss a single-block extent at EXT_MAX_BLOCK
3871 if (ext4_ext_next_allocated_block(path) == EXT_MAX_BLOCK ||
3872 newex->ec_block + newex->ec_len - 1 == EXT_MAX_BLOCK) {
3873 loff_t size = i_size_read(inode);
3874 loff_t bs = EXT4_BLOCK_SIZE(inode->i_sb);
3876 flags |= FIEMAP_EXTENT_LAST;
3877 if ((flags & FIEMAP_EXTENT_DELALLOC) &&
3878 logical+length > size)
3879 length = (size - logical + bs - 1) & ~(bs-1);
3882 error = fiemap_fill_next_extent(fieinfo, logical, physical,
3883 length, flags);
3884 if (error < 0)
3885 return error;
3886 if (error == 1)
3887 return EXT_BREAK;
3889 return EXT_CONTINUE;
3892 /* fiemap flags we can handle specified here */
3893 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
3895 static int ext4_xattr_fiemap(struct inode *inode,
3896 struct fiemap_extent_info *fieinfo)
3898 __u64 physical = 0;
3899 __u64 length;
3900 __u32 flags = FIEMAP_EXTENT_LAST;
3901 int blockbits = inode->i_sb->s_blocksize_bits;
3902 int error = 0;
3904 /* in-inode? */
3905 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
3906 struct ext4_iloc iloc;
3907 int offset; /* offset of xattr in inode */
3909 error = ext4_get_inode_loc(inode, &iloc);
3910 if (error)
3911 return error;
3912 physical = iloc.bh->b_blocknr << blockbits;
3913 offset = EXT4_GOOD_OLD_INODE_SIZE +
3914 EXT4_I(inode)->i_extra_isize;
3915 physical += offset;
3916 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
3917 flags |= FIEMAP_EXTENT_DATA_INLINE;
3918 brelse(iloc.bh);
3919 } else { /* external block */
3920 physical = EXT4_I(inode)->i_file_acl << blockbits;
3921 length = inode->i_sb->s_blocksize;
3924 if (physical)
3925 error = fiemap_fill_next_extent(fieinfo, 0, physical,
3926 length, flags);
3927 return (error < 0 ? error : 0);
3930 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3931 __u64 start, __u64 len)
3933 ext4_lblk_t start_blk;
3934 int error = 0;
3936 /* fallback to generic here if not in extents fmt */
3937 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
3938 return generic_block_fiemap(inode, fieinfo, start, len,
3939 ext4_get_block);
3941 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
3942 return -EBADR;
3944 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
3945 error = ext4_xattr_fiemap(inode, fieinfo);
3946 } else {
3947 ext4_lblk_t len_blks;
3948 __u64 last_blk;
3950 start_blk = start >> inode->i_sb->s_blocksize_bits;
3951 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
3952 if (last_blk >= EXT_MAX_BLOCK)
3953 last_blk = EXT_MAX_BLOCK-1;
3954 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
3957 * Walk the extent tree gathering extent information.
3958 * ext4_ext_fiemap_cb will push extents back to user.
3960 error = ext4_ext_walk_space(inode, start_blk, len_blks,
3961 ext4_ext_fiemap_cb, fieinfo);
3964 return error;