mm: fix exec activate_mm vs TLB shootdown and lazy tlb switching race
[linux/fpc-iii.git] / fs / ext4 / extents.c
blobfc6bc261f7ace62a4186719b391e2b487ab758de
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 License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
24 * Extents support for EXT4
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/fs.h>
33 #include <linux/time.h>
34 #include <linux/jbd2.h>
35 #include <linux/highuid.h>
36 #include <linux/pagemap.h>
37 #include <linux/quotaops.h>
38 #include <linux/string.h>
39 #include <linux/slab.h>
40 #include <linux/uaccess.h>
41 #include <linux/fiemap.h>
42 #include <linux/backing-dev.h>
43 #include "ext4_jbd2.h"
44 #include "ext4_extents.h"
45 #include "xattr.h"
47 #include <trace/events/ext4.h>
50 * used by extent splitting.
52 #define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
53 due to ENOSPC */
54 #define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
55 #define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
57 #define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
58 #define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
60 static __le32 ext4_extent_block_csum(struct inode *inode,
61 struct ext4_extent_header *eh)
63 struct ext4_inode_info *ei = EXT4_I(inode);
64 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
65 __u32 csum;
67 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
68 EXT4_EXTENT_TAIL_OFFSET(eh));
69 return cpu_to_le32(csum);
72 static int ext4_extent_block_csum_verify(struct inode *inode,
73 struct ext4_extent_header *eh)
75 struct ext4_extent_tail *et;
77 if (!ext4_has_metadata_csum(inode->i_sb))
78 return 1;
80 et = find_ext4_extent_tail(eh);
81 if (et->et_checksum != ext4_extent_block_csum(inode, eh))
82 return 0;
83 return 1;
86 static void ext4_extent_block_csum_set(struct inode *inode,
87 struct ext4_extent_header *eh)
89 struct ext4_extent_tail *et;
91 if (!ext4_has_metadata_csum(inode->i_sb))
92 return;
94 et = find_ext4_extent_tail(eh);
95 et->et_checksum = ext4_extent_block_csum(inode, eh);
98 static int ext4_split_extent(handle_t *handle,
99 struct inode *inode,
100 struct ext4_ext_path **ppath,
101 struct ext4_map_blocks *map,
102 int split_flag,
103 int flags);
105 static int ext4_split_extent_at(handle_t *handle,
106 struct inode *inode,
107 struct ext4_ext_path **ppath,
108 ext4_lblk_t split,
109 int split_flag,
110 int flags);
112 static int ext4_find_delayed_extent(struct inode *inode,
113 struct extent_status *newes);
115 static int ext4_ext_truncate_extend_restart(handle_t *handle,
116 struct inode *inode,
117 int needed)
119 int err;
121 if (!ext4_handle_valid(handle))
122 return 0;
123 if (handle->h_buffer_credits >= needed)
124 return 0;
126 * If we need to extend the journal get a few extra blocks
127 * while we're at it for efficiency's sake.
129 needed += 3;
130 err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
131 if (err <= 0)
132 return err;
133 err = ext4_truncate_restart_trans(handle, inode, needed);
134 if (err == 0)
135 err = -EAGAIN;
137 return err;
141 * could return:
142 * - EROFS
143 * - ENOMEM
145 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
146 struct ext4_ext_path *path)
148 if (path->p_bh) {
149 /* path points to block */
150 BUFFER_TRACE(path->p_bh, "get_write_access");
151 return ext4_journal_get_write_access(handle, path->p_bh);
153 /* path points to leaf/index in inode body */
154 /* we use in-core data, no need to protect them */
155 return 0;
159 * could return:
160 * - EROFS
161 * - ENOMEM
162 * - EIO
164 int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
165 struct inode *inode, struct ext4_ext_path *path)
167 int err;
169 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
170 if (path->p_bh) {
171 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
172 /* path points to block */
173 err = __ext4_handle_dirty_metadata(where, line, handle,
174 inode, path->p_bh);
175 } else {
176 /* path points to leaf/index in inode body */
177 err = ext4_mark_inode_dirty(handle, inode);
179 return err;
182 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
183 struct ext4_ext_path *path,
184 ext4_lblk_t block)
186 if (path) {
187 int depth = path->p_depth;
188 struct ext4_extent *ex;
191 * Try to predict block placement assuming that we are
192 * filling in a file which will eventually be
193 * non-sparse --- i.e., in the case of libbfd writing
194 * an ELF object sections out-of-order but in a way
195 * the eventually results in a contiguous object or
196 * executable file, or some database extending a table
197 * space file. However, this is actually somewhat
198 * non-ideal if we are writing a sparse file such as
199 * qemu or KVM writing a raw image file that is going
200 * to stay fairly sparse, since it will end up
201 * fragmenting the file system's free space. Maybe we
202 * should have some hueristics or some way to allow
203 * userspace to pass a hint to file system,
204 * especially if the latter case turns out to be
205 * common.
207 ex = path[depth].p_ext;
208 if (ex) {
209 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
210 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
212 if (block > ext_block)
213 return ext_pblk + (block - ext_block);
214 else
215 return ext_pblk - (ext_block - block);
218 /* it looks like index is empty;
219 * try to find starting block from index itself */
220 if (path[depth].p_bh)
221 return path[depth].p_bh->b_blocknr;
224 /* OK. use inode's group */
225 return ext4_inode_to_goal_block(inode);
229 * Allocation for a meta data block
231 static ext4_fsblk_t
232 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
233 struct ext4_ext_path *path,
234 struct ext4_extent *ex, int *err, unsigned int flags)
236 ext4_fsblk_t goal, newblock;
238 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
239 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
240 NULL, err);
241 return newblock;
244 static inline int ext4_ext_space_block(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);
250 #ifdef AGGRESSIVE_TEST
251 if (!check && size > 6)
252 size = 6;
253 #endif
254 return size;
257 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
259 int size;
261 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
262 / sizeof(struct ext4_extent_idx);
263 #ifdef AGGRESSIVE_TEST
264 if (!check && size > 5)
265 size = 5;
266 #endif
267 return size;
270 static inline int ext4_ext_space_root(struct inode *inode, int check)
272 int size;
274 size = sizeof(EXT4_I(inode)->i_data);
275 size -= sizeof(struct ext4_extent_header);
276 size /= sizeof(struct ext4_extent);
277 #ifdef AGGRESSIVE_TEST
278 if (!check && size > 3)
279 size = 3;
280 #endif
281 return size;
284 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
286 int size;
288 size = sizeof(EXT4_I(inode)->i_data);
289 size -= sizeof(struct ext4_extent_header);
290 size /= sizeof(struct ext4_extent_idx);
291 #ifdef AGGRESSIVE_TEST
292 if (!check && size > 4)
293 size = 4;
294 #endif
295 return size;
298 static inline int
299 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
300 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
301 int nofail)
303 struct ext4_ext_path *path = *ppath;
304 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
306 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
307 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
308 EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
309 (nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
313 * Calculate the number of metadata blocks needed
314 * to allocate @blocks
315 * Worse case is one block per extent
317 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
319 struct ext4_inode_info *ei = EXT4_I(inode);
320 int idxs;
322 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
323 / sizeof(struct ext4_extent_idx));
326 * If the new delayed allocation block is contiguous with the
327 * previous da block, it can share index blocks with the
328 * previous block, so we only need to allocate a new index
329 * block every idxs leaf blocks. At ldxs**2 blocks, we need
330 * an additional index block, and at ldxs**3 blocks, yet
331 * another index blocks.
333 if (ei->i_da_metadata_calc_len &&
334 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
335 int num = 0;
337 if ((ei->i_da_metadata_calc_len % idxs) == 0)
338 num++;
339 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
340 num++;
341 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
342 num++;
343 ei->i_da_metadata_calc_len = 0;
344 } else
345 ei->i_da_metadata_calc_len++;
346 ei->i_da_metadata_calc_last_lblock++;
347 return num;
351 * In the worst case we need a new set of index blocks at
352 * every level of the inode's extent tree.
354 ei->i_da_metadata_calc_len = 1;
355 ei->i_da_metadata_calc_last_lblock = lblock;
356 return ext_depth(inode) + 1;
359 static int
360 ext4_ext_max_entries(struct inode *inode, int depth)
362 int max;
364 if (depth == ext_depth(inode)) {
365 if (depth == 0)
366 max = ext4_ext_space_root(inode, 1);
367 else
368 max = ext4_ext_space_root_idx(inode, 1);
369 } else {
370 if (depth == 0)
371 max = ext4_ext_space_block(inode, 1);
372 else
373 max = ext4_ext_space_block_idx(inode, 1);
376 return max;
379 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
381 ext4_fsblk_t block = ext4_ext_pblock(ext);
382 int len = ext4_ext_get_actual_len(ext);
383 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
386 * We allow neither:
387 * - zero length
388 * - overflow/wrap-around
390 if (lblock + len <= lblock)
391 return 0;
392 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
395 static int ext4_valid_extent_idx(struct inode *inode,
396 struct ext4_extent_idx *ext_idx)
398 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
400 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
403 static int ext4_valid_extent_entries(struct inode *inode,
404 struct ext4_extent_header *eh,
405 int depth)
407 unsigned short entries;
408 if (eh->eh_entries == 0)
409 return 1;
411 entries = le16_to_cpu(eh->eh_entries);
413 if (depth == 0) {
414 /* leaf entries */
415 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
416 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
417 ext4_fsblk_t pblock = 0;
418 ext4_lblk_t lblock = 0;
419 ext4_lblk_t prev = 0;
420 int len = 0;
421 while (entries) {
422 if (!ext4_valid_extent(inode, ext))
423 return 0;
425 /* Check for overlapping extents */
426 lblock = le32_to_cpu(ext->ee_block);
427 len = ext4_ext_get_actual_len(ext);
428 if ((lblock <= prev) && prev) {
429 pblock = ext4_ext_pblock(ext);
430 es->s_last_error_block = cpu_to_le64(pblock);
431 return 0;
433 ext++;
434 entries--;
435 prev = lblock + len - 1;
437 } else {
438 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
439 while (entries) {
440 if (!ext4_valid_extent_idx(inode, ext_idx))
441 return 0;
442 ext_idx++;
443 entries--;
446 return 1;
449 static int __ext4_ext_check(const char *function, unsigned int line,
450 struct inode *inode, struct ext4_extent_header *eh,
451 int depth, ext4_fsblk_t pblk)
453 const char *error_msg;
454 int max = 0, err = -EFSCORRUPTED;
456 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
457 error_msg = "invalid magic";
458 goto corrupted;
460 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
461 error_msg = "unexpected eh_depth";
462 goto corrupted;
464 if (unlikely(eh->eh_max == 0)) {
465 error_msg = "invalid eh_max";
466 goto corrupted;
468 max = ext4_ext_max_entries(inode, depth);
469 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
470 error_msg = "too large eh_max";
471 goto corrupted;
473 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
474 error_msg = "invalid eh_entries";
475 goto corrupted;
477 if (!ext4_valid_extent_entries(inode, eh, depth)) {
478 error_msg = "invalid extent entries";
479 goto corrupted;
481 if (unlikely(depth > 32)) {
482 error_msg = "too large eh_depth";
483 goto corrupted;
485 /* Verify checksum on non-root extent tree nodes */
486 if (ext_depth(inode) != depth &&
487 !ext4_extent_block_csum_verify(inode, eh)) {
488 error_msg = "extent tree corrupted";
489 err = -EFSBADCRC;
490 goto corrupted;
492 return 0;
494 corrupted:
495 ext4_error_inode(inode, function, line, 0,
496 "pblk %llu bad header/extent: %s - magic %x, "
497 "entries %u, max %u(%u), depth %u(%u)",
498 (unsigned long long) pblk, error_msg,
499 le16_to_cpu(eh->eh_magic),
500 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
501 max, le16_to_cpu(eh->eh_depth), depth);
502 return err;
505 #define ext4_ext_check(inode, eh, depth, pblk) \
506 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
508 int ext4_ext_check_inode(struct inode *inode)
510 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
513 static void ext4_cache_extents(struct inode *inode,
514 struct ext4_extent_header *eh)
516 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
517 ext4_lblk_t prev = 0;
518 int i;
520 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
521 unsigned int status = EXTENT_STATUS_WRITTEN;
522 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
523 int len = ext4_ext_get_actual_len(ex);
525 if (prev && (prev != lblk))
526 ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
527 EXTENT_STATUS_HOLE);
529 if (ext4_ext_is_unwritten(ex))
530 status = EXTENT_STATUS_UNWRITTEN;
531 ext4_es_cache_extent(inode, lblk, len,
532 ext4_ext_pblock(ex), status);
533 prev = lblk + len;
537 static struct buffer_head *
538 __read_extent_tree_block(const char *function, unsigned int line,
539 struct inode *inode, ext4_fsblk_t pblk, int depth,
540 int flags)
542 struct buffer_head *bh;
543 int err;
545 bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
546 if (unlikely(!bh))
547 return ERR_PTR(-ENOMEM);
549 if (!bh_uptodate_or_lock(bh)) {
550 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
551 err = bh_submit_read(bh);
552 if (err < 0)
553 goto errout;
555 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
556 return bh;
557 if (!ext4_has_feature_journal(inode->i_sb) ||
558 (inode->i_ino !=
559 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum))) {
560 err = __ext4_ext_check(function, line, inode,
561 ext_block_hdr(bh), depth, pblk);
562 if (err)
563 goto errout;
565 set_buffer_verified(bh);
567 * If this is a leaf block, cache all of its entries
569 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
570 struct ext4_extent_header *eh = ext_block_hdr(bh);
571 ext4_cache_extents(inode, eh);
573 return bh;
574 errout:
575 put_bh(bh);
576 return ERR_PTR(err);
580 #define read_extent_tree_block(inode, pblk, depth, flags) \
581 __read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
582 (depth), (flags))
585 * This function is called to cache a file's extent information in the
586 * extent status tree
588 int ext4_ext_precache(struct inode *inode)
590 struct ext4_inode_info *ei = EXT4_I(inode);
591 struct ext4_ext_path *path = NULL;
592 struct buffer_head *bh;
593 int i = 0, depth, ret = 0;
595 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
596 return 0; /* not an extent-mapped inode */
598 down_read(&ei->i_data_sem);
599 depth = ext_depth(inode);
601 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
602 GFP_NOFS);
603 if (path == NULL) {
604 up_read(&ei->i_data_sem);
605 return -ENOMEM;
608 /* Don't cache anything if there are no external extent blocks */
609 if (depth == 0)
610 goto out;
611 path[0].p_hdr = ext_inode_hdr(inode);
612 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
613 if (ret)
614 goto out;
615 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
616 while (i >= 0) {
618 * If this is a leaf block or we've reached the end of
619 * the index block, go up
621 if ((i == depth) ||
622 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
623 brelse(path[i].p_bh);
624 path[i].p_bh = NULL;
625 i--;
626 continue;
628 bh = read_extent_tree_block(inode,
629 ext4_idx_pblock(path[i].p_idx++),
630 depth - i - 1,
631 EXT4_EX_FORCE_CACHE);
632 if (IS_ERR(bh)) {
633 ret = PTR_ERR(bh);
634 break;
636 i++;
637 path[i].p_bh = bh;
638 path[i].p_hdr = ext_block_hdr(bh);
639 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
641 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
642 out:
643 up_read(&ei->i_data_sem);
644 ext4_ext_drop_refs(path);
645 kfree(path);
646 return ret;
649 #ifdef EXT_DEBUG
650 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
652 int k, l = path->p_depth;
654 ext_debug("path:");
655 for (k = 0; k <= l; k++, path++) {
656 if (path->p_idx) {
657 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
658 ext4_idx_pblock(path->p_idx));
659 } else if (path->p_ext) {
660 ext_debug(" %d:[%d]%d:%llu ",
661 le32_to_cpu(path->p_ext->ee_block),
662 ext4_ext_is_unwritten(path->p_ext),
663 ext4_ext_get_actual_len(path->p_ext),
664 ext4_ext_pblock(path->p_ext));
665 } else
666 ext_debug(" []");
668 ext_debug("\n");
671 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
673 int depth = ext_depth(inode);
674 struct ext4_extent_header *eh;
675 struct ext4_extent *ex;
676 int i;
678 if (!path)
679 return;
681 eh = path[depth].p_hdr;
682 ex = EXT_FIRST_EXTENT(eh);
684 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
686 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
687 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
688 ext4_ext_is_unwritten(ex),
689 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
691 ext_debug("\n");
694 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
695 ext4_fsblk_t newblock, int level)
697 int depth = ext_depth(inode);
698 struct ext4_extent *ex;
700 if (depth != level) {
701 struct ext4_extent_idx *idx;
702 idx = path[level].p_idx;
703 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
704 ext_debug("%d: move %d:%llu in new index %llu\n", level,
705 le32_to_cpu(idx->ei_block),
706 ext4_idx_pblock(idx),
707 newblock);
708 idx++;
711 return;
714 ex = path[depth].p_ext;
715 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
716 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
717 le32_to_cpu(ex->ee_block),
718 ext4_ext_pblock(ex),
719 ext4_ext_is_unwritten(ex),
720 ext4_ext_get_actual_len(ex),
721 newblock);
722 ex++;
726 #else
727 #define ext4_ext_show_path(inode, path)
728 #define ext4_ext_show_leaf(inode, path)
729 #define ext4_ext_show_move(inode, path, newblock, level)
730 #endif
732 void ext4_ext_drop_refs(struct ext4_ext_path *path)
734 int depth, i;
736 if (!path)
737 return;
738 depth = path->p_depth;
739 for (i = 0; i <= depth; i++, path++)
740 if (path->p_bh) {
741 brelse(path->p_bh);
742 path->p_bh = NULL;
747 * ext4_ext_binsearch_idx:
748 * binary search for the closest index of the given block
749 * the header must be checked before calling this
751 static void
752 ext4_ext_binsearch_idx(struct inode *inode,
753 struct ext4_ext_path *path, ext4_lblk_t block)
755 struct ext4_extent_header *eh = path->p_hdr;
756 struct ext4_extent_idx *r, *l, *m;
759 ext_debug("binsearch for %u(idx): ", block);
761 l = EXT_FIRST_INDEX(eh) + 1;
762 r = EXT_LAST_INDEX(eh);
763 while (l <= r) {
764 m = l + (r - l) / 2;
765 if (block < le32_to_cpu(m->ei_block))
766 r = m - 1;
767 else
768 l = m + 1;
769 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
770 m, le32_to_cpu(m->ei_block),
771 r, le32_to_cpu(r->ei_block));
774 path->p_idx = l - 1;
775 ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
776 ext4_idx_pblock(path->p_idx));
778 #ifdef CHECK_BINSEARCH
780 struct ext4_extent_idx *chix, *ix;
781 int k;
783 chix = ix = EXT_FIRST_INDEX(eh);
784 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
785 if (k != 0 &&
786 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
787 printk(KERN_DEBUG "k=%d, ix=0x%p, "
788 "first=0x%p\n", k,
789 ix, EXT_FIRST_INDEX(eh));
790 printk(KERN_DEBUG "%u <= %u\n",
791 le32_to_cpu(ix->ei_block),
792 le32_to_cpu(ix[-1].ei_block));
794 BUG_ON(k && le32_to_cpu(ix->ei_block)
795 <= le32_to_cpu(ix[-1].ei_block));
796 if (block < le32_to_cpu(ix->ei_block))
797 break;
798 chix = ix;
800 BUG_ON(chix != path->p_idx);
802 #endif
807 * ext4_ext_binsearch:
808 * binary search for closest extent of the given block
809 * the header must be checked before calling this
811 static void
812 ext4_ext_binsearch(struct inode *inode,
813 struct ext4_ext_path *path, ext4_lblk_t block)
815 struct ext4_extent_header *eh = path->p_hdr;
816 struct ext4_extent *r, *l, *m;
818 if (eh->eh_entries == 0) {
820 * this leaf is empty:
821 * we get such a leaf in split/add case
823 return;
826 ext_debug("binsearch for %u: ", block);
828 l = EXT_FIRST_EXTENT(eh) + 1;
829 r = EXT_LAST_EXTENT(eh);
831 while (l <= r) {
832 m = l + (r - l) / 2;
833 if (block < le32_to_cpu(m->ee_block))
834 r = m - 1;
835 else
836 l = m + 1;
837 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
838 m, le32_to_cpu(m->ee_block),
839 r, le32_to_cpu(r->ee_block));
842 path->p_ext = l - 1;
843 ext_debug(" -> %d:%llu:[%d]%d ",
844 le32_to_cpu(path->p_ext->ee_block),
845 ext4_ext_pblock(path->p_ext),
846 ext4_ext_is_unwritten(path->p_ext),
847 ext4_ext_get_actual_len(path->p_ext));
849 #ifdef CHECK_BINSEARCH
851 struct ext4_extent *chex, *ex;
852 int k;
854 chex = ex = EXT_FIRST_EXTENT(eh);
855 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
856 BUG_ON(k && le32_to_cpu(ex->ee_block)
857 <= le32_to_cpu(ex[-1].ee_block));
858 if (block < le32_to_cpu(ex->ee_block))
859 break;
860 chex = ex;
862 BUG_ON(chex != path->p_ext);
864 #endif
868 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
870 struct ext4_extent_header *eh;
872 eh = ext_inode_hdr(inode);
873 eh->eh_depth = 0;
874 eh->eh_entries = 0;
875 eh->eh_magic = EXT4_EXT_MAGIC;
876 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
877 ext4_mark_inode_dirty(handle, inode);
878 return 0;
881 struct ext4_ext_path *
882 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
883 struct ext4_ext_path **orig_path, int flags)
885 struct ext4_extent_header *eh;
886 struct buffer_head *bh;
887 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
888 short int depth, i, ppos = 0;
889 int ret;
891 eh = ext_inode_hdr(inode);
892 depth = ext_depth(inode);
893 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
894 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
895 depth);
896 ret = -EFSCORRUPTED;
897 goto err;
900 if (path) {
901 ext4_ext_drop_refs(path);
902 if (depth > path[0].p_maxdepth) {
903 kfree(path);
904 *orig_path = path = NULL;
907 if (!path) {
908 /* account possible depth increase */
909 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
910 GFP_NOFS);
911 if (unlikely(!path))
912 return ERR_PTR(-ENOMEM);
913 path[0].p_maxdepth = depth + 1;
915 path[0].p_hdr = eh;
916 path[0].p_bh = NULL;
918 i = depth;
919 if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
920 ext4_cache_extents(inode, eh);
921 /* walk through the tree */
922 while (i) {
923 ext_debug("depth %d: num %d, max %d\n",
924 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
926 ext4_ext_binsearch_idx(inode, path + ppos, block);
927 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
928 path[ppos].p_depth = i;
929 path[ppos].p_ext = NULL;
931 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
932 flags);
933 if (IS_ERR(bh)) {
934 ret = PTR_ERR(bh);
935 goto err;
938 eh = ext_block_hdr(bh);
939 ppos++;
940 path[ppos].p_bh = bh;
941 path[ppos].p_hdr = eh;
944 path[ppos].p_depth = i;
945 path[ppos].p_ext = NULL;
946 path[ppos].p_idx = NULL;
948 /* find extent */
949 ext4_ext_binsearch(inode, path + ppos, block);
950 /* if not an empty leaf */
951 if (path[ppos].p_ext)
952 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
954 ext4_ext_show_path(inode, path);
956 return path;
958 err:
959 ext4_ext_drop_refs(path);
960 kfree(path);
961 if (orig_path)
962 *orig_path = NULL;
963 return ERR_PTR(ret);
967 * ext4_ext_insert_index:
968 * insert new index [@logical;@ptr] into the block at @curp;
969 * check where to insert: before @curp or after @curp
971 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
972 struct ext4_ext_path *curp,
973 int logical, ext4_fsblk_t ptr)
975 struct ext4_extent_idx *ix;
976 int len, err;
978 err = ext4_ext_get_access(handle, inode, curp);
979 if (err)
980 return err;
982 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
983 EXT4_ERROR_INODE(inode,
984 "logical %d == ei_block %d!",
985 logical, le32_to_cpu(curp->p_idx->ei_block));
986 return -EFSCORRUPTED;
989 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
990 >= le16_to_cpu(curp->p_hdr->eh_max))) {
991 EXT4_ERROR_INODE(inode,
992 "eh_entries %d >= eh_max %d!",
993 le16_to_cpu(curp->p_hdr->eh_entries),
994 le16_to_cpu(curp->p_hdr->eh_max));
995 return -EFSCORRUPTED;
998 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
999 /* insert after */
1000 ext_debug("insert new index %d after: %llu\n", logical, ptr);
1001 ix = curp->p_idx + 1;
1002 } else {
1003 /* insert before */
1004 ext_debug("insert new index %d before: %llu\n", logical, ptr);
1005 ix = curp->p_idx;
1008 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1009 BUG_ON(len < 0);
1010 if (len > 0) {
1011 ext_debug("insert new index %d: "
1012 "move %d indices from 0x%p to 0x%p\n",
1013 logical, len, ix, ix + 1);
1014 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1017 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1018 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1019 return -EFSCORRUPTED;
1022 ix->ei_block = cpu_to_le32(logical);
1023 ext4_idx_store_pblock(ix, ptr);
1024 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1026 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1027 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1028 return -EFSCORRUPTED;
1031 err = ext4_ext_dirty(handle, inode, curp);
1032 ext4_std_error(inode->i_sb, err);
1034 return err;
1038 * ext4_ext_split:
1039 * inserts new subtree into the path, using free index entry
1040 * at depth @at:
1041 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1042 * - makes decision where to split
1043 * - moves remaining extents and index entries (right to the split point)
1044 * into the newly allocated blocks
1045 * - initializes subtree
1047 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1048 unsigned int flags,
1049 struct ext4_ext_path *path,
1050 struct ext4_extent *newext, int at)
1052 struct buffer_head *bh = NULL;
1053 int depth = ext_depth(inode);
1054 struct ext4_extent_header *neh;
1055 struct ext4_extent_idx *fidx;
1056 int i = at, k, m, a;
1057 ext4_fsblk_t newblock, oldblock;
1058 __le32 border;
1059 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1060 int err = 0;
1061 size_t ext_size = 0;
1063 /* make decision: where to split? */
1064 /* FIXME: now decision is simplest: at current extent */
1066 /* if current leaf will be split, then we should use
1067 * border from split point */
1068 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1069 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1070 return -EFSCORRUPTED;
1072 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1073 border = path[depth].p_ext[1].ee_block;
1074 ext_debug("leaf will be split."
1075 " next leaf starts at %d\n",
1076 le32_to_cpu(border));
1077 } else {
1078 border = newext->ee_block;
1079 ext_debug("leaf will be added."
1080 " next leaf starts at %d\n",
1081 le32_to_cpu(border));
1085 * If error occurs, then we break processing
1086 * and mark filesystem read-only. index won't
1087 * be inserted and tree will be in consistent
1088 * state. Next mount will repair buffers too.
1092 * Get array to track all allocated blocks.
1093 * We need this to handle errors and free blocks
1094 * upon them.
1096 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
1097 if (!ablocks)
1098 return -ENOMEM;
1100 /* allocate all needed blocks */
1101 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1102 for (a = 0; a < depth - at; a++) {
1103 newblock = ext4_ext_new_meta_block(handle, inode, path,
1104 newext, &err, flags);
1105 if (newblock == 0)
1106 goto cleanup;
1107 ablocks[a] = newblock;
1110 /* initialize new leaf */
1111 newblock = ablocks[--a];
1112 if (unlikely(newblock == 0)) {
1113 EXT4_ERROR_INODE(inode, "newblock == 0!");
1114 err = -EFSCORRUPTED;
1115 goto cleanup;
1117 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1118 if (unlikely(!bh)) {
1119 err = -ENOMEM;
1120 goto cleanup;
1122 lock_buffer(bh);
1124 err = ext4_journal_get_create_access(handle, bh);
1125 if (err)
1126 goto cleanup;
1128 neh = ext_block_hdr(bh);
1129 neh->eh_entries = 0;
1130 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1131 neh->eh_magic = EXT4_EXT_MAGIC;
1132 neh->eh_depth = 0;
1134 /* move remainder of path[depth] to the new leaf */
1135 if (unlikely(path[depth].p_hdr->eh_entries !=
1136 path[depth].p_hdr->eh_max)) {
1137 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1138 path[depth].p_hdr->eh_entries,
1139 path[depth].p_hdr->eh_max);
1140 err = -EFSCORRUPTED;
1141 goto cleanup;
1143 /* start copy from next extent */
1144 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1145 ext4_ext_show_move(inode, path, newblock, depth);
1146 if (m) {
1147 struct ext4_extent *ex;
1148 ex = EXT_FIRST_EXTENT(neh);
1149 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1150 le16_add_cpu(&neh->eh_entries, m);
1153 /* zero out unused area in the extent block */
1154 ext_size = sizeof(struct ext4_extent_header) +
1155 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1156 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1157 ext4_extent_block_csum_set(inode, neh);
1158 set_buffer_uptodate(bh);
1159 unlock_buffer(bh);
1161 err = ext4_handle_dirty_metadata(handle, inode, bh);
1162 if (err)
1163 goto cleanup;
1164 brelse(bh);
1165 bh = NULL;
1167 /* correct old leaf */
1168 if (m) {
1169 err = ext4_ext_get_access(handle, inode, path + depth);
1170 if (err)
1171 goto cleanup;
1172 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1173 err = ext4_ext_dirty(handle, inode, path + depth);
1174 if (err)
1175 goto cleanup;
1179 /* create intermediate indexes */
1180 k = depth - at - 1;
1181 if (unlikely(k < 0)) {
1182 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1183 err = -EFSCORRUPTED;
1184 goto cleanup;
1186 if (k)
1187 ext_debug("create %d intermediate indices\n", k);
1188 /* insert new index into current index block */
1189 /* current depth stored in i var */
1190 i = depth - 1;
1191 while (k--) {
1192 oldblock = newblock;
1193 newblock = ablocks[--a];
1194 bh = sb_getblk(inode->i_sb, newblock);
1195 if (unlikely(!bh)) {
1196 err = -ENOMEM;
1197 goto cleanup;
1199 lock_buffer(bh);
1201 err = ext4_journal_get_create_access(handle, bh);
1202 if (err)
1203 goto cleanup;
1205 neh = ext_block_hdr(bh);
1206 neh->eh_entries = cpu_to_le16(1);
1207 neh->eh_magic = EXT4_EXT_MAGIC;
1208 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1209 neh->eh_depth = cpu_to_le16(depth - i);
1210 fidx = EXT_FIRST_INDEX(neh);
1211 fidx->ei_block = border;
1212 ext4_idx_store_pblock(fidx, oldblock);
1214 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1215 i, newblock, le32_to_cpu(border), oldblock);
1217 /* move remainder of path[i] to the new index block */
1218 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1219 EXT_LAST_INDEX(path[i].p_hdr))) {
1220 EXT4_ERROR_INODE(inode,
1221 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1222 le32_to_cpu(path[i].p_ext->ee_block));
1223 err = -EFSCORRUPTED;
1224 goto cleanup;
1226 /* start copy indexes */
1227 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1228 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1229 EXT_MAX_INDEX(path[i].p_hdr));
1230 ext4_ext_show_move(inode, path, newblock, i);
1231 if (m) {
1232 memmove(++fidx, path[i].p_idx,
1233 sizeof(struct ext4_extent_idx) * m);
1234 le16_add_cpu(&neh->eh_entries, m);
1236 /* zero out unused area in the extent block */
1237 ext_size = sizeof(struct ext4_extent_header) +
1238 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1239 memset(bh->b_data + ext_size, 0,
1240 inode->i_sb->s_blocksize - ext_size);
1241 ext4_extent_block_csum_set(inode, neh);
1242 set_buffer_uptodate(bh);
1243 unlock_buffer(bh);
1245 err = ext4_handle_dirty_metadata(handle, inode, bh);
1246 if (err)
1247 goto cleanup;
1248 brelse(bh);
1249 bh = NULL;
1251 /* correct old index */
1252 if (m) {
1253 err = ext4_ext_get_access(handle, inode, path + i);
1254 if (err)
1255 goto cleanup;
1256 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1257 err = ext4_ext_dirty(handle, inode, path + i);
1258 if (err)
1259 goto cleanup;
1262 i--;
1265 /* insert new index */
1266 err = ext4_ext_insert_index(handle, inode, path + at,
1267 le32_to_cpu(border), newblock);
1269 cleanup:
1270 if (bh) {
1271 if (buffer_locked(bh))
1272 unlock_buffer(bh);
1273 brelse(bh);
1276 if (err) {
1277 /* free all allocated blocks in error case */
1278 for (i = 0; i < depth; i++) {
1279 if (!ablocks[i])
1280 continue;
1281 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1282 EXT4_FREE_BLOCKS_METADATA);
1285 kfree(ablocks);
1287 return err;
1291 * ext4_ext_grow_indepth:
1292 * implements tree growing procedure:
1293 * - allocates new block
1294 * - moves top-level data (index block or leaf) into the new block
1295 * - initializes new top-level, creating index that points to the
1296 * just created block
1298 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1299 unsigned int flags)
1301 struct ext4_extent_header *neh;
1302 struct buffer_head *bh;
1303 ext4_fsblk_t newblock, goal = 0;
1304 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1305 int err = 0;
1306 size_t ext_size = 0;
1308 /* Try to prepend new index to old one */
1309 if (ext_depth(inode))
1310 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1311 if (goal > le32_to_cpu(es->s_first_data_block)) {
1312 flags |= EXT4_MB_HINT_TRY_GOAL;
1313 goal--;
1314 } else
1315 goal = ext4_inode_to_goal_block(inode);
1316 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1317 NULL, &err);
1318 if (newblock == 0)
1319 return err;
1321 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1322 if (unlikely(!bh))
1323 return -ENOMEM;
1324 lock_buffer(bh);
1326 err = ext4_journal_get_create_access(handle, bh);
1327 if (err) {
1328 unlock_buffer(bh);
1329 goto out;
1332 ext_size = sizeof(EXT4_I(inode)->i_data);
1333 /* move top-level index/leaf into new block */
1334 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1335 /* zero out unused area in the extent block */
1336 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1338 /* set size of new block */
1339 neh = ext_block_hdr(bh);
1340 /* old root could have indexes or leaves
1341 * so calculate e_max right way */
1342 if (ext_depth(inode))
1343 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1344 else
1345 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1346 neh->eh_magic = EXT4_EXT_MAGIC;
1347 ext4_extent_block_csum_set(inode, neh);
1348 set_buffer_uptodate(bh);
1349 unlock_buffer(bh);
1351 err = ext4_handle_dirty_metadata(handle, inode, bh);
1352 if (err)
1353 goto out;
1355 /* Update top-level index: num,max,pointer */
1356 neh = ext_inode_hdr(inode);
1357 neh->eh_entries = cpu_to_le16(1);
1358 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1359 if (neh->eh_depth == 0) {
1360 /* Root extent block becomes index block */
1361 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1362 EXT_FIRST_INDEX(neh)->ei_block =
1363 EXT_FIRST_EXTENT(neh)->ee_block;
1365 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1366 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1367 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1368 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1370 le16_add_cpu(&neh->eh_depth, 1);
1371 ext4_mark_inode_dirty(handle, inode);
1372 out:
1373 brelse(bh);
1375 return err;
1379 * ext4_ext_create_new_leaf:
1380 * finds empty index and adds new leaf.
1381 * if no free index is found, then it requests in-depth growing.
1383 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1384 unsigned int mb_flags,
1385 unsigned int gb_flags,
1386 struct ext4_ext_path **ppath,
1387 struct ext4_extent *newext)
1389 struct ext4_ext_path *path = *ppath;
1390 struct ext4_ext_path *curp;
1391 int depth, i, err = 0;
1393 repeat:
1394 i = depth = ext_depth(inode);
1396 /* walk up to the tree and look for free index entry */
1397 curp = path + depth;
1398 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1399 i--;
1400 curp--;
1403 /* we use already allocated block for index block,
1404 * so subsequent data blocks should be contiguous */
1405 if (EXT_HAS_FREE_INDEX(curp)) {
1406 /* if we found index with free entry, then use that
1407 * entry: create all needed subtree and add new leaf */
1408 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1409 if (err)
1410 goto out;
1412 /* refill path */
1413 path = ext4_find_extent(inode,
1414 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1415 ppath, gb_flags);
1416 if (IS_ERR(path))
1417 err = PTR_ERR(path);
1418 } else {
1419 /* tree is full, time to grow in depth */
1420 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1421 if (err)
1422 goto out;
1424 /* refill path */
1425 path = ext4_find_extent(inode,
1426 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1427 ppath, gb_flags);
1428 if (IS_ERR(path)) {
1429 err = PTR_ERR(path);
1430 goto out;
1434 * only first (depth 0 -> 1) produces free space;
1435 * in all other cases we have to split the grown tree
1437 depth = ext_depth(inode);
1438 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1439 /* now we need to split */
1440 goto repeat;
1444 out:
1445 return err;
1449 * search the closest allocated block to the left for *logical
1450 * and returns it at @logical + it's physical address at @phys
1451 * if *logical is the smallest allocated block, the function
1452 * returns 0 at @phys
1453 * return value contains 0 (success) or error code
1455 static int ext4_ext_search_left(struct inode *inode,
1456 struct ext4_ext_path *path,
1457 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1459 struct ext4_extent_idx *ix;
1460 struct ext4_extent *ex;
1461 int depth, ee_len;
1463 if (unlikely(path == NULL)) {
1464 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1465 return -EFSCORRUPTED;
1467 depth = path->p_depth;
1468 *phys = 0;
1470 if (depth == 0 && path->p_ext == NULL)
1471 return 0;
1473 /* usually extent in the path covers blocks smaller
1474 * then *logical, but it can be that extent is the
1475 * first one in the file */
1477 ex = path[depth].p_ext;
1478 ee_len = ext4_ext_get_actual_len(ex);
1479 if (*logical < le32_to_cpu(ex->ee_block)) {
1480 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1481 EXT4_ERROR_INODE(inode,
1482 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1483 *logical, le32_to_cpu(ex->ee_block));
1484 return -EFSCORRUPTED;
1486 while (--depth >= 0) {
1487 ix = path[depth].p_idx;
1488 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1489 EXT4_ERROR_INODE(inode,
1490 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1491 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1492 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1493 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1494 depth);
1495 return -EFSCORRUPTED;
1498 return 0;
1501 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1502 EXT4_ERROR_INODE(inode,
1503 "logical %d < ee_block %d + ee_len %d!",
1504 *logical, le32_to_cpu(ex->ee_block), ee_len);
1505 return -EFSCORRUPTED;
1508 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1509 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1510 return 0;
1514 * search the closest allocated block to the right for *logical
1515 * and returns it at @logical + it's physical address at @phys
1516 * if *logical is the largest allocated block, the function
1517 * returns 0 at @phys
1518 * return value contains 0 (success) or error code
1520 static int ext4_ext_search_right(struct inode *inode,
1521 struct ext4_ext_path *path,
1522 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1523 struct ext4_extent **ret_ex)
1525 struct buffer_head *bh = NULL;
1526 struct ext4_extent_header *eh;
1527 struct ext4_extent_idx *ix;
1528 struct ext4_extent *ex;
1529 ext4_fsblk_t block;
1530 int depth; /* Note, NOT eh_depth; depth from top of tree */
1531 int ee_len;
1533 if (unlikely(path == NULL)) {
1534 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1535 return -EFSCORRUPTED;
1537 depth = path->p_depth;
1538 *phys = 0;
1540 if (depth == 0 && path->p_ext == NULL)
1541 return 0;
1543 /* usually extent in the path covers blocks smaller
1544 * then *logical, but it can be that extent is the
1545 * first one in the file */
1547 ex = path[depth].p_ext;
1548 ee_len = ext4_ext_get_actual_len(ex);
1549 if (*logical < le32_to_cpu(ex->ee_block)) {
1550 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1551 EXT4_ERROR_INODE(inode,
1552 "first_extent(path[%d].p_hdr) != ex",
1553 depth);
1554 return -EFSCORRUPTED;
1556 while (--depth >= 0) {
1557 ix = path[depth].p_idx;
1558 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1559 EXT4_ERROR_INODE(inode,
1560 "ix != EXT_FIRST_INDEX *logical %d!",
1561 *logical);
1562 return -EFSCORRUPTED;
1565 goto found_extent;
1568 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1569 EXT4_ERROR_INODE(inode,
1570 "logical %d < ee_block %d + ee_len %d!",
1571 *logical, le32_to_cpu(ex->ee_block), ee_len);
1572 return -EFSCORRUPTED;
1575 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1576 /* next allocated block in this leaf */
1577 ex++;
1578 goto found_extent;
1581 /* go up and search for index to the right */
1582 while (--depth >= 0) {
1583 ix = path[depth].p_idx;
1584 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1585 goto got_index;
1588 /* we've gone up to the root and found no index to the right */
1589 return 0;
1591 got_index:
1592 /* we've found index to the right, let's
1593 * follow it and find the closest allocated
1594 * block to the right */
1595 ix++;
1596 block = ext4_idx_pblock(ix);
1597 while (++depth < path->p_depth) {
1598 /* subtract from p_depth to get proper eh_depth */
1599 bh = read_extent_tree_block(inode, block,
1600 path->p_depth - depth, 0);
1601 if (IS_ERR(bh))
1602 return PTR_ERR(bh);
1603 eh = ext_block_hdr(bh);
1604 ix = EXT_FIRST_INDEX(eh);
1605 block = ext4_idx_pblock(ix);
1606 put_bh(bh);
1609 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1610 if (IS_ERR(bh))
1611 return PTR_ERR(bh);
1612 eh = ext_block_hdr(bh);
1613 ex = EXT_FIRST_EXTENT(eh);
1614 found_extent:
1615 *logical = le32_to_cpu(ex->ee_block);
1616 *phys = ext4_ext_pblock(ex);
1617 *ret_ex = ex;
1618 if (bh)
1619 put_bh(bh);
1620 return 0;
1624 * ext4_ext_next_allocated_block:
1625 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1626 * NOTE: it considers block number from index entry as
1627 * allocated block. Thus, index entries have to be consistent
1628 * with leaves.
1630 ext4_lblk_t
1631 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1633 int depth;
1635 BUG_ON(path == NULL);
1636 depth = path->p_depth;
1638 if (depth == 0 && path->p_ext == NULL)
1639 return EXT_MAX_BLOCKS;
1641 while (depth >= 0) {
1642 if (depth == path->p_depth) {
1643 /* leaf */
1644 if (path[depth].p_ext &&
1645 path[depth].p_ext !=
1646 EXT_LAST_EXTENT(path[depth].p_hdr))
1647 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1648 } else {
1649 /* index */
1650 if (path[depth].p_idx !=
1651 EXT_LAST_INDEX(path[depth].p_hdr))
1652 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1654 depth--;
1657 return EXT_MAX_BLOCKS;
1661 * ext4_ext_next_leaf_block:
1662 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1664 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1666 int depth;
1668 BUG_ON(path == NULL);
1669 depth = path->p_depth;
1671 /* zero-tree has no leaf blocks at all */
1672 if (depth == 0)
1673 return EXT_MAX_BLOCKS;
1675 /* go to index block */
1676 depth--;
1678 while (depth >= 0) {
1679 if (path[depth].p_idx !=
1680 EXT_LAST_INDEX(path[depth].p_hdr))
1681 return (ext4_lblk_t)
1682 le32_to_cpu(path[depth].p_idx[1].ei_block);
1683 depth--;
1686 return EXT_MAX_BLOCKS;
1690 * ext4_ext_correct_indexes:
1691 * if leaf gets modified and modified extent is first in the leaf,
1692 * then we have to correct all indexes above.
1693 * TODO: do we need to correct tree in all cases?
1695 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1696 struct ext4_ext_path *path)
1698 struct ext4_extent_header *eh;
1699 int depth = ext_depth(inode);
1700 struct ext4_extent *ex;
1701 __le32 border;
1702 int k, err = 0;
1704 eh = path[depth].p_hdr;
1705 ex = path[depth].p_ext;
1707 if (unlikely(ex == NULL || eh == NULL)) {
1708 EXT4_ERROR_INODE(inode,
1709 "ex %p == NULL or eh %p == NULL", ex, eh);
1710 return -EFSCORRUPTED;
1713 if (depth == 0) {
1714 /* there is no tree at all */
1715 return 0;
1718 if (ex != EXT_FIRST_EXTENT(eh)) {
1719 /* we correct tree if first leaf got modified only */
1720 return 0;
1724 * TODO: we need correction if border is smaller than current one
1726 k = depth - 1;
1727 border = path[depth].p_ext->ee_block;
1728 err = ext4_ext_get_access(handle, inode, path + k);
1729 if (err)
1730 return err;
1731 path[k].p_idx->ei_block = border;
1732 err = ext4_ext_dirty(handle, inode, path + k);
1733 if (err)
1734 return err;
1736 while (k--) {
1737 /* change all left-side indexes */
1738 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1739 break;
1740 err = ext4_ext_get_access(handle, inode, path + k);
1741 if (err)
1742 break;
1743 path[k].p_idx->ei_block = border;
1744 err = ext4_ext_dirty(handle, inode, path + k);
1745 if (err)
1746 break;
1749 return err;
1753 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1754 struct ext4_extent *ex2)
1756 unsigned short ext1_ee_len, ext2_ee_len;
1758 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1759 return 0;
1761 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1762 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1764 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1765 le32_to_cpu(ex2->ee_block))
1766 return 0;
1769 * To allow future support for preallocated extents to be added
1770 * as an RO_COMPAT feature, refuse to merge to extents if
1771 * this can result in the top bit of ee_len being set.
1773 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1774 return 0;
1776 * The check for IO to unwritten extent is somewhat racy as we
1777 * increment i_unwritten / set EXT4_STATE_DIO_UNWRITTEN only after
1778 * dropping i_data_sem. But reserved blocks should save us in that
1779 * case.
1781 if (ext4_ext_is_unwritten(ex1) &&
1782 (ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
1783 atomic_read(&EXT4_I(inode)->i_unwritten) ||
1784 (ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
1785 return 0;
1786 #ifdef AGGRESSIVE_TEST
1787 if (ext1_ee_len >= 4)
1788 return 0;
1789 #endif
1791 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1792 return 1;
1793 return 0;
1797 * This function tries to merge the "ex" extent to the next extent in the tree.
1798 * It always tries to merge towards right. If you want to merge towards
1799 * left, pass "ex - 1" as argument instead of "ex".
1800 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1801 * 1 if they got merged.
1803 static int ext4_ext_try_to_merge_right(struct inode *inode,
1804 struct ext4_ext_path *path,
1805 struct ext4_extent *ex)
1807 struct ext4_extent_header *eh;
1808 unsigned int depth, len;
1809 int merge_done = 0, unwritten;
1811 depth = ext_depth(inode);
1812 BUG_ON(path[depth].p_hdr == NULL);
1813 eh = path[depth].p_hdr;
1815 while (ex < EXT_LAST_EXTENT(eh)) {
1816 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1817 break;
1818 /* merge with next extent! */
1819 unwritten = ext4_ext_is_unwritten(ex);
1820 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1821 + ext4_ext_get_actual_len(ex + 1));
1822 if (unwritten)
1823 ext4_ext_mark_unwritten(ex);
1825 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1826 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1827 * sizeof(struct ext4_extent);
1828 memmove(ex + 1, ex + 2, len);
1830 le16_add_cpu(&eh->eh_entries, -1);
1831 merge_done = 1;
1832 WARN_ON(eh->eh_entries == 0);
1833 if (!eh->eh_entries)
1834 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1837 return merge_done;
1841 * This function does a very simple check to see if we can collapse
1842 * an extent tree with a single extent tree leaf block into the inode.
1844 static void ext4_ext_try_to_merge_up(handle_t *handle,
1845 struct inode *inode,
1846 struct ext4_ext_path *path)
1848 size_t s;
1849 unsigned max_root = ext4_ext_space_root(inode, 0);
1850 ext4_fsblk_t blk;
1852 if ((path[0].p_depth != 1) ||
1853 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1854 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1855 return;
1858 * We need to modify the block allocation bitmap and the block
1859 * group descriptor to release the extent tree block. If we
1860 * can't get the journal credits, give up.
1862 if (ext4_journal_extend(handle, 2))
1863 return;
1866 * Copy the extent data up to the inode
1868 blk = ext4_idx_pblock(path[0].p_idx);
1869 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1870 sizeof(struct ext4_extent_idx);
1871 s += sizeof(struct ext4_extent_header);
1873 path[1].p_maxdepth = path[0].p_maxdepth;
1874 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1875 path[0].p_depth = 0;
1876 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1877 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1878 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1880 brelse(path[1].p_bh);
1881 ext4_free_blocks(handle, inode, NULL, blk, 1,
1882 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1886 * This function tries to merge the @ex extent to neighbours in the tree.
1887 * return 1 if merge left else 0.
1889 static void ext4_ext_try_to_merge(handle_t *handle,
1890 struct inode *inode,
1891 struct ext4_ext_path *path,
1892 struct ext4_extent *ex) {
1893 struct ext4_extent_header *eh;
1894 unsigned int depth;
1895 int merge_done = 0;
1897 depth = ext_depth(inode);
1898 BUG_ON(path[depth].p_hdr == NULL);
1899 eh = path[depth].p_hdr;
1901 if (ex > EXT_FIRST_EXTENT(eh))
1902 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1904 if (!merge_done)
1905 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1907 ext4_ext_try_to_merge_up(handle, inode, path);
1911 * check if a portion of the "newext" extent overlaps with an
1912 * existing extent.
1914 * If there is an overlap discovered, it updates the length of the newext
1915 * such that there will be no overlap, and then returns 1.
1916 * If there is no overlap found, it returns 0.
1918 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1919 struct inode *inode,
1920 struct ext4_extent *newext,
1921 struct ext4_ext_path *path)
1923 ext4_lblk_t b1, b2;
1924 unsigned int depth, len1;
1925 unsigned int ret = 0;
1927 b1 = le32_to_cpu(newext->ee_block);
1928 len1 = ext4_ext_get_actual_len(newext);
1929 depth = ext_depth(inode);
1930 if (!path[depth].p_ext)
1931 goto out;
1932 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1935 * get the next allocated block if the extent in the path
1936 * is before the requested block(s)
1938 if (b2 < b1) {
1939 b2 = ext4_ext_next_allocated_block(path);
1940 if (b2 == EXT_MAX_BLOCKS)
1941 goto out;
1942 b2 = EXT4_LBLK_CMASK(sbi, b2);
1945 /* check for wrap through zero on extent logical start block*/
1946 if (b1 + len1 < b1) {
1947 len1 = EXT_MAX_BLOCKS - b1;
1948 newext->ee_len = cpu_to_le16(len1);
1949 ret = 1;
1952 /* check for overlap */
1953 if (b1 + len1 > b2) {
1954 newext->ee_len = cpu_to_le16(b2 - b1);
1955 ret = 1;
1957 out:
1958 return ret;
1962 * ext4_ext_insert_extent:
1963 * tries to merge requsted extent into the existing extent or
1964 * inserts requested extent as new one into the tree,
1965 * creating new leaf in the no-space case.
1967 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1968 struct ext4_ext_path **ppath,
1969 struct ext4_extent *newext, int gb_flags)
1971 struct ext4_ext_path *path = *ppath;
1972 struct ext4_extent_header *eh;
1973 struct ext4_extent *ex, *fex;
1974 struct ext4_extent *nearex; /* nearest extent */
1975 struct ext4_ext_path *npath = NULL;
1976 int depth, len, err;
1977 ext4_lblk_t next;
1978 int mb_flags = 0, unwritten;
1980 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1981 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1982 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1983 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1984 return -EFSCORRUPTED;
1986 depth = ext_depth(inode);
1987 ex = path[depth].p_ext;
1988 eh = path[depth].p_hdr;
1989 if (unlikely(path[depth].p_hdr == NULL)) {
1990 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1991 return -EFSCORRUPTED;
1994 /* try to insert block into found extent and return */
1995 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1998 * Try to see whether we should rather test the extent on
1999 * right from ex, or from the left of ex. This is because
2000 * ext4_find_extent() can return either extent on the
2001 * left, or on the right from the searched position. This
2002 * will make merging more effective.
2004 if (ex < EXT_LAST_EXTENT(eh) &&
2005 (le32_to_cpu(ex->ee_block) +
2006 ext4_ext_get_actual_len(ex) <
2007 le32_to_cpu(newext->ee_block))) {
2008 ex += 1;
2009 goto prepend;
2010 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
2011 (le32_to_cpu(newext->ee_block) +
2012 ext4_ext_get_actual_len(newext) <
2013 le32_to_cpu(ex->ee_block)))
2014 ex -= 1;
2016 /* Try to append newex to the ex */
2017 if (ext4_can_extents_be_merged(inode, ex, newext)) {
2018 ext_debug("append [%d]%d block to %u:[%d]%d"
2019 "(from %llu)\n",
2020 ext4_ext_is_unwritten(newext),
2021 ext4_ext_get_actual_len(newext),
2022 le32_to_cpu(ex->ee_block),
2023 ext4_ext_is_unwritten(ex),
2024 ext4_ext_get_actual_len(ex),
2025 ext4_ext_pblock(ex));
2026 err = ext4_ext_get_access(handle, inode,
2027 path + depth);
2028 if (err)
2029 return err;
2030 unwritten = ext4_ext_is_unwritten(ex);
2031 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2032 + ext4_ext_get_actual_len(newext));
2033 if (unwritten)
2034 ext4_ext_mark_unwritten(ex);
2035 eh = path[depth].p_hdr;
2036 nearex = ex;
2037 goto merge;
2040 prepend:
2041 /* Try to prepend newex to the ex */
2042 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2043 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2044 "(from %llu)\n",
2045 le32_to_cpu(newext->ee_block),
2046 ext4_ext_is_unwritten(newext),
2047 ext4_ext_get_actual_len(newext),
2048 le32_to_cpu(ex->ee_block),
2049 ext4_ext_is_unwritten(ex),
2050 ext4_ext_get_actual_len(ex),
2051 ext4_ext_pblock(ex));
2052 err = ext4_ext_get_access(handle, inode,
2053 path + depth);
2054 if (err)
2055 return err;
2057 unwritten = ext4_ext_is_unwritten(ex);
2058 ex->ee_block = newext->ee_block;
2059 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2060 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2061 + ext4_ext_get_actual_len(newext));
2062 if (unwritten)
2063 ext4_ext_mark_unwritten(ex);
2064 eh = path[depth].p_hdr;
2065 nearex = ex;
2066 goto merge;
2070 depth = ext_depth(inode);
2071 eh = path[depth].p_hdr;
2072 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2073 goto has_space;
2075 /* probably next leaf has space for us? */
2076 fex = EXT_LAST_EXTENT(eh);
2077 next = EXT_MAX_BLOCKS;
2078 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2079 next = ext4_ext_next_leaf_block(path);
2080 if (next != EXT_MAX_BLOCKS) {
2081 ext_debug("next leaf block - %u\n", next);
2082 BUG_ON(npath != NULL);
2083 npath = ext4_find_extent(inode, next, NULL, 0);
2084 if (IS_ERR(npath))
2085 return PTR_ERR(npath);
2086 BUG_ON(npath->p_depth != path->p_depth);
2087 eh = npath[depth].p_hdr;
2088 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2089 ext_debug("next leaf isn't full(%d)\n",
2090 le16_to_cpu(eh->eh_entries));
2091 path = npath;
2092 goto has_space;
2094 ext_debug("next leaf has no free space(%d,%d)\n",
2095 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2099 * There is no free space in the found leaf.
2100 * We're gonna add a new leaf in the tree.
2102 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2103 mb_flags |= EXT4_MB_USE_RESERVED;
2104 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2105 ppath, newext);
2106 if (err)
2107 goto cleanup;
2108 depth = ext_depth(inode);
2109 eh = path[depth].p_hdr;
2111 has_space:
2112 nearex = path[depth].p_ext;
2114 err = ext4_ext_get_access(handle, inode, path + depth);
2115 if (err)
2116 goto cleanup;
2118 if (!nearex) {
2119 /* there is no extent in this leaf, create first one */
2120 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
2121 le32_to_cpu(newext->ee_block),
2122 ext4_ext_pblock(newext),
2123 ext4_ext_is_unwritten(newext),
2124 ext4_ext_get_actual_len(newext));
2125 nearex = EXT_FIRST_EXTENT(eh);
2126 } else {
2127 if (le32_to_cpu(newext->ee_block)
2128 > le32_to_cpu(nearex->ee_block)) {
2129 /* Insert after */
2130 ext_debug("insert %u:%llu:[%d]%d before: "
2131 "nearest %p\n",
2132 le32_to_cpu(newext->ee_block),
2133 ext4_ext_pblock(newext),
2134 ext4_ext_is_unwritten(newext),
2135 ext4_ext_get_actual_len(newext),
2136 nearex);
2137 nearex++;
2138 } else {
2139 /* Insert before */
2140 BUG_ON(newext->ee_block == nearex->ee_block);
2141 ext_debug("insert %u:%llu:[%d]%d after: "
2142 "nearest %p\n",
2143 le32_to_cpu(newext->ee_block),
2144 ext4_ext_pblock(newext),
2145 ext4_ext_is_unwritten(newext),
2146 ext4_ext_get_actual_len(newext),
2147 nearex);
2149 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2150 if (len > 0) {
2151 ext_debug("insert %u:%llu:[%d]%d: "
2152 "move %d extents from 0x%p to 0x%p\n",
2153 le32_to_cpu(newext->ee_block),
2154 ext4_ext_pblock(newext),
2155 ext4_ext_is_unwritten(newext),
2156 ext4_ext_get_actual_len(newext),
2157 len, nearex, nearex + 1);
2158 memmove(nearex + 1, nearex,
2159 len * sizeof(struct ext4_extent));
2163 le16_add_cpu(&eh->eh_entries, 1);
2164 path[depth].p_ext = nearex;
2165 nearex->ee_block = newext->ee_block;
2166 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2167 nearex->ee_len = newext->ee_len;
2169 merge:
2170 /* try to merge extents */
2171 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2172 ext4_ext_try_to_merge(handle, inode, path, nearex);
2175 /* time to correct all indexes above */
2176 err = ext4_ext_correct_indexes(handle, inode, path);
2177 if (err)
2178 goto cleanup;
2180 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2182 cleanup:
2183 ext4_ext_drop_refs(npath);
2184 kfree(npath);
2185 return err;
2188 static int ext4_fill_fiemap_extents(struct inode *inode,
2189 ext4_lblk_t block, ext4_lblk_t num,
2190 struct fiemap_extent_info *fieinfo)
2192 struct ext4_ext_path *path = NULL;
2193 struct ext4_extent *ex;
2194 struct extent_status es;
2195 ext4_lblk_t next, next_del, start = 0, end = 0;
2196 ext4_lblk_t last = block + num;
2197 int exists, depth = 0, err = 0;
2198 unsigned int flags = 0;
2199 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2201 while (block < last && block != EXT_MAX_BLOCKS) {
2202 num = last - block;
2203 /* find extent for this block */
2204 down_read(&EXT4_I(inode)->i_data_sem);
2206 path = ext4_find_extent(inode, block, &path, 0);
2207 if (IS_ERR(path)) {
2208 up_read(&EXT4_I(inode)->i_data_sem);
2209 err = PTR_ERR(path);
2210 path = NULL;
2211 break;
2214 depth = ext_depth(inode);
2215 if (unlikely(path[depth].p_hdr == NULL)) {
2216 up_read(&EXT4_I(inode)->i_data_sem);
2217 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2218 err = -EFSCORRUPTED;
2219 break;
2221 ex = path[depth].p_ext;
2222 next = ext4_ext_next_allocated_block(path);
2224 flags = 0;
2225 exists = 0;
2226 if (!ex) {
2227 /* there is no extent yet, so try to allocate
2228 * all requested space */
2229 start = block;
2230 end = block + num;
2231 } else if (le32_to_cpu(ex->ee_block) > block) {
2232 /* need to allocate space before found extent */
2233 start = block;
2234 end = le32_to_cpu(ex->ee_block);
2235 if (block + num < end)
2236 end = block + num;
2237 } else if (block >= le32_to_cpu(ex->ee_block)
2238 + ext4_ext_get_actual_len(ex)) {
2239 /* need to allocate space after found extent */
2240 start = block;
2241 end = block + num;
2242 if (end >= next)
2243 end = next;
2244 } else if (block >= le32_to_cpu(ex->ee_block)) {
2246 * some part of requested space is covered
2247 * by found extent
2249 start = block;
2250 end = le32_to_cpu(ex->ee_block)
2251 + ext4_ext_get_actual_len(ex);
2252 if (block + num < end)
2253 end = block + num;
2254 exists = 1;
2255 } else {
2256 BUG();
2258 BUG_ON(end <= start);
2260 if (!exists) {
2261 es.es_lblk = start;
2262 es.es_len = end - start;
2263 es.es_pblk = 0;
2264 } else {
2265 es.es_lblk = le32_to_cpu(ex->ee_block);
2266 es.es_len = ext4_ext_get_actual_len(ex);
2267 es.es_pblk = ext4_ext_pblock(ex);
2268 if (ext4_ext_is_unwritten(ex))
2269 flags |= FIEMAP_EXTENT_UNWRITTEN;
2273 * Find delayed extent and update es accordingly. We call
2274 * it even in !exists case to find out whether es is the
2275 * last existing extent or not.
2277 next_del = ext4_find_delayed_extent(inode, &es);
2278 if (!exists && next_del) {
2279 exists = 1;
2280 flags |= (FIEMAP_EXTENT_DELALLOC |
2281 FIEMAP_EXTENT_UNKNOWN);
2283 up_read(&EXT4_I(inode)->i_data_sem);
2285 if (unlikely(es.es_len == 0)) {
2286 EXT4_ERROR_INODE(inode, "es.es_len == 0");
2287 err = -EFSCORRUPTED;
2288 break;
2292 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2293 * we need to check next == EXT_MAX_BLOCKS because it is
2294 * possible that an extent is with unwritten and delayed
2295 * status due to when an extent is delayed allocated and
2296 * is allocated by fallocate status tree will track both of
2297 * them in a extent.
2299 * So we could return a unwritten and delayed extent, and
2300 * its block is equal to 'next'.
2302 if (next == next_del && next == EXT_MAX_BLOCKS) {
2303 flags |= FIEMAP_EXTENT_LAST;
2304 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2305 next != EXT_MAX_BLOCKS)) {
2306 EXT4_ERROR_INODE(inode,
2307 "next extent == %u, next "
2308 "delalloc extent = %u",
2309 next, next_del);
2310 err = -EFSCORRUPTED;
2311 break;
2315 if (exists) {
2316 err = fiemap_fill_next_extent(fieinfo,
2317 (__u64)es.es_lblk << blksize_bits,
2318 (__u64)es.es_pblk << blksize_bits,
2319 (__u64)es.es_len << blksize_bits,
2320 flags);
2321 if (err < 0)
2322 break;
2323 if (err == 1) {
2324 err = 0;
2325 break;
2329 block = es.es_lblk + es.es_len;
2332 ext4_ext_drop_refs(path);
2333 kfree(path);
2334 return err;
2338 * ext4_ext_determine_hole - determine hole around given block
2339 * @inode: inode we lookup in
2340 * @path: path in extent tree to @lblk
2341 * @lblk: pointer to logical block around which we want to determine hole
2343 * Determine hole length (and start if easily possible) around given logical
2344 * block. We don't try too hard to find the beginning of the hole but @path
2345 * actually points to extent before @lblk, we provide it.
2347 * The function returns the length of a hole starting at @lblk. We update @lblk
2348 * to the beginning of the hole if we managed to find it.
2350 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2351 struct ext4_ext_path *path,
2352 ext4_lblk_t *lblk)
2354 int depth = ext_depth(inode);
2355 struct ext4_extent *ex;
2356 ext4_lblk_t len;
2358 ex = path[depth].p_ext;
2359 if (ex == NULL) {
2360 /* there is no extent yet, so gap is [0;-] */
2361 *lblk = 0;
2362 len = EXT_MAX_BLOCKS;
2363 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2364 len = le32_to_cpu(ex->ee_block) - *lblk;
2365 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2366 + ext4_ext_get_actual_len(ex)) {
2367 ext4_lblk_t next;
2369 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2370 next = ext4_ext_next_allocated_block(path);
2371 BUG_ON(next == *lblk);
2372 len = next - *lblk;
2373 } else {
2374 BUG();
2376 return len;
2380 * ext4_ext_put_gap_in_cache:
2381 * calculate boundaries of the gap that the requested block fits into
2382 * and cache this gap
2384 static void
2385 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2386 ext4_lblk_t hole_len)
2388 struct extent_status es;
2390 ext4_es_find_delayed_extent_range(inode, hole_start,
2391 hole_start + hole_len - 1, &es);
2392 if (es.es_len) {
2393 /* There's delayed extent containing lblock? */
2394 if (es.es_lblk <= hole_start)
2395 return;
2396 hole_len = min(es.es_lblk - hole_start, hole_len);
2398 ext_debug(" -> %u:%u\n", hole_start, hole_len);
2399 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2400 EXTENT_STATUS_HOLE);
2404 * ext4_ext_rm_idx:
2405 * removes index from the index block.
2407 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2408 struct ext4_ext_path *path, int depth)
2410 int err;
2411 ext4_fsblk_t leaf;
2413 /* free index block */
2414 depth--;
2415 path = path + depth;
2416 leaf = ext4_idx_pblock(path->p_idx);
2417 if (unlikely(path->p_hdr->eh_entries == 0)) {
2418 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2419 return -EFSCORRUPTED;
2421 err = ext4_ext_get_access(handle, inode, path);
2422 if (err)
2423 return err;
2425 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2426 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2427 len *= sizeof(struct ext4_extent_idx);
2428 memmove(path->p_idx, path->p_idx + 1, len);
2431 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2432 err = ext4_ext_dirty(handle, inode, path);
2433 if (err)
2434 return err;
2435 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2436 trace_ext4_ext_rm_idx(inode, leaf);
2438 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2439 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2441 while (--depth >= 0) {
2442 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2443 break;
2444 path--;
2445 err = ext4_ext_get_access(handle, inode, path);
2446 if (err)
2447 break;
2448 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2449 err = ext4_ext_dirty(handle, inode, path);
2450 if (err)
2451 break;
2453 return err;
2457 * ext4_ext_calc_credits_for_single_extent:
2458 * This routine returns max. credits that needed to insert an extent
2459 * to the extent tree.
2460 * When pass the actual path, the caller should calculate credits
2461 * under i_data_sem.
2463 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2464 struct ext4_ext_path *path)
2466 if (path) {
2467 int depth = ext_depth(inode);
2468 int ret = 0;
2470 /* probably there is space in leaf? */
2471 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2472 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2475 * There are some space in the leaf tree, no
2476 * need to account for leaf block credit
2478 * bitmaps and block group descriptor blocks
2479 * and other metadata blocks still need to be
2480 * accounted.
2482 /* 1 bitmap, 1 block group descriptor */
2483 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2484 return ret;
2488 return ext4_chunk_trans_blocks(inode, nrblocks);
2492 * How many index/leaf blocks need to change/allocate to add @extents extents?
2494 * If we add a single extent, then in the worse case, each tree level
2495 * index/leaf need to be changed in case of the tree split.
2497 * If more extents are inserted, they could cause the whole tree split more
2498 * than once, but this is really rare.
2500 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2502 int index;
2503 int depth;
2505 /* If we are converting the inline data, only one is needed here. */
2506 if (ext4_has_inline_data(inode))
2507 return 1;
2509 depth = ext_depth(inode);
2511 if (extents <= 1)
2512 index = depth * 2;
2513 else
2514 index = depth * 3;
2516 return index;
2519 static inline int get_default_free_blocks_flags(struct inode *inode)
2521 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2522 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2523 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2524 else if (ext4_should_journal_data(inode))
2525 return EXT4_FREE_BLOCKS_FORGET;
2526 return 0;
2529 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2530 struct ext4_extent *ex,
2531 long long *partial_cluster,
2532 ext4_lblk_t from, ext4_lblk_t to)
2534 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2535 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2536 ext4_fsblk_t pblk;
2537 int flags = get_default_free_blocks_flags(inode);
2540 * For bigalloc file systems, we never free a partial cluster
2541 * at the beginning of the extent. Instead, we make a note
2542 * that we tried freeing the cluster, and check to see if we
2543 * need to free it on a subsequent call to ext4_remove_blocks,
2544 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2546 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2548 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2550 * If we have a partial cluster, and it's different from the
2551 * cluster of the last block, we need to explicitly free the
2552 * partial cluster here.
2554 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2555 if (*partial_cluster > 0 &&
2556 *partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2557 ext4_free_blocks(handle, inode, NULL,
2558 EXT4_C2B(sbi, *partial_cluster),
2559 sbi->s_cluster_ratio, flags);
2560 *partial_cluster = 0;
2563 #ifdef EXTENTS_STATS
2565 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2566 spin_lock(&sbi->s_ext_stats_lock);
2567 sbi->s_ext_blocks += ee_len;
2568 sbi->s_ext_extents++;
2569 if (ee_len < sbi->s_ext_min)
2570 sbi->s_ext_min = ee_len;
2571 if (ee_len > sbi->s_ext_max)
2572 sbi->s_ext_max = ee_len;
2573 if (ext_depth(inode) > sbi->s_depth_max)
2574 sbi->s_depth_max = ext_depth(inode);
2575 spin_unlock(&sbi->s_ext_stats_lock);
2577 #endif
2578 if (from >= le32_to_cpu(ex->ee_block)
2579 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2580 /* tail removal */
2581 ext4_lblk_t num;
2582 long long first_cluster;
2584 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2585 pblk = ext4_ext_pblock(ex) + ee_len - num;
2587 * Usually we want to free partial cluster at the end of the
2588 * extent, except for the situation when the cluster is still
2589 * used by any other extent (partial_cluster is negative).
2591 if (*partial_cluster < 0 &&
2592 *partial_cluster == -(long long) EXT4_B2C(sbi, pblk+num-1))
2593 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2595 ext_debug("free last %u blocks starting %llu partial %lld\n",
2596 num, pblk, *partial_cluster);
2597 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2599 * If the block range to be freed didn't start at the
2600 * beginning of a cluster, and we removed the entire
2601 * extent and the cluster is not used by any other extent,
2602 * save the partial cluster here, since we might need to
2603 * delete if we determine that the truncate or punch hole
2604 * operation has removed all of the blocks in the cluster.
2605 * If that cluster is used by another extent, preserve its
2606 * negative value so it isn't freed later on.
2608 * If the whole extent wasn't freed, we've reached the
2609 * start of the truncated/punched region and have finished
2610 * removing blocks. If there's a partial cluster here it's
2611 * shared with the remainder of the extent and is no longer
2612 * a candidate for removal.
2614 if (EXT4_PBLK_COFF(sbi, pblk) && ee_len == num) {
2615 first_cluster = (long long) EXT4_B2C(sbi, pblk);
2616 if (first_cluster != -*partial_cluster)
2617 *partial_cluster = first_cluster;
2618 } else {
2619 *partial_cluster = 0;
2621 } else
2622 ext4_error(sbi->s_sb, "strange request: removal(2) "
2623 "%u-%u from %u:%u",
2624 from, to, le32_to_cpu(ex->ee_block), ee_len);
2625 return 0;
2630 * ext4_ext_rm_leaf() Removes the extents associated with the
2631 * blocks appearing between "start" and "end". Both "start"
2632 * and "end" must appear in the same extent or EIO is returned.
2634 * @handle: The journal handle
2635 * @inode: The files inode
2636 * @path: The path to the leaf
2637 * @partial_cluster: The cluster which we'll have to free if all extents
2638 * has been released from it. However, if this value is
2639 * negative, it's a cluster just to the right of the
2640 * punched region and it must not be freed.
2641 * @start: The first block to remove
2642 * @end: The last block to remove
2644 static int
2645 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2646 struct ext4_ext_path *path,
2647 long long *partial_cluster,
2648 ext4_lblk_t start, ext4_lblk_t end)
2650 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2651 int err = 0, correct_index = 0;
2652 int depth = ext_depth(inode), credits;
2653 struct ext4_extent_header *eh;
2654 ext4_lblk_t a, b;
2655 unsigned num;
2656 ext4_lblk_t ex_ee_block;
2657 unsigned short ex_ee_len;
2658 unsigned unwritten = 0;
2659 struct ext4_extent *ex;
2660 ext4_fsblk_t pblk;
2662 /* the header must be checked already in ext4_ext_remove_space() */
2663 ext_debug("truncate since %u in leaf to %u\n", start, end);
2664 if (!path[depth].p_hdr)
2665 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2666 eh = path[depth].p_hdr;
2667 if (unlikely(path[depth].p_hdr == NULL)) {
2668 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2669 return -EFSCORRUPTED;
2671 /* find where to start removing */
2672 ex = path[depth].p_ext;
2673 if (!ex)
2674 ex = EXT_LAST_EXTENT(eh);
2676 ex_ee_block = le32_to_cpu(ex->ee_block);
2677 ex_ee_len = ext4_ext_get_actual_len(ex);
2679 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2681 while (ex >= EXT_FIRST_EXTENT(eh) &&
2682 ex_ee_block + ex_ee_len > start) {
2684 if (ext4_ext_is_unwritten(ex))
2685 unwritten = 1;
2686 else
2687 unwritten = 0;
2689 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2690 unwritten, ex_ee_len);
2691 path[depth].p_ext = ex;
2693 a = ex_ee_block > start ? ex_ee_block : start;
2694 b = ex_ee_block+ex_ee_len - 1 < end ?
2695 ex_ee_block+ex_ee_len - 1 : end;
2697 ext_debug(" border %u:%u\n", a, b);
2699 /* If this extent is beyond the end of the hole, skip it */
2700 if (end < ex_ee_block) {
2702 * We're going to skip this extent and move to another,
2703 * so note that its first cluster is in use to avoid
2704 * freeing it when removing blocks. Eventually, the
2705 * right edge of the truncated/punched region will
2706 * be just to the left.
2708 if (sbi->s_cluster_ratio > 1) {
2709 pblk = ext4_ext_pblock(ex);
2710 *partial_cluster =
2711 -(long long) EXT4_B2C(sbi, pblk);
2713 ex--;
2714 ex_ee_block = le32_to_cpu(ex->ee_block);
2715 ex_ee_len = ext4_ext_get_actual_len(ex);
2716 continue;
2717 } else if (b != ex_ee_block + ex_ee_len - 1) {
2718 EXT4_ERROR_INODE(inode,
2719 "can not handle truncate %u:%u "
2720 "on extent %u:%u",
2721 start, end, ex_ee_block,
2722 ex_ee_block + ex_ee_len - 1);
2723 err = -EFSCORRUPTED;
2724 goto out;
2725 } else if (a != ex_ee_block) {
2726 /* remove tail of the extent */
2727 num = a - ex_ee_block;
2728 } else {
2729 /* remove whole extent: excellent! */
2730 num = 0;
2733 * 3 for leaf, sb, and inode plus 2 (bmap and group
2734 * descriptor) for each block group; assume two block
2735 * groups plus ex_ee_len/blocks_per_block_group for
2736 * the worst case
2738 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2739 if (ex == EXT_FIRST_EXTENT(eh)) {
2740 correct_index = 1;
2741 credits += (ext_depth(inode)) + 1;
2743 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2745 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2746 if (err)
2747 goto out;
2749 err = ext4_ext_get_access(handle, inode, path + depth);
2750 if (err)
2751 goto out;
2753 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2754 a, b);
2755 if (err)
2756 goto out;
2758 if (num == 0)
2759 /* this extent is removed; mark slot entirely unused */
2760 ext4_ext_store_pblock(ex, 0);
2762 ex->ee_len = cpu_to_le16(num);
2764 * Do not mark unwritten if all the blocks in the
2765 * extent have been removed.
2767 if (unwritten && num)
2768 ext4_ext_mark_unwritten(ex);
2770 * If the extent was completely released,
2771 * we need to remove it from the leaf
2773 if (num == 0) {
2774 if (end != EXT_MAX_BLOCKS - 1) {
2776 * For hole punching, we need to scoot all the
2777 * extents up when an extent is removed so that
2778 * we dont have blank extents in the middle
2780 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2781 sizeof(struct ext4_extent));
2783 /* Now get rid of the one at the end */
2784 memset(EXT_LAST_EXTENT(eh), 0,
2785 sizeof(struct ext4_extent));
2787 le16_add_cpu(&eh->eh_entries, -1);
2790 err = ext4_ext_dirty(handle, inode, path + depth);
2791 if (err)
2792 goto out;
2794 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2795 ext4_ext_pblock(ex));
2796 ex--;
2797 ex_ee_block = le32_to_cpu(ex->ee_block);
2798 ex_ee_len = ext4_ext_get_actual_len(ex);
2801 if (correct_index && eh->eh_entries)
2802 err = ext4_ext_correct_indexes(handle, inode, path);
2805 * If there's a partial cluster and at least one extent remains in
2806 * the leaf, free the partial cluster if it isn't shared with the
2807 * current extent. If it is shared with the current extent
2808 * we zero partial_cluster because we've reached the start of the
2809 * truncated/punched region and we're done removing blocks.
2811 if (*partial_cluster > 0 && ex >= EXT_FIRST_EXTENT(eh)) {
2812 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2813 if (*partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2814 ext4_free_blocks(handle, inode, NULL,
2815 EXT4_C2B(sbi, *partial_cluster),
2816 sbi->s_cluster_ratio,
2817 get_default_free_blocks_flags(inode));
2819 *partial_cluster = 0;
2822 /* if this leaf is free, then we should
2823 * remove it from index block above */
2824 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2825 err = ext4_ext_rm_idx(handle, inode, path, depth);
2827 out:
2828 return err;
2832 * ext4_ext_more_to_rm:
2833 * returns 1 if current index has to be freed (even partial)
2835 static int
2836 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2838 BUG_ON(path->p_idx == NULL);
2840 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2841 return 0;
2844 * if truncate on deeper level happened, it wasn't partial,
2845 * so we have to consider current index for truncation
2847 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2848 return 0;
2849 return 1;
2852 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2853 ext4_lblk_t end)
2855 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2856 int depth = ext_depth(inode);
2857 struct ext4_ext_path *path = NULL;
2858 long long partial_cluster = 0;
2859 handle_t *handle;
2860 int i = 0, err = 0;
2862 ext_debug("truncate since %u to %u\n", start, end);
2864 /* probably first extent we're gonna free will be last in block */
2865 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
2866 if (IS_ERR(handle))
2867 return PTR_ERR(handle);
2869 again:
2870 trace_ext4_ext_remove_space(inode, start, end, depth);
2873 * Check if we are removing extents inside the extent tree. If that
2874 * is the case, we are going to punch a hole inside the extent tree
2875 * so we have to check whether we need to split the extent covering
2876 * the last block to remove so we can easily remove the part of it
2877 * in ext4_ext_rm_leaf().
2879 if (end < EXT_MAX_BLOCKS - 1) {
2880 struct ext4_extent *ex;
2881 ext4_lblk_t ee_block, ex_end, lblk;
2882 ext4_fsblk_t pblk;
2884 /* find extent for or closest extent to this block */
2885 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
2886 if (IS_ERR(path)) {
2887 ext4_journal_stop(handle);
2888 return PTR_ERR(path);
2890 depth = ext_depth(inode);
2891 /* Leaf not may not exist only if inode has no blocks at all */
2892 ex = path[depth].p_ext;
2893 if (!ex) {
2894 if (depth) {
2895 EXT4_ERROR_INODE(inode,
2896 "path[%d].p_hdr == NULL",
2897 depth);
2898 err = -EFSCORRUPTED;
2900 goto out;
2903 ee_block = le32_to_cpu(ex->ee_block);
2904 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2907 * See if the last block is inside the extent, if so split
2908 * the extent at 'end' block so we can easily remove the
2909 * tail of the first part of the split extent in
2910 * ext4_ext_rm_leaf().
2912 if (end >= ee_block && end < ex_end) {
2915 * If we're going to split the extent, note that
2916 * the cluster containing the block after 'end' is
2917 * in use to avoid freeing it when removing blocks.
2919 if (sbi->s_cluster_ratio > 1) {
2920 pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
2921 partial_cluster =
2922 -(long long) EXT4_B2C(sbi, pblk);
2926 * Split the extent in two so that 'end' is the last
2927 * block in the first new extent. Also we should not
2928 * fail removing space due to ENOSPC so try to use
2929 * reserved block if that happens.
2931 err = ext4_force_split_extent_at(handle, inode, &path,
2932 end + 1, 1);
2933 if (err < 0)
2934 goto out;
2936 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end) {
2938 * If there's an extent to the right its first cluster
2939 * contains the immediate right boundary of the
2940 * truncated/punched region. Set partial_cluster to
2941 * its negative value so it won't be freed if shared
2942 * with the current extent. The end < ee_block case
2943 * is handled in ext4_ext_rm_leaf().
2945 lblk = ex_end + 1;
2946 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2947 &ex);
2948 if (err)
2949 goto out;
2950 if (pblk)
2951 partial_cluster =
2952 -(long long) EXT4_B2C(sbi, pblk);
2956 * We start scanning from right side, freeing all the blocks
2957 * after i_size and walking into the tree depth-wise.
2959 depth = ext_depth(inode);
2960 if (path) {
2961 int k = i = depth;
2962 while (--k > 0)
2963 path[k].p_block =
2964 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2965 } else {
2966 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2967 GFP_NOFS);
2968 if (path == NULL) {
2969 ext4_journal_stop(handle);
2970 return -ENOMEM;
2972 path[0].p_maxdepth = path[0].p_depth = depth;
2973 path[0].p_hdr = ext_inode_hdr(inode);
2974 i = 0;
2976 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2977 err = -EFSCORRUPTED;
2978 goto out;
2981 err = 0;
2983 while (i >= 0 && err == 0) {
2984 if (i == depth) {
2985 /* this is leaf block */
2986 err = ext4_ext_rm_leaf(handle, inode, path,
2987 &partial_cluster, start,
2988 end);
2989 /* root level has p_bh == NULL, brelse() eats this */
2990 brelse(path[i].p_bh);
2991 path[i].p_bh = NULL;
2992 i--;
2993 continue;
2996 /* this is index block */
2997 if (!path[i].p_hdr) {
2998 ext_debug("initialize header\n");
2999 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
3002 if (!path[i].p_idx) {
3003 /* this level hasn't been touched yet */
3004 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
3005 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
3006 ext_debug("init index ptr: hdr 0x%p, num %d\n",
3007 path[i].p_hdr,
3008 le16_to_cpu(path[i].p_hdr->eh_entries));
3009 } else {
3010 /* we were already here, see at next index */
3011 path[i].p_idx--;
3014 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
3015 i, EXT_FIRST_INDEX(path[i].p_hdr),
3016 path[i].p_idx);
3017 if (ext4_ext_more_to_rm(path + i)) {
3018 struct buffer_head *bh;
3019 /* go to the next level */
3020 ext_debug("move to level %d (block %llu)\n",
3021 i + 1, ext4_idx_pblock(path[i].p_idx));
3022 memset(path + i + 1, 0, sizeof(*path));
3023 bh = read_extent_tree_block(inode,
3024 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
3025 EXT4_EX_NOCACHE);
3026 if (IS_ERR(bh)) {
3027 /* should we reset i_size? */
3028 err = PTR_ERR(bh);
3029 break;
3031 /* Yield here to deal with large extent trees.
3032 * Should be a no-op if we did IO above. */
3033 cond_resched();
3034 if (WARN_ON(i + 1 > depth)) {
3035 err = -EFSCORRUPTED;
3036 break;
3038 path[i + 1].p_bh = bh;
3040 /* save actual number of indexes since this
3041 * number is changed at the next iteration */
3042 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3043 i++;
3044 } else {
3045 /* we finished processing this index, go up */
3046 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3047 /* index is empty, remove it;
3048 * handle must be already prepared by the
3049 * truncatei_leaf() */
3050 err = ext4_ext_rm_idx(handle, inode, path, i);
3052 /* root level has p_bh == NULL, brelse() eats this */
3053 brelse(path[i].p_bh);
3054 path[i].p_bh = NULL;
3055 i--;
3056 ext_debug("return to level %d\n", i);
3060 trace_ext4_ext_remove_space_done(inode, start, end, depth,
3061 partial_cluster, path->p_hdr->eh_entries);
3064 * If we still have something in the partial cluster and we have removed
3065 * even the first extent, then we should free the blocks in the partial
3066 * cluster as well. (This code will only run when there are no leaves
3067 * to the immediate left of the truncated/punched region.)
3069 if (partial_cluster > 0 && err == 0) {
3070 /* don't zero partial_cluster since it's not used afterwards */
3071 ext4_free_blocks(handle, inode, NULL,
3072 EXT4_C2B(sbi, partial_cluster),
3073 sbi->s_cluster_ratio,
3074 get_default_free_blocks_flags(inode));
3077 /* TODO: flexible tree reduction should be here */
3078 if (path->p_hdr->eh_entries == 0) {
3080 * truncate to zero freed all the tree,
3081 * so we need to correct eh_depth
3083 err = ext4_ext_get_access(handle, inode, path);
3084 if (err == 0) {
3085 ext_inode_hdr(inode)->eh_depth = 0;
3086 ext_inode_hdr(inode)->eh_max =
3087 cpu_to_le16(ext4_ext_space_root(inode, 0));
3088 err = ext4_ext_dirty(handle, inode, path);
3091 out:
3092 ext4_ext_drop_refs(path);
3093 kfree(path);
3094 path = NULL;
3095 if (err == -EAGAIN)
3096 goto again;
3097 ext4_journal_stop(handle);
3099 return err;
3103 * called at mount time
3105 void ext4_ext_init(struct super_block *sb)
3108 * possible initialization would be here
3111 if (ext4_has_feature_extents(sb)) {
3112 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3113 printk(KERN_INFO "EXT4-fs: file extents enabled"
3114 #ifdef AGGRESSIVE_TEST
3115 ", aggressive tests"
3116 #endif
3117 #ifdef CHECK_BINSEARCH
3118 ", check binsearch"
3119 #endif
3120 #ifdef EXTENTS_STATS
3121 ", stats"
3122 #endif
3123 "\n");
3124 #endif
3125 #ifdef EXTENTS_STATS
3126 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3127 EXT4_SB(sb)->s_ext_min = 1 << 30;
3128 EXT4_SB(sb)->s_ext_max = 0;
3129 #endif
3134 * called at umount time
3136 void ext4_ext_release(struct super_block *sb)
3138 if (!ext4_has_feature_extents(sb))
3139 return;
3141 #ifdef EXTENTS_STATS
3142 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3143 struct ext4_sb_info *sbi = EXT4_SB(sb);
3144 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3145 sbi->s_ext_blocks, sbi->s_ext_extents,
3146 sbi->s_ext_blocks / sbi->s_ext_extents);
3147 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3148 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3150 #endif
3153 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3155 ext4_lblk_t ee_block;
3156 ext4_fsblk_t ee_pblock;
3157 unsigned int ee_len;
3159 ee_block = le32_to_cpu(ex->ee_block);
3160 ee_len = ext4_ext_get_actual_len(ex);
3161 ee_pblock = ext4_ext_pblock(ex);
3163 if (ee_len == 0)
3164 return 0;
3166 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3167 EXTENT_STATUS_WRITTEN);
3170 /* FIXME!! we need to try to merge to left or right after zero-out */
3171 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3173 ext4_fsblk_t ee_pblock;
3174 unsigned int ee_len;
3176 ee_len = ext4_ext_get_actual_len(ex);
3177 ee_pblock = ext4_ext_pblock(ex);
3178 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3179 ee_len);
3183 * ext4_split_extent_at() splits an extent at given block.
3185 * @handle: the journal handle
3186 * @inode: the file inode
3187 * @path: the path to the extent
3188 * @split: the logical block where the extent is splitted.
3189 * @split_flags: indicates if the extent could be zeroout if split fails, and
3190 * the states(init or unwritten) of new extents.
3191 * @flags: flags used to insert new extent to extent tree.
3194 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3195 * of which are deterimined by split_flag.
3197 * There are two cases:
3198 * a> the extent are splitted into two extent.
3199 * b> split is not needed, and just mark the extent.
3201 * return 0 on success.
3203 static int ext4_split_extent_at(handle_t *handle,
3204 struct inode *inode,
3205 struct ext4_ext_path **ppath,
3206 ext4_lblk_t split,
3207 int split_flag,
3208 int flags)
3210 struct ext4_ext_path *path = *ppath;
3211 ext4_fsblk_t newblock;
3212 ext4_lblk_t ee_block;
3213 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3214 struct ext4_extent *ex2 = NULL;
3215 unsigned int ee_len, depth;
3216 int err = 0;
3218 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3219 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3221 ext_debug("ext4_split_extents_at: inode %lu, logical"
3222 "block %llu\n", inode->i_ino, (unsigned long long)split);
3224 ext4_ext_show_leaf(inode, path);
3226 depth = ext_depth(inode);
3227 ex = path[depth].p_ext;
3228 ee_block = le32_to_cpu(ex->ee_block);
3229 ee_len = ext4_ext_get_actual_len(ex);
3230 newblock = split - ee_block + ext4_ext_pblock(ex);
3232 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3233 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3234 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3235 EXT4_EXT_MARK_UNWRIT1 |
3236 EXT4_EXT_MARK_UNWRIT2));
3238 err = ext4_ext_get_access(handle, inode, path + depth);
3239 if (err)
3240 goto out;
3242 if (split == ee_block) {
3244 * case b: block @split is the block that the extent begins with
3245 * then we just change the state of the extent, and splitting
3246 * is not needed.
3248 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3249 ext4_ext_mark_unwritten(ex);
3250 else
3251 ext4_ext_mark_initialized(ex);
3253 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3254 ext4_ext_try_to_merge(handle, inode, path, ex);
3256 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3257 goto out;
3260 /* case a */
3261 memcpy(&orig_ex, ex, sizeof(orig_ex));
3262 ex->ee_len = cpu_to_le16(split - ee_block);
3263 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3264 ext4_ext_mark_unwritten(ex);
3267 * path may lead to new leaf, not to original leaf any more
3268 * after ext4_ext_insert_extent() returns,
3270 err = ext4_ext_dirty(handle, inode, path + depth);
3271 if (err)
3272 goto fix_extent_len;
3274 ex2 = &newex;
3275 ex2->ee_block = cpu_to_le32(split);
3276 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3277 ext4_ext_store_pblock(ex2, newblock);
3278 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3279 ext4_ext_mark_unwritten(ex2);
3281 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3282 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3283 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3284 if (split_flag & EXT4_EXT_DATA_VALID1) {
3285 err = ext4_ext_zeroout(inode, ex2);
3286 zero_ex.ee_block = ex2->ee_block;
3287 zero_ex.ee_len = cpu_to_le16(
3288 ext4_ext_get_actual_len(ex2));
3289 ext4_ext_store_pblock(&zero_ex,
3290 ext4_ext_pblock(ex2));
3291 } else {
3292 err = ext4_ext_zeroout(inode, ex);
3293 zero_ex.ee_block = ex->ee_block;
3294 zero_ex.ee_len = cpu_to_le16(
3295 ext4_ext_get_actual_len(ex));
3296 ext4_ext_store_pblock(&zero_ex,
3297 ext4_ext_pblock(ex));
3299 } else {
3300 err = ext4_ext_zeroout(inode, &orig_ex);
3301 zero_ex.ee_block = orig_ex.ee_block;
3302 zero_ex.ee_len = cpu_to_le16(
3303 ext4_ext_get_actual_len(&orig_ex));
3304 ext4_ext_store_pblock(&zero_ex,
3305 ext4_ext_pblock(&orig_ex));
3308 if (err)
3309 goto fix_extent_len;
3310 /* update the extent length and mark as initialized */
3311 ex->ee_len = cpu_to_le16(ee_len);
3312 ext4_ext_try_to_merge(handle, inode, path, ex);
3313 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3314 if (err)
3315 goto fix_extent_len;
3317 /* update extent status tree */
3318 err = ext4_zeroout_es(inode, &zero_ex);
3320 goto out;
3321 } else if (err)
3322 goto fix_extent_len;
3324 out:
3325 ext4_ext_show_leaf(inode, path);
3326 return err;
3328 fix_extent_len:
3329 ex->ee_len = orig_ex.ee_len;
3330 ext4_ext_dirty(handle, inode, path + path->p_depth);
3331 return err;
3335 * ext4_split_extents() splits an extent and mark extent which is covered
3336 * by @map as split_flags indicates
3338 * It may result in splitting the extent into multiple extents (up to three)
3339 * There are three possibilities:
3340 * a> There is no split required
3341 * b> Splits in two extents: Split is happening at either end of the extent
3342 * c> Splits in three extents: Somone is splitting in middle of the extent
3345 static int ext4_split_extent(handle_t *handle,
3346 struct inode *inode,
3347 struct ext4_ext_path **ppath,
3348 struct ext4_map_blocks *map,
3349 int split_flag,
3350 int flags)
3352 struct ext4_ext_path *path = *ppath;
3353 ext4_lblk_t ee_block;
3354 struct ext4_extent *ex;
3355 unsigned int ee_len, depth;
3356 int err = 0;
3357 int unwritten;
3358 int split_flag1, flags1;
3359 int allocated = map->m_len;
3361 depth = ext_depth(inode);
3362 ex = path[depth].p_ext;
3363 ee_block = le32_to_cpu(ex->ee_block);
3364 ee_len = ext4_ext_get_actual_len(ex);
3365 unwritten = ext4_ext_is_unwritten(ex);
3367 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3368 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3369 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3370 if (unwritten)
3371 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3372 EXT4_EXT_MARK_UNWRIT2;
3373 if (split_flag & EXT4_EXT_DATA_VALID2)
3374 split_flag1 |= EXT4_EXT_DATA_VALID1;
3375 err = ext4_split_extent_at(handle, inode, ppath,
3376 map->m_lblk + map->m_len, split_flag1, flags1);
3377 if (err)
3378 goto out;
3379 } else {
3380 allocated = ee_len - (map->m_lblk - ee_block);
3383 * Update path is required because previous ext4_split_extent_at() may
3384 * result in split of original leaf or extent zeroout.
3386 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3387 if (IS_ERR(path))
3388 return PTR_ERR(path);
3389 depth = ext_depth(inode);
3390 ex = path[depth].p_ext;
3391 if (!ex) {
3392 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3393 (unsigned long) map->m_lblk);
3394 return -EFSCORRUPTED;
3396 unwritten = ext4_ext_is_unwritten(ex);
3397 split_flag1 = 0;
3399 if (map->m_lblk >= ee_block) {
3400 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3401 if (unwritten) {
3402 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3403 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3404 EXT4_EXT_MARK_UNWRIT2);
3406 err = ext4_split_extent_at(handle, inode, ppath,
3407 map->m_lblk, split_flag1, flags);
3408 if (err)
3409 goto out;
3412 ext4_ext_show_leaf(inode, path);
3413 out:
3414 return err ? err : allocated;
3418 * This function is called by ext4_ext_map_blocks() if someone tries to write
3419 * to an unwritten extent. It may result in splitting the unwritten
3420 * extent into multiple extents (up to three - one initialized and two
3421 * unwritten).
3422 * There are three possibilities:
3423 * a> There is no split required: Entire extent should be initialized
3424 * b> Splits in two extents: Write is happening at either end of the extent
3425 * c> Splits in three extents: Somone is writing in middle of the extent
3427 * Pre-conditions:
3428 * - The extent pointed to by 'path' is unwritten.
3429 * - The extent pointed to by 'path' contains a superset
3430 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3432 * Post-conditions on success:
3433 * - the returned value is the number of blocks beyond map->l_lblk
3434 * that are allocated and initialized.
3435 * It is guaranteed to be >= map->m_len.
3437 static int ext4_ext_convert_to_initialized(handle_t *handle,
3438 struct inode *inode,
3439 struct ext4_map_blocks *map,
3440 struct ext4_ext_path **ppath,
3441 int flags)
3443 struct ext4_ext_path *path = *ppath;
3444 struct ext4_sb_info *sbi;
3445 struct ext4_extent_header *eh;
3446 struct ext4_map_blocks split_map;
3447 struct ext4_extent zero_ex1, zero_ex2;
3448 struct ext4_extent *ex, *abut_ex;
3449 ext4_lblk_t ee_block, eof_block;
3450 unsigned int ee_len, depth, map_len = map->m_len;
3451 int allocated = 0, max_zeroout = 0;
3452 int err = 0;
3453 int split_flag = EXT4_EXT_DATA_VALID2;
3455 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3456 "block %llu, max_blocks %u\n", inode->i_ino,
3457 (unsigned long long)map->m_lblk, map_len);
3459 sbi = EXT4_SB(inode->i_sb);
3460 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3461 >> inode->i_sb->s_blocksize_bits;
3462 if (eof_block < map->m_lblk + map_len)
3463 eof_block = map->m_lblk + map_len;
3465 depth = ext_depth(inode);
3466 eh = path[depth].p_hdr;
3467 ex = path[depth].p_ext;
3468 ee_block = le32_to_cpu(ex->ee_block);
3469 ee_len = ext4_ext_get_actual_len(ex);
3470 zero_ex1.ee_len = 0;
3471 zero_ex2.ee_len = 0;
3473 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3475 /* Pre-conditions */
3476 BUG_ON(!ext4_ext_is_unwritten(ex));
3477 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3480 * Attempt to transfer newly initialized blocks from the currently
3481 * unwritten extent to its neighbor. This is much cheaper
3482 * than an insertion followed by a merge as those involve costly
3483 * memmove() calls. Transferring to the left is the common case in
3484 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3485 * followed by append writes.
3487 * Limitations of the current logic:
3488 * - L1: we do not deal with writes covering the whole extent.
3489 * This would require removing the extent if the transfer
3490 * is possible.
3491 * - L2: we only attempt to merge with an extent stored in the
3492 * same extent tree node.
3494 if ((map->m_lblk == ee_block) &&
3495 /* See if we can merge left */
3496 (map_len < ee_len) && /*L1*/
3497 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3498 ext4_lblk_t prev_lblk;
3499 ext4_fsblk_t prev_pblk, ee_pblk;
3500 unsigned int prev_len;
3502 abut_ex = ex - 1;
3503 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3504 prev_len = ext4_ext_get_actual_len(abut_ex);
3505 prev_pblk = ext4_ext_pblock(abut_ex);
3506 ee_pblk = ext4_ext_pblock(ex);
3509 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3510 * upon those conditions:
3511 * - C1: abut_ex is initialized,
3512 * - C2: abut_ex is logically abutting ex,
3513 * - C3: abut_ex is physically abutting ex,
3514 * - C4: abut_ex can receive the additional blocks without
3515 * overflowing the (initialized) length limit.
3517 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3518 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3519 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3520 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3521 err = ext4_ext_get_access(handle, inode, path + depth);
3522 if (err)
3523 goto out;
3525 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3526 map, ex, abut_ex);
3528 /* Shift the start of ex by 'map_len' blocks */
3529 ex->ee_block = cpu_to_le32(ee_block + map_len);
3530 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3531 ex->ee_len = cpu_to_le16(ee_len - map_len);
3532 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3534 /* Extend abut_ex by 'map_len' blocks */
3535 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3537 /* Result: number of initialized blocks past m_lblk */
3538 allocated = map_len;
3540 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3541 (map_len < ee_len) && /*L1*/
3542 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3543 /* See if we can merge right */
3544 ext4_lblk_t next_lblk;
3545 ext4_fsblk_t next_pblk, ee_pblk;
3546 unsigned int next_len;
3548 abut_ex = ex + 1;
3549 next_lblk = le32_to_cpu(abut_ex->ee_block);
3550 next_len = ext4_ext_get_actual_len(abut_ex);
3551 next_pblk = ext4_ext_pblock(abut_ex);
3552 ee_pblk = ext4_ext_pblock(ex);
3555 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3556 * upon those conditions:
3557 * - C1: abut_ex is initialized,
3558 * - C2: abut_ex is logically abutting ex,
3559 * - C3: abut_ex is physically abutting ex,
3560 * - C4: abut_ex can receive the additional blocks without
3561 * overflowing the (initialized) length limit.
3563 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3564 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3565 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3566 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3567 err = ext4_ext_get_access(handle, inode, path + depth);
3568 if (err)
3569 goto out;
3571 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3572 map, ex, abut_ex);
3574 /* Shift the start of abut_ex by 'map_len' blocks */
3575 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3576 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3577 ex->ee_len = cpu_to_le16(ee_len - map_len);
3578 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3580 /* Extend abut_ex by 'map_len' blocks */
3581 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3583 /* Result: number of initialized blocks past m_lblk */
3584 allocated = map_len;
3587 if (allocated) {
3588 /* Mark the block containing both extents as dirty */
3589 ext4_ext_dirty(handle, inode, path + depth);
3591 /* Update path to point to the right extent */
3592 path[depth].p_ext = abut_ex;
3593 goto out;
3594 } else
3595 allocated = ee_len - (map->m_lblk - ee_block);
3597 WARN_ON(map->m_lblk < ee_block);
3599 * It is safe to convert extent to initialized via explicit
3600 * zeroout only if extent is fully inside i_size or new_size.
3602 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3604 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3605 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3606 (inode->i_sb->s_blocksize_bits - 10);
3608 if (ext4_encrypted_inode(inode))
3609 max_zeroout = 0;
3612 * five cases:
3613 * 1. split the extent into three extents.
3614 * 2. split the extent into two extents, zeroout the head of the first
3615 * extent.
3616 * 3. split the extent into two extents, zeroout the tail of the second
3617 * extent.
3618 * 4. split the extent into two extents with out zeroout.
3619 * 5. no splitting needed, just possibly zeroout the head and / or the
3620 * tail of the extent.
3622 split_map.m_lblk = map->m_lblk;
3623 split_map.m_len = map->m_len;
3625 if (max_zeroout && (allocated > split_map.m_len)) {
3626 if (allocated <= max_zeroout) {
3627 /* case 3 or 5 */
3628 zero_ex1.ee_block =
3629 cpu_to_le32(split_map.m_lblk +
3630 split_map.m_len);
3631 zero_ex1.ee_len =
3632 cpu_to_le16(allocated - split_map.m_len);
3633 ext4_ext_store_pblock(&zero_ex1,
3634 ext4_ext_pblock(ex) + split_map.m_lblk +
3635 split_map.m_len - ee_block);
3636 err = ext4_ext_zeroout(inode, &zero_ex1);
3637 if (err)
3638 goto out;
3639 split_map.m_len = allocated;
3641 if (split_map.m_lblk - ee_block + split_map.m_len <
3642 max_zeroout) {
3643 /* case 2 or 5 */
3644 if (split_map.m_lblk != ee_block) {
3645 zero_ex2.ee_block = ex->ee_block;
3646 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3647 ee_block);
3648 ext4_ext_store_pblock(&zero_ex2,
3649 ext4_ext_pblock(ex));
3650 err = ext4_ext_zeroout(inode, &zero_ex2);
3651 if (err)
3652 goto out;
3655 split_map.m_len += split_map.m_lblk - ee_block;
3656 split_map.m_lblk = ee_block;
3657 allocated = map->m_len;
3661 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3662 flags);
3663 if (err > 0)
3664 err = 0;
3665 out:
3666 /* If we have gotten a failure, don't zero out status tree */
3667 if (!err) {
3668 err = ext4_zeroout_es(inode, &zero_ex1);
3669 if (!err)
3670 err = ext4_zeroout_es(inode, &zero_ex2);
3672 return err ? err : allocated;
3676 * This function is called by ext4_ext_map_blocks() from
3677 * ext4_get_blocks_dio_write() when DIO to write
3678 * to an unwritten extent.
3680 * Writing to an unwritten extent may result in splitting the unwritten
3681 * extent into multiple initialized/unwritten extents (up to three)
3682 * There are three possibilities:
3683 * a> There is no split required: Entire extent should be unwritten
3684 * b> Splits in two extents: Write is happening at either end of the extent
3685 * c> Splits in three extents: Somone is writing in middle of the extent
3687 * This works the same way in the case of initialized -> unwritten conversion.
3689 * One of more index blocks maybe needed if the extent tree grow after
3690 * the unwritten extent split. To prevent ENOSPC occur at the IO
3691 * complete, we need to split the unwritten extent before DIO submit
3692 * the IO. The unwritten extent called at this time will be split
3693 * into three unwritten extent(at most). After IO complete, the part
3694 * being filled will be convert to initialized by the end_io callback function
3695 * via ext4_convert_unwritten_extents().
3697 * Returns the size of unwritten extent to be written on success.
3699 static int ext4_split_convert_extents(handle_t *handle,
3700 struct inode *inode,
3701 struct ext4_map_blocks *map,
3702 struct ext4_ext_path **ppath,
3703 int flags)
3705 struct ext4_ext_path *path = *ppath;
3706 ext4_lblk_t eof_block;
3707 ext4_lblk_t ee_block;
3708 struct ext4_extent *ex;
3709 unsigned int ee_len;
3710 int split_flag = 0, depth;
3712 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3713 __func__, inode->i_ino,
3714 (unsigned long long)map->m_lblk, map->m_len);
3716 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3717 >> inode->i_sb->s_blocksize_bits;
3718 if (eof_block < map->m_lblk + map->m_len)
3719 eof_block = map->m_lblk + map->m_len;
3721 * It is safe to convert extent to initialized via explicit
3722 * zeroout only if extent is fully insde i_size or new_size.
3724 depth = ext_depth(inode);
3725 ex = path[depth].p_ext;
3726 ee_block = le32_to_cpu(ex->ee_block);
3727 ee_len = ext4_ext_get_actual_len(ex);
3729 /* Convert to unwritten */
3730 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3731 split_flag |= EXT4_EXT_DATA_VALID1;
3732 /* Convert to initialized */
3733 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3734 split_flag |= ee_block + ee_len <= eof_block ?
3735 EXT4_EXT_MAY_ZEROOUT : 0;
3736 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3738 flags |= EXT4_GET_BLOCKS_PRE_IO;
3739 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3742 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3743 struct inode *inode,
3744 struct ext4_map_blocks *map,
3745 struct ext4_ext_path **ppath)
3747 struct ext4_ext_path *path = *ppath;
3748 struct ext4_extent *ex;
3749 ext4_lblk_t ee_block;
3750 unsigned int ee_len;
3751 int depth;
3752 int err = 0;
3754 depth = ext_depth(inode);
3755 ex = path[depth].p_ext;
3756 ee_block = le32_to_cpu(ex->ee_block);
3757 ee_len = ext4_ext_get_actual_len(ex);
3759 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3760 "block %llu, max_blocks %u\n", inode->i_ino,
3761 (unsigned long long)ee_block, ee_len);
3763 /* If extent is larger than requested it is a clear sign that we still
3764 * have some extent state machine issues left. So extent_split is still
3765 * required.
3766 * TODO: Once all related issues will be fixed this situation should be
3767 * illegal.
3769 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3770 #ifdef CONFIG_EXT4_DEBUG
3771 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3772 " len %u; IO logical block %llu, len %u",
3773 inode->i_ino, (unsigned long long)ee_block, ee_len,
3774 (unsigned long long)map->m_lblk, map->m_len);
3775 #endif
3776 err = ext4_split_convert_extents(handle, inode, map, ppath,
3777 EXT4_GET_BLOCKS_CONVERT);
3778 if (err < 0)
3779 return err;
3780 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3781 if (IS_ERR(path))
3782 return PTR_ERR(path);
3783 depth = ext_depth(inode);
3784 ex = path[depth].p_ext;
3787 err = ext4_ext_get_access(handle, inode, path + depth);
3788 if (err)
3789 goto out;
3790 /* first mark the extent as initialized */
3791 ext4_ext_mark_initialized(ex);
3793 /* note: ext4_ext_correct_indexes() isn't needed here because
3794 * borders are not changed
3796 ext4_ext_try_to_merge(handle, inode, path, ex);
3798 /* Mark modified extent as dirty */
3799 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3800 out:
3801 ext4_ext_show_leaf(inode, path);
3802 return err;
3806 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3808 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3809 ext4_lblk_t lblk,
3810 struct ext4_ext_path *path,
3811 unsigned int len)
3813 int i, depth;
3814 struct ext4_extent_header *eh;
3815 struct ext4_extent *last_ex;
3817 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3818 return 0;
3820 depth = ext_depth(inode);
3821 eh = path[depth].p_hdr;
3824 * We're going to remove EOFBLOCKS_FL entirely in future so we
3825 * do not care for this case anymore. Simply remove the flag
3826 * if there are no extents.
3828 if (unlikely(!eh->eh_entries))
3829 goto out;
3830 last_ex = EXT_LAST_EXTENT(eh);
3832 * We should clear the EOFBLOCKS_FL flag if we are writing the
3833 * last block in the last extent in the file. We test this by
3834 * first checking to see if the caller to
3835 * ext4_ext_get_blocks() was interested in the last block (or
3836 * a block beyond the last block) in the current extent. If
3837 * this turns out to be false, we can bail out from this
3838 * function immediately.
3840 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3841 ext4_ext_get_actual_len(last_ex))
3842 return 0;
3844 * If the caller does appear to be planning to write at or
3845 * beyond the end of the current extent, we then test to see
3846 * if the current extent is the last extent in the file, by
3847 * checking to make sure it was reached via the rightmost node
3848 * at each level of the tree.
3850 for (i = depth-1; i >= 0; i--)
3851 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3852 return 0;
3853 out:
3854 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3855 return ext4_mark_inode_dirty(handle, inode);
3859 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3861 * Return 1 if there is a delalloc block in the range, otherwise 0.
3863 int ext4_find_delalloc_range(struct inode *inode,
3864 ext4_lblk_t lblk_start,
3865 ext4_lblk_t lblk_end)
3867 struct extent_status es;
3869 ext4_es_find_delayed_extent_range(inode, lblk_start, lblk_end, &es);
3870 if (es.es_len == 0)
3871 return 0; /* there is no delay extent in this tree */
3872 else if (es.es_lblk <= lblk_start &&
3873 lblk_start < es.es_lblk + es.es_len)
3874 return 1;
3875 else if (lblk_start <= es.es_lblk && es.es_lblk <= lblk_end)
3876 return 1;
3877 else
3878 return 0;
3881 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk)
3883 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3884 ext4_lblk_t lblk_start, lblk_end;
3885 lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
3886 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3888 return ext4_find_delalloc_range(inode, lblk_start, lblk_end);
3892 * Determines how many complete clusters (out of those specified by the 'map')
3893 * are under delalloc and were reserved quota for.
3894 * This function is called when we are writing out the blocks that were
3895 * originally written with their allocation delayed, but then the space was
3896 * allocated using fallocate() before the delayed allocation could be resolved.
3897 * The cases to look for are:
3898 * ('=' indicated delayed allocated blocks
3899 * '-' indicates non-delayed allocated blocks)
3900 * (a) partial clusters towards beginning and/or end outside of allocated range
3901 * are not delalloc'ed.
3902 * Ex:
3903 * |----c---=|====c====|====c====|===-c----|
3904 * |++++++ allocated ++++++|
3905 * ==> 4 complete clusters in above example
3907 * (b) partial cluster (outside of allocated range) towards either end is
3908 * marked for delayed allocation. In this case, we will exclude that
3909 * cluster.
3910 * Ex:
3911 * |----====c========|========c========|
3912 * |++++++ allocated ++++++|
3913 * ==> 1 complete clusters in above example
3915 * Ex:
3916 * |================c================|
3917 * |++++++ allocated ++++++|
3918 * ==> 0 complete clusters in above example
3920 * The ext4_da_update_reserve_space will be called only if we
3921 * determine here that there were some "entire" clusters that span
3922 * this 'allocated' range.
3923 * In the non-bigalloc case, this function will just end up returning num_blks
3924 * without ever calling ext4_find_delalloc_range.
3926 static unsigned int
3927 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3928 unsigned int num_blks)
3930 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3931 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3932 ext4_lblk_t lblk_from, lblk_to, c_offset;
3933 unsigned int allocated_clusters = 0;
3935 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3936 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3938 /* max possible clusters for this allocation */
3939 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3941 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3943 /* Check towards left side */
3944 c_offset = EXT4_LBLK_COFF(sbi, lblk_start);
3945 if (c_offset) {
3946 lblk_from = EXT4_LBLK_CMASK(sbi, lblk_start);
3947 lblk_to = lblk_from + c_offset - 1;
3949 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3950 allocated_clusters--;
3953 /* Now check towards right. */
3954 c_offset = EXT4_LBLK_COFF(sbi, lblk_start + num_blks);
3955 if (allocated_clusters && c_offset) {
3956 lblk_from = lblk_start + num_blks;
3957 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3959 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3960 allocated_clusters--;
3963 return allocated_clusters;
3966 static int
3967 convert_initialized_extent(handle_t *handle, struct inode *inode,
3968 struct ext4_map_blocks *map,
3969 struct ext4_ext_path **ppath,
3970 unsigned int allocated)
3972 struct ext4_ext_path *path = *ppath;
3973 struct ext4_extent *ex;
3974 ext4_lblk_t ee_block;
3975 unsigned int ee_len;
3976 int depth;
3977 int err = 0;
3980 * Make sure that the extent is no bigger than we support with
3981 * unwritten extent
3983 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3984 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3986 depth = ext_depth(inode);
3987 ex = path[depth].p_ext;
3988 ee_block = le32_to_cpu(ex->ee_block);
3989 ee_len = ext4_ext_get_actual_len(ex);
3991 ext_debug("%s: inode %lu, logical"
3992 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3993 (unsigned long long)ee_block, ee_len);
3995 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3996 err = ext4_split_convert_extents(handle, inode, map, ppath,
3997 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3998 if (err < 0)
3999 return err;
4000 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
4001 if (IS_ERR(path))
4002 return PTR_ERR(path);
4003 depth = ext_depth(inode);
4004 ex = path[depth].p_ext;
4005 if (!ex) {
4006 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
4007 (unsigned long) map->m_lblk);
4008 return -EFSCORRUPTED;
4012 err = ext4_ext_get_access(handle, inode, path + depth);
4013 if (err)
4014 return err;
4015 /* first mark the extent as unwritten */
4016 ext4_ext_mark_unwritten(ex);
4018 /* note: ext4_ext_correct_indexes() isn't needed here because
4019 * borders are not changed
4021 ext4_ext_try_to_merge(handle, inode, path, ex);
4023 /* Mark modified extent as dirty */
4024 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4025 if (err)
4026 return err;
4027 ext4_ext_show_leaf(inode, path);
4029 ext4_update_inode_fsync_trans(handle, inode, 1);
4030 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4031 if (err)
4032 return err;
4033 map->m_flags |= EXT4_MAP_UNWRITTEN;
4034 if (allocated > map->m_len)
4035 allocated = map->m_len;
4036 map->m_len = allocated;
4037 return allocated;
4040 static int
4041 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4042 struct ext4_map_blocks *map,
4043 struct ext4_ext_path **ppath, int flags,
4044 unsigned int allocated, ext4_fsblk_t newblock)
4046 struct ext4_ext_path *path = *ppath;
4047 int ret = 0;
4048 int err = 0;
4050 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4051 "block %llu, max_blocks %u, flags %x, allocated %u\n",
4052 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4053 flags, allocated);
4054 ext4_ext_show_leaf(inode, path);
4057 * When writing into unwritten space, we should not fail to
4058 * allocate metadata blocks for the new extent block if needed.
4060 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4062 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4063 allocated, newblock);
4065 /* get_block() before submit the IO, split the extent */
4066 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4067 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4068 flags | EXT4_GET_BLOCKS_CONVERT);
4069 if (ret <= 0)
4070 goto out;
4071 map->m_flags |= EXT4_MAP_UNWRITTEN;
4072 goto out;
4074 /* IO end_io complete, convert the filled extent to written */
4075 if (flags & EXT4_GET_BLOCKS_CONVERT) {
4076 if (flags & EXT4_GET_BLOCKS_ZERO) {
4077 if (allocated > map->m_len)
4078 allocated = map->m_len;
4079 err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4080 allocated);
4081 if (err < 0)
4082 goto out2;
4084 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4085 ppath);
4086 if (ret >= 0) {
4087 ext4_update_inode_fsync_trans(handle, inode, 1);
4088 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4089 path, map->m_len);
4090 } else
4091 err = ret;
4092 map->m_flags |= EXT4_MAP_MAPPED;
4093 map->m_pblk = newblock;
4094 if (allocated > map->m_len)
4095 allocated = map->m_len;
4096 map->m_len = allocated;
4097 goto out2;
4099 /* buffered IO case */
4101 * repeat fallocate creation request
4102 * we already have an unwritten extent
4104 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4105 map->m_flags |= EXT4_MAP_UNWRITTEN;
4106 goto map_out;
4109 /* buffered READ or buffered write_begin() lookup */
4110 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4112 * We have blocks reserved already. We
4113 * return allocated blocks so that delalloc
4114 * won't do block reservation for us. But
4115 * the buffer head will be unmapped so that
4116 * a read from the block returns 0s.
4118 map->m_flags |= EXT4_MAP_UNWRITTEN;
4119 goto out1;
4122 /* buffered write, writepage time, convert*/
4123 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4124 if (ret >= 0)
4125 ext4_update_inode_fsync_trans(handle, inode, 1);
4126 out:
4127 if (ret <= 0) {
4128 err = ret;
4129 goto out2;
4130 } else
4131 allocated = ret;
4132 map->m_flags |= EXT4_MAP_NEW;
4134 * if we allocated more blocks than requested
4135 * we need to make sure we unmap the extra block
4136 * allocated. The actual needed block will get
4137 * unmapped later when we find the buffer_head marked
4138 * new.
4140 if (allocated > map->m_len) {
4141 clean_bdev_aliases(inode->i_sb->s_bdev, newblock + map->m_len,
4142 allocated - map->m_len);
4143 allocated = map->m_len;
4145 map->m_len = allocated;
4148 * If we have done fallocate with the offset that is already
4149 * delayed allocated, we would have block reservation
4150 * and quota reservation done in the delayed write path.
4151 * But fallocate would have already updated quota and block
4152 * count for this offset. So cancel these reservation
4154 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4155 unsigned int reserved_clusters;
4156 reserved_clusters = get_reserved_cluster_alloc(inode,
4157 map->m_lblk, map->m_len);
4158 if (reserved_clusters)
4159 ext4_da_update_reserve_space(inode,
4160 reserved_clusters,
4164 map_out:
4165 map->m_flags |= EXT4_MAP_MAPPED;
4166 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4167 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4168 map->m_len);
4169 if (err < 0)
4170 goto out2;
4172 out1:
4173 if (allocated > map->m_len)
4174 allocated = map->m_len;
4175 ext4_ext_show_leaf(inode, path);
4176 map->m_pblk = newblock;
4177 map->m_len = allocated;
4178 out2:
4179 return err ? err : allocated;
4183 * get_implied_cluster_alloc - check to see if the requested
4184 * allocation (in the map structure) overlaps with a cluster already
4185 * allocated in an extent.
4186 * @sb The filesystem superblock structure
4187 * @map The requested lblk->pblk mapping
4188 * @ex The extent structure which might contain an implied
4189 * cluster allocation
4191 * This function is called by ext4_ext_map_blocks() after we failed to
4192 * find blocks that were already in the inode's extent tree. Hence,
4193 * we know that the beginning of the requested region cannot overlap
4194 * the extent from the inode's extent tree. There are three cases we
4195 * want to catch. The first is this case:
4197 * |--- cluster # N--|
4198 * |--- extent ---| |---- requested region ---|
4199 * |==========|
4201 * The second case that we need to test for is this one:
4203 * |--------- cluster # N ----------------|
4204 * |--- requested region --| |------- extent ----|
4205 * |=======================|
4207 * The third case is when the requested region lies between two extents
4208 * within the same cluster:
4209 * |------------- cluster # N-------------|
4210 * |----- ex -----| |---- ex_right ----|
4211 * |------ requested region ------|
4212 * |================|
4214 * In each of the above cases, we need to set the map->m_pblk and
4215 * map->m_len so it corresponds to the return the extent labelled as
4216 * "|====|" from cluster #N, since it is already in use for data in
4217 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4218 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4219 * as a new "allocated" block region. Otherwise, we will return 0 and
4220 * ext4_ext_map_blocks() will then allocate one or more new clusters
4221 * by calling ext4_mb_new_blocks().
4223 static int get_implied_cluster_alloc(struct super_block *sb,
4224 struct ext4_map_blocks *map,
4225 struct ext4_extent *ex,
4226 struct ext4_ext_path *path)
4228 struct ext4_sb_info *sbi = EXT4_SB(sb);
4229 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4230 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4231 ext4_lblk_t rr_cluster_start;
4232 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4233 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4234 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4236 /* The extent passed in that we are trying to match */
4237 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4238 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4240 /* The requested region passed into ext4_map_blocks() */
4241 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4243 if ((rr_cluster_start == ex_cluster_end) ||
4244 (rr_cluster_start == ex_cluster_start)) {
4245 if (rr_cluster_start == ex_cluster_end)
4246 ee_start += ee_len - 1;
4247 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4248 map->m_len = min(map->m_len,
4249 (unsigned) sbi->s_cluster_ratio - c_offset);
4251 * Check for and handle this case:
4253 * |--------- cluster # N-------------|
4254 * |------- extent ----|
4255 * |--- requested region ---|
4256 * |===========|
4259 if (map->m_lblk < ee_block)
4260 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4263 * Check for the case where there is already another allocated
4264 * block to the right of 'ex' but before the end of the cluster.
4266 * |------------- cluster # N-------------|
4267 * |----- ex -----| |---- ex_right ----|
4268 * |------ requested region ------|
4269 * |================|
4271 if (map->m_lblk > ee_block) {
4272 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4273 map->m_len = min(map->m_len, next - map->m_lblk);
4276 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4277 return 1;
4280 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4281 return 0;
4286 * Block allocation/map/preallocation routine for extents based files
4289 * Need to be called with
4290 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4291 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4293 * return > 0, number of of blocks already mapped/allocated
4294 * if create == 0 and these are pre-allocated blocks
4295 * buffer head is unmapped
4296 * otherwise blocks are mapped
4298 * return = 0, if plain look up failed (blocks have not been allocated)
4299 * buffer head is unmapped
4301 * return < 0, error case.
4303 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4304 struct ext4_map_blocks *map, int flags)
4306 struct ext4_ext_path *path = NULL;
4307 struct ext4_extent newex, *ex, *ex2;
4308 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4309 ext4_fsblk_t newblock = 0;
4310 int free_on_err = 0, err = 0, depth, ret;
4311 unsigned int allocated = 0, offset = 0;
4312 unsigned int allocated_clusters = 0;
4313 struct ext4_allocation_request ar;
4314 ext4_lblk_t cluster_offset;
4315 bool map_from_cluster = false;
4317 ext_debug("blocks %u/%u requested for inode %lu\n",
4318 map->m_lblk, map->m_len, inode->i_ino);
4319 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4321 /* find extent for this block */
4322 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4323 if (IS_ERR(path)) {
4324 err = PTR_ERR(path);
4325 path = NULL;
4326 goto out2;
4329 depth = ext_depth(inode);
4332 * consistent leaf must not be empty;
4333 * this situation is possible, though, _during_ tree modification;
4334 * this is why assert can't be put in ext4_find_extent()
4336 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4337 EXT4_ERROR_INODE(inode, "bad extent address "
4338 "lblock: %lu, depth: %d pblock %lld",
4339 (unsigned long) map->m_lblk, depth,
4340 path[depth].p_block);
4341 err = -EFSCORRUPTED;
4342 goto out2;
4345 ex = path[depth].p_ext;
4346 if (ex) {
4347 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4348 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4349 unsigned short ee_len;
4353 * unwritten extents are treated as holes, except that
4354 * we split out initialized portions during a write.
4356 ee_len = ext4_ext_get_actual_len(ex);
4358 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4360 /* if found extent covers block, simply return it */
4361 if (in_range(map->m_lblk, ee_block, ee_len)) {
4362 newblock = map->m_lblk - ee_block + ee_start;
4363 /* number of remaining blocks in the extent */
4364 allocated = ee_len - (map->m_lblk - ee_block);
4365 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4366 ee_block, ee_len, newblock);
4369 * If the extent is initialized check whether the
4370 * caller wants to convert it to unwritten.
4372 if ((!ext4_ext_is_unwritten(ex)) &&
4373 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4374 allocated = convert_initialized_extent(
4375 handle, inode, map, &path,
4376 allocated);
4377 goto out2;
4378 } else if (!ext4_ext_is_unwritten(ex))
4379 goto out;
4381 ret = ext4_ext_handle_unwritten_extents(
4382 handle, inode, map, &path, flags,
4383 allocated, newblock);
4384 if (ret < 0)
4385 err = ret;
4386 else
4387 allocated = ret;
4388 goto out2;
4393 * requested block isn't allocated yet;
4394 * we couldn't try to create block if create flag is zero
4396 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4397 ext4_lblk_t hole_start, hole_len;
4399 hole_start = map->m_lblk;
4400 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4402 * put just found gap into cache to speed up
4403 * subsequent requests
4405 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4407 /* Update hole_len to reflect hole size after map->m_lblk */
4408 if (hole_start != map->m_lblk)
4409 hole_len -= map->m_lblk - hole_start;
4410 map->m_pblk = 0;
4411 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4413 goto out2;
4417 * Okay, we need to do block allocation.
4419 newex.ee_block = cpu_to_le32(map->m_lblk);
4420 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4423 * If we are doing bigalloc, check to see if the extent returned
4424 * by ext4_find_extent() implies a cluster we can use.
4426 if (cluster_offset && ex &&
4427 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4428 ar.len = allocated = map->m_len;
4429 newblock = map->m_pblk;
4430 map_from_cluster = true;
4431 goto got_allocated_blocks;
4434 /* find neighbour allocated blocks */
4435 ar.lleft = map->m_lblk;
4436 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4437 if (err)
4438 goto out2;
4439 ar.lright = map->m_lblk;
4440 ex2 = NULL;
4441 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4442 if (err)
4443 goto out2;
4445 /* Check if the extent after searching to the right implies a
4446 * cluster we can use. */
4447 if ((sbi->s_cluster_ratio > 1) && ex2 &&
4448 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4449 ar.len = allocated = map->m_len;
4450 newblock = map->m_pblk;
4451 map_from_cluster = true;
4452 goto got_allocated_blocks;
4456 * See if request is beyond maximum number of blocks we can have in
4457 * a single extent. For an initialized extent this limit is
4458 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4459 * EXT_UNWRITTEN_MAX_LEN.
4461 if (map->m_len > EXT_INIT_MAX_LEN &&
4462 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4463 map->m_len = EXT_INIT_MAX_LEN;
4464 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4465 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4466 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4468 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4469 newex.ee_len = cpu_to_le16(map->m_len);
4470 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4471 if (err)
4472 allocated = ext4_ext_get_actual_len(&newex);
4473 else
4474 allocated = map->m_len;
4476 /* allocate new block */
4477 ar.inode = inode;
4478 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4479 ar.logical = map->m_lblk;
4481 * We calculate the offset from the beginning of the cluster
4482 * for the logical block number, since when we allocate a
4483 * physical cluster, the physical block should start at the
4484 * same offset from the beginning of the cluster. This is
4485 * needed so that future calls to get_implied_cluster_alloc()
4486 * work correctly.
4488 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4489 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4490 ar.goal -= offset;
4491 ar.logical -= offset;
4492 if (S_ISREG(inode->i_mode))
4493 ar.flags = EXT4_MB_HINT_DATA;
4494 else
4495 /* disable in-core preallocation for non-regular files */
4496 ar.flags = 0;
4497 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4498 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4499 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4500 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4501 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4502 ar.flags |= EXT4_MB_USE_RESERVED;
4503 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4504 if (!newblock)
4505 goto out2;
4506 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4507 ar.goal, newblock, allocated);
4508 free_on_err = 1;
4509 allocated_clusters = ar.len;
4510 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4511 if (ar.len > allocated)
4512 ar.len = allocated;
4514 got_allocated_blocks:
4515 /* try to insert new extent into found leaf and return */
4516 ext4_ext_store_pblock(&newex, newblock + offset);
4517 newex.ee_len = cpu_to_le16(ar.len);
4518 /* Mark unwritten */
4519 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4520 ext4_ext_mark_unwritten(&newex);
4521 map->m_flags |= EXT4_MAP_UNWRITTEN;
4524 err = 0;
4525 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4526 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4527 path, ar.len);
4528 if (!err)
4529 err = ext4_ext_insert_extent(handle, inode, &path,
4530 &newex, flags);
4532 if (err && free_on_err) {
4533 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4534 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4535 /* free data blocks we just allocated */
4536 /* not a good idea to call discard here directly,
4537 * but otherwise we'd need to call it every free() */
4538 ext4_discard_preallocations(inode);
4539 ext4_free_blocks(handle, inode, NULL, newblock,
4540 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4541 goto out2;
4544 /* previous routine could use block we allocated */
4545 newblock = ext4_ext_pblock(&newex);
4546 allocated = ext4_ext_get_actual_len(&newex);
4547 if (allocated > map->m_len)
4548 allocated = map->m_len;
4549 map->m_flags |= EXT4_MAP_NEW;
4552 * Update reserved blocks/metadata blocks after successful
4553 * block allocation which had been deferred till now.
4555 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4556 unsigned int reserved_clusters;
4558 * Check how many clusters we had reserved this allocated range
4560 reserved_clusters = get_reserved_cluster_alloc(inode,
4561 map->m_lblk, allocated);
4562 if (!map_from_cluster) {
4563 BUG_ON(allocated_clusters < reserved_clusters);
4564 if (reserved_clusters < allocated_clusters) {
4565 struct ext4_inode_info *ei = EXT4_I(inode);
4566 int reservation = allocated_clusters -
4567 reserved_clusters;
4569 * It seems we claimed few clusters outside of
4570 * the range of this allocation. We should give
4571 * it back to the reservation pool. This can
4572 * happen in the following case:
4574 * * Suppose s_cluster_ratio is 4 (i.e., each
4575 * cluster has 4 blocks. Thus, the clusters
4576 * are [0-3],[4-7],[8-11]...
4577 * * First comes delayed allocation write for
4578 * logical blocks 10 & 11. Since there were no
4579 * previous delayed allocated blocks in the
4580 * range [8-11], we would reserve 1 cluster
4581 * for this write.
4582 * * Next comes write for logical blocks 3 to 8.
4583 * In this case, we will reserve 2 clusters
4584 * (for [0-3] and [4-7]; and not for [8-11] as
4585 * that range has a delayed allocated blocks.
4586 * Thus total reserved clusters now becomes 3.
4587 * * Now, during the delayed allocation writeout
4588 * time, we will first write blocks [3-8] and
4589 * allocate 3 clusters for writing these
4590 * blocks. Also, we would claim all these
4591 * three clusters above.
4592 * * Now when we come here to writeout the
4593 * blocks [10-11], we would expect to claim
4594 * the reservation of 1 cluster we had made
4595 * (and we would claim it since there are no
4596 * more delayed allocated blocks in the range
4597 * [8-11]. But our reserved cluster count had
4598 * already gone to 0.
4600 * Thus, at the step 4 above when we determine
4601 * that there are still some unwritten delayed
4602 * allocated blocks outside of our current
4603 * block range, we should increment the
4604 * reserved clusters count so that when the
4605 * remaining blocks finally gets written, we
4606 * could claim them.
4608 dquot_reserve_block(inode,
4609 EXT4_C2B(sbi, reservation));
4610 spin_lock(&ei->i_block_reservation_lock);
4611 ei->i_reserved_data_blocks += reservation;
4612 spin_unlock(&ei->i_block_reservation_lock);
4615 * We will claim quota for all newly allocated blocks.
4616 * We're updating the reserved space *after* the
4617 * correction above so we do not accidentally free
4618 * all the metadata reservation because we might
4619 * actually need it later on.
4621 ext4_da_update_reserve_space(inode, allocated_clusters,
4627 * Cache the extent and update transaction to commit on fdatasync only
4628 * when it is _not_ an unwritten extent.
4630 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4631 ext4_update_inode_fsync_trans(handle, inode, 1);
4632 else
4633 ext4_update_inode_fsync_trans(handle, inode, 0);
4634 out:
4635 if (allocated > map->m_len)
4636 allocated = map->m_len;
4637 ext4_ext_show_leaf(inode, path);
4638 map->m_flags |= EXT4_MAP_MAPPED;
4639 map->m_pblk = newblock;
4640 map->m_len = allocated;
4641 out2:
4642 ext4_ext_drop_refs(path);
4643 kfree(path);
4645 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4646 err ? err : allocated);
4647 return err ? err : allocated;
4650 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4652 struct super_block *sb = inode->i_sb;
4653 ext4_lblk_t last_block;
4654 int err = 0;
4657 * TODO: optimization is possible here.
4658 * Probably we need not scan at all,
4659 * because page truncation is enough.
4662 /* we have to know where to truncate from in crash case */
4663 EXT4_I(inode)->i_disksize = inode->i_size;
4664 err = ext4_mark_inode_dirty(handle, inode);
4665 if (err)
4666 return err;
4668 last_block = (inode->i_size + sb->s_blocksize - 1)
4669 >> EXT4_BLOCK_SIZE_BITS(sb);
4670 retry:
4671 err = ext4_es_remove_extent(inode, last_block,
4672 EXT_MAX_BLOCKS - last_block);
4673 if (err == -ENOMEM) {
4674 cond_resched();
4675 congestion_wait(BLK_RW_ASYNC, HZ/50);
4676 goto retry;
4678 if (err)
4679 return err;
4680 return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4683 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4684 ext4_lblk_t len, loff_t new_size,
4685 int flags)
4687 struct inode *inode = file_inode(file);
4688 handle_t *handle;
4689 int ret = 0;
4690 int ret2 = 0;
4691 int retries = 0;
4692 int depth = 0;
4693 struct ext4_map_blocks map;
4694 unsigned int credits;
4695 loff_t epos;
4697 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4698 map.m_lblk = offset;
4699 map.m_len = len;
4701 * Don't normalize the request if it can fit in one extent so
4702 * that it doesn't get unnecessarily split into multiple
4703 * extents.
4705 if (len <= EXT_UNWRITTEN_MAX_LEN)
4706 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4709 * credits to insert 1 extent into extent tree
4711 credits = ext4_chunk_trans_blocks(inode, len);
4712 depth = ext_depth(inode);
4714 retry:
4715 while (ret >= 0 && len) {
4717 * Recalculate credits when extent tree depth changes.
4719 if (depth != ext_depth(inode)) {
4720 credits = ext4_chunk_trans_blocks(inode, len);
4721 depth = ext_depth(inode);
4724 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4725 credits);
4726 if (IS_ERR(handle)) {
4727 ret = PTR_ERR(handle);
4728 break;
4730 ret = ext4_map_blocks(handle, inode, &map, flags);
4731 if (ret <= 0) {
4732 ext4_debug("inode #%lu: block %u: len %u: "
4733 "ext4_ext_map_blocks returned %d",
4734 inode->i_ino, map.m_lblk,
4735 map.m_len, ret);
4736 ext4_mark_inode_dirty(handle, inode);
4737 ret2 = ext4_journal_stop(handle);
4738 break;
4740 map.m_lblk += ret;
4741 map.m_len = len = len - ret;
4742 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4743 inode->i_ctime = current_time(inode);
4744 if (new_size) {
4745 if (epos > new_size)
4746 epos = new_size;
4747 if (ext4_update_inode_size(inode, epos) & 0x1)
4748 inode->i_mtime = inode->i_ctime;
4749 } else {
4750 if (epos > inode->i_size)
4751 ext4_set_inode_flag(inode,
4752 EXT4_INODE_EOFBLOCKS);
4754 ext4_mark_inode_dirty(handle, inode);
4755 ext4_update_inode_fsync_trans(handle, inode, 1);
4756 ret2 = ext4_journal_stop(handle);
4757 if (ret2)
4758 break;
4760 if (ret == -ENOSPC &&
4761 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4762 ret = 0;
4763 goto retry;
4766 return ret > 0 ? ret2 : ret;
4769 static long ext4_zero_range(struct file *file, loff_t offset,
4770 loff_t len, int mode)
4772 struct inode *inode = file_inode(file);
4773 handle_t *handle = NULL;
4774 unsigned int max_blocks;
4775 loff_t new_size = 0;
4776 int ret = 0;
4777 int flags;
4778 int credits;
4779 int partial_begin, partial_end;
4780 loff_t start, end;
4781 ext4_lblk_t lblk;
4782 unsigned int blkbits = inode->i_blkbits;
4784 trace_ext4_zero_range(inode, offset, len, mode);
4786 if (!S_ISREG(inode->i_mode))
4787 return -EINVAL;
4789 /* Call ext4_force_commit to flush all data in case of data=journal. */
4790 if (ext4_should_journal_data(inode)) {
4791 ret = ext4_force_commit(inode->i_sb);
4792 if (ret)
4793 return ret;
4797 * Round up offset. This is not fallocate, we neet to zero out
4798 * blocks, so convert interior block aligned part of the range to
4799 * unwritten and possibly manually zero out unaligned parts of the
4800 * range.
4802 start = round_up(offset, 1 << blkbits);
4803 end = round_down((offset + len), 1 << blkbits);
4805 if (start < offset || end > offset + len)
4806 return -EINVAL;
4807 partial_begin = offset & ((1 << blkbits) - 1);
4808 partial_end = (offset + len) & ((1 << blkbits) - 1);
4810 lblk = start >> blkbits;
4811 max_blocks = (end >> blkbits);
4812 if (max_blocks < lblk)
4813 max_blocks = 0;
4814 else
4815 max_blocks -= lblk;
4817 inode_lock(inode);
4820 * Indirect files do not support unwritten extnets
4822 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4823 ret = -EOPNOTSUPP;
4824 goto out_mutex;
4827 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4828 (offset + len > i_size_read(inode) ||
4829 offset + len > EXT4_I(inode)->i_disksize)) {
4830 new_size = offset + len;
4831 ret = inode_newsize_ok(inode, new_size);
4832 if (ret)
4833 goto out_mutex;
4836 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4837 if (mode & FALLOC_FL_KEEP_SIZE)
4838 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4840 /* Wait all existing dio workers, newcomers will block on i_mutex */
4841 ext4_inode_block_unlocked_dio(inode);
4842 inode_dio_wait(inode);
4844 /* Preallocate the range including the unaligned edges */
4845 if (partial_begin || partial_end) {
4846 ret = ext4_alloc_file_blocks(file,
4847 round_down(offset, 1 << blkbits) >> blkbits,
4848 (round_up((offset + len), 1 << blkbits) -
4849 round_down(offset, 1 << blkbits)) >> blkbits,
4850 new_size, flags);
4851 if (ret)
4852 goto out_dio;
4856 /* Zero range excluding the unaligned edges */
4857 if (max_blocks > 0) {
4858 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4859 EXT4_EX_NOCACHE);
4862 * Prevent page faults from reinstantiating pages we have
4863 * released from page cache.
4865 down_write(&EXT4_I(inode)->i_mmap_sem);
4866 ret = ext4_update_disksize_before_punch(inode, offset, len);
4867 if (ret) {
4868 up_write(&EXT4_I(inode)->i_mmap_sem);
4869 goto out_dio;
4871 /* Now release the pages and zero block aligned part of pages */
4872 truncate_pagecache_range(inode, start, end - 1);
4873 inode->i_mtime = inode->i_ctime = current_time(inode);
4875 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4876 flags);
4877 up_write(&EXT4_I(inode)->i_mmap_sem);
4878 if (ret)
4879 goto out_dio;
4881 if (!partial_begin && !partial_end)
4882 goto out_dio;
4885 * In worst case we have to writeout two nonadjacent unwritten
4886 * blocks and update the inode
4888 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4889 if (ext4_should_journal_data(inode))
4890 credits += 2;
4891 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4892 if (IS_ERR(handle)) {
4893 ret = PTR_ERR(handle);
4894 ext4_std_error(inode->i_sb, ret);
4895 goto out_dio;
4898 inode->i_mtime = inode->i_ctime = current_time(inode);
4899 if (new_size) {
4900 ext4_update_inode_size(inode, new_size);
4901 } else {
4903 * Mark that we allocate beyond EOF so the subsequent truncate
4904 * can proceed even if the new size is the same as i_size.
4906 if ((offset + len) > i_size_read(inode))
4907 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4909 ext4_mark_inode_dirty(handle, inode);
4911 /* Zero out partial block at the edges of the range */
4912 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4913 if (ret >= 0)
4914 ext4_update_inode_fsync_trans(handle, inode, 1);
4916 if (file->f_flags & O_SYNC)
4917 ext4_handle_sync(handle);
4919 ext4_journal_stop(handle);
4920 out_dio:
4921 ext4_inode_resume_unlocked_dio(inode);
4922 out_mutex:
4923 inode_unlock(inode);
4924 return ret;
4928 * preallocate space for a file. This implements ext4's fallocate file
4929 * operation, which gets called from sys_fallocate system call.
4930 * For block-mapped files, posix_fallocate should fall back to the method
4931 * of writing zeroes to the required new blocks (the same behavior which is
4932 * expected for file systems which do not support fallocate() system call).
4934 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4936 struct inode *inode = file_inode(file);
4937 loff_t new_size = 0;
4938 unsigned int max_blocks;
4939 int ret = 0;
4940 int flags;
4941 ext4_lblk_t lblk;
4942 unsigned int blkbits = inode->i_blkbits;
4945 * Encrypted inodes can't handle collapse range or insert
4946 * range since we would need to re-encrypt blocks with a
4947 * different IV or XTS tweak (which are based on the logical
4948 * block number).
4950 * XXX It's not clear why zero range isn't working, but we'll
4951 * leave it disabled for encrypted inodes for now. This is a
4952 * bug we should fix....
4954 if (ext4_encrypted_inode(inode) &&
4955 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
4956 FALLOC_FL_ZERO_RANGE)))
4957 return -EOPNOTSUPP;
4959 /* Return error if mode is not supported */
4960 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4961 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4962 FALLOC_FL_INSERT_RANGE))
4963 return -EOPNOTSUPP;
4965 if (mode & FALLOC_FL_PUNCH_HOLE)
4966 return ext4_punch_hole(inode, offset, len);
4968 ret = ext4_convert_inline_data(inode);
4969 if (ret)
4970 return ret;
4972 if (mode & FALLOC_FL_COLLAPSE_RANGE)
4973 return ext4_collapse_range(inode, offset, len);
4975 if (mode & FALLOC_FL_INSERT_RANGE)
4976 return ext4_insert_range(inode, offset, len);
4978 if (mode & FALLOC_FL_ZERO_RANGE)
4979 return ext4_zero_range(file, offset, len, mode);
4981 trace_ext4_fallocate_enter(inode, offset, len, mode);
4982 lblk = offset >> blkbits;
4984 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4985 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4986 if (mode & FALLOC_FL_KEEP_SIZE)
4987 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4989 inode_lock(inode);
4992 * We only support preallocation for extent-based files only
4994 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4995 ret = -EOPNOTSUPP;
4996 goto out;
4999 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
5000 (offset + len > i_size_read(inode) ||
5001 offset + len > EXT4_I(inode)->i_disksize)) {
5002 new_size = offset + len;
5003 ret = inode_newsize_ok(inode, new_size);
5004 if (ret)
5005 goto out;
5008 /* Wait all existing dio workers, newcomers will block on i_mutex */
5009 ext4_inode_block_unlocked_dio(inode);
5010 inode_dio_wait(inode);
5012 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
5013 ext4_inode_resume_unlocked_dio(inode);
5014 if (ret)
5015 goto out;
5017 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
5018 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5019 EXT4_I(inode)->i_sync_tid);
5021 out:
5022 inode_unlock(inode);
5023 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
5024 return ret;
5028 * This function convert a range of blocks to written extents
5029 * The caller of this function will pass the start offset and the size.
5030 * all unwritten extents within this range will be converted to
5031 * written extents.
5033 * This function is called from the direct IO end io call back
5034 * function, to convert the fallocated extents after IO is completed.
5035 * Returns 0 on success.
5037 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
5038 loff_t offset, ssize_t len)
5040 unsigned int max_blocks;
5041 int ret = 0;
5042 int ret2 = 0;
5043 struct ext4_map_blocks map;
5044 unsigned int credits, blkbits = inode->i_blkbits;
5046 map.m_lblk = offset >> blkbits;
5047 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
5050 * This is somewhat ugly but the idea is clear: When transaction is
5051 * reserved, everything goes into it. Otherwise we rather start several
5052 * smaller transactions for conversion of each extent separately.
5054 if (handle) {
5055 handle = ext4_journal_start_reserved(handle,
5056 EXT4_HT_EXT_CONVERT);
5057 if (IS_ERR(handle))
5058 return PTR_ERR(handle);
5059 credits = 0;
5060 } else {
5062 * credits to insert 1 extent into extent tree
5064 credits = ext4_chunk_trans_blocks(inode, max_blocks);
5066 while (ret >= 0 && ret < max_blocks) {
5067 map.m_lblk += ret;
5068 map.m_len = (max_blocks -= ret);
5069 if (credits) {
5070 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5071 credits);
5072 if (IS_ERR(handle)) {
5073 ret = PTR_ERR(handle);
5074 break;
5077 ret = ext4_map_blocks(handle, inode, &map,
5078 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5079 if (ret <= 0)
5080 ext4_warning(inode->i_sb,
5081 "inode #%lu: block %u: len %u: "
5082 "ext4_ext_map_blocks returned %d",
5083 inode->i_ino, map.m_lblk,
5084 map.m_len, ret);
5085 ext4_mark_inode_dirty(handle, inode);
5086 if (credits)
5087 ret2 = ext4_journal_stop(handle);
5088 if (ret <= 0 || ret2)
5089 break;
5091 if (!credits)
5092 ret2 = ext4_journal_stop(handle);
5093 return ret > 0 ? ret2 : ret;
5097 * If newes is not existing extent (newes->ec_pblk equals zero) find
5098 * delayed extent at start of newes and update newes accordingly and
5099 * return start of the next delayed extent.
5101 * If newes is existing extent (newes->ec_pblk is not equal zero)
5102 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5103 * extent found. Leave newes unmodified.
5105 static int ext4_find_delayed_extent(struct inode *inode,
5106 struct extent_status *newes)
5108 struct extent_status es;
5109 ext4_lblk_t block, next_del;
5111 if (newes->es_pblk == 0) {
5112 ext4_es_find_delayed_extent_range(inode, newes->es_lblk,
5113 newes->es_lblk + newes->es_len - 1, &es);
5116 * No extent in extent-tree contains block @newes->es_pblk,
5117 * then the block may stay in 1)a hole or 2)delayed-extent.
5119 if (es.es_len == 0)
5120 /* A hole found. */
5121 return 0;
5123 if (es.es_lblk > newes->es_lblk) {
5124 /* A hole found. */
5125 newes->es_len = min(es.es_lblk - newes->es_lblk,
5126 newes->es_len);
5127 return 0;
5130 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5133 block = newes->es_lblk + newes->es_len;
5134 ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es);
5135 if (es.es_len == 0)
5136 next_del = EXT_MAX_BLOCKS;
5137 else
5138 next_del = es.es_lblk;
5140 return next_del;
5142 /* fiemap flags we can handle specified here */
5143 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
5145 static int ext4_xattr_fiemap(struct inode *inode,
5146 struct fiemap_extent_info *fieinfo)
5148 __u64 physical = 0;
5149 __u64 length;
5150 __u32 flags = FIEMAP_EXTENT_LAST;
5151 int blockbits = inode->i_sb->s_blocksize_bits;
5152 int error = 0;
5154 /* in-inode? */
5155 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5156 struct ext4_iloc iloc;
5157 int offset; /* offset of xattr in inode */
5159 error = ext4_get_inode_loc(inode, &iloc);
5160 if (error)
5161 return error;
5162 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5163 offset = EXT4_GOOD_OLD_INODE_SIZE +
5164 EXT4_I(inode)->i_extra_isize;
5165 physical += offset;
5166 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5167 flags |= FIEMAP_EXTENT_DATA_INLINE;
5168 brelse(iloc.bh);
5169 } else { /* external block */
5170 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5171 length = inode->i_sb->s_blocksize;
5174 if (physical)
5175 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5176 length, flags);
5177 return (error < 0 ? error : 0);
5180 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5181 __u64 start, __u64 len)
5183 ext4_lblk_t start_blk;
5184 int error = 0;
5186 if (ext4_has_inline_data(inode)) {
5187 int has_inline = 1;
5189 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5190 start, len);
5192 if (has_inline)
5193 return error;
5196 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5197 error = ext4_ext_precache(inode);
5198 if (error)
5199 return error;
5202 /* fallback to generic here if not in extents fmt */
5203 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5204 return generic_block_fiemap(inode, fieinfo, start, len,
5205 ext4_get_block);
5207 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
5208 return -EBADR;
5210 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5211 error = ext4_xattr_fiemap(inode, fieinfo);
5212 } else {
5213 ext4_lblk_t len_blks;
5214 __u64 last_blk;
5216 start_blk = start >> inode->i_sb->s_blocksize_bits;
5217 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5218 if (last_blk >= EXT_MAX_BLOCKS)
5219 last_blk = EXT_MAX_BLOCKS-1;
5220 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5223 * Walk the extent tree gathering extent information
5224 * and pushing extents back to the user.
5226 error = ext4_fill_fiemap_extents(inode, start_blk,
5227 len_blks, fieinfo);
5229 return error;
5233 * ext4_access_path:
5234 * Function to access the path buffer for marking it dirty.
5235 * It also checks if there are sufficient credits left in the journal handle
5236 * to update path.
5238 static int
5239 ext4_access_path(handle_t *handle, struct inode *inode,
5240 struct ext4_ext_path *path)
5242 int credits, err;
5244 if (!ext4_handle_valid(handle))
5245 return 0;
5248 * Check if need to extend journal credits
5249 * 3 for leaf, sb, and inode plus 2 (bmap and group
5250 * descriptor) for each block group; assume two block
5251 * groups
5253 if (handle->h_buffer_credits < 7) {
5254 credits = ext4_writepage_trans_blocks(inode);
5255 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
5256 /* EAGAIN is success */
5257 if (err && err != -EAGAIN)
5258 return err;
5261 err = ext4_ext_get_access(handle, inode, path);
5262 return err;
5266 * ext4_ext_shift_path_extents:
5267 * Shift the extents of a path structure lying between path[depth].p_ext
5268 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5269 * if it is right shift or left shift operation.
5271 static int
5272 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5273 struct inode *inode, handle_t *handle,
5274 enum SHIFT_DIRECTION SHIFT)
5276 int depth, err = 0;
5277 struct ext4_extent *ex_start, *ex_last;
5278 bool update = 0;
5279 depth = path->p_depth;
5281 while (depth >= 0) {
5282 if (depth == path->p_depth) {
5283 ex_start = path[depth].p_ext;
5284 if (!ex_start)
5285 return -EFSCORRUPTED;
5287 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5289 err = ext4_access_path(handle, inode, path + depth);
5290 if (err)
5291 goto out;
5293 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5294 update = 1;
5296 while (ex_start <= ex_last) {
5297 if (SHIFT == SHIFT_LEFT) {
5298 le32_add_cpu(&ex_start->ee_block,
5299 -shift);
5300 /* Try to merge to the left. */
5301 if ((ex_start >
5302 EXT_FIRST_EXTENT(path[depth].p_hdr))
5304 ext4_ext_try_to_merge_right(inode,
5305 path, ex_start - 1))
5306 ex_last--;
5307 else
5308 ex_start++;
5309 } else {
5310 le32_add_cpu(&ex_last->ee_block, shift);
5311 ext4_ext_try_to_merge_right(inode, path,
5312 ex_last);
5313 ex_last--;
5316 err = ext4_ext_dirty(handle, inode, path + depth);
5317 if (err)
5318 goto out;
5320 if (--depth < 0 || !update)
5321 break;
5324 /* Update index too */
5325 err = ext4_access_path(handle, inode, path + depth);
5326 if (err)
5327 goto out;
5329 if (SHIFT == SHIFT_LEFT)
5330 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5331 else
5332 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5333 err = ext4_ext_dirty(handle, inode, path + depth);
5334 if (err)
5335 goto out;
5337 /* we are done if current index is not a starting index */
5338 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5339 break;
5341 depth--;
5344 out:
5345 return err;
5349 * ext4_ext_shift_extents:
5350 * All the extents which lies in the range from @start to the last allocated
5351 * block for the @inode are shifted either towards left or right (depending
5352 * upon @SHIFT) by @shift blocks.
5353 * On success, 0 is returned, error otherwise.
5355 static int
5356 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5357 ext4_lblk_t start, ext4_lblk_t shift,
5358 enum SHIFT_DIRECTION SHIFT)
5360 struct ext4_ext_path *path;
5361 int ret = 0, depth;
5362 struct ext4_extent *extent;
5363 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5365 /* Let path point to the last extent */
5366 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5367 EXT4_EX_NOCACHE);
5368 if (IS_ERR(path))
5369 return PTR_ERR(path);
5371 depth = path->p_depth;
5372 extent = path[depth].p_ext;
5373 if (!extent)
5374 goto out;
5376 stop = le32_to_cpu(extent->ee_block);
5379 * For left shifts, make sure the hole on the left is big enough to
5380 * accommodate the shift. For right shifts, make sure the last extent
5381 * won't be shifted beyond EXT_MAX_BLOCKS.
5383 if (SHIFT == SHIFT_LEFT) {
5384 path = ext4_find_extent(inode, start - 1, &path,
5385 EXT4_EX_NOCACHE);
5386 if (IS_ERR(path))
5387 return PTR_ERR(path);
5388 depth = path->p_depth;
5389 extent = path[depth].p_ext;
5390 if (extent) {
5391 ex_start = le32_to_cpu(extent->ee_block);
5392 ex_end = le32_to_cpu(extent->ee_block) +
5393 ext4_ext_get_actual_len(extent);
5394 } else {
5395 ex_start = 0;
5396 ex_end = 0;
5399 if ((start == ex_start && shift > ex_start) ||
5400 (shift > start - ex_end)) {
5401 ret = -EINVAL;
5402 goto out;
5404 } else {
5405 if (shift > EXT_MAX_BLOCKS -
5406 (stop + ext4_ext_get_actual_len(extent))) {
5407 ret = -EINVAL;
5408 goto out;
5413 * In case of left shift, iterator points to start and it is increased
5414 * till we reach stop. In case of right shift, iterator points to stop
5415 * and it is decreased till we reach start.
5417 if (SHIFT == SHIFT_LEFT)
5418 iterator = &start;
5419 else
5420 iterator = &stop;
5423 * Its safe to start updating extents. Start and stop are unsigned, so
5424 * in case of right shift if extent with 0 block is reached, iterator
5425 * becomes NULL to indicate the end of the loop.
5427 while (iterator && start <= stop) {
5428 path = ext4_find_extent(inode, *iterator, &path,
5429 EXT4_EX_NOCACHE);
5430 if (IS_ERR(path))
5431 return PTR_ERR(path);
5432 depth = path->p_depth;
5433 extent = path[depth].p_ext;
5434 if (!extent) {
5435 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5436 (unsigned long) *iterator);
5437 return -EFSCORRUPTED;
5439 if (SHIFT == SHIFT_LEFT && *iterator >
5440 le32_to_cpu(extent->ee_block)) {
5441 /* Hole, move to the next extent */
5442 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5443 path[depth].p_ext++;
5444 } else {
5445 *iterator = ext4_ext_next_allocated_block(path);
5446 continue;
5450 if (SHIFT == SHIFT_LEFT) {
5451 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5452 *iterator = le32_to_cpu(extent->ee_block) +
5453 ext4_ext_get_actual_len(extent);
5454 } else {
5455 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5456 if (le32_to_cpu(extent->ee_block) > 0)
5457 *iterator = le32_to_cpu(extent->ee_block) - 1;
5458 else
5459 /* Beginning is reached, end of the loop */
5460 iterator = NULL;
5461 /* Update path extent in case we need to stop */
5462 while (le32_to_cpu(extent->ee_block) < start)
5463 extent++;
5464 path[depth].p_ext = extent;
5466 ret = ext4_ext_shift_path_extents(path, shift, inode,
5467 handle, SHIFT);
5468 if (ret)
5469 break;
5471 out:
5472 ext4_ext_drop_refs(path);
5473 kfree(path);
5474 return ret;
5478 * ext4_collapse_range:
5479 * This implements the fallocate's collapse range functionality for ext4
5480 * Returns: 0 and non-zero on error.
5482 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5484 struct super_block *sb = inode->i_sb;
5485 ext4_lblk_t punch_start, punch_stop;
5486 handle_t *handle;
5487 unsigned int credits;
5488 loff_t new_size, ioffset;
5489 int ret;
5492 * We need to test this early because xfstests assumes that a
5493 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5494 * system does not support collapse range.
5496 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5497 return -EOPNOTSUPP;
5499 /* Collapse range works only on fs block size aligned offsets. */
5500 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5501 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5502 return -EINVAL;
5504 if (!S_ISREG(inode->i_mode))
5505 return -EINVAL;
5507 trace_ext4_collapse_range(inode, offset, len);
5509 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5510 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5512 /* Call ext4_force_commit to flush all data in case of data=journal. */
5513 if (ext4_should_journal_data(inode)) {
5514 ret = ext4_force_commit(inode->i_sb);
5515 if (ret)
5516 return ret;
5519 inode_lock(inode);
5521 * There is no need to overlap collapse range with EOF, in which case
5522 * it is effectively a truncate operation
5524 if (offset + len >= i_size_read(inode)) {
5525 ret = -EINVAL;
5526 goto out_mutex;
5529 /* Currently just for extent based files */
5530 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5531 ret = -EOPNOTSUPP;
5532 goto out_mutex;
5535 /* Wait for existing dio to complete */
5536 ext4_inode_block_unlocked_dio(inode);
5537 inode_dio_wait(inode);
5540 * Prevent page faults from reinstantiating pages we have released from
5541 * page cache.
5543 down_write(&EXT4_I(inode)->i_mmap_sem);
5545 * Need to round down offset to be aligned with page size boundary
5546 * for page size > block size.
5548 ioffset = round_down(offset, PAGE_SIZE);
5550 * Write tail of the last page before removed range since it will get
5551 * removed from the page cache below.
5553 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5554 if (ret)
5555 goto out_mmap;
5557 * Write data that will be shifted to preserve them when discarding
5558 * page cache below. We are also protected from pages becoming dirty
5559 * by i_mmap_sem.
5561 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5562 LLONG_MAX);
5563 if (ret)
5564 goto out_mmap;
5565 truncate_pagecache(inode, ioffset);
5567 credits = ext4_writepage_trans_blocks(inode);
5568 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5569 if (IS_ERR(handle)) {
5570 ret = PTR_ERR(handle);
5571 goto out_mmap;
5574 down_write(&EXT4_I(inode)->i_data_sem);
5575 ext4_discard_preallocations(inode);
5577 ret = ext4_es_remove_extent(inode, punch_start,
5578 EXT_MAX_BLOCKS - punch_start);
5579 if (ret) {
5580 up_write(&EXT4_I(inode)->i_data_sem);
5581 goto out_stop;
5584 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5585 if (ret) {
5586 up_write(&EXT4_I(inode)->i_data_sem);
5587 goto out_stop;
5589 ext4_discard_preallocations(inode);
5591 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5592 punch_stop - punch_start, SHIFT_LEFT);
5593 if (ret) {
5594 up_write(&EXT4_I(inode)->i_data_sem);
5595 goto out_stop;
5598 new_size = i_size_read(inode) - len;
5599 i_size_write(inode, new_size);
5600 EXT4_I(inode)->i_disksize = new_size;
5602 up_write(&EXT4_I(inode)->i_data_sem);
5603 if (IS_SYNC(inode))
5604 ext4_handle_sync(handle);
5605 inode->i_mtime = inode->i_ctime = current_time(inode);
5606 ext4_mark_inode_dirty(handle, inode);
5607 ext4_update_inode_fsync_trans(handle, inode, 1);
5609 out_stop:
5610 ext4_journal_stop(handle);
5611 out_mmap:
5612 up_write(&EXT4_I(inode)->i_mmap_sem);
5613 ext4_inode_resume_unlocked_dio(inode);
5614 out_mutex:
5615 inode_unlock(inode);
5616 return ret;
5620 * ext4_insert_range:
5621 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5622 * The data blocks starting from @offset to the EOF are shifted by @len
5623 * towards right to create a hole in the @inode. Inode size is increased
5624 * by len bytes.
5625 * Returns 0 on success, error otherwise.
5627 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5629 struct super_block *sb = inode->i_sb;
5630 handle_t *handle;
5631 struct ext4_ext_path *path;
5632 struct ext4_extent *extent;
5633 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5634 unsigned int credits, ee_len;
5635 int ret = 0, depth, split_flag = 0;
5636 loff_t ioffset;
5639 * We need to test this early because xfstests assumes that an
5640 * insert range of (0, 1) will return EOPNOTSUPP if the file
5641 * system does not support insert range.
5643 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5644 return -EOPNOTSUPP;
5646 /* Insert range works only on fs block size aligned offsets. */
5647 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5648 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5649 return -EINVAL;
5651 if (!S_ISREG(inode->i_mode))
5652 return -EOPNOTSUPP;
5654 trace_ext4_insert_range(inode, offset, len);
5656 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5657 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5659 /* Call ext4_force_commit to flush all data in case of data=journal */
5660 if (ext4_should_journal_data(inode)) {
5661 ret = ext4_force_commit(inode->i_sb);
5662 if (ret)
5663 return ret;
5666 inode_lock(inode);
5667 /* Currently just for extent based files */
5668 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5669 ret = -EOPNOTSUPP;
5670 goto out_mutex;
5673 /* Check for wrap through zero */
5674 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5675 ret = -EFBIG;
5676 goto out_mutex;
5679 /* Offset should be less than i_size */
5680 if (offset >= i_size_read(inode)) {
5681 ret = -EINVAL;
5682 goto out_mutex;
5685 /* Wait for existing dio to complete */
5686 ext4_inode_block_unlocked_dio(inode);
5687 inode_dio_wait(inode);
5690 * Prevent page faults from reinstantiating pages we have released from
5691 * page cache.
5693 down_write(&EXT4_I(inode)->i_mmap_sem);
5695 * Need to round down to align start offset to page size boundary
5696 * for page size > block size.
5698 ioffset = round_down(offset, PAGE_SIZE);
5699 /* Write out all dirty pages */
5700 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5701 LLONG_MAX);
5702 if (ret)
5703 goto out_mmap;
5704 truncate_pagecache(inode, ioffset);
5706 credits = ext4_writepage_trans_blocks(inode);
5707 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5708 if (IS_ERR(handle)) {
5709 ret = PTR_ERR(handle);
5710 goto out_mmap;
5713 /* Expand file to avoid data loss if there is error while shifting */
5714 inode->i_size += len;
5715 EXT4_I(inode)->i_disksize += len;
5716 inode->i_mtime = inode->i_ctime = current_time(inode);
5717 ret = ext4_mark_inode_dirty(handle, inode);
5718 if (ret)
5719 goto out_stop;
5721 down_write(&EXT4_I(inode)->i_data_sem);
5722 ext4_discard_preallocations(inode);
5724 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5725 if (IS_ERR(path)) {
5726 up_write(&EXT4_I(inode)->i_data_sem);
5727 goto out_stop;
5730 depth = ext_depth(inode);
5731 extent = path[depth].p_ext;
5732 if (extent) {
5733 ee_start_lblk = le32_to_cpu(extent->ee_block);
5734 ee_len = ext4_ext_get_actual_len(extent);
5737 * If offset_lblk is not the starting block of extent, split
5738 * the extent @offset_lblk
5740 if ((offset_lblk > ee_start_lblk) &&
5741 (offset_lblk < (ee_start_lblk + ee_len))) {
5742 if (ext4_ext_is_unwritten(extent))
5743 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5744 EXT4_EXT_MARK_UNWRIT2;
5745 ret = ext4_split_extent_at(handle, inode, &path,
5746 offset_lblk, split_flag,
5747 EXT4_EX_NOCACHE |
5748 EXT4_GET_BLOCKS_PRE_IO |
5749 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5752 ext4_ext_drop_refs(path);
5753 kfree(path);
5754 if (ret < 0) {
5755 up_write(&EXT4_I(inode)->i_data_sem);
5756 goto out_stop;
5758 } else {
5759 ext4_ext_drop_refs(path);
5760 kfree(path);
5763 ret = ext4_es_remove_extent(inode, offset_lblk,
5764 EXT_MAX_BLOCKS - offset_lblk);
5765 if (ret) {
5766 up_write(&EXT4_I(inode)->i_data_sem);
5767 goto out_stop;
5771 * if offset_lblk lies in a hole which is at start of file, use
5772 * ee_start_lblk to shift extents
5774 ret = ext4_ext_shift_extents(inode, handle,
5775 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5776 len_lblk, SHIFT_RIGHT);
5778 up_write(&EXT4_I(inode)->i_data_sem);
5779 if (IS_SYNC(inode))
5780 ext4_handle_sync(handle);
5781 if (ret >= 0)
5782 ext4_update_inode_fsync_trans(handle, inode, 1);
5784 out_stop:
5785 ext4_journal_stop(handle);
5786 out_mmap:
5787 up_write(&EXT4_I(inode)->i_mmap_sem);
5788 ext4_inode_resume_unlocked_dio(inode);
5789 out_mutex:
5790 inode_unlock(inode);
5791 return ret;
5795 * ext4_swap_extents - Swap extents between two inodes
5797 * @inode1: First inode
5798 * @inode2: Second inode
5799 * @lblk1: Start block for first inode
5800 * @lblk2: Start block for second inode
5801 * @count: Number of blocks to swap
5802 * @mark_unwritten: Mark second inode's extents as unwritten after swap
5803 * @erp: Pointer to save error value
5805 * This helper routine does exactly what is promise "swap extents". All other
5806 * stuff such as page-cache locking consistency, bh mapping consistency or
5807 * extent's data copying must be performed by caller.
5808 * Locking:
5809 * i_mutex is held for both inodes
5810 * i_data_sem is locked for write for both inodes
5811 * Assumptions:
5812 * All pages from requested range are locked for both inodes
5815 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5816 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5817 ext4_lblk_t count, int unwritten, int *erp)
5819 struct ext4_ext_path *path1 = NULL;
5820 struct ext4_ext_path *path2 = NULL;
5821 int replaced_count = 0;
5823 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5824 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5825 BUG_ON(!inode_is_locked(inode1));
5826 BUG_ON(!inode_is_locked(inode2));
5828 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5829 if (unlikely(*erp))
5830 return 0;
5831 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5832 if (unlikely(*erp))
5833 return 0;
5835 while (count) {
5836 struct ext4_extent *ex1, *ex2, tmp_ex;
5837 ext4_lblk_t e1_blk, e2_blk;
5838 int e1_len, e2_len, len;
5839 int split = 0;
5841 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5842 if (IS_ERR(path1)) {
5843 *erp = PTR_ERR(path1);
5844 path1 = NULL;
5845 finish:
5846 count = 0;
5847 goto repeat;
5849 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5850 if (IS_ERR(path2)) {
5851 *erp = PTR_ERR(path2);
5852 path2 = NULL;
5853 goto finish;
5855 ex1 = path1[path1->p_depth].p_ext;
5856 ex2 = path2[path2->p_depth].p_ext;
5857 /* Do we have somthing to swap ? */
5858 if (unlikely(!ex2 || !ex1))
5859 goto finish;
5861 e1_blk = le32_to_cpu(ex1->ee_block);
5862 e2_blk = le32_to_cpu(ex2->ee_block);
5863 e1_len = ext4_ext_get_actual_len(ex1);
5864 e2_len = ext4_ext_get_actual_len(ex2);
5866 /* Hole handling */
5867 if (!in_range(lblk1, e1_blk, e1_len) ||
5868 !in_range(lblk2, e2_blk, e2_len)) {
5869 ext4_lblk_t next1, next2;
5871 /* if hole after extent, then go to next extent */
5872 next1 = ext4_ext_next_allocated_block(path1);
5873 next2 = ext4_ext_next_allocated_block(path2);
5874 /* If hole before extent, then shift to that extent */
5875 if (e1_blk > lblk1)
5876 next1 = e1_blk;
5877 if (e2_blk > lblk2)
5878 next2 = e2_blk;
5879 /* Do we have something to swap */
5880 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5881 goto finish;
5882 /* Move to the rightest boundary */
5883 len = next1 - lblk1;
5884 if (len < next2 - lblk2)
5885 len = next2 - lblk2;
5886 if (len > count)
5887 len = count;
5888 lblk1 += len;
5889 lblk2 += len;
5890 count -= len;
5891 goto repeat;
5894 /* Prepare left boundary */
5895 if (e1_blk < lblk1) {
5896 split = 1;
5897 *erp = ext4_force_split_extent_at(handle, inode1,
5898 &path1, lblk1, 0);
5899 if (unlikely(*erp))
5900 goto finish;
5902 if (e2_blk < lblk2) {
5903 split = 1;
5904 *erp = ext4_force_split_extent_at(handle, inode2,
5905 &path2, lblk2, 0);
5906 if (unlikely(*erp))
5907 goto finish;
5909 /* ext4_split_extent_at() may result in leaf extent split,
5910 * path must to be revalidated. */
5911 if (split)
5912 goto repeat;
5914 /* Prepare right boundary */
5915 len = count;
5916 if (len > e1_blk + e1_len - lblk1)
5917 len = e1_blk + e1_len - lblk1;
5918 if (len > e2_blk + e2_len - lblk2)
5919 len = e2_blk + e2_len - lblk2;
5921 if (len != e1_len) {
5922 split = 1;
5923 *erp = ext4_force_split_extent_at(handle, inode1,
5924 &path1, lblk1 + len, 0);
5925 if (unlikely(*erp))
5926 goto finish;
5928 if (len != e2_len) {
5929 split = 1;
5930 *erp = ext4_force_split_extent_at(handle, inode2,
5931 &path2, lblk2 + len, 0);
5932 if (*erp)
5933 goto finish;
5935 /* ext4_split_extent_at() may result in leaf extent split,
5936 * path must to be revalidated. */
5937 if (split)
5938 goto repeat;
5940 BUG_ON(e2_len != e1_len);
5941 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5942 if (unlikely(*erp))
5943 goto finish;
5944 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5945 if (unlikely(*erp))
5946 goto finish;
5948 /* Both extents are fully inside boundaries. Swap it now */
5949 tmp_ex = *ex1;
5950 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5951 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5952 ex1->ee_len = cpu_to_le16(e2_len);
5953 ex2->ee_len = cpu_to_le16(e1_len);
5954 if (unwritten)
5955 ext4_ext_mark_unwritten(ex2);
5956 if (ext4_ext_is_unwritten(&tmp_ex))
5957 ext4_ext_mark_unwritten(ex1);
5959 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5960 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5961 *erp = ext4_ext_dirty(handle, inode2, path2 +
5962 path2->p_depth);
5963 if (unlikely(*erp))
5964 goto finish;
5965 *erp = ext4_ext_dirty(handle, inode1, path1 +
5966 path1->p_depth);
5968 * Looks scarry ah..? second inode already points to new blocks,
5969 * and it was successfully dirtied. But luckily error may happen
5970 * only due to journal error, so full transaction will be
5971 * aborted anyway.
5973 if (unlikely(*erp))
5974 goto finish;
5975 lblk1 += len;
5976 lblk2 += len;
5977 replaced_count += len;
5978 count -= len;
5980 repeat:
5981 ext4_ext_drop_refs(path1);
5982 kfree(path1);
5983 ext4_ext_drop_refs(path2);
5984 kfree(path2);
5985 path1 = path2 = NULL;
5987 return replaced_count;