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>
40 #include <linux/workqueue.h>
42 #include "ext4_jbd2.h"
45 #include "ext4_extents.h"
47 #include <trace/events/ext4.h>
49 #define MPAGE_DA_EXTENT_TAIL 0x01
51 static inline int ext4_begin_ordered_truncate(struct inode *inode,
54 return jbd2_journal_begin_ordered_truncate(
55 EXT4_SB(inode->i_sb)->s_journal,
56 &EXT4_I(inode)->jinode,
60 static void ext4_invalidatepage(struct page *page, unsigned long offset);
63 * Test whether an inode is a fast symlink.
65 static int ext4_inode_is_fast_symlink(struct inode *inode)
67 int ea_blocks = EXT4_I(inode)->i_file_acl ?
68 (inode->i_sb->s_blocksize >> 9) : 0;
70 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
74 * Work out how many blocks we need to proceed with the next chunk of a
75 * truncate transaction.
77 static unsigned long blocks_for_truncate(struct inode *inode)
81 needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
83 /* Give ourselves just enough room to cope with inodes in which
84 * i_blocks is corrupt: we've seen disk corruptions in the past
85 * which resulted in random data in an inode which looked enough
86 * like a regular file for ext4 to try to delete it. Things
87 * will go a bit crazy if that happens, but at least we should
88 * try not to panic the whole kernel. */
92 /* But we need to bound the transaction so we don't overflow the
94 if (needed > EXT4_MAX_TRANS_DATA)
95 needed = EXT4_MAX_TRANS_DATA;
97 return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
101 * Truncate transactions can be complex and absolutely huge. So we need to
102 * be able to restart the transaction at a conventient checkpoint to make
103 * sure we don't overflow the journal.
105 * start_transaction gets us a new handle for a truncate transaction,
106 * and extend_transaction tries to extend the existing one a bit. If
107 * extend fails, we need to propagate the failure up and restart the
108 * transaction in the top-level truncate loop. --sct
110 static handle_t *start_transaction(struct inode *inode)
114 result = ext4_journal_start(inode, blocks_for_truncate(inode));
118 ext4_std_error(inode->i_sb, PTR_ERR(result));
123 * Try to extend this transaction for the purposes of truncation.
125 * Returns 0 if we managed to create more room. If we can't create more
126 * room, and the transaction must be restarted we return 1.
128 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
130 if (!ext4_handle_valid(handle))
132 if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
134 if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
140 * Restart the transaction associated with *handle. This does a commit,
141 * so before we call here everything must be consistently dirtied against
144 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
150 * Drop i_data_sem to avoid deadlock with ext4_get_blocks At this
151 * moment, get_block can be called only for blocks inside i_size since
152 * page cache has been already dropped and writes are blocked by
153 * i_mutex. So we can safely drop the i_data_sem here.
155 BUG_ON(EXT4_JOURNAL(inode) == NULL);
156 jbd_debug(2, "restarting handle %p\n", handle);
157 up_write(&EXT4_I(inode)->i_data_sem);
158 ret = ext4_journal_restart(handle, blocks_for_truncate(inode));
159 down_write(&EXT4_I(inode)->i_data_sem);
160 ext4_discard_preallocations(inode);
166 * Called at the last iput() if i_nlink is zero.
168 void ext4_delete_inode(struct inode *inode)
173 if (!is_bad_inode(inode))
176 if (ext4_should_order_data(inode))
177 ext4_begin_ordered_truncate(inode, 0);
178 truncate_inode_pages(&inode->i_data, 0);
180 if (is_bad_inode(inode))
183 handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
184 if (IS_ERR(handle)) {
185 ext4_std_error(inode->i_sb, PTR_ERR(handle));
187 * If we're going to skip the normal cleanup, we still need to
188 * make sure that the in-core orphan linked list is properly
191 ext4_orphan_del(NULL, inode);
196 ext4_handle_sync(handle);
198 err = ext4_mark_inode_dirty(handle, inode);
200 ext4_warning(inode->i_sb, __func__,
201 "couldn't mark inode dirty (err %d)", err);
205 ext4_truncate(inode);
208 * ext4_ext_truncate() doesn't reserve any slop when it
209 * restarts journal transactions; therefore there may not be
210 * enough credits left in the handle to remove the inode from
211 * the orphan list and set the dtime field.
213 if (!ext4_handle_has_enough_credits(handle, 3)) {
214 err = ext4_journal_extend(handle, 3);
216 err = ext4_journal_restart(handle, 3);
218 ext4_warning(inode->i_sb, __func__,
219 "couldn't extend journal (err %d)", err);
221 ext4_journal_stop(handle);
227 * Kill off the orphan record which ext4_truncate created.
228 * AKPM: I think this can be inside the above `if'.
229 * Note that ext4_orphan_del() has to be able to cope with the
230 * deletion of a non-existent orphan - this is because we don't
231 * know if ext4_truncate() actually created an orphan record.
232 * (Well, we could do this if we need to, but heck - it works)
234 ext4_orphan_del(handle, inode);
235 EXT4_I(inode)->i_dtime = get_seconds();
238 * One subtle ordering requirement: if anything has gone wrong
239 * (transaction abort, IO errors, whatever), then we can still
240 * do these next steps (the fs will already have been marked as
241 * having errors), but we can't free the inode if the mark_dirty
244 if (ext4_mark_inode_dirty(handle, inode))
245 /* If that failed, just do the required in-core inode clear. */
248 ext4_free_inode(handle, inode);
249 ext4_journal_stop(handle);
252 clear_inode(inode); /* We must guarantee clearing of inode... */
258 struct buffer_head *bh;
261 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
263 p->key = *(p->p = v);
268 * ext4_block_to_path - parse the block number into array of offsets
269 * @inode: inode in question (we are only interested in its superblock)
270 * @i_block: block number to be parsed
271 * @offsets: array to store the offsets in
272 * @boundary: set this non-zero if the referred-to block is likely to be
273 * followed (on disk) by an indirect block.
275 * To store the locations of file's data ext4 uses a data structure common
276 * for UNIX filesystems - tree of pointers anchored in the inode, with
277 * data blocks at leaves and indirect blocks in intermediate nodes.
278 * This function translates the block number into path in that tree -
279 * return value is the path length and @offsets[n] is the offset of
280 * pointer to (n+1)th node in the nth one. If @block is out of range
281 * (negative or too large) warning is printed and zero returned.
283 * Note: function doesn't find node addresses, so no IO is needed. All
284 * we need to know is the capacity of indirect blocks (taken from the
289 * Portability note: the last comparison (check that we fit into triple
290 * indirect block) is spelled differently, because otherwise on an
291 * architecture with 32-bit longs and 8Kb pages we might get into trouble
292 * if our filesystem had 8Kb blocks. We might use long long, but that would
293 * kill us on x86. Oh, well, at least the sign propagation does not matter -
294 * i_block would have to be negative in the very beginning, so we would not
298 static int ext4_block_to_path(struct inode *inode,
300 ext4_lblk_t offsets[4], int *boundary)
302 int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
303 int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
304 const long direct_blocks = EXT4_NDIR_BLOCKS,
305 indirect_blocks = ptrs,
306 double_blocks = (1 << (ptrs_bits * 2));
310 if (i_block < direct_blocks) {
311 offsets[n++] = i_block;
312 final = direct_blocks;
313 } else if ((i_block -= direct_blocks) < indirect_blocks) {
314 offsets[n++] = EXT4_IND_BLOCK;
315 offsets[n++] = i_block;
317 } else if ((i_block -= indirect_blocks) < double_blocks) {
318 offsets[n++] = EXT4_DIND_BLOCK;
319 offsets[n++] = i_block >> ptrs_bits;
320 offsets[n++] = i_block & (ptrs - 1);
322 } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
323 offsets[n++] = EXT4_TIND_BLOCK;
324 offsets[n++] = i_block >> (ptrs_bits * 2);
325 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
326 offsets[n++] = i_block & (ptrs - 1);
329 ext4_warning(inode->i_sb, "ext4_block_to_path",
330 "block %lu > max in inode %lu",
331 i_block + direct_blocks +
332 indirect_blocks + double_blocks, inode->i_ino);
335 *boundary = final - 1 - (i_block & (ptrs - 1));
339 static int __ext4_check_blockref(const char *function, struct inode *inode,
340 __le32 *p, unsigned int max)
345 while (bref < p+max) {
346 blk = le32_to_cpu(*bref++);
348 unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
350 ext4_error(inode->i_sb, function,
351 "invalid block reference %u "
352 "in inode #%lu", blk, inode->i_ino);
360 #define ext4_check_indirect_blockref(inode, bh) \
361 __ext4_check_blockref(__func__, inode, (__le32 *)(bh)->b_data, \
362 EXT4_ADDR_PER_BLOCK((inode)->i_sb))
364 #define ext4_check_inode_blockref(inode) \
365 __ext4_check_blockref(__func__, inode, EXT4_I(inode)->i_data, \
369 * ext4_get_branch - read the chain of indirect blocks leading to data
370 * @inode: inode in question
371 * @depth: depth of the chain (1 - direct pointer, etc.)
372 * @offsets: offsets of pointers in inode/indirect blocks
373 * @chain: place to store the result
374 * @err: here we store the error value
376 * Function fills the array of triples <key, p, bh> and returns %NULL
377 * if everything went OK or the pointer to the last filled triple
378 * (incomplete one) otherwise. Upon the return chain[i].key contains
379 * the number of (i+1)-th block in the chain (as it is stored in memory,
380 * i.e. little-endian 32-bit), chain[i].p contains the address of that
381 * number (it points into struct inode for i==0 and into the bh->b_data
382 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
383 * block for i>0 and NULL for i==0. In other words, it holds the block
384 * numbers of the chain, addresses they were taken from (and where we can
385 * verify that chain did not change) and buffer_heads hosting these
388 * Function stops when it stumbles upon zero pointer (absent block)
389 * (pointer to last triple returned, *@err == 0)
390 * or when it gets an IO error reading an indirect block
391 * (ditto, *@err == -EIO)
392 * or when it reads all @depth-1 indirect blocks successfully and finds
393 * the whole chain, all way to the data (returns %NULL, *err == 0).
395 * Need to be called with
396 * down_read(&EXT4_I(inode)->i_data_sem)
398 static Indirect *ext4_get_branch(struct inode *inode, int depth,
399 ext4_lblk_t *offsets,
400 Indirect chain[4], int *err)
402 struct super_block *sb = inode->i_sb;
404 struct buffer_head *bh;
407 /* i_data is not going away, no lock needed */
408 add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
412 bh = sb_getblk(sb, le32_to_cpu(p->key));
416 if (!bh_uptodate_or_lock(bh)) {
417 if (bh_submit_read(bh) < 0) {
421 /* validate block references */
422 if (ext4_check_indirect_blockref(inode, bh)) {
428 add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
442 * ext4_find_near - find a place for allocation with sufficient locality
444 * @ind: descriptor of indirect block.
446 * This function returns the preferred place for block allocation.
447 * It is used when heuristic for sequential allocation fails.
449 * + if there is a block to the left of our position - allocate near it.
450 * + if pointer will live in indirect block - allocate near that block.
451 * + if pointer will live in inode - allocate in the same
454 * In the latter case we colour the starting block by the callers PID to
455 * prevent it from clashing with concurrent allocations for a different inode
456 * in the same block group. The PID is used here so that functionally related
457 * files will be close-by on-disk.
459 * Caller must make sure that @ind is valid and will stay that way.
461 static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
463 struct ext4_inode_info *ei = EXT4_I(inode);
464 __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
466 ext4_fsblk_t bg_start;
467 ext4_fsblk_t last_block;
468 ext4_grpblk_t colour;
469 ext4_group_t block_group;
470 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
472 /* Try to find previous block */
473 for (p = ind->p - 1; p >= start; p--) {
475 return le32_to_cpu(*p);
478 /* No such thing, so let's try location of indirect block */
480 return ind->bh->b_blocknr;
483 * It is going to be referred to from the inode itself? OK, just put it
484 * into the same cylinder group then.
486 block_group = ei->i_block_group;
487 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
488 block_group &= ~(flex_size-1);
489 if (S_ISREG(inode->i_mode))
492 bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
493 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
496 * If we are doing delayed allocation, we don't need take
497 * colour into account.
499 if (test_opt(inode->i_sb, DELALLOC))
502 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
503 colour = (current->pid % 16) *
504 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
506 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
507 return bg_start + colour;
511 * ext4_find_goal - find a preferred place for allocation.
513 * @block: block we want
514 * @partial: pointer to the last triple within a chain
516 * Normally this function find the preferred place for block allocation,
518 * Because this is only used for non-extent files, we limit the block nr
521 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
527 * XXX need to get goal block from mballoc's data structures
530 goal = ext4_find_near(inode, partial);
531 goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
536 * ext4_blks_to_allocate: Look up the block map and count the number
537 * of direct blocks need to be allocated for the given branch.
539 * @branch: chain of indirect blocks
540 * @k: number of blocks need for indirect blocks
541 * @blks: number of data blocks to be mapped.
542 * @blocks_to_boundary: the offset in the indirect block
544 * return the total number of blocks to be allocate, including the
545 * direct and indirect blocks.
547 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
548 int blocks_to_boundary)
550 unsigned int count = 0;
553 * Simple case, [t,d]Indirect block(s) has not allocated yet
554 * then it's clear blocks on that path have not allocated
557 /* right now we don't handle cross boundary allocation */
558 if (blks < blocks_to_boundary + 1)
561 count += blocks_to_boundary + 1;
566 while (count < blks && count <= blocks_to_boundary &&
567 le32_to_cpu(*(branch[0].p + count)) == 0) {
574 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
575 * @indirect_blks: the number of blocks need to allocate for indirect
578 * @new_blocks: on return it will store the new block numbers for
579 * the indirect blocks(if needed) and the first direct block,
580 * @blks: on return it will store the total number of allocated
583 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
584 ext4_lblk_t iblock, ext4_fsblk_t goal,
585 int indirect_blks, int blks,
586 ext4_fsblk_t new_blocks[4], int *err)
588 struct ext4_allocation_request ar;
590 unsigned long count = 0, blk_allocated = 0;
592 ext4_fsblk_t current_block = 0;
596 * Here we try to allocate the requested multiple blocks at once,
597 * on a best-effort basis.
598 * To build a branch, we should allocate blocks for
599 * the indirect blocks(if not allocated yet), and at least
600 * the first direct block of this branch. That's the
601 * minimum number of blocks need to allocate(required)
603 /* first we try to allocate the indirect blocks */
604 target = indirect_blks;
607 /* allocating blocks for indirect blocks and direct blocks */
608 current_block = ext4_new_meta_blocks(handle, inode,
613 BUG_ON(current_block + count > EXT4_MAX_BLOCK_FILE_PHYS);
616 /* allocate blocks for indirect blocks */
617 while (index < indirect_blks && count) {
618 new_blocks[index++] = current_block++;
623 * save the new block number
624 * for the first direct block
626 new_blocks[index] = current_block;
627 printk(KERN_INFO "%s returned more blocks than "
628 "requested\n", __func__);
634 target = blks - count ;
635 blk_allocated = count;
638 /* Now allocate data blocks */
639 memset(&ar, 0, sizeof(ar));
644 if (S_ISREG(inode->i_mode))
645 /* enable in-core preallocation only for regular files */
646 ar.flags = EXT4_MB_HINT_DATA;
648 current_block = ext4_mb_new_blocks(handle, &ar, err);
649 BUG_ON(current_block + ar.len > EXT4_MAX_BLOCK_FILE_PHYS);
651 if (*err && (target == blks)) {
653 * if the allocation failed and we didn't allocate
659 if (target == blks) {
661 * save the new block number
662 * for the first direct block
664 new_blocks[index] = current_block;
666 blk_allocated += ar.len;
669 /* total number of blocks allocated for direct blocks */
674 for (i = 0; i < index; i++)
675 ext4_free_blocks(handle, inode, 0, new_blocks[i], 1, 0);
680 * ext4_alloc_branch - allocate and set up a chain of blocks.
682 * @indirect_blks: number of allocated indirect blocks
683 * @blks: number of allocated direct blocks
684 * @offsets: offsets (in the blocks) to store the pointers to next.
685 * @branch: place to store the chain in.
687 * This function allocates blocks, zeroes out all but the last one,
688 * links them into chain and (if we are synchronous) writes them to disk.
689 * In other words, it prepares a branch that can be spliced onto the
690 * inode. It stores the information about that chain in the branch[], in
691 * the same format as ext4_get_branch() would do. We are calling it after
692 * we had read the existing part of chain and partial points to the last
693 * triple of that (one with zero ->key). Upon the exit we have the same
694 * picture as after the successful ext4_get_block(), except that in one
695 * place chain is disconnected - *branch->p is still zero (we did not
696 * set the last link), but branch->key contains the number that should
697 * be placed into *branch->p to fill that gap.
699 * If allocation fails we free all blocks we've allocated (and forget
700 * their buffer_heads) and return the error value the from failed
701 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
702 * as described above and return 0.
704 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
705 ext4_lblk_t iblock, int indirect_blks,
706 int *blks, ext4_fsblk_t goal,
707 ext4_lblk_t *offsets, Indirect *branch)
709 int blocksize = inode->i_sb->s_blocksize;
712 struct buffer_head *bh;
714 ext4_fsblk_t new_blocks[4];
715 ext4_fsblk_t current_block;
717 num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
718 *blks, new_blocks, &err);
722 branch[0].key = cpu_to_le32(new_blocks[0]);
724 * metadata blocks and data blocks are allocated.
726 for (n = 1; n <= indirect_blks; n++) {
728 * Get buffer_head for parent block, zero it out
729 * and set the pointer to new one, then send
732 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
735 BUFFER_TRACE(bh, "call get_create_access");
736 err = ext4_journal_get_create_access(handle, bh);
738 /* Don't brelse(bh) here; it's done in
739 * ext4_journal_forget() below */
744 memset(bh->b_data, 0, blocksize);
745 branch[n].p = (__le32 *) bh->b_data + offsets[n];
746 branch[n].key = cpu_to_le32(new_blocks[n]);
747 *branch[n].p = branch[n].key;
748 if (n == indirect_blks) {
749 current_block = new_blocks[n];
751 * End of chain, update the last new metablock of
752 * the chain to point to the new allocated
753 * data blocks numbers
755 for (i = 1; i < num; i++)
756 *(branch[n].p + i) = cpu_to_le32(++current_block);
758 BUFFER_TRACE(bh, "marking uptodate");
759 set_buffer_uptodate(bh);
762 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
763 err = ext4_handle_dirty_metadata(handle, inode, bh);
770 /* Allocation failed, free what we already allocated */
771 ext4_free_blocks(handle, inode, 0, new_blocks[0], 1, 0);
772 for (i = 1; i <= n ; i++) {
774 * branch[i].bh is newly allocated, so there is no
775 * need to revoke the block, which is why we don't
776 * need to set EXT4_FREE_BLOCKS_METADATA.
778 ext4_free_blocks(handle, inode, 0, new_blocks[i], 1,
779 EXT4_FREE_BLOCKS_FORGET);
781 for (i = n+1; i < indirect_blks; i++)
782 ext4_free_blocks(handle, inode, 0, new_blocks[i], 1, 0);
784 ext4_free_blocks(handle, inode, 0, new_blocks[i], num, 0);
790 * ext4_splice_branch - splice the allocated branch onto inode.
792 * @block: (logical) number of block we are adding
793 * @chain: chain of indirect blocks (with a missing link - see
795 * @where: location of missing link
796 * @num: number of indirect blocks we are adding
797 * @blks: number of direct blocks we are adding
799 * This function fills the missing link and does all housekeeping needed in
800 * inode (->i_blocks, etc.). In case of success we end up with the full
801 * chain to new block and return 0.
803 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
804 ext4_lblk_t block, Indirect *where, int num,
809 ext4_fsblk_t current_block;
812 * If we're splicing into a [td]indirect block (as opposed to the
813 * inode) then we need to get write access to the [td]indirect block
817 BUFFER_TRACE(where->bh, "get_write_access");
818 err = ext4_journal_get_write_access(handle, where->bh);
824 *where->p = where->key;
827 * Update the host buffer_head or inode to point to more just allocated
828 * direct blocks blocks
830 if (num == 0 && blks > 1) {
831 current_block = le32_to_cpu(where->key) + 1;
832 for (i = 1; i < blks; i++)
833 *(where->p + i) = cpu_to_le32(current_block++);
836 /* We are done with atomic stuff, now do the rest of housekeeping */
837 /* had we spliced it onto indirect block? */
840 * If we spliced it onto an indirect block, we haven't
841 * altered the inode. Note however that if it is being spliced
842 * onto an indirect block at the very end of the file (the
843 * file is growing) then we *will* alter the inode to reflect
844 * the new i_size. But that is not done here - it is done in
845 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
847 jbd_debug(5, "splicing indirect only\n");
848 BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
849 err = ext4_handle_dirty_metadata(handle, inode, where->bh);
854 * OK, we spliced it into the inode itself on a direct block.
856 ext4_mark_inode_dirty(handle, inode);
857 jbd_debug(5, "splicing direct\n");
862 for (i = 1; i <= num; i++) {
864 * branch[i].bh is newly allocated, so there is no
865 * need to revoke the block, which is why we don't
866 * need to set EXT4_FREE_BLOCKS_METADATA.
868 ext4_free_blocks(handle, inode, where[i].bh, 0, 1,
869 EXT4_FREE_BLOCKS_FORGET);
871 ext4_free_blocks(handle, inode, 0, le32_to_cpu(where[num].key),
878 * The ext4_ind_get_blocks() function handles non-extents inodes
879 * (i.e., using the traditional indirect/double-indirect i_blocks
880 * scheme) for ext4_get_blocks().
882 * Allocation strategy is simple: if we have to allocate something, we will
883 * have to go the whole way to leaf. So let's do it before attaching anything
884 * to tree, set linkage between the newborn blocks, write them if sync is
885 * required, recheck the path, free and repeat if check fails, otherwise
886 * set the last missing link (that will protect us from any truncate-generated
887 * removals - all blocks on the path are immune now) and possibly force the
888 * write on the parent block.
889 * That has a nice additional property: no special recovery from the failed
890 * allocations is needed - we simply release blocks and do not touch anything
891 * reachable from inode.
893 * `handle' can be NULL if create == 0.
895 * return > 0, # of blocks mapped or allocated.
896 * return = 0, if plain lookup failed.
897 * return < 0, error case.
899 * The ext4_ind_get_blocks() function should be called with
900 * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
901 * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
902 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
905 static int ext4_ind_get_blocks(handle_t *handle, struct inode *inode,
906 ext4_lblk_t iblock, unsigned int maxblocks,
907 struct buffer_head *bh_result,
911 ext4_lblk_t offsets[4];
916 int blocks_to_boundary = 0;
919 ext4_fsblk_t first_block = 0;
921 J_ASSERT(!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL));
922 J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
923 depth = ext4_block_to_path(inode, iblock, offsets,
924 &blocks_to_boundary);
929 partial = ext4_get_branch(inode, depth, offsets, chain, &err);
931 /* Simplest case - block found, no allocation needed */
933 first_block = le32_to_cpu(chain[depth - 1].key);
934 clear_buffer_new(bh_result);
937 while (count < maxblocks && count <= blocks_to_boundary) {
940 blk = le32_to_cpu(*(chain[depth-1].p + count));
942 if (blk == first_block + count)
950 /* Next simple case - plain lookup or failed read of indirect block */
951 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
955 * Okay, we need to do block allocation.
957 goal = ext4_find_goal(inode, iblock, partial);
959 /* the number of blocks need to allocate for [d,t]indirect blocks */
960 indirect_blks = (chain + depth) - partial - 1;
963 * Next look up the indirect map to count the totoal number of
964 * direct blocks to allocate for this branch.
966 count = ext4_blks_to_allocate(partial, indirect_blks,
967 maxblocks, blocks_to_boundary);
969 * Block out ext4_truncate while we alter the tree
971 err = ext4_alloc_branch(handle, inode, iblock, indirect_blks,
973 offsets + (partial - chain), partial);
976 * The ext4_splice_branch call will free and forget any buffers
977 * on the new chain if there is a failure, but that risks using
978 * up transaction credits, especially for bitmaps where the
979 * credits cannot be returned. Can we handle this somehow? We
980 * may need to return -EAGAIN upwards in the worst case. --sct
983 err = ext4_splice_branch(handle, inode, iblock,
984 partial, indirect_blks, count);
988 set_buffer_new(bh_result);
990 ext4_update_inode_fsync_trans(handle, inode, 1);
992 map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
993 if (count > blocks_to_boundary)
994 set_buffer_boundary(bh_result);
996 /* Clean up and exit */
997 partial = chain + depth - 1; /* the whole chain */
999 while (partial > chain) {
1000 BUFFER_TRACE(partial->bh, "call brelse");
1001 brelse(partial->bh);
1004 BUFFER_TRACE(bh_result, "returned");
1010 qsize_t *ext4_get_reserved_space(struct inode *inode)
1012 return &EXT4_I(inode)->i_reserved_quota;
1017 * Calculate the number of metadata blocks need to reserve
1018 * to allocate a new block at @lblocks for non extent file based file
1020 static int ext4_indirect_calc_metadata_amount(struct inode *inode,
1023 struct ext4_inode_info *ei = EXT4_I(inode);
1024 int dind_mask = EXT4_ADDR_PER_BLOCK(inode->i_sb) - 1;
1027 if (lblock < EXT4_NDIR_BLOCKS)
1030 lblock -= EXT4_NDIR_BLOCKS;
1032 if (ei->i_da_metadata_calc_len &&
1033 (lblock & dind_mask) == ei->i_da_metadata_calc_last_lblock) {
1034 ei->i_da_metadata_calc_len++;
1037 ei->i_da_metadata_calc_last_lblock = lblock & dind_mask;
1038 ei->i_da_metadata_calc_len = 1;
1039 blk_bits = roundup_pow_of_two(lblock + 1);
1040 return (blk_bits / EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb)) + 1;
1044 * Calculate the number of metadata blocks need to reserve
1045 * to allocate a block located at @lblock
1047 static int ext4_calc_metadata_amount(struct inode *inode, sector_t lblock)
1049 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
1050 return ext4_ext_calc_metadata_amount(inode, lblock);
1052 return ext4_indirect_calc_metadata_amount(inode, lblock);
1056 * Called with i_data_sem down, which is important since we can call
1057 * ext4_discard_preallocations() from here.
1059 void ext4_da_update_reserve_space(struct inode *inode,
1060 int used, int quota_claim)
1062 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1063 struct ext4_inode_info *ei = EXT4_I(inode);
1064 int mdb_free = 0, allocated_meta_blocks = 0;
1066 spin_lock(&ei->i_block_reservation_lock);
1067 if (unlikely(used > ei->i_reserved_data_blocks)) {
1068 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
1069 "with only %d reserved data blocks\n",
1070 __func__, inode->i_ino, used,
1071 ei->i_reserved_data_blocks);
1073 used = ei->i_reserved_data_blocks;
1076 /* Update per-inode reservations */
1077 ei->i_reserved_data_blocks -= used;
1078 used += ei->i_allocated_meta_blocks;
1079 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
1080 allocated_meta_blocks = ei->i_allocated_meta_blocks;
1081 ei->i_allocated_meta_blocks = 0;
1082 percpu_counter_sub(&sbi->s_dirtyblocks_counter, used);
1084 if (ei->i_reserved_data_blocks == 0) {
1086 * We can release all of the reserved metadata blocks
1087 * only when we have written all of the delayed
1088 * allocation blocks.
1090 mdb_free = ei->i_reserved_meta_blocks;
1091 ei->i_reserved_meta_blocks = 0;
1092 ei->i_da_metadata_calc_len = 0;
1093 percpu_counter_sub(&sbi->s_dirtyblocks_counter, mdb_free);
1095 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1097 /* Update quota subsystem */
1099 dquot_claim_block(inode, used);
1101 dquot_release_reservation_block(inode, mdb_free);
1104 * We did fallocate with an offset that is already delayed
1105 * allocated. So on delayed allocated writeback we should
1106 * not update the quota for allocated blocks. But then
1107 * converting an fallocate region to initialized region would
1108 * have caused a metadata allocation. So claim quota for
1111 if (allocated_meta_blocks)
1112 dquot_claim_block(inode, allocated_meta_blocks);
1113 dquot_release_reservation_block(inode, mdb_free + used);
1117 * If we have done all the pending block allocations and if
1118 * there aren't any writers on the inode, we can discard the
1119 * inode's preallocations.
1121 if ((ei->i_reserved_data_blocks == 0) &&
1122 (atomic_read(&inode->i_writecount) == 0))
1123 ext4_discard_preallocations(inode);
1126 static int check_block_validity(struct inode *inode, const char *msg,
1127 sector_t logical, sector_t phys, int len)
1129 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), phys, len)) {
1130 ext4_error(inode->i_sb, msg,
1131 "inode #%lu logical block %llu mapped to %llu "
1132 "(size %d)", inode->i_ino,
1133 (unsigned long long) logical,
1134 (unsigned long long) phys, len);
1141 * Return the number of contiguous dirty pages in a given inode
1142 * starting at page frame idx.
1144 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
1145 unsigned int max_pages)
1147 struct address_space *mapping = inode->i_mapping;
1149 struct pagevec pvec;
1151 int i, nr_pages, done = 0;
1155 pagevec_init(&pvec, 0);
1158 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
1159 PAGECACHE_TAG_DIRTY,
1160 (pgoff_t)PAGEVEC_SIZE);
1163 for (i = 0; i < nr_pages; i++) {
1164 struct page *page = pvec.pages[i];
1165 struct buffer_head *bh, *head;
1168 if (unlikely(page->mapping != mapping) ||
1170 PageWriteback(page) ||
1171 page->index != idx) {
1176 if (page_has_buffers(page)) {
1177 bh = head = page_buffers(page);
1179 if (!buffer_delay(bh) &&
1180 !buffer_unwritten(bh))
1182 bh = bh->b_this_page;
1183 } while (!done && (bh != head));
1190 if (num >= max_pages)
1193 pagevec_release(&pvec);
1199 * The ext4_get_blocks() function tries to look up the requested blocks,
1200 * and returns if the blocks are already mapped.
1202 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1203 * and store the allocated blocks in the result buffer head and mark it
1206 * If file type is extents based, it will call ext4_ext_get_blocks(),
1207 * Otherwise, call with ext4_ind_get_blocks() to handle indirect mapping
1210 * On success, it returns the number of blocks being mapped or allocate.
1211 * if create==0 and the blocks are pre-allocated and uninitialized block,
1212 * the result buffer head is unmapped. If the create ==1, it will make sure
1213 * the buffer head is mapped.
1215 * It returns 0 if plain look up failed (blocks have not been allocated), in
1216 * that casem, buffer head is unmapped
1218 * It returns the error in case of allocation failure.
1220 int ext4_get_blocks(handle_t *handle, struct inode *inode, sector_t block,
1221 unsigned int max_blocks, struct buffer_head *bh,
1226 clear_buffer_mapped(bh);
1227 clear_buffer_unwritten(bh);
1229 ext_debug("ext4_get_blocks(): inode %lu, flag %d, max_blocks %u,"
1230 "logical block %lu\n", inode->i_ino, flags, max_blocks,
1231 (unsigned long)block);
1233 * Try to see if we can get the block without requesting a new
1234 * file system block.
1236 down_read((&EXT4_I(inode)->i_data_sem));
1237 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1238 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1241 retval = ext4_ind_get_blocks(handle, inode, block, max_blocks,
1244 up_read((&EXT4_I(inode)->i_data_sem));
1246 if (retval > 0 && buffer_mapped(bh)) {
1247 int ret = check_block_validity(inode, "file system corruption",
1248 block, bh->b_blocknr, retval);
1253 /* If it is only a block(s) look up */
1254 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
1258 * Returns if the blocks have already allocated
1260 * Note that if blocks have been preallocated
1261 * ext4_ext_get_block() returns th create = 0
1262 * with buffer head unmapped.
1264 if (retval > 0 && buffer_mapped(bh))
1268 * When we call get_blocks without the create flag, the
1269 * BH_Unwritten flag could have gotten set if the blocks
1270 * requested were part of a uninitialized extent. We need to
1271 * clear this flag now that we are committed to convert all or
1272 * part of the uninitialized extent to be an initialized
1273 * extent. This is because we need to avoid the combination
1274 * of BH_Unwritten and BH_Mapped flags being simultaneously
1275 * set on the buffer_head.
1277 clear_buffer_unwritten(bh);
1280 * New blocks allocate and/or writing to uninitialized extent
1281 * will possibly result in updating i_data, so we take
1282 * the write lock of i_data_sem, and call get_blocks()
1283 * with create == 1 flag.
1285 down_write((&EXT4_I(inode)->i_data_sem));
1288 * if the caller is from delayed allocation writeout path
1289 * we have already reserved fs blocks for allocation
1290 * let the underlying get_block() function know to
1291 * avoid double accounting
1293 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1294 EXT4_I(inode)->i_delalloc_reserved_flag = 1;
1296 * We need to check for EXT4 here because migrate
1297 * could have changed the inode type in between
1299 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1300 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1303 retval = ext4_ind_get_blocks(handle, inode, block,
1304 max_blocks, bh, flags);
1306 if (retval > 0 && buffer_new(bh)) {
1308 * We allocated new blocks which will result in
1309 * i_data's format changing. Force the migrate
1310 * to fail by clearing migrate flags
1312 EXT4_I(inode)->i_state &= ~EXT4_STATE_EXT_MIGRATE;
1316 * Update reserved blocks/metadata blocks after successful
1317 * block allocation which had been deferred till now. We don't
1318 * support fallocate for non extent files. So we can update
1319 * reserve space here.
1322 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
1323 ext4_da_update_reserve_space(inode, retval, 1);
1325 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1326 EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1328 up_write((&EXT4_I(inode)->i_data_sem));
1329 if (retval > 0 && buffer_mapped(bh)) {
1330 int ret = check_block_validity(inode, "file system "
1331 "corruption after allocation",
1332 block, bh->b_blocknr, retval);
1339 /* Maximum number of blocks we map for direct IO at once. */
1340 #define DIO_MAX_BLOCKS 4096
1342 int ext4_get_block(struct inode *inode, sector_t iblock,
1343 struct buffer_head *bh_result, int create)
1345 handle_t *handle = ext4_journal_current_handle();
1346 int ret = 0, started = 0;
1347 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
1350 if (create && !handle) {
1351 /* Direct IO write... */
1352 if (max_blocks > DIO_MAX_BLOCKS)
1353 max_blocks = DIO_MAX_BLOCKS;
1354 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
1355 handle = ext4_journal_start(inode, dio_credits);
1356 if (IS_ERR(handle)) {
1357 ret = PTR_ERR(handle);
1363 ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
1364 create ? EXT4_GET_BLOCKS_CREATE : 0);
1366 bh_result->b_size = (ret << inode->i_blkbits);
1370 ext4_journal_stop(handle);
1376 * `handle' can be NULL if create is zero
1378 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1379 ext4_lblk_t block, int create, int *errp)
1381 struct buffer_head dummy;
1385 J_ASSERT(handle != NULL || create == 0);
1388 dummy.b_blocknr = -1000;
1389 buffer_trace_init(&dummy.b_history);
1391 flags |= EXT4_GET_BLOCKS_CREATE;
1392 err = ext4_get_blocks(handle, inode, block, 1, &dummy, flags);
1394 * ext4_get_blocks() returns number of blocks mapped. 0 in
1403 if (!err && buffer_mapped(&dummy)) {
1404 struct buffer_head *bh;
1405 bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
1410 if (buffer_new(&dummy)) {
1411 J_ASSERT(create != 0);
1412 J_ASSERT(handle != NULL);
1415 * Now that we do not always journal data, we should
1416 * keep in mind whether this should always journal the
1417 * new buffer as metadata. For now, regular file
1418 * writes use ext4_get_block instead, so it's not a
1422 BUFFER_TRACE(bh, "call get_create_access");
1423 fatal = ext4_journal_get_create_access(handle, bh);
1424 if (!fatal && !buffer_uptodate(bh)) {
1425 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1426 set_buffer_uptodate(bh);
1429 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1430 err = ext4_handle_dirty_metadata(handle, inode, bh);
1434 BUFFER_TRACE(bh, "not a new buffer");
1447 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1448 ext4_lblk_t block, int create, int *err)
1450 struct buffer_head *bh;
1452 bh = ext4_getblk(handle, inode, block, create, err);
1455 if (buffer_uptodate(bh))
1457 ll_rw_block(READ_META, 1, &bh);
1459 if (buffer_uptodate(bh))
1466 static int walk_page_buffers(handle_t *handle,
1467 struct buffer_head *head,
1471 int (*fn)(handle_t *handle,
1472 struct buffer_head *bh))
1474 struct buffer_head *bh;
1475 unsigned block_start, block_end;
1476 unsigned blocksize = head->b_size;
1478 struct buffer_head *next;
1480 for (bh = head, block_start = 0;
1481 ret == 0 && (bh != head || !block_start);
1482 block_start = block_end, bh = next) {
1483 next = bh->b_this_page;
1484 block_end = block_start + blocksize;
1485 if (block_end <= from || block_start >= to) {
1486 if (partial && !buffer_uptodate(bh))
1490 err = (*fn)(handle, bh);
1498 * To preserve ordering, it is essential that the hole instantiation and
1499 * the data write be encapsulated in a single transaction. We cannot
1500 * close off a transaction and start a new one between the ext4_get_block()
1501 * and the commit_write(). So doing the jbd2_journal_start at the start of
1502 * prepare_write() is the right place.
1504 * Also, this function can nest inside ext4_writepage() ->
1505 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1506 * has generated enough buffer credits to do the whole page. So we won't
1507 * block on the journal in that case, which is good, because the caller may
1510 * By accident, ext4 can be reentered when a transaction is open via
1511 * quota file writes. If we were to commit the transaction while thus
1512 * reentered, there can be a deadlock - we would be holding a quota
1513 * lock, and the commit would never complete if another thread had a
1514 * transaction open and was blocking on the quota lock - a ranking
1517 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1518 * will _not_ run commit under these circumstances because handle->h_ref
1519 * is elevated. We'll still have enough credits for the tiny quotafile
1522 static int do_journal_get_write_access(handle_t *handle,
1523 struct buffer_head *bh)
1525 if (!buffer_mapped(bh) || buffer_freed(bh))
1527 return ext4_journal_get_write_access(handle, bh);
1531 * Truncate blocks that were not used by write. We have to truncate the
1532 * pagecache as well so that corresponding buffers get properly unmapped.
1534 static void ext4_truncate_failed_write(struct inode *inode)
1536 truncate_inode_pages(inode->i_mapping, inode->i_size);
1537 ext4_truncate(inode);
1540 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1541 loff_t pos, unsigned len, unsigned flags,
1542 struct page **pagep, void **fsdata)
1544 struct inode *inode = mapping->host;
1545 int ret, needed_blocks;
1552 trace_ext4_write_begin(inode, pos, len, flags);
1554 * Reserve one block more for addition to orphan list in case
1555 * we allocate blocks but write fails for some reason
1557 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1558 index = pos >> PAGE_CACHE_SHIFT;
1559 from = pos & (PAGE_CACHE_SIZE - 1);
1563 handle = ext4_journal_start(inode, needed_blocks);
1564 if (IS_ERR(handle)) {
1565 ret = PTR_ERR(handle);
1569 /* We cannot recurse into the filesystem as the transaction is already
1571 flags |= AOP_FLAG_NOFS;
1573 page = grab_cache_page_write_begin(mapping, index, flags);
1575 ext4_journal_stop(handle);
1581 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1584 if (!ret && ext4_should_journal_data(inode)) {
1585 ret = walk_page_buffers(handle, page_buffers(page),
1586 from, to, NULL, do_journal_get_write_access);
1591 page_cache_release(page);
1593 * block_write_begin may have instantiated a few blocks
1594 * outside i_size. Trim these off again. Don't need
1595 * i_size_read because we hold i_mutex.
1597 * Add inode to orphan list in case we crash before
1600 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1601 ext4_orphan_add(handle, inode);
1603 ext4_journal_stop(handle);
1604 if (pos + len > inode->i_size) {
1605 ext4_truncate_failed_write(inode);
1607 * If truncate failed early the inode might
1608 * still be on the orphan list; we need to
1609 * make sure the inode is removed from the
1610 * orphan list in that case.
1613 ext4_orphan_del(NULL, inode);
1617 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1623 /* For write_end() in data=journal mode */
1624 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1626 if (!buffer_mapped(bh) || buffer_freed(bh))
1628 set_buffer_uptodate(bh);
1629 return ext4_handle_dirty_metadata(handle, NULL, bh);
1632 static int ext4_generic_write_end(struct file *file,
1633 struct address_space *mapping,
1634 loff_t pos, unsigned len, unsigned copied,
1635 struct page *page, void *fsdata)
1637 int i_size_changed = 0;
1638 struct inode *inode = mapping->host;
1639 handle_t *handle = ext4_journal_current_handle();
1641 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1644 * No need to use i_size_read() here, the i_size
1645 * cannot change under us because we hold i_mutex.
1647 * But it's important to update i_size while still holding page lock:
1648 * page writeout could otherwise come in and zero beyond i_size.
1650 if (pos + copied > inode->i_size) {
1651 i_size_write(inode, pos + copied);
1655 if (pos + copied > EXT4_I(inode)->i_disksize) {
1656 /* We need to mark inode dirty even if
1657 * new_i_size is less that inode->i_size
1658 * bu greater than i_disksize.(hint delalloc)
1660 ext4_update_i_disksize(inode, (pos + copied));
1664 page_cache_release(page);
1667 * Don't mark the inode dirty under page lock. First, it unnecessarily
1668 * makes the holding time of page lock longer. Second, it forces lock
1669 * ordering of page lock and transaction start for journaling
1673 ext4_mark_inode_dirty(handle, inode);
1679 * We need to pick up the new inode size which generic_commit_write gave us
1680 * `file' can be NULL - eg, when called from page_symlink().
1682 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1683 * buffers are managed internally.
1685 static int ext4_ordered_write_end(struct file *file,
1686 struct address_space *mapping,
1687 loff_t pos, unsigned len, unsigned copied,
1688 struct page *page, void *fsdata)
1690 handle_t *handle = ext4_journal_current_handle();
1691 struct inode *inode = mapping->host;
1694 trace_ext4_ordered_write_end(inode, pos, len, copied);
1695 ret = ext4_jbd2_file_inode(handle, inode);
1698 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1701 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1702 /* if we have allocated more blocks and copied
1703 * less. We will have blocks allocated outside
1704 * inode->i_size. So truncate them
1706 ext4_orphan_add(handle, inode);
1710 ret2 = ext4_journal_stop(handle);
1714 if (pos + len > inode->i_size) {
1715 ext4_truncate_failed_write(inode);
1717 * If truncate failed early the inode might still be
1718 * on the orphan list; we need to make sure the inode
1719 * is removed from the orphan list in that case.
1722 ext4_orphan_del(NULL, inode);
1726 return ret ? ret : copied;
1729 static int ext4_writeback_write_end(struct file *file,
1730 struct address_space *mapping,
1731 loff_t pos, unsigned len, unsigned copied,
1732 struct page *page, void *fsdata)
1734 handle_t *handle = ext4_journal_current_handle();
1735 struct inode *inode = mapping->host;
1738 trace_ext4_writeback_write_end(inode, pos, len, copied);
1739 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1742 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1743 /* if we have allocated more blocks and copied
1744 * less. We will have blocks allocated outside
1745 * inode->i_size. So truncate them
1747 ext4_orphan_add(handle, inode);
1752 ret2 = ext4_journal_stop(handle);
1756 if (pos + len > inode->i_size) {
1757 ext4_truncate_failed_write(inode);
1759 * If truncate failed early the inode might still be
1760 * on the orphan list; we need to make sure the inode
1761 * is removed from the orphan list in that case.
1764 ext4_orphan_del(NULL, inode);
1767 return ret ? ret : copied;
1770 static int ext4_journalled_write_end(struct file *file,
1771 struct address_space *mapping,
1772 loff_t pos, unsigned len, unsigned copied,
1773 struct page *page, void *fsdata)
1775 handle_t *handle = ext4_journal_current_handle();
1776 struct inode *inode = mapping->host;
1782 trace_ext4_journalled_write_end(inode, pos, len, copied);
1783 from = pos & (PAGE_CACHE_SIZE - 1);
1787 if (!PageUptodate(page))
1789 page_zero_new_buffers(page, from+copied, to);
1792 ret = walk_page_buffers(handle, page_buffers(page), from,
1793 to, &partial, write_end_fn);
1795 SetPageUptodate(page);
1796 new_i_size = pos + copied;
1797 if (new_i_size > inode->i_size)
1798 i_size_write(inode, pos+copied);
1799 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
1800 if (new_i_size > EXT4_I(inode)->i_disksize) {
1801 ext4_update_i_disksize(inode, new_i_size);
1802 ret2 = ext4_mark_inode_dirty(handle, inode);
1808 page_cache_release(page);
1809 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1810 /* if we have allocated more blocks and copied
1811 * less. We will have blocks allocated outside
1812 * inode->i_size. So truncate them
1814 ext4_orphan_add(handle, inode);
1816 ret2 = ext4_journal_stop(handle);
1819 if (pos + len > inode->i_size) {
1820 ext4_truncate_failed_write(inode);
1822 * If truncate failed early the inode might still be
1823 * on the orphan list; we need to make sure the inode
1824 * is removed from the orphan list in that case.
1827 ext4_orphan_del(NULL, inode);
1830 return ret ? ret : copied;
1834 * Reserve a single block located at lblock
1836 static int ext4_da_reserve_space(struct inode *inode, sector_t lblock)
1839 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1840 struct ext4_inode_info *ei = EXT4_I(inode);
1841 unsigned long md_needed, md_reserved;
1845 * recalculate the amount of metadata blocks to reserve
1846 * in order to allocate nrblocks
1847 * worse case is one extent per block
1850 spin_lock(&ei->i_block_reservation_lock);
1851 md_reserved = ei->i_reserved_meta_blocks;
1852 md_needed = ext4_calc_metadata_amount(inode, lblock);
1853 spin_unlock(&ei->i_block_reservation_lock);
1856 * Make quota reservation here to prevent quota overflow
1857 * later. Real quota accounting is done at pages writeout
1860 ret = dquot_reserve_block(inode, md_needed + 1);
1864 if (ext4_claim_free_blocks(sbi, md_needed + 1)) {
1865 dquot_release_reservation_block(inode, md_needed + 1);
1866 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1872 spin_lock(&ei->i_block_reservation_lock);
1873 ei->i_reserved_data_blocks++;
1874 ei->i_reserved_meta_blocks += md_needed;
1875 spin_unlock(&ei->i_block_reservation_lock);
1877 return 0; /* success */
1880 static void ext4_da_release_space(struct inode *inode, int to_free)
1882 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1883 struct ext4_inode_info *ei = EXT4_I(inode);
1886 return; /* Nothing to release, exit */
1888 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1890 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1892 * if there aren't enough reserved blocks, then the
1893 * counter is messed up somewhere. Since this
1894 * function is called from invalidate page, it's
1895 * harmless to return without any action.
1897 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1898 "ino %lu, to_free %d with only %d reserved "
1899 "data blocks\n", inode->i_ino, to_free,
1900 ei->i_reserved_data_blocks);
1902 to_free = ei->i_reserved_data_blocks;
1904 ei->i_reserved_data_blocks -= to_free;
1906 if (ei->i_reserved_data_blocks == 0) {
1908 * We can release all of the reserved metadata blocks
1909 * only when we have written all of the delayed
1910 * allocation blocks.
1912 to_free += ei->i_reserved_meta_blocks;
1913 ei->i_reserved_meta_blocks = 0;
1914 ei->i_da_metadata_calc_len = 0;
1917 /* update fs dirty blocks counter */
1918 percpu_counter_sub(&sbi->s_dirtyblocks_counter, to_free);
1920 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1922 dquot_release_reservation_block(inode, to_free);
1925 static void ext4_da_page_release_reservation(struct page *page,
1926 unsigned long offset)
1929 struct buffer_head *head, *bh;
1930 unsigned int curr_off = 0;
1932 head = page_buffers(page);
1935 unsigned int next_off = curr_off + bh->b_size;
1937 if ((offset <= curr_off) && (buffer_delay(bh))) {
1939 clear_buffer_delay(bh);
1941 curr_off = next_off;
1942 } while ((bh = bh->b_this_page) != head);
1943 ext4_da_release_space(page->mapping->host, to_release);
1947 * Delayed allocation stuff
1951 * mpage_da_submit_io - walks through extent of pages and try to write
1952 * them with writepage() call back
1954 * @mpd->inode: inode
1955 * @mpd->first_page: first page of the extent
1956 * @mpd->next_page: page after the last page of the extent
1958 * By the time mpage_da_submit_io() is called we expect all blocks
1959 * to be allocated. this may be wrong if allocation failed.
1961 * As pages are already locked by write_cache_pages(), we can't use it
1963 static int mpage_da_submit_io(struct mpage_da_data *mpd)
1966 struct pagevec pvec;
1967 unsigned long index, end;
1968 int ret = 0, err, nr_pages, i;
1969 struct inode *inode = mpd->inode;
1970 struct address_space *mapping = inode->i_mapping;
1972 BUG_ON(mpd->next_page <= mpd->first_page);
1974 * We need to start from the first_page to the next_page - 1
1975 * to make sure we also write the mapped dirty buffer_heads.
1976 * If we look at mpd->b_blocknr we would only be looking
1977 * at the currently mapped buffer_heads.
1979 index = mpd->first_page;
1980 end = mpd->next_page - 1;
1982 pagevec_init(&pvec, 0);
1983 while (index <= end) {
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));
1998 pages_skipped = mpd->wbc->pages_skipped;
1999 err = mapping->a_ops->writepage(page, mpd->wbc);
2000 if (!err && (pages_skipped == mpd->wbc->pages_skipped))
2002 * have successfully written the page
2003 * without skipping the same
2005 mpd->pages_written++;
2007 * In error case, we have to continue because
2008 * remaining pages are still locked
2009 * XXX: unlock and re-dirty them?
2014 pagevec_release(&pvec);
2020 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
2022 * @mpd->inode - inode to walk through
2023 * @exbh->b_blocknr - first block on a disk
2024 * @exbh->b_size - amount of space in bytes
2025 * @logical - first logical block to start assignment with
2027 * the function goes through all passed space and put actual disk
2028 * block numbers into buffer heads, dropping BH_Delay and BH_Unwritten
2030 static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
2031 struct buffer_head *exbh)
2033 struct inode *inode = mpd->inode;
2034 struct address_space *mapping = inode->i_mapping;
2035 int blocks = exbh->b_size >> inode->i_blkbits;
2036 sector_t pblock = exbh->b_blocknr, cur_logical;
2037 struct buffer_head *head, *bh;
2039 struct pagevec pvec;
2042 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2043 end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2044 cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
2046 pagevec_init(&pvec, 0);
2048 while (index <= end) {
2049 /* XXX: optimize tail */
2050 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2053 for (i = 0; i < nr_pages; i++) {
2054 struct page *page = pvec.pages[i];
2056 index = page->index;
2061 BUG_ON(!PageLocked(page));
2062 BUG_ON(PageWriteback(page));
2063 BUG_ON(!page_has_buffers(page));
2065 bh = page_buffers(page);
2068 /* skip blocks out of the range */
2070 if (cur_logical >= logical)
2073 } while ((bh = bh->b_this_page) != head);
2076 if (cur_logical >= logical + blocks)
2079 if (buffer_delay(bh) ||
2080 buffer_unwritten(bh)) {
2082 BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
2084 if (buffer_delay(bh)) {
2085 clear_buffer_delay(bh);
2086 bh->b_blocknr = pblock;
2089 * unwritten already should have
2090 * blocknr assigned. Verify that
2092 clear_buffer_unwritten(bh);
2093 BUG_ON(bh->b_blocknr != pblock);
2096 } else if (buffer_mapped(bh))
2097 BUG_ON(bh->b_blocknr != pblock);
2101 } while ((bh = bh->b_this_page) != head);
2103 pagevec_release(&pvec);
2109 * __unmap_underlying_blocks - just a helper function to unmap
2110 * set of blocks described by @bh
2112 static inline void __unmap_underlying_blocks(struct inode *inode,
2113 struct buffer_head *bh)
2115 struct block_device *bdev = inode->i_sb->s_bdev;
2118 blocks = bh->b_size >> inode->i_blkbits;
2119 for (i = 0; i < blocks; i++)
2120 unmap_underlying_metadata(bdev, bh->b_blocknr + i);
2123 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
2124 sector_t logical, long blk_cnt)
2128 struct pagevec pvec;
2129 struct inode *inode = mpd->inode;
2130 struct address_space *mapping = inode->i_mapping;
2132 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2133 end = (logical + blk_cnt - 1) >>
2134 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2135 while (index <= end) {
2136 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2139 for (i = 0; i < nr_pages; i++) {
2140 struct page *page = pvec.pages[i];
2141 index = page->index;
2146 BUG_ON(!PageLocked(page));
2147 BUG_ON(PageWriteback(page));
2148 block_invalidatepage(page, 0);
2149 ClearPageUptodate(page);
2156 static void ext4_print_free_blocks(struct inode *inode)
2158 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2159 printk(KERN_CRIT "Total free blocks count %lld\n",
2160 ext4_count_free_blocks(inode->i_sb));
2161 printk(KERN_CRIT "Free/Dirty block details\n");
2162 printk(KERN_CRIT "free_blocks=%lld\n",
2163 (long long) percpu_counter_sum(&sbi->s_freeblocks_counter));
2164 printk(KERN_CRIT "dirty_blocks=%lld\n",
2165 (long long) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
2166 printk(KERN_CRIT "Block reservation details\n");
2167 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
2168 EXT4_I(inode)->i_reserved_data_blocks);
2169 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
2170 EXT4_I(inode)->i_reserved_meta_blocks);
2175 * mpage_da_map_blocks - go through given space
2177 * @mpd - bh describing space
2179 * The function skips space we know is already mapped to disk blocks.
2182 static int mpage_da_map_blocks(struct mpage_da_data *mpd)
2184 int err, blks, get_blocks_flags;
2185 struct buffer_head new;
2186 sector_t next = mpd->b_blocknr;
2187 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
2188 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
2189 handle_t *handle = NULL;
2192 * We consider only non-mapped and non-allocated blocks
2194 if ((mpd->b_state & (1 << BH_Mapped)) &&
2195 !(mpd->b_state & (1 << BH_Delay)) &&
2196 !(mpd->b_state & (1 << BH_Unwritten)))
2200 * If we didn't accumulate anything to write simply return
2205 handle = ext4_journal_current_handle();
2209 * Call ext4_get_blocks() to allocate any delayed allocation
2210 * blocks, or to convert an uninitialized extent to be
2211 * initialized (in the case where we have written into
2212 * one or more preallocated blocks).
2214 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
2215 * indicate that we are on the delayed allocation path. This
2216 * affects functions in many different parts of the allocation
2217 * call path. This flag exists primarily because we don't
2218 * want to change *many* call functions, so ext4_get_blocks()
2219 * will set the magic i_delalloc_reserved_flag once the
2220 * inode's allocation semaphore is taken.
2222 * If the blocks in questions were delalloc blocks, set
2223 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
2224 * variables are updated after the blocks have been allocated.
2227 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
2228 if (mpd->b_state & (1 << BH_Delay))
2229 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2231 blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks,
2232 &new, get_blocks_flags);
2236 * If get block returns with error we simply
2237 * return. Later writepage will redirty the page and
2238 * writepages will find the dirty page again
2243 if (err == -ENOSPC &&
2244 ext4_count_free_blocks(mpd->inode->i_sb)) {
2250 * get block failure will cause us to loop in
2251 * writepages, because a_ops->writepage won't be able
2252 * to make progress. The page will be redirtied by
2253 * writepage and writepages will again try to write
2256 ext4_msg(mpd->inode->i_sb, KERN_CRIT,
2257 "delayed block allocation failed for inode %lu at "
2258 "logical offset %llu with max blocks %zd with "
2259 "error %d\n", mpd->inode->i_ino,
2260 (unsigned long long) next,
2261 mpd->b_size >> mpd->inode->i_blkbits, err);
2262 printk(KERN_CRIT "This should not happen!! "
2263 "Data will be lost\n");
2264 if (err == -ENOSPC) {
2265 ext4_print_free_blocks(mpd->inode);
2267 /* invalidate all the pages */
2268 ext4_da_block_invalidatepages(mpd, next,
2269 mpd->b_size >> mpd->inode->i_blkbits);
2274 new.b_size = (blks << mpd->inode->i_blkbits);
2276 if (buffer_new(&new))
2277 __unmap_underlying_blocks(mpd->inode, &new);
2280 * If blocks are delayed marked, we need to
2281 * put actual blocknr and drop delayed bit
2283 if ((mpd->b_state & (1 << BH_Delay)) ||
2284 (mpd->b_state & (1 << BH_Unwritten)))
2285 mpage_put_bnr_to_bhs(mpd, next, &new);
2287 if (ext4_should_order_data(mpd->inode)) {
2288 err = ext4_jbd2_file_inode(handle, mpd->inode);
2294 * Update on-disk size along with block allocation.
2296 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
2297 if (disksize > i_size_read(mpd->inode))
2298 disksize = i_size_read(mpd->inode);
2299 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
2300 ext4_update_i_disksize(mpd->inode, disksize);
2301 return ext4_mark_inode_dirty(handle, mpd->inode);
2307 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
2308 (1 << BH_Delay) | (1 << BH_Unwritten))
2311 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
2313 * @mpd->lbh - extent of blocks
2314 * @logical - logical number of the block in the file
2315 * @bh - bh of the block (used to access block's state)
2317 * the function is used to collect contig. blocks in same state
2319 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
2320 sector_t logical, size_t b_size,
2321 unsigned long b_state)
2324 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
2326 /* check if thereserved journal credits might overflow */
2327 if (!(EXT4_I(mpd->inode)->i_flags & EXT4_EXTENTS_FL)) {
2328 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2330 * With non-extent format we are limited by the journal
2331 * credit available. Total credit needed to insert
2332 * nrblocks contiguous blocks is dependent on the
2333 * nrblocks. So limit nrblocks.
2336 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2337 EXT4_MAX_TRANS_DATA) {
2339 * Adding the new buffer_head would make it cross the
2340 * allowed limit for which we have journal credit
2341 * reserved. So limit the new bh->b_size
2343 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2344 mpd->inode->i_blkbits;
2345 /* we will do mpage_da_submit_io in the next loop */
2349 * First block in the extent
2351 if (mpd->b_size == 0) {
2352 mpd->b_blocknr = logical;
2353 mpd->b_size = b_size;
2354 mpd->b_state = b_state & BH_FLAGS;
2358 next = mpd->b_blocknr + nrblocks;
2360 * Can we merge the block to our big extent?
2362 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
2363 mpd->b_size += b_size;
2369 * We couldn't merge the block to our extent, so we
2370 * need to flush current extent and start new one
2372 if (mpage_da_map_blocks(mpd) == 0)
2373 mpage_da_submit_io(mpd);
2378 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
2380 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
2384 * __mpage_da_writepage - finds extent of pages and blocks
2386 * @page: page to consider
2387 * @wbc: not used, we just follow rules
2390 * The function finds extents of pages and scan them for all blocks.
2392 static int __mpage_da_writepage(struct page *page,
2393 struct writeback_control *wbc, void *data)
2395 struct mpage_da_data *mpd = data;
2396 struct inode *inode = mpd->inode;
2397 struct buffer_head *bh, *head;
2402 * Rest of the page in the page_vec
2403 * redirty then and skip then. We will
2404 * try to write them again after
2405 * starting a new transaction
2407 redirty_page_for_writepage(wbc, page);
2409 return MPAGE_DA_EXTENT_TAIL;
2412 * Can we merge this page to current extent?
2414 if (mpd->next_page != page->index) {
2416 * Nope, we can't. So, we map non-allocated blocks
2417 * and start IO on them using writepage()
2419 if (mpd->next_page != mpd->first_page) {
2420 if (mpage_da_map_blocks(mpd) == 0)
2421 mpage_da_submit_io(mpd);
2423 * skip rest of the page in the page_vec
2426 redirty_page_for_writepage(wbc, page);
2428 return MPAGE_DA_EXTENT_TAIL;
2432 * Start next extent of pages ...
2434 mpd->first_page = page->index;
2444 mpd->next_page = page->index + 1;
2445 logical = (sector_t) page->index <<
2446 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2448 if (!page_has_buffers(page)) {
2449 mpage_add_bh_to_extent(mpd, logical, PAGE_CACHE_SIZE,
2450 (1 << BH_Dirty) | (1 << BH_Uptodate));
2452 return MPAGE_DA_EXTENT_TAIL;
2455 * Page with regular buffer heads, just add all dirty ones
2457 head = page_buffers(page);
2460 BUG_ON(buffer_locked(bh));
2462 * We need to try to allocate
2463 * unmapped blocks in the same page.
2464 * Otherwise we won't make progress
2465 * with the page in ext4_writepage
2467 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2468 mpage_add_bh_to_extent(mpd, logical,
2472 return MPAGE_DA_EXTENT_TAIL;
2473 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2475 * mapped dirty buffer. We need to update
2476 * the b_state because we look at
2477 * b_state in mpage_da_map_blocks. We don't
2478 * update b_size because if we find an
2479 * unmapped buffer_head later we need to
2480 * use the b_state flag of that buffer_head.
2482 if (mpd->b_size == 0)
2483 mpd->b_state = bh->b_state & BH_FLAGS;
2486 } while ((bh = bh->b_this_page) != head);
2493 * This is a special get_blocks_t callback which is used by
2494 * ext4_da_write_begin(). It will either return mapped block or
2495 * reserve space for a single block.
2497 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2498 * We also have b_blocknr = -1 and b_bdev initialized properly
2500 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2501 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2502 * initialized properly.
2504 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2505 struct buffer_head *bh_result, int create)
2508 sector_t invalid_block = ~((sector_t) 0xffff);
2510 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2513 BUG_ON(create == 0);
2514 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2517 * first, we need to know whether the block is allocated already
2518 * preallocated blocks are unmapped but should treated
2519 * the same as allocated blocks.
2521 ret = ext4_get_blocks(NULL, inode, iblock, 1, bh_result, 0);
2522 if ((ret == 0) && !buffer_delay(bh_result)) {
2523 /* the block isn't (pre)allocated yet, let's reserve space */
2525 * XXX: __block_prepare_write() unmaps passed block,
2528 ret = ext4_da_reserve_space(inode, iblock);
2530 /* not enough space to reserve */
2533 map_bh(bh_result, inode->i_sb, invalid_block);
2534 set_buffer_new(bh_result);
2535 set_buffer_delay(bh_result);
2536 } else if (ret > 0) {
2537 bh_result->b_size = (ret << inode->i_blkbits);
2538 if (buffer_unwritten(bh_result)) {
2539 /* A delayed write to unwritten bh should
2540 * be marked new and mapped. Mapped ensures
2541 * that we don't do get_block multiple times
2542 * when we write to the same offset and new
2543 * ensures that we do proper zero out for
2546 set_buffer_new(bh_result);
2547 set_buffer_mapped(bh_result);
2556 * This function is used as a standard get_block_t calback function
2557 * when there is no desire to allocate any blocks. It is used as a
2558 * callback function for block_prepare_write(), nobh_writepage(), and
2559 * block_write_full_page(). These functions should only try to map a
2560 * single block at a time.
2562 * Since this function doesn't do block allocations even if the caller
2563 * requests it by passing in create=1, it is critically important that
2564 * any caller checks to make sure that any buffer heads are returned
2565 * by this function are either all already mapped or marked for
2566 * delayed allocation before calling nobh_writepage() or
2567 * block_write_full_page(). Otherwise, b_blocknr could be left
2568 * unitialized, and the page write functions will be taken by
2571 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
2572 struct buffer_head *bh_result, int create)
2575 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2577 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2580 * we don't want to do block allocation in writepage
2581 * so call get_block_wrap with create = 0
2583 ret = ext4_get_blocks(NULL, inode, iblock, max_blocks, bh_result, 0);
2585 bh_result->b_size = (ret << inode->i_blkbits);
2591 static int bget_one(handle_t *handle, struct buffer_head *bh)
2597 static int bput_one(handle_t *handle, struct buffer_head *bh)
2603 static int __ext4_journalled_writepage(struct page *page,
2606 struct address_space *mapping = page->mapping;
2607 struct inode *inode = mapping->host;
2608 struct buffer_head *page_bufs;
2609 handle_t *handle = NULL;
2613 page_bufs = page_buffers(page);
2615 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
2616 /* As soon as we unlock the page, it can go away, but we have
2617 * references to buffers so we are safe */
2620 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
2621 if (IS_ERR(handle)) {
2622 ret = PTR_ERR(handle);
2626 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2627 do_journal_get_write_access);
2629 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2633 err = ext4_journal_stop(handle);
2637 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
2638 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
2644 * Note that we don't need to start a transaction unless we're journaling data
2645 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2646 * need to file the inode to the transaction's list in ordered mode because if
2647 * we are writing back data added by write(), the inode is already there and if
2648 * we are writing back data modified via mmap(), noone guarantees in which
2649 * transaction the data will hit the disk. In case we are journaling data, we
2650 * cannot start transaction directly because transaction start ranks above page
2651 * lock so we have to do some magic.
2653 * This function can get called via...
2654 * - ext4_da_writepages after taking page lock (have journal handle)
2655 * - journal_submit_inode_data_buffers (no journal handle)
2656 * - shrink_page_list via pdflush (no journal handle)
2657 * - grab_page_cache when doing write_begin (have journal handle)
2659 * We don't do any block allocation in this function. If we have page with
2660 * multiple blocks we need to write those buffer_heads that are mapped. This
2661 * is important for mmaped based write. So if we do with blocksize 1K
2662 * truncate(f, 1024);
2663 * a = mmap(f, 0, 4096);
2665 * truncate(f, 4096);
2666 * we have in the page first buffer_head mapped via page_mkwrite call back
2667 * but other bufer_heads would be unmapped but dirty(dirty done via the
2668 * do_wp_page). So writepage should write the first block. If we modify
2669 * the mmap area beyond 1024 we will again get a page_fault and the
2670 * page_mkwrite callback will do the block allocation and mark the
2671 * buffer_heads mapped.
2673 * We redirty the page if we have any buffer_heads that is either delay or
2674 * unwritten in the page.
2676 * We can get recursively called as show below.
2678 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2681 * But since we don't do any block allocation we should not deadlock.
2682 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2684 static int ext4_writepage(struct page *page,
2685 struct writeback_control *wbc)
2690 struct buffer_head *page_bufs;
2691 struct inode *inode = page->mapping->host;
2693 trace_ext4_writepage(inode, page);
2694 size = i_size_read(inode);
2695 if (page->index == size >> PAGE_CACHE_SHIFT)
2696 len = size & ~PAGE_CACHE_MASK;
2698 len = PAGE_CACHE_SIZE;
2700 if (page_has_buffers(page)) {
2701 page_bufs = page_buffers(page);
2702 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2703 ext4_bh_delay_or_unwritten)) {
2705 * We don't want to do block allocation
2706 * So redirty the page and return
2707 * We may reach here when we do a journal commit
2708 * via journal_submit_inode_data_buffers.
2709 * If we don't have mapping block we just ignore
2710 * them. We can also reach here via shrink_page_list
2712 redirty_page_for_writepage(wbc, page);
2718 * The test for page_has_buffers() is subtle:
2719 * We know the page is dirty but it lost buffers. That means
2720 * that at some moment in time after write_begin()/write_end()
2721 * has been called all buffers have been clean and thus they
2722 * must have been written at least once. So they are all
2723 * mapped and we can happily proceed with mapping them
2724 * and writing the page.
2726 * Try to initialize the buffer_heads and check whether
2727 * all are mapped and non delay. We don't want to
2728 * do block allocation here.
2730 ret = block_prepare_write(page, 0, len,
2731 noalloc_get_block_write);
2733 page_bufs = page_buffers(page);
2734 /* check whether all are mapped and non delay */
2735 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2736 ext4_bh_delay_or_unwritten)) {
2737 redirty_page_for_writepage(wbc, page);
2743 * We can't do block allocation here
2744 * so just redity the page and unlock
2747 redirty_page_for_writepage(wbc, page);
2751 /* now mark the buffer_heads as dirty and uptodate */
2752 block_commit_write(page, 0, len);
2755 if (PageChecked(page) && ext4_should_journal_data(inode)) {
2757 * It's mmapped pagecache. Add buffers and journal it. There
2758 * doesn't seem much point in redirtying the page here.
2760 ClearPageChecked(page);
2761 return __ext4_journalled_writepage(page, len);
2764 if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
2765 ret = nobh_writepage(page, noalloc_get_block_write, wbc);
2767 ret = block_write_full_page(page, noalloc_get_block_write,
2774 * This is called via ext4_da_writepages() to
2775 * calulate the total number of credits to reserve to fit
2776 * a single extent allocation into a single transaction,
2777 * ext4_da_writpeages() will loop calling this before
2778 * the block allocation.
2781 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2783 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2786 * With non-extent format the journal credit needed to
2787 * insert nrblocks contiguous block is dependent on
2788 * number of contiguous block. So we will limit
2789 * number of contiguous block to a sane value
2791 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) &&
2792 (max_blocks > EXT4_MAX_TRANS_DATA))
2793 max_blocks = EXT4_MAX_TRANS_DATA;
2795 return ext4_chunk_trans_blocks(inode, max_blocks);
2798 static int ext4_da_writepages(struct address_space *mapping,
2799 struct writeback_control *wbc)
2802 int range_whole = 0;
2803 handle_t *handle = NULL;
2804 struct mpage_da_data mpd;
2805 struct inode *inode = mapping->host;
2806 int no_nrwrite_index_update;
2807 int pages_written = 0;
2809 unsigned int max_pages;
2810 int range_cyclic, cycled = 1, io_done = 0;
2811 int needed_blocks, ret = 0;
2812 long desired_nr_to_write, nr_to_writebump = 0;
2813 loff_t range_start = wbc->range_start;
2814 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2816 trace_ext4_da_writepages(inode, wbc);
2819 * No pages to write? This is mainly a kludge to avoid starting
2820 * a transaction for special inodes like journal inode on last iput()
2821 * because that could violate lock ordering on umount
2823 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2827 * If the filesystem has aborted, it is read-only, so return
2828 * right away instead of dumping stack traces later on that
2829 * will obscure the real source of the problem. We test
2830 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2831 * the latter could be true if the filesystem is mounted
2832 * read-only, and in that case, ext4_da_writepages should
2833 * *never* be called, so if that ever happens, we would want
2836 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2839 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2842 range_cyclic = wbc->range_cyclic;
2843 if (wbc->range_cyclic) {
2844 index = mapping->writeback_index;
2847 wbc->range_start = index << PAGE_CACHE_SHIFT;
2848 wbc->range_end = LLONG_MAX;
2849 wbc->range_cyclic = 0;
2851 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2854 * This works around two forms of stupidity. The first is in
2855 * the writeback code, which caps the maximum number of pages
2856 * written to be 1024 pages. This is wrong on multiple
2857 * levels; different architectues have a different page size,
2858 * which changes the maximum amount of data which gets
2859 * written. Secondly, 4 megabytes is way too small. XFS
2860 * forces this value to be 16 megabytes by multiplying
2861 * nr_to_write parameter by four, and then relies on its
2862 * allocator to allocate larger extents to make them
2863 * contiguous. Unfortunately this brings us to the second
2864 * stupidity, which is that ext4's mballoc code only allocates
2865 * at most 2048 blocks. So we force contiguous writes up to
2866 * the number of dirty blocks in the inode, or
2867 * sbi->max_writeback_mb_bump whichever is smaller.
2869 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2870 if (!range_cyclic && range_whole)
2871 desired_nr_to_write = wbc->nr_to_write * 8;
2873 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2875 if (desired_nr_to_write > max_pages)
2876 desired_nr_to_write = max_pages;
2878 if (wbc->nr_to_write < desired_nr_to_write) {
2879 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2880 wbc->nr_to_write = desired_nr_to_write;
2884 mpd.inode = mapping->host;
2887 * we don't want write_cache_pages to update
2888 * nr_to_write and writeback_index
2890 no_nrwrite_index_update = wbc->no_nrwrite_index_update;
2891 wbc->no_nrwrite_index_update = 1;
2892 pages_skipped = wbc->pages_skipped;
2895 while (!ret && wbc->nr_to_write > 0) {
2898 * we insert one extent at a time. So we need
2899 * credit needed for single extent allocation.
2900 * journalled mode is currently not supported
2903 BUG_ON(ext4_should_journal_data(inode));
2904 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2906 /* start a new transaction*/
2907 handle = ext4_journal_start(inode, needed_blocks);
2908 if (IS_ERR(handle)) {
2909 ret = PTR_ERR(handle);
2910 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2911 "%ld pages, ino %lu; err %d\n", __func__,
2912 wbc->nr_to_write, inode->i_ino, ret);
2913 goto out_writepages;
2917 * Now call __mpage_da_writepage to find the next
2918 * contiguous region of logical blocks that need
2919 * blocks to be allocated by ext4. We don't actually
2920 * submit the blocks for I/O here, even though
2921 * write_cache_pages thinks it will, and will set the
2922 * pages as clean for write before calling
2923 * __mpage_da_writepage().
2931 mpd.pages_written = 0;
2933 ret = write_cache_pages(mapping, wbc, __mpage_da_writepage,
2936 * If we have a contiguous extent of pages and we
2937 * haven't done the I/O yet, map the blocks and submit
2940 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2941 if (mpage_da_map_blocks(&mpd) == 0)
2942 mpage_da_submit_io(&mpd);
2944 ret = MPAGE_DA_EXTENT_TAIL;
2946 trace_ext4_da_write_pages(inode, &mpd);
2947 wbc->nr_to_write -= mpd.pages_written;
2949 ext4_journal_stop(handle);
2951 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2952 /* commit the transaction which would
2953 * free blocks released in the transaction
2956 jbd2_journal_force_commit_nested(sbi->s_journal);
2957 wbc->pages_skipped = pages_skipped;
2959 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2961 * got one extent now try with
2964 pages_written += mpd.pages_written;
2965 wbc->pages_skipped = pages_skipped;
2968 } else if (wbc->nr_to_write)
2970 * There is no more writeout needed
2971 * or we requested for a noblocking writeout
2972 * and we found the device congested
2976 if (!io_done && !cycled) {
2979 wbc->range_start = index << PAGE_CACHE_SHIFT;
2980 wbc->range_end = mapping->writeback_index - 1;
2983 if (pages_skipped != wbc->pages_skipped)
2984 ext4_msg(inode->i_sb, KERN_CRIT,
2985 "This should not happen leaving %s "
2986 "with nr_to_write = %ld ret = %d\n",
2987 __func__, wbc->nr_to_write, ret);
2990 index += pages_written;
2991 wbc->range_cyclic = range_cyclic;
2992 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2994 * set the writeback_index so that range_cyclic
2995 * mode will write it back later
2997 mapping->writeback_index = index;
3000 if (!no_nrwrite_index_update)
3001 wbc->no_nrwrite_index_update = 0;
3002 wbc->nr_to_write -= nr_to_writebump;
3003 wbc->range_start = range_start;
3004 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
3008 #define FALL_BACK_TO_NONDELALLOC 1
3009 static int ext4_nonda_switch(struct super_block *sb)
3011 s64 free_blocks, dirty_blocks;
3012 struct ext4_sb_info *sbi = EXT4_SB(sb);
3015 * switch to non delalloc mode if we are running low
3016 * on free block. The free block accounting via percpu
3017 * counters can get slightly wrong with percpu_counter_batch getting
3018 * accumulated on each CPU without updating global counters
3019 * Delalloc need an accurate free block accounting. So switch
3020 * to non delalloc when we are near to error range.
3022 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
3023 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
3024 if (2 * free_blocks < 3 * dirty_blocks ||
3025 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
3027 * free block count is less than 150% of dirty blocks
3028 * or free blocks is less than watermark
3033 * Even if we don't switch but are nearing capacity,
3034 * start pushing delalloc when 1/2 of free blocks are dirty.
3036 if (free_blocks < 2 * dirty_blocks)
3037 writeback_inodes_sb_if_idle(sb);
3042 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3043 loff_t pos, unsigned len, unsigned flags,
3044 struct page **pagep, void **fsdata)
3046 int ret, retries = 0, quota_retries = 0;
3050 struct inode *inode = mapping->host;
3053 index = pos >> PAGE_CACHE_SHIFT;
3054 from = pos & (PAGE_CACHE_SIZE - 1);
3057 if (ext4_nonda_switch(inode->i_sb)) {
3058 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3059 return ext4_write_begin(file, mapping, pos,
3060 len, flags, pagep, fsdata);
3062 *fsdata = (void *)0;
3063 trace_ext4_da_write_begin(inode, pos, len, flags);
3066 * With delayed allocation, we don't log the i_disksize update
3067 * if there is delayed block allocation. But we still need
3068 * to journalling the i_disksize update if writes to the end
3069 * of file which has an already mapped buffer.
3071 handle = ext4_journal_start(inode, 1);
3072 if (IS_ERR(handle)) {
3073 ret = PTR_ERR(handle);
3076 /* We cannot recurse into the filesystem as the transaction is already
3078 flags |= AOP_FLAG_NOFS;
3080 page = grab_cache_page_write_begin(mapping, index, flags);
3082 ext4_journal_stop(handle);
3088 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
3089 ext4_da_get_block_prep);
3092 ext4_journal_stop(handle);
3093 page_cache_release(page);
3095 * block_write_begin may have instantiated a few blocks
3096 * outside i_size. Trim these off again. Don't need
3097 * i_size_read because we hold i_mutex.
3099 if (pos + len > inode->i_size)
3100 ext4_truncate_failed_write(inode);
3103 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3106 if ((ret == -EDQUOT) &&
3107 EXT4_I(inode)->i_reserved_meta_blocks &&
3108 (quota_retries++ < 3)) {
3110 * Since we often over-estimate the number of meta
3111 * data blocks required, we may sometimes get a
3112 * spurios out of quota error even though there would
3113 * be enough space once we write the data blocks and
3114 * find out how many meta data blocks were _really_
3115 * required. So try forcing the inode write to see if
3118 write_inode_now(inode, (quota_retries == 3));
3126 * Check if we should update i_disksize
3127 * when write to the end of file but not require block allocation
3129 static int ext4_da_should_update_i_disksize(struct page *page,
3130 unsigned long offset)
3132 struct buffer_head *bh;
3133 struct inode *inode = page->mapping->host;
3137 bh = page_buffers(page);
3138 idx = offset >> inode->i_blkbits;
3140 for (i = 0; i < idx; i++)
3141 bh = bh->b_this_page;
3143 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3148 static int ext4_da_write_end(struct file *file,
3149 struct address_space *mapping,
3150 loff_t pos, unsigned len, unsigned copied,
3151 struct page *page, void *fsdata)
3153 struct inode *inode = mapping->host;
3155 handle_t *handle = ext4_journal_current_handle();
3157 unsigned long start, end;
3158 int write_mode = (int)(unsigned long)fsdata;
3160 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
3161 if (ext4_should_order_data(inode)) {
3162 return ext4_ordered_write_end(file, mapping, pos,
3163 len, copied, page, fsdata);
3164 } else if (ext4_should_writeback_data(inode)) {
3165 return ext4_writeback_write_end(file, mapping, pos,
3166 len, copied, page, fsdata);
3172 trace_ext4_da_write_end(inode, pos, len, copied);
3173 start = pos & (PAGE_CACHE_SIZE - 1);
3174 end = start + copied - 1;
3177 * generic_write_end() will run mark_inode_dirty() if i_size
3178 * changes. So let's piggyback the i_disksize mark_inode_dirty
3182 new_i_size = pos + copied;
3183 if (new_i_size > EXT4_I(inode)->i_disksize) {
3184 if (ext4_da_should_update_i_disksize(page, end)) {
3185 down_write(&EXT4_I(inode)->i_data_sem);
3186 if (new_i_size > EXT4_I(inode)->i_disksize) {
3188 * Updating i_disksize when extending file
3189 * without needing block allocation
3191 if (ext4_should_order_data(inode))
3192 ret = ext4_jbd2_file_inode(handle,
3195 EXT4_I(inode)->i_disksize = new_i_size;
3197 up_write(&EXT4_I(inode)->i_data_sem);
3198 /* We need to mark inode dirty even if
3199 * new_i_size is less that inode->i_size
3200 * bu greater than i_disksize.(hint delalloc)
3202 ext4_mark_inode_dirty(handle, inode);
3205 ret2 = generic_write_end(file, mapping, pos, len, copied,
3210 ret2 = ext4_journal_stop(handle);
3214 return ret ? ret : copied;
3217 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
3220 * Drop reserved blocks
3222 BUG_ON(!PageLocked(page));
3223 if (!page_has_buffers(page))
3226 ext4_da_page_release_reservation(page, offset);
3229 ext4_invalidatepage(page, offset);
3235 * Force all delayed allocation blocks to be allocated for a given inode.
3237 int ext4_alloc_da_blocks(struct inode *inode)
3239 trace_ext4_alloc_da_blocks(inode);
3241 if (!EXT4_I(inode)->i_reserved_data_blocks &&
3242 !EXT4_I(inode)->i_reserved_meta_blocks)
3246 * We do something simple for now. The filemap_flush() will
3247 * also start triggering a write of the data blocks, which is
3248 * not strictly speaking necessary (and for users of
3249 * laptop_mode, not even desirable). However, to do otherwise
3250 * would require replicating code paths in:
3252 * ext4_da_writepages() ->
3253 * write_cache_pages() ---> (via passed in callback function)
3254 * __mpage_da_writepage() -->
3255 * mpage_add_bh_to_extent()
3256 * mpage_da_map_blocks()
3258 * The problem is that write_cache_pages(), located in
3259 * mm/page-writeback.c, marks pages clean in preparation for
3260 * doing I/O, which is not desirable if we're not planning on
3263 * We could call write_cache_pages(), and then redirty all of
3264 * the pages by calling redirty_page_for_writeback() but that
3265 * would be ugly in the extreme. So instead we would need to
3266 * replicate parts of the code in the above functions,
3267 * simplifying them becuase we wouldn't actually intend to
3268 * write out the pages, but rather only collect contiguous
3269 * logical block extents, call the multi-block allocator, and
3270 * then update the buffer heads with the block allocations.
3272 * For now, though, we'll cheat by calling filemap_flush(),
3273 * which will map the blocks, and start the I/O, but not
3274 * actually wait for the I/O to complete.
3276 return filemap_flush(inode->i_mapping);
3280 * bmap() is special. It gets used by applications such as lilo and by
3281 * the swapper to find the on-disk block of a specific piece of data.
3283 * Naturally, this is dangerous if the block concerned is still in the
3284 * journal. If somebody makes a swapfile on an ext4 data-journaling
3285 * filesystem and enables swap, then they may get a nasty shock when the
3286 * data getting swapped to that swapfile suddenly gets overwritten by
3287 * the original zero's written out previously to the journal and
3288 * awaiting writeback in the kernel's buffer cache.
3290 * So, if we see any bmap calls here on a modified, data-journaled file,
3291 * take extra steps to flush any blocks which might be in the cache.
3293 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3295 struct inode *inode = mapping->host;
3299 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3300 test_opt(inode->i_sb, DELALLOC)) {
3302 * With delalloc we want to sync the file
3303 * so that we can make sure we allocate
3306 filemap_write_and_wait(mapping);
3309 if (EXT4_JOURNAL(inode) && EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
3311 * This is a REALLY heavyweight approach, but the use of
3312 * bmap on dirty files is expected to be extremely rare:
3313 * only if we run lilo or swapon on a freshly made file
3314 * do we expect this to happen.
3316 * (bmap requires CAP_SYS_RAWIO so this does not
3317 * represent an unprivileged user DOS attack --- we'd be
3318 * in trouble if mortal users could trigger this path at
3321 * NB. EXT4_STATE_JDATA is not set on files other than
3322 * regular files. If somebody wants to bmap a directory
3323 * or symlink and gets confused because the buffer
3324 * hasn't yet been flushed to disk, they deserve
3325 * everything they get.
3328 EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
3329 journal = EXT4_JOURNAL(inode);
3330 jbd2_journal_lock_updates(journal);
3331 err = jbd2_journal_flush(journal);
3332 jbd2_journal_unlock_updates(journal);
3338 return generic_block_bmap(mapping, block, ext4_get_block);
3341 static int ext4_readpage(struct file *file, struct page *page)
3343 return mpage_readpage(page, ext4_get_block);
3347 ext4_readpages(struct file *file, struct address_space *mapping,
3348 struct list_head *pages, unsigned nr_pages)
3350 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3353 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3355 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3358 * If it's a full truncate we just forget about the pending dirtying
3361 ClearPageChecked(page);
3364 jbd2_journal_invalidatepage(journal, page, offset);
3366 block_invalidatepage(page, offset);
3369 static int ext4_releasepage(struct page *page, gfp_t wait)
3371 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3373 WARN_ON(PageChecked(page));
3374 if (!page_has_buffers(page))
3377 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3379 return try_to_free_buffers(page);
3383 * O_DIRECT for ext3 (or indirect map) based files
3385 * If the O_DIRECT write will extend the file then add this inode to the
3386 * orphan list. So recovery will truncate it back to the original size
3387 * if the machine crashes during the write.
3389 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3390 * crashes then stale disk data _may_ be exposed inside the file. But current
3391 * VFS code falls back into buffered path in that case so we are safe.
3393 static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
3394 const struct iovec *iov, loff_t offset,
3395 unsigned long nr_segs)
3397 struct file *file = iocb->ki_filp;
3398 struct inode *inode = file->f_mapping->host;
3399 struct ext4_inode_info *ei = EXT4_I(inode);
3403 size_t count = iov_length(iov, nr_segs);
3407 loff_t final_size = offset + count;
3409 if (final_size > inode->i_size) {
3410 /* Credits for sb + inode write */
3411 handle = ext4_journal_start(inode, 2);
3412 if (IS_ERR(handle)) {
3413 ret = PTR_ERR(handle);
3416 ret = ext4_orphan_add(handle, inode);
3418 ext4_journal_stop(handle);
3422 ei->i_disksize = inode->i_size;
3423 ext4_journal_stop(handle);
3428 ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
3430 ext4_get_block, NULL);
3431 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3437 /* Credits for sb + inode write */
3438 handle = ext4_journal_start(inode, 2);
3439 if (IS_ERR(handle)) {
3440 /* This is really bad luck. We've written the data
3441 * but cannot extend i_size. Bail out and pretend
3442 * the write failed... */
3443 ret = PTR_ERR(handle);
3447 ext4_orphan_del(handle, inode);
3449 loff_t end = offset + ret;
3450 if (end > inode->i_size) {
3451 ei->i_disksize = end;
3452 i_size_write(inode, end);
3454 * We're going to return a positive `ret'
3455 * here due to non-zero-length I/O, so there's
3456 * no way of reporting error returns from
3457 * ext4_mark_inode_dirty() to userspace. So
3460 ext4_mark_inode_dirty(handle, inode);
3463 err = ext4_journal_stop(handle);
3471 static int ext4_get_block_dio_write(struct inode *inode, sector_t iblock,
3472 struct buffer_head *bh_result, int create)
3474 handle_t *handle = NULL;
3476 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
3479 ext4_debug("ext4_get_block_dio_write: inode %lu, create flag %d\n",
3480 inode->i_ino, create);
3482 * DIO VFS code passes create = 0 flag for write to
3483 * the middle of file. It does this to avoid block
3484 * allocation for holes, to prevent expose stale data
3485 * out when there is parallel buffered read (which does
3486 * not hold the i_mutex lock) while direct IO write has
3487 * not completed. DIO request on holes finally falls back
3488 * to buffered IO for this reason.
3490 * For ext4 extent based file, since we support fallocate,
3491 * new allocated extent as uninitialized, for holes, we
3492 * could fallocate blocks for holes, thus parallel
3493 * buffered IO read will zero out the page when read on
3494 * a hole while parallel DIO write to the hole has not completed.
3496 * when we come here, we know it's a direct IO write to
3497 * to the middle of file (<i_size)
3498 * so it's safe to override the create flag from VFS.
3500 create = EXT4_GET_BLOCKS_DIO_CREATE_EXT;
3502 if (max_blocks > DIO_MAX_BLOCKS)
3503 max_blocks = DIO_MAX_BLOCKS;
3504 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
3505 handle = ext4_journal_start(inode, dio_credits);
3506 if (IS_ERR(handle)) {
3507 ret = PTR_ERR(handle);
3510 ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
3513 bh_result->b_size = (ret << inode->i_blkbits);
3516 ext4_journal_stop(handle);
3521 static void ext4_free_io_end(ext4_io_end_t *io)
3527 static void dump_aio_dio_list(struct inode * inode)
3530 struct list_head *cur, *before, *after;
3531 ext4_io_end_t *io, *io0, *io1;
3533 if (list_empty(&EXT4_I(inode)->i_aio_dio_complete_list)){
3534 ext4_debug("inode %lu aio dio list is empty\n", inode->i_ino);
3538 ext4_debug("Dump inode %lu aio_dio_completed_IO list \n", inode->i_ino);
3539 list_for_each_entry(io, &EXT4_I(inode)->i_aio_dio_complete_list, list){
3542 io0 = container_of(before, ext4_io_end_t, list);
3544 io1 = container_of(after, ext4_io_end_t, list);
3546 ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
3547 io, inode->i_ino, io0, io1);
3553 * check a range of space and convert unwritten extents to written.
3555 static int ext4_end_aio_dio_nolock(ext4_io_end_t *io)
3557 struct inode *inode = io->inode;
3558 loff_t offset = io->offset;
3559 size_t size = io->size;
3562 ext4_debug("end_aio_dio_onlock: io 0x%p from inode %lu,list->next 0x%p,"
3563 "list->prev 0x%p\n",
3564 io, inode->i_ino, io->list.next, io->list.prev);
3566 if (list_empty(&io->list))
3569 if (io->flag != DIO_AIO_UNWRITTEN)
3572 if (offset + size <= i_size_read(inode))
3573 ret = ext4_convert_unwritten_extents(inode, offset, size);
3576 printk(KERN_EMERG "%s: failed to convert unwritten"
3577 "extents to written extents, error is %d"
3578 " io is still on inode %lu aio dio list\n",
3579 __func__, ret, inode->i_ino);
3583 /* clear the DIO AIO unwritten flag */
3588 * work on completed aio dio IO, to convert unwritten extents to extents
3590 static void ext4_end_aio_dio_work(struct work_struct *work)
3592 ext4_io_end_t *io = container_of(work, ext4_io_end_t, work);
3593 struct inode *inode = io->inode;
3596 mutex_lock(&inode->i_mutex);
3597 ret = ext4_end_aio_dio_nolock(io);
3599 if (!list_empty(&io->list))
3600 list_del_init(&io->list);
3601 ext4_free_io_end(io);
3603 mutex_unlock(&inode->i_mutex);
3606 * This function is called from ext4_sync_file().
3608 * When AIO DIO IO is completed, the work to convert unwritten
3609 * extents to written is queued on workqueue but may not get immediately
3610 * scheduled. When fsync is called, we need to ensure the
3611 * conversion is complete before fsync returns.
3612 * The inode keeps track of a list of completed AIO from DIO path
3613 * that might needs to do the conversion. This function walks through
3614 * the list and convert the related unwritten extents to written.
3616 int flush_aio_dio_completed_IO(struct inode *inode)
3622 if (list_empty(&EXT4_I(inode)->i_aio_dio_complete_list))
3625 dump_aio_dio_list(inode);
3626 while (!list_empty(&EXT4_I(inode)->i_aio_dio_complete_list)){
3627 io = list_entry(EXT4_I(inode)->i_aio_dio_complete_list.next,
3628 ext4_io_end_t, list);
3630 * Calling ext4_end_aio_dio_nolock() to convert completed
3633 * When ext4_sync_file() is called, run_queue() may already
3634 * about to flush the work corresponding to this io structure.
3635 * It will be upset if it founds the io structure related
3636 * to the work-to-be schedule is freed.
3638 * Thus we need to keep the io structure still valid here after
3639 * convertion finished. The io structure has a flag to
3640 * avoid double converting from both fsync and background work
3643 ret = ext4_end_aio_dio_nolock(io);
3647 list_del_init(&io->list);
3649 return (ret2 < 0) ? ret2 : 0;
3652 static ext4_io_end_t *ext4_init_io_end (struct inode *inode)
3654 ext4_io_end_t *io = NULL;
3656 io = kmalloc(sizeof(*io), GFP_NOFS);
3665 INIT_WORK(&io->work, ext4_end_aio_dio_work);
3666 INIT_LIST_HEAD(&io->list);
3672 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3673 ssize_t size, void *private)
3675 ext4_io_end_t *io_end = iocb->private;
3676 struct workqueue_struct *wq;
3678 /* if not async direct IO or dio with 0 bytes write, just return */
3679 if (!io_end || !size)
3682 ext_debug("ext4_end_io_dio(): io_end 0x%p"
3683 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
3684 iocb->private, io_end->inode->i_ino, iocb, offset,
3687 /* if not aio dio with unwritten extents, just free io and return */
3688 if (io_end->flag != DIO_AIO_UNWRITTEN){
3689 ext4_free_io_end(io_end);
3690 iocb->private = NULL;
3694 io_end->offset = offset;
3695 io_end->size = size;
3696 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
3698 /* queue the work to convert unwritten extents to written */
3699 queue_work(wq, &io_end->work);
3701 /* Add the io_end to per-inode completed aio dio list*/
3702 list_add_tail(&io_end->list,
3703 &EXT4_I(io_end->inode)->i_aio_dio_complete_list);
3704 iocb->private = NULL;
3707 * For ext4 extent files, ext4 will do direct-io write to holes,
3708 * preallocated extents, and those write extend the file, no need to
3709 * fall back to buffered IO.
3711 * For holes, we fallocate those blocks, mark them as unintialized
3712 * If those blocks were preallocated, we mark sure they are splited, but
3713 * still keep the range to write as unintialized.
3715 * The unwrritten extents will be converted to written when DIO is completed.
3716 * For async direct IO, since the IO may still pending when return, we
3717 * set up an end_io call back function, which will do the convertion
3718 * when async direct IO completed.
3720 * If the O_DIRECT write will extend the file then add this inode to the
3721 * orphan list. So recovery will truncate it back to the original size
3722 * if the machine crashes during the write.
3725 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3726 const struct iovec *iov, loff_t offset,
3727 unsigned long nr_segs)
3729 struct file *file = iocb->ki_filp;
3730 struct inode *inode = file->f_mapping->host;
3732 size_t count = iov_length(iov, nr_segs);
3734 loff_t final_size = offset + count;
3735 if (rw == WRITE && final_size <= inode->i_size) {
3737 * We could direct write to holes and fallocate.
3739 * Allocated blocks to fill the hole are marked as uninitialized
3740 * to prevent paralel buffered read to expose the stale data
3741 * before DIO complete the data IO.
3743 * As to previously fallocated extents, ext4 get_block
3744 * will just simply mark the buffer mapped but still
3745 * keep the extents uninitialized.
3747 * for non AIO case, we will convert those unwritten extents
3748 * to written after return back from blockdev_direct_IO.
3750 * for async DIO, the conversion needs to be defered when
3751 * the IO is completed. The ext4 end_io callback function
3752 * will be called to take care of the conversion work.
3753 * Here for async case, we allocate an io_end structure to
3756 iocb->private = NULL;
3757 EXT4_I(inode)->cur_aio_dio = NULL;
3758 if (!is_sync_kiocb(iocb)) {
3759 iocb->private = ext4_init_io_end(inode);
3763 * we save the io structure for current async
3764 * direct IO, so that later ext4_get_blocks()
3765 * could flag the io structure whether there
3766 * is a unwritten extents needs to be converted
3767 * when IO is completed.
3769 EXT4_I(inode)->cur_aio_dio = iocb->private;
3772 ret = blockdev_direct_IO(rw, iocb, inode,
3773 inode->i_sb->s_bdev, iov,
3775 ext4_get_block_dio_write,
3778 EXT4_I(inode)->cur_aio_dio = NULL;
3780 * The io_end structure takes a reference to the inode,
3781 * that structure needs to be destroyed and the
3782 * reference to the inode need to be dropped, when IO is
3783 * complete, even with 0 byte write, or failed.
3785 * In the successful AIO DIO case, the io_end structure will be
3786 * desctroyed and the reference to the inode will be dropped
3787 * after the end_io call back function is called.
3789 * In the case there is 0 byte write, or error case, since
3790 * VFS direct IO won't invoke the end_io call back function,
3791 * we need to free the end_io structure here.
3793 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3794 ext4_free_io_end(iocb->private);
3795 iocb->private = NULL;
3796 } else if (ret > 0 && (EXT4_I(inode)->i_state &
3797 EXT4_STATE_DIO_UNWRITTEN)) {
3800 * for non AIO case, since the IO is already
3801 * completed, we could do the convertion right here
3803 err = ext4_convert_unwritten_extents(inode,
3807 EXT4_I(inode)->i_state &= ~EXT4_STATE_DIO_UNWRITTEN;
3812 /* for write the the end of file case, we fall back to old way */
3813 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3816 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3817 const struct iovec *iov, loff_t offset,
3818 unsigned long nr_segs)
3820 struct file *file = iocb->ki_filp;
3821 struct inode *inode = file->f_mapping->host;
3823 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
3824 return ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3826 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3830 * Pages can be marked dirty completely asynchronously from ext4's journalling
3831 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3832 * much here because ->set_page_dirty is called under VFS locks. The page is
3833 * not necessarily locked.
3835 * We cannot just dirty the page and leave attached buffers clean, because the
3836 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3837 * or jbddirty because all the journalling code will explode.
3839 * So what we do is to mark the page "pending dirty" and next time writepage
3840 * is called, propagate that into the buffers appropriately.
3842 static int ext4_journalled_set_page_dirty(struct page *page)
3844 SetPageChecked(page);
3845 return __set_page_dirty_nobuffers(page);
3848 static const struct address_space_operations ext4_ordered_aops = {
3849 .readpage = ext4_readpage,
3850 .readpages = ext4_readpages,
3851 .writepage = ext4_writepage,
3852 .sync_page = block_sync_page,
3853 .write_begin = ext4_write_begin,
3854 .write_end = ext4_ordered_write_end,
3856 .invalidatepage = ext4_invalidatepage,
3857 .releasepage = ext4_releasepage,
3858 .direct_IO = ext4_direct_IO,
3859 .migratepage = buffer_migrate_page,
3860 .is_partially_uptodate = block_is_partially_uptodate,
3861 .error_remove_page = generic_error_remove_page,
3864 static const struct address_space_operations ext4_writeback_aops = {
3865 .readpage = ext4_readpage,
3866 .readpages = ext4_readpages,
3867 .writepage = ext4_writepage,
3868 .sync_page = block_sync_page,
3869 .write_begin = ext4_write_begin,
3870 .write_end = ext4_writeback_write_end,
3872 .invalidatepage = ext4_invalidatepage,
3873 .releasepage = ext4_releasepage,
3874 .direct_IO = ext4_direct_IO,
3875 .migratepage = buffer_migrate_page,
3876 .is_partially_uptodate = block_is_partially_uptodate,
3877 .error_remove_page = generic_error_remove_page,
3880 static const struct address_space_operations ext4_journalled_aops = {
3881 .readpage = ext4_readpage,
3882 .readpages = ext4_readpages,
3883 .writepage = ext4_writepage,
3884 .sync_page = block_sync_page,
3885 .write_begin = ext4_write_begin,
3886 .write_end = ext4_journalled_write_end,
3887 .set_page_dirty = ext4_journalled_set_page_dirty,
3889 .invalidatepage = ext4_invalidatepage,
3890 .releasepage = ext4_releasepage,
3891 .is_partially_uptodate = block_is_partially_uptodate,
3892 .error_remove_page = generic_error_remove_page,
3895 static const struct address_space_operations ext4_da_aops = {
3896 .readpage = ext4_readpage,
3897 .readpages = ext4_readpages,
3898 .writepage = ext4_writepage,
3899 .writepages = ext4_da_writepages,
3900 .sync_page = block_sync_page,
3901 .write_begin = ext4_da_write_begin,
3902 .write_end = ext4_da_write_end,
3904 .invalidatepage = ext4_da_invalidatepage,
3905 .releasepage = ext4_releasepage,
3906 .direct_IO = ext4_direct_IO,
3907 .migratepage = buffer_migrate_page,
3908 .is_partially_uptodate = block_is_partially_uptodate,
3909 .error_remove_page = generic_error_remove_page,
3912 void ext4_set_aops(struct inode *inode)
3914 if (ext4_should_order_data(inode) &&
3915 test_opt(inode->i_sb, DELALLOC))
3916 inode->i_mapping->a_ops = &ext4_da_aops;
3917 else if (ext4_should_order_data(inode))
3918 inode->i_mapping->a_ops = &ext4_ordered_aops;
3919 else if (ext4_should_writeback_data(inode) &&
3920 test_opt(inode->i_sb, DELALLOC))
3921 inode->i_mapping->a_ops = &ext4_da_aops;
3922 else if (ext4_should_writeback_data(inode))
3923 inode->i_mapping->a_ops = &ext4_writeback_aops;
3925 inode->i_mapping->a_ops = &ext4_journalled_aops;
3929 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3930 * up to the end of the block which corresponds to `from'.
3931 * This required during truncate. We need to physically zero the tail end
3932 * of that block so it doesn't yield old data if the file is later grown.
3934 int ext4_block_truncate_page(handle_t *handle,
3935 struct address_space *mapping, loff_t from)
3937 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3938 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3939 unsigned blocksize, length, pos;
3941 struct inode *inode = mapping->host;
3942 struct buffer_head *bh;
3946 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3947 mapping_gfp_mask(mapping) & ~__GFP_FS);
3951 blocksize = inode->i_sb->s_blocksize;
3952 length = blocksize - (offset & (blocksize - 1));
3953 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3956 * For "nobh" option, we can only work if we don't need to
3957 * read-in the page - otherwise we create buffers to do the IO.
3959 if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
3960 ext4_should_writeback_data(inode) && PageUptodate(page)) {
3961 zero_user(page, offset, length);
3962 set_page_dirty(page);
3966 if (!page_has_buffers(page))
3967 create_empty_buffers(page, blocksize, 0);
3969 /* Find the buffer that contains "offset" */
3970 bh = page_buffers(page);
3972 while (offset >= pos) {
3973 bh = bh->b_this_page;
3979 if (buffer_freed(bh)) {
3980 BUFFER_TRACE(bh, "freed: skip");
3984 if (!buffer_mapped(bh)) {
3985 BUFFER_TRACE(bh, "unmapped");
3986 ext4_get_block(inode, iblock, bh, 0);
3987 /* unmapped? It's a hole - nothing to do */
3988 if (!buffer_mapped(bh)) {
3989 BUFFER_TRACE(bh, "still unmapped");
3994 /* Ok, it's mapped. Make sure it's up-to-date */
3995 if (PageUptodate(page))
3996 set_buffer_uptodate(bh);
3998 if (!buffer_uptodate(bh)) {
4000 ll_rw_block(READ, 1, &bh);
4002 /* Uhhuh. Read error. Complain and punt. */
4003 if (!buffer_uptodate(bh))
4007 if (ext4_should_journal_data(inode)) {
4008 BUFFER_TRACE(bh, "get write access");
4009 err = ext4_journal_get_write_access(handle, bh);
4014 zero_user(page, offset, length);
4016 BUFFER_TRACE(bh, "zeroed end of block");
4019 if (ext4_should_journal_data(inode)) {
4020 err = ext4_handle_dirty_metadata(handle, inode, bh);
4022 if (ext4_should_order_data(inode))
4023 err = ext4_jbd2_file_inode(handle, inode);
4024 mark_buffer_dirty(bh);
4029 page_cache_release(page);
4034 * Probably it should be a library function... search for first non-zero word
4035 * or memcmp with zero_page, whatever is better for particular architecture.
4038 static inline int all_zeroes(__le32 *p, __le32 *q)
4047 * ext4_find_shared - find the indirect blocks for partial truncation.
4048 * @inode: inode in question
4049 * @depth: depth of the affected branch
4050 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
4051 * @chain: place to store the pointers to partial indirect blocks
4052 * @top: place to the (detached) top of branch
4054 * This is a helper function used by ext4_truncate().
4056 * When we do truncate() we may have to clean the ends of several
4057 * indirect blocks but leave the blocks themselves alive. Block is
4058 * partially truncated if some data below the new i_size is refered
4059 * from it (and it is on the path to the first completely truncated
4060 * data block, indeed). We have to free the top of that path along
4061 * with everything to the right of the path. Since no allocation
4062 * past the truncation point is possible until ext4_truncate()
4063 * finishes, we may safely do the latter, but top of branch may
4064 * require special attention - pageout below the truncation point
4065 * might try to populate it.
4067 * We atomically detach the top of branch from the tree, store the
4068 * block number of its root in *@top, pointers to buffer_heads of
4069 * partially truncated blocks - in @chain[].bh and pointers to
4070 * their last elements that should not be removed - in
4071 * @chain[].p. Return value is the pointer to last filled element
4074 * The work left to caller to do the actual freeing of subtrees:
4075 * a) free the subtree starting from *@top
4076 * b) free the subtrees whose roots are stored in
4077 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
4078 * c) free the subtrees growing from the inode past the @chain[0].
4079 * (no partially truncated stuff there). */
4081 static Indirect *ext4_find_shared(struct inode *inode, int depth,
4082 ext4_lblk_t offsets[4], Indirect chain[4],
4085 Indirect *partial, *p;
4089 /* Make k index the deepest non-null offset + 1 */
4090 for (k = depth; k > 1 && !offsets[k-1]; k--)
4092 partial = ext4_get_branch(inode, k, offsets, chain, &err);
4093 /* Writer: pointers */
4095 partial = chain + k-1;
4097 * If the branch acquired continuation since we've looked at it -
4098 * fine, it should all survive and (new) top doesn't belong to us.
4100 if (!partial->key && *partial->p)
4103 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
4106 * OK, we've found the last block that must survive. The rest of our
4107 * branch should be detached before unlocking. However, if that rest
4108 * of branch is all ours and does not grow immediately from the inode
4109 * it's easier to cheat and just decrement partial->p.
4111 if (p == chain + k - 1 && p > chain) {
4115 /* Nope, don't do this in ext4. Must leave the tree intact */
4122 while (partial > p) {
4123 brelse(partial->bh);
4131 * Zero a number of block pointers in either an inode or an indirect block.
4132 * If we restart the transaction we must again get write access to the
4133 * indirect block for further modification.
4135 * We release `count' blocks on disk, but (last - first) may be greater
4136 * than `count' because there can be holes in there.
4138 static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
4139 struct buffer_head *bh,
4140 ext4_fsblk_t block_to_free,
4141 unsigned long count, __le32 *first,
4145 int flags = EXT4_FREE_BLOCKS_FORGET;
4147 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
4148 flags |= EXT4_FREE_BLOCKS_METADATA;
4150 if (try_to_extend_transaction(handle, inode)) {
4152 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4153 ext4_handle_dirty_metadata(handle, inode, bh);
4155 ext4_mark_inode_dirty(handle, inode);
4156 ext4_truncate_restart_trans(handle, inode,
4157 blocks_for_truncate(inode));
4159 BUFFER_TRACE(bh, "retaking write access");
4160 ext4_journal_get_write_access(handle, bh);
4164 for (p = first; p < last; p++)
4167 ext4_free_blocks(handle, inode, 0, block_to_free, count, flags);
4171 * ext4_free_data - free a list of data blocks
4172 * @handle: handle for this transaction
4173 * @inode: inode we are dealing with
4174 * @this_bh: indirect buffer_head which contains *@first and *@last
4175 * @first: array of block numbers
4176 * @last: points immediately past the end of array
4178 * We are freeing all blocks refered from that array (numbers are stored as
4179 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
4181 * We accumulate contiguous runs of blocks to free. Conveniently, if these
4182 * blocks are contiguous then releasing them at one time will only affect one
4183 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
4184 * actually use a lot of journal space.
4186 * @this_bh will be %NULL if @first and @last point into the inode's direct
4189 static void ext4_free_data(handle_t *handle, struct inode *inode,
4190 struct buffer_head *this_bh,
4191 __le32 *first, __le32 *last)
4193 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
4194 unsigned long count = 0; /* Number of blocks in the run */
4195 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
4198 ext4_fsblk_t nr; /* Current block # */
4199 __le32 *p; /* Pointer into inode/ind
4200 for current block */
4203 if (this_bh) { /* For indirect block */
4204 BUFFER_TRACE(this_bh, "get_write_access");
4205 err = ext4_journal_get_write_access(handle, this_bh);
4206 /* Important: if we can't update the indirect pointers
4207 * to the blocks, we can't free them. */
4212 for (p = first; p < last; p++) {
4213 nr = le32_to_cpu(*p);
4215 /* accumulate blocks to free if they're contiguous */
4218 block_to_free_p = p;
4220 } else if (nr == block_to_free + count) {
4223 ext4_clear_blocks(handle, inode, this_bh,
4225 count, block_to_free_p, p);
4227 block_to_free_p = p;
4234 ext4_clear_blocks(handle, inode, this_bh, block_to_free,
4235 count, block_to_free_p, p);
4238 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
4241 * The buffer head should have an attached journal head at this
4242 * point. However, if the data is corrupted and an indirect
4243 * block pointed to itself, it would have been detached when
4244 * the block was cleared. Check for this instead of OOPSing.
4246 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
4247 ext4_handle_dirty_metadata(handle, inode, this_bh);
4249 ext4_error(inode->i_sb, __func__,
4250 "circular indirect block detected, "
4251 "inode=%lu, block=%llu",
4253 (unsigned long long) this_bh->b_blocknr);
4258 * ext4_free_branches - free an array of branches
4259 * @handle: JBD handle for this transaction
4260 * @inode: inode we are dealing with
4261 * @parent_bh: the buffer_head which contains *@first and *@last
4262 * @first: array of block numbers
4263 * @last: pointer immediately past the end of array
4264 * @depth: depth of the branches to free
4266 * We are freeing all blocks refered from these branches (numbers are
4267 * stored as little-endian 32-bit) and updating @inode->i_blocks
4270 static void ext4_free_branches(handle_t *handle, struct inode *inode,
4271 struct buffer_head *parent_bh,
4272 __le32 *first, __le32 *last, int depth)
4277 if (ext4_handle_is_aborted(handle))
4281 struct buffer_head *bh;
4282 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4284 while (--p >= first) {
4285 nr = le32_to_cpu(*p);
4287 continue; /* A hole */
4289 /* Go read the buffer for the next level down */
4290 bh = sb_bread(inode->i_sb, nr);
4293 * A read failure? Report error and clear slot
4297 ext4_error(inode->i_sb, "ext4_free_branches",
4298 "Read failure, inode=%lu, block=%llu",
4303 /* This zaps the entire block. Bottom up. */
4304 BUFFER_TRACE(bh, "free child branches");
4305 ext4_free_branches(handle, inode, bh,
4306 (__le32 *) bh->b_data,
4307 (__le32 *) bh->b_data + addr_per_block,
4311 * We've probably journalled the indirect block several
4312 * times during the truncate. But it's no longer
4313 * needed and we now drop it from the transaction via
4314 * jbd2_journal_revoke().
4316 * That's easy if it's exclusively part of this
4317 * transaction. But if it's part of the committing
4318 * transaction then jbd2_journal_forget() will simply
4319 * brelse() it. That means that if the underlying
4320 * block is reallocated in ext4_get_block(),
4321 * unmap_underlying_metadata() will find this block
4322 * and will try to get rid of it. damn, damn.
4324 * If this block has already been committed to the
4325 * journal, a revoke record will be written. And
4326 * revoke records must be emitted *before* clearing
4327 * this block's bit in the bitmaps.
4329 ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
4332 * Everything below this this pointer has been
4333 * released. Now let this top-of-subtree go.
4335 * We want the freeing of this indirect block to be
4336 * atomic in the journal with the updating of the
4337 * bitmap block which owns it. So make some room in
4340 * We zero the parent pointer *after* freeing its
4341 * pointee in the bitmaps, so if extend_transaction()
4342 * for some reason fails to put the bitmap changes and
4343 * the release into the same transaction, recovery
4344 * will merely complain about releasing a free block,
4345 * rather than leaking blocks.
4347 if (ext4_handle_is_aborted(handle))
4349 if (try_to_extend_transaction(handle, inode)) {
4350 ext4_mark_inode_dirty(handle, inode);
4351 ext4_truncate_restart_trans(handle, inode,
4352 blocks_for_truncate(inode));
4355 ext4_free_blocks(handle, inode, 0, nr, 1,
4356 EXT4_FREE_BLOCKS_METADATA);
4360 * The block which we have just freed is
4361 * pointed to by an indirect block: journal it
4363 BUFFER_TRACE(parent_bh, "get_write_access");
4364 if (!ext4_journal_get_write_access(handle,
4367 BUFFER_TRACE(parent_bh,
4368 "call ext4_handle_dirty_metadata");
4369 ext4_handle_dirty_metadata(handle,
4376 /* We have reached the bottom of the tree. */
4377 BUFFER_TRACE(parent_bh, "free data blocks");
4378 ext4_free_data(handle, inode, parent_bh, first, last);
4382 int ext4_can_truncate(struct inode *inode)
4384 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4386 if (S_ISREG(inode->i_mode))
4388 if (S_ISDIR(inode->i_mode))
4390 if (S_ISLNK(inode->i_mode))
4391 return !ext4_inode_is_fast_symlink(inode);
4398 * We block out ext4_get_block() block instantiations across the entire
4399 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4400 * simultaneously on behalf of the same inode.
4402 * As we work through the truncate and commmit bits of it to the journal there
4403 * is one core, guiding principle: the file's tree must always be consistent on
4404 * disk. We must be able to restart the truncate after a crash.
4406 * The file's tree may be transiently inconsistent in memory (although it
4407 * probably isn't), but whenever we close off and commit a journal transaction,
4408 * the contents of (the filesystem + the journal) must be consistent and
4409 * restartable. It's pretty simple, really: bottom up, right to left (although
4410 * left-to-right works OK too).
4412 * Note that at recovery time, journal replay occurs *before* the restart of
4413 * truncate against the orphan inode list.
4415 * The committed inode has the new, desired i_size (which is the same as
4416 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4417 * that this inode's truncate did not complete and it will again call
4418 * ext4_truncate() to have another go. So there will be instantiated blocks
4419 * to the right of the truncation point in a crashed ext4 filesystem. But
4420 * that's fine - as long as they are linked from the inode, the post-crash
4421 * ext4_truncate() run will find them and release them.
4423 void ext4_truncate(struct inode *inode)
4426 struct ext4_inode_info *ei = EXT4_I(inode);
4427 __le32 *i_data = ei->i_data;
4428 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4429 struct address_space *mapping = inode->i_mapping;
4430 ext4_lblk_t offsets[4];
4435 ext4_lblk_t last_block;
4436 unsigned blocksize = inode->i_sb->s_blocksize;
4438 if (!ext4_can_truncate(inode))
4441 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4442 ei->i_state |= EXT4_STATE_DA_ALLOC_CLOSE;
4444 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
4445 ext4_ext_truncate(inode);
4449 handle = start_transaction(inode);
4451 return; /* AKPM: return what? */
4453 last_block = (inode->i_size + blocksize-1)
4454 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4456 if (inode->i_size & (blocksize - 1))
4457 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
4460 n = ext4_block_to_path(inode, last_block, offsets, NULL);
4462 goto out_stop; /* error */
4465 * OK. This truncate is going to happen. We add the inode to the
4466 * orphan list, so that if this truncate spans multiple transactions,
4467 * and we crash, we will resume the truncate when the filesystem
4468 * recovers. It also marks the inode dirty, to catch the new size.
4470 * Implication: the file must always be in a sane, consistent
4471 * truncatable state while each transaction commits.
4473 if (ext4_orphan_add(handle, inode))
4477 * From here we block out all ext4_get_block() callers who want to
4478 * modify the block allocation tree.
4480 down_write(&ei->i_data_sem);
4482 ext4_discard_preallocations(inode);
4485 * The orphan list entry will now protect us from any crash which
4486 * occurs before the truncate completes, so it is now safe to propagate
4487 * the new, shorter inode size (held for now in i_size) into the
4488 * on-disk inode. We do this via i_disksize, which is the value which
4489 * ext4 *really* writes onto the disk inode.
4491 ei->i_disksize = inode->i_size;
4493 if (n == 1) { /* direct blocks */
4494 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
4495 i_data + EXT4_NDIR_BLOCKS);
4499 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
4500 /* Kill the top of shared branch (not detached) */
4502 if (partial == chain) {
4503 /* Shared branch grows from the inode */
4504 ext4_free_branches(handle, inode, NULL,
4505 &nr, &nr+1, (chain+n-1) - partial);
4508 * We mark the inode dirty prior to restart,
4509 * and prior to stop. No need for it here.
4512 /* Shared branch grows from an indirect block */
4513 BUFFER_TRACE(partial->bh, "get_write_access");
4514 ext4_free_branches(handle, inode, partial->bh,
4516 partial->p+1, (chain+n-1) - partial);
4519 /* Clear the ends of indirect blocks on the shared branch */
4520 while (partial > chain) {
4521 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
4522 (__le32*)partial->bh->b_data+addr_per_block,
4523 (chain+n-1) - partial);
4524 BUFFER_TRACE(partial->bh, "call brelse");
4525 brelse(partial->bh);
4529 /* Kill the remaining (whole) subtrees */
4530 switch (offsets[0]) {
4532 nr = i_data[EXT4_IND_BLOCK];
4534 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4535 i_data[EXT4_IND_BLOCK] = 0;
4537 case EXT4_IND_BLOCK:
4538 nr = i_data[EXT4_DIND_BLOCK];
4540 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4541 i_data[EXT4_DIND_BLOCK] = 0;
4543 case EXT4_DIND_BLOCK:
4544 nr = i_data[EXT4_TIND_BLOCK];
4546 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4547 i_data[EXT4_TIND_BLOCK] = 0;
4549 case EXT4_TIND_BLOCK:
4553 up_write(&ei->i_data_sem);
4554 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4555 ext4_mark_inode_dirty(handle, inode);
4558 * In a multi-transaction truncate, we only make the final transaction
4562 ext4_handle_sync(handle);
4565 * If this was a simple ftruncate(), and the file will remain alive
4566 * then we need to clear up the orphan record which we created above.
4567 * However, if this was a real unlink then we were called by
4568 * ext4_delete_inode(), and we allow that function to clean up the
4569 * orphan info for us.
4572 ext4_orphan_del(handle, inode);
4574 ext4_journal_stop(handle);
4578 * ext4_get_inode_loc returns with an extra refcount against the inode's
4579 * underlying buffer_head on success. If 'in_mem' is true, we have all
4580 * data in memory that is needed to recreate the on-disk version of this
4583 static int __ext4_get_inode_loc(struct inode *inode,
4584 struct ext4_iloc *iloc, int in_mem)
4586 struct ext4_group_desc *gdp;
4587 struct buffer_head *bh;
4588 struct super_block *sb = inode->i_sb;
4590 int inodes_per_block, inode_offset;
4593 if (!ext4_valid_inum(sb, inode->i_ino))
4596 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4597 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4602 * Figure out the offset within the block group inode table
4604 inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
4605 inode_offset = ((inode->i_ino - 1) %
4606 EXT4_INODES_PER_GROUP(sb));
4607 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4608 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4610 bh = sb_getblk(sb, block);
4612 ext4_error(sb, "ext4_get_inode_loc", "unable to read "
4613 "inode block - inode=%lu, block=%llu",
4614 inode->i_ino, block);
4617 if (!buffer_uptodate(bh)) {
4621 * If the buffer has the write error flag, we have failed
4622 * to write out another inode in the same block. In this
4623 * case, we don't have to read the block because we may
4624 * read the old inode data successfully.
4626 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4627 set_buffer_uptodate(bh);
4629 if (buffer_uptodate(bh)) {
4630 /* someone brought it uptodate while we waited */
4636 * If we have all information of the inode in memory and this
4637 * is the only valid inode in the block, we need not read the
4641 struct buffer_head *bitmap_bh;
4644 start = inode_offset & ~(inodes_per_block - 1);
4646 /* Is the inode bitmap in cache? */
4647 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4652 * If the inode bitmap isn't in cache then the
4653 * optimisation may end up performing two reads instead
4654 * of one, so skip it.
4656 if (!buffer_uptodate(bitmap_bh)) {
4660 for (i = start; i < start + inodes_per_block; i++) {
4661 if (i == inode_offset)
4663 if (ext4_test_bit(i, bitmap_bh->b_data))
4667 if (i == start + inodes_per_block) {
4668 /* all other inodes are free, so skip I/O */
4669 memset(bh->b_data, 0, bh->b_size);
4670 set_buffer_uptodate(bh);
4678 * If we need to do any I/O, try to pre-readahead extra
4679 * blocks from the inode table.
4681 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4682 ext4_fsblk_t b, end, table;
4685 table = ext4_inode_table(sb, gdp);
4686 /* s_inode_readahead_blks is always a power of 2 */
4687 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4690 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4691 num = EXT4_INODES_PER_GROUP(sb);
4692 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4693 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4694 num -= ext4_itable_unused_count(sb, gdp);
4695 table += num / inodes_per_block;
4699 sb_breadahead(sb, b++);
4703 * There are other valid inodes in the buffer, this inode
4704 * has in-inode xattrs, or we don't have this inode in memory.
4705 * Read the block from disk.
4708 bh->b_end_io = end_buffer_read_sync;
4709 submit_bh(READ_META, bh);
4711 if (!buffer_uptodate(bh)) {
4712 ext4_error(sb, __func__,
4713 "unable to read inode block - inode=%lu, "
4714 "block=%llu", inode->i_ino, block);
4724 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4726 /* We have all inode data except xattrs in memory here. */
4727 return __ext4_get_inode_loc(inode, iloc,
4728 !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
4731 void ext4_set_inode_flags(struct inode *inode)
4733 unsigned int flags = EXT4_I(inode)->i_flags;
4735 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4736 if (flags & EXT4_SYNC_FL)
4737 inode->i_flags |= S_SYNC;
4738 if (flags & EXT4_APPEND_FL)
4739 inode->i_flags |= S_APPEND;
4740 if (flags & EXT4_IMMUTABLE_FL)
4741 inode->i_flags |= S_IMMUTABLE;
4742 if (flags & EXT4_NOATIME_FL)
4743 inode->i_flags |= S_NOATIME;
4744 if (flags & EXT4_DIRSYNC_FL)
4745 inode->i_flags |= S_DIRSYNC;
4748 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4749 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4751 unsigned int flags = ei->vfs_inode.i_flags;
4753 ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4754 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
4756 ei->i_flags |= EXT4_SYNC_FL;
4757 if (flags & S_APPEND)
4758 ei->i_flags |= EXT4_APPEND_FL;
4759 if (flags & S_IMMUTABLE)
4760 ei->i_flags |= EXT4_IMMUTABLE_FL;
4761 if (flags & S_NOATIME)
4762 ei->i_flags |= EXT4_NOATIME_FL;
4763 if (flags & S_DIRSYNC)
4764 ei->i_flags |= EXT4_DIRSYNC_FL;
4767 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4768 struct ext4_inode_info *ei)
4771 struct inode *inode = &(ei->vfs_inode);
4772 struct super_block *sb = inode->i_sb;
4774 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4775 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4776 /* we are using combined 48 bit field */
4777 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4778 le32_to_cpu(raw_inode->i_blocks_lo);
4779 if (ei->i_flags & EXT4_HUGE_FILE_FL) {
4780 /* i_blocks represent file system block size */
4781 return i_blocks << (inode->i_blkbits - 9);
4786 return le32_to_cpu(raw_inode->i_blocks_lo);
4790 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4792 struct ext4_iloc iloc;
4793 struct ext4_inode *raw_inode;
4794 struct ext4_inode_info *ei;
4795 struct inode *inode;
4796 journal_t *journal = EXT4_SB(sb)->s_journal;
4800 inode = iget_locked(sb, ino);
4802 return ERR_PTR(-ENOMEM);
4803 if (!(inode->i_state & I_NEW))
4809 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4812 raw_inode = ext4_raw_inode(&iloc);
4813 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4814 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4815 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4816 if (!(test_opt(inode->i_sb, NO_UID32))) {
4817 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4818 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4820 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4823 ei->i_dir_start_lookup = 0;
4824 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4825 /* We now have enough fields to check if the inode was active or not.
4826 * This is needed because nfsd might try to access dead inodes
4827 * the test is that same one that e2fsck uses
4828 * NeilBrown 1999oct15
4830 if (inode->i_nlink == 0) {
4831 if (inode->i_mode == 0 ||
4832 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4833 /* this inode is deleted */
4837 /* The only unlinked inodes we let through here have
4838 * valid i_mode and are being read by the orphan
4839 * recovery code: that's fine, we're about to complete
4840 * the process of deleting those. */
4842 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4843 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4844 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4845 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4847 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4848 inode->i_size = ext4_isize(raw_inode);
4849 ei->i_disksize = inode->i_size;
4851 ei->i_reserved_quota = 0;
4853 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4854 ei->i_block_group = iloc.block_group;
4855 ei->i_last_alloc_group = ~0;
4857 * NOTE! The in-memory inode i_data array is in little-endian order
4858 * even on big-endian machines: we do NOT byteswap the block numbers!
4860 for (block = 0; block < EXT4_N_BLOCKS; block++)
4861 ei->i_data[block] = raw_inode->i_block[block];
4862 INIT_LIST_HEAD(&ei->i_orphan);
4865 * Set transaction id's of transactions that have to be committed
4866 * to finish f[data]sync. We set them to currently running transaction
4867 * as we cannot be sure that the inode or some of its metadata isn't
4868 * part of the transaction - the inode could have been reclaimed and
4869 * now it is reread from disk.
4872 transaction_t *transaction;
4875 spin_lock(&journal->j_state_lock);
4876 if (journal->j_running_transaction)
4877 transaction = journal->j_running_transaction;
4879 transaction = journal->j_committing_transaction;
4881 tid = transaction->t_tid;
4883 tid = journal->j_commit_sequence;
4884 spin_unlock(&journal->j_state_lock);
4885 ei->i_sync_tid = tid;
4886 ei->i_datasync_tid = tid;
4889 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4890 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4891 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4892 EXT4_INODE_SIZE(inode->i_sb)) {
4896 if (ei->i_extra_isize == 0) {
4897 /* The extra space is currently unused. Use it. */
4898 ei->i_extra_isize = sizeof(struct ext4_inode) -
4899 EXT4_GOOD_OLD_INODE_SIZE;
4901 __le32 *magic = (void *)raw_inode +
4902 EXT4_GOOD_OLD_INODE_SIZE +
4904 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
4905 ei->i_state |= EXT4_STATE_XATTR;
4908 ei->i_extra_isize = 0;
4910 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4911 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4912 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4913 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4915 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4916 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4917 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4919 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4923 if (ei->i_file_acl &&
4924 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4925 ext4_error(sb, __func__,
4926 "bad extended attribute block %llu in inode #%lu",
4927 ei->i_file_acl, inode->i_ino);
4930 } else if (ei->i_flags & EXT4_EXTENTS_FL) {
4931 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4932 (S_ISLNK(inode->i_mode) &&
4933 !ext4_inode_is_fast_symlink(inode)))
4934 /* Validate extent which is part of inode */
4935 ret = ext4_ext_check_inode(inode);
4936 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4937 (S_ISLNK(inode->i_mode) &&
4938 !ext4_inode_is_fast_symlink(inode))) {
4939 /* Validate block references which are part of inode */
4940 ret = ext4_check_inode_blockref(inode);
4945 if (S_ISREG(inode->i_mode)) {
4946 inode->i_op = &ext4_file_inode_operations;
4947 inode->i_fop = &ext4_file_operations;
4948 ext4_set_aops(inode);
4949 } else if (S_ISDIR(inode->i_mode)) {
4950 inode->i_op = &ext4_dir_inode_operations;
4951 inode->i_fop = &ext4_dir_operations;
4952 } else if (S_ISLNK(inode->i_mode)) {
4953 if (ext4_inode_is_fast_symlink(inode)) {
4954 inode->i_op = &ext4_fast_symlink_inode_operations;
4955 nd_terminate_link(ei->i_data, inode->i_size,
4956 sizeof(ei->i_data) - 1);
4958 inode->i_op = &ext4_symlink_inode_operations;
4959 ext4_set_aops(inode);
4961 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4962 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4963 inode->i_op = &ext4_special_inode_operations;
4964 if (raw_inode->i_block[0])
4965 init_special_inode(inode, inode->i_mode,
4966 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4968 init_special_inode(inode, inode->i_mode,
4969 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4972 ext4_error(inode->i_sb, __func__,
4973 "bogus i_mode (%o) for inode=%lu",
4974 inode->i_mode, inode->i_ino);
4978 ext4_set_inode_flags(inode);
4979 unlock_new_inode(inode);
4985 return ERR_PTR(ret);
4988 static int ext4_inode_blocks_set(handle_t *handle,
4989 struct ext4_inode *raw_inode,
4990 struct ext4_inode_info *ei)
4992 struct inode *inode = &(ei->vfs_inode);
4993 u64 i_blocks = inode->i_blocks;
4994 struct super_block *sb = inode->i_sb;
4996 if (i_blocks <= ~0U) {
4998 * i_blocks can be represnted in a 32 bit variable
4999 * as multiple of 512 bytes
5001 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5002 raw_inode->i_blocks_high = 0;
5003 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
5006 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
5009 if (i_blocks <= 0xffffffffffffULL) {
5011 * i_blocks can be represented in a 48 bit variable
5012 * as multiple of 512 bytes
5014 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5015 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5016 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
5018 ei->i_flags |= EXT4_HUGE_FILE_FL;
5019 /* i_block is stored in file system block size */
5020 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5021 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5022 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5028 * Post the struct inode info into an on-disk inode location in the
5029 * buffer-cache. This gobbles the caller's reference to the
5030 * buffer_head in the inode location struct.
5032 * The caller must have write access to iloc->bh.
5034 static int ext4_do_update_inode(handle_t *handle,
5035 struct inode *inode,
5036 struct ext4_iloc *iloc)
5038 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5039 struct ext4_inode_info *ei = EXT4_I(inode);
5040 struct buffer_head *bh = iloc->bh;
5041 int err = 0, rc, block;
5043 /* For fields not not tracking in the in-memory inode,
5044 * initialise them to zero for new inodes. */
5045 if (ei->i_state & EXT4_STATE_NEW)
5046 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5048 ext4_get_inode_flags(ei);
5049 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5050 if (!(test_opt(inode->i_sb, NO_UID32))) {
5051 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
5052 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
5054 * Fix up interoperability with old kernels. Otherwise, old inodes get
5055 * re-used with the upper 16 bits of the uid/gid intact
5058 raw_inode->i_uid_high =
5059 cpu_to_le16(high_16_bits(inode->i_uid));
5060 raw_inode->i_gid_high =
5061 cpu_to_le16(high_16_bits(inode->i_gid));
5063 raw_inode->i_uid_high = 0;
5064 raw_inode->i_gid_high = 0;
5067 raw_inode->i_uid_low =
5068 cpu_to_le16(fs_high2lowuid(inode->i_uid));
5069 raw_inode->i_gid_low =
5070 cpu_to_le16(fs_high2lowgid(inode->i_gid));
5071 raw_inode->i_uid_high = 0;
5072 raw_inode->i_gid_high = 0;
5074 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5076 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5077 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5078 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5079 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5081 if (ext4_inode_blocks_set(handle, raw_inode, ei))
5083 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5084 raw_inode->i_flags = cpu_to_le32(ei->i_flags);
5085 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
5086 cpu_to_le32(EXT4_OS_HURD))
5087 raw_inode->i_file_acl_high =
5088 cpu_to_le16(ei->i_file_acl >> 32);
5089 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5090 ext4_isize_set(raw_inode, ei->i_disksize);
5091 if (ei->i_disksize > 0x7fffffffULL) {
5092 struct super_block *sb = inode->i_sb;
5093 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
5094 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
5095 EXT4_SB(sb)->s_es->s_rev_level ==
5096 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
5097 /* If this is the first large file
5098 * created, add a flag to the superblock.
5100 err = ext4_journal_get_write_access(handle,
5101 EXT4_SB(sb)->s_sbh);
5104 ext4_update_dynamic_rev(sb);
5105 EXT4_SET_RO_COMPAT_FEATURE(sb,
5106 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
5108 ext4_handle_sync(handle);
5109 err = ext4_handle_dirty_metadata(handle, inode,
5110 EXT4_SB(sb)->s_sbh);
5113 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5114 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5115 if (old_valid_dev(inode->i_rdev)) {
5116 raw_inode->i_block[0] =
5117 cpu_to_le32(old_encode_dev(inode->i_rdev));
5118 raw_inode->i_block[1] = 0;
5120 raw_inode->i_block[0] = 0;
5121 raw_inode->i_block[1] =
5122 cpu_to_le32(new_encode_dev(inode->i_rdev));
5123 raw_inode->i_block[2] = 0;
5126 for (block = 0; block < EXT4_N_BLOCKS; block++)
5127 raw_inode->i_block[block] = ei->i_data[block];
5129 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5130 if (ei->i_extra_isize) {
5131 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5132 raw_inode->i_version_hi =
5133 cpu_to_le32(inode->i_version >> 32);
5134 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
5137 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5138 rc = ext4_handle_dirty_metadata(handle, inode, bh);
5141 ei->i_state &= ~EXT4_STATE_NEW;
5143 ext4_update_inode_fsync_trans(handle, inode, 0);
5146 ext4_std_error(inode->i_sb, err);
5151 * ext4_write_inode()
5153 * We are called from a few places:
5155 * - Within generic_file_write() for O_SYNC files.
5156 * Here, there will be no transaction running. We wait for any running
5157 * trasnaction to commit.
5159 * - Within sys_sync(), kupdate and such.
5160 * We wait on commit, if tol to.
5162 * - Within prune_icache() (PF_MEMALLOC == true)
5163 * Here we simply return. We can't afford to block kswapd on the
5166 * In all cases it is actually safe for us to return without doing anything,
5167 * because the inode has been copied into a raw inode buffer in
5168 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
5171 * Note that we are absolutely dependent upon all inode dirtiers doing the
5172 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5173 * which we are interested.
5175 * It would be a bug for them to not do this. The code:
5177 * mark_inode_dirty(inode)
5179 * inode->i_size = expr;
5181 * is in error because a kswapd-driven write_inode() could occur while
5182 * `stuff()' is running, and the new i_size will be lost. Plus the inode
5183 * will no longer be on the superblock's dirty inode list.
5185 int ext4_write_inode(struct inode *inode, int wait)
5189 if (current->flags & PF_MEMALLOC)
5192 if (EXT4_SB(inode->i_sb)->s_journal) {
5193 if (ext4_journal_current_handle()) {
5194 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5202 err = ext4_force_commit(inode->i_sb);
5204 struct ext4_iloc iloc;
5206 err = ext4_get_inode_loc(inode, &iloc);
5210 sync_dirty_buffer(iloc.bh);
5211 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5212 ext4_error(inode->i_sb, __func__,
5213 "IO error syncing inode, "
5214 "inode=%lu, block=%llu",
5216 (unsigned long long)iloc.bh->b_blocknr);
5226 * Called from notify_change.
5228 * We want to trap VFS attempts to truncate the file as soon as
5229 * possible. In particular, we want to make sure that when the VFS
5230 * shrinks i_size, we put the inode on the orphan list and modify
5231 * i_disksize immediately, so that during the subsequent flushing of
5232 * dirty pages and freeing of disk blocks, we can guarantee that any
5233 * commit will leave the blocks being flushed in an unused state on
5234 * disk. (On recovery, the inode will get truncated and the blocks will
5235 * be freed, so we have a strong guarantee that no future commit will
5236 * leave these blocks visible to the user.)
5238 * Another thing we have to assure is that if we are in ordered mode
5239 * and inode is still attached to the committing transaction, we must
5240 * we start writeout of all the dirty pages which are being truncated.
5241 * This way we are sure that all the data written in the previous
5242 * transaction are already on disk (truncate waits for pages under
5245 * Called with inode->i_mutex down.
5247 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5249 struct inode *inode = dentry->d_inode;
5251 const unsigned int ia_valid = attr->ia_valid;
5253 error = inode_change_ok(inode, attr);
5257 if (ia_valid & ATTR_SIZE)
5259 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
5260 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
5263 /* (user+group)*(old+new) structure, inode write (sb,
5264 * inode block, ? - but truncate inode update has it) */
5265 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
5266 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
5267 if (IS_ERR(handle)) {
5268 error = PTR_ERR(handle);
5271 error = dquot_transfer(inode, attr);
5273 ext4_journal_stop(handle);
5276 /* Update corresponding info in inode so that everything is in
5277 * one transaction */
5278 if (attr->ia_valid & ATTR_UID)
5279 inode->i_uid = attr->ia_uid;
5280 if (attr->ia_valid & ATTR_GID)
5281 inode->i_gid = attr->ia_gid;
5282 error = ext4_mark_inode_dirty(handle, inode);
5283 ext4_journal_stop(handle);
5286 if (attr->ia_valid & ATTR_SIZE) {
5287 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
5288 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5290 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5297 if (S_ISREG(inode->i_mode) &&
5298 attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
5301 handle = ext4_journal_start(inode, 3);
5302 if (IS_ERR(handle)) {
5303 error = PTR_ERR(handle);
5307 error = ext4_orphan_add(handle, inode);
5308 EXT4_I(inode)->i_disksize = attr->ia_size;
5309 rc = ext4_mark_inode_dirty(handle, inode);
5312 ext4_journal_stop(handle);
5314 if (ext4_should_order_data(inode)) {
5315 error = ext4_begin_ordered_truncate(inode,
5318 /* Do as much error cleanup as possible */
5319 handle = ext4_journal_start(inode, 3);
5320 if (IS_ERR(handle)) {
5321 ext4_orphan_del(NULL, inode);
5324 ext4_orphan_del(handle, inode);
5325 ext4_journal_stop(handle);
5331 rc = inode_setattr(inode, attr);
5333 /* If inode_setattr's call to ext4_truncate failed to get a
5334 * transaction handle at all, we need to clean up the in-core
5335 * orphan list manually. */
5337 ext4_orphan_del(NULL, inode);
5339 if (!rc && (ia_valid & ATTR_MODE))
5340 rc = ext4_acl_chmod(inode);
5343 ext4_std_error(inode->i_sb, error);
5349 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
5352 struct inode *inode;
5353 unsigned long delalloc_blocks;
5355 inode = dentry->d_inode;
5356 generic_fillattr(inode, stat);
5359 * We can't update i_blocks if the block allocation is delayed
5360 * otherwise in the case of system crash before the real block
5361 * allocation is done, we will have i_blocks inconsistent with
5362 * on-disk file blocks.
5363 * We always keep i_blocks updated together with real
5364 * allocation. But to not confuse with user, stat
5365 * will return the blocks that include the delayed allocation
5366 * blocks for this file.
5368 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
5369 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
5370 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
5372 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
5376 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
5381 /* if nrblocks are contiguous */
5384 * With N contiguous data blocks, it need at most
5385 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
5386 * 2 dindirect blocks
5389 indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
5390 return indirects + 3;
5393 * if nrblocks are not contiguous, worse case, each block touch
5394 * a indirect block, and each indirect block touch a double indirect
5395 * block, plus a triple indirect block
5397 indirects = nrblocks * 2 + 1;
5401 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5403 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
5404 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
5405 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
5409 * Account for index blocks, block groups bitmaps and block group
5410 * descriptor blocks if modify datablocks and index blocks
5411 * worse case, the indexs blocks spread over different block groups
5413 * If datablocks are discontiguous, they are possible to spread over
5414 * different block groups too. If they are contiuguous, with flexbg,
5415 * they could still across block group boundary.
5417 * Also account for superblock, inode, quota and xattr blocks
5419 int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5421 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5427 * How many index blocks need to touch to modify nrblocks?
5428 * The "Chunk" flag indicating whether the nrblocks is
5429 * physically contiguous on disk
5431 * For Direct IO and fallocate, they calls get_block to allocate
5432 * one single extent at a time, so they could set the "Chunk" flag
5434 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
5439 * Now let's see how many group bitmaps and group descriptors need
5449 if (groups > ngroups)
5451 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5452 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5454 /* bitmaps and block group descriptor blocks */
5455 ret += groups + gdpblocks;
5457 /* Blocks for super block, inode, quota and xattr blocks */
5458 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5464 * Calulate the total number of credits to reserve to fit
5465 * the modification of a single pages into a single transaction,
5466 * which may include multiple chunks of block allocations.
5468 * This could be called via ext4_write_begin()
5470 * We need to consider the worse case, when
5471 * one new block per extent.
5473 int ext4_writepage_trans_blocks(struct inode *inode)
5475 int bpp = ext4_journal_blocks_per_page(inode);
5478 ret = ext4_meta_trans_blocks(inode, bpp, 0);
5480 /* Account for data blocks for journalled mode */
5481 if (ext4_should_journal_data(inode))
5487 * Calculate the journal credits for a chunk of data modification.
5489 * This is called from DIO, fallocate or whoever calling
5490 * ext4_get_blocks() to map/allocate a chunk of contiguous disk blocks.
5492 * journal buffers for data blocks are not included here, as DIO
5493 * and fallocate do no need to journal data buffers.
5495 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5497 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5501 * The caller must have previously called ext4_reserve_inode_write().
5502 * Give this, we know that the caller already has write access to iloc->bh.
5504 int ext4_mark_iloc_dirty(handle_t *handle,
5505 struct inode *inode, struct ext4_iloc *iloc)
5509 if (test_opt(inode->i_sb, I_VERSION))
5510 inode_inc_iversion(inode);
5512 /* the do_update_inode consumes one bh->b_count */
5515 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5516 err = ext4_do_update_inode(handle, inode, iloc);
5522 * On success, We end up with an outstanding reference count against
5523 * iloc->bh. This _must_ be cleaned up later.
5527 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5528 struct ext4_iloc *iloc)
5532 err = ext4_get_inode_loc(inode, iloc);
5534 BUFFER_TRACE(iloc->bh, "get_write_access");
5535 err = ext4_journal_get_write_access(handle, iloc->bh);
5541 ext4_std_error(inode->i_sb, err);
5546 * Expand an inode by new_extra_isize bytes.
5547 * Returns 0 on success or negative error number on failure.
5549 static int ext4_expand_extra_isize(struct inode *inode,
5550 unsigned int new_extra_isize,
5551 struct ext4_iloc iloc,
5554 struct ext4_inode *raw_inode;
5555 struct ext4_xattr_ibody_header *header;
5556 struct ext4_xattr_entry *entry;
5558 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5561 raw_inode = ext4_raw_inode(&iloc);
5563 header = IHDR(inode, raw_inode);
5564 entry = IFIRST(header);
5566 /* No extended attributes present */
5567 if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
5568 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5569 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5571 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5575 /* try to expand with EAs present */
5576 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5581 * What we do here is to mark the in-core inode as clean with respect to inode
5582 * dirtiness (it may still be data-dirty).
5583 * This means that the in-core inode may be reaped by prune_icache
5584 * without having to perform any I/O. This is a very good thing,
5585 * because *any* task may call prune_icache - even ones which
5586 * have a transaction open against a different journal.
5588 * Is this cheating? Not really. Sure, we haven't written the
5589 * inode out, but prune_icache isn't a user-visible syncing function.
5590 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5591 * we start and wait on commits.
5593 * Is this efficient/effective? Well, we're being nice to the system
5594 * by cleaning up our inodes proactively so they can be reaped
5595 * without I/O. But we are potentially leaving up to five seconds'
5596 * worth of inodes floating about which prune_icache wants us to
5597 * write out. One way to fix that would be to get prune_icache()
5598 * to do a write_super() to free up some memory. It has the desired
5601 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5603 struct ext4_iloc iloc;
5604 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5605 static unsigned int mnt_count;
5609 err = ext4_reserve_inode_write(handle, inode, &iloc);
5610 if (ext4_handle_valid(handle) &&
5611 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5612 !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
5614 * We need extra buffer credits since we may write into EA block
5615 * with this same handle. If journal_extend fails, then it will
5616 * only result in a minor loss of functionality for that inode.
5617 * If this is felt to be critical, then e2fsck should be run to
5618 * force a large enough s_min_extra_isize.
5620 if ((jbd2_journal_extend(handle,
5621 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5622 ret = ext4_expand_extra_isize(inode,
5623 sbi->s_want_extra_isize,
5626 EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
5628 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5629 ext4_warning(inode->i_sb, __func__,
5630 "Unable to expand inode %lu. Delete"
5631 " some EAs or run e2fsck.",
5634 le16_to_cpu(sbi->s_es->s_mnt_count);
5640 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5645 * ext4_dirty_inode() is called from __mark_inode_dirty()
5647 * We're really interested in the case where a file is being extended.
5648 * i_size has been changed by generic_commit_write() and we thus need
5649 * to include the updated inode in the current transaction.
5651 * Also, dquot_alloc_block() will always dirty the inode when blocks
5652 * are allocated to the file.
5654 * If the inode is marked synchronous, we don't honour that here - doing
5655 * so would cause a commit on atime updates, which we don't bother doing.
5656 * We handle synchronous inodes at the highest possible level.
5658 void ext4_dirty_inode(struct inode *inode)
5662 handle = ext4_journal_start(inode, 2);
5666 ext4_mark_inode_dirty(handle, inode);
5668 ext4_journal_stop(handle);
5675 * Bind an inode's backing buffer_head into this transaction, to prevent
5676 * it from being flushed to disk early. Unlike
5677 * ext4_reserve_inode_write, this leaves behind no bh reference and
5678 * returns no iloc structure, so the caller needs to repeat the iloc
5679 * lookup to mark the inode dirty later.
5681 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5683 struct ext4_iloc iloc;
5687 err = ext4_get_inode_loc(inode, &iloc);
5689 BUFFER_TRACE(iloc.bh, "get_write_access");
5690 err = jbd2_journal_get_write_access(handle, iloc.bh);
5692 err = ext4_handle_dirty_metadata(handle,
5698 ext4_std_error(inode->i_sb, err);
5703 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5710 * We have to be very careful here: changing a data block's
5711 * journaling status dynamically is dangerous. If we write a
5712 * data block to the journal, change the status and then delete
5713 * that block, we risk forgetting to revoke the old log record
5714 * from the journal and so a subsequent replay can corrupt data.
5715 * So, first we make sure that the journal is empty and that
5716 * nobody is changing anything.
5719 journal = EXT4_JOURNAL(inode);
5722 if (is_journal_aborted(journal))
5725 jbd2_journal_lock_updates(journal);
5726 jbd2_journal_flush(journal);
5729 * OK, there are no updates running now, and all cached data is
5730 * synced to disk. We are now in a completely consistent state
5731 * which doesn't have anything in the journal, and we know that
5732 * no filesystem updates are running, so it is safe to modify
5733 * the inode's in-core data-journaling state flag now.
5737 EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
5739 EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
5740 ext4_set_aops(inode);
5742 jbd2_journal_unlock_updates(journal);
5744 /* Finally we can mark the inode as dirty. */
5746 handle = ext4_journal_start(inode, 1);
5748 return PTR_ERR(handle);
5750 err = ext4_mark_inode_dirty(handle, inode);
5751 ext4_handle_sync(handle);
5752 ext4_journal_stop(handle);
5753 ext4_std_error(inode->i_sb, err);
5758 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5760 return !buffer_mapped(bh);
5763 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5765 struct page *page = vmf->page;
5770 struct file *file = vma->vm_file;
5771 struct inode *inode = file->f_path.dentry->d_inode;
5772 struct address_space *mapping = inode->i_mapping;
5775 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5776 * get i_mutex because we are already holding mmap_sem.
5778 down_read(&inode->i_alloc_sem);
5779 size = i_size_read(inode);
5780 if (page->mapping != mapping || size <= page_offset(page)
5781 || !PageUptodate(page)) {
5782 /* page got truncated from under us? */
5786 if (PageMappedToDisk(page))
5789 if (page->index == size >> PAGE_CACHE_SHIFT)
5790 len = size & ~PAGE_CACHE_MASK;
5792 len = PAGE_CACHE_SIZE;
5796 * return if we have all the buffers mapped. This avoid
5797 * the need to call write_begin/write_end which does a
5798 * journal_start/journal_stop which can block and take
5801 if (page_has_buffers(page)) {
5802 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5803 ext4_bh_unmapped)) {
5810 * OK, we need to fill the hole... Do write_begin write_end
5811 * to do block allocation/reservation.We are not holding
5812 * inode.i__mutex here. That allow * parallel write_begin,
5813 * write_end call. lock_page prevent this from happening
5814 * on the same page though
5816 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5817 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5820 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5821 len, len, page, fsdata);
5827 ret = VM_FAULT_SIGBUS;
5828 up_read(&inode->i_alloc_sem);