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 "ext4_jbd2.h"
43 #include "ext4_extents.h"
45 #define MPAGE_DA_EXTENT_TAIL 0x01
47 static inline int ext4_begin_ordered_truncate(struct inode
*inode
,
50 return jbd2_journal_begin_ordered_truncate(&EXT4_I(inode
)->jinode
,
54 static void ext4_invalidatepage(struct page
*page
, unsigned long offset
);
57 * Test whether an inode is a fast symlink.
59 static int ext4_inode_is_fast_symlink(struct inode
*inode
)
61 int ea_blocks
= EXT4_I(inode
)->i_file_acl
?
62 (inode
->i_sb
->s_blocksize
>> 9) : 0;
64 return (S_ISLNK(inode
->i_mode
) && inode
->i_blocks
- ea_blocks
== 0);
68 * The ext4 forget function must perform a revoke if we are freeing data
69 * which has been journaled. Metadata (eg. indirect blocks) must be
70 * revoked in all cases.
72 * "bh" may be NULL: a metadata block may have been freed from memory
73 * but there may still be a record of it in the journal, and that record
74 * still needs to be revoked.
76 * If the handle isn't valid we're not journaling so there's nothing to do.
78 int ext4_forget(handle_t
*handle
, int is_metadata
, struct inode
*inode
,
79 struct buffer_head
*bh
, ext4_fsblk_t blocknr
)
83 if (!ext4_handle_valid(handle
))
88 BUFFER_TRACE(bh
, "enter");
90 jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
92 bh
, is_metadata
, inode
->i_mode
,
93 test_opt(inode
->i_sb
, DATA_FLAGS
));
95 /* Never use the revoke function if we are doing full data
96 * journaling: there is no need to, and a V1 superblock won't
97 * support it. Otherwise, only skip the revoke on un-journaled
100 if (test_opt(inode
->i_sb
, DATA_FLAGS
) == EXT4_MOUNT_JOURNAL_DATA
||
101 (!is_metadata
&& !ext4_should_journal_data(inode
))) {
103 BUFFER_TRACE(bh
, "call jbd2_journal_forget");
104 return ext4_journal_forget(handle
, bh
);
110 * data!=journal && (is_metadata || should_journal_data(inode))
112 BUFFER_TRACE(bh
, "call ext4_journal_revoke");
113 err
= ext4_journal_revoke(handle
, blocknr
, bh
);
115 ext4_abort(inode
->i_sb
, __func__
,
116 "error %d when attempting revoke", err
);
117 BUFFER_TRACE(bh
, "exit");
122 * Work out how many blocks we need to proceed with the next chunk of a
123 * truncate transaction.
125 static unsigned long blocks_for_truncate(struct inode
*inode
)
129 needed
= inode
->i_blocks
>> (inode
->i_sb
->s_blocksize_bits
- 9);
131 /* Give ourselves just enough room to cope with inodes in which
132 * i_blocks is corrupt: we've seen disk corruptions in the past
133 * which resulted in random data in an inode which looked enough
134 * like a regular file for ext4 to try to delete it. Things
135 * will go a bit crazy if that happens, but at least we should
136 * try not to panic the whole kernel. */
140 /* But we need to bound the transaction so we don't overflow the
142 if (needed
> EXT4_MAX_TRANS_DATA
)
143 needed
= EXT4_MAX_TRANS_DATA
;
145 return EXT4_DATA_TRANS_BLOCKS(inode
->i_sb
) + needed
;
149 * Truncate transactions can be complex and absolutely huge. So we need to
150 * be able to restart the transaction at a conventient checkpoint to make
151 * sure we don't overflow the journal.
153 * start_transaction gets us a new handle for a truncate transaction,
154 * and extend_transaction tries to extend the existing one a bit. If
155 * extend fails, we need to propagate the failure up and restart the
156 * transaction in the top-level truncate loop. --sct
158 static handle_t
*start_transaction(struct inode
*inode
)
162 result
= ext4_journal_start(inode
, blocks_for_truncate(inode
));
166 ext4_std_error(inode
->i_sb
, PTR_ERR(result
));
171 * Try to extend this transaction for the purposes of truncation.
173 * Returns 0 if we managed to create more room. If we can't create more
174 * room, and the transaction must be restarted we return 1.
176 static int try_to_extend_transaction(handle_t
*handle
, struct inode
*inode
)
178 if (!ext4_handle_valid(handle
))
180 if (ext4_handle_has_enough_credits(handle
, EXT4_RESERVE_TRANS_BLOCKS
+1))
182 if (!ext4_journal_extend(handle
, blocks_for_truncate(inode
)))
188 * Restart the transaction associated with *handle. This does a commit,
189 * so before we call here everything must be consistently dirtied against
192 static int ext4_journal_test_restart(handle_t
*handle
, struct inode
*inode
)
194 BUG_ON(EXT4_JOURNAL(inode
) == NULL
);
195 jbd_debug(2, "restarting handle %p\n", handle
);
196 return ext4_journal_restart(handle
, blocks_for_truncate(inode
));
200 * Called at the last iput() if i_nlink is zero.
202 void ext4_delete_inode(struct inode
*inode
)
207 if (ext4_should_order_data(inode
))
208 ext4_begin_ordered_truncate(inode
, 0);
209 truncate_inode_pages(&inode
->i_data
, 0);
211 if (is_bad_inode(inode
))
214 handle
= ext4_journal_start(inode
, blocks_for_truncate(inode
)+3);
215 if (IS_ERR(handle
)) {
216 ext4_std_error(inode
->i_sb
, PTR_ERR(handle
));
218 * If we're going to skip the normal cleanup, we still need to
219 * make sure that the in-core orphan linked list is properly
222 ext4_orphan_del(NULL
, inode
);
227 ext4_handle_sync(handle
);
229 err
= ext4_mark_inode_dirty(handle
, inode
);
231 ext4_warning(inode
->i_sb
, __func__
,
232 "couldn't mark inode dirty (err %d)", err
);
236 ext4_truncate(inode
);
239 * ext4_ext_truncate() doesn't reserve any slop when it
240 * restarts journal transactions; therefore there may not be
241 * enough credits left in the handle to remove the inode from
242 * the orphan list and set the dtime field.
244 if (!ext4_handle_has_enough_credits(handle
, 3)) {
245 err
= ext4_journal_extend(handle
, 3);
247 err
= ext4_journal_restart(handle
, 3);
249 ext4_warning(inode
->i_sb
, __func__
,
250 "couldn't extend journal (err %d)", err
);
252 ext4_journal_stop(handle
);
258 * Kill off the orphan record which ext4_truncate created.
259 * AKPM: I think this can be inside the above `if'.
260 * Note that ext4_orphan_del() has to be able to cope with the
261 * deletion of a non-existent orphan - this is because we don't
262 * know if ext4_truncate() actually created an orphan record.
263 * (Well, we could do this if we need to, but heck - it works)
265 ext4_orphan_del(handle
, inode
);
266 EXT4_I(inode
)->i_dtime
= get_seconds();
269 * One subtle ordering requirement: if anything has gone wrong
270 * (transaction abort, IO errors, whatever), then we can still
271 * do these next steps (the fs will already have been marked as
272 * having errors), but we can't free the inode if the mark_dirty
275 if (ext4_mark_inode_dirty(handle
, inode
))
276 /* If that failed, just do the required in-core inode clear. */
279 ext4_free_inode(handle
, inode
);
280 ext4_journal_stop(handle
);
283 clear_inode(inode
); /* We must guarantee clearing of inode... */
289 struct buffer_head
*bh
;
292 static inline void add_chain(Indirect
*p
, struct buffer_head
*bh
, __le32
*v
)
294 p
->key
= *(p
->p
= v
);
299 * ext4_block_to_path - parse the block number into array of offsets
300 * @inode: inode in question (we are only interested in its superblock)
301 * @i_block: block number to be parsed
302 * @offsets: array to store the offsets in
303 * @boundary: set this non-zero if the referred-to block is likely to be
304 * followed (on disk) by an indirect block.
306 * To store the locations of file's data ext4 uses a data structure common
307 * for UNIX filesystems - tree of pointers anchored in the inode, with
308 * data blocks at leaves and indirect blocks in intermediate nodes.
309 * This function translates the block number into path in that tree -
310 * return value is the path length and @offsets[n] is the offset of
311 * pointer to (n+1)th node in the nth one. If @block is out of range
312 * (negative or too large) warning is printed and zero returned.
314 * Note: function doesn't find node addresses, so no IO is needed. All
315 * we need to know is the capacity of indirect blocks (taken from the
320 * Portability note: the last comparison (check that we fit into triple
321 * indirect block) is spelled differently, because otherwise on an
322 * architecture with 32-bit longs and 8Kb pages we might get into trouble
323 * if our filesystem had 8Kb blocks. We might use long long, but that would
324 * kill us on x86. Oh, well, at least the sign propagation does not matter -
325 * i_block would have to be negative in the very beginning, so we would not
329 static int ext4_block_to_path(struct inode
*inode
,
331 ext4_lblk_t offsets
[4], int *boundary
)
333 int ptrs
= EXT4_ADDR_PER_BLOCK(inode
->i_sb
);
334 int ptrs_bits
= EXT4_ADDR_PER_BLOCK_BITS(inode
->i_sb
);
335 const long direct_blocks
= EXT4_NDIR_BLOCKS
,
336 indirect_blocks
= ptrs
,
337 double_blocks
= (1 << (ptrs_bits
* 2));
342 ext4_warning(inode
->i_sb
, "ext4_block_to_path", "block < 0");
343 } else if (i_block
< direct_blocks
) {
344 offsets
[n
++] = i_block
;
345 final
= direct_blocks
;
346 } else if ((i_block
-= direct_blocks
) < indirect_blocks
) {
347 offsets
[n
++] = EXT4_IND_BLOCK
;
348 offsets
[n
++] = i_block
;
350 } else if ((i_block
-= indirect_blocks
) < double_blocks
) {
351 offsets
[n
++] = EXT4_DIND_BLOCK
;
352 offsets
[n
++] = i_block
>> ptrs_bits
;
353 offsets
[n
++] = i_block
& (ptrs
- 1);
355 } else if (((i_block
-= double_blocks
) >> (ptrs_bits
* 2)) < ptrs
) {
356 offsets
[n
++] = EXT4_TIND_BLOCK
;
357 offsets
[n
++] = i_block
>> (ptrs_bits
* 2);
358 offsets
[n
++] = (i_block
>> ptrs_bits
) & (ptrs
- 1);
359 offsets
[n
++] = i_block
& (ptrs
- 1);
362 ext4_warning(inode
->i_sb
, "ext4_block_to_path",
363 "block %lu > max in inode %lu",
364 i_block
+ direct_blocks
+
365 indirect_blocks
+ double_blocks
, inode
->i_ino
);
368 *boundary
= final
- 1 - (i_block
& (ptrs
- 1));
373 * ext4_get_branch - read the chain of indirect blocks leading to data
374 * @inode: inode in question
375 * @depth: depth of the chain (1 - direct pointer, etc.)
376 * @offsets: offsets of pointers in inode/indirect blocks
377 * @chain: place to store the result
378 * @err: here we store the error value
380 * Function fills the array of triples <key, p, bh> and returns %NULL
381 * if everything went OK or the pointer to the last filled triple
382 * (incomplete one) otherwise. Upon the return chain[i].key contains
383 * the number of (i+1)-th block in the chain (as it is stored in memory,
384 * i.e. little-endian 32-bit), chain[i].p contains the address of that
385 * number (it points into struct inode for i==0 and into the bh->b_data
386 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
387 * block for i>0 and NULL for i==0. In other words, it holds the block
388 * numbers of the chain, addresses they were taken from (and where we can
389 * verify that chain did not change) and buffer_heads hosting these
392 * Function stops when it stumbles upon zero pointer (absent block)
393 * (pointer to last triple returned, *@err == 0)
394 * or when it gets an IO error reading an indirect block
395 * (ditto, *@err == -EIO)
396 * or when it reads all @depth-1 indirect blocks successfully and finds
397 * the whole chain, all way to the data (returns %NULL, *err == 0).
399 * Need to be called with
400 * down_read(&EXT4_I(inode)->i_data_sem)
402 static Indirect
*ext4_get_branch(struct inode
*inode
, int depth
,
403 ext4_lblk_t
*offsets
,
404 Indirect chain
[4], int *err
)
406 struct super_block
*sb
= inode
->i_sb
;
408 struct buffer_head
*bh
;
411 /* i_data is not going away, no lock needed */
412 add_chain(chain
, NULL
, EXT4_I(inode
)->i_data
+ *offsets
);
416 bh
= sb_bread(sb
, le32_to_cpu(p
->key
));
419 add_chain(++p
, bh
, (__le32
*)bh
->b_data
+ *++offsets
);
433 * ext4_find_near - find a place for allocation with sufficient locality
435 * @ind: descriptor of indirect block.
437 * This function returns the preferred place for block allocation.
438 * It is used when heuristic for sequential allocation fails.
440 * + if there is a block to the left of our position - allocate near it.
441 * + if pointer will live in indirect block - allocate near that block.
442 * + if pointer will live in inode - allocate in the same
445 * In the latter case we colour the starting block by the callers PID to
446 * prevent it from clashing with concurrent allocations for a different inode
447 * in the same block group. The PID is used here so that functionally related
448 * files will be close-by on-disk.
450 * Caller must make sure that @ind is valid and will stay that way.
452 static ext4_fsblk_t
ext4_find_near(struct inode
*inode
, Indirect
*ind
)
454 struct ext4_inode_info
*ei
= EXT4_I(inode
);
455 __le32
*start
= ind
->bh
? (__le32
*) ind
->bh
->b_data
: ei
->i_data
;
457 ext4_fsblk_t bg_start
;
458 ext4_fsblk_t last_block
;
459 ext4_grpblk_t colour
;
461 /* Try to find previous block */
462 for (p
= ind
->p
- 1; p
>= start
; p
--) {
464 return le32_to_cpu(*p
);
467 /* No such thing, so let's try location of indirect block */
469 return ind
->bh
->b_blocknr
;
472 * It is going to be referred to from the inode itself? OK, just put it
473 * into the same cylinder group then.
475 bg_start
= ext4_group_first_block_no(inode
->i_sb
, ei
->i_block_group
);
476 last_block
= ext4_blocks_count(EXT4_SB(inode
->i_sb
)->s_es
) - 1;
478 if (bg_start
+ EXT4_BLOCKS_PER_GROUP(inode
->i_sb
) <= last_block
)
479 colour
= (current
->pid
% 16) *
480 (EXT4_BLOCKS_PER_GROUP(inode
->i_sb
) / 16);
482 colour
= (current
->pid
% 16) * ((last_block
- bg_start
) / 16);
483 return bg_start
+ colour
;
487 * ext4_find_goal - find a preferred place for allocation.
489 * @block: block we want
490 * @partial: pointer to the last triple within a chain
492 * Normally this function find the preferred place for block allocation,
495 static ext4_fsblk_t
ext4_find_goal(struct inode
*inode
, ext4_lblk_t block
,
499 * XXX need to get goal block from mballoc's data structures
502 return ext4_find_near(inode
, partial
);
506 * ext4_blks_to_allocate: Look up the block map and count the number
507 * of direct blocks need to be allocated for the given branch.
509 * @branch: chain of indirect blocks
510 * @k: number of blocks need for indirect blocks
511 * @blks: number of data blocks to be mapped.
512 * @blocks_to_boundary: the offset in the indirect block
514 * return the total number of blocks to be allocate, including the
515 * direct and indirect blocks.
517 static int ext4_blks_to_allocate(Indirect
*branch
, int k
, unsigned int blks
,
518 int blocks_to_boundary
)
520 unsigned int count
= 0;
523 * Simple case, [t,d]Indirect block(s) has not allocated yet
524 * then it's clear blocks on that path have not allocated
527 /* right now we don't handle cross boundary allocation */
528 if (blks
< blocks_to_boundary
+ 1)
531 count
+= blocks_to_boundary
+ 1;
536 while (count
< blks
&& count
<= blocks_to_boundary
&&
537 le32_to_cpu(*(branch
[0].p
+ count
)) == 0) {
544 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
545 * @indirect_blks: the number of blocks need to allocate for indirect
548 * @new_blocks: on return it will store the new block numbers for
549 * the indirect blocks(if needed) and the first direct block,
550 * @blks: on return it will store the total number of allocated
553 static int ext4_alloc_blocks(handle_t
*handle
, struct inode
*inode
,
554 ext4_lblk_t iblock
, ext4_fsblk_t goal
,
555 int indirect_blks
, int blks
,
556 ext4_fsblk_t new_blocks
[4], int *err
)
558 struct ext4_allocation_request ar
;
560 unsigned long count
= 0, blk_allocated
= 0;
562 ext4_fsblk_t current_block
= 0;
566 * Here we try to allocate the requested multiple blocks at once,
567 * on a best-effort basis.
568 * To build a branch, we should allocate blocks for
569 * the indirect blocks(if not allocated yet), and at least
570 * the first direct block of this branch. That's the
571 * minimum number of blocks need to allocate(required)
573 /* first we try to allocate the indirect blocks */
574 target
= indirect_blks
;
577 /* allocating blocks for indirect blocks and direct blocks */
578 current_block
= ext4_new_meta_blocks(handle
, inode
,
584 /* allocate blocks for indirect blocks */
585 while (index
< indirect_blks
&& count
) {
586 new_blocks
[index
++] = current_block
++;
591 * save the new block number
592 * for the first direct block
594 new_blocks
[index
] = current_block
;
595 printk(KERN_INFO
"%s returned more blocks than "
596 "requested\n", __func__
);
602 target
= blks
- count
;
603 blk_allocated
= count
;
606 /* Now allocate data blocks */
607 memset(&ar
, 0, sizeof(ar
));
612 if (S_ISREG(inode
->i_mode
))
613 /* enable in-core preallocation only for regular files */
614 ar
.flags
= EXT4_MB_HINT_DATA
;
616 current_block
= ext4_mb_new_blocks(handle
, &ar
, err
);
618 if (*err
&& (target
== blks
)) {
620 * if the allocation failed and we didn't allocate
626 if (target
== blks
) {
628 * save the new block number
629 * for the first direct block
631 new_blocks
[index
] = current_block
;
633 blk_allocated
+= ar
.len
;
636 /* total number of blocks allocated for direct blocks */
641 for (i
= 0; i
< index
; i
++)
642 ext4_free_blocks(handle
, inode
, new_blocks
[i
], 1, 0);
647 * ext4_alloc_branch - allocate and set up a chain of blocks.
649 * @indirect_blks: number of allocated indirect blocks
650 * @blks: number of allocated direct blocks
651 * @offsets: offsets (in the blocks) to store the pointers to next.
652 * @branch: place to store the chain in.
654 * This function allocates blocks, zeroes out all but the last one,
655 * links them into chain and (if we are synchronous) writes them to disk.
656 * In other words, it prepares a branch that can be spliced onto the
657 * inode. It stores the information about that chain in the branch[], in
658 * the same format as ext4_get_branch() would do. We are calling it after
659 * we had read the existing part of chain and partial points to the last
660 * triple of that (one with zero ->key). Upon the exit we have the same
661 * picture as after the successful ext4_get_block(), except that in one
662 * place chain is disconnected - *branch->p is still zero (we did not
663 * set the last link), but branch->key contains the number that should
664 * be placed into *branch->p to fill that gap.
666 * If allocation fails we free all blocks we've allocated (and forget
667 * their buffer_heads) and return the error value the from failed
668 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
669 * as described above and return 0.
671 static int ext4_alloc_branch(handle_t
*handle
, struct inode
*inode
,
672 ext4_lblk_t iblock
, int indirect_blks
,
673 int *blks
, ext4_fsblk_t goal
,
674 ext4_lblk_t
*offsets
, Indirect
*branch
)
676 int blocksize
= inode
->i_sb
->s_blocksize
;
679 struct buffer_head
*bh
;
681 ext4_fsblk_t new_blocks
[4];
682 ext4_fsblk_t current_block
;
684 num
= ext4_alloc_blocks(handle
, inode
, iblock
, goal
, indirect_blks
,
685 *blks
, new_blocks
, &err
);
689 branch
[0].key
= cpu_to_le32(new_blocks
[0]);
691 * metadata blocks and data blocks are allocated.
693 for (n
= 1; n
<= indirect_blks
; n
++) {
695 * Get buffer_head for parent block, zero it out
696 * and set the pointer to new one, then send
699 bh
= sb_getblk(inode
->i_sb
, new_blocks
[n
-1]);
702 BUFFER_TRACE(bh
, "call get_create_access");
703 err
= ext4_journal_get_create_access(handle
, bh
);
710 memset(bh
->b_data
, 0, blocksize
);
711 branch
[n
].p
= (__le32
*) bh
->b_data
+ offsets
[n
];
712 branch
[n
].key
= cpu_to_le32(new_blocks
[n
]);
713 *branch
[n
].p
= branch
[n
].key
;
714 if (n
== indirect_blks
) {
715 current_block
= new_blocks
[n
];
717 * End of chain, update the last new metablock of
718 * the chain to point to the new allocated
719 * data blocks numbers
721 for (i
=1; i
< num
; i
++)
722 *(branch
[n
].p
+ i
) = cpu_to_le32(++current_block
);
724 BUFFER_TRACE(bh
, "marking uptodate");
725 set_buffer_uptodate(bh
);
728 BUFFER_TRACE(bh
, "call ext4_handle_dirty_metadata");
729 err
= ext4_handle_dirty_metadata(handle
, inode
, bh
);
736 /* Allocation failed, free what we already allocated */
737 for (i
= 1; i
<= n
; i
++) {
738 BUFFER_TRACE(branch
[i
].bh
, "call jbd2_journal_forget");
739 ext4_journal_forget(handle
, branch
[i
].bh
);
741 for (i
= 0; i
< indirect_blks
; i
++)
742 ext4_free_blocks(handle
, inode
, new_blocks
[i
], 1, 0);
744 ext4_free_blocks(handle
, inode
, new_blocks
[i
], num
, 0);
750 * ext4_splice_branch - splice the allocated branch onto inode.
752 * @block: (logical) number of block we are adding
753 * @chain: chain of indirect blocks (with a missing link - see
755 * @where: location of missing link
756 * @num: number of indirect blocks we are adding
757 * @blks: number of direct blocks we are adding
759 * This function fills the missing link and does all housekeeping needed in
760 * inode (->i_blocks, etc.). In case of success we end up with the full
761 * chain to new block and return 0.
763 static int ext4_splice_branch(handle_t
*handle
, struct inode
*inode
,
764 ext4_lblk_t block
, Indirect
*where
, int num
, int blks
)
768 ext4_fsblk_t current_block
;
771 * If we're splicing into a [td]indirect block (as opposed to the
772 * inode) then we need to get write access to the [td]indirect block
776 BUFFER_TRACE(where
->bh
, "get_write_access");
777 err
= ext4_journal_get_write_access(handle
, where
->bh
);
783 *where
->p
= where
->key
;
786 * Update the host buffer_head or inode to point to more just allocated
787 * direct blocks blocks
789 if (num
== 0 && blks
> 1) {
790 current_block
= le32_to_cpu(where
->key
) + 1;
791 for (i
= 1; i
< blks
; i
++)
792 *(where
->p
+ i
) = cpu_to_le32(current_block
++);
795 /* We are done with atomic stuff, now do the rest of housekeeping */
797 inode
->i_ctime
= ext4_current_time(inode
);
798 ext4_mark_inode_dirty(handle
, inode
);
800 /* had we spliced it onto indirect block? */
803 * If we spliced it onto an indirect block, we haven't
804 * altered the inode. Note however that if it is being spliced
805 * onto an indirect block at the very end of the file (the
806 * file is growing) then we *will* alter the inode to reflect
807 * the new i_size. But that is not done here - it is done in
808 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
810 jbd_debug(5, "splicing indirect only\n");
811 BUFFER_TRACE(where
->bh
, "call ext4_handle_dirty_metadata");
812 err
= ext4_handle_dirty_metadata(handle
, inode
, where
->bh
);
817 * OK, we spliced it into the inode itself on a direct block.
818 * Inode was dirtied above.
820 jbd_debug(5, "splicing direct\n");
825 for (i
= 1; i
<= num
; i
++) {
826 BUFFER_TRACE(where
[i
].bh
, "call jbd2_journal_forget");
827 ext4_journal_forget(handle
, where
[i
].bh
);
828 ext4_free_blocks(handle
, inode
,
829 le32_to_cpu(where
[i
-1].key
), 1, 0);
831 ext4_free_blocks(handle
, inode
, le32_to_cpu(where
[num
].key
), blks
, 0);
837 * Allocation strategy is simple: if we have to allocate something, we will
838 * have to go the whole way to leaf. So let's do it before attaching anything
839 * to tree, set linkage between the newborn blocks, write them if sync is
840 * required, recheck the path, free and repeat if check fails, otherwise
841 * set the last missing link (that will protect us from any truncate-generated
842 * removals - all blocks on the path are immune now) and possibly force the
843 * write on the parent block.
844 * That has a nice additional property: no special recovery from the failed
845 * allocations is needed - we simply release blocks and do not touch anything
846 * reachable from inode.
848 * `handle' can be NULL if create == 0.
850 * return > 0, # of blocks mapped or allocated.
851 * return = 0, if plain lookup failed.
852 * return < 0, error case.
855 * Need to be called with
856 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
857 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
859 static int ext4_get_blocks_handle(handle_t
*handle
, struct inode
*inode
,
860 ext4_lblk_t iblock
, unsigned int maxblocks
,
861 struct buffer_head
*bh_result
,
862 int create
, int extend_disksize
)
865 ext4_lblk_t offsets
[4];
870 int blocks_to_boundary
= 0;
872 struct ext4_inode_info
*ei
= EXT4_I(inode
);
874 ext4_fsblk_t first_block
= 0;
878 J_ASSERT(!(EXT4_I(inode
)->i_flags
& EXT4_EXTENTS_FL
));
879 J_ASSERT(handle
!= NULL
|| create
== 0);
880 depth
= ext4_block_to_path(inode
, iblock
, offsets
,
881 &blocks_to_boundary
);
886 partial
= ext4_get_branch(inode
, depth
, offsets
, chain
, &err
);
888 /* Simplest case - block found, no allocation needed */
890 first_block
= le32_to_cpu(chain
[depth
- 1].key
);
891 clear_buffer_new(bh_result
);
894 while (count
< maxblocks
&& count
<= blocks_to_boundary
) {
897 blk
= le32_to_cpu(*(chain
[depth
-1].p
+ count
));
899 if (blk
== first_block
+ count
)
907 /* Next simple case - plain lookup or failed read of indirect block */
908 if (!create
|| err
== -EIO
)
912 * Okay, we need to do block allocation.
914 goal
= ext4_find_goal(inode
, iblock
, partial
);
916 /* the number of blocks need to allocate for [d,t]indirect blocks */
917 indirect_blks
= (chain
+ depth
) - partial
- 1;
920 * Next look up the indirect map to count the totoal number of
921 * direct blocks to allocate for this branch.
923 count
= ext4_blks_to_allocate(partial
, indirect_blks
,
924 maxblocks
, blocks_to_boundary
);
926 * Block out ext4_truncate while we alter the tree
928 err
= ext4_alloc_branch(handle
, inode
, iblock
, indirect_blks
,
930 offsets
+ (partial
- chain
), partial
);
933 * The ext4_splice_branch call will free and forget any buffers
934 * on the new chain if there is a failure, but that risks using
935 * up transaction credits, especially for bitmaps where the
936 * credits cannot be returned. Can we handle this somehow? We
937 * may need to return -EAGAIN upwards in the worst case. --sct
940 err
= ext4_splice_branch(handle
, inode
, iblock
,
941 partial
, indirect_blks
, count
);
943 * i_disksize growing is protected by i_data_sem. Don't forget to
944 * protect it if you're about to implement concurrent
945 * ext4_get_block() -bzzz
947 if (!err
&& extend_disksize
) {
948 disksize
= ((loff_t
) iblock
+ count
) << inode
->i_blkbits
;
949 if (disksize
> i_size_read(inode
))
950 disksize
= i_size_read(inode
);
951 if (disksize
> ei
->i_disksize
)
952 ei
->i_disksize
= disksize
;
957 set_buffer_new(bh_result
);
959 map_bh(bh_result
, inode
->i_sb
, le32_to_cpu(chain
[depth
-1].key
));
960 if (count
> blocks_to_boundary
)
961 set_buffer_boundary(bh_result
);
963 /* Clean up and exit */
964 partial
= chain
+ depth
- 1; /* the whole chain */
966 while (partial
> chain
) {
967 BUFFER_TRACE(partial
->bh
, "call brelse");
971 BUFFER_TRACE(bh_result
, "returned");
977 * Calculate the number of metadata blocks need to reserve
978 * to allocate @blocks for non extent file based file
980 static int ext4_indirect_calc_metadata_amount(struct inode
*inode
, int blocks
)
982 int icap
= EXT4_ADDR_PER_BLOCK(inode
->i_sb
);
983 int ind_blks
, dind_blks
, tind_blks
;
985 /* number of new indirect blocks needed */
986 ind_blks
= (blocks
+ icap
- 1) / icap
;
988 dind_blks
= (ind_blks
+ icap
- 1) / icap
;
992 return ind_blks
+ dind_blks
+ tind_blks
;
996 * Calculate the number of metadata blocks need to reserve
997 * to allocate given number of blocks
999 static int ext4_calc_metadata_amount(struct inode
*inode
, int blocks
)
1004 if (EXT4_I(inode
)->i_flags
& EXT4_EXTENTS_FL
)
1005 return ext4_ext_calc_metadata_amount(inode
, blocks
);
1007 return ext4_indirect_calc_metadata_amount(inode
, blocks
);
1010 static void ext4_da_update_reserve_space(struct inode
*inode
, int used
)
1012 struct ext4_sb_info
*sbi
= EXT4_SB(inode
->i_sb
);
1013 int total
, mdb
, mdb_free
;
1015 spin_lock(&EXT4_I(inode
)->i_block_reservation_lock
);
1016 /* recalculate the number of metablocks still need to be reserved */
1017 total
= EXT4_I(inode
)->i_reserved_data_blocks
- used
;
1018 mdb
= ext4_calc_metadata_amount(inode
, total
);
1020 /* figure out how many metablocks to release */
1021 BUG_ON(mdb
> EXT4_I(inode
)->i_reserved_meta_blocks
);
1022 mdb_free
= EXT4_I(inode
)->i_reserved_meta_blocks
- mdb
;
1025 /* Account for allocated meta_blocks */
1026 mdb_free
-= EXT4_I(inode
)->i_allocated_meta_blocks
;
1028 /* update fs dirty blocks counter */
1029 percpu_counter_sub(&sbi
->s_dirtyblocks_counter
, mdb_free
);
1030 EXT4_I(inode
)->i_allocated_meta_blocks
= 0;
1031 EXT4_I(inode
)->i_reserved_meta_blocks
= mdb
;
1034 /* update per-inode reservations */
1035 BUG_ON(used
> EXT4_I(inode
)->i_reserved_data_blocks
);
1036 EXT4_I(inode
)->i_reserved_data_blocks
-= used
;
1038 spin_unlock(&EXT4_I(inode
)->i_block_reservation_lock
);
1042 * The ext4_get_blocks_wrap() function try to look up the requested blocks,
1043 * and returns if the blocks are already mapped.
1045 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1046 * and store the allocated blocks in the result buffer head and mark it
1049 * If file type is extents based, it will call ext4_ext_get_blocks(),
1050 * Otherwise, call with ext4_get_blocks_handle() to handle indirect mapping
1053 * On success, it returns the number of blocks being mapped or allocate.
1054 * if create==0 and the blocks are pre-allocated and uninitialized block,
1055 * the result buffer head is unmapped. If the create ==1, it will make sure
1056 * the buffer head is mapped.
1058 * It returns 0 if plain look up failed (blocks have not been allocated), in
1059 * that casem, buffer head is unmapped
1061 * It returns the error in case of allocation failure.
1063 int ext4_get_blocks_wrap(handle_t
*handle
, struct inode
*inode
, sector_t block
,
1064 unsigned int max_blocks
, struct buffer_head
*bh
,
1065 int create
, int extend_disksize
, int flag
)
1069 clear_buffer_mapped(bh
);
1072 * Try to see if we can get the block without requesting
1073 * for new file system block.
1075 down_read((&EXT4_I(inode
)->i_data_sem
));
1076 if (EXT4_I(inode
)->i_flags
& EXT4_EXTENTS_FL
) {
1077 retval
= ext4_ext_get_blocks(handle
, inode
, block
, max_blocks
,
1080 retval
= ext4_get_blocks_handle(handle
,
1081 inode
, block
, max_blocks
, bh
, 0, 0);
1083 up_read((&EXT4_I(inode
)->i_data_sem
));
1085 /* If it is only a block(s) look up */
1090 * Returns if the blocks have already allocated
1092 * Note that if blocks have been preallocated
1093 * ext4_ext_get_block() returns th create = 0
1094 * with buffer head unmapped.
1096 if (retval
> 0 && buffer_mapped(bh
))
1100 * New blocks allocate and/or writing to uninitialized extent
1101 * will possibly result in updating i_data, so we take
1102 * the write lock of i_data_sem, and call get_blocks()
1103 * with create == 1 flag.
1105 down_write((&EXT4_I(inode
)->i_data_sem
));
1108 * if the caller is from delayed allocation writeout path
1109 * we have already reserved fs blocks for allocation
1110 * let the underlying get_block() function know to
1111 * avoid double accounting
1114 EXT4_I(inode
)->i_delalloc_reserved_flag
= 1;
1116 * We need to check for EXT4 here because migrate
1117 * could have changed the inode type in between
1119 if (EXT4_I(inode
)->i_flags
& EXT4_EXTENTS_FL
) {
1120 retval
= ext4_ext_get_blocks(handle
, inode
, block
, max_blocks
,
1121 bh
, create
, extend_disksize
);
1123 retval
= ext4_get_blocks_handle(handle
, inode
, block
,
1124 max_blocks
, bh
, create
, extend_disksize
);
1126 if (retval
> 0 && buffer_new(bh
)) {
1128 * We allocated new blocks which will result in
1129 * i_data's format changing. Force the migrate
1130 * to fail by clearing migrate flags
1132 EXT4_I(inode
)->i_flags
= EXT4_I(inode
)->i_flags
&
1138 EXT4_I(inode
)->i_delalloc_reserved_flag
= 0;
1140 * Update reserved blocks/metadata blocks
1141 * after successful block allocation
1142 * which were deferred till now
1144 if ((retval
> 0) && buffer_delay(bh
))
1145 ext4_da_update_reserve_space(inode
, retval
);
1148 up_write((&EXT4_I(inode
)->i_data_sem
));
1152 /* Maximum number of blocks we map for direct IO at once. */
1153 #define DIO_MAX_BLOCKS 4096
1155 int ext4_get_block(struct inode
*inode
, sector_t iblock
,
1156 struct buffer_head
*bh_result
, int create
)
1158 handle_t
*handle
= ext4_journal_current_handle();
1159 int ret
= 0, started
= 0;
1160 unsigned max_blocks
= bh_result
->b_size
>> inode
->i_blkbits
;
1163 if (create
&& !handle
) {
1164 /* Direct IO write... */
1165 if (max_blocks
> DIO_MAX_BLOCKS
)
1166 max_blocks
= DIO_MAX_BLOCKS
;
1167 dio_credits
= ext4_chunk_trans_blocks(inode
, max_blocks
);
1168 handle
= ext4_journal_start(inode
, dio_credits
);
1169 if (IS_ERR(handle
)) {
1170 ret
= PTR_ERR(handle
);
1176 ret
= ext4_get_blocks_wrap(handle
, inode
, iblock
,
1177 max_blocks
, bh_result
, create
, 0, 0);
1179 bh_result
->b_size
= (ret
<< inode
->i_blkbits
);
1183 ext4_journal_stop(handle
);
1189 * `handle' can be NULL if create is zero
1191 struct buffer_head
*ext4_getblk(handle_t
*handle
, struct inode
*inode
,
1192 ext4_lblk_t block
, int create
, int *errp
)
1194 struct buffer_head dummy
;
1197 J_ASSERT(handle
!= NULL
|| create
== 0);
1200 dummy
.b_blocknr
= -1000;
1201 buffer_trace_init(&dummy
.b_history
);
1202 err
= ext4_get_blocks_wrap(handle
, inode
, block
, 1,
1203 &dummy
, create
, 1, 0);
1205 * ext4_get_blocks_handle() returns number of blocks
1206 * mapped. 0 in case of a HOLE.
1214 if (!err
&& buffer_mapped(&dummy
)) {
1215 struct buffer_head
*bh
;
1216 bh
= sb_getblk(inode
->i_sb
, dummy
.b_blocknr
);
1221 if (buffer_new(&dummy
)) {
1222 J_ASSERT(create
!= 0);
1223 J_ASSERT(handle
!= NULL
);
1226 * Now that we do not always journal data, we should
1227 * keep in mind whether this should always journal the
1228 * new buffer as metadata. For now, regular file
1229 * writes use ext4_get_block instead, so it's not a
1233 BUFFER_TRACE(bh
, "call get_create_access");
1234 fatal
= ext4_journal_get_create_access(handle
, bh
);
1235 if (!fatal
&& !buffer_uptodate(bh
)) {
1236 memset(bh
->b_data
, 0, inode
->i_sb
->s_blocksize
);
1237 set_buffer_uptodate(bh
);
1240 BUFFER_TRACE(bh
, "call ext4_handle_dirty_metadata");
1241 err
= ext4_handle_dirty_metadata(handle
, inode
, bh
);
1245 BUFFER_TRACE(bh
, "not a new buffer");
1258 struct buffer_head
*ext4_bread(handle_t
*handle
, struct inode
*inode
,
1259 ext4_lblk_t block
, int create
, int *err
)
1261 struct buffer_head
*bh
;
1263 bh
= ext4_getblk(handle
, inode
, block
, create
, err
);
1266 if (buffer_uptodate(bh
))
1268 ll_rw_block(READ_META
, 1, &bh
);
1270 if (buffer_uptodate(bh
))
1277 static int walk_page_buffers(handle_t
*handle
,
1278 struct buffer_head
*head
,
1282 int (*fn
)(handle_t
*handle
,
1283 struct buffer_head
*bh
))
1285 struct buffer_head
*bh
;
1286 unsigned block_start
, block_end
;
1287 unsigned blocksize
= head
->b_size
;
1289 struct buffer_head
*next
;
1291 for (bh
= head
, block_start
= 0;
1292 ret
== 0 && (bh
!= head
|| !block_start
);
1293 block_start
= block_end
, bh
= next
)
1295 next
= bh
->b_this_page
;
1296 block_end
= block_start
+ blocksize
;
1297 if (block_end
<= from
|| block_start
>= to
) {
1298 if (partial
&& !buffer_uptodate(bh
))
1302 err
= (*fn
)(handle
, bh
);
1310 * To preserve ordering, it is essential that the hole instantiation and
1311 * the data write be encapsulated in a single transaction. We cannot
1312 * close off a transaction and start a new one between the ext4_get_block()
1313 * and the commit_write(). So doing the jbd2_journal_start at the start of
1314 * prepare_write() is the right place.
1316 * Also, this function can nest inside ext4_writepage() ->
1317 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1318 * has generated enough buffer credits to do the whole page. So we won't
1319 * block on the journal in that case, which is good, because the caller may
1322 * By accident, ext4 can be reentered when a transaction is open via
1323 * quota file writes. If we were to commit the transaction while thus
1324 * reentered, there can be a deadlock - we would be holding a quota
1325 * lock, and the commit would never complete if another thread had a
1326 * transaction open and was blocking on the quota lock - a ranking
1329 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1330 * will _not_ run commit under these circumstances because handle->h_ref
1331 * is elevated. We'll still have enough credits for the tiny quotafile
1334 static int do_journal_get_write_access(handle_t
*handle
,
1335 struct buffer_head
*bh
)
1337 if (!buffer_mapped(bh
) || buffer_freed(bh
))
1339 return ext4_journal_get_write_access(handle
, bh
);
1342 static int ext4_write_begin(struct file
*file
, struct address_space
*mapping
,
1343 loff_t pos
, unsigned len
, unsigned flags
,
1344 struct page
**pagep
, void **fsdata
)
1346 struct inode
*inode
= mapping
->host
;
1347 int ret
, needed_blocks
= ext4_writepage_trans_blocks(inode
);
1354 trace_mark(ext4_write_begin
,
1355 "dev %s ino %lu pos %llu len %u flags %u",
1356 inode
->i_sb
->s_id
, inode
->i_ino
,
1357 (unsigned long long) pos
, len
, flags
);
1358 index
= pos
>> PAGE_CACHE_SHIFT
;
1359 from
= pos
& (PAGE_CACHE_SIZE
- 1);
1363 handle
= ext4_journal_start(inode
, needed_blocks
);
1364 if (IS_ERR(handle
)) {
1365 ret
= PTR_ERR(handle
);
1369 page
= grab_cache_page_write_begin(mapping
, index
, flags
);
1371 ext4_journal_stop(handle
);
1377 ret
= block_write_begin(file
, mapping
, pos
, len
, flags
, pagep
, fsdata
,
1380 if (!ret
&& ext4_should_journal_data(inode
)) {
1381 ret
= walk_page_buffers(handle
, page_buffers(page
),
1382 from
, to
, NULL
, do_journal_get_write_access
);
1387 ext4_journal_stop(handle
);
1388 page_cache_release(page
);
1390 * block_write_begin may have instantiated a few blocks
1391 * outside i_size. Trim these off again. Don't need
1392 * i_size_read because we hold i_mutex.
1394 if (pos
+ len
> inode
->i_size
)
1395 vmtruncate(inode
, inode
->i_size
);
1398 if (ret
== -ENOSPC
&& ext4_should_retry_alloc(inode
->i_sb
, &retries
))
1404 /* For write_end() in data=journal mode */
1405 static int write_end_fn(handle_t
*handle
, struct buffer_head
*bh
)
1407 if (!buffer_mapped(bh
) || buffer_freed(bh
))
1409 set_buffer_uptodate(bh
);
1410 return ext4_handle_dirty_metadata(handle
, NULL
, bh
);
1414 * We need to pick up the new inode size which generic_commit_write gave us
1415 * `file' can be NULL - eg, when called from page_symlink().
1417 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1418 * buffers are managed internally.
1420 static int ext4_ordered_write_end(struct file
*file
,
1421 struct address_space
*mapping
,
1422 loff_t pos
, unsigned len
, unsigned copied
,
1423 struct page
*page
, void *fsdata
)
1425 handle_t
*handle
= ext4_journal_current_handle();
1426 struct inode
*inode
= mapping
->host
;
1429 trace_mark(ext4_ordered_write_end
,
1430 "dev %s ino %lu pos %llu len %u copied %u",
1431 inode
->i_sb
->s_id
, inode
->i_ino
,
1432 (unsigned long long) pos
, len
, copied
);
1433 ret
= ext4_jbd2_file_inode(handle
, inode
);
1438 new_i_size
= pos
+ copied
;
1439 if (new_i_size
> EXT4_I(inode
)->i_disksize
) {
1440 ext4_update_i_disksize(inode
, new_i_size
);
1441 /* We need to mark inode dirty even if
1442 * new_i_size is less that inode->i_size
1443 * bu greater than i_disksize.(hint delalloc)
1445 ext4_mark_inode_dirty(handle
, inode
);
1448 ret2
= generic_write_end(file
, mapping
, pos
, len
, copied
,
1454 ret2
= ext4_journal_stop(handle
);
1458 return ret
? ret
: copied
;
1461 static int ext4_writeback_write_end(struct file
*file
,
1462 struct address_space
*mapping
,
1463 loff_t pos
, unsigned len
, unsigned copied
,
1464 struct page
*page
, void *fsdata
)
1466 handle_t
*handle
= ext4_journal_current_handle();
1467 struct inode
*inode
= mapping
->host
;
1471 trace_mark(ext4_writeback_write_end
,
1472 "dev %s ino %lu pos %llu len %u copied %u",
1473 inode
->i_sb
->s_id
, inode
->i_ino
,
1474 (unsigned long long) pos
, len
, copied
);
1475 new_i_size
= pos
+ copied
;
1476 if (new_i_size
> EXT4_I(inode
)->i_disksize
) {
1477 ext4_update_i_disksize(inode
, new_i_size
);
1478 /* We need to mark inode dirty even if
1479 * new_i_size is less that inode->i_size
1480 * bu greater than i_disksize.(hint delalloc)
1482 ext4_mark_inode_dirty(handle
, inode
);
1485 ret2
= generic_write_end(file
, mapping
, pos
, len
, copied
,
1491 ret2
= ext4_journal_stop(handle
);
1495 return ret
? ret
: copied
;
1498 static int ext4_journalled_write_end(struct file
*file
,
1499 struct address_space
*mapping
,
1500 loff_t pos
, unsigned len
, unsigned copied
,
1501 struct page
*page
, void *fsdata
)
1503 handle_t
*handle
= ext4_journal_current_handle();
1504 struct inode
*inode
= mapping
->host
;
1510 trace_mark(ext4_journalled_write_end
,
1511 "dev %s ino %lu pos %llu len %u copied %u",
1512 inode
->i_sb
->s_id
, inode
->i_ino
,
1513 (unsigned long long) pos
, len
, copied
);
1514 from
= pos
& (PAGE_CACHE_SIZE
- 1);
1518 if (!PageUptodate(page
))
1520 page_zero_new_buffers(page
, from
+copied
, to
);
1523 ret
= walk_page_buffers(handle
, page_buffers(page
), from
,
1524 to
, &partial
, write_end_fn
);
1526 SetPageUptodate(page
);
1527 new_i_size
= pos
+ copied
;
1528 if (new_i_size
> inode
->i_size
)
1529 i_size_write(inode
, pos
+copied
);
1530 EXT4_I(inode
)->i_state
|= EXT4_STATE_JDATA
;
1531 if (new_i_size
> EXT4_I(inode
)->i_disksize
) {
1532 ext4_update_i_disksize(inode
, new_i_size
);
1533 ret2
= ext4_mark_inode_dirty(handle
, inode
);
1539 ret2
= ext4_journal_stop(handle
);
1542 page_cache_release(page
);
1544 return ret
? ret
: copied
;
1547 static int ext4_da_reserve_space(struct inode
*inode
, int nrblocks
)
1550 struct ext4_sb_info
*sbi
= EXT4_SB(inode
->i_sb
);
1551 unsigned long md_needed
, mdblocks
, total
= 0;
1554 * recalculate the amount of metadata blocks to reserve
1555 * in order to allocate nrblocks
1556 * worse case is one extent per block
1559 spin_lock(&EXT4_I(inode
)->i_block_reservation_lock
);
1560 total
= EXT4_I(inode
)->i_reserved_data_blocks
+ nrblocks
;
1561 mdblocks
= ext4_calc_metadata_amount(inode
, total
);
1562 BUG_ON(mdblocks
< EXT4_I(inode
)->i_reserved_meta_blocks
);
1564 md_needed
= mdblocks
- EXT4_I(inode
)->i_reserved_meta_blocks
;
1565 total
= md_needed
+ nrblocks
;
1567 if (ext4_claim_free_blocks(sbi
, total
)) {
1568 spin_unlock(&EXT4_I(inode
)->i_block_reservation_lock
);
1569 if (ext4_should_retry_alloc(inode
->i_sb
, &retries
)) {
1575 EXT4_I(inode
)->i_reserved_data_blocks
+= nrblocks
;
1576 EXT4_I(inode
)->i_reserved_meta_blocks
= mdblocks
;
1578 spin_unlock(&EXT4_I(inode
)->i_block_reservation_lock
);
1579 return 0; /* success */
1582 static void ext4_da_release_space(struct inode
*inode
, int to_free
)
1584 struct ext4_sb_info
*sbi
= EXT4_SB(inode
->i_sb
);
1585 int total
, mdb
, mdb_free
, release
;
1588 return; /* Nothing to release, exit */
1590 spin_lock(&EXT4_I(inode
)->i_block_reservation_lock
);
1592 if (!EXT4_I(inode
)->i_reserved_data_blocks
) {
1594 * if there is no reserved blocks, but we try to free some
1595 * then the counter is messed up somewhere.
1596 * but since this function is called from invalidate
1597 * page, it's harmless to return without any action
1599 printk(KERN_INFO
"ext4 delalloc try to release %d reserved "
1600 "blocks for inode %lu, but there is no reserved "
1601 "data blocks\n", to_free
, inode
->i_ino
);
1602 spin_unlock(&EXT4_I(inode
)->i_block_reservation_lock
);
1606 /* recalculate the number of metablocks still need to be reserved */
1607 total
= EXT4_I(inode
)->i_reserved_data_blocks
- to_free
;
1608 mdb
= ext4_calc_metadata_amount(inode
, total
);
1610 /* figure out how many metablocks to release */
1611 BUG_ON(mdb
> EXT4_I(inode
)->i_reserved_meta_blocks
);
1612 mdb_free
= EXT4_I(inode
)->i_reserved_meta_blocks
- mdb
;
1614 release
= to_free
+ mdb_free
;
1616 /* update fs dirty blocks counter for truncate case */
1617 percpu_counter_sub(&sbi
->s_dirtyblocks_counter
, release
);
1619 /* update per-inode reservations */
1620 BUG_ON(to_free
> EXT4_I(inode
)->i_reserved_data_blocks
);
1621 EXT4_I(inode
)->i_reserved_data_blocks
-= to_free
;
1623 BUG_ON(mdb
> EXT4_I(inode
)->i_reserved_meta_blocks
);
1624 EXT4_I(inode
)->i_reserved_meta_blocks
= mdb
;
1625 spin_unlock(&EXT4_I(inode
)->i_block_reservation_lock
);
1628 static void ext4_da_page_release_reservation(struct page
*page
,
1629 unsigned long offset
)
1632 struct buffer_head
*head
, *bh
;
1633 unsigned int curr_off
= 0;
1635 head
= page_buffers(page
);
1638 unsigned int next_off
= curr_off
+ bh
->b_size
;
1640 if ((offset
<= curr_off
) && (buffer_delay(bh
))) {
1642 clear_buffer_delay(bh
);
1644 curr_off
= next_off
;
1645 } while ((bh
= bh
->b_this_page
) != head
);
1646 ext4_da_release_space(page
->mapping
->host
, to_release
);
1650 * Delayed allocation stuff
1653 struct mpage_da_data
{
1654 struct inode
*inode
;
1655 struct buffer_head lbh
; /* extent of blocks */
1656 unsigned long first_page
, next_page
; /* extent of pages */
1657 get_block_t
*get_block
;
1658 struct writeback_control
*wbc
;
1665 * mpage_da_submit_io - walks through extent of pages and try to write
1666 * them with writepage() call back
1668 * @mpd->inode: inode
1669 * @mpd->first_page: first page of the extent
1670 * @mpd->next_page: page after the last page of the extent
1671 * @mpd->get_block: the filesystem's block mapper function
1673 * By the time mpage_da_submit_io() is called we expect all blocks
1674 * to be allocated. this may be wrong if allocation failed.
1676 * As pages are already locked by write_cache_pages(), we can't use it
1678 static int mpage_da_submit_io(struct mpage_da_data
*mpd
)
1681 struct pagevec pvec
;
1682 unsigned long index
, end
;
1683 int ret
= 0, err
, nr_pages
, i
;
1684 struct inode
*inode
= mpd
->inode
;
1685 struct address_space
*mapping
= inode
->i_mapping
;
1687 BUG_ON(mpd
->next_page
<= mpd
->first_page
);
1689 * We need to start from the first_page to the next_page - 1
1690 * to make sure we also write the mapped dirty buffer_heads.
1691 * If we look at mpd->lbh.b_blocknr we would only be looking
1692 * at the currently mapped buffer_heads.
1694 index
= mpd
->first_page
;
1695 end
= mpd
->next_page
- 1;
1697 pagevec_init(&pvec
, 0);
1698 while (index
<= end
) {
1699 nr_pages
= pagevec_lookup(&pvec
, mapping
, index
, PAGEVEC_SIZE
);
1702 for (i
= 0; i
< nr_pages
; i
++) {
1703 struct page
*page
= pvec
.pages
[i
];
1705 index
= page
->index
;
1710 BUG_ON(!PageLocked(page
));
1711 BUG_ON(PageWriteback(page
));
1713 pages_skipped
= mpd
->wbc
->pages_skipped
;
1714 err
= mapping
->a_ops
->writepage(page
, mpd
->wbc
);
1715 if (!err
&& (pages_skipped
== mpd
->wbc
->pages_skipped
))
1717 * have successfully written the page
1718 * without skipping the same
1720 mpd
->pages_written
++;
1722 * In error case, we have to continue because
1723 * remaining pages are still locked
1724 * XXX: unlock and re-dirty them?
1729 pagevec_release(&pvec
);
1735 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
1737 * @mpd->inode - inode to walk through
1738 * @exbh->b_blocknr - first block on a disk
1739 * @exbh->b_size - amount of space in bytes
1740 * @logical - first logical block to start assignment with
1742 * the function goes through all passed space and put actual disk
1743 * block numbers into buffer heads, dropping BH_Delay
1745 static void mpage_put_bnr_to_bhs(struct mpage_da_data
*mpd
, sector_t logical
,
1746 struct buffer_head
*exbh
)
1748 struct inode
*inode
= mpd
->inode
;
1749 struct address_space
*mapping
= inode
->i_mapping
;
1750 int blocks
= exbh
->b_size
>> inode
->i_blkbits
;
1751 sector_t pblock
= exbh
->b_blocknr
, cur_logical
;
1752 struct buffer_head
*head
, *bh
;
1754 struct pagevec pvec
;
1757 index
= logical
>> (PAGE_CACHE_SHIFT
- inode
->i_blkbits
);
1758 end
= (logical
+ blocks
- 1) >> (PAGE_CACHE_SHIFT
- inode
->i_blkbits
);
1759 cur_logical
= index
<< (PAGE_CACHE_SHIFT
- inode
->i_blkbits
);
1761 pagevec_init(&pvec
, 0);
1763 while (index
<= end
) {
1764 /* XXX: optimize tail */
1765 nr_pages
= pagevec_lookup(&pvec
, mapping
, index
, PAGEVEC_SIZE
);
1768 for (i
= 0; i
< nr_pages
; i
++) {
1769 struct page
*page
= pvec
.pages
[i
];
1771 index
= page
->index
;
1776 BUG_ON(!PageLocked(page
));
1777 BUG_ON(PageWriteback(page
));
1778 BUG_ON(!page_has_buffers(page
));
1780 bh
= page_buffers(page
);
1783 /* skip blocks out of the range */
1785 if (cur_logical
>= logical
)
1788 } while ((bh
= bh
->b_this_page
) != head
);
1791 if (cur_logical
>= logical
+ blocks
)
1793 if (buffer_delay(bh
)) {
1794 bh
->b_blocknr
= pblock
;
1795 clear_buffer_delay(bh
);
1796 bh
->b_bdev
= inode
->i_sb
->s_bdev
;
1797 } else if (buffer_unwritten(bh
)) {
1798 bh
->b_blocknr
= pblock
;
1799 clear_buffer_unwritten(bh
);
1800 set_buffer_mapped(bh
);
1802 bh
->b_bdev
= inode
->i_sb
->s_bdev
;
1803 } else if (buffer_mapped(bh
))
1804 BUG_ON(bh
->b_blocknr
!= pblock
);
1808 } while ((bh
= bh
->b_this_page
) != head
);
1810 pagevec_release(&pvec
);
1816 * __unmap_underlying_blocks - just a helper function to unmap
1817 * set of blocks described by @bh
1819 static inline void __unmap_underlying_blocks(struct inode
*inode
,
1820 struct buffer_head
*bh
)
1822 struct block_device
*bdev
= inode
->i_sb
->s_bdev
;
1825 blocks
= bh
->b_size
>> inode
->i_blkbits
;
1826 for (i
= 0; i
< blocks
; i
++)
1827 unmap_underlying_metadata(bdev
, bh
->b_blocknr
+ i
);
1830 static void ext4_da_block_invalidatepages(struct mpage_da_data
*mpd
,
1831 sector_t logical
, long blk_cnt
)
1835 struct pagevec pvec
;
1836 struct inode
*inode
= mpd
->inode
;
1837 struct address_space
*mapping
= inode
->i_mapping
;
1839 index
= logical
>> (PAGE_CACHE_SHIFT
- inode
->i_blkbits
);
1840 end
= (logical
+ blk_cnt
- 1) >>
1841 (PAGE_CACHE_SHIFT
- inode
->i_blkbits
);
1842 while (index
<= end
) {
1843 nr_pages
= pagevec_lookup(&pvec
, mapping
, index
, PAGEVEC_SIZE
);
1846 for (i
= 0; i
< nr_pages
; i
++) {
1847 struct page
*page
= pvec
.pages
[i
];
1848 index
= page
->index
;
1853 BUG_ON(!PageLocked(page
));
1854 BUG_ON(PageWriteback(page
));
1855 block_invalidatepage(page
, 0);
1856 ClearPageUptodate(page
);
1863 static void ext4_print_free_blocks(struct inode
*inode
)
1865 struct ext4_sb_info
*sbi
= EXT4_SB(inode
->i_sb
);
1866 printk(KERN_EMERG
"Total free blocks count %lld\n",
1867 ext4_count_free_blocks(inode
->i_sb
));
1868 printk(KERN_EMERG
"Free/Dirty block details\n");
1869 printk(KERN_EMERG
"free_blocks=%lld\n",
1870 (long long)percpu_counter_sum(&sbi
->s_freeblocks_counter
));
1871 printk(KERN_EMERG
"dirty_blocks=%lld\n",
1872 (long long)percpu_counter_sum(&sbi
->s_dirtyblocks_counter
));
1873 printk(KERN_EMERG
"Block reservation details\n");
1874 printk(KERN_EMERG
"i_reserved_data_blocks=%u\n",
1875 EXT4_I(inode
)->i_reserved_data_blocks
);
1876 printk(KERN_EMERG
"i_reserved_meta_blocks=%u\n",
1877 EXT4_I(inode
)->i_reserved_meta_blocks
);
1882 * mpage_da_map_blocks - go through given space
1884 * @mpd->lbh - bh describing space
1885 * @mpd->get_block - the filesystem's block mapper function
1887 * The function skips space we know is already mapped to disk blocks.
1890 static int mpage_da_map_blocks(struct mpage_da_data
*mpd
)
1893 struct buffer_head
new;
1894 struct buffer_head
*lbh
= &mpd
->lbh
;
1898 * We consider only non-mapped and non-allocated blocks
1900 if (buffer_mapped(lbh
) && !buffer_delay(lbh
))
1902 new.b_state
= lbh
->b_state
;
1904 new.b_size
= lbh
->b_size
;
1905 next
= lbh
->b_blocknr
;
1907 * If we didn't accumulate anything
1908 * to write simply return
1912 err
= mpd
->get_block(mpd
->inode
, next
, &new, 1);
1915 /* If get block returns with error
1916 * we simply return. Later writepage
1917 * will redirty the page and writepages
1918 * will find the dirty page again
1923 if (err
== -ENOSPC
&&
1924 ext4_count_free_blocks(mpd
->inode
->i_sb
)) {
1930 * get block failure will cause us
1931 * to loop in writepages. Because
1932 * a_ops->writepage won't be able to
1933 * make progress. The page will be redirtied
1934 * by writepage and writepages will again
1935 * try to write the same.
1937 printk(KERN_EMERG
"%s block allocation failed for inode %lu "
1938 "at logical offset %llu with max blocks "
1939 "%zd with error %d\n",
1940 __func__
, mpd
->inode
->i_ino
,
1941 (unsigned long long)next
,
1942 lbh
->b_size
>> mpd
->inode
->i_blkbits
, err
);
1943 printk(KERN_EMERG
"This should not happen.!! "
1944 "Data will be lost\n");
1945 if (err
== -ENOSPC
) {
1946 ext4_print_free_blocks(mpd
->inode
);
1948 /* invlaidate all the pages */
1949 ext4_da_block_invalidatepages(mpd
, next
,
1950 lbh
->b_size
>> mpd
->inode
->i_blkbits
);
1953 BUG_ON(new.b_size
== 0);
1955 if (buffer_new(&new))
1956 __unmap_underlying_blocks(mpd
->inode
, &new);
1959 * If blocks are delayed marked, we need to
1960 * put actual blocknr and drop delayed bit
1962 if (buffer_delay(lbh
) || buffer_unwritten(lbh
))
1963 mpage_put_bnr_to_bhs(mpd
, next
, &new);
1968 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1969 (1 << BH_Delay) | (1 << BH_Unwritten))
1972 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1974 * @mpd->lbh - extent of blocks
1975 * @logical - logical number of the block in the file
1976 * @bh - bh of the block (used to access block's state)
1978 * the function is used to collect contig. blocks in same state
1980 static void mpage_add_bh_to_extent(struct mpage_da_data
*mpd
,
1981 sector_t logical
, struct buffer_head
*bh
)
1984 size_t b_size
= bh
->b_size
;
1985 struct buffer_head
*lbh
= &mpd
->lbh
;
1986 int nrblocks
= lbh
->b_size
>> mpd
->inode
->i_blkbits
;
1988 /* check if thereserved journal credits might overflow */
1989 if (!(EXT4_I(mpd
->inode
)->i_flags
& EXT4_EXTENTS_FL
)) {
1990 if (nrblocks
>= EXT4_MAX_TRANS_DATA
) {
1992 * With non-extent format we are limited by the journal
1993 * credit available. Total credit needed to insert
1994 * nrblocks contiguous blocks is dependent on the
1995 * nrblocks. So limit nrblocks.
1998 } else if ((nrblocks
+ (b_size
>> mpd
->inode
->i_blkbits
)) >
1999 EXT4_MAX_TRANS_DATA
) {
2001 * Adding the new buffer_head would make it cross the
2002 * allowed limit for which we have journal credit
2003 * reserved. So limit the new bh->b_size
2005 b_size
= (EXT4_MAX_TRANS_DATA
- nrblocks
) <<
2006 mpd
->inode
->i_blkbits
;
2007 /* we will do mpage_da_submit_io in the next loop */
2011 * First block in the extent
2013 if (lbh
->b_size
== 0) {
2014 lbh
->b_blocknr
= logical
;
2015 lbh
->b_size
= b_size
;
2016 lbh
->b_state
= bh
->b_state
& BH_FLAGS
;
2020 next
= lbh
->b_blocknr
+ nrblocks
;
2022 * Can we merge the block to our big extent?
2024 if (logical
== next
&& (bh
->b_state
& BH_FLAGS
) == lbh
->b_state
) {
2025 lbh
->b_size
+= b_size
;
2031 * We couldn't merge the block to our extent, so we
2032 * need to flush current extent and start new one
2034 if (mpage_da_map_blocks(mpd
) == 0)
2035 mpage_da_submit_io(mpd
);
2041 * __mpage_da_writepage - finds extent of pages and blocks
2043 * @page: page to consider
2044 * @wbc: not used, we just follow rules
2047 * The function finds extents of pages and scan them for all blocks.
2049 static int __mpage_da_writepage(struct page
*page
,
2050 struct writeback_control
*wbc
, void *data
)
2052 struct mpage_da_data
*mpd
= data
;
2053 struct inode
*inode
= mpd
->inode
;
2054 struct buffer_head
*bh
, *head
, fake
;
2059 * Rest of the page in the page_vec
2060 * redirty then and skip then. We will
2061 * try to to write them again after
2062 * starting a new transaction
2064 redirty_page_for_writepage(wbc
, page
);
2066 return MPAGE_DA_EXTENT_TAIL
;
2069 * Can we merge this page to current extent?
2071 if (mpd
->next_page
!= page
->index
) {
2073 * Nope, we can't. So, we map non-allocated blocks
2074 * and start IO on them using writepage()
2076 if (mpd
->next_page
!= mpd
->first_page
) {
2077 if (mpage_da_map_blocks(mpd
) == 0)
2078 mpage_da_submit_io(mpd
);
2080 * skip rest of the page in the page_vec
2083 redirty_page_for_writepage(wbc
, page
);
2085 return MPAGE_DA_EXTENT_TAIL
;
2089 * Start next extent of pages ...
2091 mpd
->first_page
= page
->index
;
2096 mpd
->lbh
.b_size
= 0;
2097 mpd
->lbh
.b_state
= 0;
2098 mpd
->lbh
.b_blocknr
= 0;
2101 mpd
->next_page
= page
->index
+ 1;
2102 logical
= (sector_t
) page
->index
<<
2103 (PAGE_CACHE_SHIFT
- inode
->i_blkbits
);
2105 if (!page_has_buffers(page
)) {
2107 * There is no attached buffer heads yet (mmap?)
2108 * we treat the page asfull of dirty blocks
2111 bh
->b_size
= PAGE_CACHE_SIZE
;
2113 set_buffer_dirty(bh
);
2114 set_buffer_uptodate(bh
);
2115 mpage_add_bh_to_extent(mpd
, logical
, bh
);
2117 return MPAGE_DA_EXTENT_TAIL
;
2120 * Page with regular buffer heads, just add all dirty ones
2122 head
= page_buffers(page
);
2125 BUG_ON(buffer_locked(bh
));
2127 * We need to try to allocate
2128 * unmapped blocks in the same page.
2129 * Otherwise we won't make progress
2130 * with the page in ext4_da_writepage
2132 if (buffer_dirty(bh
) &&
2133 (!buffer_mapped(bh
) || buffer_delay(bh
))) {
2134 mpage_add_bh_to_extent(mpd
, logical
, bh
);
2136 return MPAGE_DA_EXTENT_TAIL
;
2137 } else if (buffer_dirty(bh
) && (buffer_mapped(bh
))) {
2139 * mapped dirty buffer. We need to update
2140 * the b_state because we look at
2141 * b_state in mpage_da_map_blocks. We don't
2142 * update b_size because if we find an
2143 * unmapped buffer_head later we need to
2144 * use the b_state flag of that buffer_head.
2146 if (mpd
->lbh
.b_size
== 0)
2148 bh
->b_state
& BH_FLAGS
;
2151 } while ((bh
= bh
->b_this_page
) != head
);
2158 * mpage_da_writepages - walk the list of dirty pages of the given
2159 * address space, allocates non-allocated blocks, maps newly-allocated
2160 * blocks to existing bhs and issue IO them
2162 * @mapping: address space structure to write
2163 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2164 * @get_block: the filesystem's block mapper function.
2166 * This is a library function, which implements the writepages()
2167 * address_space_operation.
2169 static int mpage_da_writepages(struct address_space
*mapping
,
2170 struct writeback_control
*wbc
,
2171 struct mpage_da_data
*mpd
)
2175 if (!mpd
->get_block
)
2176 return generic_writepages(mapping
, wbc
);
2178 mpd
->lbh
.b_size
= 0;
2179 mpd
->lbh
.b_state
= 0;
2180 mpd
->lbh
.b_blocknr
= 0;
2181 mpd
->first_page
= 0;
2184 mpd
->pages_written
= 0;
2187 ret
= write_cache_pages(mapping
, wbc
, __mpage_da_writepage
, mpd
);
2189 * Handle last extent of pages
2191 if (!mpd
->io_done
&& mpd
->next_page
!= mpd
->first_page
) {
2192 if (mpage_da_map_blocks(mpd
) == 0)
2193 mpage_da_submit_io(mpd
);
2196 ret
= MPAGE_DA_EXTENT_TAIL
;
2198 wbc
->nr_to_write
-= mpd
->pages_written
;
2203 * this is a special callback for ->write_begin() only
2204 * it's intention is to return mapped block or reserve space
2206 static int ext4_da_get_block_prep(struct inode
*inode
, sector_t iblock
,
2207 struct buffer_head
*bh_result
, int create
)
2211 BUG_ON(create
== 0);
2212 BUG_ON(bh_result
->b_size
!= inode
->i_sb
->s_blocksize
);
2215 * first, we need to know whether the block is allocated already
2216 * preallocated blocks are unmapped but should treated
2217 * the same as allocated blocks.
2219 ret
= ext4_get_blocks_wrap(NULL
, inode
, iblock
, 1, bh_result
, 0, 0, 0);
2220 if ((ret
== 0) && !buffer_delay(bh_result
)) {
2221 /* the block isn't (pre)allocated yet, let's reserve space */
2223 * XXX: __block_prepare_write() unmaps passed block,
2226 ret
= ext4_da_reserve_space(inode
, 1);
2228 /* not enough space to reserve */
2231 map_bh(bh_result
, inode
->i_sb
, 0);
2232 set_buffer_new(bh_result
);
2233 set_buffer_delay(bh_result
);
2234 } else if (ret
> 0) {
2235 bh_result
->b_size
= (ret
<< inode
->i_blkbits
);
2241 #define EXT4_DELALLOC_RSVED 1
2242 static int ext4_da_get_block_write(struct inode
*inode
, sector_t iblock
,
2243 struct buffer_head
*bh_result
, int create
)
2246 unsigned max_blocks
= bh_result
->b_size
>> inode
->i_blkbits
;
2247 loff_t disksize
= EXT4_I(inode
)->i_disksize
;
2248 handle_t
*handle
= NULL
;
2250 handle
= ext4_journal_current_handle();
2252 ret
= ext4_get_blocks_wrap(handle
, inode
, iblock
, max_blocks
,
2253 bh_result
, create
, 0, EXT4_DELALLOC_RSVED
);
2256 bh_result
->b_size
= (ret
<< inode
->i_blkbits
);
2258 if (ext4_should_order_data(inode
)) {
2260 retval
= ext4_jbd2_file_inode(handle
, inode
);
2263 * Failed to add inode for ordered
2264 * mode. Don't update file size
2270 * Update on-disk size along with block allocation
2271 * we don't use 'extend_disksize' as size may change
2272 * within already allocated block -bzzz
2274 disksize
= ((loff_t
) iblock
+ ret
) << inode
->i_blkbits
;
2275 if (disksize
> i_size_read(inode
))
2276 disksize
= i_size_read(inode
);
2277 if (disksize
> EXT4_I(inode
)->i_disksize
) {
2278 ext4_update_i_disksize(inode
, disksize
);
2279 ret
= ext4_mark_inode_dirty(handle
, inode
);
2287 static int ext4_bh_unmapped_or_delay(handle_t
*handle
, struct buffer_head
*bh
)
2290 * unmapped buffer is possible for holes.
2291 * delay buffer is possible with delayed allocation
2293 return ((!buffer_mapped(bh
) || buffer_delay(bh
)) && buffer_dirty(bh
));
2296 static int ext4_normal_get_block_write(struct inode
*inode
, sector_t iblock
,
2297 struct buffer_head
*bh_result
, int create
)
2300 unsigned max_blocks
= bh_result
->b_size
>> inode
->i_blkbits
;
2303 * we don't want to do block allocation in writepage
2304 * so call get_block_wrap with create = 0
2306 ret
= ext4_get_blocks_wrap(NULL
, inode
, iblock
, max_blocks
,
2307 bh_result
, 0, 0, 0);
2309 bh_result
->b_size
= (ret
<< inode
->i_blkbits
);
2316 * get called vi ext4_da_writepages after taking page lock (have journal handle)
2317 * get called via journal_submit_inode_data_buffers (no journal handle)
2318 * get called via shrink_page_list via pdflush (no journal handle)
2319 * or grab_page_cache when doing write_begin (have journal handle)
2321 static int ext4_da_writepage(struct page
*page
,
2322 struct writeback_control
*wbc
)
2327 struct buffer_head
*page_bufs
;
2328 struct inode
*inode
= page
->mapping
->host
;
2330 trace_mark(ext4_da_writepage
,
2331 "dev %s ino %lu page_index %lu",
2332 inode
->i_sb
->s_id
, inode
->i_ino
, page
->index
);
2333 size
= i_size_read(inode
);
2334 if (page
->index
== size
>> PAGE_CACHE_SHIFT
)
2335 len
= size
& ~PAGE_CACHE_MASK
;
2337 len
= PAGE_CACHE_SIZE
;
2339 if (page_has_buffers(page
)) {
2340 page_bufs
= page_buffers(page
);
2341 if (walk_page_buffers(NULL
, page_bufs
, 0, len
, NULL
,
2342 ext4_bh_unmapped_or_delay
)) {
2344 * We don't want to do block allocation
2345 * So redirty the page and return
2346 * We may reach here when we do a journal commit
2347 * via journal_submit_inode_data_buffers.
2348 * If we don't have mapping block we just ignore
2349 * them. We can also reach here via shrink_page_list
2351 redirty_page_for_writepage(wbc
, page
);
2357 * The test for page_has_buffers() is subtle:
2358 * We know the page is dirty but it lost buffers. That means
2359 * that at some moment in time after write_begin()/write_end()
2360 * has been called all buffers have been clean and thus they
2361 * must have been written at least once. So they are all
2362 * mapped and we can happily proceed with mapping them
2363 * and writing the page.
2365 * Try to initialize the buffer_heads and check whether
2366 * all are mapped and non delay. We don't want to
2367 * do block allocation here.
2369 ret
= block_prepare_write(page
, 0, PAGE_CACHE_SIZE
,
2370 ext4_normal_get_block_write
);
2372 page_bufs
= page_buffers(page
);
2373 /* check whether all are mapped and non delay */
2374 if (walk_page_buffers(NULL
, page_bufs
, 0, len
, NULL
,
2375 ext4_bh_unmapped_or_delay
)) {
2376 redirty_page_for_writepage(wbc
, page
);
2382 * We can't do block allocation here
2383 * so just redity the page and unlock
2386 redirty_page_for_writepage(wbc
, page
);
2390 /* now mark the buffer_heads as dirty and uptodate */
2391 block_commit_write(page
, 0, PAGE_CACHE_SIZE
);
2394 if (test_opt(inode
->i_sb
, NOBH
) && ext4_should_writeback_data(inode
))
2395 ret
= nobh_writepage(page
, ext4_normal_get_block_write
, wbc
);
2397 ret
= block_write_full_page(page
,
2398 ext4_normal_get_block_write
,
2405 * This is called via ext4_da_writepages() to
2406 * calulate the total number of credits to reserve to fit
2407 * a single extent allocation into a single transaction,
2408 * ext4_da_writpeages() will loop calling this before
2409 * the block allocation.
2412 static int ext4_da_writepages_trans_blocks(struct inode
*inode
)
2414 int max_blocks
= EXT4_I(inode
)->i_reserved_data_blocks
;
2417 * With non-extent format the journal credit needed to
2418 * insert nrblocks contiguous block is dependent on
2419 * number of contiguous block. So we will limit
2420 * number of contiguous block to a sane value
2422 if (!(inode
->i_flags
& EXT4_EXTENTS_FL
) &&
2423 (max_blocks
> EXT4_MAX_TRANS_DATA
))
2424 max_blocks
= EXT4_MAX_TRANS_DATA
;
2426 return ext4_chunk_trans_blocks(inode
, max_blocks
);
2429 static int ext4_da_writepages(struct address_space
*mapping
,
2430 struct writeback_control
*wbc
)
2433 int range_whole
= 0;
2434 handle_t
*handle
= NULL
;
2435 struct mpage_da_data mpd
;
2436 struct inode
*inode
= mapping
->host
;
2437 int no_nrwrite_index_update
;
2438 int pages_written
= 0;
2440 int needed_blocks
, ret
= 0, nr_to_writebump
= 0;
2441 struct ext4_sb_info
*sbi
= EXT4_SB(mapping
->host
->i_sb
);
2443 trace_mark(ext4_da_writepages
,
2444 "dev %s ino %lu nr_t_write %ld "
2445 "pages_skipped %ld range_start %llu "
2446 "range_end %llu nonblocking %d "
2447 "for_kupdate %d for_reclaim %d "
2448 "for_writepages %d range_cyclic %d",
2449 inode
->i_sb
->s_id
, inode
->i_ino
,
2450 wbc
->nr_to_write
, wbc
->pages_skipped
,
2451 (unsigned long long) wbc
->range_start
,
2452 (unsigned long long) wbc
->range_end
,
2453 wbc
->nonblocking
, wbc
->for_kupdate
,
2454 wbc
->for_reclaim
, wbc
->for_writepages
,
2458 * No pages to write? This is mainly a kludge to avoid starting
2459 * a transaction for special inodes like journal inode on last iput()
2460 * because that could violate lock ordering on umount
2462 if (!mapping
->nrpages
|| !mapping_tagged(mapping
, PAGECACHE_TAG_DIRTY
))
2466 * If the filesystem has aborted, it is read-only, so return
2467 * right away instead of dumping stack traces later on that
2468 * will obscure the real source of the problem. We test
2469 * EXT4_MOUNT_ABORT instead of sb->s_flag's MS_RDONLY because
2470 * the latter could be true if the filesystem is mounted
2471 * read-only, and in that case, ext4_da_writepages should
2472 * *never* be called, so if that ever happens, we would want
2475 if (unlikely(sbi
->s_mount_opt
& EXT4_MOUNT_ABORT
))
2479 * Make sure nr_to_write is >= sbi->s_mb_stream_request
2480 * This make sure small files blocks are allocated in
2481 * single attempt. This ensure that small files
2482 * get less fragmented.
2484 if (wbc
->nr_to_write
< sbi
->s_mb_stream_request
) {
2485 nr_to_writebump
= sbi
->s_mb_stream_request
- wbc
->nr_to_write
;
2486 wbc
->nr_to_write
= sbi
->s_mb_stream_request
;
2488 if (wbc
->range_start
== 0 && wbc
->range_end
== LLONG_MAX
)
2491 if (wbc
->range_cyclic
)
2492 index
= mapping
->writeback_index
;
2494 index
= wbc
->range_start
>> PAGE_CACHE_SHIFT
;
2497 mpd
.inode
= mapping
->host
;
2500 * we don't want write_cache_pages to update
2501 * nr_to_write and writeback_index
2503 no_nrwrite_index_update
= wbc
->no_nrwrite_index_update
;
2504 wbc
->no_nrwrite_index_update
= 1;
2505 pages_skipped
= wbc
->pages_skipped
;
2507 while (!ret
&& wbc
->nr_to_write
> 0) {
2510 * we insert one extent at a time. So we need
2511 * credit needed for single extent allocation.
2512 * journalled mode is currently not supported
2515 BUG_ON(ext4_should_journal_data(inode
));
2516 needed_blocks
= ext4_da_writepages_trans_blocks(inode
);
2518 /* start a new transaction*/
2519 handle
= ext4_journal_start(inode
, needed_blocks
);
2520 if (IS_ERR(handle
)) {
2521 ret
= PTR_ERR(handle
);
2522 printk(KERN_CRIT
"%s: jbd2_start: "
2523 "%ld pages, ino %lu; err %d\n", __func__
,
2524 wbc
->nr_to_write
, inode
->i_ino
, ret
);
2526 goto out_writepages
;
2528 mpd
.get_block
= ext4_da_get_block_write
;
2529 ret
= mpage_da_writepages(mapping
, wbc
, &mpd
);
2531 ext4_journal_stop(handle
);
2533 if (mpd
.retval
== -ENOSPC
) {
2534 /* commit the transaction which would
2535 * free blocks released in the transaction
2538 jbd2_journal_force_commit_nested(sbi
->s_journal
);
2539 wbc
->pages_skipped
= pages_skipped
;
2541 } else if (ret
== MPAGE_DA_EXTENT_TAIL
) {
2543 * got one extent now try with
2546 pages_written
+= mpd
.pages_written
;
2547 wbc
->pages_skipped
= pages_skipped
;
2549 } else if (wbc
->nr_to_write
)
2551 * There is no more writeout needed
2552 * or we requested for a noblocking writeout
2553 * and we found the device congested
2557 if (pages_skipped
!= wbc
->pages_skipped
)
2558 printk(KERN_EMERG
"This should not happen leaving %s "
2559 "with nr_to_write = %ld ret = %d\n",
2560 __func__
, wbc
->nr_to_write
, ret
);
2563 index
+= pages_written
;
2564 if (wbc
->range_cyclic
|| (range_whole
&& wbc
->nr_to_write
> 0))
2566 * set the writeback_index so that range_cyclic
2567 * mode will write it back later
2569 mapping
->writeback_index
= index
;
2572 if (!no_nrwrite_index_update
)
2573 wbc
->no_nrwrite_index_update
= 0;
2574 wbc
->nr_to_write
-= nr_to_writebump
;
2575 trace_mark(ext4_da_writepage_result
,
2576 "dev %s ino %lu ret %d pages_written %d "
2577 "pages_skipped %ld congestion %d "
2578 "more_io %d no_nrwrite_index_update %d",
2579 inode
->i_sb
->s_id
, inode
->i_ino
, ret
,
2580 pages_written
, wbc
->pages_skipped
,
2581 wbc
->encountered_congestion
, wbc
->more_io
,
2582 wbc
->no_nrwrite_index_update
);
2586 #define FALL_BACK_TO_NONDELALLOC 1
2587 static int ext4_nonda_switch(struct super_block
*sb
)
2589 s64 free_blocks
, dirty_blocks
;
2590 struct ext4_sb_info
*sbi
= EXT4_SB(sb
);
2593 * switch to non delalloc mode if we are running low
2594 * on free block. The free block accounting via percpu
2595 * counters can get slightly wrong with percpu_counter_batch getting
2596 * accumulated on each CPU without updating global counters
2597 * Delalloc need an accurate free block accounting. So switch
2598 * to non delalloc when we are near to error range.
2600 free_blocks
= percpu_counter_read_positive(&sbi
->s_freeblocks_counter
);
2601 dirty_blocks
= percpu_counter_read_positive(&sbi
->s_dirtyblocks_counter
);
2602 if (2 * free_blocks
< 3 * dirty_blocks
||
2603 free_blocks
< (dirty_blocks
+ EXT4_FREEBLOCKS_WATERMARK
)) {
2605 * free block count is less that 150% of dirty blocks
2606 * or free blocks is less that watermark
2613 static int ext4_da_write_begin(struct file
*file
, struct address_space
*mapping
,
2614 loff_t pos
, unsigned len
, unsigned flags
,
2615 struct page
**pagep
, void **fsdata
)
2617 int ret
, retries
= 0;
2621 struct inode
*inode
= mapping
->host
;
2624 index
= pos
>> PAGE_CACHE_SHIFT
;
2625 from
= pos
& (PAGE_CACHE_SIZE
- 1);
2628 if (ext4_nonda_switch(inode
->i_sb
)) {
2629 *fsdata
= (void *)FALL_BACK_TO_NONDELALLOC
;
2630 return ext4_write_begin(file
, mapping
, pos
,
2631 len
, flags
, pagep
, fsdata
);
2633 *fsdata
= (void *)0;
2635 trace_mark(ext4_da_write_begin
,
2636 "dev %s ino %lu pos %llu len %u flags %u",
2637 inode
->i_sb
->s_id
, inode
->i_ino
,
2638 (unsigned long long) pos
, len
, flags
);
2641 * With delayed allocation, we don't log the i_disksize update
2642 * if there is delayed block allocation. But we still need
2643 * to journalling the i_disksize update if writes to the end
2644 * of file which has an already mapped buffer.
2646 handle
= ext4_journal_start(inode
, 1);
2647 if (IS_ERR(handle
)) {
2648 ret
= PTR_ERR(handle
);
2652 page
= grab_cache_page_write_begin(mapping
, index
, flags
);
2654 ext4_journal_stop(handle
);
2660 ret
= block_write_begin(file
, mapping
, pos
, len
, flags
, pagep
, fsdata
,
2661 ext4_da_get_block_prep
);
2664 ext4_journal_stop(handle
);
2665 page_cache_release(page
);
2667 * block_write_begin may have instantiated a few blocks
2668 * outside i_size. Trim these off again. Don't need
2669 * i_size_read because we hold i_mutex.
2671 if (pos
+ len
> inode
->i_size
)
2672 vmtruncate(inode
, inode
->i_size
);
2675 if (ret
== -ENOSPC
&& ext4_should_retry_alloc(inode
->i_sb
, &retries
))
2682 * Check if we should update i_disksize
2683 * when write to the end of file but not require block allocation
2685 static int ext4_da_should_update_i_disksize(struct page
*page
,
2686 unsigned long offset
)
2688 struct buffer_head
*bh
;
2689 struct inode
*inode
= page
->mapping
->host
;
2693 bh
= page_buffers(page
);
2694 idx
= offset
>> inode
->i_blkbits
;
2696 for (i
= 0; i
< idx
; i
++)
2697 bh
= bh
->b_this_page
;
2699 if (!buffer_mapped(bh
) || (buffer_delay(bh
)))
2704 static int ext4_da_write_end(struct file
*file
,
2705 struct address_space
*mapping
,
2706 loff_t pos
, unsigned len
, unsigned copied
,
2707 struct page
*page
, void *fsdata
)
2709 struct inode
*inode
= mapping
->host
;
2711 handle_t
*handle
= ext4_journal_current_handle();
2713 unsigned long start
, end
;
2714 int write_mode
= (int)(unsigned long)fsdata
;
2716 if (write_mode
== FALL_BACK_TO_NONDELALLOC
) {
2717 if (ext4_should_order_data(inode
)) {
2718 return ext4_ordered_write_end(file
, mapping
, pos
,
2719 len
, copied
, page
, fsdata
);
2720 } else if (ext4_should_writeback_data(inode
)) {
2721 return ext4_writeback_write_end(file
, mapping
, pos
,
2722 len
, copied
, page
, fsdata
);
2728 trace_mark(ext4_da_write_end
,
2729 "dev %s ino %lu pos %llu len %u copied %u",
2730 inode
->i_sb
->s_id
, inode
->i_ino
,
2731 (unsigned long long) pos
, len
, copied
);
2732 start
= pos
& (PAGE_CACHE_SIZE
- 1);
2733 end
= start
+ copied
- 1;
2736 * generic_write_end() will run mark_inode_dirty() if i_size
2737 * changes. So let's piggyback the i_disksize mark_inode_dirty
2741 new_i_size
= pos
+ copied
;
2742 if (new_i_size
> EXT4_I(inode
)->i_disksize
) {
2743 if (ext4_da_should_update_i_disksize(page
, end
)) {
2744 down_write(&EXT4_I(inode
)->i_data_sem
);
2745 if (new_i_size
> EXT4_I(inode
)->i_disksize
) {
2747 * Updating i_disksize when extending file
2748 * without needing block allocation
2750 if (ext4_should_order_data(inode
))
2751 ret
= ext4_jbd2_file_inode(handle
,
2754 EXT4_I(inode
)->i_disksize
= new_i_size
;
2756 up_write(&EXT4_I(inode
)->i_data_sem
);
2757 /* We need to mark inode dirty even if
2758 * new_i_size is less that inode->i_size
2759 * bu greater than i_disksize.(hint delalloc)
2761 ext4_mark_inode_dirty(handle
, inode
);
2764 ret2
= generic_write_end(file
, mapping
, pos
, len
, copied
,
2769 ret2
= ext4_journal_stop(handle
);
2773 return ret
? ret
: copied
;
2776 static void ext4_da_invalidatepage(struct page
*page
, unsigned long offset
)
2779 * Drop reserved blocks
2781 BUG_ON(!PageLocked(page
));
2782 if (!page_has_buffers(page
))
2785 ext4_da_page_release_reservation(page
, offset
);
2788 ext4_invalidatepage(page
, offset
);
2795 * bmap() is special. It gets used by applications such as lilo and by
2796 * the swapper to find the on-disk block of a specific piece of data.
2798 * Naturally, this is dangerous if the block concerned is still in the
2799 * journal. If somebody makes a swapfile on an ext4 data-journaling
2800 * filesystem and enables swap, then they may get a nasty shock when the
2801 * data getting swapped to that swapfile suddenly gets overwritten by
2802 * the original zero's written out previously to the journal and
2803 * awaiting writeback in the kernel's buffer cache.
2805 * So, if we see any bmap calls here on a modified, data-journaled file,
2806 * take extra steps to flush any blocks which might be in the cache.
2808 static sector_t
ext4_bmap(struct address_space
*mapping
, sector_t block
)
2810 struct inode
*inode
= mapping
->host
;
2814 if (mapping_tagged(mapping
, PAGECACHE_TAG_DIRTY
) &&
2815 test_opt(inode
->i_sb
, DELALLOC
)) {
2817 * With delalloc we want to sync the file
2818 * so that we can make sure we allocate
2821 filemap_write_and_wait(mapping
);
2824 if (EXT4_JOURNAL(inode
) && EXT4_I(inode
)->i_state
& EXT4_STATE_JDATA
) {
2826 * This is a REALLY heavyweight approach, but the use of
2827 * bmap on dirty files is expected to be extremely rare:
2828 * only if we run lilo or swapon on a freshly made file
2829 * do we expect this to happen.
2831 * (bmap requires CAP_SYS_RAWIO so this does not
2832 * represent an unprivileged user DOS attack --- we'd be
2833 * in trouble if mortal users could trigger this path at
2836 * NB. EXT4_STATE_JDATA is not set on files other than
2837 * regular files. If somebody wants to bmap a directory
2838 * or symlink and gets confused because the buffer
2839 * hasn't yet been flushed to disk, they deserve
2840 * everything they get.
2843 EXT4_I(inode
)->i_state
&= ~EXT4_STATE_JDATA
;
2844 journal
= EXT4_JOURNAL(inode
);
2845 jbd2_journal_lock_updates(journal
);
2846 err
= jbd2_journal_flush(journal
);
2847 jbd2_journal_unlock_updates(journal
);
2853 return generic_block_bmap(mapping
, block
, ext4_get_block
);
2856 static int bget_one(handle_t
*handle
, struct buffer_head
*bh
)
2862 static int bput_one(handle_t
*handle
, struct buffer_head
*bh
)
2869 * Note that we don't need to start a transaction unless we're journaling data
2870 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2871 * need to file the inode to the transaction's list in ordered mode because if
2872 * we are writing back data added by write(), the inode is already there and if
2873 * we are writing back data modified via mmap(), noone guarantees in which
2874 * transaction the data will hit the disk. In case we are journaling data, we
2875 * cannot start transaction directly because transaction start ranks above page
2876 * lock so we have to do some magic.
2878 * In all journaling modes block_write_full_page() will start the I/O.
2882 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2887 * ext4_file_write() -> generic_file_write() -> __alloc_pages() -> ...
2889 * Same applies to ext4_get_block(). We will deadlock on various things like
2890 * lock_journal and i_data_sem
2892 * Setting PF_MEMALLOC here doesn't work - too many internal memory
2895 * 16May01: If we're reentered then journal_current_handle() will be
2896 * non-zero. We simply *return*.
2898 * 1 July 2001: @@@ FIXME:
2899 * In journalled data mode, a data buffer may be metadata against the
2900 * current transaction. But the same file is part of a shared mapping
2901 * and someone does a writepage() on it.
2903 * We will move the buffer onto the async_data list, but *after* it has
2904 * been dirtied. So there's a small window where we have dirty data on
2907 * Note that this only applies to the last partial page in the file. The
2908 * bit which block_write_full_page() uses prepare/commit for. (That's
2909 * broken code anyway: it's wrong for msync()).
2911 * It's a rare case: affects the final partial page, for journalled data
2912 * where the file is subject to bith write() and writepage() in the same
2913 * transction. To fix it we'll need a custom block_write_full_page().
2914 * We'll probably need that anyway for journalling writepage() output.
2916 * We don't honour synchronous mounts for writepage(). That would be
2917 * disastrous. Any write() or metadata operation will sync the fs for
2921 static int __ext4_normal_writepage(struct page
*page
,
2922 struct writeback_control
*wbc
)
2924 struct inode
*inode
= page
->mapping
->host
;
2926 if (test_opt(inode
->i_sb
, NOBH
))
2927 return nobh_writepage(page
,
2928 ext4_normal_get_block_write
, wbc
);
2930 return block_write_full_page(page
,
2931 ext4_normal_get_block_write
,
2935 static int ext4_normal_writepage(struct page
*page
,
2936 struct writeback_control
*wbc
)
2938 struct inode
*inode
= page
->mapping
->host
;
2939 loff_t size
= i_size_read(inode
);
2942 trace_mark(ext4_normal_writepage
,
2943 "dev %s ino %lu page_index %lu",
2944 inode
->i_sb
->s_id
, inode
->i_ino
, page
->index
);
2945 J_ASSERT(PageLocked(page
));
2946 if (page
->index
== size
>> PAGE_CACHE_SHIFT
)
2947 len
= size
& ~PAGE_CACHE_MASK
;
2949 len
= PAGE_CACHE_SIZE
;
2951 if (page_has_buffers(page
)) {
2952 /* if page has buffers it should all be mapped
2953 * and allocated. If there are not buffers attached
2954 * to the page we know the page is dirty but it lost
2955 * buffers. That means that at some moment in time
2956 * after write_begin() / write_end() has been called
2957 * all buffers have been clean and thus they must have been
2958 * written at least once. So they are all mapped and we can
2959 * happily proceed with mapping them and writing the page.
2961 BUG_ON(walk_page_buffers(NULL
, page_buffers(page
), 0, len
, NULL
,
2962 ext4_bh_unmapped_or_delay
));
2965 if (!ext4_journal_current_handle())
2966 return __ext4_normal_writepage(page
, wbc
);
2968 redirty_page_for_writepage(wbc
, page
);
2973 static int __ext4_journalled_writepage(struct page
*page
,
2974 struct writeback_control
*wbc
)
2976 struct address_space
*mapping
= page
->mapping
;
2977 struct inode
*inode
= mapping
->host
;
2978 struct buffer_head
*page_bufs
;
2979 handle_t
*handle
= NULL
;
2983 ret
= block_prepare_write(page
, 0, PAGE_CACHE_SIZE
,
2984 ext4_normal_get_block_write
);
2988 page_bufs
= page_buffers(page
);
2989 walk_page_buffers(handle
, page_bufs
, 0, PAGE_CACHE_SIZE
, NULL
,
2991 /* As soon as we unlock the page, it can go away, but we have
2992 * references to buffers so we are safe */
2995 handle
= ext4_journal_start(inode
, ext4_writepage_trans_blocks(inode
));
2996 if (IS_ERR(handle
)) {
2997 ret
= PTR_ERR(handle
);
3001 ret
= walk_page_buffers(handle
, page_bufs
, 0,
3002 PAGE_CACHE_SIZE
, NULL
, do_journal_get_write_access
);
3004 err
= walk_page_buffers(handle
, page_bufs
, 0,
3005 PAGE_CACHE_SIZE
, NULL
, write_end_fn
);
3008 err
= ext4_journal_stop(handle
);
3012 walk_page_buffers(handle
, page_bufs
, 0,
3013 PAGE_CACHE_SIZE
, NULL
, bput_one
);
3014 EXT4_I(inode
)->i_state
|= EXT4_STATE_JDATA
;
3023 static int ext4_journalled_writepage(struct page
*page
,
3024 struct writeback_control
*wbc
)
3026 struct inode
*inode
= page
->mapping
->host
;
3027 loff_t size
= i_size_read(inode
);
3030 trace_mark(ext4_journalled_writepage
,
3031 "dev %s ino %lu page_index %lu",
3032 inode
->i_sb
->s_id
, inode
->i_ino
, page
->index
);
3033 J_ASSERT(PageLocked(page
));
3034 if (page
->index
== size
>> PAGE_CACHE_SHIFT
)
3035 len
= size
& ~PAGE_CACHE_MASK
;
3037 len
= PAGE_CACHE_SIZE
;
3039 if (page_has_buffers(page
)) {
3040 /* if page has buffers it should all be mapped
3041 * and allocated. If there are not buffers attached
3042 * to the page we know the page is dirty but it lost
3043 * buffers. That means that at some moment in time
3044 * after write_begin() / write_end() has been called
3045 * all buffers have been clean and thus they must have been
3046 * written at least once. So they are all mapped and we can
3047 * happily proceed with mapping them and writing the page.
3049 BUG_ON(walk_page_buffers(NULL
, page_buffers(page
), 0, len
, NULL
,
3050 ext4_bh_unmapped_or_delay
));
3053 if (ext4_journal_current_handle())
3056 if (PageChecked(page
)) {
3058 * It's mmapped pagecache. Add buffers and journal it. There
3059 * doesn't seem much point in redirtying the page here.
3061 ClearPageChecked(page
);
3062 return __ext4_journalled_writepage(page
, wbc
);
3065 * It may be a page full of checkpoint-mode buffers. We don't
3066 * really know unless we go poke around in the buffer_heads.
3067 * But block_write_full_page will do the right thing.
3069 return block_write_full_page(page
,
3070 ext4_normal_get_block_write
,
3074 redirty_page_for_writepage(wbc
, page
);
3079 static int ext4_readpage(struct file
*file
, struct page
*page
)
3081 return mpage_readpage(page
, ext4_get_block
);
3085 ext4_readpages(struct file
*file
, struct address_space
*mapping
,
3086 struct list_head
*pages
, unsigned nr_pages
)
3088 return mpage_readpages(mapping
, pages
, nr_pages
, ext4_get_block
);
3091 static void ext4_invalidatepage(struct page
*page
, unsigned long offset
)
3093 journal_t
*journal
= EXT4_JOURNAL(page
->mapping
->host
);
3096 * If it's a full truncate we just forget about the pending dirtying
3099 ClearPageChecked(page
);
3102 jbd2_journal_invalidatepage(journal
, page
, offset
);
3104 block_invalidatepage(page
, offset
);
3107 static int ext4_releasepage(struct page
*page
, gfp_t wait
)
3109 journal_t
*journal
= EXT4_JOURNAL(page
->mapping
->host
);
3111 WARN_ON(PageChecked(page
));
3112 if (!page_has_buffers(page
))
3115 return jbd2_journal_try_to_free_buffers(journal
, page
, wait
);
3117 return try_to_free_buffers(page
);
3121 * If the O_DIRECT write will extend the file then add this inode to the
3122 * orphan list. So recovery will truncate it back to the original size
3123 * if the machine crashes during the write.
3125 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3126 * crashes then stale disk data _may_ be exposed inside the file. But current
3127 * VFS code falls back into buffered path in that case so we are safe.
3129 static ssize_t
ext4_direct_IO(int rw
, struct kiocb
*iocb
,
3130 const struct iovec
*iov
, loff_t offset
,
3131 unsigned long nr_segs
)
3133 struct file
*file
= iocb
->ki_filp
;
3134 struct inode
*inode
= file
->f_mapping
->host
;
3135 struct ext4_inode_info
*ei
= EXT4_I(inode
);
3139 size_t count
= iov_length(iov
, nr_segs
);
3142 loff_t final_size
= offset
+ count
;
3144 if (final_size
> inode
->i_size
) {
3145 /* Credits for sb + inode write */
3146 handle
= ext4_journal_start(inode
, 2);
3147 if (IS_ERR(handle
)) {
3148 ret
= PTR_ERR(handle
);
3151 ret
= ext4_orphan_add(handle
, inode
);
3153 ext4_journal_stop(handle
);
3157 ei
->i_disksize
= inode
->i_size
;
3158 ext4_journal_stop(handle
);
3162 ret
= blockdev_direct_IO(rw
, iocb
, inode
, inode
->i_sb
->s_bdev
, iov
,
3164 ext4_get_block
, NULL
);
3169 /* Credits for sb + inode write */
3170 handle
= ext4_journal_start(inode
, 2);
3171 if (IS_ERR(handle
)) {
3172 /* This is really bad luck. We've written the data
3173 * but cannot extend i_size. Bail out and pretend
3174 * the write failed... */
3175 ret
= PTR_ERR(handle
);
3179 ext4_orphan_del(handle
, inode
);
3181 loff_t end
= offset
+ ret
;
3182 if (end
> inode
->i_size
) {
3183 ei
->i_disksize
= end
;
3184 i_size_write(inode
, end
);
3186 * We're going to return a positive `ret'
3187 * here due to non-zero-length I/O, so there's
3188 * no way of reporting error returns from
3189 * ext4_mark_inode_dirty() to userspace. So
3192 ext4_mark_inode_dirty(handle
, inode
);
3195 err
= ext4_journal_stop(handle
);
3204 * Pages can be marked dirty completely asynchronously from ext4's journalling
3205 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3206 * much here because ->set_page_dirty is called under VFS locks. The page is
3207 * not necessarily locked.
3209 * We cannot just dirty the page and leave attached buffers clean, because the
3210 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3211 * or jbddirty because all the journalling code will explode.
3213 * So what we do is to mark the page "pending dirty" and next time writepage
3214 * is called, propagate that into the buffers appropriately.
3216 static int ext4_journalled_set_page_dirty(struct page
*page
)
3218 SetPageChecked(page
);
3219 return __set_page_dirty_nobuffers(page
);
3222 static const struct address_space_operations ext4_ordered_aops
= {
3223 .readpage
= ext4_readpage
,
3224 .readpages
= ext4_readpages
,
3225 .writepage
= ext4_normal_writepage
,
3226 .sync_page
= block_sync_page
,
3227 .write_begin
= ext4_write_begin
,
3228 .write_end
= ext4_ordered_write_end
,
3230 .invalidatepage
= ext4_invalidatepage
,
3231 .releasepage
= ext4_releasepage
,
3232 .direct_IO
= ext4_direct_IO
,
3233 .migratepage
= buffer_migrate_page
,
3234 .is_partially_uptodate
= block_is_partially_uptodate
,
3237 static const struct address_space_operations ext4_writeback_aops
= {
3238 .readpage
= ext4_readpage
,
3239 .readpages
= ext4_readpages
,
3240 .writepage
= ext4_normal_writepage
,
3241 .sync_page
= block_sync_page
,
3242 .write_begin
= ext4_write_begin
,
3243 .write_end
= ext4_writeback_write_end
,
3245 .invalidatepage
= ext4_invalidatepage
,
3246 .releasepage
= ext4_releasepage
,
3247 .direct_IO
= ext4_direct_IO
,
3248 .migratepage
= buffer_migrate_page
,
3249 .is_partially_uptodate
= block_is_partially_uptodate
,
3252 static const struct address_space_operations ext4_journalled_aops
= {
3253 .readpage
= ext4_readpage
,
3254 .readpages
= ext4_readpages
,
3255 .writepage
= ext4_journalled_writepage
,
3256 .sync_page
= block_sync_page
,
3257 .write_begin
= ext4_write_begin
,
3258 .write_end
= ext4_journalled_write_end
,
3259 .set_page_dirty
= ext4_journalled_set_page_dirty
,
3261 .invalidatepage
= ext4_invalidatepage
,
3262 .releasepage
= ext4_releasepage
,
3263 .is_partially_uptodate
= block_is_partially_uptodate
,
3266 static const struct address_space_operations ext4_da_aops
= {
3267 .readpage
= ext4_readpage
,
3268 .readpages
= ext4_readpages
,
3269 .writepage
= ext4_da_writepage
,
3270 .writepages
= ext4_da_writepages
,
3271 .sync_page
= block_sync_page
,
3272 .write_begin
= ext4_da_write_begin
,
3273 .write_end
= ext4_da_write_end
,
3275 .invalidatepage
= ext4_da_invalidatepage
,
3276 .releasepage
= ext4_releasepage
,
3277 .direct_IO
= ext4_direct_IO
,
3278 .migratepage
= buffer_migrate_page
,
3279 .is_partially_uptodate
= block_is_partially_uptodate
,
3282 void ext4_set_aops(struct inode
*inode
)
3284 if (ext4_should_order_data(inode
) &&
3285 test_opt(inode
->i_sb
, DELALLOC
))
3286 inode
->i_mapping
->a_ops
= &ext4_da_aops
;
3287 else if (ext4_should_order_data(inode
))
3288 inode
->i_mapping
->a_ops
= &ext4_ordered_aops
;
3289 else if (ext4_should_writeback_data(inode
) &&
3290 test_opt(inode
->i_sb
, DELALLOC
))
3291 inode
->i_mapping
->a_ops
= &ext4_da_aops
;
3292 else if (ext4_should_writeback_data(inode
))
3293 inode
->i_mapping
->a_ops
= &ext4_writeback_aops
;
3295 inode
->i_mapping
->a_ops
= &ext4_journalled_aops
;
3299 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3300 * up to the end of the block which corresponds to `from'.
3301 * This required during truncate. We need to physically zero the tail end
3302 * of that block so it doesn't yield old data if the file is later grown.
3304 int ext4_block_truncate_page(handle_t
*handle
,
3305 struct address_space
*mapping
, loff_t from
)
3307 ext4_fsblk_t index
= from
>> PAGE_CACHE_SHIFT
;
3308 unsigned offset
= from
& (PAGE_CACHE_SIZE
-1);
3309 unsigned blocksize
, length
, pos
;
3311 struct inode
*inode
= mapping
->host
;
3312 struct buffer_head
*bh
;
3316 page
= grab_cache_page(mapping
, from
>> PAGE_CACHE_SHIFT
);
3320 blocksize
= inode
->i_sb
->s_blocksize
;
3321 length
= blocksize
- (offset
& (blocksize
- 1));
3322 iblock
= index
<< (PAGE_CACHE_SHIFT
- inode
->i_sb
->s_blocksize_bits
);
3325 * For "nobh" option, we can only work if we don't need to
3326 * read-in the page - otherwise we create buffers to do the IO.
3328 if (!page_has_buffers(page
) && test_opt(inode
->i_sb
, NOBH
) &&
3329 ext4_should_writeback_data(inode
) && PageUptodate(page
)) {
3330 zero_user(page
, offset
, length
);
3331 set_page_dirty(page
);
3335 if (!page_has_buffers(page
))
3336 create_empty_buffers(page
, blocksize
, 0);
3338 /* Find the buffer that contains "offset" */
3339 bh
= page_buffers(page
);
3341 while (offset
>= pos
) {
3342 bh
= bh
->b_this_page
;
3348 if (buffer_freed(bh
)) {
3349 BUFFER_TRACE(bh
, "freed: skip");
3353 if (!buffer_mapped(bh
)) {
3354 BUFFER_TRACE(bh
, "unmapped");
3355 ext4_get_block(inode
, iblock
, bh
, 0);
3356 /* unmapped? It's a hole - nothing to do */
3357 if (!buffer_mapped(bh
)) {
3358 BUFFER_TRACE(bh
, "still unmapped");
3363 /* Ok, it's mapped. Make sure it's up-to-date */
3364 if (PageUptodate(page
))
3365 set_buffer_uptodate(bh
);
3367 if (!buffer_uptodate(bh
)) {
3369 ll_rw_block(READ
, 1, &bh
);
3371 /* Uhhuh. Read error. Complain and punt. */
3372 if (!buffer_uptodate(bh
))
3376 if (ext4_should_journal_data(inode
)) {
3377 BUFFER_TRACE(bh
, "get write access");
3378 err
= ext4_journal_get_write_access(handle
, bh
);
3383 zero_user(page
, offset
, length
);
3385 BUFFER_TRACE(bh
, "zeroed end of block");
3388 if (ext4_should_journal_data(inode
)) {
3389 err
= ext4_handle_dirty_metadata(handle
, inode
, bh
);
3391 if (ext4_should_order_data(inode
))
3392 err
= ext4_jbd2_file_inode(handle
, inode
);
3393 mark_buffer_dirty(bh
);
3398 page_cache_release(page
);
3403 * Probably it should be a library function... search for first non-zero word
3404 * or memcmp with zero_page, whatever is better for particular architecture.
3407 static inline int all_zeroes(__le32
*p
, __le32
*q
)
3416 * ext4_find_shared - find the indirect blocks for partial truncation.
3417 * @inode: inode in question
3418 * @depth: depth of the affected branch
3419 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
3420 * @chain: place to store the pointers to partial indirect blocks
3421 * @top: place to the (detached) top of branch
3423 * This is a helper function used by ext4_truncate().
3425 * When we do truncate() we may have to clean the ends of several
3426 * indirect blocks but leave the blocks themselves alive. Block is
3427 * partially truncated if some data below the new i_size is refered
3428 * from it (and it is on the path to the first completely truncated
3429 * data block, indeed). We have to free the top of that path along
3430 * with everything to the right of the path. Since no allocation
3431 * past the truncation point is possible until ext4_truncate()
3432 * finishes, we may safely do the latter, but top of branch may
3433 * require special attention - pageout below the truncation point
3434 * might try to populate it.
3436 * We atomically detach the top of branch from the tree, store the
3437 * block number of its root in *@top, pointers to buffer_heads of
3438 * partially truncated blocks - in @chain[].bh and pointers to
3439 * their last elements that should not be removed - in
3440 * @chain[].p. Return value is the pointer to last filled element
3443 * The work left to caller to do the actual freeing of subtrees:
3444 * a) free the subtree starting from *@top
3445 * b) free the subtrees whose roots are stored in
3446 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
3447 * c) free the subtrees growing from the inode past the @chain[0].
3448 * (no partially truncated stuff there). */
3450 static Indirect
*ext4_find_shared(struct inode
*inode
, int depth
,
3451 ext4_lblk_t offsets
[4], Indirect chain
[4], __le32
*top
)
3453 Indirect
*partial
, *p
;
3457 /* Make k index the deepest non-null offest + 1 */
3458 for (k
= depth
; k
> 1 && !offsets
[k
-1]; k
--)
3460 partial
= ext4_get_branch(inode
, k
, offsets
, chain
, &err
);
3461 /* Writer: pointers */
3463 partial
= chain
+ k
-1;
3465 * If the branch acquired continuation since we've looked at it -
3466 * fine, it should all survive and (new) top doesn't belong to us.
3468 if (!partial
->key
&& *partial
->p
)
3471 for (p
= partial
; (p
> chain
) && all_zeroes((__le32
*) p
->bh
->b_data
, p
->p
); p
--)
3474 * OK, we've found the last block that must survive. The rest of our
3475 * branch should be detached before unlocking. However, if that rest
3476 * of branch is all ours and does not grow immediately from the inode
3477 * it's easier to cheat and just decrement partial->p.
3479 if (p
== chain
+ k
- 1 && p
> chain
) {
3483 /* Nope, don't do this in ext4. Must leave the tree intact */
3490 while (partial
> p
) {
3491 brelse(partial
->bh
);
3499 * Zero a number of block pointers in either an inode or an indirect block.
3500 * If we restart the transaction we must again get write access to the
3501 * indirect block for further modification.
3503 * We release `count' blocks on disk, but (last - first) may be greater
3504 * than `count' because there can be holes in there.
3506 static void ext4_clear_blocks(handle_t
*handle
, struct inode
*inode
,
3507 struct buffer_head
*bh
, ext4_fsblk_t block_to_free
,
3508 unsigned long count
, __le32
*first
, __le32
*last
)
3511 if (try_to_extend_transaction(handle
, inode
)) {
3513 BUFFER_TRACE(bh
, "call ext4_handle_dirty_metadata");
3514 ext4_handle_dirty_metadata(handle
, inode
, bh
);
3516 ext4_mark_inode_dirty(handle
, inode
);
3517 ext4_journal_test_restart(handle
, inode
);
3519 BUFFER_TRACE(bh
, "retaking write access");
3520 ext4_journal_get_write_access(handle
, bh
);
3525 * Any buffers which are on the journal will be in memory. We find
3526 * them on the hash table so jbd2_journal_revoke() will run jbd2_journal_forget()
3527 * on them. We've already detached each block from the file, so
3528 * bforget() in jbd2_journal_forget() should be safe.
3530 * AKPM: turn on bforget in jbd2_journal_forget()!!!
3532 for (p
= first
; p
< last
; p
++) {
3533 u32 nr
= le32_to_cpu(*p
);
3535 struct buffer_head
*tbh
;
3538 tbh
= sb_find_get_block(inode
->i_sb
, nr
);
3539 ext4_forget(handle
, 0, inode
, tbh
, nr
);
3543 ext4_free_blocks(handle
, inode
, block_to_free
, count
, 0);
3547 * ext4_free_data - free a list of data blocks
3548 * @handle: handle for this transaction
3549 * @inode: inode we are dealing with
3550 * @this_bh: indirect buffer_head which contains *@first and *@last
3551 * @first: array of block numbers
3552 * @last: points immediately past the end of array
3554 * We are freeing all blocks refered from that array (numbers are stored as
3555 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
3557 * We accumulate contiguous runs of blocks to free. Conveniently, if these
3558 * blocks are contiguous then releasing them at one time will only affect one
3559 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
3560 * actually use a lot of journal space.
3562 * @this_bh will be %NULL if @first and @last point into the inode's direct
3565 static void ext4_free_data(handle_t
*handle
, struct inode
*inode
,
3566 struct buffer_head
*this_bh
,
3567 __le32
*first
, __le32
*last
)
3569 ext4_fsblk_t block_to_free
= 0; /* Starting block # of a run */
3570 unsigned long count
= 0; /* Number of blocks in the run */
3571 __le32
*block_to_free_p
= NULL
; /* Pointer into inode/ind
3574 ext4_fsblk_t nr
; /* Current block # */
3575 __le32
*p
; /* Pointer into inode/ind
3576 for current block */
3579 if (this_bh
) { /* For indirect block */
3580 BUFFER_TRACE(this_bh
, "get_write_access");
3581 err
= ext4_journal_get_write_access(handle
, this_bh
);
3582 /* Important: if we can't update the indirect pointers
3583 * to the blocks, we can't free them. */
3588 for (p
= first
; p
< last
; p
++) {
3589 nr
= le32_to_cpu(*p
);
3591 /* accumulate blocks to free if they're contiguous */
3594 block_to_free_p
= p
;
3596 } else if (nr
== block_to_free
+ count
) {
3599 ext4_clear_blocks(handle
, inode
, this_bh
,
3601 count
, block_to_free_p
, p
);
3603 block_to_free_p
= p
;
3610 ext4_clear_blocks(handle
, inode
, this_bh
, block_to_free
,
3611 count
, block_to_free_p
, p
);
3614 BUFFER_TRACE(this_bh
, "call ext4_handle_dirty_metadata");
3617 * The buffer head should have an attached journal head at this
3618 * point. However, if the data is corrupted and an indirect
3619 * block pointed to itself, it would have been detached when
3620 * the block was cleared. Check for this instead of OOPSing.
3622 if ((EXT4_JOURNAL(inode
) == NULL
) || bh2jh(this_bh
))
3623 ext4_handle_dirty_metadata(handle
, inode
, this_bh
);
3625 ext4_error(inode
->i_sb
, __func__
,
3626 "circular indirect block detected, "
3627 "inode=%lu, block=%llu",
3629 (unsigned long long) this_bh
->b_blocknr
);
3634 * ext4_free_branches - free an array of branches
3635 * @handle: JBD handle for this transaction
3636 * @inode: inode we are dealing with
3637 * @parent_bh: the buffer_head which contains *@first and *@last
3638 * @first: array of block numbers
3639 * @last: pointer immediately past the end of array
3640 * @depth: depth of the branches to free
3642 * We are freeing all blocks refered from these branches (numbers are
3643 * stored as little-endian 32-bit) and updating @inode->i_blocks
3646 static void ext4_free_branches(handle_t
*handle
, struct inode
*inode
,
3647 struct buffer_head
*parent_bh
,
3648 __le32
*first
, __le32
*last
, int depth
)
3653 if (ext4_handle_is_aborted(handle
))
3657 struct buffer_head
*bh
;
3658 int addr_per_block
= EXT4_ADDR_PER_BLOCK(inode
->i_sb
);
3660 while (--p
>= first
) {
3661 nr
= le32_to_cpu(*p
);
3663 continue; /* A hole */
3665 /* Go read the buffer for the next level down */
3666 bh
= sb_bread(inode
->i_sb
, nr
);
3669 * A read failure? Report error and clear slot
3673 ext4_error(inode
->i_sb
, "ext4_free_branches",
3674 "Read failure, inode=%lu, block=%llu",
3679 /* This zaps the entire block. Bottom up. */
3680 BUFFER_TRACE(bh
, "free child branches");
3681 ext4_free_branches(handle
, inode
, bh
,
3682 (__le32
*) bh
->b_data
,
3683 (__le32
*) bh
->b_data
+ addr_per_block
,
3687 * We've probably journalled the indirect block several
3688 * times during the truncate. But it's no longer
3689 * needed and we now drop it from the transaction via
3690 * jbd2_journal_revoke().
3692 * That's easy if it's exclusively part of this
3693 * transaction. But if it's part of the committing
3694 * transaction then jbd2_journal_forget() will simply
3695 * brelse() it. That means that if the underlying
3696 * block is reallocated in ext4_get_block(),
3697 * unmap_underlying_metadata() will find this block
3698 * and will try to get rid of it. damn, damn.
3700 * If this block has already been committed to the
3701 * journal, a revoke record will be written. And
3702 * revoke records must be emitted *before* clearing
3703 * this block's bit in the bitmaps.
3705 ext4_forget(handle
, 1, inode
, bh
, bh
->b_blocknr
);
3708 * Everything below this this pointer has been
3709 * released. Now let this top-of-subtree go.
3711 * We want the freeing of this indirect block to be
3712 * atomic in the journal with the updating of the
3713 * bitmap block which owns it. So make some room in
3716 * We zero the parent pointer *after* freeing its
3717 * pointee in the bitmaps, so if extend_transaction()
3718 * for some reason fails to put the bitmap changes and
3719 * the release into the same transaction, recovery
3720 * will merely complain about releasing a free block,
3721 * rather than leaking blocks.
3723 if (ext4_handle_is_aborted(handle
))
3725 if (try_to_extend_transaction(handle
, inode
)) {
3726 ext4_mark_inode_dirty(handle
, inode
);
3727 ext4_journal_test_restart(handle
, inode
);
3730 ext4_free_blocks(handle
, inode
, nr
, 1, 1);
3734 * The block which we have just freed is
3735 * pointed to by an indirect block: journal it
3737 BUFFER_TRACE(parent_bh
, "get_write_access");
3738 if (!ext4_journal_get_write_access(handle
,
3741 BUFFER_TRACE(parent_bh
,
3742 "call ext4_handle_dirty_metadata");
3743 ext4_handle_dirty_metadata(handle
,
3750 /* We have reached the bottom of the tree. */
3751 BUFFER_TRACE(parent_bh
, "free data blocks");
3752 ext4_free_data(handle
, inode
, parent_bh
, first
, last
);
3756 int ext4_can_truncate(struct inode
*inode
)
3758 if (IS_APPEND(inode
) || IS_IMMUTABLE(inode
))
3760 if (S_ISREG(inode
->i_mode
))
3762 if (S_ISDIR(inode
->i_mode
))
3764 if (S_ISLNK(inode
->i_mode
))
3765 return !ext4_inode_is_fast_symlink(inode
);
3772 * We block out ext4_get_block() block instantiations across the entire
3773 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3774 * simultaneously on behalf of the same inode.
3776 * As we work through the truncate and commmit bits of it to the journal there
3777 * is one core, guiding principle: the file's tree must always be consistent on
3778 * disk. We must be able to restart the truncate after a crash.
3780 * The file's tree may be transiently inconsistent in memory (although it
3781 * probably isn't), but whenever we close off and commit a journal transaction,
3782 * the contents of (the filesystem + the journal) must be consistent and
3783 * restartable. It's pretty simple, really: bottom up, right to left (although
3784 * left-to-right works OK too).
3786 * Note that at recovery time, journal replay occurs *before* the restart of
3787 * truncate against the orphan inode list.
3789 * The committed inode has the new, desired i_size (which is the same as
3790 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3791 * that this inode's truncate did not complete and it will again call
3792 * ext4_truncate() to have another go. So there will be instantiated blocks
3793 * to the right of the truncation point in a crashed ext4 filesystem. But
3794 * that's fine - as long as they are linked from the inode, the post-crash
3795 * ext4_truncate() run will find them and release them.
3797 void ext4_truncate(struct inode
*inode
)
3800 struct ext4_inode_info
*ei
= EXT4_I(inode
);
3801 __le32
*i_data
= ei
->i_data
;
3802 int addr_per_block
= EXT4_ADDR_PER_BLOCK(inode
->i_sb
);
3803 struct address_space
*mapping
= inode
->i_mapping
;
3804 ext4_lblk_t offsets
[4];
3809 ext4_lblk_t last_block
;
3810 unsigned blocksize
= inode
->i_sb
->s_blocksize
;
3812 if (!ext4_can_truncate(inode
))
3815 if (EXT4_I(inode
)->i_flags
& EXT4_EXTENTS_FL
) {
3816 ext4_ext_truncate(inode
);
3820 handle
= start_transaction(inode
);
3822 return; /* AKPM: return what? */
3824 last_block
= (inode
->i_size
+ blocksize
-1)
3825 >> EXT4_BLOCK_SIZE_BITS(inode
->i_sb
);
3827 if (inode
->i_size
& (blocksize
- 1))
3828 if (ext4_block_truncate_page(handle
, mapping
, inode
->i_size
))
3831 n
= ext4_block_to_path(inode
, last_block
, offsets
, NULL
);
3833 goto out_stop
; /* error */
3836 * OK. This truncate is going to happen. We add the inode to the
3837 * orphan list, so that if this truncate spans multiple transactions,
3838 * and we crash, we will resume the truncate when the filesystem
3839 * recovers. It also marks the inode dirty, to catch the new size.
3841 * Implication: the file must always be in a sane, consistent
3842 * truncatable state while each transaction commits.
3844 if (ext4_orphan_add(handle
, inode
))
3848 * From here we block out all ext4_get_block() callers who want to
3849 * modify the block allocation tree.
3851 down_write(&ei
->i_data_sem
);
3853 ext4_discard_preallocations(inode
);
3856 * The orphan list entry will now protect us from any crash which
3857 * occurs before the truncate completes, so it is now safe to propagate
3858 * the new, shorter inode size (held for now in i_size) into the
3859 * on-disk inode. We do this via i_disksize, which is the value which
3860 * ext4 *really* writes onto the disk inode.
3862 ei
->i_disksize
= inode
->i_size
;
3864 if (n
== 1) { /* direct blocks */
3865 ext4_free_data(handle
, inode
, NULL
, i_data
+offsets
[0],
3866 i_data
+ EXT4_NDIR_BLOCKS
);
3870 partial
= ext4_find_shared(inode
, n
, offsets
, chain
, &nr
);
3871 /* Kill the top of shared branch (not detached) */
3873 if (partial
== chain
) {
3874 /* Shared branch grows from the inode */
3875 ext4_free_branches(handle
, inode
, NULL
,
3876 &nr
, &nr
+1, (chain
+n
-1) - partial
);
3879 * We mark the inode dirty prior to restart,
3880 * and prior to stop. No need for it here.
3883 /* Shared branch grows from an indirect block */
3884 BUFFER_TRACE(partial
->bh
, "get_write_access");
3885 ext4_free_branches(handle
, inode
, partial
->bh
,
3887 partial
->p
+1, (chain
+n
-1) - partial
);
3890 /* Clear the ends of indirect blocks on the shared branch */
3891 while (partial
> chain
) {
3892 ext4_free_branches(handle
, inode
, partial
->bh
, partial
->p
+ 1,
3893 (__le32
*)partial
->bh
->b_data
+addr_per_block
,
3894 (chain
+n
-1) - partial
);
3895 BUFFER_TRACE(partial
->bh
, "call brelse");
3896 brelse (partial
->bh
);
3900 /* Kill the remaining (whole) subtrees */
3901 switch (offsets
[0]) {
3903 nr
= i_data
[EXT4_IND_BLOCK
];
3905 ext4_free_branches(handle
, inode
, NULL
, &nr
, &nr
+1, 1);
3906 i_data
[EXT4_IND_BLOCK
] = 0;
3908 case EXT4_IND_BLOCK
:
3909 nr
= i_data
[EXT4_DIND_BLOCK
];
3911 ext4_free_branches(handle
, inode
, NULL
, &nr
, &nr
+1, 2);
3912 i_data
[EXT4_DIND_BLOCK
] = 0;
3914 case EXT4_DIND_BLOCK
:
3915 nr
= i_data
[EXT4_TIND_BLOCK
];
3917 ext4_free_branches(handle
, inode
, NULL
, &nr
, &nr
+1, 3);
3918 i_data
[EXT4_TIND_BLOCK
] = 0;
3920 case EXT4_TIND_BLOCK
:
3924 up_write(&ei
->i_data_sem
);
3925 inode
->i_mtime
= inode
->i_ctime
= ext4_current_time(inode
);
3926 ext4_mark_inode_dirty(handle
, inode
);
3929 * In a multi-transaction truncate, we only make the final transaction
3933 ext4_handle_sync(handle
);
3936 * If this was a simple ftruncate(), and the file will remain alive
3937 * then we need to clear up the orphan record which we created above.
3938 * However, if this was a real unlink then we were called by
3939 * ext4_delete_inode(), and we allow that function to clean up the
3940 * orphan info for us.
3943 ext4_orphan_del(handle
, inode
);
3945 ext4_journal_stop(handle
);
3949 * ext4_get_inode_loc returns with an extra refcount against the inode's
3950 * underlying buffer_head on success. If 'in_mem' is true, we have all
3951 * data in memory that is needed to recreate the on-disk version of this
3954 static int __ext4_get_inode_loc(struct inode
*inode
,
3955 struct ext4_iloc
*iloc
, int in_mem
)
3957 struct ext4_group_desc
*gdp
;
3958 struct buffer_head
*bh
;
3959 struct super_block
*sb
= inode
->i_sb
;
3961 int inodes_per_block
, inode_offset
;
3964 if (!ext4_valid_inum(sb
, inode
->i_ino
))
3967 iloc
->block_group
= (inode
->i_ino
- 1) / EXT4_INODES_PER_GROUP(sb
);
3968 gdp
= ext4_get_group_desc(sb
, iloc
->block_group
, NULL
);
3973 * Figure out the offset within the block group inode table
3975 inodes_per_block
= (EXT4_BLOCK_SIZE(sb
) / EXT4_INODE_SIZE(sb
));
3976 inode_offset
= ((inode
->i_ino
- 1) %
3977 EXT4_INODES_PER_GROUP(sb
));
3978 block
= ext4_inode_table(sb
, gdp
) + (inode_offset
/ inodes_per_block
);
3979 iloc
->offset
= (inode_offset
% inodes_per_block
) * EXT4_INODE_SIZE(sb
);
3981 bh
= sb_getblk(sb
, block
);
3983 ext4_error(sb
, "ext4_get_inode_loc", "unable to read "
3984 "inode block - inode=%lu, block=%llu",
3985 inode
->i_ino
, block
);
3988 if (!buffer_uptodate(bh
)) {
3992 * If the buffer has the write error flag, we have failed
3993 * to write out another inode in the same block. In this
3994 * case, we don't have to read the block because we may
3995 * read the old inode data successfully.
3997 if (buffer_write_io_error(bh
) && !buffer_uptodate(bh
))
3998 set_buffer_uptodate(bh
);
4000 if (buffer_uptodate(bh
)) {
4001 /* someone brought it uptodate while we waited */
4007 * If we have all information of the inode in memory and this
4008 * is the only valid inode in the block, we need not read the
4012 struct buffer_head
*bitmap_bh
;
4015 start
= inode_offset
& ~(inodes_per_block
- 1);
4017 /* Is the inode bitmap in cache? */
4018 bitmap_bh
= sb_getblk(sb
, ext4_inode_bitmap(sb
, gdp
));
4023 * If the inode bitmap isn't in cache then the
4024 * optimisation may end up performing two reads instead
4025 * of one, so skip it.
4027 if (!buffer_uptodate(bitmap_bh
)) {
4031 for (i
= start
; i
< start
+ inodes_per_block
; i
++) {
4032 if (i
== inode_offset
)
4034 if (ext4_test_bit(i
, bitmap_bh
->b_data
))
4038 if (i
== start
+ inodes_per_block
) {
4039 /* all other inodes are free, so skip I/O */
4040 memset(bh
->b_data
, 0, bh
->b_size
);
4041 set_buffer_uptodate(bh
);
4049 * If we need to do any I/O, try to pre-readahead extra
4050 * blocks from the inode table.
4052 if (EXT4_SB(sb
)->s_inode_readahead_blks
) {
4053 ext4_fsblk_t b
, end
, table
;
4056 table
= ext4_inode_table(sb
, gdp
);
4057 /* Make sure s_inode_readahead_blks is a power of 2 */
4058 while (EXT4_SB(sb
)->s_inode_readahead_blks
&
4059 (EXT4_SB(sb
)->s_inode_readahead_blks
-1))
4060 EXT4_SB(sb
)->s_inode_readahead_blks
=
4061 (EXT4_SB(sb
)->s_inode_readahead_blks
&
4062 (EXT4_SB(sb
)->s_inode_readahead_blks
-1));
4063 b
= block
& ~(EXT4_SB(sb
)->s_inode_readahead_blks
-1);
4066 end
= b
+ EXT4_SB(sb
)->s_inode_readahead_blks
;
4067 num
= EXT4_INODES_PER_GROUP(sb
);
4068 if (EXT4_HAS_RO_COMPAT_FEATURE(sb
,
4069 EXT4_FEATURE_RO_COMPAT_GDT_CSUM
))
4070 num
-= ext4_itable_unused_count(sb
, gdp
);
4071 table
+= num
/ inodes_per_block
;
4075 sb_breadahead(sb
, b
++);
4079 * There are other valid inodes in the buffer, this inode
4080 * has in-inode xattrs, or we don't have this inode in memory.
4081 * Read the block from disk.
4084 bh
->b_end_io
= end_buffer_read_sync
;
4085 submit_bh(READ_META
, bh
);
4087 if (!buffer_uptodate(bh
)) {
4088 ext4_error(sb
, __func__
,
4089 "unable to read inode block - inode=%lu, "
4090 "block=%llu", inode
->i_ino
, block
);
4100 int ext4_get_inode_loc(struct inode
*inode
, struct ext4_iloc
*iloc
)
4102 /* We have all inode data except xattrs in memory here. */
4103 return __ext4_get_inode_loc(inode
, iloc
,
4104 !(EXT4_I(inode
)->i_state
& EXT4_STATE_XATTR
));
4107 void ext4_set_inode_flags(struct inode
*inode
)
4109 unsigned int flags
= EXT4_I(inode
)->i_flags
;
4111 inode
->i_flags
&= ~(S_SYNC
|S_APPEND
|S_IMMUTABLE
|S_NOATIME
|S_DIRSYNC
);
4112 if (flags
& EXT4_SYNC_FL
)
4113 inode
->i_flags
|= S_SYNC
;
4114 if (flags
& EXT4_APPEND_FL
)
4115 inode
->i_flags
|= S_APPEND
;
4116 if (flags
& EXT4_IMMUTABLE_FL
)
4117 inode
->i_flags
|= S_IMMUTABLE
;
4118 if (flags
& EXT4_NOATIME_FL
)
4119 inode
->i_flags
|= S_NOATIME
;
4120 if (flags
& EXT4_DIRSYNC_FL
)
4121 inode
->i_flags
|= S_DIRSYNC
;
4124 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4125 void ext4_get_inode_flags(struct ext4_inode_info
*ei
)
4127 unsigned int flags
= ei
->vfs_inode
.i_flags
;
4129 ei
->i_flags
&= ~(EXT4_SYNC_FL
|EXT4_APPEND_FL
|
4130 EXT4_IMMUTABLE_FL
|EXT4_NOATIME_FL
|EXT4_DIRSYNC_FL
);
4132 ei
->i_flags
|= EXT4_SYNC_FL
;
4133 if (flags
& S_APPEND
)
4134 ei
->i_flags
|= EXT4_APPEND_FL
;
4135 if (flags
& S_IMMUTABLE
)
4136 ei
->i_flags
|= EXT4_IMMUTABLE_FL
;
4137 if (flags
& S_NOATIME
)
4138 ei
->i_flags
|= EXT4_NOATIME_FL
;
4139 if (flags
& S_DIRSYNC
)
4140 ei
->i_flags
|= EXT4_DIRSYNC_FL
;
4142 static blkcnt_t
ext4_inode_blocks(struct ext4_inode
*raw_inode
,
4143 struct ext4_inode_info
*ei
)
4146 struct inode
*inode
= &(ei
->vfs_inode
);
4147 struct super_block
*sb
= inode
->i_sb
;
4149 if (EXT4_HAS_RO_COMPAT_FEATURE(sb
,
4150 EXT4_FEATURE_RO_COMPAT_HUGE_FILE
)) {
4151 /* we are using combined 48 bit field */
4152 i_blocks
= ((u64
)le16_to_cpu(raw_inode
->i_blocks_high
)) << 32 |
4153 le32_to_cpu(raw_inode
->i_blocks_lo
);
4154 if (ei
->i_flags
& EXT4_HUGE_FILE_FL
) {
4155 /* i_blocks represent file system block size */
4156 return i_blocks
<< (inode
->i_blkbits
- 9);
4161 return le32_to_cpu(raw_inode
->i_blocks_lo
);
4165 struct inode
*ext4_iget(struct super_block
*sb
, unsigned long ino
)
4167 struct ext4_iloc iloc
;
4168 struct ext4_inode
*raw_inode
;
4169 struct ext4_inode_info
*ei
;
4170 struct buffer_head
*bh
;
4171 struct inode
*inode
;
4175 inode
= iget_locked(sb
, ino
);
4177 return ERR_PTR(-ENOMEM
);
4178 if (!(inode
->i_state
& I_NEW
))
4182 #ifdef CONFIG_EXT4_FS_POSIX_ACL
4183 ei
->i_acl
= EXT4_ACL_NOT_CACHED
;
4184 ei
->i_default_acl
= EXT4_ACL_NOT_CACHED
;
4187 ret
= __ext4_get_inode_loc(inode
, &iloc
, 0);
4191 raw_inode
= ext4_raw_inode(&iloc
);
4192 inode
->i_mode
= le16_to_cpu(raw_inode
->i_mode
);
4193 inode
->i_uid
= (uid_t
)le16_to_cpu(raw_inode
->i_uid_low
);
4194 inode
->i_gid
= (gid_t
)le16_to_cpu(raw_inode
->i_gid_low
);
4195 if (!(test_opt(inode
->i_sb
, NO_UID32
))) {
4196 inode
->i_uid
|= le16_to_cpu(raw_inode
->i_uid_high
) << 16;
4197 inode
->i_gid
|= le16_to_cpu(raw_inode
->i_gid_high
) << 16;
4199 inode
->i_nlink
= le16_to_cpu(raw_inode
->i_links_count
);
4202 ei
->i_dir_start_lookup
= 0;
4203 ei
->i_dtime
= le32_to_cpu(raw_inode
->i_dtime
);
4204 /* We now have enough fields to check if the inode was active or not.
4205 * This is needed because nfsd might try to access dead inodes
4206 * the test is that same one that e2fsck uses
4207 * NeilBrown 1999oct15
4209 if (inode
->i_nlink
== 0) {
4210 if (inode
->i_mode
== 0 ||
4211 !(EXT4_SB(inode
->i_sb
)->s_mount_state
& EXT4_ORPHAN_FS
)) {
4212 /* this inode is deleted */
4217 /* The only unlinked inodes we let through here have
4218 * valid i_mode and are being read by the orphan
4219 * recovery code: that's fine, we're about to complete
4220 * the process of deleting those. */
4222 ei
->i_flags
= le32_to_cpu(raw_inode
->i_flags
);
4223 inode
->i_blocks
= ext4_inode_blocks(raw_inode
, ei
);
4224 ei
->i_file_acl
= le32_to_cpu(raw_inode
->i_file_acl_lo
);
4225 if (EXT4_SB(inode
->i_sb
)->s_es
->s_creator_os
!=
4226 cpu_to_le32(EXT4_OS_HURD
)) {
4228 ((__u64
)le16_to_cpu(raw_inode
->i_file_acl_high
)) << 32;
4230 inode
->i_size
= ext4_isize(raw_inode
);
4231 ei
->i_disksize
= inode
->i_size
;
4232 inode
->i_generation
= le32_to_cpu(raw_inode
->i_generation
);
4233 ei
->i_block_group
= iloc
.block_group
;
4235 * NOTE! The in-memory inode i_data array is in little-endian order
4236 * even on big-endian machines: we do NOT byteswap the block numbers!
4238 for (block
= 0; block
< EXT4_N_BLOCKS
; block
++)
4239 ei
->i_data
[block
] = raw_inode
->i_block
[block
];
4240 INIT_LIST_HEAD(&ei
->i_orphan
);
4242 if (EXT4_INODE_SIZE(inode
->i_sb
) > EXT4_GOOD_OLD_INODE_SIZE
) {
4243 ei
->i_extra_isize
= le16_to_cpu(raw_inode
->i_extra_isize
);
4244 if (EXT4_GOOD_OLD_INODE_SIZE
+ ei
->i_extra_isize
>
4245 EXT4_INODE_SIZE(inode
->i_sb
)) {
4250 if (ei
->i_extra_isize
== 0) {
4251 /* The extra space is currently unused. Use it. */
4252 ei
->i_extra_isize
= sizeof(struct ext4_inode
) -
4253 EXT4_GOOD_OLD_INODE_SIZE
;
4255 __le32
*magic
= (void *)raw_inode
+
4256 EXT4_GOOD_OLD_INODE_SIZE
+
4258 if (*magic
== cpu_to_le32(EXT4_XATTR_MAGIC
))
4259 ei
->i_state
|= EXT4_STATE_XATTR
;
4262 ei
->i_extra_isize
= 0;
4264 EXT4_INODE_GET_XTIME(i_ctime
, inode
, raw_inode
);
4265 EXT4_INODE_GET_XTIME(i_mtime
, inode
, raw_inode
);
4266 EXT4_INODE_GET_XTIME(i_atime
, inode
, raw_inode
);
4267 EXT4_EINODE_GET_XTIME(i_crtime
, ei
, raw_inode
);
4269 inode
->i_version
= le32_to_cpu(raw_inode
->i_disk_version
);
4270 if (EXT4_INODE_SIZE(inode
->i_sb
) > EXT4_GOOD_OLD_INODE_SIZE
) {
4271 if (EXT4_FITS_IN_INODE(raw_inode
, ei
, i_version_hi
))
4273 (__u64
)(le32_to_cpu(raw_inode
->i_version_hi
)) << 32;
4276 if (S_ISREG(inode
->i_mode
)) {
4277 inode
->i_op
= &ext4_file_inode_operations
;
4278 inode
->i_fop
= &ext4_file_operations
;
4279 ext4_set_aops(inode
);
4280 } else if (S_ISDIR(inode
->i_mode
)) {
4281 inode
->i_op
= &ext4_dir_inode_operations
;
4282 inode
->i_fop
= &ext4_dir_operations
;
4283 } else if (S_ISLNK(inode
->i_mode
)) {
4284 if (ext4_inode_is_fast_symlink(inode
)) {
4285 inode
->i_op
= &ext4_fast_symlink_inode_operations
;
4286 nd_terminate_link(ei
->i_data
, inode
->i_size
,
4287 sizeof(ei
->i_data
) - 1);
4289 inode
->i_op
= &ext4_symlink_inode_operations
;
4290 ext4_set_aops(inode
);
4293 inode
->i_op
= &ext4_special_inode_operations
;
4294 if (raw_inode
->i_block
[0])
4295 init_special_inode(inode
, inode
->i_mode
,
4296 old_decode_dev(le32_to_cpu(raw_inode
->i_block
[0])));
4298 init_special_inode(inode
, inode
->i_mode
,
4299 new_decode_dev(le32_to_cpu(raw_inode
->i_block
[1])));
4302 ext4_set_inode_flags(inode
);
4303 unlock_new_inode(inode
);
4308 return ERR_PTR(ret
);
4311 static int ext4_inode_blocks_set(handle_t
*handle
,
4312 struct ext4_inode
*raw_inode
,
4313 struct ext4_inode_info
*ei
)
4315 struct inode
*inode
= &(ei
->vfs_inode
);
4316 u64 i_blocks
= inode
->i_blocks
;
4317 struct super_block
*sb
= inode
->i_sb
;
4319 if (i_blocks
<= ~0U) {
4321 * i_blocks can be represnted in a 32 bit variable
4322 * as multiple of 512 bytes
4324 raw_inode
->i_blocks_lo
= cpu_to_le32(i_blocks
);
4325 raw_inode
->i_blocks_high
= 0;
4326 ei
->i_flags
&= ~EXT4_HUGE_FILE_FL
;
4329 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb
, EXT4_FEATURE_RO_COMPAT_HUGE_FILE
))
4332 if (i_blocks
<= 0xffffffffffffULL
) {
4334 * i_blocks can be represented in a 48 bit variable
4335 * as multiple of 512 bytes
4337 raw_inode
->i_blocks_lo
= cpu_to_le32(i_blocks
);
4338 raw_inode
->i_blocks_high
= cpu_to_le16(i_blocks
>> 32);
4339 ei
->i_flags
&= ~EXT4_HUGE_FILE_FL
;
4341 ei
->i_flags
|= EXT4_HUGE_FILE_FL
;
4342 /* i_block is stored in file system block size */
4343 i_blocks
= i_blocks
>> (inode
->i_blkbits
- 9);
4344 raw_inode
->i_blocks_lo
= cpu_to_le32(i_blocks
);
4345 raw_inode
->i_blocks_high
= cpu_to_le16(i_blocks
>> 32);
4351 * Post the struct inode info into an on-disk inode location in the
4352 * buffer-cache. This gobbles the caller's reference to the
4353 * buffer_head in the inode location struct.
4355 * The caller must have write access to iloc->bh.
4357 static int ext4_do_update_inode(handle_t
*handle
,
4358 struct inode
*inode
,
4359 struct ext4_iloc
*iloc
)
4361 struct ext4_inode
*raw_inode
= ext4_raw_inode(iloc
);
4362 struct ext4_inode_info
*ei
= EXT4_I(inode
);
4363 struct buffer_head
*bh
= iloc
->bh
;
4364 int err
= 0, rc
, block
;
4366 /* For fields not not tracking in the in-memory inode,
4367 * initialise them to zero for new inodes. */
4368 if (ei
->i_state
& EXT4_STATE_NEW
)
4369 memset(raw_inode
, 0, EXT4_SB(inode
->i_sb
)->s_inode_size
);
4371 ext4_get_inode_flags(ei
);
4372 raw_inode
->i_mode
= cpu_to_le16(inode
->i_mode
);
4373 if (!(test_opt(inode
->i_sb
, NO_UID32
))) {
4374 raw_inode
->i_uid_low
= cpu_to_le16(low_16_bits(inode
->i_uid
));
4375 raw_inode
->i_gid_low
= cpu_to_le16(low_16_bits(inode
->i_gid
));
4377 * Fix up interoperability with old kernels. Otherwise, old inodes get
4378 * re-used with the upper 16 bits of the uid/gid intact
4381 raw_inode
->i_uid_high
=
4382 cpu_to_le16(high_16_bits(inode
->i_uid
));
4383 raw_inode
->i_gid_high
=
4384 cpu_to_le16(high_16_bits(inode
->i_gid
));
4386 raw_inode
->i_uid_high
= 0;
4387 raw_inode
->i_gid_high
= 0;
4390 raw_inode
->i_uid_low
=
4391 cpu_to_le16(fs_high2lowuid(inode
->i_uid
));
4392 raw_inode
->i_gid_low
=
4393 cpu_to_le16(fs_high2lowgid(inode
->i_gid
));
4394 raw_inode
->i_uid_high
= 0;
4395 raw_inode
->i_gid_high
= 0;
4397 raw_inode
->i_links_count
= cpu_to_le16(inode
->i_nlink
);
4399 EXT4_INODE_SET_XTIME(i_ctime
, inode
, raw_inode
);
4400 EXT4_INODE_SET_XTIME(i_mtime
, inode
, raw_inode
);
4401 EXT4_INODE_SET_XTIME(i_atime
, inode
, raw_inode
);
4402 EXT4_EINODE_SET_XTIME(i_crtime
, ei
, raw_inode
);
4404 if (ext4_inode_blocks_set(handle
, raw_inode
, ei
))
4406 raw_inode
->i_dtime
= cpu_to_le32(ei
->i_dtime
);
4407 /* clear the migrate flag in the raw_inode */
4408 raw_inode
->i_flags
= cpu_to_le32(ei
->i_flags
& ~EXT4_EXT_MIGRATE
);
4409 if (EXT4_SB(inode
->i_sb
)->s_es
->s_creator_os
!=
4410 cpu_to_le32(EXT4_OS_HURD
))
4411 raw_inode
->i_file_acl_high
=
4412 cpu_to_le16(ei
->i_file_acl
>> 32);
4413 raw_inode
->i_file_acl_lo
= cpu_to_le32(ei
->i_file_acl
);
4414 ext4_isize_set(raw_inode
, ei
->i_disksize
);
4415 if (ei
->i_disksize
> 0x7fffffffULL
) {
4416 struct super_block
*sb
= inode
->i_sb
;
4417 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb
,
4418 EXT4_FEATURE_RO_COMPAT_LARGE_FILE
) ||
4419 EXT4_SB(sb
)->s_es
->s_rev_level
==
4420 cpu_to_le32(EXT4_GOOD_OLD_REV
)) {
4421 /* If this is the first large file
4422 * created, add a flag to the superblock.
4424 err
= ext4_journal_get_write_access(handle
,
4425 EXT4_SB(sb
)->s_sbh
);
4428 ext4_update_dynamic_rev(sb
);
4429 EXT4_SET_RO_COMPAT_FEATURE(sb
,
4430 EXT4_FEATURE_RO_COMPAT_LARGE_FILE
);
4432 ext4_handle_sync(handle
);
4433 err
= ext4_handle_dirty_metadata(handle
, inode
,
4434 EXT4_SB(sb
)->s_sbh
);
4437 raw_inode
->i_generation
= cpu_to_le32(inode
->i_generation
);
4438 if (S_ISCHR(inode
->i_mode
) || S_ISBLK(inode
->i_mode
)) {
4439 if (old_valid_dev(inode
->i_rdev
)) {
4440 raw_inode
->i_block
[0] =
4441 cpu_to_le32(old_encode_dev(inode
->i_rdev
));
4442 raw_inode
->i_block
[1] = 0;
4444 raw_inode
->i_block
[0] = 0;
4445 raw_inode
->i_block
[1] =
4446 cpu_to_le32(new_encode_dev(inode
->i_rdev
));
4447 raw_inode
->i_block
[2] = 0;
4449 } else for (block
= 0; block
< EXT4_N_BLOCKS
; block
++)
4450 raw_inode
->i_block
[block
] = ei
->i_data
[block
];
4452 raw_inode
->i_disk_version
= cpu_to_le32(inode
->i_version
);
4453 if (ei
->i_extra_isize
) {
4454 if (EXT4_FITS_IN_INODE(raw_inode
, ei
, i_version_hi
))
4455 raw_inode
->i_version_hi
=
4456 cpu_to_le32(inode
->i_version
>> 32);
4457 raw_inode
->i_extra_isize
= cpu_to_le16(ei
->i_extra_isize
);
4460 BUFFER_TRACE(bh
, "call ext4_handle_dirty_metadata");
4461 rc
= ext4_handle_dirty_metadata(handle
, inode
, bh
);
4464 ei
->i_state
&= ~EXT4_STATE_NEW
;
4468 ext4_std_error(inode
->i_sb
, err
);
4473 * ext4_write_inode()
4475 * We are called from a few places:
4477 * - Within generic_file_write() for O_SYNC files.
4478 * Here, there will be no transaction running. We wait for any running
4479 * trasnaction to commit.
4481 * - Within sys_sync(), kupdate and such.
4482 * We wait on commit, if tol to.
4484 * - Within prune_icache() (PF_MEMALLOC == true)
4485 * Here we simply return. We can't afford to block kswapd on the
4488 * In all cases it is actually safe for us to return without doing anything,
4489 * because the inode has been copied into a raw inode buffer in
4490 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4493 * Note that we are absolutely dependent upon all inode dirtiers doing the
4494 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4495 * which we are interested.
4497 * It would be a bug for them to not do this. The code:
4499 * mark_inode_dirty(inode)
4501 * inode->i_size = expr;
4503 * is in error because a kswapd-driven write_inode() could occur while
4504 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4505 * will no longer be on the superblock's dirty inode list.
4507 int ext4_write_inode(struct inode
*inode
, int wait
)
4509 if (current
->flags
& PF_MEMALLOC
)
4512 if (ext4_journal_current_handle()) {
4513 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4521 return ext4_force_commit(inode
->i_sb
);
4524 int __ext4_write_dirty_metadata(struct inode
*inode
, struct buffer_head
*bh
)
4528 mark_buffer_dirty(bh
);
4529 if (inode
&& inode_needs_sync(inode
)) {
4530 sync_dirty_buffer(bh
);
4531 if (buffer_req(bh
) && !buffer_uptodate(bh
)) {
4532 ext4_error(inode
->i_sb
, __func__
,
4533 "IO error syncing inode, "
4534 "inode=%lu, block=%llu",
4536 (unsigned long long)bh
->b_blocknr
);
4546 * Called from notify_change.
4548 * We want to trap VFS attempts to truncate the file as soon as
4549 * possible. In particular, we want to make sure that when the VFS
4550 * shrinks i_size, we put the inode on the orphan list and modify
4551 * i_disksize immediately, so that during the subsequent flushing of
4552 * dirty pages and freeing of disk blocks, we can guarantee that any
4553 * commit will leave the blocks being flushed in an unused state on
4554 * disk. (On recovery, the inode will get truncated and the blocks will
4555 * be freed, so we have a strong guarantee that no future commit will
4556 * leave these blocks visible to the user.)
4558 * Another thing we have to assure is that if we are in ordered mode
4559 * and inode is still attached to the committing transaction, we must
4560 * we start writeout of all the dirty pages which are being truncated.
4561 * This way we are sure that all the data written in the previous
4562 * transaction are already on disk (truncate waits for pages under
4565 * Called with inode->i_mutex down.
4567 int ext4_setattr(struct dentry
*dentry
, struct iattr
*attr
)
4569 struct inode
*inode
= dentry
->d_inode
;
4571 const unsigned int ia_valid
= attr
->ia_valid
;
4573 error
= inode_change_ok(inode
, attr
);
4577 if ((ia_valid
& ATTR_UID
&& attr
->ia_uid
!= inode
->i_uid
) ||
4578 (ia_valid
& ATTR_GID
&& attr
->ia_gid
!= inode
->i_gid
)) {
4581 /* (user+group)*(old+new) structure, inode write (sb,
4582 * inode block, ? - but truncate inode update has it) */
4583 handle
= ext4_journal_start(inode
, 2*(EXT4_QUOTA_INIT_BLOCKS(inode
->i_sb
)+
4584 EXT4_QUOTA_DEL_BLOCKS(inode
->i_sb
))+3);
4585 if (IS_ERR(handle
)) {
4586 error
= PTR_ERR(handle
);
4589 error
= DQUOT_TRANSFER(inode
, attr
) ? -EDQUOT
: 0;
4591 ext4_journal_stop(handle
);
4594 /* Update corresponding info in inode so that everything is in
4595 * one transaction */
4596 if (attr
->ia_valid
& ATTR_UID
)
4597 inode
->i_uid
= attr
->ia_uid
;
4598 if (attr
->ia_valid
& ATTR_GID
)
4599 inode
->i_gid
= attr
->ia_gid
;
4600 error
= ext4_mark_inode_dirty(handle
, inode
);
4601 ext4_journal_stop(handle
);
4604 if (attr
->ia_valid
& ATTR_SIZE
) {
4605 if (!(EXT4_I(inode
)->i_flags
& EXT4_EXTENTS_FL
)) {
4606 struct ext4_sb_info
*sbi
= EXT4_SB(inode
->i_sb
);
4608 if (attr
->ia_size
> sbi
->s_bitmap_maxbytes
) {
4615 if (S_ISREG(inode
->i_mode
) &&
4616 attr
->ia_valid
& ATTR_SIZE
&& attr
->ia_size
< inode
->i_size
) {
4619 handle
= ext4_journal_start(inode
, 3);
4620 if (IS_ERR(handle
)) {
4621 error
= PTR_ERR(handle
);
4625 error
= ext4_orphan_add(handle
, inode
);
4626 EXT4_I(inode
)->i_disksize
= attr
->ia_size
;
4627 rc
= ext4_mark_inode_dirty(handle
, inode
);
4630 ext4_journal_stop(handle
);
4632 if (ext4_should_order_data(inode
)) {
4633 error
= ext4_begin_ordered_truncate(inode
,
4636 /* Do as much error cleanup as possible */
4637 handle
= ext4_journal_start(inode
, 3);
4638 if (IS_ERR(handle
)) {
4639 ext4_orphan_del(NULL
, inode
);
4642 ext4_orphan_del(handle
, inode
);
4643 ext4_journal_stop(handle
);
4649 rc
= inode_setattr(inode
, attr
);
4651 /* If inode_setattr's call to ext4_truncate failed to get a
4652 * transaction handle at all, we need to clean up the in-core
4653 * orphan list manually. */
4655 ext4_orphan_del(NULL
, inode
);
4657 if (!rc
&& (ia_valid
& ATTR_MODE
))
4658 rc
= ext4_acl_chmod(inode
);
4661 ext4_std_error(inode
->i_sb
, error
);
4667 int ext4_getattr(struct vfsmount
*mnt
, struct dentry
*dentry
,
4670 struct inode
*inode
;
4671 unsigned long delalloc_blocks
;
4673 inode
= dentry
->d_inode
;
4674 generic_fillattr(inode
, stat
);
4677 * We can't update i_blocks if the block allocation is delayed
4678 * otherwise in the case of system crash before the real block
4679 * allocation is done, we will have i_blocks inconsistent with
4680 * on-disk file blocks.
4681 * We always keep i_blocks updated together with real
4682 * allocation. But to not confuse with user, stat
4683 * will return the blocks that include the delayed allocation
4684 * blocks for this file.
4686 spin_lock(&EXT4_I(inode
)->i_block_reservation_lock
);
4687 delalloc_blocks
= EXT4_I(inode
)->i_reserved_data_blocks
;
4688 spin_unlock(&EXT4_I(inode
)->i_block_reservation_lock
);
4690 stat
->blocks
+= (delalloc_blocks
<< inode
->i_sb
->s_blocksize_bits
)>>9;
4694 static int ext4_indirect_trans_blocks(struct inode
*inode
, int nrblocks
,
4699 /* if nrblocks are contiguous */
4702 * With N contiguous data blocks, it need at most
4703 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
4704 * 2 dindirect blocks
4707 indirects
= nrblocks
/ EXT4_ADDR_PER_BLOCK(inode
->i_sb
);
4708 return indirects
+ 3;
4711 * if nrblocks are not contiguous, worse case, each block touch
4712 * a indirect block, and each indirect block touch a double indirect
4713 * block, plus a triple indirect block
4715 indirects
= nrblocks
* 2 + 1;
4719 static int ext4_index_trans_blocks(struct inode
*inode
, int nrblocks
, int chunk
)
4721 if (!(EXT4_I(inode
)->i_flags
& EXT4_EXTENTS_FL
))
4722 return ext4_indirect_trans_blocks(inode
, nrblocks
, chunk
);
4723 return ext4_ext_index_trans_blocks(inode
, nrblocks
, chunk
);
4727 * Account for index blocks, block groups bitmaps and block group
4728 * descriptor blocks if modify datablocks and index blocks
4729 * worse case, the indexs blocks spread over different block groups
4731 * If datablocks are discontiguous, they are possible to spread over
4732 * different block groups too. If they are contiugous, with flexbg,
4733 * they could still across block group boundary.
4735 * Also account for superblock, inode, quota and xattr blocks
4737 int ext4_meta_trans_blocks(struct inode
*inode
, int nrblocks
, int chunk
)
4739 int groups
, gdpblocks
;
4744 * How many index blocks need to touch to modify nrblocks?
4745 * The "Chunk" flag indicating whether the nrblocks is
4746 * physically contiguous on disk
4748 * For Direct IO and fallocate, they calls get_block to allocate
4749 * one single extent at a time, so they could set the "Chunk" flag
4751 idxblocks
= ext4_index_trans_blocks(inode
, nrblocks
, chunk
);
4756 * Now let's see how many group bitmaps and group descriptors need
4766 if (groups
> EXT4_SB(inode
->i_sb
)->s_groups_count
)
4767 groups
= EXT4_SB(inode
->i_sb
)->s_groups_count
;
4768 if (groups
> EXT4_SB(inode
->i_sb
)->s_gdb_count
)
4769 gdpblocks
= EXT4_SB(inode
->i_sb
)->s_gdb_count
;
4771 /* bitmaps and block group descriptor blocks */
4772 ret
+= groups
+ gdpblocks
;
4774 /* Blocks for super block, inode, quota and xattr blocks */
4775 ret
+= EXT4_META_TRANS_BLOCKS(inode
->i_sb
);
4781 * Calulate the total number of credits to reserve to fit
4782 * the modification of a single pages into a single transaction,
4783 * which may include multiple chunks of block allocations.
4785 * This could be called via ext4_write_begin()
4787 * We need to consider the worse case, when
4788 * one new block per extent.
4790 int ext4_writepage_trans_blocks(struct inode
*inode
)
4792 int bpp
= ext4_journal_blocks_per_page(inode
);
4795 ret
= ext4_meta_trans_blocks(inode
, bpp
, 0);
4797 /* Account for data blocks for journalled mode */
4798 if (ext4_should_journal_data(inode
))
4804 * Calculate the journal credits for a chunk of data modification.
4806 * This is called from DIO, fallocate or whoever calling
4807 * ext4_get_blocks_wrap() to map/allocate a chunk of contigous disk blocks.
4809 * journal buffers for data blocks are not included here, as DIO
4810 * and fallocate do no need to journal data buffers.
4812 int ext4_chunk_trans_blocks(struct inode
*inode
, int nrblocks
)
4814 return ext4_meta_trans_blocks(inode
, nrblocks
, 1);
4818 * The caller must have previously called ext4_reserve_inode_write().
4819 * Give this, we know that the caller already has write access to iloc->bh.
4821 int ext4_mark_iloc_dirty(handle_t
*handle
,
4822 struct inode
*inode
, struct ext4_iloc
*iloc
)
4826 if (test_opt(inode
->i_sb
, I_VERSION
))
4827 inode_inc_iversion(inode
);
4829 /* the do_update_inode consumes one bh->b_count */
4832 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4833 err
= ext4_do_update_inode(handle
, inode
, iloc
);
4839 * On success, We end up with an outstanding reference count against
4840 * iloc->bh. This _must_ be cleaned up later.
4844 ext4_reserve_inode_write(handle_t
*handle
, struct inode
*inode
,
4845 struct ext4_iloc
*iloc
)
4849 err
= ext4_get_inode_loc(inode
, iloc
);
4851 BUFFER_TRACE(iloc
->bh
, "get_write_access");
4852 err
= ext4_journal_get_write_access(handle
, iloc
->bh
);
4858 ext4_std_error(inode
->i_sb
, err
);
4863 * Expand an inode by new_extra_isize bytes.
4864 * Returns 0 on success or negative error number on failure.
4866 static int ext4_expand_extra_isize(struct inode
*inode
,
4867 unsigned int new_extra_isize
,
4868 struct ext4_iloc iloc
,
4871 struct ext4_inode
*raw_inode
;
4872 struct ext4_xattr_ibody_header
*header
;
4873 struct ext4_xattr_entry
*entry
;
4875 if (EXT4_I(inode
)->i_extra_isize
>= new_extra_isize
)
4878 raw_inode
= ext4_raw_inode(&iloc
);
4880 header
= IHDR(inode
, raw_inode
);
4881 entry
= IFIRST(header
);
4883 /* No extended attributes present */
4884 if (!(EXT4_I(inode
)->i_state
& EXT4_STATE_XATTR
) ||
4885 header
->h_magic
!= cpu_to_le32(EXT4_XATTR_MAGIC
)) {
4886 memset((void *)raw_inode
+ EXT4_GOOD_OLD_INODE_SIZE
, 0,
4888 EXT4_I(inode
)->i_extra_isize
= new_extra_isize
;
4892 /* try to expand with EAs present */
4893 return ext4_expand_extra_isize_ea(inode
, new_extra_isize
,
4898 * What we do here is to mark the in-core inode as clean with respect to inode
4899 * dirtiness (it may still be data-dirty).
4900 * This means that the in-core inode may be reaped by prune_icache
4901 * without having to perform any I/O. This is a very good thing,
4902 * because *any* task may call prune_icache - even ones which
4903 * have a transaction open against a different journal.
4905 * Is this cheating? Not really. Sure, we haven't written the
4906 * inode out, but prune_icache isn't a user-visible syncing function.
4907 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4908 * we start and wait on commits.
4910 * Is this efficient/effective? Well, we're being nice to the system
4911 * by cleaning up our inodes proactively so they can be reaped
4912 * without I/O. But we are potentially leaving up to five seconds'
4913 * worth of inodes floating about which prune_icache wants us to
4914 * write out. One way to fix that would be to get prune_icache()
4915 * to do a write_super() to free up some memory. It has the desired
4918 int ext4_mark_inode_dirty(handle_t
*handle
, struct inode
*inode
)
4920 struct ext4_iloc iloc
;
4921 struct ext4_sb_info
*sbi
= EXT4_SB(inode
->i_sb
);
4922 static unsigned int mnt_count
;
4926 err
= ext4_reserve_inode_write(handle
, inode
, &iloc
);
4927 if (ext4_handle_valid(handle
) &&
4928 EXT4_I(inode
)->i_extra_isize
< sbi
->s_want_extra_isize
&&
4929 !(EXT4_I(inode
)->i_state
& EXT4_STATE_NO_EXPAND
)) {
4931 * We need extra buffer credits since we may write into EA block
4932 * with this same handle. If journal_extend fails, then it will
4933 * only result in a minor loss of functionality for that inode.
4934 * If this is felt to be critical, then e2fsck should be run to
4935 * force a large enough s_min_extra_isize.
4937 if ((jbd2_journal_extend(handle
,
4938 EXT4_DATA_TRANS_BLOCKS(inode
->i_sb
))) == 0) {
4939 ret
= ext4_expand_extra_isize(inode
,
4940 sbi
->s_want_extra_isize
,
4943 EXT4_I(inode
)->i_state
|= EXT4_STATE_NO_EXPAND
;
4945 le16_to_cpu(sbi
->s_es
->s_mnt_count
)) {
4946 ext4_warning(inode
->i_sb
, __func__
,
4947 "Unable to expand inode %lu. Delete"
4948 " some EAs or run e2fsck.",
4951 le16_to_cpu(sbi
->s_es
->s_mnt_count
);
4957 err
= ext4_mark_iloc_dirty(handle
, inode
, &iloc
);
4962 * ext4_dirty_inode() is called from __mark_inode_dirty()
4964 * We're really interested in the case where a file is being extended.
4965 * i_size has been changed by generic_commit_write() and we thus need
4966 * to include the updated inode in the current transaction.
4968 * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
4969 * are allocated to the file.
4971 * If the inode is marked synchronous, we don't honour that here - doing
4972 * so would cause a commit on atime updates, which we don't bother doing.
4973 * We handle synchronous inodes at the highest possible level.
4975 void ext4_dirty_inode(struct inode
*inode
)
4977 handle_t
*current_handle
= ext4_journal_current_handle();
4980 if (!ext4_handle_valid(current_handle
)) {
4981 ext4_mark_inode_dirty(current_handle
, inode
);
4985 handle
= ext4_journal_start(inode
, 2);
4988 if (current_handle
&&
4989 current_handle
->h_transaction
!= handle
->h_transaction
) {
4990 /* This task has a transaction open against a different fs */
4991 printk(KERN_EMERG
"%s: transactions do not match!\n",
4994 jbd_debug(5, "marking dirty. outer handle=%p\n",
4996 ext4_mark_inode_dirty(handle
, inode
);
4998 ext4_journal_stop(handle
);
5005 * Bind an inode's backing buffer_head into this transaction, to prevent
5006 * it from being flushed to disk early. Unlike
5007 * ext4_reserve_inode_write, this leaves behind no bh reference and
5008 * returns no iloc structure, so the caller needs to repeat the iloc
5009 * lookup to mark the inode dirty later.
5011 static int ext4_pin_inode(handle_t
*handle
, struct inode
*inode
)
5013 struct ext4_iloc iloc
;
5017 err
= ext4_get_inode_loc(inode
, &iloc
);
5019 BUFFER_TRACE(iloc
.bh
, "get_write_access");
5020 err
= jbd2_journal_get_write_access(handle
, iloc
.bh
);
5022 err
= ext4_handle_dirty_metadata(handle
,
5028 ext4_std_error(inode
->i_sb
, err
);
5033 int ext4_change_inode_journal_flag(struct inode
*inode
, int val
)
5040 * We have to be very careful here: changing a data block's
5041 * journaling status dynamically is dangerous. If we write a
5042 * data block to the journal, change the status and then delete
5043 * that block, we risk forgetting to revoke the old log record
5044 * from the journal and so a subsequent replay can corrupt data.
5045 * So, first we make sure that the journal is empty and that
5046 * nobody is changing anything.
5049 journal
= EXT4_JOURNAL(inode
);
5052 if (is_journal_aborted(journal
))
5055 jbd2_journal_lock_updates(journal
);
5056 jbd2_journal_flush(journal
);
5059 * OK, there are no updates running now, and all cached data is
5060 * synced to disk. We are now in a completely consistent state
5061 * which doesn't have anything in the journal, and we know that
5062 * no filesystem updates are running, so it is safe to modify
5063 * the inode's in-core data-journaling state flag now.
5067 EXT4_I(inode
)->i_flags
|= EXT4_JOURNAL_DATA_FL
;
5069 EXT4_I(inode
)->i_flags
&= ~EXT4_JOURNAL_DATA_FL
;
5070 ext4_set_aops(inode
);
5072 jbd2_journal_unlock_updates(journal
);
5074 /* Finally we can mark the inode as dirty. */
5076 handle
= ext4_journal_start(inode
, 1);
5078 return PTR_ERR(handle
);
5080 err
= ext4_mark_inode_dirty(handle
, inode
);
5081 ext4_handle_sync(handle
);
5082 ext4_journal_stop(handle
);
5083 ext4_std_error(inode
->i_sb
, err
);
5088 static int ext4_bh_unmapped(handle_t
*handle
, struct buffer_head
*bh
)
5090 return !buffer_mapped(bh
);
5093 int ext4_page_mkwrite(struct vm_area_struct
*vma
, struct page
*page
)
5099 struct file
*file
= vma
->vm_file
;
5100 struct inode
*inode
= file
->f_path
.dentry
->d_inode
;
5101 struct address_space
*mapping
= inode
->i_mapping
;
5104 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5105 * get i_mutex because we are already holding mmap_sem.
5107 down_read(&inode
->i_alloc_sem
);
5108 size
= i_size_read(inode
);
5109 if (page
->mapping
!= mapping
|| size
<= page_offset(page
)
5110 || !PageUptodate(page
)) {
5111 /* page got truncated from under us? */
5115 if (PageMappedToDisk(page
))
5118 if (page
->index
== size
>> PAGE_CACHE_SHIFT
)
5119 len
= size
& ~PAGE_CACHE_MASK
;
5121 len
= PAGE_CACHE_SIZE
;
5123 if (page_has_buffers(page
)) {
5124 /* return if we have all the buffers mapped */
5125 if (!walk_page_buffers(NULL
, page_buffers(page
), 0, len
, NULL
,
5130 * OK, we need to fill the hole... Do write_begin write_end
5131 * to do block allocation/reservation.We are not holding
5132 * inode.i__mutex here. That allow * parallel write_begin,
5133 * write_end call. lock_page prevent this from happening
5134 * on the same page though
5136 ret
= mapping
->a_ops
->write_begin(file
, mapping
, page_offset(page
),
5137 len
, AOP_FLAG_UNINTERRUPTIBLE
, &page
, &fsdata
);
5140 ret
= mapping
->a_ops
->write_end(file
, mapping
, page_offset(page
),
5141 len
, len
, page
, fsdata
);
5146 up_read(&inode
->i_alloc_sem
);