added 2.6.29.6 aldebaran kernel
[nao-ulib.git] / kernel / 2.6.29.6-aldebaran-rt / fs / ext4 / extents.c
blob83ea52868f2d2ed2a02eaed27e7b4f8566065b67
1 /*
2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
5 * Architecture independence:
6 * Copyright (c) 2005, Bull S.A.
7 * Written by Pierre Peiffer <pierre.peiffer@bull.net>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public Licens
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
24 * Extents support for EXT4
26 * TODO:
27 * - ext4*_error() should be used in some situations
28 * - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29 * - smart tree reduction
32 #include <linux/module.h>
33 #include <linux/fs.h>
34 #include <linux/time.h>
35 #include <linux/jbd2.h>
36 #include <linux/highuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/quotaops.h>
39 #include <linux/string.h>
40 #include <linux/slab.h>
41 #include <linux/falloc.h>
42 #include <asm/uaccess.h>
43 #include <linux/fiemap.h>
44 #include "ext4_jbd2.h"
45 #include "ext4_extents.h"
49 * ext_pblock:
50 * combine low and high parts of physical block number into ext4_fsblk_t
52 static ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
54 ext4_fsblk_t block;
56 block = le32_to_cpu(ex->ee_start_lo);
57 block |= ((ext4_fsblk_t) le16_to_cpu(ex->ee_start_hi) << 31) << 1;
58 return block;
62 * idx_pblock:
63 * combine low and high parts of a leaf physical block number into ext4_fsblk_t
65 ext4_fsblk_t idx_pblock(struct ext4_extent_idx *ix)
67 ext4_fsblk_t block;
69 block = le32_to_cpu(ix->ei_leaf_lo);
70 block |= ((ext4_fsblk_t) le16_to_cpu(ix->ei_leaf_hi) << 31) << 1;
71 return block;
75 * ext4_ext_store_pblock:
76 * stores a large physical block number into an extent struct,
77 * breaking it into parts
79 void ext4_ext_store_pblock(struct ext4_extent *ex, ext4_fsblk_t pb)
81 ex->ee_start_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
82 ex->ee_start_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
86 * ext4_idx_store_pblock:
87 * stores a large physical block number into an index struct,
88 * breaking it into parts
90 static void ext4_idx_store_pblock(struct ext4_extent_idx *ix, ext4_fsblk_t pb)
92 ix->ei_leaf_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
93 ix->ei_leaf_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
96 static int ext4_ext_journal_restart(handle_t *handle, int needed)
98 int err;
100 if (!ext4_handle_valid(handle))
101 return 0;
102 if (handle->h_buffer_credits > needed)
103 return 0;
104 err = ext4_journal_extend(handle, needed);
105 if (err <= 0)
106 return err;
107 return ext4_journal_restart(handle, needed);
111 * could return:
112 * - EROFS
113 * - ENOMEM
115 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
116 struct ext4_ext_path *path)
118 if (path->p_bh) {
119 /* path points to block */
120 return ext4_journal_get_write_access(handle, path->p_bh);
122 /* path points to leaf/index in inode body */
123 /* we use in-core data, no need to protect them */
124 return 0;
128 * could return:
129 * - EROFS
130 * - ENOMEM
131 * - EIO
133 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
134 struct ext4_ext_path *path)
136 int err;
137 if (path->p_bh) {
138 /* path points to block */
139 err = ext4_handle_dirty_metadata(handle, inode, path->p_bh);
140 } else {
141 /* path points to leaf/index in inode body */
142 err = ext4_mark_inode_dirty(handle, inode);
144 return err;
147 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
148 struct ext4_ext_path *path,
149 ext4_lblk_t block)
151 struct ext4_inode_info *ei = EXT4_I(inode);
152 ext4_fsblk_t bg_start;
153 ext4_fsblk_t last_block;
154 ext4_grpblk_t colour;
155 int depth;
157 if (path) {
158 struct ext4_extent *ex;
159 depth = path->p_depth;
161 /* try to predict block placement */
162 ex = path[depth].p_ext;
163 if (ex)
164 return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
166 /* it looks like index is empty;
167 * try to find starting block from index itself */
168 if (path[depth].p_bh)
169 return path[depth].p_bh->b_blocknr;
172 /* OK. use inode's group */
173 bg_start = (ei->i_block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
174 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
175 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
177 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
178 colour = (current->pid % 16) *
179 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
180 else
181 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
182 return bg_start + colour + block;
186 * Allocation for a meta data block
188 static ext4_fsblk_t
189 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
190 struct ext4_ext_path *path,
191 struct ext4_extent *ex, int *err)
193 ext4_fsblk_t goal, newblock;
195 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
196 newblock = ext4_new_meta_blocks(handle, inode, goal, NULL, err);
197 return newblock;
200 static int ext4_ext_space_block(struct inode *inode)
202 int size;
204 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
205 / sizeof(struct ext4_extent);
206 #ifdef AGGRESSIVE_TEST
207 if (size > 6)
208 size = 6;
209 #endif
210 return size;
213 static int ext4_ext_space_block_idx(struct inode *inode)
215 int size;
217 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
218 / sizeof(struct ext4_extent_idx);
219 #ifdef AGGRESSIVE_TEST
220 if (size > 5)
221 size = 5;
222 #endif
223 return size;
226 static int ext4_ext_space_root(struct inode *inode)
228 int size;
230 size = sizeof(EXT4_I(inode)->i_data);
231 size -= sizeof(struct ext4_extent_header);
232 size /= sizeof(struct ext4_extent);
233 #ifdef AGGRESSIVE_TEST
234 if (size > 3)
235 size = 3;
236 #endif
237 return size;
240 static int ext4_ext_space_root_idx(struct inode *inode)
242 int size;
244 size = sizeof(EXT4_I(inode)->i_data);
245 size -= sizeof(struct ext4_extent_header);
246 size /= sizeof(struct ext4_extent_idx);
247 #ifdef AGGRESSIVE_TEST
248 if (size > 4)
249 size = 4;
250 #endif
251 return size;
255 * Calculate the number of metadata blocks needed
256 * to allocate @blocks
257 * Worse case is one block per extent
259 int ext4_ext_calc_metadata_amount(struct inode *inode, int blocks)
261 int lcap, icap, rcap, leafs, idxs, num;
262 int newextents = blocks;
264 rcap = ext4_ext_space_root_idx(inode);
265 lcap = ext4_ext_space_block(inode);
266 icap = ext4_ext_space_block_idx(inode);
268 /* number of new leaf blocks needed */
269 num = leafs = (newextents + lcap - 1) / lcap;
272 * Worse case, we need separate index block(s)
273 * to link all new leaf blocks
275 idxs = (leafs + icap - 1) / icap;
276 do {
277 num += idxs;
278 idxs = (idxs + icap - 1) / icap;
279 } while (idxs > rcap);
281 return num;
284 static int
285 ext4_ext_max_entries(struct inode *inode, int depth)
287 int max;
289 if (depth == ext_depth(inode)) {
290 if (depth == 0)
291 max = ext4_ext_space_root(inode);
292 else
293 max = ext4_ext_space_root_idx(inode);
294 } else {
295 if (depth == 0)
296 max = ext4_ext_space_block(inode);
297 else
298 max = ext4_ext_space_block_idx(inode);
301 return max;
304 static int __ext4_ext_check_header(const char *function, struct inode *inode,
305 struct ext4_extent_header *eh,
306 int depth)
308 const char *error_msg;
309 int max = 0;
311 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
312 error_msg = "invalid magic";
313 goto corrupted;
315 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
316 error_msg = "unexpected eh_depth";
317 goto corrupted;
319 if (unlikely(eh->eh_max == 0)) {
320 error_msg = "invalid eh_max";
321 goto corrupted;
323 max = ext4_ext_max_entries(inode, depth);
324 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
325 error_msg = "too large eh_max";
326 goto corrupted;
328 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
329 error_msg = "invalid eh_entries";
330 goto corrupted;
332 return 0;
334 corrupted:
335 ext4_error(inode->i_sb, function,
336 "bad header in inode #%lu: %s - magic %x, "
337 "entries %u, max %u(%u), depth %u(%u)",
338 inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
339 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
340 max, le16_to_cpu(eh->eh_depth), depth);
342 return -EIO;
345 #define ext4_ext_check_header(inode, eh, depth) \
346 __ext4_ext_check_header(__func__, inode, eh, depth)
348 #ifdef EXT_DEBUG
349 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
351 int k, l = path->p_depth;
353 ext_debug("path:");
354 for (k = 0; k <= l; k++, path++) {
355 if (path->p_idx) {
356 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
357 idx_pblock(path->p_idx));
358 } else if (path->p_ext) {
359 ext_debug(" %d:%d:%llu ",
360 le32_to_cpu(path->p_ext->ee_block),
361 ext4_ext_get_actual_len(path->p_ext),
362 ext_pblock(path->p_ext));
363 } else
364 ext_debug(" []");
366 ext_debug("\n");
369 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
371 int depth = ext_depth(inode);
372 struct ext4_extent_header *eh;
373 struct ext4_extent *ex;
374 int i;
376 if (!path)
377 return;
379 eh = path[depth].p_hdr;
380 ex = EXT_FIRST_EXTENT(eh);
382 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
383 ext_debug("%d:%d:%llu ", le32_to_cpu(ex->ee_block),
384 ext4_ext_get_actual_len(ex), ext_pblock(ex));
386 ext_debug("\n");
388 #else
389 #define ext4_ext_show_path(inode, path)
390 #define ext4_ext_show_leaf(inode, path)
391 #endif
393 void ext4_ext_drop_refs(struct ext4_ext_path *path)
395 int depth = path->p_depth;
396 int i;
398 for (i = 0; i <= depth; i++, path++)
399 if (path->p_bh) {
400 brelse(path->p_bh);
401 path->p_bh = NULL;
406 * ext4_ext_binsearch_idx:
407 * binary search for the closest index of the given block
408 * the header must be checked before calling this
410 static void
411 ext4_ext_binsearch_idx(struct inode *inode,
412 struct ext4_ext_path *path, ext4_lblk_t block)
414 struct ext4_extent_header *eh = path->p_hdr;
415 struct ext4_extent_idx *r, *l, *m;
418 ext_debug("binsearch for %u(idx): ", block);
420 l = EXT_FIRST_INDEX(eh) + 1;
421 r = EXT_LAST_INDEX(eh);
422 while (l <= r) {
423 m = l + (r - l) / 2;
424 if (block < le32_to_cpu(m->ei_block))
425 r = m - 1;
426 else
427 l = m + 1;
428 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
429 m, le32_to_cpu(m->ei_block),
430 r, le32_to_cpu(r->ei_block));
433 path->p_idx = l - 1;
434 ext_debug(" -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
435 idx_pblock(path->p_idx));
437 #ifdef CHECK_BINSEARCH
439 struct ext4_extent_idx *chix, *ix;
440 int k;
442 chix = ix = EXT_FIRST_INDEX(eh);
443 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
444 if (k != 0 &&
445 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
446 printk(KERN_DEBUG "k=%d, ix=0x%p, "
447 "first=0x%p\n", k,
448 ix, EXT_FIRST_INDEX(eh));
449 printk(KERN_DEBUG "%u <= %u\n",
450 le32_to_cpu(ix->ei_block),
451 le32_to_cpu(ix[-1].ei_block));
453 BUG_ON(k && le32_to_cpu(ix->ei_block)
454 <= le32_to_cpu(ix[-1].ei_block));
455 if (block < le32_to_cpu(ix->ei_block))
456 break;
457 chix = ix;
459 BUG_ON(chix != path->p_idx);
461 #endif
466 * ext4_ext_binsearch:
467 * binary search for closest extent of the given block
468 * the header must be checked before calling this
470 static void
471 ext4_ext_binsearch(struct inode *inode,
472 struct ext4_ext_path *path, ext4_lblk_t block)
474 struct ext4_extent_header *eh = path->p_hdr;
475 struct ext4_extent *r, *l, *m;
477 if (eh->eh_entries == 0) {
479 * this leaf is empty:
480 * we get such a leaf in split/add case
482 return;
485 ext_debug("binsearch for %u: ", block);
487 l = EXT_FIRST_EXTENT(eh) + 1;
488 r = EXT_LAST_EXTENT(eh);
490 while (l <= r) {
491 m = l + (r - l) / 2;
492 if (block < le32_to_cpu(m->ee_block))
493 r = m - 1;
494 else
495 l = m + 1;
496 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
497 m, le32_to_cpu(m->ee_block),
498 r, le32_to_cpu(r->ee_block));
501 path->p_ext = l - 1;
502 ext_debug(" -> %d:%llu:%d ",
503 le32_to_cpu(path->p_ext->ee_block),
504 ext_pblock(path->p_ext),
505 ext4_ext_get_actual_len(path->p_ext));
507 #ifdef CHECK_BINSEARCH
509 struct ext4_extent *chex, *ex;
510 int k;
512 chex = ex = EXT_FIRST_EXTENT(eh);
513 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
514 BUG_ON(k && le32_to_cpu(ex->ee_block)
515 <= le32_to_cpu(ex[-1].ee_block));
516 if (block < le32_to_cpu(ex->ee_block))
517 break;
518 chex = ex;
520 BUG_ON(chex != path->p_ext);
522 #endif
526 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
528 struct ext4_extent_header *eh;
530 eh = ext_inode_hdr(inode);
531 eh->eh_depth = 0;
532 eh->eh_entries = 0;
533 eh->eh_magic = EXT4_EXT_MAGIC;
534 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode));
535 ext4_mark_inode_dirty(handle, inode);
536 ext4_ext_invalidate_cache(inode);
537 return 0;
540 struct ext4_ext_path *
541 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
542 struct ext4_ext_path *path)
544 struct ext4_extent_header *eh;
545 struct buffer_head *bh;
546 short int depth, i, ppos = 0, alloc = 0;
548 eh = ext_inode_hdr(inode);
549 depth = ext_depth(inode);
550 if (ext4_ext_check_header(inode, eh, depth))
551 return ERR_PTR(-EIO);
554 /* account possible depth increase */
555 if (!path) {
556 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
557 GFP_NOFS);
558 if (!path)
559 return ERR_PTR(-ENOMEM);
560 alloc = 1;
562 path[0].p_hdr = eh;
563 path[0].p_bh = NULL;
565 i = depth;
566 /* walk through the tree */
567 while (i) {
568 ext_debug("depth %d: num %d, max %d\n",
569 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
571 ext4_ext_binsearch_idx(inode, path + ppos, block);
572 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
573 path[ppos].p_depth = i;
574 path[ppos].p_ext = NULL;
576 bh = sb_bread(inode->i_sb, path[ppos].p_block);
577 if (!bh)
578 goto err;
580 eh = ext_block_hdr(bh);
581 ppos++;
582 BUG_ON(ppos > depth);
583 path[ppos].p_bh = bh;
584 path[ppos].p_hdr = eh;
585 i--;
587 if (ext4_ext_check_header(inode, eh, i))
588 goto err;
591 path[ppos].p_depth = i;
592 path[ppos].p_ext = NULL;
593 path[ppos].p_idx = NULL;
595 /* find extent */
596 ext4_ext_binsearch(inode, path + ppos, block);
597 /* if not an empty leaf */
598 if (path[ppos].p_ext)
599 path[ppos].p_block = ext_pblock(path[ppos].p_ext);
601 ext4_ext_show_path(inode, path);
603 return path;
605 err:
606 ext4_ext_drop_refs(path);
607 if (alloc)
608 kfree(path);
609 return ERR_PTR(-EIO);
613 * ext4_ext_insert_index:
614 * insert new index [@logical;@ptr] into the block at @curp;
615 * check where to insert: before @curp or after @curp
617 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
618 struct ext4_ext_path *curp,
619 int logical, ext4_fsblk_t ptr)
621 struct ext4_extent_idx *ix;
622 int len, err;
624 err = ext4_ext_get_access(handle, inode, curp);
625 if (err)
626 return err;
628 BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
629 len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
630 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
631 /* insert after */
632 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
633 len = (len - 1) * sizeof(struct ext4_extent_idx);
634 len = len < 0 ? 0 : len;
635 ext_debug("insert new index %d after: %llu. "
636 "move %d from 0x%p to 0x%p\n",
637 logical, ptr, len,
638 (curp->p_idx + 1), (curp->p_idx + 2));
639 memmove(curp->p_idx + 2, curp->p_idx + 1, len);
641 ix = curp->p_idx + 1;
642 } else {
643 /* insert before */
644 len = len * sizeof(struct ext4_extent_idx);
645 len = len < 0 ? 0 : len;
646 ext_debug("insert new index %d before: %llu. "
647 "move %d from 0x%p to 0x%p\n",
648 logical, ptr, len,
649 curp->p_idx, (curp->p_idx + 1));
650 memmove(curp->p_idx + 1, curp->p_idx, len);
651 ix = curp->p_idx;
654 ix->ei_block = cpu_to_le32(logical);
655 ext4_idx_store_pblock(ix, ptr);
656 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
658 BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
659 > le16_to_cpu(curp->p_hdr->eh_max));
660 BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
662 err = ext4_ext_dirty(handle, inode, curp);
663 ext4_std_error(inode->i_sb, err);
665 return err;
669 * ext4_ext_split:
670 * inserts new subtree into the path, using free index entry
671 * at depth @at:
672 * - allocates all needed blocks (new leaf and all intermediate index blocks)
673 * - makes decision where to split
674 * - moves remaining extents and index entries (right to the split point)
675 * into the newly allocated blocks
676 * - initializes subtree
678 static int ext4_ext_split(handle_t *handle, struct inode *inode,
679 struct ext4_ext_path *path,
680 struct ext4_extent *newext, int at)
682 struct buffer_head *bh = NULL;
683 int depth = ext_depth(inode);
684 struct ext4_extent_header *neh;
685 struct ext4_extent_idx *fidx;
686 struct ext4_extent *ex;
687 int i = at, k, m, a;
688 ext4_fsblk_t newblock, oldblock;
689 __le32 border;
690 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
691 int err = 0;
693 /* make decision: where to split? */
694 /* FIXME: now decision is simplest: at current extent */
696 /* if current leaf will be split, then we should use
697 * border from split point */
698 BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
699 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
700 border = path[depth].p_ext[1].ee_block;
701 ext_debug("leaf will be split."
702 " next leaf starts at %d\n",
703 le32_to_cpu(border));
704 } else {
705 border = newext->ee_block;
706 ext_debug("leaf will be added."
707 " next leaf starts at %d\n",
708 le32_to_cpu(border));
712 * If error occurs, then we break processing
713 * and mark filesystem read-only. index won't
714 * be inserted and tree will be in consistent
715 * state. Next mount will repair buffers too.
719 * Get array to track all allocated blocks.
720 * We need this to handle errors and free blocks
721 * upon them.
723 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
724 if (!ablocks)
725 return -ENOMEM;
727 /* allocate all needed blocks */
728 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
729 for (a = 0; a < depth - at; a++) {
730 newblock = ext4_ext_new_meta_block(handle, inode, path,
731 newext, &err);
732 if (newblock == 0)
733 goto cleanup;
734 ablocks[a] = newblock;
737 /* initialize new leaf */
738 newblock = ablocks[--a];
739 BUG_ON(newblock == 0);
740 bh = sb_getblk(inode->i_sb, newblock);
741 if (!bh) {
742 err = -EIO;
743 goto cleanup;
745 lock_buffer(bh);
747 err = ext4_journal_get_create_access(handle, bh);
748 if (err)
749 goto cleanup;
751 neh = ext_block_hdr(bh);
752 neh->eh_entries = 0;
753 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
754 neh->eh_magic = EXT4_EXT_MAGIC;
755 neh->eh_depth = 0;
756 ex = EXT_FIRST_EXTENT(neh);
758 /* move remainder of path[depth] to the new leaf */
759 BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
760 /* start copy from next extent */
761 /* TODO: we could do it by single memmove */
762 m = 0;
763 path[depth].p_ext++;
764 while (path[depth].p_ext <=
765 EXT_MAX_EXTENT(path[depth].p_hdr)) {
766 ext_debug("move %d:%llu:%d in new leaf %llu\n",
767 le32_to_cpu(path[depth].p_ext->ee_block),
768 ext_pblock(path[depth].p_ext),
769 ext4_ext_get_actual_len(path[depth].p_ext),
770 newblock);
771 /*memmove(ex++, path[depth].p_ext++,
772 sizeof(struct ext4_extent));
773 neh->eh_entries++;*/
774 path[depth].p_ext++;
775 m++;
777 if (m) {
778 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
779 le16_add_cpu(&neh->eh_entries, m);
782 set_buffer_uptodate(bh);
783 unlock_buffer(bh);
785 err = ext4_handle_dirty_metadata(handle, inode, bh);
786 if (err)
787 goto cleanup;
788 brelse(bh);
789 bh = NULL;
791 /* correct old leaf */
792 if (m) {
793 err = ext4_ext_get_access(handle, inode, path + depth);
794 if (err)
795 goto cleanup;
796 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
797 err = ext4_ext_dirty(handle, inode, path + depth);
798 if (err)
799 goto cleanup;
803 /* create intermediate indexes */
804 k = depth - at - 1;
805 BUG_ON(k < 0);
806 if (k)
807 ext_debug("create %d intermediate indices\n", k);
808 /* insert new index into current index block */
809 /* current depth stored in i var */
810 i = depth - 1;
811 while (k--) {
812 oldblock = newblock;
813 newblock = ablocks[--a];
814 bh = sb_getblk(inode->i_sb, newblock);
815 if (!bh) {
816 err = -EIO;
817 goto cleanup;
819 lock_buffer(bh);
821 err = ext4_journal_get_create_access(handle, bh);
822 if (err)
823 goto cleanup;
825 neh = ext_block_hdr(bh);
826 neh->eh_entries = cpu_to_le16(1);
827 neh->eh_magic = EXT4_EXT_MAGIC;
828 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
829 neh->eh_depth = cpu_to_le16(depth - i);
830 fidx = EXT_FIRST_INDEX(neh);
831 fidx->ei_block = border;
832 ext4_idx_store_pblock(fidx, oldblock);
834 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
835 i, newblock, le32_to_cpu(border), oldblock);
836 /* copy indexes */
837 m = 0;
838 path[i].p_idx++;
840 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
841 EXT_MAX_INDEX(path[i].p_hdr));
842 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
843 EXT_LAST_INDEX(path[i].p_hdr));
844 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
845 ext_debug("%d: move %d:%llu in new index %llu\n", i,
846 le32_to_cpu(path[i].p_idx->ei_block),
847 idx_pblock(path[i].p_idx),
848 newblock);
849 /*memmove(++fidx, path[i].p_idx++,
850 sizeof(struct ext4_extent_idx));
851 neh->eh_entries++;
852 BUG_ON(neh->eh_entries > neh->eh_max);*/
853 path[i].p_idx++;
854 m++;
856 if (m) {
857 memmove(++fidx, path[i].p_idx - m,
858 sizeof(struct ext4_extent_idx) * m);
859 le16_add_cpu(&neh->eh_entries, m);
861 set_buffer_uptodate(bh);
862 unlock_buffer(bh);
864 err = ext4_handle_dirty_metadata(handle, inode, bh);
865 if (err)
866 goto cleanup;
867 brelse(bh);
868 bh = NULL;
870 /* correct old index */
871 if (m) {
872 err = ext4_ext_get_access(handle, inode, path + i);
873 if (err)
874 goto cleanup;
875 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
876 err = ext4_ext_dirty(handle, inode, path + i);
877 if (err)
878 goto cleanup;
881 i--;
884 /* insert new index */
885 err = ext4_ext_insert_index(handle, inode, path + at,
886 le32_to_cpu(border), newblock);
888 cleanup:
889 if (bh) {
890 if (buffer_locked(bh))
891 unlock_buffer(bh);
892 brelse(bh);
895 if (err) {
896 /* free all allocated blocks in error case */
897 for (i = 0; i < depth; i++) {
898 if (!ablocks[i])
899 continue;
900 ext4_free_blocks(handle, inode, ablocks[i], 1, 1);
903 kfree(ablocks);
905 return err;
909 * ext4_ext_grow_indepth:
910 * implements tree growing procedure:
911 * - allocates new block
912 * - moves top-level data (index block or leaf) into the new block
913 * - initializes new top-level, creating index that points to the
914 * just created block
916 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
917 struct ext4_ext_path *path,
918 struct ext4_extent *newext)
920 struct ext4_ext_path *curp = path;
921 struct ext4_extent_header *neh;
922 struct ext4_extent_idx *fidx;
923 struct buffer_head *bh;
924 ext4_fsblk_t newblock;
925 int err = 0;
927 newblock = ext4_ext_new_meta_block(handle, inode, path, newext, &err);
928 if (newblock == 0)
929 return err;
931 bh = sb_getblk(inode->i_sb, newblock);
932 if (!bh) {
933 err = -EIO;
934 ext4_std_error(inode->i_sb, err);
935 return err;
937 lock_buffer(bh);
939 err = ext4_journal_get_create_access(handle, bh);
940 if (err) {
941 unlock_buffer(bh);
942 goto out;
945 /* move top-level index/leaf into new block */
946 memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
948 /* set size of new block */
949 neh = ext_block_hdr(bh);
950 /* old root could have indexes or leaves
951 * so calculate e_max right way */
952 if (ext_depth(inode))
953 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
954 else
955 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
956 neh->eh_magic = EXT4_EXT_MAGIC;
957 set_buffer_uptodate(bh);
958 unlock_buffer(bh);
960 err = ext4_handle_dirty_metadata(handle, inode, bh);
961 if (err)
962 goto out;
964 /* create index in new top-level index: num,max,pointer */
965 err = ext4_ext_get_access(handle, inode, curp);
966 if (err)
967 goto out;
969 curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
970 curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode));
971 curp->p_hdr->eh_entries = cpu_to_le16(1);
972 curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
974 if (path[0].p_hdr->eh_depth)
975 curp->p_idx->ei_block =
976 EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
977 else
978 curp->p_idx->ei_block =
979 EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
980 ext4_idx_store_pblock(curp->p_idx, newblock);
982 neh = ext_inode_hdr(inode);
983 fidx = EXT_FIRST_INDEX(neh);
984 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
985 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
986 le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
988 neh->eh_depth = cpu_to_le16(path->p_depth + 1);
989 err = ext4_ext_dirty(handle, inode, curp);
990 out:
991 brelse(bh);
993 return err;
997 * ext4_ext_create_new_leaf:
998 * finds empty index and adds new leaf.
999 * if no free index is found, then it requests in-depth growing.
1001 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1002 struct ext4_ext_path *path,
1003 struct ext4_extent *newext)
1005 struct ext4_ext_path *curp;
1006 int depth, i, err = 0;
1008 repeat:
1009 i = depth = ext_depth(inode);
1011 /* walk up to the tree and look for free index entry */
1012 curp = path + depth;
1013 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1014 i--;
1015 curp--;
1018 /* we use already allocated block for index block,
1019 * so subsequent data blocks should be contiguous */
1020 if (EXT_HAS_FREE_INDEX(curp)) {
1021 /* if we found index with free entry, then use that
1022 * entry: create all needed subtree and add new leaf */
1023 err = ext4_ext_split(handle, inode, path, newext, i);
1024 if (err)
1025 goto out;
1027 /* refill path */
1028 ext4_ext_drop_refs(path);
1029 path = ext4_ext_find_extent(inode,
1030 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1031 path);
1032 if (IS_ERR(path))
1033 err = PTR_ERR(path);
1034 } else {
1035 /* tree is full, time to grow in depth */
1036 err = ext4_ext_grow_indepth(handle, inode, path, newext);
1037 if (err)
1038 goto out;
1040 /* refill path */
1041 ext4_ext_drop_refs(path);
1042 path = ext4_ext_find_extent(inode,
1043 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1044 path);
1045 if (IS_ERR(path)) {
1046 err = PTR_ERR(path);
1047 goto out;
1051 * only first (depth 0 -> 1) produces free space;
1052 * in all other cases we have to split the grown tree
1054 depth = ext_depth(inode);
1055 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1056 /* now we need to split */
1057 goto repeat;
1061 out:
1062 return err;
1066 * search the closest allocated block to the left for *logical
1067 * and returns it at @logical + it's physical address at @phys
1068 * if *logical is the smallest allocated block, the function
1069 * returns 0 at @phys
1070 * return value contains 0 (success) or error code
1073 ext4_ext_search_left(struct inode *inode, struct ext4_ext_path *path,
1074 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1076 struct ext4_extent_idx *ix;
1077 struct ext4_extent *ex;
1078 int depth, ee_len;
1080 BUG_ON(path == NULL);
1081 depth = path->p_depth;
1082 *phys = 0;
1084 if (depth == 0 && path->p_ext == NULL)
1085 return 0;
1087 /* usually extent in the path covers blocks smaller
1088 * then *logical, but it can be that extent is the
1089 * first one in the file */
1091 ex = path[depth].p_ext;
1092 ee_len = ext4_ext_get_actual_len(ex);
1093 if (*logical < le32_to_cpu(ex->ee_block)) {
1094 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1095 while (--depth >= 0) {
1096 ix = path[depth].p_idx;
1097 BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1099 return 0;
1102 BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1104 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1105 *phys = ext_pblock(ex) + ee_len - 1;
1106 return 0;
1110 * search the closest allocated block to the right for *logical
1111 * and returns it at @logical + it's physical address at @phys
1112 * if *logical is the smallest allocated block, the function
1113 * returns 0 at @phys
1114 * return value contains 0 (success) or error code
1117 ext4_ext_search_right(struct inode *inode, struct ext4_ext_path *path,
1118 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1120 struct buffer_head *bh = NULL;
1121 struct ext4_extent_header *eh;
1122 struct ext4_extent_idx *ix;
1123 struct ext4_extent *ex;
1124 ext4_fsblk_t block;
1125 int depth; /* Note, NOT eh_depth; depth from top of tree */
1126 int ee_len;
1128 BUG_ON(path == NULL);
1129 depth = path->p_depth;
1130 *phys = 0;
1132 if (depth == 0 && path->p_ext == NULL)
1133 return 0;
1135 /* usually extent in the path covers blocks smaller
1136 * then *logical, but it can be that extent is the
1137 * first one in the file */
1139 ex = path[depth].p_ext;
1140 ee_len = ext4_ext_get_actual_len(ex);
1141 if (*logical < le32_to_cpu(ex->ee_block)) {
1142 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1143 while (--depth >= 0) {
1144 ix = path[depth].p_idx;
1145 BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1147 *logical = le32_to_cpu(ex->ee_block);
1148 *phys = ext_pblock(ex);
1149 return 0;
1152 BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1154 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1155 /* next allocated block in this leaf */
1156 ex++;
1157 *logical = le32_to_cpu(ex->ee_block);
1158 *phys = ext_pblock(ex);
1159 return 0;
1162 ix = NULL; /* avoid gcc false positive warning */
1163 /* go up and search for index to the right */
1164 while (--depth >= 0) {
1165 ix = path[depth].p_idx;
1166 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1167 goto got_index;
1170 /* we've gone up to the root and found no index to the right */
1171 return 0;
1173 got_index:
1174 /* we've found index to the right, let's
1175 * follow it and find the closest allocated
1176 * block to the right */
1177 ix++;
1178 block = idx_pblock(ix);
1179 while (++depth < path->p_depth) {
1180 bh = sb_bread(inode->i_sb, block);
1181 if (bh == NULL)
1182 return -EIO;
1183 eh = ext_block_hdr(bh);
1184 /* subtract from p_depth to get proper eh_depth */
1185 if (ext4_ext_check_header(inode, eh, path->p_depth - depth)) {
1186 put_bh(bh);
1187 return -EIO;
1189 ix = EXT_FIRST_INDEX(eh);
1190 block = idx_pblock(ix);
1191 put_bh(bh);
1194 bh = sb_bread(inode->i_sb, block);
1195 if (bh == NULL)
1196 return -EIO;
1197 eh = ext_block_hdr(bh);
1198 if (ext4_ext_check_header(inode, eh, path->p_depth - depth)) {
1199 put_bh(bh);
1200 return -EIO;
1202 ex = EXT_FIRST_EXTENT(eh);
1203 *logical = le32_to_cpu(ex->ee_block);
1204 *phys = ext_pblock(ex);
1205 put_bh(bh);
1206 return 0;
1210 * ext4_ext_next_allocated_block:
1211 * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1212 * NOTE: it considers block number from index entry as
1213 * allocated block. Thus, index entries have to be consistent
1214 * with leaves.
1216 static ext4_lblk_t
1217 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1219 int depth;
1221 BUG_ON(path == NULL);
1222 depth = path->p_depth;
1224 if (depth == 0 && path->p_ext == NULL)
1225 return EXT_MAX_BLOCK;
1227 while (depth >= 0) {
1228 if (depth == path->p_depth) {
1229 /* leaf */
1230 if (path[depth].p_ext !=
1231 EXT_LAST_EXTENT(path[depth].p_hdr))
1232 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1233 } else {
1234 /* index */
1235 if (path[depth].p_idx !=
1236 EXT_LAST_INDEX(path[depth].p_hdr))
1237 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1239 depth--;
1242 return EXT_MAX_BLOCK;
1246 * ext4_ext_next_leaf_block:
1247 * returns first allocated block from next leaf or EXT_MAX_BLOCK
1249 static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1250 struct ext4_ext_path *path)
1252 int depth;
1254 BUG_ON(path == NULL);
1255 depth = path->p_depth;
1257 /* zero-tree has no leaf blocks at all */
1258 if (depth == 0)
1259 return EXT_MAX_BLOCK;
1261 /* go to index block */
1262 depth--;
1264 while (depth >= 0) {
1265 if (path[depth].p_idx !=
1266 EXT_LAST_INDEX(path[depth].p_hdr))
1267 return (ext4_lblk_t)
1268 le32_to_cpu(path[depth].p_idx[1].ei_block);
1269 depth--;
1272 return EXT_MAX_BLOCK;
1276 * ext4_ext_correct_indexes:
1277 * if leaf gets modified and modified extent is first in the leaf,
1278 * then we have to correct all indexes above.
1279 * TODO: do we need to correct tree in all cases?
1281 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1282 struct ext4_ext_path *path)
1284 struct ext4_extent_header *eh;
1285 int depth = ext_depth(inode);
1286 struct ext4_extent *ex;
1287 __le32 border;
1288 int k, err = 0;
1290 eh = path[depth].p_hdr;
1291 ex = path[depth].p_ext;
1292 BUG_ON(ex == NULL);
1293 BUG_ON(eh == NULL);
1295 if (depth == 0) {
1296 /* there is no tree at all */
1297 return 0;
1300 if (ex != EXT_FIRST_EXTENT(eh)) {
1301 /* we correct tree if first leaf got modified only */
1302 return 0;
1306 * TODO: we need correction if border is smaller than current one
1308 k = depth - 1;
1309 border = path[depth].p_ext->ee_block;
1310 err = ext4_ext_get_access(handle, inode, path + k);
1311 if (err)
1312 return err;
1313 path[k].p_idx->ei_block = border;
1314 err = ext4_ext_dirty(handle, inode, path + k);
1315 if (err)
1316 return err;
1318 while (k--) {
1319 /* change all left-side indexes */
1320 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1321 break;
1322 err = ext4_ext_get_access(handle, inode, path + k);
1323 if (err)
1324 break;
1325 path[k].p_idx->ei_block = border;
1326 err = ext4_ext_dirty(handle, inode, path + k);
1327 if (err)
1328 break;
1331 return err;
1334 static int
1335 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1336 struct ext4_extent *ex2)
1338 unsigned short ext1_ee_len, ext2_ee_len, max_len;
1341 * Make sure that either both extents are uninitialized, or
1342 * both are _not_.
1344 if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1345 return 0;
1347 if (ext4_ext_is_uninitialized(ex1))
1348 max_len = EXT_UNINIT_MAX_LEN;
1349 else
1350 max_len = EXT_INIT_MAX_LEN;
1352 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1353 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1355 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1356 le32_to_cpu(ex2->ee_block))
1357 return 0;
1360 * To allow future support for preallocated extents to be added
1361 * as an RO_COMPAT feature, refuse to merge to extents if
1362 * this can result in the top bit of ee_len being set.
1364 if (ext1_ee_len + ext2_ee_len > max_len)
1365 return 0;
1366 #ifdef AGGRESSIVE_TEST
1367 if (ext1_ee_len >= 4)
1368 return 0;
1369 #endif
1371 if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1372 return 1;
1373 return 0;
1377 * This function tries to merge the "ex" extent to the next extent in the tree.
1378 * It always tries to merge towards right. If you want to merge towards
1379 * left, pass "ex - 1" as argument instead of "ex".
1380 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1381 * 1 if they got merged.
1383 int ext4_ext_try_to_merge(struct inode *inode,
1384 struct ext4_ext_path *path,
1385 struct ext4_extent *ex)
1387 struct ext4_extent_header *eh;
1388 unsigned int depth, len;
1389 int merge_done = 0;
1390 int uninitialized = 0;
1392 depth = ext_depth(inode);
1393 BUG_ON(path[depth].p_hdr == NULL);
1394 eh = path[depth].p_hdr;
1396 while (ex < EXT_LAST_EXTENT(eh)) {
1397 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1398 break;
1399 /* merge with next extent! */
1400 if (ext4_ext_is_uninitialized(ex))
1401 uninitialized = 1;
1402 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1403 + ext4_ext_get_actual_len(ex + 1));
1404 if (uninitialized)
1405 ext4_ext_mark_uninitialized(ex);
1407 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1408 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1409 * sizeof(struct ext4_extent);
1410 memmove(ex + 1, ex + 2, len);
1412 le16_add_cpu(&eh->eh_entries, -1);
1413 merge_done = 1;
1414 WARN_ON(eh->eh_entries == 0);
1415 if (!eh->eh_entries)
1416 ext4_error(inode->i_sb, "ext4_ext_try_to_merge",
1417 "inode#%lu, eh->eh_entries = 0!", inode->i_ino);
1420 return merge_done;
1424 * check if a portion of the "newext" extent overlaps with an
1425 * existing extent.
1427 * If there is an overlap discovered, it updates the length of the newext
1428 * such that there will be no overlap, and then returns 1.
1429 * If there is no overlap found, it returns 0.
1431 unsigned int ext4_ext_check_overlap(struct inode *inode,
1432 struct ext4_extent *newext,
1433 struct ext4_ext_path *path)
1435 ext4_lblk_t b1, b2;
1436 unsigned int depth, len1;
1437 unsigned int ret = 0;
1439 b1 = le32_to_cpu(newext->ee_block);
1440 len1 = ext4_ext_get_actual_len(newext);
1441 depth = ext_depth(inode);
1442 if (!path[depth].p_ext)
1443 goto out;
1444 b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1447 * get the next allocated block if the extent in the path
1448 * is before the requested block(s)
1450 if (b2 < b1) {
1451 b2 = ext4_ext_next_allocated_block(path);
1452 if (b2 == EXT_MAX_BLOCK)
1453 goto out;
1456 /* check for wrap through zero on extent logical start block*/
1457 if (b1 + len1 < b1) {
1458 len1 = EXT_MAX_BLOCK - b1;
1459 newext->ee_len = cpu_to_le16(len1);
1460 ret = 1;
1463 /* check for overlap */
1464 if (b1 + len1 > b2) {
1465 newext->ee_len = cpu_to_le16(b2 - b1);
1466 ret = 1;
1468 out:
1469 return ret;
1473 * ext4_ext_insert_extent:
1474 * tries to merge requsted extent into the existing extent or
1475 * inserts requested extent as new one into the tree,
1476 * creating new leaf in the no-space case.
1478 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1479 struct ext4_ext_path *path,
1480 struct ext4_extent *newext)
1482 struct ext4_extent_header *eh;
1483 struct ext4_extent *ex, *fex;
1484 struct ext4_extent *nearex; /* nearest extent */
1485 struct ext4_ext_path *npath = NULL;
1486 int depth, len, err;
1487 ext4_lblk_t next;
1488 unsigned uninitialized = 0;
1490 BUG_ON(ext4_ext_get_actual_len(newext) == 0);
1491 depth = ext_depth(inode);
1492 ex = path[depth].p_ext;
1493 BUG_ON(path[depth].p_hdr == NULL);
1495 /* try to insert block into found extent and return */
1496 if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1497 ext_debug("append %d block to %d:%d (from %llu)\n",
1498 ext4_ext_get_actual_len(newext),
1499 le32_to_cpu(ex->ee_block),
1500 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1501 err = ext4_ext_get_access(handle, inode, path + depth);
1502 if (err)
1503 return err;
1506 * ext4_can_extents_be_merged should have checked that either
1507 * both extents are uninitialized, or both aren't. Thus we
1508 * need to check only one of them here.
1510 if (ext4_ext_is_uninitialized(ex))
1511 uninitialized = 1;
1512 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1513 + ext4_ext_get_actual_len(newext));
1514 if (uninitialized)
1515 ext4_ext_mark_uninitialized(ex);
1516 eh = path[depth].p_hdr;
1517 nearex = ex;
1518 goto merge;
1521 repeat:
1522 depth = ext_depth(inode);
1523 eh = path[depth].p_hdr;
1524 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1525 goto has_space;
1527 /* probably next leaf has space for us? */
1528 fex = EXT_LAST_EXTENT(eh);
1529 next = ext4_ext_next_leaf_block(inode, path);
1530 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1531 && next != EXT_MAX_BLOCK) {
1532 ext_debug("next leaf block - %d\n", next);
1533 BUG_ON(npath != NULL);
1534 npath = ext4_ext_find_extent(inode, next, NULL);
1535 if (IS_ERR(npath))
1536 return PTR_ERR(npath);
1537 BUG_ON(npath->p_depth != path->p_depth);
1538 eh = npath[depth].p_hdr;
1539 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1540 ext_debug("next leaf isnt full(%d)\n",
1541 le16_to_cpu(eh->eh_entries));
1542 path = npath;
1543 goto repeat;
1545 ext_debug("next leaf has no free space(%d,%d)\n",
1546 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1550 * There is no free space in the found leaf.
1551 * We're gonna add a new leaf in the tree.
1553 err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1554 if (err)
1555 goto cleanup;
1556 depth = ext_depth(inode);
1557 eh = path[depth].p_hdr;
1559 has_space:
1560 nearex = path[depth].p_ext;
1562 err = ext4_ext_get_access(handle, inode, path + depth);
1563 if (err)
1564 goto cleanup;
1566 if (!nearex) {
1567 /* there is no extent in this leaf, create first one */
1568 ext_debug("first extent in the leaf: %d:%llu:%d\n",
1569 le32_to_cpu(newext->ee_block),
1570 ext_pblock(newext),
1571 ext4_ext_get_actual_len(newext));
1572 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1573 } else if (le32_to_cpu(newext->ee_block)
1574 > le32_to_cpu(nearex->ee_block)) {
1575 /* BUG_ON(newext->ee_block == nearex->ee_block); */
1576 if (nearex != EXT_LAST_EXTENT(eh)) {
1577 len = EXT_MAX_EXTENT(eh) - nearex;
1578 len = (len - 1) * sizeof(struct ext4_extent);
1579 len = len < 0 ? 0 : len;
1580 ext_debug("insert %d:%llu:%d after: nearest 0x%p, "
1581 "move %d from 0x%p to 0x%p\n",
1582 le32_to_cpu(newext->ee_block),
1583 ext_pblock(newext),
1584 ext4_ext_get_actual_len(newext),
1585 nearex, len, nearex + 1, nearex + 2);
1586 memmove(nearex + 2, nearex + 1, len);
1588 path[depth].p_ext = nearex + 1;
1589 } else {
1590 BUG_ON(newext->ee_block == nearex->ee_block);
1591 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1592 len = len < 0 ? 0 : len;
1593 ext_debug("insert %d:%llu:%d before: nearest 0x%p, "
1594 "move %d from 0x%p to 0x%p\n",
1595 le32_to_cpu(newext->ee_block),
1596 ext_pblock(newext),
1597 ext4_ext_get_actual_len(newext),
1598 nearex, len, nearex + 1, nearex + 2);
1599 memmove(nearex + 1, nearex, len);
1600 path[depth].p_ext = nearex;
1603 le16_add_cpu(&eh->eh_entries, 1);
1604 nearex = path[depth].p_ext;
1605 nearex->ee_block = newext->ee_block;
1606 ext4_ext_store_pblock(nearex, ext_pblock(newext));
1607 nearex->ee_len = newext->ee_len;
1609 merge:
1610 /* try to merge extents to the right */
1611 ext4_ext_try_to_merge(inode, path, nearex);
1613 /* try to merge extents to the left */
1615 /* time to correct all indexes above */
1616 err = ext4_ext_correct_indexes(handle, inode, path);
1617 if (err)
1618 goto cleanup;
1620 err = ext4_ext_dirty(handle, inode, path + depth);
1622 cleanup:
1623 if (npath) {
1624 ext4_ext_drop_refs(npath);
1625 kfree(npath);
1627 ext4_ext_invalidate_cache(inode);
1628 return err;
1631 int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1632 ext4_lblk_t num, ext_prepare_callback func,
1633 void *cbdata)
1635 struct ext4_ext_path *path = NULL;
1636 struct ext4_ext_cache cbex;
1637 struct ext4_extent *ex;
1638 ext4_lblk_t next, start = 0, end = 0;
1639 ext4_lblk_t last = block + num;
1640 int depth, exists, err = 0;
1642 BUG_ON(func == NULL);
1643 BUG_ON(inode == NULL);
1645 while (block < last && block != EXT_MAX_BLOCK) {
1646 num = last - block;
1647 /* find extent for this block */
1648 path = ext4_ext_find_extent(inode, block, path);
1649 if (IS_ERR(path)) {
1650 err = PTR_ERR(path);
1651 path = NULL;
1652 break;
1655 depth = ext_depth(inode);
1656 BUG_ON(path[depth].p_hdr == NULL);
1657 ex = path[depth].p_ext;
1658 next = ext4_ext_next_allocated_block(path);
1660 exists = 0;
1661 if (!ex) {
1662 /* there is no extent yet, so try to allocate
1663 * all requested space */
1664 start = block;
1665 end = block + num;
1666 } else if (le32_to_cpu(ex->ee_block) > block) {
1667 /* need to allocate space before found extent */
1668 start = block;
1669 end = le32_to_cpu(ex->ee_block);
1670 if (block + num < end)
1671 end = block + num;
1672 } else if (block >= le32_to_cpu(ex->ee_block)
1673 + ext4_ext_get_actual_len(ex)) {
1674 /* need to allocate space after found extent */
1675 start = block;
1676 end = block + num;
1677 if (end >= next)
1678 end = next;
1679 } else if (block >= le32_to_cpu(ex->ee_block)) {
1681 * some part of requested space is covered
1682 * by found extent
1684 start = block;
1685 end = le32_to_cpu(ex->ee_block)
1686 + ext4_ext_get_actual_len(ex);
1687 if (block + num < end)
1688 end = block + num;
1689 exists = 1;
1690 } else {
1691 BUG();
1693 BUG_ON(end <= start);
1695 if (!exists) {
1696 cbex.ec_block = start;
1697 cbex.ec_len = end - start;
1698 cbex.ec_start = 0;
1699 cbex.ec_type = EXT4_EXT_CACHE_GAP;
1700 } else {
1701 cbex.ec_block = le32_to_cpu(ex->ee_block);
1702 cbex.ec_len = ext4_ext_get_actual_len(ex);
1703 cbex.ec_start = ext_pblock(ex);
1704 cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1707 BUG_ON(cbex.ec_len == 0);
1708 err = func(inode, path, &cbex, ex, cbdata);
1709 ext4_ext_drop_refs(path);
1711 if (err < 0)
1712 break;
1714 if (err == EXT_REPEAT)
1715 continue;
1716 else if (err == EXT_BREAK) {
1717 err = 0;
1718 break;
1721 if (ext_depth(inode) != depth) {
1722 /* depth was changed. we have to realloc path */
1723 kfree(path);
1724 path = NULL;
1727 block = cbex.ec_block + cbex.ec_len;
1730 if (path) {
1731 ext4_ext_drop_refs(path);
1732 kfree(path);
1735 return err;
1738 static void
1739 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1740 __u32 len, ext4_fsblk_t start, int type)
1742 struct ext4_ext_cache *cex;
1743 BUG_ON(len == 0);
1744 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1745 cex = &EXT4_I(inode)->i_cached_extent;
1746 cex->ec_type = type;
1747 cex->ec_block = block;
1748 cex->ec_len = len;
1749 cex->ec_start = start;
1750 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1754 * ext4_ext_put_gap_in_cache:
1755 * calculate boundaries of the gap that the requested block fits into
1756 * and cache this gap
1758 static void
1759 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1760 ext4_lblk_t block)
1762 int depth = ext_depth(inode);
1763 unsigned long len;
1764 ext4_lblk_t lblock;
1765 struct ext4_extent *ex;
1767 ex = path[depth].p_ext;
1768 if (ex == NULL) {
1769 /* there is no extent yet, so gap is [0;-] */
1770 lblock = 0;
1771 len = EXT_MAX_BLOCK;
1772 ext_debug("cache gap(whole file):");
1773 } else if (block < le32_to_cpu(ex->ee_block)) {
1774 lblock = block;
1775 len = le32_to_cpu(ex->ee_block) - block;
1776 ext_debug("cache gap(before): %u [%u:%u]",
1777 block,
1778 le32_to_cpu(ex->ee_block),
1779 ext4_ext_get_actual_len(ex));
1780 } else if (block >= le32_to_cpu(ex->ee_block)
1781 + ext4_ext_get_actual_len(ex)) {
1782 ext4_lblk_t next;
1783 lblock = le32_to_cpu(ex->ee_block)
1784 + ext4_ext_get_actual_len(ex);
1786 next = ext4_ext_next_allocated_block(path);
1787 ext_debug("cache gap(after): [%u:%u] %u",
1788 le32_to_cpu(ex->ee_block),
1789 ext4_ext_get_actual_len(ex),
1790 block);
1791 BUG_ON(next == lblock);
1792 len = next - lblock;
1793 } else {
1794 lblock = len = 0;
1795 BUG();
1798 ext_debug(" -> %u:%lu\n", lblock, len);
1799 ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1802 static int
1803 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
1804 struct ext4_extent *ex)
1806 struct ext4_ext_cache *cex;
1807 int ret = EXT4_EXT_CACHE_NO;
1810 * We borrow i_block_reservation_lock to protect i_cached_extent
1812 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1813 cex = &EXT4_I(inode)->i_cached_extent;
1815 /* has cache valid data? */
1816 if (cex->ec_type == EXT4_EXT_CACHE_NO)
1817 goto errout;
1819 BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1820 cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1821 if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1822 ex->ee_block = cpu_to_le32(cex->ec_block);
1823 ext4_ext_store_pblock(ex, cex->ec_start);
1824 ex->ee_len = cpu_to_le16(cex->ec_len);
1825 ext_debug("%u cached by %u:%u:%llu\n",
1826 block,
1827 cex->ec_block, cex->ec_len, cex->ec_start);
1828 ret = cex->ec_type;
1830 errout:
1831 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1832 return ret;
1836 * ext4_ext_rm_idx:
1837 * removes index from the index block.
1838 * It's used in truncate case only, thus all requests are for
1839 * last index in the block only.
1841 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1842 struct ext4_ext_path *path)
1844 struct buffer_head *bh;
1845 int err;
1846 ext4_fsblk_t leaf;
1848 /* free index block */
1849 path--;
1850 leaf = idx_pblock(path->p_idx);
1851 BUG_ON(path->p_hdr->eh_entries == 0);
1852 err = ext4_ext_get_access(handle, inode, path);
1853 if (err)
1854 return err;
1855 le16_add_cpu(&path->p_hdr->eh_entries, -1);
1856 err = ext4_ext_dirty(handle, inode, path);
1857 if (err)
1858 return err;
1859 ext_debug("index is empty, remove it, free block %llu\n", leaf);
1860 bh = sb_find_get_block(inode->i_sb, leaf);
1861 ext4_forget(handle, 1, inode, bh, leaf);
1862 ext4_free_blocks(handle, inode, leaf, 1, 1);
1863 return err;
1867 * ext4_ext_calc_credits_for_single_extent:
1868 * This routine returns max. credits that needed to insert an extent
1869 * to the extent tree.
1870 * When pass the actual path, the caller should calculate credits
1871 * under i_data_sem.
1873 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
1874 struct ext4_ext_path *path)
1876 if (path) {
1877 int depth = ext_depth(inode);
1878 int ret = 0;
1880 /* probably there is space in leaf? */
1881 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1882 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
1885 * There are some space in the leaf tree, no
1886 * need to account for leaf block credit
1888 * bitmaps and block group descriptor blocks
1889 * and other metadat blocks still need to be
1890 * accounted.
1892 /* 1 bitmap, 1 block group descriptor */
1893 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
1897 return ext4_chunk_trans_blocks(inode, nrblocks);
1901 * How many index/leaf blocks need to change/allocate to modify nrblocks?
1903 * if nrblocks are fit in a single extent (chunk flag is 1), then
1904 * in the worse case, each tree level index/leaf need to be changed
1905 * if the tree split due to insert a new extent, then the old tree
1906 * index/leaf need to be updated too
1908 * If the nrblocks are discontiguous, they could cause
1909 * the whole tree split more than once, but this is really rare.
1911 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
1913 int index;
1914 int depth = ext_depth(inode);
1916 if (chunk)
1917 index = depth * 2;
1918 else
1919 index = depth * 3;
1921 return index;
1924 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
1925 struct ext4_extent *ex,
1926 ext4_lblk_t from, ext4_lblk_t to)
1928 struct buffer_head *bh;
1929 unsigned short ee_len = ext4_ext_get_actual_len(ex);
1930 int i, metadata = 0;
1932 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
1933 metadata = 1;
1934 #ifdef EXTENTS_STATS
1936 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1937 spin_lock(&sbi->s_ext_stats_lock);
1938 sbi->s_ext_blocks += ee_len;
1939 sbi->s_ext_extents++;
1940 if (ee_len < sbi->s_ext_min)
1941 sbi->s_ext_min = ee_len;
1942 if (ee_len > sbi->s_ext_max)
1943 sbi->s_ext_max = ee_len;
1944 if (ext_depth(inode) > sbi->s_depth_max)
1945 sbi->s_depth_max = ext_depth(inode);
1946 spin_unlock(&sbi->s_ext_stats_lock);
1948 #endif
1949 if (from >= le32_to_cpu(ex->ee_block)
1950 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
1951 /* tail removal */
1952 ext4_lblk_t num;
1953 ext4_fsblk_t start;
1955 num = le32_to_cpu(ex->ee_block) + ee_len - from;
1956 start = ext_pblock(ex) + ee_len - num;
1957 ext_debug("free last %u blocks starting %llu\n", num, start);
1958 for (i = 0; i < num; i++) {
1959 bh = sb_find_get_block(inode->i_sb, start + i);
1960 ext4_forget(handle, 0, inode, bh, start + i);
1962 ext4_free_blocks(handle, inode, start, num, metadata);
1963 } else if (from == le32_to_cpu(ex->ee_block)
1964 && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
1965 printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
1966 from, to, le32_to_cpu(ex->ee_block), ee_len);
1967 } else {
1968 printk(KERN_INFO "strange request: removal(2) "
1969 "%u-%u from %u:%u\n",
1970 from, to, le32_to_cpu(ex->ee_block), ee_len);
1972 return 0;
1975 static int
1976 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
1977 struct ext4_ext_path *path, ext4_lblk_t start)
1979 int err = 0, correct_index = 0;
1980 int depth = ext_depth(inode), credits;
1981 struct ext4_extent_header *eh;
1982 ext4_lblk_t a, b, block;
1983 unsigned num;
1984 ext4_lblk_t ex_ee_block;
1985 unsigned short ex_ee_len;
1986 unsigned uninitialized = 0;
1987 struct ext4_extent *ex;
1989 /* the header must be checked already in ext4_ext_remove_space() */
1990 ext_debug("truncate since %u in leaf\n", start);
1991 if (!path[depth].p_hdr)
1992 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
1993 eh = path[depth].p_hdr;
1994 BUG_ON(eh == NULL);
1996 /* find where to start removing */
1997 ex = EXT_LAST_EXTENT(eh);
1999 ex_ee_block = le32_to_cpu(ex->ee_block);
2000 if (ext4_ext_is_uninitialized(ex))
2001 uninitialized = 1;
2002 ex_ee_len = ext4_ext_get_actual_len(ex);
2004 while (ex >= EXT_FIRST_EXTENT(eh) &&
2005 ex_ee_block + ex_ee_len > start) {
2006 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
2007 path[depth].p_ext = ex;
2009 a = ex_ee_block > start ? ex_ee_block : start;
2010 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
2011 ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
2013 ext_debug(" border %u:%u\n", a, b);
2015 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
2016 block = 0;
2017 num = 0;
2018 BUG();
2019 } else if (a != ex_ee_block) {
2020 /* remove tail of the extent */
2021 block = ex_ee_block;
2022 num = a - block;
2023 } else if (b != ex_ee_block + ex_ee_len - 1) {
2024 /* remove head of the extent */
2025 block = a;
2026 num = b - a;
2027 /* there is no "make a hole" API yet */
2028 BUG();
2029 } else {
2030 /* remove whole extent: excellent! */
2031 block = ex_ee_block;
2032 num = 0;
2033 BUG_ON(a != ex_ee_block);
2034 BUG_ON(b != ex_ee_block + ex_ee_len - 1);
2038 * 3 for leaf, sb, and inode plus 2 (bmap and group
2039 * descriptor) for each block group; assume two block
2040 * groups plus ex_ee_len/blocks_per_block_group for
2041 * the worst case
2043 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2044 if (ex == EXT_FIRST_EXTENT(eh)) {
2045 correct_index = 1;
2046 credits += (ext_depth(inode)) + 1;
2048 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2050 err = ext4_ext_journal_restart(handle, credits);
2051 if (err)
2052 goto out;
2054 err = ext4_ext_get_access(handle, inode, path + depth);
2055 if (err)
2056 goto out;
2058 err = ext4_remove_blocks(handle, inode, ex, a, b);
2059 if (err)
2060 goto out;
2062 if (num == 0) {
2063 /* this extent is removed; mark slot entirely unused */
2064 ext4_ext_store_pblock(ex, 0);
2065 le16_add_cpu(&eh->eh_entries, -1);
2068 ex->ee_block = cpu_to_le32(block);
2069 ex->ee_len = cpu_to_le16(num);
2071 * Do not mark uninitialized if all the blocks in the
2072 * extent have been removed.
2074 if (uninitialized && num)
2075 ext4_ext_mark_uninitialized(ex);
2077 err = ext4_ext_dirty(handle, inode, path + depth);
2078 if (err)
2079 goto out;
2081 ext_debug("new extent: %u:%u:%llu\n", block, num,
2082 ext_pblock(ex));
2083 ex--;
2084 ex_ee_block = le32_to_cpu(ex->ee_block);
2085 ex_ee_len = ext4_ext_get_actual_len(ex);
2088 if (correct_index && eh->eh_entries)
2089 err = ext4_ext_correct_indexes(handle, inode, path);
2091 /* if this leaf is free, then we should
2092 * remove it from index block above */
2093 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2094 err = ext4_ext_rm_idx(handle, inode, path + depth);
2096 out:
2097 return err;
2101 * ext4_ext_more_to_rm:
2102 * returns 1 if current index has to be freed (even partial)
2104 static int
2105 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2107 BUG_ON(path->p_idx == NULL);
2109 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2110 return 0;
2113 * if truncate on deeper level happened, it wasn't partial,
2114 * so we have to consider current index for truncation
2116 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2117 return 0;
2118 return 1;
2121 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2123 struct super_block *sb = inode->i_sb;
2124 int depth = ext_depth(inode);
2125 struct ext4_ext_path *path;
2126 handle_t *handle;
2127 int i = 0, err = 0;
2129 ext_debug("truncate since %u\n", start);
2131 /* probably first extent we're gonna free will be last in block */
2132 handle = ext4_journal_start(inode, depth + 1);
2133 if (IS_ERR(handle))
2134 return PTR_ERR(handle);
2136 ext4_ext_invalidate_cache(inode);
2139 * We start scanning from right side, freeing all the blocks
2140 * after i_size and walking into the tree depth-wise.
2142 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2143 if (path == NULL) {
2144 ext4_journal_stop(handle);
2145 return -ENOMEM;
2147 path[0].p_hdr = ext_inode_hdr(inode);
2148 if (ext4_ext_check_header(inode, path[0].p_hdr, depth)) {
2149 err = -EIO;
2150 goto out;
2152 path[0].p_depth = depth;
2154 while (i >= 0 && err == 0) {
2155 if (i == depth) {
2156 /* this is leaf block */
2157 err = ext4_ext_rm_leaf(handle, inode, path, start);
2158 /* root level has p_bh == NULL, brelse() eats this */
2159 brelse(path[i].p_bh);
2160 path[i].p_bh = NULL;
2161 i--;
2162 continue;
2165 /* this is index block */
2166 if (!path[i].p_hdr) {
2167 ext_debug("initialize header\n");
2168 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2171 if (!path[i].p_idx) {
2172 /* this level hasn't been touched yet */
2173 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2174 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2175 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2176 path[i].p_hdr,
2177 le16_to_cpu(path[i].p_hdr->eh_entries));
2178 } else {
2179 /* we were already here, see at next index */
2180 path[i].p_idx--;
2183 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2184 i, EXT_FIRST_INDEX(path[i].p_hdr),
2185 path[i].p_idx);
2186 if (ext4_ext_more_to_rm(path + i)) {
2187 struct buffer_head *bh;
2188 /* go to the next level */
2189 ext_debug("move to level %d (block %llu)\n",
2190 i + 1, idx_pblock(path[i].p_idx));
2191 memset(path + i + 1, 0, sizeof(*path));
2192 bh = sb_bread(sb, idx_pblock(path[i].p_idx));
2193 if (!bh) {
2194 /* should we reset i_size? */
2195 err = -EIO;
2196 break;
2198 if (WARN_ON(i + 1 > depth)) {
2199 err = -EIO;
2200 break;
2202 if (ext4_ext_check_header(inode, ext_block_hdr(bh),
2203 depth - i - 1)) {
2204 err = -EIO;
2205 break;
2207 path[i + 1].p_bh = bh;
2209 /* save actual number of indexes since this
2210 * number is changed at the next iteration */
2211 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2212 i++;
2213 } else {
2214 /* we finished processing this index, go up */
2215 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2216 /* index is empty, remove it;
2217 * handle must be already prepared by the
2218 * truncatei_leaf() */
2219 err = ext4_ext_rm_idx(handle, inode, path + i);
2221 /* root level has p_bh == NULL, brelse() eats this */
2222 brelse(path[i].p_bh);
2223 path[i].p_bh = NULL;
2224 i--;
2225 ext_debug("return to level %d\n", i);
2229 /* TODO: flexible tree reduction should be here */
2230 if (path->p_hdr->eh_entries == 0) {
2232 * truncate to zero freed all the tree,
2233 * so we need to correct eh_depth
2235 err = ext4_ext_get_access(handle, inode, path);
2236 if (err == 0) {
2237 ext_inode_hdr(inode)->eh_depth = 0;
2238 ext_inode_hdr(inode)->eh_max =
2239 cpu_to_le16(ext4_ext_space_root(inode));
2240 err = ext4_ext_dirty(handle, inode, path);
2243 out:
2244 ext4_ext_drop_refs(path);
2245 kfree(path);
2246 ext4_journal_stop(handle);
2248 return err;
2252 * called at mount time
2254 void ext4_ext_init(struct super_block *sb)
2257 * possible initialization would be here
2260 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2261 printk(KERN_INFO "EXT4-fs: file extents enabled");
2262 #ifdef AGGRESSIVE_TEST
2263 printk(", aggressive tests");
2264 #endif
2265 #ifdef CHECK_BINSEARCH
2266 printk(", check binsearch");
2267 #endif
2268 #ifdef EXTENTS_STATS
2269 printk(", stats");
2270 #endif
2271 printk("\n");
2272 #ifdef EXTENTS_STATS
2273 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2274 EXT4_SB(sb)->s_ext_min = 1 << 30;
2275 EXT4_SB(sb)->s_ext_max = 0;
2276 #endif
2281 * called at umount time
2283 void ext4_ext_release(struct super_block *sb)
2285 if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2286 return;
2288 #ifdef EXTENTS_STATS
2289 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2290 struct ext4_sb_info *sbi = EXT4_SB(sb);
2291 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2292 sbi->s_ext_blocks, sbi->s_ext_extents,
2293 sbi->s_ext_blocks / sbi->s_ext_extents);
2294 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2295 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2297 #endif
2300 static void bi_complete(struct bio *bio, int error)
2302 complete((struct completion *)bio->bi_private);
2305 /* FIXME!! we need to try to merge to left or right after zero-out */
2306 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2308 int ret = -EIO;
2309 struct bio *bio;
2310 int blkbits, blocksize;
2311 sector_t ee_pblock;
2312 struct completion event;
2313 unsigned int ee_len, len, done, offset;
2316 blkbits = inode->i_blkbits;
2317 blocksize = inode->i_sb->s_blocksize;
2318 ee_len = ext4_ext_get_actual_len(ex);
2319 ee_pblock = ext_pblock(ex);
2321 /* convert ee_pblock to 512 byte sectors */
2322 ee_pblock = ee_pblock << (blkbits - 9);
2324 while (ee_len > 0) {
2326 if (ee_len > BIO_MAX_PAGES)
2327 len = BIO_MAX_PAGES;
2328 else
2329 len = ee_len;
2331 bio = bio_alloc(GFP_NOIO, len);
2332 if (!bio)
2333 return -ENOMEM;
2334 bio->bi_sector = ee_pblock;
2335 bio->bi_bdev = inode->i_sb->s_bdev;
2337 done = 0;
2338 offset = 0;
2339 while (done < len) {
2340 ret = bio_add_page(bio, ZERO_PAGE(0),
2341 blocksize, offset);
2342 if (ret != blocksize) {
2344 * We can't add any more pages because of
2345 * hardware limitations. Start a new bio.
2347 break;
2349 done++;
2350 offset += blocksize;
2351 if (offset >= PAGE_CACHE_SIZE)
2352 offset = 0;
2355 init_completion(&event);
2356 bio->bi_private = &event;
2357 bio->bi_end_io = bi_complete;
2358 submit_bio(WRITE, bio);
2359 wait_for_completion(&event);
2361 if (test_bit(BIO_UPTODATE, &bio->bi_flags))
2362 ret = 0;
2363 else {
2364 ret = -EIO;
2365 break;
2367 bio_put(bio);
2368 ee_len -= done;
2369 ee_pblock += done << (blkbits - 9);
2371 return ret;
2374 #define EXT4_EXT_ZERO_LEN 7
2377 * This function is called by ext4_ext_get_blocks() if someone tries to write
2378 * to an uninitialized extent. It may result in splitting the uninitialized
2379 * extent into multiple extents (upto three - one initialized and two
2380 * uninitialized).
2381 * There are three possibilities:
2382 * a> There is no split required: Entire extent should be initialized
2383 * b> Splits in two extents: Write is happening at either end of the extent
2384 * c> Splits in three extents: Somone is writing in middle of the extent
2386 static int ext4_ext_convert_to_initialized(handle_t *handle,
2387 struct inode *inode,
2388 struct ext4_ext_path *path,
2389 ext4_lblk_t iblock,
2390 unsigned int max_blocks)
2392 struct ext4_extent *ex, newex, orig_ex;
2393 struct ext4_extent *ex1 = NULL;
2394 struct ext4_extent *ex2 = NULL;
2395 struct ext4_extent *ex3 = NULL;
2396 struct ext4_extent_header *eh;
2397 ext4_lblk_t ee_block;
2398 unsigned int allocated, ee_len, depth;
2399 ext4_fsblk_t newblock;
2400 int err = 0;
2401 int ret = 0;
2403 depth = ext_depth(inode);
2404 eh = path[depth].p_hdr;
2405 ex = path[depth].p_ext;
2406 ee_block = le32_to_cpu(ex->ee_block);
2407 ee_len = ext4_ext_get_actual_len(ex);
2408 allocated = ee_len - (iblock - ee_block);
2409 newblock = iblock - ee_block + ext_pblock(ex);
2410 ex2 = ex;
2411 orig_ex.ee_block = ex->ee_block;
2412 orig_ex.ee_len = cpu_to_le16(ee_len);
2413 ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2415 err = ext4_ext_get_access(handle, inode, path + depth);
2416 if (err)
2417 goto out;
2418 /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
2419 if (ee_len <= 2*EXT4_EXT_ZERO_LEN) {
2420 err = ext4_ext_zeroout(inode, &orig_ex);
2421 if (err)
2422 goto fix_extent_len;
2423 /* update the extent length and mark as initialized */
2424 ex->ee_block = orig_ex.ee_block;
2425 ex->ee_len = orig_ex.ee_len;
2426 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2427 ext4_ext_dirty(handle, inode, path + depth);
2428 /* zeroed the full extent */
2429 return allocated;
2432 /* ex1: ee_block to iblock - 1 : uninitialized */
2433 if (iblock > ee_block) {
2434 ex1 = ex;
2435 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2436 ext4_ext_mark_uninitialized(ex1);
2437 ex2 = &newex;
2440 * for sanity, update the length of the ex2 extent before
2441 * we insert ex3, if ex1 is NULL. This is to avoid temporary
2442 * overlap of blocks.
2444 if (!ex1 && allocated > max_blocks)
2445 ex2->ee_len = cpu_to_le16(max_blocks);
2446 /* ex3: to ee_block + ee_len : uninitialised */
2447 if (allocated > max_blocks) {
2448 unsigned int newdepth;
2449 /* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
2450 if (allocated <= EXT4_EXT_ZERO_LEN) {
2452 * iblock == ee_block is handled by the zerouout
2453 * at the beginning.
2454 * Mark first half uninitialized.
2455 * Mark second half initialized and zero out the
2456 * initialized extent
2458 ex->ee_block = orig_ex.ee_block;
2459 ex->ee_len = cpu_to_le16(ee_len - allocated);
2460 ext4_ext_mark_uninitialized(ex);
2461 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2462 ext4_ext_dirty(handle, inode, path + depth);
2464 ex3 = &newex;
2465 ex3->ee_block = cpu_to_le32(iblock);
2466 ext4_ext_store_pblock(ex3, newblock);
2467 ex3->ee_len = cpu_to_le16(allocated);
2468 err = ext4_ext_insert_extent(handle, inode, path, ex3);
2469 if (err == -ENOSPC) {
2470 err = ext4_ext_zeroout(inode, &orig_ex);
2471 if (err)
2472 goto fix_extent_len;
2473 ex->ee_block = orig_ex.ee_block;
2474 ex->ee_len = orig_ex.ee_len;
2475 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2476 ext4_ext_dirty(handle, inode, path + depth);
2477 /* blocks available from iblock */
2478 return allocated;
2480 } else if (err)
2481 goto fix_extent_len;
2484 * We need to zero out the second half because
2485 * an fallocate request can update file size and
2486 * converting the second half to initialized extent
2487 * implies that we can leak some junk data to user
2488 * space.
2490 err = ext4_ext_zeroout(inode, ex3);
2491 if (err) {
2493 * We should actually mark the
2494 * second half as uninit and return error
2495 * Insert would have changed the extent
2497 depth = ext_depth(inode);
2498 ext4_ext_drop_refs(path);
2499 path = ext4_ext_find_extent(inode,
2500 iblock, path);
2501 if (IS_ERR(path)) {
2502 err = PTR_ERR(path);
2503 return err;
2505 /* get the second half extent details */
2506 ex = path[depth].p_ext;
2507 err = ext4_ext_get_access(handle, inode,
2508 path + depth);
2509 if (err)
2510 return err;
2511 ext4_ext_mark_uninitialized(ex);
2512 ext4_ext_dirty(handle, inode, path + depth);
2513 return err;
2516 /* zeroed the second half */
2517 return allocated;
2519 ex3 = &newex;
2520 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2521 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2522 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2523 ext4_ext_mark_uninitialized(ex3);
2524 err = ext4_ext_insert_extent(handle, inode, path, ex3);
2525 if (err == -ENOSPC) {
2526 err = ext4_ext_zeroout(inode, &orig_ex);
2527 if (err)
2528 goto fix_extent_len;
2529 /* update the extent length and mark as initialized */
2530 ex->ee_block = orig_ex.ee_block;
2531 ex->ee_len = orig_ex.ee_len;
2532 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2533 ext4_ext_dirty(handle, inode, path + depth);
2534 /* zeroed the full extent */
2535 /* blocks available from iblock */
2536 return allocated;
2538 } else if (err)
2539 goto fix_extent_len;
2541 * The depth, and hence eh & ex might change
2542 * as part of the insert above.
2544 newdepth = ext_depth(inode);
2546 * update the extent length after successful insert of the
2547 * split extent
2549 orig_ex.ee_len = cpu_to_le16(ee_len -
2550 ext4_ext_get_actual_len(ex3));
2551 depth = newdepth;
2552 ext4_ext_drop_refs(path);
2553 path = ext4_ext_find_extent(inode, iblock, path);
2554 if (IS_ERR(path)) {
2555 err = PTR_ERR(path);
2556 goto out;
2558 eh = path[depth].p_hdr;
2559 ex = path[depth].p_ext;
2560 if (ex2 != &newex)
2561 ex2 = ex;
2563 err = ext4_ext_get_access(handle, inode, path + depth);
2564 if (err)
2565 goto out;
2567 allocated = max_blocks;
2569 /* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
2570 * to insert a extent in the middle zerout directly
2571 * otherwise give the extent a chance to merge to left
2573 if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
2574 iblock != ee_block) {
2575 err = ext4_ext_zeroout(inode, &orig_ex);
2576 if (err)
2577 goto fix_extent_len;
2578 /* update the extent length and mark as initialized */
2579 ex->ee_block = orig_ex.ee_block;
2580 ex->ee_len = orig_ex.ee_len;
2581 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2582 ext4_ext_dirty(handle, inode, path + depth);
2583 /* zero out the first half */
2584 /* blocks available from iblock */
2585 return allocated;
2589 * If there was a change of depth as part of the
2590 * insertion of ex3 above, we need to update the length
2591 * of the ex1 extent again here
2593 if (ex1 && ex1 != ex) {
2594 ex1 = ex;
2595 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2596 ext4_ext_mark_uninitialized(ex1);
2597 ex2 = &newex;
2599 /* ex2: iblock to iblock + maxblocks-1 : initialised */
2600 ex2->ee_block = cpu_to_le32(iblock);
2601 ext4_ext_store_pblock(ex2, newblock);
2602 ex2->ee_len = cpu_to_le16(allocated);
2603 if (ex2 != ex)
2604 goto insert;
2606 * New (initialized) extent starts from the first block
2607 * in the current extent. i.e., ex2 == ex
2608 * We have to see if it can be merged with the extent
2609 * on the left.
2611 if (ex2 > EXT_FIRST_EXTENT(eh)) {
2613 * To merge left, pass "ex2 - 1" to try_to_merge(),
2614 * since it merges towards right _only_.
2616 ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
2617 if (ret) {
2618 err = ext4_ext_correct_indexes(handle, inode, path);
2619 if (err)
2620 goto out;
2621 depth = ext_depth(inode);
2622 ex2--;
2626 * Try to Merge towards right. This might be required
2627 * only when the whole extent is being written to.
2628 * i.e. ex2 == ex and ex3 == NULL.
2630 if (!ex3) {
2631 ret = ext4_ext_try_to_merge(inode, path, ex2);
2632 if (ret) {
2633 err = ext4_ext_correct_indexes(handle, inode, path);
2634 if (err)
2635 goto out;
2638 /* Mark modified extent as dirty */
2639 err = ext4_ext_dirty(handle, inode, path + depth);
2640 goto out;
2641 insert:
2642 err = ext4_ext_insert_extent(handle, inode, path, &newex);
2643 if (err == -ENOSPC) {
2644 err = ext4_ext_zeroout(inode, &orig_ex);
2645 if (err)
2646 goto fix_extent_len;
2647 /* update the extent length and mark as initialized */
2648 ex->ee_block = orig_ex.ee_block;
2649 ex->ee_len = orig_ex.ee_len;
2650 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2651 ext4_ext_dirty(handle, inode, path + depth);
2652 /* zero out the first half */
2653 return allocated;
2654 } else if (err)
2655 goto fix_extent_len;
2656 out:
2657 return err ? err : allocated;
2659 fix_extent_len:
2660 ex->ee_block = orig_ex.ee_block;
2661 ex->ee_len = orig_ex.ee_len;
2662 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2663 ext4_ext_mark_uninitialized(ex);
2664 ext4_ext_dirty(handle, inode, path + depth);
2665 return err;
2669 * Block allocation/map/preallocation routine for extents based files
2672 * Need to be called with
2673 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
2674 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
2676 * return > 0, number of of blocks already mapped/allocated
2677 * if create == 0 and these are pre-allocated blocks
2678 * buffer head is unmapped
2679 * otherwise blocks are mapped
2681 * return = 0, if plain look up failed (blocks have not been allocated)
2682 * buffer head is unmapped
2684 * return < 0, error case.
2686 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
2687 ext4_lblk_t iblock,
2688 unsigned int max_blocks, struct buffer_head *bh_result,
2689 int create, int extend_disksize)
2691 struct ext4_ext_path *path = NULL;
2692 struct ext4_extent_header *eh;
2693 struct ext4_extent newex, *ex;
2694 ext4_fsblk_t newblock;
2695 int err = 0, depth, ret, cache_type;
2696 unsigned int allocated = 0;
2697 struct ext4_allocation_request ar;
2698 loff_t disksize;
2700 __clear_bit(BH_New, &bh_result->b_state);
2701 ext_debug("blocks %u/%u requested for inode %u\n",
2702 iblock, max_blocks, inode->i_ino);
2704 /* check in cache */
2705 cache_type = ext4_ext_in_cache(inode, iblock, &newex);
2706 if (cache_type) {
2707 if (cache_type == EXT4_EXT_CACHE_GAP) {
2708 if (!create) {
2710 * block isn't allocated yet and
2711 * user doesn't want to allocate it
2713 goto out2;
2715 /* we should allocate requested block */
2716 } else if (cache_type == EXT4_EXT_CACHE_EXTENT) {
2717 /* block is already allocated */
2718 newblock = iblock
2719 - le32_to_cpu(newex.ee_block)
2720 + ext_pblock(&newex);
2721 /* number of remaining blocks in the extent */
2722 allocated = ext4_ext_get_actual_len(&newex) -
2723 (iblock - le32_to_cpu(newex.ee_block));
2724 goto out;
2725 } else {
2726 BUG();
2730 /* find extent for this block */
2731 path = ext4_ext_find_extent(inode, iblock, NULL);
2732 if (IS_ERR(path)) {
2733 err = PTR_ERR(path);
2734 path = NULL;
2735 goto out2;
2738 depth = ext_depth(inode);
2741 * consistent leaf must not be empty;
2742 * this situation is possible, though, _during_ tree modification;
2743 * this is why assert can't be put in ext4_ext_find_extent()
2745 BUG_ON(path[depth].p_ext == NULL && depth != 0);
2746 eh = path[depth].p_hdr;
2748 ex = path[depth].p_ext;
2749 if (ex) {
2750 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
2751 ext4_fsblk_t ee_start = ext_pblock(ex);
2752 unsigned short ee_len;
2755 * Uninitialized extents are treated as holes, except that
2756 * we split out initialized portions during a write.
2758 ee_len = ext4_ext_get_actual_len(ex);
2759 /* if found extent covers block, simply return it */
2760 if (iblock >= ee_block && iblock < ee_block + ee_len) {
2761 newblock = iblock - ee_block + ee_start;
2762 /* number of remaining blocks in the extent */
2763 allocated = ee_len - (iblock - ee_block);
2764 ext_debug("%u fit into %lu:%d -> %llu\n", iblock,
2765 ee_block, ee_len, newblock);
2767 /* Do not put uninitialized extent in the cache */
2768 if (!ext4_ext_is_uninitialized(ex)) {
2769 ext4_ext_put_in_cache(inode, ee_block,
2770 ee_len, ee_start,
2771 EXT4_EXT_CACHE_EXTENT);
2772 goto out;
2774 if (create == EXT4_CREATE_UNINITIALIZED_EXT)
2775 goto out;
2776 if (!create) {
2778 * We have blocks reserved already. We
2779 * return allocated blocks so that delalloc
2780 * won't do block reservation for us. But
2781 * the buffer head will be unmapped so that
2782 * a read from the block returns 0s.
2784 if (allocated > max_blocks)
2785 allocated = max_blocks;
2786 set_buffer_unwritten(bh_result);
2787 bh_result->b_bdev = inode->i_sb->s_bdev;
2788 bh_result->b_blocknr = newblock;
2789 goto out2;
2792 ret = ext4_ext_convert_to_initialized(handle, inode,
2793 path, iblock,
2794 max_blocks);
2795 if (ret <= 0) {
2796 err = ret;
2797 goto out2;
2798 } else
2799 allocated = ret;
2800 goto outnew;
2805 * requested block isn't allocated yet;
2806 * we couldn't try to create block if create flag is zero
2808 if (!create) {
2810 * put just found gap into cache to speed up
2811 * subsequent requests
2813 ext4_ext_put_gap_in_cache(inode, path, iblock);
2814 goto out2;
2817 * Okay, we need to do block allocation.
2820 /* find neighbour allocated blocks */
2821 ar.lleft = iblock;
2822 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
2823 if (err)
2824 goto out2;
2825 ar.lright = iblock;
2826 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
2827 if (err)
2828 goto out2;
2831 * See if request is beyond maximum number of blocks we can have in
2832 * a single extent. For an initialized extent this limit is
2833 * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
2834 * EXT_UNINIT_MAX_LEN.
2836 if (max_blocks > EXT_INIT_MAX_LEN &&
2837 create != EXT4_CREATE_UNINITIALIZED_EXT)
2838 max_blocks = EXT_INIT_MAX_LEN;
2839 else if (max_blocks > EXT_UNINIT_MAX_LEN &&
2840 create == EXT4_CREATE_UNINITIALIZED_EXT)
2841 max_blocks = EXT_UNINIT_MAX_LEN;
2843 /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
2844 newex.ee_block = cpu_to_le32(iblock);
2845 newex.ee_len = cpu_to_le16(max_blocks);
2846 err = ext4_ext_check_overlap(inode, &newex, path);
2847 if (err)
2848 allocated = ext4_ext_get_actual_len(&newex);
2849 else
2850 allocated = max_blocks;
2852 /* allocate new block */
2853 ar.inode = inode;
2854 ar.goal = ext4_ext_find_goal(inode, path, iblock);
2855 ar.logical = iblock;
2856 ar.len = allocated;
2857 if (S_ISREG(inode->i_mode))
2858 ar.flags = EXT4_MB_HINT_DATA;
2859 else
2860 /* disable in-core preallocation for non-regular files */
2861 ar.flags = 0;
2862 newblock = ext4_mb_new_blocks(handle, &ar, &err);
2863 if (!newblock)
2864 goto out2;
2865 ext_debug("allocate new block: goal %llu, found %llu/%lu\n",
2866 ar.goal, newblock, allocated);
2868 /* try to insert new extent into found leaf and return */
2869 ext4_ext_store_pblock(&newex, newblock);
2870 newex.ee_len = cpu_to_le16(ar.len);
2871 if (create == EXT4_CREATE_UNINITIALIZED_EXT) /* Mark uninitialized */
2872 ext4_ext_mark_uninitialized(&newex);
2873 err = ext4_ext_insert_extent(handle, inode, path, &newex);
2874 if (err) {
2875 /* free data blocks we just allocated */
2876 /* not a good idea to call discard here directly,
2877 * but otherwise we'd need to call it every free() */
2878 ext4_discard_preallocations(inode);
2879 ext4_free_blocks(handle, inode, ext_pblock(&newex),
2880 ext4_ext_get_actual_len(&newex), 0);
2881 goto out2;
2884 /* previous routine could use block we allocated */
2885 newblock = ext_pblock(&newex);
2886 allocated = ext4_ext_get_actual_len(&newex);
2887 outnew:
2888 if (extend_disksize) {
2889 disksize = ((loff_t) iblock + ar.len) << inode->i_blkbits;
2890 if (disksize > i_size_read(inode))
2891 disksize = i_size_read(inode);
2892 if (disksize > EXT4_I(inode)->i_disksize)
2893 EXT4_I(inode)->i_disksize = disksize;
2896 set_buffer_new(bh_result);
2898 /* Cache only when it is _not_ an uninitialized extent */
2899 if (create != EXT4_CREATE_UNINITIALIZED_EXT)
2900 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2901 EXT4_EXT_CACHE_EXTENT);
2902 out:
2903 if (allocated > max_blocks)
2904 allocated = max_blocks;
2905 ext4_ext_show_leaf(inode, path);
2906 set_buffer_mapped(bh_result);
2907 bh_result->b_bdev = inode->i_sb->s_bdev;
2908 bh_result->b_blocknr = newblock;
2909 out2:
2910 if (path) {
2911 ext4_ext_drop_refs(path);
2912 kfree(path);
2914 return err ? err : allocated;
2917 void ext4_ext_truncate(struct inode *inode)
2919 struct address_space *mapping = inode->i_mapping;
2920 struct super_block *sb = inode->i_sb;
2921 ext4_lblk_t last_block;
2922 handle_t *handle;
2923 int err = 0;
2926 * probably first extent we're gonna free will be last in block
2928 err = ext4_writepage_trans_blocks(inode);
2929 handle = ext4_journal_start(inode, err);
2930 if (IS_ERR(handle))
2931 return;
2933 if (inode->i_size & (sb->s_blocksize - 1))
2934 ext4_block_truncate_page(handle, mapping, inode->i_size);
2936 if (ext4_orphan_add(handle, inode))
2937 goto out_stop;
2939 down_write(&EXT4_I(inode)->i_data_sem);
2940 ext4_ext_invalidate_cache(inode);
2942 ext4_discard_preallocations(inode);
2945 * TODO: optimization is possible here.
2946 * Probably we need not scan at all,
2947 * because page truncation is enough.
2950 /* we have to know where to truncate from in crash case */
2951 EXT4_I(inode)->i_disksize = inode->i_size;
2952 ext4_mark_inode_dirty(handle, inode);
2954 last_block = (inode->i_size + sb->s_blocksize - 1)
2955 >> EXT4_BLOCK_SIZE_BITS(sb);
2956 err = ext4_ext_remove_space(inode, last_block);
2958 /* In a multi-transaction truncate, we only make the final
2959 * transaction synchronous.
2961 if (IS_SYNC(inode))
2962 ext4_handle_sync(handle);
2964 out_stop:
2965 up_write(&EXT4_I(inode)->i_data_sem);
2967 * If this was a simple ftruncate() and the file will remain alive,
2968 * then we need to clear up the orphan record which we created above.
2969 * However, if this was a real unlink then we were called by
2970 * ext4_delete_inode(), and we allow that function to clean up the
2971 * orphan info for us.
2973 if (inode->i_nlink)
2974 ext4_orphan_del(handle, inode);
2976 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
2977 ext4_mark_inode_dirty(handle, inode);
2978 ext4_journal_stop(handle);
2981 static void ext4_falloc_update_inode(struct inode *inode,
2982 int mode, loff_t new_size, int update_ctime)
2984 struct timespec now;
2986 if (update_ctime) {
2987 now = current_fs_time(inode->i_sb);
2988 if (!timespec_equal(&inode->i_ctime, &now))
2989 inode->i_ctime = now;
2992 * Update only when preallocation was requested beyond
2993 * the file size.
2995 if (!(mode & FALLOC_FL_KEEP_SIZE)) {
2996 if (new_size > i_size_read(inode))
2997 i_size_write(inode, new_size);
2998 if (new_size > EXT4_I(inode)->i_disksize)
2999 ext4_update_i_disksize(inode, new_size);
3005 * preallocate space for a file. This implements ext4's fallocate inode
3006 * operation, which gets called from sys_fallocate system call.
3007 * For block-mapped files, posix_fallocate should fall back to the method
3008 * of writing zeroes to the required new blocks (the same behavior which is
3009 * expected for file systems which do not support fallocate() system call).
3011 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
3013 handle_t *handle;
3014 ext4_lblk_t block;
3015 loff_t new_size;
3016 unsigned int max_blocks;
3017 int ret = 0;
3018 int ret2 = 0;
3019 int retries = 0;
3020 struct buffer_head map_bh;
3021 unsigned int credits, blkbits = inode->i_blkbits;
3024 * currently supporting (pre)allocate mode for extent-based
3025 * files _only_
3027 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
3028 return -EOPNOTSUPP;
3030 /* preallocation to directories is currently not supported */
3031 if (S_ISDIR(inode->i_mode))
3032 return -ENODEV;
3034 block = offset >> blkbits;
3036 * We can't just convert len to max_blocks because
3037 * If blocksize = 4096 offset = 3072 and len = 2048
3039 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3040 - block;
3042 * credits to insert 1 extent into extent tree
3044 credits = ext4_chunk_trans_blocks(inode, max_blocks);
3045 mutex_lock(&inode->i_mutex);
3046 retry:
3047 while (ret >= 0 && ret < max_blocks) {
3048 block = block + ret;
3049 max_blocks = max_blocks - ret;
3050 handle = ext4_journal_start(inode, credits);
3051 if (IS_ERR(handle)) {
3052 ret = PTR_ERR(handle);
3053 break;
3055 ret = ext4_get_blocks_wrap(handle, inode, block,
3056 max_blocks, &map_bh,
3057 EXT4_CREATE_UNINITIALIZED_EXT, 0, 0);
3058 if (ret <= 0) {
3059 #ifdef EXT4FS_DEBUG
3060 WARN_ON(ret <= 0);
3061 printk(KERN_ERR "%s: ext4_ext_get_blocks "
3062 "returned error inode#%lu, block=%u, "
3063 "max_blocks=%u", __func__,
3064 inode->i_ino, block, max_blocks);
3065 #endif
3066 ext4_mark_inode_dirty(handle, inode);
3067 ret2 = ext4_journal_stop(handle);
3068 break;
3070 if ((block + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
3071 blkbits) >> blkbits))
3072 new_size = offset + len;
3073 else
3074 new_size = (block + ret) << blkbits;
3076 ext4_falloc_update_inode(inode, mode, new_size,
3077 buffer_new(&map_bh));
3078 ext4_mark_inode_dirty(handle, inode);
3079 ret2 = ext4_journal_stop(handle);
3080 if (ret2)
3081 break;
3083 if (ret == -ENOSPC &&
3084 ext4_should_retry_alloc(inode->i_sb, &retries)) {
3085 ret = 0;
3086 goto retry;
3088 mutex_unlock(&inode->i_mutex);
3089 return ret > 0 ? ret2 : ret;
3093 * Callback function called for each extent to gather FIEMAP information.
3095 static int ext4_ext_fiemap_cb(struct inode *inode, struct ext4_ext_path *path,
3096 struct ext4_ext_cache *newex, struct ext4_extent *ex,
3097 void *data)
3099 struct fiemap_extent_info *fieinfo = data;
3100 unsigned long blksize_bits = inode->i_sb->s_blocksize_bits;
3101 __u64 logical;
3102 __u64 physical;
3103 __u64 length;
3104 __u32 flags = 0;
3105 int error;
3107 logical = (__u64)newex->ec_block << blksize_bits;
3109 if (newex->ec_type == EXT4_EXT_CACHE_GAP) {
3110 pgoff_t offset;
3111 struct page *page;
3112 struct buffer_head *bh = NULL;
3114 offset = logical >> PAGE_SHIFT;
3115 page = find_get_page(inode->i_mapping, offset);
3116 if (!page || !page_has_buffers(page))
3117 return EXT_CONTINUE;
3119 bh = page_buffers(page);
3121 if (!bh)
3122 return EXT_CONTINUE;
3124 if (buffer_delay(bh)) {
3125 flags |= FIEMAP_EXTENT_DELALLOC;
3126 page_cache_release(page);
3127 } else {
3128 page_cache_release(page);
3129 return EXT_CONTINUE;
3133 physical = (__u64)newex->ec_start << blksize_bits;
3134 length = (__u64)newex->ec_len << blksize_bits;
3136 if (ex && ext4_ext_is_uninitialized(ex))
3137 flags |= FIEMAP_EXTENT_UNWRITTEN;
3140 * If this extent reaches EXT_MAX_BLOCK, it must be last.
3142 * Or if ext4_ext_next_allocated_block is EXT_MAX_BLOCK,
3143 * this also indicates no more allocated blocks.
3145 * XXX this might miss a single-block extent at EXT_MAX_BLOCK
3147 if (logical + length - 1 == EXT_MAX_BLOCK ||
3148 ext4_ext_next_allocated_block(path) == EXT_MAX_BLOCK)
3149 flags |= FIEMAP_EXTENT_LAST;
3151 error = fiemap_fill_next_extent(fieinfo, logical, physical,
3152 length, flags);
3153 if (error < 0)
3154 return error;
3155 if (error == 1)
3156 return EXT_BREAK;
3158 return EXT_CONTINUE;
3161 /* fiemap flags we can handle specified here */
3162 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
3164 static int ext4_xattr_fiemap(struct inode *inode,
3165 struct fiemap_extent_info *fieinfo)
3167 __u64 physical = 0;
3168 __u64 length;
3169 __u32 flags = FIEMAP_EXTENT_LAST;
3170 int blockbits = inode->i_sb->s_blocksize_bits;
3171 int error = 0;
3173 /* in-inode? */
3174 if (EXT4_I(inode)->i_state & EXT4_STATE_XATTR) {
3175 struct ext4_iloc iloc;
3176 int offset; /* offset of xattr in inode */
3178 error = ext4_get_inode_loc(inode, &iloc);
3179 if (error)
3180 return error;
3181 physical = iloc.bh->b_blocknr << blockbits;
3182 offset = EXT4_GOOD_OLD_INODE_SIZE +
3183 EXT4_I(inode)->i_extra_isize;
3184 physical += offset;
3185 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
3186 flags |= FIEMAP_EXTENT_DATA_INLINE;
3187 } else { /* external block */
3188 physical = EXT4_I(inode)->i_file_acl << blockbits;
3189 length = inode->i_sb->s_blocksize;
3192 if (physical)
3193 error = fiemap_fill_next_extent(fieinfo, 0, physical,
3194 length, flags);
3195 return (error < 0 ? error : 0);
3198 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3199 __u64 start, __u64 len)
3201 ext4_lblk_t start_blk;
3202 ext4_lblk_t len_blks;
3203 int error = 0;
3205 /* fallback to generic here if not in extents fmt */
3206 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
3207 return generic_block_fiemap(inode, fieinfo, start, len,
3208 ext4_get_block);
3210 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
3211 return -EBADR;
3213 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
3214 error = ext4_xattr_fiemap(inode, fieinfo);
3215 } else {
3216 start_blk = start >> inode->i_sb->s_blocksize_bits;
3217 len_blks = len >> inode->i_sb->s_blocksize_bits;
3220 * Walk the extent tree gathering extent information.
3221 * ext4_ext_fiemap_cb will push extents back to user.
3223 down_write(&EXT4_I(inode)->i_data_sem);
3224 error = ext4_ext_walk_space(inode, start_blk, len_blks,
3225 ext4_ext_fiemap_cb, fieinfo);
3226 up_write(&EXT4_I(inode)->i_data_sem);
3229 return error;