2 * linux/fs/ext4/inode.c
4 * Copyright (C) 1992, 1993, 1994, 1995
5 * Remy Card (card@masi.ibp.fr)
6 * Laboratoire MASI - Institut Blaise Pascal
7 * Universite Pierre et Marie Curie (Paris VI)
11 * linux/fs/minix/inode.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * Goal-directed block allocation by Stephen Tweedie
16 * (sct@redhat.com), 1993, 1998
17 * Big-endian to little-endian byte-swapping/bitmaps by
18 * David S. Miller (davem@caip.rutgers.edu), 1995
19 * 64-bit file support on 64-bit platforms by Jakub Jelinek
20 * (jj@sunsite.ms.mff.cuni.cz)
22 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
25 #include <linux/module.h>
27 #include <linux/time.h>
28 #include <linux/jbd2.h>
29 #include <linux/highuid.h>
30 #include <linux/pagemap.h>
31 #include <linux/quotaops.h>
32 #include <linux/string.h>
33 #include <linux/buffer_head.h>
34 #include <linux/writeback.h>
35 #include <linux/pagevec.h>
36 #include <linux/mpage.h>
37 #include <linux/namei.h>
38 #include <linux/uio.h>
39 #include <linux/bio.h>
41 #include "ext4_jbd2.h"
44 #include "ext4_extents.h"
46 #include <trace/events/ext4.h>
48 #define MPAGE_DA_EXTENT_TAIL 0x01
50 static inline int ext4_begin_ordered_truncate(struct inode *inode,
53 return jbd2_journal_begin_ordered_truncate(
54 EXT4_SB(inode->i_sb)->s_journal,
55 &EXT4_I(inode)->jinode,
59 static void ext4_invalidatepage(struct page *page, unsigned long offset);
62 * Test whether an inode is a fast symlink.
64 static int ext4_inode_is_fast_symlink(struct inode *inode)
66 int ea_blocks = EXT4_I(inode)->i_file_acl ?
67 (inode->i_sb->s_blocksize >> 9) : 0;
69 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
73 * The ext4 forget function must perform a revoke if we are freeing data
74 * which has been journaled. Metadata (eg. indirect blocks) must be
75 * revoked in all cases.
77 * "bh" may be NULL: a metadata block may have been freed from memory
78 * but there may still be a record of it in the journal, and that record
79 * still needs to be revoked.
81 * If the handle isn't valid we're not journaling so there's nothing to do.
83 int ext4_forget(handle_t *handle, int is_metadata, struct inode *inode,
84 struct buffer_head *bh, ext4_fsblk_t blocknr)
88 if (!ext4_handle_valid(handle))
93 BUFFER_TRACE(bh, "enter");
95 jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
97 bh, is_metadata, inode->i_mode,
98 test_opt(inode->i_sb, DATA_FLAGS));
100 /* Never use the revoke function if we are doing full data
101 * journaling: there is no need to, and a V1 superblock won't
102 * support it. Otherwise, only skip the revoke on un-journaled
105 if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
106 (!is_metadata && !ext4_should_journal_data(inode))) {
108 BUFFER_TRACE(bh, "call jbd2_journal_forget");
109 return ext4_journal_forget(handle, bh);
115 * data!=journal && (is_metadata || should_journal_data(inode))
117 BUFFER_TRACE(bh, "call ext4_journal_revoke");
118 err = ext4_journal_revoke(handle, blocknr, bh);
120 ext4_abort(inode->i_sb, __func__,
121 "error %d when attempting revoke", err);
122 BUFFER_TRACE(bh, "exit");
127 * Work out how many blocks we need to proceed with the next chunk of a
128 * truncate transaction.
130 static unsigned long blocks_for_truncate(struct inode *inode)
134 needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
136 /* Give ourselves just enough room to cope with inodes in which
137 * i_blocks is corrupt: we've seen disk corruptions in the past
138 * which resulted in random data in an inode which looked enough
139 * like a regular file for ext4 to try to delete it. Things
140 * will go a bit crazy if that happens, but at least we should
141 * try not to panic the whole kernel. */
145 /* But we need to bound the transaction so we don't overflow the
147 if (needed > EXT4_MAX_TRANS_DATA)
148 needed = EXT4_MAX_TRANS_DATA;
150 return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
154 * Truncate transactions can be complex and absolutely huge. So we need to
155 * be able to restart the transaction at a conventient checkpoint to make
156 * sure we don't overflow the journal.
158 * start_transaction gets us a new handle for a truncate transaction,
159 * and extend_transaction tries to extend the existing one a bit. If
160 * extend fails, we need to propagate the failure up and restart the
161 * transaction in the top-level truncate loop. --sct
163 static handle_t *start_transaction(struct inode *inode)
167 result = ext4_journal_start(inode, blocks_for_truncate(inode));
171 ext4_std_error(inode->i_sb, PTR_ERR(result));
176 * Try to extend this transaction for the purposes of truncation.
178 * Returns 0 if we managed to create more room. If we can't create more
179 * room, and the transaction must be restarted we return 1.
181 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
183 if (!ext4_handle_valid(handle))
185 if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
187 if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
193 * Restart the transaction associated with *handle. This does a commit,
194 * so before we call here everything must be consistently dirtied against
197 static int ext4_journal_test_restart(handle_t *handle, struct inode *inode)
199 BUG_ON(EXT4_JOURNAL(inode) == NULL);
200 jbd_debug(2, "restarting handle %p\n", handle);
201 return ext4_journal_restart(handle, blocks_for_truncate(inode));
205 * Called at the last iput() if i_nlink is zero.
207 void ext4_delete_inode(struct inode *inode)
212 if (ext4_should_order_data(inode))
213 ext4_begin_ordered_truncate(inode, 0);
214 truncate_inode_pages(&inode->i_data, 0);
216 if (is_bad_inode(inode))
219 handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
220 if (IS_ERR(handle)) {
221 ext4_std_error(inode->i_sb, PTR_ERR(handle));
223 * If we're going to skip the normal cleanup, we still need to
224 * make sure that the in-core orphan linked list is properly
227 ext4_orphan_del(NULL, inode);
232 ext4_handle_sync(handle);
234 err = ext4_mark_inode_dirty(handle, inode);
236 ext4_warning(inode->i_sb, __func__,
237 "couldn't mark inode dirty (err %d)", err);
241 ext4_truncate(inode);
244 * ext4_ext_truncate() doesn't reserve any slop when it
245 * restarts journal transactions; therefore there may not be
246 * enough credits left in the handle to remove the inode from
247 * the orphan list and set the dtime field.
249 if (!ext4_handle_has_enough_credits(handle, 3)) {
250 err = ext4_journal_extend(handle, 3);
252 err = ext4_journal_restart(handle, 3);
254 ext4_warning(inode->i_sb, __func__,
255 "couldn't extend journal (err %d)", err);
257 ext4_journal_stop(handle);
263 * Kill off the orphan record which ext4_truncate created.
264 * AKPM: I think this can be inside the above `if'.
265 * Note that ext4_orphan_del() has to be able to cope with the
266 * deletion of a non-existent orphan - this is because we don't
267 * know if ext4_truncate() actually created an orphan record.
268 * (Well, we could do this if we need to, but heck - it works)
270 ext4_orphan_del(handle, inode);
271 EXT4_I(inode)->i_dtime = get_seconds();
274 * One subtle ordering requirement: if anything has gone wrong
275 * (transaction abort, IO errors, whatever), then we can still
276 * do these next steps (the fs will already have been marked as
277 * having errors), but we can't free the inode if the mark_dirty
280 if (ext4_mark_inode_dirty(handle, inode))
281 /* If that failed, just do the required in-core inode clear. */
284 ext4_free_inode(handle, inode);
285 ext4_journal_stop(handle);
288 clear_inode(inode); /* We must guarantee clearing of inode... */
294 struct buffer_head *bh;
297 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
299 p->key = *(p->p = v);
304 * ext4_block_to_path - parse the block number into array of offsets
305 * @inode: inode in question (we are only interested in its superblock)
306 * @i_block: block number to be parsed
307 * @offsets: array to store the offsets in
308 * @boundary: set this non-zero if the referred-to block is likely to be
309 * followed (on disk) by an indirect block.
311 * To store the locations of file's data ext4 uses a data structure common
312 * for UNIX filesystems - tree of pointers anchored in the inode, with
313 * data blocks at leaves and indirect blocks in intermediate nodes.
314 * This function translates the block number into path in that tree -
315 * return value is the path length and @offsets[n] is the offset of
316 * pointer to (n+1)th node in the nth one. If @block is out of range
317 * (negative or too large) warning is printed and zero returned.
319 * Note: function doesn't find node addresses, so no IO is needed. All
320 * we need to know is the capacity of indirect blocks (taken from the
325 * Portability note: the last comparison (check that we fit into triple
326 * indirect block) is spelled differently, because otherwise on an
327 * architecture with 32-bit longs and 8Kb pages we might get into trouble
328 * if our filesystem had 8Kb blocks. We might use long long, but that would
329 * kill us on x86. Oh, well, at least the sign propagation does not matter -
330 * i_block would have to be negative in the very beginning, so we would not
334 static int ext4_block_to_path(struct inode *inode,
336 ext4_lblk_t offsets[4], int *boundary)
338 int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
339 int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
340 const long direct_blocks = EXT4_NDIR_BLOCKS,
341 indirect_blocks = ptrs,
342 double_blocks = (1 << (ptrs_bits * 2));
347 ext4_warning(inode->i_sb, "ext4_block_to_path", "block < 0");
348 } else if (i_block < direct_blocks) {
349 offsets[n++] = i_block;
350 final = direct_blocks;
351 } else if ((i_block -= direct_blocks) < indirect_blocks) {
352 offsets[n++] = EXT4_IND_BLOCK;
353 offsets[n++] = i_block;
355 } else if ((i_block -= indirect_blocks) < double_blocks) {
356 offsets[n++] = EXT4_DIND_BLOCK;
357 offsets[n++] = i_block >> ptrs_bits;
358 offsets[n++] = i_block & (ptrs - 1);
360 } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
361 offsets[n++] = EXT4_TIND_BLOCK;
362 offsets[n++] = i_block >> (ptrs_bits * 2);
363 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
364 offsets[n++] = i_block & (ptrs - 1);
367 ext4_warning(inode->i_sb, "ext4_block_to_path",
368 "block %lu > max in inode %lu",
369 i_block + direct_blocks +
370 indirect_blocks + double_blocks, inode->i_ino);
373 *boundary = final - 1 - (i_block & (ptrs - 1));
377 static int __ext4_check_blockref(const char *function, struct inode *inode,
378 __le32 *p, unsigned int max)
383 while (bref < p+max) {
384 blk = le32_to_cpu(*bref++);
386 unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
388 ext4_error(inode->i_sb, function,
389 "invalid block reference %u "
390 "in inode #%lu", blk, inode->i_ino);
398 #define ext4_check_indirect_blockref(inode, bh) \
399 __ext4_check_blockref(__func__, inode, (__le32 *)(bh)->b_data, \
400 EXT4_ADDR_PER_BLOCK((inode)->i_sb))
402 #define ext4_check_inode_blockref(inode) \
403 __ext4_check_blockref(__func__, inode, EXT4_I(inode)->i_data, \
407 * ext4_get_branch - read the chain of indirect blocks leading to data
408 * @inode: inode in question
409 * @depth: depth of the chain (1 - direct pointer, etc.)
410 * @offsets: offsets of pointers in inode/indirect blocks
411 * @chain: place to store the result
412 * @err: here we store the error value
414 * Function fills the array of triples <key, p, bh> and returns %NULL
415 * if everything went OK or the pointer to the last filled triple
416 * (incomplete one) otherwise. Upon the return chain[i].key contains
417 * the number of (i+1)-th block in the chain (as it is stored in memory,
418 * i.e. little-endian 32-bit), chain[i].p contains the address of that
419 * number (it points into struct inode for i==0 and into the bh->b_data
420 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
421 * block for i>0 and NULL for i==0. In other words, it holds the block
422 * numbers of the chain, addresses they were taken from (and where we can
423 * verify that chain did not change) and buffer_heads hosting these
426 * Function stops when it stumbles upon zero pointer (absent block)
427 * (pointer to last triple returned, *@err == 0)
428 * or when it gets an IO error reading an indirect block
429 * (ditto, *@err == -EIO)
430 * or when it reads all @depth-1 indirect blocks successfully and finds
431 * the whole chain, all way to the data (returns %NULL, *err == 0).
433 * Need to be called with
434 * down_read(&EXT4_I(inode)->i_data_sem)
436 static Indirect *ext4_get_branch(struct inode *inode, int depth,
437 ext4_lblk_t *offsets,
438 Indirect chain[4], int *err)
440 struct super_block *sb = inode->i_sb;
442 struct buffer_head *bh;
445 /* i_data is not going away, no lock needed */
446 add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
450 bh = sb_getblk(sb, le32_to_cpu(p->key));
454 if (!bh_uptodate_or_lock(bh)) {
455 if (bh_submit_read(bh) < 0) {
459 /* validate block references */
460 if (ext4_check_indirect_blockref(inode, bh)) {
466 add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
480 * ext4_find_near - find a place for allocation with sufficient locality
482 * @ind: descriptor of indirect block.
484 * This function returns the preferred place for block allocation.
485 * It is used when heuristic for sequential allocation fails.
487 * + if there is a block to the left of our position - allocate near it.
488 * + if pointer will live in indirect block - allocate near that block.
489 * + if pointer will live in inode - allocate in the same
492 * In the latter case we colour the starting block by the callers PID to
493 * prevent it from clashing with concurrent allocations for a different inode
494 * in the same block group. The PID is used here so that functionally related
495 * files will be close-by on-disk.
497 * Caller must make sure that @ind is valid and will stay that way.
499 static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
501 struct ext4_inode_info *ei = EXT4_I(inode);
502 __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
504 ext4_fsblk_t bg_start;
505 ext4_fsblk_t last_block;
506 ext4_grpblk_t colour;
507 ext4_group_t block_group;
508 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
510 /* Try to find previous block */
511 for (p = ind->p - 1; p >= start; p--) {
513 return le32_to_cpu(*p);
516 /* No such thing, so let's try location of indirect block */
518 return ind->bh->b_blocknr;
521 * It is going to be referred to from the inode itself? OK, just put it
522 * into the same cylinder group then.
524 block_group = ei->i_block_group;
525 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
526 block_group &= ~(flex_size-1);
527 if (S_ISREG(inode->i_mode))
530 bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
531 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
534 * If we are doing delayed allocation, we don't need take
535 * colour into account.
537 if (test_opt(inode->i_sb, DELALLOC))
540 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
541 colour = (current->pid % 16) *
542 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
544 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
545 return bg_start + colour;
549 * ext4_find_goal - find a preferred place for allocation.
551 * @block: block we want
552 * @partial: pointer to the last triple within a chain
554 * Normally this function find the preferred place for block allocation,
557 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
561 * XXX need to get goal block from mballoc's data structures
564 return ext4_find_near(inode, partial);
568 * ext4_blks_to_allocate: Look up the block map and count the number
569 * of direct blocks need to be allocated for the given branch.
571 * @branch: chain of indirect blocks
572 * @k: number of blocks need for indirect blocks
573 * @blks: number of data blocks to be mapped.
574 * @blocks_to_boundary: the offset in the indirect block
576 * return the total number of blocks to be allocate, including the
577 * direct and indirect blocks.
579 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
580 int blocks_to_boundary)
582 unsigned int count = 0;
585 * Simple case, [t,d]Indirect block(s) has not allocated yet
586 * then it's clear blocks on that path have not allocated
589 /* right now we don't handle cross boundary allocation */
590 if (blks < blocks_to_boundary + 1)
593 count += blocks_to_boundary + 1;
598 while (count < blks && count <= blocks_to_boundary &&
599 le32_to_cpu(*(branch[0].p + count)) == 0) {
606 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
607 * @indirect_blks: the number of blocks need to allocate for indirect
610 * @new_blocks: on return it will store the new block numbers for
611 * the indirect blocks(if needed) and the first direct block,
612 * @blks: on return it will store the total number of allocated
615 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
616 ext4_lblk_t iblock, ext4_fsblk_t goal,
617 int indirect_blks, int blks,
618 ext4_fsblk_t new_blocks[4], int *err)
620 struct ext4_allocation_request ar;
622 unsigned long count = 0, blk_allocated = 0;
624 ext4_fsblk_t current_block = 0;
628 * Here we try to allocate the requested multiple blocks at once,
629 * on a best-effort basis.
630 * To build a branch, we should allocate blocks for
631 * the indirect blocks(if not allocated yet), and at least
632 * the first direct block of this branch. That's the
633 * minimum number of blocks need to allocate(required)
635 /* first we try to allocate the indirect blocks */
636 target = indirect_blks;
639 /* allocating blocks for indirect blocks and direct blocks */
640 current_block = ext4_new_meta_blocks(handle, inode,
646 /* allocate blocks for indirect blocks */
647 while (index < indirect_blks && count) {
648 new_blocks[index++] = current_block++;
653 * save the new block number
654 * for the first direct block
656 new_blocks[index] = current_block;
657 printk(KERN_INFO "%s returned more blocks than "
658 "requested\n", __func__);
664 target = blks - count ;
665 blk_allocated = count;
668 /* Now allocate data blocks */
669 memset(&ar, 0, sizeof(ar));
674 if (S_ISREG(inode->i_mode))
675 /* enable in-core preallocation only for regular files */
676 ar.flags = EXT4_MB_HINT_DATA;
678 current_block = ext4_mb_new_blocks(handle, &ar, err);
680 if (*err && (target == blks)) {
682 * if the allocation failed and we didn't allocate
688 if (target == blks) {
690 * save the new block number
691 * for the first direct block
693 new_blocks[index] = current_block;
695 blk_allocated += ar.len;
698 /* total number of blocks allocated for direct blocks */
703 for (i = 0; i < index; i++)
704 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
709 * ext4_alloc_branch - allocate and set up a chain of blocks.
711 * @indirect_blks: number of allocated indirect blocks
712 * @blks: number of allocated direct blocks
713 * @offsets: offsets (in the blocks) to store the pointers to next.
714 * @branch: place to store the chain in.
716 * This function allocates blocks, zeroes out all but the last one,
717 * links them into chain and (if we are synchronous) writes them to disk.
718 * In other words, it prepares a branch that can be spliced onto the
719 * inode. It stores the information about that chain in the branch[], in
720 * the same format as ext4_get_branch() would do. We are calling it after
721 * we had read the existing part of chain and partial points to the last
722 * triple of that (one with zero ->key). Upon the exit we have the same
723 * picture as after the successful ext4_get_block(), except that in one
724 * place chain is disconnected - *branch->p is still zero (we did not
725 * set the last link), but branch->key contains the number that should
726 * be placed into *branch->p to fill that gap.
728 * If allocation fails we free all blocks we've allocated (and forget
729 * their buffer_heads) and return the error value the from failed
730 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
731 * as described above and return 0.
733 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
734 ext4_lblk_t iblock, int indirect_blks,
735 int *blks, ext4_fsblk_t goal,
736 ext4_lblk_t *offsets, Indirect *branch)
738 int blocksize = inode->i_sb->s_blocksize;
741 struct buffer_head *bh;
743 ext4_fsblk_t new_blocks[4];
744 ext4_fsblk_t current_block;
746 num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
747 *blks, new_blocks, &err);
751 branch[0].key = cpu_to_le32(new_blocks[0]);
753 * metadata blocks and data blocks are allocated.
755 for (n = 1; n <= indirect_blks; n++) {
757 * Get buffer_head for parent block, zero it out
758 * and set the pointer to new one, then send
761 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
764 BUFFER_TRACE(bh, "call get_create_access");
765 err = ext4_journal_get_create_access(handle, bh);
772 memset(bh->b_data, 0, blocksize);
773 branch[n].p = (__le32 *) bh->b_data + offsets[n];
774 branch[n].key = cpu_to_le32(new_blocks[n]);
775 *branch[n].p = branch[n].key;
776 if (n == indirect_blks) {
777 current_block = new_blocks[n];
779 * End of chain, update the last new metablock of
780 * the chain to point to the new allocated
781 * data blocks numbers
783 for (i = 1; i < num; i++)
784 *(branch[n].p + i) = cpu_to_le32(++current_block);
786 BUFFER_TRACE(bh, "marking uptodate");
787 set_buffer_uptodate(bh);
790 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
791 err = ext4_handle_dirty_metadata(handle, inode, bh);
798 /* Allocation failed, free what we already allocated */
799 for (i = 1; i <= n ; i++) {
800 BUFFER_TRACE(branch[i].bh, "call jbd2_journal_forget");
801 ext4_journal_forget(handle, branch[i].bh);
803 for (i = 0; i < indirect_blks; i++)
804 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
806 ext4_free_blocks(handle, inode, new_blocks[i], num, 0);
812 * ext4_splice_branch - splice the allocated branch onto inode.
814 * @block: (logical) number of block we are adding
815 * @chain: chain of indirect blocks (with a missing link - see
817 * @where: location of missing link
818 * @num: number of indirect blocks we are adding
819 * @blks: number of direct blocks we are adding
821 * This function fills the missing link and does all housekeeping needed in
822 * inode (->i_blocks, etc.). In case of success we end up with the full
823 * chain to new block and return 0.
825 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
826 ext4_lblk_t block, Indirect *where, int num,
831 ext4_fsblk_t current_block;
834 * If we're splicing into a [td]indirect block (as opposed to the
835 * inode) then we need to get write access to the [td]indirect block
839 BUFFER_TRACE(where->bh, "get_write_access");
840 err = ext4_journal_get_write_access(handle, where->bh);
846 *where->p = where->key;
849 * Update the host buffer_head or inode to point to more just allocated
850 * direct blocks blocks
852 if (num == 0 && blks > 1) {
853 current_block = le32_to_cpu(where->key) + 1;
854 for (i = 1; i < blks; i++)
855 *(where->p + i) = cpu_to_le32(current_block++);
858 /* We are done with atomic stuff, now do the rest of housekeeping */
860 inode->i_ctime = ext4_current_time(inode);
861 ext4_mark_inode_dirty(handle, inode);
863 /* had we spliced it onto indirect block? */
866 * If we spliced it onto an indirect block, we haven't
867 * altered the inode. Note however that if it is being spliced
868 * onto an indirect block at the very end of the file (the
869 * file is growing) then we *will* alter the inode to reflect
870 * the new i_size. But that is not done here - it is done in
871 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
873 jbd_debug(5, "splicing indirect only\n");
874 BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
875 err = ext4_handle_dirty_metadata(handle, inode, where->bh);
880 * OK, we spliced it into the inode itself on a direct block.
881 * Inode was dirtied above.
883 jbd_debug(5, "splicing direct\n");
888 for (i = 1; i <= num; i++) {
889 BUFFER_TRACE(where[i].bh, "call jbd2_journal_forget");
890 ext4_journal_forget(handle, where[i].bh);
891 ext4_free_blocks(handle, inode,
892 le32_to_cpu(where[i-1].key), 1, 0);
894 ext4_free_blocks(handle, inode, le32_to_cpu(where[num].key), blks, 0);
900 * The ext4_ind_get_blocks() function handles non-extents inodes
901 * (i.e., using the traditional indirect/double-indirect i_blocks
902 * scheme) for ext4_get_blocks().
904 * Allocation strategy is simple: if we have to allocate something, we will
905 * have to go the whole way to leaf. So let's do it before attaching anything
906 * to tree, set linkage between the newborn blocks, write them if sync is
907 * required, recheck the path, free and repeat if check fails, otherwise
908 * set the last missing link (that will protect us from any truncate-generated
909 * removals - all blocks on the path are immune now) and possibly force the
910 * write on the parent block.
911 * That has a nice additional property: no special recovery from the failed
912 * allocations is needed - we simply release blocks and do not touch anything
913 * reachable from inode.
915 * `handle' can be NULL if create == 0.
917 * return > 0, # of blocks mapped or allocated.
918 * return = 0, if plain lookup failed.
919 * return < 0, error case.
921 * The ext4_ind_get_blocks() function should be called with
922 * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
923 * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
924 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
927 static int ext4_ind_get_blocks(handle_t *handle, struct inode *inode,
928 ext4_lblk_t iblock, unsigned int maxblocks,
929 struct buffer_head *bh_result,
933 ext4_lblk_t offsets[4];
938 int blocks_to_boundary = 0;
941 ext4_fsblk_t first_block = 0;
943 J_ASSERT(!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL));
944 J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
945 depth = ext4_block_to_path(inode, iblock, offsets,
946 &blocks_to_boundary);
951 partial = ext4_get_branch(inode, depth, offsets, chain, &err);
953 /* Simplest case - block found, no allocation needed */
955 first_block = le32_to_cpu(chain[depth - 1].key);
956 clear_buffer_new(bh_result);
959 while (count < maxblocks && count <= blocks_to_boundary) {
962 blk = le32_to_cpu(*(chain[depth-1].p + count));
964 if (blk == first_block + count)
972 /* Next simple case - plain lookup or failed read of indirect block */
973 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
977 * Okay, we need to do block allocation.
979 goal = ext4_find_goal(inode, iblock, partial);
981 /* the number of blocks need to allocate for [d,t]indirect blocks */
982 indirect_blks = (chain + depth) - partial - 1;
985 * Next look up the indirect map to count the totoal number of
986 * direct blocks to allocate for this branch.
988 count = ext4_blks_to_allocate(partial, indirect_blks,
989 maxblocks, blocks_to_boundary);
991 * Block out ext4_truncate while we alter the tree
993 err = ext4_alloc_branch(handle, inode, iblock, indirect_blks,
995 offsets + (partial - chain), partial);
998 * The ext4_splice_branch call will free and forget any buffers
999 * on the new chain if there is a failure, but that risks using
1000 * up transaction credits, especially for bitmaps where the
1001 * credits cannot be returned. Can we handle this somehow? We
1002 * may need to return -EAGAIN upwards in the worst case. --sct
1005 err = ext4_splice_branch(handle, inode, iblock,
1006 partial, indirect_blks, count);
1010 set_buffer_new(bh_result);
1012 map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
1013 if (count > blocks_to_boundary)
1014 set_buffer_boundary(bh_result);
1016 /* Clean up and exit */
1017 partial = chain + depth - 1; /* the whole chain */
1019 while (partial > chain) {
1020 BUFFER_TRACE(partial->bh, "call brelse");
1021 brelse(partial->bh);
1024 BUFFER_TRACE(bh_result, "returned");
1029 qsize_t ext4_get_reserved_space(struct inode *inode)
1031 unsigned long long total;
1033 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1034 total = EXT4_I(inode)->i_reserved_data_blocks +
1035 EXT4_I(inode)->i_reserved_meta_blocks;
1036 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1041 * Calculate the number of metadata blocks need to reserve
1042 * to allocate @blocks for non extent file based file
1044 static int ext4_indirect_calc_metadata_amount(struct inode *inode, int blocks)
1046 int icap = EXT4_ADDR_PER_BLOCK(inode->i_sb);
1047 int ind_blks, dind_blks, tind_blks;
1049 /* number of new indirect blocks needed */
1050 ind_blks = (blocks + icap - 1) / icap;
1052 dind_blks = (ind_blks + icap - 1) / icap;
1056 return ind_blks + dind_blks + tind_blks;
1060 * Calculate the number of metadata blocks need to reserve
1061 * to allocate given number of blocks
1063 static int ext4_calc_metadata_amount(struct inode *inode, int blocks)
1068 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
1069 return ext4_ext_calc_metadata_amount(inode, blocks);
1071 return ext4_indirect_calc_metadata_amount(inode, blocks);
1074 static void ext4_da_update_reserve_space(struct inode *inode, int used)
1076 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1077 int total, mdb, mdb_free;
1079 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1080 /* recalculate the number of metablocks still need to be reserved */
1081 total = EXT4_I(inode)->i_reserved_data_blocks - used;
1082 mdb = ext4_calc_metadata_amount(inode, total);
1084 /* figure out how many metablocks to release */
1085 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1086 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1089 /* Account for allocated meta_blocks */
1090 mdb_free -= EXT4_I(inode)->i_allocated_meta_blocks;
1092 /* update fs dirty blocks counter */
1093 percpu_counter_sub(&sbi->s_dirtyblocks_counter, mdb_free);
1094 EXT4_I(inode)->i_allocated_meta_blocks = 0;
1095 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1098 /* update per-inode reservations */
1099 BUG_ON(used > EXT4_I(inode)->i_reserved_data_blocks);
1100 EXT4_I(inode)->i_reserved_data_blocks -= used;
1101 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1104 * free those over-booking quota for metadata blocks
1107 vfs_dq_release_reservation_block(inode, mdb_free);
1110 * If we have done all the pending block allocations and if
1111 * there aren't any writers on the inode, we can discard the
1112 * inode's preallocations.
1114 if (!total && (atomic_read(&inode->i_writecount) == 0))
1115 ext4_discard_preallocations(inode);
1118 static int check_block_validity(struct inode *inode, sector_t logical,
1119 sector_t phys, int len)
1121 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), phys, len)) {
1122 ext4_error(inode->i_sb, "check_block_validity",
1123 "inode #%lu logical block %llu mapped to %llu "
1124 "(size %d)", inode->i_ino,
1125 (unsigned long long) logical,
1126 (unsigned long long) phys, len);
1134 * The ext4_get_blocks() function tries to look up the requested blocks,
1135 * and returns if the blocks are already mapped.
1137 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1138 * and store the allocated blocks in the result buffer head and mark it
1141 * If file type is extents based, it will call ext4_ext_get_blocks(),
1142 * Otherwise, call with ext4_ind_get_blocks() to handle indirect mapping
1145 * On success, it returns the number of blocks being mapped or allocate.
1146 * if create==0 and the blocks are pre-allocated and uninitialized block,
1147 * the result buffer head is unmapped. If the create ==1, it will make sure
1148 * the buffer head is mapped.
1150 * It returns 0 if plain look up failed (blocks have not been allocated), in
1151 * that casem, buffer head is unmapped
1153 * It returns the error in case of allocation failure.
1155 int ext4_get_blocks(handle_t *handle, struct inode *inode, sector_t block,
1156 unsigned int max_blocks, struct buffer_head *bh,
1161 clear_buffer_mapped(bh);
1162 clear_buffer_unwritten(bh);
1165 * Try to see if we can get the block without requesting a new
1166 * file system block.
1168 down_read((&EXT4_I(inode)->i_data_sem));
1169 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1170 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1173 retval = ext4_ind_get_blocks(handle, inode, block, max_blocks,
1176 up_read((&EXT4_I(inode)->i_data_sem));
1178 if (retval > 0 && buffer_mapped(bh)) {
1179 int ret = check_block_validity(inode, block,
1180 bh->b_blocknr, retval);
1185 /* If it is only a block(s) look up */
1186 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
1190 * Returns if the blocks have already allocated
1192 * Note that if blocks have been preallocated
1193 * ext4_ext_get_block() returns th create = 0
1194 * with buffer head unmapped.
1196 if (retval > 0 && buffer_mapped(bh))
1200 * When we call get_blocks without the create flag, the
1201 * BH_Unwritten flag could have gotten set if the blocks
1202 * requested were part of a uninitialized extent. We need to
1203 * clear this flag now that we are committed to convert all or
1204 * part of the uninitialized extent to be an initialized
1205 * extent. This is because we need to avoid the combination
1206 * of BH_Unwritten and BH_Mapped flags being simultaneously
1207 * set on the buffer_head.
1209 clear_buffer_unwritten(bh);
1212 * New blocks allocate and/or writing to uninitialized extent
1213 * will possibly result in updating i_data, so we take
1214 * the write lock of i_data_sem, and call get_blocks()
1215 * with create == 1 flag.
1217 down_write((&EXT4_I(inode)->i_data_sem));
1220 * if the caller is from delayed allocation writeout path
1221 * we have already reserved fs blocks for allocation
1222 * let the underlying get_block() function know to
1223 * avoid double accounting
1225 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1226 EXT4_I(inode)->i_delalloc_reserved_flag = 1;
1228 * We need to check for EXT4 here because migrate
1229 * could have changed the inode type in between
1231 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1232 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1235 retval = ext4_ind_get_blocks(handle, inode, block,
1236 max_blocks, bh, flags);
1238 if (retval > 0 && buffer_new(bh)) {
1240 * We allocated new blocks which will result in
1241 * i_data's format changing. Force the migrate
1242 * to fail by clearing migrate flags
1244 EXT4_I(inode)->i_flags = EXT4_I(inode)->i_flags &
1249 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1250 EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1253 * Update reserved blocks/metadata blocks after successful
1254 * block allocation which had been deferred till now.
1256 if ((retval > 0) && (flags & EXT4_GET_BLOCKS_UPDATE_RESERVE_SPACE))
1257 ext4_da_update_reserve_space(inode, retval);
1259 up_write((&EXT4_I(inode)->i_data_sem));
1260 if (retval > 0 && buffer_mapped(bh)) {
1261 int ret = check_block_validity(inode, block,
1262 bh->b_blocknr, retval);
1269 /* Maximum number of blocks we map for direct IO at once. */
1270 #define DIO_MAX_BLOCKS 4096
1272 int ext4_get_block(struct inode *inode, sector_t iblock,
1273 struct buffer_head *bh_result, int create)
1275 handle_t *handle = ext4_journal_current_handle();
1276 int ret = 0, started = 0;
1277 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
1280 if (create && !handle) {
1281 /* Direct IO write... */
1282 if (max_blocks > DIO_MAX_BLOCKS)
1283 max_blocks = DIO_MAX_BLOCKS;
1284 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
1285 handle = ext4_journal_start(inode, dio_credits);
1286 if (IS_ERR(handle)) {
1287 ret = PTR_ERR(handle);
1293 ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
1294 create ? EXT4_GET_BLOCKS_CREATE : 0);
1296 bh_result->b_size = (ret << inode->i_blkbits);
1300 ext4_journal_stop(handle);
1306 * `handle' can be NULL if create is zero
1308 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1309 ext4_lblk_t block, int create, int *errp)
1311 struct buffer_head dummy;
1315 J_ASSERT(handle != NULL || create == 0);
1318 dummy.b_blocknr = -1000;
1319 buffer_trace_init(&dummy.b_history);
1321 flags |= EXT4_GET_BLOCKS_CREATE;
1322 err = ext4_get_blocks(handle, inode, block, 1, &dummy, flags);
1324 * ext4_get_blocks() returns number of blocks mapped. 0 in
1333 if (!err && buffer_mapped(&dummy)) {
1334 struct buffer_head *bh;
1335 bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
1340 if (buffer_new(&dummy)) {
1341 J_ASSERT(create != 0);
1342 J_ASSERT(handle != NULL);
1345 * Now that we do not always journal data, we should
1346 * keep in mind whether this should always journal the
1347 * new buffer as metadata. For now, regular file
1348 * writes use ext4_get_block instead, so it's not a
1352 BUFFER_TRACE(bh, "call get_create_access");
1353 fatal = ext4_journal_get_create_access(handle, bh);
1354 if (!fatal && !buffer_uptodate(bh)) {
1355 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1356 set_buffer_uptodate(bh);
1359 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1360 err = ext4_handle_dirty_metadata(handle, inode, bh);
1364 BUFFER_TRACE(bh, "not a new buffer");
1377 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1378 ext4_lblk_t block, int create, int *err)
1380 struct buffer_head *bh;
1382 bh = ext4_getblk(handle, inode, block, create, err);
1385 if (buffer_uptodate(bh))
1387 ll_rw_block(READ_META, 1, &bh);
1389 if (buffer_uptodate(bh))
1396 static int walk_page_buffers(handle_t *handle,
1397 struct buffer_head *head,
1401 int (*fn)(handle_t *handle,
1402 struct buffer_head *bh))
1404 struct buffer_head *bh;
1405 unsigned block_start, block_end;
1406 unsigned blocksize = head->b_size;
1408 struct buffer_head *next;
1410 for (bh = head, block_start = 0;
1411 ret == 0 && (bh != head || !block_start);
1412 block_start = block_end, bh = next) {
1413 next = bh->b_this_page;
1414 block_end = block_start + blocksize;
1415 if (block_end <= from || block_start >= to) {
1416 if (partial && !buffer_uptodate(bh))
1420 err = (*fn)(handle, bh);
1428 * To preserve ordering, it is essential that the hole instantiation and
1429 * the data write be encapsulated in a single transaction. We cannot
1430 * close off a transaction and start a new one between the ext4_get_block()
1431 * and the commit_write(). So doing the jbd2_journal_start at the start of
1432 * prepare_write() is the right place.
1434 * Also, this function can nest inside ext4_writepage() ->
1435 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1436 * has generated enough buffer credits to do the whole page. So we won't
1437 * block on the journal in that case, which is good, because the caller may
1440 * By accident, ext4 can be reentered when a transaction is open via
1441 * quota file writes. If we were to commit the transaction while thus
1442 * reentered, there can be a deadlock - we would be holding a quota
1443 * lock, and the commit would never complete if another thread had a
1444 * transaction open and was blocking on the quota lock - a ranking
1447 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1448 * will _not_ run commit under these circumstances because handle->h_ref
1449 * is elevated. We'll still have enough credits for the tiny quotafile
1452 static int do_journal_get_write_access(handle_t *handle,
1453 struct buffer_head *bh)
1455 if (!buffer_mapped(bh) || buffer_freed(bh))
1457 return ext4_journal_get_write_access(handle, bh);
1460 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1461 loff_t pos, unsigned len, unsigned flags,
1462 struct page **pagep, void **fsdata)
1464 struct inode *inode = mapping->host;
1465 int ret, needed_blocks;
1472 trace_ext4_write_begin(inode, pos, len, flags);
1474 * Reserve one block more for addition to orphan list in case
1475 * we allocate blocks but write fails for some reason
1477 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1478 index = pos >> PAGE_CACHE_SHIFT;
1479 from = pos & (PAGE_CACHE_SIZE - 1);
1483 handle = ext4_journal_start(inode, needed_blocks);
1484 if (IS_ERR(handle)) {
1485 ret = PTR_ERR(handle);
1489 /* We cannot recurse into the filesystem as the transaction is already
1491 flags |= AOP_FLAG_NOFS;
1493 page = grab_cache_page_write_begin(mapping, index, flags);
1495 ext4_journal_stop(handle);
1501 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1504 if (!ret && ext4_should_journal_data(inode)) {
1505 ret = walk_page_buffers(handle, page_buffers(page),
1506 from, to, NULL, do_journal_get_write_access);
1511 page_cache_release(page);
1513 * block_write_begin may have instantiated a few blocks
1514 * outside i_size. Trim these off again. Don't need
1515 * i_size_read because we hold i_mutex.
1517 * Add inode to orphan list in case we crash before
1520 if (pos + len > inode->i_size)
1521 ext4_orphan_add(handle, inode);
1523 ext4_journal_stop(handle);
1524 if (pos + len > inode->i_size) {
1525 vmtruncate(inode, inode->i_size);
1527 * If vmtruncate failed early the inode might
1528 * still be on the orphan list; we need to
1529 * make sure the inode is removed from the
1530 * orphan list in that case.
1533 ext4_orphan_del(NULL, inode);
1537 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1543 /* For write_end() in data=journal mode */
1544 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1546 if (!buffer_mapped(bh) || buffer_freed(bh))
1548 set_buffer_uptodate(bh);
1549 return ext4_handle_dirty_metadata(handle, NULL, bh);
1552 static int ext4_generic_write_end(struct file *file,
1553 struct address_space *mapping,
1554 loff_t pos, unsigned len, unsigned copied,
1555 struct page *page, void *fsdata)
1557 int i_size_changed = 0;
1558 struct inode *inode = mapping->host;
1559 handle_t *handle = ext4_journal_current_handle();
1561 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1564 * No need to use i_size_read() here, the i_size
1565 * cannot change under us because we hold i_mutex.
1567 * But it's important to update i_size while still holding page lock:
1568 * page writeout could otherwise come in and zero beyond i_size.
1570 if (pos + copied > inode->i_size) {
1571 i_size_write(inode, pos + copied);
1575 if (pos + copied > EXT4_I(inode)->i_disksize) {
1576 /* We need to mark inode dirty even if
1577 * new_i_size is less that inode->i_size
1578 * bu greater than i_disksize.(hint delalloc)
1580 ext4_update_i_disksize(inode, (pos + copied));
1584 page_cache_release(page);
1587 * Don't mark the inode dirty under page lock. First, it unnecessarily
1588 * makes the holding time of page lock longer. Second, it forces lock
1589 * ordering of page lock and transaction start for journaling
1593 ext4_mark_inode_dirty(handle, inode);
1599 * We need to pick up the new inode size which generic_commit_write gave us
1600 * `file' can be NULL - eg, when called from page_symlink().
1602 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1603 * buffers are managed internally.
1605 static int ext4_ordered_write_end(struct file *file,
1606 struct address_space *mapping,
1607 loff_t pos, unsigned len, unsigned copied,
1608 struct page *page, void *fsdata)
1610 handle_t *handle = ext4_journal_current_handle();
1611 struct inode *inode = mapping->host;
1614 trace_ext4_ordered_write_end(inode, pos, len, copied);
1615 ret = ext4_jbd2_file_inode(handle, inode);
1618 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1621 if (pos + len > inode->i_size)
1622 /* if we have allocated more blocks and copied
1623 * less. We will have blocks allocated outside
1624 * inode->i_size. So truncate them
1626 ext4_orphan_add(handle, inode);
1630 ret2 = ext4_journal_stop(handle);
1634 if (pos + len > inode->i_size) {
1635 vmtruncate(inode, inode->i_size);
1637 * If vmtruncate failed early the inode might still be
1638 * on the orphan list; we need to make sure the inode
1639 * is removed from the orphan list in that case.
1642 ext4_orphan_del(NULL, inode);
1646 return ret ? ret : copied;
1649 static int ext4_writeback_write_end(struct file *file,
1650 struct address_space *mapping,
1651 loff_t pos, unsigned len, unsigned copied,
1652 struct page *page, void *fsdata)
1654 handle_t *handle = ext4_journal_current_handle();
1655 struct inode *inode = mapping->host;
1658 trace_ext4_writeback_write_end(inode, pos, len, copied);
1659 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1662 if (pos + len > inode->i_size)
1663 /* if we have allocated more blocks and copied
1664 * less. We will have blocks allocated outside
1665 * inode->i_size. So truncate them
1667 ext4_orphan_add(handle, inode);
1672 ret2 = ext4_journal_stop(handle);
1676 if (pos + len > inode->i_size) {
1677 vmtruncate(inode, inode->i_size);
1679 * If vmtruncate failed early the inode might still be
1680 * on the orphan list; we need to make sure the inode
1681 * is removed from the orphan list in that case.
1684 ext4_orphan_del(NULL, inode);
1687 return ret ? ret : copied;
1690 static int ext4_journalled_write_end(struct file *file,
1691 struct address_space *mapping,
1692 loff_t pos, unsigned len, unsigned copied,
1693 struct page *page, void *fsdata)
1695 handle_t *handle = ext4_journal_current_handle();
1696 struct inode *inode = mapping->host;
1702 trace_ext4_journalled_write_end(inode, pos, len, copied);
1703 from = pos & (PAGE_CACHE_SIZE - 1);
1707 if (!PageUptodate(page))
1709 page_zero_new_buffers(page, from+copied, to);
1712 ret = walk_page_buffers(handle, page_buffers(page), from,
1713 to, &partial, write_end_fn);
1715 SetPageUptodate(page);
1716 new_i_size = pos + copied;
1717 if (new_i_size > inode->i_size)
1718 i_size_write(inode, pos+copied);
1719 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
1720 if (new_i_size > EXT4_I(inode)->i_disksize) {
1721 ext4_update_i_disksize(inode, new_i_size);
1722 ret2 = ext4_mark_inode_dirty(handle, inode);
1728 page_cache_release(page);
1729 if (pos + len > inode->i_size)
1730 /* if we have allocated more blocks and copied
1731 * less. We will have blocks allocated outside
1732 * inode->i_size. So truncate them
1734 ext4_orphan_add(handle, inode);
1736 ret2 = ext4_journal_stop(handle);
1739 if (pos + len > inode->i_size) {
1740 vmtruncate(inode, inode->i_size);
1742 * If vmtruncate failed early the inode might still be
1743 * on the orphan list; we need to make sure the inode
1744 * is removed from the orphan list in that case.
1747 ext4_orphan_del(NULL, inode);
1750 return ret ? ret : copied;
1753 static int ext4_da_reserve_space(struct inode *inode, int nrblocks)
1756 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1757 unsigned long md_needed, mdblocks, total = 0;
1760 * recalculate the amount of metadata blocks to reserve
1761 * in order to allocate nrblocks
1762 * worse case is one extent per block
1765 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1766 total = EXT4_I(inode)->i_reserved_data_blocks + nrblocks;
1767 mdblocks = ext4_calc_metadata_amount(inode, total);
1768 BUG_ON(mdblocks < EXT4_I(inode)->i_reserved_meta_blocks);
1770 md_needed = mdblocks - EXT4_I(inode)->i_reserved_meta_blocks;
1771 total = md_needed + nrblocks;
1774 * Make quota reservation here to prevent quota overflow
1775 * later. Real quota accounting is done at pages writeout
1778 if (vfs_dq_reserve_block(inode, total)) {
1779 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1783 if (ext4_claim_free_blocks(sbi, total)) {
1784 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1785 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1789 vfs_dq_release_reservation_block(inode, total);
1792 EXT4_I(inode)->i_reserved_data_blocks += nrblocks;
1793 EXT4_I(inode)->i_reserved_meta_blocks = mdblocks;
1795 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1796 return 0; /* success */
1799 static void ext4_da_release_space(struct inode *inode, int to_free)
1801 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1802 int total, mdb, mdb_free, release;
1805 return; /* Nothing to release, exit */
1807 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1809 if (!EXT4_I(inode)->i_reserved_data_blocks) {
1811 * if there is no reserved blocks, but we try to free some
1812 * then the counter is messed up somewhere.
1813 * but since this function is called from invalidate
1814 * page, it's harmless to return without any action
1816 printk(KERN_INFO "ext4 delalloc try to release %d reserved "
1817 "blocks for inode %lu, but there is no reserved "
1818 "data blocks\n", to_free, inode->i_ino);
1819 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1823 /* recalculate the number of metablocks still need to be reserved */
1824 total = EXT4_I(inode)->i_reserved_data_blocks - to_free;
1825 mdb = ext4_calc_metadata_amount(inode, total);
1827 /* figure out how many metablocks to release */
1828 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1829 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1831 release = to_free + mdb_free;
1833 /* update fs dirty blocks counter for truncate case */
1834 percpu_counter_sub(&sbi->s_dirtyblocks_counter, release);
1836 /* update per-inode reservations */
1837 BUG_ON(to_free > EXT4_I(inode)->i_reserved_data_blocks);
1838 EXT4_I(inode)->i_reserved_data_blocks -= to_free;
1840 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1841 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1842 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1844 vfs_dq_release_reservation_block(inode, release);
1847 static void ext4_da_page_release_reservation(struct page *page,
1848 unsigned long offset)
1851 struct buffer_head *head, *bh;
1852 unsigned int curr_off = 0;
1854 head = page_buffers(page);
1857 unsigned int next_off = curr_off + bh->b_size;
1859 if ((offset <= curr_off) && (buffer_delay(bh))) {
1861 clear_buffer_delay(bh);
1863 curr_off = next_off;
1864 } while ((bh = bh->b_this_page) != head);
1865 ext4_da_release_space(page->mapping->host, to_release);
1869 * Delayed allocation stuff
1872 struct mpage_da_data {
1873 struct inode *inode;
1874 sector_t b_blocknr; /* start block number of extent */
1875 size_t b_size; /* size of extent */
1876 unsigned long b_state; /* state of the extent */
1877 unsigned long first_page, next_page; /* extent of pages */
1878 struct writeback_control *wbc;
1885 * mpage_da_submit_io - walks through extent of pages and try to write
1886 * them with writepage() call back
1888 * @mpd->inode: inode
1889 * @mpd->first_page: first page of the extent
1890 * @mpd->next_page: page after the last page of the extent
1892 * By the time mpage_da_submit_io() is called we expect all blocks
1893 * to be allocated. this may be wrong if allocation failed.
1895 * As pages are already locked by write_cache_pages(), we can't use it
1897 static int mpage_da_submit_io(struct mpage_da_data *mpd)
1900 struct pagevec pvec;
1901 unsigned long index, end;
1902 int ret = 0, err, nr_pages, i;
1903 struct inode *inode = mpd->inode;
1904 struct address_space *mapping = inode->i_mapping;
1906 BUG_ON(mpd->next_page <= mpd->first_page);
1908 * We need to start from the first_page to the next_page - 1
1909 * to make sure we also write the mapped dirty buffer_heads.
1910 * If we look at mpd->b_blocknr we would only be looking
1911 * at the currently mapped buffer_heads.
1913 index = mpd->first_page;
1914 end = mpd->next_page - 1;
1916 pagevec_init(&pvec, 0);
1917 while (index <= end) {
1918 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1921 for (i = 0; i < nr_pages; i++) {
1922 struct page *page = pvec.pages[i];
1924 index = page->index;
1929 BUG_ON(!PageLocked(page));
1930 BUG_ON(PageWriteback(page));
1932 pages_skipped = mpd->wbc->pages_skipped;
1933 err = mapping->a_ops->writepage(page, mpd->wbc);
1934 if (!err && (pages_skipped == mpd->wbc->pages_skipped))
1936 * have successfully written the page
1937 * without skipping the same
1939 mpd->pages_written++;
1941 * In error case, we have to continue because
1942 * remaining pages are still locked
1943 * XXX: unlock and re-dirty them?
1948 pagevec_release(&pvec);
1954 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
1956 * @mpd->inode - inode to walk through
1957 * @exbh->b_blocknr - first block on a disk
1958 * @exbh->b_size - amount of space in bytes
1959 * @logical - first logical block to start assignment with
1961 * the function goes through all passed space and put actual disk
1962 * block numbers into buffer heads, dropping BH_Delay and BH_Unwritten
1964 static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
1965 struct buffer_head *exbh)
1967 struct inode *inode = mpd->inode;
1968 struct address_space *mapping = inode->i_mapping;
1969 int blocks = exbh->b_size >> inode->i_blkbits;
1970 sector_t pblock = exbh->b_blocknr, cur_logical;
1971 struct buffer_head *head, *bh;
1973 struct pagevec pvec;
1976 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1977 end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1978 cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1980 pagevec_init(&pvec, 0);
1982 while (index <= end) {
1983 /* XXX: optimize tail */
1984 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1987 for (i = 0; i < nr_pages; i++) {
1988 struct page *page = pvec.pages[i];
1990 index = page->index;
1995 BUG_ON(!PageLocked(page));
1996 BUG_ON(PageWriteback(page));
1997 BUG_ON(!page_has_buffers(page));
1999 bh = page_buffers(page);
2002 /* skip blocks out of the range */
2004 if (cur_logical >= logical)
2007 } while ((bh = bh->b_this_page) != head);
2010 if (cur_logical >= logical + blocks)
2013 if (buffer_delay(bh) ||
2014 buffer_unwritten(bh)) {
2016 BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
2018 if (buffer_delay(bh)) {
2019 clear_buffer_delay(bh);
2020 bh->b_blocknr = pblock;
2023 * unwritten already should have
2024 * blocknr assigned. Verify that
2026 clear_buffer_unwritten(bh);
2027 BUG_ON(bh->b_blocknr != pblock);
2030 } else if (buffer_mapped(bh))
2031 BUG_ON(bh->b_blocknr != pblock);
2035 } while ((bh = bh->b_this_page) != head);
2037 pagevec_release(&pvec);
2043 * __unmap_underlying_blocks - just a helper function to unmap
2044 * set of blocks described by @bh
2046 static inline void __unmap_underlying_blocks(struct inode *inode,
2047 struct buffer_head *bh)
2049 struct block_device *bdev = inode->i_sb->s_bdev;
2052 blocks = bh->b_size >> inode->i_blkbits;
2053 for (i = 0; i < blocks; i++)
2054 unmap_underlying_metadata(bdev, bh->b_blocknr + i);
2057 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
2058 sector_t logical, long blk_cnt)
2062 struct pagevec pvec;
2063 struct inode *inode = mpd->inode;
2064 struct address_space *mapping = inode->i_mapping;
2066 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2067 end = (logical + blk_cnt - 1) >>
2068 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2069 while (index <= end) {
2070 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2073 for (i = 0; i < nr_pages; i++) {
2074 struct page *page = pvec.pages[i];
2075 index = page->index;
2080 BUG_ON(!PageLocked(page));
2081 BUG_ON(PageWriteback(page));
2082 block_invalidatepage(page, 0);
2083 ClearPageUptodate(page);
2090 static void ext4_print_free_blocks(struct inode *inode)
2092 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2093 printk(KERN_EMERG "Total free blocks count %lld\n",
2094 ext4_count_free_blocks(inode->i_sb));
2095 printk(KERN_EMERG "Free/Dirty block details\n");
2096 printk(KERN_EMERG "free_blocks=%lld\n",
2097 (long long)percpu_counter_sum(&sbi->s_freeblocks_counter));
2098 printk(KERN_EMERG "dirty_blocks=%lld\n",
2099 (long long)percpu_counter_sum(&sbi->s_dirtyblocks_counter));
2100 printk(KERN_EMERG "Block reservation details\n");
2101 printk(KERN_EMERG "i_reserved_data_blocks=%u\n",
2102 EXT4_I(inode)->i_reserved_data_blocks);
2103 printk(KERN_EMERG "i_reserved_meta_blocks=%u\n",
2104 EXT4_I(inode)->i_reserved_meta_blocks);
2109 * mpage_da_map_blocks - go through given space
2111 * @mpd - bh describing space
2113 * The function skips space we know is already mapped to disk blocks.
2116 static int mpage_da_map_blocks(struct mpage_da_data *mpd)
2118 int err, blks, get_blocks_flags;
2119 struct buffer_head new;
2120 sector_t next = mpd->b_blocknr;
2121 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
2122 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
2123 handle_t *handle = NULL;
2126 * We consider only non-mapped and non-allocated blocks
2128 if ((mpd->b_state & (1 << BH_Mapped)) &&
2129 !(mpd->b_state & (1 << BH_Delay)) &&
2130 !(mpd->b_state & (1 << BH_Unwritten)))
2134 * If we didn't accumulate anything to write simply return
2139 handle = ext4_journal_current_handle();
2143 * Call ext4_get_blocks() to allocate any delayed allocation
2144 * blocks, or to convert an uninitialized extent to be
2145 * initialized (in the case where we have written into
2146 * one or more preallocated blocks).
2148 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
2149 * indicate that we are on the delayed allocation path. This
2150 * affects functions in many different parts of the allocation
2151 * call path. This flag exists primarily because we don't
2152 * want to change *many* call functions, so ext4_get_blocks()
2153 * will set the magic i_delalloc_reserved_flag once the
2154 * inode's allocation semaphore is taken.
2156 * If the blocks in questions were delalloc blocks, set
2157 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
2158 * variables are updated after the blocks have been allocated.
2161 get_blocks_flags = (EXT4_GET_BLOCKS_CREATE |
2162 EXT4_GET_BLOCKS_DELALLOC_RESERVE);
2163 if (mpd->b_state & (1 << BH_Delay))
2164 get_blocks_flags |= EXT4_GET_BLOCKS_UPDATE_RESERVE_SPACE;
2165 blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks,
2166 &new, get_blocks_flags);
2170 * If get block returns with error we simply
2171 * return. Later writepage will redirty the page and
2172 * writepages will find the dirty page again
2177 if (err == -ENOSPC &&
2178 ext4_count_free_blocks(mpd->inode->i_sb)) {
2184 * get block failure will cause us to loop in
2185 * writepages, because a_ops->writepage won't be able
2186 * to make progress. The page will be redirtied by
2187 * writepage and writepages will again try to write
2190 printk(KERN_EMERG "%s block allocation failed for inode %lu "
2191 "at logical offset %llu with max blocks "
2192 "%zd with error %d\n",
2193 __func__, mpd->inode->i_ino,
2194 (unsigned long long)next,
2195 mpd->b_size >> mpd->inode->i_blkbits, err);
2196 printk(KERN_EMERG "This should not happen.!! "
2197 "Data will be lost\n");
2198 if (err == -ENOSPC) {
2199 ext4_print_free_blocks(mpd->inode);
2201 /* invalidate all the pages */
2202 ext4_da_block_invalidatepages(mpd, next,
2203 mpd->b_size >> mpd->inode->i_blkbits);
2208 new.b_size = (blks << mpd->inode->i_blkbits);
2210 if (buffer_new(&new))
2211 __unmap_underlying_blocks(mpd->inode, &new);
2214 * If blocks are delayed marked, we need to
2215 * put actual blocknr and drop delayed bit
2217 if ((mpd->b_state & (1 << BH_Delay)) ||
2218 (mpd->b_state & (1 << BH_Unwritten)))
2219 mpage_put_bnr_to_bhs(mpd, next, &new);
2221 if (ext4_should_order_data(mpd->inode)) {
2222 err = ext4_jbd2_file_inode(handle, mpd->inode);
2228 * Update on-disk size along with block allocation.
2230 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
2231 if (disksize > i_size_read(mpd->inode))
2232 disksize = i_size_read(mpd->inode);
2233 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
2234 ext4_update_i_disksize(mpd->inode, disksize);
2235 return ext4_mark_inode_dirty(handle, mpd->inode);
2241 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
2242 (1 << BH_Delay) | (1 << BH_Unwritten))
2245 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
2247 * @mpd->lbh - extent of blocks
2248 * @logical - logical number of the block in the file
2249 * @bh - bh of the block (used to access block's state)
2251 * the function is used to collect contig. blocks in same state
2253 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
2254 sector_t logical, size_t b_size,
2255 unsigned long b_state)
2258 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
2260 /* check if thereserved journal credits might overflow */
2261 if (!(EXT4_I(mpd->inode)->i_flags & EXT4_EXTENTS_FL)) {
2262 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2264 * With non-extent format we are limited by the journal
2265 * credit available. Total credit needed to insert
2266 * nrblocks contiguous blocks is dependent on the
2267 * nrblocks. So limit nrblocks.
2270 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2271 EXT4_MAX_TRANS_DATA) {
2273 * Adding the new buffer_head would make it cross the
2274 * allowed limit for which we have journal credit
2275 * reserved. So limit the new bh->b_size
2277 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2278 mpd->inode->i_blkbits;
2279 /* we will do mpage_da_submit_io in the next loop */
2283 * First block in the extent
2285 if (mpd->b_size == 0) {
2286 mpd->b_blocknr = logical;
2287 mpd->b_size = b_size;
2288 mpd->b_state = b_state & BH_FLAGS;
2292 next = mpd->b_blocknr + nrblocks;
2294 * Can we merge the block to our big extent?
2296 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
2297 mpd->b_size += b_size;
2303 * We couldn't merge the block to our extent, so we
2304 * need to flush current extent and start new one
2306 if (mpage_da_map_blocks(mpd) == 0)
2307 mpage_da_submit_io(mpd);
2312 static int ext4_bh_unmapped_or_delay(handle_t *handle, struct buffer_head *bh)
2315 * unmapped buffer is possible for holes.
2316 * delay buffer is possible with delayed allocation.
2317 * We also need to consider unwritten buffer as unmapped.
2319 return (!buffer_mapped(bh) || buffer_delay(bh) ||
2320 buffer_unwritten(bh)) && buffer_dirty(bh);
2324 * __mpage_da_writepage - finds extent of pages and blocks
2326 * @page: page to consider
2327 * @wbc: not used, we just follow rules
2330 * The function finds extents of pages and scan them for all blocks.
2332 static int __mpage_da_writepage(struct page *page,
2333 struct writeback_control *wbc, void *data)
2335 struct mpage_da_data *mpd = data;
2336 struct inode *inode = mpd->inode;
2337 struct buffer_head *bh, *head;
2342 * Rest of the page in the page_vec
2343 * redirty then and skip then. We will
2344 * try to to write them again after
2345 * starting a new transaction
2347 redirty_page_for_writepage(wbc, page);
2349 return MPAGE_DA_EXTENT_TAIL;
2352 * Can we merge this page to current extent?
2354 if (mpd->next_page != page->index) {
2356 * Nope, we can't. So, we map non-allocated blocks
2357 * and start IO on them using writepage()
2359 if (mpd->next_page != mpd->first_page) {
2360 if (mpage_da_map_blocks(mpd) == 0)
2361 mpage_da_submit_io(mpd);
2363 * skip rest of the page in the page_vec
2366 redirty_page_for_writepage(wbc, page);
2368 return MPAGE_DA_EXTENT_TAIL;
2372 * Start next extent of pages ...
2374 mpd->first_page = page->index;
2384 mpd->next_page = page->index + 1;
2385 logical = (sector_t) page->index <<
2386 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2388 if (!page_has_buffers(page)) {
2389 mpage_add_bh_to_extent(mpd, logical, PAGE_CACHE_SIZE,
2390 (1 << BH_Dirty) | (1 << BH_Uptodate));
2392 return MPAGE_DA_EXTENT_TAIL;
2395 * Page with regular buffer heads, just add all dirty ones
2397 head = page_buffers(page);
2400 BUG_ON(buffer_locked(bh));
2402 * We need to try to allocate
2403 * unmapped blocks in the same page.
2404 * Otherwise we won't make progress
2405 * with the page in ext4_da_writepage
2407 if (ext4_bh_unmapped_or_delay(NULL, bh)) {
2408 mpage_add_bh_to_extent(mpd, logical,
2412 return MPAGE_DA_EXTENT_TAIL;
2413 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2415 * mapped dirty buffer. We need to update
2416 * the b_state because we look at
2417 * b_state in mpage_da_map_blocks. We don't
2418 * update b_size because if we find an
2419 * unmapped buffer_head later we need to
2420 * use the b_state flag of that buffer_head.
2422 if (mpd->b_size == 0)
2423 mpd->b_state = bh->b_state & BH_FLAGS;
2426 } while ((bh = bh->b_this_page) != head);
2433 * This is a special get_blocks_t callback which is used by
2434 * ext4_da_write_begin(). It will either return mapped block or
2435 * reserve space for a single block.
2437 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2438 * We also have b_blocknr = -1 and b_bdev initialized properly
2440 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2441 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2442 * initialized properly.
2444 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2445 struct buffer_head *bh_result, int create)
2448 sector_t invalid_block = ~((sector_t) 0xffff);
2450 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2453 BUG_ON(create == 0);
2454 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2457 * first, we need to know whether the block is allocated already
2458 * preallocated blocks are unmapped but should treated
2459 * the same as allocated blocks.
2461 ret = ext4_get_blocks(NULL, inode, iblock, 1, bh_result, 0);
2462 if ((ret == 0) && !buffer_delay(bh_result)) {
2463 /* the block isn't (pre)allocated yet, let's reserve space */
2465 * XXX: __block_prepare_write() unmaps passed block,
2468 ret = ext4_da_reserve_space(inode, 1);
2470 /* not enough space to reserve */
2473 map_bh(bh_result, inode->i_sb, invalid_block);
2474 set_buffer_new(bh_result);
2475 set_buffer_delay(bh_result);
2476 } else if (ret > 0) {
2477 bh_result->b_size = (ret << inode->i_blkbits);
2478 if (buffer_unwritten(bh_result)) {
2479 /* A delayed write to unwritten bh should
2480 * be marked new and mapped. Mapped ensures
2481 * that we don't do get_block multiple times
2482 * when we write to the same offset and new
2483 * ensures that we do proper zero out for
2486 set_buffer_new(bh_result);
2487 set_buffer_mapped(bh_result);
2496 * This function is used as a standard get_block_t calback function
2497 * when there is no desire to allocate any blocks. It is used as a
2498 * callback function for block_prepare_write(), nobh_writepage(), and
2499 * block_write_full_page(). These functions should only try to map a
2500 * single block at a time.
2502 * Since this function doesn't do block allocations even if the caller
2503 * requests it by passing in create=1, it is critically important that
2504 * any caller checks to make sure that any buffer heads are returned
2505 * by this function are either all already mapped or marked for
2506 * delayed allocation before calling nobh_writepage() or
2507 * block_write_full_page(). Otherwise, b_blocknr could be left
2508 * unitialized, and the page write functions will be taken by
2511 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
2512 struct buffer_head *bh_result, int create)
2515 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2517 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2520 * we don't want to do block allocation in writepage
2521 * so call get_block_wrap with create = 0
2523 ret = ext4_get_blocks(NULL, inode, iblock, max_blocks, bh_result, 0);
2524 BUG_ON(create && ret == 0);
2526 bh_result->b_size = (ret << inode->i_blkbits);
2533 * This function can get called via...
2534 * - ext4_da_writepages after taking page lock (have journal handle)
2535 * - journal_submit_inode_data_buffers (no journal handle)
2536 * - shrink_page_list via pdflush (no journal handle)
2537 * - grab_page_cache when doing write_begin (have journal handle)
2539 static int ext4_da_writepage(struct page *page,
2540 struct writeback_control *wbc)
2545 struct buffer_head *page_bufs;
2546 struct inode *inode = page->mapping->host;
2548 trace_ext4_da_writepage(inode, page);
2549 size = i_size_read(inode);
2550 if (page->index == size >> PAGE_CACHE_SHIFT)
2551 len = size & ~PAGE_CACHE_MASK;
2553 len = PAGE_CACHE_SIZE;
2555 if (page_has_buffers(page)) {
2556 page_bufs = page_buffers(page);
2557 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2558 ext4_bh_unmapped_or_delay)) {
2560 * We don't want to do block allocation
2561 * So redirty the page and return
2562 * We may reach here when we do a journal commit
2563 * via journal_submit_inode_data_buffers.
2564 * If we don't have mapping block we just ignore
2565 * them. We can also reach here via shrink_page_list
2567 redirty_page_for_writepage(wbc, page);
2573 * The test for page_has_buffers() is subtle:
2574 * We know the page is dirty but it lost buffers. That means
2575 * that at some moment in time after write_begin()/write_end()
2576 * has been called all buffers have been clean and thus they
2577 * must have been written at least once. So they are all
2578 * mapped and we can happily proceed with mapping them
2579 * and writing the page.
2581 * Try to initialize the buffer_heads and check whether
2582 * all are mapped and non delay. We don't want to
2583 * do block allocation here.
2585 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
2586 noalloc_get_block_write);
2588 page_bufs = page_buffers(page);
2589 /* check whether all are mapped and non delay */
2590 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2591 ext4_bh_unmapped_or_delay)) {
2592 redirty_page_for_writepage(wbc, page);
2598 * We can't do block allocation here
2599 * so just redity the page and unlock
2602 redirty_page_for_writepage(wbc, page);
2606 /* now mark the buffer_heads as dirty and uptodate */
2607 block_commit_write(page, 0, PAGE_CACHE_SIZE);
2610 if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
2611 ret = nobh_writepage(page, noalloc_get_block_write, wbc);
2613 ret = block_write_full_page(page, noalloc_get_block_write,
2620 * This is called via ext4_da_writepages() to
2621 * calulate the total number of credits to reserve to fit
2622 * a single extent allocation into a single transaction,
2623 * ext4_da_writpeages() will loop calling this before
2624 * the block allocation.
2627 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2629 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2632 * With non-extent format the journal credit needed to
2633 * insert nrblocks contiguous block is dependent on
2634 * number of contiguous block. So we will limit
2635 * number of contiguous block to a sane value
2637 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
2638 (max_blocks > EXT4_MAX_TRANS_DATA))
2639 max_blocks = EXT4_MAX_TRANS_DATA;
2641 return ext4_chunk_trans_blocks(inode, max_blocks);
2644 static int ext4_da_writepages(struct address_space *mapping,
2645 struct writeback_control *wbc)
2648 int range_whole = 0;
2649 handle_t *handle = NULL;
2650 struct mpage_da_data mpd;
2651 struct inode *inode = mapping->host;
2652 int no_nrwrite_index_update;
2653 int pages_written = 0;
2655 int range_cyclic, cycled = 1, io_done = 0;
2656 int needed_blocks, ret = 0, nr_to_writebump = 0;
2657 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2659 trace_ext4_da_writepages(inode, wbc);
2662 * No pages to write? This is mainly a kludge to avoid starting
2663 * a transaction for special inodes like journal inode on last iput()
2664 * because that could violate lock ordering on umount
2666 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2670 * If the filesystem has aborted, it is read-only, so return
2671 * right away instead of dumping stack traces later on that
2672 * will obscure the real source of the problem. We test
2673 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2674 * the latter could be true if the filesystem is mounted
2675 * read-only, and in that case, ext4_da_writepages should
2676 * *never* be called, so if that ever happens, we would want
2679 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2683 * Make sure nr_to_write is >= sbi->s_mb_stream_request
2684 * This make sure small files blocks are allocated in
2685 * single attempt. This ensure that small files
2686 * get less fragmented.
2688 if (wbc->nr_to_write < sbi->s_mb_stream_request) {
2689 nr_to_writebump = sbi->s_mb_stream_request - wbc->nr_to_write;
2690 wbc->nr_to_write = sbi->s_mb_stream_request;
2692 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2695 range_cyclic = wbc->range_cyclic;
2696 if (wbc->range_cyclic) {
2697 index = mapping->writeback_index;
2700 wbc->range_start = index << PAGE_CACHE_SHIFT;
2701 wbc->range_end = LLONG_MAX;
2702 wbc->range_cyclic = 0;
2704 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2707 mpd.inode = mapping->host;
2710 * we don't want write_cache_pages to update
2711 * nr_to_write and writeback_index
2713 no_nrwrite_index_update = wbc->no_nrwrite_index_update;
2714 wbc->no_nrwrite_index_update = 1;
2715 pages_skipped = wbc->pages_skipped;
2718 while (!ret && wbc->nr_to_write > 0) {
2721 * we insert one extent at a time. So we need
2722 * credit needed for single extent allocation.
2723 * journalled mode is currently not supported
2726 BUG_ON(ext4_should_journal_data(inode));
2727 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2729 /* start a new transaction*/
2730 handle = ext4_journal_start(inode, needed_blocks);
2731 if (IS_ERR(handle)) {
2732 ret = PTR_ERR(handle);
2733 printk(KERN_CRIT "%s: jbd2_start: "
2734 "%ld pages, ino %lu; err %d\n", __func__,
2735 wbc->nr_to_write, inode->i_ino, ret);
2737 goto out_writepages;
2741 * Now call __mpage_da_writepage to find the next
2742 * contiguous region of logical blocks that need
2743 * blocks to be allocated by ext4. We don't actually
2744 * submit the blocks for I/O here, even though
2745 * write_cache_pages thinks it will, and will set the
2746 * pages as clean for write before calling
2747 * __mpage_da_writepage().
2755 mpd.pages_written = 0;
2757 ret = write_cache_pages(mapping, wbc, __mpage_da_writepage,
2760 * If we have a contigous extent of pages and we
2761 * haven't done the I/O yet, map the blocks and submit
2764 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2765 if (mpage_da_map_blocks(&mpd) == 0)
2766 mpage_da_submit_io(&mpd);
2768 ret = MPAGE_DA_EXTENT_TAIL;
2770 wbc->nr_to_write -= mpd.pages_written;
2772 ext4_journal_stop(handle);
2774 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2775 /* commit the transaction which would
2776 * free blocks released in the transaction
2779 jbd2_journal_force_commit_nested(sbi->s_journal);
2780 wbc->pages_skipped = pages_skipped;
2782 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2784 * got one extent now try with
2787 pages_written += mpd.pages_written;
2788 wbc->pages_skipped = pages_skipped;
2791 } else if (wbc->nr_to_write)
2793 * There is no more writeout needed
2794 * or we requested for a noblocking writeout
2795 * and we found the device congested
2799 if (!io_done && !cycled) {
2802 wbc->range_start = index << PAGE_CACHE_SHIFT;
2803 wbc->range_end = mapping->writeback_index - 1;
2806 if (pages_skipped != wbc->pages_skipped)
2807 printk(KERN_EMERG "This should not happen leaving %s "
2808 "with nr_to_write = %ld ret = %d\n",
2809 __func__, wbc->nr_to_write, ret);
2812 index += pages_written;
2813 wbc->range_cyclic = range_cyclic;
2814 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2816 * set the writeback_index so that range_cyclic
2817 * mode will write it back later
2819 mapping->writeback_index = index;
2822 if (!no_nrwrite_index_update)
2823 wbc->no_nrwrite_index_update = 0;
2824 wbc->nr_to_write -= nr_to_writebump;
2825 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2829 #define FALL_BACK_TO_NONDELALLOC 1
2830 static int ext4_nonda_switch(struct super_block *sb)
2832 s64 free_blocks, dirty_blocks;
2833 struct ext4_sb_info *sbi = EXT4_SB(sb);
2836 * switch to non delalloc mode if we are running low
2837 * on free block. The free block accounting via percpu
2838 * counters can get slightly wrong with percpu_counter_batch getting
2839 * accumulated on each CPU without updating global counters
2840 * Delalloc need an accurate free block accounting. So switch
2841 * to non delalloc when we are near to error range.
2843 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
2844 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
2845 if (2 * free_blocks < 3 * dirty_blocks ||
2846 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
2848 * free block count is less that 150% of dirty blocks
2849 * or free blocks is less that watermark
2856 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2857 loff_t pos, unsigned len, unsigned flags,
2858 struct page **pagep, void **fsdata)
2860 int ret, retries = 0;
2864 struct inode *inode = mapping->host;
2867 index = pos >> PAGE_CACHE_SHIFT;
2868 from = pos & (PAGE_CACHE_SIZE - 1);
2871 if (ext4_nonda_switch(inode->i_sb)) {
2872 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2873 return ext4_write_begin(file, mapping, pos,
2874 len, flags, pagep, fsdata);
2876 *fsdata = (void *)0;
2877 trace_ext4_da_write_begin(inode, pos, len, flags);
2880 * With delayed allocation, we don't log the i_disksize update
2881 * if there is delayed block allocation. But we still need
2882 * to journalling the i_disksize update if writes to the end
2883 * of file which has an already mapped buffer.
2885 handle = ext4_journal_start(inode, 1);
2886 if (IS_ERR(handle)) {
2887 ret = PTR_ERR(handle);
2890 /* We cannot recurse into the filesystem as the transaction is already
2892 flags |= AOP_FLAG_NOFS;
2894 page = grab_cache_page_write_begin(mapping, index, flags);
2896 ext4_journal_stop(handle);
2902 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
2903 ext4_da_get_block_prep);
2906 ext4_journal_stop(handle);
2907 page_cache_release(page);
2909 * block_write_begin may have instantiated a few blocks
2910 * outside i_size. Trim these off again. Don't need
2911 * i_size_read because we hold i_mutex.
2913 if (pos + len > inode->i_size)
2914 vmtruncate(inode, inode->i_size);
2917 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2924 * Check if we should update i_disksize
2925 * when write to the end of file but not require block allocation
2927 static int ext4_da_should_update_i_disksize(struct page *page,
2928 unsigned long offset)
2930 struct buffer_head *bh;
2931 struct inode *inode = page->mapping->host;
2935 bh = page_buffers(page);
2936 idx = offset >> inode->i_blkbits;
2938 for (i = 0; i < idx; i++)
2939 bh = bh->b_this_page;
2941 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2946 static int ext4_da_write_end(struct file *file,
2947 struct address_space *mapping,
2948 loff_t pos, unsigned len, unsigned copied,
2949 struct page *page, void *fsdata)
2951 struct inode *inode = mapping->host;
2953 handle_t *handle = ext4_journal_current_handle();
2955 unsigned long start, end;
2956 int write_mode = (int)(unsigned long)fsdata;
2958 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2959 if (ext4_should_order_data(inode)) {
2960 return ext4_ordered_write_end(file, mapping, pos,
2961 len, copied, page, fsdata);
2962 } else if (ext4_should_writeback_data(inode)) {
2963 return ext4_writeback_write_end(file, mapping, pos,
2964 len, copied, page, fsdata);
2970 trace_ext4_da_write_end(inode, pos, len, copied);
2971 start = pos & (PAGE_CACHE_SIZE - 1);
2972 end = start + copied - 1;
2975 * generic_write_end() will run mark_inode_dirty() if i_size
2976 * changes. So let's piggyback the i_disksize mark_inode_dirty
2980 new_i_size = pos + copied;
2981 if (new_i_size > EXT4_I(inode)->i_disksize) {
2982 if (ext4_da_should_update_i_disksize(page, end)) {
2983 down_write(&EXT4_I(inode)->i_data_sem);
2984 if (new_i_size > EXT4_I(inode)->i_disksize) {
2986 * Updating i_disksize when extending file
2987 * without needing block allocation
2989 if (ext4_should_order_data(inode))
2990 ret = ext4_jbd2_file_inode(handle,
2993 EXT4_I(inode)->i_disksize = new_i_size;
2995 up_write(&EXT4_I(inode)->i_data_sem);
2996 /* We need to mark inode dirty even if
2997 * new_i_size is less that inode->i_size
2998 * bu greater than i_disksize.(hint delalloc)
3000 ext4_mark_inode_dirty(handle, inode);
3003 ret2 = generic_write_end(file, mapping, pos, len, copied,
3008 ret2 = ext4_journal_stop(handle);
3012 return ret ? ret : copied;
3015 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
3018 * Drop reserved blocks
3020 BUG_ON(!PageLocked(page));
3021 if (!page_has_buffers(page))
3024 ext4_da_page_release_reservation(page, offset);
3027 ext4_invalidatepage(page, offset);
3033 * Force all delayed allocation blocks to be allocated for a given inode.
3035 int ext4_alloc_da_blocks(struct inode *inode)
3037 if (!EXT4_I(inode)->i_reserved_data_blocks &&
3038 !EXT4_I(inode)->i_reserved_meta_blocks)
3042 * We do something simple for now. The filemap_flush() will
3043 * also start triggering a write of the data blocks, which is
3044 * not strictly speaking necessary (and for users of
3045 * laptop_mode, not even desirable). However, to do otherwise
3046 * would require replicating code paths in:
3048 * ext4_da_writepages() ->
3049 * write_cache_pages() ---> (via passed in callback function)
3050 * __mpage_da_writepage() -->
3051 * mpage_add_bh_to_extent()
3052 * mpage_da_map_blocks()
3054 * The problem is that write_cache_pages(), located in
3055 * mm/page-writeback.c, marks pages clean in preparation for
3056 * doing I/O, which is not desirable if we're not planning on
3059 * We could call write_cache_pages(), and then redirty all of
3060 * the pages by calling redirty_page_for_writeback() but that
3061 * would be ugly in the extreme. So instead we would need to
3062 * replicate parts of the code in the above functions,
3063 * simplifying them becuase we wouldn't actually intend to
3064 * write out the pages, but rather only collect contiguous
3065 * logical block extents, call the multi-block allocator, and
3066 * then update the buffer heads with the block allocations.
3068 * For now, though, we'll cheat by calling filemap_flush(),
3069 * which will map the blocks, and start the I/O, but not
3070 * actually wait for the I/O to complete.
3072 return filemap_flush(inode->i_mapping);
3076 * bmap() is special. It gets used by applications such as lilo and by
3077 * the swapper to find the on-disk block of a specific piece of data.
3079 * Naturally, this is dangerous if the block concerned is still in the
3080 * journal. If somebody makes a swapfile on an ext4 data-journaling
3081 * filesystem and enables swap, then they may get a nasty shock when the
3082 * data getting swapped to that swapfile suddenly gets overwritten by
3083 * the original zero's written out previously to the journal and
3084 * awaiting writeback in the kernel's buffer cache.
3086 * So, if we see any bmap calls here on a modified, data-journaled file,
3087 * take extra steps to flush any blocks which might be in the cache.
3089 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3091 struct inode *inode = mapping->host;
3095 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3096 test_opt(inode->i_sb, DELALLOC)) {
3098 * With delalloc we want to sync the file
3099 * so that we can make sure we allocate
3102 filemap_write_and_wait(mapping);
3105 if (EXT4_JOURNAL(inode) && EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
3107 * This is a REALLY heavyweight approach, but the use of
3108 * bmap on dirty files is expected to be extremely rare:
3109 * only if we run lilo or swapon on a freshly made file
3110 * do we expect this to happen.
3112 * (bmap requires CAP_SYS_RAWIO so this does not
3113 * represent an unprivileged user DOS attack --- we'd be
3114 * in trouble if mortal users could trigger this path at
3117 * NB. EXT4_STATE_JDATA is not set on files other than
3118 * regular files. If somebody wants to bmap a directory
3119 * or symlink and gets confused because the buffer
3120 * hasn't yet been flushed to disk, they deserve
3121 * everything they get.
3124 EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
3125 journal = EXT4_JOURNAL(inode);
3126 jbd2_journal_lock_updates(journal);
3127 err = jbd2_journal_flush(journal);
3128 jbd2_journal_unlock_updates(journal);
3134 return generic_block_bmap(mapping, block, ext4_get_block);
3137 static int bget_one(handle_t *handle, struct buffer_head *bh)
3143 static int bput_one(handle_t *handle, struct buffer_head *bh)
3150 * Note that we don't need to start a transaction unless we're journaling data
3151 * because we should have holes filled from ext4_page_mkwrite(). We even don't
3152 * need to file the inode to the transaction's list in ordered mode because if
3153 * we are writing back data added by write(), the inode is already there and if
3154 * we are writing back data modified via mmap(), noone guarantees in which
3155 * transaction the data will hit the disk. In case we are journaling data, we
3156 * cannot start transaction directly because transaction start ranks above page
3157 * lock so we have to do some magic.
3159 * In all journaling modes block_write_full_page() will start the I/O.
3163 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
3168 * ext4_file_write() -> generic_file_write() -> __alloc_pages() -> ...
3170 * Same applies to ext4_get_block(). We will deadlock on various things like
3171 * lock_journal and i_data_sem
3173 * Setting PF_MEMALLOC here doesn't work - too many internal memory
3176 * 16May01: If we're reentered then journal_current_handle() will be
3177 * non-zero. We simply *return*.
3179 * 1 July 2001: @@@ FIXME:
3180 * In journalled data mode, a data buffer may be metadata against the
3181 * current transaction. But the same file is part of a shared mapping
3182 * and someone does a writepage() on it.
3184 * We will move the buffer onto the async_data list, but *after* it has
3185 * been dirtied. So there's a small window where we have dirty data on
3188 * Note that this only applies to the last partial page in the file. The
3189 * bit which block_write_full_page() uses prepare/commit for. (That's
3190 * broken code anyway: it's wrong for msync()).
3192 * It's a rare case: affects the final partial page, for journalled data
3193 * where the file is subject to bith write() and writepage() in the same
3194 * transction. To fix it we'll need a custom block_write_full_page().
3195 * We'll probably need that anyway for journalling writepage() output.
3197 * We don't honour synchronous mounts for writepage(). That would be
3198 * disastrous. Any write() or metadata operation will sync the fs for
3202 static int __ext4_normal_writepage(struct page *page,
3203 struct writeback_control *wbc)
3205 struct inode *inode = page->mapping->host;
3207 if (test_opt(inode->i_sb, NOBH))
3208 return nobh_writepage(page, noalloc_get_block_write, wbc);
3210 return block_write_full_page(page, noalloc_get_block_write,
3214 static int ext4_normal_writepage(struct page *page,
3215 struct writeback_control *wbc)
3217 struct inode *inode = page->mapping->host;
3218 loff_t size = i_size_read(inode);
3221 trace_ext4_normal_writepage(inode, page);
3222 J_ASSERT(PageLocked(page));
3223 if (page->index == size >> PAGE_CACHE_SHIFT)
3224 len = size & ~PAGE_CACHE_MASK;
3226 len = PAGE_CACHE_SIZE;
3228 if (page_has_buffers(page)) {
3229 /* if page has buffers it should all be mapped
3230 * and allocated. If there are not buffers attached
3231 * to the page we know the page is dirty but it lost
3232 * buffers. That means that at some moment in time
3233 * after write_begin() / write_end() has been called
3234 * all buffers have been clean and thus they must have been
3235 * written at least once. So they are all mapped and we can
3236 * happily proceed with mapping them and writing the page.
3238 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
3239 ext4_bh_unmapped_or_delay));
3242 if (!ext4_journal_current_handle())
3243 return __ext4_normal_writepage(page, wbc);
3245 redirty_page_for_writepage(wbc, page);
3250 static int __ext4_journalled_writepage(struct page *page,
3251 struct writeback_control *wbc)
3253 struct address_space *mapping = page->mapping;
3254 struct inode *inode = mapping->host;
3255 struct buffer_head *page_bufs;
3256 handle_t *handle = NULL;
3260 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
3261 noalloc_get_block_write);
3265 page_bufs = page_buffers(page);
3266 walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE, NULL,
3268 /* As soon as we unlock the page, it can go away, but we have
3269 * references to buffers so we are safe */
3272 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
3273 if (IS_ERR(handle)) {
3274 ret = PTR_ERR(handle);
3278 ret = walk_page_buffers(handle, page_bufs, 0,
3279 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
3281 err = walk_page_buffers(handle, page_bufs, 0,
3282 PAGE_CACHE_SIZE, NULL, write_end_fn);
3285 err = ext4_journal_stop(handle);
3289 walk_page_buffers(handle, page_bufs, 0,
3290 PAGE_CACHE_SIZE, NULL, bput_one);
3291 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
3300 static int ext4_journalled_writepage(struct page *page,
3301 struct writeback_control *wbc)
3303 struct inode *inode = page->mapping->host;
3304 loff_t size = i_size_read(inode);
3307 trace_ext4_journalled_writepage(inode, page);
3308 J_ASSERT(PageLocked(page));
3309 if (page->index == size >> PAGE_CACHE_SHIFT)
3310 len = size & ~PAGE_CACHE_MASK;
3312 len = PAGE_CACHE_SIZE;
3314 if (page_has_buffers(page)) {
3315 /* if page has buffers it should all be mapped
3316 * and allocated. If there are not buffers attached
3317 * to the page we know the page is dirty but it lost
3318 * buffers. That means that at some moment in time
3319 * after write_begin() / write_end() has been called
3320 * all buffers have been clean and thus they must have been
3321 * written at least once. So they are all mapped and we can
3322 * happily proceed with mapping them and writing the page.
3324 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
3325 ext4_bh_unmapped_or_delay));
3328 if (ext4_journal_current_handle())
3331 if (PageChecked(page)) {
3333 * It's mmapped pagecache. Add buffers and journal it. There
3334 * doesn't seem much point in redirtying the page here.
3336 ClearPageChecked(page);
3337 return __ext4_journalled_writepage(page, wbc);
3340 * It may be a page full of checkpoint-mode buffers. We don't
3341 * really know unless we go poke around in the buffer_heads.
3342 * But block_write_full_page will do the right thing.
3344 return block_write_full_page(page, noalloc_get_block_write,
3348 redirty_page_for_writepage(wbc, page);
3353 static int ext4_readpage(struct file *file, struct page *page)
3355 return mpage_readpage(page, ext4_get_block);
3359 ext4_readpages(struct file *file, struct address_space *mapping,
3360 struct list_head *pages, unsigned nr_pages)
3362 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3365 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3367 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3370 * If it's a full truncate we just forget about the pending dirtying
3373 ClearPageChecked(page);
3376 jbd2_journal_invalidatepage(journal, page, offset);
3378 block_invalidatepage(page, offset);
3381 static int ext4_releasepage(struct page *page, gfp_t wait)
3383 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3385 WARN_ON(PageChecked(page));
3386 if (!page_has_buffers(page))
3389 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3391 return try_to_free_buffers(page);
3395 * If the O_DIRECT write will extend the file then add this inode to the
3396 * orphan list. So recovery will truncate it back to the original size
3397 * if the machine crashes during the write.
3399 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3400 * crashes then stale disk data _may_ be exposed inside the file. But current
3401 * VFS code falls back into buffered path in that case so we are safe.
3403 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3404 const struct iovec *iov, loff_t offset,
3405 unsigned long nr_segs)
3407 struct file *file = iocb->ki_filp;
3408 struct inode *inode = file->f_mapping->host;
3409 struct ext4_inode_info *ei = EXT4_I(inode);
3413 size_t count = iov_length(iov, nr_segs);
3416 loff_t final_size = offset + count;
3418 if (final_size > inode->i_size) {
3419 /* Credits for sb + inode write */
3420 handle = ext4_journal_start(inode, 2);
3421 if (IS_ERR(handle)) {
3422 ret = PTR_ERR(handle);
3425 ret = ext4_orphan_add(handle, inode);
3427 ext4_journal_stop(handle);
3431 ei->i_disksize = inode->i_size;
3432 ext4_journal_stop(handle);
3436 ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
3438 ext4_get_block, NULL);
3443 /* Credits for sb + inode write */
3444 handle = ext4_journal_start(inode, 2);
3445 if (IS_ERR(handle)) {
3446 /* This is really bad luck. We've written the data
3447 * but cannot extend i_size. Bail out and pretend
3448 * the write failed... */
3449 ret = PTR_ERR(handle);
3453 ext4_orphan_del(handle, inode);
3455 loff_t end = offset + ret;
3456 if (end > inode->i_size) {
3457 ei->i_disksize = end;
3458 i_size_write(inode, end);
3460 * We're going to return a positive `ret'
3461 * here due to non-zero-length I/O, so there's
3462 * no way of reporting error returns from
3463 * ext4_mark_inode_dirty() to userspace. So
3466 ext4_mark_inode_dirty(handle, inode);
3469 err = ext4_journal_stop(handle);
3478 * Pages can be marked dirty completely asynchronously from ext4's journalling
3479 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3480 * much here because ->set_page_dirty is called under VFS locks. The page is
3481 * not necessarily locked.
3483 * We cannot just dirty the page and leave attached buffers clean, because the
3484 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3485 * or jbddirty because all the journalling code will explode.
3487 * So what we do is to mark the page "pending dirty" and next time writepage
3488 * is called, propagate that into the buffers appropriately.
3490 static int ext4_journalled_set_page_dirty(struct page *page)
3492 SetPageChecked(page);
3493 return __set_page_dirty_nobuffers(page);
3496 static const struct address_space_operations ext4_ordered_aops = {
3497 .readpage = ext4_readpage,
3498 .readpages = ext4_readpages,
3499 .writepage = ext4_normal_writepage,
3500 .sync_page = block_sync_page,
3501 .write_begin = ext4_write_begin,
3502 .write_end = ext4_ordered_write_end,
3504 .invalidatepage = ext4_invalidatepage,
3505 .releasepage = ext4_releasepage,
3506 .direct_IO = ext4_direct_IO,
3507 .migratepage = buffer_migrate_page,
3508 .is_partially_uptodate = block_is_partially_uptodate,
3511 static const struct address_space_operations ext4_writeback_aops = {
3512 .readpage = ext4_readpage,
3513 .readpages = ext4_readpages,
3514 .writepage = ext4_normal_writepage,
3515 .sync_page = block_sync_page,
3516 .write_begin = ext4_write_begin,
3517 .write_end = ext4_writeback_write_end,
3519 .invalidatepage = ext4_invalidatepage,
3520 .releasepage = ext4_releasepage,
3521 .direct_IO = ext4_direct_IO,
3522 .migratepage = buffer_migrate_page,
3523 .is_partially_uptodate = block_is_partially_uptodate,
3526 static const struct address_space_operations ext4_journalled_aops = {
3527 .readpage = ext4_readpage,
3528 .readpages = ext4_readpages,
3529 .writepage = ext4_journalled_writepage,
3530 .sync_page = block_sync_page,
3531 .write_begin = ext4_write_begin,
3532 .write_end = ext4_journalled_write_end,
3533 .set_page_dirty = ext4_journalled_set_page_dirty,
3535 .invalidatepage = ext4_invalidatepage,
3536 .releasepage = ext4_releasepage,
3537 .is_partially_uptodate = block_is_partially_uptodate,
3540 static const struct address_space_operations ext4_da_aops = {
3541 .readpage = ext4_readpage,
3542 .readpages = ext4_readpages,
3543 .writepage = ext4_da_writepage,
3544 .writepages = ext4_da_writepages,
3545 .sync_page = block_sync_page,
3546 .write_begin = ext4_da_write_begin,
3547 .write_end = ext4_da_write_end,
3549 .invalidatepage = ext4_da_invalidatepage,
3550 .releasepage = ext4_releasepage,
3551 .direct_IO = ext4_direct_IO,
3552 .migratepage = buffer_migrate_page,
3553 .is_partially_uptodate = block_is_partially_uptodate,
3556 void ext4_set_aops(struct inode *inode)
3558 if (ext4_should_order_data(inode) &&
3559 test_opt(inode->i_sb, DELALLOC))
3560 inode->i_mapping->a_ops = &ext4_da_aops;
3561 else if (ext4_should_order_data(inode))
3562 inode->i_mapping->a_ops = &ext4_ordered_aops;
3563 else if (ext4_should_writeback_data(inode) &&
3564 test_opt(inode->i_sb, DELALLOC))
3565 inode->i_mapping->a_ops = &ext4_da_aops;
3566 else if (ext4_should_writeback_data(inode))
3567 inode->i_mapping->a_ops = &ext4_writeback_aops;
3569 inode->i_mapping->a_ops = &ext4_journalled_aops;
3573 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3574 * up to the end of the block which corresponds to `from'.
3575 * This required during truncate. We need to physically zero the tail end
3576 * of that block so it doesn't yield old data if the file is later grown.
3578 int ext4_block_truncate_page(handle_t *handle,
3579 struct address_space *mapping, loff_t from)
3581 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3582 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3583 unsigned blocksize, length, pos;
3585 struct inode *inode = mapping->host;
3586 struct buffer_head *bh;
3590 page = grab_cache_page(mapping, from >> PAGE_CACHE_SHIFT);
3594 blocksize = inode->i_sb->s_blocksize;
3595 length = blocksize - (offset & (blocksize - 1));
3596 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3599 * For "nobh" option, we can only work if we don't need to
3600 * read-in the page - otherwise we create buffers to do the IO.
3602 if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
3603 ext4_should_writeback_data(inode) && PageUptodate(page)) {
3604 zero_user(page, offset, length);
3605 set_page_dirty(page);
3609 if (!page_has_buffers(page))
3610 create_empty_buffers(page, blocksize, 0);
3612 /* Find the buffer that contains "offset" */
3613 bh = page_buffers(page);
3615 while (offset >= pos) {
3616 bh = bh->b_this_page;
3622 if (buffer_freed(bh)) {
3623 BUFFER_TRACE(bh, "freed: skip");
3627 if (!buffer_mapped(bh)) {
3628 BUFFER_TRACE(bh, "unmapped");
3629 ext4_get_block(inode, iblock, bh, 0);
3630 /* unmapped? It's a hole - nothing to do */
3631 if (!buffer_mapped(bh)) {
3632 BUFFER_TRACE(bh, "still unmapped");
3637 /* Ok, it's mapped. Make sure it's up-to-date */
3638 if (PageUptodate(page))
3639 set_buffer_uptodate(bh);
3641 if (!buffer_uptodate(bh)) {
3643 ll_rw_block(READ, 1, &bh);
3645 /* Uhhuh. Read error. Complain and punt. */
3646 if (!buffer_uptodate(bh))
3650 if (ext4_should_journal_data(inode)) {
3651 BUFFER_TRACE(bh, "get write access");
3652 err = ext4_journal_get_write_access(handle, bh);
3657 zero_user(page, offset, length);
3659 BUFFER_TRACE(bh, "zeroed end of block");
3662 if (ext4_should_journal_data(inode)) {
3663 err = ext4_handle_dirty_metadata(handle, inode, bh);
3665 if (ext4_should_order_data(inode))
3666 err = ext4_jbd2_file_inode(handle, inode);
3667 mark_buffer_dirty(bh);
3672 page_cache_release(page);
3677 * Probably it should be a library function... search for first non-zero word
3678 * or memcmp with zero_page, whatever is better for particular architecture.
3681 static inline int all_zeroes(__le32 *p, __le32 *q)
3690 * ext4_find_shared - find the indirect blocks for partial truncation.
3691 * @inode: inode in question
3692 * @depth: depth of the affected branch
3693 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
3694 * @chain: place to store the pointers to partial indirect blocks
3695 * @top: place to the (detached) top of branch
3697 * This is a helper function used by ext4_truncate().
3699 * When we do truncate() we may have to clean the ends of several
3700 * indirect blocks but leave the blocks themselves alive. Block is
3701 * partially truncated if some data below the new i_size is refered
3702 * from it (and it is on the path to the first completely truncated
3703 * data block, indeed). We have to free the top of that path along
3704 * with everything to the right of the path. Since no allocation
3705 * past the truncation point is possible until ext4_truncate()
3706 * finishes, we may safely do the latter, but top of branch may
3707 * require special attention - pageout below the truncation point
3708 * might try to populate it.
3710 * We atomically detach the top of branch from the tree, store the
3711 * block number of its root in *@top, pointers to buffer_heads of
3712 * partially truncated blocks - in @chain[].bh and pointers to
3713 * their last elements that should not be removed - in
3714 * @chain[].p. Return value is the pointer to last filled element
3717 * The work left to caller to do the actual freeing of subtrees:
3718 * a) free the subtree starting from *@top
3719 * b) free the subtrees whose roots are stored in
3720 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
3721 * c) free the subtrees growing from the inode past the @chain[0].
3722 * (no partially truncated stuff there). */
3724 static Indirect *ext4_find_shared(struct inode *inode, int depth,
3725 ext4_lblk_t offsets[4], Indirect chain[4],
3728 Indirect *partial, *p;
3732 /* Make k index the deepest non-null offest + 1 */
3733 for (k = depth; k > 1 && !offsets[k-1]; k--)
3735 partial = ext4_get_branch(inode, k, offsets, chain, &err);
3736 /* Writer: pointers */
3738 partial = chain + k-1;
3740 * If the branch acquired continuation since we've looked at it -
3741 * fine, it should all survive and (new) top doesn't belong to us.
3743 if (!partial->key && *partial->p)
3746 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
3749 * OK, we've found the last block that must survive. The rest of our
3750 * branch should be detached before unlocking. However, if that rest
3751 * of branch is all ours and does not grow immediately from the inode
3752 * it's easier to cheat and just decrement partial->p.
3754 if (p == chain + k - 1 && p > chain) {
3758 /* Nope, don't do this in ext4. Must leave the tree intact */
3765 while (partial > p) {
3766 brelse(partial->bh);
3774 * Zero a number of block pointers in either an inode or an indirect block.
3775 * If we restart the transaction we must again get write access to the
3776 * indirect block for further modification.
3778 * We release `count' blocks on disk, but (last - first) may be greater
3779 * than `count' because there can be holes in there.
3781 static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
3782 struct buffer_head *bh,
3783 ext4_fsblk_t block_to_free,
3784 unsigned long count, __le32 *first,
3788 if (try_to_extend_transaction(handle, inode)) {
3790 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
3791 ext4_handle_dirty_metadata(handle, inode, bh);
3793 ext4_mark_inode_dirty(handle, inode);
3794 ext4_journal_test_restart(handle, inode);
3796 BUFFER_TRACE(bh, "retaking write access");
3797 ext4_journal_get_write_access(handle, bh);
3802 * Any buffers which are on the journal will be in memory. We
3803 * find them on the hash table so jbd2_journal_revoke() will
3804 * run jbd2_journal_forget() on them. We've already detached
3805 * each block from the file, so bforget() in
3806 * jbd2_journal_forget() should be safe.
3808 * AKPM: turn on bforget in jbd2_journal_forget()!!!
3810 for (p = first; p < last; p++) {
3811 u32 nr = le32_to_cpu(*p);
3813 struct buffer_head *tbh;
3816 tbh = sb_find_get_block(inode->i_sb, nr);
3817 ext4_forget(handle, 0, inode, tbh, nr);
3821 ext4_free_blocks(handle, inode, block_to_free, count, 0);
3825 * ext4_free_data - free a list of data blocks
3826 * @handle: handle for this transaction
3827 * @inode: inode we are dealing with
3828 * @this_bh: indirect buffer_head which contains *@first and *@last
3829 * @first: array of block numbers
3830 * @last: points immediately past the end of array
3832 * We are freeing all blocks refered from that array (numbers are stored as
3833 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
3835 * We accumulate contiguous runs of blocks to free. Conveniently, if these
3836 * blocks are contiguous then releasing them at one time will only affect one
3837 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
3838 * actually use a lot of journal space.
3840 * @this_bh will be %NULL if @first and @last point into the inode's direct
3843 static void ext4_free_data(handle_t *handle, struct inode *inode,
3844 struct buffer_head *this_bh,
3845 __le32 *first, __le32 *last)
3847 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
3848 unsigned long count = 0; /* Number of blocks in the run */
3849 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
3852 ext4_fsblk_t nr; /* Current block # */
3853 __le32 *p; /* Pointer into inode/ind
3854 for current block */
3857 if (this_bh) { /* For indirect block */
3858 BUFFER_TRACE(this_bh, "get_write_access");
3859 err = ext4_journal_get_write_access(handle, this_bh);
3860 /* Important: if we can't update the indirect pointers
3861 * to the blocks, we can't free them. */
3866 for (p = first; p < last; p++) {
3867 nr = le32_to_cpu(*p);
3869 /* accumulate blocks to free if they're contiguous */
3872 block_to_free_p = p;
3874 } else if (nr == block_to_free + count) {
3877 ext4_clear_blocks(handle, inode, this_bh,
3879 count, block_to_free_p, p);
3881 block_to_free_p = p;
3888 ext4_clear_blocks(handle, inode, this_bh, block_to_free,
3889 count, block_to_free_p, p);
3892 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
3895 * The buffer head should have an attached journal head at this
3896 * point. However, if the data is corrupted and an indirect
3897 * block pointed to itself, it would have been detached when
3898 * the block was cleared. Check for this instead of OOPSing.
3900 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
3901 ext4_handle_dirty_metadata(handle, inode, this_bh);
3903 ext4_error(inode->i_sb, __func__,
3904 "circular indirect block detected, "
3905 "inode=%lu, block=%llu",
3907 (unsigned long long) this_bh->b_blocknr);
3912 * ext4_free_branches - free an array of branches
3913 * @handle: JBD handle for this transaction
3914 * @inode: inode we are dealing with
3915 * @parent_bh: the buffer_head which contains *@first and *@last
3916 * @first: array of block numbers
3917 * @last: pointer immediately past the end of array
3918 * @depth: depth of the branches to free
3920 * We are freeing all blocks refered from these branches (numbers are
3921 * stored as little-endian 32-bit) and updating @inode->i_blocks
3924 static void ext4_free_branches(handle_t *handle, struct inode *inode,
3925 struct buffer_head *parent_bh,
3926 __le32 *first, __le32 *last, int depth)
3931 if (ext4_handle_is_aborted(handle))
3935 struct buffer_head *bh;
3936 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
3938 while (--p >= first) {
3939 nr = le32_to_cpu(*p);
3941 continue; /* A hole */
3943 /* Go read the buffer for the next level down */
3944 bh = sb_bread(inode->i_sb, nr);
3947 * A read failure? Report error and clear slot
3951 ext4_error(inode->i_sb, "ext4_free_branches",
3952 "Read failure, inode=%lu, block=%llu",
3957 /* This zaps the entire block. Bottom up. */
3958 BUFFER_TRACE(bh, "free child branches");
3959 ext4_free_branches(handle, inode, bh,
3960 (__le32 *) bh->b_data,
3961 (__le32 *) bh->b_data + addr_per_block,
3965 * We've probably journalled the indirect block several
3966 * times during the truncate. But it's no longer
3967 * needed and we now drop it from the transaction via
3968 * jbd2_journal_revoke().
3970 * That's easy if it's exclusively part of this
3971 * transaction. But if it's part of the committing
3972 * transaction then jbd2_journal_forget() will simply
3973 * brelse() it. That means that if the underlying
3974 * block is reallocated in ext4_get_block(),
3975 * unmap_underlying_metadata() will find this block
3976 * and will try to get rid of it. damn, damn.
3978 * If this block has already been committed to the
3979 * journal, a revoke record will be written. And
3980 * revoke records must be emitted *before* clearing
3981 * this block's bit in the bitmaps.
3983 ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
3986 * Everything below this this pointer has been
3987 * released. Now let this top-of-subtree go.
3989 * We want the freeing of this indirect block to be
3990 * atomic in the journal with the updating of the
3991 * bitmap block which owns it. So make some room in
3994 * We zero the parent pointer *after* freeing its
3995 * pointee in the bitmaps, so if extend_transaction()
3996 * for some reason fails to put the bitmap changes and
3997 * the release into the same transaction, recovery
3998 * will merely complain about releasing a free block,
3999 * rather than leaking blocks.
4001 if (ext4_handle_is_aborted(handle))
4003 if (try_to_extend_transaction(handle, inode)) {
4004 ext4_mark_inode_dirty(handle, inode);
4005 ext4_journal_test_restart(handle, inode);
4008 ext4_free_blocks(handle, inode, nr, 1, 1);
4012 * The block which we have just freed is
4013 * pointed to by an indirect block: journal it
4015 BUFFER_TRACE(parent_bh, "get_write_access");
4016 if (!ext4_journal_get_write_access(handle,
4019 BUFFER_TRACE(parent_bh,
4020 "call ext4_handle_dirty_metadata");
4021 ext4_handle_dirty_metadata(handle,
4028 /* We have reached the bottom of the tree. */
4029 BUFFER_TRACE(parent_bh, "free data blocks");
4030 ext4_free_data(handle, inode, parent_bh, first, last);
4034 int ext4_can_truncate(struct inode *inode)
4036 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4038 if (S_ISREG(inode->i_mode))
4040 if (S_ISDIR(inode->i_mode))
4042 if (S_ISLNK(inode->i_mode))
4043 return !ext4_inode_is_fast_symlink(inode);
4050 * We block out ext4_get_block() block instantiations across the entire
4051 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4052 * simultaneously on behalf of the same inode.
4054 * As we work through the truncate and commmit bits of it to the journal there
4055 * is one core, guiding principle: the file's tree must always be consistent on
4056 * disk. We must be able to restart the truncate after a crash.
4058 * The file's tree may be transiently inconsistent in memory (although it
4059 * probably isn't), but whenever we close off and commit a journal transaction,
4060 * the contents of (the filesystem + the journal) must be consistent and
4061 * restartable. It's pretty simple, really: bottom up, right to left (although
4062 * left-to-right works OK too).
4064 * Note that at recovery time, journal replay occurs *before* the restart of
4065 * truncate against the orphan inode list.
4067 * The committed inode has the new, desired i_size (which is the same as
4068 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4069 * that this inode's truncate did not complete and it will again call
4070 * ext4_truncate() to have another go. So there will be instantiated blocks
4071 * to the right of the truncation point in a crashed ext4 filesystem. But
4072 * that's fine - as long as they are linked from the inode, the post-crash
4073 * ext4_truncate() run will find them and release them.
4075 void ext4_truncate(struct inode *inode)
4078 struct ext4_inode_info *ei = EXT4_I(inode);
4079 __le32 *i_data = ei->i_data;
4080 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4081 struct address_space *mapping = inode->i_mapping;
4082 ext4_lblk_t offsets[4];
4087 ext4_lblk_t last_block;
4088 unsigned blocksize = inode->i_sb->s_blocksize;
4090 if (!ext4_can_truncate(inode))
4093 if (ei->i_disksize && inode->i_size == 0 &&
4094 !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4095 ei->i_state |= EXT4_STATE_DA_ALLOC_CLOSE;
4097 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
4098 ext4_ext_truncate(inode);
4102 handle = start_transaction(inode);
4104 return; /* AKPM: return what? */
4106 last_block = (inode->i_size + blocksize-1)
4107 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4109 if (inode->i_size & (blocksize - 1))
4110 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
4113 n = ext4_block_to_path(inode, last_block, offsets, NULL);
4115 goto out_stop; /* error */
4118 * OK. This truncate is going to happen. We add the inode to the
4119 * orphan list, so that if this truncate spans multiple transactions,
4120 * and we crash, we will resume the truncate when the filesystem
4121 * recovers. It also marks the inode dirty, to catch the new size.
4123 * Implication: the file must always be in a sane, consistent
4124 * truncatable state while each transaction commits.
4126 if (ext4_orphan_add(handle, inode))
4130 * From here we block out all ext4_get_block() callers who want to
4131 * modify the block allocation tree.
4133 down_write(&ei->i_data_sem);
4135 ext4_discard_preallocations(inode);
4138 * The orphan list entry will now protect us from any crash which
4139 * occurs before the truncate completes, so it is now safe to propagate
4140 * the new, shorter inode size (held for now in i_size) into the
4141 * on-disk inode. We do this via i_disksize, which is the value which
4142 * ext4 *really* writes onto the disk inode.
4144 ei->i_disksize = inode->i_size;
4146 if (n == 1) { /* direct blocks */
4147 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
4148 i_data + EXT4_NDIR_BLOCKS);
4152 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
4153 /* Kill the top of shared branch (not detached) */
4155 if (partial == chain) {
4156 /* Shared branch grows from the inode */
4157 ext4_free_branches(handle, inode, NULL,
4158 &nr, &nr+1, (chain+n-1) - partial);
4161 * We mark the inode dirty prior to restart,
4162 * and prior to stop. No need for it here.
4165 /* Shared branch grows from an indirect block */
4166 BUFFER_TRACE(partial->bh, "get_write_access");
4167 ext4_free_branches(handle, inode, partial->bh,
4169 partial->p+1, (chain+n-1) - partial);
4172 /* Clear the ends of indirect blocks on the shared branch */
4173 while (partial > chain) {
4174 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
4175 (__le32*)partial->bh->b_data+addr_per_block,
4176 (chain+n-1) - partial);
4177 BUFFER_TRACE(partial->bh, "call brelse");
4178 brelse(partial->bh);
4182 /* Kill the remaining (whole) subtrees */
4183 switch (offsets[0]) {
4185 nr = i_data[EXT4_IND_BLOCK];
4187 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4188 i_data[EXT4_IND_BLOCK] = 0;
4190 case EXT4_IND_BLOCK:
4191 nr = i_data[EXT4_DIND_BLOCK];
4193 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4194 i_data[EXT4_DIND_BLOCK] = 0;
4196 case EXT4_DIND_BLOCK:
4197 nr = i_data[EXT4_TIND_BLOCK];
4199 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4200 i_data[EXT4_TIND_BLOCK] = 0;
4202 case EXT4_TIND_BLOCK:
4206 up_write(&ei->i_data_sem);
4207 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4208 ext4_mark_inode_dirty(handle, inode);
4211 * In a multi-transaction truncate, we only make the final transaction
4215 ext4_handle_sync(handle);
4218 * If this was a simple ftruncate(), and the file will remain alive
4219 * then we need to clear up the orphan record which we created above.
4220 * However, if this was a real unlink then we were called by
4221 * ext4_delete_inode(), and we allow that function to clean up the
4222 * orphan info for us.
4225 ext4_orphan_del(handle, inode);
4227 ext4_journal_stop(handle);
4231 * ext4_get_inode_loc returns with an extra refcount against the inode's
4232 * underlying buffer_head on success. If 'in_mem' is true, we have all
4233 * data in memory that is needed to recreate the on-disk version of this
4236 static int __ext4_get_inode_loc(struct inode *inode,
4237 struct ext4_iloc *iloc, int in_mem)
4239 struct ext4_group_desc *gdp;
4240 struct buffer_head *bh;
4241 struct super_block *sb = inode->i_sb;
4243 int inodes_per_block, inode_offset;
4246 if (!ext4_valid_inum(sb, inode->i_ino))
4249 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4250 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4255 * Figure out the offset within the block group inode table
4257 inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
4258 inode_offset = ((inode->i_ino - 1) %
4259 EXT4_INODES_PER_GROUP(sb));
4260 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4261 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4263 bh = sb_getblk(sb, block);
4265 ext4_error(sb, "ext4_get_inode_loc", "unable to read "
4266 "inode block - inode=%lu, block=%llu",
4267 inode->i_ino, block);
4270 if (!buffer_uptodate(bh)) {
4274 * If the buffer has the write error flag, we have failed
4275 * to write out another inode in the same block. In this
4276 * case, we don't have to read the block because we may
4277 * read the old inode data successfully.
4279 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4280 set_buffer_uptodate(bh);
4282 if (buffer_uptodate(bh)) {
4283 /* someone brought it uptodate while we waited */
4289 * If we have all information of the inode in memory and this
4290 * is the only valid inode in the block, we need not read the
4294 struct buffer_head *bitmap_bh;
4297 start = inode_offset & ~(inodes_per_block - 1);
4299 /* Is the inode bitmap in cache? */
4300 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4305 * If the inode bitmap isn't in cache then the
4306 * optimisation may end up performing two reads instead
4307 * of one, so skip it.
4309 if (!buffer_uptodate(bitmap_bh)) {
4313 for (i = start; i < start + inodes_per_block; i++) {
4314 if (i == inode_offset)
4316 if (ext4_test_bit(i, bitmap_bh->b_data))
4320 if (i == start + inodes_per_block) {
4321 /* all other inodes are free, so skip I/O */
4322 memset(bh->b_data, 0, bh->b_size);
4323 set_buffer_uptodate(bh);
4331 * If we need to do any I/O, try to pre-readahead extra
4332 * blocks from the inode table.
4334 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4335 ext4_fsblk_t b, end, table;
4338 table = ext4_inode_table(sb, gdp);
4339 /* s_inode_readahead_blks is always a power of 2 */
4340 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4343 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4344 num = EXT4_INODES_PER_GROUP(sb);
4345 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4346 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4347 num -= ext4_itable_unused_count(sb, gdp);
4348 table += num / inodes_per_block;
4352 sb_breadahead(sb, b++);
4356 * There are other valid inodes in the buffer, this inode
4357 * has in-inode xattrs, or we don't have this inode in memory.
4358 * Read the block from disk.
4361 bh->b_end_io = end_buffer_read_sync;
4362 submit_bh(READ_META, bh);
4364 if (!buffer_uptodate(bh)) {
4365 ext4_error(sb, __func__,
4366 "unable to read inode block - inode=%lu, "
4367 "block=%llu", inode->i_ino, block);
4377 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4379 /* We have all inode data except xattrs in memory here. */
4380 return __ext4_get_inode_loc(inode, iloc,
4381 !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
4384 void ext4_set_inode_flags(struct inode *inode)
4386 unsigned int flags = EXT4_I(inode)->i_flags;
4388 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4389 if (flags & EXT4_SYNC_FL)
4390 inode->i_flags |= S_SYNC;
4391 if (flags & EXT4_APPEND_FL)
4392 inode->i_flags |= S_APPEND;
4393 if (flags & EXT4_IMMUTABLE_FL)
4394 inode->i_flags |= S_IMMUTABLE;
4395 if (flags & EXT4_NOATIME_FL)
4396 inode->i_flags |= S_NOATIME;
4397 if (flags & EXT4_DIRSYNC_FL)
4398 inode->i_flags |= S_DIRSYNC;
4401 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4402 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4404 unsigned int flags = ei->vfs_inode.i_flags;
4406 ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4407 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
4409 ei->i_flags |= EXT4_SYNC_FL;
4410 if (flags & S_APPEND)
4411 ei->i_flags |= EXT4_APPEND_FL;
4412 if (flags & S_IMMUTABLE)
4413 ei->i_flags |= EXT4_IMMUTABLE_FL;
4414 if (flags & S_NOATIME)
4415 ei->i_flags |= EXT4_NOATIME_FL;
4416 if (flags & S_DIRSYNC)
4417 ei->i_flags |= EXT4_DIRSYNC_FL;
4420 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4421 struct ext4_inode_info *ei)
4424 struct inode *inode = &(ei->vfs_inode);
4425 struct super_block *sb = inode->i_sb;
4427 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4428 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4429 /* we are using combined 48 bit field */
4430 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4431 le32_to_cpu(raw_inode->i_blocks_lo);
4432 if (ei->i_flags & EXT4_HUGE_FILE_FL) {
4433 /* i_blocks represent file system block size */
4434 return i_blocks << (inode->i_blkbits - 9);
4439 return le32_to_cpu(raw_inode->i_blocks_lo);
4443 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4445 struct ext4_iloc iloc;
4446 struct ext4_inode *raw_inode;
4447 struct ext4_inode_info *ei;
4448 struct buffer_head *bh;
4449 struct inode *inode;
4453 inode = iget_locked(sb, ino);
4455 return ERR_PTR(-ENOMEM);
4456 if (!(inode->i_state & I_NEW))
4460 #ifdef CONFIG_EXT4_FS_POSIX_ACL
4461 ei->i_acl = EXT4_ACL_NOT_CACHED;
4462 ei->i_default_acl = EXT4_ACL_NOT_CACHED;
4465 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4469 raw_inode = ext4_raw_inode(&iloc);
4470 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4471 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4472 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4473 if (!(test_opt(inode->i_sb, NO_UID32))) {
4474 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4475 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4477 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4480 ei->i_dir_start_lookup = 0;
4481 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4482 /* We now have enough fields to check if the inode was active or not.
4483 * This is needed because nfsd might try to access dead inodes
4484 * the test is that same one that e2fsck uses
4485 * NeilBrown 1999oct15
4487 if (inode->i_nlink == 0) {
4488 if (inode->i_mode == 0 ||
4489 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4490 /* this inode is deleted */
4495 /* The only unlinked inodes we let through here have
4496 * valid i_mode and are being read by the orphan
4497 * recovery code: that's fine, we're about to complete
4498 * the process of deleting those. */
4500 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4501 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4502 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4503 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4505 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4506 inode->i_size = ext4_isize(raw_inode);
4507 ei->i_disksize = inode->i_size;
4508 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4509 ei->i_block_group = iloc.block_group;
4510 ei->i_last_alloc_group = ~0;
4512 * NOTE! The in-memory inode i_data array is in little-endian order
4513 * even on big-endian machines: we do NOT byteswap the block numbers!
4515 for (block = 0; block < EXT4_N_BLOCKS; block++)
4516 ei->i_data[block] = raw_inode->i_block[block];
4517 INIT_LIST_HEAD(&ei->i_orphan);
4519 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4520 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4521 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4522 EXT4_INODE_SIZE(inode->i_sb)) {
4527 if (ei->i_extra_isize == 0) {
4528 /* The extra space is currently unused. Use it. */
4529 ei->i_extra_isize = sizeof(struct ext4_inode) -
4530 EXT4_GOOD_OLD_INODE_SIZE;
4532 __le32 *magic = (void *)raw_inode +
4533 EXT4_GOOD_OLD_INODE_SIZE +
4535 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
4536 ei->i_state |= EXT4_STATE_XATTR;
4539 ei->i_extra_isize = 0;
4541 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4542 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4543 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4544 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4546 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4547 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4548 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4550 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4554 if (ei->i_file_acl &&
4556 (le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) +
4557 EXT4_SB(sb)->s_gdb_count)) ||
4558 (ei->i_file_acl >= ext4_blocks_count(EXT4_SB(sb)->s_es)))) {
4559 ext4_error(sb, __func__,
4560 "bad extended attribute block %llu in inode #%lu",
4561 ei->i_file_acl, inode->i_ino);
4564 } else if (ei->i_flags & EXT4_EXTENTS_FL) {
4565 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4566 (S_ISLNK(inode->i_mode) &&
4567 !ext4_inode_is_fast_symlink(inode)))
4568 /* Validate extent which is part of inode */
4569 ret = ext4_ext_check_inode(inode);
4570 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4571 (S_ISLNK(inode->i_mode) &&
4572 !ext4_inode_is_fast_symlink(inode))) {
4573 /* Validate block references which are part of inode */
4574 ret = ext4_check_inode_blockref(inode);
4581 if (S_ISREG(inode->i_mode)) {
4582 inode->i_op = &ext4_file_inode_operations;
4583 inode->i_fop = &ext4_file_operations;
4584 ext4_set_aops(inode);
4585 } else if (S_ISDIR(inode->i_mode)) {
4586 inode->i_op = &ext4_dir_inode_operations;
4587 inode->i_fop = &ext4_dir_operations;
4588 } else if (S_ISLNK(inode->i_mode)) {
4589 if (ext4_inode_is_fast_symlink(inode)) {
4590 inode->i_op = &ext4_fast_symlink_inode_operations;
4591 nd_terminate_link(ei->i_data, inode->i_size,
4592 sizeof(ei->i_data) - 1);
4594 inode->i_op = &ext4_symlink_inode_operations;
4595 ext4_set_aops(inode);
4597 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4598 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4599 inode->i_op = &ext4_special_inode_operations;
4600 if (raw_inode->i_block[0])
4601 init_special_inode(inode, inode->i_mode,
4602 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4604 init_special_inode(inode, inode->i_mode,
4605 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4609 ext4_error(inode->i_sb, __func__,
4610 "bogus i_mode (%o) for inode=%lu",
4611 inode->i_mode, inode->i_ino);
4615 ext4_set_inode_flags(inode);
4616 unlock_new_inode(inode);
4621 return ERR_PTR(ret);
4624 static int ext4_inode_blocks_set(handle_t *handle,
4625 struct ext4_inode *raw_inode,
4626 struct ext4_inode_info *ei)
4628 struct inode *inode = &(ei->vfs_inode);
4629 u64 i_blocks = inode->i_blocks;
4630 struct super_block *sb = inode->i_sb;
4632 if (i_blocks <= ~0U) {
4634 * i_blocks can be represnted in a 32 bit variable
4635 * as multiple of 512 bytes
4637 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4638 raw_inode->i_blocks_high = 0;
4639 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4642 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4645 if (i_blocks <= 0xffffffffffffULL) {
4647 * i_blocks can be represented in a 48 bit variable
4648 * as multiple of 512 bytes
4650 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4651 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4652 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4654 ei->i_flags |= EXT4_HUGE_FILE_FL;
4655 /* i_block is stored in file system block size */
4656 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4657 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4658 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4664 * Post the struct inode info into an on-disk inode location in the
4665 * buffer-cache. This gobbles the caller's reference to the
4666 * buffer_head in the inode location struct.
4668 * The caller must have write access to iloc->bh.
4670 static int ext4_do_update_inode(handle_t *handle,
4671 struct inode *inode,
4672 struct ext4_iloc *iloc)
4674 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4675 struct ext4_inode_info *ei = EXT4_I(inode);
4676 struct buffer_head *bh = iloc->bh;
4677 int err = 0, rc, block;
4679 /* For fields not not tracking in the in-memory inode,
4680 * initialise them to zero for new inodes. */
4681 if (ei->i_state & EXT4_STATE_NEW)
4682 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4684 ext4_get_inode_flags(ei);
4685 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4686 if (!(test_opt(inode->i_sb, NO_UID32))) {
4687 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4688 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4690 * Fix up interoperability with old kernels. Otherwise, old inodes get
4691 * re-used with the upper 16 bits of the uid/gid intact
4694 raw_inode->i_uid_high =
4695 cpu_to_le16(high_16_bits(inode->i_uid));
4696 raw_inode->i_gid_high =
4697 cpu_to_le16(high_16_bits(inode->i_gid));
4699 raw_inode->i_uid_high = 0;
4700 raw_inode->i_gid_high = 0;
4703 raw_inode->i_uid_low =
4704 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4705 raw_inode->i_gid_low =
4706 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4707 raw_inode->i_uid_high = 0;
4708 raw_inode->i_gid_high = 0;
4710 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4712 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4713 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4714 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4715 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4717 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4719 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4720 /* clear the migrate flag in the raw_inode */
4721 raw_inode->i_flags = cpu_to_le32(ei->i_flags & ~EXT4_EXT_MIGRATE);
4722 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4723 cpu_to_le32(EXT4_OS_HURD))
4724 raw_inode->i_file_acl_high =
4725 cpu_to_le16(ei->i_file_acl >> 32);
4726 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4727 ext4_isize_set(raw_inode, ei->i_disksize);
4728 if (ei->i_disksize > 0x7fffffffULL) {
4729 struct super_block *sb = inode->i_sb;
4730 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4731 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4732 EXT4_SB(sb)->s_es->s_rev_level ==
4733 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4734 /* If this is the first large file
4735 * created, add a flag to the superblock.
4737 err = ext4_journal_get_write_access(handle,
4738 EXT4_SB(sb)->s_sbh);
4741 ext4_update_dynamic_rev(sb);
4742 EXT4_SET_RO_COMPAT_FEATURE(sb,
4743 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4745 ext4_handle_sync(handle);
4746 err = ext4_handle_dirty_metadata(handle, inode,
4747 EXT4_SB(sb)->s_sbh);
4750 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4751 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4752 if (old_valid_dev(inode->i_rdev)) {
4753 raw_inode->i_block[0] =
4754 cpu_to_le32(old_encode_dev(inode->i_rdev));
4755 raw_inode->i_block[1] = 0;
4757 raw_inode->i_block[0] = 0;
4758 raw_inode->i_block[1] =
4759 cpu_to_le32(new_encode_dev(inode->i_rdev));
4760 raw_inode->i_block[2] = 0;
4763 for (block = 0; block < EXT4_N_BLOCKS; block++)
4764 raw_inode->i_block[block] = ei->i_data[block];
4766 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4767 if (ei->i_extra_isize) {
4768 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4769 raw_inode->i_version_hi =
4770 cpu_to_le32(inode->i_version >> 32);
4771 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4774 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4775 rc = ext4_handle_dirty_metadata(handle, inode, bh);
4778 ei->i_state &= ~EXT4_STATE_NEW;
4782 ext4_std_error(inode->i_sb, err);
4787 * ext4_write_inode()
4789 * We are called from a few places:
4791 * - Within generic_file_write() for O_SYNC files.
4792 * Here, there will be no transaction running. We wait for any running
4793 * trasnaction to commit.
4795 * - Within sys_sync(), kupdate and such.
4796 * We wait on commit, if tol to.
4798 * - Within prune_icache() (PF_MEMALLOC == true)
4799 * Here we simply return. We can't afford to block kswapd on the
4802 * In all cases it is actually safe for us to return without doing anything,
4803 * because the inode has been copied into a raw inode buffer in
4804 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4807 * Note that we are absolutely dependent upon all inode dirtiers doing the
4808 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4809 * which we are interested.
4811 * It would be a bug for them to not do this. The code:
4813 * mark_inode_dirty(inode)
4815 * inode->i_size = expr;
4817 * is in error because a kswapd-driven write_inode() could occur while
4818 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4819 * will no longer be on the superblock's dirty inode list.
4821 int ext4_write_inode(struct inode *inode, int wait)
4823 if (current->flags & PF_MEMALLOC)
4826 if (ext4_journal_current_handle()) {
4827 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4835 return ext4_force_commit(inode->i_sb);
4841 * Called from notify_change.
4843 * We want to trap VFS attempts to truncate the file as soon as
4844 * possible. In particular, we want to make sure that when the VFS
4845 * shrinks i_size, we put the inode on the orphan list and modify
4846 * i_disksize immediately, so that during the subsequent flushing of
4847 * dirty pages and freeing of disk blocks, we can guarantee that any
4848 * commit will leave the blocks being flushed in an unused state on
4849 * disk. (On recovery, the inode will get truncated and the blocks will
4850 * be freed, so we have a strong guarantee that no future commit will
4851 * leave these blocks visible to the user.)
4853 * Another thing we have to assure is that if we are in ordered mode
4854 * and inode is still attached to the committing transaction, we must
4855 * we start writeout of all the dirty pages which are being truncated.
4856 * This way we are sure that all the data written in the previous
4857 * transaction are already on disk (truncate waits for pages under
4860 * Called with inode->i_mutex down.
4862 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4864 struct inode *inode = dentry->d_inode;
4866 const unsigned int ia_valid = attr->ia_valid;
4868 error = inode_change_ok(inode, attr);
4872 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4873 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4876 /* (user+group)*(old+new) structure, inode write (sb,
4877 * inode block, ? - but truncate inode update has it) */
4878 handle = ext4_journal_start(inode, 2*(EXT4_QUOTA_INIT_BLOCKS(inode->i_sb)+
4879 EXT4_QUOTA_DEL_BLOCKS(inode->i_sb))+3);
4880 if (IS_ERR(handle)) {
4881 error = PTR_ERR(handle);
4884 error = vfs_dq_transfer(inode, attr) ? -EDQUOT : 0;
4886 ext4_journal_stop(handle);
4889 /* Update corresponding info in inode so that everything is in
4890 * one transaction */
4891 if (attr->ia_valid & ATTR_UID)
4892 inode->i_uid = attr->ia_uid;
4893 if (attr->ia_valid & ATTR_GID)
4894 inode->i_gid = attr->ia_gid;
4895 error = ext4_mark_inode_dirty(handle, inode);
4896 ext4_journal_stop(handle);
4899 if (attr->ia_valid & ATTR_SIZE) {
4900 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
4901 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4903 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
4910 if (S_ISREG(inode->i_mode) &&
4911 attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
4914 handle = ext4_journal_start(inode, 3);
4915 if (IS_ERR(handle)) {
4916 error = PTR_ERR(handle);
4920 error = ext4_orphan_add(handle, inode);
4921 EXT4_I(inode)->i_disksize = attr->ia_size;
4922 rc = ext4_mark_inode_dirty(handle, inode);
4925 ext4_journal_stop(handle);
4927 if (ext4_should_order_data(inode)) {
4928 error = ext4_begin_ordered_truncate(inode,
4931 /* Do as much error cleanup as possible */
4932 handle = ext4_journal_start(inode, 3);
4933 if (IS_ERR(handle)) {
4934 ext4_orphan_del(NULL, inode);
4937 ext4_orphan_del(handle, inode);
4938 ext4_journal_stop(handle);
4944 rc = inode_setattr(inode, attr);
4946 /* If inode_setattr's call to ext4_truncate failed to get a
4947 * transaction handle at all, we need to clean up the in-core
4948 * orphan list manually. */
4950 ext4_orphan_del(NULL, inode);
4952 if (!rc && (ia_valid & ATTR_MODE))
4953 rc = ext4_acl_chmod(inode);
4956 ext4_std_error(inode->i_sb, error);
4962 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4965 struct inode *inode;
4966 unsigned long delalloc_blocks;
4968 inode = dentry->d_inode;
4969 generic_fillattr(inode, stat);
4972 * We can't update i_blocks if the block allocation is delayed
4973 * otherwise in the case of system crash before the real block
4974 * allocation is done, we will have i_blocks inconsistent with
4975 * on-disk file blocks.
4976 * We always keep i_blocks updated together with real
4977 * allocation. But to not confuse with user, stat
4978 * will return the blocks that include the delayed allocation
4979 * blocks for this file.
4981 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
4982 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4983 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
4985 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4989 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
4994 /* if nrblocks are contiguous */
4997 * With N contiguous data blocks, it need at most
4998 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
4999 * 2 dindirect blocks
5002 indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
5003 return indirects + 3;
5006 * if nrblocks are not contiguous, worse case, each block touch
5007 * a indirect block, and each indirect block touch a double indirect
5008 * block, plus a triple indirect block
5010 indirects = nrblocks * 2 + 1;
5014 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5016 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
5017 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
5018 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
5022 * Account for index blocks, block groups bitmaps and block group
5023 * descriptor blocks if modify datablocks and index blocks
5024 * worse case, the indexs blocks spread over different block groups
5026 * If datablocks are discontiguous, they are possible to spread over
5027 * different block groups too. If they are contiugous, with flexbg,
5028 * they could still across block group boundary.
5030 * Also account for superblock, inode, quota and xattr blocks
5032 int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5034 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5040 * How many index blocks need to touch to modify nrblocks?
5041 * The "Chunk" flag indicating whether the nrblocks is
5042 * physically contiguous on disk
5044 * For Direct IO and fallocate, they calls get_block to allocate
5045 * one single extent at a time, so they could set the "Chunk" flag
5047 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
5052 * Now let's see how many group bitmaps and group descriptors need
5062 if (groups > ngroups)
5064 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5065 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5067 /* bitmaps and block group descriptor blocks */
5068 ret += groups + gdpblocks;
5070 /* Blocks for super block, inode, quota and xattr blocks */
5071 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5077 * Calulate the total number of credits to reserve to fit
5078 * the modification of a single pages into a single transaction,
5079 * which may include multiple chunks of block allocations.
5081 * This could be called via ext4_write_begin()
5083 * We need to consider the worse case, when
5084 * one new block per extent.
5086 int ext4_writepage_trans_blocks(struct inode *inode)
5088 int bpp = ext4_journal_blocks_per_page(inode);
5091 ret = ext4_meta_trans_blocks(inode, bpp, 0);
5093 /* Account for data blocks for journalled mode */
5094 if (ext4_should_journal_data(inode))
5100 * Calculate the journal credits for a chunk of data modification.
5102 * This is called from DIO, fallocate or whoever calling
5103 * ext4_get_blocks() to map/allocate a chunk of contigous disk blocks.
5105 * journal buffers for data blocks are not included here, as DIO
5106 * and fallocate do no need to journal data buffers.
5108 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5110 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5114 * The caller must have previously called ext4_reserve_inode_write().
5115 * Give this, we know that the caller already has write access to iloc->bh.
5117 int ext4_mark_iloc_dirty(handle_t *handle,
5118 struct inode *inode, struct ext4_iloc *iloc)
5122 if (test_opt(inode->i_sb, I_VERSION))
5123 inode_inc_iversion(inode);
5125 /* the do_update_inode consumes one bh->b_count */
5128 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5129 err = ext4_do_update_inode(handle, inode, iloc);
5135 * On success, We end up with an outstanding reference count against
5136 * iloc->bh. This _must_ be cleaned up later.
5140 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5141 struct ext4_iloc *iloc)
5145 err = ext4_get_inode_loc(inode, iloc);
5147 BUFFER_TRACE(iloc->bh, "get_write_access");
5148 err = ext4_journal_get_write_access(handle, iloc->bh);
5154 ext4_std_error(inode->i_sb, err);
5159 * Expand an inode by new_extra_isize bytes.
5160 * Returns 0 on success or negative error number on failure.
5162 static int ext4_expand_extra_isize(struct inode *inode,
5163 unsigned int new_extra_isize,
5164 struct ext4_iloc iloc,
5167 struct ext4_inode *raw_inode;
5168 struct ext4_xattr_ibody_header *header;
5169 struct ext4_xattr_entry *entry;
5171 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5174 raw_inode = ext4_raw_inode(&iloc);
5176 header = IHDR(inode, raw_inode);
5177 entry = IFIRST(header);
5179 /* No extended attributes present */
5180 if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
5181 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5182 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5184 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5188 /* try to expand with EAs present */
5189 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5194 * What we do here is to mark the in-core inode as clean with respect to inode
5195 * dirtiness (it may still be data-dirty).
5196 * This means that the in-core inode may be reaped by prune_icache
5197 * without having to perform any I/O. This is a very good thing,
5198 * because *any* task may call prune_icache - even ones which
5199 * have a transaction open against a different journal.
5201 * Is this cheating? Not really. Sure, we haven't written the
5202 * inode out, but prune_icache isn't a user-visible syncing function.
5203 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5204 * we start and wait on commits.
5206 * Is this efficient/effective? Well, we're being nice to the system
5207 * by cleaning up our inodes proactively so they can be reaped
5208 * without I/O. But we are potentially leaving up to five seconds'
5209 * worth of inodes floating about which prune_icache wants us to
5210 * write out. One way to fix that would be to get prune_icache()
5211 * to do a write_super() to free up some memory. It has the desired
5214 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5216 struct ext4_iloc iloc;
5217 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5218 static unsigned int mnt_count;
5222 err = ext4_reserve_inode_write(handle, inode, &iloc);
5223 if (ext4_handle_valid(handle) &&
5224 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5225 !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
5227 * We need extra buffer credits since we may write into EA block
5228 * with this same handle. If journal_extend fails, then it will
5229 * only result in a minor loss of functionality for that inode.
5230 * If this is felt to be critical, then e2fsck should be run to
5231 * force a large enough s_min_extra_isize.
5233 if ((jbd2_journal_extend(handle,
5234 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5235 ret = ext4_expand_extra_isize(inode,
5236 sbi->s_want_extra_isize,
5239 EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
5241 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5242 ext4_warning(inode->i_sb, __func__,
5243 "Unable to expand inode %lu. Delete"
5244 " some EAs or run e2fsck.",
5247 le16_to_cpu(sbi->s_es->s_mnt_count);
5253 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5258 * ext4_dirty_inode() is called from __mark_inode_dirty()
5260 * We're really interested in the case where a file is being extended.
5261 * i_size has been changed by generic_commit_write() and we thus need
5262 * to include the updated inode in the current transaction.
5264 * Also, vfs_dq_alloc_block() will always dirty the inode when blocks
5265 * are allocated to the file.
5267 * If the inode is marked synchronous, we don't honour that here - doing
5268 * so would cause a commit on atime updates, which we don't bother doing.
5269 * We handle synchronous inodes at the highest possible level.
5271 void ext4_dirty_inode(struct inode *inode)
5273 handle_t *current_handle = ext4_journal_current_handle();
5276 if (!ext4_handle_valid(current_handle)) {
5277 ext4_mark_inode_dirty(current_handle, inode);
5281 handle = ext4_journal_start(inode, 2);
5284 if (current_handle &&
5285 current_handle->h_transaction != handle->h_transaction) {
5286 /* This task has a transaction open against a different fs */
5287 printk(KERN_EMERG "%s: transactions do not match!\n",
5290 jbd_debug(5, "marking dirty. outer handle=%p\n",
5292 ext4_mark_inode_dirty(handle, inode);
5294 ext4_journal_stop(handle);
5301 * Bind an inode's backing buffer_head into this transaction, to prevent
5302 * it from being flushed to disk early. Unlike
5303 * ext4_reserve_inode_write, this leaves behind no bh reference and
5304 * returns no iloc structure, so the caller needs to repeat the iloc
5305 * lookup to mark the inode dirty later.
5307 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5309 struct ext4_iloc iloc;
5313 err = ext4_get_inode_loc(inode, &iloc);
5315 BUFFER_TRACE(iloc.bh, "get_write_access");
5316 err = jbd2_journal_get_write_access(handle, iloc.bh);
5318 err = ext4_handle_dirty_metadata(handle,
5324 ext4_std_error(inode->i_sb, err);
5329 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5336 * We have to be very careful here: changing a data block's
5337 * journaling status dynamically is dangerous. If we write a
5338 * data block to the journal, change the status and then delete
5339 * that block, we risk forgetting to revoke the old log record
5340 * from the journal and so a subsequent replay can corrupt data.
5341 * So, first we make sure that the journal is empty and that
5342 * nobody is changing anything.
5345 journal = EXT4_JOURNAL(inode);
5348 if (is_journal_aborted(journal))
5351 jbd2_journal_lock_updates(journal);
5352 jbd2_journal_flush(journal);
5355 * OK, there are no updates running now, and all cached data is
5356 * synced to disk. We are now in a completely consistent state
5357 * which doesn't have anything in the journal, and we know that
5358 * no filesystem updates are running, so it is safe to modify
5359 * the inode's in-core data-journaling state flag now.
5363 EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
5365 EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
5366 ext4_set_aops(inode);
5368 jbd2_journal_unlock_updates(journal);
5370 /* Finally we can mark the inode as dirty. */
5372 handle = ext4_journal_start(inode, 1);
5374 return PTR_ERR(handle);
5376 err = ext4_mark_inode_dirty(handle, inode);
5377 ext4_handle_sync(handle);
5378 ext4_journal_stop(handle);
5379 ext4_std_error(inode->i_sb, err);
5384 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5386 return !buffer_mapped(bh);
5389 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5391 struct page *page = vmf->page;
5396 struct file *file = vma->vm_file;
5397 struct inode *inode = file->f_path.dentry->d_inode;
5398 struct address_space *mapping = inode->i_mapping;
5401 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5402 * get i_mutex because we are already holding mmap_sem.
5404 down_read(&inode->i_alloc_sem);
5405 size = i_size_read(inode);
5406 if (page->mapping != mapping || size <= page_offset(page)
5407 || !PageUptodate(page)) {
5408 /* page got truncated from under us? */
5412 if (PageMappedToDisk(page))
5415 if (page->index == size >> PAGE_CACHE_SHIFT)
5416 len = size & ~PAGE_CACHE_MASK;
5418 len = PAGE_CACHE_SIZE;
5420 if (page_has_buffers(page)) {
5421 /* return if we have all the buffers mapped */
5422 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5427 * OK, we need to fill the hole... Do write_begin write_end
5428 * to do block allocation/reservation.We are not holding
5429 * inode.i__mutex here. That allow * parallel write_begin,
5430 * write_end call. lock_page prevent this from happening
5431 * on the same page though
5433 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5434 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5437 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5438 len, len, page, fsdata);
5444 ret = VM_FAULT_SIGBUS;
5445 up_read(&inode->i_alloc_sem);