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/mount.h>
24 #include <linux/time.h>
25 #include <linux/highuid.h>
26 #include <linux/pagemap.h>
27 #include <linux/dax.h>
28 #include <linux/quotaops.h>
29 #include <linux/string.h>
30 #include <linux/buffer_head.h>
31 #include <linux/writeback.h>
32 #include <linux/pagevec.h>
33 #include <linux/mpage.h>
34 #include <linux/namei.h>
35 #include <linux/uio.h>
36 #include <linux/bio.h>
37 #include <linux/workqueue.h>
38 #include <linux/kernel.h>
39 #include <linux/printk.h>
40 #include <linux/slab.h>
41 #include <linux/bitops.h>
42 #include <linux/iomap.h>
43 #include <linux/iversion.h>
45 #include "ext4_jbd2.h"
50 #include <trace/events/ext4.h>
52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 struct ext4_inode_info *ei)
55 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
58 int offset = offsetof(struct ext4_inode, i_checksum_lo);
59 unsigned int csum_size = sizeof(dummy_csum);
61 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
64 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65 EXT4_GOOD_OLD_INODE_SIZE - offset);
67 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68 offset = offsetof(struct ext4_inode, i_checksum_hi);
69 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70 EXT4_GOOD_OLD_INODE_SIZE,
71 offset - EXT4_GOOD_OLD_INODE_SIZE);
72 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
77 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
78 EXT4_INODE_SIZE(inode->i_sb) - offset);
84 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85 struct ext4_inode_info *ei)
87 __u32 provided, calculated;
89 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90 cpu_to_le32(EXT4_OS_LINUX) ||
91 !ext4_has_metadata_csum(inode->i_sb))
94 provided = le16_to_cpu(raw->i_checksum_lo);
95 calculated = ext4_inode_csum(inode, raw, ei);
96 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
100 calculated &= 0xFFFF;
102 return provided == calculated;
105 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106 struct ext4_inode_info *ei)
110 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111 cpu_to_le32(EXT4_OS_LINUX) ||
112 !ext4_has_metadata_csum(inode->i_sb))
115 csum = ext4_inode_csum(inode, raw, ei);
116 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
122 static inline int ext4_begin_ordered_truncate(struct inode *inode,
125 trace_ext4_begin_ordered_truncate(inode, new_size);
127 * If jinode is zero, then we never opened the file for
128 * writing, so there's no need to call
129 * jbd2_journal_begin_ordered_truncate() since there's no
130 * outstanding writes we need to flush.
132 if (!EXT4_I(inode)->jinode)
134 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
135 EXT4_I(inode)->jinode,
139 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
143 * Test whether an inode is a fast symlink.
144 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
146 int ext4_inode_is_fast_symlink(struct inode *inode)
148 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
149 int ea_blocks = EXT4_I(inode)->i_file_acl ?
150 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152 if (ext4_has_inline_data(inode))
155 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
157 return S_ISLNK(inode->i_mode) && inode->i_size &&
158 (inode->i_size < EXT4_N_BLOCKS * 4);
162 * Called at the last iput() if i_nlink is zero.
164 void ext4_evict_inode(struct inode *inode)
169 * Credits for final inode cleanup and freeing:
170 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
171 * (xattr block freeing), bitmap, group descriptor (inode freeing)
173 int extra_credits = 6;
174 struct ext4_xattr_inode_array *ea_inode_array = NULL;
175 bool freeze_protected = false;
177 trace_ext4_evict_inode(inode);
179 if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
180 ext4_evict_ea_inode(inode);
181 if (inode->i_nlink) {
182 truncate_inode_pages_final(&inode->i_data);
187 if (is_bad_inode(inode))
189 dquot_initialize(inode);
191 if (ext4_should_order_data(inode))
192 ext4_begin_ordered_truncate(inode, 0);
193 truncate_inode_pages_final(&inode->i_data);
196 * For inodes with journalled data, transaction commit could have
197 * dirtied the inode. And for inodes with dioread_nolock, unwritten
198 * extents converting worker could merge extents and also have dirtied
199 * the inode. Flush worker is ignoring it because of I_FREEING flag but
200 * we still need to remove the inode from the writeback lists.
202 if (!list_empty_careful(&inode->i_io_list))
203 inode_io_list_del(inode);
206 * Protect us against freezing - iput() caller didn't have to have any
207 * protection against it. When we are in a running transaction though,
208 * we are already protected against freezing and we cannot grab further
209 * protection due to lock ordering constraints.
211 if (!ext4_journal_current_handle()) {
212 sb_start_intwrite(inode->i_sb);
213 freeze_protected = true;
216 if (!IS_NOQUOTA(inode))
217 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
220 * Block bitmap, group descriptor, and inode are accounted in both
221 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
223 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
224 ext4_blocks_for_truncate(inode) + extra_credits - 3);
225 if (IS_ERR(handle)) {
226 ext4_std_error(inode->i_sb, PTR_ERR(handle));
228 * If we're going to skip the normal cleanup, we still need to
229 * make sure that the in-core orphan linked list is properly
232 ext4_orphan_del(NULL, inode);
233 if (freeze_protected)
234 sb_end_intwrite(inode->i_sb);
239 ext4_handle_sync(handle);
242 * Set inode->i_size to 0 before calling ext4_truncate(). We need
243 * special handling of symlinks here because i_size is used to
244 * determine whether ext4_inode_info->i_data contains symlink data or
245 * block mappings. Setting i_size to 0 will remove its fast symlink
246 * status. Erase i_data so that it becomes a valid empty block map.
248 if (ext4_inode_is_fast_symlink(inode))
249 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
251 err = ext4_mark_inode_dirty(handle, inode);
253 ext4_warning(inode->i_sb,
254 "couldn't mark inode dirty (err %d)", err);
257 if (inode->i_blocks) {
258 err = ext4_truncate(inode);
260 ext4_error_err(inode->i_sb, -err,
261 "couldn't truncate inode %lu (err %d)",
267 /* Remove xattr references. */
268 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
271 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
273 ext4_journal_stop(handle);
274 ext4_orphan_del(NULL, inode);
275 if (freeze_protected)
276 sb_end_intwrite(inode->i_sb);
277 ext4_xattr_inode_array_free(ea_inode_array);
282 * Kill off the orphan record which ext4_truncate created.
283 * AKPM: I think this can be inside the above `if'.
284 * Note that ext4_orphan_del() has to be able to cope with the
285 * deletion of a non-existent orphan - this is because we don't
286 * know if ext4_truncate() actually created an orphan record.
287 * (Well, we could do this if we need to, but heck - it works)
289 ext4_orphan_del(handle, inode);
290 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
293 * One subtle ordering requirement: if anything has gone wrong
294 * (transaction abort, IO errors, whatever), then we can still
295 * do these next steps (the fs will already have been marked as
296 * having errors), but we can't free the inode if the mark_dirty
299 if (ext4_mark_inode_dirty(handle, inode))
300 /* If that failed, just do the required in-core inode clear. */
301 ext4_clear_inode(inode);
303 ext4_free_inode(handle, inode);
304 ext4_journal_stop(handle);
305 if (freeze_protected)
306 sb_end_intwrite(inode->i_sb);
307 ext4_xattr_inode_array_free(ea_inode_array);
311 * Check out some where else accidentally dirty the evicting inode,
312 * which may probably cause inode use-after-free issues later.
314 WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
316 if (!list_empty(&EXT4_I(inode)->i_fc_list))
317 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
318 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
322 qsize_t *ext4_get_reserved_space(struct inode *inode)
324 return &EXT4_I(inode)->i_reserved_quota;
329 * Called with i_data_sem down, which is important since we can call
330 * ext4_discard_preallocations() from here.
332 void ext4_da_update_reserve_space(struct inode *inode,
333 int used, int quota_claim)
335 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
336 struct ext4_inode_info *ei = EXT4_I(inode);
338 spin_lock(&ei->i_block_reservation_lock);
339 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
340 if (unlikely(used > ei->i_reserved_data_blocks)) {
341 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
342 "with only %d reserved data blocks",
343 __func__, inode->i_ino, used,
344 ei->i_reserved_data_blocks);
346 used = ei->i_reserved_data_blocks;
349 /* Update per-inode reservations */
350 ei->i_reserved_data_blocks -= used;
351 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
353 spin_unlock(&ei->i_block_reservation_lock);
355 /* Update quota subsystem for data blocks */
357 dquot_claim_block(inode, EXT4_C2B(sbi, used));
360 * We did fallocate with an offset that is already delayed
361 * allocated. So on delayed allocated writeback we should
362 * not re-claim the quota for fallocated blocks.
364 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
368 * If we have done all the pending block allocations and if
369 * there aren't any writers on the inode, we can discard the
370 * inode's preallocations.
372 if ((ei->i_reserved_data_blocks == 0) &&
373 !inode_is_open_for_write(inode))
374 ext4_discard_preallocations(inode);
377 static int __check_block_validity(struct inode *inode, const char *func,
379 struct ext4_map_blocks *map)
381 if (ext4_has_feature_journal(inode->i_sb) &&
383 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
385 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
386 ext4_error_inode(inode, func, line, map->m_pblk,
387 "lblock %lu mapped to illegal pblock %llu "
388 "(length %d)", (unsigned long) map->m_lblk,
389 map->m_pblk, map->m_len);
390 return -EFSCORRUPTED;
395 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
400 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
401 return fscrypt_zeroout_range(inode, lblk, pblk, len);
403 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
410 #define check_block_validity(inode, map) \
411 __check_block_validity((inode), __func__, __LINE__, (map))
413 #ifdef ES_AGGRESSIVE_TEST
414 static void ext4_map_blocks_es_recheck(handle_t *handle,
416 struct ext4_map_blocks *es_map,
417 struct ext4_map_blocks *map,
424 * There is a race window that the result is not the same.
425 * e.g. xfstests #223 when dioread_nolock enables. The reason
426 * is that we lookup a block mapping in extent status tree with
427 * out taking i_data_sem. So at the time the unwritten extent
428 * could be converted.
430 down_read(&EXT4_I(inode)->i_data_sem);
431 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
432 retval = ext4_ext_map_blocks(handle, inode, map, 0);
434 retval = ext4_ind_map_blocks(handle, inode, map, 0);
436 up_read((&EXT4_I(inode)->i_data_sem));
439 * We don't check m_len because extent will be collpased in status
440 * tree. So the m_len might not equal.
442 if (es_map->m_lblk != map->m_lblk ||
443 es_map->m_flags != map->m_flags ||
444 es_map->m_pblk != map->m_pblk) {
445 printk("ES cache assertion failed for inode: %lu "
446 "es_cached ex [%d/%d/%llu/%x] != "
447 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
448 inode->i_ino, es_map->m_lblk, es_map->m_len,
449 es_map->m_pblk, es_map->m_flags, map->m_lblk,
450 map->m_len, map->m_pblk, map->m_flags,
454 #endif /* ES_AGGRESSIVE_TEST */
456 static int ext4_map_query_blocks(handle_t *handle, struct inode *inode,
457 struct ext4_map_blocks *map)
462 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
463 retval = ext4_ext_map_blocks(handle, inode, map, 0);
465 retval = ext4_ind_map_blocks(handle, inode, map, 0);
470 if (unlikely(retval != map->m_len)) {
471 ext4_warning(inode->i_sb,
472 "ES len assertion failed for inode "
473 "%lu: retval %d != map->m_len %d",
474 inode->i_ino, retval, map->m_len);
478 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
479 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
480 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
481 map->m_pblk, status);
486 * The ext4_map_blocks() function tries to look up the requested blocks,
487 * and returns if the blocks are already mapped.
489 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
490 * and store the allocated blocks in the result buffer head and mark it
493 * If file type is extents based, it will call ext4_ext_map_blocks(),
494 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
497 * On success, it returns the number of blocks being mapped or allocated.
498 * If flags doesn't contain EXT4_GET_BLOCKS_CREATE the blocks are
499 * pre-allocated and unwritten, the resulting @map is marked as unwritten.
500 * If the flags contain EXT4_GET_BLOCKS_CREATE, it will mark @map as mapped.
502 * It returns 0 if plain look up failed (blocks have not been allocated), in
503 * that case, @map is returned as unmapped but we still do fill map->m_len to
504 * indicate the length of a hole starting at map->m_lblk.
506 * It returns the error in case of allocation failure.
508 int ext4_map_blocks(handle_t *handle, struct inode *inode,
509 struct ext4_map_blocks *map, int flags)
511 struct extent_status es;
514 #ifdef ES_AGGRESSIVE_TEST
515 struct ext4_map_blocks orig_map;
517 memcpy(&orig_map, map, sizeof(*map));
521 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
522 flags, map->m_len, (unsigned long) map->m_lblk);
525 * ext4_map_blocks returns an int, and m_len is an unsigned int
527 if (unlikely(map->m_len > INT_MAX))
528 map->m_len = INT_MAX;
530 /* We can handle the block number less than EXT_MAX_BLOCKS */
531 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
532 return -EFSCORRUPTED;
534 /* Lookup extent status tree firstly */
535 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
536 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
537 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
538 map->m_pblk = ext4_es_pblock(&es) +
539 map->m_lblk - es.es_lblk;
540 map->m_flags |= ext4_es_is_written(&es) ?
541 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
542 retval = es.es_len - (map->m_lblk - es.es_lblk);
543 if (retval > map->m_len)
546 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
548 map->m_flags |= ext4_es_is_delayed(&es) ?
549 EXT4_MAP_DELAYED : 0;
550 retval = es.es_len - (map->m_lblk - es.es_lblk);
551 if (retval > map->m_len)
559 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
561 #ifdef ES_AGGRESSIVE_TEST
562 ext4_map_blocks_es_recheck(handle, inode, map,
568 * In the query cache no-wait mode, nothing we can do more if we
569 * cannot find extent in the cache.
571 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
575 * Try to see if we can get the block without requesting a new
578 down_read(&EXT4_I(inode)->i_data_sem);
579 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
580 retval = ext4_ext_map_blocks(handle, inode, map, 0);
582 retval = ext4_ind_map_blocks(handle, inode, map, 0);
587 if (unlikely(retval != map->m_len)) {
588 ext4_warning(inode->i_sb,
589 "ES len assertion failed for inode "
590 "%lu: retval %d != map->m_len %d",
591 inode->i_ino, retval, map->m_len);
595 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
596 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
597 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
598 !(status & EXTENT_STATUS_WRITTEN) &&
599 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
600 map->m_lblk + map->m_len - 1))
601 status |= EXTENT_STATUS_DELAYED;
602 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
603 map->m_pblk, status);
605 up_read((&EXT4_I(inode)->i_data_sem));
608 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
609 ret = check_block_validity(inode, map);
614 /* If it is only a block(s) look up */
615 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
619 * Returns if the blocks have already allocated
621 * Note that if blocks have been preallocated
622 * ext4_ext_map_blocks() returns with buffer head unmapped
624 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
626 * If we need to convert extent to unwritten
627 * we continue and do the actual work in
628 * ext4_ext_map_blocks()
630 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
634 * Here we clear m_flags because after allocating an new extent,
635 * it will be set again.
637 map->m_flags &= ~EXT4_MAP_FLAGS;
640 * New blocks allocate and/or writing to unwritten extent
641 * will possibly result in updating i_data, so we take
642 * the write lock of i_data_sem, and call get_block()
643 * with create == 1 flag.
645 down_write(&EXT4_I(inode)->i_data_sem);
648 * We need to check for EXT4 here because migrate
649 * could have changed the inode type in between
651 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
652 retval = ext4_ext_map_blocks(handle, inode, map, flags);
654 retval = ext4_ind_map_blocks(handle, inode, map, flags);
656 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
658 * We allocated new blocks which will result in
659 * i_data's format changing. Force the migrate
660 * to fail by clearing migrate flags
662 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
669 if (unlikely(retval != map->m_len)) {
670 ext4_warning(inode->i_sb,
671 "ES len assertion failed for inode "
672 "%lu: retval %d != map->m_len %d",
673 inode->i_ino, retval, map->m_len);
678 * We have to zeroout blocks before inserting them into extent
679 * status tree. Otherwise someone could look them up there and
680 * use them before they are really zeroed. We also have to
681 * unmap metadata before zeroing as otherwise writeback can
682 * overwrite zeros with stale data from block device.
684 if (flags & EXT4_GET_BLOCKS_ZERO &&
685 map->m_flags & EXT4_MAP_MAPPED &&
686 map->m_flags & EXT4_MAP_NEW) {
687 ret = ext4_issue_zeroout(inode, map->m_lblk,
688 map->m_pblk, map->m_len);
696 * If the extent has been zeroed out, we don't need to update
697 * extent status tree.
699 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
700 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
701 if (ext4_es_is_written(&es))
704 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
705 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
706 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
707 !(status & EXTENT_STATUS_WRITTEN) &&
708 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
709 map->m_lblk + map->m_len - 1))
710 status |= EXTENT_STATUS_DELAYED;
711 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
712 map->m_pblk, status);
716 up_write((&EXT4_I(inode)->i_data_sem));
717 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
718 ret = check_block_validity(inode, map);
723 * Inodes with freshly allocated blocks where contents will be
724 * visible after transaction commit must be on transaction's
727 if (map->m_flags & EXT4_MAP_NEW &&
728 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
729 !(flags & EXT4_GET_BLOCKS_ZERO) &&
730 !ext4_is_quota_file(inode) &&
731 ext4_should_order_data(inode)) {
733 (loff_t)map->m_lblk << inode->i_blkbits;
734 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
736 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
737 ret = ext4_jbd2_inode_add_wait(handle, inode,
740 ret = ext4_jbd2_inode_add_write(handle, inode,
746 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
747 map->m_flags & EXT4_MAP_MAPPED))
748 ext4_fc_track_range(handle, inode, map->m_lblk,
749 map->m_lblk + map->m_len - 1);
751 ext_debug(inode, "failed with err %d\n", retval);
756 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
757 * we have to be careful as someone else may be manipulating b_state as well.
759 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
761 unsigned long old_state;
762 unsigned long new_state;
764 flags &= EXT4_MAP_FLAGS;
766 /* Dummy buffer_head? Set non-atomically. */
768 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
772 * Someone else may be modifying b_state. Be careful! This is ugly but
773 * once we get rid of using bh as a container for mapping information
774 * to pass to / from get_block functions, this can go away.
776 old_state = READ_ONCE(bh->b_state);
778 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
779 } while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
782 static int _ext4_get_block(struct inode *inode, sector_t iblock,
783 struct buffer_head *bh, int flags)
785 struct ext4_map_blocks map;
788 if (ext4_has_inline_data(inode))
792 map.m_len = bh->b_size >> inode->i_blkbits;
794 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
797 map_bh(bh, inode->i_sb, map.m_pblk);
798 ext4_update_bh_state(bh, map.m_flags);
799 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
801 } else if (ret == 0) {
802 /* hole case, need to fill in bh->b_size */
803 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
808 int ext4_get_block(struct inode *inode, sector_t iblock,
809 struct buffer_head *bh, int create)
811 return _ext4_get_block(inode, iblock, bh,
812 create ? EXT4_GET_BLOCKS_CREATE : 0);
816 * Get block function used when preparing for buffered write if we require
817 * creating an unwritten extent if blocks haven't been allocated. The extent
818 * will be converted to written after the IO is complete.
820 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
821 struct buffer_head *bh_result, int create)
825 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
826 inode->i_ino, create);
827 ret = _ext4_get_block(inode, iblock, bh_result,
828 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
831 * If the buffer is marked unwritten, mark it as new to make sure it is
832 * zeroed out correctly in case of partial writes. Otherwise, there is
833 * a chance of stale data getting exposed.
835 if (ret == 0 && buffer_unwritten(bh_result))
836 set_buffer_new(bh_result);
841 /* Maximum number of blocks we map for direct IO at once. */
842 #define DIO_MAX_BLOCKS 4096
845 * `handle' can be NULL if create is zero
847 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
848 ext4_lblk_t block, int map_flags)
850 struct ext4_map_blocks map;
851 struct buffer_head *bh;
852 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
853 bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
856 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
857 || handle != NULL || create == 0);
858 ASSERT(create == 0 || !nowait);
862 err = ext4_map_blocks(handle, inode, &map, map_flags);
865 return create ? ERR_PTR(-ENOSPC) : NULL;
870 return sb_find_get_block(inode->i_sb, map.m_pblk);
872 bh = sb_getblk(inode->i_sb, map.m_pblk);
874 return ERR_PTR(-ENOMEM);
875 if (map.m_flags & EXT4_MAP_NEW) {
877 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
878 || (handle != NULL));
881 * Now that we do not always journal data, we should
882 * keep in mind whether this should always journal the
883 * new buffer as metadata. For now, regular file
884 * writes use ext4_get_block instead, so it's not a
888 BUFFER_TRACE(bh, "call get_create_access");
889 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
895 if (!buffer_uptodate(bh)) {
896 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
897 set_buffer_uptodate(bh);
900 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
901 err = ext4_handle_dirty_metadata(handle, inode, bh);
905 BUFFER_TRACE(bh, "not a new buffer");
912 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
913 ext4_lblk_t block, int map_flags)
915 struct buffer_head *bh;
918 bh = ext4_getblk(handle, inode, block, map_flags);
921 if (!bh || ext4_buffer_uptodate(bh))
924 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
932 /* Read a contiguous batch of blocks. */
933 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
934 bool wait, struct buffer_head **bhs)
938 for (i = 0; i < bh_count; i++) {
939 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
940 if (IS_ERR(bhs[i])) {
941 err = PTR_ERR(bhs[i]);
947 for (i = 0; i < bh_count; i++)
948 /* Note that NULL bhs[i] is valid because of holes. */
949 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
950 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
955 for (i = 0; i < bh_count; i++)
957 wait_on_buffer(bhs[i]);
959 for (i = 0; i < bh_count; i++) {
960 if (bhs[i] && !buffer_uptodate(bhs[i])) {
968 for (i = 0; i < bh_count; i++) {
975 int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
976 struct buffer_head *head,
980 int (*fn)(handle_t *handle, struct inode *inode,
981 struct buffer_head *bh))
983 struct buffer_head *bh;
984 unsigned block_start, block_end;
985 unsigned blocksize = head->b_size;
987 struct buffer_head *next;
989 for (bh = head, block_start = 0;
990 ret == 0 && (bh != head || !block_start);
991 block_start = block_end, bh = next) {
992 next = bh->b_this_page;
993 block_end = block_start + blocksize;
994 if (block_end <= from || block_start >= to) {
995 if (partial && !buffer_uptodate(bh))
999 err = (*fn)(handle, inode, bh);
1007 * Helper for handling dirtying of journalled data. We also mark the folio as
1008 * dirty so that writeback code knows about this page (and inode) contains
1009 * dirty data. ext4_writepages() then commits appropriate transaction to
1012 static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
1014 folio_mark_dirty(bh->b_folio);
1015 return ext4_handle_dirty_metadata(handle, NULL, bh);
1018 int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1019 struct buffer_head *bh)
1021 int dirty = buffer_dirty(bh);
1024 if (!buffer_mapped(bh) || buffer_freed(bh))
1027 * __block_write_begin() could have dirtied some buffers. Clean
1028 * the dirty bit as jbd2_journal_get_write_access() could complain
1029 * otherwise about fs integrity issues. Setting of the dirty bit
1030 * by __block_write_begin() isn't a real problem here as we clear
1031 * the bit before releasing a page lock and thus writeback cannot
1032 * ever write the buffer.
1035 clear_buffer_dirty(bh);
1036 BUFFER_TRACE(bh, "get write access");
1037 ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1040 ret = ext4_dirty_journalled_data(handle, bh);
1044 #ifdef CONFIG_FS_ENCRYPTION
1045 static int ext4_block_write_begin(struct folio *folio, loff_t pos, unsigned len,
1046 get_block_t *get_block)
1048 unsigned from = pos & (PAGE_SIZE - 1);
1049 unsigned to = from + len;
1050 struct inode *inode = folio->mapping->host;
1051 unsigned block_start, block_end;
1054 unsigned blocksize = inode->i_sb->s_blocksize;
1056 struct buffer_head *bh, *head, *wait[2];
1060 BUG_ON(!folio_test_locked(folio));
1061 BUG_ON(from > PAGE_SIZE);
1062 BUG_ON(to > PAGE_SIZE);
1065 head = folio_buffers(folio);
1067 head = create_empty_buffers(folio, blocksize, 0);
1068 bbits = ilog2(blocksize);
1069 block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
1071 for (bh = head, block_start = 0; bh != head || !block_start;
1072 block++, block_start = block_end, bh = bh->b_this_page) {
1073 block_end = block_start + blocksize;
1074 if (block_end <= from || block_start >= to) {
1075 if (folio_test_uptodate(folio)) {
1076 set_buffer_uptodate(bh);
1081 clear_buffer_new(bh);
1082 if (!buffer_mapped(bh)) {
1083 WARN_ON(bh->b_size != blocksize);
1084 err = get_block(inode, block, bh, 1);
1087 if (buffer_new(bh)) {
1088 if (folio_test_uptodate(folio)) {
1089 clear_buffer_new(bh);
1090 set_buffer_uptodate(bh);
1091 mark_buffer_dirty(bh);
1094 if (block_end > to || block_start < from)
1095 folio_zero_segments(folio, to,
1101 if (folio_test_uptodate(folio)) {
1102 set_buffer_uptodate(bh);
1105 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1106 !buffer_unwritten(bh) &&
1107 (block_start < from || block_end > to)) {
1108 ext4_read_bh_lock(bh, 0, false);
1109 wait[nr_wait++] = bh;
1113 * If we issued read requests, let them complete.
1115 for (i = 0; i < nr_wait; i++) {
1116 wait_on_buffer(wait[i]);
1117 if (!buffer_uptodate(wait[i]))
1120 if (unlikely(err)) {
1121 folio_zero_new_buffers(folio, from, to);
1122 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1123 for (i = 0; i < nr_wait; i++) {
1126 err2 = fscrypt_decrypt_pagecache_blocks(folio,
1127 blocksize, bh_offset(wait[i]));
1129 clear_buffer_uptodate(wait[i]);
1140 * To preserve ordering, it is essential that the hole instantiation and
1141 * the data write be encapsulated in a single transaction. We cannot
1142 * close off a transaction and start a new one between the ext4_get_block()
1143 * and the ext4_write_end(). So doing the jbd2_journal_start at the start of
1144 * ext4_write_begin() is the right place.
1146 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1147 loff_t pos, unsigned len,
1148 struct page **pagep, void **fsdata)
1150 struct inode *inode = mapping->host;
1151 int ret, needed_blocks;
1154 struct folio *folio;
1158 if (unlikely(ext4_forced_shutdown(inode->i_sb)))
1161 trace_ext4_write_begin(inode, pos, len);
1163 * Reserve one block more for addition to orphan list in case
1164 * we allocate blocks but write fails for some reason
1166 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1167 index = pos >> PAGE_SHIFT;
1168 from = pos & (PAGE_SIZE - 1);
1171 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1172 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1181 * __filemap_get_folio() can take a long time if the
1182 * system is thrashing due to memory pressure, or if the folio
1183 * is being written back. So grab it first before we start
1184 * the transaction handle. This also allows us to allocate
1185 * the folio (if needed) without using GFP_NOFS.
1188 folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
1189 mapping_gfp_mask(mapping));
1191 return PTR_ERR(folio);
1193 * The same as page allocation, we prealloc buffer heads before
1194 * starting the handle.
1196 if (!folio_buffers(folio))
1197 create_empty_buffers(folio, inode->i_sb->s_blocksize, 0);
1199 folio_unlock(folio);
1202 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1203 if (IS_ERR(handle)) {
1205 return PTR_ERR(handle);
1209 if (folio->mapping != mapping) {
1210 /* The folio got truncated from under us */
1211 folio_unlock(folio);
1213 ext4_journal_stop(handle);
1216 /* In case writeback began while the folio was unlocked */
1217 folio_wait_stable(folio);
1219 #ifdef CONFIG_FS_ENCRYPTION
1220 if (ext4_should_dioread_nolock(inode))
1221 ret = ext4_block_write_begin(folio, pos, len,
1222 ext4_get_block_unwritten);
1224 ret = ext4_block_write_begin(folio, pos, len, ext4_get_block);
1226 if (ext4_should_dioread_nolock(inode))
1227 ret = __block_write_begin(&folio->page, pos, len,
1228 ext4_get_block_unwritten);
1230 ret = __block_write_begin(&folio->page, pos, len, ext4_get_block);
1232 if (!ret && ext4_should_journal_data(inode)) {
1233 ret = ext4_walk_page_buffers(handle, inode,
1234 folio_buffers(folio), from, to,
1235 NULL, do_journal_get_write_access);
1239 bool extended = (pos + len > inode->i_size) &&
1240 !ext4_verity_in_progress(inode);
1242 folio_unlock(folio);
1244 * __block_write_begin may have instantiated a few blocks
1245 * outside i_size. Trim these off again. Don't need
1246 * i_size_read because we hold i_rwsem.
1248 * Add inode to orphan list in case we crash before
1251 if (extended && ext4_can_truncate(inode))
1252 ext4_orphan_add(handle, inode);
1254 ext4_journal_stop(handle);
1256 ext4_truncate_failed_write(inode);
1258 * If truncate failed early the inode might
1259 * still be on the orphan list; we need to
1260 * make sure the inode is removed from the
1261 * orphan list in that case.
1264 ext4_orphan_del(NULL, inode);
1267 if (ret == -ENOSPC &&
1268 ext4_should_retry_alloc(inode->i_sb, &retries))
1273 *pagep = &folio->page;
1277 /* For write_end() in data=journal mode */
1278 static int write_end_fn(handle_t *handle, struct inode *inode,
1279 struct buffer_head *bh)
1282 if (!buffer_mapped(bh) || buffer_freed(bh))
1284 set_buffer_uptodate(bh);
1285 ret = ext4_dirty_journalled_data(handle, bh);
1286 clear_buffer_meta(bh);
1287 clear_buffer_prio(bh);
1292 * We need to pick up the new inode size which generic_commit_write gave us
1293 * `file' can be NULL - eg, when called from page_symlink().
1295 * ext4 never places buffers on inode->i_mapping->i_private_list. metadata
1296 * buffers are managed internally.
1298 static int ext4_write_end(struct file *file,
1299 struct address_space *mapping,
1300 loff_t pos, unsigned len, unsigned copied,
1301 struct page *page, void *fsdata)
1303 struct folio *folio = page_folio(page);
1304 handle_t *handle = ext4_journal_current_handle();
1305 struct inode *inode = mapping->host;
1306 loff_t old_size = inode->i_size;
1308 int i_size_changed = 0;
1309 bool verity = ext4_verity_in_progress(inode);
1311 trace_ext4_write_end(inode, pos, len, copied);
1313 if (ext4_has_inline_data(inode) &&
1314 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1315 return ext4_write_inline_data_end(inode, pos, len, copied,
1318 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1320 * it's important to update i_size while still holding folio lock:
1321 * page writeout could otherwise come in and zero beyond i_size.
1323 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1324 * blocks are being written past EOF, so skip the i_size update.
1327 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1328 folio_unlock(folio);
1331 if (old_size < pos && !verity)
1332 pagecache_isize_extended(inode, old_size, pos);
1334 * Don't mark the inode dirty under folio lock. First, it unnecessarily
1335 * makes the holding time of folio lock longer. Second, it forces lock
1336 * ordering of folio lock and transaction start for journaling
1340 ret = ext4_mark_inode_dirty(handle, inode);
1342 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1343 /* if we have allocated more blocks and copied
1344 * less. We will have blocks allocated outside
1345 * inode->i_size. So truncate them
1347 ext4_orphan_add(handle, inode);
1349 ret2 = ext4_journal_stop(handle);
1353 if (pos + len > inode->i_size && !verity) {
1354 ext4_truncate_failed_write(inode);
1356 * If truncate failed early the inode might still be
1357 * on the orphan list; we need to make sure the inode
1358 * is removed from the orphan list in that case.
1361 ext4_orphan_del(NULL, inode);
1364 return ret ? ret : copied;
1368 * This is a private version of folio_zero_new_buffers() which doesn't
1369 * set the buffer to be dirty, since in data=journalled mode we need
1370 * to call ext4_dirty_journalled_data() instead.
1372 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1373 struct inode *inode,
1374 struct folio *folio,
1375 unsigned from, unsigned to)
1377 unsigned int block_start = 0, block_end;
1378 struct buffer_head *head, *bh;
1380 bh = head = folio_buffers(folio);
1382 block_end = block_start + bh->b_size;
1383 if (buffer_new(bh)) {
1384 if (block_end > from && block_start < to) {
1385 if (!folio_test_uptodate(folio)) {
1386 unsigned start, size;
1388 start = max(from, block_start);
1389 size = min(to, block_end) - start;
1391 folio_zero_range(folio, start, size);
1392 write_end_fn(handle, inode, bh);
1394 clear_buffer_new(bh);
1397 block_start = block_end;
1398 bh = bh->b_this_page;
1399 } while (bh != head);
1402 static int ext4_journalled_write_end(struct file *file,
1403 struct address_space *mapping,
1404 loff_t pos, unsigned len, unsigned copied,
1405 struct page *page, void *fsdata)
1407 struct folio *folio = page_folio(page);
1408 handle_t *handle = ext4_journal_current_handle();
1409 struct inode *inode = mapping->host;
1410 loff_t old_size = inode->i_size;
1414 int size_changed = 0;
1415 bool verity = ext4_verity_in_progress(inode);
1417 trace_ext4_journalled_write_end(inode, pos, len, copied);
1418 from = pos & (PAGE_SIZE - 1);
1421 BUG_ON(!ext4_handle_valid(handle));
1423 if (ext4_has_inline_data(inode))
1424 return ext4_write_inline_data_end(inode, pos, len, copied,
1427 if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
1429 ext4_journalled_zero_new_buffers(handle, inode, folio,
1432 if (unlikely(copied < len))
1433 ext4_journalled_zero_new_buffers(handle, inode, folio,
1435 ret = ext4_walk_page_buffers(handle, inode,
1436 folio_buffers(folio),
1437 from, from + copied, &partial,
1440 folio_mark_uptodate(folio);
1443 size_changed = ext4_update_inode_size(inode, pos + copied);
1444 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1445 folio_unlock(folio);
1448 if (old_size < pos && !verity)
1449 pagecache_isize_extended(inode, old_size, pos);
1452 ret2 = ext4_mark_inode_dirty(handle, inode);
1457 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1458 /* if we have allocated more blocks and copied
1459 * less. We will have blocks allocated outside
1460 * inode->i_size. So truncate them
1462 ext4_orphan_add(handle, inode);
1464 ret2 = ext4_journal_stop(handle);
1467 if (pos + len > inode->i_size && !verity) {
1468 ext4_truncate_failed_write(inode);
1470 * If truncate failed early the inode might still be
1471 * on the orphan list; we need to make sure the inode
1472 * is removed from the orphan list in that case.
1475 ext4_orphan_del(NULL, inode);
1478 return ret ? ret : copied;
1482 * Reserve space for 'nr_resv' clusters
1484 static int ext4_da_reserve_space(struct inode *inode, int nr_resv)
1486 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1487 struct ext4_inode_info *ei = EXT4_I(inode);
1491 * We will charge metadata quota at writeout time; this saves
1492 * us from metadata over-estimation, though we may go over by
1493 * a small amount in the end. Here we just reserve for data.
1495 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, nr_resv));
1499 spin_lock(&ei->i_block_reservation_lock);
1500 if (ext4_claim_free_clusters(sbi, nr_resv, 0)) {
1501 spin_unlock(&ei->i_block_reservation_lock);
1502 dquot_release_reservation_block(inode, EXT4_C2B(sbi, nr_resv));
1505 ei->i_reserved_data_blocks += nr_resv;
1506 trace_ext4_da_reserve_space(inode, nr_resv);
1507 spin_unlock(&ei->i_block_reservation_lock);
1509 return 0; /* success */
1512 void ext4_da_release_space(struct inode *inode, int to_free)
1514 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1515 struct ext4_inode_info *ei = EXT4_I(inode);
1518 return; /* Nothing to release, exit */
1520 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1522 trace_ext4_da_release_space(inode, to_free);
1523 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1525 * if there aren't enough reserved blocks, then the
1526 * counter is messed up somewhere. Since this
1527 * function is called from invalidate page, it's
1528 * harmless to return without any action.
1530 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1531 "ino %lu, to_free %d with only %d reserved "
1532 "data blocks", inode->i_ino, to_free,
1533 ei->i_reserved_data_blocks);
1535 to_free = ei->i_reserved_data_blocks;
1537 ei->i_reserved_data_blocks -= to_free;
1539 /* update fs dirty data blocks counter */
1540 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1542 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1544 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1548 * Delayed allocation stuff
1551 struct mpage_da_data {
1552 /* These are input fields for ext4_do_writepages() */
1553 struct inode *inode;
1554 struct writeback_control *wbc;
1555 unsigned int can_map:1; /* Can writepages call map blocks? */
1557 /* These are internal state of ext4_do_writepages() */
1558 pgoff_t first_page; /* The first page to write */
1559 pgoff_t next_page; /* Current page to examine */
1560 pgoff_t last_page; /* Last page to examine */
1562 * Extent to map - this can be after first_page because that can be
1563 * fully mapped. We somewhat abuse m_flags to store whether the extent
1564 * is delalloc or unwritten.
1566 struct ext4_map_blocks map;
1567 struct ext4_io_submit io_submit; /* IO submission data */
1568 unsigned int do_map:1;
1569 unsigned int scanned_until_end:1;
1570 unsigned int journalled_more_data:1;
1573 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1578 struct folio_batch fbatch;
1579 struct inode *inode = mpd->inode;
1580 struct address_space *mapping = inode->i_mapping;
1582 /* This is necessary when next_page == 0. */
1583 if (mpd->first_page >= mpd->next_page)
1586 mpd->scanned_until_end = 0;
1587 index = mpd->first_page;
1588 end = mpd->next_page - 1;
1590 ext4_lblk_t start, last;
1591 start = index << (PAGE_SHIFT - inode->i_blkbits);
1592 last = end << (PAGE_SHIFT - inode->i_blkbits);
1595 * avoid racing with extent status tree scans made by
1596 * ext4_insert_delayed_block()
1598 down_write(&EXT4_I(inode)->i_data_sem);
1599 ext4_es_remove_extent(inode, start, last - start + 1);
1600 up_write(&EXT4_I(inode)->i_data_sem);
1603 folio_batch_init(&fbatch);
1604 while (index <= end) {
1605 nr = filemap_get_folios(mapping, &index, end, &fbatch);
1608 for (i = 0; i < nr; i++) {
1609 struct folio *folio = fbatch.folios[i];
1611 if (folio->index < mpd->first_page)
1613 if (folio_next_index(folio) - 1 > end)
1615 BUG_ON(!folio_test_locked(folio));
1616 BUG_ON(folio_test_writeback(folio));
1618 if (folio_mapped(folio))
1619 folio_clear_dirty_for_io(folio);
1620 block_invalidate_folio(folio, 0,
1622 folio_clear_uptodate(folio);
1624 folio_unlock(folio);
1626 folio_batch_release(&fbatch);
1630 static void ext4_print_free_blocks(struct inode *inode)
1632 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1633 struct super_block *sb = inode->i_sb;
1634 struct ext4_inode_info *ei = EXT4_I(inode);
1636 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1637 EXT4_C2B(EXT4_SB(inode->i_sb),
1638 ext4_count_free_clusters(sb)));
1639 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1640 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1641 (long long) EXT4_C2B(EXT4_SB(sb),
1642 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1643 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1644 (long long) EXT4_C2B(EXT4_SB(sb),
1645 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1646 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1647 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1648 ei->i_reserved_data_blocks);
1653 * Check whether the cluster containing lblk has been allocated or has
1654 * delalloc reservation.
1656 * Returns 0 if the cluster doesn't have either, 1 if it has delalloc
1657 * reservation, 2 if it's already been allocated, negative error code on
1660 static int ext4_clu_alloc_state(struct inode *inode, ext4_lblk_t lblk)
1662 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1665 /* Has delalloc reservation? */
1666 if (ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk))
1669 /* Already been allocated? */
1670 if (ext4_es_scan_clu(inode, &ext4_es_is_mapped, lblk))
1672 ret = ext4_clu_mapped(inode, EXT4_B2C(sbi, lblk));
1682 * ext4_insert_delayed_blocks - adds a multiple delayed blocks to the extents
1683 * status tree, incrementing the reserved
1684 * cluster/block count or making pending
1685 * reservations where needed
1687 * @inode - file containing the newly added block
1688 * @lblk - start logical block to be added
1689 * @len - length of blocks to be added
1691 * Returns 0 on success, negative error code on failure.
1693 static int ext4_insert_delayed_blocks(struct inode *inode, ext4_lblk_t lblk,
1696 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1698 bool lclu_allocated = false;
1699 bool end_allocated = false;
1700 ext4_lblk_t resv_clu;
1701 ext4_lblk_t end = lblk + len - 1;
1704 * If the cluster containing lblk or end is shared with a delayed,
1705 * written, or unwritten extent in a bigalloc file system, it's
1706 * already been accounted for and does not need to be reserved.
1707 * A pending reservation must be made for the cluster if it's
1708 * shared with a written or unwritten extent and doesn't already
1709 * have one. Written and unwritten extents can be purged from the
1710 * extents status tree if the system is under memory pressure, so
1711 * it's necessary to examine the extent tree if a search of the
1712 * extents status tree doesn't get a match.
1714 if (sbi->s_cluster_ratio == 1) {
1715 ret = ext4_da_reserve_space(inode, len);
1716 if (ret != 0) /* ENOSPC */
1718 } else { /* bigalloc */
1719 resv_clu = EXT4_B2C(sbi, end) - EXT4_B2C(sbi, lblk) + 1;
1721 ret = ext4_clu_alloc_state(inode, lblk);
1726 lclu_allocated = (ret == 2);
1729 if (EXT4_B2C(sbi, lblk) != EXT4_B2C(sbi, end)) {
1730 ret = ext4_clu_alloc_state(inode, end);
1735 end_allocated = (ret == 2);
1740 ret = ext4_da_reserve_space(inode, resv_clu);
1741 if (ret != 0) /* ENOSPC */
1746 ext4_es_insert_delayed_extent(inode, lblk, len, lclu_allocated,
1752 * Looks up the requested blocks and sets the delalloc extent map.
1753 * First try to look up for the extent entry that contains the requested
1754 * blocks in the extent status tree without i_data_sem, then try to look
1755 * up for the ondisk extent mapping with i_data_sem in read mode,
1756 * finally hold i_data_sem in write mode, looks up again and add a
1757 * delalloc extent entry if it still couldn't find any extent. Pass out
1758 * the mapped extent through @map and return 0 on success.
1760 static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map)
1762 struct extent_status es;
1764 #ifdef ES_AGGRESSIVE_TEST
1765 struct ext4_map_blocks orig_map;
1767 memcpy(&orig_map, map, sizeof(*map));
1771 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1772 (unsigned long) map->m_lblk);
1774 /* Lookup extent status tree firstly */
1775 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
1776 map->m_len = min_t(unsigned int, map->m_len,
1777 es.es_len - (map->m_lblk - es.es_lblk));
1779 if (ext4_es_is_hole(&es))
1784 * Delayed extent could be allocated by fallocate.
1785 * So we need to check it.
1787 if (ext4_es_is_delonly(&es)) {
1788 map->m_flags |= EXT4_MAP_DELAYED;
1792 map->m_pblk = ext4_es_pblock(&es) + map->m_lblk - es.es_lblk;
1793 if (ext4_es_is_written(&es))
1794 map->m_flags |= EXT4_MAP_MAPPED;
1795 else if (ext4_es_is_unwritten(&es))
1796 map->m_flags |= EXT4_MAP_UNWRITTEN;
1800 #ifdef ES_AGGRESSIVE_TEST
1801 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1807 * Try to see if we can get the block without requesting a new
1808 * file system block.
1810 down_read(&EXT4_I(inode)->i_data_sem);
1811 if (ext4_has_inline_data(inode))
1814 retval = ext4_map_query_blocks(NULL, inode, map);
1815 up_read(&EXT4_I(inode)->i_data_sem);
1817 return retval < 0 ? retval : 0;
1820 down_write(&EXT4_I(inode)->i_data_sem);
1822 * Page fault path (ext4_page_mkwrite does not take i_rwsem)
1823 * and fallocate path (no folio lock) can race. Make sure we
1824 * lookup the extent status tree here again while i_data_sem
1825 * is held in write mode, before inserting a new da entry in
1826 * the extent status tree.
1828 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
1829 map->m_len = min_t(unsigned int, map->m_len,
1830 es.es_len - (map->m_lblk - es.es_lblk));
1832 if (!ext4_es_is_hole(&es)) {
1833 up_write(&EXT4_I(inode)->i_data_sem);
1836 } else if (!ext4_has_inline_data(inode)) {
1837 retval = ext4_map_query_blocks(NULL, inode, map);
1839 up_write(&EXT4_I(inode)->i_data_sem);
1840 return retval < 0 ? retval : 0;
1844 map->m_flags |= EXT4_MAP_DELAYED;
1845 retval = ext4_insert_delayed_blocks(inode, map->m_lblk, map->m_len);
1846 up_write(&EXT4_I(inode)->i_data_sem);
1852 * This is a special get_block_t callback which is used by
1853 * ext4_da_write_begin(). It will either return mapped block or
1854 * reserve space for a single block.
1856 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1857 * We also have b_blocknr = -1 and b_bdev initialized properly
1859 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1860 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1861 * initialized properly.
1863 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1864 struct buffer_head *bh, int create)
1866 struct ext4_map_blocks map;
1867 sector_t invalid_block = ~((sector_t) 0xffff);
1870 BUG_ON(create == 0);
1871 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1873 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1876 map.m_lblk = iblock;
1880 * first, we need to know whether the block is allocated already
1881 * preallocated blocks are unmapped but should treated
1882 * the same as allocated blocks.
1884 ret = ext4_da_map_blocks(inode, &map);
1888 if (map.m_flags & EXT4_MAP_DELAYED) {
1889 map_bh(bh, inode->i_sb, invalid_block);
1891 set_buffer_delay(bh);
1895 map_bh(bh, inode->i_sb, map.m_pblk);
1896 ext4_update_bh_state(bh, map.m_flags);
1898 if (buffer_unwritten(bh)) {
1899 /* A delayed write to unwritten bh should be marked
1900 * new and mapped. Mapped ensures that we don't do
1901 * get_block multiple times when we write to the same
1902 * offset and new ensures that we do proper zero out
1903 * for partial write.
1906 set_buffer_mapped(bh);
1911 static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
1913 mpd->first_page += folio_nr_pages(folio);
1914 folio_unlock(folio);
1917 static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
1923 BUG_ON(folio->index != mpd->first_page);
1924 folio_clear_dirty_for_io(folio);
1926 * We have to be very careful here! Nothing protects writeback path
1927 * against i_size changes and the page can be writeably mapped into
1928 * page tables. So an application can be growing i_size and writing
1929 * data through mmap while writeback runs. folio_clear_dirty_for_io()
1930 * write-protects our page in page tables and the page cannot get
1931 * written to again until we release folio lock. So only after
1932 * folio_clear_dirty_for_io() we are safe to sample i_size for
1933 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
1934 * on the barrier provided by folio_test_clear_dirty() in
1935 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
1936 * after page tables are updated.
1938 size = i_size_read(mpd->inode);
1939 len = folio_size(folio);
1940 if (folio_pos(folio) + len > size &&
1941 !ext4_verity_in_progress(mpd->inode))
1942 len = size & (len - 1);
1943 err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
1945 mpd->wbc->nr_to_write--;
1950 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
1953 * mballoc gives us at most this number of blocks...
1954 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1955 * The rest of mballoc seems to handle chunks up to full group size.
1957 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1960 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1962 * @mpd - extent of blocks
1963 * @lblk - logical number of the block in the file
1964 * @bh - buffer head we want to add to the extent
1966 * The function is used to collect contig. blocks in the same state. If the
1967 * buffer doesn't require mapping for writeback and we haven't started the
1968 * extent of buffers to map yet, the function returns 'true' immediately - the
1969 * caller can write the buffer right away. Otherwise the function returns true
1970 * if the block has been added to the extent, false if the block couldn't be
1973 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1974 struct buffer_head *bh)
1976 struct ext4_map_blocks *map = &mpd->map;
1978 /* Buffer that doesn't need mapping for writeback? */
1979 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1980 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1981 /* So far no extent to map => we write the buffer right away */
1982 if (map->m_len == 0)
1987 /* First block in the extent? */
1988 if (map->m_len == 0) {
1989 /* We cannot map unless handle is started... */
1994 map->m_flags = bh->b_state & BH_FLAGS;
1998 /* Don't go larger than mballoc is willing to allocate */
1999 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2002 /* Can we merge the block to our big extent? */
2003 if (lblk == map->m_lblk + map->m_len &&
2004 (bh->b_state & BH_FLAGS) == map->m_flags) {
2012 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2014 * @mpd - extent of blocks for mapping
2015 * @head - the first buffer in the page
2016 * @bh - buffer we should start processing from
2017 * @lblk - logical number of the block in the file corresponding to @bh
2019 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2020 * the page for IO if all buffers in this page were mapped and there's no
2021 * accumulated extent of buffers to map or add buffers in the page to the
2022 * extent of buffers to map. The function returns 1 if the caller can continue
2023 * by processing the next page, 0 if it should stop adding buffers to the
2024 * extent to map because we cannot extend it anymore. It can also return value
2025 * < 0 in case of error during IO submission.
2027 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2028 struct buffer_head *head,
2029 struct buffer_head *bh,
2032 struct inode *inode = mpd->inode;
2034 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2035 >> inode->i_blkbits;
2037 if (ext4_verity_in_progress(inode))
2038 blocks = EXT_MAX_BLOCKS;
2041 BUG_ON(buffer_locked(bh));
2043 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2044 /* Found extent to map? */
2047 /* Buffer needs mapping and handle is not started? */
2050 /* Everything mapped so far and we hit EOF */
2053 } while (lblk++, (bh = bh->b_this_page) != head);
2054 /* So far everything mapped? Submit the page for IO. */
2055 if (mpd->map.m_len == 0) {
2056 err = mpage_submit_folio(mpd, head->b_folio);
2059 mpage_folio_done(mpd, head->b_folio);
2061 if (lblk >= blocks) {
2062 mpd->scanned_until_end = 1;
2069 * mpage_process_folio - update folio buffers corresponding to changed extent
2070 * and may submit fully mapped page for IO
2071 * @mpd: description of extent to map, on return next extent to map
2072 * @folio: Contains these buffers.
2073 * @m_lblk: logical block mapping.
2074 * @m_pblk: corresponding physical mapping.
2075 * @map_bh: determines on return whether this page requires any further
2078 * Scan given folio buffers corresponding to changed extent and update buffer
2079 * state according to new extent state.
2080 * We map delalloc buffers to their physical location, clear unwritten bits.
2081 * If the given folio is not fully mapped, we update @mpd to the next extent in
2082 * the given folio that needs mapping & return @map_bh as true.
2084 static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
2085 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2088 struct buffer_head *head, *bh;
2089 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2090 ext4_lblk_t lblk = *m_lblk;
2091 ext4_fsblk_t pblock = *m_pblk;
2093 int blkbits = mpd->inode->i_blkbits;
2094 ssize_t io_end_size = 0;
2095 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2097 bh = head = folio_buffers(folio);
2099 if (lblk < mpd->map.m_lblk)
2101 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2103 * Buffer after end of mapped extent.
2104 * Find next buffer in the folio to map.
2107 mpd->map.m_flags = 0;
2108 io_end_vec->size += io_end_size;
2110 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2113 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2114 io_end_vec = ext4_alloc_io_end_vec(io_end);
2115 if (IS_ERR(io_end_vec)) {
2116 err = PTR_ERR(io_end_vec);
2119 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2124 if (buffer_delay(bh)) {
2125 clear_buffer_delay(bh);
2126 bh->b_blocknr = pblock++;
2128 clear_buffer_unwritten(bh);
2129 io_end_size += (1 << blkbits);
2130 } while (lblk++, (bh = bh->b_this_page) != head);
2132 io_end_vec->size += io_end_size;
2141 * mpage_map_buffers - update buffers corresponding to changed extent and
2142 * submit fully mapped pages for IO
2144 * @mpd - description of extent to map, on return next extent to map
2146 * Scan buffers corresponding to changed extent (we expect corresponding pages
2147 * to be already locked) and update buffer state according to new extent state.
2148 * We map delalloc buffers to their physical location, clear unwritten bits,
2149 * and mark buffers as uninit when we perform writes to unwritten extents
2150 * and do extent conversion after IO is finished. If the last page is not fully
2151 * mapped, we update @map to the next extent in the last page that needs
2152 * mapping. Otherwise we submit the page for IO.
2154 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2156 struct folio_batch fbatch;
2158 struct inode *inode = mpd->inode;
2159 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2162 ext4_fsblk_t pblock;
2164 bool map_bh = false;
2166 start = mpd->map.m_lblk >> bpp_bits;
2167 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2168 lblk = start << bpp_bits;
2169 pblock = mpd->map.m_pblk;
2171 folio_batch_init(&fbatch);
2172 while (start <= end) {
2173 nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
2176 for (i = 0; i < nr; i++) {
2177 struct folio *folio = fbatch.folios[i];
2179 err = mpage_process_folio(mpd, folio, &lblk, &pblock,
2182 * If map_bh is true, means page may require further bh
2183 * mapping, or maybe the page was submitted for IO.
2184 * So we return to call further extent mapping.
2186 if (err < 0 || map_bh)
2188 /* Page fully mapped - let IO run! */
2189 err = mpage_submit_folio(mpd, folio);
2192 mpage_folio_done(mpd, folio);
2194 folio_batch_release(&fbatch);
2196 /* Extent fully mapped and matches with page boundary. We are done. */
2198 mpd->map.m_flags = 0;
2201 folio_batch_release(&fbatch);
2205 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2207 struct inode *inode = mpd->inode;
2208 struct ext4_map_blocks *map = &mpd->map;
2209 int get_blocks_flags;
2210 int err, dioread_nolock;
2212 trace_ext4_da_write_pages_extent(inode, map);
2214 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2215 * to convert an unwritten extent to be initialized (in the case
2216 * where we have written into one or more preallocated blocks). It is
2217 * possible that we're going to need more metadata blocks than
2218 * previously reserved. However we must not fail because we're in
2219 * writeback and there is nothing we can do about it so it might result
2220 * in data loss. So use reserved blocks to allocate metadata if
2223 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2224 * the blocks in question are delalloc blocks. This indicates
2225 * that the blocks and quotas has already been checked when
2226 * the data was copied into the page cache.
2228 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2229 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2230 EXT4_GET_BLOCKS_IO_SUBMIT;
2231 dioread_nolock = ext4_should_dioread_nolock(inode);
2233 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2234 if (map->m_flags & BIT(BH_Delay))
2235 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2237 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2240 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2241 if (!mpd->io_submit.io_end->handle &&
2242 ext4_handle_valid(handle)) {
2243 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2244 handle->h_rsv_handle = NULL;
2246 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2249 BUG_ON(map->m_len == 0);
2254 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2255 * mpd->len and submit pages underlying it for IO
2257 * @handle - handle for journal operations
2258 * @mpd - extent to map
2259 * @give_up_on_write - we set this to true iff there is a fatal error and there
2260 * is no hope of writing the data. The caller should discard
2261 * dirty pages to avoid infinite loops.
2263 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2264 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2265 * them to initialized or split the described range from larger unwritten
2266 * extent. Note that we need not map all the described range since allocation
2267 * can return less blocks or the range is covered by more unwritten extents. We
2268 * cannot map more because we are limited by reserved transaction credits. On
2269 * the other hand we always make sure that the last touched page is fully
2270 * mapped so that it can be written out (and thus forward progress is
2271 * guaranteed). After mapping we submit all mapped pages for IO.
2273 static int mpage_map_and_submit_extent(handle_t *handle,
2274 struct mpage_da_data *mpd,
2275 bool *give_up_on_write)
2277 struct inode *inode = mpd->inode;
2278 struct ext4_map_blocks *map = &mpd->map;
2282 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2283 struct ext4_io_end_vec *io_end_vec;
2285 io_end_vec = ext4_alloc_io_end_vec(io_end);
2286 if (IS_ERR(io_end_vec))
2287 return PTR_ERR(io_end_vec);
2288 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2290 err = mpage_map_one_extent(handle, mpd);
2292 struct super_block *sb = inode->i_sb;
2294 if (ext4_forced_shutdown(sb))
2295 goto invalidate_dirty_pages;
2297 * Let the uper layers retry transient errors.
2298 * In the case of ENOSPC, if ext4_count_free_blocks()
2299 * is non-zero, a commit should free up blocks.
2301 if ((err == -ENOMEM) ||
2302 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2304 goto update_disksize;
2307 ext4_msg(sb, KERN_CRIT,
2308 "Delayed block allocation failed for "
2309 "inode %lu at logical offset %llu with"
2310 " max blocks %u with error %d",
2312 (unsigned long long)map->m_lblk,
2313 (unsigned)map->m_len, -err);
2314 ext4_msg(sb, KERN_CRIT,
2315 "This should not happen!! Data will "
2318 ext4_print_free_blocks(inode);
2319 invalidate_dirty_pages:
2320 *give_up_on_write = true;
2325 * Update buffer state, submit mapped pages, and get us new
2328 err = mpage_map_and_submit_buffers(mpd);
2330 goto update_disksize;
2331 } while (map->m_len);
2335 * Update on-disk size after IO is submitted. Races with
2336 * truncate are avoided by checking i_size under i_data_sem.
2338 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2339 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2343 down_write(&EXT4_I(inode)->i_data_sem);
2344 i_size = i_size_read(inode);
2345 if (disksize > i_size)
2347 if (disksize > EXT4_I(inode)->i_disksize)
2348 EXT4_I(inode)->i_disksize = disksize;
2349 up_write(&EXT4_I(inode)->i_data_sem);
2350 err2 = ext4_mark_inode_dirty(handle, inode);
2352 ext4_error_err(inode->i_sb, -err2,
2353 "Failed to mark inode %lu dirty",
2363 * Calculate the total number of credits to reserve for one writepages
2364 * iteration. This is called from ext4_writepages(). We map an extent of
2365 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2366 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2367 * bpp - 1 blocks in bpp different extents.
2369 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2371 int bpp = ext4_journal_blocks_per_page(inode);
2373 return ext4_meta_trans_blocks(inode,
2374 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2377 static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
2380 struct buffer_head *page_bufs = folio_buffers(folio);
2381 struct inode *inode = folio->mapping->host;
2384 ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2385 NULL, do_journal_get_write_access);
2386 err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2387 NULL, write_end_fn);
2390 err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
2393 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2398 static int mpage_journal_page_buffers(handle_t *handle,
2399 struct mpage_da_data *mpd,
2400 struct folio *folio)
2402 struct inode *inode = mpd->inode;
2403 loff_t size = i_size_read(inode);
2404 size_t len = folio_size(folio);
2406 folio_clear_checked(folio);
2407 mpd->wbc->nr_to_write--;
2409 if (folio_pos(folio) + len > size &&
2410 !ext4_verity_in_progress(inode))
2411 len = size & (len - 1);
2413 return ext4_journal_folio_buffers(handle, folio, len);
2417 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2418 * needing mapping, submit mapped pages
2420 * @mpd - where to look for pages
2422 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2423 * IO immediately. If we cannot map blocks, we submit just already mapped
2424 * buffers in the page for IO and keep page dirty. When we can map blocks and
2425 * we find a page which isn't mapped we start accumulating extent of buffers
2426 * underlying these pages that needs mapping (formed by either delayed or
2427 * unwritten buffers). We also lock the pages containing these buffers. The
2428 * extent found is returned in @mpd structure (starting at mpd->lblk with
2429 * length mpd->len blocks).
2431 * Note that this function can attach bios to one io_end structure which are
2432 * neither logically nor physically contiguous. Although it may seem as an
2433 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2434 * case as we need to track IO to all buffers underlying a page in one io_end.
2436 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2438 struct address_space *mapping = mpd->inode->i_mapping;
2439 struct folio_batch fbatch;
2440 unsigned int nr_folios;
2441 pgoff_t index = mpd->first_page;
2442 pgoff_t end = mpd->last_page;
2445 int blkbits = mpd->inode->i_blkbits;
2447 struct buffer_head *head;
2448 handle_t *handle = NULL;
2449 int bpp = ext4_journal_blocks_per_page(mpd->inode);
2451 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2452 tag = PAGECACHE_TAG_TOWRITE;
2454 tag = PAGECACHE_TAG_DIRTY;
2457 mpd->next_page = index;
2458 if (ext4_should_journal_data(mpd->inode)) {
2459 handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
2462 return PTR_ERR(handle);
2464 folio_batch_init(&fbatch);
2465 while (index <= end) {
2466 nr_folios = filemap_get_folios_tag(mapping, &index, end,
2471 for (i = 0; i < nr_folios; i++) {
2472 struct folio *folio = fbatch.folios[i];
2475 * Accumulated enough dirty pages? This doesn't apply
2476 * to WB_SYNC_ALL mode. For integrity sync we have to
2477 * keep going because someone may be concurrently
2478 * dirtying pages, and we might have synced a lot of
2479 * newly appeared dirty pages, but have not synced all
2480 * of the old dirty pages.
2482 if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2483 mpd->wbc->nr_to_write <=
2484 mpd->map.m_len >> (PAGE_SHIFT - blkbits))
2487 /* If we can't merge this page, we are done. */
2488 if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
2492 err = ext4_journal_ensure_credits(handle, bpp,
2500 * If the page is no longer dirty, or its mapping no
2501 * longer corresponds to inode we are writing (which
2502 * means it has been truncated or invalidated), or the
2503 * page is already under writeback and we are not doing
2504 * a data integrity writeback, skip the page
2506 if (!folio_test_dirty(folio) ||
2507 (folio_test_writeback(folio) &&
2508 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2509 unlikely(folio->mapping != mapping)) {
2510 folio_unlock(folio);
2514 folio_wait_writeback(folio);
2515 BUG_ON(folio_test_writeback(folio));
2518 * Should never happen but for buggy code in
2519 * other subsystems that call
2520 * set_page_dirty() without properly warning
2521 * the file system first. See [1] for more
2524 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2526 if (!folio_buffers(folio)) {
2527 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
2528 folio_clear_dirty(folio);
2529 folio_unlock(folio);
2533 if (mpd->map.m_len == 0)
2534 mpd->first_page = folio->index;
2535 mpd->next_page = folio_next_index(folio);
2537 * Writeout when we cannot modify metadata is simple.
2538 * Just submit the page. For data=journal mode we
2539 * first handle writeout of the page for checkpoint and
2540 * only after that handle delayed page dirtying. This
2541 * makes sure current data is checkpointed to the final
2542 * location before possibly journalling it again which
2543 * is desirable when the page is frequently dirtied
2546 if (!mpd->can_map) {
2547 err = mpage_submit_folio(mpd, folio);
2550 /* Pending dirtying of journalled data? */
2551 if (folio_test_checked(folio)) {
2552 err = mpage_journal_page_buffers(handle,
2556 mpd->journalled_more_data = 1;
2558 mpage_folio_done(mpd, folio);
2560 /* Add all dirty buffers to mpd */
2561 lblk = ((ext4_lblk_t)folio->index) <<
2562 (PAGE_SHIFT - blkbits);
2563 head = folio_buffers(folio);
2564 err = mpage_process_page_bufs(mpd, head, head,
2571 folio_batch_release(&fbatch);
2574 mpd->scanned_until_end = 1;
2576 ext4_journal_stop(handle);
2579 folio_batch_release(&fbatch);
2581 ext4_journal_stop(handle);
2585 static int ext4_do_writepages(struct mpage_da_data *mpd)
2587 struct writeback_control *wbc = mpd->wbc;
2588 pgoff_t writeback_index = 0;
2589 long nr_to_write = wbc->nr_to_write;
2590 int range_whole = 0;
2592 handle_t *handle = NULL;
2593 struct inode *inode = mpd->inode;
2594 struct address_space *mapping = inode->i_mapping;
2595 int needed_blocks, rsv_blocks = 0, ret = 0;
2596 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2597 struct blk_plug plug;
2598 bool give_up_on_write = false;
2600 trace_ext4_writepages(inode, wbc);
2603 * No pages to write? This is mainly a kludge to avoid starting
2604 * a transaction for special inodes like journal inode on last iput()
2605 * because that could violate lock ordering on umount
2607 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2608 goto out_writepages;
2611 * If the filesystem has aborted, it is read-only, so return
2612 * right away instead of dumping stack traces later on that
2613 * will obscure the real source of the problem. We test
2614 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
2615 * the latter could be true if the filesystem is mounted
2616 * read-only, and in that case, ext4_writepages should
2617 * *never* be called, so if that ever happens, we would want
2620 if (unlikely(ext4_forced_shutdown(mapping->host->i_sb))) {
2622 goto out_writepages;
2626 * If we have inline data and arrive here, it means that
2627 * we will soon create the block for the 1st page, so
2628 * we'd better clear the inline data here.
2630 if (ext4_has_inline_data(inode)) {
2631 /* Just inode will be modified... */
2632 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2633 if (IS_ERR(handle)) {
2634 ret = PTR_ERR(handle);
2635 goto out_writepages;
2637 BUG_ON(ext4_test_inode_state(inode,
2638 EXT4_STATE_MAY_INLINE_DATA));
2639 ext4_destroy_inline_data(handle, inode);
2640 ext4_journal_stop(handle);
2644 * data=journal mode does not do delalloc so we just need to writeout /
2645 * journal already mapped buffers. On the other hand we need to commit
2646 * transaction to make data stable. We expect all the data to be
2647 * already in the journal (the only exception are DMA pinned pages
2648 * dirtied behind our back) so we commit transaction here and run the
2649 * writeback loop to checkpoint them. The checkpointing is not actually
2650 * necessary to make data persistent *but* quite a few places (extent
2651 * shifting operations, fsverity, ...) depend on being able to drop
2652 * pagecache pages after calling filemap_write_and_wait() and for that
2653 * checkpointing needs to happen.
2655 if (ext4_should_journal_data(inode)) {
2657 if (wbc->sync_mode == WB_SYNC_ALL)
2658 ext4_fc_commit(sbi->s_journal,
2659 EXT4_I(inode)->i_datasync_tid);
2661 mpd->journalled_more_data = 0;
2663 if (ext4_should_dioread_nolock(inode)) {
2665 * We may need to convert up to one extent per block in
2666 * the page and we may dirty the inode.
2668 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2669 PAGE_SIZE >> inode->i_blkbits);
2672 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2675 if (wbc->range_cyclic) {
2676 writeback_index = mapping->writeback_index;
2677 if (writeback_index)
2679 mpd->first_page = writeback_index;
2680 mpd->last_page = -1;
2682 mpd->first_page = wbc->range_start >> PAGE_SHIFT;
2683 mpd->last_page = wbc->range_end >> PAGE_SHIFT;
2686 ext4_io_submit_init(&mpd->io_submit, wbc);
2688 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2689 tag_pages_for_writeback(mapping, mpd->first_page,
2691 blk_start_plug(&plug);
2694 * First writeback pages that don't need mapping - we can avoid
2695 * starting a transaction unnecessarily and also avoid being blocked
2696 * in the block layer on device congestion while having transaction
2700 mpd->scanned_until_end = 0;
2701 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2702 if (!mpd->io_submit.io_end) {
2706 ret = mpage_prepare_extent_to_map(mpd);
2707 /* Unlock pages we didn't use */
2708 mpage_release_unused_pages(mpd, false);
2709 /* Submit prepared bio */
2710 ext4_io_submit(&mpd->io_submit);
2711 ext4_put_io_end_defer(mpd->io_submit.io_end);
2712 mpd->io_submit.io_end = NULL;
2716 while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
2717 /* For each extent of pages we use new io_end */
2718 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2719 if (!mpd->io_submit.io_end) {
2724 WARN_ON_ONCE(!mpd->can_map);
2726 * We have two constraints: We find one extent to map and we
2727 * must always write out whole page (makes a difference when
2728 * blocksize < pagesize) so that we don't block on IO when we
2729 * try to write out the rest of the page. Journalled mode is
2730 * not supported by delalloc.
2732 BUG_ON(ext4_should_journal_data(inode));
2733 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2735 /* start a new transaction */
2736 handle = ext4_journal_start_with_reserve(inode,
2737 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2738 if (IS_ERR(handle)) {
2739 ret = PTR_ERR(handle);
2740 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2741 "%ld pages, ino %lu; err %d", __func__,
2742 wbc->nr_to_write, inode->i_ino, ret);
2743 /* Release allocated io_end */
2744 ext4_put_io_end(mpd->io_submit.io_end);
2745 mpd->io_submit.io_end = NULL;
2750 trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
2751 ret = mpage_prepare_extent_to_map(mpd);
2752 if (!ret && mpd->map.m_len)
2753 ret = mpage_map_and_submit_extent(handle, mpd,
2756 * Caution: If the handle is synchronous,
2757 * ext4_journal_stop() can wait for transaction commit
2758 * to finish which may depend on writeback of pages to
2759 * complete or on page lock to be released. In that
2760 * case, we have to wait until after we have
2761 * submitted all the IO, released page locks we hold,
2762 * and dropped io_end reference (for extent conversion
2763 * to be able to complete) before stopping the handle.
2765 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2766 ext4_journal_stop(handle);
2770 /* Unlock pages we didn't use */
2771 mpage_release_unused_pages(mpd, give_up_on_write);
2772 /* Submit prepared bio */
2773 ext4_io_submit(&mpd->io_submit);
2776 * Drop our io_end reference we got from init. We have
2777 * to be careful and use deferred io_end finishing if
2778 * we are still holding the transaction as we can
2779 * release the last reference to io_end which may end
2780 * up doing unwritten extent conversion.
2783 ext4_put_io_end_defer(mpd->io_submit.io_end);
2784 ext4_journal_stop(handle);
2786 ext4_put_io_end(mpd->io_submit.io_end);
2787 mpd->io_submit.io_end = NULL;
2789 if (ret == -ENOSPC && sbi->s_journal) {
2791 * Commit the transaction which would
2792 * free blocks released in the transaction
2795 jbd2_journal_force_commit_nested(sbi->s_journal);
2799 /* Fatal error - ENOMEM, EIO... */
2804 blk_finish_plug(&plug);
2805 if (!ret && !cycled && wbc->nr_to_write > 0) {
2807 mpd->last_page = writeback_index - 1;
2808 mpd->first_page = 0;
2813 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2815 * Set the writeback_index so that range_cyclic
2816 * mode will write it back later
2818 mapping->writeback_index = mpd->first_page;
2821 trace_ext4_writepages_result(inode, wbc, ret,
2822 nr_to_write - wbc->nr_to_write);
2826 static int ext4_writepages(struct address_space *mapping,
2827 struct writeback_control *wbc)
2829 struct super_block *sb = mapping->host->i_sb;
2830 struct mpage_da_data mpd = {
2831 .inode = mapping->host,
2838 if (unlikely(ext4_forced_shutdown(sb)))
2841 alloc_ctx = ext4_writepages_down_read(sb);
2842 ret = ext4_do_writepages(&mpd);
2844 * For data=journal writeback we could have come across pages marked
2845 * for delayed dirtying (PageChecked) which were just added to the
2846 * running transaction. Try once more to get them to stable storage.
2848 if (!ret && mpd.journalled_more_data)
2849 ret = ext4_do_writepages(&mpd);
2850 ext4_writepages_up_read(sb, alloc_ctx);
2855 int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
2857 struct writeback_control wbc = {
2858 .sync_mode = WB_SYNC_ALL,
2859 .nr_to_write = LONG_MAX,
2860 .range_start = jinode->i_dirty_start,
2861 .range_end = jinode->i_dirty_end,
2863 struct mpage_da_data mpd = {
2864 .inode = jinode->i_vfs_inode,
2868 return ext4_do_writepages(&mpd);
2871 static int ext4_dax_writepages(struct address_space *mapping,
2872 struct writeback_control *wbc)
2875 long nr_to_write = wbc->nr_to_write;
2876 struct inode *inode = mapping->host;
2879 if (unlikely(ext4_forced_shutdown(inode->i_sb)))
2882 alloc_ctx = ext4_writepages_down_read(inode->i_sb);
2883 trace_ext4_writepages(inode, wbc);
2885 ret = dax_writeback_mapping_range(mapping,
2886 EXT4_SB(inode->i_sb)->s_daxdev, wbc);
2887 trace_ext4_writepages_result(inode, wbc, ret,
2888 nr_to_write - wbc->nr_to_write);
2889 ext4_writepages_up_read(inode->i_sb, alloc_ctx);
2893 static int ext4_nonda_switch(struct super_block *sb)
2895 s64 free_clusters, dirty_clusters;
2896 struct ext4_sb_info *sbi = EXT4_SB(sb);
2899 * switch to non delalloc mode if we are running low
2900 * on free block. The free block accounting via percpu
2901 * counters can get slightly wrong with percpu_counter_batch getting
2902 * accumulated on each CPU without updating global counters
2903 * Delalloc need an accurate free block accounting. So switch
2904 * to non delalloc when we are near to error range.
2907 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2909 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2911 * Start pushing delalloc when 1/2 of free blocks are dirty.
2913 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2914 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2916 if (2 * free_clusters < 3 * dirty_clusters ||
2917 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2919 * free block count is less than 150% of dirty blocks
2920 * or free blocks is less than watermark
2927 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2928 loff_t pos, unsigned len,
2929 struct page **pagep, void **fsdata)
2931 int ret, retries = 0;
2932 struct folio *folio;
2934 struct inode *inode = mapping->host;
2936 if (unlikely(ext4_forced_shutdown(inode->i_sb)))
2939 index = pos >> PAGE_SHIFT;
2941 if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
2942 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2943 return ext4_write_begin(file, mapping, pos,
2944 len, pagep, fsdata);
2946 *fsdata = (void *)0;
2947 trace_ext4_da_write_begin(inode, pos, len);
2949 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2950 ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
2959 folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
2960 mapping_gfp_mask(mapping));
2962 return PTR_ERR(folio);
2964 #ifdef CONFIG_FS_ENCRYPTION
2965 ret = ext4_block_write_begin(folio, pos, len, ext4_da_get_block_prep);
2967 ret = __block_write_begin(&folio->page, pos, len, ext4_da_get_block_prep);
2970 folio_unlock(folio);
2973 * block_write_begin may have instantiated a few blocks
2974 * outside i_size. Trim these off again. Don't need
2975 * i_size_read because we hold inode lock.
2977 if (pos + len > inode->i_size)
2978 ext4_truncate_failed_write(inode);
2980 if (ret == -ENOSPC &&
2981 ext4_should_retry_alloc(inode->i_sb, &retries))
2986 *pagep = &folio->page;
2991 * Check if we should update i_disksize
2992 * when write to the end of file but not require block allocation
2994 static int ext4_da_should_update_i_disksize(struct folio *folio,
2995 unsigned long offset)
2997 struct buffer_head *bh;
2998 struct inode *inode = folio->mapping->host;
3002 bh = folio_buffers(folio);
3003 idx = offset >> inode->i_blkbits;
3005 for (i = 0; i < idx; i++)
3006 bh = bh->b_this_page;
3008 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3013 static int ext4_da_do_write_end(struct address_space *mapping,
3014 loff_t pos, unsigned len, unsigned copied,
3015 struct folio *folio)
3017 struct inode *inode = mapping->host;
3018 loff_t old_size = inode->i_size;
3019 bool disksize_changed = false;
3022 if (unlikely(!folio_buffers(folio))) {
3023 folio_unlock(folio);
3028 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
3029 * flag, which all that's needed to trigger page writeback.
3031 copied = block_write_end(NULL, mapping, pos, len, copied,
3032 &folio->page, NULL);
3033 new_i_size = pos + copied;
3036 * It's important to update i_size while still holding folio lock,
3037 * because folio writeout could otherwise come in and zero beyond
3040 * Since we are holding inode lock, we are sure i_disksize <=
3041 * i_size. We also know that if i_disksize < i_size, there are
3042 * delalloc writes pending in the range up to i_size. If the end of
3043 * the current write is <= i_size, there's no need to touch
3044 * i_disksize since writeback will push i_disksize up to i_size
3045 * eventually. If the end of the current write is > i_size and
3046 * inside an allocated block which ext4_da_should_update_i_disksize()
3047 * checked, we need to update i_disksize here as certain
3048 * ext4_writepages() paths not allocating blocks and update i_disksize.
3050 if (new_i_size > inode->i_size) {
3053 i_size_write(inode, new_i_size);
3054 end = (new_i_size - 1) & (PAGE_SIZE - 1);
3055 if (copied && ext4_da_should_update_i_disksize(folio, end)) {
3056 ext4_update_i_disksize(inode, new_i_size);
3057 disksize_changed = true;
3061 folio_unlock(folio);
3065 pagecache_isize_extended(inode, old_size, pos);
3067 if (disksize_changed) {
3070 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3072 return PTR_ERR(handle);
3073 ext4_mark_inode_dirty(handle, inode);
3074 ext4_journal_stop(handle);
3080 static int ext4_da_write_end(struct file *file,
3081 struct address_space *mapping,
3082 loff_t pos, unsigned len, unsigned copied,
3083 struct page *page, void *fsdata)
3085 struct inode *inode = mapping->host;
3086 int write_mode = (int)(unsigned long)fsdata;
3087 struct folio *folio = page_folio(page);
3089 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3090 return ext4_write_end(file, mapping, pos,
3091 len, copied, &folio->page, fsdata);
3093 trace_ext4_da_write_end(inode, pos, len, copied);
3095 if (write_mode != CONVERT_INLINE_DATA &&
3096 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3097 ext4_has_inline_data(inode))
3098 return ext4_write_inline_data_end(inode, pos, len, copied,
3101 if (unlikely(copied < len) && !folio_test_uptodate(folio))
3104 return ext4_da_do_write_end(mapping, pos, len, copied, folio);
3108 * Force all delayed allocation blocks to be allocated for a given inode.
3110 int ext4_alloc_da_blocks(struct inode *inode)
3112 trace_ext4_alloc_da_blocks(inode);
3114 if (!EXT4_I(inode)->i_reserved_data_blocks)
3118 * We do something simple for now. The filemap_flush() will
3119 * also start triggering a write of the data blocks, which is
3120 * not strictly speaking necessary (and for users of
3121 * laptop_mode, not even desirable). However, to do otherwise
3122 * would require replicating code paths in:
3124 * ext4_writepages() ->
3125 * write_cache_pages() ---> (via passed in callback function)
3126 * __mpage_da_writepage() -->
3127 * mpage_add_bh_to_extent()
3128 * mpage_da_map_blocks()
3130 * The problem is that write_cache_pages(), located in
3131 * mm/page-writeback.c, marks pages clean in preparation for
3132 * doing I/O, which is not desirable if we're not planning on
3135 * We could call write_cache_pages(), and then redirty all of
3136 * the pages by calling redirty_page_for_writepage() but that
3137 * would be ugly in the extreme. So instead we would need to
3138 * replicate parts of the code in the above functions,
3139 * simplifying them because we wouldn't actually intend to
3140 * write out the pages, but rather only collect contiguous
3141 * logical block extents, call the multi-block allocator, and
3142 * then update the buffer heads with the block allocations.
3144 * For now, though, we'll cheat by calling filemap_flush(),
3145 * which will map the blocks, and start the I/O, but not
3146 * actually wait for the I/O to complete.
3148 return filemap_flush(inode->i_mapping);
3152 * bmap() is special. It gets used by applications such as lilo and by
3153 * the swapper to find the on-disk block of a specific piece of data.
3155 * Naturally, this is dangerous if the block concerned is still in the
3156 * journal. If somebody makes a swapfile on an ext4 data-journaling
3157 * filesystem and enables swap, then they may get a nasty shock when the
3158 * data getting swapped to that swapfile suddenly gets overwritten by
3159 * the original zero's written out previously to the journal and
3160 * awaiting writeback in the kernel's buffer cache.
3162 * So, if we see any bmap calls here on a modified, data-journaled file,
3163 * take extra steps to flush any blocks which might be in the cache.
3165 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3167 struct inode *inode = mapping->host;
3170 inode_lock_shared(inode);
3172 * We can get here for an inline file via the FIBMAP ioctl
3174 if (ext4_has_inline_data(inode))
3177 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3178 (test_opt(inode->i_sb, DELALLOC) ||
3179 ext4_should_journal_data(inode))) {
3181 * With delalloc or journalled data we want to sync the file so
3182 * that we can make sure we allocate blocks for file and data
3183 * is in place for the user to see it
3185 filemap_write_and_wait(mapping);
3188 ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3191 inode_unlock_shared(inode);
3195 static int ext4_read_folio(struct file *file, struct folio *folio)
3198 struct inode *inode = folio->mapping->host;
3200 trace_ext4_read_folio(inode, folio);
3202 if (ext4_has_inline_data(inode))
3203 ret = ext4_readpage_inline(inode, folio);
3206 return ext4_mpage_readpages(inode, NULL, folio);
3211 static void ext4_readahead(struct readahead_control *rac)
3213 struct inode *inode = rac->mapping->host;
3215 /* If the file has inline data, no need to do readahead. */
3216 if (ext4_has_inline_data(inode))
3219 ext4_mpage_readpages(inode, rac, NULL);
3222 static void ext4_invalidate_folio(struct folio *folio, size_t offset,
3225 trace_ext4_invalidate_folio(folio, offset, length);
3227 /* No journalling happens on data buffers when this function is used */
3228 WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
3230 block_invalidate_folio(folio, offset, length);
3233 static int __ext4_journalled_invalidate_folio(struct folio *folio,
3234 size_t offset, size_t length)
3236 journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3238 trace_ext4_journalled_invalidate_folio(folio, offset, length);
3241 * If it's a full truncate we just forget about the pending dirtying
3243 if (offset == 0 && length == folio_size(folio))
3244 folio_clear_checked(folio);
3246 return jbd2_journal_invalidate_folio(journal, folio, offset, length);
3249 /* Wrapper for aops... */
3250 static void ext4_journalled_invalidate_folio(struct folio *folio,
3254 WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3257 static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3259 struct inode *inode = folio->mapping->host;
3260 journal_t *journal = EXT4_JOURNAL(inode);
3262 trace_ext4_release_folio(inode, folio);
3264 /* Page has dirty journalled data -> cannot release */
3265 if (folio_test_checked(folio))
3268 return jbd2_journal_try_to_free_buffers(journal, folio);
3270 return try_to_free_buffers(folio);
3273 static bool ext4_inode_datasync_dirty(struct inode *inode)
3275 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3278 if (jbd2_transaction_committed(journal,
3279 EXT4_I(inode)->i_datasync_tid))
3281 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3282 return !list_empty(&EXT4_I(inode)->i_fc_list);
3286 /* Any metadata buffers to write? */
3287 if (!list_empty(&inode->i_mapping->i_private_list))
3289 return inode->i_state & I_DIRTY_DATASYNC;
3292 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3293 struct ext4_map_blocks *map, loff_t offset,
3294 loff_t length, unsigned int flags)
3296 u8 blkbits = inode->i_blkbits;
3299 * Writes that span EOF might trigger an I/O size update on completion,
3300 * so consider them to be dirty for the purpose of O_DSYNC, even if
3301 * there is no other metadata changes being made or are pending.
3304 if (ext4_inode_datasync_dirty(inode) ||
3305 offset + length > i_size_read(inode))
3306 iomap->flags |= IOMAP_F_DIRTY;
3308 if (map->m_flags & EXT4_MAP_NEW)
3309 iomap->flags |= IOMAP_F_NEW;
3311 if (flags & IOMAP_DAX)
3312 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3314 iomap->bdev = inode->i_sb->s_bdev;
3315 iomap->offset = (u64) map->m_lblk << blkbits;
3316 iomap->length = (u64) map->m_len << blkbits;
3318 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3319 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3320 iomap->flags |= IOMAP_F_MERGED;
3323 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3324 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3325 * set. In order for any allocated unwritten extents to be converted
3326 * into written extents correctly within the ->end_io() handler, we
3327 * need to ensure that the iomap->type is set appropriately. Hence, the
3328 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3331 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3332 iomap->type = IOMAP_UNWRITTEN;
3333 iomap->addr = (u64) map->m_pblk << blkbits;
3334 if (flags & IOMAP_DAX)
3335 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3336 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3337 iomap->type = IOMAP_MAPPED;
3338 iomap->addr = (u64) map->m_pblk << blkbits;
3339 if (flags & IOMAP_DAX)
3340 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3341 } else if (map->m_flags & EXT4_MAP_DELAYED) {
3342 iomap->type = IOMAP_DELALLOC;
3343 iomap->addr = IOMAP_NULL_ADDR;
3345 iomap->type = IOMAP_HOLE;
3346 iomap->addr = IOMAP_NULL_ADDR;
3350 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3354 u8 blkbits = inode->i_blkbits;
3355 int ret, dio_credits, m_flags = 0, retries = 0;
3358 * Trim the mapping request to the maximum value that we can map at
3359 * once for direct I/O.
3361 if (map->m_len > DIO_MAX_BLOCKS)
3362 map->m_len = DIO_MAX_BLOCKS;
3363 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3367 * Either we allocate blocks and then don't get an unwritten extent, so
3368 * in that case we have reserved enough credits. Or, the blocks are
3369 * already allocated and unwritten. In that case, the extent conversion
3370 * fits into the credits as well.
3372 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3374 return PTR_ERR(handle);
3377 * DAX and direct I/O are the only two operations that are currently
3378 * supported with IOMAP_WRITE.
3380 WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3381 if (flags & IOMAP_DAX)
3382 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3384 * We use i_size instead of i_disksize here because delalloc writeback
3385 * can complete at any point during the I/O and subsequently push the
3386 * i_disksize out to i_size. This could be beyond where direct I/O is
3387 * happening and thus expose allocated blocks to direct I/O reads.
3389 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3390 m_flags = EXT4_GET_BLOCKS_CREATE;
3391 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3392 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3394 ret = ext4_map_blocks(handle, inode, map, m_flags);
3397 * We cannot fill holes in indirect tree based inodes as that could
3398 * expose stale data in the case of a crash. Use the magic error code
3399 * to fallback to buffered I/O.
3401 if (!m_flags && !ret)
3404 ext4_journal_stop(handle);
3405 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3412 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3413 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3416 struct ext4_map_blocks map;
3417 u8 blkbits = inode->i_blkbits;
3419 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3422 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3426 * Calculate the first and last logical blocks respectively.
3428 map.m_lblk = offset >> blkbits;
3429 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3430 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3432 if (flags & IOMAP_WRITE) {
3434 * We check here if the blocks are already allocated, then we
3435 * don't need to start a journal txn and we can directly return
3436 * the mapping information. This could boost performance
3437 * especially in multi-threaded overwrite requests.
3439 if (offset + length <= i_size_read(inode)) {
3440 ret = ext4_map_blocks(NULL, inode, &map, 0);
3441 if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3444 ret = ext4_iomap_alloc(inode, &map, flags);
3446 ret = ext4_map_blocks(NULL, inode, &map, 0);
3453 * When inline encryption is enabled, sometimes I/O to an encrypted file
3454 * has to be broken up to guarantee DUN contiguity. Handle this by
3455 * limiting the length of the mapping returned.
3457 map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
3459 ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3464 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3465 loff_t length, unsigned flags, struct iomap *iomap,
3466 struct iomap *srcmap)
3471 * Even for writes we don't need to allocate blocks, so just pretend
3472 * we are reading to save overhead of starting a transaction.
3474 flags &= ~IOMAP_WRITE;
3475 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3476 WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
3480 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3481 ssize_t written, unsigned flags, struct iomap *iomap)
3484 * Check to see whether an error occurred while writing out the data to
3485 * the allocated blocks. If so, return the magic error code so that we
3486 * fallback to buffered I/O and attempt to complete the remainder of
3487 * the I/O. Any blocks that may have been allocated in preparation for
3488 * the direct I/O will be reused during buffered I/O.
3490 if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3496 const struct iomap_ops ext4_iomap_ops = {
3497 .iomap_begin = ext4_iomap_begin,
3498 .iomap_end = ext4_iomap_end,
3501 const struct iomap_ops ext4_iomap_overwrite_ops = {
3502 .iomap_begin = ext4_iomap_overwrite_begin,
3503 .iomap_end = ext4_iomap_end,
3506 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3507 loff_t length, unsigned int flags,
3508 struct iomap *iomap, struct iomap *srcmap)
3511 struct ext4_map_blocks map;
3512 u8 blkbits = inode->i_blkbits;
3514 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3517 if (ext4_has_inline_data(inode)) {
3518 ret = ext4_inline_data_iomap(inode, iomap);
3519 if (ret != -EAGAIN) {
3520 if (ret == 0 && offset >= iomap->length)
3527 * Calculate the first and last logical block respectively.
3529 map.m_lblk = offset >> blkbits;
3530 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3531 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3534 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3535 * So handle it here itself instead of querying ext4_map_blocks().
3536 * Since ext4_map_blocks() will warn about it and will return
3539 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3540 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3542 if (offset >= sbi->s_bitmap_maxbytes) {
3548 ret = ext4_map_blocks(NULL, inode, &map, 0);
3552 ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3557 const struct iomap_ops ext4_iomap_report_ops = {
3558 .iomap_begin = ext4_iomap_begin_report,
3562 * For data=journal mode, folio should be marked dirty only when it was
3563 * writeably mapped. When that happens, it was already attached to the
3564 * transaction and marked as jbddirty (we take care of this in
3565 * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
3566 * so we should have nothing to do here, except for the case when someone
3567 * had the page pinned and dirtied the page through this pin (e.g. by doing
3568 * direct IO to it). In that case we'd need to attach buffers here to the
3569 * transaction but we cannot due to lock ordering. We cannot just dirty the
3570 * folio and leave attached buffers clean, because the buffers' dirty state is
3571 * "definitive". We cannot just set the buffers dirty or jbddirty because all
3572 * the journalling code will explode. So what we do is to mark the folio
3573 * "pending dirty" and next time ext4_writepages() is called, attach buffers
3574 * to the transaction appropriately.
3576 static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3577 struct folio *folio)
3579 WARN_ON_ONCE(!folio_buffers(folio));
3580 if (folio_maybe_dma_pinned(folio))
3581 folio_set_checked(folio);
3582 return filemap_dirty_folio(mapping, folio);
3585 static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
3587 WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3588 WARN_ON_ONCE(!folio_buffers(folio));
3589 return block_dirty_folio(mapping, folio);
3592 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3593 struct file *file, sector_t *span)
3595 return iomap_swapfile_activate(sis, file, span,
3596 &ext4_iomap_report_ops);
3599 static const struct address_space_operations ext4_aops = {
3600 .read_folio = ext4_read_folio,
3601 .readahead = ext4_readahead,
3602 .writepages = ext4_writepages,
3603 .write_begin = ext4_write_begin,
3604 .write_end = ext4_write_end,
3605 .dirty_folio = ext4_dirty_folio,
3607 .invalidate_folio = ext4_invalidate_folio,
3608 .release_folio = ext4_release_folio,
3609 .migrate_folio = buffer_migrate_folio,
3610 .is_partially_uptodate = block_is_partially_uptodate,
3611 .error_remove_folio = generic_error_remove_folio,
3612 .swap_activate = ext4_iomap_swap_activate,
3615 static const struct address_space_operations ext4_journalled_aops = {
3616 .read_folio = ext4_read_folio,
3617 .readahead = ext4_readahead,
3618 .writepages = ext4_writepages,
3619 .write_begin = ext4_write_begin,
3620 .write_end = ext4_journalled_write_end,
3621 .dirty_folio = ext4_journalled_dirty_folio,
3623 .invalidate_folio = ext4_journalled_invalidate_folio,
3624 .release_folio = ext4_release_folio,
3625 .migrate_folio = buffer_migrate_folio_norefs,
3626 .is_partially_uptodate = block_is_partially_uptodate,
3627 .error_remove_folio = generic_error_remove_folio,
3628 .swap_activate = ext4_iomap_swap_activate,
3631 static const struct address_space_operations ext4_da_aops = {
3632 .read_folio = ext4_read_folio,
3633 .readahead = ext4_readahead,
3634 .writepages = ext4_writepages,
3635 .write_begin = ext4_da_write_begin,
3636 .write_end = ext4_da_write_end,
3637 .dirty_folio = ext4_dirty_folio,
3639 .invalidate_folio = ext4_invalidate_folio,
3640 .release_folio = ext4_release_folio,
3641 .migrate_folio = buffer_migrate_folio,
3642 .is_partially_uptodate = block_is_partially_uptodate,
3643 .error_remove_folio = generic_error_remove_folio,
3644 .swap_activate = ext4_iomap_swap_activate,
3647 static const struct address_space_operations ext4_dax_aops = {
3648 .writepages = ext4_dax_writepages,
3649 .dirty_folio = noop_dirty_folio,
3651 .swap_activate = ext4_iomap_swap_activate,
3654 void ext4_set_aops(struct inode *inode)
3656 switch (ext4_inode_journal_mode(inode)) {
3657 case EXT4_INODE_ORDERED_DATA_MODE:
3658 case EXT4_INODE_WRITEBACK_DATA_MODE:
3660 case EXT4_INODE_JOURNAL_DATA_MODE:
3661 inode->i_mapping->a_ops = &ext4_journalled_aops;
3667 inode->i_mapping->a_ops = &ext4_dax_aops;
3668 else if (test_opt(inode->i_sb, DELALLOC))
3669 inode->i_mapping->a_ops = &ext4_da_aops;
3671 inode->i_mapping->a_ops = &ext4_aops;
3675 * Here we can't skip an unwritten buffer even though it usually reads zero
3676 * because it might have data in pagecache (eg, if called from ext4_zero_range,
3677 * ext4_punch_hole, etc) which needs to be properly zeroed out. Otherwise a
3678 * racing writeback can come later and flush the stale pagecache to disk.
3680 static int __ext4_block_zero_page_range(handle_t *handle,
3681 struct address_space *mapping, loff_t from, loff_t length)
3683 ext4_fsblk_t index = from >> PAGE_SHIFT;
3684 unsigned offset = from & (PAGE_SIZE-1);
3685 unsigned blocksize, pos;
3687 struct inode *inode = mapping->host;
3688 struct buffer_head *bh;
3689 struct folio *folio;
3692 folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
3693 FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3694 mapping_gfp_constraint(mapping, ~__GFP_FS));
3696 return PTR_ERR(folio);
3698 blocksize = inode->i_sb->s_blocksize;
3700 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3702 bh = folio_buffers(folio);
3704 bh = create_empty_buffers(folio, blocksize, 0);
3706 /* Find the buffer that contains "offset" */
3708 while (offset >= pos) {
3709 bh = bh->b_this_page;
3713 if (buffer_freed(bh)) {
3714 BUFFER_TRACE(bh, "freed: skip");
3717 if (!buffer_mapped(bh)) {
3718 BUFFER_TRACE(bh, "unmapped");
3719 ext4_get_block(inode, iblock, bh, 0);
3720 /* unmapped? It's a hole - nothing to do */
3721 if (!buffer_mapped(bh)) {
3722 BUFFER_TRACE(bh, "still unmapped");
3727 /* Ok, it's mapped. Make sure it's up-to-date */
3728 if (folio_test_uptodate(folio))
3729 set_buffer_uptodate(bh);
3731 if (!buffer_uptodate(bh)) {
3732 err = ext4_read_bh_lock(bh, 0, true);
3735 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3736 /* We expect the key to be set. */
3737 BUG_ON(!fscrypt_has_encryption_key(inode));
3738 err = fscrypt_decrypt_pagecache_blocks(folio,
3742 clear_buffer_uptodate(bh);
3747 if (ext4_should_journal_data(inode)) {
3748 BUFFER_TRACE(bh, "get write access");
3749 err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3754 folio_zero_range(folio, offset, length);
3755 BUFFER_TRACE(bh, "zeroed end of block");
3757 if (ext4_should_journal_data(inode)) {
3758 err = ext4_dirty_journalled_data(handle, bh);
3761 mark_buffer_dirty(bh);
3762 if (ext4_should_order_data(inode))
3763 err = ext4_jbd2_inode_add_write(handle, inode, from,
3768 folio_unlock(folio);
3774 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3775 * starting from file offset 'from'. The range to be zero'd must
3776 * be contained with in one block. If the specified range exceeds
3777 * the end of the block it will be shortened to end of the block
3778 * that corresponds to 'from'
3780 static int ext4_block_zero_page_range(handle_t *handle,
3781 struct address_space *mapping, loff_t from, loff_t length)
3783 struct inode *inode = mapping->host;
3784 unsigned offset = from & (PAGE_SIZE-1);
3785 unsigned blocksize = inode->i_sb->s_blocksize;
3786 unsigned max = blocksize - (offset & (blocksize - 1));
3789 * correct length if it does not fall between
3790 * 'from' and the end of the block
3792 if (length > max || length < 0)
3795 if (IS_DAX(inode)) {
3796 return dax_zero_range(inode, from, length, NULL,
3799 return __ext4_block_zero_page_range(handle, mapping, from, length);
3803 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3804 * up to the end of the block which corresponds to `from'.
3805 * This required during truncate. We need to physically zero the tail end
3806 * of that block so it doesn't yield old data if the file is later grown.
3808 static int ext4_block_truncate_page(handle_t *handle,
3809 struct address_space *mapping, loff_t from)
3811 unsigned offset = from & (PAGE_SIZE-1);
3814 struct inode *inode = mapping->host;
3816 /* If we are processing an encrypted inode during orphan list handling */
3817 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3820 blocksize = inode->i_sb->s_blocksize;
3821 length = blocksize - (offset & (blocksize - 1));
3823 return ext4_block_zero_page_range(handle, mapping, from, length);
3826 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3827 loff_t lstart, loff_t length)
3829 struct super_block *sb = inode->i_sb;
3830 struct address_space *mapping = inode->i_mapping;
3831 unsigned partial_start, partial_end;
3832 ext4_fsblk_t start, end;
3833 loff_t byte_end = (lstart + length - 1);
3836 partial_start = lstart & (sb->s_blocksize - 1);
3837 partial_end = byte_end & (sb->s_blocksize - 1);
3839 start = lstart >> sb->s_blocksize_bits;
3840 end = byte_end >> sb->s_blocksize_bits;
3842 /* Handle partial zero within the single block */
3844 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3845 err = ext4_block_zero_page_range(handle, mapping,
3849 /* Handle partial zero out on the start of the range */
3850 if (partial_start) {
3851 err = ext4_block_zero_page_range(handle, mapping,
3852 lstart, sb->s_blocksize);
3856 /* Handle partial zero out on the end of the range */
3857 if (partial_end != sb->s_blocksize - 1)
3858 err = ext4_block_zero_page_range(handle, mapping,
3859 byte_end - partial_end,
3864 int ext4_can_truncate(struct inode *inode)
3866 if (S_ISREG(inode->i_mode))
3868 if (S_ISDIR(inode->i_mode))
3870 if (S_ISLNK(inode->i_mode))
3871 return !ext4_inode_is_fast_symlink(inode);
3876 * We have to make sure i_disksize gets properly updated before we truncate
3877 * page cache due to hole punching or zero range. Otherwise i_disksize update
3878 * can get lost as it may have been postponed to submission of writeback but
3879 * that will never happen after we truncate page cache.
3881 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3887 loff_t size = i_size_read(inode);
3889 WARN_ON(!inode_is_locked(inode));
3890 if (offset > size || offset + len < size)
3893 if (EXT4_I(inode)->i_disksize >= size)
3896 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3898 return PTR_ERR(handle);
3899 ext4_update_i_disksize(inode, size);
3900 ret = ext4_mark_inode_dirty(handle, inode);
3901 ext4_journal_stop(handle);
3906 static void ext4_wait_dax_page(struct inode *inode)
3908 filemap_invalidate_unlock(inode->i_mapping);
3910 filemap_invalidate_lock(inode->i_mapping);
3913 int ext4_break_layouts(struct inode *inode)
3918 if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3922 page = dax_layout_busy_page(inode->i_mapping);
3926 error = ___wait_var_event(&page->_refcount,
3927 atomic_read(&page->_refcount) == 1,
3928 TASK_INTERRUPTIBLE, 0, 0,
3929 ext4_wait_dax_page(inode));
3930 } while (error == 0);
3936 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3937 * associated with the given offset and length
3939 * @inode: File inode
3940 * @offset: The offset where the hole will begin
3941 * @len: The length of the hole
3943 * Returns: 0 on success or negative on failure
3946 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3948 struct inode *inode = file_inode(file);
3949 struct super_block *sb = inode->i_sb;
3950 ext4_lblk_t first_block, stop_block;
3951 struct address_space *mapping = inode->i_mapping;
3952 loff_t first_block_offset, last_block_offset, max_length;
3953 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3955 unsigned int credits;
3956 int ret = 0, ret2 = 0;
3958 trace_ext4_punch_hole(inode, offset, length, 0);
3961 * Write out all dirty pages to avoid race conditions
3962 * Then release them.
3964 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3965 ret = filemap_write_and_wait_range(mapping, offset,
3966 offset + length - 1);
3973 /* No need to punch hole beyond i_size */
3974 if (offset >= inode->i_size)
3978 * If the hole extends beyond i_size, set the hole
3979 * to end after the page that contains i_size
3981 if (offset + length > inode->i_size) {
3982 length = inode->i_size +
3983 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
3988 * For punch hole the length + offset needs to be within one block
3989 * before last range. Adjust the length if it goes beyond that limit.
3991 max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
3992 if (offset + length > max_length)
3993 length = max_length - offset;
3995 if (offset & (sb->s_blocksize - 1) ||
3996 (offset + length) & (sb->s_blocksize - 1)) {
3998 * Attach jinode to inode for jbd2 if we do any zeroing of
4001 ret = ext4_inode_attach_jinode(inode);
4007 /* Wait all existing dio workers, newcomers will block on i_rwsem */
4008 inode_dio_wait(inode);
4010 ret = file_modified(file);
4015 * Prevent page faults from reinstantiating pages we have released from
4018 filemap_invalidate_lock(mapping);
4020 ret = ext4_break_layouts(inode);
4024 first_block_offset = round_up(offset, sb->s_blocksize);
4025 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4027 /* Now release the pages and zero block aligned part of pages*/
4028 if (last_block_offset > first_block_offset) {
4029 ret = ext4_update_disksize_before_punch(inode, offset, length);
4032 truncate_pagecache_range(inode, first_block_offset,
4036 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4037 credits = ext4_writepage_trans_blocks(inode);
4039 credits = ext4_blocks_for_truncate(inode);
4040 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4041 if (IS_ERR(handle)) {
4042 ret = PTR_ERR(handle);
4043 ext4_std_error(sb, ret);
4047 ret = ext4_zero_partial_blocks(handle, inode, offset,
4052 first_block = (offset + sb->s_blocksize - 1) >>
4053 EXT4_BLOCK_SIZE_BITS(sb);
4054 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4056 /* If there are blocks to remove, do it */
4057 if (stop_block > first_block) {
4058 ext4_lblk_t hole_len = stop_block - first_block;
4060 down_write(&EXT4_I(inode)->i_data_sem);
4061 ext4_discard_preallocations(inode);
4063 ext4_es_remove_extent(inode, first_block, hole_len);
4065 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4066 ret = ext4_ext_remove_space(inode, first_block,
4069 ret = ext4_ind_remove_space(handle, inode, first_block,
4072 ext4_es_insert_extent(inode, first_block, hole_len, ~0,
4073 EXTENT_STATUS_HOLE);
4074 up_write(&EXT4_I(inode)->i_data_sem);
4076 ext4_fc_track_range(handle, inode, first_block, stop_block);
4078 ext4_handle_sync(handle);
4080 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
4081 ret2 = ext4_mark_inode_dirty(handle, inode);
4085 ext4_update_inode_fsync_trans(handle, inode, 1);
4087 ext4_journal_stop(handle);
4089 filemap_invalidate_unlock(mapping);
4091 inode_unlock(inode);
4095 int ext4_inode_attach_jinode(struct inode *inode)
4097 struct ext4_inode_info *ei = EXT4_I(inode);
4098 struct jbd2_inode *jinode;
4100 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4103 jinode = jbd2_alloc_inode(GFP_KERNEL);
4104 spin_lock(&inode->i_lock);
4107 spin_unlock(&inode->i_lock);
4110 ei->jinode = jinode;
4111 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4114 spin_unlock(&inode->i_lock);
4115 if (unlikely(jinode != NULL))
4116 jbd2_free_inode(jinode);
4123 * We block out ext4_get_block() block instantiations across the entire
4124 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4125 * simultaneously on behalf of the same inode.
4127 * As we work through the truncate and commit bits of it to the journal there
4128 * is one core, guiding principle: the file's tree must always be consistent on
4129 * disk. We must be able to restart the truncate after a crash.
4131 * The file's tree may be transiently inconsistent in memory (although it
4132 * probably isn't), but whenever we close off and commit a journal transaction,
4133 * the contents of (the filesystem + the journal) must be consistent and
4134 * restartable. It's pretty simple, really: bottom up, right to left (although
4135 * left-to-right works OK too).
4137 * Note that at recovery time, journal replay occurs *before* the restart of
4138 * truncate against the orphan inode list.
4140 * The committed inode has the new, desired i_size (which is the same as
4141 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4142 * that this inode's truncate did not complete and it will again call
4143 * ext4_truncate() to have another go. So there will be instantiated blocks
4144 * to the right of the truncation point in a crashed ext4 filesystem. But
4145 * that's fine - as long as they are linked from the inode, the post-crash
4146 * ext4_truncate() run will find them and release them.
4148 int ext4_truncate(struct inode *inode)
4150 struct ext4_inode_info *ei = EXT4_I(inode);
4151 unsigned int credits;
4154 struct address_space *mapping = inode->i_mapping;
4157 * There is a possibility that we're either freeing the inode
4158 * or it's a completely new inode. In those cases we might not
4159 * have i_rwsem locked because it's not necessary.
4161 if (!(inode->i_state & (I_NEW|I_FREEING)))
4162 WARN_ON(!inode_is_locked(inode));
4163 trace_ext4_truncate_enter(inode);
4165 if (!ext4_can_truncate(inode))
4168 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4169 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4171 if (ext4_has_inline_data(inode)) {
4174 err = ext4_inline_data_truncate(inode, &has_inline);
4175 if (err || has_inline)
4179 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4180 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4181 err = ext4_inode_attach_jinode(inode);
4186 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4187 credits = ext4_writepage_trans_blocks(inode);
4189 credits = ext4_blocks_for_truncate(inode);
4191 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4192 if (IS_ERR(handle)) {
4193 err = PTR_ERR(handle);
4197 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4198 ext4_block_truncate_page(handle, mapping, inode->i_size);
4201 * We add the inode to the orphan list, so that if this
4202 * truncate spans multiple transactions, and we crash, we will
4203 * resume the truncate when the filesystem recovers. It also
4204 * marks the inode dirty, to catch the new size.
4206 * Implication: the file must always be in a sane, consistent
4207 * truncatable state while each transaction commits.
4209 err = ext4_orphan_add(handle, inode);
4213 down_write(&EXT4_I(inode)->i_data_sem);
4215 ext4_discard_preallocations(inode);
4217 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4218 err = ext4_ext_truncate(handle, inode);
4220 ext4_ind_truncate(handle, inode);
4222 up_write(&ei->i_data_sem);
4227 ext4_handle_sync(handle);
4231 * If this was a simple ftruncate() and the file will remain alive,
4232 * then we need to clear up the orphan record which we created above.
4233 * However, if this was a real unlink then we were called by
4234 * ext4_evict_inode(), and we allow that function to clean up the
4235 * orphan info for us.
4238 ext4_orphan_del(handle, inode);
4240 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
4241 err2 = ext4_mark_inode_dirty(handle, inode);
4242 if (unlikely(err2 && !err))
4244 ext4_journal_stop(handle);
4247 trace_ext4_truncate_exit(inode);
4251 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4253 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4254 return inode_peek_iversion_raw(inode);
4256 return inode_peek_iversion(inode);
4259 static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
4260 struct ext4_inode_info *ei)
4262 struct inode *inode = &(ei->vfs_inode);
4263 u64 i_blocks = READ_ONCE(inode->i_blocks);
4264 struct super_block *sb = inode->i_sb;
4266 if (i_blocks <= ~0U) {
4268 * i_blocks can be represented in a 32 bit variable
4269 * as multiple of 512 bytes
4271 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4272 raw_inode->i_blocks_high = 0;
4273 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4278 * This should never happen since sb->s_maxbytes should not have
4279 * allowed this, sb->s_maxbytes was set according to the huge_file
4280 * feature in ext4_fill_super().
4282 if (!ext4_has_feature_huge_file(sb))
4283 return -EFSCORRUPTED;
4285 if (i_blocks <= 0xffffffffffffULL) {
4287 * i_blocks can be represented in a 48 bit variable
4288 * as multiple of 512 bytes
4290 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4291 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4292 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4294 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4295 /* i_block is stored in file system block size */
4296 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4297 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4298 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4303 static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
4305 struct ext4_inode_info *ei = EXT4_I(inode);
4312 err = ext4_inode_blocks_set(raw_inode, ei);
4314 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4315 i_uid = i_uid_read(inode);
4316 i_gid = i_gid_read(inode);
4317 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4318 if (!(test_opt(inode->i_sb, NO_UID32))) {
4319 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4320 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4322 * Fix up interoperability with old kernels. Otherwise,
4323 * old inodes get re-used with the upper 16 bits of the
4326 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4327 raw_inode->i_uid_high = 0;
4328 raw_inode->i_gid_high = 0;
4330 raw_inode->i_uid_high =
4331 cpu_to_le16(high_16_bits(i_uid));
4332 raw_inode->i_gid_high =
4333 cpu_to_le16(high_16_bits(i_gid));
4336 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4337 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4338 raw_inode->i_uid_high = 0;
4339 raw_inode->i_gid_high = 0;
4341 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4343 EXT4_INODE_SET_CTIME(inode, raw_inode);
4344 EXT4_INODE_SET_MTIME(inode, raw_inode);
4345 EXT4_INODE_SET_ATIME(inode, raw_inode);
4346 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4348 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4349 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4350 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4351 raw_inode->i_file_acl_high =
4352 cpu_to_le16(ei->i_file_acl >> 32);
4353 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4354 ext4_isize_set(raw_inode, ei->i_disksize);
4356 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4357 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4358 if (old_valid_dev(inode->i_rdev)) {
4359 raw_inode->i_block[0] =
4360 cpu_to_le32(old_encode_dev(inode->i_rdev));
4361 raw_inode->i_block[1] = 0;
4363 raw_inode->i_block[0] = 0;
4364 raw_inode->i_block[1] =
4365 cpu_to_le32(new_encode_dev(inode->i_rdev));
4366 raw_inode->i_block[2] = 0;
4368 } else if (!ext4_has_inline_data(inode)) {
4369 for (block = 0; block < EXT4_N_BLOCKS; block++)
4370 raw_inode->i_block[block] = ei->i_data[block];
4373 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4374 u64 ivers = ext4_inode_peek_iversion(inode);
4376 raw_inode->i_disk_version = cpu_to_le32(ivers);
4377 if (ei->i_extra_isize) {
4378 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4379 raw_inode->i_version_hi =
4380 cpu_to_le32(ivers >> 32);
4381 raw_inode->i_extra_isize =
4382 cpu_to_le16(ei->i_extra_isize);
4386 if (i_projid != EXT4_DEF_PROJID &&
4387 !ext4_has_feature_project(inode->i_sb))
4388 err = err ?: -EFSCORRUPTED;
4390 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4391 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4392 raw_inode->i_projid = cpu_to_le32(i_projid);
4394 ext4_inode_csum_set(inode, raw_inode, ei);
4399 * ext4_get_inode_loc returns with an extra refcount against the inode's
4400 * underlying buffer_head on success. If we pass 'inode' and it does not
4401 * have in-inode xattr, we have all inode data in memory that is needed
4402 * to recreate the on-disk version of this inode.
4404 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4405 struct inode *inode, struct ext4_iloc *iloc,
4406 ext4_fsblk_t *ret_block)
4408 struct ext4_group_desc *gdp;
4409 struct buffer_head *bh;
4411 struct blk_plug plug;
4412 int inodes_per_block, inode_offset;
4415 if (ino < EXT4_ROOT_INO ||
4416 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4417 return -EFSCORRUPTED;
4419 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4420 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4425 * Figure out the offset within the block group inode table
4427 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4428 inode_offset = ((ino - 1) %
4429 EXT4_INODES_PER_GROUP(sb));
4430 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4432 block = ext4_inode_table(sb, gdp);
4433 if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4434 (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4435 ext4_error(sb, "Invalid inode table block %llu in "
4436 "block_group %u", block, iloc->block_group);
4437 return -EFSCORRUPTED;
4439 block += (inode_offset / inodes_per_block);
4441 bh = sb_getblk(sb, block);
4444 if (ext4_buffer_uptodate(bh))
4448 if (ext4_buffer_uptodate(bh)) {
4449 /* Someone brought it uptodate while we waited */
4455 * If we have all information of the inode in memory and this
4456 * is the only valid inode in the block, we need not read the
4459 if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4460 struct buffer_head *bitmap_bh;
4463 start = inode_offset & ~(inodes_per_block - 1);
4465 /* Is the inode bitmap in cache? */
4466 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4467 if (unlikely(!bitmap_bh))
4471 * If the inode bitmap isn't in cache then the
4472 * optimisation may end up performing two reads instead
4473 * of one, so skip it.
4475 if (!buffer_uptodate(bitmap_bh)) {
4479 for (i = start; i < start + inodes_per_block; i++) {
4480 if (i == inode_offset)
4482 if (ext4_test_bit(i, bitmap_bh->b_data))
4486 if (i == start + inodes_per_block) {
4487 struct ext4_inode *raw_inode =
4488 (struct ext4_inode *) (bh->b_data + iloc->offset);
4490 /* all other inodes are free, so skip I/O */
4491 memset(bh->b_data, 0, bh->b_size);
4492 if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4493 ext4_fill_raw_inode(inode, raw_inode);
4494 set_buffer_uptodate(bh);
4502 * If we need to do any I/O, try to pre-readahead extra
4503 * blocks from the inode table.
4505 blk_start_plug(&plug);
4506 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4507 ext4_fsblk_t b, end, table;
4509 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4511 table = ext4_inode_table(sb, gdp);
4512 /* s_inode_readahead_blks is always a power of 2 */
4513 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4517 num = EXT4_INODES_PER_GROUP(sb);
4518 if (ext4_has_group_desc_csum(sb))
4519 num -= ext4_itable_unused_count(sb, gdp);
4520 table += num / inodes_per_block;
4524 ext4_sb_breadahead_unmovable(sb, b++);
4528 * There are other valid inodes in the buffer, this inode
4529 * has in-inode xattrs, or we don't have this inode in memory.
4530 * Read the block from disk.
4532 trace_ext4_load_inode(sb, ino);
4533 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4534 blk_finish_plug(&plug);
4536 ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4537 if (!buffer_uptodate(bh)) {
4548 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4549 struct ext4_iloc *iloc)
4551 ext4_fsblk_t err_blk = 0;
4554 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
4558 ext4_error_inode_block(inode, err_blk, EIO,
4559 "unable to read itable block");
4564 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4566 ext4_fsblk_t err_blk = 0;
4569 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4573 ext4_error_inode_block(inode, err_blk, EIO,
4574 "unable to read itable block");
4580 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4581 struct ext4_iloc *iloc)
4583 return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4586 static bool ext4_should_enable_dax(struct inode *inode)
4588 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4590 if (test_opt2(inode->i_sb, DAX_NEVER))
4592 if (!S_ISREG(inode->i_mode))
4594 if (ext4_should_journal_data(inode))
4596 if (ext4_has_inline_data(inode))
4598 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4600 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4602 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4604 if (test_opt(inode->i_sb, DAX_ALWAYS))
4607 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4610 void ext4_set_inode_flags(struct inode *inode, bool init)
4612 unsigned int flags = EXT4_I(inode)->i_flags;
4613 unsigned int new_fl = 0;
4615 WARN_ON_ONCE(IS_DAX(inode) && init);
4617 if (flags & EXT4_SYNC_FL)
4619 if (flags & EXT4_APPEND_FL)
4621 if (flags & EXT4_IMMUTABLE_FL)
4622 new_fl |= S_IMMUTABLE;
4623 if (flags & EXT4_NOATIME_FL)
4624 new_fl |= S_NOATIME;
4625 if (flags & EXT4_DIRSYNC_FL)
4626 new_fl |= S_DIRSYNC;
4628 /* Because of the way inode_set_flags() works we must preserve S_DAX
4629 * here if already set. */
4630 new_fl |= (inode->i_flags & S_DAX);
4631 if (init && ext4_should_enable_dax(inode))
4634 if (flags & EXT4_ENCRYPT_FL)
4635 new_fl |= S_ENCRYPTED;
4636 if (flags & EXT4_CASEFOLD_FL)
4637 new_fl |= S_CASEFOLD;
4638 if (flags & EXT4_VERITY_FL)
4640 inode_set_flags(inode, new_fl,
4641 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4642 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4645 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4646 struct ext4_inode_info *ei)
4649 struct inode *inode = &(ei->vfs_inode);
4650 struct super_block *sb = inode->i_sb;
4652 if (ext4_has_feature_huge_file(sb)) {
4653 /* we are using combined 48 bit field */
4654 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4655 le32_to_cpu(raw_inode->i_blocks_lo);
4656 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4657 /* i_blocks represent file system block size */
4658 return i_blocks << (inode->i_blkbits - 9);
4663 return le32_to_cpu(raw_inode->i_blocks_lo);
4667 static inline int ext4_iget_extra_inode(struct inode *inode,
4668 struct ext4_inode *raw_inode,
4669 struct ext4_inode_info *ei)
4671 __le32 *magic = (void *)raw_inode +
4672 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4674 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
4675 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4678 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4679 err = ext4_find_inline_data_nolock(inode);
4680 if (!err && ext4_has_inline_data(inode))
4681 ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4684 EXT4_I(inode)->i_inline_off = 0;
4688 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4690 if (!ext4_has_feature_project(inode->i_sb))
4692 *projid = EXT4_I(inode)->i_projid;
4697 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4698 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4701 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4703 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4704 inode_set_iversion_raw(inode, val);
4706 inode_set_iversion_queried(inode, val);
4709 static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)
4712 if (flags & EXT4_IGET_EA_INODE) {
4713 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4714 return "missing EA_INODE flag";
4715 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4716 EXT4_I(inode)->i_file_acl)
4717 return "ea_inode with extended attributes";
4719 if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4720 return "unexpected EA_INODE flag";
4722 if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
4723 return "unexpected bad inode w/o EXT4_IGET_BAD";
4727 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4728 ext4_iget_flags flags, const char *function,
4731 struct ext4_iloc iloc;
4732 struct ext4_inode *raw_inode;
4733 struct ext4_inode_info *ei;
4734 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
4735 struct inode *inode;
4736 const char *err_str;
4737 journal_t *journal = EXT4_SB(sb)->s_journal;
4745 if ((!(flags & EXT4_IGET_SPECIAL) &&
4746 ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4747 ino == le32_to_cpu(es->s_usr_quota_inum) ||
4748 ino == le32_to_cpu(es->s_grp_quota_inum) ||
4749 ino == le32_to_cpu(es->s_prj_quota_inum) ||
4750 ino == le32_to_cpu(es->s_orphan_file_inum))) ||
4751 (ino < EXT4_ROOT_INO) ||
4752 (ino > le32_to_cpu(es->s_inodes_count))) {
4753 if (flags & EXT4_IGET_HANDLE)
4754 return ERR_PTR(-ESTALE);
4755 __ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
4756 "inode #%lu: comm %s: iget: illegal inode #",
4757 ino, current->comm);
4758 return ERR_PTR(-EFSCORRUPTED);
4761 inode = iget_locked(sb, ino);
4763 return ERR_PTR(-ENOMEM);
4764 if (!(inode->i_state & I_NEW)) {
4765 if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4766 ext4_error_inode(inode, function, line, 0, err_str);
4768 return ERR_PTR(-EFSCORRUPTED);
4776 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4779 raw_inode = ext4_raw_inode(&iloc);
4781 if ((flags & EXT4_IGET_HANDLE) &&
4782 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4787 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4788 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4789 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4790 EXT4_INODE_SIZE(inode->i_sb) ||
4791 (ei->i_extra_isize & 3)) {
4792 ext4_error_inode(inode, function, line, 0,
4793 "iget: bad extra_isize %u "
4796 EXT4_INODE_SIZE(inode->i_sb));
4797 ret = -EFSCORRUPTED;
4801 ei->i_extra_isize = 0;
4803 /* Precompute checksum seed for inode metadata */
4804 if (ext4_has_metadata_csum(sb)) {
4805 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4807 __le32 inum = cpu_to_le32(inode->i_ino);
4808 __le32 gen = raw_inode->i_generation;
4809 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4811 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4815 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4816 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4817 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4818 ext4_error_inode_err(inode, function, line, 0,
4819 EFSBADCRC, "iget: checksum invalid");
4824 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4825 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4826 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4827 if (ext4_has_feature_project(sb) &&
4828 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4829 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4830 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4832 i_projid = EXT4_DEF_PROJID;
4834 if (!(test_opt(inode->i_sb, NO_UID32))) {
4835 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4836 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4838 i_uid_write(inode, i_uid);
4839 i_gid_write(inode, i_gid);
4840 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4841 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4843 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4844 ei->i_inline_off = 0;
4845 ei->i_dir_start_lookup = 0;
4846 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4847 /* We now have enough fields to check if the inode was active or not.
4848 * This is needed because nfsd might try to access dead inodes
4849 * the test is that same one that e2fsck uses
4850 * NeilBrown 1999oct15
4852 if (inode->i_nlink == 0) {
4853 if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4854 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4855 ino != EXT4_BOOT_LOADER_INO) {
4856 /* this inode is deleted or unallocated */
4857 if (flags & EXT4_IGET_SPECIAL) {
4858 ext4_error_inode(inode, function, line, 0,
4859 "iget: special inode unallocated");
4860 ret = -EFSCORRUPTED;
4865 /* The only unlinked inodes we let through here have
4866 * valid i_mode and are being read by the orphan
4867 * recovery code: that's fine, we're about to complete
4868 * the process of deleting those.
4869 * OR it is the EXT4_BOOT_LOADER_INO which is
4870 * not initialized on a new filesystem. */
4872 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4873 ext4_set_inode_flags(inode, true);
4874 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4875 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4876 if (ext4_has_feature_64bit(sb))
4878 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4879 inode->i_size = ext4_isize(sb, raw_inode);
4880 if ((size = i_size_read(inode)) < 0) {
4881 ext4_error_inode(inode, function, line, 0,
4882 "iget: bad i_size value: %lld", size);
4883 ret = -EFSCORRUPTED;
4887 * If dir_index is not enabled but there's dir with INDEX flag set,
4888 * we'd normally treat htree data as empty space. But with metadata
4889 * checksumming that corrupts checksums so forbid that.
4891 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4892 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4893 ext4_error_inode(inode, function, line, 0,
4894 "iget: Dir with htree data on filesystem without dir_index feature.");
4895 ret = -EFSCORRUPTED;
4898 ei->i_disksize = inode->i_size;
4900 ei->i_reserved_quota = 0;
4902 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4903 ei->i_block_group = iloc.block_group;
4904 ei->i_last_alloc_group = ~0;
4906 * NOTE! The in-memory inode i_data array is in little-endian order
4907 * even on big-endian machines: we do NOT byteswap the block numbers!
4909 for (block = 0; block < EXT4_N_BLOCKS; block++)
4910 ei->i_data[block] = raw_inode->i_block[block];
4911 INIT_LIST_HEAD(&ei->i_orphan);
4912 ext4_fc_init_inode(&ei->vfs_inode);
4915 * Set transaction id's of transactions that have to be committed
4916 * to finish f[data]sync. We set them to currently running transaction
4917 * as we cannot be sure that the inode or some of its metadata isn't
4918 * part of the transaction - the inode could have been reclaimed and
4919 * now it is reread from disk.
4922 transaction_t *transaction;
4925 read_lock(&journal->j_state_lock);
4926 if (journal->j_running_transaction)
4927 transaction = journal->j_running_transaction;
4929 transaction = journal->j_committing_transaction;
4931 tid = transaction->t_tid;
4933 tid = journal->j_commit_sequence;
4934 read_unlock(&journal->j_state_lock);
4935 ei->i_sync_tid = tid;
4936 ei->i_datasync_tid = tid;
4939 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4940 if (ei->i_extra_isize == 0) {
4941 /* The extra space is currently unused. Use it. */
4942 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4943 ei->i_extra_isize = sizeof(struct ext4_inode) -
4944 EXT4_GOOD_OLD_INODE_SIZE;
4946 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4952 EXT4_INODE_GET_CTIME(inode, raw_inode);
4953 EXT4_INODE_GET_ATIME(inode, raw_inode);
4954 EXT4_INODE_GET_MTIME(inode, raw_inode);
4955 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4957 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4958 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4960 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4961 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4963 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4965 ext4_inode_set_iversion_queried(inode, ivers);
4969 if (ei->i_file_acl &&
4970 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4971 ext4_error_inode(inode, function, line, 0,
4972 "iget: bad extended attribute block %llu",
4974 ret = -EFSCORRUPTED;
4976 } else if (!ext4_has_inline_data(inode)) {
4977 /* validate the block references in the inode */
4978 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4979 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4980 (S_ISLNK(inode->i_mode) &&
4981 !ext4_inode_is_fast_symlink(inode)))) {
4982 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4983 ret = ext4_ext_check_inode(inode);
4985 ret = ext4_ind_check_inode(inode);
4991 if (S_ISREG(inode->i_mode)) {
4992 inode->i_op = &ext4_file_inode_operations;
4993 inode->i_fop = &ext4_file_operations;
4994 ext4_set_aops(inode);
4995 } else if (S_ISDIR(inode->i_mode)) {
4996 inode->i_op = &ext4_dir_inode_operations;
4997 inode->i_fop = &ext4_dir_operations;
4998 } else if (S_ISLNK(inode->i_mode)) {
4999 /* VFS does not allow setting these so must be corruption */
5000 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
5001 ext4_error_inode(inode, function, line, 0,
5002 "iget: immutable or append flags "
5003 "not allowed on symlinks");
5004 ret = -EFSCORRUPTED;
5007 if (IS_ENCRYPTED(inode)) {
5008 inode->i_op = &ext4_encrypted_symlink_inode_operations;
5009 } else if (ext4_inode_is_fast_symlink(inode)) {
5010 inode->i_link = (char *)ei->i_data;
5011 inode->i_op = &ext4_fast_symlink_inode_operations;
5012 nd_terminate_link(ei->i_data, inode->i_size,
5013 sizeof(ei->i_data) - 1);
5015 inode->i_op = &ext4_symlink_inode_operations;
5017 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5018 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5019 inode->i_op = &ext4_special_inode_operations;
5020 if (raw_inode->i_block[0])
5021 init_special_inode(inode, inode->i_mode,
5022 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5024 init_special_inode(inode, inode->i_mode,
5025 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5026 } else if (ino == EXT4_BOOT_LOADER_INO) {
5027 make_bad_inode(inode);
5029 ret = -EFSCORRUPTED;
5030 ext4_error_inode(inode, function, line, 0,
5031 "iget: bogus i_mode (%o)", inode->i_mode);
5034 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
5035 ext4_error_inode(inode, function, line, 0,
5036 "casefold flag without casefold feature");
5037 ret = -EFSCORRUPTED;
5040 if ((err_str = check_igot_inode(inode, flags)) != NULL) {
5041 ext4_error_inode(inode, function, line, 0, err_str);
5042 ret = -EFSCORRUPTED;
5047 unlock_new_inode(inode);
5053 return ERR_PTR(ret);
5056 static void __ext4_update_other_inode_time(struct super_block *sb,
5057 unsigned long orig_ino,
5059 struct ext4_inode *raw_inode)
5061 struct inode *inode;
5063 inode = find_inode_by_ino_rcu(sb, ino);
5067 if (!inode_is_dirtytime_only(inode))
5070 spin_lock(&inode->i_lock);
5071 if (inode_is_dirtytime_only(inode)) {
5072 struct ext4_inode_info *ei = EXT4_I(inode);
5074 inode->i_state &= ~I_DIRTY_TIME;
5075 spin_unlock(&inode->i_lock);
5077 spin_lock(&ei->i_raw_lock);
5078 EXT4_INODE_SET_CTIME(inode, raw_inode);
5079 EXT4_INODE_SET_MTIME(inode, raw_inode);
5080 EXT4_INODE_SET_ATIME(inode, raw_inode);
5081 ext4_inode_csum_set(inode, raw_inode, ei);
5082 spin_unlock(&ei->i_raw_lock);
5083 trace_ext4_other_inode_update_time(inode, orig_ino);
5086 spin_unlock(&inode->i_lock);
5090 * Opportunistically update the other time fields for other inodes in
5091 * the same inode table block.
5093 static void ext4_update_other_inodes_time(struct super_block *sb,
5094 unsigned long orig_ino, char *buf)
5097 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5098 int inode_size = EXT4_INODE_SIZE(sb);
5101 * Calculate the first inode in the inode table block. Inode
5102 * numbers are one-based. That is, the first inode in a block
5103 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5105 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5107 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5108 if (ino == orig_ino)
5110 __ext4_update_other_inode_time(sb, orig_ino, ino,
5111 (struct ext4_inode *)buf);
5117 * Post the struct inode info into an on-disk inode location in the
5118 * buffer-cache. This gobbles the caller's reference to the
5119 * buffer_head in the inode location struct.
5121 * The caller must have write access to iloc->bh.
5123 static int ext4_do_update_inode(handle_t *handle,
5124 struct inode *inode,
5125 struct ext4_iloc *iloc)
5127 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5128 struct ext4_inode_info *ei = EXT4_I(inode);
5129 struct buffer_head *bh = iloc->bh;
5130 struct super_block *sb = inode->i_sb;
5132 int need_datasync = 0, set_large_file = 0;
5134 spin_lock(&ei->i_raw_lock);
5137 * For fields not tracked in the in-memory inode, initialise them
5138 * to zero for new inodes.
5140 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5141 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5143 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5145 if (ei->i_disksize > 0x7fffffffULL) {
5146 if (!ext4_has_feature_large_file(sb) ||
5147 EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5151 err = ext4_fill_raw_inode(inode, raw_inode);
5152 spin_unlock(&ei->i_raw_lock);
5154 EXT4_ERROR_INODE(inode, "corrupted inode contents");
5158 if (inode->i_sb->s_flags & SB_LAZYTIME)
5159 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5162 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5163 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5166 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5167 if (set_large_file) {
5168 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5169 err = ext4_journal_get_write_access(handle, sb,
5174 lock_buffer(EXT4_SB(sb)->s_sbh);
5175 ext4_set_feature_large_file(sb);
5176 ext4_superblock_csum_set(sb);
5177 unlock_buffer(EXT4_SB(sb)->s_sbh);
5178 ext4_handle_sync(handle);
5179 err = ext4_handle_dirty_metadata(handle, NULL,
5180 EXT4_SB(sb)->s_sbh);
5182 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5184 ext4_std_error(inode->i_sb, err);
5191 * ext4_write_inode()
5193 * We are called from a few places:
5195 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5196 * Here, there will be no transaction running. We wait for any running
5197 * transaction to commit.
5199 * - Within flush work (sys_sync(), kupdate and such).
5200 * We wait on commit, if told to.
5202 * - Within iput_final() -> write_inode_now()
5203 * We wait on commit, if told to.
5205 * In all cases it is actually safe for us to return without doing anything,
5206 * because the inode has been copied into a raw inode buffer in
5207 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5210 * Note that we are absolutely dependent upon all inode dirtiers doing the
5211 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5212 * which we are interested.
5214 * It would be a bug for them to not do this. The code:
5216 * mark_inode_dirty(inode)
5218 * inode->i_size = expr;
5220 * is in error because write_inode() could occur while `stuff()' is running,
5221 * and the new i_size will be lost. Plus the inode will no longer be on the
5222 * superblock's dirty inode list.
5224 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5228 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5231 if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5234 if (EXT4_SB(inode->i_sb)->s_journal) {
5235 if (ext4_journal_current_handle()) {
5236 ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5242 * No need to force transaction in WB_SYNC_NONE mode. Also
5243 * ext4_sync_fs() will force the commit after everything is
5246 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5249 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5250 EXT4_I(inode)->i_sync_tid);
5252 struct ext4_iloc iloc;
5254 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5258 * sync(2) will flush the whole buffer cache. No need to do
5259 * it here separately for each inode.
5261 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5262 sync_dirty_buffer(iloc.bh);
5263 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5264 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5265 "IO error syncing inode");
5274 * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5275 * buffers that are attached to a folio straddling i_size and are undergoing
5276 * commit. In that case we have to wait for commit to finish and try again.
5278 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5281 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5282 tid_t commit_tid = 0;
5285 offset = inode->i_size & (PAGE_SIZE - 1);
5287 * If the folio is fully truncated, we don't need to wait for any commit
5288 * (and we even should not as __ext4_journalled_invalidate_folio() may
5289 * strip all buffers from the folio but keep the folio dirty which can then
5290 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5291 * buffers). Also we don't need to wait for any commit if all buffers in
5292 * the folio remain valid. This is most beneficial for the common case of
5293 * blocksize == PAGESIZE.
5295 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5298 struct folio *folio = filemap_lock_folio(inode->i_mapping,
5299 inode->i_size >> PAGE_SHIFT);
5302 ret = __ext4_journalled_invalidate_folio(folio, offset,
5303 folio_size(folio) - offset);
5304 folio_unlock(folio);
5309 read_lock(&journal->j_state_lock);
5310 if (journal->j_committing_transaction)
5311 commit_tid = journal->j_committing_transaction->t_tid;
5312 read_unlock(&journal->j_state_lock);
5314 jbd2_log_wait_commit(journal, commit_tid);
5321 * Called from notify_change.
5323 * We want to trap VFS attempts to truncate the file as soon as
5324 * possible. In particular, we want to make sure that when the VFS
5325 * shrinks i_size, we put the inode on the orphan list and modify
5326 * i_disksize immediately, so that during the subsequent flushing of
5327 * dirty pages and freeing of disk blocks, we can guarantee that any
5328 * commit will leave the blocks being flushed in an unused state on
5329 * disk. (On recovery, the inode will get truncated and the blocks will
5330 * be freed, so we have a strong guarantee that no future commit will
5331 * leave these blocks visible to the user.)
5333 * Another thing we have to assure is that if we are in ordered mode
5334 * and inode is still attached to the committing transaction, we must
5335 * we start writeout of all the dirty pages which are being truncated.
5336 * This way we are sure that all the data written in the previous
5337 * transaction are already on disk (truncate waits for pages under
5340 * Called with inode->i_rwsem down.
5342 int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5345 struct inode *inode = d_inode(dentry);
5348 const unsigned int ia_valid = attr->ia_valid;
5349 bool inc_ivers = true;
5351 if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5354 if (unlikely(IS_IMMUTABLE(inode)))
5357 if (unlikely(IS_APPEND(inode) &&
5358 (ia_valid & (ATTR_MODE | ATTR_UID |
5359 ATTR_GID | ATTR_TIMES_SET))))
5362 error = setattr_prepare(idmap, dentry, attr);
5366 error = fscrypt_prepare_setattr(dentry, attr);
5370 error = fsverity_prepare_setattr(dentry, attr);
5374 if (is_quota_modification(idmap, inode, attr)) {
5375 error = dquot_initialize(inode);
5380 if (i_uid_needs_update(idmap, attr, inode) ||
5381 i_gid_needs_update(idmap, attr, inode)) {
5384 /* (user+group)*(old+new) structure, inode write (sb,
5385 * inode block, ? - but truncate inode update has it) */
5386 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5387 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5388 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5389 if (IS_ERR(handle)) {
5390 error = PTR_ERR(handle);
5394 /* dquot_transfer() calls back ext4_get_inode_usage() which
5395 * counts xattr inode references.
5397 down_read(&EXT4_I(inode)->xattr_sem);
5398 error = dquot_transfer(idmap, inode, attr);
5399 up_read(&EXT4_I(inode)->xattr_sem);
5402 ext4_journal_stop(handle);
5405 /* Update corresponding info in inode so that everything is in
5406 * one transaction */
5407 i_uid_update(idmap, attr, inode);
5408 i_gid_update(idmap, attr, inode);
5409 error = ext4_mark_inode_dirty(handle, inode);
5410 ext4_journal_stop(handle);
5411 if (unlikely(error)) {
5416 if (attr->ia_valid & ATTR_SIZE) {
5418 loff_t oldsize = inode->i_size;
5419 loff_t old_disksize;
5420 int shrink = (attr->ia_size < inode->i_size);
5422 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5423 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5425 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5429 if (!S_ISREG(inode->i_mode)) {
5433 if (attr->ia_size == inode->i_size)
5437 if (ext4_should_order_data(inode)) {
5438 error = ext4_begin_ordered_truncate(inode,
5444 * Blocks are going to be removed from the inode. Wait
5445 * for dio in flight.
5447 inode_dio_wait(inode);
5450 filemap_invalidate_lock(inode->i_mapping);
5452 rc = ext4_break_layouts(inode);
5454 filemap_invalidate_unlock(inode->i_mapping);
5458 if (attr->ia_size != inode->i_size) {
5459 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5460 if (IS_ERR(handle)) {
5461 error = PTR_ERR(handle);
5464 if (ext4_handle_valid(handle) && shrink) {
5465 error = ext4_orphan_add(handle, inode);
5469 * Update c/mtime on truncate up, ext4_truncate() will
5470 * update c/mtime in shrink case below
5473 inode_set_mtime_to_ts(inode,
5474 inode_set_ctime_current(inode));
5477 ext4_fc_track_range(handle, inode,
5478 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5479 inode->i_sb->s_blocksize_bits,
5480 EXT_MAX_BLOCKS - 1);
5482 ext4_fc_track_range(
5484 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5485 inode->i_sb->s_blocksize_bits,
5486 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5487 inode->i_sb->s_blocksize_bits);
5489 down_write(&EXT4_I(inode)->i_data_sem);
5490 old_disksize = EXT4_I(inode)->i_disksize;
5491 EXT4_I(inode)->i_disksize = attr->ia_size;
5492 rc = ext4_mark_inode_dirty(handle, inode);
5496 * We have to update i_size under i_data_sem together
5497 * with i_disksize to avoid races with writeback code
5498 * running ext4_wb_update_i_disksize().
5501 i_size_write(inode, attr->ia_size);
5503 EXT4_I(inode)->i_disksize = old_disksize;
5504 up_write(&EXT4_I(inode)->i_data_sem);
5505 ext4_journal_stop(handle);
5509 pagecache_isize_extended(inode, oldsize,
5511 } else if (ext4_should_journal_data(inode)) {
5512 ext4_wait_for_tail_page_commit(inode);
5517 * Truncate pagecache after we've waited for commit
5518 * in data=journal mode to make pages freeable.
5520 truncate_pagecache(inode, inode->i_size);
5522 * Call ext4_truncate() even if i_size didn't change to
5523 * truncate possible preallocated blocks.
5525 if (attr->ia_size <= oldsize) {
5526 rc = ext4_truncate(inode);
5531 filemap_invalidate_unlock(inode->i_mapping);
5536 inode_inc_iversion(inode);
5537 setattr_copy(idmap, inode, attr);
5538 mark_inode_dirty(inode);
5542 * If the call to ext4_truncate failed to get a transaction handle at
5543 * all, we need to clean up the in-core orphan list manually.
5545 if (orphan && inode->i_nlink)
5546 ext4_orphan_del(NULL, inode);
5548 if (!error && (ia_valid & ATTR_MODE))
5549 rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
5553 ext4_std_error(inode->i_sb, error);
5559 u32 ext4_dio_alignment(struct inode *inode)
5561 if (fsverity_active(inode))
5563 if (ext4_should_journal_data(inode))
5565 if (ext4_has_inline_data(inode))
5567 if (IS_ENCRYPTED(inode)) {
5568 if (!fscrypt_dio_supported(inode))
5570 return i_blocksize(inode);
5572 return 1; /* use the iomap defaults */
5575 int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
5576 struct kstat *stat, u32 request_mask, unsigned int query_flags)
5578 struct inode *inode = d_inode(path->dentry);
5579 struct ext4_inode *raw_inode;
5580 struct ext4_inode_info *ei = EXT4_I(inode);
5583 if ((request_mask & STATX_BTIME) &&
5584 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5585 stat->result_mask |= STATX_BTIME;
5586 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5587 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5591 * Return the DIO alignment restrictions if requested. We only return
5592 * this information when requested, since on encrypted files it might
5593 * take a fair bit of work to get if the file wasn't opened recently.
5595 if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
5596 u32 dio_align = ext4_dio_alignment(inode);
5598 stat->result_mask |= STATX_DIOALIGN;
5599 if (dio_align == 1) {
5600 struct block_device *bdev = inode->i_sb->s_bdev;
5602 /* iomap defaults */
5603 stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
5604 stat->dio_offset_align = bdev_logical_block_size(bdev);
5606 stat->dio_mem_align = dio_align;
5607 stat->dio_offset_align = dio_align;
5611 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5612 if (flags & EXT4_APPEND_FL)
5613 stat->attributes |= STATX_ATTR_APPEND;
5614 if (flags & EXT4_COMPR_FL)
5615 stat->attributes |= STATX_ATTR_COMPRESSED;
5616 if (flags & EXT4_ENCRYPT_FL)
5617 stat->attributes |= STATX_ATTR_ENCRYPTED;
5618 if (flags & EXT4_IMMUTABLE_FL)
5619 stat->attributes |= STATX_ATTR_IMMUTABLE;
5620 if (flags & EXT4_NODUMP_FL)
5621 stat->attributes |= STATX_ATTR_NODUMP;
5622 if (flags & EXT4_VERITY_FL)
5623 stat->attributes |= STATX_ATTR_VERITY;
5625 stat->attributes_mask |= (STATX_ATTR_APPEND |
5626 STATX_ATTR_COMPRESSED |
5627 STATX_ATTR_ENCRYPTED |
5628 STATX_ATTR_IMMUTABLE |
5632 generic_fillattr(idmap, request_mask, inode, stat);
5636 int ext4_file_getattr(struct mnt_idmap *idmap,
5637 const struct path *path, struct kstat *stat,
5638 u32 request_mask, unsigned int query_flags)
5640 struct inode *inode = d_inode(path->dentry);
5641 u64 delalloc_blocks;
5643 ext4_getattr(idmap, path, stat, request_mask, query_flags);
5646 * If there is inline data in the inode, the inode will normally not
5647 * have data blocks allocated (it may have an external xattr block).
5648 * Report at least one sector for such files, so tools like tar, rsync,
5649 * others don't incorrectly think the file is completely sparse.
5651 if (unlikely(ext4_has_inline_data(inode)))
5652 stat->blocks += (stat->size + 511) >> 9;
5655 * We can't update i_blocks if the block allocation is delayed
5656 * otherwise in the case of system crash before the real block
5657 * allocation is done, we will have i_blocks inconsistent with
5658 * on-disk file blocks.
5659 * We always keep i_blocks updated together with real
5660 * allocation. But to not confuse with user, stat
5661 * will return the blocks that include the delayed allocation
5662 * blocks for this file.
5664 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5665 EXT4_I(inode)->i_reserved_data_blocks);
5666 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5670 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5673 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5674 return ext4_ind_trans_blocks(inode, lblocks);
5675 return ext4_ext_index_trans_blocks(inode, pextents);
5679 * Account for index blocks, block groups bitmaps and block group
5680 * descriptor blocks if modify datablocks and index blocks
5681 * worse case, the indexs blocks spread over different block groups
5683 * If datablocks are discontiguous, they are possible to spread over
5684 * different block groups too. If they are contiguous, with flexbg,
5685 * they could still across block group boundary.
5687 * Also account for superblock, inode, quota and xattr blocks
5689 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5692 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5698 * How many index blocks need to touch to map @lblocks logical blocks
5699 * to @pextents physical extents?
5701 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5706 * Now let's see how many group bitmaps and group descriptors need
5709 groups = idxblocks + pextents;
5711 if (groups > ngroups)
5713 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5714 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5716 /* bitmaps and block group descriptor blocks */
5717 ret += groups + gdpblocks;
5719 /* Blocks for super block, inode, quota and xattr blocks */
5720 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5726 * Calculate the total number of credits to reserve to fit
5727 * the modification of a single pages into a single transaction,
5728 * which may include multiple chunks of block allocations.
5730 * This could be called via ext4_write_begin()
5732 * We need to consider the worse case, when
5733 * one new block per extent.
5735 int ext4_writepage_trans_blocks(struct inode *inode)
5737 int bpp = ext4_journal_blocks_per_page(inode);
5740 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5742 /* Account for data blocks for journalled mode */
5743 if (ext4_should_journal_data(inode))
5749 * Calculate the journal credits for a chunk of data modification.
5751 * This is called from DIO, fallocate or whoever calling
5752 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5754 * journal buffers for data blocks are not included here, as DIO
5755 * and fallocate do no need to journal data buffers.
5757 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5759 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5763 * The caller must have previously called ext4_reserve_inode_write().
5764 * Give this, we know that the caller already has write access to iloc->bh.
5766 int ext4_mark_iloc_dirty(handle_t *handle,
5767 struct inode *inode, struct ext4_iloc *iloc)
5771 if (unlikely(ext4_forced_shutdown(inode->i_sb))) {
5775 ext4_fc_track_inode(handle, inode);
5777 /* the do_update_inode consumes one bh->b_count */
5780 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5781 err = ext4_do_update_inode(handle, inode, iloc);
5787 * On success, We end up with an outstanding reference count against
5788 * iloc->bh. This _must_ be cleaned up later.
5792 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5793 struct ext4_iloc *iloc)
5797 if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5800 err = ext4_get_inode_loc(inode, iloc);
5802 BUFFER_TRACE(iloc->bh, "get_write_access");
5803 err = ext4_journal_get_write_access(handle, inode->i_sb,
5804 iloc->bh, EXT4_JTR_NONE);
5810 ext4_std_error(inode->i_sb, err);
5814 static int __ext4_expand_extra_isize(struct inode *inode,
5815 unsigned int new_extra_isize,
5816 struct ext4_iloc *iloc,
5817 handle_t *handle, int *no_expand)
5819 struct ext4_inode *raw_inode;
5820 struct ext4_xattr_ibody_header *header;
5821 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5822 struct ext4_inode_info *ei = EXT4_I(inode);
5825 /* this was checked at iget time, but double check for good measure */
5826 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5827 (ei->i_extra_isize & 3)) {
5828 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5830 EXT4_INODE_SIZE(inode->i_sb));
5831 return -EFSCORRUPTED;
5833 if ((new_extra_isize < ei->i_extra_isize) ||
5834 (new_extra_isize < 4) ||
5835 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5836 return -EINVAL; /* Should never happen */
5838 raw_inode = ext4_raw_inode(iloc);
5840 header = IHDR(inode, raw_inode);
5842 /* No extended attributes present */
5843 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5844 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5845 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5846 EXT4_I(inode)->i_extra_isize, 0,
5847 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5848 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5853 * We may need to allocate external xattr block so we need quotas
5854 * initialized. Here we can be called with various locks held so we
5855 * cannot affort to initialize quotas ourselves. So just bail.
5857 if (dquot_initialize_needed(inode))
5860 /* try to expand with EAs present */
5861 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5865 * Inode size expansion failed; don't try again
5874 * Expand an inode by new_extra_isize bytes.
5875 * Returns 0 on success or negative error number on failure.
5877 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5878 unsigned int new_extra_isize,
5879 struct ext4_iloc iloc,
5885 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5889 * In nojournal mode, we can immediately attempt to expand
5890 * the inode. When journaled, we first need to obtain extra
5891 * buffer credits since we may write into the EA block
5892 * with this same handle. If journal_extend fails, then it will
5893 * only result in a minor loss of functionality for that inode.
5894 * If this is felt to be critical, then e2fsck should be run to
5895 * force a large enough s_min_extra_isize.
5897 if (ext4_journal_extend(handle,
5898 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5901 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5904 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5905 handle, &no_expand);
5906 ext4_write_unlock_xattr(inode, &no_expand);
5911 int ext4_expand_extra_isize(struct inode *inode,
5912 unsigned int new_extra_isize,
5913 struct ext4_iloc *iloc)
5919 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5924 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5925 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5926 if (IS_ERR(handle)) {
5927 error = PTR_ERR(handle);
5932 ext4_write_lock_xattr(inode, &no_expand);
5934 BUFFER_TRACE(iloc->bh, "get_write_access");
5935 error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5942 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5943 handle, &no_expand);
5945 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5950 ext4_write_unlock_xattr(inode, &no_expand);
5951 ext4_journal_stop(handle);
5956 * What we do here is to mark the in-core inode as clean with respect to inode
5957 * dirtiness (it may still be data-dirty).
5958 * This means that the in-core inode may be reaped by prune_icache
5959 * without having to perform any I/O. This is a very good thing,
5960 * because *any* task may call prune_icache - even ones which
5961 * have a transaction open against a different journal.
5963 * Is this cheating? Not really. Sure, we haven't written the
5964 * inode out, but prune_icache isn't a user-visible syncing function.
5965 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5966 * we start and wait on commits.
5968 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5969 const char *func, unsigned int line)
5971 struct ext4_iloc iloc;
5972 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5976 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5977 err = ext4_reserve_inode_write(handle, inode, &iloc);
5981 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5982 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5985 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5988 ext4_error_inode_err(inode, func, line, 0, err,
5989 "mark_inode_dirty error");
5994 * ext4_dirty_inode() is called from __mark_inode_dirty()
5996 * We're really interested in the case where a file is being extended.
5997 * i_size has been changed by generic_commit_write() and we thus need
5998 * to include the updated inode in the current transaction.
6000 * Also, dquot_alloc_block() will always dirty the inode when blocks
6001 * are allocated to the file.
6003 * If the inode is marked synchronous, we don't honour that here - doing
6004 * so would cause a commit on atime updates, which we don't bother doing.
6005 * We handle synchronous inodes at the highest possible level.
6007 void ext4_dirty_inode(struct inode *inode, int flags)
6011 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6014 ext4_mark_inode_dirty(handle, inode);
6015 ext4_journal_stop(handle);
6018 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6026 * We have to be very careful here: changing a data block's
6027 * journaling status dynamically is dangerous. If we write a
6028 * data block to the journal, change the status and then delete
6029 * that block, we risk forgetting to revoke the old log record
6030 * from the journal and so a subsequent replay can corrupt data.
6031 * So, first we make sure that the journal is empty and that
6032 * nobody is changing anything.
6035 journal = EXT4_JOURNAL(inode);
6038 if (is_journal_aborted(journal))
6041 /* Wait for all existing dio workers */
6042 inode_dio_wait(inode);
6045 * Before flushing the journal and switching inode's aops, we have
6046 * to flush all dirty data the inode has. There can be outstanding
6047 * delayed allocations, there can be unwritten extents created by
6048 * fallocate or buffered writes in dioread_nolock mode covered by
6049 * dirty data which can be converted only after flushing the dirty
6050 * data (and journalled aops don't know how to handle these cases).
6053 filemap_invalidate_lock(inode->i_mapping);
6054 err = filemap_write_and_wait(inode->i_mapping);
6056 filemap_invalidate_unlock(inode->i_mapping);
6061 alloc_ctx = ext4_writepages_down_write(inode->i_sb);
6062 jbd2_journal_lock_updates(journal);
6065 * OK, there are no updates running now, and all cached data is
6066 * synced to disk. We are now in a completely consistent state
6067 * which doesn't have anything in the journal, and we know that
6068 * no filesystem updates are running, so it is safe to modify
6069 * the inode's in-core data-journaling state flag now.
6073 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6075 err = jbd2_journal_flush(journal, 0);
6077 jbd2_journal_unlock_updates(journal);
6078 ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6081 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6083 ext4_set_aops(inode);
6085 jbd2_journal_unlock_updates(journal);
6086 ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6089 filemap_invalidate_unlock(inode->i_mapping);
6091 /* Finally we can mark the inode as dirty. */
6093 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6095 return PTR_ERR(handle);
6097 ext4_fc_mark_ineligible(inode->i_sb,
6098 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6099 err = ext4_mark_inode_dirty(handle, inode);
6100 ext4_handle_sync(handle);
6101 ext4_journal_stop(handle);
6102 ext4_std_error(inode->i_sb, err);
6107 static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6108 struct buffer_head *bh)
6110 return !buffer_mapped(bh);
6113 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6115 struct vm_area_struct *vma = vmf->vma;
6116 struct folio *folio = page_folio(vmf->page);
6121 struct file *file = vma->vm_file;
6122 struct inode *inode = file_inode(file);
6123 struct address_space *mapping = inode->i_mapping;
6125 get_block_t *get_block;
6128 if (unlikely(IS_IMMUTABLE(inode)))
6129 return VM_FAULT_SIGBUS;
6131 sb_start_pagefault(inode->i_sb);
6132 file_update_time(vma->vm_file);
6134 filemap_invalidate_lock_shared(mapping);
6136 err = ext4_convert_inline_data(inode);
6141 * On data journalling we skip straight to the transaction handle:
6142 * there's no delalloc; page truncated will be checked later; the
6143 * early return w/ all buffers mapped (calculates size/len) can't
6144 * be used; and there's no dioread_nolock, so only ext4_get_block.
6146 if (ext4_should_journal_data(inode))
6149 /* Delalloc case is easy... */
6150 if (test_opt(inode->i_sb, DELALLOC) &&
6151 !ext4_nonda_switch(inode->i_sb)) {
6153 err = block_page_mkwrite(vma, vmf,
6154 ext4_da_get_block_prep);
6155 } while (err == -ENOSPC &&
6156 ext4_should_retry_alloc(inode->i_sb, &retries));
6161 size = i_size_read(inode);
6162 /* Page got truncated from under us? */
6163 if (folio->mapping != mapping || folio_pos(folio) > size) {
6164 folio_unlock(folio);
6165 ret = VM_FAULT_NOPAGE;
6169 len = folio_size(folio);
6170 if (folio_pos(folio) + len > size)
6171 len = size - folio_pos(folio);
6173 * Return if we have all the buffers mapped. This avoids the need to do
6174 * journal_start/journal_stop which can block and take a long time
6176 * This cannot be done for data journalling, as we have to add the
6177 * inode to the transaction's list to writeprotect pages on commit.
6179 if (folio_buffers(folio)) {
6180 if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6182 ext4_bh_unmapped)) {
6183 /* Wait so that we don't change page under IO */
6184 folio_wait_stable(folio);
6185 ret = VM_FAULT_LOCKED;
6189 folio_unlock(folio);
6190 /* OK, we need to fill the hole... */
6191 if (ext4_should_dioread_nolock(inode))
6192 get_block = ext4_get_block_unwritten;
6194 get_block = ext4_get_block;
6196 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6197 ext4_writepage_trans_blocks(inode));
6198 if (IS_ERR(handle)) {
6199 ret = VM_FAULT_SIGBUS;
6203 * Data journalling can't use block_page_mkwrite() because it
6204 * will set_buffer_dirty() before do_journal_get_write_access()
6205 * thus might hit warning messages for dirty metadata buffers.
6207 if (!ext4_should_journal_data(inode)) {
6208 err = block_page_mkwrite(vma, vmf, get_block);
6211 size = i_size_read(inode);
6212 /* Page got truncated from under us? */
6213 if (folio->mapping != mapping || folio_pos(folio) > size) {
6214 ret = VM_FAULT_NOPAGE;
6218 len = folio_size(folio);
6219 if (folio_pos(folio) + len > size)
6220 len = size - folio_pos(folio);
6222 err = __block_write_begin(&folio->page, 0, len, ext4_get_block);
6224 ret = VM_FAULT_SIGBUS;
6225 if (ext4_journal_folio_buffers(handle, folio, len))
6228 folio_unlock(folio);
6231 ext4_journal_stop(handle);
6232 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6235 ret = vmf_fs_error(err);
6237 filemap_invalidate_unlock_shared(mapping);
6238 sb_end_pagefault(inode->i_sb);
6241 folio_unlock(folio);
6242 ext4_journal_stop(handle);