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 * 64-bit file support on 64-bit platforms by Jakub Jelinek
16 * (jj@sunsite.ms.mff.cuni.cz)
18 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
22 #include <linux/time.h>
23 #include <linux/highuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/dax.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/bitops.h>
41 #include "ext4_jbd2.h"
46 #include <trace/events/ext4.h>
48 #define MPAGE_DA_EXTENT_TAIL 0x01
50 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
51 struct ext4_inode_info *ei)
53 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56 int offset = offsetof(struct ext4_inode, i_checksum_lo);
57 unsigned int csum_size = sizeof(dummy_csum);
59 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
60 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
62 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
63 EXT4_GOOD_OLD_INODE_SIZE - offset);
65 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
66 offset = offsetof(struct ext4_inode, i_checksum_hi);
67 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
68 EXT4_GOOD_OLD_INODE_SIZE,
69 offset - EXT4_GOOD_OLD_INODE_SIZE);
70 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
71 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
75 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
76 EXT4_INODE_SIZE(inode->i_sb) - offset);
82 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
83 struct ext4_inode_info *ei)
85 __u32 provided, calculated;
87 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
88 cpu_to_le32(EXT4_OS_LINUX) ||
89 !ext4_has_metadata_csum(inode->i_sb))
92 provided = le16_to_cpu(raw->i_checksum_lo);
93 calculated = ext4_inode_csum(inode, raw, ei);
94 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
95 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
96 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
100 return provided == calculated;
103 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
104 struct ext4_inode_info *ei)
108 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
109 cpu_to_le32(EXT4_OS_LINUX) ||
110 !ext4_has_metadata_csum(inode->i_sb))
113 csum = ext4_inode_csum(inode, raw, ei);
114 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
115 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
116 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
117 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
120 static inline int ext4_begin_ordered_truncate(struct inode *inode,
123 trace_ext4_begin_ordered_truncate(inode, new_size);
125 * If jinode is zero, then we never opened the file for
126 * writing, so there's no need to call
127 * jbd2_journal_begin_ordered_truncate() since there's no
128 * outstanding writes we need to flush.
130 if (!EXT4_I(inode)->jinode)
132 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
133 EXT4_I(inode)->jinode,
137 static void ext4_invalidatepage(struct page *page, unsigned int offset,
138 unsigned int length);
139 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
140 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
141 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
145 * Test whether an inode is a fast symlink.
147 int ext4_inode_is_fast_symlink(struct inode *inode)
149 int ea_blocks = EXT4_I(inode)->i_file_acl ?
150 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152 if (ext4_has_inline_data(inode))
155 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
159 * Restart the transaction associated with *handle. This does a commit,
160 * so before we call here everything must be consistently dirtied against
163 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
169 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
170 * moment, get_block can be called only for blocks inside i_size since
171 * page cache has been already dropped and writes are blocked by
172 * i_mutex. So we can safely drop the i_data_sem here.
174 BUG_ON(EXT4_JOURNAL(inode) == NULL);
175 jbd_debug(2, "restarting handle %p\n", handle);
176 up_write(&EXT4_I(inode)->i_data_sem);
177 ret = ext4_journal_restart(handle, nblocks);
178 down_write(&EXT4_I(inode)->i_data_sem);
179 ext4_discard_preallocations(inode);
185 * Called at the last iput() if i_nlink is zero.
187 void ext4_evict_inode(struct inode *inode)
192 trace_ext4_evict_inode(inode);
194 if (inode->i_nlink) {
196 * When journalling data dirty buffers are tracked only in the
197 * journal. So although mm thinks everything is clean and
198 * ready for reaping the inode might still have some pages to
199 * write in the running transaction or waiting to be
200 * checkpointed. Thus calling jbd2_journal_invalidatepage()
201 * (via truncate_inode_pages()) to discard these buffers can
202 * cause data loss. Also even if we did not discard these
203 * buffers, we would have no way to find them after the inode
204 * is reaped and thus user could see stale data if he tries to
205 * read them before the transaction is checkpointed. So be
206 * careful and force everything to disk here... We use
207 * ei->i_datasync_tid to store the newest transaction
208 * containing inode's data.
210 * Note that directories do not have this problem because they
211 * don't use page cache.
213 if (inode->i_ino != EXT4_JOURNAL_INO &&
214 ext4_should_journal_data(inode) &&
215 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
216 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
217 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
219 jbd2_complete_transaction(journal, commit_tid);
220 filemap_write_and_wait(&inode->i_data);
222 truncate_inode_pages_final(&inode->i_data);
224 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
228 if (is_bad_inode(inode))
230 dquot_initialize(inode);
232 if (ext4_should_order_data(inode))
233 ext4_begin_ordered_truncate(inode, 0);
234 truncate_inode_pages_final(&inode->i_data);
236 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
239 * Protect us against freezing - iput() caller didn't have to have any
240 * protection against it
242 sb_start_intwrite(inode->i_sb);
243 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
244 ext4_blocks_for_truncate(inode)+3);
245 if (IS_ERR(handle)) {
246 ext4_std_error(inode->i_sb, PTR_ERR(handle));
248 * If we're going to skip the normal cleanup, we still need to
249 * make sure that the in-core orphan linked list is properly
252 ext4_orphan_del(NULL, inode);
253 sb_end_intwrite(inode->i_sb);
258 ext4_handle_sync(handle);
260 err = ext4_mark_inode_dirty(handle, inode);
262 ext4_warning(inode->i_sb,
263 "couldn't mark inode dirty (err %d)", err);
267 ext4_truncate(inode);
270 * ext4_ext_truncate() doesn't reserve any slop when it
271 * restarts journal transactions; therefore there may not be
272 * enough credits left in the handle to remove the inode from
273 * the orphan list and set the dtime field.
275 if (!ext4_handle_has_enough_credits(handle, 3)) {
276 err = ext4_journal_extend(handle, 3);
278 err = ext4_journal_restart(handle, 3);
280 ext4_warning(inode->i_sb,
281 "couldn't extend journal (err %d)", err);
283 ext4_journal_stop(handle);
284 ext4_orphan_del(NULL, inode);
285 sb_end_intwrite(inode->i_sb);
291 * Kill off the orphan record which ext4_truncate created.
292 * AKPM: I think this can be inside the above `if'.
293 * Note that ext4_orphan_del() has to be able to cope with the
294 * deletion of a non-existent orphan - this is because we don't
295 * know if ext4_truncate() actually created an orphan record.
296 * (Well, we could do this if we need to, but heck - it works)
298 ext4_orphan_del(handle, inode);
299 EXT4_I(inode)->i_dtime = get_seconds();
302 * One subtle ordering requirement: if anything has gone wrong
303 * (transaction abort, IO errors, whatever), then we can still
304 * do these next steps (the fs will already have been marked as
305 * having errors), but we can't free the inode if the mark_dirty
308 if (ext4_mark_inode_dirty(handle, inode))
309 /* If that failed, just do the required in-core inode clear. */
310 ext4_clear_inode(inode);
312 ext4_free_inode(handle, inode);
313 ext4_journal_stop(handle);
314 sb_end_intwrite(inode->i_sb);
317 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
321 qsize_t *ext4_get_reserved_space(struct inode *inode)
323 return &EXT4_I(inode)->i_reserved_quota;
328 * Called with i_data_sem down, which is important since we can call
329 * ext4_discard_preallocations() from here.
331 void ext4_da_update_reserve_space(struct inode *inode,
332 int used, int quota_claim)
334 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
335 struct ext4_inode_info *ei = EXT4_I(inode);
337 spin_lock(&ei->i_block_reservation_lock);
338 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
339 if (unlikely(used > ei->i_reserved_data_blocks)) {
340 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
341 "with only %d reserved data blocks",
342 __func__, inode->i_ino, used,
343 ei->i_reserved_data_blocks);
345 used = ei->i_reserved_data_blocks;
348 /* Update per-inode reservations */
349 ei->i_reserved_data_blocks -= used;
350 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
352 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
354 /* Update quota subsystem for data blocks */
356 dquot_claim_block(inode, EXT4_C2B(sbi, used));
359 * We did fallocate with an offset that is already delayed
360 * allocated. So on delayed allocated writeback we should
361 * not re-claim the quota for fallocated blocks.
363 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
367 * If we have done all the pending block allocations and if
368 * there aren't any writers on the inode, we can discard the
369 * inode's preallocations.
371 if ((ei->i_reserved_data_blocks == 0) &&
372 (atomic_read(&inode->i_writecount) == 0))
373 ext4_discard_preallocations(inode);
376 static int __check_block_validity(struct inode *inode, const char *func,
378 struct ext4_map_blocks *map)
380 if (ext4_has_feature_journal(inode->i_sb) &&
382 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
384 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
385 ext4_error_inode(inode, func, line, map->m_pblk,
386 "lblock %lu mapped to illegal pblock %llu "
387 "(length %d)", (unsigned long) map->m_lblk,
388 map->m_pblk, map->m_len);
389 return -EFSCORRUPTED;
394 #define check_block_validity(inode, map) \
395 __check_block_validity((inode), __func__, __LINE__, (map))
397 #ifdef ES_AGGRESSIVE_TEST
398 static void ext4_map_blocks_es_recheck(handle_t *handle,
400 struct ext4_map_blocks *es_map,
401 struct ext4_map_blocks *map,
408 * There is a race window that the result is not the same.
409 * e.g. xfstests #223 when dioread_nolock enables. The reason
410 * is that we lookup a block mapping in extent status tree with
411 * out taking i_data_sem. So at the time the unwritten extent
412 * could be converted.
414 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
415 down_read(&EXT4_I(inode)->i_data_sem);
416 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
417 retval = ext4_ext_map_blocks(handle, inode, map, flags &
418 EXT4_GET_BLOCKS_KEEP_SIZE);
420 retval = ext4_ind_map_blocks(handle, inode, map, flags &
421 EXT4_GET_BLOCKS_KEEP_SIZE);
423 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
424 up_read((&EXT4_I(inode)->i_data_sem));
427 * We don't check m_len because extent will be collpased in status
428 * tree. So the m_len might not equal.
430 if (es_map->m_lblk != map->m_lblk ||
431 es_map->m_flags != map->m_flags ||
432 es_map->m_pblk != map->m_pblk) {
433 printk("ES cache assertion failed for inode: %lu "
434 "es_cached ex [%d/%d/%llu/%x] != "
435 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
436 inode->i_ino, es_map->m_lblk, es_map->m_len,
437 es_map->m_pblk, es_map->m_flags, map->m_lblk,
438 map->m_len, map->m_pblk, map->m_flags,
442 #endif /* ES_AGGRESSIVE_TEST */
445 * The ext4_map_blocks() function tries to look up the requested blocks,
446 * and returns if the blocks are already mapped.
448 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
449 * and store the allocated blocks in the result buffer head and mark it
452 * If file type is extents based, it will call ext4_ext_map_blocks(),
453 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
456 * On success, it returns the number of blocks being mapped or allocated.
457 * if create==0 and the blocks are pre-allocated and unwritten block,
458 * the result buffer head is unmapped. If the create ==1, it will make sure
459 * the buffer head is mapped.
461 * It returns 0 if plain look up failed (blocks have not been allocated), in
462 * that case, buffer head is unmapped
464 * It returns the error in case of allocation failure.
466 int ext4_map_blocks(handle_t *handle, struct inode *inode,
467 struct ext4_map_blocks *map, int flags)
469 struct extent_status es;
472 #ifdef ES_AGGRESSIVE_TEST
473 struct ext4_map_blocks orig_map;
475 memcpy(&orig_map, map, sizeof(*map));
479 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
480 "logical block %lu\n", inode->i_ino, flags, map->m_len,
481 (unsigned long) map->m_lblk);
484 * ext4_map_blocks returns an int, and m_len is an unsigned int
486 if (unlikely(map->m_len > INT_MAX))
487 map->m_len = INT_MAX;
489 /* We can handle the block number less than EXT_MAX_BLOCKS */
490 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
491 return -EFSCORRUPTED;
493 /* Lookup extent status tree firstly */
494 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
495 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
496 map->m_pblk = ext4_es_pblock(&es) +
497 map->m_lblk - es.es_lblk;
498 map->m_flags |= ext4_es_is_written(&es) ?
499 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
500 retval = es.es_len - (map->m_lblk - es.es_lblk);
501 if (retval > map->m_len)
504 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
509 #ifdef ES_AGGRESSIVE_TEST
510 ext4_map_blocks_es_recheck(handle, inode, map,
517 * Try to see if we can get the block without requesting a new
520 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
521 down_read(&EXT4_I(inode)->i_data_sem);
522 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
523 retval = ext4_ext_map_blocks(handle, inode, map, flags &
524 EXT4_GET_BLOCKS_KEEP_SIZE);
526 retval = ext4_ind_map_blocks(handle, inode, map, flags &
527 EXT4_GET_BLOCKS_KEEP_SIZE);
532 if (unlikely(retval != map->m_len)) {
533 ext4_warning(inode->i_sb,
534 "ES len assertion failed for inode "
535 "%lu: retval %d != map->m_len %d",
536 inode->i_ino, retval, map->m_len);
540 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
541 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
542 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
543 !(status & EXTENT_STATUS_WRITTEN) &&
544 ext4_find_delalloc_range(inode, map->m_lblk,
545 map->m_lblk + map->m_len - 1))
546 status |= EXTENT_STATUS_DELAYED;
547 ret = ext4_es_insert_extent(inode, map->m_lblk,
548 map->m_len, map->m_pblk, status);
552 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
553 up_read((&EXT4_I(inode)->i_data_sem));
556 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
557 ret = check_block_validity(inode, map);
562 /* If it is only a block(s) look up */
563 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
567 * Returns if the blocks have already allocated
569 * Note that if blocks have been preallocated
570 * ext4_ext_get_block() returns the create = 0
571 * with buffer head unmapped.
573 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
575 * If we need to convert extent to unwritten
576 * we continue and do the actual work in
577 * ext4_ext_map_blocks()
579 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
583 * Here we clear m_flags because after allocating an new extent,
584 * it will be set again.
586 map->m_flags &= ~EXT4_MAP_FLAGS;
589 * New blocks allocate and/or writing to unwritten extent
590 * will possibly result in updating i_data, so we take
591 * the write lock of i_data_sem, and call get_block()
592 * with create == 1 flag.
594 down_write(&EXT4_I(inode)->i_data_sem);
597 * We need to check for EXT4 here because migrate
598 * could have changed the inode type in between
600 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
601 retval = ext4_ext_map_blocks(handle, inode, map, flags);
603 retval = ext4_ind_map_blocks(handle, inode, map, flags);
605 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
607 * We allocated new blocks which will result in
608 * i_data's format changing. Force the migrate
609 * to fail by clearing migrate flags
611 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
615 * Update reserved blocks/metadata blocks after successful
616 * block allocation which had been deferred till now. We don't
617 * support fallocate for non extent files. So we can update
618 * reserve space here.
621 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
622 ext4_da_update_reserve_space(inode, retval, 1);
628 if (unlikely(retval != map->m_len)) {
629 ext4_warning(inode->i_sb,
630 "ES len assertion failed for inode "
631 "%lu: retval %d != map->m_len %d",
632 inode->i_ino, retval, map->m_len);
637 * If the extent has been zeroed out, we don't need to update
638 * extent status tree.
640 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
641 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
642 if (ext4_es_is_written(&es))
645 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
646 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
647 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
648 !(status & EXTENT_STATUS_WRITTEN) &&
649 ext4_find_delalloc_range(inode, map->m_lblk,
650 map->m_lblk + map->m_len - 1))
651 status |= EXTENT_STATUS_DELAYED;
652 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
653 map->m_pblk, status);
659 up_write((&EXT4_I(inode)->i_data_sem));
660 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
661 ret = check_block_validity(inode, map);
666 * Inodes with freshly allocated blocks where contents will be
667 * visible after transaction commit must be on transaction's
670 if (map->m_flags & EXT4_MAP_NEW &&
671 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
672 !IS_NOQUOTA(inode) &&
673 ext4_should_order_data(inode)) {
674 ret = ext4_jbd2_file_inode(handle, inode);
683 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
684 * we have to be careful as someone else may be manipulating b_state as well.
686 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
688 unsigned long old_state;
689 unsigned long new_state;
691 flags &= EXT4_MAP_FLAGS;
693 /* Dummy buffer_head? Set non-atomically. */
695 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
699 * Someone else may be modifying b_state. Be careful! This is ugly but
700 * once we get rid of using bh as a container for mapping information
701 * to pass to / from get_block functions, this can go away.
704 old_state = READ_ONCE(bh->b_state);
705 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
707 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
710 /* Maximum number of blocks we map for direct IO at once. */
711 #define DIO_MAX_BLOCKS 4096
713 static int _ext4_get_block(struct inode *inode, sector_t iblock,
714 struct buffer_head *bh, int flags)
716 handle_t *handle = ext4_journal_current_handle();
717 struct ext4_map_blocks map;
718 int ret = 0, started = 0;
721 if (ext4_has_inline_data(inode))
725 map.m_len = bh->b_size >> inode->i_blkbits;
727 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
728 /* Direct IO write... */
729 if (map.m_len > DIO_MAX_BLOCKS)
730 map.m_len = DIO_MAX_BLOCKS;
731 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
732 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
734 if (IS_ERR(handle)) {
735 ret = PTR_ERR(handle);
741 ret = ext4_map_blocks(handle, inode, &map, flags);
743 ext4_io_end_t *io_end = ext4_inode_aio(inode);
745 map_bh(bh, inode->i_sb, map.m_pblk);
746 ext4_update_bh_state(bh, map.m_flags);
747 if (IS_DAX(inode) && buffer_unwritten(bh)) {
749 * dgc: I suspect unwritten conversion on ext4+DAX is
750 * fundamentally broken here when there are concurrent
751 * read/write in progress on this inode.
753 WARN_ON_ONCE(io_end);
754 bh->b_assoc_map = inode->i_mapping;
755 bh->b_private = (void *)(unsigned long)iblock;
757 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
758 set_buffer_defer_completion(bh);
759 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
763 ext4_journal_stop(handle);
767 int ext4_get_block(struct inode *inode, sector_t iblock,
768 struct buffer_head *bh, int create)
770 return _ext4_get_block(inode, iblock, bh,
771 create ? EXT4_GET_BLOCKS_CREATE : 0);
775 * `handle' can be NULL if create is zero
777 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
778 ext4_lblk_t block, int map_flags)
780 struct ext4_map_blocks map;
781 struct buffer_head *bh;
782 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
785 J_ASSERT(handle != NULL || create == 0);
789 err = ext4_map_blocks(handle, inode, &map, map_flags);
792 return create ? ERR_PTR(-ENOSPC) : NULL;
796 bh = sb_getblk(inode->i_sb, map.m_pblk);
798 return ERR_PTR(-ENOMEM);
799 if (map.m_flags & EXT4_MAP_NEW) {
800 J_ASSERT(create != 0);
801 J_ASSERT(handle != NULL);
804 * Now that we do not always journal data, we should
805 * keep in mind whether this should always journal the
806 * new buffer as metadata. For now, regular file
807 * writes use ext4_get_block instead, so it's not a
811 BUFFER_TRACE(bh, "call get_create_access");
812 err = ext4_journal_get_create_access(handle, bh);
817 if (!buffer_uptodate(bh)) {
818 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
819 set_buffer_uptodate(bh);
822 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
823 err = ext4_handle_dirty_metadata(handle, inode, bh);
827 BUFFER_TRACE(bh, "not a new buffer");
834 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
835 ext4_lblk_t block, int map_flags)
837 struct buffer_head *bh;
839 bh = ext4_getblk(handle, inode, block, map_flags);
842 if (!bh || buffer_uptodate(bh))
844 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
846 if (buffer_uptodate(bh))
849 return ERR_PTR(-EIO);
852 int ext4_walk_page_buffers(handle_t *handle,
853 struct buffer_head *head,
857 int (*fn)(handle_t *handle,
858 struct buffer_head *bh))
860 struct buffer_head *bh;
861 unsigned block_start, block_end;
862 unsigned blocksize = head->b_size;
864 struct buffer_head *next;
866 for (bh = head, block_start = 0;
867 ret == 0 && (bh != head || !block_start);
868 block_start = block_end, bh = next) {
869 next = bh->b_this_page;
870 block_end = block_start + blocksize;
871 if (block_end <= from || block_start >= to) {
872 if (partial && !buffer_uptodate(bh))
876 err = (*fn)(handle, bh);
884 * To preserve ordering, it is essential that the hole instantiation and
885 * the data write be encapsulated in a single transaction. We cannot
886 * close off a transaction and start a new one between the ext4_get_block()
887 * and the commit_write(). So doing the jbd2_journal_start at the start of
888 * prepare_write() is the right place.
890 * Also, this function can nest inside ext4_writepage(). In that case, we
891 * *know* that ext4_writepage() has generated enough buffer credits to do the
892 * whole page. So we won't block on the journal in that case, which is good,
893 * because the caller may be PF_MEMALLOC.
895 * By accident, ext4 can be reentered when a transaction is open via
896 * quota file writes. If we were to commit the transaction while thus
897 * reentered, there can be a deadlock - we would be holding a quota
898 * lock, and the commit would never complete if another thread had a
899 * transaction open and was blocking on the quota lock - a ranking
902 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
903 * will _not_ run commit under these circumstances because handle->h_ref
904 * is elevated. We'll still have enough credits for the tiny quotafile
907 int do_journal_get_write_access(handle_t *handle,
908 struct buffer_head *bh)
910 int dirty = buffer_dirty(bh);
913 if (!buffer_mapped(bh) || buffer_freed(bh))
916 * __block_write_begin() could have dirtied some buffers. Clean
917 * the dirty bit as jbd2_journal_get_write_access() could complain
918 * otherwise about fs integrity issues. Setting of the dirty bit
919 * by __block_write_begin() isn't a real problem here as we clear
920 * the bit before releasing a page lock and thus writeback cannot
921 * ever write the buffer.
924 clear_buffer_dirty(bh);
925 BUFFER_TRACE(bh, "get write access");
926 ret = ext4_journal_get_write_access(handle, bh);
928 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
932 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
933 struct buffer_head *bh_result, int create);
935 #ifdef CONFIG_EXT4_FS_ENCRYPTION
936 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
937 get_block_t *get_block)
939 unsigned from = pos & (PAGE_CACHE_SIZE - 1);
940 unsigned to = from + len;
941 struct inode *inode = page->mapping->host;
942 unsigned block_start, block_end;
945 unsigned blocksize = inode->i_sb->s_blocksize;
947 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
948 bool decrypt = false;
950 BUG_ON(!PageLocked(page));
951 BUG_ON(from > PAGE_CACHE_SIZE);
952 BUG_ON(to > PAGE_CACHE_SIZE);
955 if (!page_has_buffers(page))
956 create_empty_buffers(page, blocksize, 0);
957 head = page_buffers(page);
958 bbits = ilog2(blocksize);
959 block = (sector_t)page->index << (PAGE_CACHE_SHIFT - bbits);
961 for (bh = head, block_start = 0; bh != head || !block_start;
962 block++, block_start = block_end, bh = bh->b_this_page) {
963 block_end = block_start + blocksize;
964 if (block_end <= from || block_start >= to) {
965 if (PageUptodate(page)) {
966 if (!buffer_uptodate(bh))
967 set_buffer_uptodate(bh);
972 clear_buffer_new(bh);
973 if (!buffer_mapped(bh)) {
974 WARN_ON(bh->b_size != blocksize);
975 err = get_block(inode, block, bh, 1);
978 if (buffer_new(bh)) {
979 unmap_underlying_metadata(bh->b_bdev,
981 if (PageUptodate(page)) {
982 clear_buffer_new(bh);
983 set_buffer_uptodate(bh);
984 mark_buffer_dirty(bh);
987 if (block_end > to || block_start < from)
988 zero_user_segments(page, to, block_end,
993 if (PageUptodate(page)) {
994 if (!buffer_uptodate(bh))
995 set_buffer_uptodate(bh);
998 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
999 !buffer_unwritten(bh) &&
1000 (block_start < from || block_end > to)) {
1001 ll_rw_block(READ, 1, &bh);
1003 decrypt = ext4_encrypted_inode(inode) &&
1004 S_ISREG(inode->i_mode);
1008 * If we issued read requests, let them complete.
1010 while (wait_bh > wait) {
1011 wait_on_buffer(*--wait_bh);
1012 if (!buffer_uptodate(*wait_bh))
1016 page_zero_new_buffers(page, from, to);
1018 err = ext4_decrypt(page);
1023 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1024 loff_t pos, unsigned len, unsigned flags,
1025 struct page **pagep, void **fsdata)
1027 struct inode *inode = mapping->host;
1028 int ret, needed_blocks;
1035 trace_ext4_write_begin(inode, pos, len, flags);
1037 * Reserve one block more for addition to orphan list in case
1038 * we allocate blocks but write fails for some reason
1040 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1041 index = pos >> PAGE_CACHE_SHIFT;
1042 from = pos & (PAGE_CACHE_SIZE - 1);
1045 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1046 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1055 * grab_cache_page_write_begin() can take a long time if the
1056 * system is thrashing due to memory pressure, or if the page
1057 * is being written back. So grab it first before we start
1058 * the transaction handle. This also allows us to allocate
1059 * the page (if needed) without using GFP_NOFS.
1062 page = grab_cache_page_write_begin(mapping, index, flags);
1068 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1069 if (IS_ERR(handle)) {
1070 page_cache_release(page);
1071 return PTR_ERR(handle);
1075 if (page->mapping != mapping) {
1076 /* The page got truncated from under us */
1078 page_cache_release(page);
1079 ext4_journal_stop(handle);
1082 /* In case writeback began while the page was unlocked */
1083 wait_for_stable_page(page);
1085 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1086 if (ext4_should_dioread_nolock(inode))
1087 ret = ext4_block_write_begin(page, pos, len,
1088 ext4_get_block_write);
1090 ret = ext4_block_write_begin(page, pos, len,
1093 if (ext4_should_dioread_nolock(inode))
1094 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1096 ret = __block_write_begin(page, pos, len, ext4_get_block);
1098 if (!ret && ext4_should_journal_data(inode)) {
1099 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1101 do_journal_get_write_access);
1107 * __block_write_begin may have instantiated a few blocks
1108 * outside i_size. Trim these off again. Don't need
1109 * i_size_read because we hold i_mutex.
1111 * Add inode to orphan list in case we crash before
1114 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1115 ext4_orphan_add(handle, inode);
1117 ext4_journal_stop(handle);
1118 if (pos + len > inode->i_size) {
1119 ext4_truncate_failed_write(inode);
1121 * If truncate failed early the inode might
1122 * still be on the orphan list; we need to
1123 * make sure the inode is removed from the
1124 * orphan list in that case.
1127 ext4_orphan_del(NULL, inode);
1130 if (ret == -ENOSPC &&
1131 ext4_should_retry_alloc(inode->i_sb, &retries))
1133 page_cache_release(page);
1140 /* For write_end() in data=journal mode */
1141 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1144 if (!buffer_mapped(bh) || buffer_freed(bh))
1146 set_buffer_uptodate(bh);
1147 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1148 clear_buffer_meta(bh);
1149 clear_buffer_prio(bh);
1154 * We need to pick up the new inode size which generic_commit_write gave us
1155 * `file' can be NULL - eg, when called from page_symlink().
1157 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1158 * buffers are managed internally.
1160 static int ext4_write_end(struct file *file,
1161 struct address_space *mapping,
1162 loff_t pos, unsigned len, unsigned copied,
1163 struct page *page, void *fsdata)
1165 handle_t *handle = ext4_journal_current_handle();
1166 struct inode *inode = mapping->host;
1167 loff_t old_size = inode->i_size;
1169 int i_size_changed = 0;
1170 int inline_data = ext4_has_inline_data(inode);
1172 trace_ext4_write_end(inode, pos, len, copied);
1174 ret = ext4_write_inline_data_end(inode, pos, len,
1183 copied = block_write_end(file, mapping, pos,
1184 len, copied, page, fsdata);
1186 * it's important to update i_size while still holding page lock:
1187 * page writeout could otherwise come in and zero beyond i_size.
1189 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1191 page_cache_release(page);
1194 pagecache_isize_extended(inode, old_size, pos);
1196 * Don't mark the inode dirty under page lock. First, it unnecessarily
1197 * makes the holding time of page lock longer. Second, it forces lock
1198 * ordering of page lock and transaction start for journaling
1201 if (i_size_changed || inline_data)
1202 ext4_mark_inode_dirty(handle, inode);
1204 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1205 /* if we have allocated more blocks and copied
1206 * less. We will have blocks allocated outside
1207 * inode->i_size. So truncate them
1209 ext4_orphan_add(handle, inode);
1211 ret2 = ext4_journal_stop(handle);
1215 if (pos + len > inode->i_size) {
1216 ext4_truncate_failed_write(inode);
1218 * If truncate failed early the inode might still be
1219 * on the orphan list; we need to make sure the inode
1220 * is removed from the orphan list in that case.
1223 ext4_orphan_del(NULL, inode);
1226 return ret ? ret : copied;
1230 * This is a private version of page_zero_new_buffers() which doesn't
1231 * set the buffer to be dirty, since in data=journalled mode we need
1232 * to call ext4_handle_dirty_metadata() instead.
1234 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1236 unsigned from, unsigned to)
1238 unsigned int block_start = 0, block_end;
1239 struct buffer_head *head, *bh;
1241 bh = head = page_buffers(page);
1243 block_end = block_start + bh->b_size;
1244 if (buffer_new(bh)) {
1245 if (block_end > from && block_start < to) {
1246 if (!PageUptodate(page)) {
1247 unsigned start, size;
1249 start = max(from, block_start);
1250 size = min(to, block_end) - start;
1252 zero_user(page, start, size);
1253 write_end_fn(handle, bh);
1255 clear_buffer_new(bh);
1258 block_start = block_end;
1259 bh = bh->b_this_page;
1260 } while (bh != head);
1263 static int ext4_journalled_write_end(struct file *file,
1264 struct address_space *mapping,
1265 loff_t pos, unsigned len, unsigned copied,
1266 struct page *page, void *fsdata)
1268 handle_t *handle = ext4_journal_current_handle();
1269 struct inode *inode = mapping->host;
1270 loff_t old_size = inode->i_size;
1274 int size_changed = 0;
1275 int inline_data = ext4_has_inline_data(inode);
1277 trace_ext4_journalled_write_end(inode, pos, len, copied);
1278 from = pos & (PAGE_CACHE_SIZE - 1);
1281 BUG_ON(!ext4_handle_valid(handle));
1284 ret = ext4_write_inline_data_end(inode, pos, len,
1292 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1294 ext4_journalled_zero_new_buffers(handle, page, from, to);
1296 if (unlikely(copied < len))
1297 ext4_journalled_zero_new_buffers(handle, page,
1299 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1300 from + copied, &partial,
1303 SetPageUptodate(page);
1305 size_changed = ext4_update_inode_size(inode, pos + copied);
1306 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1307 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1309 page_cache_release(page);
1312 pagecache_isize_extended(inode, old_size, pos);
1314 if (size_changed || inline_data) {
1315 ret2 = ext4_mark_inode_dirty(handle, inode);
1320 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1321 /* if we have allocated more blocks and copied
1322 * less. We will have blocks allocated outside
1323 * inode->i_size. So truncate them
1325 ext4_orphan_add(handle, inode);
1328 ret2 = ext4_journal_stop(handle);
1331 if (pos + len > inode->i_size) {
1332 ext4_truncate_failed_write(inode);
1334 * If truncate failed early the inode might still be
1335 * on the orphan list; we need to make sure the inode
1336 * is removed from the orphan list in that case.
1339 ext4_orphan_del(NULL, inode);
1342 return ret ? ret : copied;
1346 * Reserve space for a single cluster
1348 static int ext4_da_reserve_space(struct inode *inode)
1350 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1351 struct ext4_inode_info *ei = EXT4_I(inode);
1355 * We will charge metadata quota at writeout time; this saves
1356 * us from metadata over-estimation, though we may go over by
1357 * a small amount in the end. Here we just reserve for data.
1359 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1363 spin_lock(&ei->i_block_reservation_lock);
1364 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1365 spin_unlock(&ei->i_block_reservation_lock);
1366 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1369 ei->i_reserved_data_blocks++;
1370 trace_ext4_da_reserve_space(inode);
1371 spin_unlock(&ei->i_block_reservation_lock);
1373 return 0; /* success */
1376 static void ext4_da_release_space(struct inode *inode, int to_free)
1378 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1379 struct ext4_inode_info *ei = EXT4_I(inode);
1382 return; /* Nothing to release, exit */
1384 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1386 trace_ext4_da_release_space(inode, to_free);
1387 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1389 * if there aren't enough reserved blocks, then the
1390 * counter is messed up somewhere. Since this
1391 * function is called from invalidate page, it's
1392 * harmless to return without any action.
1394 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1395 "ino %lu, to_free %d with only %d reserved "
1396 "data blocks", inode->i_ino, to_free,
1397 ei->i_reserved_data_blocks);
1399 to_free = ei->i_reserved_data_blocks;
1401 ei->i_reserved_data_blocks -= to_free;
1403 /* update fs dirty data blocks counter */
1404 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1406 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1408 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1411 static void ext4_da_page_release_reservation(struct page *page,
1412 unsigned int offset,
1413 unsigned int length)
1415 int to_release = 0, contiguous_blks = 0;
1416 struct buffer_head *head, *bh;
1417 unsigned int curr_off = 0;
1418 struct inode *inode = page->mapping->host;
1419 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1420 unsigned int stop = offset + length;
1424 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1426 head = page_buffers(page);
1429 unsigned int next_off = curr_off + bh->b_size;
1431 if (next_off > stop)
1434 if ((offset <= curr_off) && (buffer_delay(bh))) {
1437 clear_buffer_delay(bh);
1438 } else if (contiguous_blks) {
1439 lblk = page->index <<
1440 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1441 lblk += (curr_off >> inode->i_blkbits) -
1443 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1444 contiguous_blks = 0;
1446 curr_off = next_off;
1447 } while ((bh = bh->b_this_page) != head);
1449 if (contiguous_blks) {
1450 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1451 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1452 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1455 /* If we have released all the blocks belonging to a cluster, then we
1456 * need to release the reserved space for that cluster. */
1457 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1458 while (num_clusters > 0) {
1459 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1460 ((num_clusters - 1) << sbi->s_cluster_bits);
1461 if (sbi->s_cluster_ratio == 1 ||
1462 !ext4_find_delalloc_cluster(inode, lblk))
1463 ext4_da_release_space(inode, 1);
1470 * Delayed allocation stuff
1473 struct mpage_da_data {
1474 struct inode *inode;
1475 struct writeback_control *wbc;
1477 pgoff_t first_page; /* The first page to write */
1478 pgoff_t next_page; /* Current page to examine */
1479 pgoff_t last_page; /* Last page to examine */
1481 * Extent to map - this can be after first_page because that can be
1482 * fully mapped. We somewhat abuse m_flags to store whether the extent
1483 * is delalloc or unwritten.
1485 struct ext4_map_blocks map;
1486 struct ext4_io_submit io_submit; /* IO submission data */
1489 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1494 struct pagevec pvec;
1495 struct inode *inode = mpd->inode;
1496 struct address_space *mapping = inode->i_mapping;
1498 /* This is necessary when next_page == 0. */
1499 if (mpd->first_page >= mpd->next_page)
1502 index = mpd->first_page;
1503 end = mpd->next_page - 1;
1505 ext4_lblk_t start, last;
1506 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1507 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1508 ext4_es_remove_extent(inode, start, last - start + 1);
1511 pagevec_init(&pvec, 0);
1512 while (index <= end) {
1513 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1516 for (i = 0; i < nr_pages; i++) {
1517 struct page *page = pvec.pages[i];
1518 if (page->index > end)
1520 BUG_ON(!PageLocked(page));
1521 BUG_ON(PageWriteback(page));
1523 if (page_mapped(page))
1524 clear_page_dirty_for_io(page);
1525 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1526 ClearPageUptodate(page);
1530 index = pvec.pages[nr_pages - 1]->index + 1;
1531 pagevec_release(&pvec);
1535 static void ext4_print_free_blocks(struct inode *inode)
1537 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1538 struct super_block *sb = inode->i_sb;
1539 struct ext4_inode_info *ei = EXT4_I(inode);
1541 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1542 EXT4_C2B(EXT4_SB(inode->i_sb),
1543 ext4_count_free_clusters(sb)));
1544 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1545 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1546 (long long) EXT4_C2B(EXT4_SB(sb),
1547 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1548 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1549 (long long) EXT4_C2B(EXT4_SB(sb),
1550 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1551 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1552 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1553 ei->i_reserved_data_blocks);
1557 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1559 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1563 * This function is grabs code from the very beginning of
1564 * ext4_map_blocks, but assumes that the caller is from delayed write
1565 * time. This function looks up the requested blocks and sets the
1566 * buffer delay bit under the protection of i_data_sem.
1568 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1569 struct ext4_map_blocks *map,
1570 struct buffer_head *bh)
1572 struct extent_status es;
1574 sector_t invalid_block = ~((sector_t) 0xffff);
1575 #ifdef ES_AGGRESSIVE_TEST
1576 struct ext4_map_blocks orig_map;
1578 memcpy(&orig_map, map, sizeof(*map));
1581 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1585 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1586 "logical block %lu\n", inode->i_ino, map->m_len,
1587 (unsigned long) map->m_lblk);
1589 /* Lookup extent status tree firstly */
1590 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1591 if (ext4_es_is_hole(&es)) {
1593 down_read(&EXT4_I(inode)->i_data_sem);
1598 * Delayed extent could be allocated by fallocate.
1599 * So we need to check it.
1601 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1602 map_bh(bh, inode->i_sb, invalid_block);
1604 set_buffer_delay(bh);
1608 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1609 retval = es.es_len - (iblock - es.es_lblk);
1610 if (retval > map->m_len)
1611 retval = map->m_len;
1612 map->m_len = retval;
1613 if (ext4_es_is_written(&es))
1614 map->m_flags |= EXT4_MAP_MAPPED;
1615 else if (ext4_es_is_unwritten(&es))
1616 map->m_flags |= EXT4_MAP_UNWRITTEN;
1620 #ifdef ES_AGGRESSIVE_TEST
1621 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1627 * Try to see if we can get the block without requesting a new
1628 * file system block.
1630 down_read(&EXT4_I(inode)->i_data_sem);
1631 if (ext4_has_inline_data(inode))
1633 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1634 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1636 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1642 * XXX: __block_prepare_write() unmaps passed block,
1646 * If the block was allocated from previously allocated cluster,
1647 * then we don't need to reserve it again. However we still need
1648 * to reserve metadata for every block we're going to write.
1650 if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1651 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1652 ret = ext4_da_reserve_space(inode);
1654 /* not enough space to reserve */
1660 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1661 ~0, EXTENT_STATUS_DELAYED);
1667 map_bh(bh, inode->i_sb, invalid_block);
1669 set_buffer_delay(bh);
1670 } else if (retval > 0) {
1672 unsigned int status;
1674 if (unlikely(retval != map->m_len)) {
1675 ext4_warning(inode->i_sb,
1676 "ES len assertion failed for inode "
1677 "%lu: retval %d != map->m_len %d",
1678 inode->i_ino, retval, map->m_len);
1682 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1683 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1684 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1685 map->m_pblk, status);
1691 up_read((&EXT4_I(inode)->i_data_sem));
1697 * This is a special get_block_t callback which is used by
1698 * ext4_da_write_begin(). It will either return mapped block or
1699 * reserve space for a single block.
1701 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1702 * We also have b_blocknr = -1 and b_bdev initialized properly
1704 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1705 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1706 * initialized properly.
1708 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1709 struct buffer_head *bh, int create)
1711 struct ext4_map_blocks map;
1714 BUG_ON(create == 0);
1715 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1717 map.m_lblk = iblock;
1721 * first, we need to know whether the block is allocated already
1722 * preallocated blocks are unmapped but should treated
1723 * the same as allocated blocks.
1725 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1729 map_bh(bh, inode->i_sb, map.m_pblk);
1730 ext4_update_bh_state(bh, map.m_flags);
1732 if (buffer_unwritten(bh)) {
1733 /* A delayed write to unwritten bh should be marked
1734 * new and mapped. Mapped ensures that we don't do
1735 * get_block multiple times when we write to the same
1736 * offset and new ensures that we do proper zero out
1737 * for partial write.
1740 set_buffer_mapped(bh);
1745 static int bget_one(handle_t *handle, struct buffer_head *bh)
1751 static int bput_one(handle_t *handle, struct buffer_head *bh)
1757 static int __ext4_journalled_writepage(struct page *page,
1760 struct address_space *mapping = page->mapping;
1761 struct inode *inode = mapping->host;
1762 struct buffer_head *page_bufs = NULL;
1763 handle_t *handle = NULL;
1764 int ret = 0, err = 0;
1765 int inline_data = ext4_has_inline_data(inode);
1766 struct buffer_head *inode_bh = NULL;
1768 ClearPageChecked(page);
1771 BUG_ON(page->index != 0);
1772 BUG_ON(len > ext4_get_max_inline_size(inode));
1773 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1774 if (inode_bh == NULL)
1777 page_bufs = page_buffers(page);
1782 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1786 * We need to release the page lock before we start the
1787 * journal, so grab a reference so the page won't disappear
1788 * out from under us.
1793 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1794 ext4_writepage_trans_blocks(inode));
1795 if (IS_ERR(handle)) {
1796 ret = PTR_ERR(handle);
1798 goto out_no_pagelock;
1800 BUG_ON(!ext4_handle_valid(handle));
1804 if (page->mapping != mapping) {
1805 /* The page got truncated from under us */
1806 ext4_journal_stop(handle);
1812 ret = ext4_mark_inode_dirty(handle, inode);
1814 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1815 do_journal_get_write_access);
1817 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1822 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1823 err = ext4_journal_stop(handle);
1827 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1831 if (!inline_data && page_bufs)
1832 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1839 * Note that we don't need to start a transaction unless we're journaling data
1840 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1841 * need to file the inode to the transaction's list in ordered mode because if
1842 * we are writing back data added by write(), the inode is already there and if
1843 * we are writing back data modified via mmap(), no one guarantees in which
1844 * transaction the data will hit the disk. In case we are journaling data, we
1845 * cannot start transaction directly because transaction start ranks above page
1846 * lock so we have to do some magic.
1848 * This function can get called via...
1849 * - ext4_writepages after taking page lock (have journal handle)
1850 * - journal_submit_inode_data_buffers (no journal handle)
1851 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1852 * - grab_page_cache when doing write_begin (have journal handle)
1854 * We don't do any block allocation in this function. If we have page with
1855 * multiple blocks we need to write those buffer_heads that are mapped. This
1856 * is important for mmaped based write. So if we do with blocksize 1K
1857 * truncate(f, 1024);
1858 * a = mmap(f, 0, 4096);
1860 * truncate(f, 4096);
1861 * we have in the page first buffer_head mapped via page_mkwrite call back
1862 * but other buffer_heads would be unmapped but dirty (dirty done via the
1863 * do_wp_page). So writepage should write the first block. If we modify
1864 * the mmap area beyond 1024 we will again get a page_fault and the
1865 * page_mkwrite callback will do the block allocation and mark the
1866 * buffer_heads mapped.
1868 * We redirty the page if we have any buffer_heads that is either delay or
1869 * unwritten in the page.
1871 * We can get recursively called as show below.
1873 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1876 * But since we don't do any block allocation we should not deadlock.
1877 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1879 static int ext4_writepage(struct page *page,
1880 struct writeback_control *wbc)
1885 struct buffer_head *page_bufs = NULL;
1886 struct inode *inode = page->mapping->host;
1887 struct ext4_io_submit io_submit;
1888 bool keep_towrite = false;
1890 trace_ext4_writepage(page);
1891 size = i_size_read(inode);
1892 if (page->index == size >> PAGE_CACHE_SHIFT)
1893 len = size & ~PAGE_CACHE_MASK;
1895 len = PAGE_CACHE_SIZE;
1897 page_bufs = page_buffers(page);
1899 * We cannot do block allocation or other extent handling in this
1900 * function. If there are buffers needing that, we have to redirty
1901 * the page. But we may reach here when we do a journal commit via
1902 * journal_submit_inode_data_buffers() and in that case we must write
1903 * allocated buffers to achieve data=ordered mode guarantees.
1905 * Also, if there is only one buffer per page (the fs block
1906 * size == the page size), if one buffer needs block
1907 * allocation or needs to modify the extent tree to clear the
1908 * unwritten flag, we know that the page can't be written at
1909 * all, so we might as well refuse the write immediately.
1910 * Unfortunately if the block size != page size, we can't as
1911 * easily detect this case using ext4_walk_page_buffers(), but
1912 * for the extremely common case, this is an optimization that
1913 * skips a useless round trip through ext4_bio_write_page().
1915 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1916 ext4_bh_delay_or_unwritten)) {
1917 redirty_page_for_writepage(wbc, page);
1918 if ((current->flags & PF_MEMALLOC) ||
1919 (inode->i_sb->s_blocksize == PAGE_CACHE_SIZE)) {
1921 * For memory cleaning there's no point in writing only
1922 * some buffers. So just bail out. Warn if we came here
1923 * from direct reclaim.
1925 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1930 keep_towrite = true;
1933 if (PageChecked(page) && ext4_should_journal_data(inode))
1935 * It's mmapped pagecache. Add buffers and journal it. There
1936 * doesn't seem much point in redirtying the page here.
1938 return __ext4_journalled_writepage(page, len);
1940 ext4_io_submit_init(&io_submit, wbc);
1941 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1942 if (!io_submit.io_end) {
1943 redirty_page_for_writepage(wbc, page);
1947 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
1948 ext4_io_submit(&io_submit);
1949 /* Drop io_end reference we got from init */
1950 ext4_put_io_end_defer(io_submit.io_end);
1954 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1960 BUG_ON(page->index != mpd->first_page);
1961 clear_page_dirty_for_io(page);
1963 * We have to be very careful here! Nothing protects writeback path
1964 * against i_size changes and the page can be writeably mapped into
1965 * page tables. So an application can be growing i_size and writing
1966 * data through mmap while writeback runs. clear_page_dirty_for_io()
1967 * write-protects our page in page tables and the page cannot get
1968 * written to again until we release page lock. So only after
1969 * clear_page_dirty_for_io() we are safe to sample i_size for
1970 * ext4_bio_write_page() to zero-out tail of the written page. We rely
1971 * on the barrier provided by TestClearPageDirty in
1972 * clear_page_dirty_for_io() to make sure i_size is really sampled only
1973 * after page tables are updated.
1975 size = i_size_read(mpd->inode);
1976 if (page->index == size >> PAGE_SHIFT)
1977 len = size & ~PAGE_MASK;
1980 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
1982 mpd->wbc->nr_to_write--;
1988 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1991 * mballoc gives us at most this number of blocks...
1992 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1993 * The rest of mballoc seems to handle chunks up to full group size.
1995 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1998 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2000 * @mpd - extent of blocks
2001 * @lblk - logical number of the block in the file
2002 * @bh - buffer head we want to add to the extent
2004 * The function is used to collect contig. blocks in the same state. If the
2005 * buffer doesn't require mapping for writeback and we haven't started the
2006 * extent of buffers to map yet, the function returns 'true' immediately - the
2007 * caller can write the buffer right away. Otherwise the function returns true
2008 * if the block has been added to the extent, false if the block couldn't be
2011 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2012 struct buffer_head *bh)
2014 struct ext4_map_blocks *map = &mpd->map;
2016 /* Buffer that doesn't need mapping for writeback? */
2017 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2018 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2019 /* So far no extent to map => we write the buffer right away */
2020 if (map->m_len == 0)
2025 /* First block in the extent? */
2026 if (map->m_len == 0) {
2029 map->m_flags = bh->b_state & BH_FLAGS;
2033 /* Don't go larger than mballoc is willing to allocate */
2034 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2037 /* Can we merge the block to our big extent? */
2038 if (lblk == map->m_lblk + map->m_len &&
2039 (bh->b_state & BH_FLAGS) == map->m_flags) {
2047 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2049 * @mpd - extent of blocks for mapping
2050 * @head - the first buffer in the page
2051 * @bh - buffer we should start processing from
2052 * @lblk - logical number of the block in the file corresponding to @bh
2054 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2055 * the page for IO if all buffers in this page were mapped and there's no
2056 * accumulated extent of buffers to map or add buffers in the page to the
2057 * extent of buffers to map. The function returns 1 if the caller can continue
2058 * by processing the next page, 0 if it should stop adding buffers to the
2059 * extent to map because we cannot extend it anymore. It can also return value
2060 * < 0 in case of error during IO submission.
2062 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2063 struct buffer_head *head,
2064 struct buffer_head *bh,
2067 struct inode *inode = mpd->inode;
2069 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2070 >> inode->i_blkbits;
2073 BUG_ON(buffer_locked(bh));
2075 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2076 /* Found extent to map? */
2079 /* Everything mapped so far and we hit EOF */
2082 } while (lblk++, (bh = bh->b_this_page) != head);
2083 /* So far everything mapped? Submit the page for IO. */
2084 if (mpd->map.m_len == 0) {
2085 err = mpage_submit_page(mpd, head->b_page);
2089 return lblk < blocks;
2093 * mpage_map_buffers - update buffers corresponding to changed extent and
2094 * submit fully mapped pages for IO
2096 * @mpd - description of extent to map, on return next extent to map
2098 * Scan buffers corresponding to changed extent (we expect corresponding pages
2099 * to be already locked) and update buffer state according to new extent state.
2100 * We map delalloc buffers to their physical location, clear unwritten bits,
2101 * and mark buffers as uninit when we perform writes to unwritten extents
2102 * and do extent conversion after IO is finished. If the last page is not fully
2103 * mapped, we update @map to the next extent in the last page that needs
2104 * mapping. Otherwise we submit the page for IO.
2106 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2108 struct pagevec pvec;
2110 struct inode *inode = mpd->inode;
2111 struct buffer_head *head, *bh;
2112 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
2118 start = mpd->map.m_lblk >> bpp_bits;
2119 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2120 lblk = start << bpp_bits;
2121 pblock = mpd->map.m_pblk;
2123 pagevec_init(&pvec, 0);
2124 while (start <= end) {
2125 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2129 for (i = 0; i < nr_pages; i++) {
2130 struct page *page = pvec.pages[i];
2132 if (page->index > end)
2134 /* Up to 'end' pages must be contiguous */
2135 BUG_ON(page->index != start);
2136 bh = head = page_buffers(page);
2138 if (lblk < mpd->map.m_lblk)
2140 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2142 * Buffer after end of mapped extent.
2143 * Find next buffer in the page to map.
2146 mpd->map.m_flags = 0;
2148 * FIXME: If dioread_nolock supports
2149 * blocksize < pagesize, we need to make
2150 * sure we add size mapped so far to
2151 * io_end->size as the following call
2152 * can submit the page for IO.
2154 err = mpage_process_page_bufs(mpd, head,
2156 pagevec_release(&pvec);
2161 if (buffer_delay(bh)) {
2162 clear_buffer_delay(bh);
2163 bh->b_blocknr = pblock++;
2165 clear_buffer_unwritten(bh);
2166 } while (lblk++, (bh = bh->b_this_page) != head);
2169 * FIXME: This is going to break if dioread_nolock
2170 * supports blocksize < pagesize as we will try to
2171 * convert potentially unmapped parts of inode.
2173 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2174 /* Page fully mapped - let IO run! */
2175 err = mpage_submit_page(mpd, page);
2177 pagevec_release(&pvec);
2182 pagevec_release(&pvec);
2184 /* Extent fully mapped and matches with page boundary. We are done. */
2186 mpd->map.m_flags = 0;
2190 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2192 struct inode *inode = mpd->inode;
2193 struct ext4_map_blocks *map = &mpd->map;
2194 int get_blocks_flags;
2195 int err, dioread_nolock;
2197 trace_ext4_da_write_pages_extent(inode, map);
2199 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2200 * to convert an unwritten extent to be initialized (in the case
2201 * where we have written into one or more preallocated blocks). It is
2202 * possible that we're going to need more metadata blocks than
2203 * previously reserved. However we must not fail because we're in
2204 * writeback and there is nothing we can do about it so it might result
2205 * in data loss. So use reserved blocks to allocate metadata if
2208 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2209 * the blocks in question are delalloc blocks. This indicates
2210 * that the blocks and quotas has already been checked when
2211 * the data was copied into the page cache.
2213 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2214 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2215 dioread_nolock = ext4_should_dioread_nolock(inode);
2217 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2218 if (map->m_flags & (1 << BH_Delay))
2219 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2221 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2224 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2225 if (!mpd->io_submit.io_end->handle &&
2226 ext4_handle_valid(handle)) {
2227 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2228 handle->h_rsv_handle = NULL;
2230 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2233 BUG_ON(map->m_len == 0);
2234 if (map->m_flags & EXT4_MAP_NEW) {
2235 struct block_device *bdev = inode->i_sb->s_bdev;
2238 for (i = 0; i < map->m_len; i++)
2239 unmap_underlying_metadata(bdev, map->m_pblk + i);
2245 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2246 * mpd->len and submit pages underlying it for IO
2248 * @handle - handle for journal operations
2249 * @mpd - extent to map
2250 * @give_up_on_write - we set this to true iff there is a fatal error and there
2251 * is no hope of writing the data. The caller should discard
2252 * dirty pages to avoid infinite loops.
2254 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2255 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2256 * them to initialized or split the described range from larger unwritten
2257 * extent. Note that we need not map all the described range since allocation
2258 * can return less blocks or the range is covered by more unwritten extents. We
2259 * cannot map more because we are limited by reserved transaction credits. On
2260 * the other hand we always make sure that the last touched page is fully
2261 * mapped so that it can be written out (and thus forward progress is
2262 * guaranteed). After mapping we submit all mapped pages for IO.
2264 static int mpage_map_and_submit_extent(handle_t *handle,
2265 struct mpage_da_data *mpd,
2266 bool *give_up_on_write)
2268 struct inode *inode = mpd->inode;
2269 struct ext4_map_blocks *map = &mpd->map;
2274 mpd->io_submit.io_end->offset =
2275 ((loff_t)map->m_lblk) << inode->i_blkbits;
2277 err = mpage_map_one_extent(handle, mpd);
2279 struct super_block *sb = inode->i_sb;
2281 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2282 goto invalidate_dirty_pages;
2284 * Let the uper layers retry transient errors.
2285 * In the case of ENOSPC, if ext4_count_free_blocks()
2286 * is non-zero, a commit should free up blocks.
2288 if ((err == -ENOMEM) ||
2289 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2291 goto update_disksize;
2294 ext4_msg(sb, KERN_CRIT,
2295 "Delayed block allocation failed for "
2296 "inode %lu at logical offset %llu with"
2297 " max blocks %u with error %d",
2299 (unsigned long long)map->m_lblk,
2300 (unsigned)map->m_len, -err);
2301 ext4_msg(sb, KERN_CRIT,
2302 "This should not happen!! Data will "
2305 ext4_print_free_blocks(inode);
2306 invalidate_dirty_pages:
2307 *give_up_on_write = true;
2312 * Update buffer state, submit mapped pages, and get us new
2315 err = mpage_map_and_submit_buffers(mpd);
2317 goto update_disksize;
2318 } while (map->m_len);
2322 * Update on-disk size after IO is submitted. Races with
2323 * truncate are avoided by checking i_size under i_data_sem.
2325 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2326 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2330 down_write(&EXT4_I(inode)->i_data_sem);
2331 i_size = i_size_read(inode);
2332 if (disksize > i_size)
2334 if (disksize > EXT4_I(inode)->i_disksize)
2335 EXT4_I(inode)->i_disksize = disksize;
2336 err2 = ext4_mark_inode_dirty(handle, inode);
2337 up_write(&EXT4_I(inode)->i_data_sem);
2339 ext4_error(inode->i_sb,
2340 "Failed to mark inode %lu dirty",
2349 * Calculate the total number of credits to reserve for one writepages
2350 * iteration. This is called from ext4_writepages(). We map an extent of
2351 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2352 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2353 * bpp - 1 blocks in bpp different extents.
2355 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2357 int bpp = ext4_journal_blocks_per_page(inode);
2359 return ext4_meta_trans_blocks(inode,
2360 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2364 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2365 * and underlying extent to map
2367 * @mpd - where to look for pages
2369 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2370 * IO immediately. When we find a page which isn't mapped we start accumulating
2371 * extent of buffers underlying these pages that needs mapping (formed by
2372 * either delayed or unwritten buffers). We also lock the pages containing
2373 * these buffers. The extent found is returned in @mpd structure (starting at
2374 * mpd->lblk with length mpd->len blocks).
2376 * Note that this function can attach bios to one io_end structure which are
2377 * neither logically nor physically contiguous. Although it may seem as an
2378 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2379 * case as we need to track IO to all buffers underlying a page in one io_end.
2381 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2383 struct address_space *mapping = mpd->inode->i_mapping;
2384 struct pagevec pvec;
2385 unsigned int nr_pages;
2386 long left = mpd->wbc->nr_to_write;
2387 pgoff_t index = mpd->first_page;
2388 pgoff_t end = mpd->last_page;
2391 int blkbits = mpd->inode->i_blkbits;
2393 struct buffer_head *head;
2395 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2396 tag = PAGECACHE_TAG_TOWRITE;
2398 tag = PAGECACHE_TAG_DIRTY;
2400 pagevec_init(&pvec, 0);
2402 mpd->next_page = index;
2403 while (index <= end) {
2404 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2405 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2409 for (i = 0; i < nr_pages; i++) {
2410 struct page *page = pvec.pages[i];
2413 * At this point, the page may be truncated or
2414 * invalidated (changing page->mapping to NULL), or
2415 * even swizzled back from swapper_space to tmpfs file
2416 * mapping. However, page->index will not change
2417 * because we have a reference on the page.
2419 if (page->index > end)
2423 * Accumulated enough dirty pages? This doesn't apply
2424 * to WB_SYNC_ALL mode. For integrity sync we have to
2425 * keep going because someone may be concurrently
2426 * dirtying pages, and we might have synced a lot of
2427 * newly appeared dirty pages, but have not synced all
2428 * of the old dirty pages.
2430 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2433 /* If we can't merge this page, we are done. */
2434 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2439 * If the page is no longer dirty, or its mapping no
2440 * longer corresponds to inode we are writing (which
2441 * means it has been truncated or invalidated), or the
2442 * page is already under writeback and we are not doing
2443 * a data integrity writeback, skip the page
2445 if (!PageDirty(page) ||
2446 (PageWriteback(page) &&
2447 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2448 unlikely(page->mapping != mapping)) {
2453 wait_on_page_writeback(page);
2454 BUG_ON(PageWriteback(page));
2456 if (mpd->map.m_len == 0)
2457 mpd->first_page = page->index;
2458 mpd->next_page = page->index + 1;
2459 /* Add all dirty buffers to mpd */
2460 lblk = ((ext4_lblk_t)page->index) <<
2461 (PAGE_CACHE_SHIFT - blkbits);
2462 head = page_buffers(page);
2463 err = mpage_process_page_bufs(mpd, head, head, lblk);
2469 pagevec_release(&pvec);
2474 pagevec_release(&pvec);
2478 static int __writepage(struct page *page, struct writeback_control *wbc,
2481 struct address_space *mapping = data;
2482 int ret = ext4_writepage(page, wbc);
2483 mapping_set_error(mapping, ret);
2487 static int ext4_writepages(struct address_space *mapping,
2488 struct writeback_control *wbc)
2490 pgoff_t writeback_index = 0;
2491 long nr_to_write = wbc->nr_to_write;
2492 int range_whole = 0;
2494 handle_t *handle = NULL;
2495 struct mpage_da_data mpd;
2496 struct inode *inode = mapping->host;
2497 int needed_blocks, rsv_blocks = 0, ret = 0;
2498 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2500 struct blk_plug plug;
2501 bool give_up_on_write = false;
2503 trace_ext4_writepages(inode, wbc);
2506 * No pages to write? This is mainly a kludge to avoid starting
2507 * a transaction for special inodes like journal inode on last iput()
2508 * because that could violate lock ordering on umount
2510 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2511 goto out_writepages;
2513 if (ext4_should_journal_data(inode)) {
2514 struct blk_plug plug;
2516 blk_start_plug(&plug);
2517 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2518 blk_finish_plug(&plug);
2519 goto out_writepages;
2523 * If the filesystem has aborted, it is read-only, so return
2524 * right away instead of dumping stack traces later on that
2525 * will obscure the real source of the problem. We test
2526 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2527 * the latter could be true if the filesystem is mounted
2528 * read-only, and in that case, ext4_writepages should
2529 * *never* be called, so if that ever happens, we would want
2532 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2534 goto out_writepages;
2537 if (ext4_should_dioread_nolock(inode)) {
2539 * We may need to convert up to one extent per block in
2540 * the page and we may dirty the inode.
2542 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2546 * If we have inline data and arrive here, it means that
2547 * we will soon create the block for the 1st page, so
2548 * we'd better clear the inline data here.
2550 if (ext4_has_inline_data(inode)) {
2551 /* Just inode will be modified... */
2552 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2553 if (IS_ERR(handle)) {
2554 ret = PTR_ERR(handle);
2555 goto out_writepages;
2557 BUG_ON(ext4_test_inode_state(inode,
2558 EXT4_STATE_MAY_INLINE_DATA));
2559 ext4_destroy_inline_data(handle, inode);
2560 ext4_journal_stop(handle);
2563 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2566 if (wbc->range_cyclic) {
2567 writeback_index = mapping->writeback_index;
2568 if (writeback_index)
2570 mpd.first_page = writeback_index;
2573 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2574 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2579 ext4_io_submit_init(&mpd.io_submit, wbc);
2581 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2582 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2584 blk_start_plug(&plug);
2585 while (!done && mpd.first_page <= mpd.last_page) {
2586 /* For each extent of pages we use new io_end */
2587 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2588 if (!mpd.io_submit.io_end) {
2594 * We have two constraints: We find one extent to map and we
2595 * must always write out whole page (makes a difference when
2596 * blocksize < pagesize) so that we don't block on IO when we
2597 * try to write out the rest of the page. Journalled mode is
2598 * not supported by delalloc.
2600 BUG_ON(ext4_should_journal_data(inode));
2601 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2603 /* start a new transaction */
2604 handle = ext4_journal_start_with_reserve(inode,
2605 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2606 if (IS_ERR(handle)) {
2607 ret = PTR_ERR(handle);
2608 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2609 "%ld pages, ino %lu; err %d", __func__,
2610 wbc->nr_to_write, inode->i_ino, ret);
2611 /* Release allocated io_end */
2612 ext4_put_io_end(mpd.io_submit.io_end);
2616 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2617 ret = mpage_prepare_extent_to_map(&mpd);
2620 ret = mpage_map_and_submit_extent(handle, &mpd,
2624 * We scanned the whole range (or exhausted
2625 * nr_to_write), submitted what was mapped and
2626 * didn't find anything needing mapping. We are
2633 * Caution: If the handle is synchronous,
2634 * ext4_journal_stop() can wait for transaction commit
2635 * to finish which may depend on writeback of pages to
2636 * complete or on page lock to be released. In that
2637 * case, we have to wait until after after we have
2638 * submitted all the IO, released page locks we hold,
2639 * and dropped io_end reference (for extent conversion
2640 * to be able to complete) before stopping the handle.
2642 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2643 ext4_journal_stop(handle);
2646 /* Submit prepared bio */
2647 ext4_io_submit(&mpd.io_submit);
2648 /* Unlock pages we didn't use */
2649 mpage_release_unused_pages(&mpd, give_up_on_write);
2651 * Drop our io_end reference we got from init. We have
2652 * to be careful and use deferred io_end finishing if
2653 * we are still holding the transaction as we can
2654 * release the last reference to io_end which may end
2655 * up doing unwritten extent conversion.
2658 ext4_put_io_end_defer(mpd.io_submit.io_end);
2659 ext4_journal_stop(handle);
2661 ext4_put_io_end(mpd.io_submit.io_end);
2663 if (ret == -ENOSPC && sbi->s_journal) {
2665 * Commit the transaction which would
2666 * free blocks released in the transaction
2669 jbd2_journal_force_commit_nested(sbi->s_journal);
2673 /* Fatal error - ENOMEM, EIO... */
2677 blk_finish_plug(&plug);
2678 if (!ret && !cycled && wbc->nr_to_write > 0) {
2680 mpd.last_page = writeback_index - 1;
2686 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2688 * Set the writeback_index so that range_cyclic
2689 * mode will write it back later
2691 mapping->writeback_index = mpd.first_page;
2694 trace_ext4_writepages_result(inode, wbc, ret,
2695 nr_to_write - wbc->nr_to_write);
2699 static int ext4_nonda_switch(struct super_block *sb)
2701 s64 free_clusters, dirty_clusters;
2702 struct ext4_sb_info *sbi = EXT4_SB(sb);
2705 * switch to non delalloc mode if we are running low
2706 * on free block. The free block accounting via percpu
2707 * counters can get slightly wrong with percpu_counter_batch getting
2708 * accumulated on each CPU without updating global counters
2709 * Delalloc need an accurate free block accounting. So switch
2710 * to non delalloc when we are near to error range.
2713 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2715 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2717 * Start pushing delalloc when 1/2 of free blocks are dirty.
2719 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2720 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2722 if (2 * free_clusters < 3 * dirty_clusters ||
2723 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2725 * free block count is less than 150% of dirty blocks
2726 * or free blocks is less than watermark
2733 /* We always reserve for an inode update; the superblock could be there too */
2734 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2736 if (likely(ext4_has_feature_large_file(inode->i_sb)))
2739 if (pos + len <= 0x7fffffffULL)
2742 /* We might need to update the superblock to set LARGE_FILE */
2746 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2747 loff_t pos, unsigned len, unsigned flags,
2748 struct page **pagep, void **fsdata)
2750 int ret, retries = 0;
2753 struct inode *inode = mapping->host;
2756 index = pos >> PAGE_CACHE_SHIFT;
2758 if (ext4_nonda_switch(inode->i_sb)) {
2759 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2760 return ext4_write_begin(file, mapping, pos,
2761 len, flags, pagep, fsdata);
2763 *fsdata = (void *)0;
2764 trace_ext4_da_write_begin(inode, pos, len, flags);
2766 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2767 ret = ext4_da_write_inline_data_begin(mapping, inode,
2777 * grab_cache_page_write_begin() can take a long time if the
2778 * system is thrashing due to memory pressure, or if the page
2779 * is being written back. So grab it first before we start
2780 * the transaction handle. This also allows us to allocate
2781 * the page (if needed) without using GFP_NOFS.
2784 page = grab_cache_page_write_begin(mapping, index, flags);
2790 * With delayed allocation, we don't log the i_disksize update
2791 * if there is delayed block allocation. But we still need
2792 * to journalling the i_disksize update if writes to the end
2793 * of file which has an already mapped buffer.
2796 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2797 ext4_da_write_credits(inode, pos, len));
2798 if (IS_ERR(handle)) {
2799 page_cache_release(page);
2800 return PTR_ERR(handle);
2804 if (page->mapping != mapping) {
2805 /* The page got truncated from under us */
2807 page_cache_release(page);
2808 ext4_journal_stop(handle);
2811 /* In case writeback began while the page was unlocked */
2812 wait_for_stable_page(page);
2814 #ifdef CONFIG_EXT4_FS_ENCRYPTION
2815 ret = ext4_block_write_begin(page, pos, len,
2816 ext4_da_get_block_prep);
2818 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2822 ext4_journal_stop(handle);
2824 * block_write_begin may have instantiated a few blocks
2825 * outside i_size. Trim these off again. Don't need
2826 * i_size_read because we hold i_mutex.
2828 if (pos + len > inode->i_size)
2829 ext4_truncate_failed_write(inode);
2831 if (ret == -ENOSPC &&
2832 ext4_should_retry_alloc(inode->i_sb, &retries))
2835 page_cache_release(page);
2844 * Check if we should update i_disksize
2845 * when write to the end of file but not require block allocation
2847 static int ext4_da_should_update_i_disksize(struct page *page,
2848 unsigned long offset)
2850 struct buffer_head *bh;
2851 struct inode *inode = page->mapping->host;
2855 bh = page_buffers(page);
2856 idx = offset >> inode->i_blkbits;
2858 for (i = 0; i < idx; i++)
2859 bh = bh->b_this_page;
2861 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2866 static int ext4_da_write_end(struct file *file,
2867 struct address_space *mapping,
2868 loff_t pos, unsigned len, unsigned copied,
2869 struct page *page, void *fsdata)
2871 struct inode *inode = mapping->host;
2873 handle_t *handle = ext4_journal_current_handle();
2875 unsigned long start, end;
2876 int write_mode = (int)(unsigned long)fsdata;
2878 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2879 return ext4_write_end(file, mapping, pos,
2880 len, copied, page, fsdata);
2882 trace_ext4_da_write_end(inode, pos, len, copied);
2883 start = pos & (PAGE_CACHE_SIZE - 1);
2884 end = start + copied - 1;
2887 * generic_write_end() will run mark_inode_dirty() if i_size
2888 * changes. So let's piggyback the i_disksize mark_inode_dirty
2891 new_i_size = pos + copied;
2892 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2893 if (ext4_has_inline_data(inode) ||
2894 ext4_da_should_update_i_disksize(page, end)) {
2895 ext4_update_i_disksize(inode, new_i_size);
2896 /* We need to mark inode dirty even if
2897 * new_i_size is less that inode->i_size
2898 * bu greater than i_disksize.(hint delalloc)
2900 ext4_mark_inode_dirty(handle, inode);
2904 if (write_mode != CONVERT_INLINE_DATA &&
2905 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2906 ext4_has_inline_data(inode))
2907 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2910 ret2 = generic_write_end(file, mapping, pos, len, copied,
2916 ret2 = ext4_journal_stop(handle);
2920 return ret ? ret : copied;
2923 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2924 unsigned int length)
2927 * Drop reserved blocks
2929 BUG_ON(!PageLocked(page));
2930 if (!page_has_buffers(page))
2933 ext4_da_page_release_reservation(page, offset, length);
2936 ext4_invalidatepage(page, offset, length);
2942 * Force all delayed allocation blocks to be allocated for a given inode.
2944 int ext4_alloc_da_blocks(struct inode *inode)
2946 trace_ext4_alloc_da_blocks(inode);
2948 if (!EXT4_I(inode)->i_reserved_data_blocks)
2952 * We do something simple for now. The filemap_flush() will
2953 * also start triggering a write of the data blocks, which is
2954 * not strictly speaking necessary (and for users of
2955 * laptop_mode, not even desirable). However, to do otherwise
2956 * would require replicating code paths in:
2958 * ext4_writepages() ->
2959 * write_cache_pages() ---> (via passed in callback function)
2960 * __mpage_da_writepage() -->
2961 * mpage_add_bh_to_extent()
2962 * mpage_da_map_blocks()
2964 * The problem is that write_cache_pages(), located in
2965 * mm/page-writeback.c, marks pages clean in preparation for
2966 * doing I/O, which is not desirable if we're not planning on
2969 * We could call write_cache_pages(), and then redirty all of
2970 * the pages by calling redirty_page_for_writepage() but that
2971 * would be ugly in the extreme. So instead we would need to
2972 * replicate parts of the code in the above functions,
2973 * simplifying them because we wouldn't actually intend to
2974 * write out the pages, but rather only collect contiguous
2975 * logical block extents, call the multi-block allocator, and
2976 * then update the buffer heads with the block allocations.
2978 * For now, though, we'll cheat by calling filemap_flush(),
2979 * which will map the blocks, and start the I/O, but not
2980 * actually wait for the I/O to complete.
2982 return filemap_flush(inode->i_mapping);
2986 * bmap() is special. It gets used by applications such as lilo and by
2987 * the swapper to find the on-disk block of a specific piece of data.
2989 * Naturally, this is dangerous if the block concerned is still in the
2990 * journal. If somebody makes a swapfile on an ext4 data-journaling
2991 * filesystem and enables swap, then they may get a nasty shock when the
2992 * data getting swapped to that swapfile suddenly gets overwritten by
2993 * the original zero's written out previously to the journal and
2994 * awaiting writeback in the kernel's buffer cache.
2996 * So, if we see any bmap calls here on a modified, data-journaled file,
2997 * take extra steps to flush any blocks which might be in the cache.
2999 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3001 struct inode *inode = mapping->host;
3006 * We can get here for an inline file via the FIBMAP ioctl
3008 if (ext4_has_inline_data(inode))
3011 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3012 test_opt(inode->i_sb, DELALLOC)) {
3014 * With delalloc we want to sync the file
3015 * so that we can make sure we allocate
3018 filemap_write_and_wait(mapping);
3021 if (EXT4_JOURNAL(inode) &&
3022 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3024 * This is a REALLY heavyweight approach, but the use of
3025 * bmap on dirty files is expected to be extremely rare:
3026 * only if we run lilo or swapon on a freshly made file
3027 * do we expect this to happen.
3029 * (bmap requires CAP_SYS_RAWIO so this does not
3030 * represent an unprivileged user DOS attack --- we'd be
3031 * in trouble if mortal users could trigger this path at
3034 * NB. EXT4_STATE_JDATA is not set on files other than
3035 * regular files. If somebody wants to bmap a directory
3036 * or symlink and gets confused because the buffer
3037 * hasn't yet been flushed to disk, they deserve
3038 * everything they get.
3041 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3042 journal = EXT4_JOURNAL(inode);
3043 jbd2_journal_lock_updates(journal);
3044 err = jbd2_journal_flush(journal);
3045 jbd2_journal_unlock_updates(journal);
3051 return generic_block_bmap(mapping, block, ext4_get_block);
3054 static int ext4_readpage(struct file *file, struct page *page)
3057 struct inode *inode = page->mapping->host;
3059 trace_ext4_readpage(page);
3061 if (ext4_has_inline_data(inode))
3062 ret = ext4_readpage_inline(inode, page);
3065 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
3071 ext4_readpages(struct file *file, struct address_space *mapping,
3072 struct list_head *pages, unsigned nr_pages)
3074 struct inode *inode = mapping->host;
3076 /* If the file has inline data, no need to do readpages. */
3077 if (ext4_has_inline_data(inode))
3080 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3083 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3084 unsigned int length)
3086 trace_ext4_invalidatepage(page, offset, length);
3088 /* No journalling happens on data buffers when this function is used */
3089 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3091 block_invalidatepage(page, offset, length);
3094 static int __ext4_journalled_invalidatepage(struct page *page,
3095 unsigned int offset,
3096 unsigned int length)
3098 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3100 trace_ext4_journalled_invalidatepage(page, offset, length);
3103 * If it's a full truncate we just forget about the pending dirtying
3105 if (offset == 0 && length == PAGE_CACHE_SIZE)
3106 ClearPageChecked(page);
3108 return jbd2_journal_invalidatepage(journal, page, offset, length);
3111 /* Wrapper for aops... */
3112 static void ext4_journalled_invalidatepage(struct page *page,
3113 unsigned int offset,
3114 unsigned int length)
3116 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3119 static int ext4_releasepage(struct page *page, gfp_t wait)
3121 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3123 trace_ext4_releasepage(page);
3125 /* Page has dirty journalled data -> cannot release */
3126 if (PageChecked(page))
3129 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3131 return try_to_free_buffers(page);
3135 * ext4_get_block used when preparing for a DIO write or buffer write.
3136 * We allocate an uinitialized extent if blocks haven't been allocated.
3137 * The extent will be converted to initialized after the IO is complete.
3139 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3140 struct buffer_head *bh_result, int create)
3142 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3143 inode->i_ino, create);
3144 return _ext4_get_block(inode, iblock, bh_result,
3145 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3148 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3149 struct buffer_head *bh_result, int create)
3151 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3152 inode->i_ino, create);
3153 return _ext4_get_block(inode, iblock, bh_result,
3154 EXT4_GET_BLOCKS_NO_LOCK);
3157 int ext4_get_block_dax(struct inode *inode, sector_t iblock,
3158 struct buffer_head *bh_result, int create)
3160 int flags = EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_UNWRIT_EXT;
3162 flags |= EXT4_GET_BLOCKS_CREATE;
3163 ext4_debug("ext4_get_block_dax: inode %lu, create flag %d\n",
3164 inode->i_ino, create);
3165 return _ext4_get_block(inode, iblock, bh_result, flags);
3168 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3169 ssize_t size, void *private)
3171 ext4_io_end_t *io_end = iocb->private;
3173 /* if not async direct IO just return */
3177 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3178 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3179 iocb->private, io_end->inode->i_ino, iocb, offset,
3182 iocb->private = NULL;
3183 io_end->offset = offset;
3184 io_end->size = size;
3185 ext4_put_io_end(io_end);
3189 * For ext4 extent files, ext4 will do direct-io write to holes,
3190 * preallocated extents, and those write extend the file, no need to
3191 * fall back to buffered IO.
3193 * For holes, we fallocate those blocks, mark them as unwritten
3194 * If those blocks were preallocated, we mark sure they are split, but
3195 * still keep the range to write as unwritten.
3197 * The unwritten extents will be converted to written when DIO is completed.
3198 * For async direct IO, since the IO may still pending when return, we
3199 * set up an end_io call back function, which will do the conversion
3200 * when async direct IO completed.
3202 * If the O_DIRECT write will extend the file then add this inode to the
3203 * orphan list. So recovery will truncate it back to the original size
3204 * if the machine crashes during the write.
3207 static ssize_t ext4_ext_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3210 struct file *file = iocb->ki_filp;
3211 struct inode *inode = file->f_mapping->host;
3213 size_t count = iov_iter_count(iter);
3215 get_block_t *get_block_func = NULL;
3217 loff_t final_size = offset + count;
3218 ext4_io_end_t *io_end = NULL;
3220 /* Use the old path for reads and writes beyond i_size. */
3221 if (iov_iter_rw(iter) != WRITE || final_size > inode->i_size)
3222 return ext4_ind_direct_IO(iocb, iter, offset);
3224 BUG_ON(iocb->private == NULL);
3227 * Make all waiters for direct IO properly wait also for extent
3228 * conversion. This also disallows race between truncate() and
3229 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3231 if (iov_iter_rw(iter) == WRITE)
3232 inode_dio_begin(inode);
3234 /* If we do a overwrite dio, i_mutex locking can be released */
3235 overwrite = *((int *)iocb->private);
3238 down_read(&EXT4_I(inode)->i_data_sem);
3239 mutex_unlock(&inode->i_mutex);
3243 * We could direct write to holes and fallocate.
3245 * Allocated blocks to fill the hole are marked as
3246 * unwritten to prevent parallel buffered read to expose
3247 * the stale data before DIO complete the data IO.
3249 * As to previously fallocated extents, ext4 get_block will
3250 * just simply mark the buffer mapped but still keep the
3251 * extents unwritten.
3253 * For non AIO case, we will convert those unwritten extents
3254 * to written after return back from blockdev_direct_IO.
3256 * For async DIO, the conversion needs to be deferred when the
3257 * IO is completed. The ext4 end_io callback function will be
3258 * called to take care of the conversion work. Here for async
3259 * case, we allocate an io_end structure to hook to the iocb.
3261 iocb->private = NULL;
3263 get_block_func = ext4_get_block_write_nolock;
3265 ext4_inode_aio_set(inode, NULL);
3266 if (!is_sync_kiocb(iocb)) {
3267 io_end = ext4_init_io_end(inode, GFP_NOFS);
3273 * Grab reference for DIO. Will be dropped in
3276 iocb->private = ext4_get_io_end(io_end);
3278 * we save the io structure for current async direct
3279 * IO, so that later ext4_map_blocks() could flag the
3280 * io structure whether there is a unwritten extents
3281 * needs to be converted when IO is completed.
3283 ext4_inode_aio_set(inode, io_end);
3285 get_block_func = ext4_get_block_write;
3286 dio_flags = DIO_LOCKING;
3288 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3289 BUG_ON(ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode));
3292 ret = dax_do_io(iocb, inode, iter, offset, get_block_func,
3293 ext4_end_io_dio, dio_flags);
3295 ret = __blockdev_direct_IO(iocb, inode,
3296 inode->i_sb->s_bdev, iter, offset,
3298 ext4_end_io_dio, NULL, dio_flags);
3301 * Put our reference to io_end. This can free the io_end structure e.g.
3302 * in sync IO case or in case of error. It can even perform extent
3303 * conversion if all bios we submitted finished before we got here.
3304 * Note that in that case iocb->private can be already set to NULL
3308 ext4_inode_aio_set(inode, NULL);
3309 ext4_put_io_end(io_end);
3311 * When no IO was submitted ext4_end_io_dio() was not
3312 * called so we have to put iocb's reference.
3314 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3315 WARN_ON(iocb->private != io_end);
3316 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3317 ext4_put_io_end(io_end);
3318 iocb->private = NULL;
3321 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3322 EXT4_STATE_DIO_UNWRITTEN)) {
3325 * for non AIO case, since the IO is already
3326 * completed, we could do the conversion right here
3328 err = ext4_convert_unwritten_extents(NULL, inode,
3332 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3336 if (iov_iter_rw(iter) == WRITE)
3337 inode_dio_end(inode);
3338 /* take i_mutex locking again if we do a ovewrite dio */
3340 up_read(&EXT4_I(inode)->i_data_sem);
3341 mutex_lock(&inode->i_mutex);
3347 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3350 struct file *file = iocb->ki_filp;
3351 struct inode *inode = file->f_mapping->host;
3352 size_t count = iov_iter_count(iter);
3355 if (iov_iter_rw(iter) == READ) {
3356 loff_t size = i_size_read(inode);
3362 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3363 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3368 * If we are doing data journalling we don't support O_DIRECT
3370 if (ext4_should_journal_data(inode))
3373 /* Let buffer I/O handle the inline data case. */
3374 if (ext4_has_inline_data(inode))
3377 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3378 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3379 ret = ext4_ext_direct_IO(iocb, iter, offset);
3381 ret = ext4_ind_direct_IO(iocb, iter, offset);
3382 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3387 * Pages can be marked dirty completely asynchronously from ext4's journalling
3388 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3389 * much here because ->set_page_dirty is called under VFS locks. The page is
3390 * not necessarily locked.
3392 * We cannot just dirty the page and leave attached buffers clean, because the
3393 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3394 * or jbddirty because all the journalling code will explode.
3396 * So what we do is to mark the page "pending dirty" and next time writepage
3397 * is called, propagate that into the buffers appropriately.
3399 static int ext4_journalled_set_page_dirty(struct page *page)
3401 SetPageChecked(page);
3402 return __set_page_dirty_nobuffers(page);
3405 static const struct address_space_operations ext4_aops = {
3406 .readpage = ext4_readpage,
3407 .readpages = ext4_readpages,
3408 .writepage = ext4_writepage,
3409 .writepages = ext4_writepages,
3410 .write_begin = ext4_write_begin,
3411 .write_end = ext4_write_end,
3413 .invalidatepage = ext4_invalidatepage,
3414 .releasepage = ext4_releasepage,
3415 .direct_IO = ext4_direct_IO,
3416 .migratepage = buffer_migrate_page,
3417 .is_partially_uptodate = block_is_partially_uptodate,
3418 .error_remove_page = generic_error_remove_page,
3421 static const struct address_space_operations ext4_journalled_aops = {
3422 .readpage = ext4_readpage,
3423 .readpages = ext4_readpages,
3424 .writepage = ext4_writepage,
3425 .writepages = ext4_writepages,
3426 .write_begin = ext4_write_begin,
3427 .write_end = ext4_journalled_write_end,
3428 .set_page_dirty = ext4_journalled_set_page_dirty,
3430 .invalidatepage = ext4_journalled_invalidatepage,
3431 .releasepage = ext4_releasepage,
3432 .direct_IO = ext4_direct_IO,
3433 .is_partially_uptodate = block_is_partially_uptodate,
3434 .error_remove_page = generic_error_remove_page,
3437 static const struct address_space_operations ext4_da_aops = {
3438 .readpage = ext4_readpage,
3439 .readpages = ext4_readpages,
3440 .writepage = ext4_writepage,
3441 .writepages = ext4_writepages,
3442 .write_begin = ext4_da_write_begin,
3443 .write_end = ext4_da_write_end,
3445 .invalidatepage = ext4_da_invalidatepage,
3446 .releasepage = ext4_releasepage,
3447 .direct_IO = ext4_direct_IO,
3448 .migratepage = buffer_migrate_page,
3449 .is_partially_uptodate = block_is_partially_uptodate,
3450 .error_remove_page = generic_error_remove_page,
3453 void ext4_set_aops(struct inode *inode)
3455 switch (ext4_inode_journal_mode(inode)) {
3456 case EXT4_INODE_ORDERED_DATA_MODE:
3457 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3459 case EXT4_INODE_WRITEBACK_DATA_MODE:
3460 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3462 case EXT4_INODE_JOURNAL_DATA_MODE:
3463 inode->i_mapping->a_ops = &ext4_journalled_aops;
3468 if (test_opt(inode->i_sb, DELALLOC))
3469 inode->i_mapping->a_ops = &ext4_da_aops;
3471 inode->i_mapping->a_ops = &ext4_aops;
3474 static int __ext4_block_zero_page_range(handle_t *handle,
3475 struct address_space *mapping, loff_t from, loff_t length)
3477 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3478 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3479 unsigned blocksize, pos;
3481 struct inode *inode = mapping->host;
3482 struct buffer_head *bh;
3486 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3487 mapping_gfp_constraint(mapping, ~__GFP_FS));
3491 blocksize = inode->i_sb->s_blocksize;
3493 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3495 if (!page_has_buffers(page))
3496 create_empty_buffers(page, blocksize, 0);
3498 /* Find the buffer that contains "offset" */
3499 bh = page_buffers(page);
3501 while (offset >= pos) {
3502 bh = bh->b_this_page;
3506 if (buffer_freed(bh)) {
3507 BUFFER_TRACE(bh, "freed: skip");
3510 if (!buffer_mapped(bh)) {
3511 BUFFER_TRACE(bh, "unmapped");
3512 ext4_get_block(inode, iblock, bh, 0);
3513 /* unmapped? It's a hole - nothing to do */
3514 if (!buffer_mapped(bh)) {
3515 BUFFER_TRACE(bh, "still unmapped");
3520 /* Ok, it's mapped. Make sure it's up-to-date */
3521 if (PageUptodate(page))
3522 set_buffer_uptodate(bh);
3524 if (!buffer_uptodate(bh)) {
3526 ll_rw_block(READ, 1, &bh);
3528 /* Uhhuh. Read error. Complain and punt. */
3529 if (!buffer_uptodate(bh))
3531 if (S_ISREG(inode->i_mode) &&
3532 ext4_encrypted_inode(inode)) {
3533 /* We expect the key to be set. */
3534 BUG_ON(!ext4_has_encryption_key(inode));
3535 BUG_ON(blocksize != PAGE_CACHE_SIZE);
3536 WARN_ON_ONCE(ext4_decrypt(page));
3539 if (ext4_should_journal_data(inode)) {
3540 BUFFER_TRACE(bh, "get write access");
3541 err = ext4_journal_get_write_access(handle, bh);
3545 zero_user(page, offset, length);
3546 BUFFER_TRACE(bh, "zeroed end of block");
3548 if (ext4_should_journal_data(inode)) {
3549 err = ext4_handle_dirty_metadata(handle, inode, bh);
3552 mark_buffer_dirty(bh);
3553 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3554 err = ext4_jbd2_file_inode(handle, inode);
3559 page_cache_release(page);
3564 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3565 * starting from file offset 'from'. The range to be zero'd must
3566 * be contained with in one block. If the specified range exceeds
3567 * the end of the block it will be shortened to end of the block
3568 * that cooresponds to 'from'
3570 static int ext4_block_zero_page_range(handle_t *handle,
3571 struct address_space *mapping, loff_t from, loff_t length)
3573 struct inode *inode = mapping->host;
3574 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3575 unsigned blocksize = inode->i_sb->s_blocksize;
3576 unsigned max = blocksize - (offset & (blocksize - 1));
3579 * correct length if it does not fall between
3580 * 'from' and the end of the block
3582 if (length > max || length < 0)
3586 return dax_zero_page_range(inode, from, length, ext4_get_block);
3587 return __ext4_block_zero_page_range(handle, mapping, from, length);
3591 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3592 * up to the end of the block which corresponds to `from'.
3593 * This required during truncate. We need to physically zero the tail end
3594 * of that block so it doesn't yield old data if the file is later grown.
3596 static int ext4_block_truncate_page(handle_t *handle,
3597 struct address_space *mapping, loff_t from)
3599 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3602 struct inode *inode = mapping->host;
3604 /* If we are processing an encrypted inode during orphan list handling */
3605 if (ext4_encrypted_inode(inode) && !ext4_has_encryption_key(inode))
3608 blocksize = inode->i_sb->s_blocksize;
3609 length = blocksize - (offset & (blocksize - 1));
3611 return ext4_block_zero_page_range(handle, mapping, from, length);
3614 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3615 loff_t lstart, loff_t length)
3617 struct super_block *sb = inode->i_sb;
3618 struct address_space *mapping = inode->i_mapping;
3619 unsigned partial_start, partial_end;
3620 ext4_fsblk_t start, end;
3621 loff_t byte_end = (lstart + length - 1);
3624 partial_start = lstart & (sb->s_blocksize - 1);
3625 partial_end = byte_end & (sb->s_blocksize - 1);
3627 start = lstart >> sb->s_blocksize_bits;
3628 end = byte_end >> sb->s_blocksize_bits;
3630 /* Handle partial zero within the single block */
3632 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3633 err = ext4_block_zero_page_range(handle, mapping,
3637 /* Handle partial zero out on the start of the range */
3638 if (partial_start) {
3639 err = ext4_block_zero_page_range(handle, mapping,
3640 lstart, sb->s_blocksize);
3644 /* Handle partial zero out on the end of the range */
3645 if (partial_end != sb->s_blocksize - 1)
3646 err = ext4_block_zero_page_range(handle, mapping,
3647 byte_end - partial_end,
3652 int ext4_can_truncate(struct inode *inode)
3654 if (S_ISREG(inode->i_mode))
3656 if (S_ISDIR(inode->i_mode))
3658 if (S_ISLNK(inode->i_mode))
3659 return !ext4_inode_is_fast_symlink(inode);
3664 * We have to make sure i_disksize gets properly updated before we truncate
3665 * page cache due to hole punching or zero range. Otherwise i_disksize update
3666 * can get lost as it may have been postponed to submission of writeback but
3667 * that will never happen after we truncate page cache.
3669 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3673 loff_t size = i_size_read(inode);
3675 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3676 if (offset > size || offset + len < size)
3679 if (EXT4_I(inode)->i_disksize >= size)
3682 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3684 return PTR_ERR(handle);
3685 ext4_update_i_disksize(inode, size);
3686 ext4_mark_inode_dirty(handle, inode);
3687 ext4_journal_stop(handle);
3693 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3694 * associated with the given offset and length
3696 * @inode: File inode
3697 * @offset: The offset where the hole will begin
3698 * @len: The length of the hole
3700 * Returns: 0 on success or negative on failure
3703 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3705 struct super_block *sb = inode->i_sb;
3706 ext4_lblk_t first_block, stop_block;
3707 struct address_space *mapping = inode->i_mapping;
3708 loff_t first_block_offset, last_block_offset;
3710 unsigned int credits;
3713 if (!S_ISREG(inode->i_mode))
3716 trace_ext4_punch_hole(inode, offset, length, 0);
3718 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
3719 if (ext4_has_inline_data(inode)) {
3720 down_write(&EXT4_I(inode)->i_mmap_sem);
3721 ret = ext4_convert_inline_data(inode);
3722 up_write(&EXT4_I(inode)->i_mmap_sem);
3728 * Write out all dirty pages to avoid race conditions
3729 * Then release them.
3731 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3732 ret = filemap_write_and_wait_range(mapping, offset,
3733 offset + length - 1);
3738 mutex_lock(&inode->i_mutex);
3740 /* No need to punch hole beyond i_size */
3741 if (offset >= inode->i_size)
3745 * If the hole extends beyond i_size, set the hole
3746 * to end after the page that contains i_size
3748 if (offset + length > inode->i_size) {
3749 length = inode->i_size +
3750 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3754 if (offset & (sb->s_blocksize - 1) ||
3755 (offset + length) & (sb->s_blocksize - 1)) {
3757 * Attach jinode to inode for jbd2 if we do any zeroing of
3760 ret = ext4_inode_attach_jinode(inode);
3766 /* Wait all existing dio workers, newcomers will block on i_mutex */
3767 ext4_inode_block_unlocked_dio(inode);
3768 inode_dio_wait(inode);
3771 * Prevent page faults from reinstantiating pages we have released from
3774 down_write(&EXT4_I(inode)->i_mmap_sem);
3775 first_block_offset = round_up(offset, sb->s_blocksize);
3776 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3778 /* Now release the pages and zero block aligned part of pages*/
3779 if (last_block_offset > first_block_offset) {
3780 ret = ext4_update_disksize_before_punch(inode, offset, length);
3783 truncate_pagecache_range(inode, first_block_offset,
3787 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3788 credits = ext4_writepage_trans_blocks(inode);
3790 credits = ext4_blocks_for_truncate(inode);
3791 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3792 if (IS_ERR(handle)) {
3793 ret = PTR_ERR(handle);
3794 ext4_std_error(sb, ret);
3798 ret = ext4_zero_partial_blocks(handle, inode, offset,
3803 first_block = (offset + sb->s_blocksize - 1) >>
3804 EXT4_BLOCK_SIZE_BITS(sb);
3805 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3807 /* If there are blocks to remove, do it */
3808 if (stop_block > first_block) {
3810 down_write(&EXT4_I(inode)->i_data_sem);
3811 ext4_discard_preallocations(inode);
3813 ret = ext4_es_remove_extent(inode, first_block,
3814 stop_block - first_block);
3816 up_write(&EXT4_I(inode)->i_data_sem);
3820 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3821 ret = ext4_ext_remove_space(inode, first_block,
3824 ret = ext4_ind_remove_space(handle, inode, first_block,
3827 up_write(&EXT4_I(inode)->i_data_sem);
3830 ext4_handle_sync(handle);
3832 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3833 ext4_mark_inode_dirty(handle, inode);
3835 ext4_update_inode_fsync_trans(handle, inode, 1);
3837 ext4_journal_stop(handle);
3839 up_write(&EXT4_I(inode)->i_mmap_sem);
3840 ext4_inode_resume_unlocked_dio(inode);
3842 mutex_unlock(&inode->i_mutex);
3846 int ext4_inode_attach_jinode(struct inode *inode)
3848 struct ext4_inode_info *ei = EXT4_I(inode);
3849 struct jbd2_inode *jinode;
3851 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3854 jinode = jbd2_alloc_inode(GFP_KERNEL);
3855 spin_lock(&inode->i_lock);
3858 spin_unlock(&inode->i_lock);
3861 ei->jinode = jinode;
3862 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3865 spin_unlock(&inode->i_lock);
3866 if (unlikely(jinode != NULL))
3867 jbd2_free_inode(jinode);
3874 * We block out ext4_get_block() block instantiations across the entire
3875 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3876 * simultaneously on behalf of the same inode.
3878 * As we work through the truncate and commit bits of it to the journal there
3879 * is one core, guiding principle: the file's tree must always be consistent on
3880 * disk. We must be able to restart the truncate after a crash.
3882 * The file's tree may be transiently inconsistent in memory (although it
3883 * probably isn't), but whenever we close off and commit a journal transaction,
3884 * the contents of (the filesystem + the journal) must be consistent and
3885 * restartable. It's pretty simple, really: bottom up, right to left (although
3886 * left-to-right works OK too).
3888 * Note that at recovery time, journal replay occurs *before* the restart of
3889 * truncate against the orphan inode list.
3891 * The committed inode has the new, desired i_size (which is the same as
3892 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3893 * that this inode's truncate did not complete and it will again call
3894 * ext4_truncate() to have another go. So there will be instantiated blocks
3895 * to the right of the truncation point in a crashed ext4 filesystem. But
3896 * that's fine - as long as they are linked from the inode, the post-crash
3897 * ext4_truncate() run will find them and release them.
3899 void ext4_truncate(struct inode *inode)
3901 struct ext4_inode_info *ei = EXT4_I(inode);
3902 unsigned int credits;
3904 struct address_space *mapping = inode->i_mapping;
3907 * There is a possibility that we're either freeing the inode
3908 * or it's a completely new inode. In those cases we might not
3909 * have i_mutex locked because it's not necessary.
3911 if (!(inode->i_state & (I_NEW|I_FREEING)))
3912 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3913 trace_ext4_truncate_enter(inode);
3915 if (!ext4_can_truncate(inode))
3918 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3920 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3921 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3923 if (ext4_has_inline_data(inode)) {
3926 ext4_inline_data_truncate(inode, &has_inline);
3931 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3932 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3933 if (ext4_inode_attach_jinode(inode) < 0)
3937 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3938 credits = ext4_writepage_trans_blocks(inode);
3940 credits = ext4_blocks_for_truncate(inode);
3942 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3943 if (IS_ERR(handle)) {
3944 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3948 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3949 ext4_block_truncate_page(handle, mapping, inode->i_size);
3952 * We add the inode to the orphan list, so that if this
3953 * truncate spans multiple transactions, and we crash, we will
3954 * resume the truncate when the filesystem recovers. It also
3955 * marks the inode dirty, to catch the new size.
3957 * Implication: the file must always be in a sane, consistent
3958 * truncatable state while each transaction commits.
3960 if (ext4_orphan_add(handle, inode))
3963 down_write(&EXT4_I(inode)->i_data_sem);
3965 ext4_discard_preallocations(inode);
3967 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3968 ext4_ext_truncate(handle, inode);
3970 ext4_ind_truncate(handle, inode);
3972 up_write(&ei->i_data_sem);
3975 ext4_handle_sync(handle);
3979 * If this was a simple ftruncate() and the file will remain alive,
3980 * then we need to clear up the orphan record which we created above.
3981 * However, if this was a real unlink then we were called by
3982 * ext4_evict_inode(), and we allow that function to clean up the
3983 * orphan info for us.
3986 ext4_orphan_del(handle, inode);
3988 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3989 ext4_mark_inode_dirty(handle, inode);
3990 ext4_journal_stop(handle);
3992 trace_ext4_truncate_exit(inode);
3996 * ext4_get_inode_loc returns with an extra refcount against the inode's
3997 * underlying buffer_head on success. If 'in_mem' is true, we have all
3998 * data in memory that is needed to recreate the on-disk version of this
4001 static int __ext4_get_inode_loc(struct inode *inode,
4002 struct ext4_iloc *iloc, int in_mem)
4004 struct ext4_group_desc *gdp;
4005 struct buffer_head *bh;
4006 struct super_block *sb = inode->i_sb;
4008 int inodes_per_block, inode_offset;
4011 if (inode->i_ino < EXT4_ROOT_INO ||
4012 inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4013 return -EFSCORRUPTED;
4015 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4016 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4021 * Figure out the offset within the block group inode table
4023 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4024 inode_offset = ((inode->i_ino - 1) %
4025 EXT4_INODES_PER_GROUP(sb));
4026 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4027 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4029 bh = sb_getblk(sb, block);
4032 if (!buffer_uptodate(bh)) {
4036 * If the buffer has the write error flag, we have failed
4037 * to write out another inode in the same block. In this
4038 * case, we don't have to read the block because we may
4039 * read the old inode data successfully.
4041 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4042 set_buffer_uptodate(bh);
4044 if (buffer_uptodate(bh)) {
4045 /* someone brought it uptodate while we waited */
4051 * If we have all information of the inode in memory and this
4052 * is the only valid inode in the block, we need not read the
4056 struct buffer_head *bitmap_bh;
4059 start = inode_offset & ~(inodes_per_block - 1);
4061 /* Is the inode bitmap in cache? */
4062 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4063 if (unlikely(!bitmap_bh))
4067 * If the inode bitmap isn't in cache then the
4068 * optimisation may end up performing two reads instead
4069 * of one, so skip it.
4071 if (!buffer_uptodate(bitmap_bh)) {
4075 for (i = start; i < start + inodes_per_block; i++) {
4076 if (i == inode_offset)
4078 if (ext4_test_bit(i, bitmap_bh->b_data))
4082 if (i == start + inodes_per_block) {
4083 /* all other inodes are free, so skip I/O */
4084 memset(bh->b_data, 0, bh->b_size);
4085 set_buffer_uptodate(bh);
4093 * If we need to do any I/O, try to pre-readahead extra
4094 * blocks from the inode table.
4096 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4097 ext4_fsblk_t b, end, table;
4099 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4101 table = ext4_inode_table(sb, gdp);
4102 /* s_inode_readahead_blks is always a power of 2 */
4103 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4107 num = EXT4_INODES_PER_GROUP(sb);
4108 if (ext4_has_group_desc_csum(sb))
4109 num -= ext4_itable_unused_count(sb, gdp);
4110 table += num / inodes_per_block;
4114 sb_breadahead(sb, b++);
4118 * There are other valid inodes in the buffer, this inode
4119 * has in-inode xattrs, or we don't have this inode in memory.
4120 * Read the block from disk.
4122 trace_ext4_load_inode(inode);
4124 bh->b_end_io = end_buffer_read_sync;
4125 submit_bh(READ | REQ_META | REQ_PRIO, bh);
4127 if (!buffer_uptodate(bh)) {
4128 EXT4_ERROR_INODE_BLOCK(inode, block,
4129 "unable to read itable block");
4139 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4141 /* We have all inode data except xattrs in memory here. */
4142 return __ext4_get_inode_loc(inode, iloc,
4143 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4146 void ext4_set_inode_flags(struct inode *inode)
4148 unsigned int flags = EXT4_I(inode)->i_flags;
4149 unsigned int new_fl = 0;
4151 if (flags & EXT4_SYNC_FL)
4153 if (flags & EXT4_APPEND_FL)
4155 if (flags & EXT4_IMMUTABLE_FL)
4156 new_fl |= S_IMMUTABLE;
4157 if (flags & EXT4_NOATIME_FL)
4158 new_fl |= S_NOATIME;
4159 if (flags & EXT4_DIRSYNC_FL)
4160 new_fl |= S_DIRSYNC;
4161 if (test_opt(inode->i_sb, DAX))
4163 inode_set_flags(inode, new_fl,
4164 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4167 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4168 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4170 unsigned int vfs_fl;
4171 unsigned long old_fl, new_fl;
4174 vfs_fl = ei->vfs_inode.i_flags;
4175 old_fl = ei->i_flags;
4176 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4177 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4179 if (vfs_fl & S_SYNC)
4180 new_fl |= EXT4_SYNC_FL;
4181 if (vfs_fl & S_APPEND)
4182 new_fl |= EXT4_APPEND_FL;
4183 if (vfs_fl & S_IMMUTABLE)
4184 new_fl |= EXT4_IMMUTABLE_FL;
4185 if (vfs_fl & S_NOATIME)
4186 new_fl |= EXT4_NOATIME_FL;
4187 if (vfs_fl & S_DIRSYNC)
4188 new_fl |= EXT4_DIRSYNC_FL;
4189 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4192 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4193 struct ext4_inode_info *ei)
4196 struct inode *inode = &(ei->vfs_inode);
4197 struct super_block *sb = inode->i_sb;
4199 if (ext4_has_feature_huge_file(sb)) {
4200 /* we are using combined 48 bit field */
4201 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4202 le32_to_cpu(raw_inode->i_blocks_lo);
4203 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4204 /* i_blocks represent file system block size */
4205 return i_blocks << (inode->i_blkbits - 9);
4210 return le32_to_cpu(raw_inode->i_blocks_lo);
4214 static inline void ext4_iget_extra_inode(struct inode *inode,
4215 struct ext4_inode *raw_inode,
4216 struct ext4_inode_info *ei)
4218 __le32 *magic = (void *)raw_inode +
4219 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4220 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4221 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4222 ext4_find_inline_data_nolock(inode);
4224 EXT4_I(inode)->i_inline_off = 0;
4227 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4228 ext4_iget_flags flags, const char *function,
4231 struct ext4_iloc iloc;
4232 struct ext4_inode *raw_inode;
4233 struct ext4_inode_info *ei;
4234 struct inode *inode;
4235 journal_t *journal = EXT4_SB(sb)->s_journal;
4242 if ((!(flags & EXT4_IGET_SPECIAL) &&
4243 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4244 (ino < EXT4_ROOT_INO) ||
4245 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4246 if (flags & EXT4_IGET_HANDLE)
4247 return ERR_PTR(-ESTALE);
4248 __ext4_error(sb, function, line,
4249 "inode #%lu: comm %s: iget: illegal inode #",
4250 ino, current->comm);
4251 return ERR_PTR(-EFSCORRUPTED);
4254 inode = iget_locked(sb, ino);
4256 return ERR_PTR(-ENOMEM);
4257 if (!(inode->i_state & I_NEW))
4263 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4266 raw_inode = ext4_raw_inode(&iloc);
4268 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4269 ext4_error_inode(inode, function, line, 0,
4270 "iget: root inode unallocated");
4271 ret = -EFSCORRUPTED;
4275 if ((flags & EXT4_IGET_HANDLE) &&
4276 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4281 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4282 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4283 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4284 EXT4_INODE_SIZE(inode->i_sb)) {
4285 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4286 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4287 EXT4_INODE_SIZE(inode->i_sb));
4288 ret = -EFSCORRUPTED;
4292 ei->i_extra_isize = 0;
4294 /* Precompute checksum seed for inode metadata */
4295 if (ext4_has_metadata_csum(sb)) {
4296 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4298 __le32 inum = cpu_to_le32(inode->i_ino);
4299 __le32 gen = raw_inode->i_generation;
4300 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4302 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4306 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4307 ext4_error_inode(inode, function, line, 0,
4308 "iget: checksum invalid");
4313 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4314 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4315 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4316 if (!(test_opt(inode->i_sb, NO_UID32))) {
4317 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4318 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4320 i_uid_write(inode, i_uid);
4321 i_gid_write(inode, i_gid);
4322 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4324 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4325 ei->i_inline_off = 0;
4326 ei->i_dir_start_lookup = 0;
4327 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4328 /* We now have enough fields to check if the inode was active or not.
4329 * This is needed because nfsd might try to access dead inodes
4330 * the test is that same one that e2fsck uses
4331 * NeilBrown 1999oct15
4333 if (inode->i_nlink == 0) {
4334 if ((inode->i_mode == 0 ||
4335 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4336 ino != EXT4_BOOT_LOADER_INO) {
4337 /* this inode is deleted */
4341 /* The only unlinked inodes we let through here have
4342 * valid i_mode and are being read by the orphan
4343 * recovery code: that's fine, we're about to complete
4344 * the process of deleting those.
4345 * OR it is the EXT4_BOOT_LOADER_INO which is
4346 * not initialized on a new filesystem. */
4348 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4349 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4350 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4351 if (ext4_has_feature_64bit(sb))
4353 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4354 inode->i_size = ext4_isize(raw_inode);
4355 if ((size = i_size_read(inode)) < 0) {
4356 ext4_error_inode(inode, function, line, 0,
4357 "iget: bad i_size value: %lld", size);
4358 ret = -EFSCORRUPTED;
4362 * If dir_index is not enabled but there's dir with INDEX flag set,
4363 * we'd normally treat htree data as empty space. But with metadata
4364 * checksumming that corrupts checksums so forbid that.
4366 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4367 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4368 EXT4_ERROR_INODE(inode,
4369 "iget: Dir with htree data on filesystem without dir_index feature.");
4370 ret = -EFSCORRUPTED;
4373 ei->i_disksize = inode->i_size;
4375 ei->i_reserved_quota = 0;
4377 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4378 ei->i_block_group = iloc.block_group;
4379 ei->i_last_alloc_group = ~0;
4381 * NOTE! The in-memory inode i_data array is in little-endian order
4382 * even on big-endian machines: we do NOT byteswap the block numbers!
4384 for (block = 0; block < EXT4_N_BLOCKS; block++)
4385 ei->i_data[block] = raw_inode->i_block[block];
4386 INIT_LIST_HEAD(&ei->i_orphan);
4389 * Set transaction id's of transactions that have to be committed
4390 * to finish f[data]sync. We set them to currently running transaction
4391 * as we cannot be sure that the inode or some of its metadata isn't
4392 * part of the transaction - the inode could have been reclaimed and
4393 * now it is reread from disk.
4396 transaction_t *transaction;
4399 read_lock(&journal->j_state_lock);
4400 if (journal->j_running_transaction)
4401 transaction = journal->j_running_transaction;
4403 transaction = journal->j_committing_transaction;
4405 tid = transaction->t_tid;
4407 tid = journal->j_commit_sequence;
4408 read_unlock(&journal->j_state_lock);
4409 ei->i_sync_tid = tid;
4410 ei->i_datasync_tid = tid;
4413 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4414 if (ei->i_extra_isize == 0) {
4415 /* The extra space is currently unused. Use it. */
4416 ei->i_extra_isize = sizeof(struct ext4_inode) -
4417 EXT4_GOOD_OLD_INODE_SIZE;
4419 ext4_iget_extra_inode(inode, raw_inode, ei);
4423 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4424 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4425 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4426 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4428 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4429 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4430 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4431 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4433 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4438 if (ei->i_file_acl &&
4439 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4440 ext4_error_inode(inode, function, line, 0,
4441 "iget: bad extended attribute block %llu",
4443 ret = -EFSCORRUPTED;
4445 } else if (!ext4_has_inline_data(inode)) {
4446 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4447 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4448 (S_ISLNK(inode->i_mode) &&
4449 !ext4_inode_is_fast_symlink(inode))))
4450 /* Validate extent which is part of inode */
4451 ret = ext4_ext_check_inode(inode);
4452 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4453 (S_ISLNK(inode->i_mode) &&
4454 !ext4_inode_is_fast_symlink(inode))) {
4455 /* Validate block references which are part of inode */
4456 ret = ext4_ind_check_inode(inode);
4462 if (S_ISREG(inode->i_mode)) {
4463 inode->i_op = &ext4_file_inode_operations;
4464 inode->i_fop = &ext4_file_operations;
4465 ext4_set_aops(inode);
4466 } else if (S_ISDIR(inode->i_mode)) {
4467 inode->i_op = &ext4_dir_inode_operations;
4468 inode->i_fop = &ext4_dir_operations;
4469 } else if (S_ISLNK(inode->i_mode)) {
4470 if (ext4_encrypted_inode(inode)) {
4471 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4472 ext4_set_aops(inode);
4473 } else if (ext4_inode_is_fast_symlink(inode)) {
4474 inode->i_link = (char *)ei->i_data;
4475 inode->i_op = &ext4_fast_symlink_inode_operations;
4476 nd_terminate_link(ei->i_data, inode->i_size,
4477 sizeof(ei->i_data) - 1);
4479 inode->i_op = &ext4_symlink_inode_operations;
4480 ext4_set_aops(inode);
4482 inode_nohighmem(inode);
4483 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4484 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4485 inode->i_op = &ext4_special_inode_operations;
4486 if (raw_inode->i_block[0])
4487 init_special_inode(inode, inode->i_mode,
4488 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4490 init_special_inode(inode, inode->i_mode,
4491 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4492 } else if (ino == EXT4_BOOT_LOADER_INO) {
4493 make_bad_inode(inode);
4495 ret = -EFSCORRUPTED;
4496 ext4_error_inode(inode, function, line, 0,
4497 "iget: bogus i_mode (%o)", inode->i_mode);
4501 ext4_set_inode_flags(inode);
4502 unlock_new_inode(inode);
4508 return ERR_PTR(ret);
4511 static int ext4_inode_blocks_set(handle_t *handle,
4512 struct ext4_inode *raw_inode,
4513 struct ext4_inode_info *ei)
4515 struct inode *inode = &(ei->vfs_inode);
4516 u64 i_blocks = READ_ONCE(inode->i_blocks);
4517 struct super_block *sb = inode->i_sb;
4519 if (i_blocks <= ~0U) {
4521 * i_blocks can be represented in a 32 bit variable
4522 * as multiple of 512 bytes
4524 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4525 raw_inode->i_blocks_high = 0;
4526 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4529 if (!ext4_has_feature_huge_file(sb))
4532 if (i_blocks <= 0xffffffffffffULL) {
4534 * i_blocks can be represented in a 48 bit variable
4535 * as multiple of 512 bytes
4537 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4538 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4539 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4541 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4542 /* i_block is stored in file system block size */
4543 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4544 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4545 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4550 struct other_inode {
4551 unsigned long orig_ino;
4552 struct ext4_inode *raw_inode;
4555 static int other_inode_match(struct inode * inode, unsigned long ino,
4558 struct other_inode *oi = (struct other_inode *) data;
4560 if ((inode->i_ino != ino) ||
4561 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4562 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4563 ((inode->i_state & I_DIRTY_TIME) == 0))
4565 spin_lock(&inode->i_lock);
4566 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4567 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4568 (inode->i_state & I_DIRTY_TIME)) {
4569 struct ext4_inode_info *ei = EXT4_I(inode);
4571 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4572 spin_unlock(&inode->i_lock);
4574 spin_lock(&ei->i_raw_lock);
4575 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4576 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4577 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4578 ext4_inode_csum_set(inode, oi->raw_inode, ei);
4579 spin_unlock(&ei->i_raw_lock);
4580 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4583 spin_unlock(&inode->i_lock);
4588 * Opportunistically update the other time fields for other inodes in
4589 * the same inode table block.
4591 static void ext4_update_other_inodes_time(struct super_block *sb,
4592 unsigned long orig_ino, char *buf)
4594 struct other_inode oi;
4596 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4597 int inode_size = EXT4_INODE_SIZE(sb);
4599 oi.orig_ino = orig_ino;
4601 * Calculate the first inode in the inode table block. Inode
4602 * numbers are one-based. That is, the first inode in a block
4603 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
4605 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4606 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4607 if (ino == orig_ino)
4609 oi.raw_inode = (struct ext4_inode *) buf;
4610 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4615 * Post the struct inode info into an on-disk inode location in the
4616 * buffer-cache. This gobbles the caller's reference to the
4617 * buffer_head in the inode location struct.
4619 * The caller must have write access to iloc->bh.
4621 static int ext4_do_update_inode(handle_t *handle,
4622 struct inode *inode,
4623 struct ext4_iloc *iloc)
4625 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4626 struct ext4_inode_info *ei = EXT4_I(inode);
4627 struct buffer_head *bh = iloc->bh;
4628 struct super_block *sb = inode->i_sb;
4630 int need_datasync = 0, set_large_file = 0;
4634 spin_lock(&ei->i_raw_lock);
4636 /* For fields not tracked in the in-memory inode,
4637 * initialise them to zero for new inodes. */
4638 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4639 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4641 ext4_get_inode_flags(ei);
4642 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4643 i_uid = i_uid_read(inode);
4644 i_gid = i_gid_read(inode);
4645 if (!(test_opt(inode->i_sb, NO_UID32))) {
4646 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4647 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4649 * Fix up interoperability with old kernels. Otherwise, old inodes get
4650 * re-used with the upper 16 bits of the uid/gid intact
4652 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4653 raw_inode->i_uid_high = 0;
4654 raw_inode->i_gid_high = 0;
4656 raw_inode->i_uid_high =
4657 cpu_to_le16(high_16_bits(i_uid));
4658 raw_inode->i_gid_high =
4659 cpu_to_le16(high_16_bits(i_gid));
4662 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4663 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4664 raw_inode->i_uid_high = 0;
4665 raw_inode->i_gid_high = 0;
4667 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4669 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4670 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4671 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4672 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4674 err = ext4_inode_blocks_set(handle, raw_inode, ei);
4676 spin_unlock(&ei->i_raw_lock);
4679 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4680 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4681 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4682 raw_inode->i_file_acl_high =
4683 cpu_to_le16(ei->i_file_acl >> 32);
4684 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4685 if (ei->i_disksize != ext4_isize(raw_inode)) {
4686 ext4_isize_set(raw_inode, ei->i_disksize);
4689 if (ei->i_disksize > 0x7fffffffULL) {
4690 if (!ext4_has_feature_large_file(sb) ||
4691 EXT4_SB(sb)->s_es->s_rev_level ==
4692 cpu_to_le32(EXT4_GOOD_OLD_REV))
4695 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4696 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4697 if (old_valid_dev(inode->i_rdev)) {
4698 raw_inode->i_block[0] =
4699 cpu_to_le32(old_encode_dev(inode->i_rdev));
4700 raw_inode->i_block[1] = 0;
4702 raw_inode->i_block[0] = 0;
4703 raw_inode->i_block[1] =
4704 cpu_to_le32(new_encode_dev(inode->i_rdev));
4705 raw_inode->i_block[2] = 0;
4707 } else if (!ext4_has_inline_data(inode)) {
4708 for (block = 0; block < EXT4_N_BLOCKS; block++)
4709 raw_inode->i_block[block] = ei->i_data[block];
4712 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4713 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4714 if (ei->i_extra_isize) {
4715 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4716 raw_inode->i_version_hi =
4717 cpu_to_le32(inode->i_version >> 32);
4718 raw_inode->i_extra_isize =
4719 cpu_to_le16(ei->i_extra_isize);
4722 ext4_inode_csum_set(inode, raw_inode, ei);
4723 spin_unlock(&ei->i_raw_lock);
4724 if (inode->i_sb->s_flags & MS_LAZYTIME)
4725 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
4728 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4729 err = ext4_handle_dirty_metadata(handle, NULL, bh);
4732 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4733 if (set_large_file) {
4734 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
4735 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
4738 ext4_update_dynamic_rev(sb);
4739 ext4_set_feature_large_file(sb);
4740 ext4_handle_sync(handle);
4741 err = ext4_handle_dirty_super(handle, sb);
4743 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4746 ext4_std_error(inode->i_sb, err);
4751 * ext4_write_inode()
4753 * We are called from a few places:
4755 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
4756 * Here, there will be no transaction running. We wait for any running
4757 * transaction to commit.
4759 * - Within flush work (sys_sync(), kupdate and such).
4760 * We wait on commit, if told to.
4762 * - Within iput_final() -> write_inode_now()
4763 * We wait on commit, if told to.
4765 * In all cases it is actually safe for us to return without doing anything,
4766 * because the inode has been copied into a raw inode buffer in
4767 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
4770 * Note that we are absolutely dependent upon all inode dirtiers doing the
4771 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4772 * which we are interested.
4774 * It would be a bug for them to not do this. The code:
4776 * mark_inode_dirty(inode)
4778 * inode->i_size = expr;
4780 * is in error because write_inode() could occur while `stuff()' is running,
4781 * and the new i_size will be lost. Plus the inode will no longer be on the
4782 * superblock's dirty inode list.
4784 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4788 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
4791 if (EXT4_SB(inode->i_sb)->s_journal) {
4792 if (ext4_journal_current_handle()) {
4793 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4799 * No need to force transaction in WB_SYNC_NONE mode. Also
4800 * ext4_sync_fs() will force the commit after everything is
4803 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4806 err = ext4_force_commit(inode->i_sb);
4808 struct ext4_iloc iloc;
4810 err = __ext4_get_inode_loc(inode, &iloc, 0);
4814 * sync(2) will flush the whole buffer cache. No need to do
4815 * it here separately for each inode.
4817 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4818 sync_dirty_buffer(iloc.bh);
4819 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4820 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4821 "IO error syncing inode");
4830 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4831 * buffers that are attached to a page stradding i_size and are undergoing
4832 * commit. In that case we have to wait for commit to finish and try again.
4834 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4838 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4839 tid_t commit_tid = 0;
4842 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4844 * All buffers in the last page remain valid? Then there's nothing to
4845 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4848 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4851 page = find_lock_page(inode->i_mapping,
4852 inode->i_size >> PAGE_CACHE_SHIFT);
4855 ret = __ext4_journalled_invalidatepage(page, offset,
4856 PAGE_CACHE_SIZE - offset);
4858 page_cache_release(page);
4862 read_lock(&journal->j_state_lock);
4863 if (journal->j_committing_transaction)
4864 commit_tid = journal->j_committing_transaction->t_tid;
4865 read_unlock(&journal->j_state_lock);
4867 jbd2_log_wait_commit(journal, commit_tid);
4874 * Called from notify_change.
4876 * We want to trap VFS attempts to truncate the file as soon as
4877 * possible. In particular, we want to make sure that when the VFS
4878 * shrinks i_size, we put the inode on the orphan list and modify
4879 * i_disksize immediately, so that during the subsequent flushing of
4880 * dirty pages and freeing of disk blocks, we can guarantee that any
4881 * commit will leave the blocks being flushed in an unused state on
4882 * disk. (On recovery, the inode will get truncated and the blocks will
4883 * be freed, so we have a strong guarantee that no future commit will
4884 * leave these blocks visible to the user.)
4886 * Another thing we have to assure is that if we are in ordered mode
4887 * and inode is still attached to the committing transaction, we must
4888 * we start writeout of all the dirty pages which are being truncated.
4889 * This way we are sure that all the data written in the previous
4890 * transaction are already on disk (truncate waits for pages under
4893 * Called with inode->i_mutex down.
4895 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4897 struct inode *inode = d_inode(dentry);
4900 const unsigned int ia_valid = attr->ia_valid;
4902 error = inode_change_ok(inode, attr);
4906 if (is_quota_modification(inode, attr)) {
4907 error = dquot_initialize(inode);
4911 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4912 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4915 /* (user+group)*(old+new) structure, inode write (sb,
4916 * inode block, ? - but truncate inode update has it) */
4917 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4918 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4919 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4920 if (IS_ERR(handle)) {
4921 error = PTR_ERR(handle);
4924 error = dquot_transfer(inode, attr);
4926 ext4_journal_stop(handle);
4929 /* Update corresponding info in inode so that everything is in
4930 * one transaction */
4931 if (attr->ia_valid & ATTR_UID)
4932 inode->i_uid = attr->ia_uid;
4933 if (attr->ia_valid & ATTR_GID)
4934 inode->i_gid = attr->ia_gid;
4935 error = ext4_mark_inode_dirty(handle, inode);
4936 ext4_journal_stop(handle);
4939 if (attr->ia_valid & ATTR_SIZE) {
4941 loff_t oldsize = inode->i_size;
4942 int shrink = (attr->ia_size <= inode->i_size);
4944 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4945 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4947 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4950 if (!S_ISREG(inode->i_mode))
4953 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4954 inode_inc_iversion(inode);
4956 if (ext4_should_order_data(inode) &&
4957 (attr->ia_size < inode->i_size)) {
4958 error = ext4_begin_ordered_truncate(inode,
4963 if (attr->ia_size != inode->i_size) {
4964 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4965 if (IS_ERR(handle)) {
4966 error = PTR_ERR(handle);
4969 if (ext4_handle_valid(handle) && shrink) {
4970 error = ext4_orphan_add(handle, inode);
4974 * Update c/mtime on truncate up, ext4_truncate() will
4975 * update c/mtime in shrink case below
4978 inode->i_mtime = ext4_current_time(inode);
4979 inode->i_ctime = inode->i_mtime;
4981 down_write(&EXT4_I(inode)->i_data_sem);
4982 EXT4_I(inode)->i_disksize = attr->ia_size;
4983 rc = ext4_mark_inode_dirty(handle, inode);
4987 * We have to update i_size under i_data_sem together
4988 * with i_disksize to avoid races with writeback code
4989 * running ext4_wb_update_i_disksize().
4992 i_size_write(inode, attr->ia_size);
4993 up_write(&EXT4_I(inode)->i_data_sem);
4994 ext4_journal_stop(handle);
4996 if (orphan && inode->i_nlink)
4997 ext4_orphan_del(NULL, inode);
5002 pagecache_isize_extended(inode, oldsize, inode->i_size);
5005 * Blocks are going to be removed from the inode. Wait
5006 * for dio in flight. Temporarily disable
5007 * dioread_nolock to prevent livelock.
5010 if (!ext4_should_journal_data(inode)) {
5011 ext4_inode_block_unlocked_dio(inode);
5012 inode_dio_wait(inode);
5013 ext4_inode_resume_unlocked_dio(inode);
5015 ext4_wait_for_tail_page_commit(inode);
5017 down_write(&EXT4_I(inode)->i_mmap_sem);
5019 * Truncate pagecache after we've waited for commit
5020 * in data=journal mode to make pages freeable.
5022 truncate_pagecache(inode, inode->i_size);
5024 ext4_truncate(inode);
5025 up_write(&EXT4_I(inode)->i_mmap_sem);
5029 setattr_copy(inode, attr);
5030 mark_inode_dirty(inode);
5034 * If the call to ext4_truncate failed to get a transaction handle at
5035 * all, we need to clean up the in-core orphan list manually.
5037 if (orphan && inode->i_nlink)
5038 ext4_orphan_del(NULL, inode);
5040 if (!rc && (ia_valid & ATTR_MODE))
5041 rc = posix_acl_chmod(inode, inode->i_mode);
5044 ext4_std_error(inode->i_sb, error);
5050 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
5053 struct inode *inode;
5054 unsigned long long delalloc_blocks;
5056 inode = d_inode(dentry);
5057 generic_fillattr(inode, stat);
5060 * If there is inline data in the inode, the inode will normally not
5061 * have data blocks allocated (it may have an external xattr block).
5062 * Report at least one sector for such files, so tools like tar, rsync,
5063 * others doen't incorrectly think the file is completely sparse.
5065 if (unlikely(ext4_has_inline_data(inode)))
5066 stat->blocks += (stat->size + 511) >> 9;
5069 * We can't update i_blocks if the block allocation is delayed
5070 * otherwise in the case of system crash before the real block
5071 * allocation is done, we will have i_blocks inconsistent with
5072 * on-disk file blocks.
5073 * We always keep i_blocks updated together with real
5074 * allocation. But to not confuse with user, stat
5075 * will return the blocks that include the delayed allocation
5076 * blocks for this file.
5078 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5079 EXT4_I(inode)->i_reserved_data_blocks);
5080 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5084 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5087 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5088 return ext4_ind_trans_blocks(inode, lblocks);
5089 return ext4_ext_index_trans_blocks(inode, pextents);
5093 * Account for index blocks, block groups bitmaps and block group
5094 * descriptor blocks if modify datablocks and index blocks
5095 * worse case, the indexs blocks spread over different block groups
5097 * If datablocks are discontiguous, they are possible to spread over
5098 * different block groups too. If they are contiguous, with flexbg,
5099 * they could still across block group boundary.
5101 * Also account for superblock, inode, quota and xattr blocks
5103 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5106 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5112 * How many index blocks need to touch to map @lblocks logical blocks
5113 * to @pextents physical extents?
5115 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5120 * Now let's see how many group bitmaps and group descriptors need
5123 groups = idxblocks + pextents;
5125 if (groups > ngroups)
5127 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5128 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5130 /* bitmaps and block group descriptor blocks */
5131 ret += groups + gdpblocks;
5133 /* Blocks for super block, inode, quota and xattr blocks */
5134 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5140 * Calculate the total number of credits to reserve to fit
5141 * the modification of a single pages into a single transaction,
5142 * which may include multiple chunks of block allocations.
5144 * This could be called via ext4_write_begin()
5146 * We need to consider the worse case, when
5147 * one new block per extent.
5149 int ext4_writepage_trans_blocks(struct inode *inode)
5151 int bpp = ext4_journal_blocks_per_page(inode);
5154 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5156 /* Account for data blocks for journalled mode */
5157 if (ext4_should_journal_data(inode))
5163 * Calculate the journal credits for a chunk of data modification.
5165 * This is called from DIO, fallocate or whoever calling
5166 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5168 * journal buffers for data blocks are not included here, as DIO
5169 * and fallocate do no need to journal data buffers.
5171 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5173 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5177 * The caller must have previously called ext4_reserve_inode_write().
5178 * Give this, we know that the caller already has write access to iloc->bh.
5180 int ext4_mark_iloc_dirty(handle_t *handle,
5181 struct inode *inode, struct ext4_iloc *iloc)
5185 if (IS_I_VERSION(inode))
5186 inode_inc_iversion(inode);
5188 /* the do_update_inode consumes one bh->b_count */
5191 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5192 err = ext4_do_update_inode(handle, inode, iloc);
5198 * On success, We end up with an outstanding reference count against
5199 * iloc->bh. This _must_ be cleaned up later.
5203 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5204 struct ext4_iloc *iloc)
5208 err = ext4_get_inode_loc(inode, iloc);
5210 BUFFER_TRACE(iloc->bh, "get_write_access");
5211 err = ext4_journal_get_write_access(handle, iloc->bh);
5217 ext4_std_error(inode->i_sb, err);
5222 * Expand an inode by new_extra_isize bytes.
5223 * Returns 0 on success or negative error number on failure.
5225 static int ext4_expand_extra_isize(struct inode *inode,
5226 unsigned int new_extra_isize,
5227 struct ext4_iloc iloc,
5230 struct ext4_inode *raw_inode;
5231 struct ext4_xattr_ibody_header *header;
5232 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5233 struct ext4_inode_info *ei = EXT4_I(inode);
5235 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5238 /* this was checked at iget time, but double check for good measure */
5239 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5240 (ei->i_extra_isize & 3)) {
5241 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5243 EXT4_INODE_SIZE(inode->i_sb));
5244 return -EFSCORRUPTED;
5246 if ((new_extra_isize < ei->i_extra_isize) ||
5247 (new_extra_isize < 4) ||
5248 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5249 return -EINVAL; /* Should never happen */
5251 raw_inode = ext4_raw_inode(&iloc);
5253 header = IHDR(inode, raw_inode);
5255 /* No extended attributes present */
5256 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5257 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5258 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5259 EXT4_I(inode)->i_extra_isize, 0,
5260 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5261 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5265 /* try to expand with EAs present */
5266 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5271 * What we do here is to mark the in-core inode as clean with respect to inode
5272 * dirtiness (it may still be data-dirty).
5273 * This means that the in-core inode may be reaped by prune_icache
5274 * without having to perform any I/O. This is a very good thing,
5275 * because *any* task may call prune_icache - even ones which
5276 * have a transaction open against a different journal.
5278 * Is this cheating? Not really. Sure, we haven't written the
5279 * inode out, but prune_icache isn't a user-visible syncing function.
5280 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5281 * we start and wait on commits.
5283 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5285 struct ext4_iloc iloc;
5286 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5287 static unsigned int mnt_count;
5291 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5292 err = ext4_reserve_inode_write(handle, inode, &iloc);
5295 if (ext4_handle_valid(handle) &&
5296 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5297 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5299 * We need extra buffer credits since we may write into EA block
5300 * with this same handle. If journal_extend fails, then it will
5301 * only result in a minor loss of functionality for that inode.
5302 * If this is felt to be critical, then e2fsck should be run to
5303 * force a large enough s_min_extra_isize.
5305 if ((jbd2_journal_extend(handle,
5306 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5307 ret = ext4_expand_extra_isize(inode,
5308 sbi->s_want_extra_isize,
5312 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5313 ext4_warning(inode->i_sb,
5314 "Unable to expand inode %lu. Delete"
5315 " some EAs or run e2fsck.",
5318 le16_to_cpu(sbi->s_es->s_mnt_count);
5323 return ext4_mark_iloc_dirty(handle, inode, &iloc);
5327 * ext4_dirty_inode() is called from __mark_inode_dirty()
5329 * We're really interested in the case where a file is being extended.
5330 * i_size has been changed by generic_commit_write() and we thus need
5331 * to include the updated inode in the current transaction.
5333 * Also, dquot_alloc_block() will always dirty the inode when blocks
5334 * are allocated to the file.
5336 * If the inode is marked synchronous, we don't honour that here - doing
5337 * so would cause a commit on atime updates, which we don't bother doing.
5338 * We handle synchronous inodes at the highest possible level.
5340 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5341 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5342 * to copy into the on-disk inode structure are the timestamp files.
5344 void ext4_dirty_inode(struct inode *inode, int flags)
5348 if (flags == I_DIRTY_TIME)
5350 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5354 ext4_mark_inode_dirty(handle, inode);
5356 ext4_journal_stop(handle);
5363 * Bind an inode's backing buffer_head into this transaction, to prevent
5364 * it from being flushed to disk early. Unlike
5365 * ext4_reserve_inode_write, this leaves behind no bh reference and
5366 * returns no iloc structure, so the caller needs to repeat the iloc
5367 * lookup to mark the inode dirty later.
5369 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5371 struct ext4_iloc iloc;
5375 err = ext4_get_inode_loc(inode, &iloc);
5377 BUFFER_TRACE(iloc.bh, "get_write_access");
5378 err = jbd2_journal_get_write_access(handle, iloc.bh);
5380 err = ext4_handle_dirty_metadata(handle,
5386 ext4_std_error(inode->i_sb, err);
5391 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5398 * We have to be very careful here: changing a data block's
5399 * journaling status dynamically is dangerous. If we write a
5400 * data block to the journal, change the status and then delete
5401 * that block, we risk forgetting to revoke the old log record
5402 * from the journal and so a subsequent replay can corrupt data.
5403 * So, first we make sure that the journal is empty and that
5404 * nobody is changing anything.
5407 journal = EXT4_JOURNAL(inode);
5410 if (is_journal_aborted(journal))
5412 /* We have to allocate physical blocks for delalloc blocks
5413 * before flushing journal. otherwise delalloc blocks can not
5414 * be allocated any more. even more truncate on delalloc blocks
5415 * could trigger BUG by flushing delalloc blocks in journal.
5416 * There is no delalloc block in non-journal data mode.
5418 if (val && test_opt(inode->i_sb, DELALLOC)) {
5419 err = ext4_alloc_da_blocks(inode);
5424 /* Wait for all existing dio workers */
5425 ext4_inode_block_unlocked_dio(inode);
5426 inode_dio_wait(inode);
5428 jbd2_journal_lock_updates(journal);
5431 * OK, there are no updates running now, and all cached data is
5432 * synced to disk. We are now in a completely consistent state
5433 * which doesn't have anything in the journal, and we know that
5434 * no filesystem updates are running, so it is safe to modify
5435 * the inode's in-core data-journaling state flag now.
5439 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5441 err = jbd2_journal_flush(journal);
5443 jbd2_journal_unlock_updates(journal);
5444 ext4_inode_resume_unlocked_dio(inode);
5447 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5449 ext4_set_aops(inode);
5451 jbd2_journal_unlock_updates(journal);
5452 ext4_inode_resume_unlocked_dio(inode);
5454 /* Finally we can mark the inode as dirty. */
5456 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5458 return PTR_ERR(handle);
5460 err = ext4_mark_inode_dirty(handle, inode);
5461 ext4_handle_sync(handle);
5462 ext4_journal_stop(handle);
5463 ext4_std_error(inode->i_sb, err);
5468 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5470 return !buffer_mapped(bh);
5473 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5475 struct page *page = vmf->page;
5479 struct file *file = vma->vm_file;
5480 struct inode *inode = file_inode(file);
5481 struct address_space *mapping = inode->i_mapping;
5483 get_block_t *get_block;
5486 sb_start_pagefault(inode->i_sb);
5487 file_update_time(vma->vm_file);
5489 down_read(&EXT4_I(inode)->i_mmap_sem);
5491 ret = ext4_convert_inline_data(inode);
5495 /* Delalloc case is easy... */
5496 if (test_opt(inode->i_sb, DELALLOC) &&
5497 !ext4_should_journal_data(inode) &&
5498 !ext4_nonda_switch(inode->i_sb)) {
5500 ret = block_page_mkwrite(vma, vmf,
5501 ext4_da_get_block_prep);
5502 } while (ret == -ENOSPC &&
5503 ext4_should_retry_alloc(inode->i_sb, &retries));
5508 size = i_size_read(inode);
5509 /* Page got truncated from under us? */
5510 if (page->mapping != mapping || page_offset(page) > size) {
5512 ret = VM_FAULT_NOPAGE;
5516 if (page->index == size >> PAGE_CACHE_SHIFT)
5517 len = size & ~PAGE_CACHE_MASK;
5519 len = PAGE_CACHE_SIZE;
5521 * Return if we have all the buffers mapped. This avoids the need to do
5522 * journal_start/journal_stop which can block and take a long time
5524 if (page_has_buffers(page)) {
5525 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5527 ext4_bh_unmapped)) {
5528 /* Wait so that we don't change page under IO */
5529 wait_for_stable_page(page);
5530 ret = VM_FAULT_LOCKED;
5535 /* OK, we need to fill the hole... */
5536 if (ext4_should_dioread_nolock(inode))
5537 get_block = ext4_get_block_write;
5539 get_block = ext4_get_block;
5541 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5542 ext4_writepage_trans_blocks(inode));
5543 if (IS_ERR(handle)) {
5544 ret = VM_FAULT_SIGBUS;
5547 ret = block_page_mkwrite(vma, vmf, get_block);
5548 if (!ret && ext4_should_journal_data(inode)) {
5549 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5550 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5552 ret = VM_FAULT_SIGBUS;
5553 ext4_journal_stop(handle);
5556 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5558 ext4_journal_stop(handle);
5559 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5562 ret = block_page_mkwrite_return(ret);
5564 up_read(&EXT4_I(inode)->i_mmap_sem);
5565 sb_end_pagefault(inode->i_sb);
5569 int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
5571 struct inode *inode = file_inode(vma->vm_file);
5574 down_read(&EXT4_I(inode)->i_mmap_sem);
5575 err = filemap_fault(vma, vmf);
5576 up_read(&EXT4_I(inode)->i_mmap_sem);