Linux 2.6.32.48
[linux/fpc-iii.git] / fs / ext4 / extents.c
blob93f7999a092090f37ffc5afeb5ad9fae0a6d0919
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);
110 if (err == 0)
111 err = -EAGAIN;
113 return err;
117 * could return:
118 * - EROFS
119 * - ENOMEM
121 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
122 struct ext4_ext_path *path)
124 if (path->p_bh) {
125 /* path points to block */
126 return ext4_journal_get_write_access(handle, path->p_bh);
128 /* path points to leaf/index in inode body */
129 /* we use in-core data, no need to protect them */
130 return 0;
134 * could return:
135 * - EROFS
136 * - ENOMEM
137 * - EIO
139 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
140 struct ext4_ext_path *path)
142 int err;
143 if (path->p_bh) {
144 /* path points to block */
145 err = ext4_handle_dirty_metadata(handle, inode, path->p_bh);
146 } else {
147 /* path points to leaf/index in inode body */
148 err = ext4_mark_inode_dirty(handle, inode);
150 return err;
153 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
154 struct ext4_ext_path *path,
155 ext4_lblk_t block)
157 struct ext4_inode_info *ei = EXT4_I(inode);
158 ext4_fsblk_t bg_start;
159 ext4_fsblk_t last_block;
160 ext4_grpblk_t colour;
161 ext4_group_t block_group;
162 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
163 int depth;
165 if (path) {
166 struct ext4_extent *ex;
167 depth = path->p_depth;
169 /* try to predict block placement */
170 ex = path[depth].p_ext;
171 if (ex)
172 return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
174 /* it looks like index is empty;
175 * try to find starting block from index itself */
176 if (path[depth].p_bh)
177 return path[depth].p_bh->b_blocknr;
180 /* OK. use inode's group */
181 block_group = ei->i_block_group;
182 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
184 * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
185 * block groups per flexgroup, reserve the first block
186 * group for directories and special files. Regular
187 * files will start at the second block group. This
188 * tends to speed up directory access and improves
189 * fsck times.
191 block_group &= ~(flex_size-1);
192 if (S_ISREG(inode->i_mode))
193 block_group++;
195 bg_start = (block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
196 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
197 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
200 * If we are doing delayed allocation, we don't need take
201 * colour into account.
203 if (test_opt(inode->i_sb, DELALLOC))
204 return bg_start;
206 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
207 colour = (current->pid % 16) *
208 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
209 else
210 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
211 return bg_start + colour + block;
215 * Allocation for a meta data block
217 static ext4_fsblk_t
218 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
219 struct ext4_ext_path *path,
220 struct ext4_extent *ex, int *err)
222 ext4_fsblk_t goal, newblock;
224 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
225 newblock = ext4_new_meta_blocks(handle, inode, goal, NULL, err);
226 return newblock;
229 static inline int ext4_ext_space_block(struct inode *inode, int check)
231 int size;
233 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
234 / sizeof(struct ext4_extent);
235 if (!check) {
236 #ifdef AGGRESSIVE_TEST
237 if (size > 6)
238 size = 6;
239 #endif
241 return size;
244 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
246 int size;
248 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
249 / sizeof(struct ext4_extent_idx);
250 if (!check) {
251 #ifdef AGGRESSIVE_TEST
252 if (size > 5)
253 size = 5;
254 #endif
256 return size;
259 static inline int ext4_ext_space_root(struct inode *inode, int check)
261 int size;
263 size = sizeof(EXT4_I(inode)->i_data);
264 size -= sizeof(struct ext4_extent_header);
265 size /= sizeof(struct ext4_extent);
266 if (!check) {
267 #ifdef AGGRESSIVE_TEST
268 if (size > 3)
269 size = 3;
270 #endif
272 return size;
275 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
277 int size;
279 size = sizeof(EXT4_I(inode)->i_data);
280 size -= sizeof(struct ext4_extent_header);
281 size /= sizeof(struct ext4_extent_idx);
282 if (!check) {
283 #ifdef AGGRESSIVE_TEST
284 if (size > 4)
285 size = 4;
286 #endif
288 return size;
292 * Calculate the number of metadata blocks needed
293 * to allocate @blocks
294 * Worse case is one block per extent
296 int ext4_ext_calc_metadata_amount(struct inode *inode, sector_t lblock)
298 struct ext4_inode_info *ei = EXT4_I(inode);
299 int idxs, num = 0;
301 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
302 / sizeof(struct ext4_extent_idx));
305 * If the new delayed allocation block is contiguous with the
306 * previous da block, it can share index blocks with the
307 * previous block, so we only need to allocate a new index
308 * block every idxs leaf blocks. At ldxs**2 blocks, we need
309 * an additional index block, and at ldxs**3 blocks, yet
310 * another index blocks.
312 if (ei->i_da_metadata_calc_len &&
313 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
314 if ((ei->i_da_metadata_calc_len % idxs) == 0)
315 num++;
316 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
317 num++;
318 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
319 num++;
320 ei->i_da_metadata_calc_len = 0;
321 } else
322 ei->i_da_metadata_calc_len++;
323 ei->i_da_metadata_calc_last_lblock++;
324 return num;
328 * In the worst case we need a new set of index blocks at
329 * every level of the inode's extent tree.
331 ei->i_da_metadata_calc_len = 1;
332 ei->i_da_metadata_calc_last_lblock = lblock;
333 return ext_depth(inode) + 1;
336 static int
337 ext4_ext_max_entries(struct inode *inode, int depth)
339 int max;
341 if (depth == ext_depth(inode)) {
342 if (depth == 0)
343 max = ext4_ext_space_root(inode, 1);
344 else
345 max = ext4_ext_space_root_idx(inode, 1);
346 } else {
347 if (depth == 0)
348 max = ext4_ext_space_block(inode, 1);
349 else
350 max = ext4_ext_space_block_idx(inode, 1);
353 return max;
356 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
358 ext4_fsblk_t block = ext_pblock(ext);
359 int len = ext4_ext_get_actual_len(ext);
361 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
364 static int ext4_valid_extent_idx(struct inode *inode,
365 struct ext4_extent_idx *ext_idx)
367 ext4_fsblk_t block = idx_pblock(ext_idx);
369 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
372 static int ext4_valid_extent_entries(struct inode *inode,
373 struct ext4_extent_header *eh,
374 int depth)
376 struct ext4_extent *ext;
377 struct ext4_extent_idx *ext_idx;
378 unsigned short entries;
379 if (eh->eh_entries == 0)
380 return 1;
382 entries = le16_to_cpu(eh->eh_entries);
384 if (depth == 0) {
385 /* leaf entries */
386 ext = EXT_FIRST_EXTENT(eh);
387 while (entries) {
388 if (!ext4_valid_extent(inode, ext))
389 return 0;
390 ext++;
391 entries--;
393 } else {
394 ext_idx = EXT_FIRST_INDEX(eh);
395 while (entries) {
396 if (!ext4_valid_extent_idx(inode, ext_idx))
397 return 0;
398 ext_idx++;
399 entries--;
402 return 1;
405 static int __ext4_ext_check(const char *function, struct inode *inode,
406 struct ext4_extent_header *eh,
407 int depth)
409 const char *error_msg;
410 int max = 0;
412 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
413 error_msg = "invalid magic";
414 goto corrupted;
416 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
417 error_msg = "unexpected eh_depth";
418 goto corrupted;
420 if (unlikely(eh->eh_max == 0)) {
421 error_msg = "invalid eh_max";
422 goto corrupted;
424 max = ext4_ext_max_entries(inode, depth);
425 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
426 error_msg = "too large eh_max";
427 goto corrupted;
429 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
430 error_msg = "invalid eh_entries";
431 goto corrupted;
433 if (!ext4_valid_extent_entries(inode, eh, depth)) {
434 error_msg = "invalid extent entries";
435 goto corrupted;
437 return 0;
439 corrupted:
440 ext4_error(inode->i_sb, function,
441 "bad header/extent in inode #%lu: %s - magic %x, "
442 "entries %u, max %u(%u), depth %u(%u)",
443 inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
444 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
445 max, le16_to_cpu(eh->eh_depth), depth);
447 return -EIO;
450 #define ext4_ext_check(inode, eh, depth) \
451 __ext4_ext_check(__func__, inode, eh, depth)
453 int ext4_ext_check_inode(struct inode *inode)
455 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
458 #ifdef EXT_DEBUG
459 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
461 int k, l = path->p_depth;
463 ext_debug("path:");
464 for (k = 0; k <= l; k++, path++) {
465 if (path->p_idx) {
466 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
467 idx_pblock(path->p_idx));
468 } else if (path->p_ext) {
469 ext_debug(" %d:[%d]%d:%llu ",
470 le32_to_cpu(path->p_ext->ee_block),
471 ext4_ext_is_uninitialized(path->p_ext),
472 ext4_ext_get_actual_len(path->p_ext),
473 ext_pblock(path->p_ext));
474 } else
475 ext_debug(" []");
477 ext_debug("\n");
480 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
482 int depth = ext_depth(inode);
483 struct ext4_extent_header *eh;
484 struct ext4_extent *ex;
485 int i;
487 if (!path)
488 return;
490 eh = path[depth].p_hdr;
491 ex = EXT_FIRST_EXTENT(eh);
493 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
495 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
496 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
497 ext4_ext_is_uninitialized(ex),
498 ext4_ext_get_actual_len(ex), ext_pblock(ex));
500 ext_debug("\n");
502 #else
503 #define ext4_ext_show_path(inode, path)
504 #define ext4_ext_show_leaf(inode, path)
505 #endif
507 void ext4_ext_drop_refs(struct ext4_ext_path *path)
509 int depth = path->p_depth;
510 int i;
512 for (i = 0; i <= depth; i++, path++)
513 if (path->p_bh) {
514 brelse(path->p_bh);
515 path->p_bh = NULL;
520 * ext4_ext_binsearch_idx:
521 * binary search for the closest index of the given block
522 * the header must be checked before calling this
524 static void
525 ext4_ext_binsearch_idx(struct inode *inode,
526 struct ext4_ext_path *path, ext4_lblk_t block)
528 struct ext4_extent_header *eh = path->p_hdr;
529 struct ext4_extent_idx *r, *l, *m;
532 ext_debug("binsearch for %u(idx): ", block);
534 l = EXT_FIRST_INDEX(eh) + 1;
535 r = EXT_LAST_INDEX(eh);
536 while (l <= r) {
537 m = l + (r - l) / 2;
538 if (block < le32_to_cpu(m->ei_block))
539 r = m - 1;
540 else
541 l = m + 1;
542 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
543 m, le32_to_cpu(m->ei_block),
544 r, le32_to_cpu(r->ei_block));
547 path->p_idx = l - 1;
548 ext_debug(" -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
549 idx_pblock(path->p_idx));
551 #ifdef CHECK_BINSEARCH
553 struct ext4_extent_idx *chix, *ix;
554 int k;
556 chix = ix = EXT_FIRST_INDEX(eh);
557 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
558 if (k != 0 &&
559 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
560 printk(KERN_DEBUG "k=%d, ix=0x%p, "
561 "first=0x%p\n", k,
562 ix, EXT_FIRST_INDEX(eh));
563 printk(KERN_DEBUG "%u <= %u\n",
564 le32_to_cpu(ix->ei_block),
565 le32_to_cpu(ix[-1].ei_block));
567 BUG_ON(k && le32_to_cpu(ix->ei_block)
568 <= le32_to_cpu(ix[-1].ei_block));
569 if (block < le32_to_cpu(ix->ei_block))
570 break;
571 chix = ix;
573 BUG_ON(chix != path->p_idx);
575 #endif
580 * ext4_ext_binsearch:
581 * binary search for closest extent of the given block
582 * the header must be checked before calling this
584 static void
585 ext4_ext_binsearch(struct inode *inode,
586 struct ext4_ext_path *path, ext4_lblk_t block)
588 struct ext4_extent_header *eh = path->p_hdr;
589 struct ext4_extent *r, *l, *m;
591 if (eh->eh_entries == 0) {
593 * this leaf is empty:
594 * we get such a leaf in split/add case
596 return;
599 ext_debug("binsearch for %u: ", block);
601 l = EXT_FIRST_EXTENT(eh) + 1;
602 r = EXT_LAST_EXTENT(eh);
604 while (l <= r) {
605 m = l + (r - l) / 2;
606 if (block < le32_to_cpu(m->ee_block))
607 r = m - 1;
608 else
609 l = m + 1;
610 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
611 m, le32_to_cpu(m->ee_block),
612 r, le32_to_cpu(r->ee_block));
615 path->p_ext = l - 1;
616 ext_debug(" -> %d:%llu:[%d]%d ",
617 le32_to_cpu(path->p_ext->ee_block),
618 ext_pblock(path->p_ext),
619 ext4_ext_is_uninitialized(path->p_ext),
620 ext4_ext_get_actual_len(path->p_ext));
622 #ifdef CHECK_BINSEARCH
624 struct ext4_extent *chex, *ex;
625 int k;
627 chex = ex = EXT_FIRST_EXTENT(eh);
628 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
629 BUG_ON(k && le32_to_cpu(ex->ee_block)
630 <= le32_to_cpu(ex[-1].ee_block));
631 if (block < le32_to_cpu(ex->ee_block))
632 break;
633 chex = ex;
635 BUG_ON(chex != path->p_ext);
637 #endif
641 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
643 struct ext4_extent_header *eh;
645 eh = ext_inode_hdr(inode);
646 eh->eh_depth = 0;
647 eh->eh_entries = 0;
648 eh->eh_magic = EXT4_EXT_MAGIC;
649 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
650 ext4_mark_inode_dirty(handle, inode);
651 ext4_ext_invalidate_cache(inode);
652 return 0;
655 struct ext4_ext_path *
656 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
657 struct ext4_ext_path *path)
659 struct ext4_extent_header *eh;
660 struct buffer_head *bh;
661 short int depth, i, ppos = 0, alloc = 0;
663 eh = ext_inode_hdr(inode);
664 depth = ext_depth(inode);
666 /* account possible depth increase */
667 if (!path) {
668 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
669 GFP_NOFS);
670 if (!path)
671 return ERR_PTR(-ENOMEM);
672 alloc = 1;
674 path[0].p_hdr = eh;
675 path[0].p_bh = NULL;
677 i = depth;
678 /* walk through the tree */
679 while (i) {
680 int need_to_validate = 0;
682 ext_debug("depth %d: num %d, max %d\n",
683 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
685 ext4_ext_binsearch_idx(inode, path + ppos, block);
686 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
687 path[ppos].p_depth = i;
688 path[ppos].p_ext = NULL;
690 bh = sb_getblk(inode->i_sb, path[ppos].p_block);
691 if (unlikely(!bh))
692 goto err;
693 if (!bh_uptodate_or_lock(bh)) {
694 if (bh_submit_read(bh) < 0) {
695 put_bh(bh);
696 goto err;
698 /* validate the extent entries */
699 need_to_validate = 1;
701 eh = ext_block_hdr(bh);
702 ppos++;
703 BUG_ON(ppos > depth);
704 path[ppos].p_bh = bh;
705 path[ppos].p_hdr = eh;
706 i--;
708 if (need_to_validate && ext4_ext_check(inode, eh, i))
709 goto err;
712 path[ppos].p_depth = i;
713 path[ppos].p_ext = NULL;
714 path[ppos].p_idx = NULL;
716 /* find extent */
717 ext4_ext_binsearch(inode, path + ppos, block);
718 /* if not an empty leaf */
719 if (path[ppos].p_ext)
720 path[ppos].p_block = ext_pblock(path[ppos].p_ext);
722 ext4_ext_show_path(inode, path);
724 return path;
726 err:
727 ext4_ext_drop_refs(path);
728 if (alloc)
729 kfree(path);
730 return ERR_PTR(-EIO);
734 * ext4_ext_insert_index:
735 * insert new index [@logical;@ptr] into the block at @curp;
736 * check where to insert: before @curp or after @curp
738 int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
739 struct ext4_ext_path *curp,
740 int logical, ext4_fsblk_t ptr)
742 struct ext4_extent_idx *ix;
743 int len, err;
745 err = ext4_ext_get_access(handle, inode, curp);
746 if (err)
747 return err;
749 BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
750 len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
751 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
752 /* insert after */
753 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
754 len = (len - 1) * sizeof(struct ext4_extent_idx);
755 len = len < 0 ? 0 : len;
756 ext_debug("insert new index %d after: %llu. "
757 "move %d from 0x%p to 0x%p\n",
758 logical, ptr, len,
759 (curp->p_idx + 1), (curp->p_idx + 2));
760 memmove(curp->p_idx + 2, curp->p_idx + 1, len);
762 ix = curp->p_idx + 1;
763 } else {
764 /* insert before */
765 len = len * sizeof(struct ext4_extent_idx);
766 len = len < 0 ? 0 : len;
767 ext_debug("insert new index %d before: %llu. "
768 "move %d from 0x%p to 0x%p\n",
769 logical, ptr, len,
770 curp->p_idx, (curp->p_idx + 1));
771 memmove(curp->p_idx + 1, curp->p_idx, len);
772 ix = curp->p_idx;
775 ix->ei_block = cpu_to_le32(logical);
776 ext4_idx_store_pblock(ix, ptr);
777 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
779 BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
780 > le16_to_cpu(curp->p_hdr->eh_max));
781 BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
783 err = ext4_ext_dirty(handle, inode, curp);
784 ext4_std_error(inode->i_sb, err);
786 return err;
790 * ext4_ext_split:
791 * inserts new subtree into the path, using free index entry
792 * at depth @at:
793 * - allocates all needed blocks (new leaf and all intermediate index blocks)
794 * - makes decision where to split
795 * - moves remaining extents and index entries (right to the split point)
796 * into the newly allocated blocks
797 * - initializes subtree
799 static int ext4_ext_split(handle_t *handle, struct inode *inode,
800 struct ext4_ext_path *path,
801 struct ext4_extent *newext, int at)
803 struct buffer_head *bh = NULL;
804 int depth = ext_depth(inode);
805 struct ext4_extent_header *neh;
806 struct ext4_extent_idx *fidx;
807 struct ext4_extent *ex;
808 int i = at, k, m, a;
809 ext4_fsblk_t newblock, oldblock;
810 __le32 border;
811 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
812 int err = 0;
814 /* make decision: where to split? */
815 /* FIXME: now decision is simplest: at current extent */
817 /* if current leaf will be split, then we should use
818 * border from split point */
819 BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
820 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
821 border = path[depth].p_ext[1].ee_block;
822 ext_debug("leaf will be split."
823 " next leaf starts at %d\n",
824 le32_to_cpu(border));
825 } else {
826 border = newext->ee_block;
827 ext_debug("leaf will be added."
828 " next leaf starts at %d\n",
829 le32_to_cpu(border));
833 * If error occurs, then we break processing
834 * and mark filesystem read-only. index won't
835 * be inserted and tree will be in consistent
836 * state. Next mount will repair buffers too.
840 * Get array to track all allocated blocks.
841 * We need this to handle errors and free blocks
842 * upon them.
844 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
845 if (!ablocks)
846 return -ENOMEM;
848 /* allocate all needed blocks */
849 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
850 for (a = 0; a < depth - at; a++) {
851 newblock = ext4_ext_new_meta_block(handle, inode, path,
852 newext, &err);
853 if (newblock == 0)
854 goto cleanup;
855 ablocks[a] = newblock;
858 /* initialize new leaf */
859 newblock = ablocks[--a];
860 BUG_ON(newblock == 0);
861 bh = sb_getblk(inode->i_sb, newblock);
862 if (!bh) {
863 err = -EIO;
864 goto cleanup;
866 lock_buffer(bh);
868 err = ext4_journal_get_create_access(handle, bh);
869 if (err)
870 goto cleanup;
872 neh = ext_block_hdr(bh);
873 neh->eh_entries = 0;
874 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
875 neh->eh_magic = EXT4_EXT_MAGIC;
876 neh->eh_depth = 0;
877 ex = EXT_FIRST_EXTENT(neh);
879 /* move remainder of path[depth] to the new leaf */
880 BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
881 /* start copy from next extent */
882 /* TODO: we could do it by single memmove */
883 m = 0;
884 path[depth].p_ext++;
885 while (path[depth].p_ext <=
886 EXT_MAX_EXTENT(path[depth].p_hdr)) {
887 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
888 le32_to_cpu(path[depth].p_ext->ee_block),
889 ext_pblock(path[depth].p_ext),
890 ext4_ext_is_uninitialized(path[depth].p_ext),
891 ext4_ext_get_actual_len(path[depth].p_ext),
892 newblock);
893 /*memmove(ex++, path[depth].p_ext++,
894 sizeof(struct ext4_extent));
895 neh->eh_entries++;*/
896 path[depth].p_ext++;
897 m++;
899 if (m) {
900 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
901 le16_add_cpu(&neh->eh_entries, m);
904 set_buffer_uptodate(bh);
905 unlock_buffer(bh);
907 err = ext4_handle_dirty_metadata(handle, inode, bh);
908 if (err)
909 goto cleanup;
910 brelse(bh);
911 bh = NULL;
913 /* correct old leaf */
914 if (m) {
915 err = ext4_ext_get_access(handle, inode, path + depth);
916 if (err)
917 goto cleanup;
918 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
919 err = ext4_ext_dirty(handle, inode, path + depth);
920 if (err)
921 goto cleanup;
925 /* create intermediate indexes */
926 k = depth - at - 1;
927 BUG_ON(k < 0);
928 if (k)
929 ext_debug("create %d intermediate indices\n", k);
930 /* insert new index into current index block */
931 /* current depth stored in i var */
932 i = depth - 1;
933 while (k--) {
934 oldblock = newblock;
935 newblock = ablocks[--a];
936 bh = sb_getblk(inode->i_sb, newblock);
937 if (!bh) {
938 err = -EIO;
939 goto cleanup;
941 lock_buffer(bh);
943 err = ext4_journal_get_create_access(handle, bh);
944 if (err)
945 goto cleanup;
947 neh = ext_block_hdr(bh);
948 neh->eh_entries = cpu_to_le16(1);
949 neh->eh_magic = EXT4_EXT_MAGIC;
950 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
951 neh->eh_depth = cpu_to_le16(depth - i);
952 fidx = EXT_FIRST_INDEX(neh);
953 fidx->ei_block = border;
954 ext4_idx_store_pblock(fidx, oldblock);
956 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
957 i, newblock, le32_to_cpu(border), oldblock);
958 /* copy indexes */
959 m = 0;
960 path[i].p_idx++;
962 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
963 EXT_MAX_INDEX(path[i].p_hdr));
964 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
965 EXT_LAST_INDEX(path[i].p_hdr));
966 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
967 ext_debug("%d: move %d:%llu in new index %llu\n", i,
968 le32_to_cpu(path[i].p_idx->ei_block),
969 idx_pblock(path[i].p_idx),
970 newblock);
971 /*memmove(++fidx, path[i].p_idx++,
972 sizeof(struct ext4_extent_idx));
973 neh->eh_entries++;
974 BUG_ON(neh->eh_entries > neh->eh_max);*/
975 path[i].p_idx++;
976 m++;
978 if (m) {
979 memmove(++fidx, path[i].p_idx - m,
980 sizeof(struct ext4_extent_idx) * m);
981 le16_add_cpu(&neh->eh_entries, m);
983 set_buffer_uptodate(bh);
984 unlock_buffer(bh);
986 err = ext4_handle_dirty_metadata(handle, inode, bh);
987 if (err)
988 goto cleanup;
989 brelse(bh);
990 bh = NULL;
992 /* correct old index */
993 if (m) {
994 err = ext4_ext_get_access(handle, inode, path + i);
995 if (err)
996 goto cleanup;
997 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
998 err = ext4_ext_dirty(handle, inode, path + i);
999 if (err)
1000 goto cleanup;
1003 i--;
1006 /* insert new index */
1007 err = ext4_ext_insert_index(handle, inode, path + at,
1008 le32_to_cpu(border), newblock);
1010 cleanup:
1011 if (bh) {
1012 if (buffer_locked(bh))
1013 unlock_buffer(bh);
1014 brelse(bh);
1017 if (err) {
1018 /* free all allocated blocks in error case */
1019 for (i = 0; i < depth; i++) {
1020 if (!ablocks[i])
1021 continue;
1022 ext4_free_blocks(handle, inode, ablocks[i], 1, 1);
1025 kfree(ablocks);
1027 return err;
1031 * ext4_ext_grow_indepth:
1032 * implements tree growing procedure:
1033 * - allocates new block
1034 * - moves top-level data (index block or leaf) into the new block
1035 * - initializes new top-level, creating index that points to the
1036 * just created block
1038 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1039 struct ext4_ext_path *path,
1040 struct ext4_extent *newext)
1042 struct ext4_ext_path *curp = path;
1043 struct ext4_extent_header *neh;
1044 struct ext4_extent_idx *fidx;
1045 struct buffer_head *bh;
1046 ext4_fsblk_t newblock;
1047 int err = 0;
1049 newblock = ext4_ext_new_meta_block(handle, inode, path, newext, &err);
1050 if (newblock == 0)
1051 return err;
1053 bh = sb_getblk(inode->i_sb, newblock);
1054 if (!bh) {
1055 err = -EIO;
1056 ext4_std_error(inode->i_sb, err);
1057 return err;
1059 lock_buffer(bh);
1061 err = ext4_journal_get_create_access(handle, bh);
1062 if (err) {
1063 unlock_buffer(bh);
1064 goto out;
1067 /* move top-level index/leaf into new block */
1068 memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
1070 /* set size of new block */
1071 neh = ext_block_hdr(bh);
1072 /* old root could have indexes or leaves
1073 * so calculate e_max right way */
1074 if (ext_depth(inode))
1075 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1076 else
1077 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1078 neh->eh_magic = EXT4_EXT_MAGIC;
1079 set_buffer_uptodate(bh);
1080 unlock_buffer(bh);
1082 err = ext4_handle_dirty_metadata(handle, inode, bh);
1083 if (err)
1084 goto out;
1086 /* create index in new top-level index: num,max,pointer */
1087 err = ext4_ext_get_access(handle, inode, curp);
1088 if (err)
1089 goto out;
1091 curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
1092 curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1093 curp->p_hdr->eh_entries = cpu_to_le16(1);
1094 curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
1096 if (path[0].p_hdr->eh_depth)
1097 curp->p_idx->ei_block =
1098 EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
1099 else
1100 curp->p_idx->ei_block =
1101 EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
1102 ext4_idx_store_pblock(curp->p_idx, newblock);
1104 neh = ext_inode_hdr(inode);
1105 fidx = EXT_FIRST_INDEX(neh);
1106 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1107 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1108 le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
1110 neh->eh_depth = cpu_to_le16(path->p_depth + 1);
1111 err = ext4_ext_dirty(handle, inode, curp);
1112 out:
1113 brelse(bh);
1115 return err;
1119 * ext4_ext_create_new_leaf:
1120 * finds empty index and adds new leaf.
1121 * if no free index is found, then it requests in-depth growing.
1123 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1124 struct ext4_ext_path *path,
1125 struct ext4_extent *newext)
1127 struct ext4_ext_path *curp;
1128 int depth, i, err = 0;
1130 repeat:
1131 i = depth = ext_depth(inode);
1133 /* walk up to the tree and look for free index entry */
1134 curp = path + depth;
1135 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1136 i--;
1137 curp--;
1140 /* we use already allocated block for index block,
1141 * so subsequent data blocks should be contiguous */
1142 if (EXT_HAS_FREE_INDEX(curp)) {
1143 /* if we found index with free entry, then use that
1144 * entry: create all needed subtree and add new leaf */
1145 err = ext4_ext_split(handle, inode, path, newext, i);
1146 if (err)
1147 goto out;
1149 /* refill path */
1150 ext4_ext_drop_refs(path);
1151 path = ext4_ext_find_extent(inode,
1152 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1153 path);
1154 if (IS_ERR(path))
1155 err = PTR_ERR(path);
1156 } else {
1157 /* tree is full, time to grow in depth */
1158 err = ext4_ext_grow_indepth(handle, inode, path, newext);
1159 if (err)
1160 goto out;
1162 /* refill path */
1163 ext4_ext_drop_refs(path);
1164 path = ext4_ext_find_extent(inode,
1165 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1166 path);
1167 if (IS_ERR(path)) {
1168 err = PTR_ERR(path);
1169 goto out;
1173 * only first (depth 0 -> 1) produces free space;
1174 * in all other cases we have to split the grown tree
1176 depth = ext_depth(inode);
1177 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1178 /* now we need to split */
1179 goto repeat;
1183 out:
1184 return err;
1188 * search the closest allocated block to the left for *logical
1189 * and returns it at @logical + it's physical address at @phys
1190 * if *logical is the smallest allocated block, the function
1191 * returns 0 at @phys
1192 * return value contains 0 (success) or error code
1195 ext4_ext_search_left(struct inode *inode, struct ext4_ext_path *path,
1196 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1198 struct ext4_extent_idx *ix;
1199 struct ext4_extent *ex;
1200 int depth, ee_len;
1202 BUG_ON(path == NULL);
1203 depth = path->p_depth;
1204 *phys = 0;
1206 if (depth == 0 && path->p_ext == NULL)
1207 return 0;
1209 /* usually extent in the path covers blocks smaller
1210 * then *logical, but it can be that extent is the
1211 * first one in the file */
1213 ex = path[depth].p_ext;
1214 ee_len = ext4_ext_get_actual_len(ex);
1215 if (*logical < le32_to_cpu(ex->ee_block)) {
1216 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1217 while (--depth >= 0) {
1218 ix = path[depth].p_idx;
1219 BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1221 return 0;
1224 BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1226 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1227 *phys = ext_pblock(ex) + ee_len - 1;
1228 return 0;
1232 * search the closest allocated block to the right for *logical
1233 * and returns it at @logical + it's physical address at @phys
1234 * if *logical is the smallest allocated block, the function
1235 * returns 0 at @phys
1236 * return value contains 0 (success) or error code
1239 ext4_ext_search_right(struct inode *inode, struct ext4_ext_path *path,
1240 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1242 struct buffer_head *bh = NULL;
1243 struct ext4_extent_header *eh;
1244 struct ext4_extent_idx *ix;
1245 struct ext4_extent *ex;
1246 ext4_fsblk_t block;
1247 int depth; /* Note, NOT eh_depth; depth from top of tree */
1248 int ee_len;
1250 BUG_ON(path == NULL);
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 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1265 while (--depth >= 0) {
1266 ix = path[depth].p_idx;
1267 BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1269 *logical = le32_to_cpu(ex->ee_block);
1270 *phys = ext_pblock(ex);
1271 return 0;
1274 BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1276 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1277 /* next allocated block in this leaf */
1278 ex++;
1279 *logical = le32_to_cpu(ex->ee_block);
1280 *phys = ext_pblock(ex);
1281 return 0;
1284 /* go up and search for index to the right */
1285 while (--depth >= 0) {
1286 ix = path[depth].p_idx;
1287 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1288 goto got_index;
1291 /* we've gone up to the root and found no index to the right */
1292 return 0;
1294 got_index:
1295 /* we've found index to the right, let's
1296 * follow it and find the closest allocated
1297 * block to the right */
1298 ix++;
1299 block = idx_pblock(ix);
1300 while (++depth < path->p_depth) {
1301 bh = sb_bread(inode->i_sb, block);
1302 if (bh == NULL)
1303 return -EIO;
1304 eh = ext_block_hdr(bh);
1305 /* subtract from p_depth to get proper eh_depth */
1306 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1307 put_bh(bh);
1308 return -EIO;
1310 ix = EXT_FIRST_INDEX(eh);
1311 block = idx_pblock(ix);
1312 put_bh(bh);
1315 bh = sb_bread(inode->i_sb, block);
1316 if (bh == NULL)
1317 return -EIO;
1318 eh = ext_block_hdr(bh);
1319 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1320 put_bh(bh);
1321 return -EIO;
1323 ex = EXT_FIRST_EXTENT(eh);
1324 *logical = le32_to_cpu(ex->ee_block);
1325 *phys = ext_pblock(ex);
1326 put_bh(bh);
1327 return 0;
1331 * ext4_ext_next_allocated_block:
1332 * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1333 * NOTE: it considers block number from index entry as
1334 * allocated block. Thus, index entries have to be consistent
1335 * with leaves.
1337 static ext4_lblk_t
1338 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1340 int depth;
1342 BUG_ON(path == NULL);
1343 depth = path->p_depth;
1345 if (depth == 0 && path->p_ext == NULL)
1346 return EXT_MAX_BLOCK;
1348 while (depth >= 0) {
1349 if (depth == path->p_depth) {
1350 /* leaf */
1351 if (path[depth].p_ext !=
1352 EXT_LAST_EXTENT(path[depth].p_hdr))
1353 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1354 } else {
1355 /* index */
1356 if (path[depth].p_idx !=
1357 EXT_LAST_INDEX(path[depth].p_hdr))
1358 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1360 depth--;
1363 return EXT_MAX_BLOCK;
1367 * ext4_ext_next_leaf_block:
1368 * returns first allocated block from next leaf or EXT_MAX_BLOCK
1370 static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1371 struct ext4_ext_path *path)
1373 int depth;
1375 BUG_ON(path == NULL);
1376 depth = path->p_depth;
1378 /* zero-tree has no leaf blocks at all */
1379 if (depth == 0)
1380 return EXT_MAX_BLOCK;
1382 /* go to index block */
1383 depth--;
1385 while (depth >= 0) {
1386 if (path[depth].p_idx !=
1387 EXT_LAST_INDEX(path[depth].p_hdr))
1388 return (ext4_lblk_t)
1389 le32_to_cpu(path[depth].p_idx[1].ei_block);
1390 depth--;
1393 return EXT_MAX_BLOCK;
1397 * ext4_ext_correct_indexes:
1398 * if leaf gets modified and modified extent is first in the leaf,
1399 * then we have to correct all indexes above.
1400 * TODO: do we need to correct tree in all cases?
1402 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1403 struct ext4_ext_path *path)
1405 struct ext4_extent_header *eh;
1406 int depth = ext_depth(inode);
1407 struct ext4_extent *ex;
1408 __le32 border;
1409 int k, err = 0;
1411 eh = path[depth].p_hdr;
1412 ex = path[depth].p_ext;
1413 BUG_ON(ex == NULL);
1414 BUG_ON(eh == NULL);
1416 if (depth == 0) {
1417 /* there is no tree at all */
1418 return 0;
1421 if (ex != EXT_FIRST_EXTENT(eh)) {
1422 /* we correct tree if first leaf got modified only */
1423 return 0;
1427 * TODO: we need correction if border is smaller than current one
1429 k = depth - 1;
1430 border = path[depth].p_ext->ee_block;
1431 err = ext4_ext_get_access(handle, inode, path + k);
1432 if (err)
1433 return err;
1434 path[k].p_idx->ei_block = border;
1435 err = ext4_ext_dirty(handle, inode, path + k);
1436 if (err)
1437 return err;
1439 while (k--) {
1440 /* change all left-side indexes */
1441 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1442 break;
1443 err = ext4_ext_get_access(handle, inode, path + k);
1444 if (err)
1445 break;
1446 path[k].p_idx->ei_block = border;
1447 err = ext4_ext_dirty(handle, inode, path + k);
1448 if (err)
1449 break;
1452 return err;
1456 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1457 struct ext4_extent *ex2)
1459 unsigned short ext1_ee_len, ext2_ee_len, max_len;
1462 * Make sure that either both extents are uninitialized, or
1463 * both are _not_.
1465 if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1466 return 0;
1468 if (ext4_ext_is_uninitialized(ex1))
1469 max_len = EXT_UNINIT_MAX_LEN;
1470 else
1471 max_len = EXT_INIT_MAX_LEN;
1473 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1474 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1476 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1477 le32_to_cpu(ex2->ee_block))
1478 return 0;
1481 * To allow future support for preallocated extents to be added
1482 * as an RO_COMPAT feature, refuse to merge to extents if
1483 * this can result in the top bit of ee_len being set.
1485 if (ext1_ee_len + ext2_ee_len > max_len)
1486 return 0;
1487 #ifdef AGGRESSIVE_TEST
1488 if (ext1_ee_len >= 4)
1489 return 0;
1490 #endif
1492 if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1493 return 1;
1494 return 0;
1498 * This function tries to merge the "ex" extent to the next extent in the tree.
1499 * It always tries to merge towards right. If you want to merge towards
1500 * left, pass "ex - 1" as argument instead of "ex".
1501 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1502 * 1 if they got merged.
1504 int ext4_ext_try_to_merge(struct inode *inode,
1505 struct ext4_ext_path *path,
1506 struct ext4_extent *ex)
1508 struct ext4_extent_header *eh;
1509 unsigned int depth, len;
1510 int merge_done = 0;
1511 int uninitialized = 0;
1513 depth = ext_depth(inode);
1514 BUG_ON(path[depth].p_hdr == NULL);
1515 eh = path[depth].p_hdr;
1517 while (ex < EXT_LAST_EXTENT(eh)) {
1518 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1519 break;
1520 /* merge with next extent! */
1521 if (ext4_ext_is_uninitialized(ex))
1522 uninitialized = 1;
1523 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1524 + ext4_ext_get_actual_len(ex + 1));
1525 if (uninitialized)
1526 ext4_ext_mark_uninitialized(ex);
1528 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1529 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1530 * sizeof(struct ext4_extent);
1531 memmove(ex + 1, ex + 2, len);
1533 le16_add_cpu(&eh->eh_entries, -1);
1534 merge_done = 1;
1535 WARN_ON(eh->eh_entries == 0);
1536 if (!eh->eh_entries)
1537 ext4_error(inode->i_sb, "ext4_ext_try_to_merge",
1538 "inode#%lu, eh->eh_entries = 0!", inode->i_ino);
1541 return merge_done;
1545 * check if a portion of the "newext" extent overlaps with an
1546 * existing extent.
1548 * If there is an overlap discovered, it updates the length of the newext
1549 * such that there will be no overlap, and then returns 1.
1550 * If there is no overlap found, it returns 0.
1552 unsigned int ext4_ext_check_overlap(struct inode *inode,
1553 struct ext4_extent *newext,
1554 struct ext4_ext_path *path)
1556 ext4_lblk_t b1, b2;
1557 unsigned int depth, len1;
1558 unsigned int ret = 0;
1560 b1 = le32_to_cpu(newext->ee_block);
1561 len1 = ext4_ext_get_actual_len(newext);
1562 depth = ext_depth(inode);
1563 if (!path[depth].p_ext)
1564 goto out;
1565 b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1568 * get the next allocated block if the extent in the path
1569 * is before the requested block(s)
1571 if (b2 < b1) {
1572 b2 = ext4_ext_next_allocated_block(path);
1573 if (b2 == EXT_MAX_BLOCK)
1574 goto out;
1577 /* check for wrap through zero on extent logical start block*/
1578 if (b1 + len1 < b1) {
1579 len1 = EXT_MAX_BLOCK - b1;
1580 newext->ee_len = cpu_to_le16(len1);
1581 ret = 1;
1584 /* check for overlap */
1585 if (b1 + len1 > b2) {
1586 newext->ee_len = cpu_to_le16(b2 - b1);
1587 ret = 1;
1589 out:
1590 return ret;
1594 * ext4_ext_insert_extent:
1595 * tries to merge requsted extent into the existing extent or
1596 * inserts requested extent as new one into the tree,
1597 * creating new leaf in the no-space case.
1599 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1600 struct ext4_ext_path *path,
1601 struct ext4_extent *newext, int flag)
1603 struct ext4_extent_header *eh;
1604 struct ext4_extent *ex, *fex;
1605 struct ext4_extent *nearex; /* nearest extent */
1606 struct ext4_ext_path *npath = NULL;
1607 int depth, len, err;
1608 ext4_lblk_t next;
1609 unsigned uninitialized = 0;
1611 BUG_ON(ext4_ext_get_actual_len(newext) == 0);
1612 depth = ext_depth(inode);
1613 ex = path[depth].p_ext;
1614 BUG_ON(path[depth].p_hdr == NULL);
1616 /* try to insert block into found extent and return */
1617 if (ex && (flag != EXT4_GET_BLOCKS_DIO_CREATE_EXT)
1618 && ext4_can_extents_be_merged(inode, ex, newext)) {
1619 ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
1620 ext4_ext_is_uninitialized(newext),
1621 ext4_ext_get_actual_len(newext),
1622 le32_to_cpu(ex->ee_block),
1623 ext4_ext_is_uninitialized(ex),
1624 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1625 err = ext4_ext_get_access(handle, inode, path + depth);
1626 if (err)
1627 return err;
1630 * ext4_can_extents_be_merged should have checked that either
1631 * both extents are uninitialized, or both aren't. Thus we
1632 * need to check only one of them here.
1634 if (ext4_ext_is_uninitialized(ex))
1635 uninitialized = 1;
1636 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1637 + ext4_ext_get_actual_len(newext));
1638 if (uninitialized)
1639 ext4_ext_mark_uninitialized(ex);
1640 eh = path[depth].p_hdr;
1641 nearex = ex;
1642 goto merge;
1645 repeat:
1646 depth = ext_depth(inode);
1647 eh = path[depth].p_hdr;
1648 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1649 goto has_space;
1651 /* probably next leaf has space for us? */
1652 fex = EXT_LAST_EXTENT(eh);
1653 next = ext4_ext_next_leaf_block(inode, path);
1654 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1655 && next != EXT_MAX_BLOCK) {
1656 ext_debug("next leaf block - %d\n", next);
1657 BUG_ON(npath != NULL);
1658 npath = ext4_ext_find_extent(inode, next, NULL);
1659 if (IS_ERR(npath))
1660 return PTR_ERR(npath);
1661 BUG_ON(npath->p_depth != path->p_depth);
1662 eh = npath[depth].p_hdr;
1663 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1664 ext_debug("next leaf isnt full(%d)\n",
1665 le16_to_cpu(eh->eh_entries));
1666 path = npath;
1667 goto repeat;
1669 ext_debug("next leaf has no free space(%d,%d)\n",
1670 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1674 * There is no free space in the found leaf.
1675 * We're gonna add a new leaf in the tree.
1677 err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1678 if (err)
1679 goto cleanup;
1680 depth = ext_depth(inode);
1681 eh = path[depth].p_hdr;
1683 has_space:
1684 nearex = path[depth].p_ext;
1686 err = ext4_ext_get_access(handle, inode, path + depth);
1687 if (err)
1688 goto cleanup;
1690 if (!nearex) {
1691 /* there is no extent in this leaf, create first one */
1692 ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
1693 le32_to_cpu(newext->ee_block),
1694 ext_pblock(newext),
1695 ext4_ext_is_uninitialized(newext),
1696 ext4_ext_get_actual_len(newext));
1697 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1698 } else if (le32_to_cpu(newext->ee_block)
1699 > le32_to_cpu(nearex->ee_block)) {
1700 /* BUG_ON(newext->ee_block == nearex->ee_block); */
1701 if (nearex != EXT_LAST_EXTENT(eh)) {
1702 len = EXT_MAX_EXTENT(eh) - nearex;
1703 len = (len - 1) * sizeof(struct ext4_extent);
1704 len = len < 0 ? 0 : len;
1705 ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
1706 "move %d from 0x%p to 0x%p\n",
1707 le32_to_cpu(newext->ee_block),
1708 ext_pblock(newext),
1709 ext4_ext_is_uninitialized(newext),
1710 ext4_ext_get_actual_len(newext),
1711 nearex, len, nearex + 1, nearex + 2);
1712 memmove(nearex + 2, nearex + 1, len);
1714 path[depth].p_ext = nearex + 1;
1715 } else {
1716 BUG_ON(newext->ee_block == nearex->ee_block);
1717 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1718 len = len < 0 ? 0 : len;
1719 ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
1720 "move %d from 0x%p to 0x%p\n",
1721 le32_to_cpu(newext->ee_block),
1722 ext_pblock(newext),
1723 ext4_ext_is_uninitialized(newext),
1724 ext4_ext_get_actual_len(newext),
1725 nearex, len, nearex + 1, nearex + 2);
1726 memmove(nearex + 1, nearex, len);
1727 path[depth].p_ext = nearex;
1730 le16_add_cpu(&eh->eh_entries, 1);
1731 nearex = path[depth].p_ext;
1732 nearex->ee_block = newext->ee_block;
1733 ext4_ext_store_pblock(nearex, ext_pblock(newext));
1734 nearex->ee_len = newext->ee_len;
1736 merge:
1737 /* try to merge extents to the right */
1738 if (flag != EXT4_GET_BLOCKS_DIO_CREATE_EXT)
1739 ext4_ext_try_to_merge(inode, path, nearex);
1741 /* try to merge extents to the left */
1743 /* time to correct all indexes above */
1744 err = ext4_ext_correct_indexes(handle, inode, path);
1745 if (err)
1746 goto cleanup;
1748 err = ext4_ext_dirty(handle, inode, path + depth);
1750 cleanup:
1751 if (npath) {
1752 ext4_ext_drop_refs(npath);
1753 kfree(npath);
1755 ext4_ext_invalidate_cache(inode);
1756 return err;
1759 int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1760 ext4_lblk_t num, ext_prepare_callback func,
1761 void *cbdata)
1763 struct ext4_ext_path *path = NULL;
1764 struct ext4_ext_cache cbex;
1765 struct ext4_extent *ex;
1766 ext4_lblk_t next, start = 0, end = 0;
1767 ext4_lblk_t last = block + num;
1768 int depth, exists, err = 0;
1770 BUG_ON(func == NULL);
1771 BUG_ON(inode == NULL);
1773 while (block < last && block != EXT_MAX_BLOCK) {
1774 num = last - block;
1775 /* find extent for this block */
1776 down_read(&EXT4_I(inode)->i_data_sem);
1777 path = ext4_ext_find_extent(inode, block, path);
1778 up_read(&EXT4_I(inode)->i_data_sem);
1779 if (IS_ERR(path)) {
1780 err = PTR_ERR(path);
1781 path = NULL;
1782 break;
1785 depth = ext_depth(inode);
1786 BUG_ON(path[depth].p_hdr == NULL);
1787 ex = path[depth].p_ext;
1788 next = ext4_ext_next_allocated_block(path);
1790 exists = 0;
1791 if (!ex) {
1792 /* there is no extent yet, so try to allocate
1793 * all requested space */
1794 start = block;
1795 end = block + num;
1796 } else if (le32_to_cpu(ex->ee_block) > block) {
1797 /* need to allocate space before found extent */
1798 start = block;
1799 end = le32_to_cpu(ex->ee_block);
1800 if (block + num < end)
1801 end = block + num;
1802 } else if (block >= le32_to_cpu(ex->ee_block)
1803 + ext4_ext_get_actual_len(ex)) {
1804 /* need to allocate space after found extent */
1805 start = block;
1806 end = block + num;
1807 if (end >= next)
1808 end = next;
1809 } else if (block >= le32_to_cpu(ex->ee_block)) {
1811 * some part of requested space is covered
1812 * by found extent
1814 start = block;
1815 end = le32_to_cpu(ex->ee_block)
1816 + ext4_ext_get_actual_len(ex);
1817 if (block + num < end)
1818 end = block + num;
1819 exists = 1;
1820 } else {
1821 BUG();
1823 BUG_ON(end <= start);
1825 if (!exists) {
1826 cbex.ec_block = start;
1827 cbex.ec_len = end - start;
1828 cbex.ec_start = 0;
1829 cbex.ec_type = EXT4_EXT_CACHE_GAP;
1830 } else {
1831 cbex.ec_block = le32_to_cpu(ex->ee_block);
1832 cbex.ec_len = ext4_ext_get_actual_len(ex);
1833 cbex.ec_start = ext_pblock(ex);
1834 cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1837 BUG_ON(cbex.ec_len == 0);
1838 err = func(inode, path, &cbex, ex, cbdata);
1839 ext4_ext_drop_refs(path);
1841 if (err < 0)
1842 break;
1844 if (err == EXT_REPEAT)
1845 continue;
1846 else if (err == EXT_BREAK) {
1847 err = 0;
1848 break;
1851 if (ext_depth(inode) != depth) {
1852 /* depth was changed. we have to realloc path */
1853 kfree(path);
1854 path = NULL;
1857 block = cbex.ec_block + cbex.ec_len;
1860 if (path) {
1861 ext4_ext_drop_refs(path);
1862 kfree(path);
1865 return err;
1868 static void
1869 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1870 __u32 len, ext4_fsblk_t start, int type)
1872 struct ext4_ext_cache *cex;
1873 BUG_ON(len == 0);
1874 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1875 cex = &EXT4_I(inode)->i_cached_extent;
1876 cex->ec_type = type;
1877 cex->ec_block = block;
1878 cex->ec_len = len;
1879 cex->ec_start = start;
1880 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1884 * ext4_ext_put_gap_in_cache:
1885 * calculate boundaries of the gap that the requested block fits into
1886 * and cache this gap
1888 static void
1889 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1890 ext4_lblk_t block)
1892 int depth = ext_depth(inode);
1893 unsigned long len;
1894 ext4_lblk_t lblock;
1895 struct ext4_extent *ex;
1897 ex = path[depth].p_ext;
1898 if (ex == NULL) {
1899 /* there is no extent yet, so gap is [0;-] */
1900 lblock = 0;
1901 len = EXT_MAX_BLOCK;
1902 ext_debug("cache gap(whole file):");
1903 } else if (block < le32_to_cpu(ex->ee_block)) {
1904 lblock = block;
1905 len = le32_to_cpu(ex->ee_block) - block;
1906 ext_debug("cache gap(before): %u [%u:%u]",
1907 block,
1908 le32_to_cpu(ex->ee_block),
1909 ext4_ext_get_actual_len(ex));
1910 } else if (block >= le32_to_cpu(ex->ee_block)
1911 + ext4_ext_get_actual_len(ex)) {
1912 ext4_lblk_t next;
1913 lblock = le32_to_cpu(ex->ee_block)
1914 + ext4_ext_get_actual_len(ex);
1916 next = ext4_ext_next_allocated_block(path);
1917 ext_debug("cache gap(after): [%u:%u] %u",
1918 le32_to_cpu(ex->ee_block),
1919 ext4_ext_get_actual_len(ex),
1920 block);
1921 BUG_ON(next == lblock);
1922 len = next - lblock;
1923 } else {
1924 lblock = len = 0;
1925 BUG();
1928 ext_debug(" -> %u:%lu\n", lblock, len);
1929 ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1932 static int
1933 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
1934 struct ext4_extent *ex)
1936 struct ext4_ext_cache *cex;
1937 int ret = EXT4_EXT_CACHE_NO;
1940 * We borrow i_block_reservation_lock to protect i_cached_extent
1942 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1943 cex = &EXT4_I(inode)->i_cached_extent;
1945 /* has cache valid data? */
1946 if (cex->ec_type == EXT4_EXT_CACHE_NO)
1947 goto errout;
1949 BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1950 cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1951 if (in_range(block, cex->ec_block, cex->ec_len)) {
1952 ex->ee_block = cpu_to_le32(cex->ec_block);
1953 ext4_ext_store_pblock(ex, cex->ec_start);
1954 ex->ee_len = cpu_to_le16(cex->ec_len);
1955 ext_debug("%u cached by %u:%u:%llu\n",
1956 block,
1957 cex->ec_block, cex->ec_len, cex->ec_start);
1958 ret = cex->ec_type;
1960 errout:
1961 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1962 return ret;
1966 * ext4_ext_rm_idx:
1967 * removes index from the index block.
1968 * It's used in truncate case only, thus all requests are for
1969 * last index in the block only.
1971 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1972 struct ext4_ext_path *path)
1974 struct buffer_head *bh;
1975 int err;
1976 ext4_fsblk_t leaf;
1978 /* free index block */
1979 path--;
1980 leaf = idx_pblock(path->p_idx);
1981 BUG_ON(path->p_hdr->eh_entries == 0);
1982 err = ext4_ext_get_access(handle, inode, path);
1983 if (err)
1984 return err;
1985 le16_add_cpu(&path->p_hdr->eh_entries, -1);
1986 err = ext4_ext_dirty(handle, inode, path);
1987 if (err)
1988 return err;
1989 ext_debug("index is empty, remove it, free block %llu\n", leaf);
1990 bh = sb_find_get_block(inode->i_sb, leaf);
1991 ext4_forget(handle, 1, inode, bh, leaf);
1992 ext4_free_blocks(handle, inode, leaf, 1, 1);
1993 return err;
1997 * ext4_ext_calc_credits_for_single_extent:
1998 * This routine returns max. credits that needed to insert an extent
1999 * to the extent tree.
2000 * When pass the actual path, the caller should calculate credits
2001 * under i_data_sem.
2003 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2004 struct ext4_ext_path *path)
2006 if (path) {
2007 int depth = ext_depth(inode);
2008 int ret = 0;
2010 /* probably there is space in leaf? */
2011 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2012 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2015 * There are some space in the leaf tree, no
2016 * need to account for leaf block credit
2018 * bitmaps and block group descriptor blocks
2019 * and other metadat blocks still need to be
2020 * accounted.
2022 /* 1 bitmap, 1 block group descriptor */
2023 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2024 return ret;
2028 return ext4_chunk_trans_blocks(inode, nrblocks);
2032 * How many index/leaf blocks need to change/allocate to modify nrblocks?
2034 * if nrblocks are fit in a single extent (chunk flag is 1), then
2035 * in the worse case, each tree level index/leaf need to be changed
2036 * if the tree split due to insert a new extent, then the old tree
2037 * index/leaf need to be updated too
2039 * If the nrblocks are discontiguous, they could cause
2040 * the whole tree split more than once, but this is really rare.
2042 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2044 int index;
2045 int depth = ext_depth(inode);
2047 if (chunk)
2048 index = depth * 2;
2049 else
2050 index = depth * 3;
2052 return index;
2055 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2056 struct ext4_extent *ex,
2057 ext4_lblk_t from, ext4_lblk_t to)
2059 struct buffer_head *bh;
2060 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2061 int i, metadata = 0;
2063 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2064 metadata = 1;
2065 #ifdef EXTENTS_STATS
2067 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2068 spin_lock(&sbi->s_ext_stats_lock);
2069 sbi->s_ext_blocks += ee_len;
2070 sbi->s_ext_extents++;
2071 if (ee_len < sbi->s_ext_min)
2072 sbi->s_ext_min = ee_len;
2073 if (ee_len > sbi->s_ext_max)
2074 sbi->s_ext_max = ee_len;
2075 if (ext_depth(inode) > sbi->s_depth_max)
2076 sbi->s_depth_max = ext_depth(inode);
2077 spin_unlock(&sbi->s_ext_stats_lock);
2079 #endif
2080 if (from >= le32_to_cpu(ex->ee_block)
2081 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2082 /* tail removal */
2083 ext4_lblk_t num;
2084 ext4_fsblk_t start;
2086 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2087 start = ext_pblock(ex) + ee_len - num;
2088 ext_debug("free last %u blocks starting %llu\n", num, start);
2089 for (i = 0; i < num; i++) {
2090 bh = sb_find_get_block(inode->i_sb, start + i);
2091 ext4_forget(handle, metadata, inode, bh, start + i);
2093 ext4_free_blocks(handle, inode, start, num, metadata);
2094 } else if (from == le32_to_cpu(ex->ee_block)
2095 && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2096 printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
2097 from, to, le32_to_cpu(ex->ee_block), ee_len);
2098 } else {
2099 printk(KERN_INFO "strange request: removal(2) "
2100 "%u-%u from %u:%u\n",
2101 from, to, le32_to_cpu(ex->ee_block), ee_len);
2103 return 0;
2106 static int
2107 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2108 struct ext4_ext_path *path, ext4_lblk_t start)
2110 int err = 0, correct_index = 0;
2111 int depth = ext_depth(inode), credits;
2112 struct ext4_extent_header *eh;
2113 ext4_lblk_t a, b, block;
2114 unsigned num;
2115 ext4_lblk_t ex_ee_block;
2116 unsigned short ex_ee_len;
2117 unsigned uninitialized = 0;
2118 struct ext4_extent *ex;
2120 /* the header must be checked already in ext4_ext_remove_space() */
2121 ext_debug("truncate since %u in leaf\n", start);
2122 if (!path[depth].p_hdr)
2123 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2124 eh = path[depth].p_hdr;
2125 BUG_ON(eh == NULL);
2127 /* find where to start removing */
2128 ex = EXT_LAST_EXTENT(eh);
2130 ex_ee_block = le32_to_cpu(ex->ee_block);
2131 ex_ee_len = ext4_ext_get_actual_len(ex);
2133 while (ex >= EXT_FIRST_EXTENT(eh) &&
2134 ex_ee_block + ex_ee_len > start) {
2136 if (ext4_ext_is_uninitialized(ex))
2137 uninitialized = 1;
2138 else
2139 uninitialized = 0;
2141 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2142 uninitialized, ex_ee_len);
2143 path[depth].p_ext = ex;
2145 a = ex_ee_block > start ? ex_ee_block : start;
2146 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
2147 ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
2149 ext_debug(" border %u:%u\n", a, b);
2151 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
2152 block = 0;
2153 num = 0;
2154 BUG();
2155 } else if (a != ex_ee_block) {
2156 /* remove tail of the extent */
2157 block = ex_ee_block;
2158 num = a - block;
2159 } else if (b != ex_ee_block + ex_ee_len - 1) {
2160 /* remove head of the extent */
2161 block = a;
2162 num = b - a;
2163 /* there is no "make a hole" API yet */
2164 BUG();
2165 } else {
2166 /* remove whole extent: excellent! */
2167 block = ex_ee_block;
2168 num = 0;
2169 BUG_ON(a != ex_ee_block);
2170 BUG_ON(b != ex_ee_block + ex_ee_len - 1);
2174 * 3 for leaf, sb, and inode plus 2 (bmap and group
2175 * descriptor) for each block group; assume two block
2176 * groups plus ex_ee_len/blocks_per_block_group for
2177 * the worst case
2179 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2180 if (ex == EXT_FIRST_EXTENT(eh)) {
2181 correct_index = 1;
2182 credits += (ext_depth(inode)) + 1;
2184 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2186 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2187 if (err)
2188 goto out;
2190 err = ext4_ext_get_access(handle, inode, path + depth);
2191 if (err)
2192 goto out;
2194 err = ext4_remove_blocks(handle, inode, ex, a, b);
2195 if (err)
2196 goto out;
2198 if (num == 0) {
2199 /* this extent is removed; mark slot entirely unused */
2200 ext4_ext_store_pblock(ex, 0);
2201 le16_add_cpu(&eh->eh_entries, -1);
2204 ex->ee_block = cpu_to_le32(block);
2205 ex->ee_len = cpu_to_le16(num);
2207 * Do not mark uninitialized if all the blocks in the
2208 * extent have been removed.
2210 if (uninitialized && num)
2211 ext4_ext_mark_uninitialized(ex);
2213 err = ext4_ext_dirty(handle, inode, path + depth);
2214 if (err)
2215 goto out;
2217 ext_debug("new extent: %u:%u:%llu\n", block, num,
2218 ext_pblock(ex));
2219 ex--;
2220 ex_ee_block = le32_to_cpu(ex->ee_block);
2221 ex_ee_len = ext4_ext_get_actual_len(ex);
2224 if (correct_index && eh->eh_entries)
2225 err = ext4_ext_correct_indexes(handle, inode, path);
2227 /* if this leaf is free, then we should
2228 * remove it from index block above */
2229 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2230 err = ext4_ext_rm_idx(handle, inode, path + depth);
2232 out:
2233 return err;
2237 * ext4_ext_more_to_rm:
2238 * returns 1 if current index has to be freed (even partial)
2240 static int
2241 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2243 BUG_ON(path->p_idx == NULL);
2245 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2246 return 0;
2249 * if truncate on deeper level happened, it wasn't partial,
2250 * so we have to consider current index for truncation
2252 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2253 return 0;
2254 return 1;
2257 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2259 struct super_block *sb = inode->i_sb;
2260 int depth = ext_depth(inode);
2261 struct ext4_ext_path *path;
2262 handle_t *handle;
2263 int i, err;
2265 ext_debug("truncate since %u\n", start);
2267 /* probably first extent we're gonna free will be last in block */
2268 handle = ext4_journal_start(inode, depth + 1);
2269 if (IS_ERR(handle))
2270 return PTR_ERR(handle);
2272 again:
2273 ext4_ext_invalidate_cache(inode);
2276 * We start scanning from right side, freeing all the blocks
2277 * after i_size and walking into the tree depth-wise.
2279 depth = ext_depth(inode);
2280 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2281 if (path == NULL) {
2282 ext4_journal_stop(handle);
2283 return -ENOMEM;
2285 path[0].p_depth = depth;
2286 path[0].p_hdr = ext_inode_hdr(inode);
2287 if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2288 err = -EIO;
2289 goto out;
2291 i = err = 0;
2293 while (i >= 0 && err == 0) {
2294 if (i == depth) {
2295 /* this is leaf block */
2296 err = ext4_ext_rm_leaf(handle, inode, path, start);
2297 /* root level has p_bh == NULL, brelse() eats this */
2298 brelse(path[i].p_bh);
2299 path[i].p_bh = NULL;
2300 i--;
2301 continue;
2304 /* this is index block */
2305 if (!path[i].p_hdr) {
2306 ext_debug("initialize header\n");
2307 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2310 if (!path[i].p_idx) {
2311 /* this level hasn't been touched yet */
2312 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2313 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2314 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2315 path[i].p_hdr,
2316 le16_to_cpu(path[i].p_hdr->eh_entries));
2317 } else {
2318 /* we were already here, see at next index */
2319 path[i].p_idx--;
2322 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2323 i, EXT_FIRST_INDEX(path[i].p_hdr),
2324 path[i].p_idx);
2325 if (ext4_ext_more_to_rm(path + i)) {
2326 struct buffer_head *bh;
2327 /* go to the next level */
2328 ext_debug("move to level %d (block %llu)\n",
2329 i + 1, idx_pblock(path[i].p_idx));
2330 memset(path + i + 1, 0, sizeof(*path));
2331 bh = sb_bread(sb, idx_pblock(path[i].p_idx));
2332 if (!bh) {
2333 /* should we reset i_size? */
2334 err = -EIO;
2335 break;
2337 if (WARN_ON(i + 1 > depth)) {
2338 err = -EIO;
2339 break;
2341 if (ext4_ext_check(inode, ext_block_hdr(bh),
2342 depth - i - 1)) {
2343 err = -EIO;
2344 break;
2346 path[i + 1].p_bh = bh;
2348 /* save actual number of indexes since this
2349 * number is changed at the next iteration */
2350 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2351 i++;
2352 } else {
2353 /* we finished processing this index, go up */
2354 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2355 /* index is empty, remove it;
2356 * handle must be already prepared by the
2357 * truncatei_leaf() */
2358 err = ext4_ext_rm_idx(handle, inode, path + i);
2360 /* root level has p_bh == NULL, brelse() eats this */
2361 brelse(path[i].p_bh);
2362 path[i].p_bh = NULL;
2363 i--;
2364 ext_debug("return to level %d\n", i);
2368 /* TODO: flexible tree reduction should be here */
2369 if (path->p_hdr->eh_entries == 0) {
2371 * truncate to zero freed all the tree,
2372 * so we need to correct eh_depth
2374 err = ext4_ext_get_access(handle, inode, path);
2375 if (err == 0) {
2376 ext_inode_hdr(inode)->eh_depth = 0;
2377 ext_inode_hdr(inode)->eh_max =
2378 cpu_to_le16(ext4_ext_space_root(inode, 0));
2379 err = ext4_ext_dirty(handle, inode, path);
2382 out:
2383 ext4_ext_drop_refs(path);
2384 kfree(path);
2385 if (err == -EAGAIN)
2386 goto again;
2387 ext4_journal_stop(handle);
2389 return err;
2393 * called at mount time
2395 void ext4_ext_init(struct super_block *sb)
2398 * possible initialization would be here
2401 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2402 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
2403 printk(KERN_INFO "EXT4-fs: file extents enabled");
2404 #ifdef AGGRESSIVE_TEST
2405 printk(", aggressive tests");
2406 #endif
2407 #ifdef CHECK_BINSEARCH
2408 printk(", check binsearch");
2409 #endif
2410 #ifdef EXTENTS_STATS
2411 printk(", stats");
2412 #endif
2413 printk("\n");
2414 #endif
2415 #ifdef EXTENTS_STATS
2416 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2417 EXT4_SB(sb)->s_ext_min = 1 << 30;
2418 EXT4_SB(sb)->s_ext_max = 0;
2419 #endif
2424 * called at umount time
2426 void ext4_ext_release(struct super_block *sb)
2428 if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2429 return;
2431 #ifdef EXTENTS_STATS
2432 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2433 struct ext4_sb_info *sbi = EXT4_SB(sb);
2434 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2435 sbi->s_ext_blocks, sbi->s_ext_extents,
2436 sbi->s_ext_blocks / sbi->s_ext_extents);
2437 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2438 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2440 #endif
2443 static void bi_complete(struct bio *bio, int error)
2445 complete((struct completion *)bio->bi_private);
2448 /* FIXME!! we need to try to merge to left or right after zero-out */
2449 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2451 int ret;
2452 struct bio *bio;
2453 int blkbits, blocksize;
2454 sector_t ee_pblock;
2455 struct completion event;
2456 unsigned int ee_len, len, done, offset;
2459 blkbits = inode->i_blkbits;
2460 blocksize = inode->i_sb->s_blocksize;
2461 ee_len = ext4_ext_get_actual_len(ex);
2462 ee_pblock = ext_pblock(ex);
2464 /* convert ee_pblock to 512 byte sectors */
2465 ee_pblock = ee_pblock << (blkbits - 9);
2467 while (ee_len > 0) {
2469 if (ee_len > BIO_MAX_PAGES)
2470 len = BIO_MAX_PAGES;
2471 else
2472 len = ee_len;
2474 bio = bio_alloc(GFP_NOIO, len);
2475 if (!bio)
2476 return -ENOMEM;
2478 bio->bi_sector = ee_pblock;
2479 bio->bi_bdev = inode->i_sb->s_bdev;
2481 done = 0;
2482 offset = 0;
2483 while (done < len) {
2484 ret = bio_add_page(bio, ZERO_PAGE(0),
2485 blocksize, offset);
2486 if (ret != blocksize) {
2488 * We can't add any more pages because of
2489 * hardware limitations. Start a new bio.
2491 break;
2493 done++;
2494 offset += blocksize;
2495 if (offset >= PAGE_CACHE_SIZE)
2496 offset = 0;
2499 init_completion(&event);
2500 bio->bi_private = &event;
2501 bio->bi_end_io = bi_complete;
2502 submit_bio(WRITE, bio);
2503 wait_for_completion(&event);
2505 if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) {
2506 bio_put(bio);
2507 return -EIO;
2509 bio_put(bio);
2510 ee_len -= done;
2511 ee_pblock += done << (blkbits - 9);
2513 return 0;
2516 #define EXT4_EXT_ZERO_LEN 7
2518 * This function is called by ext4_ext_get_blocks() if someone tries to write
2519 * to an uninitialized extent. It may result in splitting the uninitialized
2520 * extent into multiple extents (upto three - one initialized and two
2521 * uninitialized).
2522 * There are three possibilities:
2523 * a> There is no split required: Entire extent should be initialized
2524 * b> Splits in two extents: Write is happening at either end of the extent
2525 * c> Splits in three extents: Somone is writing in middle of the extent
2527 static int ext4_ext_convert_to_initialized(handle_t *handle,
2528 struct inode *inode,
2529 struct ext4_ext_path *path,
2530 ext4_lblk_t iblock,
2531 unsigned int max_blocks)
2533 struct ext4_extent *ex, newex, orig_ex;
2534 struct ext4_extent *ex1 = NULL;
2535 struct ext4_extent *ex2 = NULL;
2536 struct ext4_extent *ex3 = NULL;
2537 struct ext4_extent_header *eh;
2538 ext4_lblk_t ee_block, eof_block;
2539 unsigned int allocated, ee_len, depth;
2540 ext4_fsblk_t newblock;
2541 int err = 0;
2542 int ret = 0;
2543 int may_zeroout;
2545 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
2546 "block %llu, max_blocks %u\n", inode->i_ino,
2547 (unsigned long long)iblock, max_blocks);
2549 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2550 inode->i_sb->s_blocksize_bits;
2551 if (eof_block < iblock + max_blocks)
2552 eof_block = iblock + max_blocks;
2554 depth = ext_depth(inode);
2555 eh = path[depth].p_hdr;
2556 ex = path[depth].p_ext;
2557 ee_block = le32_to_cpu(ex->ee_block);
2558 ee_len = ext4_ext_get_actual_len(ex);
2559 allocated = ee_len - (iblock - ee_block);
2560 newblock = iblock - ee_block + ext_pblock(ex);
2562 ex2 = ex;
2563 orig_ex.ee_block = ex->ee_block;
2564 orig_ex.ee_len = cpu_to_le16(ee_len);
2565 ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2568 * It is safe to convert extent to initialized via explicit
2569 * zeroout only if extent is fully insde i_size or new_size.
2571 may_zeroout = ee_block + ee_len <= eof_block;
2573 err = ext4_ext_get_access(handle, inode, path + depth);
2574 if (err)
2575 goto out;
2576 /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
2577 if (ee_len <= 2*EXT4_EXT_ZERO_LEN && may_zeroout) {
2578 err = ext4_ext_zeroout(inode, &orig_ex);
2579 if (err)
2580 goto fix_extent_len;
2581 /* update the extent length and mark as initialized */
2582 ex->ee_block = orig_ex.ee_block;
2583 ex->ee_len = orig_ex.ee_len;
2584 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2585 ext4_ext_dirty(handle, inode, path + depth);
2586 /* zeroed the full extent */
2587 return allocated;
2590 /* ex1: ee_block to iblock - 1 : uninitialized */
2591 if (iblock > ee_block) {
2592 ex1 = ex;
2593 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2594 ext4_ext_mark_uninitialized(ex1);
2595 ext4_ext_dirty(handle, inode, path + depth);
2596 ex2 = &newex;
2599 * for sanity, update the length of the ex2 extent before
2600 * we insert ex3, if ex1 is NULL. This is to avoid temporary
2601 * overlap of blocks.
2603 if (!ex1 && allocated > max_blocks)
2604 ex2->ee_len = cpu_to_le16(max_blocks);
2605 /* ex3: to ee_block + ee_len : uninitialised */
2606 if (allocated > max_blocks) {
2607 unsigned int newdepth;
2608 /* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
2609 if (allocated <= EXT4_EXT_ZERO_LEN && may_zeroout) {
2611 * iblock == ee_block is handled by the zerouout
2612 * at the beginning.
2613 * Mark first half uninitialized.
2614 * Mark second half initialized and zero out the
2615 * initialized extent
2617 ex->ee_block = orig_ex.ee_block;
2618 ex->ee_len = cpu_to_le16(ee_len - allocated);
2619 ext4_ext_mark_uninitialized(ex);
2620 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2621 ext4_ext_dirty(handle, inode, path + depth);
2623 ex3 = &newex;
2624 ex3->ee_block = cpu_to_le32(iblock);
2625 ext4_ext_store_pblock(ex3, newblock);
2626 ex3->ee_len = cpu_to_le16(allocated);
2627 err = ext4_ext_insert_extent(handle, inode, path,
2628 ex3, 0);
2629 if (err == -ENOSPC) {
2630 err = ext4_ext_zeroout(inode, &orig_ex);
2631 if (err)
2632 goto fix_extent_len;
2633 ex->ee_block = orig_ex.ee_block;
2634 ex->ee_len = orig_ex.ee_len;
2635 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2636 ext4_ext_dirty(handle, inode, path + depth);
2637 /* blocks available from iblock */
2638 return allocated;
2640 } else if (err)
2641 goto fix_extent_len;
2644 * We need to zero out the second half because
2645 * an fallocate request can update file size and
2646 * converting the second half to initialized extent
2647 * implies that we can leak some junk data to user
2648 * space.
2650 err = ext4_ext_zeroout(inode, ex3);
2651 if (err) {
2653 * We should actually mark the
2654 * second half as uninit and return error
2655 * Insert would have changed the extent
2657 depth = ext_depth(inode);
2658 ext4_ext_drop_refs(path);
2659 path = ext4_ext_find_extent(inode,
2660 iblock, path);
2661 if (IS_ERR(path)) {
2662 err = PTR_ERR(path);
2663 return err;
2665 /* get the second half extent details */
2666 ex = path[depth].p_ext;
2667 err = ext4_ext_get_access(handle, inode,
2668 path + depth);
2669 if (err)
2670 return err;
2671 ext4_ext_mark_uninitialized(ex);
2672 ext4_ext_dirty(handle, inode, path + depth);
2673 return err;
2676 /* zeroed the second half */
2677 return allocated;
2679 ex3 = &newex;
2680 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2681 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2682 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2683 ext4_ext_mark_uninitialized(ex3);
2684 err = ext4_ext_insert_extent(handle, inode, path, ex3, 0);
2685 if (err == -ENOSPC && may_zeroout) {
2686 err = ext4_ext_zeroout(inode, &orig_ex);
2687 if (err)
2688 goto fix_extent_len;
2689 /* update the extent length and mark as initialized */
2690 ex->ee_block = orig_ex.ee_block;
2691 ex->ee_len = orig_ex.ee_len;
2692 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2693 ext4_ext_dirty(handle, inode, path + depth);
2694 /* zeroed the full extent */
2695 /* blocks available from iblock */
2696 return allocated;
2698 } else if (err)
2699 goto fix_extent_len;
2701 * The depth, and hence eh & ex might change
2702 * as part of the insert above.
2704 newdepth = ext_depth(inode);
2706 * update the extent length after successful insert of the
2707 * split extent
2709 ee_len -= ext4_ext_get_actual_len(ex3);
2710 orig_ex.ee_len = cpu_to_le16(ee_len);
2711 may_zeroout = ee_block + ee_len <= eof_block;
2713 depth = newdepth;
2714 ext4_ext_drop_refs(path);
2715 path = ext4_ext_find_extent(inode, iblock, path);
2716 if (IS_ERR(path)) {
2717 err = PTR_ERR(path);
2718 goto out;
2720 eh = path[depth].p_hdr;
2721 ex = path[depth].p_ext;
2722 if (ex2 != &newex)
2723 ex2 = ex;
2725 err = ext4_ext_get_access(handle, inode, path + depth);
2726 if (err)
2727 goto out;
2729 allocated = max_blocks;
2731 /* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
2732 * to insert a extent in the middle zerout directly
2733 * otherwise give the extent a chance to merge to left
2735 if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
2736 iblock != ee_block && may_zeroout) {
2737 err = ext4_ext_zeroout(inode, &orig_ex);
2738 if (err)
2739 goto fix_extent_len;
2740 /* update the extent length and mark as initialized */
2741 ex->ee_block = orig_ex.ee_block;
2742 ex->ee_len = orig_ex.ee_len;
2743 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2744 ext4_ext_dirty(handle, inode, path + depth);
2745 /* zero out the first half */
2746 /* blocks available from iblock */
2747 return allocated;
2751 * If there was a change of depth as part of the
2752 * insertion of ex3 above, we need to update the length
2753 * of the ex1 extent again here
2755 if (ex1 && ex1 != ex) {
2756 ex1 = ex;
2757 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2758 ext4_ext_mark_uninitialized(ex1);
2759 ex2 = &newex;
2761 /* ex2: iblock to iblock + maxblocks-1 : initialised */
2762 ex2->ee_block = cpu_to_le32(iblock);
2763 ext4_ext_store_pblock(ex2, newblock);
2764 ex2->ee_len = cpu_to_le16(allocated);
2765 if (ex2 != ex)
2766 goto insert;
2768 * New (initialized) extent starts from the first block
2769 * in the current extent. i.e., ex2 == ex
2770 * We have to see if it can be merged with the extent
2771 * on the left.
2773 if (ex2 > EXT_FIRST_EXTENT(eh)) {
2775 * To merge left, pass "ex2 - 1" to try_to_merge(),
2776 * since it merges towards right _only_.
2778 ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
2779 if (ret) {
2780 err = ext4_ext_correct_indexes(handle, inode, path);
2781 if (err)
2782 goto out;
2783 depth = ext_depth(inode);
2784 ex2--;
2788 * Try to Merge towards right. This might be required
2789 * only when the whole extent is being written to.
2790 * i.e. ex2 == ex and ex3 == NULL.
2792 if (!ex3) {
2793 ret = ext4_ext_try_to_merge(inode, path, ex2);
2794 if (ret) {
2795 err = ext4_ext_correct_indexes(handle, inode, path);
2796 if (err)
2797 goto out;
2800 /* Mark modified extent as dirty */
2801 err = ext4_ext_dirty(handle, inode, path + depth);
2802 goto out;
2803 insert:
2804 err = ext4_ext_insert_extent(handle, inode, path, &newex, 0);
2805 if (err == -ENOSPC && may_zeroout) {
2806 err = ext4_ext_zeroout(inode, &orig_ex);
2807 if (err)
2808 goto fix_extent_len;
2809 /* update the extent length and mark as initialized */
2810 ex->ee_block = orig_ex.ee_block;
2811 ex->ee_len = orig_ex.ee_len;
2812 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2813 ext4_ext_dirty(handle, inode, path + depth);
2814 /* zero out the first half */
2815 return allocated;
2816 } else if (err)
2817 goto fix_extent_len;
2818 out:
2819 ext4_ext_show_leaf(inode, path);
2820 return err ? err : allocated;
2822 fix_extent_len:
2823 ex->ee_block = orig_ex.ee_block;
2824 ex->ee_len = orig_ex.ee_len;
2825 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2826 ext4_ext_mark_uninitialized(ex);
2827 ext4_ext_dirty(handle, inode, path + depth);
2828 return err;
2832 * This function is called by ext4_ext_get_blocks() from
2833 * ext4_get_blocks_dio_write() when DIO to write
2834 * to an uninitialized extent.
2836 * Writing to an uninitized extent may result in splitting the uninitialized
2837 * extent into multiple /intialized unintialized extents (up to three)
2838 * There are three possibilities:
2839 * a> There is no split required: Entire extent should be uninitialized
2840 * b> Splits in two extents: Write is happening at either end of the extent
2841 * c> Splits in three extents: Somone is writing in middle of the extent
2843 * One of more index blocks maybe needed if the extent tree grow after
2844 * the unintialized extent split. To prevent ENOSPC occur at the IO
2845 * complete, we need to split the uninitialized extent before DIO submit
2846 * the IO. The uninitilized extent called at this time will be split
2847 * into three uninitialized extent(at most). After IO complete, the part
2848 * being filled will be convert to initialized by the end_io callback function
2849 * via ext4_convert_unwritten_extents().
2851 * Returns the size of uninitialized extent to be written on success.
2853 static int ext4_split_unwritten_extents(handle_t *handle,
2854 struct inode *inode,
2855 struct ext4_ext_path *path,
2856 ext4_lblk_t iblock,
2857 unsigned int max_blocks,
2858 int flags)
2860 struct ext4_extent *ex, newex, orig_ex;
2861 struct ext4_extent *ex1 = NULL;
2862 struct ext4_extent *ex2 = NULL;
2863 struct ext4_extent *ex3 = NULL;
2864 struct ext4_extent_header *eh;
2865 ext4_lblk_t ee_block, eof_block;
2866 unsigned int allocated, ee_len, depth;
2867 ext4_fsblk_t newblock;
2868 int err = 0;
2869 int may_zeroout;
2871 ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
2872 "block %llu, max_blocks %u\n", inode->i_ino,
2873 (unsigned long long)iblock, max_blocks);
2875 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2876 inode->i_sb->s_blocksize_bits;
2877 if (eof_block < iblock + max_blocks)
2878 eof_block = iblock + max_blocks;
2880 depth = ext_depth(inode);
2881 eh = path[depth].p_hdr;
2882 ex = path[depth].p_ext;
2883 ee_block = le32_to_cpu(ex->ee_block);
2884 ee_len = ext4_ext_get_actual_len(ex);
2885 allocated = ee_len - (iblock - ee_block);
2886 newblock = iblock - ee_block + ext_pblock(ex);
2888 ex2 = ex;
2889 orig_ex.ee_block = ex->ee_block;
2890 orig_ex.ee_len = cpu_to_le16(ee_len);
2891 ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2894 * It is safe to convert extent to initialized via explicit
2895 * zeroout only if extent is fully insde i_size or new_size.
2897 may_zeroout = ee_block + ee_len <= eof_block;
2900 * If the uninitialized extent begins at the same logical
2901 * block where the write begins, and the write completely
2902 * covers the extent, then we don't need to split it.
2904 if ((iblock == ee_block) && (allocated <= max_blocks))
2905 return allocated;
2907 err = ext4_ext_get_access(handle, inode, path + depth);
2908 if (err)
2909 goto out;
2910 /* ex1: ee_block to iblock - 1 : uninitialized */
2911 if (iblock > ee_block) {
2912 ex1 = ex;
2913 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2914 ext4_ext_mark_uninitialized(ex1);
2915 ex2 = &newex;
2918 * for sanity, update the length of the ex2 extent before
2919 * we insert ex3, if ex1 is NULL. This is to avoid temporary
2920 * overlap of blocks.
2922 if (!ex1 && allocated > max_blocks)
2923 ex2->ee_len = cpu_to_le16(max_blocks);
2924 /* ex3: to ee_block + ee_len : uninitialised */
2925 if (allocated > max_blocks) {
2926 unsigned int newdepth;
2927 ex3 = &newex;
2928 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2929 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2930 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2931 ext4_ext_mark_uninitialized(ex3);
2932 err = ext4_ext_insert_extent(handle, inode, path, ex3, flags);
2933 if (err == -ENOSPC && may_zeroout) {
2934 err = ext4_ext_zeroout(inode, &orig_ex);
2935 if (err)
2936 goto fix_extent_len;
2937 /* update the extent length and mark as initialized */
2938 ex->ee_block = orig_ex.ee_block;
2939 ex->ee_len = orig_ex.ee_len;
2940 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2941 ext4_ext_dirty(handle, inode, path + depth);
2942 /* zeroed the full extent */
2943 /* blocks available from iblock */
2944 return allocated;
2946 } else if (err)
2947 goto fix_extent_len;
2949 * The depth, and hence eh & ex might change
2950 * as part of the insert above.
2952 newdepth = ext_depth(inode);
2954 * update the extent length after successful insert of the
2955 * split extent
2957 ee_len -= ext4_ext_get_actual_len(ex3);
2958 orig_ex.ee_len = cpu_to_le16(ee_len);
2959 may_zeroout = ee_block + ee_len <= eof_block;
2961 depth = newdepth;
2962 ext4_ext_drop_refs(path);
2963 path = ext4_ext_find_extent(inode, iblock, path);
2964 if (IS_ERR(path)) {
2965 err = PTR_ERR(path);
2966 goto out;
2968 eh = path[depth].p_hdr;
2969 ex = path[depth].p_ext;
2970 if (ex2 != &newex)
2971 ex2 = ex;
2973 err = ext4_ext_get_access(handle, inode, path + depth);
2974 if (err)
2975 goto out;
2977 allocated = max_blocks;
2980 * If there was a change of depth as part of the
2981 * insertion of ex3 above, we need to update the length
2982 * of the ex1 extent again here
2984 if (ex1 && ex1 != ex) {
2985 ex1 = ex;
2986 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2987 ext4_ext_mark_uninitialized(ex1);
2988 ex2 = &newex;
2991 * ex2: iblock to iblock + maxblocks-1 : to be direct IO written,
2992 * uninitialised still.
2994 ex2->ee_block = cpu_to_le32(iblock);
2995 ext4_ext_store_pblock(ex2, newblock);
2996 ex2->ee_len = cpu_to_le16(allocated);
2997 ext4_ext_mark_uninitialized(ex2);
2998 if (ex2 != ex)
2999 goto insert;
3000 /* Mark modified extent as dirty */
3001 err = ext4_ext_dirty(handle, inode, path + depth);
3002 ext_debug("out here\n");
3003 goto out;
3004 insert:
3005 err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
3006 if (err == -ENOSPC && may_zeroout) {
3007 err = ext4_ext_zeroout(inode, &orig_ex);
3008 if (err)
3009 goto fix_extent_len;
3010 /* update the extent length and mark as initialized */
3011 ex->ee_block = orig_ex.ee_block;
3012 ex->ee_len = orig_ex.ee_len;
3013 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
3014 ext4_ext_dirty(handle, inode, path + depth);
3015 /* zero out the first half */
3016 return allocated;
3017 } else if (err)
3018 goto fix_extent_len;
3019 out:
3020 ext4_ext_show_leaf(inode, path);
3021 return err ? err : allocated;
3023 fix_extent_len:
3024 ex->ee_block = orig_ex.ee_block;
3025 ex->ee_len = orig_ex.ee_len;
3026 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
3027 ext4_ext_mark_uninitialized(ex);
3028 ext4_ext_dirty(handle, inode, path + depth);
3029 return err;
3031 static int ext4_convert_unwritten_extents_dio(handle_t *handle,
3032 struct inode *inode,
3033 struct ext4_ext_path *path)
3035 struct ext4_extent *ex;
3036 struct ext4_extent_header *eh;
3037 int depth;
3038 int err = 0;
3039 int ret = 0;
3041 depth = ext_depth(inode);
3042 eh = path[depth].p_hdr;
3043 ex = path[depth].p_ext;
3045 err = ext4_ext_get_access(handle, inode, path + depth);
3046 if (err)
3047 goto out;
3048 /* first mark the extent as initialized */
3049 ext4_ext_mark_initialized(ex);
3052 * We have to see if it can be merged with the extent
3053 * on the left.
3055 if (ex > EXT_FIRST_EXTENT(eh)) {
3057 * To merge left, pass "ex - 1" to try_to_merge(),
3058 * since it merges towards right _only_.
3060 ret = ext4_ext_try_to_merge(inode, path, ex - 1);
3061 if (ret) {
3062 err = ext4_ext_correct_indexes(handle, inode, path);
3063 if (err)
3064 goto out;
3065 depth = ext_depth(inode);
3066 ex--;
3070 * Try to Merge towards right.
3072 ret = ext4_ext_try_to_merge(inode, path, ex);
3073 if (ret) {
3074 err = ext4_ext_correct_indexes(handle, inode, path);
3075 if (err)
3076 goto out;
3077 depth = ext_depth(inode);
3079 /* Mark modified extent as dirty */
3080 err = ext4_ext_dirty(handle, inode, path + depth);
3081 out:
3082 ext4_ext_show_leaf(inode, path);
3083 return err;
3086 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3087 sector_t block, int count)
3089 int i;
3090 for (i = 0; i < count; i++)
3091 unmap_underlying_metadata(bdev, block + i);
3094 static int
3095 ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
3096 ext4_lblk_t iblock, unsigned int max_blocks,
3097 struct ext4_ext_path *path, int flags,
3098 unsigned int allocated, struct buffer_head *bh_result,
3099 ext4_fsblk_t newblock)
3101 int ret = 0;
3102 int err = 0;
3103 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3105 ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
3106 "block %llu, max_blocks %u, flags %d, allocated %u",
3107 inode->i_ino, (unsigned long long)iblock, max_blocks,
3108 flags, allocated);
3109 ext4_ext_show_leaf(inode, path);
3111 /* DIO get_block() before submit the IO, split the extent */
3112 if (flags == EXT4_GET_BLOCKS_DIO_CREATE_EXT) {
3113 ret = ext4_split_unwritten_extents(handle,
3114 inode, path, iblock,
3115 max_blocks, flags);
3117 * Flag the inode(non aio case) or end_io struct (aio case)
3118 * that this IO needs to convertion to written when IO is
3119 * completed
3121 if (io)
3122 io->flag = DIO_AIO_UNWRITTEN;
3123 else
3124 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3125 goto out;
3127 /* async DIO end_io complete, convert the filled extent to written */
3128 if (flags == EXT4_GET_BLOCKS_DIO_CONVERT_EXT) {
3129 ret = ext4_convert_unwritten_extents_dio(handle, inode,
3130 path);
3131 if (ret >= 0)
3132 ext4_update_inode_fsync_trans(handle, inode, 1);
3133 goto out2;
3135 /* buffered IO case */
3137 * repeat fallocate creation request
3138 * we already have an unwritten extent
3140 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
3141 goto map_out;
3143 /* buffered READ or buffered write_begin() lookup */
3144 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3146 * We have blocks reserved already. We
3147 * return allocated blocks so that delalloc
3148 * won't do block reservation for us. But
3149 * the buffer head will be unmapped so that
3150 * a read from the block returns 0s.
3152 set_buffer_unwritten(bh_result);
3153 goto out1;
3156 /* buffered write, writepage time, convert*/
3157 ret = ext4_ext_convert_to_initialized(handle, inode,
3158 path, iblock,
3159 max_blocks);
3160 if (ret >= 0)
3161 ext4_update_inode_fsync_trans(handle, inode, 1);
3162 out:
3163 if (ret <= 0) {
3164 err = ret;
3165 goto out2;
3166 } else
3167 allocated = ret;
3168 set_buffer_new(bh_result);
3170 * if we allocated more blocks than requested
3171 * we need to make sure we unmap the extra block
3172 * allocated. The actual needed block will get
3173 * unmapped later when we find the buffer_head marked
3174 * new.
3176 if (allocated > max_blocks) {
3177 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
3178 newblock + max_blocks,
3179 allocated - max_blocks);
3180 allocated = max_blocks;
3184 * If we have done fallocate with the offset that is already
3185 * delayed allocated, we would have block reservation
3186 * and quota reservation done in the delayed write path.
3187 * But fallocate would have already updated quota and block
3188 * count for this offset. So cancel these reservation
3190 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3191 ext4_da_update_reserve_space(inode, allocated, 0);
3193 map_out:
3194 set_buffer_mapped(bh_result);
3195 out1:
3196 if (allocated > max_blocks)
3197 allocated = max_blocks;
3198 ext4_ext_show_leaf(inode, path);
3199 bh_result->b_bdev = inode->i_sb->s_bdev;
3200 bh_result->b_blocknr = newblock;
3201 out2:
3202 if (path) {
3203 ext4_ext_drop_refs(path);
3204 kfree(path);
3206 return err ? err : allocated;
3209 * Block allocation/map/preallocation routine for extents based files
3212 * Need to be called with
3213 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
3214 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
3216 * return > 0, number of of blocks already mapped/allocated
3217 * if create == 0 and these are pre-allocated blocks
3218 * buffer head is unmapped
3219 * otherwise blocks are mapped
3221 * return = 0, if plain look up failed (blocks have not been allocated)
3222 * buffer head is unmapped
3224 * return < 0, error case.
3226 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
3227 ext4_lblk_t iblock,
3228 unsigned int max_blocks, struct buffer_head *bh_result,
3229 int flags)
3231 struct ext4_ext_path *path = NULL;
3232 struct ext4_extent_header *eh;
3233 struct ext4_extent newex, *ex, *last_ex;
3234 ext4_fsblk_t newblock;
3235 int i, err = 0, depth, ret, cache_type;
3236 unsigned int allocated = 0;
3237 struct ext4_allocation_request ar;
3238 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3240 __clear_bit(BH_New, &bh_result->b_state);
3241 ext_debug("blocks %u/%u requested for inode %lu\n",
3242 iblock, max_blocks, inode->i_ino);
3244 /* check in cache */
3245 cache_type = ext4_ext_in_cache(inode, iblock, &newex);
3246 if (cache_type) {
3247 if (cache_type == EXT4_EXT_CACHE_GAP) {
3248 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3250 * block isn't allocated yet and
3251 * user doesn't want to allocate it
3253 goto out2;
3255 /* we should allocate requested block */
3256 } else if (cache_type == EXT4_EXT_CACHE_EXTENT) {
3257 /* block is already allocated */
3258 newblock = iblock
3259 - le32_to_cpu(newex.ee_block)
3260 + ext_pblock(&newex);
3261 /* number of remaining blocks in the extent */
3262 allocated = ext4_ext_get_actual_len(&newex) -
3263 (iblock - le32_to_cpu(newex.ee_block));
3264 goto out;
3265 } else {
3266 BUG();
3270 /* find extent for this block */
3271 path = ext4_ext_find_extent(inode, iblock, NULL);
3272 if (IS_ERR(path)) {
3273 err = PTR_ERR(path);
3274 path = NULL;
3275 goto out2;
3278 depth = ext_depth(inode);
3281 * consistent leaf must not be empty;
3282 * this situation is possible, though, _during_ tree modification;
3283 * this is why assert can't be put in ext4_ext_find_extent()
3285 if (path[depth].p_ext == NULL && depth != 0) {
3286 ext4_error(inode->i_sb, __func__, "bad extent address "
3287 "inode: %lu, iblock: %lu, depth: %d",
3288 inode->i_ino, (unsigned long) iblock, depth);
3289 err = -EIO;
3290 goto out2;
3292 eh = path[depth].p_hdr;
3294 ex = path[depth].p_ext;
3295 if (ex) {
3296 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3297 ext4_fsblk_t ee_start = ext_pblock(ex);
3298 unsigned short ee_len;
3301 * Uninitialized extents are treated as holes, except that
3302 * we split out initialized portions during a write.
3304 ee_len = ext4_ext_get_actual_len(ex);
3305 /* if found extent covers block, simply return it */
3306 if (in_range(iblock, ee_block, ee_len)) {
3307 newblock = iblock - ee_block + ee_start;
3308 /* number of remaining blocks in the extent */
3309 allocated = ee_len - (iblock - ee_block);
3310 ext_debug("%u fit into %u:%d -> %llu\n", iblock,
3311 ee_block, ee_len, newblock);
3313 /* Do not put uninitialized extent in the cache */
3314 if (!ext4_ext_is_uninitialized(ex)) {
3315 ext4_ext_put_in_cache(inode, ee_block,
3316 ee_len, ee_start,
3317 EXT4_EXT_CACHE_EXTENT);
3318 goto out;
3320 ret = ext4_ext_handle_uninitialized_extents(handle,
3321 inode, iblock, max_blocks, path,
3322 flags, allocated, bh_result, newblock);
3323 return ret;
3328 * requested block isn't allocated yet;
3329 * we couldn't try to create block if create flag is zero
3331 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3333 * put just found gap into cache to speed up
3334 * subsequent requests
3336 ext4_ext_put_gap_in_cache(inode, path, iblock);
3337 goto out2;
3340 * Okay, we need to do block allocation.
3343 /* find neighbour allocated blocks */
3344 ar.lleft = iblock;
3345 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3346 if (err)
3347 goto out2;
3348 ar.lright = iblock;
3349 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
3350 if (err)
3351 goto out2;
3354 * See if request is beyond maximum number of blocks we can have in
3355 * a single extent. For an initialized extent this limit is
3356 * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
3357 * EXT_UNINIT_MAX_LEN.
3359 if (max_blocks > EXT_INIT_MAX_LEN &&
3360 !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3361 max_blocks = EXT_INIT_MAX_LEN;
3362 else if (max_blocks > EXT_UNINIT_MAX_LEN &&
3363 (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3364 max_blocks = EXT_UNINIT_MAX_LEN;
3366 /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
3367 newex.ee_block = cpu_to_le32(iblock);
3368 newex.ee_len = cpu_to_le16(max_blocks);
3369 err = ext4_ext_check_overlap(inode, &newex, path);
3370 if (err)
3371 allocated = ext4_ext_get_actual_len(&newex);
3372 else
3373 allocated = max_blocks;
3375 /* allocate new block */
3376 ar.inode = inode;
3377 ar.goal = ext4_ext_find_goal(inode, path, iblock);
3378 ar.logical = iblock;
3379 ar.len = allocated;
3380 if (S_ISREG(inode->i_mode))
3381 ar.flags = EXT4_MB_HINT_DATA;
3382 else
3383 /* disable in-core preallocation for non-regular files */
3384 ar.flags = 0;
3385 newblock = ext4_mb_new_blocks(handle, &ar, &err);
3386 if (!newblock)
3387 goto out2;
3388 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
3389 ar.goal, newblock, allocated);
3391 /* try to insert new extent into found leaf and return */
3392 ext4_ext_store_pblock(&newex, newblock);
3393 newex.ee_len = cpu_to_le16(ar.len);
3394 /* Mark uninitialized */
3395 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
3396 ext4_ext_mark_uninitialized(&newex);
3398 * io_end structure was created for every async
3399 * direct IO write to the middle of the file.
3400 * To avoid unecessary convertion for every aio dio rewrite
3401 * to the mid of file, here we flag the IO that is really
3402 * need the convertion.
3403 * For non asycn direct IO case, flag the inode state
3404 * that we need to perform convertion when IO is done.
3406 if (flags == EXT4_GET_BLOCKS_DIO_CREATE_EXT) {
3407 if (io)
3408 io->flag = DIO_AIO_UNWRITTEN;
3409 else
3410 ext4_set_inode_state(inode,
3411 EXT4_STATE_DIO_UNWRITTEN);
3415 if (unlikely(ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))) {
3416 if (unlikely(!eh->eh_entries)) {
3417 ext4_error(inode->i_sb, __func__,
3418 "inode#%lu, eh->eh_entries = 0 and "
3419 "EOFBLOCKS_FL set", inode->i_ino);
3420 err = -EIO;
3421 goto out2;
3423 last_ex = EXT_LAST_EXTENT(eh);
3425 * If the current leaf block was reached by looking at
3426 * the last index block all the way down the tree, and
3427 * we are extending the inode beyond the last extent
3428 * in the current leaf block, then clear the
3429 * EOFBLOCKS_FL flag.
3431 for (i = depth-1; i >= 0; i--) {
3432 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3433 break;
3435 if ((i < 0) &&
3436 (iblock + ar.len > le32_to_cpu(last_ex->ee_block) +
3437 ext4_ext_get_actual_len(last_ex)))
3438 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3440 err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
3441 if (err) {
3442 /* free data blocks we just allocated */
3443 /* not a good idea to call discard here directly,
3444 * but otherwise we'd need to call it every free() */
3445 ext4_discard_preallocations(inode);
3446 ext4_free_blocks(handle, inode, ext_pblock(&newex),
3447 ext4_ext_get_actual_len(&newex), 0);
3448 goto out2;
3451 /* previous routine could use block we allocated */
3452 newblock = ext_pblock(&newex);
3453 allocated = ext4_ext_get_actual_len(&newex);
3454 if (allocated > max_blocks)
3455 allocated = max_blocks;
3456 set_buffer_new(bh_result);
3459 * Update reserved blocks/metadata blocks after successful
3460 * block allocation which had been deferred till now.
3462 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3463 ext4_da_update_reserve_space(inode, allocated, 1);
3466 * Cache the extent and update transaction to commit on fdatasync only
3467 * when it is _not_ an uninitialized extent.
3469 if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
3470 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
3471 EXT4_EXT_CACHE_EXTENT);
3472 ext4_update_inode_fsync_trans(handle, inode, 1);
3473 } else
3474 ext4_update_inode_fsync_trans(handle, inode, 0);
3475 out:
3476 if (allocated > max_blocks)
3477 allocated = max_blocks;
3478 ext4_ext_show_leaf(inode, path);
3479 set_buffer_mapped(bh_result);
3480 bh_result->b_bdev = inode->i_sb->s_bdev;
3481 bh_result->b_blocknr = newblock;
3482 out2:
3483 if (path) {
3484 ext4_ext_drop_refs(path);
3485 kfree(path);
3487 return err ? err : allocated;
3490 void ext4_ext_truncate(struct inode *inode)
3492 struct address_space *mapping = inode->i_mapping;
3493 struct super_block *sb = inode->i_sb;
3494 ext4_lblk_t last_block;
3495 handle_t *handle;
3496 int err = 0;
3499 * probably first extent we're gonna free will be last in block
3501 err = ext4_writepage_trans_blocks(inode);
3502 handle = ext4_journal_start(inode, err);
3503 if (IS_ERR(handle))
3504 return;
3506 if (inode->i_size & (sb->s_blocksize - 1))
3507 ext4_block_truncate_page(handle, mapping, inode->i_size);
3509 if (ext4_orphan_add(handle, inode))
3510 goto out_stop;
3512 down_write(&EXT4_I(inode)->i_data_sem);
3513 ext4_ext_invalidate_cache(inode);
3515 ext4_discard_preallocations(inode);
3518 * TODO: optimization is possible here.
3519 * Probably we need not scan at all,
3520 * because page truncation is enough.
3523 /* we have to know where to truncate from in crash case */
3524 EXT4_I(inode)->i_disksize = inode->i_size;
3525 ext4_mark_inode_dirty(handle, inode);
3527 last_block = (inode->i_size + sb->s_blocksize - 1)
3528 >> EXT4_BLOCK_SIZE_BITS(sb);
3529 err = ext4_ext_remove_space(inode, last_block);
3531 /* In a multi-transaction truncate, we only make the final
3532 * transaction synchronous.
3534 if (IS_SYNC(inode))
3535 ext4_handle_sync(handle);
3537 out_stop:
3538 up_write(&EXT4_I(inode)->i_data_sem);
3540 * If this was a simple ftruncate() and the file will remain alive,
3541 * then we need to clear up the orphan record which we created above.
3542 * However, if this was a real unlink then we were called by
3543 * ext4_delete_inode(), and we allow that function to clean up the
3544 * orphan info for us.
3546 if (inode->i_nlink)
3547 ext4_orphan_del(handle, inode);
3549 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3550 ext4_mark_inode_dirty(handle, inode);
3551 ext4_journal_stop(handle);
3554 static void ext4_falloc_update_inode(struct inode *inode,
3555 int mode, loff_t new_size, int update_ctime)
3557 struct timespec now;
3559 if (update_ctime) {
3560 now = current_fs_time(inode->i_sb);
3561 if (!timespec_equal(&inode->i_ctime, &now))
3562 inode->i_ctime = now;
3565 * Update only when preallocation was requested beyond
3566 * the file size.
3568 if (!(mode & FALLOC_FL_KEEP_SIZE)) {
3569 if (new_size > i_size_read(inode))
3570 i_size_write(inode, new_size);
3571 if (new_size > EXT4_I(inode)->i_disksize)
3572 ext4_update_i_disksize(inode, new_size);
3573 } else {
3575 * Mark that we allocate beyond EOF so the subsequent truncate
3576 * can proceed even if the new size is the same as i_size.
3578 if (new_size > i_size_read(inode))
3579 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3585 * preallocate space for a file. This implements ext4's fallocate inode
3586 * operation, which gets called from sys_fallocate system call.
3587 * For block-mapped files, posix_fallocate should fall back to the method
3588 * of writing zeroes to the required new blocks (the same behavior which is
3589 * expected for file systems which do not support fallocate() system call).
3591 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
3593 handle_t *handle;
3594 ext4_lblk_t block;
3595 loff_t new_size;
3596 unsigned int max_blocks;
3597 int ret = 0;
3598 int ret2 = 0;
3599 int retries = 0;
3600 struct buffer_head map_bh;
3601 unsigned int credits, blkbits = inode->i_blkbits;
3604 * currently supporting (pre)allocate mode for extent-based
3605 * files _only_
3607 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
3608 return -EOPNOTSUPP;
3610 /* preallocation to directories is currently not supported */
3611 if (S_ISDIR(inode->i_mode))
3612 return -ENODEV;
3614 block = offset >> blkbits;
3616 * We can't just convert len to max_blocks because
3617 * If blocksize = 4096 offset = 3072 and len = 2048
3619 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3620 - block;
3622 * credits to insert 1 extent into extent tree
3624 credits = ext4_chunk_trans_blocks(inode, max_blocks);
3625 mutex_lock(&inode->i_mutex);
3626 ret = inode_newsize_ok(inode, (len + offset));
3627 if (ret) {
3628 mutex_unlock(&inode->i_mutex);
3629 return ret;
3631 retry:
3632 while (ret >= 0 && ret < max_blocks) {
3633 block = block + ret;
3634 max_blocks = max_blocks - ret;
3635 handle = ext4_journal_start(inode, credits);
3636 if (IS_ERR(handle)) {
3637 ret = PTR_ERR(handle);
3638 break;
3640 map_bh.b_state = 0;
3641 ret = ext4_get_blocks(handle, inode, block,
3642 max_blocks, &map_bh,
3643 EXT4_GET_BLOCKS_CREATE_UNINIT_EXT);
3644 if (ret <= 0) {
3645 #ifdef EXT4FS_DEBUG
3646 WARN_ON(ret <= 0);
3647 printk(KERN_ERR "%s: ext4_ext_get_blocks "
3648 "returned error inode#%lu, block=%u, "
3649 "max_blocks=%u", __func__,
3650 inode->i_ino, block, max_blocks);
3651 #endif
3652 ext4_mark_inode_dirty(handle, inode);
3653 ret2 = ext4_journal_stop(handle);
3654 break;
3656 if ((block + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
3657 blkbits) >> blkbits))
3658 new_size = offset + len;
3659 else
3660 new_size = (block + ret) << blkbits;
3662 ext4_falloc_update_inode(inode, mode, new_size,
3663 buffer_new(&map_bh));
3664 ext4_mark_inode_dirty(handle, inode);
3665 ret2 = ext4_journal_stop(handle);
3666 if (ret2)
3667 break;
3669 if (ret == -ENOSPC &&
3670 ext4_should_retry_alloc(inode->i_sb, &retries)) {
3671 ret = 0;
3672 goto retry;
3674 mutex_unlock(&inode->i_mutex);
3675 return ret > 0 ? ret2 : ret;
3679 * This function convert a range of blocks to written extents
3680 * The caller of this function will pass the start offset and the size.
3681 * all unwritten extents within this range will be converted to
3682 * written extents.
3684 * This function is called from the direct IO end io call back
3685 * function, to convert the fallocated extents after IO is completed.
3686 * Returns 0 on success.
3688 int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
3689 ssize_t len)
3691 handle_t *handle;
3692 ext4_lblk_t block;
3693 unsigned int max_blocks;
3694 int ret = 0;
3695 int ret2 = 0;
3696 struct buffer_head map_bh;
3697 unsigned int credits, blkbits = inode->i_blkbits;
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 while (ret >= 0 && ret < max_blocks) {
3711 block = block + ret;
3712 max_blocks = max_blocks - ret;
3713 handle = ext4_journal_start(inode, credits);
3714 if (IS_ERR(handle)) {
3715 ret = PTR_ERR(handle);
3716 break;
3718 map_bh.b_state = 0;
3719 ret = ext4_get_blocks(handle, inode, block,
3720 max_blocks, &map_bh,
3721 EXT4_GET_BLOCKS_DIO_CONVERT_EXT);
3722 if (ret <= 0) {
3723 WARN_ON(ret <= 0);
3724 printk(KERN_ERR "%s: ext4_ext_get_blocks "
3725 "returned error inode#%lu, block=%u, "
3726 "max_blocks=%u", __func__,
3727 inode->i_ino, block, max_blocks);
3729 ext4_mark_inode_dirty(handle, inode);
3730 ret2 = ext4_journal_stop(handle);
3731 if (ret <= 0 || ret2 )
3732 break;
3734 return ret > 0 ? ret2 : ret;
3737 * Callback function called for each extent to gather FIEMAP information.
3739 static int ext4_ext_fiemap_cb(struct inode *inode, struct ext4_ext_path *path,
3740 struct ext4_ext_cache *newex, struct ext4_extent *ex,
3741 void *data)
3743 struct fiemap_extent_info *fieinfo = data;
3744 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
3745 __u64 logical;
3746 __u64 physical;
3747 __u64 length;
3748 __u32 flags = 0;
3749 int error;
3751 logical = (__u64)newex->ec_block << blksize_bits;
3753 if (newex->ec_type == EXT4_EXT_CACHE_GAP) {
3754 pgoff_t offset;
3755 struct page *page;
3756 struct buffer_head *bh = NULL;
3758 offset = logical >> PAGE_SHIFT;
3759 page = find_get_page(inode->i_mapping, offset);
3760 if (!page || !page_has_buffers(page))
3761 return EXT_CONTINUE;
3763 bh = page_buffers(page);
3765 if (!bh)
3766 return EXT_CONTINUE;
3768 if (buffer_delay(bh)) {
3769 flags |= FIEMAP_EXTENT_DELALLOC;
3770 page_cache_release(page);
3771 } else {
3772 page_cache_release(page);
3773 return EXT_CONTINUE;
3777 physical = (__u64)newex->ec_start << blksize_bits;
3778 length = (__u64)newex->ec_len << blksize_bits;
3780 if (ex && ext4_ext_is_uninitialized(ex))
3781 flags |= FIEMAP_EXTENT_UNWRITTEN;
3784 * If this extent reaches EXT_MAX_BLOCK, it must be last.
3786 * Or if ext4_ext_next_allocated_block is EXT_MAX_BLOCK,
3787 * this also indicates no more allocated blocks.
3789 * XXX this might miss a single-block extent at EXT_MAX_BLOCK
3791 if (ext4_ext_next_allocated_block(path) == EXT_MAX_BLOCK ||
3792 newex->ec_block + newex->ec_len - 1 == EXT_MAX_BLOCK) {
3793 loff_t size = i_size_read(inode);
3794 loff_t bs = EXT4_BLOCK_SIZE(inode->i_sb);
3796 flags |= FIEMAP_EXTENT_LAST;
3797 if ((flags & FIEMAP_EXTENT_DELALLOC) &&
3798 logical+length > size)
3799 length = (size - logical + bs - 1) & ~(bs-1);
3802 error = fiemap_fill_next_extent(fieinfo, logical, physical,
3803 length, flags);
3804 if (error < 0)
3805 return error;
3806 if (error == 1)
3807 return EXT_BREAK;
3809 return EXT_CONTINUE;
3812 /* fiemap flags we can handle specified here */
3813 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
3815 static int ext4_xattr_fiemap(struct inode *inode,
3816 struct fiemap_extent_info *fieinfo)
3818 __u64 physical = 0;
3819 __u64 length;
3820 __u32 flags = FIEMAP_EXTENT_LAST;
3821 int blockbits = inode->i_sb->s_blocksize_bits;
3822 int error = 0;
3824 /* in-inode? */
3825 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
3826 struct ext4_iloc iloc;
3827 int offset; /* offset of xattr in inode */
3829 error = ext4_get_inode_loc(inode, &iloc);
3830 if (error)
3831 return error;
3832 physical = iloc.bh->b_blocknr << blockbits;
3833 offset = EXT4_GOOD_OLD_INODE_SIZE +
3834 EXT4_I(inode)->i_extra_isize;
3835 physical += offset;
3836 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
3837 flags |= FIEMAP_EXTENT_DATA_INLINE;
3838 brelse(iloc.bh);
3839 } else { /* external block */
3840 physical = EXT4_I(inode)->i_file_acl << blockbits;
3841 length = inode->i_sb->s_blocksize;
3844 if (physical)
3845 error = fiemap_fill_next_extent(fieinfo, 0, physical,
3846 length, flags);
3847 return (error < 0 ? error : 0);
3850 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3851 __u64 start, __u64 len)
3853 ext4_lblk_t start_blk;
3854 int error = 0;
3856 /* fallback to generic here if not in extents fmt */
3857 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
3858 return generic_block_fiemap(inode, fieinfo, start, len,
3859 ext4_get_block);
3861 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
3862 return -EBADR;
3864 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
3865 error = ext4_xattr_fiemap(inode, fieinfo);
3866 } else {
3867 ext4_lblk_t len_blks;
3868 __u64 last_blk;
3870 start_blk = start >> inode->i_sb->s_blocksize_bits;
3871 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
3872 if (last_blk >= EXT_MAX_BLOCK)
3873 last_blk = EXT_MAX_BLOCK-1;
3874 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
3877 * Walk the extent tree gathering extent information.
3878 * ext4_ext_fiemap_cb will push extents back to user.
3880 error = ext4_ext_walk_space(inode, start_blk, len_blks,
3881 ext4_ext_fiemap_cb, fieinfo);
3884 return error;