1 // SPDX-License-Identifier: GPL-2.0
3 * linux/fs/ext4/inode.c
5 * Copyright (C) 1992, 1993, 1994, 1995
6 * Remy Card (card@masi.ibp.fr)
7 * Laboratoire MASI - Institut Blaise Pascal
8 * Universite Pierre et Marie Curie (Paris VI)
12 * linux/fs/minix/inode.c
14 * Copyright (C) 1991, 1992 Linus Torvalds
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
23 #include <linux/time.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/dax.h>
27 #include <linux/quotaops.h>
28 #include <linux/string.h>
29 #include <linux/buffer_head.h>
30 #include <linux/writeback.h>
31 #include <linux/pagevec.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/uio.h>
35 #include <linux/bio.h>
36 #include <linux/workqueue.h>
37 #include <linux/kernel.h>
38 #include <linux/printk.h>
39 #include <linux/slab.h>
40 #include <linux/bitops.h>
41 #include <linux/iomap.h>
42 #include <linux/iversion.h>
44 #include "ext4_jbd2.h"
49 #include <trace/events/ext4.h>
51 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52 struct ext4_inode_info *ei)
54 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
57 int offset = offsetof(struct ext4_inode, i_checksum_lo);
58 unsigned int csum_size = sizeof(dummy_csum);
60 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
61 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
64 EXT4_GOOD_OLD_INODE_SIZE - offset);
66 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
67 offset = offsetof(struct ext4_inode, i_checksum_hi);
68 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
69 EXT4_GOOD_OLD_INODE_SIZE,
70 offset - EXT4_GOOD_OLD_INODE_SIZE);
71 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
72 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
76 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
77 EXT4_INODE_SIZE(inode->i_sb) - offset);
83 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
84 struct ext4_inode_info *ei)
86 __u32 provided, calculated;
88 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
89 cpu_to_le32(EXT4_OS_LINUX) ||
90 !ext4_has_metadata_csum(inode->i_sb))
93 provided = le16_to_cpu(raw->i_checksum_lo);
94 calculated = ext4_inode_csum(inode, raw, ei);
95 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
96 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
97 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
101 return provided == calculated;
104 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
105 struct ext4_inode_info *ei)
109 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
110 cpu_to_le32(EXT4_OS_LINUX) ||
111 !ext4_has_metadata_csum(inode->i_sb))
114 csum = ext4_inode_csum(inode, raw, ei);
115 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
116 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
117 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
118 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
121 static inline int ext4_begin_ordered_truncate(struct inode *inode,
124 trace_ext4_begin_ordered_truncate(inode, new_size);
126 * If jinode is zero, then we never opened the file for
127 * writing, so there's no need to call
128 * jbd2_journal_begin_ordered_truncate() since there's no
129 * outstanding writes we need to flush.
131 if (!EXT4_I(inode)->jinode)
133 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
134 EXT4_I(inode)->jinode,
138 static void ext4_invalidatepage(struct page *page, unsigned int offset,
139 unsigned int length);
140 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
141 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
142 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
146 * Test whether an inode is a fast symlink.
147 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
149 int ext4_inode_is_fast_symlink(struct inode *inode)
151 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
152 int ea_blocks = EXT4_I(inode)->i_file_acl ?
153 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
155 if (ext4_has_inline_data(inode))
158 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
160 return S_ISLNK(inode->i_mode) && inode->i_size &&
161 (inode->i_size < EXT4_N_BLOCKS * 4);
165 * Called at the last iput() if i_nlink is zero.
167 void ext4_evict_inode(struct inode *inode)
172 * Credits for final inode cleanup and freeing:
173 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
174 * (xattr block freeing), bitmap, group descriptor (inode freeing)
176 int extra_credits = 6;
177 struct ext4_xattr_inode_array *ea_inode_array = NULL;
179 trace_ext4_evict_inode(inode);
181 if (inode->i_nlink) {
183 * When journalling data dirty buffers are tracked only in the
184 * journal. So although mm thinks everything is clean and
185 * ready for reaping the inode might still have some pages to
186 * write in the running transaction or waiting to be
187 * checkpointed. Thus calling jbd2_journal_invalidatepage()
188 * (via truncate_inode_pages()) to discard these buffers can
189 * cause data loss. Also even if we did not discard these
190 * buffers, we would have no way to find them after the inode
191 * is reaped and thus user could see stale data if he tries to
192 * read them before the transaction is checkpointed. So be
193 * careful and force everything to disk here... We use
194 * ei->i_datasync_tid to store the newest transaction
195 * containing inode's data.
197 * Note that directories do not have this problem because they
198 * don't use page cache.
200 if (inode->i_ino != EXT4_JOURNAL_INO &&
201 ext4_should_journal_data(inode) &&
202 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
203 inode->i_data.nrpages) {
204 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
205 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
207 jbd2_complete_transaction(journal, commit_tid);
208 filemap_write_and_wait(&inode->i_data);
210 truncate_inode_pages_final(&inode->i_data);
215 if (is_bad_inode(inode))
217 dquot_initialize(inode);
219 if (ext4_should_order_data(inode))
220 ext4_begin_ordered_truncate(inode, 0);
221 truncate_inode_pages_final(&inode->i_data);
224 * For inodes with journalled data, transaction commit could have
225 * dirtied the inode. Flush worker is ignoring it because of I_FREEING
226 * flag but we still need to remove the inode from the writeback lists.
228 if (!list_empty_careful(&inode->i_io_list)) {
229 WARN_ON_ONCE(!ext4_should_journal_data(inode));
230 inode_io_list_del(inode);
234 * Protect us against freezing - iput() caller didn't have to have any
235 * protection against it
237 sb_start_intwrite(inode->i_sb);
239 if (!IS_NOQUOTA(inode))
240 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
243 * Block bitmap, group descriptor, and inode are accounted in both
244 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
246 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
247 ext4_blocks_for_truncate(inode) + extra_credits - 3);
248 if (IS_ERR(handle)) {
249 ext4_std_error(inode->i_sb, PTR_ERR(handle));
251 * If we're going to skip the normal cleanup, we still need to
252 * make sure that the in-core orphan linked list is properly
255 ext4_orphan_del(NULL, inode);
256 sb_end_intwrite(inode->i_sb);
261 ext4_handle_sync(handle);
264 * Set inode->i_size to 0 before calling ext4_truncate(). We need
265 * special handling of symlinks here because i_size is used to
266 * determine whether ext4_inode_info->i_data contains symlink data or
267 * block mappings. Setting i_size to 0 will remove its fast symlink
268 * status. Erase i_data so that it becomes a valid empty block map.
270 if (ext4_inode_is_fast_symlink(inode))
271 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
273 err = ext4_mark_inode_dirty(handle, inode);
275 ext4_warning(inode->i_sb,
276 "couldn't mark inode dirty (err %d)", err);
279 if (inode->i_blocks) {
280 err = ext4_truncate(inode);
282 ext4_error_err(inode->i_sb, -err,
283 "couldn't truncate inode %lu (err %d)",
289 /* Remove xattr references. */
290 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
293 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
295 ext4_journal_stop(handle);
296 ext4_orphan_del(NULL, inode);
297 sb_end_intwrite(inode->i_sb);
298 ext4_xattr_inode_array_free(ea_inode_array);
303 * Kill off the orphan record which ext4_truncate created.
304 * AKPM: I think this can be inside the above `if'.
305 * Note that ext4_orphan_del() has to be able to cope with the
306 * deletion of a non-existent orphan - this is because we don't
307 * know if ext4_truncate() actually created an orphan record.
308 * (Well, we could do this if we need to, but heck - it works)
310 ext4_orphan_del(handle, inode);
311 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
314 * One subtle ordering requirement: if anything has gone wrong
315 * (transaction abort, IO errors, whatever), then we can still
316 * do these next steps (the fs will already have been marked as
317 * having errors), but we can't free the inode if the mark_dirty
320 if (ext4_mark_inode_dirty(handle, inode))
321 /* If that failed, just do the required in-core inode clear. */
322 ext4_clear_inode(inode);
324 ext4_free_inode(handle, inode);
325 ext4_journal_stop(handle);
326 sb_end_intwrite(inode->i_sb);
327 ext4_xattr_inode_array_free(ea_inode_array);
330 if (!list_empty(&EXT4_I(inode)->i_fc_list))
331 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM);
332 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
336 qsize_t *ext4_get_reserved_space(struct inode *inode)
338 return &EXT4_I(inode)->i_reserved_quota;
343 * Called with i_data_sem down, which is important since we can call
344 * ext4_discard_preallocations() from here.
346 void ext4_da_update_reserve_space(struct inode *inode,
347 int used, int quota_claim)
349 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
350 struct ext4_inode_info *ei = EXT4_I(inode);
352 spin_lock(&ei->i_block_reservation_lock);
353 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
354 if (unlikely(used > ei->i_reserved_data_blocks)) {
355 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
356 "with only %d reserved data blocks",
357 __func__, inode->i_ino, used,
358 ei->i_reserved_data_blocks);
360 used = ei->i_reserved_data_blocks;
363 /* Update per-inode reservations */
364 ei->i_reserved_data_blocks -= used;
365 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
367 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
369 /* Update quota subsystem for data blocks */
371 dquot_claim_block(inode, EXT4_C2B(sbi, used));
374 * We did fallocate with an offset that is already delayed
375 * allocated. So on delayed allocated writeback we should
376 * not re-claim the quota for fallocated blocks.
378 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
382 * If we have done all the pending block allocations and if
383 * there aren't any writers on the inode, we can discard the
384 * inode's preallocations.
386 if ((ei->i_reserved_data_blocks == 0) &&
387 !inode_is_open_for_write(inode))
388 ext4_discard_preallocations(inode, 0);
391 static int __check_block_validity(struct inode *inode, const char *func,
393 struct ext4_map_blocks *map)
395 if (ext4_has_feature_journal(inode->i_sb) &&
397 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
399 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
400 ext4_error_inode(inode, func, line, map->m_pblk,
401 "lblock %lu mapped to illegal pblock %llu "
402 "(length %d)", (unsigned long) map->m_lblk,
403 map->m_pblk, map->m_len);
404 return -EFSCORRUPTED;
409 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
414 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
415 return fscrypt_zeroout_range(inode, lblk, pblk, len);
417 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
424 #define check_block_validity(inode, map) \
425 __check_block_validity((inode), __func__, __LINE__, (map))
427 #ifdef ES_AGGRESSIVE_TEST
428 static void ext4_map_blocks_es_recheck(handle_t *handle,
430 struct ext4_map_blocks *es_map,
431 struct ext4_map_blocks *map,
438 * There is a race window that the result is not the same.
439 * e.g. xfstests #223 when dioread_nolock enables. The reason
440 * is that we lookup a block mapping in extent status tree with
441 * out taking i_data_sem. So at the time the unwritten extent
442 * could be converted.
444 down_read(&EXT4_I(inode)->i_data_sem);
445 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
446 retval = ext4_ext_map_blocks(handle, inode, map, 0);
448 retval = ext4_ind_map_blocks(handle, inode, map, 0);
450 up_read((&EXT4_I(inode)->i_data_sem));
453 * We don't check m_len because extent will be collpased in status
454 * tree. So the m_len might not equal.
456 if (es_map->m_lblk != map->m_lblk ||
457 es_map->m_flags != map->m_flags ||
458 es_map->m_pblk != map->m_pblk) {
459 printk("ES cache assertion failed for inode: %lu "
460 "es_cached ex [%d/%d/%llu/%x] != "
461 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
462 inode->i_ino, es_map->m_lblk, es_map->m_len,
463 es_map->m_pblk, es_map->m_flags, map->m_lblk,
464 map->m_len, map->m_pblk, map->m_flags,
468 #endif /* ES_AGGRESSIVE_TEST */
471 * The ext4_map_blocks() function tries to look up the requested blocks,
472 * and returns if the blocks are already mapped.
474 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
475 * and store the allocated blocks in the result buffer head and mark it
478 * If file type is extents based, it will call ext4_ext_map_blocks(),
479 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
482 * On success, it returns the number of blocks being mapped or allocated. if
483 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
484 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
486 * It returns 0 if plain look up failed (blocks have not been allocated), in
487 * that case, @map is returned as unmapped but we still do fill map->m_len to
488 * indicate the length of a hole starting at map->m_lblk.
490 * It returns the error in case of allocation failure.
492 int ext4_map_blocks(handle_t *handle, struct inode *inode,
493 struct ext4_map_blocks *map, int flags)
495 struct extent_status es;
498 #ifdef ES_AGGRESSIVE_TEST
499 struct ext4_map_blocks orig_map;
501 memcpy(&orig_map, map, sizeof(*map));
505 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
506 flags, map->m_len, (unsigned long) map->m_lblk);
509 * ext4_map_blocks returns an int, and m_len is an unsigned int
511 if (unlikely(map->m_len > INT_MAX))
512 map->m_len = INT_MAX;
514 /* We can handle the block number less than EXT_MAX_BLOCKS */
515 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
516 return -EFSCORRUPTED;
518 /* Lookup extent status tree firstly */
519 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
520 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
521 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
522 map->m_pblk = ext4_es_pblock(&es) +
523 map->m_lblk - es.es_lblk;
524 map->m_flags |= ext4_es_is_written(&es) ?
525 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
526 retval = es.es_len - (map->m_lblk - es.es_lblk);
527 if (retval > map->m_len)
530 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
532 retval = es.es_len - (map->m_lblk - es.es_lblk);
533 if (retval > map->m_len)
540 #ifdef ES_AGGRESSIVE_TEST
541 ext4_map_blocks_es_recheck(handle, inode, map,
548 * Try to see if we can get the block without requesting a new
551 down_read(&EXT4_I(inode)->i_data_sem);
552 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
553 retval = ext4_ext_map_blocks(handle, inode, map, 0);
555 retval = ext4_ind_map_blocks(handle, inode, map, 0);
560 if (unlikely(retval != map->m_len)) {
561 ext4_warning(inode->i_sb,
562 "ES len assertion failed for inode "
563 "%lu: retval %d != map->m_len %d",
564 inode->i_ino, retval, map->m_len);
568 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
569 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
570 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
571 !(status & EXTENT_STATUS_WRITTEN) &&
572 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
573 map->m_lblk + map->m_len - 1))
574 status |= EXTENT_STATUS_DELAYED;
575 ret = ext4_es_insert_extent(inode, map->m_lblk,
576 map->m_len, map->m_pblk, status);
580 up_read((&EXT4_I(inode)->i_data_sem));
583 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
584 ret = check_block_validity(inode, map);
589 /* If it is only a block(s) look up */
590 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
594 * Returns if the blocks have already allocated
596 * Note that if blocks have been preallocated
597 * ext4_ext_get_block() returns the create = 0
598 * with buffer head unmapped.
600 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
602 * If we need to convert extent to unwritten
603 * we continue and do the actual work in
604 * ext4_ext_map_blocks()
606 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
610 * Here we clear m_flags because after allocating an new extent,
611 * it will be set again.
613 map->m_flags &= ~EXT4_MAP_FLAGS;
616 * New blocks allocate and/or writing to unwritten extent
617 * will possibly result in updating i_data, so we take
618 * the write lock of i_data_sem, and call get_block()
619 * with create == 1 flag.
621 down_write(&EXT4_I(inode)->i_data_sem);
624 * We need to check for EXT4 here because migrate
625 * could have changed the inode type in between
627 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
628 retval = ext4_ext_map_blocks(handle, inode, map, flags);
630 retval = ext4_ind_map_blocks(handle, inode, map, flags);
632 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
634 * We allocated new blocks which will result in
635 * i_data's format changing. Force the migrate
636 * to fail by clearing migrate flags
638 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
642 * Update reserved blocks/metadata blocks after successful
643 * block allocation which had been deferred till now. We don't
644 * support fallocate for non extent files. So we can update
645 * reserve space here.
648 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
649 ext4_da_update_reserve_space(inode, retval, 1);
655 if (unlikely(retval != map->m_len)) {
656 ext4_warning(inode->i_sb,
657 "ES len assertion failed for inode "
658 "%lu: retval %d != map->m_len %d",
659 inode->i_ino, retval, map->m_len);
664 * We have to zeroout blocks before inserting them into extent
665 * status tree. Otherwise someone could look them up there and
666 * use them before they are really zeroed. We also have to
667 * unmap metadata before zeroing as otherwise writeback can
668 * overwrite zeros with stale data from block device.
670 if (flags & EXT4_GET_BLOCKS_ZERO &&
671 map->m_flags & EXT4_MAP_MAPPED &&
672 map->m_flags & EXT4_MAP_NEW) {
673 ret = ext4_issue_zeroout(inode, map->m_lblk,
674 map->m_pblk, map->m_len);
682 * If the extent has been zeroed out, we don't need to update
683 * extent status tree.
685 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
686 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
687 if (ext4_es_is_written(&es))
690 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
691 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
692 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
693 !(status & EXTENT_STATUS_WRITTEN) &&
694 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
695 map->m_lblk + map->m_len - 1))
696 status |= EXTENT_STATUS_DELAYED;
697 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
698 map->m_pblk, status);
706 up_write((&EXT4_I(inode)->i_data_sem));
707 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
708 ret = check_block_validity(inode, map);
713 * Inodes with freshly allocated blocks where contents will be
714 * visible after transaction commit must be on transaction's
717 if (map->m_flags & EXT4_MAP_NEW &&
718 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
719 !(flags & EXT4_GET_BLOCKS_ZERO) &&
720 !ext4_is_quota_file(inode) &&
721 ext4_should_order_data(inode)) {
723 (loff_t)map->m_lblk << inode->i_blkbits;
724 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
726 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
727 ret = ext4_jbd2_inode_add_wait(handle, inode,
730 ret = ext4_jbd2_inode_add_write(handle, inode,
735 ext4_fc_track_range(handle, inode, map->m_lblk,
736 map->m_lblk + map->m_len - 1);
740 ext_debug(inode, "failed with err %d\n", retval);
745 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
746 * we have to be careful as someone else may be manipulating b_state as well.
748 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
750 unsigned long old_state;
751 unsigned long new_state;
753 flags &= EXT4_MAP_FLAGS;
755 /* Dummy buffer_head? Set non-atomically. */
757 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
761 * Someone else may be modifying b_state. Be careful! This is ugly but
762 * once we get rid of using bh as a container for mapping information
763 * to pass to / from get_block functions, this can go away.
766 old_state = READ_ONCE(bh->b_state);
767 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
769 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
772 static int _ext4_get_block(struct inode *inode, sector_t iblock,
773 struct buffer_head *bh, int flags)
775 struct ext4_map_blocks map;
778 if (ext4_has_inline_data(inode))
782 map.m_len = bh->b_size >> inode->i_blkbits;
784 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
787 map_bh(bh, inode->i_sb, map.m_pblk);
788 ext4_update_bh_state(bh, map.m_flags);
789 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
791 } else if (ret == 0) {
792 /* hole case, need to fill in bh->b_size */
793 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
798 int ext4_get_block(struct inode *inode, sector_t iblock,
799 struct buffer_head *bh, int create)
801 return _ext4_get_block(inode, iblock, bh,
802 create ? EXT4_GET_BLOCKS_CREATE : 0);
806 * Get block function used when preparing for buffered write if we require
807 * creating an unwritten extent if blocks haven't been allocated. The extent
808 * will be converted to written after the IO is complete.
810 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
811 struct buffer_head *bh_result, int create)
813 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
814 inode->i_ino, create);
815 return _ext4_get_block(inode, iblock, bh_result,
816 EXT4_GET_BLOCKS_IO_CREATE_EXT);
819 /* Maximum number of blocks we map for direct IO at once. */
820 #define DIO_MAX_BLOCKS 4096
823 * `handle' can be NULL if create is zero
825 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
826 ext4_lblk_t block, int map_flags)
828 struct ext4_map_blocks map;
829 struct buffer_head *bh;
830 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
833 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
834 || handle != NULL || create == 0);
838 err = ext4_map_blocks(handle, inode, &map, map_flags);
841 return create ? ERR_PTR(-ENOSPC) : NULL;
845 bh = sb_getblk(inode->i_sb, map.m_pblk);
847 return ERR_PTR(-ENOMEM);
848 if (map.m_flags & EXT4_MAP_NEW) {
849 J_ASSERT(create != 0);
850 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
851 || (handle != NULL));
854 * Now that we do not always journal data, we should
855 * keep in mind whether this should always journal the
856 * new buffer as metadata. For now, regular file
857 * writes use ext4_get_block instead, so it's not a
861 BUFFER_TRACE(bh, "call get_create_access");
862 err = ext4_journal_get_create_access(handle, bh);
867 if (!buffer_uptodate(bh)) {
868 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
869 set_buffer_uptodate(bh);
872 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
873 err = ext4_handle_dirty_metadata(handle, inode, bh);
877 BUFFER_TRACE(bh, "not a new buffer");
884 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
885 ext4_lblk_t block, int map_flags)
887 struct buffer_head *bh;
890 bh = ext4_getblk(handle, inode, block, map_flags);
893 if (!bh || ext4_buffer_uptodate(bh))
896 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
904 /* Read a contiguous batch of blocks. */
905 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
906 bool wait, struct buffer_head **bhs)
910 for (i = 0; i < bh_count; i++) {
911 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
912 if (IS_ERR(bhs[i])) {
913 err = PTR_ERR(bhs[i]);
919 for (i = 0; i < bh_count; i++)
920 /* Note that NULL bhs[i] is valid because of holes. */
921 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
922 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
927 for (i = 0; i < bh_count; i++)
929 wait_on_buffer(bhs[i]);
931 for (i = 0; i < bh_count; i++) {
932 if (bhs[i] && !buffer_uptodate(bhs[i])) {
940 for (i = 0; i < bh_count; i++) {
947 int ext4_walk_page_buffers(handle_t *handle,
948 struct buffer_head *head,
952 int (*fn)(handle_t *handle,
953 struct buffer_head *bh))
955 struct buffer_head *bh;
956 unsigned block_start, block_end;
957 unsigned blocksize = head->b_size;
959 struct buffer_head *next;
961 for (bh = head, block_start = 0;
962 ret == 0 && (bh != head || !block_start);
963 block_start = block_end, bh = next) {
964 next = bh->b_this_page;
965 block_end = block_start + blocksize;
966 if (block_end <= from || block_start >= to) {
967 if (partial && !buffer_uptodate(bh))
971 err = (*fn)(handle, bh);
979 * To preserve ordering, it is essential that the hole instantiation and
980 * the data write be encapsulated in a single transaction. We cannot
981 * close off a transaction and start a new one between the ext4_get_block()
982 * and the commit_write(). So doing the jbd2_journal_start at the start of
983 * prepare_write() is the right place.
985 * Also, this function can nest inside ext4_writepage(). In that case, we
986 * *know* that ext4_writepage() has generated enough buffer credits to do the
987 * whole page. So we won't block on the journal in that case, which is good,
988 * because the caller may be PF_MEMALLOC.
990 * By accident, ext4 can be reentered when a transaction is open via
991 * quota file writes. If we were to commit the transaction while thus
992 * reentered, there can be a deadlock - we would be holding a quota
993 * lock, and the commit would never complete if another thread had a
994 * transaction open and was blocking on the quota lock - a ranking
997 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
998 * will _not_ run commit under these circumstances because handle->h_ref
999 * is elevated. We'll still have enough credits for the tiny quotafile
1002 int do_journal_get_write_access(handle_t *handle,
1003 struct buffer_head *bh)
1005 int dirty = buffer_dirty(bh);
1008 if (!buffer_mapped(bh) || buffer_freed(bh))
1011 * __block_write_begin() could have dirtied some buffers. Clean
1012 * the dirty bit as jbd2_journal_get_write_access() could complain
1013 * otherwise about fs integrity issues. Setting of the dirty bit
1014 * by __block_write_begin() isn't a real problem here as we clear
1015 * the bit before releasing a page lock and thus writeback cannot
1016 * ever write the buffer.
1019 clear_buffer_dirty(bh);
1020 BUFFER_TRACE(bh, "get write access");
1021 ret = ext4_journal_get_write_access(handle, bh);
1023 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1027 #ifdef CONFIG_FS_ENCRYPTION
1028 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1029 get_block_t *get_block)
1031 unsigned from = pos & (PAGE_SIZE - 1);
1032 unsigned to = from + len;
1033 struct inode *inode = page->mapping->host;
1034 unsigned block_start, block_end;
1037 unsigned blocksize = inode->i_sb->s_blocksize;
1039 struct buffer_head *bh, *head, *wait[2];
1043 BUG_ON(!PageLocked(page));
1044 BUG_ON(from > PAGE_SIZE);
1045 BUG_ON(to > PAGE_SIZE);
1048 if (!page_has_buffers(page))
1049 create_empty_buffers(page, blocksize, 0);
1050 head = page_buffers(page);
1051 bbits = ilog2(blocksize);
1052 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1054 for (bh = head, block_start = 0; bh != head || !block_start;
1055 block++, block_start = block_end, bh = bh->b_this_page) {
1056 block_end = block_start + blocksize;
1057 if (block_end <= from || block_start >= to) {
1058 if (PageUptodate(page)) {
1059 if (!buffer_uptodate(bh))
1060 set_buffer_uptodate(bh);
1065 clear_buffer_new(bh);
1066 if (!buffer_mapped(bh)) {
1067 WARN_ON(bh->b_size != blocksize);
1068 err = get_block(inode, block, bh, 1);
1071 if (buffer_new(bh)) {
1072 if (PageUptodate(page)) {
1073 clear_buffer_new(bh);
1074 set_buffer_uptodate(bh);
1075 mark_buffer_dirty(bh);
1078 if (block_end > to || block_start < from)
1079 zero_user_segments(page, to, block_end,
1084 if (PageUptodate(page)) {
1085 if (!buffer_uptodate(bh))
1086 set_buffer_uptodate(bh);
1089 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1090 !buffer_unwritten(bh) &&
1091 (block_start < from || block_end > to)) {
1092 ext4_read_bh_lock(bh, 0, false);
1093 wait[nr_wait++] = bh;
1097 * If we issued read requests, let them complete.
1099 for (i = 0; i < nr_wait; i++) {
1100 wait_on_buffer(wait[i]);
1101 if (!buffer_uptodate(wait[i]))
1104 if (unlikely(err)) {
1105 page_zero_new_buffers(page, from, to);
1106 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1107 for (i = 0; i < nr_wait; i++) {
1110 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1111 bh_offset(wait[i]));
1113 clear_buffer_uptodate(wait[i]);
1123 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1124 loff_t pos, unsigned len, unsigned flags,
1125 struct page **pagep, void **fsdata)
1127 struct inode *inode = mapping->host;
1128 int ret, needed_blocks;
1135 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1138 trace_ext4_write_begin(inode, pos, len, flags);
1140 * Reserve one block more for addition to orphan list in case
1141 * we allocate blocks but write fails for some reason
1143 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1144 index = pos >> PAGE_SHIFT;
1145 from = pos & (PAGE_SIZE - 1);
1148 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1149 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1158 * grab_cache_page_write_begin() can take a long time if the
1159 * system is thrashing due to memory pressure, or if the page
1160 * is being written back. So grab it first before we start
1161 * the transaction handle. This also allows us to allocate
1162 * the page (if needed) without using GFP_NOFS.
1165 page = grab_cache_page_write_begin(mapping, index, flags);
1171 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1172 if (IS_ERR(handle)) {
1174 return PTR_ERR(handle);
1178 if (page->mapping != mapping) {
1179 /* The page got truncated from under us */
1182 ext4_journal_stop(handle);
1185 /* In case writeback began while the page was unlocked */
1186 wait_for_stable_page(page);
1188 #ifdef CONFIG_FS_ENCRYPTION
1189 if (ext4_should_dioread_nolock(inode))
1190 ret = ext4_block_write_begin(page, pos, len,
1191 ext4_get_block_unwritten);
1193 ret = ext4_block_write_begin(page, pos, len,
1196 if (ext4_should_dioread_nolock(inode))
1197 ret = __block_write_begin(page, pos, len,
1198 ext4_get_block_unwritten);
1200 ret = __block_write_begin(page, pos, len, ext4_get_block);
1202 if (!ret && ext4_should_journal_data(inode)) {
1203 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1205 do_journal_get_write_access);
1209 bool extended = (pos + len > inode->i_size) &&
1210 !ext4_verity_in_progress(inode);
1214 * __block_write_begin may have instantiated a few blocks
1215 * outside i_size. Trim these off again. Don't need
1216 * i_size_read because we hold i_mutex.
1218 * Add inode to orphan list in case we crash before
1221 if (extended && ext4_can_truncate(inode))
1222 ext4_orphan_add(handle, inode);
1224 ext4_journal_stop(handle);
1226 ext4_truncate_failed_write(inode);
1228 * If truncate failed early the inode might
1229 * still be on the orphan list; we need to
1230 * make sure the inode is removed from the
1231 * orphan list in that case.
1234 ext4_orphan_del(NULL, inode);
1237 if (ret == -ENOSPC &&
1238 ext4_should_retry_alloc(inode->i_sb, &retries))
1247 /* For write_end() in data=journal mode */
1248 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1251 if (!buffer_mapped(bh) || buffer_freed(bh))
1253 set_buffer_uptodate(bh);
1254 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1255 clear_buffer_meta(bh);
1256 clear_buffer_prio(bh);
1261 * We need to pick up the new inode size which generic_commit_write gave us
1262 * `file' can be NULL - eg, when called from page_symlink().
1264 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1265 * buffers are managed internally.
1267 static int ext4_write_end(struct file *file,
1268 struct address_space *mapping,
1269 loff_t pos, unsigned len, unsigned copied,
1270 struct page *page, void *fsdata)
1272 handle_t *handle = ext4_journal_current_handle();
1273 struct inode *inode = mapping->host;
1274 loff_t old_size = inode->i_size;
1276 int i_size_changed = 0;
1277 int inline_data = ext4_has_inline_data(inode);
1278 bool verity = ext4_verity_in_progress(inode);
1280 trace_ext4_write_end(inode, pos, len, copied);
1282 ret = ext4_write_inline_data_end(inode, pos, len,
1291 copied = block_write_end(file, mapping, pos,
1292 len, copied, page, fsdata);
1294 * it's important to update i_size while still holding page lock:
1295 * page writeout could otherwise come in and zero beyond i_size.
1297 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1298 * blocks are being written past EOF, so skip the i_size update.
1301 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1305 if (old_size < pos && !verity)
1306 pagecache_isize_extended(inode, old_size, pos);
1308 * Don't mark the inode dirty under page lock. First, it unnecessarily
1309 * makes the holding time of page lock longer. Second, it forces lock
1310 * ordering of page lock and transaction start for journaling
1313 if (i_size_changed || inline_data)
1314 ret = ext4_mark_inode_dirty(handle, inode);
1316 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1317 /* if we have allocated more blocks and copied
1318 * less. We will have blocks allocated outside
1319 * inode->i_size. So truncate them
1321 ext4_orphan_add(handle, inode);
1323 ret2 = ext4_journal_stop(handle);
1327 if (pos + len > inode->i_size && !verity) {
1328 ext4_truncate_failed_write(inode);
1330 * If truncate failed early the inode might still be
1331 * on the orphan list; we need to make sure the inode
1332 * is removed from the orphan list in that case.
1335 ext4_orphan_del(NULL, inode);
1338 return ret ? ret : copied;
1342 * This is a private version of page_zero_new_buffers() which doesn't
1343 * set the buffer to be dirty, since in data=journalled mode we need
1344 * to call ext4_handle_dirty_metadata() instead.
1346 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1348 unsigned from, unsigned to)
1350 unsigned int block_start = 0, block_end;
1351 struct buffer_head *head, *bh;
1353 bh = head = page_buffers(page);
1355 block_end = block_start + bh->b_size;
1356 if (buffer_new(bh)) {
1357 if (block_end > from && block_start < to) {
1358 if (!PageUptodate(page)) {
1359 unsigned start, size;
1361 start = max(from, block_start);
1362 size = min(to, block_end) - start;
1364 zero_user(page, start, size);
1365 write_end_fn(handle, bh);
1367 clear_buffer_new(bh);
1370 block_start = block_end;
1371 bh = bh->b_this_page;
1372 } while (bh != head);
1375 static int ext4_journalled_write_end(struct file *file,
1376 struct address_space *mapping,
1377 loff_t pos, unsigned len, unsigned copied,
1378 struct page *page, void *fsdata)
1380 handle_t *handle = ext4_journal_current_handle();
1381 struct inode *inode = mapping->host;
1382 loff_t old_size = inode->i_size;
1386 int size_changed = 0;
1387 int inline_data = ext4_has_inline_data(inode);
1388 bool verity = ext4_verity_in_progress(inode);
1390 trace_ext4_journalled_write_end(inode, pos, len, copied);
1391 from = pos & (PAGE_SIZE - 1);
1394 BUG_ON(!ext4_handle_valid(handle));
1397 ret = ext4_write_inline_data_end(inode, pos, len,
1405 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1407 ext4_journalled_zero_new_buffers(handle, page, from, to);
1409 if (unlikely(copied < len))
1410 ext4_journalled_zero_new_buffers(handle, page,
1412 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1413 from + copied, &partial,
1416 SetPageUptodate(page);
1419 size_changed = ext4_update_inode_size(inode, pos + copied);
1420 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1421 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1425 if (old_size < pos && !verity)
1426 pagecache_isize_extended(inode, old_size, pos);
1428 if (size_changed || inline_data) {
1429 ret2 = ext4_mark_inode_dirty(handle, inode);
1434 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1435 /* if we have allocated more blocks and copied
1436 * less. We will have blocks allocated outside
1437 * inode->i_size. So truncate them
1439 ext4_orphan_add(handle, inode);
1442 ret2 = ext4_journal_stop(handle);
1445 if (pos + len > inode->i_size && !verity) {
1446 ext4_truncate_failed_write(inode);
1448 * If truncate failed early the inode might still be
1449 * on the orphan list; we need to make sure the inode
1450 * is removed from the orphan list in that case.
1453 ext4_orphan_del(NULL, inode);
1456 return ret ? ret : copied;
1460 * Reserve space for a single cluster
1462 static int ext4_da_reserve_space(struct inode *inode)
1464 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1465 struct ext4_inode_info *ei = EXT4_I(inode);
1469 * We will charge metadata quota at writeout time; this saves
1470 * us from metadata over-estimation, though we may go over by
1471 * a small amount in the end. Here we just reserve for data.
1473 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1477 spin_lock(&ei->i_block_reservation_lock);
1478 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1479 spin_unlock(&ei->i_block_reservation_lock);
1480 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1483 ei->i_reserved_data_blocks++;
1484 trace_ext4_da_reserve_space(inode);
1485 spin_unlock(&ei->i_block_reservation_lock);
1487 return 0; /* success */
1490 void ext4_da_release_space(struct inode *inode, int to_free)
1492 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1493 struct ext4_inode_info *ei = EXT4_I(inode);
1496 return; /* Nothing to release, exit */
1498 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1500 trace_ext4_da_release_space(inode, to_free);
1501 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1503 * if there aren't enough reserved blocks, then the
1504 * counter is messed up somewhere. Since this
1505 * function is called from invalidate page, it's
1506 * harmless to return without any action.
1508 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1509 "ino %lu, to_free %d with only %d reserved "
1510 "data blocks", inode->i_ino, to_free,
1511 ei->i_reserved_data_blocks);
1513 to_free = ei->i_reserved_data_blocks;
1515 ei->i_reserved_data_blocks -= to_free;
1517 /* update fs dirty data blocks counter */
1518 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1520 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1522 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1526 * Delayed allocation stuff
1529 struct mpage_da_data {
1530 struct inode *inode;
1531 struct writeback_control *wbc;
1533 pgoff_t first_page; /* The first page to write */
1534 pgoff_t next_page; /* Current page to examine */
1535 pgoff_t last_page; /* Last page to examine */
1537 * Extent to map - this can be after first_page because that can be
1538 * fully mapped. We somewhat abuse m_flags to store whether the extent
1539 * is delalloc or unwritten.
1541 struct ext4_map_blocks map;
1542 struct ext4_io_submit io_submit; /* IO submission data */
1543 unsigned int do_map:1;
1544 unsigned int scanned_until_end:1;
1547 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1552 struct pagevec pvec;
1553 struct inode *inode = mpd->inode;
1554 struct address_space *mapping = inode->i_mapping;
1556 /* This is necessary when next_page == 0. */
1557 if (mpd->first_page >= mpd->next_page)
1560 mpd->scanned_until_end = 0;
1561 index = mpd->first_page;
1562 end = mpd->next_page - 1;
1564 ext4_lblk_t start, last;
1565 start = index << (PAGE_SHIFT - inode->i_blkbits);
1566 last = end << (PAGE_SHIFT - inode->i_blkbits);
1567 ext4_es_remove_extent(inode, start, last - start + 1);
1570 pagevec_init(&pvec);
1571 while (index <= end) {
1572 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1575 for (i = 0; i < nr_pages; i++) {
1576 struct page *page = pvec.pages[i];
1578 BUG_ON(!PageLocked(page));
1579 BUG_ON(PageWriteback(page));
1581 if (page_mapped(page))
1582 clear_page_dirty_for_io(page);
1583 block_invalidatepage(page, 0, PAGE_SIZE);
1584 ClearPageUptodate(page);
1588 pagevec_release(&pvec);
1592 static void ext4_print_free_blocks(struct inode *inode)
1594 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1595 struct super_block *sb = inode->i_sb;
1596 struct ext4_inode_info *ei = EXT4_I(inode);
1598 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1599 EXT4_C2B(EXT4_SB(inode->i_sb),
1600 ext4_count_free_clusters(sb)));
1601 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1602 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1603 (long long) EXT4_C2B(EXT4_SB(sb),
1604 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1605 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1606 (long long) EXT4_C2B(EXT4_SB(sb),
1607 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1608 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1609 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1610 ei->i_reserved_data_blocks);
1614 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1616 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1620 * ext4_insert_delayed_block - adds a delayed block to the extents status
1621 * tree, incrementing the reserved cluster/block
1622 * count or making a pending reservation
1625 * @inode - file containing the newly added block
1626 * @lblk - logical block to be added
1628 * Returns 0 on success, negative error code on failure.
1630 static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1632 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1634 bool allocated = false;
1637 * If the cluster containing lblk is shared with a delayed,
1638 * written, or unwritten extent in a bigalloc file system, it's
1639 * already been accounted for and does not need to be reserved.
1640 * A pending reservation must be made for the cluster if it's
1641 * shared with a written or unwritten extent and doesn't already
1642 * have one. Written and unwritten extents can be purged from the
1643 * extents status tree if the system is under memory pressure, so
1644 * it's necessary to examine the extent tree if a search of the
1645 * extents status tree doesn't get a match.
1647 if (sbi->s_cluster_ratio == 1) {
1648 ret = ext4_da_reserve_space(inode);
1649 if (ret != 0) /* ENOSPC */
1651 } else { /* bigalloc */
1652 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1653 if (!ext4_es_scan_clu(inode,
1654 &ext4_es_is_mapped, lblk)) {
1655 ret = ext4_clu_mapped(inode,
1656 EXT4_B2C(sbi, lblk));
1660 ret = ext4_da_reserve_space(inode);
1661 if (ret != 0) /* ENOSPC */
1672 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1679 * This function is grabs code from the very beginning of
1680 * ext4_map_blocks, but assumes that the caller is from delayed write
1681 * time. This function looks up the requested blocks and sets the
1682 * buffer delay bit under the protection of i_data_sem.
1684 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1685 struct ext4_map_blocks *map,
1686 struct buffer_head *bh)
1688 struct extent_status es;
1690 sector_t invalid_block = ~((sector_t) 0xffff);
1691 #ifdef ES_AGGRESSIVE_TEST
1692 struct ext4_map_blocks orig_map;
1694 memcpy(&orig_map, map, sizeof(*map));
1697 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1701 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1702 (unsigned long) map->m_lblk);
1704 /* Lookup extent status tree firstly */
1705 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1706 if (ext4_es_is_hole(&es)) {
1708 down_read(&EXT4_I(inode)->i_data_sem);
1713 * Delayed extent could be allocated by fallocate.
1714 * So we need to check it.
1716 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1717 map_bh(bh, inode->i_sb, invalid_block);
1719 set_buffer_delay(bh);
1723 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1724 retval = es.es_len - (iblock - es.es_lblk);
1725 if (retval > map->m_len)
1726 retval = map->m_len;
1727 map->m_len = retval;
1728 if (ext4_es_is_written(&es))
1729 map->m_flags |= EXT4_MAP_MAPPED;
1730 else if (ext4_es_is_unwritten(&es))
1731 map->m_flags |= EXT4_MAP_UNWRITTEN;
1735 #ifdef ES_AGGRESSIVE_TEST
1736 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1742 * Try to see if we can get the block without requesting a new
1743 * file system block.
1745 down_read(&EXT4_I(inode)->i_data_sem);
1746 if (ext4_has_inline_data(inode))
1748 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1749 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1751 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1758 * XXX: __block_prepare_write() unmaps passed block,
1762 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1768 map_bh(bh, inode->i_sb, invalid_block);
1770 set_buffer_delay(bh);
1771 } else if (retval > 0) {
1773 unsigned int status;
1775 if (unlikely(retval != map->m_len)) {
1776 ext4_warning(inode->i_sb,
1777 "ES len assertion failed for inode "
1778 "%lu: retval %d != map->m_len %d",
1779 inode->i_ino, retval, map->m_len);
1783 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1784 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1785 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1786 map->m_pblk, status);
1792 up_read((&EXT4_I(inode)->i_data_sem));
1798 * This is a special get_block_t callback which is used by
1799 * ext4_da_write_begin(). It will either return mapped block or
1800 * reserve space for a single block.
1802 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1803 * We also have b_blocknr = -1 and b_bdev initialized properly
1805 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1806 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1807 * initialized properly.
1809 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1810 struct buffer_head *bh, int create)
1812 struct ext4_map_blocks map;
1815 BUG_ON(create == 0);
1816 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1818 map.m_lblk = iblock;
1822 * first, we need to know whether the block is allocated already
1823 * preallocated blocks are unmapped but should treated
1824 * the same as allocated blocks.
1826 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1830 map_bh(bh, inode->i_sb, map.m_pblk);
1831 ext4_update_bh_state(bh, map.m_flags);
1833 if (buffer_unwritten(bh)) {
1834 /* A delayed write to unwritten bh should be marked
1835 * new and mapped. Mapped ensures that we don't do
1836 * get_block multiple times when we write to the same
1837 * offset and new ensures that we do proper zero out
1838 * for partial write.
1841 set_buffer_mapped(bh);
1846 static int bget_one(handle_t *handle, struct buffer_head *bh)
1852 static int bput_one(handle_t *handle, struct buffer_head *bh)
1858 static int __ext4_journalled_writepage(struct page *page,
1861 struct address_space *mapping = page->mapping;
1862 struct inode *inode = mapping->host;
1863 struct buffer_head *page_bufs = NULL;
1864 handle_t *handle = NULL;
1865 int ret = 0, err = 0;
1866 int inline_data = ext4_has_inline_data(inode);
1867 struct buffer_head *inode_bh = NULL;
1869 ClearPageChecked(page);
1872 BUG_ON(page->index != 0);
1873 BUG_ON(len > ext4_get_max_inline_size(inode));
1874 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1875 if (inode_bh == NULL)
1878 page_bufs = page_buffers(page);
1883 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1887 * We need to release the page lock before we start the
1888 * journal, so grab a reference so the page won't disappear
1889 * out from under us.
1894 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1895 ext4_writepage_trans_blocks(inode));
1896 if (IS_ERR(handle)) {
1897 ret = PTR_ERR(handle);
1899 goto out_no_pagelock;
1901 BUG_ON(!ext4_handle_valid(handle));
1905 if (page->mapping != mapping) {
1906 /* The page got truncated from under us */
1907 ext4_journal_stop(handle);
1913 ret = ext4_mark_inode_dirty(handle, inode);
1915 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1916 do_journal_get_write_access);
1918 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1923 err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1926 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1927 err = ext4_journal_stop(handle);
1931 if (!ext4_has_inline_data(inode))
1932 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1934 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1943 * Note that we don't need to start a transaction unless we're journaling data
1944 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1945 * need to file the inode to the transaction's list in ordered mode because if
1946 * we are writing back data added by write(), the inode is already there and if
1947 * we are writing back data modified via mmap(), no one guarantees in which
1948 * transaction the data will hit the disk. In case we are journaling data, we
1949 * cannot start transaction directly because transaction start ranks above page
1950 * lock so we have to do some magic.
1952 * This function can get called via...
1953 * - ext4_writepages after taking page lock (have journal handle)
1954 * - journal_submit_inode_data_buffers (no journal handle)
1955 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1956 * - grab_page_cache when doing write_begin (have journal handle)
1958 * We don't do any block allocation in this function. If we have page with
1959 * multiple blocks we need to write those buffer_heads that are mapped. This
1960 * is important for mmaped based write. So if we do with blocksize 1K
1961 * truncate(f, 1024);
1962 * a = mmap(f, 0, 4096);
1964 * truncate(f, 4096);
1965 * we have in the page first buffer_head mapped via page_mkwrite call back
1966 * but other buffer_heads would be unmapped but dirty (dirty done via the
1967 * do_wp_page). So writepage should write the first block. If we modify
1968 * the mmap area beyond 1024 we will again get a page_fault and the
1969 * page_mkwrite callback will do the block allocation and mark the
1970 * buffer_heads mapped.
1972 * We redirty the page if we have any buffer_heads that is either delay or
1973 * unwritten in the page.
1975 * We can get recursively called as show below.
1977 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1980 * But since we don't do any block allocation we should not deadlock.
1981 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1983 static int ext4_writepage(struct page *page,
1984 struct writeback_control *wbc)
1989 struct buffer_head *page_bufs = NULL;
1990 struct inode *inode = page->mapping->host;
1991 struct ext4_io_submit io_submit;
1992 bool keep_towrite = false;
1994 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
1995 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
2000 trace_ext4_writepage(page);
2001 size = i_size_read(inode);
2002 if (page->index == size >> PAGE_SHIFT &&
2003 !ext4_verity_in_progress(inode))
2004 len = size & ~PAGE_MASK;
2008 page_bufs = page_buffers(page);
2010 * We cannot do block allocation or other extent handling in this
2011 * function. If there are buffers needing that, we have to redirty
2012 * the page. But we may reach here when we do a journal commit via
2013 * journal_submit_inode_data_buffers() and in that case we must write
2014 * allocated buffers to achieve data=ordered mode guarantees.
2016 * Also, if there is only one buffer per page (the fs block
2017 * size == the page size), if one buffer needs block
2018 * allocation or needs to modify the extent tree to clear the
2019 * unwritten flag, we know that the page can't be written at
2020 * all, so we might as well refuse the write immediately.
2021 * Unfortunately if the block size != page size, we can't as
2022 * easily detect this case using ext4_walk_page_buffers(), but
2023 * for the extremely common case, this is an optimization that
2024 * skips a useless round trip through ext4_bio_write_page().
2026 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2027 ext4_bh_delay_or_unwritten)) {
2028 redirty_page_for_writepage(wbc, page);
2029 if ((current->flags & PF_MEMALLOC) ||
2030 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2032 * For memory cleaning there's no point in writing only
2033 * some buffers. So just bail out. Warn if we came here
2034 * from direct reclaim.
2036 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2041 keep_towrite = true;
2044 if (PageChecked(page) && ext4_should_journal_data(inode))
2046 * It's mmapped pagecache. Add buffers and journal it. There
2047 * doesn't seem much point in redirtying the page here.
2049 return __ext4_journalled_writepage(page, len);
2051 ext4_io_submit_init(&io_submit, wbc);
2052 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2053 if (!io_submit.io_end) {
2054 redirty_page_for_writepage(wbc, page);
2058 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2059 ext4_io_submit(&io_submit);
2060 /* Drop io_end reference we got from init */
2061 ext4_put_io_end_defer(io_submit.io_end);
2065 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2071 BUG_ON(page->index != mpd->first_page);
2072 clear_page_dirty_for_io(page);
2074 * We have to be very careful here! Nothing protects writeback path
2075 * against i_size changes and the page can be writeably mapped into
2076 * page tables. So an application can be growing i_size and writing
2077 * data through mmap while writeback runs. clear_page_dirty_for_io()
2078 * write-protects our page in page tables and the page cannot get
2079 * written to again until we release page lock. So only after
2080 * clear_page_dirty_for_io() we are safe to sample i_size for
2081 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2082 * on the barrier provided by TestClearPageDirty in
2083 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2084 * after page tables are updated.
2086 size = i_size_read(mpd->inode);
2087 if (page->index == size >> PAGE_SHIFT &&
2088 !ext4_verity_in_progress(mpd->inode))
2089 len = size & ~PAGE_MASK;
2092 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2094 mpd->wbc->nr_to_write--;
2100 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2103 * mballoc gives us at most this number of blocks...
2104 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2105 * The rest of mballoc seems to handle chunks up to full group size.
2107 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2110 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2112 * @mpd - extent of blocks
2113 * @lblk - logical number of the block in the file
2114 * @bh - buffer head we want to add to the extent
2116 * The function is used to collect contig. blocks in the same state. If the
2117 * buffer doesn't require mapping for writeback and we haven't started the
2118 * extent of buffers to map yet, the function returns 'true' immediately - the
2119 * caller can write the buffer right away. Otherwise the function returns true
2120 * if the block has been added to the extent, false if the block couldn't be
2123 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2124 struct buffer_head *bh)
2126 struct ext4_map_blocks *map = &mpd->map;
2128 /* Buffer that doesn't need mapping for writeback? */
2129 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2130 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2131 /* So far no extent to map => we write the buffer right away */
2132 if (map->m_len == 0)
2137 /* First block in the extent? */
2138 if (map->m_len == 0) {
2139 /* We cannot map unless handle is started... */
2144 map->m_flags = bh->b_state & BH_FLAGS;
2148 /* Don't go larger than mballoc is willing to allocate */
2149 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2152 /* Can we merge the block to our big extent? */
2153 if (lblk == map->m_lblk + map->m_len &&
2154 (bh->b_state & BH_FLAGS) == map->m_flags) {
2162 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2164 * @mpd - extent of blocks for mapping
2165 * @head - the first buffer in the page
2166 * @bh - buffer we should start processing from
2167 * @lblk - logical number of the block in the file corresponding to @bh
2169 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2170 * the page for IO if all buffers in this page were mapped and there's no
2171 * accumulated extent of buffers to map or add buffers in the page to the
2172 * extent of buffers to map. The function returns 1 if the caller can continue
2173 * by processing the next page, 0 if it should stop adding buffers to the
2174 * extent to map because we cannot extend it anymore. It can also return value
2175 * < 0 in case of error during IO submission.
2177 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2178 struct buffer_head *head,
2179 struct buffer_head *bh,
2182 struct inode *inode = mpd->inode;
2184 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2185 >> inode->i_blkbits;
2187 if (ext4_verity_in_progress(inode))
2188 blocks = EXT_MAX_BLOCKS;
2191 BUG_ON(buffer_locked(bh));
2193 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2194 /* Found extent to map? */
2197 /* Buffer needs mapping and handle is not started? */
2200 /* Everything mapped so far and we hit EOF */
2203 } while (lblk++, (bh = bh->b_this_page) != head);
2204 /* So far everything mapped? Submit the page for IO. */
2205 if (mpd->map.m_len == 0) {
2206 err = mpage_submit_page(mpd, head->b_page);
2210 if (lblk >= blocks) {
2211 mpd->scanned_until_end = 1;
2218 * mpage_process_page - update page buffers corresponding to changed extent and
2219 * may submit fully mapped page for IO
2221 * @mpd - description of extent to map, on return next extent to map
2222 * @m_lblk - logical block mapping.
2223 * @m_pblk - corresponding physical mapping.
2224 * @map_bh - determines on return whether this page requires any further
2226 * Scan given page buffers corresponding to changed extent and update buffer
2227 * state according to new extent state.
2228 * We map delalloc buffers to their physical location, clear unwritten bits.
2229 * If the given page is not fully mapped, we update @map to the next extent in
2230 * the given page that needs mapping & return @map_bh as true.
2232 static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
2233 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2236 struct buffer_head *head, *bh;
2237 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2238 ext4_lblk_t lblk = *m_lblk;
2239 ext4_fsblk_t pblock = *m_pblk;
2241 int blkbits = mpd->inode->i_blkbits;
2242 ssize_t io_end_size = 0;
2243 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2245 bh = head = page_buffers(page);
2247 if (lblk < mpd->map.m_lblk)
2249 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2251 * Buffer after end of mapped extent.
2252 * Find next buffer in the page to map.
2255 mpd->map.m_flags = 0;
2256 io_end_vec->size += io_end_size;
2259 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2262 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2263 io_end_vec = ext4_alloc_io_end_vec(io_end);
2264 if (IS_ERR(io_end_vec)) {
2265 err = PTR_ERR(io_end_vec);
2268 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2273 if (buffer_delay(bh)) {
2274 clear_buffer_delay(bh);
2275 bh->b_blocknr = pblock++;
2277 clear_buffer_unwritten(bh);
2278 io_end_size += (1 << blkbits);
2279 } while (lblk++, (bh = bh->b_this_page) != head);
2281 io_end_vec->size += io_end_size;
2291 * mpage_map_buffers - update buffers corresponding to changed extent and
2292 * submit fully mapped pages for IO
2294 * @mpd - description of extent to map, on return next extent to map
2296 * Scan buffers corresponding to changed extent (we expect corresponding pages
2297 * to be already locked) and update buffer state according to new extent state.
2298 * We map delalloc buffers to their physical location, clear unwritten bits,
2299 * and mark buffers as uninit when we perform writes to unwritten extents
2300 * and do extent conversion after IO is finished. If the last page is not fully
2301 * mapped, we update @map to the next extent in the last page that needs
2302 * mapping. Otherwise we submit the page for IO.
2304 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2306 struct pagevec pvec;
2308 struct inode *inode = mpd->inode;
2309 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2312 ext4_fsblk_t pblock;
2314 bool map_bh = false;
2316 start = mpd->map.m_lblk >> bpp_bits;
2317 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2318 lblk = start << bpp_bits;
2319 pblock = mpd->map.m_pblk;
2321 pagevec_init(&pvec);
2322 while (start <= end) {
2323 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2327 for (i = 0; i < nr_pages; i++) {
2328 struct page *page = pvec.pages[i];
2330 err = mpage_process_page(mpd, page, &lblk, &pblock,
2333 * If map_bh is true, means page may require further bh
2334 * mapping, or maybe the page was submitted for IO.
2335 * So we return to call further extent mapping.
2337 if (err < 0 || map_bh)
2339 /* Page fully mapped - let IO run! */
2340 err = mpage_submit_page(mpd, page);
2344 pagevec_release(&pvec);
2346 /* Extent fully mapped and matches with page boundary. We are done. */
2348 mpd->map.m_flags = 0;
2351 pagevec_release(&pvec);
2355 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2357 struct inode *inode = mpd->inode;
2358 struct ext4_map_blocks *map = &mpd->map;
2359 int get_blocks_flags;
2360 int err, dioread_nolock;
2362 trace_ext4_da_write_pages_extent(inode, map);
2364 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2365 * to convert an unwritten extent to be initialized (in the case
2366 * where we have written into one or more preallocated blocks). It is
2367 * possible that we're going to need more metadata blocks than
2368 * previously reserved. However we must not fail because we're in
2369 * writeback and there is nothing we can do about it so it might result
2370 * in data loss. So use reserved blocks to allocate metadata if
2373 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2374 * the blocks in question are delalloc blocks. This indicates
2375 * that the blocks and quotas has already been checked when
2376 * the data was copied into the page cache.
2378 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2379 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2380 EXT4_GET_BLOCKS_IO_SUBMIT;
2381 dioread_nolock = ext4_should_dioread_nolock(inode);
2383 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2384 if (map->m_flags & BIT(BH_Delay))
2385 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2387 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2390 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2391 if (!mpd->io_submit.io_end->handle &&
2392 ext4_handle_valid(handle)) {
2393 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2394 handle->h_rsv_handle = NULL;
2396 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2399 BUG_ON(map->m_len == 0);
2404 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2405 * mpd->len and submit pages underlying it for IO
2407 * @handle - handle for journal operations
2408 * @mpd - extent to map
2409 * @give_up_on_write - we set this to true iff there is a fatal error and there
2410 * is no hope of writing the data. The caller should discard
2411 * dirty pages to avoid infinite loops.
2413 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2414 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2415 * them to initialized or split the described range from larger unwritten
2416 * extent. Note that we need not map all the described range since allocation
2417 * can return less blocks or the range is covered by more unwritten extents. We
2418 * cannot map more because we are limited by reserved transaction credits. On
2419 * the other hand we always make sure that the last touched page is fully
2420 * mapped so that it can be written out (and thus forward progress is
2421 * guaranteed). After mapping we submit all mapped pages for IO.
2423 static int mpage_map_and_submit_extent(handle_t *handle,
2424 struct mpage_da_data *mpd,
2425 bool *give_up_on_write)
2427 struct inode *inode = mpd->inode;
2428 struct ext4_map_blocks *map = &mpd->map;
2432 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2433 struct ext4_io_end_vec *io_end_vec;
2435 io_end_vec = ext4_alloc_io_end_vec(io_end);
2436 if (IS_ERR(io_end_vec))
2437 return PTR_ERR(io_end_vec);
2438 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2440 err = mpage_map_one_extent(handle, mpd);
2442 struct super_block *sb = inode->i_sb;
2444 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2445 ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2446 goto invalidate_dirty_pages;
2448 * Let the uper layers retry transient errors.
2449 * In the case of ENOSPC, if ext4_count_free_blocks()
2450 * is non-zero, a commit should free up blocks.
2452 if ((err == -ENOMEM) ||
2453 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2455 goto update_disksize;
2458 ext4_msg(sb, KERN_CRIT,
2459 "Delayed block allocation failed for "
2460 "inode %lu at logical offset %llu with"
2461 " max blocks %u with error %d",
2463 (unsigned long long)map->m_lblk,
2464 (unsigned)map->m_len, -err);
2465 ext4_msg(sb, KERN_CRIT,
2466 "This should not happen!! Data will "
2469 ext4_print_free_blocks(inode);
2470 invalidate_dirty_pages:
2471 *give_up_on_write = true;
2476 * Update buffer state, submit mapped pages, and get us new
2479 err = mpage_map_and_submit_buffers(mpd);
2481 goto update_disksize;
2482 } while (map->m_len);
2486 * Update on-disk size after IO is submitted. Races with
2487 * truncate are avoided by checking i_size under i_data_sem.
2489 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2490 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2494 down_write(&EXT4_I(inode)->i_data_sem);
2495 i_size = i_size_read(inode);
2496 if (disksize > i_size)
2498 if (disksize > EXT4_I(inode)->i_disksize)
2499 EXT4_I(inode)->i_disksize = disksize;
2500 up_write(&EXT4_I(inode)->i_data_sem);
2501 err2 = ext4_mark_inode_dirty(handle, inode);
2503 ext4_error_err(inode->i_sb, -err2,
2504 "Failed to mark inode %lu dirty",
2514 * Calculate the total number of credits to reserve for one writepages
2515 * iteration. This is called from ext4_writepages(). We map an extent of
2516 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2517 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2518 * bpp - 1 blocks in bpp different extents.
2520 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2522 int bpp = ext4_journal_blocks_per_page(inode);
2524 return ext4_meta_trans_blocks(inode,
2525 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2529 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2530 * and underlying extent to map
2532 * @mpd - where to look for pages
2534 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2535 * IO immediately. When we find a page which isn't mapped we start accumulating
2536 * extent of buffers underlying these pages that needs mapping (formed by
2537 * either delayed or unwritten buffers). We also lock the pages containing
2538 * these buffers. The extent found is returned in @mpd structure (starting at
2539 * mpd->lblk with length mpd->len blocks).
2541 * Note that this function can attach bios to one io_end structure which are
2542 * neither logically nor physically contiguous. Although it may seem as an
2543 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2544 * case as we need to track IO to all buffers underlying a page in one io_end.
2546 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2548 struct address_space *mapping = mpd->inode->i_mapping;
2549 struct pagevec pvec;
2550 unsigned int nr_pages;
2551 long left = mpd->wbc->nr_to_write;
2552 pgoff_t index = mpd->first_page;
2553 pgoff_t end = mpd->last_page;
2556 int blkbits = mpd->inode->i_blkbits;
2558 struct buffer_head *head;
2560 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2561 tag = PAGECACHE_TAG_TOWRITE;
2563 tag = PAGECACHE_TAG_DIRTY;
2565 pagevec_init(&pvec);
2567 mpd->next_page = index;
2568 while (index <= end) {
2569 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2574 for (i = 0; i < nr_pages; i++) {
2575 struct page *page = pvec.pages[i];
2578 * Accumulated enough dirty pages? This doesn't apply
2579 * to WB_SYNC_ALL mode. For integrity sync we have to
2580 * keep going because someone may be concurrently
2581 * dirtying pages, and we might have synced a lot of
2582 * newly appeared dirty pages, but have not synced all
2583 * of the old dirty pages.
2585 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2588 /* If we can't merge this page, we are done. */
2589 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2594 * If the page is no longer dirty, or its mapping no
2595 * longer corresponds to inode we are writing (which
2596 * means it has been truncated or invalidated), or the
2597 * page is already under writeback and we are not doing
2598 * a data integrity writeback, skip the page
2600 if (!PageDirty(page) ||
2601 (PageWriteback(page) &&
2602 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2603 unlikely(page->mapping != mapping)) {
2608 wait_on_page_writeback(page);
2609 BUG_ON(PageWriteback(page));
2611 if (mpd->map.m_len == 0)
2612 mpd->first_page = page->index;
2613 mpd->next_page = page->index + 1;
2614 /* Add all dirty buffers to mpd */
2615 lblk = ((ext4_lblk_t)page->index) <<
2616 (PAGE_SHIFT - blkbits);
2617 head = page_buffers(page);
2618 err = mpage_process_page_bufs(mpd, head, head, lblk);
2624 pagevec_release(&pvec);
2627 mpd->scanned_until_end = 1;
2630 pagevec_release(&pvec);
2634 static int ext4_writepages(struct address_space *mapping,
2635 struct writeback_control *wbc)
2637 pgoff_t writeback_index = 0;
2638 long nr_to_write = wbc->nr_to_write;
2639 int range_whole = 0;
2641 handle_t *handle = NULL;
2642 struct mpage_da_data mpd;
2643 struct inode *inode = mapping->host;
2644 int needed_blocks, rsv_blocks = 0, ret = 0;
2645 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2646 struct blk_plug plug;
2647 bool give_up_on_write = false;
2649 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2652 percpu_down_read(&sbi->s_writepages_rwsem);
2653 trace_ext4_writepages(inode, wbc);
2656 * No pages to write? This is mainly a kludge to avoid starting
2657 * a transaction for special inodes like journal inode on last iput()
2658 * because that could violate lock ordering on umount
2660 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2661 goto out_writepages;
2663 if (ext4_should_journal_data(inode)) {
2664 ret = generic_writepages(mapping, wbc);
2665 goto out_writepages;
2669 * If the filesystem has aborted, it is read-only, so return
2670 * right away instead of dumping stack traces later on that
2671 * will obscure the real source of the problem. We test
2672 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2673 * the latter could be true if the filesystem is mounted
2674 * read-only, and in that case, ext4_writepages should
2675 * *never* be called, so if that ever happens, we would want
2678 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2679 ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2681 goto out_writepages;
2685 * If we have inline data and arrive here, it means that
2686 * we will soon create the block for the 1st page, so
2687 * we'd better clear the inline data here.
2689 if (ext4_has_inline_data(inode)) {
2690 /* Just inode will be modified... */
2691 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2692 if (IS_ERR(handle)) {
2693 ret = PTR_ERR(handle);
2694 goto out_writepages;
2696 BUG_ON(ext4_test_inode_state(inode,
2697 EXT4_STATE_MAY_INLINE_DATA));
2698 ext4_destroy_inline_data(handle, inode);
2699 ext4_journal_stop(handle);
2702 if (ext4_should_dioread_nolock(inode)) {
2704 * We may need to convert up to one extent per block in
2705 * the page and we may dirty the inode.
2707 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2708 PAGE_SIZE >> inode->i_blkbits);
2711 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2714 if (wbc->range_cyclic) {
2715 writeback_index = mapping->writeback_index;
2716 if (writeback_index)
2718 mpd.first_page = writeback_index;
2721 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2722 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2727 ext4_io_submit_init(&mpd.io_submit, wbc);
2729 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2730 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2731 blk_start_plug(&plug);
2734 * First writeback pages that don't need mapping - we can avoid
2735 * starting a transaction unnecessarily and also avoid being blocked
2736 * in the block layer on device congestion while having transaction
2740 mpd.scanned_until_end = 0;
2741 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2742 if (!mpd.io_submit.io_end) {
2746 ret = mpage_prepare_extent_to_map(&mpd);
2747 /* Unlock pages we didn't use */
2748 mpage_release_unused_pages(&mpd, false);
2749 /* Submit prepared bio */
2750 ext4_io_submit(&mpd.io_submit);
2751 ext4_put_io_end_defer(mpd.io_submit.io_end);
2752 mpd.io_submit.io_end = NULL;
2756 while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
2757 /* For each extent of pages we use new io_end */
2758 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2759 if (!mpd.io_submit.io_end) {
2765 * We have two constraints: We find one extent to map and we
2766 * must always write out whole page (makes a difference when
2767 * blocksize < pagesize) so that we don't block on IO when we
2768 * try to write out the rest of the page. Journalled mode is
2769 * not supported by delalloc.
2771 BUG_ON(ext4_should_journal_data(inode));
2772 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2774 /* start a new transaction */
2775 handle = ext4_journal_start_with_reserve(inode,
2776 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2777 if (IS_ERR(handle)) {
2778 ret = PTR_ERR(handle);
2779 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2780 "%ld pages, ino %lu; err %d", __func__,
2781 wbc->nr_to_write, inode->i_ino, ret);
2782 /* Release allocated io_end */
2783 ext4_put_io_end(mpd.io_submit.io_end);
2784 mpd.io_submit.io_end = NULL;
2789 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2790 ret = mpage_prepare_extent_to_map(&mpd);
2791 if (!ret && mpd.map.m_len)
2792 ret = mpage_map_and_submit_extent(handle, &mpd,
2795 * Caution: If the handle is synchronous,
2796 * ext4_journal_stop() can wait for transaction commit
2797 * to finish which may depend on writeback of pages to
2798 * complete or on page lock to be released. In that
2799 * case, we have to wait until after we have
2800 * submitted all the IO, released page locks we hold,
2801 * and dropped io_end reference (for extent conversion
2802 * to be able to complete) before stopping the handle.
2804 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2805 ext4_journal_stop(handle);
2809 /* Unlock pages we didn't use */
2810 mpage_release_unused_pages(&mpd, give_up_on_write);
2811 /* Submit prepared bio */
2812 ext4_io_submit(&mpd.io_submit);
2815 * Drop our io_end reference we got from init. We have
2816 * to be careful and use deferred io_end finishing if
2817 * we are still holding the transaction as we can
2818 * release the last reference to io_end which may end
2819 * up doing unwritten extent conversion.
2822 ext4_put_io_end_defer(mpd.io_submit.io_end);
2823 ext4_journal_stop(handle);
2825 ext4_put_io_end(mpd.io_submit.io_end);
2826 mpd.io_submit.io_end = NULL;
2828 if (ret == -ENOSPC && sbi->s_journal) {
2830 * Commit the transaction which would
2831 * free blocks released in the transaction
2834 jbd2_journal_force_commit_nested(sbi->s_journal);
2838 /* Fatal error - ENOMEM, EIO... */
2843 blk_finish_plug(&plug);
2844 if (!ret && !cycled && wbc->nr_to_write > 0) {
2846 mpd.last_page = writeback_index - 1;
2852 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2854 * Set the writeback_index so that range_cyclic
2855 * mode will write it back later
2857 mapping->writeback_index = mpd.first_page;
2860 trace_ext4_writepages_result(inode, wbc, ret,
2861 nr_to_write - wbc->nr_to_write);
2862 percpu_up_read(&sbi->s_writepages_rwsem);
2866 static int ext4_dax_writepages(struct address_space *mapping,
2867 struct writeback_control *wbc)
2870 long nr_to_write = wbc->nr_to_write;
2871 struct inode *inode = mapping->host;
2872 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2874 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2877 percpu_down_read(&sbi->s_writepages_rwsem);
2878 trace_ext4_writepages(inode, wbc);
2880 ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
2881 trace_ext4_writepages_result(inode, wbc, ret,
2882 nr_to_write - wbc->nr_to_write);
2883 percpu_up_read(&sbi->s_writepages_rwsem);
2887 static int ext4_nonda_switch(struct super_block *sb)
2889 s64 free_clusters, dirty_clusters;
2890 struct ext4_sb_info *sbi = EXT4_SB(sb);
2893 * switch to non delalloc mode if we are running low
2894 * on free block. The free block accounting via percpu
2895 * counters can get slightly wrong with percpu_counter_batch getting
2896 * accumulated on each CPU without updating global counters
2897 * Delalloc need an accurate free block accounting. So switch
2898 * to non delalloc when we are near to error range.
2901 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2903 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2905 * Start pushing delalloc when 1/2 of free blocks are dirty.
2907 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2908 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2910 if (2 * free_clusters < 3 * dirty_clusters ||
2911 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2913 * free block count is less than 150% of dirty blocks
2914 * or free blocks is less than watermark
2921 /* We always reserve for an inode update; the superblock could be there too */
2922 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2924 if (likely(ext4_has_feature_large_file(inode->i_sb)))
2927 if (pos + len <= 0x7fffffffULL)
2930 /* We might need to update the superblock to set LARGE_FILE */
2934 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2935 loff_t pos, unsigned len, unsigned flags,
2936 struct page **pagep, void **fsdata)
2938 int ret, retries = 0;
2941 struct inode *inode = mapping->host;
2944 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2947 index = pos >> PAGE_SHIFT;
2949 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
2950 ext4_verity_in_progress(inode)) {
2951 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2952 return ext4_write_begin(file, mapping, pos,
2953 len, flags, pagep, fsdata);
2955 *fsdata = (void *)0;
2956 trace_ext4_da_write_begin(inode, pos, len, flags);
2958 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2959 ret = ext4_da_write_inline_data_begin(mapping, inode,
2969 * grab_cache_page_write_begin() can take a long time if the
2970 * system is thrashing due to memory pressure, or if the page
2971 * is being written back. So grab it first before we start
2972 * the transaction handle. This also allows us to allocate
2973 * the page (if needed) without using GFP_NOFS.
2976 page = grab_cache_page_write_begin(mapping, index, flags);
2982 * With delayed allocation, we don't log the i_disksize update
2983 * if there is delayed block allocation. But we still need
2984 * to journalling the i_disksize update if writes to the end
2985 * of file which has an already mapped buffer.
2988 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2989 ext4_da_write_credits(inode, pos, len));
2990 if (IS_ERR(handle)) {
2992 return PTR_ERR(handle);
2996 if (page->mapping != mapping) {
2997 /* The page got truncated from under us */
3000 ext4_journal_stop(handle);
3003 /* In case writeback began while the page was unlocked */
3004 wait_for_stable_page(page);
3006 #ifdef CONFIG_FS_ENCRYPTION
3007 ret = ext4_block_write_begin(page, pos, len,
3008 ext4_da_get_block_prep);
3010 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3014 ext4_journal_stop(handle);
3016 * block_write_begin may have instantiated a few blocks
3017 * outside i_size. Trim these off again. Don't need
3018 * i_size_read because we hold i_mutex.
3020 if (pos + len > inode->i_size)
3021 ext4_truncate_failed_write(inode);
3023 if (ret == -ENOSPC &&
3024 ext4_should_retry_alloc(inode->i_sb, &retries))
3036 * Check if we should update i_disksize
3037 * when write to the end of file but not require block allocation
3039 static int ext4_da_should_update_i_disksize(struct page *page,
3040 unsigned long offset)
3042 struct buffer_head *bh;
3043 struct inode *inode = page->mapping->host;
3047 bh = page_buffers(page);
3048 idx = offset >> inode->i_blkbits;
3050 for (i = 0; i < idx; i++)
3051 bh = bh->b_this_page;
3053 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3058 static int ext4_da_write_end(struct file *file,
3059 struct address_space *mapping,
3060 loff_t pos, unsigned len, unsigned copied,
3061 struct page *page, void *fsdata)
3063 struct inode *inode = mapping->host;
3065 handle_t *handle = ext4_journal_current_handle();
3067 unsigned long start, end;
3068 int write_mode = (int)(unsigned long)fsdata;
3070 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3071 return ext4_write_end(file, mapping, pos,
3072 len, copied, page, fsdata);
3074 trace_ext4_da_write_end(inode, pos, len, copied);
3075 start = pos & (PAGE_SIZE - 1);
3076 end = start + copied - 1;
3079 * generic_write_end() will run mark_inode_dirty() if i_size
3080 * changes. So let's piggyback the i_disksize mark_inode_dirty
3083 new_i_size = pos + copied;
3084 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3085 if (ext4_has_inline_data(inode) ||
3086 ext4_da_should_update_i_disksize(page, end)) {
3087 ext4_update_i_disksize(inode, new_i_size);
3088 /* We need to mark inode dirty even if
3089 * new_i_size is less that inode->i_size
3090 * bu greater than i_disksize.(hint delalloc)
3092 ret = ext4_mark_inode_dirty(handle, inode);
3096 if (write_mode != CONVERT_INLINE_DATA &&
3097 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3098 ext4_has_inline_data(inode))
3099 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
3102 ret2 = generic_write_end(file, mapping, pos, len, copied,
3108 ret2 = ext4_journal_stop(handle);
3109 if (unlikely(ret2 && !ret))
3112 return ret ? ret : copied;
3116 * Force all delayed allocation blocks to be allocated for a given inode.
3118 int ext4_alloc_da_blocks(struct inode *inode)
3120 trace_ext4_alloc_da_blocks(inode);
3122 if (!EXT4_I(inode)->i_reserved_data_blocks)
3126 * We do something simple for now. The filemap_flush() will
3127 * also start triggering a write of the data blocks, which is
3128 * not strictly speaking necessary (and for users of
3129 * laptop_mode, not even desirable). However, to do otherwise
3130 * would require replicating code paths in:
3132 * ext4_writepages() ->
3133 * write_cache_pages() ---> (via passed in callback function)
3134 * __mpage_da_writepage() -->
3135 * mpage_add_bh_to_extent()
3136 * mpage_da_map_blocks()
3138 * The problem is that write_cache_pages(), located in
3139 * mm/page-writeback.c, marks pages clean in preparation for
3140 * doing I/O, which is not desirable if we're not planning on
3143 * We could call write_cache_pages(), and then redirty all of
3144 * the pages by calling redirty_page_for_writepage() but that
3145 * would be ugly in the extreme. So instead we would need to
3146 * replicate parts of the code in the above functions,
3147 * simplifying them because we wouldn't actually intend to
3148 * write out the pages, but rather only collect contiguous
3149 * logical block extents, call the multi-block allocator, and
3150 * then update the buffer heads with the block allocations.
3152 * For now, though, we'll cheat by calling filemap_flush(),
3153 * which will map the blocks, and start the I/O, but not
3154 * actually wait for the I/O to complete.
3156 return filemap_flush(inode->i_mapping);
3160 * bmap() is special. It gets used by applications such as lilo and by
3161 * the swapper to find the on-disk block of a specific piece of data.
3163 * Naturally, this is dangerous if the block concerned is still in the
3164 * journal. If somebody makes a swapfile on an ext4 data-journaling
3165 * filesystem and enables swap, then they may get a nasty shock when the
3166 * data getting swapped to that swapfile suddenly gets overwritten by
3167 * the original zero's written out previously to the journal and
3168 * awaiting writeback in the kernel's buffer cache.
3170 * So, if we see any bmap calls here on a modified, data-journaled file,
3171 * take extra steps to flush any blocks which might be in the cache.
3173 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3175 struct inode *inode = mapping->host;
3180 * We can get here for an inline file via the FIBMAP ioctl
3182 if (ext4_has_inline_data(inode))
3185 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3186 test_opt(inode->i_sb, DELALLOC)) {
3188 * With delalloc we want to sync the file
3189 * so that we can make sure we allocate
3192 filemap_write_and_wait(mapping);
3195 if (EXT4_JOURNAL(inode) &&
3196 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3198 * This is a REALLY heavyweight approach, but the use of
3199 * bmap on dirty files is expected to be extremely rare:
3200 * only if we run lilo or swapon on a freshly made file
3201 * do we expect this to happen.
3203 * (bmap requires CAP_SYS_RAWIO so this does not
3204 * represent an unprivileged user DOS attack --- we'd be
3205 * in trouble if mortal users could trigger this path at
3208 * NB. EXT4_STATE_JDATA is not set on files other than
3209 * regular files. If somebody wants to bmap a directory
3210 * or symlink and gets confused because the buffer
3211 * hasn't yet been flushed to disk, they deserve
3212 * everything they get.
3215 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3216 journal = EXT4_JOURNAL(inode);
3217 jbd2_journal_lock_updates(journal);
3218 err = jbd2_journal_flush(journal);
3219 jbd2_journal_unlock_updates(journal);
3225 return iomap_bmap(mapping, block, &ext4_iomap_ops);
3228 static int ext4_readpage(struct file *file, struct page *page)
3231 struct inode *inode = page->mapping->host;
3233 trace_ext4_readpage(page);
3235 if (ext4_has_inline_data(inode))
3236 ret = ext4_readpage_inline(inode, page);
3239 return ext4_mpage_readpages(inode, NULL, page);
3244 static void ext4_readahead(struct readahead_control *rac)
3246 struct inode *inode = rac->mapping->host;
3248 /* If the file has inline data, no need to do readahead. */
3249 if (ext4_has_inline_data(inode))
3252 ext4_mpage_readpages(inode, rac, NULL);
3255 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3256 unsigned int length)
3258 trace_ext4_invalidatepage(page, offset, length);
3260 /* No journalling happens on data buffers when this function is used */
3261 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3263 block_invalidatepage(page, offset, length);
3266 static int __ext4_journalled_invalidatepage(struct page *page,
3267 unsigned int offset,
3268 unsigned int length)
3270 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3272 trace_ext4_journalled_invalidatepage(page, offset, length);
3275 * If it's a full truncate we just forget about the pending dirtying
3277 if (offset == 0 && length == PAGE_SIZE)
3278 ClearPageChecked(page);
3280 return jbd2_journal_invalidatepage(journal, page, offset, length);
3283 /* Wrapper for aops... */
3284 static void ext4_journalled_invalidatepage(struct page *page,
3285 unsigned int offset,
3286 unsigned int length)
3288 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3291 static int ext4_releasepage(struct page *page, gfp_t wait)
3293 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3295 trace_ext4_releasepage(page);
3297 /* Page has dirty journalled data -> cannot release */
3298 if (PageChecked(page))
3301 return jbd2_journal_try_to_free_buffers(journal, page);
3303 return try_to_free_buffers(page);
3306 static bool ext4_inode_datasync_dirty(struct inode *inode)
3308 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3311 if (jbd2_transaction_committed(journal,
3312 EXT4_I(inode)->i_datasync_tid))
3314 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3315 return !list_empty(&EXT4_I(inode)->i_fc_list);
3319 /* Any metadata buffers to write? */
3320 if (!list_empty(&inode->i_mapping->private_list))
3322 return inode->i_state & I_DIRTY_DATASYNC;
3325 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3326 struct ext4_map_blocks *map, loff_t offset,
3329 u8 blkbits = inode->i_blkbits;
3332 * Writes that span EOF might trigger an I/O size update on completion,
3333 * so consider them to be dirty for the purpose of O_DSYNC, even if
3334 * there is no other metadata changes being made or are pending.
3337 if (ext4_inode_datasync_dirty(inode) ||
3338 offset + length > i_size_read(inode))
3339 iomap->flags |= IOMAP_F_DIRTY;
3341 if (map->m_flags & EXT4_MAP_NEW)
3342 iomap->flags |= IOMAP_F_NEW;
3344 iomap->bdev = inode->i_sb->s_bdev;
3345 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3346 iomap->offset = (u64) map->m_lblk << blkbits;
3347 iomap->length = (u64) map->m_len << blkbits;
3349 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3350 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3351 iomap->flags |= IOMAP_F_MERGED;
3354 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3355 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3356 * set. In order for any allocated unwritten extents to be converted
3357 * into written extents correctly within the ->end_io() handler, we
3358 * need to ensure that the iomap->type is set appropriately. Hence, the
3359 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3362 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3363 iomap->type = IOMAP_UNWRITTEN;
3364 iomap->addr = (u64) map->m_pblk << blkbits;
3365 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3366 iomap->type = IOMAP_MAPPED;
3367 iomap->addr = (u64) map->m_pblk << blkbits;
3369 iomap->type = IOMAP_HOLE;
3370 iomap->addr = IOMAP_NULL_ADDR;
3374 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3378 u8 blkbits = inode->i_blkbits;
3379 int ret, dio_credits, m_flags = 0, retries = 0;
3382 * Trim the mapping request to the maximum value that we can map at
3383 * once for direct I/O.
3385 if (map->m_len > DIO_MAX_BLOCKS)
3386 map->m_len = DIO_MAX_BLOCKS;
3387 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3391 * Either we allocate blocks and then don't get an unwritten extent, so
3392 * in that case we have reserved enough credits. Or, the blocks are
3393 * already allocated and unwritten. In that case, the extent conversion
3394 * fits into the credits as well.
3396 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3398 return PTR_ERR(handle);
3401 * DAX and direct I/O are the only two operations that are currently
3402 * supported with IOMAP_WRITE.
3404 WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3406 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3408 * We use i_size instead of i_disksize here because delalloc writeback
3409 * can complete at any point during the I/O and subsequently push the
3410 * i_disksize out to i_size. This could be beyond where direct I/O is
3411 * happening and thus expose allocated blocks to direct I/O reads.
3413 else if ((map->m_lblk * (1 << blkbits)) >= i_size_read(inode))
3414 m_flags = EXT4_GET_BLOCKS_CREATE;
3415 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3416 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3418 ret = ext4_map_blocks(handle, inode, map, m_flags);
3421 * We cannot fill holes in indirect tree based inodes as that could
3422 * expose stale data in the case of a crash. Use the magic error code
3423 * to fallback to buffered I/O.
3425 if (!m_flags && !ret)
3428 ext4_journal_stop(handle);
3429 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3436 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3437 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3440 struct ext4_map_blocks map;
3441 u8 blkbits = inode->i_blkbits;
3443 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3446 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3450 * Calculate the first and last logical blocks respectively.
3452 map.m_lblk = offset >> blkbits;
3453 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3454 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3456 if (flags & IOMAP_WRITE) {
3458 * We check here if the blocks are already allocated, then we
3459 * don't need to start a journal txn and we can directly return
3460 * the mapping information. This could boost performance
3461 * especially in multi-threaded overwrite requests.
3463 if (offset + length <= i_size_read(inode)) {
3464 ret = ext4_map_blocks(NULL, inode, &map, 0);
3465 if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3468 ret = ext4_iomap_alloc(inode, &map, flags);
3470 ret = ext4_map_blocks(NULL, inode, &map, 0);
3476 ext4_set_iomap(inode, iomap, &map, offset, length);
3481 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3482 loff_t length, unsigned flags, struct iomap *iomap,
3483 struct iomap *srcmap)
3488 * Even for writes we don't need to allocate blocks, so just pretend
3489 * we are reading to save overhead of starting a transaction.
3491 flags &= ~IOMAP_WRITE;
3492 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3493 WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
3497 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3498 ssize_t written, unsigned flags, struct iomap *iomap)
3501 * Check to see whether an error occurred while writing out the data to
3502 * the allocated blocks. If so, return the magic error code so that we
3503 * fallback to buffered I/O and attempt to complete the remainder of
3504 * the I/O. Any blocks that may have been allocated in preparation for
3505 * the direct I/O will be reused during buffered I/O.
3507 if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3513 const struct iomap_ops ext4_iomap_ops = {
3514 .iomap_begin = ext4_iomap_begin,
3515 .iomap_end = ext4_iomap_end,
3518 const struct iomap_ops ext4_iomap_overwrite_ops = {
3519 .iomap_begin = ext4_iomap_overwrite_begin,
3520 .iomap_end = ext4_iomap_end,
3523 static bool ext4_iomap_is_delalloc(struct inode *inode,
3524 struct ext4_map_blocks *map)
3526 struct extent_status es;
3527 ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3529 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3530 map->m_lblk, end, &es);
3532 if (!es.es_len || es.es_lblk > end)
3535 if (es.es_lblk > map->m_lblk) {
3536 map->m_len = es.es_lblk - map->m_lblk;
3540 offset = map->m_lblk - es.es_lblk;
3541 map->m_len = es.es_len - offset;
3546 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3547 loff_t length, unsigned int flags,
3548 struct iomap *iomap, struct iomap *srcmap)
3551 bool delalloc = false;
3552 struct ext4_map_blocks map;
3553 u8 blkbits = inode->i_blkbits;
3555 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3558 if (ext4_has_inline_data(inode)) {
3559 ret = ext4_inline_data_iomap(inode, iomap);
3560 if (ret != -EAGAIN) {
3561 if (ret == 0 && offset >= iomap->length)
3568 * Calculate the first and last logical block respectively.
3570 map.m_lblk = offset >> blkbits;
3571 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3572 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3575 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3576 * So handle it here itself instead of querying ext4_map_blocks().
3577 * Since ext4_map_blocks() will warn about it and will return
3580 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3581 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3583 if (offset >= sbi->s_bitmap_maxbytes) {
3589 ret = ext4_map_blocks(NULL, inode, &map, 0);
3593 delalloc = ext4_iomap_is_delalloc(inode, &map);
3596 ext4_set_iomap(inode, iomap, &map, offset, length);
3597 if (delalloc && iomap->type == IOMAP_HOLE)
3598 iomap->type = IOMAP_DELALLOC;
3603 const struct iomap_ops ext4_iomap_report_ops = {
3604 .iomap_begin = ext4_iomap_begin_report,
3608 * Pages can be marked dirty completely asynchronously from ext4's journalling
3609 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3610 * much here because ->set_page_dirty is called under VFS locks. The page is
3611 * not necessarily locked.
3613 * We cannot just dirty the page and leave attached buffers clean, because the
3614 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3615 * or jbddirty because all the journalling code will explode.
3617 * So what we do is to mark the page "pending dirty" and next time writepage
3618 * is called, propagate that into the buffers appropriately.
3620 static int ext4_journalled_set_page_dirty(struct page *page)
3622 SetPageChecked(page);
3623 return __set_page_dirty_nobuffers(page);
3626 static int ext4_set_page_dirty(struct page *page)
3628 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3629 WARN_ON_ONCE(!page_has_buffers(page));
3630 return __set_page_dirty_buffers(page);
3633 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3634 struct file *file, sector_t *span)
3636 return iomap_swapfile_activate(sis, file, span,
3637 &ext4_iomap_report_ops);
3640 static const struct address_space_operations ext4_aops = {
3641 .readpage = ext4_readpage,
3642 .readahead = ext4_readahead,
3643 .writepage = ext4_writepage,
3644 .writepages = ext4_writepages,
3645 .write_begin = ext4_write_begin,
3646 .write_end = ext4_write_end,
3647 .set_page_dirty = ext4_set_page_dirty,
3649 .invalidatepage = ext4_invalidatepage,
3650 .releasepage = ext4_releasepage,
3651 .direct_IO = noop_direct_IO,
3652 .migratepage = buffer_migrate_page,
3653 .is_partially_uptodate = block_is_partially_uptodate,
3654 .error_remove_page = generic_error_remove_page,
3655 .swap_activate = ext4_iomap_swap_activate,
3658 static const struct address_space_operations ext4_journalled_aops = {
3659 .readpage = ext4_readpage,
3660 .readahead = ext4_readahead,
3661 .writepage = ext4_writepage,
3662 .writepages = ext4_writepages,
3663 .write_begin = ext4_write_begin,
3664 .write_end = ext4_journalled_write_end,
3665 .set_page_dirty = ext4_journalled_set_page_dirty,
3667 .invalidatepage = ext4_journalled_invalidatepage,
3668 .releasepage = ext4_releasepage,
3669 .direct_IO = noop_direct_IO,
3670 .is_partially_uptodate = block_is_partially_uptodate,
3671 .error_remove_page = generic_error_remove_page,
3672 .swap_activate = ext4_iomap_swap_activate,
3675 static const struct address_space_operations ext4_da_aops = {
3676 .readpage = ext4_readpage,
3677 .readahead = ext4_readahead,
3678 .writepage = ext4_writepage,
3679 .writepages = ext4_writepages,
3680 .write_begin = ext4_da_write_begin,
3681 .write_end = ext4_da_write_end,
3682 .set_page_dirty = ext4_set_page_dirty,
3684 .invalidatepage = ext4_invalidatepage,
3685 .releasepage = ext4_releasepage,
3686 .direct_IO = noop_direct_IO,
3687 .migratepage = buffer_migrate_page,
3688 .is_partially_uptodate = block_is_partially_uptodate,
3689 .error_remove_page = generic_error_remove_page,
3690 .swap_activate = ext4_iomap_swap_activate,
3693 static const struct address_space_operations ext4_dax_aops = {
3694 .writepages = ext4_dax_writepages,
3695 .direct_IO = noop_direct_IO,
3696 .set_page_dirty = noop_set_page_dirty,
3698 .invalidatepage = noop_invalidatepage,
3699 .swap_activate = ext4_iomap_swap_activate,
3702 void ext4_set_aops(struct inode *inode)
3704 switch (ext4_inode_journal_mode(inode)) {
3705 case EXT4_INODE_ORDERED_DATA_MODE:
3706 case EXT4_INODE_WRITEBACK_DATA_MODE:
3708 case EXT4_INODE_JOURNAL_DATA_MODE:
3709 inode->i_mapping->a_ops = &ext4_journalled_aops;
3715 inode->i_mapping->a_ops = &ext4_dax_aops;
3716 else if (test_opt(inode->i_sb, DELALLOC))
3717 inode->i_mapping->a_ops = &ext4_da_aops;
3719 inode->i_mapping->a_ops = &ext4_aops;
3722 static int __ext4_block_zero_page_range(handle_t *handle,
3723 struct address_space *mapping, loff_t from, loff_t length)
3725 ext4_fsblk_t index = from >> PAGE_SHIFT;
3726 unsigned offset = from & (PAGE_SIZE-1);
3727 unsigned blocksize, pos;
3729 struct inode *inode = mapping->host;
3730 struct buffer_head *bh;
3734 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3735 mapping_gfp_constraint(mapping, ~__GFP_FS));
3739 blocksize = inode->i_sb->s_blocksize;
3741 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3743 if (!page_has_buffers(page))
3744 create_empty_buffers(page, blocksize, 0);
3746 /* Find the buffer that contains "offset" */
3747 bh = page_buffers(page);
3749 while (offset >= pos) {
3750 bh = bh->b_this_page;
3754 if (buffer_freed(bh)) {
3755 BUFFER_TRACE(bh, "freed: skip");
3758 if (!buffer_mapped(bh)) {
3759 BUFFER_TRACE(bh, "unmapped");
3760 ext4_get_block(inode, iblock, bh, 0);
3761 /* unmapped? It's a hole - nothing to do */
3762 if (!buffer_mapped(bh)) {
3763 BUFFER_TRACE(bh, "still unmapped");
3768 /* Ok, it's mapped. Make sure it's up-to-date */
3769 if (PageUptodate(page))
3770 set_buffer_uptodate(bh);
3772 if (!buffer_uptodate(bh)) {
3773 err = ext4_read_bh_lock(bh, 0, true);
3776 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3777 /* We expect the key to be set. */
3778 BUG_ON(!fscrypt_has_encryption_key(inode));
3779 err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3782 clear_buffer_uptodate(bh);
3787 if (ext4_should_journal_data(inode)) {
3788 BUFFER_TRACE(bh, "get write access");
3789 err = ext4_journal_get_write_access(handle, bh);
3793 zero_user(page, offset, length);
3794 BUFFER_TRACE(bh, "zeroed end of block");
3796 if (ext4_should_journal_data(inode)) {
3797 err = ext4_handle_dirty_metadata(handle, inode, bh);
3800 mark_buffer_dirty(bh);
3801 if (ext4_should_order_data(inode))
3802 err = ext4_jbd2_inode_add_write(handle, inode, from,
3813 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3814 * starting from file offset 'from'. The range to be zero'd must
3815 * be contained with in one block. If the specified range exceeds
3816 * the end of the block it will be shortened to end of the block
3817 * that cooresponds to 'from'
3819 static int ext4_block_zero_page_range(handle_t *handle,
3820 struct address_space *mapping, loff_t from, loff_t length)
3822 struct inode *inode = mapping->host;
3823 unsigned offset = from & (PAGE_SIZE-1);
3824 unsigned blocksize = inode->i_sb->s_blocksize;
3825 unsigned max = blocksize - (offset & (blocksize - 1));
3828 * correct length if it does not fall between
3829 * 'from' and the end of the block
3831 if (length > max || length < 0)
3834 if (IS_DAX(inode)) {
3835 return iomap_zero_range(inode, from, length, NULL,
3838 return __ext4_block_zero_page_range(handle, mapping, from, length);
3842 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3843 * up to the end of the block which corresponds to `from'.
3844 * This required during truncate. We need to physically zero the tail end
3845 * of that block so it doesn't yield old data if the file is later grown.
3847 static int ext4_block_truncate_page(handle_t *handle,
3848 struct address_space *mapping, loff_t from)
3850 unsigned offset = from & (PAGE_SIZE-1);
3853 struct inode *inode = mapping->host;
3855 /* If we are processing an encrypted inode during orphan list handling */
3856 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3859 blocksize = inode->i_sb->s_blocksize;
3860 length = blocksize - (offset & (blocksize - 1));
3862 return ext4_block_zero_page_range(handle, mapping, from, length);
3865 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3866 loff_t lstart, loff_t length)
3868 struct super_block *sb = inode->i_sb;
3869 struct address_space *mapping = inode->i_mapping;
3870 unsigned partial_start, partial_end;
3871 ext4_fsblk_t start, end;
3872 loff_t byte_end = (lstart + length - 1);
3875 partial_start = lstart & (sb->s_blocksize - 1);
3876 partial_end = byte_end & (sb->s_blocksize - 1);
3878 start = lstart >> sb->s_blocksize_bits;
3879 end = byte_end >> sb->s_blocksize_bits;
3881 /* Handle partial zero within the single block */
3883 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3884 err = ext4_block_zero_page_range(handle, mapping,
3888 /* Handle partial zero out on the start of the range */
3889 if (partial_start) {
3890 err = ext4_block_zero_page_range(handle, mapping,
3891 lstart, sb->s_blocksize);
3895 /* Handle partial zero out on the end of the range */
3896 if (partial_end != sb->s_blocksize - 1)
3897 err = ext4_block_zero_page_range(handle, mapping,
3898 byte_end - partial_end,
3903 int ext4_can_truncate(struct inode *inode)
3905 if (S_ISREG(inode->i_mode))
3907 if (S_ISDIR(inode->i_mode))
3909 if (S_ISLNK(inode->i_mode))
3910 return !ext4_inode_is_fast_symlink(inode);
3915 * We have to make sure i_disksize gets properly updated before we truncate
3916 * page cache due to hole punching or zero range. Otherwise i_disksize update
3917 * can get lost as it may have been postponed to submission of writeback but
3918 * that will never happen after we truncate page cache.
3920 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3926 loff_t size = i_size_read(inode);
3928 WARN_ON(!inode_is_locked(inode));
3929 if (offset > size || offset + len < size)
3932 if (EXT4_I(inode)->i_disksize >= size)
3935 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3937 return PTR_ERR(handle);
3938 ext4_update_i_disksize(inode, size);
3939 ret = ext4_mark_inode_dirty(handle, inode);
3940 ext4_journal_stop(handle);
3945 static void ext4_wait_dax_page(struct ext4_inode_info *ei)
3947 up_write(&ei->i_mmap_sem);
3949 down_write(&ei->i_mmap_sem);
3952 int ext4_break_layouts(struct inode *inode)
3954 struct ext4_inode_info *ei = EXT4_I(inode);
3958 if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
3962 page = dax_layout_busy_page(inode->i_mapping);
3966 error = ___wait_var_event(&page->_refcount,
3967 atomic_read(&page->_refcount) == 1,
3968 TASK_INTERRUPTIBLE, 0, 0,
3969 ext4_wait_dax_page(ei));
3970 } while (error == 0);
3976 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3977 * associated with the given offset and length
3979 * @inode: File inode
3980 * @offset: The offset where the hole will begin
3981 * @len: The length of the hole
3983 * Returns: 0 on success or negative on failure
3986 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3988 struct super_block *sb = inode->i_sb;
3989 ext4_lblk_t first_block, stop_block;
3990 struct address_space *mapping = inode->i_mapping;
3991 loff_t first_block_offset, last_block_offset;
3993 unsigned int credits;
3994 int ret = 0, ret2 = 0;
3996 trace_ext4_punch_hole(inode, offset, length, 0);
3998 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
3999 if (ext4_has_inline_data(inode)) {
4000 down_write(&EXT4_I(inode)->i_mmap_sem);
4001 ret = ext4_convert_inline_data(inode);
4002 up_write(&EXT4_I(inode)->i_mmap_sem);
4008 * Write out all dirty pages to avoid race conditions
4009 * Then release them.
4011 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4012 ret = filemap_write_and_wait_range(mapping, offset,
4013 offset + length - 1);
4020 /* No need to punch hole beyond i_size */
4021 if (offset >= inode->i_size)
4025 * If the hole extends beyond i_size, set the hole
4026 * to end after the page that contains i_size
4028 if (offset + length > inode->i_size) {
4029 length = inode->i_size +
4030 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4034 if (offset & (sb->s_blocksize - 1) ||
4035 (offset + length) & (sb->s_blocksize - 1)) {
4037 * Attach jinode to inode for jbd2 if we do any zeroing of
4040 ret = ext4_inode_attach_jinode(inode);
4046 /* Wait all existing dio workers, newcomers will block on i_mutex */
4047 inode_dio_wait(inode);
4050 * Prevent page faults from reinstantiating pages we have released from
4053 down_write(&EXT4_I(inode)->i_mmap_sem);
4055 ret = ext4_break_layouts(inode);
4059 first_block_offset = round_up(offset, sb->s_blocksize);
4060 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4062 /* Now release the pages and zero block aligned part of pages*/
4063 if (last_block_offset > first_block_offset) {
4064 ret = ext4_update_disksize_before_punch(inode, offset, length);
4067 truncate_pagecache_range(inode, first_block_offset,
4071 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4072 credits = ext4_writepage_trans_blocks(inode);
4074 credits = ext4_blocks_for_truncate(inode);
4075 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4076 if (IS_ERR(handle)) {
4077 ret = PTR_ERR(handle);
4078 ext4_std_error(sb, ret);
4082 ret = ext4_zero_partial_blocks(handle, inode, offset,
4087 first_block = (offset + sb->s_blocksize - 1) >>
4088 EXT4_BLOCK_SIZE_BITS(sb);
4089 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4091 /* If there are blocks to remove, do it */
4092 if (stop_block > first_block) {
4094 down_write(&EXT4_I(inode)->i_data_sem);
4095 ext4_discard_preallocations(inode, 0);
4097 ret = ext4_es_remove_extent(inode, first_block,
4098 stop_block - first_block);
4100 up_write(&EXT4_I(inode)->i_data_sem);
4104 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4105 ret = ext4_ext_remove_space(inode, first_block,
4108 ret = ext4_ind_remove_space(handle, inode, first_block,
4111 up_write(&EXT4_I(inode)->i_data_sem);
4113 ext4_fc_track_range(handle, inode, first_block, stop_block);
4115 ext4_handle_sync(handle);
4117 inode->i_mtime = inode->i_ctime = current_time(inode);
4118 ret2 = ext4_mark_inode_dirty(handle, inode);
4122 ext4_update_inode_fsync_trans(handle, inode, 1);
4124 ext4_journal_stop(handle);
4126 up_write(&EXT4_I(inode)->i_mmap_sem);
4128 inode_unlock(inode);
4132 int ext4_inode_attach_jinode(struct inode *inode)
4134 struct ext4_inode_info *ei = EXT4_I(inode);
4135 struct jbd2_inode *jinode;
4137 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4140 jinode = jbd2_alloc_inode(GFP_KERNEL);
4141 spin_lock(&inode->i_lock);
4144 spin_unlock(&inode->i_lock);
4147 ei->jinode = jinode;
4148 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4151 spin_unlock(&inode->i_lock);
4152 if (unlikely(jinode != NULL))
4153 jbd2_free_inode(jinode);
4160 * We block out ext4_get_block() block instantiations across the entire
4161 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4162 * simultaneously on behalf of the same inode.
4164 * As we work through the truncate and commit bits of it to the journal there
4165 * is one core, guiding principle: the file's tree must always be consistent on
4166 * disk. We must be able to restart the truncate after a crash.
4168 * The file's tree may be transiently inconsistent in memory (although it
4169 * probably isn't), but whenever we close off and commit a journal transaction,
4170 * the contents of (the filesystem + the journal) must be consistent and
4171 * restartable. It's pretty simple, really: bottom up, right to left (although
4172 * left-to-right works OK too).
4174 * Note that at recovery time, journal replay occurs *before* the restart of
4175 * truncate against the orphan inode list.
4177 * The committed inode has the new, desired i_size (which is the same as
4178 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4179 * that this inode's truncate did not complete and it will again call
4180 * ext4_truncate() to have another go. So there will be instantiated blocks
4181 * to the right of the truncation point in a crashed ext4 filesystem. But
4182 * that's fine - as long as they are linked from the inode, the post-crash
4183 * ext4_truncate() run will find them and release them.
4185 int ext4_truncate(struct inode *inode)
4187 struct ext4_inode_info *ei = EXT4_I(inode);
4188 unsigned int credits;
4191 struct address_space *mapping = inode->i_mapping;
4194 * There is a possibility that we're either freeing the inode
4195 * or it's a completely new inode. In those cases we might not
4196 * have i_mutex locked because it's not necessary.
4198 if (!(inode->i_state & (I_NEW|I_FREEING)))
4199 WARN_ON(!inode_is_locked(inode));
4200 trace_ext4_truncate_enter(inode);
4202 if (!ext4_can_truncate(inode))
4205 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4206 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4208 if (ext4_has_inline_data(inode)) {
4211 err = ext4_inline_data_truncate(inode, &has_inline);
4212 if (err || has_inline)
4216 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4217 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4218 if (ext4_inode_attach_jinode(inode) < 0)
4222 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4223 credits = ext4_writepage_trans_blocks(inode);
4225 credits = ext4_blocks_for_truncate(inode);
4227 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4228 if (IS_ERR(handle)) {
4229 err = PTR_ERR(handle);
4233 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4234 ext4_block_truncate_page(handle, mapping, inode->i_size);
4237 * We add the inode to the orphan list, so that if this
4238 * truncate spans multiple transactions, and we crash, we will
4239 * resume the truncate when the filesystem recovers. It also
4240 * marks the inode dirty, to catch the new size.
4242 * Implication: the file must always be in a sane, consistent
4243 * truncatable state while each transaction commits.
4245 err = ext4_orphan_add(handle, inode);
4249 down_write(&EXT4_I(inode)->i_data_sem);
4251 ext4_discard_preallocations(inode, 0);
4253 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4254 err = ext4_ext_truncate(handle, inode);
4256 ext4_ind_truncate(handle, inode);
4258 up_write(&ei->i_data_sem);
4263 ext4_handle_sync(handle);
4267 * If this was a simple ftruncate() and the file will remain alive,
4268 * then we need to clear up the orphan record which we created above.
4269 * However, if this was a real unlink then we were called by
4270 * ext4_evict_inode(), and we allow that function to clean up the
4271 * orphan info for us.
4274 ext4_orphan_del(handle, inode);
4276 inode->i_mtime = inode->i_ctime = current_time(inode);
4277 err2 = ext4_mark_inode_dirty(handle, inode);
4278 if (unlikely(err2 && !err))
4280 ext4_journal_stop(handle);
4283 trace_ext4_truncate_exit(inode);
4288 * ext4_get_inode_loc returns with an extra refcount against the inode's
4289 * underlying buffer_head on success. If 'in_mem' is true, we have all
4290 * data in memory that is needed to recreate the on-disk version of this
4293 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4294 struct ext4_iloc *iloc, int in_mem,
4295 ext4_fsblk_t *ret_block)
4297 struct ext4_group_desc *gdp;
4298 struct buffer_head *bh;
4300 struct blk_plug plug;
4301 int inodes_per_block, inode_offset;
4304 if (ino < EXT4_ROOT_INO ||
4305 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4306 return -EFSCORRUPTED;
4308 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4309 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4314 * Figure out the offset within the block group inode table
4316 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4317 inode_offset = ((ino - 1) %
4318 EXT4_INODES_PER_GROUP(sb));
4319 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4320 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4322 bh = sb_getblk(sb, block);
4325 if (ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO))
4327 if (!buffer_uptodate(bh)) {
4330 if (ext4_buffer_uptodate(bh)) {
4331 /* someone brought it uptodate while we waited */
4337 * If we have all information of the inode in memory and this
4338 * is the only valid inode in the block, we need not read the
4342 struct buffer_head *bitmap_bh;
4345 start = inode_offset & ~(inodes_per_block - 1);
4347 /* Is the inode bitmap in cache? */
4348 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4349 if (unlikely(!bitmap_bh))
4353 * If the inode bitmap isn't in cache then the
4354 * optimisation may end up performing two reads instead
4355 * of one, so skip it.
4357 if (!buffer_uptodate(bitmap_bh)) {
4361 for (i = start; i < start + inodes_per_block; i++) {
4362 if (i == inode_offset)
4364 if (ext4_test_bit(i, bitmap_bh->b_data))
4368 if (i == start + inodes_per_block) {
4369 /* all other inodes are free, so skip I/O */
4370 memset(bh->b_data, 0, bh->b_size);
4371 set_buffer_uptodate(bh);
4379 * If we need to do any I/O, try to pre-readahead extra
4380 * blocks from the inode table.
4382 blk_start_plug(&plug);
4383 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4384 ext4_fsblk_t b, end, table;
4386 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4388 table = ext4_inode_table(sb, gdp);
4389 /* s_inode_readahead_blks is always a power of 2 */
4390 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4394 num = EXT4_INODES_PER_GROUP(sb);
4395 if (ext4_has_group_desc_csum(sb))
4396 num -= ext4_itable_unused_count(sb, gdp);
4397 table += num / inodes_per_block;
4401 ext4_sb_breadahead_unmovable(sb, b++);
4405 * There are other valid inodes in the buffer, this inode
4406 * has in-inode xattrs, or we don't have this inode in memory.
4407 * Read the block from disk.
4409 trace_ext4_load_inode(sb, ino);
4410 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4411 blk_finish_plug(&plug);
4413 if (!buffer_uptodate(bh)) {
4426 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4427 struct ext4_iloc *iloc)
4429 ext4_fsblk_t err_blk;
4432 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc, 0,
4436 ext4_error_inode_block(inode, err_blk, EIO,
4437 "unable to read itable block");
4442 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4444 ext4_fsblk_t err_blk;
4447 /* We have all inode data except xattrs in memory here. */
4448 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc,
4449 !ext4_test_inode_state(inode, EXT4_STATE_XATTR), &err_blk);
4452 ext4_error_inode_block(inode, err_blk, EIO,
4453 "unable to read itable block");
4459 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4460 struct ext4_iloc *iloc)
4462 return __ext4_get_inode_loc(sb, ino, iloc, 0, NULL);
4465 static bool ext4_should_enable_dax(struct inode *inode)
4467 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4469 if (test_opt2(inode->i_sb, DAX_NEVER))
4471 if (!S_ISREG(inode->i_mode))
4473 if (ext4_should_journal_data(inode))
4475 if (ext4_has_inline_data(inode))
4477 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4479 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4481 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4483 if (test_opt(inode->i_sb, DAX_ALWAYS))
4486 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4489 void ext4_set_inode_flags(struct inode *inode, bool init)
4491 unsigned int flags = EXT4_I(inode)->i_flags;
4492 unsigned int new_fl = 0;
4494 WARN_ON_ONCE(IS_DAX(inode) && init);
4496 if (flags & EXT4_SYNC_FL)
4498 if (flags & EXT4_APPEND_FL)
4500 if (flags & EXT4_IMMUTABLE_FL)
4501 new_fl |= S_IMMUTABLE;
4502 if (flags & EXT4_NOATIME_FL)
4503 new_fl |= S_NOATIME;
4504 if (flags & EXT4_DIRSYNC_FL)
4505 new_fl |= S_DIRSYNC;
4507 /* Because of the way inode_set_flags() works we must preserve S_DAX
4508 * here if already set. */
4509 new_fl |= (inode->i_flags & S_DAX);
4510 if (init && ext4_should_enable_dax(inode))
4513 if (flags & EXT4_ENCRYPT_FL)
4514 new_fl |= S_ENCRYPTED;
4515 if (flags & EXT4_CASEFOLD_FL)
4516 new_fl |= S_CASEFOLD;
4517 if (flags & EXT4_VERITY_FL)
4519 inode_set_flags(inode, new_fl,
4520 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4521 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4524 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4525 struct ext4_inode_info *ei)
4528 struct inode *inode = &(ei->vfs_inode);
4529 struct super_block *sb = inode->i_sb;
4531 if (ext4_has_feature_huge_file(sb)) {
4532 /* we are using combined 48 bit field */
4533 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4534 le32_to_cpu(raw_inode->i_blocks_lo);
4535 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4536 /* i_blocks represent file system block size */
4537 return i_blocks << (inode->i_blkbits - 9);
4542 return le32_to_cpu(raw_inode->i_blocks_lo);
4546 static inline int ext4_iget_extra_inode(struct inode *inode,
4547 struct ext4_inode *raw_inode,
4548 struct ext4_inode_info *ei)
4550 __le32 *magic = (void *)raw_inode +
4551 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4553 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4554 EXT4_INODE_SIZE(inode->i_sb) &&
4555 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4556 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4557 return ext4_find_inline_data_nolock(inode);
4559 EXT4_I(inode)->i_inline_off = 0;
4563 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4565 if (!ext4_has_feature_project(inode->i_sb))
4567 *projid = EXT4_I(inode)->i_projid;
4572 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4573 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4576 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4578 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4579 inode_set_iversion_raw(inode, val);
4581 inode_set_iversion_queried(inode, val);
4583 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4585 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4586 return inode_peek_iversion_raw(inode);
4588 return inode_peek_iversion(inode);
4591 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4592 ext4_iget_flags flags, const char *function,
4595 struct ext4_iloc iloc;
4596 struct ext4_inode *raw_inode;
4597 struct ext4_inode_info *ei;
4598 struct inode *inode;
4599 journal_t *journal = EXT4_SB(sb)->s_journal;
4607 if ((!(flags & EXT4_IGET_SPECIAL) &&
4608 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4609 (ino < EXT4_ROOT_INO) ||
4610 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4611 if (flags & EXT4_IGET_HANDLE)
4612 return ERR_PTR(-ESTALE);
4613 __ext4_error(sb, function, line, EFSCORRUPTED, 0,
4614 "inode #%lu: comm %s: iget: illegal inode #",
4615 ino, current->comm);
4616 return ERR_PTR(-EFSCORRUPTED);
4619 inode = iget_locked(sb, ino);
4621 return ERR_PTR(-ENOMEM);
4622 if (!(inode->i_state & I_NEW))
4628 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4631 raw_inode = ext4_raw_inode(&iloc);
4633 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4634 ext4_error_inode(inode, function, line, 0,
4635 "iget: root inode unallocated");
4636 ret = -EFSCORRUPTED;
4640 if ((flags & EXT4_IGET_HANDLE) &&
4641 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4646 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4647 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4648 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4649 EXT4_INODE_SIZE(inode->i_sb) ||
4650 (ei->i_extra_isize & 3)) {
4651 ext4_error_inode(inode, function, line, 0,
4652 "iget: bad extra_isize %u "
4655 EXT4_INODE_SIZE(inode->i_sb));
4656 ret = -EFSCORRUPTED;
4660 ei->i_extra_isize = 0;
4662 /* Precompute checksum seed for inode metadata */
4663 if (ext4_has_metadata_csum(sb)) {
4664 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4666 __le32 inum = cpu_to_le32(inode->i_ino);
4667 __le32 gen = raw_inode->i_generation;
4668 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4670 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4674 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4675 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4676 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4677 ext4_error_inode_err(inode, function, line, 0,
4678 EFSBADCRC, "iget: checksum invalid");
4683 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4684 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4685 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4686 if (ext4_has_feature_project(sb) &&
4687 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4688 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4689 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4691 i_projid = EXT4_DEF_PROJID;
4693 if (!(test_opt(inode->i_sb, NO_UID32))) {
4694 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4695 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4697 i_uid_write(inode, i_uid);
4698 i_gid_write(inode, i_gid);
4699 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4700 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4702 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4703 ei->i_inline_off = 0;
4704 ei->i_dir_start_lookup = 0;
4705 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4706 /* We now have enough fields to check if the inode was active or not.
4707 * This is needed because nfsd might try to access dead inodes
4708 * the test is that same one that e2fsck uses
4709 * NeilBrown 1999oct15
4711 if (inode->i_nlink == 0) {
4712 if ((inode->i_mode == 0 ||
4713 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4714 ino != EXT4_BOOT_LOADER_INO) {
4715 /* this inode is deleted */
4719 /* The only unlinked inodes we let through here have
4720 * valid i_mode and are being read by the orphan
4721 * recovery code: that's fine, we're about to complete
4722 * the process of deleting those.
4723 * OR it is the EXT4_BOOT_LOADER_INO which is
4724 * not initialized on a new filesystem. */
4726 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4727 ext4_set_inode_flags(inode, true);
4728 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4729 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4730 if (ext4_has_feature_64bit(sb))
4732 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4733 inode->i_size = ext4_isize(sb, raw_inode);
4734 if ((size = i_size_read(inode)) < 0) {
4735 ext4_error_inode(inode, function, line, 0,
4736 "iget: bad i_size value: %lld", size);
4737 ret = -EFSCORRUPTED;
4741 * If dir_index is not enabled but there's dir with INDEX flag set,
4742 * we'd normally treat htree data as empty space. But with metadata
4743 * checksumming that corrupts checksums so forbid that.
4745 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4746 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4747 ext4_error_inode(inode, function, line, 0,
4748 "iget: Dir with htree data on filesystem without dir_index feature.");
4749 ret = -EFSCORRUPTED;
4752 ei->i_disksize = inode->i_size;
4754 ei->i_reserved_quota = 0;
4756 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4757 ei->i_block_group = iloc.block_group;
4758 ei->i_last_alloc_group = ~0;
4760 * NOTE! The in-memory inode i_data array is in little-endian order
4761 * even on big-endian machines: we do NOT byteswap the block numbers!
4763 for (block = 0; block < EXT4_N_BLOCKS; block++)
4764 ei->i_data[block] = raw_inode->i_block[block];
4765 INIT_LIST_HEAD(&ei->i_orphan);
4766 ext4_fc_init_inode(&ei->vfs_inode);
4769 * Set transaction id's of transactions that have to be committed
4770 * to finish f[data]sync. We set them to currently running transaction
4771 * as we cannot be sure that the inode or some of its metadata isn't
4772 * part of the transaction - the inode could have been reclaimed and
4773 * now it is reread from disk.
4776 transaction_t *transaction;
4779 read_lock(&journal->j_state_lock);
4780 if (journal->j_running_transaction)
4781 transaction = journal->j_running_transaction;
4783 transaction = journal->j_committing_transaction;
4785 tid = transaction->t_tid;
4787 tid = journal->j_commit_sequence;
4788 read_unlock(&journal->j_state_lock);
4789 ei->i_sync_tid = tid;
4790 ei->i_datasync_tid = tid;
4793 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4794 if (ei->i_extra_isize == 0) {
4795 /* The extra space is currently unused. Use it. */
4796 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4797 ei->i_extra_isize = sizeof(struct ext4_inode) -
4798 EXT4_GOOD_OLD_INODE_SIZE;
4800 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4806 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4807 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4808 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4809 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4811 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4812 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4814 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4815 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4817 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4819 ext4_inode_set_iversion_queried(inode, ivers);
4823 if (ei->i_file_acl &&
4824 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4825 ext4_error_inode(inode, function, line, 0,
4826 "iget: bad extended attribute block %llu",
4828 ret = -EFSCORRUPTED;
4830 } else if (!ext4_has_inline_data(inode)) {
4831 /* validate the block references in the inode */
4832 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4833 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4834 (S_ISLNK(inode->i_mode) &&
4835 !ext4_inode_is_fast_symlink(inode)))) {
4836 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4837 ret = ext4_ext_check_inode(inode);
4839 ret = ext4_ind_check_inode(inode);
4845 if (S_ISREG(inode->i_mode)) {
4846 inode->i_op = &ext4_file_inode_operations;
4847 inode->i_fop = &ext4_file_operations;
4848 ext4_set_aops(inode);
4849 } else if (S_ISDIR(inode->i_mode)) {
4850 inode->i_op = &ext4_dir_inode_operations;
4851 inode->i_fop = &ext4_dir_operations;
4852 } else if (S_ISLNK(inode->i_mode)) {
4853 /* VFS does not allow setting these so must be corruption */
4854 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
4855 ext4_error_inode(inode, function, line, 0,
4856 "iget: immutable or append flags "
4857 "not allowed on symlinks");
4858 ret = -EFSCORRUPTED;
4861 if (IS_ENCRYPTED(inode)) {
4862 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4863 ext4_set_aops(inode);
4864 } else if (ext4_inode_is_fast_symlink(inode)) {
4865 inode->i_link = (char *)ei->i_data;
4866 inode->i_op = &ext4_fast_symlink_inode_operations;
4867 nd_terminate_link(ei->i_data, inode->i_size,
4868 sizeof(ei->i_data) - 1);
4870 inode->i_op = &ext4_symlink_inode_operations;
4871 ext4_set_aops(inode);
4873 inode_nohighmem(inode);
4874 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4875 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4876 inode->i_op = &ext4_special_inode_operations;
4877 if (raw_inode->i_block[0])
4878 init_special_inode(inode, inode->i_mode,
4879 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4881 init_special_inode(inode, inode->i_mode,
4882 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4883 } else if (ino == EXT4_BOOT_LOADER_INO) {
4884 make_bad_inode(inode);
4886 ret = -EFSCORRUPTED;
4887 ext4_error_inode(inode, function, line, 0,
4888 "iget: bogus i_mode (%o)", inode->i_mode);
4891 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
4892 ext4_error_inode(inode, function, line, 0,
4893 "casefold flag without casefold feature");
4896 unlock_new_inode(inode);
4902 return ERR_PTR(ret);
4905 static int ext4_inode_blocks_set(handle_t *handle,
4906 struct ext4_inode *raw_inode,
4907 struct ext4_inode_info *ei)
4909 struct inode *inode = &(ei->vfs_inode);
4910 u64 i_blocks = READ_ONCE(inode->i_blocks);
4911 struct super_block *sb = inode->i_sb;
4913 if (i_blocks <= ~0U) {
4915 * i_blocks can be represented in a 32 bit variable
4916 * as multiple of 512 bytes
4918 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4919 raw_inode->i_blocks_high = 0;
4920 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4923 if (!ext4_has_feature_huge_file(sb))
4926 if (i_blocks <= 0xffffffffffffULL) {
4928 * i_blocks can be represented in a 48 bit variable
4929 * as multiple of 512 bytes
4931 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4932 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4933 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4935 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4936 /* i_block is stored in file system block size */
4937 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4938 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4939 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4944 static void __ext4_update_other_inode_time(struct super_block *sb,
4945 unsigned long orig_ino,
4947 struct ext4_inode *raw_inode)
4949 struct inode *inode;
4951 inode = find_inode_by_ino_rcu(sb, ino);
4955 if ((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4957 ((inode->i_state & I_DIRTY_TIME) == 0))
4960 spin_lock(&inode->i_lock);
4961 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4962 I_DIRTY_INODE)) == 0) &&
4963 (inode->i_state & I_DIRTY_TIME)) {
4964 struct ext4_inode_info *ei = EXT4_I(inode);
4966 inode->i_state &= ~I_DIRTY_TIME;
4967 spin_unlock(&inode->i_lock);
4969 spin_lock(&ei->i_raw_lock);
4970 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4971 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4972 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4973 ext4_inode_csum_set(inode, raw_inode, ei);
4974 spin_unlock(&ei->i_raw_lock);
4975 trace_ext4_other_inode_update_time(inode, orig_ino);
4978 spin_unlock(&inode->i_lock);
4982 * Opportunistically update the other time fields for other inodes in
4983 * the same inode table block.
4985 static void ext4_update_other_inodes_time(struct super_block *sb,
4986 unsigned long orig_ino, char *buf)
4989 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4990 int inode_size = EXT4_INODE_SIZE(sb);
4993 * Calculate the first inode in the inode table block. Inode
4994 * numbers are one-based. That is, the first inode in a block
4995 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
4997 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4999 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5000 if (ino == orig_ino)
5002 __ext4_update_other_inode_time(sb, orig_ino, ino,
5003 (struct ext4_inode *)buf);
5009 * Post the struct inode info into an on-disk inode location in the
5010 * buffer-cache. This gobbles the caller's reference to the
5011 * buffer_head in the inode location struct.
5013 * The caller must have write access to iloc->bh.
5015 static int ext4_do_update_inode(handle_t *handle,
5016 struct inode *inode,
5017 struct ext4_iloc *iloc)
5019 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5020 struct ext4_inode_info *ei = EXT4_I(inode);
5021 struct buffer_head *bh = iloc->bh;
5022 struct super_block *sb = inode->i_sb;
5023 int err = 0, rc, block;
5024 int need_datasync = 0, set_large_file = 0;
5029 spin_lock(&ei->i_raw_lock);
5031 /* For fields not tracked in the in-memory inode,
5032 * initialise them to zero for new inodes. */
5033 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5034 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5036 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5038 spin_unlock(&ei->i_raw_lock);
5042 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5043 i_uid = i_uid_read(inode);
5044 i_gid = i_gid_read(inode);
5045 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5046 if (!(test_opt(inode->i_sb, NO_UID32))) {
5047 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5048 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5050 * Fix up interoperability with old kernels. Otherwise, old inodes get
5051 * re-used with the upper 16 bits of the uid/gid intact
5053 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5054 raw_inode->i_uid_high = 0;
5055 raw_inode->i_gid_high = 0;
5057 raw_inode->i_uid_high =
5058 cpu_to_le16(high_16_bits(i_uid));
5059 raw_inode->i_gid_high =
5060 cpu_to_le16(high_16_bits(i_gid));
5063 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5064 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5065 raw_inode->i_uid_high = 0;
5066 raw_inode->i_gid_high = 0;
5068 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5070 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5071 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5072 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5073 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5075 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5076 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5077 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5078 raw_inode->i_file_acl_high =
5079 cpu_to_le16(ei->i_file_acl >> 32);
5080 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5081 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5082 ext4_isize_set(raw_inode, ei->i_disksize);
5085 if (ei->i_disksize > 0x7fffffffULL) {
5086 if (!ext4_has_feature_large_file(sb) ||
5087 EXT4_SB(sb)->s_es->s_rev_level ==
5088 cpu_to_le32(EXT4_GOOD_OLD_REV))
5091 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5092 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5093 if (old_valid_dev(inode->i_rdev)) {
5094 raw_inode->i_block[0] =
5095 cpu_to_le32(old_encode_dev(inode->i_rdev));
5096 raw_inode->i_block[1] = 0;
5098 raw_inode->i_block[0] = 0;
5099 raw_inode->i_block[1] =
5100 cpu_to_le32(new_encode_dev(inode->i_rdev));
5101 raw_inode->i_block[2] = 0;
5103 } else if (!ext4_has_inline_data(inode)) {
5104 for (block = 0; block < EXT4_N_BLOCKS; block++)
5105 raw_inode->i_block[block] = ei->i_data[block];
5108 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5109 u64 ivers = ext4_inode_peek_iversion(inode);
5111 raw_inode->i_disk_version = cpu_to_le32(ivers);
5112 if (ei->i_extra_isize) {
5113 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5114 raw_inode->i_version_hi =
5115 cpu_to_le32(ivers >> 32);
5116 raw_inode->i_extra_isize =
5117 cpu_to_le16(ei->i_extra_isize);
5121 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5122 i_projid != EXT4_DEF_PROJID);
5124 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5125 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5126 raw_inode->i_projid = cpu_to_le32(i_projid);
5128 ext4_inode_csum_set(inode, raw_inode, ei);
5129 spin_unlock(&ei->i_raw_lock);
5130 if (inode->i_sb->s_flags & SB_LAZYTIME)
5131 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5134 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5135 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5138 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5139 if (set_large_file) {
5140 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5141 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5144 ext4_set_feature_large_file(sb);
5145 ext4_handle_sync(handle);
5146 err = ext4_handle_dirty_super(handle, sb);
5148 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5151 ext4_std_error(inode->i_sb, err);
5156 * ext4_write_inode()
5158 * We are called from a few places:
5160 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5161 * Here, there will be no transaction running. We wait for any running
5162 * transaction to commit.
5164 * - Within flush work (sys_sync(), kupdate and such).
5165 * We wait on commit, if told to.
5167 * - Within iput_final() -> write_inode_now()
5168 * We wait on commit, if told to.
5170 * In all cases it is actually safe for us to return without doing anything,
5171 * because the inode has been copied into a raw inode buffer in
5172 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5175 * Note that we are absolutely dependent upon all inode dirtiers doing the
5176 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5177 * which we are interested.
5179 * It would be a bug for them to not do this. The code:
5181 * mark_inode_dirty(inode)
5183 * inode->i_size = expr;
5185 * is in error because write_inode() could occur while `stuff()' is running,
5186 * and the new i_size will be lost. Plus the inode will no longer be on the
5187 * superblock's dirty inode list.
5189 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5193 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5194 sb_rdonly(inode->i_sb))
5197 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5200 if (EXT4_SB(inode->i_sb)->s_journal) {
5201 if (ext4_journal_current_handle()) {
5202 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5208 * No need to force transaction in WB_SYNC_NONE mode. Also
5209 * ext4_sync_fs() will force the commit after everything is
5212 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5215 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5216 EXT4_I(inode)->i_sync_tid);
5218 struct ext4_iloc iloc;
5220 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5224 * sync(2) will flush the whole buffer cache. No need to do
5225 * it here separately for each inode.
5227 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5228 sync_dirty_buffer(iloc.bh);
5229 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5230 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5231 "IO error syncing inode");
5240 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5241 * buffers that are attached to a page stradding i_size and are undergoing
5242 * commit. In that case we have to wait for commit to finish and try again.
5244 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5248 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5249 tid_t commit_tid = 0;
5252 offset = inode->i_size & (PAGE_SIZE - 1);
5254 * If the page is fully truncated, we don't need to wait for any commit
5255 * (and we even should not as __ext4_journalled_invalidatepage() may
5256 * strip all buffers from the page but keep the page dirty which can then
5257 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5258 * buffers). Also we don't need to wait for any commit if all buffers in
5259 * the page remain valid. This is most beneficial for the common case of
5260 * blocksize == PAGESIZE.
5262 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5265 page = find_lock_page(inode->i_mapping,
5266 inode->i_size >> PAGE_SHIFT);
5269 ret = __ext4_journalled_invalidatepage(page, offset,
5270 PAGE_SIZE - offset);
5276 read_lock(&journal->j_state_lock);
5277 if (journal->j_committing_transaction)
5278 commit_tid = journal->j_committing_transaction->t_tid;
5279 read_unlock(&journal->j_state_lock);
5281 jbd2_log_wait_commit(journal, commit_tid);
5288 * Called from notify_change.
5290 * We want to trap VFS attempts to truncate the file as soon as
5291 * possible. In particular, we want to make sure that when the VFS
5292 * shrinks i_size, we put the inode on the orphan list and modify
5293 * i_disksize immediately, so that during the subsequent flushing of
5294 * dirty pages and freeing of disk blocks, we can guarantee that any
5295 * commit will leave the blocks being flushed in an unused state on
5296 * disk. (On recovery, the inode will get truncated and the blocks will
5297 * be freed, so we have a strong guarantee that no future commit will
5298 * leave these blocks visible to the user.)
5300 * Another thing we have to assure is that if we are in ordered mode
5301 * and inode is still attached to the committing transaction, we must
5302 * we start writeout of all the dirty pages which are being truncated.
5303 * This way we are sure that all the data written in the previous
5304 * transaction are already on disk (truncate waits for pages under
5307 * Called with inode->i_mutex down.
5309 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5311 struct inode *inode = d_inode(dentry);
5314 const unsigned int ia_valid = attr->ia_valid;
5316 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5319 if (unlikely(IS_IMMUTABLE(inode)))
5322 if (unlikely(IS_APPEND(inode) &&
5323 (ia_valid & (ATTR_MODE | ATTR_UID |
5324 ATTR_GID | ATTR_TIMES_SET))))
5327 error = setattr_prepare(dentry, attr);
5331 error = fscrypt_prepare_setattr(dentry, attr);
5335 error = fsverity_prepare_setattr(dentry, attr);
5339 if (is_quota_modification(inode, attr)) {
5340 error = dquot_initialize(inode);
5344 ext4_fc_start_update(inode);
5345 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5346 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5349 /* (user+group)*(old+new) structure, inode write (sb,
5350 * inode block, ? - but truncate inode update has it) */
5351 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5352 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5353 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5354 if (IS_ERR(handle)) {
5355 error = PTR_ERR(handle);
5359 /* dquot_transfer() calls back ext4_get_inode_usage() which
5360 * counts xattr inode references.
5362 down_read(&EXT4_I(inode)->xattr_sem);
5363 error = dquot_transfer(inode, attr);
5364 up_read(&EXT4_I(inode)->xattr_sem);
5367 ext4_journal_stop(handle);
5368 ext4_fc_stop_update(inode);
5371 /* Update corresponding info in inode so that everything is in
5372 * one transaction */
5373 if (attr->ia_valid & ATTR_UID)
5374 inode->i_uid = attr->ia_uid;
5375 if (attr->ia_valid & ATTR_GID)
5376 inode->i_gid = attr->ia_gid;
5377 error = ext4_mark_inode_dirty(handle, inode);
5378 ext4_journal_stop(handle);
5379 if (unlikely(error))
5383 if (attr->ia_valid & ATTR_SIZE) {
5385 loff_t oldsize = inode->i_size;
5386 int shrink = (attr->ia_size < inode->i_size);
5388 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5389 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5391 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5392 ext4_fc_stop_update(inode);
5396 if (!S_ISREG(inode->i_mode)) {
5397 ext4_fc_stop_update(inode);
5401 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5402 inode_inc_iversion(inode);
5405 if (ext4_should_order_data(inode)) {
5406 error = ext4_begin_ordered_truncate(inode,
5412 * Blocks are going to be removed from the inode. Wait
5413 * for dio in flight.
5415 inode_dio_wait(inode);
5418 down_write(&EXT4_I(inode)->i_mmap_sem);
5420 rc = ext4_break_layouts(inode);
5422 up_write(&EXT4_I(inode)->i_mmap_sem);
5426 if (attr->ia_size != inode->i_size) {
5427 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5428 if (IS_ERR(handle)) {
5429 error = PTR_ERR(handle);
5432 if (ext4_handle_valid(handle) && shrink) {
5433 error = ext4_orphan_add(handle, inode);
5437 * Update c/mtime on truncate up, ext4_truncate() will
5438 * update c/mtime in shrink case below
5441 inode->i_mtime = current_time(inode);
5442 inode->i_ctime = inode->i_mtime;
5446 ext4_fc_track_range(handle, inode,
5447 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5448 inode->i_sb->s_blocksize_bits,
5449 (oldsize > 0 ? oldsize - 1 : 0) >>
5450 inode->i_sb->s_blocksize_bits);
5452 ext4_fc_track_range(
5454 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5455 inode->i_sb->s_blocksize_bits,
5456 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5457 inode->i_sb->s_blocksize_bits);
5459 down_write(&EXT4_I(inode)->i_data_sem);
5460 EXT4_I(inode)->i_disksize = attr->ia_size;
5461 rc = ext4_mark_inode_dirty(handle, inode);
5465 * We have to update i_size under i_data_sem together
5466 * with i_disksize to avoid races with writeback code
5467 * running ext4_wb_update_i_disksize().
5470 i_size_write(inode, attr->ia_size);
5471 up_write(&EXT4_I(inode)->i_data_sem);
5472 ext4_journal_stop(handle);
5476 pagecache_isize_extended(inode, oldsize,
5478 } else if (ext4_should_journal_data(inode)) {
5479 ext4_wait_for_tail_page_commit(inode);
5484 * Truncate pagecache after we've waited for commit
5485 * in data=journal mode to make pages freeable.
5487 truncate_pagecache(inode, inode->i_size);
5489 * Call ext4_truncate() even if i_size didn't change to
5490 * truncate possible preallocated blocks.
5492 if (attr->ia_size <= oldsize) {
5493 rc = ext4_truncate(inode);
5498 up_write(&EXT4_I(inode)->i_mmap_sem);
5502 setattr_copy(inode, attr);
5503 mark_inode_dirty(inode);
5507 * If the call to ext4_truncate failed to get a transaction handle at
5508 * all, we need to clean up the in-core orphan list manually.
5510 if (orphan && inode->i_nlink)
5511 ext4_orphan_del(NULL, inode);
5513 if (!error && (ia_valid & ATTR_MODE))
5514 rc = posix_acl_chmod(inode, inode->i_mode);
5518 ext4_std_error(inode->i_sb, error);
5521 ext4_fc_stop_update(inode);
5525 int ext4_getattr(const struct path *path, struct kstat *stat,
5526 u32 request_mask, unsigned int query_flags)
5528 struct inode *inode = d_inode(path->dentry);
5529 struct ext4_inode *raw_inode;
5530 struct ext4_inode_info *ei = EXT4_I(inode);
5533 if ((request_mask & STATX_BTIME) &&
5534 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5535 stat->result_mask |= STATX_BTIME;
5536 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5537 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5540 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5541 if (flags & EXT4_APPEND_FL)
5542 stat->attributes |= STATX_ATTR_APPEND;
5543 if (flags & EXT4_COMPR_FL)
5544 stat->attributes |= STATX_ATTR_COMPRESSED;
5545 if (flags & EXT4_ENCRYPT_FL)
5546 stat->attributes |= STATX_ATTR_ENCRYPTED;
5547 if (flags & EXT4_IMMUTABLE_FL)
5548 stat->attributes |= STATX_ATTR_IMMUTABLE;
5549 if (flags & EXT4_NODUMP_FL)
5550 stat->attributes |= STATX_ATTR_NODUMP;
5551 if (flags & EXT4_VERITY_FL)
5552 stat->attributes |= STATX_ATTR_VERITY;
5554 stat->attributes_mask |= (STATX_ATTR_APPEND |
5555 STATX_ATTR_COMPRESSED |
5556 STATX_ATTR_ENCRYPTED |
5557 STATX_ATTR_IMMUTABLE |
5561 generic_fillattr(inode, stat);
5565 int ext4_file_getattr(const struct path *path, struct kstat *stat,
5566 u32 request_mask, unsigned int query_flags)
5568 struct inode *inode = d_inode(path->dentry);
5569 u64 delalloc_blocks;
5571 ext4_getattr(path, stat, request_mask, query_flags);
5574 * If there is inline data in the inode, the inode will normally not
5575 * have data blocks allocated (it may have an external xattr block).
5576 * Report at least one sector for such files, so tools like tar, rsync,
5577 * others don't incorrectly think the file is completely sparse.
5579 if (unlikely(ext4_has_inline_data(inode)))
5580 stat->blocks += (stat->size + 511) >> 9;
5583 * We can't update i_blocks if the block allocation is delayed
5584 * otherwise in the case of system crash before the real block
5585 * allocation is done, we will have i_blocks inconsistent with
5586 * on-disk file blocks.
5587 * We always keep i_blocks updated together with real
5588 * allocation. But to not confuse with user, stat
5589 * will return the blocks that include the delayed allocation
5590 * blocks for this file.
5592 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5593 EXT4_I(inode)->i_reserved_data_blocks);
5594 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5598 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5601 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5602 return ext4_ind_trans_blocks(inode, lblocks);
5603 return ext4_ext_index_trans_blocks(inode, pextents);
5607 * Account for index blocks, block groups bitmaps and block group
5608 * descriptor blocks if modify datablocks and index blocks
5609 * worse case, the indexs blocks spread over different block groups
5611 * If datablocks are discontiguous, they are possible to spread over
5612 * different block groups too. If they are contiguous, with flexbg,
5613 * they could still across block group boundary.
5615 * Also account for superblock, inode, quota and xattr blocks
5617 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5620 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5626 * How many index blocks need to touch to map @lblocks logical blocks
5627 * to @pextents physical extents?
5629 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5634 * Now let's see how many group bitmaps and group descriptors need
5637 groups = idxblocks + pextents;
5639 if (groups > ngroups)
5641 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5642 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5644 /* bitmaps and block group descriptor blocks */
5645 ret += groups + gdpblocks;
5647 /* Blocks for super block, inode, quota and xattr blocks */
5648 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5654 * Calculate the total number of credits to reserve to fit
5655 * the modification of a single pages into a single transaction,
5656 * which may include multiple chunks of block allocations.
5658 * This could be called via ext4_write_begin()
5660 * We need to consider the worse case, when
5661 * one new block per extent.
5663 int ext4_writepage_trans_blocks(struct inode *inode)
5665 int bpp = ext4_journal_blocks_per_page(inode);
5668 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5670 /* Account for data blocks for journalled mode */
5671 if (ext4_should_journal_data(inode))
5677 * Calculate the journal credits for a chunk of data modification.
5679 * This is called from DIO, fallocate or whoever calling
5680 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5682 * journal buffers for data blocks are not included here, as DIO
5683 * and fallocate do no need to journal data buffers.
5685 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5687 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5691 * The caller must have previously called ext4_reserve_inode_write().
5692 * Give this, we know that the caller already has write access to iloc->bh.
5694 int ext4_mark_iloc_dirty(handle_t *handle,
5695 struct inode *inode, struct ext4_iloc *iloc)
5699 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5703 ext4_fc_track_inode(handle, inode);
5705 if (IS_I_VERSION(inode))
5706 inode_inc_iversion(inode);
5708 /* the do_update_inode consumes one bh->b_count */
5711 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5712 err = ext4_do_update_inode(handle, inode, iloc);
5718 * On success, We end up with an outstanding reference count against
5719 * iloc->bh. This _must_ be cleaned up later.
5723 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5724 struct ext4_iloc *iloc)
5728 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5731 err = ext4_get_inode_loc(inode, iloc);
5733 BUFFER_TRACE(iloc->bh, "get_write_access");
5734 err = ext4_journal_get_write_access(handle, iloc->bh);
5740 ext4_std_error(inode->i_sb, err);
5744 static int __ext4_expand_extra_isize(struct inode *inode,
5745 unsigned int new_extra_isize,
5746 struct ext4_iloc *iloc,
5747 handle_t *handle, int *no_expand)
5749 struct ext4_inode *raw_inode;
5750 struct ext4_xattr_ibody_header *header;
5751 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5752 struct ext4_inode_info *ei = EXT4_I(inode);
5755 /* this was checked at iget time, but double check for good measure */
5756 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5757 (ei->i_extra_isize & 3)) {
5758 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5760 EXT4_INODE_SIZE(inode->i_sb));
5761 return -EFSCORRUPTED;
5763 if ((new_extra_isize < ei->i_extra_isize) ||
5764 (new_extra_isize < 4) ||
5765 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5766 return -EINVAL; /* Should never happen */
5768 raw_inode = ext4_raw_inode(iloc);
5770 header = IHDR(inode, raw_inode);
5772 /* No extended attributes present */
5773 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5774 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5775 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5776 EXT4_I(inode)->i_extra_isize, 0,
5777 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5778 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5782 /* try to expand with EAs present */
5783 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5787 * Inode size expansion failed; don't try again
5796 * Expand an inode by new_extra_isize bytes.
5797 * Returns 0 on success or negative error number on failure.
5799 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5800 unsigned int new_extra_isize,
5801 struct ext4_iloc iloc,
5807 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5811 * In nojournal mode, we can immediately attempt to expand
5812 * the inode. When journaled, we first need to obtain extra
5813 * buffer credits since we may write into the EA block
5814 * with this same handle. If journal_extend fails, then it will
5815 * only result in a minor loss of functionality for that inode.
5816 * If this is felt to be critical, then e2fsck should be run to
5817 * force a large enough s_min_extra_isize.
5819 if (ext4_journal_extend(handle,
5820 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5823 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5826 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5827 handle, &no_expand);
5828 ext4_write_unlock_xattr(inode, &no_expand);
5833 int ext4_expand_extra_isize(struct inode *inode,
5834 unsigned int new_extra_isize,
5835 struct ext4_iloc *iloc)
5841 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5846 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5847 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5848 if (IS_ERR(handle)) {
5849 error = PTR_ERR(handle);
5854 ext4_write_lock_xattr(inode, &no_expand);
5856 BUFFER_TRACE(iloc->bh, "get_write_access");
5857 error = ext4_journal_get_write_access(handle, iloc->bh);
5863 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5864 handle, &no_expand);
5866 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5871 ext4_write_unlock_xattr(inode, &no_expand);
5872 ext4_journal_stop(handle);
5877 * What we do here is to mark the in-core inode as clean with respect to inode
5878 * dirtiness (it may still be data-dirty).
5879 * This means that the in-core inode may be reaped by prune_icache
5880 * without having to perform any I/O. This is a very good thing,
5881 * because *any* task may call prune_icache - even ones which
5882 * have a transaction open against a different journal.
5884 * Is this cheating? Not really. Sure, we haven't written the
5885 * inode out, but prune_icache isn't a user-visible syncing function.
5886 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5887 * we start and wait on commits.
5889 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5890 const char *func, unsigned int line)
5892 struct ext4_iloc iloc;
5893 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5897 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5898 err = ext4_reserve_inode_write(handle, inode, &iloc);
5902 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5903 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5906 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5909 ext4_error_inode_err(inode, func, line, 0, err,
5910 "mark_inode_dirty error");
5915 * ext4_dirty_inode() is called from __mark_inode_dirty()
5917 * We're really interested in the case where a file is being extended.
5918 * i_size has been changed by generic_commit_write() and we thus need
5919 * to include the updated inode in the current transaction.
5921 * Also, dquot_alloc_block() will always dirty the inode when blocks
5922 * are allocated to the file.
5924 * If the inode is marked synchronous, we don't honour that here - doing
5925 * so would cause a commit on atime updates, which we don't bother doing.
5926 * We handle synchronous inodes at the highest possible level.
5928 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5929 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5930 * to copy into the on-disk inode structure are the timestamp files.
5932 void ext4_dirty_inode(struct inode *inode, int flags)
5936 if (flags == I_DIRTY_TIME)
5938 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5942 ext4_mark_inode_dirty(handle, inode);
5944 ext4_journal_stop(handle);
5949 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5954 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5957 * We have to be very careful here: changing a data block's
5958 * journaling status dynamically is dangerous. If we write a
5959 * data block to the journal, change the status and then delete
5960 * that block, we risk forgetting to revoke the old log record
5961 * from the journal and so a subsequent replay can corrupt data.
5962 * So, first we make sure that the journal is empty and that
5963 * nobody is changing anything.
5966 journal = EXT4_JOURNAL(inode);
5969 if (is_journal_aborted(journal))
5972 /* Wait for all existing dio workers */
5973 inode_dio_wait(inode);
5976 * Before flushing the journal and switching inode's aops, we have
5977 * to flush all dirty data the inode has. There can be outstanding
5978 * delayed allocations, there can be unwritten extents created by
5979 * fallocate or buffered writes in dioread_nolock mode covered by
5980 * dirty data which can be converted only after flushing the dirty
5981 * data (and journalled aops don't know how to handle these cases).
5984 down_write(&EXT4_I(inode)->i_mmap_sem);
5985 err = filemap_write_and_wait(inode->i_mapping);
5987 up_write(&EXT4_I(inode)->i_mmap_sem);
5992 percpu_down_write(&sbi->s_writepages_rwsem);
5993 jbd2_journal_lock_updates(journal);
5996 * OK, there are no updates running now, and all cached data is
5997 * synced to disk. We are now in a completely consistent state
5998 * which doesn't have anything in the journal, and we know that
5999 * no filesystem updates are running, so it is safe to modify
6000 * the inode's in-core data-journaling state flag now.
6004 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6006 err = jbd2_journal_flush(journal);
6008 jbd2_journal_unlock_updates(journal);
6009 percpu_up_write(&sbi->s_writepages_rwsem);
6012 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6014 ext4_set_aops(inode);
6016 jbd2_journal_unlock_updates(journal);
6017 percpu_up_write(&sbi->s_writepages_rwsem);
6020 up_write(&EXT4_I(inode)->i_mmap_sem);
6022 /* Finally we can mark the inode as dirty. */
6024 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6026 return PTR_ERR(handle);
6028 ext4_fc_mark_ineligible(inode->i_sb,
6029 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE);
6030 err = ext4_mark_inode_dirty(handle, inode);
6031 ext4_handle_sync(handle);
6032 ext4_journal_stop(handle);
6033 ext4_std_error(inode->i_sb, err);
6038 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6040 return !buffer_mapped(bh);
6043 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6045 struct vm_area_struct *vma = vmf->vma;
6046 struct page *page = vmf->page;
6051 struct file *file = vma->vm_file;
6052 struct inode *inode = file_inode(file);
6053 struct address_space *mapping = inode->i_mapping;
6055 get_block_t *get_block;
6058 if (unlikely(IS_IMMUTABLE(inode)))
6059 return VM_FAULT_SIGBUS;
6061 sb_start_pagefault(inode->i_sb);
6062 file_update_time(vma->vm_file);
6064 down_read(&EXT4_I(inode)->i_mmap_sem);
6066 err = ext4_convert_inline_data(inode);
6071 * On data journalling we skip straight to the transaction handle:
6072 * there's no delalloc; page truncated will be checked later; the
6073 * early return w/ all buffers mapped (calculates size/len) can't
6074 * be used; and there's no dioread_nolock, so only ext4_get_block.
6076 if (ext4_should_journal_data(inode))
6079 /* Delalloc case is easy... */
6080 if (test_opt(inode->i_sb, DELALLOC) &&
6081 !ext4_nonda_switch(inode->i_sb)) {
6083 err = block_page_mkwrite(vma, vmf,
6084 ext4_da_get_block_prep);
6085 } while (err == -ENOSPC &&
6086 ext4_should_retry_alloc(inode->i_sb, &retries));
6091 size = i_size_read(inode);
6092 /* Page got truncated from under us? */
6093 if (page->mapping != mapping || page_offset(page) > size) {
6095 ret = VM_FAULT_NOPAGE;
6099 if (page->index == size >> PAGE_SHIFT)
6100 len = size & ~PAGE_MASK;
6104 * Return if we have all the buffers mapped. This avoids the need to do
6105 * journal_start/journal_stop which can block and take a long time
6107 * This cannot be done for data journalling, as we have to add the
6108 * inode to the transaction's list to writeprotect pages on commit.
6110 if (page_has_buffers(page)) {
6111 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6113 ext4_bh_unmapped)) {
6114 /* Wait so that we don't change page under IO */
6115 wait_for_stable_page(page);
6116 ret = VM_FAULT_LOCKED;
6121 /* OK, we need to fill the hole... */
6122 if (ext4_should_dioread_nolock(inode))
6123 get_block = ext4_get_block_unwritten;
6125 get_block = ext4_get_block;
6127 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6128 ext4_writepage_trans_blocks(inode));
6129 if (IS_ERR(handle)) {
6130 ret = VM_FAULT_SIGBUS;
6134 * Data journalling can't use block_page_mkwrite() because it
6135 * will set_buffer_dirty() before do_journal_get_write_access()
6136 * thus might hit warning messages for dirty metadata buffers.
6138 if (!ext4_should_journal_data(inode)) {
6139 err = block_page_mkwrite(vma, vmf, get_block);
6142 size = i_size_read(inode);
6143 /* Page got truncated from under us? */
6144 if (page->mapping != mapping || page_offset(page) > size) {
6145 ret = VM_FAULT_NOPAGE;
6149 if (page->index == size >> PAGE_SHIFT)
6150 len = size & ~PAGE_MASK;
6154 err = __block_write_begin(page, 0, len, ext4_get_block);
6156 ret = VM_FAULT_SIGBUS;
6157 if (ext4_walk_page_buffers(handle, page_buffers(page),
6158 0, len, NULL, do_journal_get_write_access))
6160 if (ext4_walk_page_buffers(handle, page_buffers(page),
6161 0, len, NULL, write_end_fn))
6163 if (ext4_jbd2_inode_add_write(handle, inode,
6164 page_offset(page), len))
6166 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6171 ext4_journal_stop(handle);
6172 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6175 ret = block_page_mkwrite_return(err);
6177 up_read(&EXT4_I(inode)->i_mmap_sem);
6178 sb_end_pagefault(inode->i_sb);
6182 ext4_journal_stop(handle);
6186 vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
6188 struct inode *inode = file_inode(vmf->vma->vm_file);
6191 down_read(&EXT4_I(inode)->i_mmap_sem);
6192 ret = filemap_fault(vmf);
6193 up_read(&EXT4_I(inode)->i_mmap_sem);