wlcore: Add RX_BA_WIN_SIZE_CHANGE_EVENT event
[linux/fpc-iii.git] / fs / ext4 / extents.c
blob8a456f9b8a4485d540423ececc5eb3f0252712dc
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);
880 if (path) {
881 ext4_ext_drop_refs(path);
882 if (depth > path[0].p_maxdepth) {
883 kfree(path);
884 *orig_path = path = NULL;
887 if (!path) {
888 /* account possible depth increase */
889 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
890 GFP_NOFS);
891 if (unlikely(!path))
892 return ERR_PTR(-ENOMEM);
893 path[0].p_maxdepth = depth + 1;
895 path[0].p_hdr = eh;
896 path[0].p_bh = NULL;
898 i = depth;
899 /* walk through the tree */
900 while (i) {
901 ext_debug("depth %d: num %d, max %d\n",
902 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
904 ext4_ext_binsearch_idx(inode, path + ppos, block);
905 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
906 path[ppos].p_depth = i;
907 path[ppos].p_ext = NULL;
909 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
910 flags);
911 if (IS_ERR(bh)) {
912 ret = PTR_ERR(bh);
913 goto err;
916 eh = ext_block_hdr(bh);
917 ppos++;
918 if (unlikely(ppos > depth)) {
919 put_bh(bh);
920 EXT4_ERROR_INODE(inode,
921 "ppos %d > depth %d", ppos, depth);
922 ret = -EFSCORRUPTED;
923 goto err;
925 path[ppos].p_bh = bh;
926 path[ppos].p_hdr = eh;
929 path[ppos].p_depth = i;
930 path[ppos].p_ext = NULL;
931 path[ppos].p_idx = NULL;
933 /* find extent */
934 ext4_ext_binsearch(inode, path + ppos, block);
935 /* if not an empty leaf */
936 if (path[ppos].p_ext)
937 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
939 ext4_ext_show_path(inode, path);
941 return path;
943 err:
944 ext4_ext_drop_refs(path);
945 kfree(path);
946 if (orig_path)
947 *orig_path = NULL;
948 return ERR_PTR(ret);
952 * ext4_ext_insert_index:
953 * insert new index [@logical;@ptr] into the block at @curp;
954 * check where to insert: before @curp or after @curp
956 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
957 struct ext4_ext_path *curp,
958 int logical, ext4_fsblk_t ptr)
960 struct ext4_extent_idx *ix;
961 int len, err;
963 err = ext4_ext_get_access(handle, inode, curp);
964 if (err)
965 return err;
967 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
968 EXT4_ERROR_INODE(inode,
969 "logical %d == ei_block %d!",
970 logical, le32_to_cpu(curp->p_idx->ei_block));
971 return -EFSCORRUPTED;
974 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
975 >= le16_to_cpu(curp->p_hdr->eh_max))) {
976 EXT4_ERROR_INODE(inode,
977 "eh_entries %d >= eh_max %d!",
978 le16_to_cpu(curp->p_hdr->eh_entries),
979 le16_to_cpu(curp->p_hdr->eh_max));
980 return -EFSCORRUPTED;
983 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
984 /* insert after */
985 ext_debug("insert new index %d after: %llu\n", logical, ptr);
986 ix = curp->p_idx + 1;
987 } else {
988 /* insert before */
989 ext_debug("insert new index %d before: %llu\n", logical, ptr);
990 ix = curp->p_idx;
993 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
994 BUG_ON(len < 0);
995 if (len > 0) {
996 ext_debug("insert new index %d: "
997 "move %d indices from 0x%p to 0x%p\n",
998 logical, len, ix, ix + 1);
999 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1002 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1003 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1004 return -EFSCORRUPTED;
1007 ix->ei_block = cpu_to_le32(logical);
1008 ext4_idx_store_pblock(ix, ptr);
1009 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1011 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1012 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1013 return -EFSCORRUPTED;
1016 err = ext4_ext_dirty(handle, inode, curp);
1017 ext4_std_error(inode->i_sb, err);
1019 return err;
1023 * ext4_ext_split:
1024 * inserts new subtree into the path, using free index entry
1025 * at depth @at:
1026 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1027 * - makes decision where to split
1028 * - moves remaining extents and index entries (right to the split point)
1029 * into the newly allocated blocks
1030 * - initializes subtree
1032 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1033 unsigned int flags,
1034 struct ext4_ext_path *path,
1035 struct ext4_extent *newext, int at)
1037 struct buffer_head *bh = NULL;
1038 int depth = ext_depth(inode);
1039 struct ext4_extent_header *neh;
1040 struct ext4_extent_idx *fidx;
1041 int i = at, k, m, a;
1042 ext4_fsblk_t newblock, oldblock;
1043 __le32 border;
1044 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1045 int err = 0;
1047 /* make decision: where to split? */
1048 /* FIXME: now decision is simplest: at current extent */
1050 /* if current leaf will be split, then we should use
1051 * border from split point */
1052 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1053 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1054 return -EFSCORRUPTED;
1056 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1057 border = path[depth].p_ext[1].ee_block;
1058 ext_debug("leaf will be split."
1059 " next leaf starts at %d\n",
1060 le32_to_cpu(border));
1061 } else {
1062 border = newext->ee_block;
1063 ext_debug("leaf will be added."
1064 " next leaf starts at %d\n",
1065 le32_to_cpu(border));
1069 * If error occurs, then we break processing
1070 * and mark filesystem read-only. index won't
1071 * be inserted and tree will be in consistent
1072 * state. Next mount will repair buffers too.
1076 * Get array to track all allocated blocks.
1077 * We need this to handle errors and free blocks
1078 * upon them.
1080 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
1081 if (!ablocks)
1082 return -ENOMEM;
1084 /* allocate all needed blocks */
1085 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1086 for (a = 0; a < depth - at; a++) {
1087 newblock = ext4_ext_new_meta_block(handle, inode, path,
1088 newext, &err, flags);
1089 if (newblock == 0)
1090 goto cleanup;
1091 ablocks[a] = newblock;
1094 /* initialize new leaf */
1095 newblock = ablocks[--a];
1096 if (unlikely(newblock == 0)) {
1097 EXT4_ERROR_INODE(inode, "newblock == 0!");
1098 err = -EFSCORRUPTED;
1099 goto cleanup;
1101 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1102 if (unlikely(!bh)) {
1103 err = -ENOMEM;
1104 goto cleanup;
1106 lock_buffer(bh);
1108 err = ext4_journal_get_create_access(handle, bh);
1109 if (err)
1110 goto cleanup;
1112 neh = ext_block_hdr(bh);
1113 neh->eh_entries = 0;
1114 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1115 neh->eh_magic = EXT4_EXT_MAGIC;
1116 neh->eh_depth = 0;
1118 /* move remainder of path[depth] to the new leaf */
1119 if (unlikely(path[depth].p_hdr->eh_entries !=
1120 path[depth].p_hdr->eh_max)) {
1121 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1122 path[depth].p_hdr->eh_entries,
1123 path[depth].p_hdr->eh_max);
1124 err = -EFSCORRUPTED;
1125 goto cleanup;
1127 /* start copy from next extent */
1128 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1129 ext4_ext_show_move(inode, path, newblock, depth);
1130 if (m) {
1131 struct ext4_extent *ex;
1132 ex = EXT_FIRST_EXTENT(neh);
1133 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1134 le16_add_cpu(&neh->eh_entries, m);
1137 ext4_extent_block_csum_set(inode, neh);
1138 set_buffer_uptodate(bh);
1139 unlock_buffer(bh);
1141 err = ext4_handle_dirty_metadata(handle, inode, bh);
1142 if (err)
1143 goto cleanup;
1144 brelse(bh);
1145 bh = NULL;
1147 /* correct old leaf */
1148 if (m) {
1149 err = ext4_ext_get_access(handle, inode, path + depth);
1150 if (err)
1151 goto cleanup;
1152 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1153 err = ext4_ext_dirty(handle, inode, path + depth);
1154 if (err)
1155 goto cleanup;
1159 /* create intermediate indexes */
1160 k = depth - at - 1;
1161 if (unlikely(k < 0)) {
1162 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1163 err = -EFSCORRUPTED;
1164 goto cleanup;
1166 if (k)
1167 ext_debug("create %d intermediate indices\n", k);
1168 /* insert new index into current index block */
1169 /* current depth stored in i var */
1170 i = depth - 1;
1171 while (k--) {
1172 oldblock = newblock;
1173 newblock = ablocks[--a];
1174 bh = sb_getblk(inode->i_sb, newblock);
1175 if (unlikely(!bh)) {
1176 err = -ENOMEM;
1177 goto cleanup;
1179 lock_buffer(bh);
1181 err = ext4_journal_get_create_access(handle, bh);
1182 if (err)
1183 goto cleanup;
1185 neh = ext_block_hdr(bh);
1186 neh->eh_entries = cpu_to_le16(1);
1187 neh->eh_magic = EXT4_EXT_MAGIC;
1188 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1189 neh->eh_depth = cpu_to_le16(depth - i);
1190 fidx = EXT_FIRST_INDEX(neh);
1191 fidx->ei_block = border;
1192 ext4_idx_store_pblock(fidx, oldblock);
1194 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1195 i, newblock, le32_to_cpu(border), oldblock);
1197 /* move remainder of path[i] to the new index block */
1198 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1199 EXT_LAST_INDEX(path[i].p_hdr))) {
1200 EXT4_ERROR_INODE(inode,
1201 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1202 le32_to_cpu(path[i].p_ext->ee_block));
1203 err = -EFSCORRUPTED;
1204 goto cleanup;
1206 /* start copy indexes */
1207 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1208 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1209 EXT_MAX_INDEX(path[i].p_hdr));
1210 ext4_ext_show_move(inode, path, newblock, i);
1211 if (m) {
1212 memmove(++fidx, path[i].p_idx,
1213 sizeof(struct ext4_extent_idx) * m);
1214 le16_add_cpu(&neh->eh_entries, m);
1216 ext4_extent_block_csum_set(inode, neh);
1217 set_buffer_uptodate(bh);
1218 unlock_buffer(bh);
1220 err = ext4_handle_dirty_metadata(handle, inode, bh);
1221 if (err)
1222 goto cleanup;
1223 brelse(bh);
1224 bh = NULL;
1226 /* correct old index */
1227 if (m) {
1228 err = ext4_ext_get_access(handle, inode, path + i);
1229 if (err)
1230 goto cleanup;
1231 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1232 err = ext4_ext_dirty(handle, inode, path + i);
1233 if (err)
1234 goto cleanup;
1237 i--;
1240 /* insert new index */
1241 err = ext4_ext_insert_index(handle, inode, path + at,
1242 le32_to_cpu(border), newblock);
1244 cleanup:
1245 if (bh) {
1246 if (buffer_locked(bh))
1247 unlock_buffer(bh);
1248 brelse(bh);
1251 if (err) {
1252 /* free all allocated blocks in error case */
1253 for (i = 0; i < depth; i++) {
1254 if (!ablocks[i])
1255 continue;
1256 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1257 EXT4_FREE_BLOCKS_METADATA);
1260 kfree(ablocks);
1262 return err;
1266 * ext4_ext_grow_indepth:
1267 * implements tree growing procedure:
1268 * - allocates new block
1269 * - moves top-level data (index block or leaf) into the new block
1270 * - initializes new top-level, creating index that points to the
1271 * just created block
1273 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1274 unsigned int flags)
1276 struct ext4_extent_header *neh;
1277 struct buffer_head *bh;
1278 ext4_fsblk_t newblock, goal = 0;
1279 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1280 int err = 0;
1282 /* Try to prepend new index to old one */
1283 if (ext_depth(inode))
1284 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1285 if (goal > le32_to_cpu(es->s_first_data_block)) {
1286 flags |= EXT4_MB_HINT_TRY_GOAL;
1287 goal--;
1288 } else
1289 goal = ext4_inode_to_goal_block(inode);
1290 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1291 NULL, &err);
1292 if (newblock == 0)
1293 return err;
1295 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1296 if (unlikely(!bh))
1297 return -ENOMEM;
1298 lock_buffer(bh);
1300 err = ext4_journal_get_create_access(handle, bh);
1301 if (err) {
1302 unlock_buffer(bh);
1303 goto out;
1306 /* move top-level index/leaf into new block */
1307 memmove(bh->b_data, EXT4_I(inode)->i_data,
1308 sizeof(EXT4_I(inode)->i_data));
1310 /* set size of new block */
1311 neh = ext_block_hdr(bh);
1312 /* old root could have indexes or leaves
1313 * so calculate e_max right way */
1314 if (ext_depth(inode))
1315 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1316 else
1317 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1318 neh->eh_magic = EXT4_EXT_MAGIC;
1319 ext4_extent_block_csum_set(inode, neh);
1320 set_buffer_uptodate(bh);
1321 unlock_buffer(bh);
1323 err = ext4_handle_dirty_metadata(handle, inode, bh);
1324 if (err)
1325 goto out;
1327 /* Update top-level index: num,max,pointer */
1328 neh = ext_inode_hdr(inode);
1329 neh->eh_entries = cpu_to_le16(1);
1330 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1331 if (neh->eh_depth == 0) {
1332 /* Root extent block becomes index block */
1333 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1334 EXT_FIRST_INDEX(neh)->ei_block =
1335 EXT_FIRST_EXTENT(neh)->ee_block;
1337 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1338 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1339 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1340 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1342 le16_add_cpu(&neh->eh_depth, 1);
1343 ext4_mark_inode_dirty(handle, inode);
1344 out:
1345 brelse(bh);
1347 return err;
1351 * ext4_ext_create_new_leaf:
1352 * finds empty index and adds new leaf.
1353 * if no free index is found, then it requests in-depth growing.
1355 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1356 unsigned int mb_flags,
1357 unsigned int gb_flags,
1358 struct ext4_ext_path **ppath,
1359 struct ext4_extent *newext)
1361 struct ext4_ext_path *path = *ppath;
1362 struct ext4_ext_path *curp;
1363 int depth, i, err = 0;
1365 repeat:
1366 i = depth = ext_depth(inode);
1368 /* walk up to the tree and look for free index entry */
1369 curp = path + depth;
1370 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1371 i--;
1372 curp--;
1375 /* we use already allocated block for index block,
1376 * so subsequent data blocks should be contiguous */
1377 if (EXT_HAS_FREE_INDEX(curp)) {
1378 /* if we found index with free entry, then use that
1379 * entry: create all needed subtree and add new leaf */
1380 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1381 if (err)
1382 goto out;
1384 /* refill path */
1385 path = ext4_find_extent(inode,
1386 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1387 ppath, gb_flags);
1388 if (IS_ERR(path))
1389 err = PTR_ERR(path);
1390 } else {
1391 /* tree is full, time to grow in depth */
1392 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1393 if (err)
1394 goto out;
1396 /* refill path */
1397 path = ext4_find_extent(inode,
1398 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1399 ppath, gb_flags);
1400 if (IS_ERR(path)) {
1401 err = PTR_ERR(path);
1402 goto out;
1406 * only first (depth 0 -> 1) produces free space;
1407 * in all other cases we have to split the grown tree
1409 depth = ext_depth(inode);
1410 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1411 /* now we need to split */
1412 goto repeat;
1416 out:
1417 return err;
1421 * search the closest allocated block to the left for *logical
1422 * and returns it at @logical + it's physical address at @phys
1423 * if *logical is the smallest allocated block, the function
1424 * returns 0 at @phys
1425 * return value contains 0 (success) or error code
1427 static int ext4_ext_search_left(struct inode *inode,
1428 struct ext4_ext_path *path,
1429 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1431 struct ext4_extent_idx *ix;
1432 struct ext4_extent *ex;
1433 int depth, ee_len;
1435 if (unlikely(path == NULL)) {
1436 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1437 return -EFSCORRUPTED;
1439 depth = path->p_depth;
1440 *phys = 0;
1442 if (depth == 0 && path->p_ext == NULL)
1443 return 0;
1445 /* usually extent in the path covers blocks smaller
1446 * then *logical, but it can be that extent is the
1447 * first one in the file */
1449 ex = path[depth].p_ext;
1450 ee_len = ext4_ext_get_actual_len(ex);
1451 if (*logical < le32_to_cpu(ex->ee_block)) {
1452 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1453 EXT4_ERROR_INODE(inode,
1454 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1455 *logical, le32_to_cpu(ex->ee_block));
1456 return -EFSCORRUPTED;
1458 while (--depth >= 0) {
1459 ix = path[depth].p_idx;
1460 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1461 EXT4_ERROR_INODE(inode,
1462 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1463 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1464 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1465 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1466 depth);
1467 return -EFSCORRUPTED;
1470 return 0;
1473 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1474 EXT4_ERROR_INODE(inode,
1475 "logical %d < ee_block %d + ee_len %d!",
1476 *logical, le32_to_cpu(ex->ee_block), ee_len);
1477 return -EFSCORRUPTED;
1480 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1481 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1482 return 0;
1486 * search the closest allocated block to the right for *logical
1487 * and returns it at @logical + it's physical address at @phys
1488 * if *logical is the largest allocated block, the function
1489 * returns 0 at @phys
1490 * return value contains 0 (success) or error code
1492 static int ext4_ext_search_right(struct inode *inode,
1493 struct ext4_ext_path *path,
1494 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1495 struct ext4_extent **ret_ex)
1497 struct buffer_head *bh = NULL;
1498 struct ext4_extent_header *eh;
1499 struct ext4_extent_idx *ix;
1500 struct ext4_extent *ex;
1501 ext4_fsblk_t block;
1502 int depth; /* Note, NOT eh_depth; depth from top of tree */
1503 int ee_len;
1505 if (unlikely(path == NULL)) {
1506 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1507 return -EFSCORRUPTED;
1509 depth = path->p_depth;
1510 *phys = 0;
1512 if (depth == 0 && path->p_ext == NULL)
1513 return 0;
1515 /* usually extent in the path covers blocks smaller
1516 * then *logical, but it can be that extent is the
1517 * first one in the file */
1519 ex = path[depth].p_ext;
1520 ee_len = ext4_ext_get_actual_len(ex);
1521 if (*logical < le32_to_cpu(ex->ee_block)) {
1522 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1523 EXT4_ERROR_INODE(inode,
1524 "first_extent(path[%d].p_hdr) != ex",
1525 depth);
1526 return -EFSCORRUPTED;
1528 while (--depth >= 0) {
1529 ix = path[depth].p_idx;
1530 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1531 EXT4_ERROR_INODE(inode,
1532 "ix != EXT_FIRST_INDEX *logical %d!",
1533 *logical);
1534 return -EFSCORRUPTED;
1537 goto found_extent;
1540 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1541 EXT4_ERROR_INODE(inode,
1542 "logical %d < ee_block %d + ee_len %d!",
1543 *logical, le32_to_cpu(ex->ee_block), ee_len);
1544 return -EFSCORRUPTED;
1547 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1548 /* next allocated block in this leaf */
1549 ex++;
1550 goto found_extent;
1553 /* go up and search for index to the right */
1554 while (--depth >= 0) {
1555 ix = path[depth].p_idx;
1556 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1557 goto got_index;
1560 /* we've gone up to the root and found no index to the right */
1561 return 0;
1563 got_index:
1564 /* we've found index to the right, let's
1565 * follow it and find the closest allocated
1566 * block to the right */
1567 ix++;
1568 block = ext4_idx_pblock(ix);
1569 while (++depth < path->p_depth) {
1570 /* subtract from p_depth to get proper eh_depth */
1571 bh = read_extent_tree_block(inode, block,
1572 path->p_depth - depth, 0);
1573 if (IS_ERR(bh))
1574 return PTR_ERR(bh);
1575 eh = ext_block_hdr(bh);
1576 ix = EXT_FIRST_INDEX(eh);
1577 block = ext4_idx_pblock(ix);
1578 put_bh(bh);
1581 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1582 if (IS_ERR(bh))
1583 return PTR_ERR(bh);
1584 eh = ext_block_hdr(bh);
1585 ex = EXT_FIRST_EXTENT(eh);
1586 found_extent:
1587 *logical = le32_to_cpu(ex->ee_block);
1588 *phys = ext4_ext_pblock(ex);
1589 *ret_ex = ex;
1590 if (bh)
1591 put_bh(bh);
1592 return 0;
1596 * ext4_ext_next_allocated_block:
1597 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1598 * NOTE: it considers block number from index entry as
1599 * allocated block. Thus, index entries have to be consistent
1600 * with leaves.
1602 ext4_lblk_t
1603 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1605 int depth;
1607 BUG_ON(path == NULL);
1608 depth = path->p_depth;
1610 if (depth == 0 && path->p_ext == NULL)
1611 return EXT_MAX_BLOCKS;
1613 while (depth >= 0) {
1614 if (depth == path->p_depth) {
1615 /* leaf */
1616 if (path[depth].p_ext &&
1617 path[depth].p_ext !=
1618 EXT_LAST_EXTENT(path[depth].p_hdr))
1619 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1620 } else {
1621 /* index */
1622 if (path[depth].p_idx !=
1623 EXT_LAST_INDEX(path[depth].p_hdr))
1624 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1626 depth--;
1629 return EXT_MAX_BLOCKS;
1633 * ext4_ext_next_leaf_block:
1634 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1636 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1638 int depth;
1640 BUG_ON(path == NULL);
1641 depth = path->p_depth;
1643 /* zero-tree has no leaf blocks at all */
1644 if (depth == 0)
1645 return EXT_MAX_BLOCKS;
1647 /* go to index block */
1648 depth--;
1650 while (depth >= 0) {
1651 if (path[depth].p_idx !=
1652 EXT_LAST_INDEX(path[depth].p_hdr))
1653 return (ext4_lblk_t)
1654 le32_to_cpu(path[depth].p_idx[1].ei_block);
1655 depth--;
1658 return EXT_MAX_BLOCKS;
1662 * ext4_ext_correct_indexes:
1663 * if leaf gets modified and modified extent is first in the leaf,
1664 * then we have to correct all indexes above.
1665 * TODO: do we need to correct tree in all cases?
1667 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1668 struct ext4_ext_path *path)
1670 struct ext4_extent_header *eh;
1671 int depth = ext_depth(inode);
1672 struct ext4_extent *ex;
1673 __le32 border;
1674 int k, err = 0;
1676 eh = path[depth].p_hdr;
1677 ex = path[depth].p_ext;
1679 if (unlikely(ex == NULL || eh == NULL)) {
1680 EXT4_ERROR_INODE(inode,
1681 "ex %p == NULL or eh %p == NULL", ex, eh);
1682 return -EFSCORRUPTED;
1685 if (depth == 0) {
1686 /* there is no tree at all */
1687 return 0;
1690 if (ex != EXT_FIRST_EXTENT(eh)) {
1691 /* we correct tree if first leaf got modified only */
1692 return 0;
1696 * TODO: we need correction if border is smaller than current one
1698 k = depth - 1;
1699 border = path[depth].p_ext->ee_block;
1700 err = ext4_ext_get_access(handle, inode, path + k);
1701 if (err)
1702 return err;
1703 path[k].p_idx->ei_block = border;
1704 err = ext4_ext_dirty(handle, inode, path + k);
1705 if (err)
1706 return err;
1708 while (k--) {
1709 /* change all left-side indexes */
1710 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1711 break;
1712 err = ext4_ext_get_access(handle, inode, path + k);
1713 if (err)
1714 break;
1715 path[k].p_idx->ei_block = border;
1716 err = ext4_ext_dirty(handle, inode, path + k);
1717 if (err)
1718 break;
1721 return err;
1725 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1726 struct ext4_extent *ex2)
1728 unsigned short ext1_ee_len, ext2_ee_len;
1730 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1731 return 0;
1733 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1734 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1736 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1737 le32_to_cpu(ex2->ee_block))
1738 return 0;
1741 * To allow future support for preallocated extents to be added
1742 * as an RO_COMPAT feature, refuse to merge to extents if
1743 * this can result in the top bit of ee_len being set.
1745 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1746 return 0;
1747 if (ext4_ext_is_unwritten(ex1) &&
1748 (ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
1749 atomic_read(&EXT4_I(inode)->i_unwritten) ||
1750 (ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
1751 return 0;
1752 #ifdef AGGRESSIVE_TEST
1753 if (ext1_ee_len >= 4)
1754 return 0;
1755 #endif
1757 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1758 return 1;
1759 return 0;
1763 * This function tries to merge the "ex" extent to the next extent in the tree.
1764 * It always tries to merge towards right. If you want to merge towards
1765 * left, pass "ex - 1" as argument instead of "ex".
1766 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1767 * 1 if they got merged.
1769 static int ext4_ext_try_to_merge_right(struct inode *inode,
1770 struct ext4_ext_path *path,
1771 struct ext4_extent *ex)
1773 struct ext4_extent_header *eh;
1774 unsigned int depth, len;
1775 int merge_done = 0, unwritten;
1777 depth = ext_depth(inode);
1778 BUG_ON(path[depth].p_hdr == NULL);
1779 eh = path[depth].p_hdr;
1781 while (ex < EXT_LAST_EXTENT(eh)) {
1782 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1783 break;
1784 /* merge with next extent! */
1785 unwritten = ext4_ext_is_unwritten(ex);
1786 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1787 + ext4_ext_get_actual_len(ex + 1));
1788 if (unwritten)
1789 ext4_ext_mark_unwritten(ex);
1791 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1792 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1793 * sizeof(struct ext4_extent);
1794 memmove(ex + 1, ex + 2, len);
1796 le16_add_cpu(&eh->eh_entries, -1);
1797 merge_done = 1;
1798 WARN_ON(eh->eh_entries == 0);
1799 if (!eh->eh_entries)
1800 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1803 return merge_done;
1807 * This function does a very simple check to see if we can collapse
1808 * an extent tree with a single extent tree leaf block into the inode.
1810 static void ext4_ext_try_to_merge_up(handle_t *handle,
1811 struct inode *inode,
1812 struct ext4_ext_path *path)
1814 size_t s;
1815 unsigned max_root = ext4_ext_space_root(inode, 0);
1816 ext4_fsblk_t blk;
1818 if ((path[0].p_depth != 1) ||
1819 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1820 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1821 return;
1824 * We need to modify the block allocation bitmap and the block
1825 * group descriptor to release the extent tree block. If we
1826 * can't get the journal credits, give up.
1828 if (ext4_journal_extend(handle, 2))
1829 return;
1832 * Copy the extent data up to the inode
1834 blk = ext4_idx_pblock(path[0].p_idx);
1835 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1836 sizeof(struct ext4_extent_idx);
1837 s += sizeof(struct ext4_extent_header);
1839 path[1].p_maxdepth = path[0].p_maxdepth;
1840 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1841 path[0].p_depth = 0;
1842 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1843 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1844 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1846 brelse(path[1].p_bh);
1847 ext4_free_blocks(handle, inode, NULL, blk, 1,
1848 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1852 * This function tries to merge the @ex extent to neighbours in the tree.
1853 * return 1 if merge left else 0.
1855 static void ext4_ext_try_to_merge(handle_t *handle,
1856 struct inode *inode,
1857 struct ext4_ext_path *path,
1858 struct ext4_extent *ex) {
1859 struct ext4_extent_header *eh;
1860 unsigned int depth;
1861 int merge_done = 0;
1863 depth = ext_depth(inode);
1864 BUG_ON(path[depth].p_hdr == NULL);
1865 eh = path[depth].p_hdr;
1867 if (ex > EXT_FIRST_EXTENT(eh))
1868 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1870 if (!merge_done)
1871 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1873 ext4_ext_try_to_merge_up(handle, inode, path);
1877 * check if a portion of the "newext" extent overlaps with an
1878 * existing extent.
1880 * If there is an overlap discovered, it updates the length of the newext
1881 * such that there will be no overlap, and then returns 1.
1882 * If there is no overlap found, it returns 0.
1884 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1885 struct inode *inode,
1886 struct ext4_extent *newext,
1887 struct ext4_ext_path *path)
1889 ext4_lblk_t b1, b2;
1890 unsigned int depth, len1;
1891 unsigned int ret = 0;
1893 b1 = le32_to_cpu(newext->ee_block);
1894 len1 = ext4_ext_get_actual_len(newext);
1895 depth = ext_depth(inode);
1896 if (!path[depth].p_ext)
1897 goto out;
1898 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1901 * get the next allocated block if the extent in the path
1902 * is before the requested block(s)
1904 if (b2 < b1) {
1905 b2 = ext4_ext_next_allocated_block(path);
1906 if (b2 == EXT_MAX_BLOCKS)
1907 goto out;
1908 b2 = EXT4_LBLK_CMASK(sbi, b2);
1911 /* check for wrap through zero on extent logical start block*/
1912 if (b1 + len1 < b1) {
1913 len1 = EXT_MAX_BLOCKS - b1;
1914 newext->ee_len = cpu_to_le16(len1);
1915 ret = 1;
1918 /* check for overlap */
1919 if (b1 + len1 > b2) {
1920 newext->ee_len = cpu_to_le16(b2 - b1);
1921 ret = 1;
1923 out:
1924 return ret;
1928 * ext4_ext_insert_extent:
1929 * tries to merge requsted extent into the existing extent or
1930 * inserts requested extent as new one into the tree,
1931 * creating new leaf in the no-space case.
1933 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1934 struct ext4_ext_path **ppath,
1935 struct ext4_extent *newext, int gb_flags)
1937 struct ext4_ext_path *path = *ppath;
1938 struct ext4_extent_header *eh;
1939 struct ext4_extent *ex, *fex;
1940 struct ext4_extent *nearex; /* nearest extent */
1941 struct ext4_ext_path *npath = NULL;
1942 int depth, len, err;
1943 ext4_lblk_t next;
1944 int mb_flags = 0, unwritten;
1946 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1947 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1948 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1949 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1950 return -EFSCORRUPTED;
1952 depth = ext_depth(inode);
1953 ex = path[depth].p_ext;
1954 eh = path[depth].p_hdr;
1955 if (unlikely(path[depth].p_hdr == NULL)) {
1956 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1957 return -EFSCORRUPTED;
1960 /* try to insert block into found extent and return */
1961 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1964 * Try to see whether we should rather test the extent on
1965 * right from ex, or from the left of ex. This is because
1966 * ext4_find_extent() can return either extent on the
1967 * left, or on the right from the searched position. This
1968 * will make merging more effective.
1970 if (ex < EXT_LAST_EXTENT(eh) &&
1971 (le32_to_cpu(ex->ee_block) +
1972 ext4_ext_get_actual_len(ex) <
1973 le32_to_cpu(newext->ee_block))) {
1974 ex += 1;
1975 goto prepend;
1976 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
1977 (le32_to_cpu(newext->ee_block) +
1978 ext4_ext_get_actual_len(newext) <
1979 le32_to_cpu(ex->ee_block)))
1980 ex -= 1;
1982 /* Try to append newex to the ex */
1983 if (ext4_can_extents_be_merged(inode, ex, newext)) {
1984 ext_debug("append [%d]%d block to %u:[%d]%d"
1985 "(from %llu)\n",
1986 ext4_ext_is_unwritten(newext),
1987 ext4_ext_get_actual_len(newext),
1988 le32_to_cpu(ex->ee_block),
1989 ext4_ext_is_unwritten(ex),
1990 ext4_ext_get_actual_len(ex),
1991 ext4_ext_pblock(ex));
1992 err = ext4_ext_get_access(handle, inode,
1993 path + depth);
1994 if (err)
1995 return err;
1996 unwritten = ext4_ext_is_unwritten(ex);
1997 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1998 + ext4_ext_get_actual_len(newext));
1999 if (unwritten)
2000 ext4_ext_mark_unwritten(ex);
2001 eh = path[depth].p_hdr;
2002 nearex = ex;
2003 goto merge;
2006 prepend:
2007 /* Try to prepend newex to the ex */
2008 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2009 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2010 "(from %llu)\n",
2011 le32_to_cpu(newext->ee_block),
2012 ext4_ext_is_unwritten(newext),
2013 ext4_ext_get_actual_len(newext),
2014 le32_to_cpu(ex->ee_block),
2015 ext4_ext_is_unwritten(ex),
2016 ext4_ext_get_actual_len(ex),
2017 ext4_ext_pblock(ex));
2018 err = ext4_ext_get_access(handle, inode,
2019 path + depth);
2020 if (err)
2021 return err;
2023 unwritten = ext4_ext_is_unwritten(ex);
2024 ex->ee_block = newext->ee_block;
2025 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2026 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2027 + ext4_ext_get_actual_len(newext));
2028 if (unwritten)
2029 ext4_ext_mark_unwritten(ex);
2030 eh = path[depth].p_hdr;
2031 nearex = ex;
2032 goto merge;
2036 depth = ext_depth(inode);
2037 eh = path[depth].p_hdr;
2038 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2039 goto has_space;
2041 /* probably next leaf has space for us? */
2042 fex = EXT_LAST_EXTENT(eh);
2043 next = EXT_MAX_BLOCKS;
2044 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2045 next = ext4_ext_next_leaf_block(path);
2046 if (next != EXT_MAX_BLOCKS) {
2047 ext_debug("next leaf block - %u\n", next);
2048 BUG_ON(npath != NULL);
2049 npath = ext4_find_extent(inode, next, NULL, 0);
2050 if (IS_ERR(npath))
2051 return PTR_ERR(npath);
2052 BUG_ON(npath->p_depth != path->p_depth);
2053 eh = npath[depth].p_hdr;
2054 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2055 ext_debug("next leaf isn't full(%d)\n",
2056 le16_to_cpu(eh->eh_entries));
2057 path = npath;
2058 goto has_space;
2060 ext_debug("next leaf has no free space(%d,%d)\n",
2061 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2065 * There is no free space in the found leaf.
2066 * We're gonna add a new leaf in the tree.
2068 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2069 mb_flags |= EXT4_MB_USE_RESERVED;
2070 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2071 ppath, newext);
2072 if (err)
2073 goto cleanup;
2074 depth = ext_depth(inode);
2075 eh = path[depth].p_hdr;
2077 has_space:
2078 nearex = path[depth].p_ext;
2080 err = ext4_ext_get_access(handle, inode, path + depth);
2081 if (err)
2082 goto cleanup;
2084 if (!nearex) {
2085 /* there is no extent in this leaf, create first one */
2086 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
2087 le32_to_cpu(newext->ee_block),
2088 ext4_ext_pblock(newext),
2089 ext4_ext_is_unwritten(newext),
2090 ext4_ext_get_actual_len(newext));
2091 nearex = EXT_FIRST_EXTENT(eh);
2092 } else {
2093 if (le32_to_cpu(newext->ee_block)
2094 > le32_to_cpu(nearex->ee_block)) {
2095 /* Insert after */
2096 ext_debug("insert %u:%llu:[%d]%d before: "
2097 "nearest %p\n",
2098 le32_to_cpu(newext->ee_block),
2099 ext4_ext_pblock(newext),
2100 ext4_ext_is_unwritten(newext),
2101 ext4_ext_get_actual_len(newext),
2102 nearex);
2103 nearex++;
2104 } else {
2105 /* Insert before */
2106 BUG_ON(newext->ee_block == nearex->ee_block);
2107 ext_debug("insert %u:%llu:[%d]%d after: "
2108 "nearest %p\n",
2109 le32_to_cpu(newext->ee_block),
2110 ext4_ext_pblock(newext),
2111 ext4_ext_is_unwritten(newext),
2112 ext4_ext_get_actual_len(newext),
2113 nearex);
2115 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2116 if (len > 0) {
2117 ext_debug("insert %u:%llu:[%d]%d: "
2118 "move %d extents from 0x%p to 0x%p\n",
2119 le32_to_cpu(newext->ee_block),
2120 ext4_ext_pblock(newext),
2121 ext4_ext_is_unwritten(newext),
2122 ext4_ext_get_actual_len(newext),
2123 len, nearex, nearex + 1);
2124 memmove(nearex + 1, nearex,
2125 len * sizeof(struct ext4_extent));
2129 le16_add_cpu(&eh->eh_entries, 1);
2130 path[depth].p_ext = nearex;
2131 nearex->ee_block = newext->ee_block;
2132 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2133 nearex->ee_len = newext->ee_len;
2135 merge:
2136 /* try to merge extents */
2137 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2138 ext4_ext_try_to_merge(handle, inode, path, nearex);
2141 /* time to correct all indexes above */
2142 err = ext4_ext_correct_indexes(handle, inode, path);
2143 if (err)
2144 goto cleanup;
2146 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2148 cleanup:
2149 ext4_ext_drop_refs(npath);
2150 kfree(npath);
2151 return err;
2154 static int ext4_fill_fiemap_extents(struct inode *inode,
2155 ext4_lblk_t block, ext4_lblk_t num,
2156 struct fiemap_extent_info *fieinfo)
2158 struct ext4_ext_path *path = NULL;
2159 struct ext4_extent *ex;
2160 struct extent_status es;
2161 ext4_lblk_t next, next_del, start = 0, end = 0;
2162 ext4_lblk_t last = block + num;
2163 int exists, depth = 0, err = 0;
2164 unsigned int flags = 0;
2165 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2167 while (block < last && block != EXT_MAX_BLOCKS) {
2168 num = last - block;
2169 /* find extent for this block */
2170 down_read(&EXT4_I(inode)->i_data_sem);
2172 path = ext4_find_extent(inode, block, &path, 0);
2173 if (IS_ERR(path)) {
2174 up_read(&EXT4_I(inode)->i_data_sem);
2175 err = PTR_ERR(path);
2176 path = NULL;
2177 break;
2180 depth = ext_depth(inode);
2181 if (unlikely(path[depth].p_hdr == NULL)) {
2182 up_read(&EXT4_I(inode)->i_data_sem);
2183 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2184 err = -EFSCORRUPTED;
2185 break;
2187 ex = path[depth].p_ext;
2188 next = ext4_ext_next_allocated_block(path);
2190 flags = 0;
2191 exists = 0;
2192 if (!ex) {
2193 /* there is no extent yet, so try to allocate
2194 * all requested space */
2195 start = block;
2196 end = block + num;
2197 } else if (le32_to_cpu(ex->ee_block) > block) {
2198 /* need to allocate space before found extent */
2199 start = block;
2200 end = le32_to_cpu(ex->ee_block);
2201 if (block + num < end)
2202 end = block + num;
2203 } else if (block >= le32_to_cpu(ex->ee_block)
2204 + ext4_ext_get_actual_len(ex)) {
2205 /* need to allocate space after found extent */
2206 start = block;
2207 end = block + num;
2208 if (end >= next)
2209 end = next;
2210 } else if (block >= le32_to_cpu(ex->ee_block)) {
2212 * some part of requested space is covered
2213 * by found extent
2215 start = block;
2216 end = le32_to_cpu(ex->ee_block)
2217 + ext4_ext_get_actual_len(ex);
2218 if (block + num < end)
2219 end = block + num;
2220 exists = 1;
2221 } else {
2222 BUG();
2224 BUG_ON(end <= start);
2226 if (!exists) {
2227 es.es_lblk = start;
2228 es.es_len = end - start;
2229 es.es_pblk = 0;
2230 } else {
2231 es.es_lblk = le32_to_cpu(ex->ee_block);
2232 es.es_len = ext4_ext_get_actual_len(ex);
2233 es.es_pblk = ext4_ext_pblock(ex);
2234 if (ext4_ext_is_unwritten(ex))
2235 flags |= FIEMAP_EXTENT_UNWRITTEN;
2239 * Find delayed extent and update es accordingly. We call
2240 * it even in !exists case to find out whether es is the
2241 * last existing extent or not.
2243 next_del = ext4_find_delayed_extent(inode, &es);
2244 if (!exists && next_del) {
2245 exists = 1;
2246 flags |= (FIEMAP_EXTENT_DELALLOC |
2247 FIEMAP_EXTENT_UNKNOWN);
2249 up_read(&EXT4_I(inode)->i_data_sem);
2251 if (unlikely(es.es_len == 0)) {
2252 EXT4_ERROR_INODE(inode, "es.es_len == 0");
2253 err = -EFSCORRUPTED;
2254 break;
2258 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2259 * we need to check next == EXT_MAX_BLOCKS because it is
2260 * possible that an extent is with unwritten and delayed
2261 * status due to when an extent is delayed allocated and
2262 * is allocated by fallocate status tree will track both of
2263 * them in a extent.
2265 * So we could return a unwritten and delayed extent, and
2266 * its block is equal to 'next'.
2268 if (next == next_del && next == EXT_MAX_BLOCKS) {
2269 flags |= FIEMAP_EXTENT_LAST;
2270 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2271 next != EXT_MAX_BLOCKS)) {
2272 EXT4_ERROR_INODE(inode,
2273 "next extent == %u, next "
2274 "delalloc extent = %u",
2275 next, next_del);
2276 err = -EFSCORRUPTED;
2277 break;
2281 if (exists) {
2282 err = fiemap_fill_next_extent(fieinfo,
2283 (__u64)es.es_lblk << blksize_bits,
2284 (__u64)es.es_pblk << blksize_bits,
2285 (__u64)es.es_len << blksize_bits,
2286 flags);
2287 if (err < 0)
2288 break;
2289 if (err == 1) {
2290 err = 0;
2291 break;
2295 block = es.es_lblk + es.es_len;
2298 ext4_ext_drop_refs(path);
2299 kfree(path);
2300 return err;
2304 * ext4_ext_put_gap_in_cache:
2305 * calculate boundaries of the gap that the requested block fits into
2306 * and cache this gap
2308 static void
2309 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
2310 ext4_lblk_t block)
2312 int depth = ext_depth(inode);
2313 ext4_lblk_t len;
2314 ext4_lblk_t lblock;
2315 struct ext4_extent *ex;
2316 struct extent_status es;
2318 ex = path[depth].p_ext;
2319 if (ex == NULL) {
2320 /* there is no extent yet, so gap is [0;-] */
2321 lblock = 0;
2322 len = EXT_MAX_BLOCKS;
2323 ext_debug("cache gap(whole file):");
2324 } else if (block < le32_to_cpu(ex->ee_block)) {
2325 lblock = block;
2326 len = le32_to_cpu(ex->ee_block) - block;
2327 ext_debug("cache gap(before): %u [%u:%u]",
2328 block,
2329 le32_to_cpu(ex->ee_block),
2330 ext4_ext_get_actual_len(ex));
2331 } else if (block >= le32_to_cpu(ex->ee_block)
2332 + ext4_ext_get_actual_len(ex)) {
2333 ext4_lblk_t next;
2334 lblock = le32_to_cpu(ex->ee_block)
2335 + ext4_ext_get_actual_len(ex);
2337 next = ext4_ext_next_allocated_block(path);
2338 ext_debug("cache gap(after): [%u:%u] %u",
2339 le32_to_cpu(ex->ee_block),
2340 ext4_ext_get_actual_len(ex),
2341 block);
2342 BUG_ON(next == lblock);
2343 len = next - lblock;
2344 } else {
2345 BUG();
2348 ext4_es_find_delayed_extent_range(inode, lblock, lblock + len - 1, &es);
2349 if (es.es_len) {
2350 /* There's delayed extent containing lblock? */
2351 if (es.es_lblk <= lblock)
2352 return;
2353 len = min(es.es_lblk - lblock, len);
2355 ext_debug(" -> %u:%u\n", lblock, len);
2356 ext4_es_insert_extent(inode, lblock, len, ~0, EXTENT_STATUS_HOLE);
2360 * ext4_ext_rm_idx:
2361 * removes index from the index block.
2363 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2364 struct ext4_ext_path *path, int depth)
2366 int err;
2367 ext4_fsblk_t leaf;
2369 /* free index block */
2370 depth--;
2371 path = path + depth;
2372 leaf = ext4_idx_pblock(path->p_idx);
2373 if (unlikely(path->p_hdr->eh_entries == 0)) {
2374 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2375 return -EFSCORRUPTED;
2377 err = ext4_ext_get_access(handle, inode, path);
2378 if (err)
2379 return err;
2381 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2382 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2383 len *= sizeof(struct ext4_extent_idx);
2384 memmove(path->p_idx, path->p_idx + 1, len);
2387 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2388 err = ext4_ext_dirty(handle, inode, path);
2389 if (err)
2390 return err;
2391 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2392 trace_ext4_ext_rm_idx(inode, leaf);
2394 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2395 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2397 while (--depth >= 0) {
2398 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2399 break;
2400 path--;
2401 err = ext4_ext_get_access(handle, inode, path);
2402 if (err)
2403 break;
2404 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2405 err = ext4_ext_dirty(handle, inode, path);
2406 if (err)
2407 break;
2409 return err;
2413 * ext4_ext_calc_credits_for_single_extent:
2414 * This routine returns max. credits that needed to insert an extent
2415 * to the extent tree.
2416 * When pass the actual path, the caller should calculate credits
2417 * under i_data_sem.
2419 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2420 struct ext4_ext_path *path)
2422 if (path) {
2423 int depth = ext_depth(inode);
2424 int ret = 0;
2426 /* probably there is space in leaf? */
2427 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2428 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2431 * There are some space in the leaf tree, no
2432 * need to account for leaf block credit
2434 * bitmaps and block group descriptor blocks
2435 * and other metadata blocks still need to be
2436 * accounted.
2438 /* 1 bitmap, 1 block group descriptor */
2439 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2440 return ret;
2444 return ext4_chunk_trans_blocks(inode, nrblocks);
2448 * How many index/leaf blocks need to change/allocate to add @extents extents?
2450 * If we add a single extent, then in the worse case, each tree level
2451 * index/leaf need to be changed in case of the tree split.
2453 * If more extents are inserted, they could cause the whole tree split more
2454 * than once, but this is really rare.
2456 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2458 int index;
2459 int depth;
2461 /* If we are converting the inline data, only one is needed here. */
2462 if (ext4_has_inline_data(inode))
2463 return 1;
2465 depth = ext_depth(inode);
2467 if (extents <= 1)
2468 index = depth * 2;
2469 else
2470 index = depth * 3;
2472 return index;
2475 static inline int get_default_free_blocks_flags(struct inode *inode)
2477 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2478 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2479 else if (ext4_should_journal_data(inode))
2480 return EXT4_FREE_BLOCKS_FORGET;
2481 return 0;
2484 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2485 struct ext4_extent *ex,
2486 long long *partial_cluster,
2487 ext4_lblk_t from, ext4_lblk_t to)
2489 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2490 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2491 ext4_fsblk_t pblk;
2492 int flags = get_default_free_blocks_flags(inode);
2495 * For bigalloc file systems, we never free a partial cluster
2496 * at the beginning of the extent. Instead, we make a note
2497 * that we tried freeing the cluster, and check to see if we
2498 * need to free it on a subsequent call to ext4_remove_blocks,
2499 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2501 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2503 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2505 * If we have a partial cluster, and it's different from the
2506 * cluster of the last block, we need to explicitly free the
2507 * partial cluster here.
2509 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2510 if (*partial_cluster > 0 &&
2511 *partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2512 ext4_free_blocks(handle, inode, NULL,
2513 EXT4_C2B(sbi, *partial_cluster),
2514 sbi->s_cluster_ratio, flags);
2515 *partial_cluster = 0;
2518 #ifdef EXTENTS_STATS
2520 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2521 spin_lock(&sbi->s_ext_stats_lock);
2522 sbi->s_ext_blocks += ee_len;
2523 sbi->s_ext_extents++;
2524 if (ee_len < sbi->s_ext_min)
2525 sbi->s_ext_min = ee_len;
2526 if (ee_len > sbi->s_ext_max)
2527 sbi->s_ext_max = ee_len;
2528 if (ext_depth(inode) > sbi->s_depth_max)
2529 sbi->s_depth_max = ext_depth(inode);
2530 spin_unlock(&sbi->s_ext_stats_lock);
2532 #endif
2533 if (from >= le32_to_cpu(ex->ee_block)
2534 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2535 /* tail removal */
2536 ext4_lblk_t num;
2537 long long first_cluster;
2539 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2540 pblk = ext4_ext_pblock(ex) + ee_len - num;
2542 * Usually we want to free partial cluster at the end of the
2543 * extent, except for the situation when the cluster is still
2544 * used by any other extent (partial_cluster is negative).
2546 if (*partial_cluster < 0 &&
2547 *partial_cluster == -(long long) EXT4_B2C(sbi, pblk+num-1))
2548 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2550 ext_debug("free last %u blocks starting %llu partial %lld\n",
2551 num, pblk, *partial_cluster);
2552 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2554 * If the block range to be freed didn't start at the
2555 * beginning of a cluster, and we removed the entire
2556 * extent and the cluster is not used by any other extent,
2557 * save the partial cluster here, since we might need to
2558 * delete if we determine that the truncate or punch hole
2559 * operation has removed all of the blocks in the cluster.
2560 * If that cluster is used by another extent, preserve its
2561 * negative value so it isn't freed later on.
2563 * If the whole extent wasn't freed, we've reached the
2564 * start of the truncated/punched region and have finished
2565 * removing blocks. If there's a partial cluster here it's
2566 * shared with the remainder of the extent and is no longer
2567 * a candidate for removal.
2569 if (EXT4_PBLK_COFF(sbi, pblk) && ee_len == num) {
2570 first_cluster = (long long) EXT4_B2C(sbi, pblk);
2571 if (first_cluster != -*partial_cluster)
2572 *partial_cluster = first_cluster;
2573 } else {
2574 *partial_cluster = 0;
2576 } else
2577 ext4_error(sbi->s_sb, "strange request: removal(2) "
2578 "%u-%u from %u:%u\n",
2579 from, to, le32_to_cpu(ex->ee_block), ee_len);
2580 return 0;
2585 * ext4_ext_rm_leaf() Removes the extents associated with the
2586 * blocks appearing between "start" and "end". Both "start"
2587 * and "end" must appear in the same extent or EIO is returned.
2589 * @handle: The journal handle
2590 * @inode: The files inode
2591 * @path: The path to the leaf
2592 * @partial_cluster: The cluster which we'll have to free if all extents
2593 * has been released from it. However, if this value is
2594 * negative, it's a cluster just to the right of the
2595 * punched region and it must not be freed.
2596 * @start: The first block to remove
2597 * @end: The last block to remove
2599 static int
2600 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2601 struct ext4_ext_path *path,
2602 long long *partial_cluster,
2603 ext4_lblk_t start, ext4_lblk_t end)
2605 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2606 int err = 0, correct_index = 0;
2607 int depth = ext_depth(inode), credits;
2608 struct ext4_extent_header *eh;
2609 ext4_lblk_t a, b;
2610 unsigned num;
2611 ext4_lblk_t ex_ee_block;
2612 unsigned short ex_ee_len;
2613 unsigned unwritten = 0;
2614 struct ext4_extent *ex;
2615 ext4_fsblk_t pblk;
2617 /* the header must be checked already in ext4_ext_remove_space() */
2618 ext_debug("truncate since %u in leaf to %u\n", start, end);
2619 if (!path[depth].p_hdr)
2620 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2621 eh = path[depth].p_hdr;
2622 if (unlikely(path[depth].p_hdr == NULL)) {
2623 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2624 return -EFSCORRUPTED;
2626 /* find where to start removing */
2627 ex = path[depth].p_ext;
2628 if (!ex)
2629 ex = EXT_LAST_EXTENT(eh);
2631 ex_ee_block = le32_to_cpu(ex->ee_block);
2632 ex_ee_len = ext4_ext_get_actual_len(ex);
2634 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2636 while (ex >= EXT_FIRST_EXTENT(eh) &&
2637 ex_ee_block + ex_ee_len > start) {
2639 if (ext4_ext_is_unwritten(ex))
2640 unwritten = 1;
2641 else
2642 unwritten = 0;
2644 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2645 unwritten, ex_ee_len);
2646 path[depth].p_ext = ex;
2648 a = ex_ee_block > start ? ex_ee_block : start;
2649 b = ex_ee_block+ex_ee_len - 1 < end ?
2650 ex_ee_block+ex_ee_len - 1 : end;
2652 ext_debug(" border %u:%u\n", a, b);
2654 /* If this extent is beyond the end of the hole, skip it */
2655 if (end < ex_ee_block) {
2657 * We're going to skip this extent and move to another,
2658 * so note that its first cluster is in use to avoid
2659 * freeing it when removing blocks. Eventually, the
2660 * right edge of the truncated/punched region will
2661 * be just to the left.
2663 if (sbi->s_cluster_ratio > 1) {
2664 pblk = ext4_ext_pblock(ex);
2665 *partial_cluster =
2666 -(long long) EXT4_B2C(sbi, pblk);
2668 ex--;
2669 ex_ee_block = le32_to_cpu(ex->ee_block);
2670 ex_ee_len = ext4_ext_get_actual_len(ex);
2671 continue;
2672 } else if (b != ex_ee_block + ex_ee_len - 1) {
2673 EXT4_ERROR_INODE(inode,
2674 "can not handle truncate %u:%u "
2675 "on extent %u:%u",
2676 start, end, ex_ee_block,
2677 ex_ee_block + ex_ee_len - 1);
2678 err = -EFSCORRUPTED;
2679 goto out;
2680 } else if (a != ex_ee_block) {
2681 /* remove tail of the extent */
2682 num = a - ex_ee_block;
2683 } else {
2684 /* remove whole extent: excellent! */
2685 num = 0;
2688 * 3 for leaf, sb, and inode plus 2 (bmap and group
2689 * descriptor) for each block group; assume two block
2690 * groups plus ex_ee_len/blocks_per_block_group for
2691 * the worst case
2693 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2694 if (ex == EXT_FIRST_EXTENT(eh)) {
2695 correct_index = 1;
2696 credits += (ext_depth(inode)) + 1;
2698 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2700 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2701 if (err)
2702 goto out;
2704 err = ext4_ext_get_access(handle, inode, path + depth);
2705 if (err)
2706 goto out;
2708 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2709 a, b);
2710 if (err)
2711 goto out;
2713 if (num == 0)
2714 /* this extent is removed; mark slot entirely unused */
2715 ext4_ext_store_pblock(ex, 0);
2717 ex->ee_len = cpu_to_le16(num);
2719 * Do not mark unwritten if all the blocks in the
2720 * extent have been removed.
2722 if (unwritten && num)
2723 ext4_ext_mark_unwritten(ex);
2725 * If the extent was completely released,
2726 * we need to remove it from the leaf
2728 if (num == 0) {
2729 if (end != EXT_MAX_BLOCKS - 1) {
2731 * For hole punching, we need to scoot all the
2732 * extents up when an extent is removed so that
2733 * we dont have blank extents in the middle
2735 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2736 sizeof(struct ext4_extent));
2738 /* Now get rid of the one at the end */
2739 memset(EXT_LAST_EXTENT(eh), 0,
2740 sizeof(struct ext4_extent));
2742 le16_add_cpu(&eh->eh_entries, -1);
2745 err = ext4_ext_dirty(handle, inode, path + depth);
2746 if (err)
2747 goto out;
2749 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2750 ext4_ext_pblock(ex));
2751 ex--;
2752 ex_ee_block = le32_to_cpu(ex->ee_block);
2753 ex_ee_len = ext4_ext_get_actual_len(ex);
2756 if (correct_index && eh->eh_entries)
2757 err = ext4_ext_correct_indexes(handle, inode, path);
2760 * If there's a partial cluster and at least one extent remains in
2761 * the leaf, free the partial cluster if it isn't shared with the
2762 * current extent. If it is shared with the current extent
2763 * we zero partial_cluster because we've reached the start of the
2764 * truncated/punched region and we're done removing blocks.
2766 if (*partial_cluster > 0 && ex >= EXT_FIRST_EXTENT(eh)) {
2767 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2768 if (*partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2769 ext4_free_blocks(handle, inode, NULL,
2770 EXT4_C2B(sbi, *partial_cluster),
2771 sbi->s_cluster_ratio,
2772 get_default_free_blocks_flags(inode));
2774 *partial_cluster = 0;
2777 /* if this leaf is free, then we should
2778 * remove it from index block above */
2779 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2780 err = ext4_ext_rm_idx(handle, inode, path, depth);
2782 out:
2783 return err;
2787 * ext4_ext_more_to_rm:
2788 * returns 1 if current index has to be freed (even partial)
2790 static int
2791 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2793 BUG_ON(path->p_idx == NULL);
2795 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2796 return 0;
2799 * if truncate on deeper level happened, it wasn't partial,
2800 * so we have to consider current index for truncation
2802 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2803 return 0;
2804 return 1;
2807 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2808 ext4_lblk_t end)
2810 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2811 int depth = ext_depth(inode);
2812 struct ext4_ext_path *path = NULL;
2813 long long partial_cluster = 0;
2814 handle_t *handle;
2815 int i = 0, err = 0;
2817 ext_debug("truncate since %u to %u\n", start, end);
2819 /* probably first extent we're gonna free will be last in block */
2820 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
2821 if (IS_ERR(handle))
2822 return PTR_ERR(handle);
2824 again:
2825 trace_ext4_ext_remove_space(inode, start, end, depth);
2828 * Check if we are removing extents inside the extent tree. If that
2829 * is the case, we are going to punch a hole inside the extent tree
2830 * so we have to check whether we need to split the extent covering
2831 * the last block to remove so we can easily remove the part of it
2832 * in ext4_ext_rm_leaf().
2834 if (end < EXT_MAX_BLOCKS - 1) {
2835 struct ext4_extent *ex;
2836 ext4_lblk_t ee_block, ex_end, lblk;
2837 ext4_fsblk_t pblk;
2839 /* find extent for or closest extent to this block */
2840 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
2841 if (IS_ERR(path)) {
2842 ext4_journal_stop(handle);
2843 return PTR_ERR(path);
2845 depth = ext_depth(inode);
2846 /* Leaf not may not exist only if inode has no blocks at all */
2847 ex = path[depth].p_ext;
2848 if (!ex) {
2849 if (depth) {
2850 EXT4_ERROR_INODE(inode,
2851 "path[%d].p_hdr == NULL",
2852 depth);
2853 err = -EFSCORRUPTED;
2855 goto out;
2858 ee_block = le32_to_cpu(ex->ee_block);
2859 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2862 * See if the last block is inside the extent, if so split
2863 * the extent at 'end' block so we can easily remove the
2864 * tail of the first part of the split extent in
2865 * ext4_ext_rm_leaf().
2867 if (end >= ee_block && end < ex_end) {
2870 * If we're going to split the extent, note that
2871 * the cluster containing the block after 'end' is
2872 * in use to avoid freeing it when removing blocks.
2874 if (sbi->s_cluster_ratio > 1) {
2875 pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
2876 partial_cluster =
2877 -(long long) EXT4_B2C(sbi, pblk);
2881 * Split the extent in two so that 'end' is the last
2882 * block in the first new extent. Also we should not
2883 * fail removing space due to ENOSPC so try to use
2884 * reserved block if that happens.
2886 err = ext4_force_split_extent_at(handle, inode, &path,
2887 end + 1, 1);
2888 if (err < 0)
2889 goto out;
2891 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end) {
2893 * If there's an extent to the right its first cluster
2894 * contains the immediate right boundary of the
2895 * truncated/punched region. Set partial_cluster to
2896 * its negative value so it won't be freed if shared
2897 * with the current extent. The end < ee_block case
2898 * is handled in ext4_ext_rm_leaf().
2900 lblk = ex_end + 1;
2901 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2902 &ex);
2903 if (err)
2904 goto out;
2905 if (pblk)
2906 partial_cluster =
2907 -(long long) EXT4_B2C(sbi, pblk);
2911 * We start scanning from right side, freeing all the blocks
2912 * after i_size and walking into the tree depth-wise.
2914 depth = ext_depth(inode);
2915 if (path) {
2916 int k = i = depth;
2917 while (--k > 0)
2918 path[k].p_block =
2919 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2920 } else {
2921 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2922 GFP_NOFS);
2923 if (path == NULL) {
2924 ext4_journal_stop(handle);
2925 return -ENOMEM;
2927 path[0].p_maxdepth = path[0].p_depth = depth;
2928 path[0].p_hdr = ext_inode_hdr(inode);
2929 i = 0;
2931 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2932 err = -EFSCORRUPTED;
2933 goto out;
2936 err = 0;
2938 while (i >= 0 && err == 0) {
2939 if (i == depth) {
2940 /* this is leaf block */
2941 err = ext4_ext_rm_leaf(handle, inode, path,
2942 &partial_cluster, start,
2943 end);
2944 /* root level has p_bh == NULL, brelse() eats this */
2945 brelse(path[i].p_bh);
2946 path[i].p_bh = NULL;
2947 i--;
2948 continue;
2951 /* this is index block */
2952 if (!path[i].p_hdr) {
2953 ext_debug("initialize header\n");
2954 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2957 if (!path[i].p_idx) {
2958 /* this level hasn't been touched yet */
2959 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2960 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2961 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2962 path[i].p_hdr,
2963 le16_to_cpu(path[i].p_hdr->eh_entries));
2964 } else {
2965 /* we were already here, see at next index */
2966 path[i].p_idx--;
2969 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2970 i, EXT_FIRST_INDEX(path[i].p_hdr),
2971 path[i].p_idx);
2972 if (ext4_ext_more_to_rm(path + i)) {
2973 struct buffer_head *bh;
2974 /* go to the next level */
2975 ext_debug("move to level %d (block %llu)\n",
2976 i + 1, ext4_idx_pblock(path[i].p_idx));
2977 memset(path + i + 1, 0, sizeof(*path));
2978 bh = read_extent_tree_block(inode,
2979 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
2980 EXT4_EX_NOCACHE);
2981 if (IS_ERR(bh)) {
2982 /* should we reset i_size? */
2983 err = PTR_ERR(bh);
2984 break;
2986 /* Yield here to deal with large extent trees.
2987 * Should be a no-op if we did IO above. */
2988 cond_resched();
2989 if (WARN_ON(i + 1 > depth)) {
2990 err = -EFSCORRUPTED;
2991 break;
2993 path[i + 1].p_bh = bh;
2995 /* save actual number of indexes since this
2996 * number is changed at the next iteration */
2997 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2998 i++;
2999 } else {
3000 /* we finished processing this index, go up */
3001 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3002 /* index is empty, remove it;
3003 * handle must be already prepared by the
3004 * truncatei_leaf() */
3005 err = ext4_ext_rm_idx(handle, inode, path, i);
3007 /* root level has p_bh == NULL, brelse() eats this */
3008 brelse(path[i].p_bh);
3009 path[i].p_bh = NULL;
3010 i--;
3011 ext_debug("return to level %d\n", i);
3015 trace_ext4_ext_remove_space_done(inode, start, end, depth,
3016 partial_cluster, path->p_hdr->eh_entries);
3019 * If we still have something in the partial cluster and we have removed
3020 * even the first extent, then we should free the blocks in the partial
3021 * cluster as well. (This code will only run when there are no leaves
3022 * to the immediate left of the truncated/punched region.)
3024 if (partial_cluster > 0 && err == 0) {
3025 /* don't zero partial_cluster since it's not used afterwards */
3026 ext4_free_blocks(handle, inode, NULL,
3027 EXT4_C2B(sbi, partial_cluster),
3028 sbi->s_cluster_ratio,
3029 get_default_free_blocks_flags(inode));
3032 /* TODO: flexible tree reduction should be here */
3033 if (path->p_hdr->eh_entries == 0) {
3035 * truncate to zero freed all the tree,
3036 * so we need to correct eh_depth
3038 err = ext4_ext_get_access(handle, inode, path);
3039 if (err == 0) {
3040 ext_inode_hdr(inode)->eh_depth = 0;
3041 ext_inode_hdr(inode)->eh_max =
3042 cpu_to_le16(ext4_ext_space_root(inode, 0));
3043 err = ext4_ext_dirty(handle, inode, path);
3046 out:
3047 ext4_ext_drop_refs(path);
3048 kfree(path);
3049 path = NULL;
3050 if (err == -EAGAIN)
3051 goto again;
3052 ext4_journal_stop(handle);
3054 return err;
3058 * called at mount time
3060 void ext4_ext_init(struct super_block *sb)
3063 * possible initialization would be here
3066 if (ext4_has_feature_extents(sb)) {
3067 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3068 printk(KERN_INFO "EXT4-fs: file extents enabled"
3069 #ifdef AGGRESSIVE_TEST
3070 ", aggressive tests"
3071 #endif
3072 #ifdef CHECK_BINSEARCH
3073 ", check binsearch"
3074 #endif
3075 #ifdef EXTENTS_STATS
3076 ", stats"
3077 #endif
3078 "\n");
3079 #endif
3080 #ifdef EXTENTS_STATS
3081 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3082 EXT4_SB(sb)->s_ext_min = 1 << 30;
3083 EXT4_SB(sb)->s_ext_max = 0;
3084 #endif
3089 * called at umount time
3091 void ext4_ext_release(struct super_block *sb)
3093 if (!ext4_has_feature_extents(sb))
3094 return;
3096 #ifdef EXTENTS_STATS
3097 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3098 struct ext4_sb_info *sbi = EXT4_SB(sb);
3099 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3100 sbi->s_ext_blocks, sbi->s_ext_extents,
3101 sbi->s_ext_blocks / sbi->s_ext_extents);
3102 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3103 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3105 #endif
3108 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3110 ext4_lblk_t ee_block;
3111 ext4_fsblk_t ee_pblock;
3112 unsigned int ee_len;
3114 ee_block = le32_to_cpu(ex->ee_block);
3115 ee_len = ext4_ext_get_actual_len(ex);
3116 ee_pblock = ext4_ext_pblock(ex);
3118 if (ee_len == 0)
3119 return 0;
3121 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3122 EXTENT_STATUS_WRITTEN);
3125 /* FIXME!! we need to try to merge to left or right after zero-out */
3126 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3128 ext4_fsblk_t ee_pblock;
3129 unsigned int ee_len;
3130 int ret;
3132 ee_len = ext4_ext_get_actual_len(ex);
3133 ee_pblock = ext4_ext_pblock(ex);
3135 if (ext4_encrypted_inode(inode))
3136 return ext4_encrypted_zeroout(inode, ex);
3138 ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
3139 if (ret > 0)
3140 ret = 0;
3142 return ret;
3146 * ext4_split_extent_at() splits an extent at given block.
3148 * @handle: the journal handle
3149 * @inode: the file inode
3150 * @path: the path to the extent
3151 * @split: the logical block where the extent is splitted.
3152 * @split_flags: indicates if the extent could be zeroout if split fails, and
3153 * the states(init or unwritten) of new extents.
3154 * @flags: flags used to insert new extent to extent tree.
3157 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3158 * of which are deterimined by split_flag.
3160 * There are two cases:
3161 * a> the extent are splitted into two extent.
3162 * b> split is not needed, and just mark the extent.
3164 * return 0 on success.
3166 static int ext4_split_extent_at(handle_t *handle,
3167 struct inode *inode,
3168 struct ext4_ext_path **ppath,
3169 ext4_lblk_t split,
3170 int split_flag,
3171 int flags)
3173 struct ext4_ext_path *path = *ppath;
3174 ext4_fsblk_t newblock;
3175 ext4_lblk_t ee_block;
3176 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3177 struct ext4_extent *ex2 = NULL;
3178 unsigned int ee_len, depth;
3179 int err = 0;
3181 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3182 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3184 ext_debug("ext4_split_extents_at: inode %lu, logical"
3185 "block %llu\n", inode->i_ino, (unsigned long long)split);
3187 ext4_ext_show_leaf(inode, path);
3189 depth = ext_depth(inode);
3190 ex = path[depth].p_ext;
3191 ee_block = le32_to_cpu(ex->ee_block);
3192 ee_len = ext4_ext_get_actual_len(ex);
3193 newblock = split - ee_block + ext4_ext_pblock(ex);
3195 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3196 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3197 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3198 EXT4_EXT_MARK_UNWRIT1 |
3199 EXT4_EXT_MARK_UNWRIT2));
3201 err = ext4_ext_get_access(handle, inode, path + depth);
3202 if (err)
3203 goto out;
3205 if (split == ee_block) {
3207 * case b: block @split is the block that the extent begins with
3208 * then we just change the state of the extent, and splitting
3209 * is not needed.
3211 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3212 ext4_ext_mark_unwritten(ex);
3213 else
3214 ext4_ext_mark_initialized(ex);
3216 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3217 ext4_ext_try_to_merge(handle, inode, path, ex);
3219 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3220 goto out;
3223 /* case a */
3224 memcpy(&orig_ex, ex, sizeof(orig_ex));
3225 ex->ee_len = cpu_to_le16(split - ee_block);
3226 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3227 ext4_ext_mark_unwritten(ex);
3230 * path may lead to new leaf, not to original leaf any more
3231 * after ext4_ext_insert_extent() returns,
3233 err = ext4_ext_dirty(handle, inode, path + depth);
3234 if (err)
3235 goto fix_extent_len;
3237 ex2 = &newex;
3238 ex2->ee_block = cpu_to_le32(split);
3239 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3240 ext4_ext_store_pblock(ex2, newblock);
3241 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3242 ext4_ext_mark_unwritten(ex2);
3244 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3245 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3246 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3247 if (split_flag & EXT4_EXT_DATA_VALID1) {
3248 err = ext4_ext_zeroout(inode, ex2);
3249 zero_ex.ee_block = ex2->ee_block;
3250 zero_ex.ee_len = cpu_to_le16(
3251 ext4_ext_get_actual_len(ex2));
3252 ext4_ext_store_pblock(&zero_ex,
3253 ext4_ext_pblock(ex2));
3254 } else {
3255 err = ext4_ext_zeroout(inode, ex);
3256 zero_ex.ee_block = ex->ee_block;
3257 zero_ex.ee_len = cpu_to_le16(
3258 ext4_ext_get_actual_len(ex));
3259 ext4_ext_store_pblock(&zero_ex,
3260 ext4_ext_pblock(ex));
3262 } else {
3263 err = ext4_ext_zeroout(inode, &orig_ex);
3264 zero_ex.ee_block = orig_ex.ee_block;
3265 zero_ex.ee_len = cpu_to_le16(
3266 ext4_ext_get_actual_len(&orig_ex));
3267 ext4_ext_store_pblock(&zero_ex,
3268 ext4_ext_pblock(&orig_ex));
3271 if (err)
3272 goto fix_extent_len;
3273 /* update the extent length and mark as initialized */
3274 ex->ee_len = cpu_to_le16(ee_len);
3275 ext4_ext_try_to_merge(handle, inode, path, ex);
3276 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3277 if (err)
3278 goto fix_extent_len;
3280 /* update extent status tree */
3281 err = ext4_zeroout_es(inode, &zero_ex);
3283 goto out;
3284 } else if (err)
3285 goto fix_extent_len;
3287 out:
3288 ext4_ext_show_leaf(inode, path);
3289 return err;
3291 fix_extent_len:
3292 ex->ee_len = orig_ex.ee_len;
3293 ext4_ext_dirty(handle, inode, path + path->p_depth);
3294 return err;
3298 * ext4_split_extents() splits an extent and mark extent which is covered
3299 * by @map as split_flags indicates
3301 * It may result in splitting the extent into multiple extents (up to three)
3302 * There are three possibilities:
3303 * a> There is no split required
3304 * b> Splits in two extents: Split is happening at either end of the extent
3305 * c> Splits in three extents: Somone is splitting in middle of the extent
3308 static int ext4_split_extent(handle_t *handle,
3309 struct inode *inode,
3310 struct ext4_ext_path **ppath,
3311 struct ext4_map_blocks *map,
3312 int split_flag,
3313 int flags)
3315 struct ext4_ext_path *path = *ppath;
3316 ext4_lblk_t ee_block;
3317 struct ext4_extent *ex;
3318 unsigned int ee_len, depth;
3319 int err = 0;
3320 int unwritten;
3321 int split_flag1, flags1;
3322 int allocated = map->m_len;
3324 depth = ext_depth(inode);
3325 ex = path[depth].p_ext;
3326 ee_block = le32_to_cpu(ex->ee_block);
3327 ee_len = ext4_ext_get_actual_len(ex);
3328 unwritten = ext4_ext_is_unwritten(ex);
3330 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3331 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3332 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3333 if (unwritten)
3334 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3335 EXT4_EXT_MARK_UNWRIT2;
3336 if (split_flag & EXT4_EXT_DATA_VALID2)
3337 split_flag1 |= EXT4_EXT_DATA_VALID1;
3338 err = ext4_split_extent_at(handle, inode, ppath,
3339 map->m_lblk + map->m_len, split_flag1, flags1);
3340 if (err)
3341 goto out;
3342 } else {
3343 allocated = ee_len - (map->m_lblk - ee_block);
3346 * Update path is required because previous ext4_split_extent_at() may
3347 * result in split of original leaf or extent zeroout.
3349 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3350 if (IS_ERR(path))
3351 return PTR_ERR(path);
3352 depth = ext_depth(inode);
3353 ex = path[depth].p_ext;
3354 if (!ex) {
3355 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3356 (unsigned long) map->m_lblk);
3357 return -EFSCORRUPTED;
3359 unwritten = ext4_ext_is_unwritten(ex);
3360 split_flag1 = 0;
3362 if (map->m_lblk >= ee_block) {
3363 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3364 if (unwritten) {
3365 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3366 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3367 EXT4_EXT_MARK_UNWRIT2);
3369 err = ext4_split_extent_at(handle, inode, ppath,
3370 map->m_lblk, split_flag1, flags);
3371 if (err)
3372 goto out;
3375 ext4_ext_show_leaf(inode, path);
3376 out:
3377 return err ? err : allocated;
3381 * This function is called by ext4_ext_map_blocks() if someone tries to write
3382 * to an unwritten extent. It may result in splitting the unwritten
3383 * extent into multiple extents (up to three - one initialized and two
3384 * unwritten).
3385 * There are three possibilities:
3386 * a> There is no split required: Entire extent should be initialized
3387 * b> Splits in two extents: Write is happening at either end of the extent
3388 * c> Splits in three extents: Somone is writing in middle of the extent
3390 * Pre-conditions:
3391 * - The extent pointed to by 'path' is unwritten.
3392 * - The extent pointed to by 'path' contains a superset
3393 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3395 * Post-conditions on success:
3396 * - the returned value is the number of blocks beyond map->l_lblk
3397 * that are allocated and initialized.
3398 * It is guaranteed to be >= map->m_len.
3400 static int ext4_ext_convert_to_initialized(handle_t *handle,
3401 struct inode *inode,
3402 struct ext4_map_blocks *map,
3403 struct ext4_ext_path **ppath,
3404 int flags)
3406 struct ext4_ext_path *path = *ppath;
3407 struct ext4_sb_info *sbi;
3408 struct ext4_extent_header *eh;
3409 struct ext4_map_blocks split_map;
3410 struct ext4_extent zero_ex;
3411 struct ext4_extent *ex, *abut_ex;
3412 ext4_lblk_t ee_block, eof_block;
3413 unsigned int ee_len, depth, map_len = map->m_len;
3414 int allocated = 0, max_zeroout = 0;
3415 int err = 0;
3416 int split_flag = 0;
3418 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3419 "block %llu, max_blocks %u\n", inode->i_ino,
3420 (unsigned long long)map->m_lblk, map_len);
3422 sbi = EXT4_SB(inode->i_sb);
3423 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3424 inode->i_sb->s_blocksize_bits;
3425 if (eof_block < map->m_lblk + map_len)
3426 eof_block = map->m_lblk + map_len;
3428 depth = ext_depth(inode);
3429 eh = path[depth].p_hdr;
3430 ex = path[depth].p_ext;
3431 ee_block = le32_to_cpu(ex->ee_block);
3432 ee_len = ext4_ext_get_actual_len(ex);
3433 zero_ex.ee_len = 0;
3435 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3437 /* Pre-conditions */
3438 BUG_ON(!ext4_ext_is_unwritten(ex));
3439 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3442 * Attempt to transfer newly initialized blocks from the currently
3443 * unwritten extent to its neighbor. This is much cheaper
3444 * than an insertion followed by a merge as those involve costly
3445 * memmove() calls. Transferring to the left is the common case in
3446 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3447 * followed by append writes.
3449 * Limitations of the current logic:
3450 * - L1: we do not deal with writes covering the whole extent.
3451 * This would require removing the extent if the transfer
3452 * is possible.
3453 * - L2: we only attempt to merge with an extent stored in the
3454 * same extent tree node.
3456 if ((map->m_lblk == ee_block) &&
3457 /* See if we can merge left */
3458 (map_len < ee_len) && /*L1*/
3459 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3460 ext4_lblk_t prev_lblk;
3461 ext4_fsblk_t prev_pblk, ee_pblk;
3462 unsigned int prev_len;
3464 abut_ex = ex - 1;
3465 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3466 prev_len = ext4_ext_get_actual_len(abut_ex);
3467 prev_pblk = ext4_ext_pblock(abut_ex);
3468 ee_pblk = ext4_ext_pblock(ex);
3471 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3472 * upon those conditions:
3473 * - C1: abut_ex is initialized,
3474 * - C2: abut_ex is logically abutting ex,
3475 * - C3: abut_ex is physically abutting ex,
3476 * - C4: abut_ex can receive the additional blocks without
3477 * overflowing the (initialized) length limit.
3479 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3480 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3481 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3482 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3483 err = ext4_ext_get_access(handle, inode, path + depth);
3484 if (err)
3485 goto out;
3487 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3488 map, ex, abut_ex);
3490 /* Shift the start of ex by 'map_len' blocks */
3491 ex->ee_block = cpu_to_le32(ee_block + map_len);
3492 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3493 ex->ee_len = cpu_to_le16(ee_len - map_len);
3494 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3496 /* Extend abut_ex by 'map_len' blocks */
3497 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3499 /* Result: number of initialized blocks past m_lblk */
3500 allocated = map_len;
3502 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3503 (map_len < ee_len) && /*L1*/
3504 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3505 /* See if we can merge right */
3506 ext4_lblk_t next_lblk;
3507 ext4_fsblk_t next_pblk, ee_pblk;
3508 unsigned int next_len;
3510 abut_ex = ex + 1;
3511 next_lblk = le32_to_cpu(abut_ex->ee_block);
3512 next_len = ext4_ext_get_actual_len(abut_ex);
3513 next_pblk = ext4_ext_pblock(abut_ex);
3514 ee_pblk = ext4_ext_pblock(ex);
3517 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3518 * upon those conditions:
3519 * - C1: abut_ex is initialized,
3520 * - C2: abut_ex is logically abutting ex,
3521 * - C3: abut_ex is physically abutting ex,
3522 * - C4: abut_ex can receive the additional blocks without
3523 * overflowing the (initialized) length limit.
3525 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3526 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3527 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3528 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3529 err = ext4_ext_get_access(handle, inode, path + depth);
3530 if (err)
3531 goto out;
3533 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3534 map, ex, abut_ex);
3536 /* Shift the start of abut_ex by 'map_len' blocks */
3537 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3538 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3539 ex->ee_len = cpu_to_le16(ee_len - map_len);
3540 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3542 /* Extend abut_ex by 'map_len' blocks */
3543 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3545 /* Result: number of initialized blocks past m_lblk */
3546 allocated = map_len;
3549 if (allocated) {
3550 /* Mark the block containing both extents as dirty */
3551 ext4_ext_dirty(handle, inode, path + depth);
3553 /* Update path to point to the right extent */
3554 path[depth].p_ext = abut_ex;
3555 goto out;
3556 } else
3557 allocated = ee_len - (map->m_lblk - ee_block);
3559 WARN_ON(map->m_lblk < ee_block);
3561 * It is safe to convert extent to initialized via explicit
3562 * zeroout only if extent is fully inside i_size or new_size.
3564 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3566 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3567 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3568 (inode->i_sb->s_blocksize_bits - 10);
3570 if (ext4_encrypted_inode(inode))
3571 max_zeroout = 0;
3573 /* If extent is less than s_max_zeroout_kb, zeroout directly */
3574 if (max_zeroout && (ee_len <= max_zeroout)) {
3575 err = ext4_ext_zeroout(inode, ex);
3576 if (err)
3577 goto out;
3578 zero_ex.ee_block = ex->ee_block;
3579 zero_ex.ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex));
3580 ext4_ext_store_pblock(&zero_ex, ext4_ext_pblock(ex));
3582 err = ext4_ext_get_access(handle, inode, path + depth);
3583 if (err)
3584 goto out;
3585 ext4_ext_mark_initialized(ex);
3586 ext4_ext_try_to_merge(handle, inode, path, ex);
3587 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3588 goto out;
3592 * four cases:
3593 * 1. split the extent into three extents.
3594 * 2. split the extent into two extents, zeroout the first half.
3595 * 3. split the extent into two extents, zeroout the second half.
3596 * 4. split the extent into two extents with out zeroout.
3598 split_map.m_lblk = map->m_lblk;
3599 split_map.m_len = map->m_len;
3601 if (max_zeroout && (allocated > map->m_len)) {
3602 if (allocated <= max_zeroout) {
3603 /* case 3 */
3604 zero_ex.ee_block =
3605 cpu_to_le32(map->m_lblk);
3606 zero_ex.ee_len = cpu_to_le16(allocated);
3607 ext4_ext_store_pblock(&zero_ex,
3608 ext4_ext_pblock(ex) + map->m_lblk - ee_block);
3609 err = ext4_ext_zeroout(inode, &zero_ex);
3610 if (err)
3611 goto out;
3612 split_map.m_lblk = map->m_lblk;
3613 split_map.m_len = allocated;
3614 } else if (map->m_lblk - ee_block + map->m_len < max_zeroout) {
3615 /* case 2 */
3616 if (map->m_lblk != ee_block) {
3617 zero_ex.ee_block = ex->ee_block;
3618 zero_ex.ee_len = cpu_to_le16(map->m_lblk -
3619 ee_block);
3620 ext4_ext_store_pblock(&zero_ex,
3621 ext4_ext_pblock(ex));
3622 err = ext4_ext_zeroout(inode, &zero_ex);
3623 if (err)
3624 goto out;
3627 split_map.m_lblk = ee_block;
3628 split_map.m_len = map->m_lblk - ee_block + map->m_len;
3629 allocated = map->m_len;
3633 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3634 flags);
3635 if (err > 0)
3636 err = 0;
3637 out:
3638 /* If we have gotten a failure, don't zero out status tree */
3639 if (!err)
3640 err = ext4_zeroout_es(inode, &zero_ex);
3641 return err ? err : allocated;
3645 * This function is called by ext4_ext_map_blocks() from
3646 * ext4_get_blocks_dio_write() when DIO to write
3647 * to an unwritten extent.
3649 * Writing to an unwritten extent may result in splitting the unwritten
3650 * extent into multiple initialized/unwritten extents (up to three)
3651 * There are three possibilities:
3652 * a> There is no split required: Entire extent should be unwritten
3653 * b> Splits in two extents: Write is happening at either end of the extent
3654 * c> Splits in three extents: Somone is writing in middle of the extent
3656 * This works the same way in the case of initialized -> unwritten conversion.
3658 * One of more index blocks maybe needed if the extent tree grow after
3659 * the unwritten extent split. To prevent ENOSPC occur at the IO
3660 * complete, we need to split the unwritten extent before DIO submit
3661 * the IO. The unwritten extent called at this time will be split
3662 * into three unwritten extent(at most). After IO complete, the part
3663 * being filled will be convert to initialized by the end_io callback function
3664 * via ext4_convert_unwritten_extents().
3666 * Returns the size of unwritten extent to be written on success.
3668 static int ext4_split_convert_extents(handle_t *handle,
3669 struct inode *inode,
3670 struct ext4_map_blocks *map,
3671 struct ext4_ext_path **ppath,
3672 int flags)
3674 struct ext4_ext_path *path = *ppath;
3675 ext4_lblk_t eof_block;
3676 ext4_lblk_t ee_block;
3677 struct ext4_extent *ex;
3678 unsigned int ee_len;
3679 int split_flag = 0, depth;
3681 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3682 __func__, inode->i_ino,
3683 (unsigned long long)map->m_lblk, map->m_len);
3685 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3686 inode->i_sb->s_blocksize_bits;
3687 if (eof_block < map->m_lblk + map->m_len)
3688 eof_block = map->m_lblk + map->m_len;
3690 * It is safe to convert extent to initialized via explicit
3691 * zeroout only if extent is fully insde i_size or new_size.
3693 depth = ext_depth(inode);
3694 ex = path[depth].p_ext;
3695 ee_block = le32_to_cpu(ex->ee_block);
3696 ee_len = ext4_ext_get_actual_len(ex);
3698 /* Convert to unwritten */
3699 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3700 split_flag |= EXT4_EXT_DATA_VALID1;
3701 /* Convert to initialized */
3702 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3703 split_flag |= ee_block + ee_len <= eof_block ?
3704 EXT4_EXT_MAY_ZEROOUT : 0;
3705 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3707 flags |= EXT4_GET_BLOCKS_PRE_IO;
3708 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3711 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3712 struct inode *inode,
3713 struct ext4_map_blocks *map,
3714 struct ext4_ext_path **ppath)
3716 struct ext4_ext_path *path = *ppath;
3717 struct ext4_extent *ex;
3718 ext4_lblk_t ee_block;
3719 unsigned int ee_len;
3720 int depth;
3721 int err = 0;
3723 depth = ext_depth(inode);
3724 ex = path[depth].p_ext;
3725 ee_block = le32_to_cpu(ex->ee_block);
3726 ee_len = ext4_ext_get_actual_len(ex);
3728 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3729 "block %llu, max_blocks %u\n", inode->i_ino,
3730 (unsigned long long)ee_block, ee_len);
3732 /* If extent is larger than requested it is a clear sign that we still
3733 * have some extent state machine issues left. So extent_split is still
3734 * required.
3735 * TODO: Once all related issues will be fixed this situation should be
3736 * illegal.
3738 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3739 #ifdef EXT4_DEBUG
3740 ext4_warning("Inode (%ld) finished: extent logical block %llu,"
3741 " len %u; IO logical block %llu, len %u\n",
3742 inode->i_ino, (unsigned long long)ee_block, ee_len,
3743 (unsigned long long)map->m_lblk, map->m_len);
3744 #endif
3745 err = ext4_split_convert_extents(handle, inode, map, ppath,
3746 EXT4_GET_BLOCKS_CONVERT);
3747 if (err < 0)
3748 return err;
3749 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3750 if (IS_ERR(path))
3751 return PTR_ERR(path);
3752 depth = ext_depth(inode);
3753 ex = path[depth].p_ext;
3756 err = ext4_ext_get_access(handle, inode, path + depth);
3757 if (err)
3758 goto out;
3759 /* first mark the extent as initialized */
3760 ext4_ext_mark_initialized(ex);
3762 /* note: ext4_ext_correct_indexes() isn't needed here because
3763 * borders are not changed
3765 ext4_ext_try_to_merge(handle, inode, path, ex);
3767 /* Mark modified extent as dirty */
3768 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3769 out:
3770 ext4_ext_show_leaf(inode, path);
3771 return err;
3774 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3775 sector_t block, int count)
3777 int i;
3778 for (i = 0; i < count; i++)
3779 unmap_underlying_metadata(bdev, block + i);
3783 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3785 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3786 ext4_lblk_t lblk,
3787 struct ext4_ext_path *path,
3788 unsigned int len)
3790 int i, depth;
3791 struct ext4_extent_header *eh;
3792 struct ext4_extent *last_ex;
3794 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3795 return 0;
3797 depth = ext_depth(inode);
3798 eh = path[depth].p_hdr;
3801 * We're going to remove EOFBLOCKS_FL entirely in future so we
3802 * do not care for this case anymore. Simply remove the flag
3803 * if there are no extents.
3805 if (unlikely(!eh->eh_entries))
3806 goto out;
3807 last_ex = EXT_LAST_EXTENT(eh);
3809 * We should clear the EOFBLOCKS_FL flag if we are writing the
3810 * last block in the last extent in the file. We test this by
3811 * first checking to see if the caller to
3812 * ext4_ext_get_blocks() was interested in the last block (or
3813 * a block beyond the last block) in the current extent. If
3814 * this turns out to be false, we can bail out from this
3815 * function immediately.
3817 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3818 ext4_ext_get_actual_len(last_ex))
3819 return 0;
3821 * If the caller does appear to be planning to write at or
3822 * beyond the end of the current extent, we then test to see
3823 * if the current extent is the last extent in the file, by
3824 * checking to make sure it was reached via the rightmost node
3825 * at each level of the tree.
3827 for (i = depth-1; i >= 0; i--)
3828 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3829 return 0;
3830 out:
3831 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3832 return ext4_mark_inode_dirty(handle, inode);
3836 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3838 * Return 1 if there is a delalloc block in the range, otherwise 0.
3840 int ext4_find_delalloc_range(struct inode *inode,
3841 ext4_lblk_t lblk_start,
3842 ext4_lblk_t lblk_end)
3844 struct extent_status es;
3846 ext4_es_find_delayed_extent_range(inode, lblk_start, lblk_end, &es);
3847 if (es.es_len == 0)
3848 return 0; /* there is no delay extent in this tree */
3849 else if (es.es_lblk <= lblk_start &&
3850 lblk_start < es.es_lblk + es.es_len)
3851 return 1;
3852 else if (lblk_start <= es.es_lblk && es.es_lblk <= lblk_end)
3853 return 1;
3854 else
3855 return 0;
3858 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk)
3860 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3861 ext4_lblk_t lblk_start, lblk_end;
3862 lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
3863 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3865 return ext4_find_delalloc_range(inode, lblk_start, lblk_end);
3869 * Determines how many complete clusters (out of those specified by the 'map')
3870 * are under delalloc and were reserved quota for.
3871 * This function is called when we are writing out the blocks that were
3872 * originally written with their allocation delayed, but then the space was
3873 * allocated using fallocate() before the delayed allocation could be resolved.
3874 * The cases to look for are:
3875 * ('=' indicated delayed allocated blocks
3876 * '-' indicates non-delayed allocated blocks)
3877 * (a) partial clusters towards beginning and/or end outside of allocated range
3878 * are not delalloc'ed.
3879 * Ex:
3880 * |----c---=|====c====|====c====|===-c----|
3881 * |++++++ allocated ++++++|
3882 * ==> 4 complete clusters in above example
3884 * (b) partial cluster (outside of allocated range) towards either end is
3885 * marked for delayed allocation. In this case, we will exclude that
3886 * cluster.
3887 * Ex:
3888 * |----====c========|========c========|
3889 * |++++++ allocated ++++++|
3890 * ==> 1 complete clusters in above example
3892 * Ex:
3893 * |================c================|
3894 * |++++++ allocated ++++++|
3895 * ==> 0 complete clusters in above example
3897 * The ext4_da_update_reserve_space will be called only if we
3898 * determine here that there were some "entire" clusters that span
3899 * this 'allocated' range.
3900 * In the non-bigalloc case, this function will just end up returning num_blks
3901 * without ever calling ext4_find_delalloc_range.
3903 static unsigned int
3904 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3905 unsigned int num_blks)
3907 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3908 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3909 ext4_lblk_t lblk_from, lblk_to, c_offset;
3910 unsigned int allocated_clusters = 0;
3912 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3913 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3915 /* max possible clusters for this allocation */
3916 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3918 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3920 /* Check towards left side */
3921 c_offset = EXT4_LBLK_COFF(sbi, lblk_start);
3922 if (c_offset) {
3923 lblk_from = EXT4_LBLK_CMASK(sbi, lblk_start);
3924 lblk_to = lblk_from + c_offset - 1;
3926 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3927 allocated_clusters--;
3930 /* Now check towards right. */
3931 c_offset = EXT4_LBLK_COFF(sbi, lblk_start + num_blks);
3932 if (allocated_clusters && c_offset) {
3933 lblk_from = lblk_start + num_blks;
3934 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3936 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3937 allocated_clusters--;
3940 return allocated_clusters;
3943 static int
3944 convert_initialized_extent(handle_t *handle, struct inode *inode,
3945 struct ext4_map_blocks *map,
3946 struct ext4_ext_path **ppath, int flags,
3947 unsigned int allocated, ext4_fsblk_t newblock)
3949 struct ext4_ext_path *path = *ppath;
3950 struct ext4_extent *ex;
3951 ext4_lblk_t ee_block;
3952 unsigned int ee_len;
3953 int depth;
3954 int err = 0;
3957 * Make sure that the extent is no bigger than we support with
3958 * unwritten extent
3960 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3961 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3963 depth = ext_depth(inode);
3964 ex = path[depth].p_ext;
3965 ee_block = le32_to_cpu(ex->ee_block);
3966 ee_len = ext4_ext_get_actual_len(ex);
3968 ext_debug("%s: inode %lu, logical"
3969 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3970 (unsigned long long)ee_block, ee_len);
3972 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3973 err = ext4_split_convert_extents(handle, inode, map, ppath,
3974 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3975 if (err < 0)
3976 return err;
3977 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3978 if (IS_ERR(path))
3979 return PTR_ERR(path);
3980 depth = ext_depth(inode);
3981 ex = path[depth].p_ext;
3982 if (!ex) {
3983 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3984 (unsigned long) map->m_lblk);
3985 return -EFSCORRUPTED;
3989 err = ext4_ext_get_access(handle, inode, path + depth);
3990 if (err)
3991 return err;
3992 /* first mark the extent as unwritten */
3993 ext4_ext_mark_unwritten(ex);
3995 /* note: ext4_ext_correct_indexes() isn't needed here because
3996 * borders are not changed
3998 ext4_ext_try_to_merge(handle, inode, path, ex);
4000 /* Mark modified extent as dirty */
4001 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4002 if (err)
4003 return err;
4004 ext4_ext_show_leaf(inode, path);
4006 ext4_update_inode_fsync_trans(handle, inode, 1);
4007 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4008 if (err)
4009 return err;
4010 map->m_flags |= EXT4_MAP_UNWRITTEN;
4011 if (allocated > map->m_len)
4012 allocated = map->m_len;
4013 map->m_len = allocated;
4014 return allocated;
4017 static int
4018 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4019 struct ext4_map_blocks *map,
4020 struct ext4_ext_path **ppath, int flags,
4021 unsigned int allocated, ext4_fsblk_t newblock)
4023 struct ext4_ext_path *path = *ppath;
4024 int ret = 0;
4025 int err = 0;
4026 ext4_io_end_t *io = ext4_inode_aio(inode);
4028 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4029 "block %llu, max_blocks %u, flags %x, allocated %u\n",
4030 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4031 flags, allocated);
4032 ext4_ext_show_leaf(inode, path);
4035 * When writing into unwritten space, we should not fail to
4036 * allocate metadata blocks for the new extent block if needed.
4038 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4040 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4041 allocated, newblock);
4043 /* get_block() before submit the IO, split the extent */
4044 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4045 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4046 flags | EXT4_GET_BLOCKS_CONVERT);
4047 if (ret <= 0)
4048 goto out;
4050 * Flag the inode(non aio case) or end_io struct (aio case)
4051 * that this IO needs to conversion to written when IO is
4052 * completed
4054 if (io)
4055 ext4_set_io_unwritten_flag(inode, io);
4056 else
4057 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
4058 map->m_flags |= EXT4_MAP_UNWRITTEN;
4059 goto out;
4061 /* IO end_io complete, convert the filled extent to written */
4062 if (flags & EXT4_GET_BLOCKS_CONVERT) {
4063 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4064 ppath);
4065 if (ret >= 0) {
4066 ext4_update_inode_fsync_trans(handle, inode, 1);
4067 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4068 path, map->m_len);
4069 } else
4070 err = ret;
4071 map->m_flags |= EXT4_MAP_MAPPED;
4072 map->m_pblk = newblock;
4073 if (allocated > map->m_len)
4074 allocated = map->m_len;
4075 map->m_len = allocated;
4076 goto out2;
4078 /* buffered IO case */
4080 * repeat fallocate creation request
4081 * we already have an unwritten extent
4083 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4084 map->m_flags |= EXT4_MAP_UNWRITTEN;
4085 goto map_out;
4088 /* buffered READ or buffered write_begin() lookup */
4089 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4091 * We have blocks reserved already. We
4092 * return allocated blocks so that delalloc
4093 * won't do block reservation for us. But
4094 * the buffer head will be unmapped so that
4095 * a read from the block returns 0s.
4097 map->m_flags |= EXT4_MAP_UNWRITTEN;
4098 goto out1;
4101 /* buffered write, writepage time, convert*/
4102 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4103 if (ret >= 0)
4104 ext4_update_inode_fsync_trans(handle, inode, 1);
4105 out:
4106 if (ret <= 0) {
4107 err = ret;
4108 goto out2;
4109 } else
4110 allocated = ret;
4111 map->m_flags |= EXT4_MAP_NEW;
4113 * if we allocated more blocks than requested
4114 * we need to make sure we unmap the extra block
4115 * allocated. The actual needed block will get
4116 * unmapped later when we find the buffer_head marked
4117 * new.
4119 if (allocated > map->m_len) {
4120 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
4121 newblock + map->m_len,
4122 allocated - map->m_len);
4123 allocated = map->m_len;
4125 map->m_len = allocated;
4128 * If we have done fallocate with the offset that is already
4129 * delayed allocated, we would have block reservation
4130 * and quota reservation done in the delayed write path.
4131 * But fallocate would have already updated quota and block
4132 * count for this offset. So cancel these reservation
4134 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4135 unsigned int reserved_clusters;
4136 reserved_clusters = get_reserved_cluster_alloc(inode,
4137 map->m_lblk, map->m_len);
4138 if (reserved_clusters)
4139 ext4_da_update_reserve_space(inode,
4140 reserved_clusters,
4144 map_out:
4145 map->m_flags |= EXT4_MAP_MAPPED;
4146 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4147 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4148 map->m_len);
4149 if (err < 0)
4150 goto out2;
4152 out1:
4153 if (allocated > map->m_len)
4154 allocated = map->m_len;
4155 ext4_ext_show_leaf(inode, path);
4156 map->m_pblk = newblock;
4157 map->m_len = allocated;
4158 out2:
4159 return err ? err : allocated;
4163 * get_implied_cluster_alloc - check to see if the requested
4164 * allocation (in the map structure) overlaps with a cluster already
4165 * allocated in an extent.
4166 * @sb The filesystem superblock structure
4167 * @map The requested lblk->pblk mapping
4168 * @ex The extent structure which might contain an implied
4169 * cluster allocation
4171 * This function is called by ext4_ext_map_blocks() after we failed to
4172 * find blocks that were already in the inode's extent tree. Hence,
4173 * we know that the beginning of the requested region cannot overlap
4174 * the extent from the inode's extent tree. There are three cases we
4175 * want to catch. The first is this case:
4177 * |--- cluster # N--|
4178 * |--- extent ---| |---- requested region ---|
4179 * |==========|
4181 * The second case that we need to test for is this one:
4183 * |--------- cluster # N ----------------|
4184 * |--- requested region --| |------- extent ----|
4185 * |=======================|
4187 * The third case is when the requested region lies between two extents
4188 * within the same cluster:
4189 * |------------- cluster # N-------------|
4190 * |----- ex -----| |---- ex_right ----|
4191 * |------ requested region ------|
4192 * |================|
4194 * In each of the above cases, we need to set the map->m_pblk and
4195 * map->m_len so it corresponds to the return the extent labelled as
4196 * "|====|" from cluster #N, since it is already in use for data in
4197 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4198 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4199 * as a new "allocated" block region. Otherwise, we will return 0 and
4200 * ext4_ext_map_blocks() will then allocate one or more new clusters
4201 * by calling ext4_mb_new_blocks().
4203 static int get_implied_cluster_alloc(struct super_block *sb,
4204 struct ext4_map_blocks *map,
4205 struct ext4_extent *ex,
4206 struct ext4_ext_path *path)
4208 struct ext4_sb_info *sbi = EXT4_SB(sb);
4209 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4210 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4211 ext4_lblk_t rr_cluster_start;
4212 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4213 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4214 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4216 /* The extent passed in that we are trying to match */
4217 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4218 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4220 /* The requested region passed into ext4_map_blocks() */
4221 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4223 if ((rr_cluster_start == ex_cluster_end) ||
4224 (rr_cluster_start == ex_cluster_start)) {
4225 if (rr_cluster_start == ex_cluster_end)
4226 ee_start += ee_len - 1;
4227 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4228 map->m_len = min(map->m_len,
4229 (unsigned) sbi->s_cluster_ratio - c_offset);
4231 * Check for and handle this case:
4233 * |--------- cluster # N-------------|
4234 * |------- extent ----|
4235 * |--- requested region ---|
4236 * |===========|
4239 if (map->m_lblk < ee_block)
4240 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4243 * Check for the case where there is already another allocated
4244 * block to the right of 'ex' but before the end of the cluster.
4246 * |------------- cluster # N-------------|
4247 * |----- ex -----| |---- ex_right ----|
4248 * |------ requested region ------|
4249 * |================|
4251 if (map->m_lblk > ee_block) {
4252 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4253 map->m_len = min(map->m_len, next - map->m_lblk);
4256 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4257 return 1;
4260 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4261 return 0;
4266 * Block allocation/map/preallocation routine for extents based files
4269 * Need to be called with
4270 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4271 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4273 * return > 0, number of of blocks already mapped/allocated
4274 * if create == 0 and these are pre-allocated blocks
4275 * buffer head is unmapped
4276 * otherwise blocks are mapped
4278 * return = 0, if plain look up failed (blocks have not been allocated)
4279 * buffer head is unmapped
4281 * return < 0, error case.
4283 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4284 struct ext4_map_blocks *map, int flags)
4286 struct ext4_ext_path *path = NULL;
4287 struct ext4_extent newex, *ex, *ex2;
4288 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4289 ext4_fsblk_t newblock = 0;
4290 int free_on_err = 0, err = 0, depth, ret;
4291 unsigned int allocated = 0, offset = 0;
4292 unsigned int allocated_clusters = 0;
4293 struct ext4_allocation_request ar;
4294 ext4_io_end_t *io = ext4_inode_aio(inode);
4295 ext4_lblk_t cluster_offset;
4296 int set_unwritten = 0;
4297 bool map_from_cluster = false;
4299 ext_debug("blocks %u/%u requested for inode %lu\n",
4300 map->m_lblk, map->m_len, inode->i_ino);
4301 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4303 /* find extent for this block */
4304 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4305 if (IS_ERR(path)) {
4306 err = PTR_ERR(path);
4307 path = NULL;
4308 goto out2;
4311 depth = ext_depth(inode);
4314 * consistent leaf must not be empty;
4315 * this situation is possible, though, _during_ tree modification;
4316 * this is why assert can't be put in ext4_find_extent()
4318 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4319 EXT4_ERROR_INODE(inode, "bad extent address "
4320 "lblock: %lu, depth: %d pblock %lld",
4321 (unsigned long) map->m_lblk, depth,
4322 path[depth].p_block);
4323 err = -EFSCORRUPTED;
4324 goto out2;
4327 ex = path[depth].p_ext;
4328 if (ex) {
4329 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4330 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4331 unsigned short ee_len;
4335 * unwritten extents are treated as holes, except that
4336 * we split out initialized portions during a write.
4338 ee_len = ext4_ext_get_actual_len(ex);
4340 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4342 /* if found extent covers block, simply return it */
4343 if (in_range(map->m_lblk, ee_block, ee_len)) {
4344 newblock = map->m_lblk - ee_block + ee_start;
4345 /* number of remaining blocks in the extent */
4346 allocated = ee_len - (map->m_lblk - ee_block);
4347 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4348 ee_block, ee_len, newblock);
4351 * If the extent is initialized check whether the
4352 * caller wants to convert it to unwritten.
4354 if ((!ext4_ext_is_unwritten(ex)) &&
4355 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4356 allocated = convert_initialized_extent(
4357 handle, inode, map, &path,
4358 flags, allocated, newblock);
4359 goto out2;
4360 } else if (!ext4_ext_is_unwritten(ex))
4361 goto out;
4363 ret = ext4_ext_handle_unwritten_extents(
4364 handle, inode, map, &path, flags,
4365 allocated, newblock);
4366 if (ret < 0)
4367 err = ret;
4368 else
4369 allocated = ret;
4370 goto out2;
4375 * requested block isn't allocated yet;
4376 * we couldn't try to create block if create flag is zero
4378 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4380 * put just found gap into cache to speed up
4381 * subsequent requests
4383 ext4_ext_put_gap_in_cache(inode, path, map->m_lblk);
4384 goto out2;
4388 * Okay, we need to do block allocation.
4390 newex.ee_block = cpu_to_le32(map->m_lblk);
4391 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4394 * If we are doing bigalloc, check to see if the extent returned
4395 * by ext4_find_extent() implies a cluster we can use.
4397 if (cluster_offset && ex &&
4398 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4399 ar.len = allocated = map->m_len;
4400 newblock = map->m_pblk;
4401 map_from_cluster = true;
4402 goto got_allocated_blocks;
4405 /* find neighbour allocated blocks */
4406 ar.lleft = map->m_lblk;
4407 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4408 if (err)
4409 goto out2;
4410 ar.lright = map->m_lblk;
4411 ex2 = NULL;
4412 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4413 if (err)
4414 goto out2;
4416 /* Check if the extent after searching to the right implies a
4417 * cluster we can use. */
4418 if ((sbi->s_cluster_ratio > 1) && ex2 &&
4419 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4420 ar.len = allocated = map->m_len;
4421 newblock = map->m_pblk;
4422 map_from_cluster = true;
4423 goto got_allocated_blocks;
4427 * See if request is beyond maximum number of blocks we can have in
4428 * a single extent. For an initialized extent this limit is
4429 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4430 * EXT_UNWRITTEN_MAX_LEN.
4432 if (map->m_len > EXT_INIT_MAX_LEN &&
4433 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4434 map->m_len = EXT_INIT_MAX_LEN;
4435 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4436 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4437 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4439 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4440 newex.ee_len = cpu_to_le16(map->m_len);
4441 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4442 if (err)
4443 allocated = ext4_ext_get_actual_len(&newex);
4444 else
4445 allocated = map->m_len;
4447 /* allocate new block */
4448 ar.inode = inode;
4449 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4450 ar.logical = map->m_lblk;
4452 * We calculate the offset from the beginning of the cluster
4453 * for the logical block number, since when we allocate a
4454 * physical cluster, the physical block should start at the
4455 * same offset from the beginning of the cluster. This is
4456 * needed so that future calls to get_implied_cluster_alloc()
4457 * work correctly.
4459 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4460 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4461 ar.goal -= offset;
4462 ar.logical -= offset;
4463 if (S_ISREG(inode->i_mode))
4464 ar.flags = EXT4_MB_HINT_DATA;
4465 else
4466 /* disable in-core preallocation for non-regular files */
4467 ar.flags = 0;
4468 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4469 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4470 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4471 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4472 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4473 ar.flags |= EXT4_MB_USE_RESERVED;
4474 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4475 if (!newblock)
4476 goto out2;
4477 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4478 ar.goal, newblock, allocated);
4479 free_on_err = 1;
4480 allocated_clusters = ar.len;
4481 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4482 if (ar.len > allocated)
4483 ar.len = allocated;
4485 got_allocated_blocks:
4486 /* try to insert new extent into found leaf and return */
4487 ext4_ext_store_pblock(&newex, newblock + offset);
4488 newex.ee_len = cpu_to_le16(ar.len);
4489 /* Mark unwritten */
4490 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4491 ext4_ext_mark_unwritten(&newex);
4492 map->m_flags |= EXT4_MAP_UNWRITTEN;
4494 * io_end structure was created for every IO write to an
4495 * unwritten extent. To avoid unnecessary conversion,
4496 * here we flag the IO that really needs the conversion.
4497 * For non asycn direct IO case, flag the inode state
4498 * that we need to perform conversion when IO is done.
4500 if (flags & EXT4_GET_BLOCKS_PRE_IO)
4501 set_unwritten = 1;
4504 err = 0;
4505 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4506 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4507 path, ar.len);
4508 if (!err)
4509 err = ext4_ext_insert_extent(handle, inode, &path,
4510 &newex, flags);
4512 if (!err && set_unwritten) {
4513 if (io)
4514 ext4_set_io_unwritten_flag(inode, io);
4515 else
4516 ext4_set_inode_state(inode,
4517 EXT4_STATE_DIO_UNWRITTEN);
4520 if (err && free_on_err) {
4521 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4522 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4523 /* free data blocks we just allocated */
4524 /* not a good idea to call discard here directly,
4525 * but otherwise we'd need to call it every free() */
4526 ext4_discard_preallocations(inode);
4527 ext4_free_blocks(handle, inode, NULL, newblock,
4528 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4529 goto out2;
4532 /* previous routine could use block we allocated */
4533 newblock = ext4_ext_pblock(&newex);
4534 allocated = ext4_ext_get_actual_len(&newex);
4535 if (allocated > map->m_len)
4536 allocated = map->m_len;
4537 map->m_flags |= EXT4_MAP_NEW;
4540 * Update reserved blocks/metadata blocks after successful
4541 * block allocation which had been deferred till now.
4543 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4544 unsigned int reserved_clusters;
4546 * Check how many clusters we had reserved this allocated range
4548 reserved_clusters = get_reserved_cluster_alloc(inode,
4549 map->m_lblk, allocated);
4550 if (!map_from_cluster) {
4551 BUG_ON(allocated_clusters < reserved_clusters);
4552 if (reserved_clusters < allocated_clusters) {
4553 struct ext4_inode_info *ei = EXT4_I(inode);
4554 int reservation = allocated_clusters -
4555 reserved_clusters;
4557 * It seems we claimed few clusters outside of
4558 * the range of this allocation. We should give
4559 * it back to the reservation pool. This can
4560 * happen in the following case:
4562 * * Suppose s_cluster_ratio is 4 (i.e., each
4563 * cluster has 4 blocks. Thus, the clusters
4564 * are [0-3],[4-7],[8-11]...
4565 * * First comes delayed allocation write for
4566 * logical blocks 10 & 11. Since there were no
4567 * previous delayed allocated blocks in the
4568 * range [8-11], we would reserve 1 cluster
4569 * for this write.
4570 * * Next comes write for logical blocks 3 to 8.
4571 * In this case, we will reserve 2 clusters
4572 * (for [0-3] and [4-7]; and not for [8-11] as
4573 * that range has a delayed allocated blocks.
4574 * Thus total reserved clusters now becomes 3.
4575 * * Now, during the delayed allocation writeout
4576 * time, we will first write blocks [3-8] and
4577 * allocate 3 clusters for writing these
4578 * blocks. Also, we would claim all these
4579 * three clusters above.
4580 * * Now when we come here to writeout the
4581 * blocks [10-11], we would expect to claim
4582 * the reservation of 1 cluster we had made
4583 * (and we would claim it since there are no
4584 * more delayed allocated blocks in the range
4585 * [8-11]. But our reserved cluster count had
4586 * already gone to 0.
4588 * Thus, at the step 4 above when we determine
4589 * that there are still some unwritten delayed
4590 * allocated blocks outside of our current
4591 * block range, we should increment the
4592 * reserved clusters count so that when the
4593 * remaining blocks finally gets written, we
4594 * could claim them.
4596 dquot_reserve_block(inode,
4597 EXT4_C2B(sbi, reservation));
4598 spin_lock(&ei->i_block_reservation_lock);
4599 ei->i_reserved_data_blocks += reservation;
4600 spin_unlock(&ei->i_block_reservation_lock);
4603 * We will claim quota for all newly allocated blocks.
4604 * We're updating the reserved space *after* the
4605 * correction above so we do not accidentally free
4606 * all the metadata reservation because we might
4607 * actually need it later on.
4609 ext4_da_update_reserve_space(inode, allocated_clusters,
4615 * Cache the extent and update transaction to commit on fdatasync only
4616 * when it is _not_ an unwritten extent.
4618 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4619 ext4_update_inode_fsync_trans(handle, inode, 1);
4620 else
4621 ext4_update_inode_fsync_trans(handle, inode, 0);
4622 out:
4623 if (allocated > map->m_len)
4624 allocated = map->m_len;
4625 ext4_ext_show_leaf(inode, path);
4626 map->m_flags |= EXT4_MAP_MAPPED;
4627 map->m_pblk = newblock;
4628 map->m_len = allocated;
4629 out2:
4630 ext4_ext_drop_refs(path);
4631 kfree(path);
4633 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4634 err ? err : allocated);
4635 return err ? err : allocated;
4638 void ext4_ext_truncate(handle_t *handle, struct inode *inode)
4640 struct super_block *sb = inode->i_sb;
4641 ext4_lblk_t last_block;
4642 int err = 0;
4645 * TODO: optimization is possible here.
4646 * Probably we need not scan at all,
4647 * because page truncation is enough.
4650 /* we have to know where to truncate from in crash case */
4651 EXT4_I(inode)->i_disksize = inode->i_size;
4652 ext4_mark_inode_dirty(handle, inode);
4654 last_block = (inode->i_size + sb->s_blocksize - 1)
4655 >> EXT4_BLOCK_SIZE_BITS(sb);
4656 retry:
4657 err = ext4_es_remove_extent(inode, last_block,
4658 EXT_MAX_BLOCKS - last_block);
4659 if (err == -ENOMEM) {
4660 cond_resched();
4661 congestion_wait(BLK_RW_ASYNC, HZ/50);
4662 goto retry;
4664 if (err) {
4665 ext4_std_error(inode->i_sb, err);
4666 return;
4668 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4669 ext4_std_error(inode->i_sb, err);
4672 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4673 ext4_lblk_t len, loff_t new_size,
4674 int flags, int mode)
4676 struct inode *inode = file_inode(file);
4677 handle_t *handle;
4678 int ret = 0;
4679 int ret2 = 0;
4680 int retries = 0;
4681 int depth = 0;
4682 struct ext4_map_blocks map;
4683 unsigned int credits;
4684 loff_t epos;
4686 map.m_lblk = offset;
4687 map.m_len = len;
4689 * Don't normalize the request if it can fit in one extent so
4690 * that it doesn't get unnecessarily split into multiple
4691 * extents.
4693 if (len <= EXT_UNWRITTEN_MAX_LEN)
4694 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4697 * credits to insert 1 extent into extent tree
4699 credits = ext4_chunk_trans_blocks(inode, len);
4701 * We can only call ext_depth() on extent based inodes
4703 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4704 depth = ext_depth(inode);
4705 else
4706 depth = -1;
4708 retry:
4709 while (ret >= 0 && len) {
4711 * Recalculate credits when extent tree depth changes.
4713 if (depth >= 0 && depth != ext_depth(inode)) {
4714 credits = ext4_chunk_trans_blocks(inode, len);
4715 depth = ext_depth(inode);
4718 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4719 credits);
4720 if (IS_ERR(handle)) {
4721 ret = PTR_ERR(handle);
4722 break;
4724 ret = ext4_map_blocks(handle, inode, &map, flags);
4725 if (ret <= 0) {
4726 ext4_debug("inode #%lu: block %u: len %u: "
4727 "ext4_ext_map_blocks returned %d",
4728 inode->i_ino, map.m_lblk,
4729 map.m_len, ret);
4730 ext4_mark_inode_dirty(handle, inode);
4731 ret2 = ext4_journal_stop(handle);
4732 break;
4734 map.m_lblk += ret;
4735 map.m_len = len = len - ret;
4736 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4737 inode->i_ctime = ext4_current_time(inode);
4738 if (new_size) {
4739 if (epos > new_size)
4740 epos = new_size;
4741 if (ext4_update_inode_size(inode, epos) & 0x1)
4742 inode->i_mtime = inode->i_ctime;
4743 } else {
4744 if (epos > inode->i_size)
4745 ext4_set_inode_flag(inode,
4746 EXT4_INODE_EOFBLOCKS);
4748 ext4_mark_inode_dirty(handle, inode);
4749 ret2 = ext4_journal_stop(handle);
4750 if (ret2)
4751 break;
4753 if (ret == -ENOSPC &&
4754 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4755 ret = 0;
4756 goto retry;
4759 return ret > 0 ? ret2 : ret;
4762 static long ext4_zero_range(struct file *file, loff_t offset,
4763 loff_t len, int mode)
4765 struct inode *inode = file_inode(file);
4766 handle_t *handle = NULL;
4767 unsigned int max_blocks;
4768 loff_t new_size = 0;
4769 int ret = 0;
4770 int flags;
4771 int credits;
4772 int partial_begin, partial_end;
4773 loff_t start, end;
4774 ext4_lblk_t lblk;
4775 unsigned int blkbits = inode->i_blkbits;
4777 trace_ext4_zero_range(inode, offset, len, mode);
4779 if (!S_ISREG(inode->i_mode))
4780 return -EINVAL;
4782 /* Call ext4_force_commit to flush all data in case of data=journal. */
4783 if (ext4_should_journal_data(inode)) {
4784 ret = ext4_force_commit(inode->i_sb);
4785 if (ret)
4786 return ret;
4790 * Round up offset. This is not fallocate, we neet to zero out
4791 * blocks, so convert interior block aligned part of the range to
4792 * unwritten and possibly manually zero out unaligned parts of the
4793 * range.
4795 start = round_up(offset, 1 << blkbits);
4796 end = round_down((offset + len), 1 << blkbits);
4798 if (start < offset || end > offset + len)
4799 return -EINVAL;
4800 partial_begin = offset & ((1 << blkbits) - 1);
4801 partial_end = (offset + len) & ((1 << blkbits) - 1);
4803 lblk = start >> blkbits;
4804 max_blocks = (end >> blkbits);
4805 if (max_blocks < lblk)
4806 max_blocks = 0;
4807 else
4808 max_blocks -= lblk;
4810 mutex_lock(&inode->i_mutex);
4813 * Indirect files do not support unwritten extnets
4815 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4816 ret = -EOPNOTSUPP;
4817 goto out_mutex;
4820 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4821 offset + len > i_size_read(inode)) {
4822 new_size = offset + len;
4823 ret = inode_newsize_ok(inode, new_size);
4824 if (ret)
4825 goto out_mutex;
4828 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4829 if (mode & FALLOC_FL_KEEP_SIZE)
4830 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4832 /* Wait all existing dio workers, newcomers will block on i_mutex */
4833 ext4_inode_block_unlocked_dio(inode);
4834 inode_dio_wait(inode);
4836 /* Preallocate the range including the unaligned edges */
4837 if (partial_begin || partial_end) {
4838 ret = ext4_alloc_file_blocks(file,
4839 round_down(offset, 1 << blkbits) >> blkbits,
4840 (round_up((offset + len), 1 << blkbits) -
4841 round_down(offset, 1 << blkbits)) >> blkbits,
4842 new_size, flags, mode);
4843 if (ret)
4844 goto out_dio;
4848 /* Zero range excluding the unaligned edges */
4849 if (max_blocks > 0) {
4850 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4851 EXT4_EX_NOCACHE);
4854 * Prevent page faults from reinstantiating pages we have
4855 * released from page cache.
4857 down_write(&EXT4_I(inode)->i_mmap_sem);
4858 ret = ext4_update_disksize_before_punch(inode, offset, len);
4859 if (ret) {
4860 up_write(&EXT4_I(inode)->i_mmap_sem);
4861 goto out_dio;
4863 /* Now release the pages and zero block aligned part of pages */
4864 truncate_pagecache_range(inode, start, end - 1);
4865 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4867 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4868 flags, mode);
4869 up_write(&EXT4_I(inode)->i_mmap_sem);
4870 if (ret)
4871 goto out_dio;
4873 if (!partial_begin && !partial_end)
4874 goto out_dio;
4877 * In worst case we have to writeout two nonadjacent unwritten
4878 * blocks and update the inode
4880 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4881 if (ext4_should_journal_data(inode))
4882 credits += 2;
4883 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4884 if (IS_ERR(handle)) {
4885 ret = PTR_ERR(handle);
4886 ext4_std_error(inode->i_sb, ret);
4887 goto out_dio;
4890 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4891 if (new_size) {
4892 ext4_update_inode_size(inode, new_size);
4893 } else {
4895 * Mark that we allocate beyond EOF so the subsequent truncate
4896 * can proceed even if the new size is the same as i_size.
4898 if ((offset + len) > i_size_read(inode))
4899 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4901 ext4_mark_inode_dirty(handle, inode);
4903 /* Zero out partial block at the edges of the range */
4904 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4906 if (file->f_flags & O_SYNC)
4907 ext4_handle_sync(handle);
4909 ext4_journal_stop(handle);
4910 out_dio:
4911 ext4_inode_resume_unlocked_dio(inode);
4912 out_mutex:
4913 mutex_unlock(&inode->i_mutex);
4914 return ret;
4918 * preallocate space for a file. This implements ext4's fallocate file
4919 * operation, which gets called from sys_fallocate system call.
4920 * For block-mapped files, posix_fallocate should fall back to the method
4921 * of writing zeroes to the required new blocks (the same behavior which is
4922 * expected for file systems which do not support fallocate() system call).
4924 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4926 struct inode *inode = file_inode(file);
4927 loff_t new_size = 0;
4928 unsigned int max_blocks;
4929 int ret = 0;
4930 int flags;
4931 ext4_lblk_t lblk;
4932 unsigned int blkbits = inode->i_blkbits;
4935 * Encrypted inodes can't handle collapse range or insert
4936 * range since we would need to re-encrypt blocks with a
4937 * different IV or XTS tweak (which are based on the logical
4938 * block number).
4940 * XXX It's not clear why zero range isn't working, but we'll
4941 * leave it disabled for encrypted inodes for now. This is a
4942 * bug we should fix....
4944 if (ext4_encrypted_inode(inode) &&
4945 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
4946 FALLOC_FL_ZERO_RANGE)))
4947 return -EOPNOTSUPP;
4949 /* Return error if mode is not supported */
4950 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4951 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4952 FALLOC_FL_INSERT_RANGE))
4953 return -EOPNOTSUPP;
4955 if (mode & FALLOC_FL_PUNCH_HOLE)
4956 return ext4_punch_hole(inode, offset, len);
4958 ret = ext4_convert_inline_data(inode);
4959 if (ret)
4960 return ret;
4962 if (mode & FALLOC_FL_COLLAPSE_RANGE)
4963 return ext4_collapse_range(inode, offset, len);
4965 if (mode & FALLOC_FL_INSERT_RANGE)
4966 return ext4_insert_range(inode, offset, len);
4968 if (mode & FALLOC_FL_ZERO_RANGE)
4969 return ext4_zero_range(file, offset, len, mode);
4971 trace_ext4_fallocate_enter(inode, offset, len, mode);
4972 lblk = offset >> blkbits;
4974 * We can't just convert len to max_blocks because
4975 * If blocksize = 4096 offset = 3072 and len = 2048
4977 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
4978 - lblk;
4980 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4981 if (mode & FALLOC_FL_KEEP_SIZE)
4982 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4984 mutex_lock(&inode->i_mutex);
4987 * We only support preallocation for extent-based files only
4989 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4990 ret = -EOPNOTSUPP;
4991 goto out;
4994 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4995 offset + len > i_size_read(inode)) {
4996 new_size = offset + len;
4997 ret = inode_newsize_ok(inode, new_size);
4998 if (ret)
4999 goto out;
5002 /* Wait all existing dio workers, newcomers will block on i_mutex */
5003 ext4_inode_block_unlocked_dio(inode);
5004 inode_dio_wait(inode);
5006 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
5007 flags, mode);
5008 ext4_inode_resume_unlocked_dio(inode);
5009 if (ret)
5010 goto out;
5012 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
5013 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5014 EXT4_I(inode)->i_sync_tid);
5016 out:
5017 mutex_unlock(&inode->i_mutex);
5018 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
5019 return ret;
5023 * This function convert a range of blocks to written extents
5024 * The caller of this function will pass the start offset and the size.
5025 * all unwritten extents within this range will be converted to
5026 * written extents.
5028 * This function is called from the direct IO end io call back
5029 * function, to convert the fallocated extents after IO is completed.
5030 * Returns 0 on success.
5032 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
5033 loff_t offset, ssize_t len)
5035 unsigned int max_blocks;
5036 int ret = 0;
5037 int ret2 = 0;
5038 struct ext4_map_blocks map;
5039 unsigned int credits, blkbits = inode->i_blkbits;
5041 map.m_lblk = offset >> blkbits;
5043 * We can't just convert len to max_blocks because
5044 * If blocksize = 4096 offset = 3072 and len = 2048
5046 max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
5047 map.m_lblk);
5049 * This is somewhat ugly but the idea is clear: When transaction is
5050 * reserved, everything goes into it. Otherwise we rather start several
5051 * smaller transactions for conversion of each extent separately.
5053 if (handle) {
5054 handle = ext4_journal_start_reserved(handle,
5055 EXT4_HT_EXT_CONVERT);
5056 if (IS_ERR(handle))
5057 return PTR_ERR(handle);
5058 credits = 0;
5059 } else {
5061 * credits to insert 1 extent into extent tree
5063 credits = ext4_chunk_trans_blocks(inode, max_blocks);
5065 while (ret >= 0 && ret < max_blocks) {
5066 map.m_lblk += ret;
5067 map.m_len = (max_blocks -= ret);
5068 if (credits) {
5069 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5070 credits);
5071 if (IS_ERR(handle)) {
5072 ret = PTR_ERR(handle);
5073 break;
5076 ret = ext4_map_blocks(handle, inode, &map,
5077 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5078 if (ret <= 0)
5079 ext4_warning(inode->i_sb,
5080 "inode #%lu: block %u: len %u: "
5081 "ext4_ext_map_blocks returned %d",
5082 inode->i_ino, map.m_lblk,
5083 map.m_len, ret);
5084 ext4_mark_inode_dirty(handle, inode);
5085 if (credits)
5086 ret2 = ext4_journal_stop(handle);
5087 if (ret <= 0 || ret2)
5088 break;
5090 if (!credits)
5091 ret2 = ext4_journal_stop(handle);
5092 return ret > 0 ? ret2 : ret;
5096 * If newes is not existing extent (newes->ec_pblk equals zero) find
5097 * delayed extent at start of newes and update newes accordingly and
5098 * return start of the next delayed extent.
5100 * If newes is existing extent (newes->ec_pblk is not equal zero)
5101 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5102 * extent found. Leave newes unmodified.
5104 static int ext4_find_delayed_extent(struct inode *inode,
5105 struct extent_status *newes)
5107 struct extent_status es;
5108 ext4_lblk_t block, next_del;
5110 if (newes->es_pblk == 0) {
5111 ext4_es_find_delayed_extent_range(inode, newes->es_lblk,
5112 newes->es_lblk + newes->es_len - 1, &es);
5115 * No extent in extent-tree contains block @newes->es_pblk,
5116 * then the block may stay in 1)a hole or 2)delayed-extent.
5118 if (es.es_len == 0)
5119 /* A hole found. */
5120 return 0;
5122 if (es.es_lblk > newes->es_lblk) {
5123 /* A hole found. */
5124 newes->es_len = min(es.es_lblk - newes->es_lblk,
5125 newes->es_len);
5126 return 0;
5129 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5132 block = newes->es_lblk + newes->es_len;
5133 ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es);
5134 if (es.es_len == 0)
5135 next_del = EXT_MAX_BLOCKS;
5136 else
5137 next_del = es.es_lblk;
5139 return next_del;
5141 /* fiemap flags we can handle specified here */
5142 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
5144 static int ext4_xattr_fiemap(struct inode *inode,
5145 struct fiemap_extent_info *fieinfo)
5147 __u64 physical = 0;
5148 __u64 length;
5149 __u32 flags = FIEMAP_EXTENT_LAST;
5150 int blockbits = inode->i_sb->s_blocksize_bits;
5151 int error = 0;
5153 /* in-inode? */
5154 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5155 struct ext4_iloc iloc;
5156 int offset; /* offset of xattr in inode */
5158 error = ext4_get_inode_loc(inode, &iloc);
5159 if (error)
5160 return error;
5161 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5162 offset = EXT4_GOOD_OLD_INODE_SIZE +
5163 EXT4_I(inode)->i_extra_isize;
5164 physical += offset;
5165 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5166 flags |= FIEMAP_EXTENT_DATA_INLINE;
5167 brelse(iloc.bh);
5168 } else { /* external block */
5169 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5170 length = inode->i_sb->s_blocksize;
5173 if (physical)
5174 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5175 length, flags);
5176 return (error < 0 ? error : 0);
5179 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5180 __u64 start, __u64 len)
5182 ext4_lblk_t start_blk;
5183 int error = 0;
5185 if (ext4_has_inline_data(inode)) {
5186 int has_inline = 1;
5188 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5189 start, len);
5191 if (has_inline)
5192 return error;
5195 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5196 error = ext4_ext_precache(inode);
5197 if (error)
5198 return error;
5201 /* fallback to generic here if not in extents fmt */
5202 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5203 return generic_block_fiemap(inode, fieinfo, start, len,
5204 ext4_get_block);
5206 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
5207 return -EBADR;
5209 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5210 error = ext4_xattr_fiemap(inode, fieinfo);
5211 } else {
5212 ext4_lblk_t len_blks;
5213 __u64 last_blk;
5215 start_blk = start >> inode->i_sb->s_blocksize_bits;
5216 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5217 if (last_blk >= EXT_MAX_BLOCKS)
5218 last_blk = EXT_MAX_BLOCKS-1;
5219 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5222 * Walk the extent tree gathering extent information
5223 * and pushing extents back to the user.
5225 error = ext4_fill_fiemap_extents(inode, start_blk,
5226 len_blks, fieinfo);
5228 return error;
5232 * ext4_access_path:
5233 * Function to access the path buffer for marking it dirty.
5234 * It also checks if there are sufficient credits left in the journal handle
5235 * to update path.
5237 static int
5238 ext4_access_path(handle_t *handle, struct inode *inode,
5239 struct ext4_ext_path *path)
5241 int credits, err;
5243 if (!ext4_handle_valid(handle))
5244 return 0;
5247 * Check if need to extend journal credits
5248 * 3 for leaf, sb, and inode plus 2 (bmap and group
5249 * descriptor) for each block group; assume two block
5250 * groups
5252 if (handle->h_buffer_credits < 7) {
5253 credits = ext4_writepage_trans_blocks(inode);
5254 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
5255 /* EAGAIN is success */
5256 if (err && err != -EAGAIN)
5257 return err;
5260 err = ext4_ext_get_access(handle, inode, path);
5261 return err;
5265 * ext4_ext_shift_path_extents:
5266 * Shift the extents of a path structure lying between path[depth].p_ext
5267 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5268 * if it is right shift or left shift operation.
5270 static int
5271 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5272 struct inode *inode, handle_t *handle,
5273 enum SHIFT_DIRECTION SHIFT)
5275 int depth, err = 0;
5276 struct ext4_extent *ex_start, *ex_last;
5277 bool update = 0;
5278 depth = path->p_depth;
5280 while (depth >= 0) {
5281 if (depth == path->p_depth) {
5282 ex_start = path[depth].p_ext;
5283 if (!ex_start)
5284 return -EFSCORRUPTED;
5286 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5288 err = ext4_access_path(handle, inode, path + depth);
5289 if (err)
5290 goto out;
5292 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5293 update = 1;
5295 while (ex_start <= ex_last) {
5296 if (SHIFT == SHIFT_LEFT) {
5297 le32_add_cpu(&ex_start->ee_block,
5298 -shift);
5299 /* Try to merge to the left. */
5300 if ((ex_start >
5301 EXT_FIRST_EXTENT(path[depth].p_hdr))
5303 ext4_ext_try_to_merge_right(inode,
5304 path, ex_start - 1))
5305 ex_last--;
5306 else
5307 ex_start++;
5308 } else {
5309 le32_add_cpu(&ex_last->ee_block, shift);
5310 ext4_ext_try_to_merge_right(inode, path,
5311 ex_last);
5312 ex_last--;
5315 err = ext4_ext_dirty(handle, inode, path + depth);
5316 if (err)
5317 goto out;
5319 if (--depth < 0 || !update)
5320 break;
5323 /* Update index too */
5324 err = ext4_access_path(handle, inode, path + depth);
5325 if (err)
5326 goto out;
5328 if (SHIFT == SHIFT_LEFT)
5329 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5330 else
5331 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5332 err = ext4_ext_dirty(handle, inode, path + depth);
5333 if (err)
5334 goto out;
5336 /* we are done if current index is not a starting index */
5337 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5338 break;
5340 depth--;
5343 out:
5344 return err;
5348 * ext4_ext_shift_extents:
5349 * All the extents which lies in the range from @start to the last allocated
5350 * block for the @inode are shifted either towards left or right (depending
5351 * upon @SHIFT) by @shift blocks.
5352 * On success, 0 is returned, error otherwise.
5354 static int
5355 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5356 ext4_lblk_t start, ext4_lblk_t shift,
5357 enum SHIFT_DIRECTION SHIFT)
5359 struct ext4_ext_path *path;
5360 int ret = 0, depth;
5361 struct ext4_extent *extent;
5362 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5364 /* Let path point to the last extent */
5365 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5366 EXT4_EX_NOCACHE);
5367 if (IS_ERR(path))
5368 return PTR_ERR(path);
5370 depth = path->p_depth;
5371 extent = path[depth].p_ext;
5372 if (!extent)
5373 goto out;
5375 stop = le32_to_cpu(extent->ee_block);
5378 * In case of left shift, Don't start shifting extents until we make
5379 * sure the hole is big enough to accommodate the shift.
5381 if (SHIFT == SHIFT_LEFT) {
5382 path = ext4_find_extent(inode, start - 1, &path,
5383 EXT4_EX_NOCACHE);
5384 if (IS_ERR(path))
5385 return PTR_ERR(path);
5386 depth = path->p_depth;
5387 extent = path[depth].p_ext;
5388 if (extent) {
5389 ex_start = le32_to_cpu(extent->ee_block);
5390 ex_end = le32_to_cpu(extent->ee_block) +
5391 ext4_ext_get_actual_len(extent);
5392 } else {
5393 ex_start = 0;
5394 ex_end = 0;
5397 if ((start == ex_start && shift > ex_start) ||
5398 (shift > start - ex_end)) {
5399 ext4_ext_drop_refs(path);
5400 kfree(path);
5401 return -EINVAL;
5406 * In case of left shift, iterator points to start and it is increased
5407 * till we reach stop. In case of right shift, iterator points to stop
5408 * and it is decreased till we reach start.
5410 if (SHIFT == SHIFT_LEFT)
5411 iterator = &start;
5412 else
5413 iterator = &stop;
5416 * Its safe to start updating extents. Start and stop are unsigned, so
5417 * in case of right shift if extent with 0 block is reached, iterator
5418 * becomes NULL to indicate the end of the loop.
5420 while (iterator && start <= stop) {
5421 path = ext4_find_extent(inode, *iterator, &path,
5422 EXT4_EX_NOCACHE);
5423 if (IS_ERR(path))
5424 return PTR_ERR(path);
5425 depth = path->p_depth;
5426 extent = path[depth].p_ext;
5427 if (!extent) {
5428 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5429 (unsigned long) *iterator);
5430 return -EFSCORRUPTED;
5432 if (SHIFT == SHIFT_LEFT && *iterator >
5433 le32_to_cpu(extent->ee_block)) {
5434 /* Hole, move to the next extent */
5435 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5436 path[depth].p_ext++;
5437 } else {
5438 *iterator = ext4_ext_next_allocated_block(path);
5439 continue;
5443 if (SHIFT == SHIFT_LEFT) {
5444 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5445 *iterator = le32_to_cpu(extent->ee_block) +
5446 ext4_ext_get_actual_len(extent);
5447 } else {
5448 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5449 if (le32_to_cpu(extent->ee_block) > 0)
5450 *iterator = le32_to_cpu(extent->ee_block) - 1;
5451 else
5452 /* Beginning is reached, end of the loop */
5453 iterator = NULL;
5454 /* Update path extent in case we need to stop */
5455 while (le32_to_cpu(extent->ee_block) < start)
5456 extent++;
5457 path[depth].p_ext = extent;
5459 ret = ext4_ext_shift_path_extents(path, shift, inode,
5460 handle, SHIFT);
5461 if (ret)
5462 break;
5464 out:
5465 ext4_ext_drop_refs(path);
5466 kfree(path);
5467 return ret;
5471 * ext4_collapse_range:
5472 * This implements the fallocate's collapse range functionality for ext4
5473 * Returns: 0 and non-zero on error.
5475 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5477 struct super_block *sb = inode->i_sb;
5478 ext4_lblk_t punch_start, punch_stop;
5479 handle_t *handle;
5480 unsigned int credits;
5481 loff_t new_size, ioffset;
5482 int ret;
5485 * We need to test this early because xfstests assumes that a
5486 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5487 * system does not support collapse range.
5489 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5490 return -EOPNOTSUPP;
5492 /* Collapse range works only on fs block size aligned offsets. */
5493 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5494 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5495 return -EINVAL;
5497 if (!S_ISREG(inode->i_mode))
5498 return -EINVAL;
5500 trace_ext4_collapse_range(inode, offset, len);
5502 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5503 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5505 /* Call ext4_force_commit to flush all data in case of data=journal. */
5506 if (ext4_should_journal_data(inode)) {
5507 ret = ext4_force_commit(inode->i_sb);
5508 if (ret)
5509 return ret;
5512 mutex_lock(&inode->i_mutex);
5514 * There is no need to overlap collapse range with EOF, in which case
5515 * it is effectively a truncate operation
5517 if (offset + len >= i_size_read(inode)) {
5518 ret = -EINVAL;
5519 goto out_mutex;
5522 /* Currently just for extent based files */
5523 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5524 ret = -EOPNOTSUPP;
5525 goto out_mutex;
5528 /* Wait for existing dio to complete */
5529 ext4_inode_block_unlocked_dio(inode);
5530 inode_dio_wait(inode);
5533 * Prevent page faults from reinstantiating pages we have released from
5534 * page cache.
5536 down_write(&EXT4_I(inode)->i_mmap_sem);
5538 * Need to round down offset to be aligned with page size boundary
5539 * for page size > block size.
5541 ioffset = round_down(offset, PAGE_SIZE);
5543 * Write tail of the last page before removed range since it will get
5544 * removed from the page cache below.
5546 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5547 if (ret)
5548 goto out_mmap;
5550 * Write data that will be shifted to preserve them when discarding
5551 * page cache below. We are also protected from pages becoming dirty
5552 * by i_mmap_sem.
5554 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5555 LLONG_MAX);
5556 if (ret)
5557 goto out_mmap;
5558 truncate_pagecache(inode, ioffset);
5560 credits = ext4_writepage_trans_blocks(inode);
5561 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5562 if (IS_ERR(handle)) {
5563 ret = PTR_ERR(handle);
5564 goto out_mmap;
5567 down_write(&EXT4_I(inode)->i_data_sem);
5568 ext4_discard_preallocations(inode);
5570 ret = ext4_es_remove_extent(inode, punch_start,
5571 EXT_MAX_BLOCKS - punch_start);
5572 if (ret) {
5573 up_write(&EXT4_I(inode)->i_data_sem);
5574 goto out_stop;
5577 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5578 if (ret) {
5579 up_write(&EXT4_I(inode)->i_data_sem);
5580 goto out_stop;
5582 ext4_discard_preallocations(inode);
5584 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5585 punch_stop - punch_start, SHIFT_LEFT);
5586 if (ret) {
5587 up_write(&EXT4_I(inode)->i_data_sem);
5588 goto out_stop;
5591 new_size = i_size_read(inode) - len;
5592 i_size_write(inode, new_size);
5593 EXT4_I(inode)->i_disksize = new_size;
5595 up_write(&EXT4_I(inode)->i_data_sem);
5596 if (IS_SYNC(inode))
5597 ext4_handle_sync(handle);
5598 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5599 ext4_mark_inode_dirty(handle, inode);
5601 out_stop:
5602 ext4_journal_stop(handle);
5603 out_mmap:
5604 up_write(&EXT4_I(inode)->i_mmap_sem);
5605 ext4_inode_resume_unlocked_dio(inode);
5606 out_mutex:
5607 mutex_unlock(&inode->i_mutex);
5608 return ret;
5612 * ext4_insert_range:
5613 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5614 * The data blocks starting from @offset to the EOF are shifted by @len
5615 * towards right to create a hole in the @inode. Inode size is increased
5616 * by len bytes.
5617 * Returns 0 on success, error otherwise.
5619 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5621 struct super_block *sb = inode->i_sb;
5622 handle_t *handle;
5623 struct ext4_ext_path *path;
5624 struct ext4_extent *extent;
5625 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5626 unsigned int credits, ee_len;
5627 int ret = 0, depth, split_flag = 0;
5628 loff_t ioffset;
5631 * We need to test this early because xfstests assumes that an
5632 * insert range of (0, 1) will return EOPNOTSUPP if the file
5633 * system does not support insert range.
5635 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5636 return -EOPNOTSUPP;
5638 /* Insert range works only on fs block size aligned offsets. */
5639 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5640 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5641 return -EINVAL;
5643 if (!S_ISREG(inode->i_mode))
5644 return -EOPNOTSUPP;
5646 trace_ext4_insert_range(inode, offset, len);
5648 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5649 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5651 /* Call ext4_force_commit to flush all data in case of data=journal */
5652 if (ext4_should_journal_data(inode)) {
5653 ret = ext4_force_commit(inode->i_sb);
5654 if (ret)
5655 return ret;
5658 mutex_lock(&inode->i_mutex);
5659 /* Currently just for extent based files */
5660 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5661 ret = -EOPNOTSUPP;
5662 goto out_mutex;
5665 /* Check for wrap through zero */
5666 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5667 ret = -EFBIG;
5668 goto out_mutex;
5671 /* Offset should be less than i_size */
5672 if (offset >= i_size_read(inode)) {
5673 ret = -EINVAL;
5674 goto out_mutex;
5677 /* Wait for existing dio to complete */
5678 ext4_inode_block_unlocked_dio(inode);
5679 inode_dio_wait(inode);
5682 * Prevent page faults from reinstantiating pages we have released from
5683 * page cache.
5685 down_write(&EXT4_I(inode)->i_mmap_sem);
5687 * Need to round down to align start offset to page size boundary
5688 * for page size > block size.
5690 ioffset = round_down(offset, PAGE_SIZE);
5691 /* Write out all dirty pages */
5692 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5693 LLONG_MAX);
5694 if (ret)
5695 goto out_mmap;
5696 truncate_pagecache(inode, ioffset);
5698 credits = ext4_writepage_trans_blocks(inode);
5699 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5700 if (IS_ERR(handle)) {
5701 ret = PTR_ERR(handle);
5702 goto out_mmap;
5705 /* Expand file to avoid data loss if there is error while shifting */
5706 inode->i_size += len;
5707 EXT4_I(inode)->i_disksize += len;
5708 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5709 ret = ext4_mark_inode_dirty(handle, inode);
5710 if (ret)
5711 goto out_stop;
5713 down_write(&EXT4_I(inode)->i_data_sem);
5714 ext4_discard_preallocations(inode);
5716 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5717 if (IS_ERR(path)) {
5718 up_write(&EXT4_I(inode)->i_data_sem);
5719 goto out_stop;
5722 depth = ext_depth(inode);
5723 extent = path[depth].p_ext;
5724 if (extent) {
5725 ee_start_lblk = le32_to_cpu(extent->ee_block);
5726 ee_len = ext4_ext_get_actual_len(extent);
5729 * If offset_lblk is not the starting block of extent, split
5730 * the extent @offset_lblk
5732 if ((offset_lblk > ee_start_lblk) &&
5733 (offset_lblk < (ee_start_lblk + ee_len))) {
5734 if (ext4_ext_is_unwritten(extent))
5735 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5736 EXT4_EXT_MARK_UNWRIT2;
5737 ret = ext4_split_extent_at(handle, inode, &path,
5738 offset_lblk, split_flag,
5739 EXT4_EX_NOCACHE |
5740 EXT4_GET_BLOCKS_PRE_IO |
5741 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5744 ext4_ext_drop_refs(path);
5745 kfree(path);
5746 if (ret < 0) {
5747 up_write(&EXT4_I(inode)->i_data_sem);
5748 goto out_stop;
5750 } else {
5751 ext4_ext_drop_refs(path);
5752 kfree(path);
5755 ret = ext4_es_remove_extent(inode, offset_lblk,
5756 EXT_MAX_BLOCKS - offset_lblk);
5757 if (ret) {
5758 up_write(&EXT4_I(inode)->i_data_sem);
5759 goto out_stop;
5763 * if offset_lblk lies in a hole which is at start of file, use
5764 * ee_start_lblk to shift extents
5766 ret = ext4_ext_shift_extents(inode, handle,
5767 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5768 len_lblk, SHIFT_RIGHT);
5770 up_write(&EXT4_I(inode)->i_data_sem);
5771 if (IS_SYNC(inode))
5772 ext4_handle_sync(handle);
5774 out_stop:
5775 ext4_journal_stop(handle);
5776 out_mmap:
5777 up_write(&EXT4_I(inode)->i_mmap_sem);
5778 ext4_inode_resume_unlocked_dio(inode);
5779 out_mutex:
5780 mutex_unlock(&inode->i_mutex);
5781 return ret;
5785 * ext4_swap_extents - Swap extents between two inodes
5787 * @inode1: First inode
5788 * @inode2: Second inode
5789 * @lblk1: Start block for first inode
5790 * @lblk2: Start block for second inode
5791 * @count: Number of blocks to swap
5792 * @mark_unwritten: Mark second inode's extents as unwritten after swap
5793 * @erp: Pointer to save error value
5795 * This helper routine does exactly what is promise "swap extents". All other
5796 * stuff such as page-cache locking consistency, bh mapping consistency or
5797 * extent's data copying must be performed by caller.
5798 * Locking:
5799 * i_mutex is held for both inodes
5800 * i_data_sem is locked for write for both inodes
5801 * Assumptions:
5802 * All pages from requested range are locked for both inodes
5805 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5806 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5807 ext4_lblk_t count, int unwritten, int *erp)
5809 struct ext4_ext_path *path1 = NULL;
5810 struct ext4_ext_path *path2 = NULL;
5811 int replaced_count = 0;
5813 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5814 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5815 BUG_ON(!mutex_is_locked(&inode1->i_mutex));
5816 BUG_ON(!mutex_is_locked(&inode2->i_mutex));
5818 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5819 if (unlikely(*erp))
5820 return 0;
5821 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5822 if (unlikely(*erp))
5823 return 0;
5825 while (count) {
5826 struct ext4_extent *ex1, *ex2, tmp_ex;
5827 ext4_lblk_t e1_blk, e2_blk;
5828 int e1_len, e2_len, len;
5829 int split = 0;
5831 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5832 if (IS_ERR(path1)) {
5833 *erp = PTR_ERR(path1);
5834 path1 = NULL;
5835 finish:
5836 count = 0;
5837 goto repeat;
5839 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5840 if (IS_ERR(path2)) {
5841 *erp = PTR_ERR(path2);
5842 path2 = NULL;
5843 goto finish;
5845 ex1 = path1[path1->p_depth].p_ext;
5846 ex2 = path2[path2->p_depth].p_ext;
5847 /* Do we have somthing to swap ? */
5848 if (unlikely(!ex2 || !ex1))
5849 goto finish;
5851 e1_blk = le32_to_cpu(ex1->ee_block);
5852 e2_blk = le32_to_cpu(ex2->ee_block);
5853 e1_len = ext4_ext_get_actual_len(ex1);
5854 e2_len = ext4_ext_get_actual_len(ex2);
5856 /* Hole handling */
5857 if (!in_range(lblk1, e1_blk, e1_len) ||
5858 !in_range(lblk2, e2_blk, e2_len)) {
5859 ext4_lblk_t next1, next2;
5861 /* if hole after extent, then go to next extent */
5862 next1 = ext4_ext_next_allocated_block(path1);
5863 next2 = ext4_ext_next_allocated_block(path2);
5864 /* If hole before extent, then shift to that extent */
5865 if (e1_blk > lblk1)
5866 next1 = e1_blk;
5867 if (e2_blk > lblk2)
5868 next2 = e1_blk;
5869 /* Do we have something to swap */
5870 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5871 goto finish;
5872 /* Move to the rightest boundary */
5873 len = next1 - lblk1;
5874 if (len < next2 - lblk2)
5875 len = next2 - lblk2;
5876 if (len > count)
5877 len = count;
5878 lblk1 += len;
5879 lblk2 += len;
5880 count -= len;
5881 goto repeat;
5884 /* Prepare left boundary */
5885 if (e1_blk < lblk1) {
5886 split = 1;
5887 *erp = ext4_force_split_extent_at(handle, inode1,
5888 &path1, lblk1, 0);
5889 if (unlikely(*erp))
5890 goto finish;
5892 if (e2_blk < lblk2) {
5893 split = 1;
5894 *erp = ext4_force_split_extent_at(handle, inode2,
5895 &path2, lblk2, 0);
5896 if (unlikely(*erp))
5897 goto finish;
5899 /* ext4_split_extent_at() may result in leaf extent split,
5900 * path must to be revalidated. */
5901 if (split)
5902 goto repeat;
5904 /* Prepare right boundary */
5905 len = count;
5906 if (len > e1_blk + e1_len - lblk1)
5907 len = e1_blk + e1_len - lblk1;
5908 if (len > e2_blk + e2_len - lblk2)
5909 len = e2_blk + e2_len - lblk2;
5911 if (len != e1_len) {
5912 split = 1;
5913 *erp = ext4_force_split_extent_at(handle, inode1,
5914 &path1, lblk1 + len, 0);
5915 if (unlikely(*erp))
5916 goto finish;
5918 if (len != e2_len) {
5919 split = 1;
5920 *erp = ext4_force_split_extent_at(handle, inode2,
5921 &path2, lblk2 + len, 0);
5922 if (*erp)
5923 goto finish;
5925 /* ext4_split_extent_at() may result in leaf extent split,
5926 * path must to be revalidated. */
5927 if (split)
5928 goto repeat;
5930 BUG_ON(e2_len != e1_len);
5931 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5932 if (unlikely(*erp))
5933 goto finish;
5934 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5935 if (unlikely(*erp))
5936 goto finish;
5938 /* Both extents are fully inside boundaries. Swap it now */
5939 tmp_ex = *ex1;
5940 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5941 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5942 ex1->ee_len = cpu_to_le16(e2_len);
5943 ex2->ee_len = cpu_to_le16(e1_len);
5944 if (unwritten)
5945 ext4_ext_mark_unwritten(ex2);
5946 if (ext4_ext_is_unwritten(&tmp_ex))
5947 ext4_ext_mark_unwritten(ex1);
5949 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5950 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5951 *erp = ext4_ext_dirty(handle, inode2, path2 +
5952 path2->p_depth);
5953 if (unlikely(*erp))
5954 goto finish;
5955 *erp = ext4_ext_dirty(handle, inode1, path1 +
5956 path1->p_depth);
5958 * Looks scarry ah..? second inode already points to new blocks,
5959 * and it was successfully dirtied. But luckily error may happen
5960 * only due to journal error, so full transaction will be
5961 * aborted anyway.
5963 if (unlikely(*erp))
5964 goto finish;
5965 lblk1 += len;
5966 lblk2 += len;
5967 replaced_count += len;
5968 count -= len;
5970 repeat:
5971 ext4_ext_drop_refs(path1);
5972 kfree(path1);
5973 ext4_ext_drop_refs(path2);
5974 kfree(path2);
5975 path1 = path2 = NULL;
5977 return replaced_count;