ocfs2: fix locking for res->tracking and dlm->tracking_list
[linux/fpc-iii.git] / fs / ext4 / extents.c
blob1708597659a14e2acefd995209426dc7f1a34398
1 /*
2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
5 * Architecture independence:
6 * Copyright (c) 2005, Bull S.A.
7 * Written by Pierre Peiffer <pierre.peiffer@bull.net>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public Licens
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
24 * Extents support for EXT4
26 * TODO:
27 * - ext4*_error() should be used in some situations
28 * - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29 * - smart tree reduction
32 #include <linux/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 <asm/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;
125 err = ext4_journal_extend(handle, needed);
126 if (err <= 0)
127 return err;
128 err = ext4_truncate_restart_trans(handle, inode, needed);
129 if (err == 0)
130 err = -EAGAIN;
132 return err;
136 * could return:
137 * - EROFS
138 * - ENOMEM
140 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
141 struct ext4_ext_path *path)
143 if (path->p_bh) {
144 /* path points to block */
145 BUFFER_TRACE(path->p_bh, "get_write_access");
146 return ext4_journal_get_write_access(handle, path->p_bh);
148 /* path points to leaf/index in inode body */
149 /* we use in-core data, no need to protect them */
150 return 0;
154 * could return:
155 * - EROFS
156 * - ENOMEM
157 * - EIO
159 int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
160 struct inode *inode, struct ext4_ext_path *path)
162 int err;
164 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
165 if (path->p_bh) {
166 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
167 /* path points to block */
168 err = __ext4_handle_dirty_metadata(where, line, handle,
169 inode, path->p_bh);
170 } else {
171 /* path points to leaf/index in inode body */
172 err = ext4_mark_inode_dirty(handle, inode);
174 return err;
177 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
178 struct ext4_ext_path *path,
179 ext4_lblk_t block)
181 if (path) {
182 int depth = path->p_depth;
183 struct ext4_extent *ex;
186 * Try to predict block placement assuming that we are
187 * filling in a file which will eventually be
188 * non-sparse --- i.e., in the case of libbfd writing
189 * an ELF object sections out-of-order but in a way
190 * the eventually results in a contiguous object or
191 * executable file, or some database extending a table
192 * space file. However, this is actually somewhat
193 * non-ideal if we are writing a sparse file such as
194 * qemu or KVM writing a raw image file that is going
195 * to stay fairly sparse, since it will end up
196 * fragmenting the file system's free space. Maybe we
197 * should have some hueristics or some way to allow
198 * userspace to pass a hint to file system,
199 * especially if the latter case turns out to be
200 * common.
202 ex = path[depth].p_ext;
203 if (ex) {
204 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
205 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
207 if (block > ext_block)
208 return ext_pblk + (block - ext_block);
209 else
210 return ext_pblk - (ext_block - block);
213 /* it looks like index is empty;
214 * try to find starting block from index itself */
215 if (path[depth].p_bh)
216 return path[depth].p_bh->b_blocknr;
219 /* OK. use inode's group */
220 return ext4_inode_to_goal_block(inode);
224 * Allocation for a meta data block
226 static ext4_fsblk_t
227 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
228 struct ext4_ext_path *path,
229 struct ext4_extent *ex, int *err, unsigned int flags)
231 ext4_fsblk_t goal, newblock;
233 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
234 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
235 NULL, err);
236 return newblock;
239 static inline int ext4_ext_space_block(struct inode *inode, int check)
241 int size;
243 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
244 / sizeof(struct ext4_extent);
245 #ifdef AGGRESSIVE_TEST
246 if (!check && size > 6)
247 size = 6;
248 #endif
249 return size;
252 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
254 int size;
256 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
257 / sizeof(struct ext4_extent_idx);
258 #ifdef AGGRESSIVE_TEST
259 if (!check && size > 5)
260 size = 5;
261 #endif
262 return size;
265 static inline int ext4_ext_space_root(struct inode *inode, int check)
267 int size;
269 size = sizeof(EXT4_I(inode)->i_data);
270 size -= sizeof(struct ext4_extent_header);
271 size /= sizeof(struct ext4_extent);
272 #ifdef AGGRESSIVE_TEST
273 if (!check && size > 3)
274 size = 3;
275 #endif
276 return size;
279 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
281 int size;
283 size = sizeof(EXT4_I(inode)->i_data);
284 size -= sizeof(struct ext4_extent_header);
285 size /= sizeof(struct ext4_extent_idx);
286 #ifdef AGGRESSIVE_TEST
287 if (!check && size > 4)
288 size = 4;
289 #endif
290 return size;
293 static inline int
294 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
295 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
296 int nofail)
298 struct ext4_ext_path *path = *ppath;
299 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
301 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
302 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
303 EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
304 (nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
308 * Calculate the number of metadata blocks needed
309 * to allocate @blocks
310 * Worse case is one block per extent
312 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
314 struct ext4_inode_info *ei = EXT4_I(inode);
315 int idxs;
317 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
318 / sizeof(struct ext4_extent_idx));
321 * If the new delayed allocation block is contiguous with the
322 * previous da block, it can share index blocks with the
323 * previous block, so we only need to allocate a new index
324 * block every idxs leaf blocks. At ldxs**2 blocks, we need
325 * an additional index block, and at ldxs**3 blocks, yet
326 * another index blocks.
328 if (ei->i_da_metadata_calc_len &&
329 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
330 int num = 0;
332 if ((ei->i_da_metadata_calc_len % idxs) == 0)
333 num++;
334 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
335 num++;
336 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
337 num++;
338 ei->i_da_metadata_calc_len = 0;
339 } else
340 ei->i_da_metadata_calc_len++;
341 ei->i_da_metadata_calc_last_lblock++;
342 return num;
346 * In the worst case we need a new set of index blocks at
347 * every level of the inode's extent tree.
349 ei->i_da_metadata_calc_len = 1;
350 ei->i_da_metadata_calc_last_lblock = lblock;
351 return ext_depth(inode) + 1;
354 static int
355 ext4_ext_max_entries(struct inode *inode, int depth)
357 int max;
359 if (depth == ext_depth(inode)) {
360 if (depth == 0)
361 max = ext4_ext_space_root(inode, 1);
362 else
363 max = ext4_ext_space_root_idx(inode, 1);
364 } else {
365 if (depth == 0)
366 max = ext4_ext_space_block(inode, 1);
367 else
368 max = ext4_ext_space_block_idx(inode, 1);
371 return max;
374 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
376 ext4_fsblk_t block = ext4_ext_pblock(ext);
377 int len = ext4_ext_get_actual_len(ext);
378 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
381 * We allow neither:
382 * - zero length
383 * - overflow/wrap-around
385 if (lblock + len <= lblock)
386 return 0;
387 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
390 static int ext4_valid_extent_idx(struct inode *inode,
391 struct ext4_extent_idx *ext_idx)
393 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
395 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
398 static int ext4_valid_extent_entries(struct inode *inode,
399 struct ext4_extent_header *eh,
400 int depth)
402 unsigned short entries;
403 if (eh->eh_entries == 0)
404 return 1;
406 entries = le16_to_cpu(eh->eh_entries);
408 if (depth == 0) {
409 /* leaf entries */
410 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
411 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
412 ext4_fsblk_t pblock = 0;
413 ext4_lblk_t lblock = 0;
414 ext4_lblk_t prev = 0;
415 int len = 0;
416 while (entries) {
417 if (!ext4_valid_extent(inode, ext))
418 return 0;
420 /* Check for overlapping extents */
421 lblock = le32_to_cpu(ext->ee_block);
422 len = ext4_ext_get_actual_len(ext);
423 if ((lblock <= prev) && prev) {
424 pblock = ext4_ext_pblock(ext);
425 es->s_last_error_block = cpu_to_le64(pblock);
426 return 0;
428 ext++;
429 entries--;
430 prev = lblock + len - 1;
432 } else {
433 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
434 while (entries) {
435 if (!ext4_valid_extent_idx(inode, ext_idx))
436 return 0;
437 ext_idx++;
438 entries--;
441 return 1;
444 static int __ext4_ext_check(const char *function, unsigned int line,
445 struct inode *inode, struct ext4_extent_header *eh,
446 int depth, ext4_fsblk_t pblk)
448 const char *error_msg;
449 int max = 0, err = -EFSCORRUPTED;
451 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
452 error_msg = "invalid magic";
453 goto corrupted;
455 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
456 error_msg = "unexpected eh_depth";
457 goto corrupted;
459 if (unlikely(eh->eh_max == 0)) {
460 error_msg = "invalid eh_max";
461 goto corrupted;
463 max = ext4_ext_max_entries(inode, depth);
464 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
465 error_msg = "too large eh_max";
466 goto corrupted;
468 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
469 error_msg = "invalid eh_entries";
470 goto corrupted;
472 if (!ext4_valid_extent_entries(inode, eh, depth)) {
473 error_msg = "invalid extent entries";
474 goto corrupted;
476 if (unlikely(depth > 32)) {
477 error_msg = "too large eh_depth";
478 goto corrupted;
480 /* Verify checksum on non-root extent tree nodes */
481 if (ext_depth(inode) != depth &&
482 !ext4_extent_block_csum_verify(inode, eh)) {
483 error_msg = "extent tree corrupted";
484 err = -EFSBADCRC;
485 goto corrupted;
487 return 0;
489 corrupted:
490 ext4_error_inode(inode, function, line, 0,
491 "pblk %llu bad header/extent: %s - magic %x, "
492 "entries %u, max %u(%u), depth %u(%u)",
493 (unsigned long long) pblk, error_msg,
494 le16_to_cpu(eh->eh_magic),
495 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
496 max, le16_to_cpu(eh->eh_depth), depth);
497 return err;
500 #define ext4_ext_check(inode, eh, depth, pblk) \
501 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
503 int ext4_ext_check_inode(struct inode *inode)
505 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
508 static struct buffer_head *
509 __read_extent_tree_block(const char *function, unsigned int line,
510 struct inode *inode, ext4_fsblk_t pblk, int depth,
511 int flags)
513 struct buffer_head *bh;
514 int err;
516 bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
517 if (unlikely(!bh))
518 return ERR_PTR(-ENOMEM);
520 if (!bh_uptodate_or_lock(bh)) {
521 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
522 err = bh_submit_read(bh);
523 if (err < 0)
524 goto errout;
526 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
527 return bh;
528 err = __ext4_ext_check(function, line, inode,
529 ext_block_hdr(bh), depth, pblk);
530 if (err)
531 goto errout;
532 set_buffer_verified(bh);
534 * If this is a leaf block, cache all of its entries
536 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
537 struct ext4_extent_header *eh = ext_block_hdr(bh);
538 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
539 ext4_lblk_t prev = 0;
540 int i;
542 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
543 unsigned int status = EXTENT_STATUS_WRITTEN;
544 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
545 int len = ext4_ext_get_actual_len(ex);
547 if (prev && (prev != lblk))
548 ext4_es_cache_extent(inode, prev,
549 lblk - prev, ~0,
550 EXTENT_STATUS_HOLE);
552 if (ext4_ext_is_unwritten(ex))
553 status = EXTENT_STATUS_UNWRITTEN;
554 ext4_es_cache_extent(inode, lblk, len,
555 ext4_ext_pblock(ex), status);
556 prev = lblk + len;
559 return bh;
560 errout:
561 put_bh(bh);
562 return ERR_PTR(err);
566 #define read_extent_tree_block(inode, pblk, depth, flags) \
567 __read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
568 (depth), (flags))
571 * This function is called to cache a file's extent information in the
572 * extent status tree
574 int ext4_ext_precache(struct inode *inode)
576 struct ext4_inode_info *ei = EXT4_I(inode);
577 struct ext4_ext_path *path = NULL;
578 struct buffer_head *bh;
579 int i = 0, depth, ret = 0;
581 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
582 return 0; /* not an extent-mapped inode */
584 down_read(&ei->i_data_sem);
585 depth = ext_depth(inode);
587 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
588 GFP_NOFS);
589 if (path == NULL) {
590 up_read(&ei->i_data_sem);
591 return -ENOMEM;
594 /* Don't cache anything if there are no external extent blocks */
595 if (depth == 0)
596 goto out;
597 path[0].p_hdr = ext_inode_hdr(inode);
598 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
599 if (ret)
600 goto out;
601 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
602 while (i >= 0) {
604 * If this is a leaf block or we've reached the end of
605 * the index block, go up
607 if ((i == depth) ||
608 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
609 brelse(path[i].p_bh);
610 path[i].p_bh = NULL;
611 i--;
612 continue;
614 bh = read_extent_tree_block(inode,
615 ext4_idx_pblock(path[i].p_idx++),
616 depth - i - 1,
617 EXT4_EX_FORCE_CACHE);
618 if (IS_ERR(bh)) {
619 ret = PTR_ERR(bh);
620 break;
622 i++;
623 path[i].p_bh = bh;
624 path[i].p_hdr = ext_block_hdr(bh);
625 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
627 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
628 out:
629 up_read(&ei->i_data_sem);
630 ext4_ext_drop_refs(path);
631 kfree(path);
632 return ret;
635 #ifdef EXT_DEBUG
636 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
638 int k, l = path->p_depth;
640 ext_debug("path:");
641 for (k = 0; k <= l; k++, path++) {
642 if (path->p_idx) {
643 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
644 ext4_idx_pblock(path->p_idx));
645 } else if (path->p_ext) {
646 ext_debug(" %d:[%d]%d:%llu ",
647 le32_to_cpu(path->p_ext->ee_block),
648 ext4_ext_is_unwritten(path->p_ext),
649 ext4_ext_get_actual_len(path->p_ext),
650 ext4_ext_pblock(path->p_ext));
651 } else
652 ext_debug(" []");
654 ext_debug("\n");
657 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
659 int depth = ext_depth(inode);
660 struct ext4_extent_header *eh;
661 struct ext4_extent *ex;
662 int i;
664 if (!path)
665 return;
667 eh = path[depth].p_hdr;
668 ex = EXT_FIRST_EXTENT(eh);
670 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
672 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
673 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
674 ext4_ext_is_unwritten(ex),
675 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
677 ext_debug("\n");
680 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
681 ext4_fsblk_t newblock, int level)
683 int depth = ext_depth(inode);
684 struct ext4_extent *ex;
686 if (depth != level) {
687 struct ext4_extent_idx *idx;
688 idx = path[level].p_idx;
689 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
690 ext_debug("%d: move %d:%llu in new index %llu\n", level,
691 le32_to_cpu(idx->ei_block),
692 ext4_idx_pblock(idx),
693 newblock);
694 idx++;
697 return;
700 ex = path[depth].p_ext;
701 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
702 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
703 le32_to_cpu(ex->ee_block),
704 ext4_ext_pblock(ex),
705 ext4_ext_is_unwritten(ex),
706 ext4_ext_get_actual_len(ex),
707 newblock);
708 ex++;
712 #else
713 #define ext4_ext_show_path(inode, path)
714 #define ext4_ext_show_leaf(inode, path)
715 #define ext4_ext_show_move(inode, path, newblock, level)
716 #endif
718 void ext4_ext_drop_refs(struct ext4_ext_path *path)
720 int depth, i;
722 if (!path)
723 return;
724 depth = path->p_depth;
725 for (i = 0; i <= depth; i++, path++)
726 if (path->p_bh) {
727 brelse(path->p_bh);
728 path->p_bh = NULL;
733 * ext4_ext_binsearch_idx:
734 * binary search for the closest index of the given block
735 * the header must be checked before calling this
737 static void
738 ext4_ext_binsearch_idx(struct inode *inode,
739 struct ext4_ext_path *path, ext4_lblk_t block)
741 struct ext4_extent_header *eh = path->p_hdr;
742 struct ext4_extent_idx *r, *l, *m;
745 ext_debug("binsearch for %u(idx): ", block);
747 l = EXT_FIRST_INDEX(eh) + 1;
748 r = EXT_LAST_INDEX(eh);
749 while (l <= r) {
750 m = l + (r - l) / 2;
751 if (block < le32_to_cpu(m->ei_block))
752 r = m - 1;
753 else
754 l = m + 1;
755 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
756 m, le32_to_cpu(m->ei_block),
757 r, le32_to_cpu(r->ei_block));
760 path->p_idx = l - 1;
761 ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
762 ext4_idx_pblock(path->p_idx));
764 #ifdef CHECK_BINSEARCH
766 struct ext4_extent_idx *chix, *ix;
767 int k;
769 chix = ix = EXT_FIRST_INDEX(eh);
770 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
771 if (k != 0 &&
772 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
773 printk(KERN_DEBUG "k=%d, ix=0x%p, "
774 "first=0x%p\n", k,
775 ix, EXT_FIRST_INDEX(eh));
776 printk(KERN_DEBUG "%u <= %u\n",
777 le32_to_cpu(ix->ei_block),
778 le32_to_cpu(ix[-1].ei_block));
780 BUG_ON(k && le32_to_cpu(ix->ei_block)
781 <= le32_to_cpu(ix[-1].ei_block));
782 if (block < le32_to_cpu(ix->ei_block))
783 break;
784 chix = ix;
786 BUG_ON(chix != path->p_idx);
788 #endif
793 * ext4_ext_binsearch:
794 * binary search for closest extent of the given block
795 * the header must be checked before calling this
797 static void
798 ext4_ext_binsearch(struct inode *inode,
799 struct ext4_ext_path *path, ext4_lblk_t block)
801 struct ext4_extent_header *eh = path->p_hdr;
802 struct ext4_extent *r, *l, *m;
804 if (eh->eh_entries == 0) {
806 * this leaf is empty:
807 * we get such a leaf in split/add case
809 return;
812 ext_debug("binsearch for %u: ", block);
814 l = EXT_FIRST_EXTENT(eh) + 1;
815 r = EXT_LAST_EXTENT(eh);
817 while (l <= r) {
818 m = l + (r - l) / 2;
819 if (block < le32_to_cpu(m->ee_block))
820 r = m - 1;
821 else
822 l = m + 1;
823 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
824 m, le32_to_cpu(m->ee_block),
825 r, le32_to_cpu(r->ee_block));
828 path->p_ext = l - 1;
829 ext_debug(" -> %d:%llu:[%d]%d ",
830 le32_to_cpu(path->p_ext->ee_block),
831 ext4_ext_pblock(path->p_ext),
832 ext4_ext_is_unwritten(path->p_ext),
833 ext4_ext_get_actual_len(path->p_ext));
835 #ifdef CHECK_BINSEARCH
837 struct ext4_extent *chex, *ex;
838 int k;
840 chex = ex = EXT_FIRST_EXTENT(eh);
841 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
842 BUG_ON(k && le32_to_cpu(ex->ee_block)
843 <= le32_to_cpu(ex[-1].ee_block));
844 if (block < le32_to_cpu(ex->ee_block))
845 break;
846 chex = ex;
848 BUG_ON(chex != path->p_ext);
850 #endif
854 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
856 struct ext4_extent_header *eh;
858 eh = ext_inode_hdr(inode);
859 eh->eh_depth = 0;
860 eh->eh_entries = 0;
861 eh->eh_magic = EXT4_EXT_MAGIC;
862 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
863 ext4_mark_inode_dirty(handle, inode);
864 return 0;
867 struct ext4_ext_path *
868 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
869 struct ext4_ext_path **orig_path, int flags)
871 struct ext4_extent_header *eh;
872 struct buffer_head *bh;
873 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
874 short int depth, i, ppos = 0;
875 int ret;
877 eh = ext_inode_hdr(inode);
878 depth = ext_depth(inode);
879 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
880 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
881 depth);
882 ret = -EFSCORRUPTED;
883 goto err;
886 if (path) {
887 ext4_ext_drop_refs(path);
888 if (depth > path[0].p_maxdepth) {
889 kfree(path);
890 *orig_path = path = NULL;
893 if (!path) {
894 /* account possible depth increase */
895 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
896 GFP_NOFS);
897 if (unlikely(!path))
898 return ERR_PTR(-ENOMEM);
899 path[0].p_maxdepth = depth + 1;
901 path[0].p_hdr = eh;
902 path[0].p_bh = NULL;
904 i = depth;
905 /* walk through the tree */
906 while (i) {
907 ext_debug("depth %d: num %d, max %d\n",
908 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
910 ext4_ext_binsearch_idx(inode, path + ppos, block);
911 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
912 path[ppos].p_depth = i;
913 path[ppos].p_ext = NULL;
915 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
916 flags);
917 if (IS_ERR(bh)) {
918 ret = PTR_ERR(bh);
919 goto err;
922 eh = ext_block_hdr(bh);
923 ppos++;
924 if (unlikely(ppos > depth)) {
925 put_bh(bh);
926 EXT4_ERROR_INODE(inode,
927 "ppos %d > depth %d", ppos, depth);
928 ret = -EFSCORRUPTED;
929 goto err;
931 path[ppos].p_bh = bh;
932 path[ppos].p_hdr = eh;
935 path[ppos].p_depth = i;
936 path[ppos].p_ext = NULL;
937 path[ppos].p_idx = NULL;
939 /* find extent */
940 ext4_ext_binsearch(inode, path + ppos, block);
941 /* if not an empty leaf */
942 if (path[ppos].p_ext)
943 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
945 ext4_ext_show_path(inode, path);
947 return path;
949 err:
950 ext4_ext_drop_refs(path);
951 kfree(path);
952 if (orig_path)
953 *orig_path = NULL;
954 return ERR_PTR(ret);
958 * ext4_ext_insert_index:
959 * insert new index [@logical;@ptr] into the block at @curp;
960 * check where to insert: before @curp or after @curp
962 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
963 struct ext4_ext_path *curp,
964 int logical, ext4_fsblk_t ptr)
966 struct ext4_extent_idx *ix;
967 int len, err;
969 err = ext4_ext_get_access(handle, inode, curp);
970 if (err)
971 return err;
973 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
974 EXT4_ERROR_INODE(inode,
975 "logical %d == ei_block %d!",
976 logical, le32_to_cpu(curp->p_idx->ei_block));
977 return -EFSCORRUPTED;
980 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
981 >= le16_to_cpu(curp->p_hdr->eh_max))) {
982 EXT4_ERROR_INODE(inode,
983 "eh_entries %d >= eh_max %d!",
984 le16_to_cpu(curp->p_hdr->eh_entries),
985 le16_to_cpu(curp->p_hdr->eh_max));
986 return -EFSCORRUPTED;
989 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
990 /* insert after */
991 ext_debug("insert new index %d after: %llu\n", logical, ptr);
992 ix = curp->p_idx + 1;
993 } else {
994 /* insert before */
995 ext_debug("insert new index %d before: %llu\n", logical, ptr);
996 ix = curp->p_idx;
999 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1000 BUG_ON(len < 0);
1001 if (len > 0) {
1002 ext_debug("insert new index %d: "
1003 "move %d indices from 0x%p to 0x%p\n",
1004 logical, len, ix, ix + 1);
1005 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1008 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1009 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1010 return -EFSCORRUPTED;
1013 ix->ei_block = cpu_to_le32(logical);
1014 ext4_idx_store_pblock(ix, ptr);
1015 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1017 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1018 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1019 return -EFSCORRUPTED;
1022 err = ext4_ext_dirty(handle, inode, curp);
1023 ext4_std_error(inode->i_sb, err);
1025 return err;
1029 * ext4_ext_split:
1030 * inserts new subtree into the path, using free index entry
1031 * at depth @at:
1032 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1033 * - makes decision where to split
1034 * - moves remaining extents and index entries (right to the split point)
1035 * into the newly allocated blocks
1036 * - initializes subtree
1038 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1039 unsigned int flags,
1040 struct ext4_ext_path *path,
1041 struct ext4_extent *newext, int at)
1043 struct buffer_head *bh = NULL;
1044 int depth = ext_depth(inode);
1045 struct ext4_extent_header *neh;
1046 struct ext4_extent_idx *fidx;
1047 int i = at, k, m, a;
1048 ext4_fsblk_t newblock, oldblock;
1049 __le32 border;
1050 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1051 int err = 0;
1053 /* make decision: where to split? */
1054 /* FIXME: now decision is simplest: at current extent */
1056 /* if current leaf will be split, then we should use
1057 * border from split point */
1058 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1059 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1060 return -EFSCORRUPTED;
1062 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1063 border = path[depth].p_ext[1].ee_block;
1064 ext_debug("leaf will be split."
1065 " next leaf starts at %d\n",
1066 le32_to_cpu(border));
1067 } else {
1068 border = newext->ee_block;
1069 ext_debug("leaf will be added."
1070 " next leaf starts at %d\n",
1071 le32_to_cpu(border));
1075 * If error occurs, then we break processing
1076 * and mark filesystem read-only. index won't
1077 * be inserted and tree will be in consistent
1078 * state. Next mount will repair buffers too.
1082 * Get array to track all allocated blocks.
1083 * We need this to handle errors and free blocks
1084 * upon them.
1086 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
1087 if (!ablocks)
1088 return -ENOMEM;
1090 /* allocate all needed blocks */
1091 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1092 for (a = 0; a < depth - at; a++) {
1093 newblock = ext4_ext_new_meta_block(handle, inode, path,
1094 newext, &err, flags);
1095 if (newblock == 0)
1096 goto cleanup;
1097 ablocks[a] = newblock;
1100 /* initialize new leaf */
1101 newblock = ablocks[--a];
1102 if (unlikely(newblock == 0)) {
1103 EXT4_ERROR_INODE(inode, "newblock == 0!");
1104 err = -EFSCORRUPTED;
1105 goto cleanup;
1107 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1108 if (unlikely(!bh)) {
1109 err = -ENOMEM;
1110 goto cleanup;
1112 lock_buffer(bh);
1114 err = ext4_journal_get_create_access(handle, bh);
1115 if (err)
1116 goto cleanup;
1118 neh = ext_block_hdr(bh);
1119 neh->eh_entries = 0;
1120 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1121 neh->eh_magic = EXT4_EXT_MAGIC;
1122 neh->eh_depth = 0;
1124 /* move remainder of path[depth] to the new leaf */
1125 if (unlikely(path[depth].p_hdr->eh_entries !=
1126 path[depth].p_hdr->eh_max)) {
1127 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1128 path[depth].p_hdr->eh_entries,
1129 path[depth].p_hdr->eh_max);
1130 err = -EFSCORRUPTED;
1131 goto cleanup;
1133 /* start copy from next extent */
1134 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1135 ext4_ext_show_move(inode, path, newblock, depth);
1136 if (m) {
1137 struct ext4_extent *ex;
1138 ex = EXT_FIRST_EXTENT(neh);
1139 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1140 le16_add_cpu(&neh->eh_entries, m);
1143 ext4_extent_block_csum_set(inode, neh);
1144 set_buffer_uptodate(bh);
1145 unlock_buffer(bh);
1147 err = ext4_handle_dirty_metadata(handle, inode, bh);
1148 if (err)
1149 goto cleanup;
1150 brelse(bh);
1151 bh = NULL;
1153 /* correct old leaf */
1154 if (m) {
1155 err = ext4_ext_get_access(handle, inode, path + depth);
1156 if (err)
1157 goto cleanup;
1158 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1159 err = ext4_ext_dirty(handle, inode, path + depth);
1160 if (err)
1161 goto cleanup;
1165 /* create intermediate indexes */
1166 k = depth - at - 1;
1167 if (unlikely(k < 0)) {
1168 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1169 err = -EFSCORRUPTED;
1170 goto cleanup;
1172 if (k)
1173 ext_debug("create %d intermediate indices\n", k);
1174 /* insert new index into current index block */
1175 /* current depth stored in i var */
1176 i = depth - 1;
1177 while (k--) {
1178 oldblock = newblock;
1179 newblock = ablocks[--a];
1180 bh = sb_getblk(inode->i_sb, newblock);
1181 if (unlikely(!bh)) {
1182 err = -ENOMEM;
1183 goto cleanup;
1185 lock_buffer(bh);
1187 err = ext4_journal_get_create_access(handle, bh);
1188 if (err)
1189 goto cleanup;
1191 neh = ext_block_hdr(bh);
1192 neh->eh_entries = cpu_to_le16(1);
1193 neh->eh_magic = EXT4_EXT_MAGIC;
1194 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1195 neh->eh_depth = cpu_to_le16(depth - i);
1196 fidx = EXT_FIRST_INDEX(neh);
1197 fidx->ei_block = border;
1198 ext4_idx_store_pblock(fidx, oldblock);
1200 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1201 i, newblock, le32_to_cpu(border), oldblock);
1203 /* move remainder of path[i] to the new index block */
1204 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1205 EXT_LAST_INDEX(path[i].p_hdr))) {
1206 EXT4_ERROR_INODE(inode,
1207 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1208 le32_to_cpu(path[i].p_ext->ee_block));
1209 err = -EFSCORRUPTED;
1210 goto cleanup;
1212 /* start copy indexes */
1213 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1214 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1215 EXT_MAX_INDEX(path[i].p_hdr));
1216 ext4_ext_show_move(inode, path, newblock, i);
1217 if (m) {
1218 memmove(++fidx, path[i].p_idx,
1219 sizeof(struct ext4_extent_idx) * m);
1220 le16_add_cpu(&neh->eh_entries, m);
1222 ext4_extent_block_csum_set(inode, neh);
1223 set_buffer_uptodate(bh);
1224 unlock_buffer(bh);
1226 err = ext4_handle_dirty_metadata(handle, inode, bh);
1227 if (err)
1228 goto cleanup;
1229 brelse(bh);
1230 bh = NULL;
1232 /* correct old index */
1233 if (m) {
1234 err = ext4_ext_get_access(handle, inode, path + i);
1235 if (err)
1236 goto cleanup;
1237 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1238 err = ext4_ext_dirty(handle, inode, path + i);
1239 if (err)
1240 goto cleanup;
1243 i--;
1246 /* insert new index */
1247 err = ext4_ext_insert_index(handle, inode, path + at,
1248 le32_to_cpu(border), newblock);
1250 cleanup:
1251 if (bh) {
1252 if (buffer_locked(bh))
1253 unlock_buffer(bh);
1254 brelse(bh);
1257 if (err) {
1258 /* free all allocated blocks in error case */
1259 for (i = 0; i < depth; i++) {
1260 if (!ablocks[i])
1261 continue;
1262 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1263 EXT4_FREE_BLOCKS_METADATA);
1266 kfree(ablocks);
1268 return err;
1272 * ext4_ext_grow_indepth:
1273 * implements tree growing procedure:
1274 * - allocates new block
1275 * - moves top-level data (index block or leaf) into the new block
1276 * - initializes new top-level, creating index that points to the
1277 * just created block
1279 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1280 unsigned int flags)
1282 struct ext4_extent_header *neh;
1283 struct buffer_head *bh;
1284 ext4_fsblk_t newblock, goal = 0;
1285 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1286 int err = 0;
1288 /* Try to prepend new index to old one */
1289 if (ext_depth(inode))
1290 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1291 if (goal > le32_to_cpu(es->s_first_data_block)) {
1292 flags |= EXT4_MB_HINT_TRY_GOAL;
1293 goal--;
1294 } else
1295 goal = ext4_inode_to_goal_block(inode);
1296 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1297 NULL, &err);
1298 if (newblock == 0)
1299 return err;
1301 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1302 if (unlikely(!bh))
1303 return -ENOMEM;
1304 lock_buffer(bh);
1306 err = ext4_journal_get_create_access(handle, bh);
1307 if (err) {
1308 unlock_buffer(bh);
1309 goto out;
1312 /* move top-level index/leaf into new block */
1313 memmove(bh->b_data, EXT4_I(inode)->i_data,
1314 sizeof(EXT4_I(inode)->i_data));
1316 /* set size of new block */
1317 neh = ext_block_hdr(bh);
1318 /* old root could have indexes or leaves
1319 * so calculate e_max right way */
1320 if (ext_depth(inode))
1321 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1322 else
1323 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1324 neh->eh_magic = EXT4_EXT_MAGIC;
1325 ext4_extent_block_csum_set(inode, neh);
1326 set_buffer_uptodate(bh);
1327 unlock_buffer(bh);
1329 err = ext4_handle_dirty_metadata(handle, inode, bh);
1330 if (err)
1331 goto out;
1333 /* Update top-level index: num,max,pointer */
1334 neh = ext_inode_hdr(inode);
1335 neh->eh_entries = cpu_to_le16(1);
1336 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1337 if (neh->eh_depth == 0) {
1338 /* Root extent block becomes index block */
1339 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1340 EXT_FIRST_INDEX(neh)->ei_block =
1341 EXT_FIRST_EXTENT(neh)->ee_block;
1343 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1344 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1345 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1346 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1348 le16_add_cpu(&neh->eh_depth, 1);
1349 ext4_mark_inode_dirty(handle, inode);
1350 out:
1351 brelse(bh);
1353 return err;
1357 * ext4_ext_create_new_leaf:
1358 * finds empty index and adds new leaf.
1359 * if no free index is found, then it requests in-depth growing.
1361 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1362 unsigned int mb_flags,
1363 unsigned int gb_flags,
1364 struct ext4_ext_path **ppath,
1365 struct ext4_extent *newext)
1367 struct ext4_ext_path *path = *ppath;
1368 struct ext4_ext_path *curp;
1369 int depth, i, err = 0;
1371 repeat:
1372 i = depth = ext_depth(inode);
1374 /* walk up to the tree and look for free index entry */
1375 curp = path + depth;
1376 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1377 i--;
1378 curp--;
1381 /* we use already allocated block for index block,
1382 * so subsequent data blocks should be contiguous */
1383 if (EXT_HAS_FREE_INDEX(curp)) {
1384 /* if we found index with free entry, then use that
1385 * entry: create all needed subtree and add new leaf */
1386 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1387 if (err)
1388 goto out;
1390 /* refill path */
1391 path = ext4_find_extent(inode,
1392 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1393 ppath, gb_flags);
1394 if (IS_ERR(path))
1395 err = PTR_ERR(path);
1396 } else {
1397 /* tree is full, time to grow in depth */
1398 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1399 if (err)
1400 goto out;
1402 /* refill path */
1403 path = ext4_find_extent(inode,
1404 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1405 ppath, gb_flags);
1406 if (IS_ERR(path)) {
1407 err = PTR_ERR(path);
1408 goto out;
1412 * only first (depth 0 -> 1) produces free space;
1413 * in all other cases we have to split the grown tree
1415 depth = ext_depth(inode);
1416 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1417 /* now we need to split */
1418 goto repeat;
1422 out:
1423 return err;
1427 * search the closest allocated block to the left for *logical
1428 * and returns it at @logical + it's physical address at @phys
1429 * if *logical is the smallest allocated block, the function
1430 * returns 0 at @phys
1431 * return value contains 0 (success) or error code
1433 static int ext4_ext_search_left(struct inode *inode,
1434 struct ext4_ext_path *path,
1435 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1437 struct ext4_extent_idx *ix;
1438 struct ext4_extent *ex;
1439 int depth, ee_len;
1441 if (unlikely(path == NULL)) {
1442 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1443 return -EFSCORRUPTED;
1445 depth = path->p_depth;
1446 *phys = 0;
1448 if (depth == 0 && path->p_ext == NULL)
1449 return 0;
1451 /* usually extent in the path covers blocks smaller
1452 * then *logical, but it can be that extent is the
1453 * first one in the file */
1455 ex = path[depth].p_ext;
1456 ee_len = ext4_ext_get_actual_len(ex);
1457 if (*logical < le32_to_cpu(ex->ee_block)) {
1458 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1459 EXT4_ERROR_INODE(inode,
1460 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1461 *logical, le32_to_cpu(ex->ee_block));
1462 return -EFSCORRUPTED;
1464 while (--depth >= 0) {
1465 ix = path[depth].p_idx;
1466 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1467 EXT4_ERROR_INODE(inode,
1468 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1469 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1470 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1471 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1472 depth);
1473 return -EFSCORRUPTED;
1476 return 0;
1479 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1480 EXT4_ERROR_INODE(inode,
1481 "logical %d < ee_block %d + ee_len %d!",
1482 *logical, le32_to_cpu(ex->ee_block), ee_len);
1483 return -EFSCORRUPTED;
1486 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1487 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1488 return 0;
1492 * search the closest allocated block to the right for *logical
1493 * and returns it at @logical + it's physical address at @phys
1494 * if *logical is the largest allocated block, the function
1495 * returns 0 at @phys
1496 * return value contains 0 (success) or error code
1498 static int ext4_ext_search_right(struct inode *inode,
1499 struct ext4_ext_path *path,
1500 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1501 struct ext4_extent **ret_ex)
1503 struct buffer_head *bh = NULL;
1504 struct ext4_extent_header *eh;
1505 struct ext4_extent_idx *ix;
1506 struct ext4_extent *ex;
1507 ext4_fsblk_t block;
1508 int depth; /* Note, NOT eh_depth; depth from top of tree */
1509 int ee_len;
1511 if (unlikely(path == NULL)) {
1512 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1513 return -EFSCORRUPTED;
1515 depth = path->p_depth;
1516 *phys = 0;
1518 if (depth == 0 && path->p_ext == NULL)
1519 return 0;
1521 /* usually extent in the path covers blocks smaller
1522 * then *logical, but it can be that extent is the
1523 * first one in the file */
1525 ex = path[depth].p_ext;
1526 ee_len = ext4_ext_get_actual_len(ex);
1527 if (*logical < le32_to_cpu(ex->ee_block)) {
1528 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1529 EXT4_ERROR_INODE(inode,
1530 "first_extent(path[%d].p_hdr) != ex",
1531 depth);
1532 return -EFSCORRUPTED;
1534 while (--depth >= 0) {
1535 ix = path[depth].p_idx;
1536 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1537 EXT4_ERROR_INODE(inode,
1538 "ix != EXT_FIRST_INDEX *logical %d!",
1539 *logical);
1540 return -EFSCORRUPTED;
1543 goto found_extent;
1546 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1547 EXT4_ERROR_INODE(inode,
1548 "logical %d < ee_block %d + ee_len %d!",
1549 *logical, le32_to_cpu(ex->ee_block), ee_len);
1550 return -EFSCORRUPTED;
1553 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1554 /* next allocated block in this leaf */
1555 ex++;
1556 goto found_extent;
1559 /* go up and search for index to the right */
1560 while (--depth >= 0) {
1561 ix = path[depth].p_idx;
1562 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1563 goto got_index;
1566 /* we've gone up to the root and found no index to the right */
1567 return 0;
1569 got_index:
1570 /* we've found index to the right, let's
1571 * follow it and find the closest allocated
1572 * block to the right */
1573 ix++;
1574 block = ext4_idx_pblock(ix);
1575 while (++depth < path->p_depth) {
1576 /* subtract from p_depth to get proper eh_depth */
1577 bh = read_extent_tree_block(inode, block,
1578 path->p_depth - depth, 0);
1579 if (IS_ERR(bh))
1580 return PTR_ERR(bh);
1581 eh = ext_block_hdr(bh);
1582 ix = EXT_FIRST_INDEX(eh);
1583 block = ext4_idx_pblock(ix);
1584 put_bh(bh);
1587 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1588 if (IS_ERR(bh))
1589 return PTR_ERR(bh);
1590 eh = ext_block_hdr(bh);
1591 ex = EXT_FIRST_EXTENT(eh);
1592 found_extent:
1593 *logical = le32_to_cpu(ex->ee_block);
1594 *phys = ext4_ext_pblock(ex);
1595 *ret_ex = ex;
1596 if (bh)
1597 put_bh(bh);
1598 return 0;
1602 * ext4_ext_next_allocated_block:
1603 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1604 * NOTE: it considers block number from index entry as
1605 * allocated block. Thus, index entries have to be consistent
1606 * with leaves.
1608 ext4_lblk_t
1609 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1611 int depth;
1613 BUG_ON(path == NULL);
1614 depth = path->p_depth;
1616 if (depth == 0 && path->p_ext == NULL)
1617 return EXT_MAX_BLOCKS;
1619 while (depth >= 0) {
1620 if (depth == path->p_depth) {
1621 /* leaf */
1622 if (path[depth].p_ext &&
1623 path[depth].p_ext !=
1624 EXT_LAST_EXTENT(path[depth].p_hdr))
1625 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1626 } else {
1627 /* index */
1628 if (path[depth].p_idx !=
1629 EXT_LAST_INDEX(path[depth].p_hdr))
1630 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1632 depth--;
1635 return EXT_MAX_BLOCKS;
1639 * ext4_ext_next_leaf_block:
1640 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1642 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1644 int depth;
1646 BUG_ON(path == NULL);
1647 depth = path->p_depth;
1649 /* zero-tree has no leaf blocks at all */
1650 if (depth == 0)
1651 return EXT_MAX_BLOCKS;
1653 /* go to index block */
1654 depth--;
1656 while (depth >= 0) {
1657 if (path[depth].p_idx !=
1658 EXT_LAST_INDEX(path[depth].p_hdr))
1659 return (ext4_lblk_t)
1660 le32_to_cpu(path[depth].p_idx[1].ei_block);
1661 depth--;
1664 return EXT_MAX_BLOCKS;
1668 * ext4_ext_correct_indexes:
1669 * if leaf gets modified and modified extent is first in the leaf,
1670 * then we have to correct all indexes above.
1671 * TODO: do we need to correct tree in all cases?
1673 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1674 struct ext4_ext_path *path)
1676 struct ext4_extent_header *eh;
1677 int depth = ext_depth(inode);
1678 struct ext4_extent *ex;
1679 __le32 border;
1680 int k, err = 0;
1682 eh = path[depth].p_hdr;
1683 ex = path[depth].p_ext;
1685 if (unlikely(ex == NULL || eh == NULL)) {
1686 EXT4_ERROR_INODE(inode,
1687 "ex %p == NULL or eh %p == NULL", ex, eh);
1688 return -EFSCORRUPTED;
1691 if (depth == 0) {
1692 /* there is no tree at all */
1693 return 0;
1696 if (ex != EXT_FIRST_EXTENT(eh)) {
1697 /* we correct tree if first leaf got modified only */
1698 return 0;
1702 * TODO: we need correction if border is smaller than current one
1704 k = depth - 1;
1705 border = path[depth].p_ext->ee_block;
1706 err = ext4_ext_get_access(handle, inode, path + k);
1707 if (err)
1708 return err;
1709 path[k].p_idx->ei_block = border;
1710 err = ext4_ext_dirty(handle, inode, path + k);
1711 if (err)
1712 return err;
1714 while (k--) {
1715 /* change all left-side indexes */
1716 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1717 break;
1718 err = ext4_ext_get_access(handle, inode, path + k);
1719 if (err)
1720 break;
1721 path[k].p_idx->ei_block = border;
1722 err = ext4_ext_dirty(handle, inode, path + k);
1723 if (err)
1724 break;
1727 return err;
1731 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1732 struct ext4_extent *ex2)
1734 unsigned short ext1_ee_len, ext2_ee_len;
1736 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1737 return 0;
1739 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1740 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1742 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1743 le32_to_cpu(ex2->ee_block))
1744 return 0;
1747 * To allow future support for preallocated extents to be added
1748 * as an RO_COMPAT feature, refuse to merge to extents if
1749 * this can result in the top bit of ee_len being set.
1751 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1752 return 0;
1753 if (ext4_ext_is_unwritten(ex1) &&
1754 (ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
1755 atomic_read(&EXT4_I(inode)->i_unwritten) ||
1756 (ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
1757 return 0;
1758 #ifdef AGGRESSIVE_TEST
1759 if (ext1_ee_len >= 4)
1760 return 0;
1761 #endif
1763 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1764 return 1;
1765 return 0;
1769 * This function tries to merge the "ex" extent to the next extent in the tree.
1770 * It always tries to merge towards right. If you want to merge towards
1771 * left, pass "ex - 1" as argument instead of "ex".
1772 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1773 * 1 if they got merged.
1775 static int ext4_ext_try_to_merge_right(struct inode *inode,
1776 struct ext4_ext_path *path,
1777 struct ext4_extent *ex)
1779 struct ext4_extent_header *eh;
1780 unsigned int depth, len;
1781 int merge_done = 0, unwritten;
1783 depth = ext_depth(inode);
1784 BUG_ON(path[depth].p_hdr == NULL);
1785 eh = path[depth].p_hdr;
1787 while (ex < EXT_LAST_EXTENT(eh)) {
1788 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1789 break;
1790 /* merge with next extent! */
1791 unwritten = ext4_ext_is_unwritten(ex);
1792 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1793 + ext4_ext_get_actual_len(ex + 1));
1794 if (unwritten)
1795 ext4_ext_mark_unwritten(ex);
1797 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1798 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1799 * sizeof(struct ext4_extent);
1800 memmove(ex + 1, ex + 2, len);
1802 le16_add_cpu(&eh->eh_entries, -1);
1803 merge_done = 1;
1804 WARN_ON(eh->eh_entries == 0);
1805 if (!eh->eh_entries)
1806 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1809 return merge_done;
1813 * This function does a very simple check to see if we can collapse
1814 * an extent tree with a single extent tree leaf block into the inode.
1816 static void ext4_ext_try_to_merge_up(handle_t *handle,
1817 struct inode *inode,
1818 struct ext4_ext_path *path)
1820 size_t s;
1821 unsigned max_root = ext4_ext_space_root(inode, 0);
1822 ext4_fsblk_t blk;
1824 if ((path[0].p_depth != 1) ||
1825 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1826 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1827 return;
1830 * We need to modify the block allocation bitmap and the block
1831 * group descriptor to release the extent tree block. If we
1832 * can't get the journal credits, give up.
1834 if (ext4_journal_extend(handle, 2))
1835 return;
1838 * Copy the extent data up to the inode
1840 blk = ext4_idx_pblock(path[0].p_idx);
1841 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1842 sizeof(struct ext4_extent_idx);
1843 s += sizeof(struct ext4_extent_header);
1845 path[1].p_maxdepth = path[0].p_maxdepth;
1846 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1847 path[0].p_depth = 0;
1848 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1849 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1850 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1852 brelse(path[1].p_bh);
1853 ext4_free_blocks(handle, inode, NULL, blk, 1,
1854 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1858 * This function tries to merge the @ex extent to neighbours in the tree.
1859 * return 1 if merge left else 0.
1861 static void ext4_ext_try_to_merge(handle_t *handle,
1862 struct inode *inode,
1863 struct ext4_ext_path *path,
1864 struct ext4_extent *ex) {
1865 struct ext4_extent_header *eh;
1866 unsigned int depth;
1867 int merge_done = 0;
1869 depth = ext_depth(inode);
1870 BUG_ON(path[depth].p_hdr == NULL);
1871 eh = path[depth].p_hdr;
1873 if (ex > EXT_FIRST_EXTENT(eh))
1874 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1876 if (!merge_done)
1877 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1879 ext4_ext_try_to_merge_up(handle, inode, path);
1883 * check if a portion of the "newext" extent overlaps with an
1884 * existing extent.
1886 * If there is an overlap discovered, it updates the length of the newext
1887 * such that there will be no overlap, and then returns 1.
1888 * If there is no overlap found, it returns 0.
1890 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1891 struct inode *inode,
1892 struct ext4_extent *newext,
1893 struct ext4_ext_path *path)
1895 ext4_lblk_t b1, b2;
1896 unsigned int depth, len1;
1897 unsigned int ret = 0;
1899 b1 = le32_to_cpu(newext->ee_block);
1900 len1 = ext4_ext_get_actual_len(newext);
1901 depth = ext_depth(inode);
1902 if (!path[depth].p_ext)
1903 goto out;
1904 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1907 * get the next allocated block if the extent in the path
1908 * is before the requested block(s)
1910 if (b2 < b1) {
1911 b2 = ext4_ext_next_allocated_block(path);
1912 if (b2 == EXT_MAX_BLOCKS)
1913 goto out;
1914 b2 = EXT4_LBLK_CMASK(sbi, b2);
1917 /* check for wrap through zero on extent logical start block*/
1918 if (b1 + len1 < b1) {
1919 len1 = EXT_MAX_BLOCKS - b1;
1920 newext->ee_len = cpu_to_le16(len1);
1921 ret = 1;
1924 /* check for overlap */
1925 if (b1 + len1 > b2) {
1926 newext->ee_len = cpu_to_le16(b2 - b1);
1927 ret = 1;
1929 out:
1930 return ret;
1934 * ext4_ext_insert_extent:
1935 * tries to merge requsted extent into the existing extent or
1936 * inserts requested extent as new one into the tree,
1937 * creating new leaf in the no-space case.
1939 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1940 struct ext4_ext_path **ppath,
1941 struct ext4_extent *newext, int gb_flags)
1943 struct ext4_ext_path *path = *ppath;
1944 struct ext4_extent_header *eh;
1945 struct ext4_extent *ex, *fex;
1946 struct ext4_extent *nearex; /* nearest extent */
1947 struct ext4_ext_path *npath = NULL;
1948 int depth, len, err;
1949 ext4_lblk_t next;
1950 int mb_flags = 0, unwritten;
1952 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1953 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1954 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1955 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1956 return -EFSCORRUPTED;
1958 depth = ext_depth(inode);
1959 ex = path[depth].p_ext;
1960 eh = path[depth].p_hdr;
1961 if (unlikely(path[depth].p_hdr == NULL)) {
1962 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1963 return -EFSCORRUPTED;
1966 /* try to insert block into found extent and return */
1967 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1970 * Try to see whether we should rather test the extent on
1971 * right from ex, or from the left of ex. This is because
1972 * ext4_find_extent() can return either extent on the
1973 * left, or on the right from the searched position. This
1974 * will make merging more effective.
1976 if (ex < EXT_LAST_EXTENT(eh) &&
1977 (le32_to_cpu(ex->ee_block) +
1978 ext4_ext_get_actual_len(ex) <
1979 le32_to_cpu(newext->ee_block))) {
1980 ex += 1;
1981 goto prepend;
1982 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
1983 (le32_to_cpu(newext->ee_block) +
1984 ext4_ext_get_actual_len(newext) <
1985 le32_to_cpu(ex->ee_block)))
1986 ex -= 1;
1988 /* Try to append newex to the ex */
1989 if (ext4_can_extents_be_merged(inode, ex, newext)) {
1990 ext_debug("append [%d]%d block to %u:[%d]%d"
1991 "(from %llu)\n",
1992 ext4_ext_is_unwritten(newext),
1993 ext4_ext_get_actual_len(newext),
1994 le32_to_cpu(ex->ee_block),
1995 ext4_ext_is_unwritten(ex),
1996 ext4_ext_get_actual_len(ex),
1997 ext4_ext_pblock(ex));
1998 err = ext4_ext_get_access(handle, inode,
1999 path + depth);
2000 if (err)
2001 return err;
2002 unwritten = ext4_ext_is_unwritten(ex);
2003 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2004 + ext4_ext_get_actual_len(newext));
2005 if (unwritten)
2006 ext4_ext_mark_unwritten(ex);
2007 eh = path[depth].p_hdr;
2008 nearex = ex;
2009 goto merge;
2012 prepend:
2013 /* Try to prepend newex to the ex */
2014 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2015 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2016 "(from %llu)\n",
2017 le32_to_cpu(newext->ee_block),
2018 ext4_ext_is_unwritten(newext),
2019 ext4_ext_get_actual_len(newext),
2020 le32_to_cpu(ex->ee_block),
2021 ext4_ext_is_unwritten(ex),
2022 ext4_ext_get_actual_len(ex),
2023 ext4_ext_pblock(ex));
2024 err = ext4_ext_get_access(handle, inode,
2025 path + depth);
2026 if (err)
2027 return err;
2029 unwritten = ext4_ext_is_unwritten(ex);
2030 ex->ee_block = newext->ee_block;
2031 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2032 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2033 + ext4_ext_get_actual_len(newext));
2034 if (unwritten)
2035 ext4_ext_mark_unwritten(ex);
2036 eh = path[depth].p_hdr;
2037 nearex = ex;
2038 goto merge;
2042 depth = ext_depth(inode);
2043 eh = path[depth].p_hdr;
2044 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2045 goto has_space;
2047 /* probably next leaf has space for us? */
2048 fex = EXT_LAST_EXTENT(eh);
2049 next = EXT_MAX_BLOCKS;
2050 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2051 next = ext4_ext_next_leaf_block(path);
2052 if (next != EXT_MAX_BLOCKS) {
2053 ext_debug("next leaf block - %u\n", next);
2054 BUG_ON(npath != NULL);
2055 npath = ext4_find_extent(inode, next, NULL, 0);
2056 if (IS_ERR(npath))
2057 return PTR_ERR(npath);
2058 BUG_ON(npath->p_depth != path->p_depth);
2059 eh = npath[depth].p_hdr;
2060 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2061 ext_debug("next leaf isn't full(%d)\n",
2062 le16_to_cpu(eh->eh_entries));
2063 path = npath;
2064 goto has_space;
2066 ext_debug("next leaf has no free space(%d,%d)\n",
2067 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2071 * There is no free space in the found leaf.
2072 * We're gonna add a new leaf in the tree.
2074 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2075 mb_flags |= EXT4_MB_USE_RESERVED;
2076 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2077 ppath, newext);
2078 if (err)
2079 goto cleanup;
2080 depth = ext_depth(inode);
2081 eh = path[depth].p_hdr;
2083 has_space:
2084 nearex = path[depth].p_ext;
2086 err = ext4_ext_get_access(handle, inode, path + depth);
2087 if (err)
2088 goto cleanup;
2090 if (!nearex) {
2091 /* there is no extent in this leaf, create first one */
2092 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
2093 le32_to_cpu(newext->ee_block),
2094 ext4_ext_pblock(newext),
2095 ext4_ext_is_unwritten(newext),
2096 ext4_ext_get_actual_len(newext));
2097 nearex = EXT_FIRST_EXTENT(eh);
2098 } else {
2099 if (le32_to_cpu(newext->ee_block)
2100 > le32_to_cpu(nearex->ee_block)) {
2101 /* Insert after */
2102 ext_debug("insert %u:%llu:[%d]%d before: "
2103 "nearest %p\n",
2104 le32_to_cpu(newext->ee_block),
2105 ext4_ext_pblock(newext),
2106 ext4_ext_is_unwritten(newext),
2107 ext4_ext_get_actual_len(newext),
2108 nearex);
2109 nearex++;
2110 } else {
2111 /* Insert before */
2112 BUG_ON(newext->ee_block == nearex->ee_block);
2113 ext_debug("insert %u:%llu:[%d]%d after: "
2114 "nearest %p\n",
2115 le32_to_cpu(newext->ee_block),
2116 ext4_ext_pblock(newext),
2117 ext4_ext_is_unwritten(newext),
2118 ext4_ext_get_actual_len(newext),
2119 nearex);
2121 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2122 if (len > 0) {
2123 ext_debug("insert %u:%llu:[%d]%d: "
2124 "move %d extents from 0x%p to 0x%p\n",
2125 le32_to_cpu(newext->ee_block),
2126 ext4_ext_pblock(newext),
2127 ext4_ext_is_unwritten(newext),
2128 ext4_ext_get_actual_len(newext),
2129 len, nearex, nearex + 1);
2130 memmove(nearex + 1, nearex,
2131 len * sizeof(struct ext4_extent));
2135 le16_add_cpu(&eh->eh_entries, 1);
2136 path[depth].p_ext = nearex;
2137 nearex->ee_block = newext->ee_block;
2138 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2139 nearex->ee_len = newext->ee_len;
2141 merge:
2142 /* try to merge extents */
2143 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2144 ext4_ext_try_to_merge(handle, inode, path, nearex);
2147 /* time to correct all indexes above */
2148 err = ext4_ext_correct_indexes(handle, inode, path);
2149 if (err)
2150 goto cleanup;
2152 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2154 cleanup:
2155 ext4_ext_drop_refs(npath);
2156 kfree(npath);
2157 return err;
2160 static int ext4_fill_fiemap_extents(struct inode *inode,
2161 ext4_lblk_t block, ext4_lblk_t num,
2162 struct fiemap_extent_info *fieinfo)
2164 struct ext4_ext_path *path = NULL;
2165 struct ext4_extent *ex;
2166 struct extent_status es;
2167 ext4_lblk_t next, next_del, start = 0, end = 0;
2168 ext4_lblk_t last = block + num;
2169 int exists, depth = 0, err = 0;
2170 unsigned int flags = 0;
2171 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2173 while (block < last && block != EXT_MAX_BLOCKS) {
2174 num = last - block;
2175 /* find extent for this block */
2176 down_read(&EXT4_I(inode)->i_data_sem);
2178 path = ext4_find_extent(inode, block, &path, 0);
2179 if (IS_ERR(path)) {
2180 up_read(&EXT4_I(inode)->i_data_sem);
2181 err = PTR_ERR(path);
2182 path = NULL;
2183 break;
2186 depth = ext_depth(inode);
2187 if (unlikely(path[depth].p_hdr == NULL)) {
2188 up_read(&EXT4_I(inode)->i_data_sem);
2189 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2190 err = -EFSCORRUPTED;
2191 break;
2193 ex = path[depth].p_ext;
2194 next = ext4_ext_next_allocated_block(path);
2196 flags = 0;
2197 exists = 0;
2198 if (!ex) {
2199 /* there is no extent yet, so try to allocate
2200 * all requested space */
2201 start = block;
2202 end = block + num;
2203 } else if (le32_to_cpu(ex->ee_block) > block) {
2204 /* need to allocate space before found extent */
2205 start = block;
2206 end = le32_to_cpu(ex->ee_block);
2207 if (block + num < end)
2208 end = block + num;
2209 } else if (block >= le32_to_cpu(ex->ee_block)
2210 + ext4_ext_get_actual_len(ex)) {
2211 /* need to allocate space after found extent */
2212 start = block;
2213 end = block + num;
2214 if (end >= next)
2215 end = next;
2216 } else if (block >= le32_to_cpu(ex->ee_block)) {
2218 * some part of requested space is covered
2219 * by found extent
2221 start = block;
2222 end = le32_to_cpu(ex->ee_block)
2223 + ext4_ext_get_actual_len(ex);
2224 if (block + num < end)
2225 end = block + num;
2226 exists = 1;
2227 } else {
2228 BUG();
2230 BUG_ON(end <= start);
2232 if (!exists) {
2233 es.es_lblk = start;
2234 es.es_len = end - start;
2235 es.es_pblk = 0;
2236 } else {
2237 es.es_lblk = le32_to_cpu(ex->ee_block);
2238 es.es_len = ext4_ext_get_actual_len(ex);
2239 es.es_pblk = ext4_ext_pblock(ex);
2240 if (ext4_ext_is_unwritten(ex))
2241 flags |= FIEMAP_EXTENT_UNWRITTEN;
2245 * Find delayed extent and update es accordingly. We call
2246 * it even in !exists case to find out whether es is the
2247 * last existing extent or not.
2249 next_del = ext4_find_delayed_extent(inode, &es);
2250 if (!exists && next_del) {
2251 exists = 1;
2252 flags |= (FIEMAP_EXTENT_DELALLOC |
2253 FIEMAP_EXTENT_UNKNOWN);
2255 up_read(&EXT4_I(inode)->i_data_sem);
2257 if (unlikely(es.es_len == 0)) {
2258 EXT4_ERROR_INODE(inode, "es.es_len == 0");
2259 err = -EFSCORRUPTED;
2260 break;
2264 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2265 * we need to check next == EXT_MAX_BLOCKS because it is
2266 * possible that an extent is with unwritten and delayed
2267 * status due to when an extent is delayed allocated and
2268 * is allocated by fallocate status tree will track both of
2269 * them in a extent.
2271 * So we could return a unwritten and delayed extent, and
2272 * its block is equal to 'next'.
2274 if (next == next_del && next == EXT_MAX_BLOCKS) {
2275 flags |= FIEMAP_EXTENT_LAST;
2276 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2277 next != EXT_MAX_BLOCKS)) {
2278 EXT4_ERROR_INODE(inode,
2279 "next extent == %u, next "
2280 "delalloc extent = %u",
2281 next, next_del);
2282 err = -EFSCORRUPTED;
2283 break;
2287 if (exists) {
2288 err = fiemap_fill_next_extent(fieinfo,
2289 (__u64)es.es_lblk << blksize_bits,
2290 (__u64)es.es_pblk << blksize_bits,
2291 (__u64)es.es_len << blksize_bits,
2292 flags);
2293 if (err < 0)
2294 break;
2295 if (err == 1) {
2296 err = 0;
2297 break;
2301 block = es.es_lblk + es.es_len;
2304 ext4_ext_drop_refs(path);
2305 kfree(path);
2306 return err;
2310 * ext4_ext_put_gap_in_cache:
2311 * calculate boundaries of the gap that the requested block fits into
2312 * and cache this gap
2314 static void
2315 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
2316 ext4_lblk_t block)
2318 int depth = ext_depth(inode);
2319 ext4_lblk_t len;
2320 ext4_lblk_t lblock;
2321 struct ext4_extent *ex;
2322 struct extent_status es;
2324 ex = path[depth].p_ext;
2325 if (ex == NULL) {
2326 /* there is no extent yet, so gap is [0;-] */
2327 lblock = 0;
2328 len = EXT_MAX_BLOCKS;
2329 ext_debug("cache gap(whole file):");
2330 } else if (block < le32_to_cpu(ex->ee_block)) {
2331 lblock = block;
2332 len = le32_to_cpu(ex->ee_block) - block;
2333 ext_debug("cache gap(before): %u [%u:%u]",
2334 block,
2335 le32_to_cpu(ex->ee_block),
2336 ext4_ext_get_actual_len(ex));
2337 } else if (block >= le32_to_cpu(ex->ee_block)
2338 + ext4_ext_get_actual_len(ex)) {
2339 ext4_lblk_t next;
2340 lblock = le32_to_cpu(ex->ee_block)
2341 + ext4_ext_get_actual_len(ex);
2343 next = ext4_ext_next_allocated_block(path);
2344 ext_debug("cache gap(after): [%u:%u] %u",
2345 le32_to_cpu(ex->ee_block),
2346 ext4_ext_get_actual_len(ex),
2347 block);
2348 BUG_ON(next == lblock);
2349 len = next - lblock;
2350 } else {
2351 BUG();
2354 ext4_es_find_delayed_extent_range(inode, lblock, lblock + len - 1, &es);
2355 if (es.es_len) {
2356 /* There's delayed extent containing lblock? */
2357 if (es.es_lblk <= lblock)
2358 return;
2359 len = min(es.es_lblk - lblock, len);
2361 ext_debug(" -> %u:%u\n", lblock, len);
2362 ext4_es_insert_extent(inode, lblock, len, ~0, EXTENT_STATUS_HOLE);
2366 * ext4_ext_rm_idx:
2367 * removes index from the index block.
2369 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2370 struct ext4_ext_path *path, int depth)
2372 int err;
2373 ext4_fsblk_t leaf;
2375 /* free index block */
2376 depth--;
2377 path = path + depth;
2378 leaf = ext4_idx_pblock(path->p_idx);
2379 if (unlikely(path->p_hdr->eh_entries == 0)) {
2380 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2381 return -EFSCORRUPTED;
2383 err = ext4_ext_get_access(handle, inode, path);
2384 if (err)
2385 return err;
2387 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2388 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2389 len *= sizeof(struct ext4_extent_idx);
2390 memmove(path->p_idx, path->p_idx + 1, len);
2393 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2394 err = ext4_ext_dirty(handle, inode, path);
2395 if (err)
2396 return err;
2397 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2398 trace_ext4_ext_rm_idx(inode, leaf);
2400 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2401 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2403 while (--depth >= 0) {
2404 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2405 break;
2406 path--;
2407 err = ext4_ext_get_access(handle, inode, path);
2408 if (err)
2409 break;
2410 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2411 err = ext4_ext_dirty(handle, inode, path);
2412 if (err)
2413 break;
2415 return err;
2419 * ext4_ext_calc_credits_for_single_extent:
2420 * This routine returns max. credits that needed to insert an extent
2421 * to the extent tree.
2422 * When pass the actual path, the caller should calculate credits
2423 * under i_data_sem.
2425 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2426 struct ext4_ext_path *path)
2428 if (path) {
2429 int depth = ext_depth(inode);
2430 int ret = 0;
2432 /* probably there is space in leaf? */
2433 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2434 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2437 * There are some space in the leaf tree, no
2438 * need to account for leaf block credit
2440 * bitmaps and block group descriptor blocks
2441 * and other metadata blocks still need to be
2442 * accounted.
2444 /* 1 bitmap, 1 block group descriptor */
2445 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2446 return ret;
2450 return ext4_chunk_trans_blocks(inode, nrblocks);
2454 * How many index/leaf blocks need to change/allocate to add @extents extents?
2456 * If we add a single extent, then in the worse case, each tree level
2457 * index/leaf need to be changed in case of the tree split.
2459 * If more extents are inserted, they could cause the whole tree split more
2460 * than once, but this is really rare.
2462 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2464 int index;
2465 int depth;
2467 /* If we are converting the inline data, only one is needed here. */
2468 if (ext4_has_inline_data(inode))
2469 return 1;
2471 depth = ext_depth(inode);
2473 if (extents <= 1)
2474 index = depth * 2;
2475 else
2476 index = depth * 3;
2478 return index;
2481 static inline int get_default_free_blocks_flags(struct inode *inode)
2483 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2484 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2485 else if (ext4_should_journal_data(inode))
2486 return EXT4_FREE_BLOCKS_FORGET;
2487 return 0;
2490 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2491 struct ext4_extent *ex,
2492 long long *partial_cluster,
2493 ext4_lblk_t from, ext4_lblk_t to)
2495 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2496 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2497 ext4_fsblk_t pblk;
2498 int flags = get_default_free_blocks_flags(inode);
2501 * For bigalloc file systems, we never free a partial cluster
2502 * at the beginning of the extent. Instead, we make a note
2503 * that we tried freeing the cluster, and check to see if we
2504 * need to free it on a subsequent call to ext4_remove_blocks,
2505 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2507 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2509 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2511 * If we have a partial cluster, and it's different from the
2512 * cluster of the last block, we need to explicitly free the
2513 * partial cluster here.
2515 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2516 if (*partial_cluster > 0 &&
2517 *partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2518 ext4_free_blocks(handle, inode, NULL,
2519 EXT4_C2B(sbi, *partial_cluster),
2520 sbi->s_cluster_ratio, flags);
2521 *partial_cluster = 0;
2524 #ifdef EXTENTS_STATS
2526 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2527 spin_lock(&sbi->s_ext_stats_lock);
2528 sbi->s_ext_blocks += ee_len;
2529 sbi->s_ext_extents++;
2530 if (ee_len < sbi->s_ext_min)
2531 sbi->s_ext_min = ee_len;
2532 if (ee_len > sbi->s_ext_max)
2533 sbi->s_ext_max = ee_len;
2534 if (ext_depth(inode) > sbi->s_depth_max)
2535 sbi->s_depth_max = ext_depth(inode);
2536 spin_unlock(&sbi->s_ext_stats_lock);
2538 #endif
2539 if (from >= le32_to_cpu(ex->ee_block)
2540 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2541 /* tail removal */
2542 ext4_lblk_t num;
2543 long long first_cluster;
2545 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2546 pblk = ext4_ext_pblock(ex) + ee_len - num;
2548 * Usually we want to free partial cluster at the end of the
2549 * extent, except for the situation when the cluster is still
2550 * used by any other extent (partial_cluster is negative).
2552 if (*partial_cluster < 0 &&
2553 *partial_cluster == -(long long) EXT4_B2C(sbi, pblk+num-1))
2554 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2556 ext_debug("free last %u blocks starting %llu partial %lld\n",
2557 num, pblk, *partial_cluster);
2558 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2560 * If the block range to be freed didn't start at the
2561 * beginning of a cluster, and we removed the entire
2562 * extent and the cluster is not used by any other extent,
2563 * save the partial cluster here, since we might need to
2564 * delete if we determine that the truncate or punch hole
2565 * operation has removed all of the blocks in the cluster.
2566 * If that cluster is used by another extent, preserve its
2567 * negative value so it isn't freed later on.
2569 * If the whole extent wasn't freed, we've reached the
2570 * start of the truncated/punched region and have finished
2571 * removing blocks. If there's a partial cluster here it's
2572 * shared with the remainder of the extent and is no longer
2573 * a candidate for removal.
2575 if (EXT4_PBLK_COFF(sbi, pblk) && ee_len == num) {
2576 first_cluster = (long long) EXT4_B2C(sbi, pblk);
2577 if (first_cluster != -*partial_cluster)
2578 *partial_cluster = first_cluster;
2579 } else {
2580 *partial_cluster = 0;
2582 } else
2583 ext4_error(sbi->s_sb, "strange request: removal(2) "
2584 "%u-%u from %u:%u\n",
2585 from, to, le32_to_cpu(ex->ee_block), ee_len);
2586 return 0;
2591 * ext4_ext_rm_leaf() Removes the extents associated with the
2592 * blocks appearing between "start" and "end". Both "start"
2593 * and "end" must appear in the same extent or EIO is returned.
2595 * @handle: The journal handle
2596 * @inode: The files inode
2597 * @path: The path to the leaf
2598 * @partial_cluster: The cluster which we'll have to free if all extents
2599 * has been released from it. However, if this value is
2600 * negative, it's a cluster just to the right of the
2601 * punched region and it must not be freed.
2602 * @start: The first block to remove
2603 * @end: The last block to remove
2605 static int
2606 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2607 struct ext4_ext_path *path,
2608 long long *partial_cluster,
2609 ext4_lblk_t start, ext4_lblk_t end)
2611 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2612 int err = 0, correct_index = 0;
2613 int depth = ext_depth(inode), credits;
2614 struct ext4_extent_header *eh;
2615 ext4_lblk_t a, b;
2616 unsigned num;
2617 ext4_lblk_t ex_ee_block;
2618 unsigned short ex_ee_len;
2619 unsigned unwritten = 0;
2620 struct ext4_extent *ex;
2621 ext4_fsblk_t pblk;
2623 /* the header must be checked already in ext4_ext_remove_space() */
2624 ext_debug("truncate since %u in leaf to %u\n", start, end);
2625 if (!path[depth].p_hdr)
2626 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2627 eh = path[depth].p_hdr;
2628 if (unlikely(path[depth].p_hdr == NULL)) {
2629 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2630 return -EFSCORRUPTED;
2632 /* find where to start removing */
2633 ex = path[depth].p_ext;
2634 if (!ex)
2635 ex = EXT_LAST_EXTENT(eh);
2637 ex_ee_block = le32_to_cpu(ex->ee_block);
2638 ex_ee_len = ext4_ext_get_actual_len(ex);
2640 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2642 while (ex >= EXT_FIRST_EXTENT(eh) &&
2643 ex_ee_block + ex_ee_len > start) {
2645 if (ext4_ext_is_unwritten(ex))
2646 unwritten = 1;
2647 else
2648 unwritten = 0;
2650 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2651 unwritten, ex_ee_len);
2652 path[depth].p_ext = ex;
2654 a = ex_ee_block > start ? ex_ee_block : start;
2655 b = ex_ee_block+ex_ee_len - 1 < end ?
2656 ex_ee_block+ex_ee_len - 1 : end;
2658 ext_debug(" border %u:%u\n", a, b);
2660 /* If this extent is beyond the end of the hole, skip it */
2661 if (end < ex_ee_block) {
2663 * We're going to skip this extent and move to another,
2664 * so note that its first cluster is in use to avoid
2665 * freeing it when removing blocks. Eventually, the
2666 * right edge of the truncated/punched region will
2667 * be just to the left.
2669 if (sbi->s_cluster_ratio > 1) {
2670 pblk = ext4_ext_pblock(ex);
2671 *partial_cluster =
2672 -(long long) EXT4_B2C(sbi, pblk);
2674 ex--;
2675 ex_ee_block = le32_to_cpu(ex->ee_block);
2676 ex_ee_len = ext4_ext_get_actual_len(ex);
2677 continue;
2678 } else if (b != ex_ee_block + ex_ee_len - 1) {
2679 EXT4_ERROR_INODE(inode,
2680 "can not handle truncate %u:%u "
2681 "on extent %u:%u",
2682 start, end, ex_ee_block,
2683 ex_ee_block + ex_ee_len - 1);
2684 err = -EFSCORRUPTED;
2685 goto out;
2686 } else if (a != ex_ee_block) {
2687 /* remove tail of the extent */
2688 num = a - ex_ee_block;
2689 } else {
2690 /* remove whole extent: excellent! */
2691 num = 0;
2694 * 3 for leaf, sb, and inode plus 2 (bmap and group
2695 * descriptor) for each block group; assume two block
2696 * groups plus ex_ee_len/blocks_per_block_group for
2697 * the worst case
2699 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2700 if (ex == EXT_FIRST_EXTENT(eh)) {
2701 correct_index = 1;
2702 credits += (ext_depth(inode)) + 1;
2704 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2706 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2707 if (err)
2708 goto out;
2710 err = ext4_ext_get_access(handle, inode, path + depth);
2711 if (err)
2712 goto out;
2714 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2715 a, b);
2716 if (err)
2717 goto out;
2719 if (num == 0)
2720 /* this extent is removed; mark slot entirely unused */
2721 ext4_ext_store_pblock(ex, 0);
2723 ex->ee_len = cpu_to_le16(num);
2725 * Do not mark unwritten if all the blocks in the
2726 * extent have been removed.
2728 if (unwritten && num)
2729 ext4_ext_mark_unwritten(ex);
2731 * If the extent was completely released,
2732 * we need to remove it from the leaf
2734 if (num == 0) {
2735 if (end != EXT_MAX_BLOCKS - 1) {
2737 * For hole punching, we need to scoot all the
2738 * extents up when an extent is removed so that
2739 * we dont have blank extents in the middle
2741 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2742 sizeof(struct ext4_extent));
2744 /* Now get rid of the one at the end */
2745 memset(EXT_LAST_EXTENT(eh), 0,
2746 sizeof(struct ext4_extent));
2748 le16_add_cpu(&eh->eh_entries, -1);
2751 err = ext4_ext_dirty(handle, inode, path + depth);
2752 if (err)
2753 goto out;
2755 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2756 ext4_ext_pblock(ex));
2757 ex--;
2758 ex_ee_block = le32_to_cpu(ex->ee_block);
2759 ex_ee_len = ext4_ext_get_actual_len(ex);
2762 if (correct_index && eh->eh_entries)
2763 err = ext4_ext_correct_indexes(handle, inode, path);
2766 * If there's a partial cluster and at least one extent remains in
2767 * the leaf, free the partial cluster if it isn't shared with the
2768 * current extent. If it is shared with the current extent
2769 * we zero partial_cluster because we've reached the start of the
2770 * truncated/punched region and we're done removing blocks.
2772 if (*partial_cluster > 0 && ex >= EXT_FIRST_EXTENT(eh)) {
2773 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2774 if (*partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2775 ext4_free_blocks(handle, inode, NULL,
2776 EXT4_C2B(sbi, *partial_cluster),
2777 sbi->s_cluster_ratio,
2778 get_default_free_blocks_flags(inode));
2780 *partial_cluster = 0;
2783 /* if this leaf is free, then we should
2784 * remove it from index block above */
2785 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2786 err = ext4_ext_rm_idx(handle, inode, path, depth);
2788 out:
2789 return err;
2793 * ext4_ext_more_to_rm:
2794 * returns 1 if current index has to be freed (even partial)
2796 static int
2797 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2799 BUG_ON(path->p_idx == NULL);
2801 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2802 return 0;
2805 * if truncate on deeper level happened, it wasn't partial,
2806 * so we have to consider current index for truncation
2808 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2809 return 0;
2810 return 1;
2813 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2814 ext4_lblk_t end)
2816 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2817 int depth = ext_depth(inode);
2818 struct ext4_ext_path *path = NULL;
2819 long long partial_cluster = 0;
2820 handle_t *handle;
2821 int i = 0, err = 0;
2823 ext_debug("truncate since %u to %u\n", start, end);
2825 /* probably first extent we're gonna free will be last in block */
2826 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
2827 if (IS_ERR(handle))
2828 return PTR_ERR(handle);
2830 again:
2831 trace_ext4_ext_remove_space(inode, start, end, depth);
2834 * Check if we are removing extents inside the extent tree. If that
2835 * is the case, we are going to punch a hole inside the extent tree
2836 * so we have to check whether we need to split the extent covering
2837 * the last block to remove so we can easily remove the part of it
2838 * in ext4_ext_rm_leaf().
2840 if (end < EXT_MAX_BLOCKS - 1) {
2841 struct ext4_extent *ex;
2842 ext4_lblk_t ee_block, ex_end, lblk;
2843 ext4_fsblk_t pblk;
2845 /* find extent for or closest extent to this block */
2846 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
2847 if (IS_ERR(path)) {
2848 ext4_journal_stop(handle);
2849 return PTR_ERR(path);
2851 depth = ext_depth(inode);
2852 /* Leaf not may not exist only if inode has no blocks at all */
2853 ex = path[depth].p_ext;
2854 if (!ex) {
2855 if (depth) {
2856 EXT4_ERROR_INODE(inode,
2857 "path[%d].p_hdr == NULL",
2858 depth);
2859 err = -EFSCORRUPTED;
2861 goto out;
2864 ee_block = le32_to_cpu(ex->ee_block);
2865 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2868 * See if the last block is inside the extent, if so split
2869 * the extent at 'end' block so we can easily remove the
2870 * tail of the first part of the split extent in
2871 * ext4_ext_rm_leaf().
2873 if (end >= ee_block && end < ex_end) {
2876 * If we're going to split the extent, note that
2877 * the cluster containing the block after 'end' is
2878 * in use to avoid freeing it when removing blocks.
2880 if (sbi->s_cluster_ratio > 1) {
2881 pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
2882 partial_cluster =
2883 -(long long) EXT4_B2C(sbi, pblk);
2887 * Split the extent in two so that 'end' is the last
2888 * block in the first new extent. Also we should not
2889 * fail removing space due to ENOSPC so try to use
2890 * reserved block if that happens.
2892 err = ext4_force_split_extent_at(handle, inode, &path,
2893 end + 1, 1);
2894 if (err < 0)
2895 goto out;
2897 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end) {
2899 * If there's an extent to the right its first cluster
2900 * contains the immediate right boundary of the
2901 * truncated/punched region. Set partial_cluster to
2902 * its negative value so it won't be freed if shared
2903 * with the current extent. The end < ee_block case
2904 * is handled in ext4_ext_rm_leaf().
2906 lblk = ex_end + 1;
2907 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2908 &ex);
2909 if (err)
2910 goto out;
2911 if (pblk)
2912 partial_cluster =
2913 -(long long) EXT4_B2C(sbi, pblk);
2917 * We start scanning from right side, freeing all the blocks
2918 * after i_size and walking into the tree depth-wise.
2920 depth = ext_depth(inode);
2921 if (path) {
2922 int k = i = depth;
2923 while (--k > 0)
2924 path[k].p_block =
2925 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2926 } else {
2927 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2928 GFP_NOFS);
2929 if (path == NULL) {
2930 ext4_journal_stop(handle);
2931 return -ENOMEM;
2933 path[0].p_maxdepth = path[0].p_depth = depth;
2934 path[0].p_hdr = ext_inode_hdr(inode);
2935 i = 0;
2937 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2938 err = -EFSCORRUPTED;
2939 goto out;
2942 err = 0;
2944 while (i >= 0 && err == 0) {
2945 if (i == depth) {
2946 /* this is leaf block */
2947 err = ext4_ext_rm_leaf(handle, inode, path,
2948 &partial_cluster, start,
2949 end);
2950 /* root level has p_bh == NULL, brelse() eats this */
2951 brelse(path[i].p_bh);
2952 path[i].p_bh = NULL;
2953 i--;
2954 continue;
2957 /* this is index block */
2958 if (!path[i].p_hdr) {
2959 ext_debug("initialize header\n");
2960 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2963 if (!path[i].p_idx) {
2964 /* this level hasn't been touched yet */
2965 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2966 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2967 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2968 path[i].p_hdr,
2969 le16_to_cpu(path[i].p_hdr->eh_entries));
2970 } else {
2971 /* we were already here, see at next index */
2972 path[i].p_idx--;
2975 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2976 i, EXT_FIRST_INDEX(path[i].p_hdr),
2977 path[i].p_idx);
2978 if (ext4_ext_more_to_rm(path + i)) {
2979 struct buffer_head *bh;
2980 /* go to the next level */
2981 ext_debug("move to level %d (block %llu)\n",
2982 i + 1, ext4_idx_pblock(path[i].p_idx));
2983 memset(path + i + 1, 0, sizeof(*path));
2984 bh = read_extent_tree_block(inode,
2985 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
2986 EXT4_EX_NOCACHE);
2987 if (IS_ERR(bh)) {
2988 /* should we reset i_size? */
2989 err = PTR_ERR(bh);
2990 break;
2992 /* Yield here to deal with large extent trees.
2993 * Should be a no-op if we did IO above. */
2994 cond_resched();
2995 if (WARN_ON(i + 1 > depth)) {
2996 err = -EFSCORRUPTED;
2997 break;
2999 path[i + 1].p_bh = bh;
3001 /* save actual number of indexes since this
3002 * number is changed at the next iteration */
3003 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3004 i++;
3005 } else {
3006 /* we finished processing this index, go up */
3007 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3008 /* index is empty, remove it;
3009 * handle must be already prepared by the
3010 * truncatei_leaf() */
3011 err = ext4_ext_rm_idx(handle, inode, path, i);
3013 /* root level has p_bh == NULL, brelse() eats this */
3014 brelse(path[i].p_bh);
3015 path[i].p_bh = NULL;
3016 i--;
3017 ext_debug("return to level %d\n", i);
3021 trace_ext4_ext_remove_space_done(inode, start, end, depth,
3022 partial_cluster, path->p_hdr->eh_entries);
3025 * If we still have something in the partial cluster and we have removed
3026 * even the first extent, then we should free the blocks in the partial
3027 * cluster as well. (This code will only run when there are no leaves
3028 * to the immediate left of the truncated/punched region.)
3030 if (partial_cluster > 0 && err == 0) {
3031 /* don't zero partial_cluster since it's not used afterwards */
3032 ext4_free_blocks(handle, inode, NULL,
3033 EXT4_C2B(sbi, partial_cluster),
3034 sbi->s_cluster_ratio,
3035 get_default_free_blocks_flags(inode));
3038 /* TODO: flexible tree reduction should be here */
3039 if (path->p_hdr->eh_entries == 0) {
3041 * truncate to zero freed all the tree,
3042 * so we need to correct eh_depth
3044 err = ext4_ext_get_access(handle, inode, path);
3045 if (err == 0) {
3046 ext_inode_hdr(inode)->eh_depth = 0;
3047 ext_inode_hdr(inode)->eh_max =
3048 cpu_to_le16(ext4_ext_space_root(inode, 0));
3049 err = ext4_ext_dirty(handle, inode, path);
3052 out:
3053 ext4_ext_drop_refs(path);
3054 kfree(path);
3055 path = NULL;
3056 if (err == -EAGAIN)
3057 goto again;
3058 ext4_journal_stop(handle);
3060 return err;
3064 * called at mount time
3066 void ext4_ext_init(struct super_block *sb)
3069 * possible initialization would be here
3072 if (ext4_has_feature_extents(sb)) {
3073 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3074 printk(KERN_INFO "EXT4-fs: file extents enabled"
3075 #ifdef AGGRESSIVE_TEST
3076 ", aggressive tests"
3077 #endif
3078 #ifdef CHECK_BINSEARCH
3079 ", check binsearch"
3080 #endif
3081 #ifdef EXTENTS_STATS
3082 ", stats"
3083 #endif
3084 "\n");
3085 #endif
3086 #ifdef EXTENTS_STATS
3087 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3088 EXT4_SB(sb)->s_ext_min = 1 << 30;
3089 EXT4_SB(sb)->s_ext_max = 0;
3090 #endif
3095 * called at umount time
3097 void ext4_ext_release(struct super_block *sb)
3099 if (!ext4_has_feature_extents(sb))
3100 return;
3102 #ifdef EXTENTS_STATS
3103 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3104 struct ext4_sb_info *sbi = EXT4_SB(sb);
3105 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3106 sbi->s_ext_blocks, sbi->s_ext_extents,
3107 sbi->s_ext_blocks / sbi->s_ext_extents);
3108 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3109 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3111 #endif
3114 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3116 ext4_lblk_t ee_block;
3117 ext4_fsblk_t ee_pblock;
3118 unsigned int ee_len;
3120 ee_block = le32_to_cpu(ex->ee_block);
3121 ee_len = ext4_ext_get_actual_len(ex);
3122 ee_pblock = ext4_ext_pblock(ex);
3124 if (ee_len == 0)
3125 return 0;
3127 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3128 EXTENT_STATUS_WRITTEN);
3131 /* FIXME!! we need to try to merge to left or right after zero-out */
3132 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3134 ext4_fsblk_t ee_pblock;
3135 unsigned int ee_len;
3136 int ret;
3138 ee_len = ext4_ext_get_actual_len(ex);
3139 ee_pblock = ext4_ext_pblock(ex);
3141 if (ext4_encrypted_inode(inode))
3142 return ext4_encrypted_zeroout(inode, ex);
3144 ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
3145 if (ret > 0)
3146 ret = 0;
3148 return ret;
3152 * ext4_split_extent_at() splits an extent at given block.
3154 * @handle: the journal handle
3155 * @inode: the file inode
3156 * @path: the path to the extent
3157 * @split: the logical block where the extent is splitted.
3158 * @split_flags: indicates if the extent could be zeroout if split fails, and
3159 * the states(init or unwritten) of new extents.
3160 * @flags: flags used to insert new extent to extent tree.
3163 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3164 * of which are deterimined by split_flag.
3166 * There are two cases:
3167 * a> the extent are splitted into two extent.
3168 * b> split is not needed, and just mark the extent.
3170 * return 0 on success.
3172 static int ext4_split_extent_at(handle_t *handle,
3173 struct inode *inode,
3174 struct ext4_ext_path **ppath,
3175 ext4_lblk_t split,
3176 int split_flag,
3177 int flags)
3179 struct ext4_ext_path *path = *ppath;
3180 ext4_fsblk_t newblock;
3181 ext4_lblk_t ee_block;
3182 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3183 struct ext4_extent *ex2 = NULL;
3184 unsigned int ee_len, depth;
3185 int err = 0;
3187 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3188 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3190 ext_debug("ext4_split_extents_at: inode %lu, logical"
3191 "block %llu\n", inode->i_ino, (unsigned long long)split);
3193 ext4_ext_show_leaf(inode, path);
3195 depth = ext_depth(inode);
3196 ex = path[depth].p_ext;
3197 ee_block = le32_to_cpu(ex->ee_block);
3198 ee_len = ext4_ext_get_actual_len(ex);
3199 newblock = split - ee_block + ext4_ext_pblock(ex);
3201 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3202 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3203 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3204 EXT4_EXT_MARK_UNWRIT1 |
3205 EXT4_EXT_MARK_UNWRIT2));
3207 err = ext4_ext_get_access(handle, inode, path + depth);
3208 if (err)
3209 goto out;
3211 if (split == ee_block) {
3213 * case b: block @split is the block that the extent begins with
3214 * then we just change the state of the extent, and splitting
3215 * is not needed.
3217 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3218 ext4_ext_mark_unwritten(ex);
3219 else
3220 ext4_ext_mark_initialized(ex);
3222 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3223 ext4_ext_try_to_merge(handle, inode, path, ex);
3225 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3226 goto out;
3229 /* case a */
3230 memcpy(&orig_ex, ex, sizeof(orig_ex));
3231 ex->ee_len = cpu_to_le16(split - ee_block);
3232 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3233 ext4_ext_mark_unwritten(ex);
3236 * path may lead to new leaf, not to original leaf any more
3237 * after ext4_ext_insert_extent() returns,
3239 err = ext4_ext_dirty(handle, inode, path + depth);
3240 if (err)
3241 goto fix_extent_len;
3243 ex2 = &newex;
3244 ex2->ee_block = cpu_to_le32(split);
3245 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3246 ext4_ext_store_pblock(ex2, newblock);
3247 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3248 ext4_ext_mark_unwritten(ex2);
3250 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3251 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3252 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3253 if (split_flag & EXT4_EXT_DATA_VALID1) {
3254 err = ext4_ext_zeroout(inode, ex2);
3255 zero_ex.ee_block = ex2->ee_block;
3256 zero_ex.ee_len = cpu_to_le16(
3257 ext4_ext_get_actual_len(ex2));
3258 ext4_ext_store_pblock(&zero_ex,
3259 ext4_ext_pblock(ex2));
3260 } else {
3261 err = ext4_ext_zeroout(inode, ex);
3262 zero_ex.ee_block = ex->ee_block;
3263 zero_ex.ee_len = cpu_to_le16(
3264 ext4_ext_get_actual_len(ex));
3265 ext4_ext_store_pblock(&zero_ex,
3266 ext4_ext_pblock(ex));
3268 } else {
3269 err = ext4_ext_zeroout(inode, &orig_ex);
3270 zero_ex.ee_block = orig_ex.ee_block;
3271 zero_ex.ee_len = cpu_to_le16(
3272 ext4_ext_get_actual_len(&orig_ex));
3273 ext4_ext_store_pblock(&zero_ex,
3274 ext4_ext_pblock(&orig_ex));
3277 if (err)
3278 goto fix_extent_len;
3279 /* update the extent length and mark as initialized */
3280 ex->ee_len = cpu_to_le16(ee_len);
3281 ext4_ext_try_to_merge(handle, inode, path, ex);
3282 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3283 if (err)
3284 goto fix_extent_len;
3286 /* update extent status tree */
3287 err = ext4_zeroout_es(inode, &zero_ex);
3289 goto out;
3290 } else if (err)
3291 goto fix_extent_len;
3293 out:
3294 ext4_ext_show_leaf(inode, path);
3295 return err;
3297 fix_extent_len:
3298 ex->ee_len = orig_ex.ee_len;
3299 ext4_ext_dirty(handle, inode, path + path->p_depth);
3300 return err;
3304 * ext4_split_extents() splits an extent and mark extent which is covered
3305 * by @map as split_flags indicates
3307 * It may result in splitting the extent into multiple extents (up to three)
3308 * There are three possibilities:
3309 * a> There is no split required
3310 * b> Splits in two extents: Split is happening at either end of the extent
3311 * c> Splits in three extents: Somone is splitting in middle of the extent
3314 static int ext4_split_extent(handle_t *handle,
3315 struct inode *inode,
3316 struct ext4_ext_path **ppath,
3317 struct ext4_map_blocks *map,
3318 int split_flag,
3319 int flags)
3321 struct ext4_ext_path *path = *ppath;
3322 ext4_lblk_t ee_block;
3323 struct ext4_extent *ex;
3324 unsigned int ee_len, depth;
3325 int err = 0;
3326 int unwritten;
3327 int split_flag1, flags1;
3328 int allocated = map->m_len;
3330 depth = ext_depth(inode);
3331 ex = path[depth].p_ext;
3332 ee_block = le32_to_cpu(ex->ee_block);
3333 ee_len = ext4_ext_get_actual_len(ex);
3334 unwritten = ext4_ext_is_unwritten(ex);
3336 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3337 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3338 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3339 if (unwritten)
3340 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3341 EXT4_EXT_MARK_UNWRIT2;
3342 if (split_flag & EXT4_EXT_DATA_VALID2)
3343 split_flag1 |= EXT4_EXT_DATA_VALID1;
3344 err = ext4_split_extent_at(handle, inode, ppath,
3345 map->m_lblk + map->m_len, split_flag1, flags1);
3346 if (err)
3347 goto out;
3348 } else {
3349 allocated = ee_len - (map->m_lblk - ee_block);
3352 * Update path is required because previous ext4_split_extent_at() may
3353 * result in split of original leaf or extent zeroout.
3355 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3356 if (IS_ERR(path))
3357 return PTR_ERR(path);
3358 depth = ext_depth(inode);
3359 ex = path[depth].p_ext;
3360 if (!ex) {
3361 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3362 (unsigned long) map->m_lblk);
3363 return -EFSCORRUPTED;
3365 unwritten = ext4_ext_is_unwritten(ex);
3366 split_flag1 = 0;
3368 if (map->m_lblk >= ee_block) {
3369 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3370 if (unwritten) {
3371 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3372 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3373 EXT4_EXT_MARK_UNWRIT2);
3375 err = ext4_split_extent_at(handle, inode, ppath,
3376 map->m_lblk, split_flag1, flags);
3377 if (err)
3378 goto out;
3381 ext4_ext_show_leaf(inode, path);
3382 out:
3383 return err ? err : allocated;
3387 * This function is called by ext4_ext_map_blocks() if someone tries to write
3388 * to an unwritten extent. It may result in splitting the unwritten
3389 * extent into multiple extents (up to three - one initialized and two
3390 * unwritten).
3391 * There are three possibilities:
3392 * a> There is no split required: Entire extent should be initialized
3393 * b> Splits in two extents: Write is happening at either end of the extent
3394 * c> Splits in three extents: Somone is writing in middle of the extent
3396 * Pre-conditions:
3397 * - The extent pointed to by 'path' is unwritten.
3398 * - The extent pointed to by 'path' contains a superset
3399 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3401 * Post-conditions on success:
3402 * - the returned value is the number of blocks beyond map->l_lblk
3403 * that are allocated and initialized.
3404 * It is guaranteed to be >= map->m_len.
3406 static int ext4_ext_convert_to_initialized(handle_t *handle,
3407 struct inode *inode,
3408 struct ext4_map_blocks *map,
3409 struct ext4_ext_path **ppath,
3410 int flags)
3412 struct ext4_ext_path *path = *ppath;
3413 struct ext4_sb_info *sbi;
3414 struct ext4_extent_header *eh;
3415 struct ext4_map_blocks split_map;
3416 struct ext4_extent zero_ex;
3417 struct ext4_extent *ex, *abut_ex;
3418 ext4_lblk_t ee_block, eof_block;
3419 unsigned int ee_len, depth, map_len = map->m_len;
3420 int allocated = 0, max_zeroout = 0;
3421 int err = 0;
3422 int split_flag = 0;
3424 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3425 "block %llu, max_blocks %u\n", inode->i_ino,
3426 (unsigned long long)map->m_lblk, map_len);
3428 sbi = EXT4_SB(inode->i_sb);
3429 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3430 inode->i_sb->s_blocksize_bits;
3431 if (eof_block < map->m_lblk + map_len)
3432 eof_block = map->m_lblk + map_len;
3434 depth = ext_depth(inode);
3435 eh = path[depth].p_hdr;
3436 ex = path[depth].p_ext;
3437 ee_block = le32_to_cpu(ex->ee_block);
3438 ee_len = ext4_ext_get_actual_len(ex);
3439 zero_ex.ee_len = 0;
3441 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3443 /* Pre-conditions */
3444 BUG_ON(!ext4_ext_is_unwritten(ex));
3445 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3448 * Attempt to transfer newly initialized blocks from the currently
3449 * unwritten extent to its neighbor. This is much cheaper
3450 * than an insertion followed by a merge as those involve costly
3451 * memmove() calls. Transferring to the left is the common case in
3452 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3453 * followed by append writes.
3455 * Limitations of the current logic:
3456 * - L1: we do not deal with writes covering the whole extent.
3457 * This would require removing the extent if the transfer
3458 * is possible.
3459 * - L2: we only attempt to merge with an extent stored in the
3460 * same extent tree node.
3462 if ((map->m_lblk == ee_block) &&
3463 /* See if we can merge left */
3464 (map_len < ee_len) && /*L1*/
3465 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3466 ext4_lblk_t prev_lblk;
3467 ext4_fsblk_t prev_pblk, ee_pblk;
3468 unsigned int prev_len;
3470 abut_ex = ex - 1;
3471 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3472 prev_len = ext4_ext_get_actual_len(abut_ex);
3473 prev_pblk = ext4_ext_pblock(abut_ex);
3474 ee_pblk = ext4_ext_pblock(ex);
3477 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3478 * upon those conditions:
3479 * - C1: abut_ex is initialized,
3480 * - C2: abut_ex is logically abutting ex,
3481 * - C3: abut_ex is physically abutting ex,
3482 * - C4: abut_ex can receive the additional blocks without
3483 * overflowing the (initialized) length limit.
3485 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3486 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3487 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3488 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3489 err = ext4_ext_get_access(handle, inode, path + depth);
3490 if (err)
3491 goto out;
3493 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3494 map, ex, abut_ex);
3496 /* Shift the start of ex by 'map_len' blocks */
3497 ex->ee_block = cpu_to_le32(ee_block + map_len);
3498 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3499 ex->ee_len = cpu_to_le16(ee_len - map_len);
3500 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3502 /* Extend abut_ex by 'map_len' blocks */
3503 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3505 /* Result: number of initialized blocks past m_lblk */
3506 allocated = map_len;
3508 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3509 (map_len < ee_len) && /*L1*/
3510 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3511 /* See if we can merge right */
3512 ext4_lblk_t next_lblk;
3513 ext4_fsblk_t next_pblk, ee_pblk;
3514 unsigned int next_len;
3516 abut_ex = ex + 1;
3517 next_lblk = le32_to_cpu(abut_ex->ee_block);
3518 next_len = ext4_ext_get_actual_len(abut_ex);
3519 next_pblk = ext4_ext_pblock(abut_ex);
3520 ee_pblk = ext4_ext_pblock(ex);
3523 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3524 * upon those conditions:
3525 * - C1: abut_ex is initialized,
3526 * - C2: abut_ex is logically abutting ex,
3527 * - C3: abut_ex is physically abutting ex,
3528 * - C4: abut_ex can receive the additional blocks without
3529 * overflowing the (initialized) length limit.
3531 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3532 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3533 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3534 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3535 err = ext4_ext_get_access(handle, inode, path + depth);
3536 if (err)
3537 goto out;
3539 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3540 map, ex, abut_ex);
3542 /* Shift the start of abut_ex by 'map_len' blocks */
3543 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3544 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3545 ex->ee_len = cpu_to_le16(ee_len - map_len);
3546 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3548 /* Extend abut_ex by 'map_len' blocks */
3549 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3551 /* Result: number of initialized blocks past m_lblk */
3552 allocated = map_len;
3555 if (allocated) {
3556 /* Mark the block containing both extents as dirty */
3557 ext4_ext_dirty(handle, inode, path + depth);
3559 /* Update path to point to the right extent */
3560 path[depth].p_ext = abut_ex;
3561 goto out;
3562 } else
3563 allocated = ee_len - (map->m_lblk - ee_block);
3565 WARN_ON(map->m_lblk < ee_block);
3567 * It is safe to convert extent to initialized via explicit
3568 * zeroout only if extent is fully inside i_size or new_size.
3570 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3572 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3573 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3574 (inode->i_sb->s_blocksize_bits - 10);
3576 if (ext4_encrypted_inode(inode))
3577 max_zeroout = 0;
3579 /* If extent is less than s_max_zeroout_kb, zeroout directly */
3580 if (max_zeroout && (ee_len <= max_zeroout)) {
3581 err = ext4_ext_zeroout(inode, ex);
3582 if (err)
3583 goto out;
3584 zero_ex.ee_block = ex->ee_block;
3585 zero_ex.ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex));
3586 ext4_ext_store_pblock(&zero_ex, ext4_ext_pblock(ex));
3588 err = ext4_ext_get_access(handle, inode, path + depth);
3589 if (err)
3590 goto out;
3591 ext4_ext_mark_initialized(ex);
3592 ext4_ext_try_to_merge(handle, inode, path, ex);
3593 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3594 goto out;
3598 * four cases:
3599 * 1. split the extent into three extents.
3600 * 2. split the extent into two extents, zeroout the first half.
3601 * 3. split the extent into two extents, zeroout the second half.
3602 * 4. split the extent into two extents with out zeroout.
3604 split_map.m_lblk = map->m_lblk;
3605 split_map.m_len = map->m_len;
3607 if (max_zeroout && (allocated > map->m_len)) {
3608 if (allocated <= max_zeroout) {
3609 /* case 3 */
3610 zero_ex.ee_block =
3611 cpu_to_le32(map->m_lblk);
3612 zero_ex.ee_len = cpu_to_le16(allocated);
3613 ext4_ext_store_pblock(&zero_ex,
3614 ext4_ext_pblock(ex) + map->m_lblk - ee_block);
3615 err = ext4_ext_zeroout(inode, &zero_ex);
3616 if (err)
3617 goto out;
3618 split_map.m_lblk = map->m_lblk;
3619 split_map.m_len = allocated;
3620 } else if (map->m_lblk - ee_block + map->m_len < max_zeroout) {
3621 /* case 2 */
3622 if (map->m_lblk != ee_block) {
3623 zero_ex.ee_block = ex->ee_block;
3624 zero_ex.ee_len = cpu_to_le16(map->m_lblk -
3625 ee_block);
3626 ext4_ext_store_pblock(&zero_ex,
3627 ext4_ext_pblock(ex));
3628 err = ext4_ext_zeroout(inode, &zero_ex);
3629 if (err)
3630 goto out;
3633 split_map.m_lblk = ee_block;
3634 split_map.m_len = map->m_lblk - ee_block + map->m_len;
3635 allocated = map->m_len;
3639 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3640 flags);
3641 if (err > 0)
3642 err = 0;
3643 out:
3644 /* If we have gotten a failure, don't zero out status tree */
3645 if (!err)
3646 err = ext4_zeroout_es(inode, &zero_ex);
3647 return err ? err : allocated;
3651 * This function is called by ext4_ext_map_blocks() from
3652 * ext4_get_blocks_dio_write() when DIO to write
3653 * to an unwritten extent.
3655 * Writing to an unwritten extent may result in splitting the unwritten
3656 * extent into multiple initialized/unwritten extents (up to three)
3657 * There are three possibilities:
3658 * a> There is no split required: Entire extent should be unwritten
3659 * b> Splits in two extents: Write is happening at either end of the extent
3660 * c> Splits in three extents: Somone is writing in middle of the extent
3662 * This works the same way in the case of initialized -> unwritten conversion.
3664 * One of more index blocks maybe needed if the extent tree grow after
3665 * the unwritten extent split. To prevent ENOSPC occur at the IO
3666 * complete, we need to split the unwritten extent before DIO submit
3667 * the IO. The unwritten extent called at this time will be split
3668 * into three unwritten extent(at most). After IO complete, the part
3669 * being filled will be convert to initialized by the end_io callback function
3670 * via ext4_convert_unwritten_extents().
3672 * Returns the size of unwritten extent to be written on success.
3674 static int ext4_split_convert_extents(handle_t *handle,
3675 struct inode *inode,
3676 struct ext4_map_blocks *map,
3677 struct ext4_ext_path **ppath,
3678 int flags)
3680 struct ext4_ext_path *path = *ppath;
3681 ext4_lblk_t eof_block;
3682 ext4_lblk_t ee_block;
3683 struct ext4_extent *ex;
3684 unsigned int ee_len;
3685 int split_flag = 0, depth;
3687 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3688 __func__, inode->i_ino,
3689 (unsigned long long)map->m_lblk, map->m_len);
3691 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3692 inode->i_sb->s_blocksize_bits;
3693 if (eof_block < map->m_lblk + map->m_len)
3694 eof_block = map->m_lblk + map->m_len;
3696 * It is safe to convert extent to initialized via explicit
3697 * zeroout only if extent is fully insde i_size or new_size.
3699 depth = ext_depth(inode);
3700 ex = path[depth].p_ext;
3701 ee_block = le32_to_cpu(ex->ee_block);
3702 ee_len = ext4_ext_get_actual_len(ex);
3704 /* Convert to unwritten */
3705 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3706 split_flag |= EXT4_EXT_DATA_VALID1;
3707 /* Convert to initialized */
3708 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3709 split_flag |= ee_block + ee_len <= eof_block ?
3710 EXT4_EXT_MAY_ZEROOUT : 0;
3711 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3713 flags |= EXT4_GET_BLOCKS_PRE_IO;
3714 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3717 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3718 struct inode *inode,
3719 struct ext4_map_blocks *map,
3720 struct ext4_ext_path **ppath)
3722 struct ext4_ext_path *path = *ppath;
3723 struct ext4_extent *ex;
3724 ext4_lblk_t ee_block;
3725 unsigned int ee_len;
3726 int depth;
3727 int err = 0;
3729 depth = ext_depth(inode);
3730 ex = path[depth].p_ext;
3731 ee_block = le32_to_cpu(ex->ee_block);
3732 ee_len = ext4_ext_get_actual_len(ex);
3734 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3735 "block %llu, max_blocks %u\n", inode->i_ino,
3736 (unsigned long long)ee_block, ee_len);
3738 /* If extent is larger than requested it is a clear sign that we still
3739 * have some extent state machine issues left. So extent_split is still
3740 * required.
3741 * TODO: Once all related issues will be fixed this situation should be
3742 * illegal.
3744 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3745 #ifdef EXT4_DEBUG
3746 ext4_warning("Inode (%ld) finished: extent logical block %llu,"
3747 " len %u; IO logical block %llu, len %u\n",
3748 inode->i_ino, (unsigned long long)ee_block, ee_len,
3749 (unsigned long long)map->m_lblk, map->m_len);
3750 #endif
3751 err = ext4_split_convert_extents(handle, inode, map, ppath,
3752 EXT4_GET_BLOCKS_CONVERT);
3753 if (err < 0)
3754 return err;
3755 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3756 if (IS_ERR(path))
3757 return PTR_ERR(path);
3758 depth = ext_depth(inode);
3759 ex = path[depth].p_ext;
3762 err = ext4_ext_get_access(handle, inode, path + depth);
3763 if (err)
3764 goto out;
3765 /* first mark the extent as initialized */
3766 ext4_ext_mark_initialized(ex);
3768 /* note: ext4_ext_correct_indexes() isn't needed here because
3769 * borders are not changed
3771 ext4_ext_try_to_merge(handle, inode, path, ex);
3773 /* Mark modified extent as dirty */
3774 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3775 out:
3776 ext4_ext_show_leaf(inode, path);
3777 return err;
3780 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3781 sector_t block, int count)
3783 int i;
3784 for (i = 0; i < count; i++)
3785 unmap_underlying_metadata(bdev, block + i);
3789 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3791 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3792 ext4_lblk_t lblk,
3793 struct ext4_ext_path *path,
3794 unsigned int len)
3796 int i, depth;
3797 struct ext4_extent_header *eh;
3798 struct ext4_extent *last_ex;
3800 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3801 return 0;
3803 depth = ext_depth(inode);
3804 eh = path[depth].p_hdr;
3807 * We're going to remove EOFBLOCKS_FL entirely in future so we
3808 * do not care for this case anymore. Simply remove the flag
3809 * if there are no extents.
3811 if (unlikely(!eh->eh_entries))
3812 goto out;
3813 last_ex = EXT_LAST_EXTENT(eh);
3815 * We should clear the EOFBLOCKS_FL flag if we are writing the
3816 * last block in the last extent in the file. We test this by
3817 * first checking to see if the caller to
3818 * ext4_ext_get_blocks() was interested in the last block (or
3819 * a block beyond the last block) in the current extent. If
3820 * this turns out to be false, we can bail out from this
3821 * function immediately.
3823 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3824 ext4_ext_get_actual_len(last_ex))
3825 return 0;
3827 * If the caller does appear to be planning to write at or
3828 * beyond the end of the current extent, we then test to see
3829 * if the current extent is the last extent in the file, by
3830 * checking to make sure it was reached via the rightmost node
3831 * at each level of the tree.
3833 for (i = depth-1; i >= 0; i--)
3834 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3835 return 0;
3836 out:
3837 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3838 return ext4_mark_inode_dirty(handle, inode);
3842 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3844 * Return 1 if there is a delalloc block in the range, otherwise 0.
3846 int ext4_find_delalloc_range(struct inode *inode,
3847 ext4_lblk_t lblk_start,
3848 ext4_lblk_t lblk_end)
3850 struct extent_status es;
3852 ext4_es_find_delayed_extent_range(inode, lblk_start, lblk_end, &es);
3853 if (es.es_len == 0)
3854 return 0; /* there is no delay extent in this tree */
3855 else if (es.es_lblk <= lblk_start &&
3856 lblk_start < es.es_lblk + es.es_len)
3857 return 1;
3858 else if (lblk_start <= es.es_lblk && es.es_lblk <= lblk_end)
3859 return 1;
3860 else
3861 return 0;
3864 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk)
3866 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3867 ext4_lblk_t lblk_start, lblk_end;
3868 lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
3869 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3871 return ext4_find_delalloc_range(inode, lblk_start, lblk_end);
3875 * Determines how many complete clusters (out of those specified by the 'map')
3876 * are under delalloc and were reserved quota for.
3877 * This function is called when we are writing out the blocks that were
3878 * originally written with their allocation delayed, but then the space was
3879 * allocated using fallocate() before the delayed allocation could be resolved.
3880 * The cases to look for are:
3881 * ('=' indicated delayed allocated blocks
3882 * '-' indicates non-delayed allocated blocks)
3883 * (a) partial clusters towards beginning and/or end outside of allocated range
3884 * are not delalloc'ed.
3885 * Ex:
3886 * |----c---=|====c====|====c====|===-c----|
3887 * |++++++ allocated ++++++|
3888 * ==> 4 complete clusters in above example
3890 * (b) partial cluster (outside of allocated range) towards either end is
3891 * marked for delayed allocation. In this case, we will exclude that
3892 * cluster.
3893 * Ex:
3894 * |----====c========|========c========|
3895 * |++++++ allocated ++++++|
3896 * ==> 1 complete clusters in above example
3898 * Ex:
3899 * |================c================|
3900 * |++++++ allocated ++++++|
3901 * ==> 0 complete clusters in above example
3903 * The ext4_da_update_reserve_space will be called only if we
3904 * determine here that there were some "entire" clusters that span
3905 * this 'allocated' range.
3906 * In the non-bigalloc case, this function will just end up returning num_blks
3907 * without ever calling ext4_find_delalloc_range.
3909 static unsigned int
3910 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3911 unsigned int num_blks)
3913 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3914 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3915 ext4_lblk_t lblk_from, lblk_to, c_offset;
3916 unsigned int allocated_clusters = 0;
3918 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3919 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3921 /* max possible clusters for this allocation */
3922 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3924 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3926 /* Check towards left side */
3927 c_offset = EXT4_LBLK_COFF(sbi, lblk_start);
3928 if (c_offset) {
3929 lblk_from = EXT4_LBLK_CMASK(sbi, lblk_start);
3930 lblk_to = lblk_from + c_offset - 1;
3932 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3933 allocated_clusters--;
3936 /* Now check towards right. */
3937 c_offset = EXT4_LBLK_COFF(sbi, lblk_start + num_blks);
3938 if (allocated_clusters && c_offset) {
3939 lblk_from = lblk_start + num_blks;
3940 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3942 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3943 allocated_clusters--;
3946 return allocated_clusters;
3949 static int
3950 convert_initialized_extent(handle_t *handle, struct inode *inode,
3951 struct ext4_map_blocks *map,
3952 struct ext4_ext_path **ppath, int flags,
3953 unsigned int allocated, ext4_fsblk_t newblock)
3955 struct ext4_ext_path *path = *ppath;
3956 struct ext4_extent *ex;
3957 ext4_lblk_t ee_block;
3958 unsigned int ee_len;
3959 int depth;
3960 int err = 0;
3963 * Make sure that the extent is no bigger than we support with
3964 * unwritten extent
3966 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3967 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3969 depth = ext_depth(inode);
3970 ex = path[depth].p_ext;
3971 ee_block = le32_to_cpu(ex->ee_block);
3972 ee_len = ext4_ext_get_actual_len(ex);
3974 ext_debug("%s: inode %lu, logical"
3975 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3976 (unsigned long long)ee_block, ee_len);
3978 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3979 err = ext4_split_convert_extents(handle, inode, map, ppath,
3980 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3981 if (err < 0)
3982 return err;
3983 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3984 if (IS_ERR(path))
3985 return PTR_ERR(path);
3986 depth = ext_depth(inode);
3987 ex = path[depth].p_ext;
3988 if (!ex) {
3989 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3990 (unsigned long) map->m_lblk);
3991 return -EFSCORRUPTED;
3995 err = ext4_ext_get_access(handle, inode, path + depth);
3996 if (err)
3997 return err;
3998 /* first mark the extent as unwritten */
3999 ext4_ext_mark_unwritten(ex);
4001 /* note: ext4_ext_correct_indexes() isn't needed here because
4002 * borders are not changed
4004 ext4_ext_try_to_merge(handle, inode, path, ex);
4006 /* Mark modified extent as dirty */
4007 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4008 if (err)
4009 return err;
4010 ext4_ext_show_leaf(inode, path);
4012 ext4_update_inode_fsync_trans(handle, inode, 1);
4013 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4014 if (err)
4015 return err;
4016 map->m_flags |= EXT4_MAP_UNWRITTEN;
4017 if (allocated > map->m_len)
4018 allocated = map->m_len;
4019 map->m_len = allocated;
4020 return allocated;
4023 static int
4024 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4025 struct ext4_map_blocks *map,
4026 struct ext4_ext_path **ppath, int flags,
4027 unsigned int allocated, ext4_fsblk_t newblock)
4029 struct ext4_ext_path *path = *ppath;
4030 int ret = 0;
4031 int err = 0;
4032 ext4_io_end_t *io = ext4_inode_aio(inode);
4034 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4035 "block %llu, max_blocks %u, flags %x, allocated %u\n",
4036 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4037 flags, allocated);
4038 ext4_ext_show_leaf(inode, path);
4041 * When writing into unwritten space, we should not fail to
4042 * allocate metadata blocks for the new extent block if needed.
4044 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4046 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4047 allocated, newblock);
4049 /* get_block() before submit the IO, split the extent */
4050 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4051 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4052 flags | EXT4_GET_BLOCKS_CONVERT);
4053 if (ret <= 0)
4054 goto out;
4056 * Flag the inode(non aio case) or end_io struct (aio case)
4057 * that this IO needs to conversion to written when IO is
4058 * completed
4060 if (io)
4061 ext4_set_io_unwritten_flag(inode, io);
4062 else
4063 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
4064 map->m_flags |= EXT4_MAP_UNWRITTEN;
4065 goto out;
4067 /* IO end_io complete, convert the filled extent to written */
4068 if (flags & EXT4_GET_BLOCKS_CONVERT) {
4069 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4070 ppath);
4071 if (ret >= 0) {
4072 ext4_update_inode_fsync_trans(handle, inode, 1);
4073 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4074 path, map->m_len);
4075 } else
4076 err = ret;
4077 map->m_flags |= EXT4_MAP_MAPPED;
4078 map->m_pblk = newblock;
4079 if (allocated > map->m_len)
4080 allocated = map->m_len;
4081 map->m_len = allocated;
4082 goto out2;
4084 /* buffered IO case */
4086 * repeat fallocate creation request
4087 * we already have an unwritten extent
4089 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4090 map->m_flags |= EXT4_MAP_UNWRITTEN;
4091 goto map_out;
4094 /* buffered READ or buffered write_begin() lookup */
4095 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4097 * We have blocks reserved already. We
4098 * return allocated blocks so that delalloc
4099 * won't do block reservation for us. But
4100 * the buffer head will be unmapped so that
4101 * a read from the block returns 0s.
4103 map->m_flags |= EXT4_MAP_UNWRITTEN;
4104 goto out1;
4107 /* buffered write, writepage time, convert*/
4108 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4109 if (ret >= 0)
4110 ext4_update_inode_fsync_trans(handle, inode, 1);
4111 out:
4112 if (ret <= 0) {
4113 err = ret;
4114 goto out2;
4115 } else
4116 allocated = ret;
4117 map->m_flags |= EXT4_MAP_NEW;
4119 * if we allocated more blocks than requested
4120 * we need to make sure we unmap the extra block
4121 * allocated. The actual needed block will get
4122 * unmapped later when we find the buffer_head marked
4123 * new.
4125 if (allocated > map->m_len) {
4126 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
4127 newblock + map->m_len,
4128 allocated - map->m_len);
4129 allocated = map->m_len;
4131 map->m_len = allocated;
4134 * If we have done fallocate with the offset that is already
4135 * delayed allocated, we would have block reservation
4136 * and quota reservation done in the delayed write path.
4137 * But fallocate would have already updated quota and block
4138 * count for this offset. So cancel these reservation
4140 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4141 unsigned int reserved_clusters;
4142 reserved_clusters = get_reserved_cluster_alloc(inode,
4143 map->m_lblk, map->m_len);
4144 if (reserved_clusters)
4145 ext4_da_update_reserve_space(inode,
4146 reserved_clusters,
4150 map_out:
4151 map->m_flags |= EXT4_MAP_MAPPED;
4152 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4153 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4154 map->m_len);
4155 if (err < 0)
4156 goto out2;
4158 out1:
4159 if (allocated > map->m_len)
4160 allocated = map->m_len;
4161 ext4_ext_show_leaf(inode, path);
4162 map->m_pblk = newblock;
4163 map->m_len = allocated;
4164 out2:
4165 return err ? err : allocated;
4169 * get_implied_cluster_alloc - check to see if the requested
4170 * allocation (in the map structure) overlaps with a cluster already
4171 * allocated in an extent.
4172 * @sb The filesystem superblock structure
4173 * @map The requested lblk->pblk mapping
4174 * @ex The extent structure which might contain an implied
4175 * cluster allocation
4177 * This function is called by ext4_ext_map_blocks() after we failed to
4178 * find blocks that were already in the inode's extent tree. Hence,
4179 * we know that the beginning of the requested region cannot overlap
4180 * the extent from the inode's extent tree. There are three cases we
4181 * want to catch. The first is this case:
4183 * |--- cluster # N--|
4184 * |--- extent ---| |---- requested region ---|
4185 * |==========|
4187 * The second case that we need to test for is this one:
4189 * |--------- cluster # N ----------------|
4190 * |--- requested region --| |------- extent ----|
4191 * |=======================|
4193 * The third case is when the requested region lies between two extents
4194 * within the same cluster:
4195 * |------------- cluster # N-------------|
4196 * |----- ex -----| |---- ex_right ----|
4197 * |------ requested region ------|
4198 * |================|
4200 * In each of the above cases, we need to set the map->m_pblk and
4201 * map->m_len so it corresponds to the return the extent labelled as
4202 * "|====|" from cluster #N, since it is already in use for data in
4203 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4204 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4205 * as a new "allocated" block region. Otherwise, we will return 0 and
4206 * ext4_ext_map_blocks() will then allocate one or more new clusters
4207 * by calling ext4_mb_new_blocks().
4209 static int get_implied_cluster_alloc(struct super_block *sb,
4210 struct ext4_map_blocks *map,
4211 struct ext4_extent *ex,
4212 struct ext4_ext_path *path)
4214 struct ext4_sb_info *sbi = EXT4_SB(sb);
4215 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4216 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4217 ext4_lblk_t rr_cluster_start;
4218 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4219 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4220 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4222 /* The extent passed in that we are trying to match */
4223 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4224 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4226 /* The requested region passed into ext4_map_blocks() */
4227 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4229 if ((rr_cluster_start == ex_cluster_end) ||
4230 (rr_cluster_start == ex_cluster_start)) {
4231 if (rr_cluster_start == ex_cluster_end)
4232 ee_start += ee_len - 1;
4233 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4234 map->m_len = min(map->m_len,
4235 (unsigned) sbi->s_cluster_ratio - c_offset);
4237 * Check for and handle this case:
4239 * |--------- cluster # N-------------|
4240 * |------- extent ----|
4241 * |--- requested region ---|
4242 * |===========|
4245 if (map->m_lblk < ee_block)
4246 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4249 * Check for the case where there is already another allocated
4250 * block to the right of 'ex' but before the end of the cluster.
4252 * |------------- cluster # N-------------|
4253 * |----- ex -----| |---- ex_right ----|
4254 * |------ requested region ------|
4255 * |================|
4257 if (map->m_lblk > ee_block) {
4258 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4259 map->m_len = min(map->m_len, next - map->m_lblk);
4262 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4263 return 1;
4266 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4267 return 0;
4272 * Block allocation/map/preallocation routine for extents based files
4275 * Need to be called with
4276 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4277 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4279 * return > 0, number of of blocks already mapped/allocated
4280 * if create == 0 and these are pre-allocated blocks
4281 * buffer head is unmapped
4282 * otherwise blocks are mapped
4284 * return = 0, if plain look up failed (blocks have not been allocated)
4285 * buffer head is unmapped
4287 * return < 0, error case.
4289 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4290 struct ext4_map_blocks *map, int flags)
4292 struct ext4_ext_path *path = NULL;
4293 struct ext4_extent newex, *ex, *ex2;
4294 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4295 ext4_fsblk_t newblock = 0;
4296 int free_on_err = 0, err = 0, depth, ret;
4297 unsigned int allocated = 0, offset = 0;
4298 unsigned int allocated_clusters = 0;
4299 struct ext4_allocation_request ar;
4300 ext4_io_end_t *io = ext4_inode_aio(inode);
4301 ext4_lblk_t cluster_offset;
4302 int set_unwritten = 0;
4303 bool map_from_cluster = false;
4305 ext_debug("blocks %u/%u requested for inode %lu\n",
4306 map->m_lblk, map->m_len, inode->i_ino);
4307 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4309 /* find extent for this block */
4310 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4311 if (IS_ERR(path)) {
4312 err = PTR_ERR(path);
4313 path = NULL;
4314 goto out2;
4317 depth = ext_depth(inode);
4320 * consistent leaf must not be empty;
4321 * this situation is possible, though, _during_ tree modification;
4322 * this is why assert can't be put in ext4_find_extent()
4324 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4325 EXT4_ERROR_INODE(inode, "bad extent address "
4326 "lblock: %lu, depth: %d pblock %lld",
4327 (unsigned long) map->m_lblk, depth,
4328 path[depth].p_block);
4329 err = -EFSCORRUPTED;
4330 goto out2;
4333 ex = path[depth].p_ext;
4334 if (ex) {
4335 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4336 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4337 unsigned short ee_len;
4341 * unwritten extents are treated as holes, except that
4342 * we split out initialized portions during a write.
4344 ee_len = ext4_ext_get_actual_len(ex);
4346 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4348 /* if found extent covers block, simply return it */
4349 if (in_range(map->m_lblk, ee_block, ee_len)) {
4350 newblock = map->m_lblk - ee_block + ee_start;
4351 /* number of remaining blocks in the extent */
4352 allocated = ee_len - (map->m_lblk - ee_block);
4353 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4354 ee_block, ee_len, newblock);
4357 * If the extent is initialized check whether the
4358 * caller wants to convert it to unwritten.
4360 if ((!ext4_ext_is_unwritten(ex)) &&
4361 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4362 allocated = convert_initialized_extent(
4363 handle, inode, map, &path,
4364 flags, allocated, newblock);
4365 goto out2;
4366 } else if (!ext4_ext_is_unwritten(ex))
4367 goto out;
4369 ret = ext4_ext_handle_unwritten_extents(
4370 handle, inode, map, &path, flags,
4371 allocated, newblock);
4372 if (ret < 0)
4373 err = ret;
4374 else
4375 allocated = ret;
4376 goto out2;
4381 * requested block isn't allocated yet;
4382 * we couldn't try to create block if create flag is zero
4384 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4386 * put just found gap into cache to speed up
4387 * subsequent requests
4389 ext4_ext_put_gap_in_cache(inode, path, map->m_lblk);
4390 goto out2;
4394 * Okay, we need to do block allocation.
4396 newex.ee_block = cpu_to_le32(map->m_lblk);
4397 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4400 * If we are doing bigalloc, check to see if the extent returned
4401 * by ext4_find_extent() implies a cluster we can use.
4403 if (cluster_offset && ex &&
4404 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4405 ar.len = allocated = map->m_len;
4406 newblock = map->m_pblk;
4407 map_from_cluster = true;
4408 goto got_allocated_blocks;
4411 /* find neighbour allocated blocks */
4412 ar.lleft = map->m_lblk;
4413 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4414 if (err)
4415 goto out2;
4416 ar.lright = map->m_lblk;
4417 ex2 = NULL;
4418 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4419 if (err)
4420 goto out2;
4422 /* Check if the extent after searching to the right implies a
4423 * cluster we can use. */
4424 if ((sbi->s_cluster_ratio > 1) && ex2 &&
4425 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4426 ar.len = allocated = map->m_len;
4427 newblock = map->m_pblk;
4428 map_from_cluster = true;
4429 goto got_allocated_blocks;
4433 * See if request is beyond maximum number of blocks we can have in
4434 * a single extent. For an initialized extent this limit is
4435 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4436 * EXT_UNWRITTEN_MAX_LEN.
4438 if (map->m_len > EXT_INIT_MAX_LEN &&
4439 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4440 map->m_len = EXT_INIT_MAX_LEN;
4441 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4442 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4443 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4445 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4446 newex.ee_len = cpu_to_le16(map->m_len);
4447 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4448 if (err)
4449 allocated = ext4_ext_get_actual_len(&newex);
4450 else
4451 allocated = map->m_len;
4453 /* allocate new block */
4454 ar.inode = inode;
4455 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4456 ar.logical = map->m_lblk;
4458 * We calculate the offset from the beginning of the cluster
4459 * for the logical block number, since when we allocate a
4460 * physical cluster, the physical block should start at the
4461 * same offset from the beginning of the cluster. This is
4462 * needed so that future calls to get_implied_cluster_alloc()
4463 * work correctly.
4465 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4466 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4467 ar.goal -= offset;
4468 ar.logical -= offset;
4469 if (S_ISREG(inode->i_mode))
4470 ar.flags = EXT4_MB_HINT_DATA;
4471 else
4472 /* disable in-core preallocation for non-regular files */
4473 ar.flags = 0;
4474 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4475 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4476 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4477 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4478 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4479 ar.flags |= EXT4_MB_USE_RESERVED;
4480 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4481 if (!newblock)
4482 goto out2;
4483 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4484 ar.goal, newblock, allocated);
4485 free_on_err = 1;
4486 allocated_clusters = ar.len;
4487 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4488 if (ar.len > allocated)
4489 ar.len = allocated;
4491 got_allocated_blocks:
4492 /* try to insert new extent into found leaf and return */
4493 ext4_ext_store_pblock(&newex, newblock + offset);
4494 newex.ee_len = cpu_to_le16(ar.len);
4495 /* Mark unwritten */
4496 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4497 ext4_ext_mark_unwritten(&newex);
4498 map->m_flags |= EXT4_MAP_UNWRITTEN;
4500 * io_end structure was created for every IO write to an
4501 * unwritten extent. To avoid unnecessary conversion,
4502 * here we flag the IO that really needs the conversion.
4503 * For non asycn direct IO case, flag the inode state
4504 * that we need to perform conversion when IO is done.
4506 if (flags & EXT4_GET_BLOCKS_PRE_IO)
4507 set_unwritten = 1;
4510 err = 0;
4511 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4512 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4513 path, ar.len);
4514 if (!err)
4515 err = ext4_ext_insert_extent(handle, inode, &path,
4516 &newex, flags);
4518 if (!err && set_unwritten) {
4519 if (io)
4520 ext4_set_io_unwritten_flag(inode, io);
4521 else
4522 ext4_set_inode_state(inode,
4523 EXT4_STATE_DIO_UNWRITTEN);
4526 if (err && free_on_err) {
4527 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4528 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4529 /* free data blocks we just allocated */
4530 /* not a good idea to call discard here directly,
4531 * but otherwise we'd need to call it every free() */
4532 ext4_discard_preallocations(inode);
4533 ext4_free_blocks(handle, inode, NULL, newblock,
4534 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4535 goto out2;
4538 /* previous routine could use block we allocated */
4539 newblock = ext4_ext_pblock(&newex);
4540 allocated = ext4_ext_get_actual_len(&newex);
4541 if (allocated > map->m_len)
4542 allocated = map->m_len;
4543 map->m_flags |= EXT4_MAP_NEW;
4546 * Update reserved blocks/metadata blocks after successful
4547 * block allocation which had been deferred till now.
4549 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4550 unsigned int reserved_clusters;
4552 * Check how many clusters we had reserved this allocated range
4554 reserved_clusters = get_reserved_cluster_alloc(inode,
4555 map->m_lblk, allocated);
4556 if (!map_from_cluster) {
4557 BUG_ON(allocated_clusters < reserved_clusters);
4558 if (reserved_clusters < allocated_clusters) {
4559 struct ext4_inode_info *ei = EXT4_I(inode);
4560 int reservation = allocated_clusters -
4561 reserved_clusters;
4563 * It seems we claimed few clusters outside of
4564 * the range of this allocation. We should give
4565 * it back to the reservation pool. This can
4566 * happen in the following case:
4568 * * Suppose s_cluster_ratio is 4 (i.e., each
4569 * cluster has 4 blocks. Thus, the clusters
4570 * are [0-3],[4-7],[8-11]...
4571 * * First comes delayed allocation write for
4572 * logical blocks 10 & 11. Since there were no
4573 * previous delayed allocated blocks in the
4574 * range [8-11], we would reserve 1 cluster
4575 * for this write.
4576 * * Next comes write for logical blocks 3 to 8.
4577 * In this case, we will reserve 2 clusters
4578 * (for [0-3] and [4-7]; and not for [8-11] as
4579 * that range has a delayed allocated blocks.
4580 * Thus total reserved clusters now becomes 3.
4581 * * Now, during the delayed allocation writeout
4582 * time, we will first write blocks [3-8] and
4583 * allocate 3 clusters for writing these
4584 * blocks. Also, we would claim all these
4585 * three clusters above.
4586 * * Now when we come here to writeout the
4587 * blocks [10-11], we would expect to claim
4588 * the reservation of 1 cluster we had made
4589 * (and we would claim it since there are no
4590 * more delayed allocated blocks in the range
4591 * [8-11]. But our reserved cluster count had
4592 * already gone to 0.
4594 * Thus, at the step 4 above when we determine
4595 * that there are still some unwritten delayed
4596 * allocated blocks outside of our current
4597 * block range, we should increment the
4598 * reserved clusters count so that when the
4599 * remaining blocks finally gets written, we
4600 * could claim them.
4602 dquot_reserve_block(inode,
4603 EXT4_C2B(sbi, reservation));
4604 spin_lock(&ei->i_block_reservation_lock);
4605 ei->i_reserved_data_blocks += reservation;
4606 spin_unlock(&ei->i_block_reservation_lock);
4609 * We will claim quota for all newly allocated blocks.
4610 * We're updating the reserved space *after* the
4611 * correction above so we do not accidentally free
4612 * all the metadata reservation because we might
4613 * actually need it later on.
4615 ext4_da_update_reserve_space(inode, allocated_clusters,
4621 * Cache the extent and update transaction to commit on fdatasync only
4622 * when it is _not_ an unwritten extent.
4624 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4625 ext4_update_inode_fsync_trans(handle, inode, 1);
4626 else
4627 ext4_update_inode_fsync_trans(handle, inode, 0);
4628 out:
4629 if (allocated > map->m_len)
4630 allocated = map->m_len;
4631 ext4_ext_show_leaf(inode, path);
4632 map->m_flags |= EXT4_MAP_MAPPED;
4633 map->m_pblk = newblock;
4634 map->m_len = allocated;
4635 out2:
4636 ext4_ext_drop_refs(path);
4637 kfree(path);
4639 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4640 err ? err : allocated);
4641 return err ? err : allocated;
4644 void ext4_ext_truncate(handle_t *handle, struct inode *inode)
4646 struct super_block *sb = inode->i_sb;
4647 ext4_lblk_t last_block;
4648 int err = 0;
4651 * TODO: optimization is possible here.
4652 * Probably we need not scan at all,
4653 * because page truncation is enough.
4656 /* we have to know where to truncate from in crash case */
4657 EXT4_I(inode)->i_disksize = inode->i_size;
4658 ext4_mark_inode_dirty(handle, inode);
4660 last_block = (inode->i_size + sb->s_blocksize - 1)
4661 >> EXT4_BLOCK_SIZE_BITS(sb);
4662 retry:
4663 err = ext4_es_remove_extent(inode, last_block,
4664 EXT_MAX_BLOCKS - last_block);
4665 if (err == -ENOMEM) {
4666 cond_resched();
4667 congestion_wait(BLK_RW_ASYNC, HZ/50);
4668 goto retry;
4670 if (err) {
4671 ext4_std_error(inode->i_sb, err);
4672 return;
4674 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4675 ext4_std_error(inode->i_sb, err);
4678 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4679 ext4_lblk_t len, loff_t new_size,
4680 int flags, int mode)
4682 struct inode *inode = file_inode(file);
4683 handle_t *handle;
4684 int ret = 0;
4685 int ret2 = 0;
4686 int retries = 0;
4687 int depth = 0;
4688 struct ext4_map_blocks map;
4689 unsigned int credits;
4690 loff_t epos;
4692 map.m_lblk = offset;
4693 map.m_len = len;
4695 * Don't normalize the request if it can fit in one extent so
4696 * that it doesn't get unnecessarily split into multiple
4697 * extents.
4699 if (len <= EXT_UNWRITTEN_MAX_LEN)
4700 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4703 * credits to insert 1 extent into extent tree
4705 credits = ext4_chunk_trans_blocks(inode, len);
4707 * We can only call ext_depth() on extent based inodes
4709 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4710 depth = ext_depth(inode);
4711 else
4712 depth = -1;
4714 retry:
4715 while (ret >= 0 && len) {
4717 * Recalculate credits when extent tree depth changes.
4719 if (depth >= 0 && 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 = ext4_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 mutex_lock(&inode->i_mutex);
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, mode);
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 = ext4_current_time(inode);
4875 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4876 flags, mode);
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 = ext4_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 mutex_unlock(&inode->i_mutex);
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 * We can't just convert len to max_blocks because
4985 * If blocksize = 4096 offset = 3072 and len = 2048
4987 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
4988 - lblk;
4990 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4991 if (mode & FALLOC_FL_KEEP_SIZE)
4992 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4994 mutex_lock(&inode->i_mutex);
4997 * We only support preallocation for extent-based files only
4999 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5000 ret = -EOPNOTSUPP;
5001 goto out;
5004 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
5005 (offset + len > i_size_read(inode) ||
5006 offset + len > EXT4_I(inode)->i_disksize)) {
5007 new_size = offset + len;
5008 ret = inode_newsize_ok(inode, new_size);
5009 if (ret)
5010 goto out;
5013 /* Wait all existing dio workers, newcomers will block on i_mutex */
5014 ext4_inode_block_unlocked_dio(inode);
5015 inode_dio_wait(inode);
5017 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
5018 flags, mode);
5019 ext4_inode_resume_unlocked_dio(inode);
5020 if (ret)
5021 goto out;
5023 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
5024 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5025 EXT4_I(inode)->i_sync_tid);
5027 out:
5028 mutex_unlock(&inode->i_mutex);
5029 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
5030 return ret;
5034 * This function convert a range of blocks to written extents
5035 * The caller of this function will pass the start offset and the size.
5036 * all unwritten extents within this range will be converted to
5037 * written extents.
5039 * This function is called from the direct IO end io call back
5040 * function, to convert the fallocated extents after IO is completed.
5041 * Returns 0 on success.
5043 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
5044 loff_t offset, ssize_t len)
5046 unsigned int max_blocks;
5047 int ret = 0;
5048 int ret2 = 0;
5049 struct ext4_map_blocks map;
5050 unsigned int credits, blkbits = inode->i_blkbits;
5052 map.m_lblk = offset >> blkbits;
5054 * We can't just convert len to max_blocks because
5055 * If blocksize = 4096 offset = 3072 and len = 2048
5057 max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
5058 map.m_lblk);
5060 * This is somewhat ugly but the idea is clear: When transaction is
5061 * reserved, everything goes into it. Otherwise we rather start several
5062 * smaller transactions for conversion of each extent separately.
5064 if (handle) {
5065 handle = ext4_journal_start_reserved(handle,
5066 EXT4_HT_EXT_CONVERT);
5067 if (IS_ERR(handle))
5068 return PTR_ERR(handle);
5069 credits = 0;
5070 } else {
5072 * credits to insert 1 extent into extent tree
5074 credits = ext4_chunk_trans_blocks(inode, max_blocks);
5076 while (ret >= 0 && ret < max_blocks) {
5077 map.m_lblk += ret;
5078 map.m_len = (max_blocks -= ret);
5079 if (credits) {
5080 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5081 credits);
5082 if (IS_ERR(handle)) {
5083 ret = PTR_ERR(handle);
5084 break;
5087 ret = ext4_map_blocks(handle, inode, &map,
5088 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5089 if (ret <= 0)
5090 ext4_warning(inode->i_sb,
5091 "inode #%lu: block %u: len %u: "
5092 "ext4_ext_map_blocks returned %d",
5093 inode->i_ino, map.m_lblk,
5094 map.m_len, ret);
5095 ext4_mark_inode_dirty(handle, inode);
5096 if (credits)
5097 ret2 = ext4_journal_stop(handle);
5098 if (ret <= 0 || ret2)
5099 break;
5101 if (!credits)
5102 ret2 = ext4_journal_stop(handle);
5103 return ret > 0 ? ret2 : ret;
5107 * If newes is not existing extent (newes->ec_pblk equals zero) find
5108 * delayed extent at start of newes and update newes accordingly and
5109 * return start of the next delayed extent.
5111 * If newes is existing extent (newes->ec_pblk is not equal zero)
5112 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5113 * extent found. Leave newes unmodified.
5115 static int ext4_find_delayed_extent(struct inode *inode,
5116 struct extent_status *newes)
5118 struct extent_status es;
5119 ext4_lblk_t block, next_del;
5121 if (newes->es_pblk == 0) {
5122 ext4_es_find_delayed_extent_range(inode, newes->es_lblk,
5123 newes->es_lblk + newes->es_len - 1, &es);
5126 * No extent in extent-tree contains block @newes->es_pblk,
5127 * then the block may stay in 1)a hole or 2)delayed-extent.
5129 if (es.es_len == 0)
5130 /* A hole found. */
5131 return 0;
5133 if (es.es_lblk > newes->es_lblk) {
5134 /* A hole found. */
5135 newes->es_len = min(es.es_lblk - newes->es_lblk,
5136 newes->es_len);
5137 return 0;
5140 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5143 block = newes->es_lblk + newes->es_len;
5144 ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es);
5145 if (es.es_len == 0)
5146 next_del = EXT_MAX_BLOCKS;
5147 else
5148 next_del = es.es_lblk;
5150 return next_del;
5152 /* fiemap flags we can handle specified here */
5153 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
5155 static int ext4_xattr_fiemap(struct inode *inode,
5156 struct fiemap_extent_info *fieinfo)
5158 __u64 physical = 0;
5159 __u64 length;
5160 __u32 flags = FIEMAP_EXTENT_LAST;
5161 int blockbits = inode->i_sb->s_blocksize_bits;
5162 int error = 0;
5164 /* in-inode? */
5165 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5166 struct ext4_iloc iloc;
5167 int offset; /* offset of xattr in inode */
5169 error = ext4_get_inode_loc(inode, &iloc);
5170 if (error)
5171 return error;
5172 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5173 offset = EXT4_GOOD_OLD_INODE_SIZE +
5174 EXT4_I(inode)->i_extra_isize;
5175 physical += offset;
5176 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5177 flags |= FIEMAP_EXTENT_DATA_INLINE;
5178 brelse(iloc.bh);
5179 } else { /* external block */
5180 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5181 length = inode->i_sb->s_blocksize;
5184 if (physical)
5185 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5186 length, flags);
5187 return (error < 0 ? error : 0);
5190 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5191 __u64 start, __u64 len)
5193 ext4_lblk_t start_blk;
5194 int error = 0;
5196 if (ext4_has_inline_data(inode)) {
5197 int has_inline = 1;
5199 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5200 start, len);
5202 if (has_inline)
5203 return error;
5206 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5207 error = ext4_ext_precache(inode);
5208 if (error)
5209 return error;
5212 /* fallback to generic here if not in extents fmt */
5213 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5214 return generic_block_fiemap(inode, fieinfo, start, len,
5215 ext4_get_block);
5217 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
5218 return -EBADR;
5220 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5221 error = ext4_xattr_fiemap(inode, fieinfo);
5222 } else {
5223 ext4_lblk_t len_blks;
5224 __u64 last_blk;
5226 start_blk = start >> inode->i_sb->s_blocksize_bits;
5227 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5228 if (last_blk >= EXT_MAX_BLOCKS)
5229 last_blk = EXT_MAX_BLOCKS-1;
5230 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5233 * Walk the extent tree gathering extent information
5234 * and pushing extents back to the user.
5236 error = ext4_fill_fiemap_extents(inode, start_blk,
5237 len_blks, fieinfo);
5239 return error;
5243 * ext4_access_path:
5244 * Function to access the path buffer for marking it dirty.
5245 * It also checks if there are sufficient credits left in the journal handle
5246 * to update path.
5248 static int
5249 ext4_access_path(handle_t *handle, struct inode *inode,
5250 struct ext4_ext_path *path)
5252 int credits, err;
5254 if (!ext4_handle_valid(handle))
5255 return 0;
5258 * Check if need to extend journal credits
5259 * 3 for leaf, sb, and inode plus 2 (bmap and group
5260 * descriptor) for each block group; assume two block
5261 * groups
5263 if (handle->h_buffer_credits < 7) {
5264 credits = ext4_writepage_trans_blocks(inode);
5265 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
5266 /* EAGAIN is success */
5267 if (err && err != -EAGAIN)
5268 return err;
5271 err = ext4_ext_get_access(handle, inode, path);
5272 return err;
5276 * ext4_ext_shift_path_extents:
5277 * Shift the extents of a path structure lying between path[depth].p_ext
5278 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5279 * if it is right shift or left shift operation.
5281 static int
5282 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5283 struct inode *inode, handle_t *handle,
5284 enum SHIFT_DIRECTION SHIFT)
5286 int depth, err = 0;
5287 struct ext4_extent *ex_start, *ex_last;
5288 bool update = 0;
5289 depth = path->p_depth;
5291 while (depth >= 0) {
5292 if (depth == path->p_depth) {
5293 ex_start = path[depth].p_ext;
5294 if (!ex_start)
5295 return -EFSCORRUPTED;
5297 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5299 err = ext4_access_path(handle, inode, path + depth);
5300 if (err)
5301 goto out;
5303 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5304 update = 1;
5306 while (ex_start <= ex_last) {
5307 if (SHIFT == SHIFT_LEFT) {
5308 le32_add_cpu(&ex_start->ee_block,
5309 -shift);
5310 /* Try to merge to the left. */
5311 if ((ex_start >
5312 EXT_FIRST_EXTENT(path[depth].p_hdr))
5314 ext4_ext_try_to_merge_right(inode,
5315 path, ex_start - 1))
5316 ex_last--;
5317 else
5318 ex_start++;
5319 } else {
5320 le32_add_cpu(&ex_last->ee_block, shift);
5321 ext4_ext_try_to_merge_right(inode, path,
5322 ex_last);
5323 ex_last--;
5326 err = ext4_ext_dirty(handle, inode, path + depth);
5327 if (err)
5328 goto out;
5330 if (--depth < 0 || !update)
5331 break;
5334 /* Update index too */
5335 err = ext4_access_path(handle, inode, path + depth);
5336 if (err)
5337 goto out;
5339 if (SHIFT == SHIFT_LEFT)
5340 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5341 else
5342 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5343 err = ext4_ext_dirty(handle, inode, path + depth);
5344 if (err)
5345 goto out;
5347 /* we are done if current index is not a starting index */
5348 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5349 break;
5351 depth--;
5354 out:
5355 return err;
5359 * ext4_ext_shift_extents:
5360 * All the extents which lies in the range from @start to the last allocated
5361 * block for the @inode are shifted either towards left or right (depending
5362 * upon @SHIFT) by @shift blocks.
5363 * On success, 0 is returned, error otherwise.
5365 static int
5366 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5367 ext4_lblk_t start, ext4_lblk_t shift,
5368 enum SHIFT_DIRECTION SHIFT)
5370 struct ext4_ext_path *path;
5371 int ret = 0, depth;
5372 struct ext4_extent *extent;
5373 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5375 /* Let path point to the last extent */
5376 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5377 EXT4_EX_NOCACHE);
5378 if (IS_ERR(path))
5379 return PTR_ERR(path);
5381 depth = path->p_depth;
5382 extent = path[depth].p_ext;
5383 if (!extent)
5384 goto out;
5386 stop = le32_to_cpu(extent->ee_block);
5389 * For left shifts, make sure the hole on the left is big enough to
5390 * accommodate the shift. For right shifts, make sure the last extent
5391 * won't be shifted beyond EXT_MAX_BLOCKS.
5393 if (SHIFT == SHIFT_LEFT) {
5394 path = ext4_find_extent(inode, start - 1, &path,
5395 EXT4_EX_NOCACHE);
5396 if (IS_ERR(path))
5397 return PTR_ERR(path);
5398 depth = path->p_depth;
5399 extent = path[depth].p_ext;
5400 if (extent) {
5401 ex_start = le32_to_cpu(extent->ee_block);
5402 ex_end = le32_to_cpu(extent->ee_block) +
5403 ext4_ext_get_actual_len(extent);
5404 } else {
5405 ex_start = 0;
5406 ex_end = 0;
5409 if ((start == ex_start && shift > ex_start) ||
5410 (shift > start - ex_end)) {
5411 ret = -EINVAL;
5412 goto out;
5414 } else {
5415 if (shift > EXT_MAX_BLOCKS -
5416 (stop + ext4_ext_get_actual_len(extent))) {
5417 ret = -EINVAL;
5418 goto out;
5423 * In case of left shift, iterator points to start and it is increased
5424 * till we reach stop. In case of right shift, iterator points to stop
5425 * and it is decreased till we reach start.
5427 if (SHIFT == SHIFT_LEFT)
5428 iterator = &start;
5429 else
5430 iterator = &stop;
5433 * Its safe to start updating extents. Start and stop are unsigned, so
5434 * in case of right shift if extent with 0 block is reached, iterator
5435 * becomes NULL to indicate the end of the loop.
5437 while (iterator && start <= stop) {
5438 path = ext4_find_extent(inode, *iterator, &path,
5439 EXT4_EX_NOCACHE);
5440 if (IS_ERR(path))
5441 return PTR_ERR(path);
5442 depth = path->p_depth;
5443 extent = path[depth].p_ext;
5444 if (!extent) {
5445 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5446 (unsigned long) *iterator);
5447 return -EFSCORRUPTED;
5449 if (SHIFT == SHIFT_LEFT && *iterator >
5450 le32_to_cpu(extent->ee_block)) {
5451 /* Hole, move to the next extent */
5452 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5453 path[depth].p_ext++;
5454 } else {
5455 *iterator = ext4_ext_next_allocated_block(path);
5456 continue;
5460 if (SHIFT == SHIFT_LEFT) {
5461 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5462 *iterator = le32_to_cpu(extent->ee_block) +
5463 ext4_ext_get_actual_len(extent);
5464 } else {
5465 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5466 if (le32_to_cpu(extent->ee_block) > 0)
5467 *iterator = le32_to_cpu(extent->ee_block) - 1;
5468 else
5469 /* Beginning is reached, end of the loop */
5470 iterator = NULL;
5471 /* Update path extent in case we need to stop */
5472 while (le32_to_cpu(extent->ee_block) < start)
5473 extent++;
5474 path[depth].p_ext = extent;
5476 ret = ext4_ext_shift_path_extents(path, shift, inode,
5477 handle, SHIFT);
5478 if (ret)
5479 break;
5481 out:
5482 ext4_ext_drop_refs(path);
5483 kfree(path);
5484 return ret;
5488 * ext4_collapse_range:
5489 * This implements the fallocate's collapse range functionality for ext4
5490 * Returns: 0 and non-zero on error.
5492 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5494 struct super_block *sb = inode->i_sb;
5495 ext4_lblk_t punch_start, punch_stop;
5496 handle_t *handle;
5497 unsigned int credits;
5498 loff_t new_size, ioffset;
5499 int ret;
5502 * We need to test this early because xfstests assumes that a
5503 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5504 * system does not support collapse range.
5506 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5507 return -EOPNOTSUPP;
5509 /* Collapse range works only on fs block size aligned offsets. */
5510 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5511 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5512 return -EINVAL;
5514 if (!S_ISREG(inode->i_mode))
5515 return -EINVAL;
5517 trace_ext4_collapse_range(inode, offset, len);
5519 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5520 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5522 /* Call ext4_force_commit to flush all data in case of data=journal. */
5523 if (ext4_should_journal_data(inode)) {
5524 ret = ext4_force_commit(inode->i_sb);
5525 if (ret)
5526 return ret;
5529 mutex_lock(&inode->i_mutex);
5531 * There is no need to overlap collapse range with EOF, in which case
5532 * it is effectively a truncate operation
5534 if (offset + len >= i_size_read(inode)) {
5535 ret = -EINVAL;
5536 goto out_mutex;
5539 /* Currently just for extent based files */
5540 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5541 ret = -EOPNOTSUPP;
5542 goto out_mutex;
5545 /* Wait for existing dio to complete */
5546 ext4_inode_block_unlocked_dio(inode);
5547 inode_dio_wait(inode);
5550 * Prevent page faults from reinstantiating pages we have released from
5551 * page cache.
5553 down_write(&EXT4_I(inode)->i_mmap_sem);
5555 * Need to round down offset to be aligned with page size boundary
5556 * for page size > block size.
5558 ioffset = round_down(offset, PAGE_SIZE);
5560 * Write tail of the last page before removed range since it will get
5561 * removed from the page cache below.
5563 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5564 if (ret)
5565 goto out_mmap;
5567 * Write data that will be shifted to preserve them when discarding
5568 * page cache below. We are also protected from pages becoming dirty
5569 * by i_mmap_sem.
5571 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5572 LLONG_MAX);
5573 if (ret)
5574 goto out_mmap;
5575 truncate_pagecache(inode, ioffset);
5577 credits = ext4_writepage_trans_blocks(inode);
5578 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5579 if (IS_ERR(handle)) {
5580 ret = PTR_ERR(handle);
5581 goto out_mmap;
5584 down_write(&EXT4_I(inode)->i_data_sem);
5585 ext4_discard_preallocations(inode);
5587 ret = ext4_es_remove_extent(inode, punch_start,
5588 EXT_MAX_BLOCKS - punch_start);
5589 if (ret) {
5590 up_write(&EXT4_I(inode)->i_data_sem);
5591 goto out_stop;
5594 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5595 if (ret) {
5596 up_write(&EXT4_I(inode)->i_data_sem);
5597 goto out_stop;
5599 ext4_discard_preallocations(inode);
5601 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5602 punch_stop - punch_start, SHIFT_LEFT);
5603 if (ret) {
5604 up_write(&EXT4_I(inode)->i_data_sem);
5605 goto out_stop;
5608 new_size = i_size_read(inode) - len;
5609 i_size_write(inode, new_size);
5610 EXT4_I(inode)->i_disksize = new_size;
5612 up_write(&EXT4_I(inode)->i_data_sem);
5613 if (IS_SYNC(inode))
5614 ext4_handle_sync(handle);
5615 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5616 ext4_mark_inode_dirty(handle, inode);
5617 ext4_update_inode_fsync_trans(handle, inode, 1);
5619 out_stop:
5620 ext4_journal_stop(handle);
5621 out_mmap:
5622 up_write(&EXT4_I(inode)->i_mmap_sem);
5623 ext4_inode_resume_unlocked_dio(inode);
5624 out_mutex:
5625 mutex_unlock(&inode->i_mutex);
5626 return ret;
5630 * ext4_insert_range:
5631 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5632 * The data blocks starting from @offset to the EOF are shifted by @len
5633 * towards right to create a hole in the @inode. Inode size is increased
5634 * by len bytes.
5635 * Returns 0 on success, error otherwise.
5637 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5639 struct super_block *sb = inode->i_sb;
5640 handle_t *handle;
5641 struct ext4_ext_path *path;
5642 struct ext4_extent *extent;
5643 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5644 unsigned int credits, ee_len;
5645 int ret = 0, depth, split_flag = 0;
5646 loff_t ioffset;
5649 * We need to test this early because xfstests assumes that an
5650 * insert range of (0, 1) will return EOPNOTSUPP if the file
5651 * system does not support insert range.
5653 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5654 return -EOPNOTSUPP;
5656 /* Insert range works only on fs block size aligned offsets. */
5657 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5658 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5659 return -EINVAL;
5661 if (!S_ISREG(inode->i_mode))
5662 return -EOPNOTSUPP;
5664 trace_ext4_insert_range(inode, offset, len);
5666 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5667 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5669 /* Call ext4_force_commit to flush all data in case of data=journal */
5670 if (ext4_should_journal_data(inode)) {
5671 ret = ext4_force_commit(inode->i_sb);
5672 if (ret)
5673 return ret;
5676 mutex_lock(&inode->i_mutex);
5677 /* Currently just for extent based files */
5678 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5679 ret = -EOPNOTSUPP;
5680 goto out_mutex;
5683 /* Check for wrap through zero */
5684 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5685 ret = -EFBIG;
5686 goto out_mutex;
5689 /* Offset should be less than i_size */
5690 if (offset >= i_size_read(inode)) {
5691 ret = -EINVAL;
5692 goto out_mutex;
5695 /* Wait for existing dio to complete */
5696 ext4_inode_block_unlocked_dio(inode);
5697 inode_dio_wait(inode);
5700 * Prevent page faults from reinstantiating pages we have released from
5701 * page cache.
5703 down_write(&EXT4_I(inode)->i_mmap_sem);
5705 * Need to round down to align start offset to page size boundary
5706 * for page size > block size.
5708 ioffset = round_down(offset, PAGE_SIZE);
5709 /* Write out all dirty pages */
5710 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5711 LLONG_MAX);
5712 if (ret)
5713 goto out_mmap;
5714 truncate_pagecache(inode, ioffset);
5716 credits = ext4_writepage_trans_blocks(inode);
5717 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5718 if (IS_ERR(handle)) {
5719 ret = PTR_ERR(handle);
5720 goto out_mmap;
5723 /* Expand file to avoid data loss if there is error while shifting */
5724 inode->i_size += len;
5725 EXT4_I(inode)->i_disksize += len;
5726 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5727 ret = ext4_mark_inode_dirty(handle, inode);
5728 if (ret)
5729 goto out_stop;
5731 down_write(&EXT4_I(inode)->i_data_sem);
5732 ext4_discard_preallocations(inode);
5734 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5735 if (IS_ERR(path)) {
5736 up_write(&EXT4_I(inode)->i_data_sem);
5737 goto out_stop;
5740 depth = ext_depth(inode);
5741 extent = path[depth].p_ext;
5742 if (extent) {
5743 ee_start_lblk = le32_to_cpu(extent->ee_block);
5744 ee_len = ext4_ext_get_actual_len(extent);
5747 * If offset_lblk is not the starting block of extent, split
5748 * the extent @offset_lblk
5750 if ((offset_lblk > ee_start_lblk) &&
5751 (offset_lblk < (ee_start_lblk + ee_len))) {
5752 if (ext4_ext_is_unwritten(extent))
5753 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5754 EXT4_EXT_MARK_UNWRIT2;
5755 ret = ext4_split_extent_at(handle, inode, &path,
5756 offset_lblk, split_flag,
5757 EXT4_EX_NOCACHE |
5758 EXT4_GET_BLOCKS_PRE_IO |
5759 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5762 ext4_ext_drop_refs(path);
5763 kfree(path);
5764 if (ret < 0) {
5765 up_write(&EXT4_I(inode)->i_data_sem);
5766 goto out_stop;
5768 } else {
5769 ext4_ext_drop_refs(path);
5770 kfree(path);
5773 ret = ext4_es_remove_extent(inode, offset_lblk,
5774 EXT_MAX_BLOCKS - offset_lblk);
5775 if (ret) {
5776 up_write(&EXT4_I(inode)->i_data_sem);
5777 goto out_stop;
5781 * if offset_lblk lies in a hole which is at start of file, use
5782 * ee_start_lblk to shift extents
5784 ret = ext4_ext_shift_extents(inode, handle,
5785 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5786 len_lblk, SHIFT_RIGHT);
5788 up_write(&EXT4_I(inode)->i_data_sem);
5789 if (IS_SYNC(inode))
5790 ext4_handle_sync(handle);
5791 if (ret >= 0)
5792 ext4_update_inode_fsync_trans(handle, inode, 1);
5794 out_stop:
5795 ext4_journal_stop(handle);
5796 out_mmap:
5797 up_write(&EXT4_I(inode)->i_mmap_sem);
5798 ext4_inode_resume_unlocked_dio(inode);
5799 out_mutex:
5800 mutex_unlock(&inode->i_mutex);
5801 return ret;
5805 * ext4_swap_extents - Swap extents between two inodes
5807 * @inode1: First inode
5808 * @inode2: Second inode
5809 * @lblk1: Start block for first inode
5810 * @lblk2: Start block for second inode
5811 * @count: Number of blocks to swap
5812 * @mark_unwritten: Mark second inode's extents as unwritten after swap
5813 * @erp: Pointer to save error value
5815 * This helper routine does exactly what is promise "swap extents". All other
5816 * stuff such as page-cache locking consistency, bh mapping consistency or
5817 * extent's data copying must be performed by caller.
5818 * Locking:
5819 * i_mutex is held for both inodes
5820 * i_data_sem is locked for write for both inodes
5821 * Assumptions:
5822 * All pages from requested range are locked for both inodes
5825 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5826 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5827 ext4_lblk_t count, int unwritten, int *erp)
5829 struct ext4_ext_path *path1 = NULL;
5830 struct ext4_ext_path *path2 = NULL;
5831 int replaced_count = 0;
5833 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5834 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5835 BUG_ON(!mutex_is_locked(&inode1->i_mutex));
5836 BUG_ON(!mutex_is_locked(&inode2->i_mutex));
5838 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5839 if (unlikely(*erp))
5840 return 0;
5841 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5842 if (unlikely(*erp))
5843 return 0;
5845 while (count) {
5846 struct ext4_extent *ex1, *ex2, tmp_ex;
5847 ext4_lblk_t e1_blk, e2_blk;
5848 int e1_len, e2_len, len;
5849 int split = 0;
5851 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5852 if (IS_ERR(path1)) {
5853 *erp = PTR_ERR(path1);
5854 path1 = NULL;
5855 finish:
5856 count = 0;
5857 goto repeat;
5859 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5860 if (IS_ERR(path2)) {
5861 *erp = PTR_ERR(path2);
5862 path2 = NULL;
5863 goto finish;
5865 ex1 = path1[path1->p_depth].p_ext;
5866 ex2 = path2[path2->p_depth].p_ext;
5867 /* Do we have somthing to swap ? */
5868 if (unlikely(!ex2 || !ex1))
5869 goto finish;
5871 e1_blk = le32_to_cpu(ex1->ee_block);
5872 e2_blk = le32_to_cpu(ex2->ee_block);
5873 e1_len = ext4_ext_get_actual_len(ex1);
5874 e2_len = ext4_ext_get_actual_len(ex2);
5876 /* Hole handling */
5877 if (!in_range(lblk1, e1_blk, e1_len) ||
5878 !in_range(lblk2, e2_blk, e2_len)) {
5879 ext4_lblk_t next1, next2;
5881 /* if hole after extent, then go to next extent */
5882 next1 = ext4_ext_next_allocated_block(path1);
5883 next2 = ext4_ext_next_allocated_block(path2);
5884 /* If hole before extent, then shift to that extent */
5885 if (e1_blk > lblk1)
5886 next1 = e1_blk;
5887 if (e2_blk > lblk2)
5888 next2 = e1_blk;
5889 /* Do we have something to swap */
5890 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5891 goto finish;
5892 /* Move to the rightest boundary */
5893 len = next1 - lblk1;
5894 if (len < next2 - lblk2)
5895 len = next2 - lblk2;
5896 if (len > count)
5897 len = count;
5898 lblk1 += len;
5899 lblk2 += len;
5900 count -= len;
5901 goto repeat;
5904 /* Prepare left boundary */
5905 if (e1_blk < lblk1) {
5906 split = 1;
5907 *erp = ext4_force_split_extent_at(handle, inode1,
5908 &path1, lblk1, 0);
5909 if (unlikely(*erp))
5910 goto finish;
5912 if (e2_blk < lblk2) {
5913 split = 1;
5914 *erp = ext4_force_split_extent_at(handle, inode2,
5915 &path2, lblk2, 0);
5916 if (unlikely(*erp))
5917 goto finish;
5919 /* ext4_split_extent_at() may result in leaf extent split,
5920 * path must to be revalidated. */
5921 if (split)
5922 goto repeat;
5924 /* Prepare right boundary */
5925 len = count;
5926 if (len > e1_blk + e1_len - lblk1)
5927 len = e1_blk + e1_len - lblk1;
5928 if (len > e2_blk + e2_len - lblk2)
5929 len = e2_blk + e2_len - lblk2;
5931 if (len != e1_len) {
5932 split = 1;
5933 *erp = ext4_force_split_extent_at(handle, inode1,
5934 &path1, lblk1 + len, 0);
5935 if (unlikely(*erp))
5936 goto finish;
5938 if (len != e2_len) {
5939 split = 1;
5940 *erp = ext4_force_split_extent_at(handle, inode2,
5941 &path2, lblk2 + len, 0);
5942 if (*erp)
5943 goto finish;
5945 /* ext4_split_extent_at() may result in leaf extent split,
5946 * path must to be revalidated. */
5947 if (split)
5948 goto repeat;
5950 BUG_ON(e2_len != e1_len);
5951 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5952 if (unlikely(*erp))
5953 goto finish;
5954 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5955 if (unlikely(*erp))
5956 goto finish;
5958 /* Both extents are fully inside boundaries. Swap it now */
5959 tmp_ex = *ex1;
5960 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5961 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5962 ex1->ee_len = cpu_to_le16(e2_len);
5963 ex2->ee_len = cpu_to_le16(e1_len);
5964 if (unwritten)
5965 ext4_ext_mark_unwritten(ex2);
5966 if (ext4_ext_is_unwritten(&tmp_ex))
5967 ext4_ext_mark_unwritten(ex1);
5969 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5970 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5971 *erp = ext4_ext_dirty(handle, inode2, path2 +
5972 path2->p_depth);
5973 if (unlikely(*erp))
5974 goto finish;
5975 *erp = ext4_ext_dirty(handle, inode1, path1 +
5976 path1->p_depth);
5978 * Looks scarry ah..? second inode already points to new blocks,
5979 * and it was successfully dirtied. But luckily error may happen
5980 * only due to journal error, so full transaction will be
5981 * aborted anyway.
5983 if (unlikely(*erp))
5984 goto finish;
5985 lblk1 += len;
5986 lblk2 += len;
5987 replaced_count += len;
5988 count -= len;
5990 repeat:
5991 ext4_ext_drop_refs(path1);
5992 kfree(path1);
5993 ext4_ext_drop_refs(path2);
5994 kfree(path2);
5995 path1 = path2 = NULL;
5997 return replaced_count;