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>
41 #include <linux/kernel.h>
42 #include <linux/printk.h>
43 #include <linux/slab.h>
44 #include <linux/ratelimit.h>
46 #include "ext4_jbd2.h"
49 #include "ext4_extents.h"
51 #include <trace/events/ext4.h>
53 #define MPAGE_DA_EXTENT_TAIL 0x01
55 static inline int ext4_begin_ordered_truncate(struct inode *inode,
58 trace_ext4_begin_ordered_truncate(inode, new_size);
60 * If jinode is zero, then we never opened the file for
61 * writing, so there's no need to call
62 * jbd2_journal_begin_ordered_truncate() since there's no
63 * outstanding writes we need to flush.
65 if (!EXT4_I(inode)->jinode)
67 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
68 EXT4_I(inode)->jinode,
72 static void ext4_invalidatepage(struct page *page, unsigned long offset);
73 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
74 struct buffer_head *bh_result, int create);
75 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
76 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
77 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
78 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
81 * Test whether an inode is a fast symlink.
83 static int ext4_inode_is_fast_symlink(struct inode *inode)
85 int ea_blocks = EXT4_I(inode)->i_file_acl ?
86 (inode->i_sb->s_blocksize >> 9) : 0;
88 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
92 * Work out how many blocks we need to proceed with the next chunk of a
93 * truncate transaction.
95 static unsigned long blocks_for_truncate(struct inode *inode)
99 needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
101 /* Give ourselves just enough room to cope with inodes in which
102 * i_blocks is corrupt: we've seen disk corruptions in the past
103 * which resulted in random data in an inode which looked enough
104 * like a regular file for ext4 to try to delete it. Things
105 * will go a bit crazy if that happens, but at least we should
106 * try not to panic the whole kernel. */
110 /* But we need to bound the transaction so we don't overflow the
112 if (needed > EXT4_MAX_TRANS_DATA)
113 needed = EXT4_MAX_TRANS_DATA;
115 return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
119 * Truncate transactions can be complex and absolutely huge. So we need to
120 * be able to restart the transaction at a conventient checkpoint to make
121 * sure we don't overflow the journal.
123 * start_transaction gets us a new handle for a truncate transaction,
124 * and extend_transaction tries to extend the existing one a bit. If
125 * extend fails, we need to propagate the failure up and restart the
126 * transaction in the top-level truncate loop. --sct
128 static handle_t *start_transaction(struct inode *inode)
132 result = ext4_journal_start(inode, blocks_for_truncate(inode));
136 ext4_std_error(inode->i_sb, PTR_ERR(result));
141 * Try to extend this transaction for the purposes of truncation.
143 * Returns 0 if we managed to create more room. If we can't create more
144 * room, and the transaction must be restarted we return 1.
146 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
148 if (!ext4_handle_valid(handle))
150 if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
152 if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
158 * Restart the transaction associated with *handle. This does a commit,
159 * so before we call here everything must be consistently dirtied against
162 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
168 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
169 * moment, get_block can be called only for blocks inside i_size since
170 * page cache has been already dropped and writes are blocked by
171 * i_mutex. So we can safely drop the i_data_sem here.
173 BUG_ON(EXT4_JOURNAL(inode) == NULL);
174 jbd_debug(2, "restarting handle %p\n", handle);
175 up_write(&EXT4_I(inode)->i_data_sem);
176 ret = ext4_journal_restart(handle, nblocks);
177 down_write(&EXT4_I(inode)->i_data_sem);
178 ext4_discard_preallocations(inode);
184 * Called at the last iput() if i_nlink is zero.
186 void ext4_evict_inode(struct inode *inode)
191 trace_ext4_evict_inode(inode);
193 ext4_ioend_wait(inode);
195 if (inode->i_nlink) {
196 truncate_inode_pages(&inode->i_data, 0);
200 if (!is_bad_inode(inode))
201 dquot_initialize(inode);
203 if (ext4_should_order_data(inode))
204 ext4_begin_ordered_truncate(inode, 0);
205 truncate_inode_pages(&inode->i_data, 0);
207 if (is_bad_inode(inode))
210 handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
211 if (IS_ERR(handle)) {
212 ext4_std_error(inode->i_sb, PTR_ERR(handle));
214 * If we're going to skip the normal cleanup, we still need to
215 * make sure that the in-core orphan linked list is properly
218 ext4_orphan_del(NULL, inode);
223 ext4_handle_sync(handle);
225 err = ext4_mark_inode_dirty(handle, inode);
227 ext4_warning(inode->i_sb,
228 "couldn't mark inode dirty (err %d)", err);
232 ext4_truncate(inode);
235 * ext4_ext_truncate() doesn't reserve any slop when it
236 * restarts journal transactions; therefore there may not be
237 * enough credits left in the handle to remove the inode from
238 * the orphan list and set the dtime field.
240 if (!ext4_handle_has_enough_credits(handle, 3)) {
241 err = ext4_journal_extend(handle, 3);
243 err = ext4_journal_restart(handle, 3);
245 ext4_warning(inode->i_sb,
246 "couldn't extend journal (err %d)", err);
248 ext4_journal_stop(handle);
249 ext4_orphan_del(NULL, inode);
255 * Kill off the orphan record which ext4_truncate created.
256 * AKPM: I think this can be inside the above `if'.
257 * Note that ext4_orphan_del() has to be able to cope with the
258 * deletion of a non-existent orphan - this is because we don't
259 * know if ext4_truncate() actually created an orphan record.
260 * (Well, we could do this if we need to, but heck - it works)
262 ext4_orphan_del(handle, inode);
263 EXT4_I(inode)->i_dtime = get_seconds();
266 * One subtle ordering requirement: if anything has gone wrong
267 * (transaction abort, IO errors, whatever), then we can still
268 * do these next steps (the fs will already have been marked as
269 * having errors), but we can't free the inode if the mark_dirty
272 if (ext4_mark_inode_dirty(handle, inode))
273 /* If that failed, just do the required in-core inode clear. */
274 ext4_clear_inode(inode);
276 ext4_free_inode(handle, inode);
277 ext4_journal_stop(handle);
280 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
286 struct buffer_head *bh;
289 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
291 p->key = *(p->p = v);
296 * ext4_block_to_path - parse the block number into array of offsets
297 * @inode: inode in question (we are only interested in its superblock)
298 * @i_block: block number to be parsed
299 * @offsets: array to store the offsets in
300 * @boundary: set this non-zero if the referred-to block is likely to be
301 * followed (on disk) by an indirect block.
303 * To store the locations of file's data ext4 uses a data structure common
304 * for UNIX filesystems - tree of pointers anchored in the inode, with
305 * data blocks at leaves and indirect blocks in intermediate nodes.
306 * This function translates the block number into path in that tree -
307 * return value is the path length and @offsets[n] is the offset of
308 * pointer to (n+1)th node in the nth one. If @block is out of range
309 * (negative or too large) warning is printed and zero returned.
311 * Note: function doesn't find node addresses, so no IO is needed. All
312 * we need to know is the capacity of indirect blocks (taken from the
317 * Portability note: the last comparison (check that we fit into triple
318 * indirect block) is spelled differently, because otherwise on an
319 * architecture with 32-bit longs and 8Kb pages we might get into trouble
320 * if our filesystem had 8Kb blocks. We might use long long, but that would
321 * kill us on x86. Oh, well, at least the sign propagation does not matter -
322 * i_block would have to be negative in the very beginning, so we would not
326 static int ext4_block_to_path(struct inode *inode,
328 ext4_lblk_t offsets[4], int *boundary)
330 int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
331 int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
332 const long direct_blocks = EXT4_NDIR_BLOCKS,
333 indirect_blocks = ptrs,
334 double_blocks = (1 << (ptrs_bits * 2));
338 if (i_block < direct_blocks) {
339 offsets[n++] = i_block;
340 final = direct_blocks;
341 } else if ((i_block -= direct_blocks) < indirect_blocks) {
342 offsets[n++] = EXT4_IND_BLOCK;
343 offsets[n++] = i_block;
345 } else if ((i_block -= indirect_blocks) < double_blocks) {
346 offsets[n++] = EXT4_DIND_BLOCK;
347 offsets[n++] = i_block >> ptrs_bits;
348 offsets[n++] = i_block & (ptrs - 1);
350 } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
351 offsets[n++] = EXT4_TIND_BLOCK;
352 offsets[n++] = i_block >> (ptrs_bits * 2);
353 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
354 offsets[n++] = i_block & (ptrs - 1);
357 ext4_warning(inode->i_sb, "block %lu > max in inode %lu",
358 i_block + direct_blocks +
359 indirect_blocks + double_blocks, inode->i_ino);
362 *boundary = final - 1 - (i_block & (ptrs - 1));
366 static int __ext4_check_blockref(const char *function, unsigned int line,
368 __le32 *p, unsigned int max)
370 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
374 while (bref < p+max) {
375 blk = le32_to_cpu(*bref++);
377 unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
379 es->s_last_error_block = cpu_to_le64(blk);
380 ext4_error_inode(inode, function, line, blk,
389 #define ext4_check_indirect_blockref(inode, bh) \
390 __ext4_check_blockref(__func__, __LINE__, inode, \
391 (__le32 *)(bh)->b_data, \
392 EXT4_ADDR_PER_BLOCK((inode)->i_sb))
394 #define ext4_check_inode_blockref(inode) \
395 __ext4_check_blockref(__func__, __LINE__, inode, \
396 EXT4_I(inode)->i_data, \
400 * ext4_get_branch - read the chain of indirect blocks leading to data
401 * @inode: inode in question
402 * @depth: depth of the chain (1 - direct pointer, etc.)
403 * @offsets: offsets of pointers in inode/indirect blocks
404 * @chain: place to store the result
405 * @err: here we store the error value
407 * Function fills the array of triples <key, p, bh> and returns %NULL
408 * if everything went OK or the pointer to the last filled triple
409 * (incomplete one) otherwise. Upon the return chain[i].key contains
410 * the number of (i+1)-th block in the chain (as it is stored in memory,
411 * i.e. little-endian 32-bit), chain[i].p contains the address of that
412 * number (it points into struct inode for i==0 and into the bh->b_data
413 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
414 * block for i>0 and NULL for i==0. In other words, it holds the block
415 * numbers of the chain, addresses they were taken from (and where we can
416 * verify that chain did not change) and buffer_heads hosting these
419 * Function stops when it stumbles upon zero pointer (absent block)
420 * (pointer to last triple returned, *@err == 0)
421 * or when it gets an IO error reading an indirect block
422 * (ditto, *@err == -EIO)
423 * or when it reads all @depth-1 indirect blocks successfully and finds
424 * the whole chain, all way to the data (returns %NULL, *err == 0).
426 * Need to be called with
427 * down_read(&EXT4_I(inode)->i_data_sem)
429 static Indirect *ext4_get_branch(struct inode *inode, int depth,
430 ext4_lblk_t *offsets,
431 Indirect chain[4], int *err)
433 struct super_block *sb = inode->i_sb;
435 struct buffer_head *bh;
438 /* i_data is not going away, no lock needed */
439 add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
443 bh = sb_getblk(sb, le32_to_cpu(p->key));
447 if (!bh_uptodate_or_lock(bh)) {
448 if (bh_submit_read(bh) < 0) {
452 /* validate block references */
453 if (ext4_check_indirect_blockref(inode, bh)) {
459 add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
473 * ext4_find_near - find a place for allocation with sufficient locality
475 * @ind: descriptor of indirect block.
477 * This function returns the preferred place for block allocation.
478 * It is used when heuristic for sequential allocation fails.
480 * + if there is a block to the left of our position - allocate near it.
481 * + if pointer will live in indirect block - allocate near that block.
482 * + if pointer will live in inode - allocate in the same
485 * In the latter case we colour the starting block by the callers PID to
486 * prevent it from clashing with concurrent allocations for a different inode
487 * in the same block group. The PID is used here so that functionally related
488 * files will be close-by on-disk.
490 * Caller must make sure that @ind is valid and will stay that way.
492 static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
494 struct ext4_inode_info *ei = EXT4_I(inode);
495 __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
497 ext4_fsblk_t bg_start;
498 ext4_fsblk_t last_block;
499 ext4_grpblk_t colour;
500 ext4_group_t block_group;
501 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
503 /* Try to find previous block */
504 for (p = ind->p - 1; p >= start; p--) {
506 return le32_to_cpu(*p);
509 /* No such thing, so let's try location of indirect block */
511 return ind->bh->b_blocknr;
514 * It is going to be referred to from the inode itself? OK, just put it
515 * into the same cylinder group then.
517 block_group = ei->i_block_group;
518 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
519 block_group &= ~(flex_size-1);
520 if (S_ISREG(inode->i_mode))
523 bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
524 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
527 * If we are doing delayed allocation, we don't need take
528 * colour into account.
530 if (test_opt(inode->i_sb, DELALLOC))
533 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
534 colour = (current->pid % 16) *
535 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
537 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
538 return bg_start + colour;
542 * ext4_find_goal - find a preferred place for allocation.
544 * @block: block we want
545 * @partial: pointer to the last triple within a chain
547 * Normally this function find the preferred place for block allocation,
549 * Because this is only used for non-extent files, we limit the block nr
552 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
558 * XXX need to get goal block from mballoc's data structures
561 goal = ext4_find_near(inode, partial);
562 goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
567 * ext4_blks_to_allocate - Look up the block map and count the number
568 * of direct blocks need to be allocated for the given branch.
570 * @branch: chain of indirect blocks
571 * @k: number of blocks need for indirect blocks
572 * @blks: number of data blocks to be mapped.
573 * @blocks_to_boundary: the offset in the indirect block
575 * return the total number of blocks to be allocate, including the
576 * direct and indirect blocks.
578 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
579 int blocks_to_boundary)
581 unsigned int count = 0;
584 * Simple case, [t,d]Indirect block(s) has not allocated yet
585 * then it's clear blocks on that path have not allocated
588 /* right now we don't handle cross boundary allocation */
589 if (blks < blocks_to_boundary + 1)
592 count += blocks_to_boundary + 1;
597 while (count < blks && count <= blocks_to_boundary &&
598 le32_to_cpu(*(branch[0].p + count)) == 0) {
605 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
606 * @handle: handle for this transaction
607 * @inode: inode which needs allocated blocks
608 * @iblock: the logical block to start allocated at
609 * @goal: preferred physical block of allocation
610 * @indirect_blks: the number of blocks need to allocate for indirect
612 * @blks: number of desired blocks
613 * @new_blocks: on return it will store the new block numbers for
614 * the indirect blocks(if needed) and the first direct block,
615 * @err: on return it will store the error code
617 * This function will return the number of blocks allocated as
618 * requested by the passed-in parameters.
620 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
621 ext4_lblk_t iblock, ext4_fsblk_t goal,
622 int indirect_blks, int blks,
623 ext4_fsblk_t new_blocks[4], int *err)
625 struct ext4_allocation_request ar;
627 unsigned long count = 0, blk_allocated = 0;
629 ext4_fsblk_t current_block = 0;
633 * Here we try to allocate the requested multiple blocks at once,
634 * on a best-effort basis.
635 * To build a branch, we should allocate blocks for
636 * the indirect blocks(if not allocated yet), and at least
637 * the first direct block of this branch. That's the
638 * minimum number of blocks need to allocate(required)
640 /* first we try to allocate the indirect blocks */
641 target = indirect_blks;
644 /* allocating blocks for indirect blocks and direct blocks */
645 current_block = ext4_new_meta_blocks(handle, inode, goal,
650 if (unlikely(current_block + count > EXT4_MAX_BLOCK_FILE_PHYS)) {
651 EXT4_ERROR_INODE(inode,
652 "current_block %llu + count %lu > %d!",
653 current_block, count,
654 EXT4_MAX_BLOCK_FILE_PHYS);
660 /* allocate blocks for indirect blocks */
661 while (index < indirect_blks && count) {
662 new_blocks[index++] = current_block++;
667 * save the new block number
668 * for the first direct block
670 new_blocks[index] = current_block;
671 printk(KERN_INFO "%s returned more blocks than "
672 "requested\n", __func__);
678 target = blks - count ;
679 blk_allocated = count;
682 /* Now allocate data blocks */
683 memset(&ar, 0, sizeof(ar));
688 if (S_ISREG(inode->i_mode))
689 /* enable in-core preallocation only for regular files */
690 ar.flags = EXT4_MB_HINT_DATA;
692 current_block = ext4_mb_new_blocks(handle, &ar, err);
693 if (unlikely(current_block + ar.len > EXT4_MAX_BLOCK_FILE_PHYS)) {
694 EXT4_ERROR_INODE(inode,
695 "current_block %llu + ar.len %d > %d!",
696 current_block, ar.len,
697 EXT4_MAX_BLOCK_FILE_PHYS);
702 if (*err && (target == blks)) {
704 * if the allocation failed and we didn't allocate
710 if (target == blks) {
712 * save the new block number
713 * for the first direct block
715 new_blocks[index] = current_block;
717 blk_allocated += ar.len;
720 /* total number of blocks allocated for direct blocks */
725 for (i = 0; i < index; i++)
726 ext4_free_blocks(handle, inode, NULL, new_blocks[i], 1, 0);
731 * ext4_alloc_branch - allocate and set up a chain of blocks.
732 * @handle: handle for this transaction
734 * @indirect_blks: number of allocated indirect blocks
735 * @blks: number of allocated direct blocks
736 * @goal: preferred place for allocation
737 * @offsets: offsets (in the blocks) to store the pointers to next.
738 * @branch: place to store the chain in.
740 * This function allocates blocks, zeroes out all but the last one,
741 * links them into chain and (if we are synchronous) writes them to disk.
742 * In other words, it prepares a branch that can be spliced onto the
743 * inode. It stores the information about that chain in the branch[], in
744 * the same format as ext4_get_branch() would do. We are calling it after
745 * we had read the existing part of chain and partial points to the last
746 * triple of that (one with zero ->key). Upon the exit we have the same
747 * picture as after the successful ext4_get_block(), except that in one
748 * place chain is disconnected - *branch->p is still zero (we did not
749 * set the last link), but branch->key contains the number that should
750 * be placed into *branch->p to fill that gap.
752 * If allocation fails we free all blocks we've allocated (and forget
753 * their buffer_heads) and return the error value the from failed
754 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
755 * as described above and return 0.
757 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
758 ext4_lblk_t iblock, int indirect_blks,
759 int *blks, ext4_fsblk_t goal,
760 ext4_lblk_t *offsets, Indirect *branch)
762 int blocksize = inode->i_sb->s_blocksize;
765 struct buffer_head *bh;
767 ext4_fsblk_t new_blocks[4];
768 ext4_fsblk_t current_block;
770 num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
771 *blks, new_blocks, &err);
775 branch[0].key = cpu_to_le32(new_blocks[0]);
777 * metadata blocks and data blocks are allocated.
779 for (n = 1; n <= indirect_blks; n++) {
781 * Get buffer_head for parent block, zero it out
782 * and set the pointer to new one, then send
785 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
793 BUFFER_TRACE(bh, "call get_create_access");
794 err = ext4_journal_get_create_access(handle, bh);
796 /* Don't brelse(bh) here; it's done in
797 * ext4_journal_forget() below */
802 memset(bh->b_data, 0, blocksize);
803 branch[n].p = (__le32 *) bh->b_data + offsets[n];
804 branch[n].key = cpu_to_le32(new_blocks[n]);
805 *branch[n].p = branch[n].key;
806 if (n == indirect_blks) {
807 current_block = new_blocks[n];
809 * End of chain, update the last new metablock of
810 * the chain to point to the new allocated
811 * data blocks numbers
813 for (i = 1; i < num; i++)
814 *(branch[n].p + i) = cpu_to_le32(++current_block);
816 BUFFER_TRACE(bh, "marking uptodate");
817 set_buffer_uptodate(bh);
820 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
821 err = ext4_handle_dirty_metadata(handle, inode, bh);
828 /* Allocation failed, free what we already allocated */
829 ext4_free_blocks(handle, inode, NULL, new_blocks[0], 1, 0);
830 for (i = 1; i <= n ; i++) {
832 * branch[i].bh is newly allocated, so there is no
833 * need to revoke the block, which is why we don't
834 * need to set EXT4_FREE_BLOCKS_METADATA.
836 ext4_free_blocks(handle, inode, NULL, new_blocks[i], 1,
837 EXT4_FREE_BLOCKS_FORGET);
839 for (i = n+1; i < indirect_blks; i++)
840 ext4_free_blocks(handle, inode, NULL, new_blocks[i], 1, 0);
842 ext4_free_blocks(handle, inode, NULL, new_blocks[i], num, 0);
848 * ext4_splice_branch - splice the allocated branch onto inode.
849 * @handle: handle for this transaction
851 * @block: (logical) number of block we are adding
852 * @chain: chain of indirect blocks (with a missing link - see
854 * @where: location of missing link
855 * @num: number of indirect blocks we are adding
856 * @blks: number of direct blocks we are adding
858 * This function fills the missing link and does all housekeeping needed in
859 * inode (->i_blocks, etc.). In case of success we end up with the full
860 * chain to new block and return 0.
862 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
863 ext4_lblk_t block, Indirect *where, int num,
868 ext4_fsblk_t current_block;
871 * If we're splicing into a [td]indirect block (as opposed to the
872 * inode) then we need to get write access to the [td]indirect block
876 BUFFER_TRACE(where->bh, "get_write_access");
877 err = ext4_journal_get_write_access(handle, where->bh);
883 *where->p = where->key;
886 * Update the host buffer_head or inode to point to more just allocated
887 * direct blocks blocks
889 if (num == 0 && blks > 1) {
890 current_block = le32_to_cpu(where->key) + 1;
891 for (i = 1; i < blks; i++)
892 *(where->p + i) = cpu_to_le32(current_block++);
895 /* We are done with atomic stuff, now do the rest of housekeeping */
896 /* had we spliced it onto indirect block? */
899 * If we spliced it onto an indirect block, we haven't
900 * altered the inode. Note however that if it is being spliced
901 * onto an indirect block at the very end of the file (the
902 * file is growing) then we *will* alter the inode to reflect
903 * the new i_size. But that is not done here - it is done in
904 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
906 jbd_debug(5, "splicing indirect only\n");
907 BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
908 err = ext4_handle_dirty_metadata(handle, inode, where->bh);
913 * OK, we spliced it into the inode itself on a direct block.
915 ext4_mark_inode_dirty(handle, inode);
916 jbd_debug(5, "splicing direct\n");
921 for (i = 1; i <= num; i++) {
923 * branch[i].bh is newly allocated, so there is no
924 * need to revoke the block, which is why we don't
925 * need to set EXT4_FREE_BLOCKS_METADATA.
927 ext4_free_blocks(handle, inode, where[i].bh, 0, 1,
928 EXT4_FREE_BLOCKS_FORGET);
930 ext4_free_blocks(handle, inode, NULL, le32_to_cpu(where[num].key),
937 * The ext4_ind_map_blocks() function handles non-extents inodes
938 * (i.e., using the traditional indirect/double-indirect i_blocks
939 * scheme) for ext4_map_blocks().
941 * Allocation strategy is simple: if we have to allocate something, we will
942 * have to go the whole way to leaf. So let's do it before attaching anything
943 * to tree, set linkage between the newborn blocks, write them if sync is
944 * required, recheck the path, free and repeat if check fails, otherwise
945 * set the last missing link (that will protect us from any truncate-generated
946 * removals - all blocks on the path are immune now) and possibly force the
947 * write on the parent block.
948 * That has a nice additional property: no special recovery from the failed
949 * allocations is needed - we simply release blocks and do not touch anything
950 * reachable from inode.
952 * `handle' can be NULL if create == 0.
954 * return > 0, # of blocks mapped or allocated.
955 * return = 0, if plain lookup failed.
956 * return < 0, error case.
958 * The ext4_ind_get_blocks() function should be called with
959 * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
960 * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
961 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
964 static int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
965 struct ext4_map_blocks *map,
969 ext4_lblk_t offsets[4];
974 int blocks_to_boundary = 0;
977 ext4_fsblk_t first_block = 0;
979 trace_ext4_ind_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
980 J_ASSERT(!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)));
981 J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
982 depth = ext4_block_to_path(inode, map->m_lblk, offsets,
983 &blocks_to_boundary);
988 partial = ext4_get_branch(inode, depth, offsets, chain, &err);
990 /* Simplest case - block found, no allocation needed */
992 first_block = le32_to_cpu(chain[depth - 1].key);
995 while (count < map->m_len && count <= blocks_to_boundary) {
998 blk = le32_to_cpu(*(chain[depth-1].p + count));
1000 if (blk == first_block + count)
1008 /* Next simple case - plain lookup or failed read of indirect block */
1009 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
1013 * Okay, we need to do block allocation.
1015 goal = ext4_find_goal(inode, map->m_lblk, partial);
1017 /* the number of blocks need to allocate for [d,t]indirect blocks */
1018 indirect_blks = (chain + depth) - partial - 1;
1021 * Next look up the indirect map to count the totoal number of
1022 * direct blocks to allocate for this branch.
1024 count = ext4_blks_to_allocate(partial, indirect_blks,
1025 map->m_len, blocks_to_boundary);
1027 * Block out ext4_truncate while we alter the tree
1029 err = ext4_alloc_branch(handle, inode, map->m_lblk, indirect_blks,
1031 offsets + (partial - chain), partial);
1034 * The ext4_splice_branch call will free and forget any buffers
1035 * on the new chain if there is a failure, but that risks using
1036 * up transaction credits, especially for bitmaps where the
1037 * credits cannot be returned. Can we handle this somehow? We
1038 * may need to return -EAGAIN upwards in the worst case. --sct
1041 err = ext4_splice_branch(handle, inode, map->m_lblk,
1042 partial, indirect_blks, count);
1046 map->m_flags |= EXT4_MAP_NEW;
1048 ext4_update_inode_fsync_trans(handle, inode, 1);
1050 map->m_flags |= EXT4_MAP_MAPPED;
1051 map->m_pblk = le32_to_cpu(chain[depth-1].key);
1053 if (count > blocks_to_boundary)
1054 map->m_flags |= EXT4_MAP_BOUNDARY;
1056 /* Clean up and exit */
1057 partial = chain + depth - 1; /* the whole chain */
1059 while (partial > chain) {
1060 BUFFER_TRACE(partial->bh, "call brelse");
1061 brelse(partial->bh);
1065 trace_ext4_ind_map_blocks_exit(inode, map->m_lblk,
1066 map->m_pblk, map->m_len, err);
1071 qsize_t *ext4_get_reserved_space(struct inode *inode)
1073 return &EXT4_I(inode)->i_reserved_quota;
1078 * Calculate the number of metadata blocks need to reserve
1079 * to allocate a new block at @lblocks for non extent file based file
1081 static int ext4_indirect_calc_metadata_amount(struct inode *inode,
1084 struct ext4_inode_info *ei = EXT4_I(inode);
1085 sector_t dind_mask = ~((sector_t)EXT4_ADDR_PER_BLOCK(inode->i_sb) - 1);
1088 if (lblock < EXT4_NDIR_BLOCKS)
1091 lblock -= EXT4_NDIR_BLOCKS;
1093 if (ei->i_da_metadata_calc_len &&
1094 (lblock & dind_mask) == ei->i_da_metadata_calc_last_lblock) {
1095 ei->i_da_metadata_calc_len++;
1098 ei->i_da_metadata_calc_last_lblock = lblock & dind_mask;
1099 ei->i_da_metadata_calc_len = 1;
1100 blk_bits = order_base_2(lblock);
1101 return (blk_bits / EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb)) + 1;
1105 * Calculate the number of metadata blocks need to reserve
1106 * to allocate a block located at @lblock
1108 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
1110 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1111 return ext4_ext_calc_metadata_amount(inode, lblock);
1113 return ext4_indirect_calc_metadata_amount(inode, lblock);
1117 * Called with i_data_sem down, which is important since we can call
1118 * ext4_discard_preallocations() from here.
1120 void ext4_da_update_reserve_space(struct inode *inode,
1121 int used, int quota_claim)
1123 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1124 struct ext4_inode_info *ei = EXT4_I(inode);
1126 spin_lock(&ei->i_block_reservation_lock);
1127 trace_ext4_da_update_reserve_space(inode, used);
1128 if (unlikely(used > ei->i_reserved_data_blocks)) {
1129 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
1130 "with only %d reserved data blocks\n",
1131 __func__, inode->i_ino, used,
1132 ei->i_reserved_data_blocks);
1134 used = ei->i_reserved_data_blocks;
1137 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
1138 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, allocated %d "
1139 "with only %d reserved metadata blocks\n", __func__,
1140 inode->i_ino, ei->i_allocated_meta_blocks,
1141 ei->i_reserved_meta_blocks);
1143 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
1146 /* Update per-inode reservations */
1147 ei->i_reserved_data_blocks -= used;
1148 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
1149 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
1150 used + ei->i_allocated_meta_blocks);
1151 ei->i_allocated_meta_blocks = 0;
1153 if (ei->i_reserved_data_blocks == 0) {
1155 * We can release all of the reserved metadata blocks
1156 * only when we have written all of the delayed
1157 * allocation blocks.
1159 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
1160 ei->i_reserved_meta_blocks);
1161 ei->i_reserved_meta_blocks = 0;
1162 ei->i_da_metadata_calc_len = 0;
1164 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1166 /* Update quota subsystem for data blocks */
1168 dquot_claim_block(inode, used);
1171 * We did fallocate with an offset that is already delayed
1172 * allocated. So on delayed allocated writeback we should
1173 * not re-claim the quota for fallocated blocks.
1175 dquot_release_reservation_block(inode, used);
1179 * If we have done all the pending block allocations and if
1180 * there aren't any writers on the inode, we can discard the
1181 * inode's preallocations.
1183 if ((ei->i_reserved_data_blocks == 0) &&
1184 (atomic_read(&inode->i_writecount) == 0))
1185 ext4_discard_preallocations(inode);
1188 static int __check_block_validity(struct inode *inode, const char *func,
1190 struct ext4_map_blocks *map)
1192 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
1194 ext4_error_inode(inode, func, line, map->m_pblk,
1195 "lblock %lu mapped to illegal pblock "
1196 "(length %d)", (unsigned long) map->m_lblk,
1203 #define check_block_validity(inode, map) \
1204 __check_block_validity((inode), __func__, __LINE__, (map))
1207 * Return the number of contiguous dirty pages in a given inode
1208 * starting at page frame idx.
1210 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
1211 unsigned int max_pages)
1213 struct address_space *mapping = inode->i_mapping;
1215 struct pagevec pvec;
1217 int i, nr_pages, done = 0;
1221 pagevec_init(&pvec, 0);
1224 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
1225 PAGECACHE_TAG_DIRTY,
1226 (pgoff_t)PAGEVEC_SIZE);
1229 for (i = 0; i < nr_pages; i++) {
1230 struct page *page = pvec.pages[i];
1231 struct buffer_head *bh, *head;
1234 if (unlikely(page->mapping != mapping) ||
1236 PageWriteback(page) ||
1237 page->index != idx) {
1242 if (page_has_buffers(page)) {
1243 bh = head = page_buffers(page);
1245 if (!buffer_delay(bh) &&
1246 !buffer_unwritten(bh))
1248 bh = bh->b_this_page;
1249 } while (!done && (bh != head));
1256 if (num >= max_pages) {
1261 pagevec_release(&pvec);
1267 * The ext4_map_blocks() function tries to look up the requested blocks,
1268 * and returns if the blocks are already mapped.
1270 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1271 * and store the allocated blocks in the result buffer head and mark it
1274 * If file type is extents based, it will call ext4_ext_map_blocks(),
1275 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
1278 * On success, it returns the number of blocks being mapped or allocate.
1279 * if create==0 and the blocks are pre-allocated and uninitialized block,
1280 * the result buffer head is unmapped. If the create ==1, it will make sure
1281 * the buffer head is mapped.
1283 * It returns 0 if plain look up failed (blocks have not been allocated), in
1284 * that casem, buffer head is unmapped
1286 * It returns the error in case of allocation failure.
1288 int ext4_map_blocks(handle_t *handle, struct inode *inode,
1289 struct ext4_map_blocks *map, int flags)
1294 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
1295 "logical block %lu\n", inode->i_ino, flags, map->m_len,
1296 (unsigned long) map->m_lblk);
1298 * Try to see if we can get the block without requesting a new
1299 * file system block.
1301 down_read((&EXT4_I(inode)->i_data_sem));
1302 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
1303 retval = ext4_ext_map_blocks(handle, inode, map, 0);
1305 retval = ext4_ind_map_blocks(handle, inode, map, 0);
1307 up_read((&EXT4_I(inode)->i_data_sem));
1309 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
1310 int ret = check_block_validity(inode, map);
1315 /* If it is only a block(s) look up */
1316 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
1320 * Returns if the blocks have already allocated
1322 * Note that if blocks have been preallocated
1323 * ext4_ext_get_block() returns th create = 0
1324 * with buffer head unmapped.
1326 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
1330 * When we call get_blocks without the create flag, the
1331 * BH_Unwritten flag could have gotten set if the blocks
1332 * requested were part of a uninitialized extent. We need to
1333 * clear this flag now that we are committed to convert all or
1334 * part of the uninitialized extent to be an initialized
1335 * extent. This is because we need to avoid the combination
1336 * of BH_Unwritten and BH_Mapped flags being simultaneously
1337 * set on the buffer_head.
1339 map->m_flags &= ~EXT4_MAP_UNWRITTEN;
1342 * New blocks allocate and/or writing to uninitialized extent
1343 * will possibly result in updating i_data, so we take
1344 * the write lock of i_data_sem, and call get_blocks()
1345 * with create == 1 flag.
1347 down_write((&EXT4_I(inode)->i_data_sem));
1350 * if the caller is from delayed allocation writeout path
1351 * we have already reserved fs blocks for allocation
1352 * let the underlying get_block() function know to
1353 * avoid double accounting
1355 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1356 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
1358 * We need to check for EXT4 here because migrate
1359 * could have changed the inode type in between
1361 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
1362 retval = ext4_ext_map_blocks(handle, inode, map, flags);
1364 retval = ext4_ind_map_blocks(handle, inode, map, flags);
1366 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
1368 * We allocated new blocks which will result in
1369 * i_data's format changing. Force the migrate
1370 * to fail by clearing migrate flags
1372 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
1376 * Update reserved blocks/metadata blocks after successful
1377 * block allocation which had been deferred till now. We don't
1378 * support fallocate for non extent files. So we can update
1379 * reserve space here.
1382 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
1383 ext4_da_update_reserve_space(inode, retval, 1);
1385 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1386 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
1388 up_write((&EXT4_I(inode)->i_data_sem));
1389 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
1390 int ret = check_block_validity(inode, map);
1397 /* Maximum number of blocks we map for direct IO at once. */
1398 #define DIO_MAX_BLOCKS 4096
1400 static int _ext4_get_block(struct inode *inode, sector_t iblock,
1401 struct buffer_head *bh, int flags)
1403 handle_t *handle = ext4_journal_current_handle();
1404 struct ext4_map_blocks map;
1405 int ret = 0, started = 0;
1408 map.m_lblk = iblock;
1409 map.m_len = bh->b_size >> inode->i_blkbits;
1411 if (flags && !handle) {
1412 /* Direct IO write... */
1413 if (map.m_len > DIO_MAX_BLOCKS)
1414 map.m_len = DIO_MAX_BLOCKS;
1415 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
1416 handle = ext4_journal_start(inode, dio_credits);
1417 if (IS_ERR(handle)) {
1418 ret = PTR_ERR(handle);
1424 ret = ext4_map_blocks(handle, inode, &map, flags);
1426 map_bh(bh, inode->i_sb, map.m_pblk);
1427 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1428 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
1432 ext4_journal_stop(handle);
1436 int ext4_get_block(struct inode *inode, sector_t iblock,
1437 struct buffer_head *bh, int create)
1439 return _ext4_get_block(inode, iblock, bh,
1440 create ? EXT4_GET_BLOCKS_CREATE : 0);
1444 * `handle' can be NULL if create is zero
1446 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1447 ext4_lblk_t block, int create, int *errp)
1449 struct ext4_map_blocks map;
1450 struct buffer_head *bh;
1453 J_ASSERT(handle != NULL || create == 0);
1457 err = ext4_map_blocks(handle, inode, &map,
1458 create ? EXT4_GET_BLOCKS_CREATE : 0);
1466 bh = sb_getblk(inode->i_sb, map.m_pblk);
1471 if (map.m_flags & EXT4_MAP_NEW) {
1472 J_ASSERT(create != 0);
1473 J_ASSERT(handle != NULL);
1476 * Now that we do not always journal data, we should
1477 * keep in mind whether this should always journal the
1478 * new buffer as metadata. For now, regular file
1479 * writes use ext4_get_block instead, so it's not a
1483 BUFFER_TRACE(bh, "call get_create_access");
1484 fatal = ext4_journal_get_create_access(handle, bh);
1485 if (!fatal && !buffer_uptodate(bh)) {
1486 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1487 set_buffer_uptodate(bh);
1490 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1491 err = ext4_handle_dirty_metadata(handle, inode, bh);
1495 BUFFER_TRACE(bh, "not a new buffer");
1505 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1506 ext4_lblk_t block, int create, int *err)
1508 struct buffer_head *bh;
1510 bh = ext4_getblk(handle, inode, block, create, err);
1513 if (buffer_uptodate(bh))
1515 ll_rw_block(READ_META, 1, &bh);
1517 if (buffer_uptodate(bh))
1524 static int walk_page_buffers(handle_t *handle,
1525 struct buffer_head *head,
1529 int (*fn)(handle_t *handle,
1530 struct buffer_head *bh))
1532 struct buffer_head *bh;
1533 unsigned block_start, block_end;
1534 unsigned blocksize = head->b_size;
1536 struct buffer_head *next;
1538 for (bh = head, block_start = 0;
1539 ret == 0 && (bh != head || !block_start);
1540 block_start = block_end, bh = next) {
1541 next = bh->b_this_page;
1542 block_end = block_start + blocksize;
1543 if (block_end <= from || block_start >= to) {
1544 if (partial && !buffer_uptodate(bh))
1548 err = (*fn)(handle, bh);
1556 * To preserve ordering, it is essential that the hole instantiation and
1557 * the data write be encapsulated in a single transaction. We cannot
1558 * close off a transaction and start a new one between the ext4_get_block()
1559 * and the commit_write(). So doing the jbd2_journal_start at the start of
1560 * prepare_write() is the right place.
1562 * Also, this function can nest inside ext4_writepage() ->
1563 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1564 * has generated enough buffer credits to do the whole page. So we won't
1565 * block on the journal in that case, which is good, because the caller may
1568 * By accident, ext4 can be reentered when a transaction is open via
1569 * quota file writes. If we were to commit the transaction while thus
1570 * reentered, there can be a deadlock - we would be holding a quota
1571 * lock, and the commit would never complete if another thread had a
1572 * transaction open and was blocking on the quota lock - a ranking
1575 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1576 * will _not_ run commit under these circumstances because handle->h_ref
1577 * is elevated. We'll still have enough credits for the tiny quotafile
1580 static int do_journal_get_write_access(handle_t *handle,
1581 struct buffer_head *bh)
1583 int dirty = buffer_dirty(bh);
1586 if (!buffer_mapped(bh) || buffer_freed(bh))
1589 * __block_write_begin() could have dirtied some buffers. Clean
1590 * the dirty bit as jbd2_journal_get_write_access() could complain
1591 * otherwise about fs integrity issues. Setting of the dirty bit
1592 * by __block_write_begin() isn't a real problem here as we clear
1593 * the bit before releasing a page lock and thus writeback cannot
1594 * ever write the buffer.
1597 clear_buffer_dirty(bh);
1598 ret = ext4_journal_get_write_access(handle, bh);
1600 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1605 * Truncate blocks that were not used by write. We have to truncate the
1606 * pagecache as well so that corresponding buffers get properly unmapped.
1608 static void ext4_truncate_failed_write(struct inode *inode)
1610 truncate_inode_pages(inode->i_mapping, inode->i_size);
1611 ext4_truncate(inode);
1614 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
1615 struct buffer_head *bh_result, int create);
1616 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1617 loff_t pos, unsigned len, unsigned flags,
1618 struct page **pagep, void **fsdata)
1620 struct inode *inode = mapping->host;
1621 int ret, needed_blocks;
1628 trace_ext4_write_begin(inode, pos, len, flags);
1630 * Reserve one block more for addition to orphan list in case
1631 * we allocate blocks but write fails for some reason
1633 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1634 index = pos >> PAGE_CACHE_SHIFT;
1635 from = pos & (PAGE_CACHE_SIZE - 1);
1639 handle = ext4_journal_start(inode, needed_blocks);
1640 if (IS_ERR(handle)) {
1641 ret = PTR_ERR(handle);
1645 /* We cannot recurse into the filesystem as the transaction is already
1647 flags |= AOP_FLAG_NOFS;
1649 page = grab_cache_page_write_begin(mapping, index, flags);
1651 ext4_journal_stop(handle);
1657 if (ext4_should_dioread_nolock(inode))
1658 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1660 ret = __block_write_begin(page, pos, len, ext4_get_block);
1662 if (!ret && ext4_should_journal_data(inode)) {
1663 ret = walk_page_buffers(handle, page_buffers(page),
1664 from, to, NULL, do_journal_get_write_access);
1669 page_cache_release(page);
1671 * __block_write_begin may have instantiated a few blocks
1672 * outside i_size. Trim these off again. Don't need
1673 * i_size_read because we hold i_mutex.
1675 * Add inode to orphan list in case we crash before
1678 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1679 ext4_orphan_add(handle, inode);
1681 ext4_journal_stop(handle);
1682 if (pos + len > inode->i_size) {
1683 ext4_truncate_failed_write(inode);
1685 * If truncate failed early the inode might
1686 * still be on the orphan list; we need to
1687 * make sure the inode is removed from the
1688 * orphan list in that case.
1691 ext4_orphan_del(NULL, inode);
1695 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1701 /* For write_end() in data=journal mode */
1702 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1704 if (!buffer_mapped(bh) || buffer_freed(bh))
1706 set_buffer_uptodate(bh);
1707 return ext4_handle_dirty_metadata(handle, NULL, bh);
1710 static int ext4_generic_write_end(struct file *file,
1711 struct address_space *mapping,
1712 loff_t pos, unsigned len, unsigned copied,
1713 struct page *page, void *fsdata)
1715 int i_size_changed = 0;
1716 struct inode *inode = mapping->host;
1717 handle_t *handle = ext4_journal_current_handle();
1719 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1722 * No need to use i_size_read() here, the i_size
1723 * cannot change under us because we hold i_mutex.
1725 * But it's important to update i_size while still holding page lock:
1726 * page writeout could otherwise come in and zero beyond i_size.
1728 if (pos + copied > inode->i_size) {
1729 i_size_write(inode, pos + copied);
1733 if (pos + copied > EXT4_I(inode)->i_disksize) {
1734 /* We need to mark inode dirty even if
1735 * new_i_size is less that inode->i_size
1736 * bu greater than i_disksize.(hint delalloc)
1738 ext4_update_i_disksize(inode, (pos + copied));
1742 page_cache_release(page);
1745 * Don't mark the inode dirty under page lock. First, it unnecessarily
1746 * makes the holding time of page lock longer. Second, it forces lock
1747 * ordering of page lock and transaction start for journaling
1751 ext4_mark_inode_dirty(handle, inode);
1757 * We need to pick up the new inode size which generic_commit_write gave us
1758 * `file' can be NULL - eg, when called from page_symlink().
1760 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1761 * buffers are managed internally.
1763 static int ext4_ordered_write_end(struct file *file,
1764 struct address_space *mapping,
1765 loff_t pos, unsigned len, unsigned copied,
1766 struct page *page, void *fsdata)
1768 handle_t *handle = ext4_journal_current_handle();
1769 struct inode *inode = mapping->host;
1772 trace_ext4_ordered_write_end(inode, pos, len, copied);
1773 ret = ext4_jbd2_file_inode(handle, inode);
1776 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1779 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1780 /* if we have allocated more blocks and copied
1781 * less. We will have blocks allocated outside
1782 * inode->i_size. So truncate them
1784 ext4_orphan_add(handle, inode);
1788 ret2 = ext4_journal_stop(handle);
1792 if (pos + len > inode->i_size) {
1793 ext4_truncate_failed_write(inode);
1795 * If truncate failed early the inode might still be
1796 * on the orphan list; we need to make sure the inode
1797 * is removed from the orphan list in that case.
1800 ext4_orphan_del(NULL, inode);
1804 return ret ? ret : copied;
1807 static int ext4_writeback_write_end(struct file *file,
1808 struct address_space *mapping,
1809 loff_t pos, unsigned len, unsigned copied,
1810 struct page *page, void *fsdata)
1812 handle_t *handle = ext4_journal_current_handle();
1813 struct inode *inode = mapping->host;
1816 trace_ext4_writeback_write_end(inode, pos, len, copied);
1817 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1820 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1821 /* if we have allocated more blocks and copied
1822 * less. We will have blocks allocated outside
1823 * inode->i_size. So truncate them
1825 ext4_orphan_add(handle, inode);
1830 ret2 = ext4_journal_stop(handle);
1834 if (pos + len > inode->i_size) {
1835 ext4_truncate_failed_write(inode);
1837 * If truncate failed early the inode might still be
1838 * on the orphan list; we need to make sure the inode
1839 * is removed from the orphan list in that case.
1842 ext4_orphan_del(NULL, inode);
1845 return ret ? ret : copied;
1848 static int ext4_journalled_write_end(struct file *file,
1849 struct address_space *mapping,
1850 loff_t pos, unsigned len, unsigned copied,
1851 struct page *page, void *fsdata)
1853 handle_t *handle = ext4_journal_current_handle();
1854 struct inode *inode = mapping->host;
1860 trace_ext4_journalled_write_end(inode, pos, len, copied);
1861 from = pos & (PAGE_CACHE_SIZE - 1);
1864 BUG_ON(!ext4_handle_valid(handle));
1867 if (!PageUptodate(page))
1869 page_zero_new_buffers(page, from+copied, to);
1872 ret = walk_page_buffers(handle, page_buffers(page), from,
1873 to, &partial, write_end_fn);
1875 SetPageUptodate(page);
1876 new_i_size = pos + copied;
1877 if (new_i_size > inode->i_size)
1878 i_size_write(inode, pos+copied);
1879 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1880 if (new_i_size > EXT4_I(inode)->i_disksize) {
1881 ext4_update_i_disksize(inode, new_i_size);
1882 ret2 = ext4_mark_inode_dirty(handle, inode);
1888 page_cache_release(page);
1889 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1890 /* if we have allocated more blocks and copied
1891 * less. We will have blocks allocated outside
1892 * inode->i_size. So truncate them
1894 ext4_orphan_add(handle, inode);
1896 ret2 = ext4_journal_stop(handle);
1899 if (pos + len > inode->i_size) {
1900 ext4_truncate_failed_write(inode);
1902 * If truncate failed early the inode might still be
1903 * on the orphan list; we need to make sure the inode
1904 * is removed from the orphan list in that case.
1907 ext4_orphan_del(NULL, inode);
1910 return ret ? ret : copied;
1914 * Reserve a single block located at lblock
1916 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1919 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1920 struct ext4_inode_info *ei = EXT4_I(inode);
1921 unsigned long md_needed;
1925 * recalculate the amount of metadata blocks to reserve
1926 * in order to allocate nrblocks
1927 * worse case is one extent per block
1930 spin_lock(&ei->i_block_reservation_lock);
1931 md_needed = ext4_calc_metadata_amount(inode, lblock);
1932 trace_ext4_da_reserve_space(inode, md_needed);
1933 spin_unlock(&ei->i_block_reservation_lock);
1936 * We will charge metadata quota at writeout time; this saves
1937 * us from metadata over-estimation, though we may go over by
1938 * a small amount in the end. Here we just reserve for data.
1940 ret = dquot_reserve_block(inode, 1);
1944 * We do still charge estimated metadata to the sb though;
1945 * we cannot afford to run out of free blocks.
1947 if (ext4_claim_free_blocks(sbi, md_needed + 1, 0)) {
1948 dquot_release_reservation_block(inode, 1);
1949 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1955 spin_lock(&ei->i_block_reservation_lock);
1956 ei->i_reserved_data_blocks++;
1957 ei->i_reserved_meta_blocks += md_needed;
1958 spin_unlock(&ei->i_block_reservation_lock);
1960 return 0; /* success */
1963 static void ext4_da_release_space(struct inode *inode, int to_free)
1965 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1966 struct ext4_inode_info *ei = EXT4_I(inode);
1969 return; /* Nothing to release, exit */
1971 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1973 trace_ext4_da_release_space(inode, to_free);
1974 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1976 * if there aren't enough reserved blocks, then the
1977 * counter is messed up somewhere. Since this
1978 * function is called from invalidate page, it's
1979 * harmless to return without any action.
1981 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1982 "ino %lu, to_free %d with only %d reserved "
1983 "data blocks\n", inode->i_ino, to_free,
1984 ei->i_reserved_data_blocks);
1986 to_free = ei->i_reserved_data_blocks;
1988 ei->i_reserved_data_blocks -= to_free;
1990 if (ei->i_reserved_data_blocks == 0) {
1992 * We can release all of the reserved metadata blocks
1993 * only when we have written all of the delayed
1994 * allocation blocks.
1996 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
1997 ei->i_reserved_meta_blocks);
1998 ei->i_reserved_meta_blocks = 0;
1999 ei->i_da_metadata_calc_len = 0;
2002 /* update fs dirty data blocks counter */
2003 percpu_counter_sub(&sbi->s_dirtyblocks_counter, to_free);
2005 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2007 dquot_release_reservation_block(inode, to_free);
2010 static void ext4_da_page_release_reservation(struct page *page,
2011 unsigned long offset)
2014 struct buffer_head *head, *bh;
2015 unsigned int curr_off = 0;
2017 head = page_buffers(page);
2020 unsigned int next_off = curr_off + bh->b_size;
2022 if ((offset <= curr_off) && (buffer_delay(bh))) {
2024 clear_buffer_delay(bh);
2026 curr_off = next_off;
2027 } while ((bh = bh->b_this_page) != head);
2028 ext4_da_release_space(page->mapping->host, to_release);
2032 * Delayed allocation stuff
2036 * mpage_da_submit_io - walks through extent of pages and try to write
2037 * them with writepage() call back
2039 * @mpd->inode: inode
2040 * @mpd->first_page: first page of the extent
2041 * @mpd->next_page: page after the last page of the extent
2043 * By the time mpage_da_submit_io() is called we expect all blocks
2044 * to be allocated. this may be wrong if allocation failed.
2046 * As pages are already locked by write_cache_pages(), we can't use it
2048 static int mpage_da_submit_io(struct mpage_da_data *mpd,
2049 struct ext4_map_blocks *map)
2051 struct pagevec pvec;
2052 unsigned long index, end;
2053 int ret = 0, err, nr_pages, i;
2054 struct inode *inode = mpd->inode;
2055 struct address_space *mapping = inode->i_mapping;
2056 loff_t size = i_size_read(inode);
2057 unsigned int len, block_start;
2058 struct buffer_head *bh, *page_bufs = NULL;
2059 int journal_data = ext4_should_journal_data(inode);
2060 sector_t pblock = 0, cur_logical = 0;
2061 struct ext4_io_submit io_submit;
2063 BUG_ON(mpd->next_page <= mpd->first_page);
2064 memset(&io_submit, 0, sizeof(io_submit));
2066 * We need to start from the first_page to the next_page - 1
2067 * to make sure we also write the mapped dirty buffer_heads.
2068 * If we look at mpd->b_blocknr we would only be looking
2069 * at the currently mapped buffer_heads.
2071 index = mpd->first_page;
2072 end = mpd->next_page - 1;
2074 pagevec_init(&pvec, 0);
2075 while (index <= end) {
2076 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2079 for (i = 0; i < nr_pages; i++) {
2080 int commit_write = 0, skip_page = 0;
2081 struct page *page = pvec.pages[i];
2083 index = page->index;
2087 if (index == size >> PAGE_CACHE_SHIFT)
2088 len = size & ~PAGE_CACHE_MASK;
2090 len = PAGE_CACHE_SIZE;
2092 cur_logical = index << (PAGE_CACHE_SHIFT -
2094 pblock = map->m_pblk + (cur_logical -
2099 BUG_ON(!PageLocked(page));
2100 BUG_ON(PageWriteback(page));
2103 * If the page does not have buffers (for
2104 * whatever reason), try to create them using
2105 * __block_write_begin. If this fails,
2106 * skip the page and move on.
2108 if (!page_has_buffers(page)) {
2109 if (__block_write_begin(page, 0, len,
2110 noalloc_get_block_write)) {
2118 bh = page_bufs = page_buffers(page);
2123 if (map && (cur_logical >= map->m_lblk) &&
2124 (cur_logical <= (map->m_lblk +
2125 (map->m_len - 1)))) {
2126 if (buffer_delay(bh)) {
2127 clear_buffer_delay(bh);
2128 bh->b_blocknr = pblock;
2130 if (buffer_unwritten(bh) ||
2132 BUG_ON(bh->b_blocknr != pblock);
2133 if (map->m_flags & EXT4_MAP_UNINIT)
2134 set_buffer_uninit(bh);
2135 clear_buffer_unwritten(bh);
2139 * skip page if block allocation undone and
2142 if (ext4_bh_delay_or_unwritten(NULL, bh))
2144 bh = bh->b_this_page;
2145 block_start += bh->b_size;
2148 } while (bh != page_bufs);
2154 /* mark the buffer_heads as dirty & uptodate */
2155 block_commit_write(page, 0, len);
2157 clear_page_dirty_for_io(page);
2159 * Delalloc doesn't support data journalling,
2160 * but eventually maybe we'll lift this
2163 if (unlikely(journal_data && PageChecked(page)))
2164 err = __ext4_journalled_writepage(page, len);
2165 else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
2166 err = ext4_bio_write_page(&io_submit, page,
2168 else if (buffer_uninit(page_bufs)) {
2169 ext4_set_bh_endio(page_bufs, inode);
2170 err = block_write_full_page_endio(page,
2171 noalloc_get_block_write,
2172 mpd->wbc, ext4_end_io_buffer_write);
2174 err = block_write_full_page(page,
2175 noalloc_get_block_write, mpd->wbc);
2178 mpd->pages_written++;
2180 * In error case, we have to continue because
2181 * remaining pages are still locked
2186 pagevec_release(&pvec);
2188 ext4_io_submit(&io_submit);
2192 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
2196 struct pagevec pvec;
2197 struct inode *inode = mpd->inode;
2198 struct address_space *mapping = inode->i_mapping;
2200 index = mpd->first_page;
2201 end = mpd->next_page - 1;
2202 while (index <= end) {
2203 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2206 for (i = 0; i < nr_pages; i++) {
2207 struct page *page = pvec.pages[i];
2208 if (page->index > end)
2210 BUG_ON(!PageLocked(page));
2211 BUG_ON(PageWriteback(page));
2212 block_invalidatepage(page, 0);
2213 ClearPageUptodate(page);
2216 index = pvec.pages[nr_pages - 1]->index + 1;
2217 pagevec_release(&pvec);
2222 static void ext4_print_free_blocks(struct inode *inode)
2224 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2225 printk(KERN_CRIT "Total free blocks count %lld\n",
2226 ext4_count_free_blocks(inode->i_sb));
2227 printk(KERN_CRIT "Free/Dirty block details\n");
2228 printk(KERN_CRIT "free_blocks=%lld\n",
2229 (long long) percpu_counter_sum(&sbi->s_freeblocks_counter));
2230 printk(KERN_CRIT "dirty_blocks=%lld\n",
2231 (long long) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
2232 printk(KERN_CRIT "Block reservation details\n");
2233 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
2234 EXT4_I(inode)->i_reserved_data_blocks);
2235 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
2236 EXT4_I(inode)->i_reserved_meta_blocks);
2241 * mpage_da_map_and_submit - go through given space, map them
2242 * if necessary, and then submit them for I/O
2244 * @mpd - bh describing space
2246 * The function skips space we know is already mapped to disk blocks.
2249 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
2251 int err, blks, get_blocks_flags;
2252 struct ext4_map_blocks map, *mapp = NULL;
2253 sector_t next = mpd->b_blocknr;
2254 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
2255 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
2256 handle_t *handle = NULL;
2259 * If the blocks are mapped already, or we couldn't accumulate
2260 * any blocks, then proceed immediately to the submission stage.
2262 if ((mpd->b_size == 0) ||
2263 ((mpd->b_state & (1 << BH_Mapped)) &&
2264 !(mpd->b_state & (1 << BH_Delay)) &&
2265 !(mpd->b_state & (1 << BH_Unwritten))))
2268 handle = ext4_journal_current_handle();
2272 * Call ext4_map_blocks() to allocate any delayed allocation
2273 * blocks, or to convert an uninitialized extent to be
2274 * initialized (in the case where we have written into
2275 * one or more preallocated blocks).
2277 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
2278 * indicate that we are on the delayed allocation path. This
2279 * affects functions in many different parts of the allocation
2280 * call path. This flag exists primarily because we don't
2281 * want to change *many* call functions, so ext4_map_blocks()
2282 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
2283 * inode's allocation semaphore is taken.
2285 * If the blocks in questions were delalloc blocks, set
2286 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
2287 * variables are updated after the blocks have been allocated.
2290 map.m_len = max_blocks;
2291 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
2292 if (ext4_should_dioread_nolock(mpd->inode))
2293 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2294 if (mpd->b_state & (1 << BH_Delay))
2295 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2297 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
2299 struct super_block *sb = mpd->inode->i_sb;
2303 * If get block returns EAGAIN or ENOSPC and there
2304 * appears to be free blocks we will just let
2305 * mpage_da_submit_io() unlock all of the pages.
2310 if (err == -ENOSPC &&
2311 ext4_count_free_blocks(sb)) {
2317 * get block failure will cause us to loop in
2318 * writepages, because a_ops->writepage won't be able
2319 * to make progress. The page will be redirtied by
2320 * writepage and writepages will again try to write
2323 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2324 ext4_msg(sb, KERN_CRIT,
2325 "delayed block allocation failed for inode %lu "
2326 "at logical offset %llu with max blocks %zd "
2327 "with error %d", mpd->inode->i_ino,
2328 (unsigned long long) next,
2329 mpd->b_size >> mpd->inode->i_blkbits, err);
2330 ext4_msg(sb, KERN_CRIT,
2331 "This should not happen!! Data will be lost\n");
2333 ext4_print_free_blocks(mpd->inode);
2335 /* invalidate all the pages */
2336 ext4_da_block_invalidatepages(mpd);
2338 /* Mark this page range as having been completed */
2345 if (map.m_flags & EXT4_MAP_NEW) {
2346 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
2349 for (i = 0; i < map.m_len; i++)
2350 unmap_underlying_metadata(bdev, map.m_pblk + i);
2353 if (ext4_should_order_data(mpd->inode)) {
2354 err = ext4_jbd2_file_inode(handle, mpd->inode);
2356 /* This only happens if the journal is aborted */
2361 * Update on-disk size along with block allocation.
2363 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
2364 if (disksize > i_size_read(mpd->inode))
2365 disksize = i_size_read(mpd->inode);
2366 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
2367 ext4_update_i_disksize(mpd->inode, disksize);
2368 err = ext4_mark_inode_dirty(handle, mpd->inode);
2370 ext4_error(mpd->inode->i_sb,
2371 "Failed to mark inode %lu dirty",
2376 mpage_da_submit_io(mpd, mapp);
2380 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
2381 (1 << BH_Delay) | (1 << BH_Unwritten))
2384 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
2386 * @mpd->lbh - extent of blocks
2387 * @logical - logical number of the block in the file
2388 * @bh - bh of the block (used to access block's state)
2390 * the function is used to collect contig. blocks in same state
2392 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
2393 sector_t logical, size_t b_size,
2394 unsigned long b_state)
2397 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
2400 * XXX Don't go larger than mballoc is willing to allocate
2401 * This is a stopgap solution. We eventually need to fold
2402 * mpage_da_submit_io() into this function and then call
2403 * ext4_map_blocks() multiple times in a loop
2405 if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
2408 /* check if thereserved journal credits might overflow */
2409 if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
2410 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2412 * With non-extent format we are limited by the journal
2413 * credit available. Total credit needed to insert
2414 * nrblocks contiguous blocks is dependent on the
2415 * nrblocks. So limit nrblocks.
2418 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2419 EXT4_MAX_TRANS_DATA) {
2421 * Adding the new buffer_head would make it cross the
2422 * allowed limit for which we have journal credit
2423 * reserved. So limit the new bh->b_size
2425 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2426 mpd->inode->i_blkbits;
2427 /* we will do mpage_da_submit_io in the next loop */
2431 * First block in the extent
2433 if (mpd->b_size == 0) {
2434 mpd->b_blocknr = logical;
2435 mpd->b_size = b_size;
2436 mpd->b_state = b_state & BH_FLAGS;
2440 next = mpd->b_blocknr + nrblocks;
2442 * Can we merge the block to our big extent?
2444 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
2445 mpd->b_size += b_size;
2451 * We couldn't merge the block to our extent, so we
2452 * need to flush current extent and start new one
2454 mpage_da_map_and_submit(mpd);
2458 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
2460 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
2464 * This is a special get_blocks_t callback which is used by
2465 * ext4_da_write_begin(). It will either return mapped block or
2466 * reserve space for a single block.
2468 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2469 * We also have b_blocknr = -1 and b_bdev initialized properly
2471 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2472 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2473 * initialized properly.
2475 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2476 struct buffer_head *bh, int create)
2478 struct ext4_map_blocks map;
2480 sector_t invalid_block = ~((sector_t) 0xffff);
2482 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2485 BUG_ON(create == 0);
2486 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
2488 map.m_lblk = iblock;
2492 * first, we need to know whether the block is allocated already
2493 * preallocated blocks are unmapped but should treated
2494 * the same as allocated blocks.
2496 ret = ext4_map_blocks(NULL, inode, &map, 0);
2500 if (buffer_delay(bh))
2501 return 0; /* Not sure this could or should happen */
2503 * XXX: __block_write_begin() unmaps passed block, is it OK?
2505 ret = ext4_da_reserve_space(inode, iblock);
2507 /* not enough space to reserve */
2510 map_bh(bh, inode->i_sb, invalid_block);
2512 set_buffer_delay(bh);
2516 map_bh(bh, inode->i_sb, map.m_pblk);
2517 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
2519 if (buffer_unwritten(bh)) {
2520 /* A delayed write to unwritten bh should be marked
2521 * new and mapped. Mapped ensures that we don't do
2522 * get_block multiple times when we write to the same
2523 * offset and new ensures that we do proper zero out
2524 * for partial write.
2527 set_buffer_mapped(bh);
2533 * This function is used as a standard get_block_t calback function
2534 * when there is no desire to allocate any blocks. It is used as a
2535 * callback function for block_write_begin() and block_write_full_page().
2536 * These functions should only try to map a single block at a time.
2538 * Since this function doesn't do block allocations even if the caller
2539 * requests it by passing in create=1, it is critically important that
2540 * any caller checks to make sure that any buffer heads are returned
2541 * by this function are either all already mapped or marked for
2542 * delayed allocation before calling block_write_full_page(). Otherwise,
2543 * b_blocknr could be left unitialized, and the page write functions will
2544 * be taken by surprise.
2546 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
2547 struct buffer_head *bh_result, int create)
2549 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2550 return _ext4_get_block(inode, iblock, bh_result, 0);
2553 static int bget_one(handle_t *handle, struct buffer_head *bh)
2559 static int bput_one(handle_t *handle, struct buffer_head *bh)
2565 static int __ext4_journalled_writepage(struct page *page,
2568 struct address_space *mapping = page->mapping;
2569 struct inode *inode = mapping->host;
2570 struct buffer_head *page_bufs;
2571 handle_t *handle = NULL;
2575 ClearPageChecked(page);
2576 page_bufs = page_buffers(page);
2578 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
2579 /* As soon as we unlock the page, it can go away, but we have
2580 * references to buffers so we are safe */
2583 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
2584 if (IS_ERR(handle)) {
2585 ret = PTR_ERR(handle);
2589 BUG_ON(!ext4_handle_valid(handle));
2591 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2592 do_journal_get_write_access);
2594 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2598 err = ext4_journal_stop(handle);
2602 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
2603 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2608 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
2609 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
2612 * Note that we don't need to start a transaction unless we're journaling data
2613 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2614 * need to file the inode to the transaction's list in ordered mode because if
2615 * we are writing back data added by write(), the inode is already there and if
2616 * we are writing back data modified via mmap(), no one guarantees in which
2617 * transaction the data will hit the disk. In case we are journaling data, we
2618 * cannot start transaction directly because transaction start ranks above page
2619 * lock so we have to do some magic.
2621 * This function can get called via...
2622 * - ext4_da_writepages after taking page lock (have journal handle)
2623 * - journal_submit_inode_data_buffers (no journal handle)
2624 * - shrink_page_list via pdflush (no journal handle)
2625 * - grab_page_cache when doing write_begin (have journal handle)
2627 * We don't do any block allocation in this function. If we have page with
2628 * multiple blocks we need to write those buffer_heads that are mapped. This
2629 * is important for mmaped based write. So if we do with blocksize 1K
2630 * truncate(f, 1024);
2631 * a = mmap(f, 0, 4096);
2633 * truncate(f, 4096);
2634 * we have in the page first buffer_head mapped via page_mkwrite call back
2635 * but other bufer_heads would be unmapped but dirty(dirty done via the
2636 * do_wp_page). So writepage should write the first block. If we modify
2637 * the mmap area beyond 1024 we will again get a page_fault and the
2638 * page_mkwrite callback will do the block allocation and mark the
2639 * buffer_heads mapped.
2641 * We redirty the page if we have any buffer_heads that is either delay or
2642 * unwritten in the page.
2644 * We can get recursively called as show below.
2646 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2649 * But since we don't do any block allocation we should not deadlock.
2650 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2652 static int ext4_writepage(struct page *page,
2653 struct writeback_control *wbc)
2655 int ret = 0, commit_write = 0;
2658 struct buffer_head *page_bufs = NULL;
2659 struct inode *inode = page->mapping->host;
2661 trace_ext4_writepage(page);
2662 size = i_size_read(inode);
2663 if (page->index == size >> PAGE_CACHE_SHIFT)
2664 len = size & ~PAGE_CACHE_MASK;
2666 len = PAGE_CACHE_SIZE;
2669 * If the page does not have buffers (for whatever reason),
2670 * try to create them using __block_write_begin. If this
2671 * fails, redirty the page and move on.
2673 if (!page_has_buffers(page)) {
2674 if (__block_write_begin(page, 0, len,
2675 noalloc_get_block_write)) {
2677 redirty_page_for_writepage(wbc, page);
2683 page_bufs = page_buffers(page);
2684 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2685 ext4_bh_delay_or_unwritten)) {
2687 * We don't want to do block allocation, so redirty
2688 * the page and return. We may reach here when we do
2689 * a journal commit via journal_submit_inode_data_buffers.
2690 * We can also reach here via shrink_page_list
2695 /* now mark the buffer_heads as dirty and uptodate */
2696 block_commit_write(page, 0, len);
2698 if (PageChecked(page) && ext4_should_journal_data(inode))
2700 * It's mmapped pagecache. Add buffers and journal it. There
2701 * doesn't seem much point in redirtying the page here.
2703 return __ext4_journalled_writepage(page, len);
2705 if (buffer_uninit(page_bufs)) {
2706 ext4_set_bh_endio(page_bufs, inode);
2707 ret = block_write_full_page_endio(page, noalloc_get_block_write,
2708 wbc, ext4_end_io_buffer_write);
2710 ret = block_write_full_page(page, noalloc_get_block_write,
2717 * This is called via ext4_da_writepages() to
2718 * calculate the total number of credits to reserve to fit
2719 * a single extent allocation into a single transaction,
2720 * ext4_da_writpeages() will loop calling this before
2721 * the block allocation.
2724 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2726 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2729 * With non-extent format the journal credit needed to
2730 * insert nrblocks contiguous block is dependent on
2731 * number of contiguous block. So we will limit
2732 * number of contiguous block to a sane value
2734 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2735 (max_blocks > EXT4_MAX_TRANS_DATA))
2736 max_blocks = EXT4_MAX_TRANS_DATA;
2738 return ext4_chunk_trans_blocks(inode, max_blocks);
2742 * write_cache_pages_da - walk the list of dirty pages of the given
2743 * address space and accumulate pages that need writing, and call
2744 * mpage_da_map_and_submit to map a single contiguous memory region
2745 * and then write them.
2747 static int write_cache_pages_da(struct address_space *mapping,
2748 struct writeback_control *wbc,
2749 struct mpage_da_data *mpd,
2750 pgoff_t *done_index)
2752 struct buffer_head *bh, *head;
2753 struct inode *inode = mapping->host;
2754 struct pagevec pvec;
2755 unsigned int nr_pages;
2758 long nr_to_write = wbc->nr_to_write;
2759 int i, tag, ret = 0;
2761 memset(mpd, 0, sizeof(struct mpage_da_data));
2764 pagevec_init(&pvec, 0);
2765 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2766 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2768 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2769 tag = PAGECACHE_TAG_TOWRITE;
2771 tag = PAGECACHE_TAG_DIRTY;
2773 *done_index = index;
2774 while (index <= end) {
2775 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2776 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2780 for (i = 0; i < nr_pages; i++) {
2781 struct page *page = pvec.pages[i];
2784 * At this point, the page may be truncated or
2785 * invalidated (changing page->mapping to NULL), or
2786 * even swizzled back from swapper_space to tmpfs file
2787 * mapping. However, page->index will not change
2788 * because we have a reference on the page.
2790 if (page->index > end)
2793 *done_index = page->index + 1;
2796 * If we can't merge this page, and we have
2797 * accumulated an contiguous region, write it
2799 if ((mpd->next_page != page->index) &&
2800 (mpd->next_page != mpd->first_page)) {
2801 mpage_da_map_and_submit(mpd);
2802 goto ret_extent_tail;
2808 * If the page is no longer dirty, or its
2809 * mapping no longer corresponds to inode we
2810 * are writing (which means it has been
2811 * truncated or invalidated), or the page is
2812 * already under writeback and we are not
2813 * doing a data integrity writeback, skip the page
2815 if (!PageDirty(page) ||
2816 (PageWriteback(page) &&
2817 (wbc->sync_mode == WB_SYNC_NONE)) ||
2818 unlikely(page->mapping != mapping)) {
2823 wait_on_page_writeback(page);
2824 BUG_ON(PageWriteback(page));
2826 if (mpd->next_page != page->index)
2827 mpd->first_page = page->index;
2828 mpd->next_page = page->index + 1;
2829 logical = (sector_t) page->index <<
2830 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2832 if (!page_has_buffers(page)) {
2833 mpage_add_bh_to_extent(mpd, logical,
2835 (1 << BH_Dirty) | (1 << BH_Uptodate));
2837 goto ret_extent_tail;
2840 * Page with regular buffer heads,
2841 * just add all dirty ones
2843 head = page_buffers(page);
2846 BUG_ON(buffer_locked(bh));
2848 * We need to try to allocate
2849 * unmapped blocks in the same page.
2850 * Otherwise we won't make progress
2851 * with the page in ext4_writepage
2853 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2854 mpage_add_bh_to_extent(mpd, logical,
2858 goto ret_extent_tail;
2859 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2861 * mapped dirty buffer. We need
2862 * to update the b_state
2863 * because we look at b_state
2864 * in mpage_da_map_blocks. We
2865 * don't update b_size because
2866 * if we find an unmapped
2867 * buffer_head later we need to
2868 * use the b_state flag of that
2871 if (mpd->b_size == 0)
2872 mpd->b_state = bh->b_state & BH_FLAGS;
2875 } while ((bh = bh->b_this_page) != head);
2878 if (nr_to_write > 0) {
2880 if (nr_to_write == 0 &&
2881 wbc->sync_mode == WB_SYNC_NONE)
2883 * We stop writing back only if we are
2884 * not doing integrity sync. In case of
2885 * integrity sync we have to keep going
2886 * because someone may be concurrently
2887 * dirtying pages, and we might have
2888 * synced a lot of newly appeared dirty
2889 * pages, but have not synced all of the
2895 pagevec_release(&pvec);
2900 ret = MPAGE_DA_EXTENT_TAIL;
2902 pagevec_release(&pvec);
2908 static int ext4_da_writepages(struct address_space *mapping,
2909 struct writeback_control *wbc)
2912 int range_whole = 0;
2913 handle_t *handle = NULL;
2914 struct mpage_da_data mpd;
2915 struct inode *inode = mapping->host;
2916 int pages_written = 0;
2917 unsigned int max_pages;
2918 int range_cyclic, cycled = 1, io_done = 0;
2919 int needed_blocks, ret = 0;
2920 long desired_nr_to_write, nr_to_writebump = 0;
2921 loff_t range_start = wbc->range_start;
2922 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2923 pgoff_t done_index = 0;
2926 trace_ext4_da_writepages(inode, wbc);
2929 * No pages to write? This is mainly a kludge to avoid starting
2930 * a transaction for special inodes like journal inode on last iput()
2931 * because that could violate lock ordering on umount
2933 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2937 * If the filesystem has aborted, it is read-only, so return
2938 * right away instead of dumping stack traces later on that
2939 * will obscure the real source of the problem. We test
2940 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2941 * the latter could be true if the filesystem is mounted
2942 * read-only, and in that case, ext4_da_writepages should
2943 * *never* be called, so if that ever happens, we would want
2946 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2949 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2952 range_cyclic = wbc->range_cyclic;
2953 if (wbc->range_cyclic) {
2954 index = mapping->writeback_index;
2957 wbc->range_start = index << PAGE_CACHE_SHIFT;
2958 wbc->range_end = LLONG_MAX;
2959 wbc->range_cyclic = 0;
2962 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2963 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2967 * This works around two forms of stupidity. The first is in
2968 * the writeback code, which caps the maximum number of pages
2969 * written to be 1024 pages. This is wrong on multiple
2970 * levels; different architectues have a different page size,
2971 * which changes the maximum amount of data which gets
2972 * written. Secondly, 4 megabytes is way too small. XFS
2973 * forces this value to be 16 megabytes by multiplying
2974 * nr_to_write parameter by four, and then relies on its
2975 * allocator to allocate larger extents to make them
2976 * contiguous. Unfortunately this brings us to the second
2977 * stupidity, which is that ext4's mballoc code only allocates
2978 * at most 2048 blocks. So we force contiguous writes up to
2979 * the number of dirty blocks in the inode, or
2980 * sbi->max_writeback_mb_bump whichever is smaller.
2982 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2983 if (!range_cyclic && range_whole) {
2984 if (wbc->nr_to_write == LONG_MAX)
2985 desired_nr_to_write = wbc->nr_to_write;
2987 desired_nr_to_write = wbc->nr_to_write * 8;
2989 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2991 if (desired_nr_to_write > max_pages)
2992 desired_nr_to_write = max_pages;
2994 if (wbc->nr_to_write < desired_nr_to_write) {
2995 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2996 wbc->nr_to_write = desired_nr_to_write;
3000 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3001 tag_pages_for_writeback(mapping, index, end);
3003 while (!ret && wbc->nr_to_write > 0) {
3006 * we insert one extent at a time. So we need
3007 * credit needed for single extent allocation.
3008 * journalled mode is currently not supported
3011 BUG_ON(ext4_should_journal_data(inode));
3012 needed_blocks = ext4_da_writepages_trans_blocks(inode);
3014 /* start a new transaction*/
3015 handle = ext4_journal_start(inode, needed_blocks);
3016 if (IS_ERR(handle)) {
3017 ret = PTR_ERR(handle);
3018 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
3019 "%ld pages, ino %lu; err %d", __func__,
3020 wbc->nr_to_write, inode->i_ino, ret);
3021 goto out_writepages;
3025 * Now call write_cache_pages_da() to find the next
3026 * contiguous region of logical blocks that need
3027 * blocks to be allocated by ext4 and submit them.
3029 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
3031 * If we have a contiguous extent of pages and we
3032 * haven't done the I/O yet, map the blocks and submit
3035 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
3036 mpage_da_map_and_submit(&mpd);
3037 ret = MPAGE_DA_EXTENT_TAIL;
3039 trace_ext4_da_write_pages(inode, &mpd);
3040 wbc->nr_to_write -= mpd.pages_written;
3042 ext4_journal_stop(handle);
3044 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
3045 /* commit the transaction which would
3046 * free blocks released in the transaction
3049 jbd2_journal_force_commit_nested(sbi->s_journal);
3051 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
3053 * got one extent now try with
3056 pages_written += mpd.pages_written;
3059 } else if (wbc->nr_to_write)
3061 * There is no more writeout needed
3062 * or we requested for a noblocking writeout
3063 * and we found the device congested
3067 if (!io_done && !cycled) {
3070 wbc->range_start = index << PAGE_CACHE_SHIFT;
3071 wbc->range_end = mapping->writeback_index - 1;
3076 wbc->range_cyclic = range_cyclic;
3077 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3079 * set the writeback_index so that range_cyclic
3080 * mode will write it back later
3082 mapping->writeback_index = done_index;
3085 wbc->nr_to_write -= nr_to_writebump;
3086 wbc->range_start = range_start;
3087 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
3091 #define FALL_BACK_TO_NONDELALLOC 1
3092 static int ext4_nonda_switch(struct super_block *sb)
3094 s64 free_blocks, dirty_blocks;
3095 struct ext4_sb_info *sbi = EXT4_SB(sb);
3098 * switch to non delalloc mode if we are running low
3099 * on free block. The free block accounting via percpu
3100 * counters can get slightly wrong with percpu_counter_batch getting
3101 * accumulated on each CPU without updating global counters
3102 * Delalloc need an accurate free block accounting. So switch
3103 * to non delalloc when we are near to error range.
3105 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
3106 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
3107 if (2 * free_blocks < 3 * dirty_blocks ||
3108 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
3110 * free block count is less than 150% of dirty blocks
3111 * or free blocks is less than watermark
3116 * Even if we don't switch but are nearing capacity,
3117 * start pushing delalloc when 1/2 of free blocks are dirty.
3119 if (free_blocks < 2 * dirty_blocks)
3120 writeback_inodes_sb_if_idle(sb);
3125 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3126 loff_t pos, unsigned len, unsigned flags,
3127 struct page **pagep, void **fsdata)
3129 int ret, retries = 0;
3132 struct inode *inode = mapping->host;
3135 index = pos >> PAGE_CACHE_SHIFT;
3137 if (ext4_nonda_switch(inode->i_sb)) {
3138 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3139 return ext4_write_begin(file, mapping, pos,
3140 len, flags, pagep, fsdata);
3142 *fsdata = (void *)0;
3143 trace_ext4_da_write_begin(inode, pos, len, flags);
3146 * With delayed allocation, we don't log the i_disksize update
3147 * if there is delayed block allocation. But we still need
3148 * to journalling the i_disksize update if writes to the end
3149 * of file which has an already mapped buffer.
3151 handle = ext4_journal_start(inode, 1);
3152 if (IS_ERR(handle)) {
3153 ret = PTR_ERR(handle);
3156 /* We cannot recurse into the filesystem as the transaction is already
3158 flags |= AOP_FLAG_NOFS;
3160 page = grab_cache_page_write_begin(mapping, index, flags);
3162 ext4_journal_stop(handle);
3168 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3171 ext4_journal_stop(handle);
3172 page_cache_release(page);
3174 * block_write_begin may have instantiated a few blocks
3175 * outside i_size. Trim these off again. Don't need
3176 * i_size_read because we hold i_mutex.
3178 if (pos + len > inode->i_size)
3179 ext4_truncate_failed_write(inode);
3182 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3189 * Check if we should update i_disksize
3190 * when write to the end of file but not require block allocation
3192 static int ext4_da_should_update_i_disksize(struct page *page,
3193 unsigned long offset)
3195 struct buffer_head *bh;
3196 struct inode *inode = page->mapping->host;
3200 bh = page_buffers(page);
3201 idx = offset >> inode->i_blkbits;
3203 for (i = 0; i < idx; i++)
3204 bh = bh->b_this_page;
3206 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3211 static int ext4_da_write_end(struct file *file,
3212 struct address_space *mapping,
3213 loff_t pos, unsigned len, unsigned copied,
3214 struct page *page, void *fsdata)
3216 struct inode *inode = mapping->host;
3218 handle_t *handle = ext4_journal_current_handle();
3220 unsigned long start, end;
3221 int write_mode = (int)(unsigned long)fsdata;
3223 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
3224 switch (ext4_inode_journal_mode(inode)) {
3225 case EXT4_INODE_ORDERED_DATA_MODE:
3226 return ext4_ordered_write_end(file, mapping, pos,
3227 len, copied, page, fsdata);
3228 case EXT4_INODE_WRITEBACK_DATA_MODE:
3229 return ext4_writeback_write_end(file, mapping, pos,
3230 len, copied, page, fsdata);
3236 trace_ext4_da_write_end(inode, pos, len, copied);
3237 start = pos & (PAGE_CACHE_SIZE - 1);
3238 end = start + copied - 1;
3241 * generic_write_end() will run mark_inode_dirty() if i_size
3242 * changes. So let's piggyback the i_disksize mark_inode_dirty
3246 new_i_size = pos + copied;
3247 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3248 if (ext4_da_should_update_i_disksize(page, end)) {
3249 down_write(&EXT4_I(inode)->i_data_sem);
3250 if (new_i_size > EXT4_I(inode)->i_disksize) {
3252 * Updating i_disksize when extending file
3253 * without needing block allocation
3255 if (ext4_should_order_data(inode))
3256 ret = ext4_jbd2_file_inode(handle,
3259 EXT4_I(inode)->i_disksize = new_i_size;
3261 up_write(&EXT4_I(inode)->i_data_sem);
3262 /* We need to mark inode dirty even if
3263 * new_i_size is less that inode->i_size
3264 * bu greater than i_disksize.(hint delalloc)
3266 ext4_mark_inode_dirty(handle, inode);
3269 ret2 = generic_write_end(file, mapping, pos, len, copied,
3274 ret2 = ext4_journal_stop(handle);
3278 return ret ? ret : copied;
3281 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
3284 * Drop reserved blocks
3286 BUG_ON(!PageLocked(page));
3287 if (!page_has_buffers(page))
3290 ext4_da_page_release_reservation(page, offset);
3293 ext4_invalidatepage(page, offset);
3299 * Force all delayed allocation blocks to be allocated for a given inode.
3301 int ext4_alloc_da_blocks(struct inode *inode)
3303 trace_ext4_alloc_da_blocks(inode);
3305 if (!EXT4_I(inode)->i_reserved_data_blocks &&
3306 !EXT4_I(inode)->i_reserved_meta_blocks)
3310 * We do something simple for now. The filemap_flush() will
3311 * also start triggering a write of the data blocks, which is
3312 * not strictly speaking necessary (and for users of
3313 * laptop_mode, not even desirable). However, to do otherwise
3314 * would require replicating code paths in:
3316 * ext4_da_writepages() ->
3317 * write_cache_pages() ---> (via passed in callback function)
3318 * __mpage_da_writepage() -->
3319 * mpage_add_bh_to_extent()
3320 * mpage_da_map_blocks()
3322 * The problem is that write_cache_pages(), located in
3323 * mm/page-writeback.c, marks pages clean in preparation for
3324 * doing I/O, which is not desirable if we're not planning on
3327 * We could call write_cache_pages(), and then redirty all of
3328 * the pages by calling redirty_page_for_writepage() but that
3329 * would be ugly in the extreme. So instead we would need to
3330 * replicate parts of the code in the above functions,
3331 * simplifying them because we wouldn't actually intend to
3332 * write out the pages, but rather only collect contiguous
3333 * logical block extents, call the multi-block allocator, and
3334 * then update the buffer heads with the block allocations.
3336 * For now, though, we'll cheat by calling filemap_flush(),
3337 * which will map the blocks, and start the I/O, but not
3338 * actually wait for the I/O to complete.
3340 return filemap_flush(inode->i_mapping);
3344 * bmap() is special. It gets used by applications such as lilo and by
3345 * the swapper to find the on-disk block of a specific piece of data.
3347 * Naturally, this is dangerous if the block concerned is still in the
3348 * journal. If somebody makes a swapfile on an ext4 data-journaling
3349 * filesystem and enables swap, then they may get a nasty shock when the
3350 * data getting swapped to that swapfile suddenly gets overwritten by
3351 * the original zero's written out previously to the journal and
3352 * awaiting writeback in the kernel's buffer cache.
3354 * So, if we see any bmap calls here on a modified, data-journaled file,
3355 * take extra steps to flush any blocks which might be in the cache.
3357 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3359 struct inode *inode = mapping->host;
3363 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3364 test_opt(inode->i_sb, DELALLOC)) {
3366 * With delalloc we want to sync the file
3367 * so that we can make sure we allocate
3370 filemap_write_and_wait(mapping);
3373 if (EXT4_JOURNAL(inode) &&
3374 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3376 * This is a REALLY heavyweight approach, but the use of
3377 * bmap on dirty files is expected to be extremely rare:
3378 * only if we run lilo or swapon on a freshly made file
3379 * do we expect this to happen.
3381 * (bmap requires CAP_SYS_RAWIO so this does not
3382 * represent an unprivileged user DOS attack --- we'd be
3383 * in trouble if mortal users could trigger this path at
3386 * NB. EXT4_STATE_JDATA is not set on files other than
3387 * regular files. If somebody wants to bmap a directory
3388 * or symlink and gets confused because the buffer
3389 * hasn't yet been flushed to disk, they deserve
3390 * everything they get.
3393 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3394 journal = EXT4_JOURNAL(inode);
3395 jbd2_journal_lock_updates(journal);
3396 err = jbd2_journal_flush(journal);
3397 jbd2_journal_unlock_updates(journal);
3403 return generic_block_bmap(mapping, block, ext4_get_block);
3406 static int ext4_readpage(struct file *file, struct page *page)
3408 trace_ext4_readpage(page);
3409 return mpage_readpage(page, ext4_get_block);
3413 ext4_readpages(struct file *file, struct address_space *mapping,
3414 struct list_head *pages, unsigned nr_pages)
3416 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3419 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
3421 struct buffer_head *head, *bh;
3422 unsigned int curr_off = 0;
3424 if (!page_has_buffers(page))
3426 head = bh = page_buffers(page);
3428 if (offset <= curr_off && test_clear_buffer_uninit(bh)
3430 ext4_free_io_end(bh->b_private);
3431 bh->b_private = NULL;
3432 bh->b_end_io = NULL;
3434 curr_off = curr_off + bh->b_size;
3435 bh = bh->b_this_page;
3436 } while (bh != head);
3439 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3441 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3443 trace_ext4_invalidatepage(page, offset);
3446 * free any io_end structure allocated for buffers to be discarded
3448 if (ext4_should_dioread_nolock(page->mapping->host))
3449 ext4_invalidatepage_free_endio(page, offset);
3451 * If it's a full truncate we just forget about the pending dirtying
3454 ClearPageChecked(page);
3457 jbd2_journal_invalidatepage(journal, page, offset);
3459 block_invalidatepage(page, offset);
3462 static int ext4_releasepage(struct page *page, gfp_t wait)
3464 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3466 trace_ext4_releasepage(page);
3468 WARN_ON(PageChecked(page));
3469 if (!page_has_buffers(page))
3472 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3474 return try_to_free_buffers(page);
3478 * O_DIRECT for ext3 (or indirect map) based files
3480 * If the O_DIRECT write will extend the file then add this inode to the
3481 * orphan list. So recovery will truncate it back to the original size
3482 * if the machine crashes during the write.
3484 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3485 * crashes then stale disk data _may_ be exposed inside the file. But current
3486 * VFS code falls back into buffered path in that case so we are safe.
3488 static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
3489 const struct iovec *iov, loff_t offset,
3490 unsigned long nr_segs)
3492 struct file *file = iocb->ki_filp;
3493 struct inode *inode = file->f_mapping->host;
3494 struct ext4_inode_info *ei = EXT4_I(inode);
3498 size_t count = iov_length(iov, nr_segs);
3502 loff_t final_size = offset + count;
3504 if (final_size > inode->i_size) {
3505 /* Credits for sb + inode write */
3506 handle = ext4_journal_start(inode, 2);
3507 if (IS_ERR(handle)) {
3508 ret = PTR_ERR(handle);
3511 ret = ext4_orphan_add(handle, inode);
3513 ext4_journal_stop(handle);
3517 ei->i_disksize = inode->i_size;
3518 ext4_journal_stop(handle);
3523 if (rw == READ && ext4_should_dioread_nolock(inode)) {
3524 if (unlikely(!list_empty(&ei->i_completed_io_list))) {
3525 mutex_lock(&inode->i_mutex);
3526 ext4_flush_completed_IO(inode);
3527 mutex_unlock(&inode->i_mutex);
3529 ret = __blockdev_direct_IO(rw, iocb, inode,
3530 inode->i_sb->s_bdev, iov,
3532 ext4_get_block, NULL, NULL, 0);
3534 ret = blockdev_direct_IO(rw, iocb, inode,
3535 inode->i_sb->s_bdev, iov,
3537 ext4_get_block, NULL);
3539 if (unlikely((rw & WRITE) && ret < 0)) {
3540 loff_t isize = i_size_read(inode);
3541 loff_t end = offset + iov_length(iov, nr_segs);
3544 ext4_truncate_failed_write(inode);
3547 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3553 /* Credits for sb + inode write */
3554 handle = ext4_journal_start(inode, 2);
3555 if (IS_ERR(handle)) {
3556 /* This is really bad luck. We've written the data
3557 * but cannot extend i_size. Bail out and pretend
3558 * the write failed... */
3559 ret = PTR_ERR(handle);
3561 ext4_orphan_del(NULL, inode);
3566 ext4_orphan_del(handle, inode);
3568 loff_t end = offset + ret;
3569 if (end > inode->i_size) {
3570 ei->i_disksize = end;
3571 i_size_write(inode, end);
3573 * We're going to return a positive `ret'
3574 * here due to non-zero-length I/O, so there's
3575 * no way of reporting error returns from
3576 * ext4_mark_inode_dirty() to userspace. So
3579 ext4_mark_inode_dirty(handle, inode);
3582 err = ext4_journal_stop(handle);
3591 * ext4_get_block used when preparing for a DIO write or buffer write.
3592 * We allocate an uinitialized extent if blocks haven't been allocated.
3593 * The extent will be converted to initialized after the IO is complete.
3595 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
3596 struct buffer_head *bh_result, int create)
3598 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3599 inode->i_ino, create);
3600 return _ext4_get_block(inode, iblock, bh_result,
3601 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3604 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3605 ssize_t size, void *private, int ret,
3608 ext4_io_end_t *io_end = iocb->private;
3609 struct workqueue_struct *wq;
3610 unsigned long flags;
3611 struct ext4_inode_info *ei;
3613 /* if not async direct IO or dio with 0 bytes write, just return */
3614 if (!io_end || !size)
3617 ext_debug("ext4_end_io_dio(): io_end 0x%p"
3618 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
3619 iocb->private, io_end->inode->i_ino, iocb, offset,
3622 /* if not aio dio with unwritten extents, just free io and return */
3623 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
3624 ext4_free_io_end(io_end);
3625 iocb->private = NULL;
3628 aio_complete(iocb, ret, 0);
3632 io_end->offset = offset;
3633 io_end->size = size;
3635 io_end->iocb = iocb;
3636 io_end->result = ret;
3638 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
3640 /* Add the io_end to per-inode completed aio dio list*/
3641 ei = EXT4_I(io_end->inode);
3642 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3643 list_add_tail(&io_end->list, &ei->i_completed_io_list);
3644 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
3646 /* queue the work to convert unwritten extents to written */
3647 queue_work(wq, &io_end->work);
3648 iocb->private = NULL;
3651 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
3653 ext4_io_end_t *io_end = bh->b_private;
3654 struct workqueue_struct *wq;
3655 struct inode *inode;
3656 unsigned long flags;
3658 if (!test_clear_buffer_uninit(bh) || !io_end)
3661 if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
3662 printk("sb umounted, discard end_io request for inode %lu\n",
3663 io_end->inode->i_ino);
3664 ext4_free_io_end(io_end);
3669 * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
3670 * but being more careful is always safe for the future change.
3672 inode = io_end->inode;
3673 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
3674 io_end->flag |= EXT4_IO_END_UNWRITTEN;
3675 atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
3678 /* Add the io_end to per-inode completed io list*/
3679 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
3680 list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
3681 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
3683 wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
3684 /* queue the work to convert unwritten extents to written */
3685 queue_work(wq, &io_end->work);
3687 bh->b_private = NULL;
3688 bh->b_end_io = NULL;
3689 clear_buffer_uninit(bh);
3690 end_buffer_async_write(bh, uptodate);
3693 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
3695 ext4_io_end_t *io_end;
3696 struct page *page = bh->b_page;
3697 loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
3698 size_t size = bh->b_size;
3701 io_end = ext4_init_io_end(inode, GFP_ATOMIC);
3703 pr_warn_ratelimited("%s: allocation fail\n", __func__);
3707 io_end->offset = offset;
3708 io_end->size = size;
3710 * We need to hold a reference to the page to make sure it
3711 * doesn't get evicted before ext4_end_io_work() has a chance
3712 * to convert the extent from written to unwritten.
3714 io_end->page = page;
3715 get_page(io_end->page);
3717 bh->b_private = io_end;
3718 bh->b_end_io = ext4_end_io_buffer_write;
3723 * For ext4 extent files, ext4 will do direct-io write to holes,
3724 * preallocated extents, and those write extend the file, no need to
3725 * fall back to buffered IO.
3727 * For holes, we fallocate those blocks, mark them as uninitialized
3728 * If those blocks were preallocated, we mark sure they are splited, but
3729 * still keep the range to write as uninitialized.
3731 * The unwrritten extents will be converted to written when DIO is completed.
3732 * For async direct IO, since the IO may still pending when return, we
3733 * set up an end_io call back function, which will do the conversion
3734 * when async direct IO completed.
3736 * If the O_DIRECT write will extend the file then add this inode to the
3737 * orphan list. So recovery will truncate it back to the original size
3738 * if the machine crashes during the write.
3741 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3742 const struct iovec *iov, loff_t offset,
3743 unsigned long nr_segs)
3745 struct file *file = iocb->ki_filp;
3746 struct inode *inode = file->f_mapping->host;
3748 size_t count = iov_length(iov, nr_segs);
3750 loff_t final_size = offset + count;
3751 if (rw == WRITE && final_size <= inode->i_size) {
3753 * We could direct write to holes and fallocate.
3755 * Allocated blocks to fill the hole are marked as uninitialized
3756 * to prevent parallel buffered read to expose the stale data
3757 * before DIO complete the data IO.
3759 * As to previously fallocated extents, ext4 get_block
3760 * will just simply mark the buffer mapped but still
3761 * keep the extents uninitialized.
3763 * for non AIO case, we will convert those unwritten extents
3764 * to written after return back from blockdev_direct_IO.
3766 * for async DIO, the conversion needs to be defered when
3767 * the IO is completed. The ext4 end_io callback function
3768 * will be called to take care of the conversion work.
3769 * Here for async case, we allocate an io_end structure to
3772 iocb->private = NULL;
3773 EXT4_I(inode)->cur_aio_dio = NULL;
3774 if (!is_sync_kiocb(iocb)) {
3775 iocb->private = ext4_init_io_end(inode, GFP_NOFS);
3779 * we save the io structure for current async
3780 * direct IO, so that later ext4_map_blocks()
3781 * could flag the io structure whether there
3782 * is a unwritten extents needs to be converted
3783 * when IO is completed.
3785 EXT4_I(inode)->cur_aio_dio = iocb->private;
3788 ret = blockdev_direct_IO(rw, iocb, inode,
3789 inode->i_sb->s_bdev, iov,
3791 ext4_get_block_write,
3794 EXT4_I(inode)->cur_aio_dio = NULL;
3796 * The io_end structure takes a reference to the inode,
3797 * that structure needs to be destroyed and the
3798 * reference to the inode need to be dropped, when IO is
3799 * complete, even with 0 byte write, or failed.
3801 * In the successful AIO DIO case, the io_end structure will be
3802 * desctroyed and the reference to the inode will be dropped
3803 * after the end_io call back function is called.
3805 * In the case there is 0 byte write, or error case, since
3806 * VFS direct IO won't invoke the end_io call back function,
3807 * we need to free the end_io structure here.
3809 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3810 ext4_free_io_end(iocb->private);
3811 iocb->private = NULL;
3812 } else if (ret > 0 && ext4_test_inode_state(inode,
3813 EXT4_STATE_DIO_UNWRITTEN)) {
3816 * for non AIO case, since the IO is already
3817 * completed, we could do the conversion right here
3819 err = ext4_convert_unwritten_extents(inode,
3823 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3828 /* for write the the end of file case, we fall back to old way */
3829 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3832 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3833 const struct iovec *iov, loff_t offset,
3834 unsigned long nr_segs)
3836 struct file *file = iocb->ki_filp;
3837 struct inode *inode = file->f_mapping->host;
3840 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3841 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3842 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3844 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3845 trace_ext4_direct_IO_exit(inode, offset,
3846 iov_length(iov, nr_segs), rw, ret);
3851 * Pages can be marked dirty completely asynchronously from ext4's journalling
3852 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3853 * much here because ->set_page_dirty is called under VFS locks. The page is
3854 * not necessarily locked.
3856 * We cannot just dirty the page and leave attached buffers clean, because the
3857 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3858 * or jbddirty because all the journalling code will explode.
3860 * So what we do is to mark the page "pending dirty" and next time writepage
3861 * is called, propagate that into the buffers appropriately.
3863 static int ext4_journalled_set_page_dirty(struct page *page)
3865 SetPageChecked(page);
3866 return __set_page_dirty_nobuffers(page);
3869 static const struct address_space_operations ext4_ordered_aops = {
3870 .readpage = ext4_readpage,
3871 .readpages = ext4_readpages,
3872 .writepage = ext4_writepage,
3873 .write_begin = ext4_write_begin,
3874 .write_end = ext4_ordered_write_end,
3876 .invalidatepage = ext4_invalidatepage,
3877 .releasepage = ext4_releasepage,
3878 .direct_IO = ext4_direct_IO,
3879 .migratepage = buffer_migrate_page,
3880 .is_partially_uptodate = block_is_partially_uptodate,
3881 .error_remove_page = generic_error_remove_page,
3884 static const struct address_space_operations ext4_writeback_aops = {
3885 .readpage = ext4_readpage,
3886 .readpages = ext4_readpages,
3887 .writepage = ext4_writepage,
3888 .write_begin = ext4_write_begin,
3889 .write_end = ext4_writeback_write_end,
3891 .invalidatepage = ext4_invalidatepage,
3892 .releasepage = ext4_releasepage,
3893 .direct_IO = ext4_direct_IO,
3894 .migratepage = buffer_migrate_page,
3895 .is_partially_uptodate = block_is_partially_uptodate,
3896 .error_remove_page = generic_error_remove_page,
3899 static const struct address_space_operations ext4_journalled_aops = {
3900 .readpage = ext4_readpage,
3901 .readpages = ext4_readpages,
3902 .writepage = ext4_writepage,
3903 .write_begin = ext4_write_begin,
3904 .write_end = ext4_journalled_write_end,
3905 .set_page_dirty = ext4_journalled_set_page_dirty,
3907 .invalidatepage = ext4_invalidatepage,
3908 .releasepage = ext4_releasepage,
3909 .is_partially_uptodate = block_is_partially_uptodate,
3910 .error_remove_page = generic_error_remove_page,
3913 static const struct address_space_operations ext4_da_aops = {
3914 .readpage = ext4_readpage,
3915 .readpages = ext4_readpages,
3916 .writepage = ext4_writepage,
3917 .writepages = ext4_da_writepages,
3918 .write_begin = ext4_da_write_begin,
3919 .write_end = ext4_da_write_end,
3921 .invalidatepage = ext4_da_invalidatepage,
3922 .releasepage = ext4_releasepage,
3923 .direct_IO = ext4_direct_IO,
3924 .migratepage = buffer_migrate_page,
3925 .is_partially_uptodate = block_is_partially_uptodate,
3926 .error_remove_page = generic_error_remove_page,
3929 void ext4_set_aops(struct inode *inode)
3931 switch (ext4_inode_journal_mode(inode)) {
3932 case EXT4_INODE_ORDERED_DATA_MODE:
3933 if (test_opt(inode->i_sb, DELALLOC))
3934 inode->i_mapping->a_ops = &ext4_da_aops;
3936 inode->i_mapping->a_ops = &ext4_ordered_aops;
3938 case EXT4_INODE_WRITEBACK_DATA_MODE:
3939 if (test_opt(inode->i_sb, DELALLOC))
3940 inode->i_mapping->a_ops = &ext4_da_aops;
3942 inode->i_mapping->a_ops = &ext4_writeback_aops;
3944 case EXT4_INODE_JOURNAL_DATA_MODE:
3945 inode->i_mapping->a_ops = &ext4_journalled_aops;
3953 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3954 * up to the end of the block which corresponds to `from'.
3955 * This required during truncate. We need to physically zero the tail end
3956 * of that block so it doesn't yield old data if the file is later grown.
3958 int ext4_block_truncate_page(handle_t *handle,
3959 struct address_space *mapping, loff_t from)
3961 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3964 struct inode *inode = mapping->host;
3966 blocksize = inode->i_sb->s_blocksize;
3967 length = blocksize - (offset & (blocksize - 1));
3969 return ext4_block_zero_page_range(handle, mapping, from, length);
3973 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3974 * starting from file offset 'from'. The range to be zero'd must
3975 * be contained with in one block. If the specified range exceeds
3976 * the end of the block it will be shortened to end of the block
3977 * that cooresponds to 'from'
3979 int ext4_block_zero_page_range(handle_t *handle,
3980 struct address_space *mapping, loff_t from, loff_t length)
3982 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3983 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3984 unsigned blocksize, max, pos;
3986 struct inode *inode = mapping->host;
3987 struct buffer_head *bh;
3991 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3992 mapping_gfp_mask(mapping) & ~__GFP_FS);
3996 blocksize = inode->i_sb->s_blocksize;
3997 max = blocksize - (offset & (blocksize - 1));
4000 * correct length if it does not fall between
4001 * 'from' and the end of the block
4003 if (length > max || length < 0)
4006 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
4008 if (!page_has_buffers(page))
4009 create_empty_buffers(page, blocksize, 0);
4011 /* Find the buffer that contains "offset" */
4012 bh = page_buffers(page);
4014 while (offset >= pos) {
4015 bh = bh->b_this_page;
4021 if (buffer_freed(bh)) {
4022 BUFFER_TRACE(bh, "freed: skip");
4026 if (!buffer_mapped(bh)) {
4027 BUFFER_TRACE(bh, "unmapped");
4028 ext4_get_block(inode, iblock, bh, 0);
4029 /* unmapped? It's a hole - nothing to do */
4030 if (!buffer_mapped(bh)) {
4031 BUFFER_TRACE(bh, "still unmapped");
4036 /* Ok, it's mapped. Make sure it's up-to-date */
4037 if (PageUptodate(page))
4038 set_buffer_uptodate(bh);
4040 if (!buffer_uptodate(bh)) {
4042 ll_rw_block(READ, 1, &bh);
4044 /* Uhhuh. Read error. Complain and punt. */
4045 if (!buffer_uptodate(bh))
4049 if (ext4_should_journal_data(inode)) {
4050 BUFFER_TRACE(bh, "get write access");
4051 err = ext4_journal_get_write_access(handle, bh);
4056 zero_user(page, offset, length);
4058 BUFFER_TRACE(bh, "zeroed end of block");
4061 if (ext4_should_journal_data(inode)) {
4062 err = ext4_handle_dirty_metadata(handle, inode, bh);
4064 if (ext4_should_order_data(inode) && EXT4_I(inode)->jinode)
4065 err = ext4_jbd2_file_inode(handle, inode);
4066 mark_buffer_dirty(bh);
4071 page_cache_release(page);
4076 * Probably it should be a library function... search for first non-zero word
4077 * or memcmp with zero_page, whatever is better for particular architecture.
4080 static inline int all_zeroes(__le32 *p, __le32 *q)
4089 * ext4_find_shared - find the indirect blocks for partial truncation.
4090 * @inode: inode in question
4091 * @depth: depth of the affected branch
4092 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
4093 * @chain: place to store the pointers to partial indirect blocks
4094 * @top: place to the (detached) top of branch
4096 * This is a helper function used by ext4_truncate().
4098 * When we do truncate() we may have to clean the ends of several
4099 * indirect blocks but leave the blocks themselves alive. Block is
4100 * partially truncated if some data below the new i_size is referred
4101 * from it (and it is on the path to the first completely truncated
4102 * data block, indeed). We have to free the top of that path along
4103 * with everything to the right of the path. Since no allocation
4104 * past the truncation point is possible until ext4_truncate()
4105 * finishes, we may safely do the latter, but top of branch may
4106 * require special attention - pageout below the truncation point
4107 * might try to populate it.
4109 * We atomically detach the top of branch from the tree, store the
4110 * block number of its root in *@top, pointers to buffer_heads of
4111 * partially truncated blocks - in @chain[].bh and pointers to
4112 * their last elements that should not be removed - in
4113 * @chain[].p. Return value is the pointer to last filled element
4116 * The work left to caller to do the actual freeing of subtrees:
4117 * a) free the subtree starting from *@top
4118 * b) free the subtrees whose roots are stored in
4119 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
4120 * c) free the subtrees growing from the inode past the @chain[0].
4121 * (no partially truncated stuff there). */
4123 static Indirect *ext4_find_shared(struct inode *inode, int depth,
4124 ext4_lblk_t offsets[4], Indirect chain[4],
4127 Indirect *partial, *p;
4131 /* Make k index the deepest non-null offset + 1 */
4132 for (k = depth; k > 1 && !offsets[k-1]; k--)
4134 partial = ext4_get_branch(inode, k, offsets, chain, &err);
4135 /* Writer: pointers */
4137 partial = chain + k-1;
4139 * If the branch acquired continuation since we've looked at it -
4140 * fine, it should all survive and (new) top doesn't belong to us.
4142 if (!partial->key && *partial->p)
4145 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
4148 * OK, we've found the last block that must survive. The rest of our
4149 * branch should be detached before unlocking. However, if that rest
4150 * of branch is all ours and does not grow immediately from the inode
4151 * it's easier to cheat and just decrement partial->p.
4153 if (p == chain + k - 1 && p > chain) {
4157 /* Nope, don't do this in ext4. Must leave the tree intact */
4164 while (partial > p) {
4165 brelse(partial->bh);
4173 * Zero a number of block pointers in either an inode or an indirect block.
4174 * If we restart the transaction we must again get write access to the
4175 * indirect block for further modification.
4177 * We release `count' blocks on disk, but (last - first) may be greater
4178 * than `count' because there can be holes in there.
4180 * Return 0 on success, 1 on invalid block range
4181 * and < 0 on fatal error.
4183 static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
4184 struct buffer_head *bh,
4185 ext4_fsblk_t block_to_free,
4186 unsigned long count, __le32 *first,
4190 int flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED;
4193 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
4194 flags |= EXT4_FREE_BLOCKS_METADATA;
4196 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
4198 EXT4_ERROR_INODE(inode, "attempt to clear invalid "
4199 "blocks %llu len %lu",
4200 (unsigned long long) block_to_free, count);
4204 if (try_to_extend_transaction(handle, inode)) {
4206 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4207 err = ext4_handle_dirty_metadata(handle, inode, bh);
4211 err = ext4_mark_inode_dirty(handle, inode);
4214 err = ext4_truncate_restart_trans(handle, inode,
4215 blocks_for_truncate(inode));
4219 BUFFER_TRACE(bh, "retaking write access");
4220 err = ext4_journal_get_write_access(handle, bh);
4226 for (p = first; p < last; p++)
4229 ext4_free_blocks(handle, inode, NULL, block_to_free, count, flags);
4232 ext4_std_error(inode->i_sb, err);
4237 * ext4_free_data - free a list of data blocks
4238 * @handle: handle for this transaction
4239 * @inode: inode we are dealing with
4240 * @this_bh: indirect buffer_head which contains *@first and *@last
4241 * @first: array of block numbers
4242 * @last: points immediately past the end of array
4244 * We are freeing all blocks referred from that array (numbers are stored as
4245 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
4247 * We accumulate contiguous runs of blocks to free. Conveniently, if these
4248 * blocks are contiguous then releasing them at one time will only affect one
4249 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
4250 * actually use a lot of journal space.
4252 * @this_bh will be %NULL if @first and @last point into the inode's direct
4255 static void ext4_free_data(handle_t *handle, struct inode *inode,
4256 struct buffer_head *this_bh,
4257 __le32 *first, __le32 *last)
4259 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
4260 unsigned long count = 0; /* Number of blocks in the run */
4261 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
4264 ext4_fsblk_t nr; /* Current block # */
4265 __le32 *p; /* Pointer into inode/ind
4266 for current block */
4269 if (this_bh) { /* For indirect block */
4270 BUFFER_TRACE(this_bh, "get_write_access");
4271 err = ext4_journal_get_write_access(handle, this_bh);
4272 /* Important: if we can't update the indirect pointers
4273 * to the blocks, we can't free them. */
4278 for (p = first; p < last; p++) {
4279 nr = le32_to_cpu(*p);
4281 /* accumulate blocks to free if they're contiguous */
4284 block_to_free_p = p;
4286 } else if (nr == block_to_free + count) {
4289 err = ext4_clear_blocks(handle, inode, this_bh,
4290 block_to_free, count,
4291 block_to_free_p, p);
4295 block_to_free_p = p;
4301 if (!err && count > 0)
4302 err = ext4_clear_blocks(handle, inode, this_bh, block_to_free,
4303 count, block_to_free_p, p);
4309 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
4312 * The buffer head should have an attached journal head at this
4313 * point. However, if the data is corrupted and an indirect
4314 * block pointed to itself, it would have been detached when
4315 * the block was cleared. Check for this instead of OOPSing.
4317 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
4318 ext4_handle_dirty_metadata(handle, inode, this_bh);
4320 EXT4_ERROR_INODE(inode,
4321 "circular indirect block detected at "
4323 (unsigned long long) this_bh->b_blocknr);
4328 * ext4_free_branches - free an array of branches
4329 * @handle: JBD handle for this transaction
4330 * @inode: inode we are dealing with
4331 * @parent_bh: the buffer_head which contains *@first and *@last
4332 * @first: array of block numbers
4333 * @last: pointer immediately past the end of array
4334 * @depth: depth of the branches to free
4336 * We are freeing all blocks referred from these branches (numbers are
4337 * stored as little-endian 32-bit) and updating @inode->i_blocks
4340 static void ext4_free_branches(handle_t *handle, struct inode *inode,
4341 struct buffer_head *parent_bh,
4342 __le32 *first, __le32 *last, int depth)
4347 if (ext4_handle_is_aborted(handle))
4351 struct buffer_head *bh;
4352 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4354 while (--p >= first) {
4355 nr = le32_to_cpu(*p);
4357 continue; /* A hole */
4359 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
4361 EXT4_ERROR_INODE(inode,
4362 "invalid indirect mapped "
4363 "block %lu (level %d)",
4364 (unsigned long) nr, depth);
4368 /* Go read the buffer for the next level down */
4369 bh = sb_bread(inode->i_sb, nr);
4372 * A read failure? Report error and clear slot
4376 EXT4_ERROR_INODE_BLOCK(inode, nr,
4381 /* This zaps the entire block. Bottom up. */
4382 BUFFER_TRACE(bh, "free child branches");
4383 ext4_free_branches(handle, inode, bh,
4384 (__le32 *) bh->b_data,
4385 (__le32 *) bh->b_data + addr_per_block,
4390 * Everything below this this pointer has been
4391 * released. Now let this top-of-subtree go.
4393 * We want the freeing of this indirect block to be
4394 * atomic in the journal with the updating of the
4395 * bitmap block which owns it. So make some room in
4398 * We zero the parent pointer *after* freeing its
4399 * pointee in the bitmaps, so if extend_transaction()
4400 * for some reason fails to put the bitmap changes and
4401 * the release into the same transaction, recovery
4402 * will merely complain about releasing a free block,
4403 * rather than leaking blocks.
4405 if (ext4_handle_is_aborted(handle))
4407 if (try_to_extend_transaction(handle, inode)) {
4408 ext4_mark_inode_dirty(handle, inode);
4409 ext4_truncate_restart_trans(handle, inode,
4410 blocks_for_truncate(inode));
4414 * The forget flag here is critical because if
4415 * we are journaling (and not doing data
4416 * journaling), we have to make sure a revoke
4417 * record is written to prevent the journal
4418 * replay from overwriting the (former)
4419 * indirect block if it gets reallocated as a
4420 * data block. This must happen in the same
4421 * transaction where the data blocks are
4424 ext4_free_blocks(handle, inode, NULL, nr, 1,
4425 EXT4_FREE_BLOCKS_METADATA|
4426 EXT4_FREE_BLOCKS_FORGET);
4430 * The block which we have just freed is
4431 * pointed to by an indirect block: journal it
4433 BUFFER_TRACE(parent_bh, "get_write_access");
4434 if (!ext4_journal_get_write_access(handle,
4437 BUFFER_TRACE(parent_bh,
4438 "call ext4_handle_dirty_metadata");
4439 ext4_handle_dirty_metadata(handle,
4446 /* We have reached the bottom of the tree. */
4447 BUFFER_TRACE(parent_bh, "free data blocks");
4448 ext4_free_data(handle, inode, parent_bh, first, last);
4452 int ext4_can_truncate(struct inode *inode)
4454 if (S_ISREG(inode->i_mode))
4456 if (S_ISDIR(inode->i_mode))
4458 if (S_ISLNK(inode->i_mode))
4459 return !ext4_inode_is_fast_symlink(inode);
4464 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
4465 * associated with the given offset and length
4467 * @inode: File inode
4468 * @offset: The offset where the hole will begin
4469 * @len: The length of the hole
4471 * Returns: 0 on sucess or negative on failure
4474 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
4476 struct inode *inode = file->f_path.dentry->d_inode;
4477 if (!S_ISREG(inode->i_mode))
4480 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4481 /* TODO: Add support for non extent hole punching */
4485 return ext4_ext_punch_hole(file, offset, length);
4491 * We block out ext4_get_block() block instantiations across the entire
4492 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4493 * simultaneously on behalf of the same inode.
4495 * As we work through the truncate and commmit bits of it to the journal there
4496 * is one core, guiding principle: the file's tree must always be consistent on
4497 * disk. We must be able to restart the truncate after a crash.
4499 * The file's tree may be transiently inconsistent in memory (although it
4500 * probably isn't), but whenever we close off and commit a journal transaction,
4501 * the contents of (the filesystem + the journal) must be consistent and
4502 * restartable. It's pretty simple, really: bottom up, right to left (although
4503 * left-to-right works OK too).
4505 * Note that at recovery time, journal replay occurs *before* the restart of
4506 * truncate against the orphan inode list.
4508 * The committed inode has the new, desired i_size (which is the same as
4509 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4510 * that this inode's truncate did not complete and it will again call
4511 * ext4_truncate() to have another go. So there will be instantiated blocks
4512 * to the right of the truncation point in a crashed ext4 filesystem. But
4513 * that's fine - as long as they are linked from the inode, the post-crash
4514 * ext4_truncate() run will find them and release them.
4516 void ext4_truncate(struct inode *inode)
4519 struct ext4_inode_info *ei = EXT4_I(inode);
4520 __le32 *i_data = ei->i_data;
4521 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4522 struct address_space *mapping = inode->i_mapping;
4523 ext4_lblk_t offsets[4];
4528 ext4_lblk_t last_block, max_block;
4529 unsigned blocksize = inode->i_sb->s_blocksize;
4531 trace_ext4_truncate_enter(inode);
4533 if (!ext4_can_truncate(inode))
4536 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4538 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4539 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4541 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4542 ext4_ext_truncate(inode);
4543 trace_ext4_truncate_exit(inode);
4547 handle = start_transaction(inode);
4549 return; /* AKPM: return what? */
4551 last_block = (inode->i_size + blocksize-1)
4552 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4553 max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
4554 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4556 if (inode->i_size & (blocksize - 1))
4557 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
4560 if (last_block != max_block) {
4561 n = ext4_block_to_path(inode, last_block, offsets, NULL);
4563 goto out_stop; /* error */
4567 * OK. This truncate is going to happen. We add the inode to the
4568 * orphan list, so that if this truncate spans multiple transactions,
4569 * and we crash, we will resume the truncate when the filesystem
4570 * recovers. It also marks the inode dirty, to catch the new size.
4572 * Implication: the file must always be in a sane, consistent
4573 * truncatable state while each transaction commits.
4575 if (ext4_orphan_add(handle, inode))
4579 * From here we block out all ext4_get_block() callers who want to
4580 * modify the block allocation tree.
4582 down_write(&ei->i_data_sem);
4584 ext4_discard_preallocations(inode);
4587 * The orphan list entry will now protect us from any crash which
4588 * occurs before the truncate completes, so it is now safe to propagate
4589 * the new, shorter inode size (held for now in i_size) into the
4590 * on-disk inode. We do this via i_disksize, which is the value which
4591 * ext4 *really* writes onto the disk inode.
4593 ei->i_disksize = inode->i_size;
4595 if (last_block == max_block) {
4597 * It is unnecessary to free any data blocks if last_block is
4598 * equal to the indirect block limit.
4601 } else if (n == 1) { /* direct blocks */
4602 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
4603 i_data + EXT4_NDIR_BLOCKS);
4607 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
4608 /* Kill the top of shared branch (not detached) */
4610 if (partial == chain) {
4611 /* Shared branch grows from the inode */
4612 ext4_free_branches(handle, inode, NULL,
4613 &nr, &nr+1, (chain+n-1) - partial);
4616 * We mark the inode dirty prior to restart,
4617 * and prior to stop. No need for it here.
4620 /* Shared branch grows from an indirect block */
4621 BUFFER_TRACE(partial->bh, "get_write_access");
4622 ext4_free_branches(handle, inode, partial->bh,
4624 partial->p+1, (chain+n-1) - partial);
4627 /* Clear the ends of indirect blocks on the shared branch */
4628 while (partial > chain) {
4629 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
4630 (__le32*)partial->bh->b_data+addr_per_block,
4631 (chain+n-1) - partial);
4632 BUFFER_TRACE(partial->bh, "call brelse");
4633 brelse(partial->bh);
4637 /* Kill the remaining (whole) subtrees */
4638 switch (offsets[0]) {
4640 nr = i_data[EXT4_IND_BLOCK];
4642 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4643 i_data[EXT4_IND_BLOCK] = 0;
4645 case EXT4_IND_BLOCK:
4646 nr = i_data[EXT4_DIND_BLOCK];
4648 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4649 i_data[EXT4_DIND_BLOCK] = 0;
4651 case EXT4_DIND_BLOCK:
4652 nr = i_data[EXT4_TIND_BLOCK];
4654 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4655 i_data[EXT4_TIND_BLOCK] = 0;
4657 case EXT4_TIND_BLOCK:
4662 up_write(&ei->i_data_sem);
4663 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4664 ext4_mark_inode_dirty(handle, inode);
4667 * In a multi-transaction truncate, we only make the final transaction
4671 ext4_handle_sync(handle);
4674 * If this was a simple ftruncate(), and the file will remain alive
4675 * then we need to clear up the orphan record which we created above.
4676 * However, if this was a real unlink then we were called by
4677 * ext4_delete_inode(), and we allow that function to clean up the
4678 * orphan info for us.
4681 ext4_orphan_del(handle, inode);
4683 ext4_journal_stop(handle);
4684 trace_ext4_truncate_exit(inode);
4688 * ext4_get_inode_loc returns with an extra refcount against the inode's
4689 * underlying buffer_head on success. If 'in_mem' is true, we have all
4690 * data in memory that is needed to recreate the on-disk version of this
4693 static int __ext4_get_inode_loc(struct inode *inode,
4694 struct ext4_iloc *iloc, int in_mem)
4696 struct ext4_group_desc *gdp;
4697 struct buffer_head *bh;
4698 struct super_block *sb = inode->i_sb;
4700 int inodes_per_block, inode_offset;
4703 if (!ext4_valid_inum(sb, inode->i_ino))
4706 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4707 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4712 * Figure out the offset within the block group inode table
4714 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4715 inode_offset = ((inode->i_ino - 1) %
4716 EXT4_INODES_PER_GROUP(sb));
4717 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4718 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4720 bh = sb_getblk(sb, block);
4722 EXT4_ERROR_INODE_BLOCK(inode, block,
4723 "unable to read itable block");
4726 if (!buffer_uptodate(bh)) {
4730 * If the buffer has the write error flag, we have failed
4731 * to write out another inode in the same block. In this
4732 * case, we don't have to read the block because we may
4733 * read the old inode data successfully.
4735 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4736 set_buffer_uptodate(bh);
4738 if (buffer_uptodate(bh)) {
4739 /* someone brought it uptodate while we waited */
4745 * If we have all information of the inode in memory and this
4746 * is the only valid inode in the block, we need not read the
4750 struct buffer_head *bitmap_bh;
4753 start = inode_offset & ~(inodes_per_block - 1);
4755 /* Is the inode bitmap in cache? */
4756 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4761 * If the inode bitmap isn't in cache then the
4762 * optimisation may end up performing two reads instead
4763 * of one, so skip it.
4765 if (!buffer_uptodate(bitmap_bh)) {
4769 for (i = start; i < start + inodes_per_block; i++) {
4770 if (i == inode_offset)
4772 if (ext4_test_bit(i, bitmap_bh->b_data))
4776 if (i == start + inodes_per_block) {
4777 /* all other inodes are free, so skip I/O */
4778 memset(bh->b_data, 0, bh->b_size);
4779 set_buffer_uptodate(bh);
4787 * If we need to do any I/O, try to pre-readahead extra
4788 * blocks from the inode table.
4790 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4791 ext4_fsblk_t b, end, table;
4794 table = ext4_inode_table(sb, gdp);
4795 /* s_inode_readahead_blks is always a power of 2 */
4796 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4799 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4800 num = EXT4_INODES_PER_GROUP(sb);
4801 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4802 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4803 num -= ext4_itable_unused_count(sb, gdp);
4804 table += num / inodes_per_block;
4808 sb_breadahead(sb, b++);
4812 * There are other valid inodes in the buffer, this inode
4813 * has in-inode xattrs, or we don't have this inode in memory.
4814 * Read the block from disk.
4816 trace_ext4_load_inode(inode);
4818 bh->b_end_io = end_buffer_read_sync;
4819 submit_bh(READ_META, bh);
4821 if (!buffer_uptodate(bh)) {
4822 EXT4_ERROR_INODE_BLOCK(inode, block,
4823 "unable to read itable block");
4833 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4835 /* We have all inode data except xattrs in memory here. */
4836 return __ext4_get_inode_loc(inode, iloc,
4837 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4840 void ext4_set_inode_flags(struct inode *inode)
4842 unsigned int flags = EXT4_I(inode)->i_flags;
4844 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4845 if (flags & EXT4_SYNC_FL)
4846 inode->i_flags |= S_SYNC;
4847 if (flags & EXT4_APPEND_FL)
4848 inode->i_flags |= S_APPEND;
4849 if (flags & EXT4_IMMUTABLE_FL)
4850 inode->i_flags |= S_IMMUTABLE;
4851 if (flags & EXT4_NOATIME_FL)
4852 inode->i_flags |= S_NOATIME;
4853 if (flags & EXT4_DIRSYNC_FL)
4854 inode->i_flags |= S_DIRSYNC;
4857 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4858 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4860 unsigned int vfs_fl;
4861 unsigned long old_fl, new_fl;
4864 vfs_fl = ei->vfs_inode.i_flags;
4865 old_fl = ei->i_flags;
4866 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4867 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4869 if (vfs_fl & S_SYNC)
4870 new_fl |= EXT4_SYNC_FL;
4871 if (vfs_fl & S_APPEND)
4872 new_fl |= EXT4_APPEND_FL;
4873 if (vfs_fl & S_IMMUTABLE)
4874 new_fl |= EXT4_IMMUTABLE_FL;
4875 if (vfs_fl & S_NOATIME)
4876 new_fl |= EXT4_NOATIME_FL;
4877 if (vfs_fl & S_DIRSYNC)
4878 new_fl |= EXT4_DIRSYNC_FL;
4879 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4882 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4883 struct ext4_inode_info *ei)
4886 struct inode *inode = &(ei->vfs_inode);
4887 struct super_block *sb = inode->i_sb;
4889 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4890 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4891 /* we are using combined 48 bit field */
4892 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4893 le32_to_cpu(raw_inode->i_blocks_lo);
4894 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4895 /* i_blocks represent file system block size */
4896 return i_blocks << (inode->i_blkbits - 9);
4901 return le32_to_cpu(raw_inode->i_blocks_lo);
4905 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4907 struct ext4_iloc iloc;
4908 struct ext4_inode *raw_inode;
4909 struct ext4_inode_info *ei;
4910 struct inode *inode;
4911 journal_t *journal = EXT4_SB(sb)->s_journal;
4915 inode = iget_locked(sb, ino);
4917 return ERR_PTR(-ENOMEM);
4918 if (!(inode->i_state & I_NEW))
4924 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4927 raw_inode = ext4_raw_inode(&iloc);
4928 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4929 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4930 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4931 if (!(test_opt(inode->i_sb, NO_UID32))) {
4932 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4933 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4935 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4937 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4938 ei->i_dir_start_lookup = 0;
4939 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4940 /* We now have enough fields to check if the inode was active or not.
4941 * This is needed because nfsd might try to access dead inodes
4942 * the test is that same one that e2fsck uses
4943 * NeilBrown 1999oct15
4945 if (inode->i_nlink == 0) {
4946 if (inode->i_mode == 0 ||
4947 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4948 /* this inode is deleted */
4952 /* The only unlinked inodes we let through here have
4953 * valid i_mode and are being read by the orphan
4954 * recovery code: that's fine, we're about to complete
4955 * the process of deleting those. */
4957 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4958 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4959 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4960 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4962 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4963 inode->i_size = ext4_isize(raw_inode);
4964 ei->i_disksize = inode->i_size;
4966 ei->i_reserved_quota = 0;
4968 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4969 ei->i_block_group = iloc.block_group;
4970 ei->i_last_alloc_group = ~0;
4972 * NOTE! The in-memory inode i_data array is in little-endian order
4973 * even on big-endian machines: we do NOT byteswap the block numbers!
4975 for (block = 0; block < EXT4_N_BLOCKS; block++)
4976 ei->i_data[block] = raw_inode->i_block[block];
4977 INIT_LIST_HEAD(&ei->i_orphan);
4980 * Set transaction id's of transactions that have to be committed
4981 * to finish f[data]sync. We set them to currently running transaction
4982 * as we cannot be sure that the inode or some of its metadata isn't
4983 * part of the transaction - the inode could have been reclaimed and
4984 * now it is reread from disk.
4987 transaction_t *transaction;
4990 read_lock(&journal->j_state_lock);
4991 if (journal->j_running_transaction)
4992 transaction = journal->j_running_transaction;
4994 transaction = journal->j_committing_transaction;
4996 tid = transaction->t_tid;
4998 tid = journal->j_commit_sequence;
4999 read_unlock(&journal->j_state_lock);
5000 ei->i_sync_tid = tid;
5001 ei->i_datasync_tid = tid;
5004 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5005 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
5006 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
5007 EXT4_INODE_SIZE(inode->i_sb)) {
5011 if (ei->i_extra_isize == 0) {
5012 /* The extra space is currently unused. Use it. */
5013 ei->i_extra_isize = sizeof(struct ext4_inode) -
5014 EXT4_GOOD_OLD_INODE_SIZE;
5016 __le32 *magic = (void *)raw_inode +
5017 EXT4_GOOD_OLD_INODE_SIZE +
5019 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
5020 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
5023 ei->i_extra_isize = 0;
5025 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
5026 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
5027 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
5028 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5030 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
5031 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5032 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5034 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5038 if (ei->i_file_acl &&
5039 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
5040 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
5044 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5045 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5046 (S_ISLNK(inode->i_mode) &&
5047 !ext4_inode_is_fast_symlink(inode)))
5048 /* Validate extent which is part of inode */
5049 ret = ext4_ext_check_inode(inode);
5050 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5051 (S_ISLNK(inode->i_mode) &&
5052 !ext4_inode_is_fast_symlink(inode))) {
5053 /* Validate block references which are part of inode */
5054 ret = ext4_check_inode_blockref(inode);
5059 if (S_ISREG(inode->i_mode)) {
5060 inode->i_op = &ext4_file_inode_operations;
5061 inode->i_fop = &ext4_file_operations;
5062 ext4_set_aops(inode);
5063 } else if (S_ISDIR(inode->i_mode)) {
5064 inode->i_op = &ext4_dir_inode_operations;
5065 inode->i_fop = &ext4_dir_operations;
5066 } else if (S_ISLNK(inode->i_mode)) {
5067 if (ext4_inode_is_fast_symlink(inode)) {
5068 inode->i_op = &ext4_fast_symlink_inode_operations;
5069 nd_terminate_link(ei->i_data, inode->i_size,
5070 sizeof(ei->i_data) - 1);
5072 inode->i_op = &ext4_symlink_inode_operations;
5073 ext4_set_aops(inode);
5075 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5076 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5077 inode->i_op = &ext4_special_inode_operations;
5078 if (raw_inode->i_block[0])
5079 init_special_inode(inode, inode->i_mode,
5080 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5082 init_special_inode(inode, inode->i_mode,
5083 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5086 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
5090 ext4_set_inode_flags(inode);
5091 unlock_new_inode(inode);
5097 return ERR_PTR(ret);
5100 static int ext4_inode_blocks_set(handle_t *handle,
5101 struct ext4_inode *raw_inode,
5102 struct ext4_inode_info *ei)
5104 struct inode *inode = &(ei->vfs_inode);
5105 u64 i_blocks = inode->i_blocks;
5106 struct super_block *sb = inode->i_sb;
5108 if (i_blocks <= ~0U) {
5110 * i_blocks can be represnted in a 32 bit variable
5111 * as multiple of 512 bytes
5113 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5114 raw_inode->i_blocks_high = 0;
5115 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5118 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
5121 if (i_blocks <= 0xffffffffffffULL) {
5123 * i_blocks can be represented in a 48 bit variable
5124 * as multiple of 512 bytes
5126 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5127 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5128 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5130 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5131 /* i_block is stored in file system block size */
5132 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5133 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5134 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5140 * Post the struct inode info into an on-disk inode location in the
5141 * buffer-cache. This gobbles the caller's reference to the
5142 * buffer_head in the inode location struct.
5144 * The caller must have write access to iloc->bh.
5146 static int ext4_do_update_inode(handle_t *handle,
5147 struct inode *inode,
5148 struct ext4_iloc *iloc)
5150 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5151 struct ext4_inode_info *ei = EXT4_I(inode);
5152 struct buffer_head *bh = iloc->bh;
5153 int err = 0, rc, block;
5155 /* For fields not not tracking in the in-memory inode,
5156 * initialise them to zero for new inodes. */
5157 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5158 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5160 ext4_get_inode_flags(ei);
5161 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5162 if (!(test_opt(inode->i_sb, NO_UID32))) {
5163 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
5164 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
5166 * Fix up interoperability with old kernels. Otherwise, old inodes get
5167 * re-used with the upper 16 bits of the uid/gid intact
5170 raw_inode->i_uid_high =
5171 cpu_to_le16(high_16_bits(inode->i_uid));
5172 raw_inode->i_gid_high =
5173 cpu_to_le16(high_16_bits(inode->i_gid));
5175 raw_inode->i_uid_high = 0;
5176 raw_inode->i_gid_high = 0;
5179 raw_inode->i_uid_low =
5180 cpu_to_le16(fs_high2lowuid(inode->i_uid));
5181 raw_inode->i_gid_low =
5182 cpu_to_le16(fs_high2lowgid(inode->i_gid));
5183 raw_inode->i_uid_high = 0;
5184 raw_inode->i_gid_high = 0;
5186 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5188 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5189 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5190 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5191 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5193 if (ext4_inode_blocks_set(handle, raw_inode, ei))
5195 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5196 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5197 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
5198 cpu_to_le32(EXT4_OS_HURD))
5199 raw_inode->i_file_acl_high =
5200 cpu_to_le16(ei->i_file_acl >> 32);
5201 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5202 ext4_isize_set(raw_inode, ei->i_disksize);
5203 if (ei->i_disksize > 0x7fffffffULL) {
5204 struct super_block *sb = inode->i_sb;
5205 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
5206 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
5207 EXT4_SB(sb)->s_es->s_rev_level ==
5208 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
5209 /* If this is the first large file
5210 * created, add a flag to the superblock.
5212 err = ext4_journal_get_write_access(handle,
5213 EXT4_SB(sb)->s_sbh);
5216 ext4_update_dynamic_rev(sb);
5217 EXT4_SET_RO_COMPAT_FEATURE(sb,
5218 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
5220 ext4_handle_sync(handle);
5221 err = ext4_handle_dirty_metadata(handle, NULL,
5222 EXT4_SB(sb)->s_sbh);
5225 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5226 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5227 if (old_valid_dev(inode->i_rdev)) {
5228 raw_inode->i_block[0] =
5229 cpu_to_le32(old_encode_dev(inode->i_rdev));
5230 raw_inode->i_block[1] = 0;
5232 raw_inode->i_block[0] = 0;
5233 raw_inode->i_block[1] =
5234 cpu_to_le32(new_encode_dev(inode->i_rdev));
5235 raw_inode->i_block[2] = 0;
5238 for (block = 0; block < EXT4_N_BLOCKS; block++)
5239 raw_inode->i_block[block] = ei->i_data[block];
5241 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5242 if (ei->i_extra_isize) {
5243 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5244 raw_inode->i_version_hi =
5245 cpu_to_le32(inode->i_version >> 32);
5246 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
5249 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5250 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5253 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5255 ext4_update_inode_fsync_trans(handle, inode, 0);
5258 ext4_std_error(inode->i_sb, err);
5263 * ext4_write_inode()
5265 * We are called from a few places:
5267 * - Within generic_file_write() for O_SYNC files.
5268 * Here, there will be no transaction running. We wait for any running
5269 * trasnaction to commit.
5271 * - Within sys_sync(), kupdate and such.
5272 * We wait on commit, if tol to.
5274 * - Within prune_icache() (PF_MEMALLOC == true)
5275 * Here we simply return. We can't afford to block kswapd on the
5278 * In all cases it is actually safe for us to return without doing anything,
5279 * because the inode has been copied into a raw inode buffer in
5280 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
5283 * Note that we are absolutely dependent upon all inode dirtiers doing the
5284 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5285 * which we are interested.
5287 * It would be a bug for them to not do this. The code:
5289 * mark_inode_dirty(inode)
5291 * inode->i_size = expr;
5293 * is in error because a kswapd-driven write_inode() could occur while
5294 * `stuff()' is running, and the new i_size will be lost. Plus the inode
5295 * will no longer be on the superblock's dirty inode list.
5297 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5301 if (current->flags & PF_MEMALLOC)
5304 if (EXT4_SB(inode->i_sb)->s_journal) {
5305 if (ext4_journal_current_handle()) {
5306 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5311 if (wbc->sync_mode != WB_SYNC_ALL)
5314 err = ext4_force_commit(inode->i_sb);
5316 struct ext4_iloc iloc;
5318 err = __ext4_get_inode_loc(inode, &iloc, 0);
5321 if (wbc->sync_mode == WB_SYNC_ALL)
5322 sync_dirty_buffer(iloc.bh);
5323 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5324 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5325 "IO error syncing inode");
5336 * Called from notify_change.
5338 * We want to trap VFS attempts to truncate the file as soon as
5339 * possible. In particular, we want to make sure that when the VFS
5340 * shrinks i_size, we put the inode on the orphan list and modify
5341 * i_disksize immediately, so that during the subsequent flushing of
5342 * dirty pages and freeing of disk blocks, we can guarantee that any
5343 * commit will leave the blocks being flushed in an unused state on
5344 * disk. (On recovery, the inode will get truncated and the blocks will
5345 * be freed, so we have a strong guarantee that no future commit will
5346 * leave these blocks visible to the user.)
5348 * Another thing we have to assure is that if we are in ordered mode
5349 * and inode is still attached to the committing transaction, we must
5350 * we start writeout of all the dirty pages which are being truncated.
5351 * This way we are sure that all the data written in the previous
5352 * transaction are already on disk (truncate waits for pages under
5355 * Called with inode->i_mutex down.
5357 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5359 struct inode *inode = dentry->d_inode;
5362 const unsigned int ia_valid = attr->ia_valid;
5364 error = inode_change_ok(inode, attr);
5368 if (is_quota_modification(inode, attr))
5369 dquot_initialize(inode);
5370 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
5371 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
5374 /* (user+group)*(old+new) structure, inode write (sb,
5375 * inode block, ? - but truncate inode update has it) */
5376 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
5377 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
5378 if (IS_ERR(handle)) {
5379 error = PTR_ERR(handle);
5382 error = dquot_transfer(inode, attr);
5384 ext4_journal_stop(handle);
5387 /* Update corresponding info in inode so that everything is in
5388 * one transaction */
5389 if (attr->ia_valid & ATTR_UID)
5390 inode->i_uid = attr->ia_uid;
5391 if (attr->ia_valid & ATTR_GID)
5392 inode->i_gid = attr->ia_gid;
5393 error = ext4_mark_inode_dirty(handle, inode);
5394 ext4_journal_stop(handle);
5397 if (attr->ia_valid & ATTR_SIZE) {
5398 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5399 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5401 if (attr->ia_size > sbi->s_bitmap_maxbytes)
5406 if (S_ISREG(inode->i_mode) &&
5407 attr->ia_valid & ATTR_SIZE &&
5408 (attr->ia_size < inode->i_size)) {
5411 handle = ext4_journal_start(inode, 3);
5412 if (IS_ERR(handle)) {
5413 error = PTR_ERR(handle);
5416 if (ext4_handle_valid(handle)) {
5417 error = ext4_orphan_add(handle, inode);
5420 EXT4_I(inode)->i_disksize = attr->ia_size;
5421 rc = ext4_mark_inode_dirty(handle, inode);
5424 ext4_journal_stop(handle);
5426 if (ext4_should_order_data(inode)) {
5427 error = ext4_begin_ordered_truncate(inode,
5430 /* Do as much error cleanup as possible */
5431 handle = ext4_journal_start(inode, 3);
5432 if (IS_ERR(handle)) {
5433 ext4_orphan_del(NULL, inode);
5436 ext4_orphan_del(handle, inode);
5438 ext4_journal_stop(handle);
5444 if (attr->ia_valid & ATTR_SIZE) {
5445 if (attr->ia_size != i_size_read(inode)) {
5446 truncate_setsize(inode, attr->ia_size);
5447 ext4_truncate(inode);
5448 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
5449 ext4_truncate(inode);
5453 setattr_copy(inode, attr);
5454 mark_inode_dirty(inode);
5458 * If the call to ext4_truncate failed to get a transaction handle at
5459 * all, we need to clean up the in-core orphan list manually.
5461 if (orphan && inode->i_nlink)
5462 ext4_orphan_del(NULL, inode);
5464 if (!rc && (ia_valid & ATTR_MODE))
5465 rc = ext4_acl_chmod(inode);
5468 ext4_std_error(inode->i_sb, error);
5474 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
5477 struct inode *inode;
5478 unsigned long delalloc_blocks;
5480 inode = dentry->d_inode;
5481 generic_fillattr(inode, stat);
5484 * We can't update i_blocks if the block allocation is delayed
5485 * otherwise in the case of system crash before the real block
5486 * allocation is done, we will have i_blocks inconsistent with
5487 * on-disk file blocks.
5488 * We always keep i_blocks updated together with real
5489 * allocation. But to not confuse with user, stat
5490 * will return the blocks that include the delayed allocation
5491 * blocks for this file.
5493 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
5495 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
5499 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
5504 /* if nrblocks are contiguous */
5507 * With N contiguous data blocks, we need at most
5508 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) + 1 indirect blocks,
5509 * 2 dindirect blocks, and 1 tindirect block
5511 return DIV_ROUND_UP(nrblocks,
5512 EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4;
5515 * if nrblocks are not contiguous, worse case, each block touch
5516 * a indirect block, and each indirect block touch a double indirect
5517 * block, plus a triple indirect block
5519 indirects = nrblocks * 2 + 1;
5523 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5525 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5526 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
5527 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
5531 * Account for index blocks, block groups bitmaps and block group
5532 * descriptor blocks if modify datablocks and index blocks
5533 * worse case, the indexs blocks spread over different block groups
5535 * If datablocks are discontiguous, they are possible to spread over
5536 * different block groups too. If they are contiuguous, with flexbg,
5537 * they could still across block group boundary.
5539 * Also account for superblock, inode, quota and xattr blocks
5541 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5543 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5549 * How many index blocks need to touch to modify nrblocks?
5550 * The "Chunk" flag indicating whether the nrblocks is
5551 * physically contiguous on disk
5553 * For Direct IO and fallocate, they calls get_block to allocate
5554 * one single extent at a time, so they could set the "Chunk" flag
5556 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
5561 * Now let's see how many group bitmaps and group descriptors need
5571 if (groups > ngroups)
5573 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5574 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5576 /* bitmaps and block group descriptor blocks */
5577 ret += groups + gdpblocks;
5579 /* Blocks for super block, inode, quota and xattr blocks */
5580 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5586 * Calculate the total number of credits to reserve to fit
5587 * the modification of a single pages into a single transaction,
5588 * which may include multiple chunks of block allocations.
5590 * This could be called via ext4_write_begin()
5592 * We need to consider the worse case, when
5593 * one new block per extent.
5595 int ext4_writepage_trans_blocks(struct inode *inode)
5597 int bpp = ext4_journal_blocks_per_page(inode);
5600 ret = ext4_meta_trans_blocks(inode, bpp, 0);
5602 /* Account for data blocks for journalled mode */
5603 if (ext4_should_journal_data(inode))
5609 * Calculate the journal credits for a chunk of data modification.
5611 * This is called from DIO, fallocate or whoever calling
5612 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5614 * journal buffers for data blocks are not included here, as DIO
5615 * and fallocate do no need to journal data buffers.
5617 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5619 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5623 * The caller must have previously called ext4_reserve_inode_write().
5624 * Give this, we know that the caller already has write access to iloc->bh.
5626 int ext4_mark_iloc_dirty(handle_t *handle,
5627 struct inode *inode, struct ext4_iloc *iloc)
5631 if (test_opt(inode->i_sb, I_VERSION))
5632 inode_inc_iversion(inode);
5634 /* the do_update_inode consumes one bh->b_count */
5637 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5638 err = ext4_do_update_inode(handle, inode, iloc);
5644 * On success, We end up with an outstanding reference count against
5645 * iloc->bh. This _must_ be cleaned up later.
5649 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5650 struct ext4_iloc *iloc)
5654 err = ext4_get_inode_loc(inode, iloc);
5656 BUFFER_TRACE(iloc->bh, "get_write_access");
5657 err = ext4_journal_get_write_access(handle, iloc->bh);
5663 ext4_std_error(inode->i_sb, err);
5668 * Expand an inode by new_extra_isize bytes.
5669 * Returns 0 on success or negative error number on failure.
5671 static int ext4_expand_extra_isize(struct inode *inode,
5672 unsigned int new_extra_isize,
5673 struct ext4_iloc iloc,
5676 struct ext4_inode *raw_inode;
5677 struct ext4_xattr_ibody_header *header;
5679 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5682 raw_inode = ext4_raw_inode(&iloc);
5684 header = IHDR(inode, raw_inode);
5686 /* No extended attributes present */
5687 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5688 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5689 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5691 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5695 /* try to expand with EAs present */
5696 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5701 * What we do here is to mark the in-core inode as clean with respect to inode
5702 * dirtiness (it may still be data-dirty).
5703 * This means that the in-core inode may be reaped by prune_icache
5704 * without having to perform any I/O. This is a very good thing,
5705 * because *any* task may call prune_icache - even ones which
5706 * have a transaction open against a different journal.
5708 * Is this cheating? Not really. Sure, we haven't written the
5709 * inode out, but prune_icache isn't a user-visible syncing function.
5710 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5711 * we start and wait on commits.
5713 * Is this efficient/effective? Well, we're being nice to the system
5714 * by cleaning up our inodes proactively so they can be reaped
5715 * without I/O. But we are potentially leaving up to five seconds'
5716 * worth of inodes floating about which prune_icache wants us to
5717 * write out. One way to fix that would be to get prune_icache()
5718 * to do a write_super() to free up some memory. It has the desired
5721 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5723 struct ext4_iloc iloc;
5724 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5725 static unsigned int mnt_count;
5729 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5730 err = ext4_reserve_inode_write(handle, inode, &iloc);
5731 if (ext4_handle_valid(handle) &&
5732 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5733 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5735 * We need extra buffer credits since we may write into EA block
5736 * with this same handle. If journal_extend fails, then it will
5737 * only result in a minor loss of functionality for that inode.
5738 * If this is felt to be critical, then e2fsck should be run to
5739 * force a large enough s_min_extra_isize.
5741 if ((jbd2_journal_extend(handle,
5742 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5743 ret = ext4_expand_extra_isize(inode,
5744 sbi->s_want_extra_isize,
5747 ext4_set_inode_state(inode,
5748 EXT4_STATE_NO_EXPAND);
5750 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5751 ext4_warning(inode->i_sb,
5752 "Unable to expand inode %lu. Delete"
5753 " some EAs or run e2fsck.",
5756 le16_to_cpu(sbi->s_es->s_mnt_count);
5762 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5767 * ext4_dirty_inode() is called from __mark_inode_dirty()
5769 * We're really interested in the case where a file is being extended.
5770 * i_size has been changed by generic_commit_write() and we thus need
5771 * to include the updated inode in the current transaction.
5773 * Also, dquot_alloc_block() will always dirty the inode when blocks
5774 * are allocated to the file.
5776 * If the inode is marked synchronous, we don't honour that here - doing
5777 * so would cause a commit on atime updates, which we don't bother doing.
5778 * We handle synchronous inodes at the highest possible level.
5780 void ext4_dirty_inode(struct inode *inode, int flags)
5784 handle = ext4_journal_start(inode, 2);
5788 ext4_mark_inode_dirty(handle, inode);
5790 ext4_journal_stop(handle);
5797 * Bind an inode's backing buffer_head into this transaction, to prevent
5798 * it from being flushed to disk early. Unlike
5799 * ext4_reserve_inode_write, this leaves behind no bh reference and
5800 * returns no iloc structure, so the caller needs to repeat the iloc
5801 * lookup to mark the inode dirty later.
5803 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5805 struct ext4_iloc iloc;
5809 err = ext4_get_inode_loc(inode, &iloc);
5811 BUFFER_TRACE(iloc.bh, "get_write_access");
5812 err = jbd2_journal_get_write_access(handle, iloc.bh);
5814 err = ext4_handle_dirty_metadata(handle,
5820 ext4_std_error(inode->i_sb, err);
5825 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5832 * We have to be very careful here: changing a data block's
5833 * journaling status dynamically is dangerous. If we write a
5834 * data block to the journal, change the status and then delete
5835 * that block, we risk forgetting to revoke the old log record
5836 * from the journal and so a subsequent replay can corrupt data.
5837 * So, first we make sure that the journal is empty and that
5838 * nobody is changing anything.
5841 journal = EXT4_JOURNAL(inode);
5844 if (is_journal_aborted(journal))
5847 jbd2_journal_lock_updates(journal);
5848 jbd2_journal_flush(journal);
5851 * OK, there are no updates running now, and all cached data is
5852 * synced to disk. We are now in a completely consistent state
5853 * which doesn't have anything in the journal, and we know that
5854 * no filesystem updates are running, so it is safe to modify
5855 * the inode's in-core data-journaling state flag now.
5859 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5861 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5862 ext4_set_aops(inode);
5864 jbd2_journal_unlock_updates(journal);
5866 /* Finally we can mark the inode as dirty. */
5868 handle = ext4_journal_start(inode, 1);
5870 return PTR_ERR(handle);
5872 err = ext4_mark_inode_dirty(handle, inode);
5873 ext4_handle_sync(handle);
5874 ext4_journal_stop(handle);
5875 ext4_std_error(inode->i_sb, err);
5880 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5882 return !buffer_mapped(bh);
5885 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5887 struct page *page = vmf->page;
5892 struct file *file = vma->vm_file;
5893 struct inode *inode = file->f_path.dentry->d_inode;
5894 struct address_space *mapping = inode->i_mapping;
5897 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5898 * get i_mutex because we are already holding mmap_sem.
5900 down_read(&inode->i_alloc_sem);
5901 size = i_size_read(inode);
5902 if (page->mapping != mapping || size <= page_offset(page)
5903 || !PageUptodate(page)) {
5904 /* page got truncated from under us? */
5910 wait_on_page_writeback(page);
5911 if (PageMappedToDisk(page)) {
5912 up_read(&inode->i_alloc_sem);
5913 return VM_FAULT_LOCKED;
5916 if (page->index == size >> PAGE_CACHE_SHIFT)
5917 len = size & ~PAGE_CACHE_MASK;
5919 len = PAGE_CACHE_SIZE;
5922 * return if we have all the buffers mapped. This avoid
5923 * the need to call write_begin/write_end which does a
5924 * journal_start/journal_stop which can block and take
5927 if (page_has_buffers(page)) {
5928 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5929 ext4_bh_unmapped)) {
5930 up_read(&inode->i_alloc_sem);
5931 return VM_FAULT_LOCKED;
5936 * OK, we need to fill the hole... Do write_begin write_end
5937 * to do block allocation/reservation.We are not holding
5938 * inode.i__mutex here. That allow * parallel write_begin,
5939 * write_end call. lock_page prevent this from happening
5940 * on the same page though
5942 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5943 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5946 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5947 len, len, page, fsdata);
5953 * write_begin/end might have created a dirty page and someone
5954 * could wander in and start the IO. Make sure that hasn't
5958 wait_on_page_writeback(page);
5959 up_read(&inode->i_alloc_sem);
5960 return VM_FAULT_LOCKED;
5963 ret = VM_FAULT_SIGBUS;
5964 up_read(&inode->i_alloc_sem);