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/rmap.h>
35 #include <linux/namei.h>
36 #include <linux/uio.h>
37 #include <linux/bio.h>
38 #include <linux/workqueue.h>
39 #include <linux/kernel.h>
40 #include <linux/printk.h>
41 #include <linux/slab.h>
42 #include <linux/bitops.h>
43 #include <linux/iomap.h>
44 #include <linux/iversion.h>
46 #include "ext4_jbd2.h"
51 #include <trace/events/ext4.h>
53 static void ext4_journalled_zero_new_buffers(handle_t *handle,
56 unsigned from, unsigned to);
58 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
59 struct ext4_inode_info *ei)
63 int offset = offsetof(struct ext4_inode, i_checksum_lo);
64 unsigned int csum_size = sizeof(dummy_csum);
66 csum = ext4_chksum(ei->i_csum_seed, (__u8 *)raw, offset);
67 csum = ext4_chksum(csum, (__u8 *)&dummy_csum, csum_size);
69 csum = ext4_chksum(csum, (__u8 *)raw + offset,
70 EXT4_GOOD_OLD_INODE_SIZE - offset);
72 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
73 offset = offsetof(struct ext4_inode, i_checksum_hi);
74 csum = ext4_chksum(csum, (__u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE,
75 offset - EXT4_GOOD_OLD_INODE_SIZE);
76 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
77 csum = ext4_chksum(csum, (__u8 *)&dummy_csum,
81 csum = ext4_chksum(csum, (__u8 *)raw + offset,
82 EXT4_INODE_SIZE(inode->i_sb) - offset);
88 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
89 struct ext4_inode_info *ei)
91 __u32 provided, calculated;
93 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
94 cpu_to_le32(EXT4_OS_LINUX) ||
95 !ext4_has_feature_metadata_csum(inode->i_sb))
98 provided = le16_to_cpu(raw->i_checksum_lo);
99 calculated = ext4_inode_csum(inode, raw, ei);
100 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
101 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
102 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
104 calculated &= 0xFFFF;
106 return provided == calculated;
109 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
110 struct ext4_inode_info *ei)
114 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
115 cpu_to_le32(EXT4_OS_LINUX) ||
116 !ext4_has_feature_metadata_csum(inode->i_sb))
119 csum = ext4_inode_csum(inode, raw, ei);
120 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
121 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
122 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
123 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
126 static inline int ext4_begin_ordered_truncate(struct inode *inode,
129 trace_ext4_begin_ordered_truncate(inode, new_size);
131 * If jinode is zero, then we never opened the file for
132 * writing, so there's no need to call
133 * jbd2_journal_begin_ordered_truncate() since there's no
134 * outstanding writes we need to flush.
136 if (!EXT4_I(inode)->jinode)
138 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
139 EXT4_I(inode)->jinode,
144 * Test whether an inode is a fast symlink.
145 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
147 int ext4_inode_is_fast_symlink(struct inode *inode)
149 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
150 int ea_blocks = EXT4_I(inode)->i_file_acl ?
151 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
153 if (ext4_has_inline_data(inode))
156 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
158 return S_ISLNK(inode->i_mode) && inode->i_size &&
159 (inode->i_size < EXT4_N_BLOCKS * 4);
163 * Called at the last iput() if i_nlink is zero.
165 void ext4_evict_inode(struct inode *inode)
170 * Credits for final inode cleanup and freeing:
171 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
172 * (xattr block freeing), bitmap, group descriptor (inode freeing)
174 int extra_credits = 6;
175 struct ext4_xattr_inode_array *ea_inode_array = NULL;
176 bool freeze_protected = false;
178 trace_ext4_evict_inode(inode);
180 dax_break_layout_final(inode);
182 if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
183 ext4_evict_ea_inode(inode);
184 if (inode->i_nlink) {
185 truncate_inode_pages_final(&inode->i_data);
190 if (is_bad_inode(inode))
192 dquot_initialize(inode);
194 if (ext4_should_order_data(inode))
195 ext4_begin_ordered_truncate(inode, 0);
196 truncate_inode_pages_final(&inode->i_data);
199 * For inodes with journalled data, transaction commit could have
200 * dirtied the inode. And for inodes with dioread_nolock, unwritten
201 * extents converting worker could merge extents and also have dirtied
202 * the inode. Flush worker is ignoring it because of I_FREEING flag but
203 * we still need to remove the inode from the writeback lists.
205 if (!list_empty_careful(&inode->i_io_list))
206 inode_io_list_del(inode);
209 * Protect us against freezing - iput() caller didn't have to have any
210 * protection against it. When we are in a running transaction though,
211 * we are already protected against freezing and we cannot grab further
212 * protection due to lock ordering constraints.
214 if (!ext4_journal_current_handle()) {
215 sb_start_intwrite(inode->i_sb);
216 freeze_protected = true;
219 if (!IS_NOQUOTA(inode))
220 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
223 * Block bitmap, group descriptor, and inode are accounted in both
224 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
226 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
227 ext4_blocks_for_truncate(inode) + extra_credits - 3);
228 if (IS_ERR(handle)) {
229 ext4_std_error(inode->i_sb, PTR_ERR(handle));
231 * If we're going to skip the normal cleanup, we still need to
232 * make sure that the in-core orphan linked list is properly
235 ext4_orphan_del(NULL, inode);
236 if (freeze_protected)
237 sb_end_intwrite(inode->i_sb);
242 ext4_handle_sync(handle);
245 * Set inode->i_size to 0 before calling ext4_truncate(). We need
246 * special handling of symlinks here because i_size is used to
247 * determine whether ext4_inode_info->i_data contains symlink data or
248 * block mappings. Setting i_size to 0 will remove its fast symlink
249 * status. Erase i_data so that it becomes a valid empty block map.
251 if (ext4_inode_is_fast_symlink(inode))
252 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
254 err = ext4_mark_inode_dirty(handle, inode);
256 ext4_warning(inode->i_sb,
257 "couldn't mark inode dirty (err %d)", err);
260 if (inode->i_blocks) {
261 err = ext4_truncate(inode);
263 ext4_error_err(inode->i_sb, -err,
264 "couldn't truncate inode %lu (err %d)",
270 /* Remove xattr references. */
271 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
274 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
276 ext4_journal_stop(handle);
277 ext4_orphan_del(NULL, inode);
278 if (freeze_protected)
279 sb_end_intwrite(inode->i_sb);
280 ext4_xattr_inode_array_free(ea_inode_array);
285 * Kill off the orphan record which ext4_truncate created.
286 * AKPM: I think this can be inside the above `if'.
287 * Note that ext4_orphan_del() has to be able to cope with the
288 * deletion of a non-existent orphan - this is because we don't
289 * know if ext4_truncate() actually created an orphan record.
290 * (Well, we could do this if we need to, but heck - it works)
292 ext4_orphan_del(handle, inode);
293 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
296 * One subtle ordering requirement: if anything has gone wrong
297 * (transaction abort, IO errors, whatever), then we can still
298 * do these next steps (the fs will already have been marked as
299 * having errors), but we can't free the inode if the mark_dirty
302 if (ext4_mark_inode_dirty(handle, inode))
303 /* If that failed, just do the required in-core inode clear. */
304 ext4_clear_inode(inode);
306 ext4_free_inode(handle, inode);
307 ext4_journal_stop(handle);
308 if (freeze_protected)
309 sb_end_intwrite(inode->i_sb);
310 ext4_xattr_inode_array_free(ea_inode_array);
314 * Check out some where else accidentally dirty the evicting inode,
315 * which may probably cause inode use-after-free issues later.
317 WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
319 if (!list_empty(&EXT4_I(inode)->i_fc_list))
320 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
321 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
325 qsize_t *ext4_get_reserved_space(struct inode *inode)
327 return &EXT4_I(inode)->i_reserved_quota;
332 * Called with i_data_sem down, which is important since we can call
333 * ext4_discard_preallocations() from here.
335 void ext4_da_update_reserve_space(struct inode *inode,
336 int used, int quota_claim)
338 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
339 struct ext4_inode_info *ei = EXT4_I(inode);
341 spin_lock(&ei->i_block_reservation_lock);
342 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
343 if (unlikely(used > ei->i_reserved_data_blocks)) {
344 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
345 "with only %d reserved data blocks",
346 __func__, inode->i_ino, used,
347 ei->i_reserved_data_blocks);
349 used = ei->i_reserved_data_blocks;
352 /* Update per-inode reservations */
353 ei->i_reserved_data_blocks -= used;
354 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
356 spin_unlock(&ei->i_block_reservation_lock);
358 /* Update quota subsystem for data blocks */
360 dquot_claim_block(inode, EXT4_C2B(sbi, used));
363 * We did fallocate with an offset that is already delayed
364 * allocated. So on delayed allocated writeback we should
365 * not re-claim the quota for fallocated blocks.
367 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
371 * If we have done all the pending block allocations and if
372 * there aren't any writers on the inode, we can discard the
373 * inode's preallocations.
375 if ((ei->i_reserved_data_blocks == 0) &&
376 !inode_is_open_for_write(inode))
377 ext4_discard_preallocations(inode);
380 static int __check_block_validity(struct inode *inode, const char *func,
382 struct ext4_map_blocks *map)
384 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
386 if (journal && inode == journal->j_inode)
389 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
390 ext4_error_inode(inode, func, line, map->m_pblk,
391 "lblock %lu mapped to illegal pblock %llu "
392 "(length %d)", (unsigned long) map->m_lblk,
393 map->m_pblk, map->m_len);
394 return -EFSCORRUPTED;
399 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
404 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
405 return fscrypt_zeroout_range(inode, lblk, pblk, len);
407 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
415 * For generic regular files, when updating the extent tree, Ext4 should
416 * hold the i_rwsem and invalidate_lock exclusively. This ensures
417 * exclusion against concurrent page faults, as well as reads and writes.
419 #ifdef CONFIG_EXT4_DEBUG
420 void ext4_check_map_extents_env(struct inode *inode)
422 if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
425 if (!S_ISREG(inode->i_mode) ||
426 IS_NOQUOTA(inode) || IS_VERITY(inode) ||
427 is_special_ino(inode->i_sb, inode->i_ino) ||
428 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) ||
429 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE) ||
430 ext4_verity_in_progress(inode))
433 WARN_ON_ONCE(!inode_is_locked(inode) &&
434 !rwsem_is_locked(&inode->i_mapping->invalidate_lock));
437 void ext4_check_map_extents_env(struct inode *inode) {}
440 #define check_block_validity(inode, map) \
441 __check_block_validity((inode), __func__, __LINE__, (map))
443 #ifdef ES_AGGRESSIVE_TEST
444 static void ext4_map_blocks_es_recheck(handle_t *handle,
446 struct ext4_map_blocks *es_map,
447 struct ext4_map_blocks *map,
454 * There is a race window that the result is not the same.
455 * e.g. xfstests #223 when dioread_nolock enables. The reason
456 * is that we lookup a block mapping in extent status tree with
457 * out taking i_data_sem. So at the time the unwritten extent
458 * could be converted.
460 down_read(&EXT4_I(inode)->i_data_sem);
461 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
462 retval = ext4_ext_map_blocks(handle, inode, map, 0);
464 retval = ext4_ind_map_blocks(handle, inode, map, 0);
466 up_read((&EXT4_I(inode)->i_data_sem));
469 * We don't check m_len because extent will be collpased in status
470 * tree. So the m_len might not equal.
472 if (es_map->m_lblk != map->m_lblk ||
473 es_map->m_flags != map->m_flags ||
474 es_map->m_pblk != map->m_pblk) {
475 printk("ES cache assertion failed for inode: %lu "
476 "es_cached ex [%d/%d/%llu/%x] != "
477 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
478 inode->i_ino, es_map->m_lblk, es_map->m_len,
479 es_map->m_pblk, es_map->m_flags, map->m_lblk,
480 map->m_len, map->m_pblk, map->m_flags,
484 #endif /* ES_AGGRESSIVE_TEST */
486 static int ext4_map_query_blocks_next_in_leaf(handle_t *handle,
487 struct inode *inode, struct ext4_map_blocks *map,
488 unsigned int orig_mlen)
490 struct ext4_map_blocks map2;
491 unsigned int status, status2;
494 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
495 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
497 WARN_ON_ONCE(!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF));
498 WARN_ON_ONCE(orig_mlen <= map->m_len);
500 /* Prepare map2 for lookup in next leaf block */
501 map2.m_lblk = map->m_lblk + map->m_len;
502 map2.m_len = orig_mlen - map->m_len;
504 retval = ext4_ext_map_blocks(handle, inode, &map2, 0);
507 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
508 map->m_pblk, status, false);
512 if (unlikely(retval != map2.m_len)) {
513 ext4_warning(inode->i_sb,
514 "ES len assertion failed for inode "
515 "%lu: retval %d != map->m_len %d",
516 inode->i_ino, retval, map2.m_len);
520 status2 = map2.m_flags & EXT4_MAP_UNWRITTEN ?
521 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
524 * If map2 is contiguous with map, then let's insert it as a single
525 * extent in es cache and return the combined length of both the maps.
527 if (map->m_pblk + map->m_len == map2.m_pblk &&
529 ext4_es_insert_extent(inode, map->m_lblk,
530 map->m_len + map2.m_len, map->m_pblk,
532 map->m_len += map2.m_len;
534 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
535 map->m_pblk, status, false);
541 static int ext4_map_query_blocks(handle_t *handle, struct inode *inode,
542 struct ext4_map_blocks *map, int flags)
546 unsigned int orig_mlen = map->m_len;
548 flags &= EXT4_EX_QUERY_FILTER;
549 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
550 retval = ext4_ext_map_blocks(handle, inode, map, flags);
552 retval = ext4_ind_map_blocks(handle, inode, map, flags);
557 if (unlikely(retval != map->m_len)) {
558 ext4_warning(inode->i_sb,
559 "ES len assertion failed for inode "
560 "%lu: retval %d != map->m_len %d",
561 inode->i_ino, retval, map->m_len);
566 * No need to query next in leaf:
567 * - if returned extent is not last in leaf or
568 * - if the last in leaf is the full requested range
570 if (!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) ||
571 map->m_len == orig_mlen) {
572 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
573 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
574 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
575 map->m_pblk, status, false);
579 return ext4_map_query_blocks_next_in_leaf(handle, inode, map,
583 static int ext4_map_create_blocks(handle_t *handle, struct inode *inode,
584 struct ext4_map_blocks *map, int flags)
586 struct extent_status es;
591 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE
592 * indicates that the blocks and quotas has already been
593 * checked when the data was copied into the page cache.
595 if (map->m_flags & EXT4_MAP_DELAYED)
596 flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
599 * Here we clear m_flags because after allocating an new extent,
600 * it will be set again.
602 map->m_flags &= ~EXT4_MAP_FLAGS;
605 * We need to check for EXT4 here because migrate could have
606 * changed the inode type in between.
608 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
609 retval = ext4_ext_map_blocks(handle, inode, map, flags);
611 retval = ext4_ind_map_blocks(handle, inode, map, flags);
614 * We allocated new blocks which will result in i_data's
615 * format changing. Force the migrate to fail by clearing
618 if (retval > 0 && map->m_flags & EXT4_MAP_NEW)
619 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
624 if (unlikely(retval != map->m_len)) {
625 ext4_warning(inode->i_sb,
626 "ES len assertion failed for inode %lu: "
627 "retval %d != map->m_len %d",
628 inode->i_ino, retval, map->m_len);
633 * We have to zeroout blocks before inserting them into extent
634 * status tree. Otherwise someone could look them up there and
635 * use them before they are really zeroed. We also have to
636 * unmap metadata before zeroing as otherwise writeback can
637 * overwrite zeros with stale data from block device.
639 if (flags & EXT4_GET_BLOCKS_ZERO &&
640 map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) {
641 err = ext4_issue_zeroout(inode, map->m_lblk, map->m_pblk,
648 * If the extent has been zeroed out, we don't need to update
649 * extent status tree.
651 if (flags & EXT4_GET_BLOCKS_PRE_IO &&
652 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
653 if (ext4_es_is_written(&es))
657 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
658 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
659 ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk,
660 status, flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE);
666 * The ext4_map_blocks() function tries to look up the requested blocks,
667 * and returns if the blocks are already mapped.
669 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
670 * and store the allocated blocks in the result buffer head and mark it
673 * If file type is extents based, it will call ext4_ext_map_blocks(),
674 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
677 * On success, it returns the number of blocks being mapped or allocated.
678 * If flags doesn't contain EXT4_GET_BLOCKS_CREATE the blocks are
679 * pre-allocated and unwritten, the resulting @map is marked as unwritten.
680 * If the flags contain EXT4_GET_BLOCKS_CREATE, it will mark @map as mapped.
682 * It returns 0 if plain look up failed (blocks have not been allocated), in
683 * that case, @map is returned as unmapped but we still do fill map->m_len to
684 * indicate the length of a hole starting at map->m_lblk.
686 * It returns the error in case of allocation failure.
688 int ext4_map_blocks(handle_t *handle, struct inode *inode,
689 struct ext4_map_blocks *map, int flags)
691 struct extent_status es;
694 unsigned int orig_mlen = map->m_len;
695 #ifdef ES_AGGRESSIVE_TEST
696 struct ext4_map_blocks orig_map;
698 memcpy(&orig_map, map, sizeof(*map));
702 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
703 flags, map->m_len, (unsigned long) map->m_lblk);
706 * ext4_map_blocks returns an int, and m_len is an unsigned int
708 if (unlikely(map->m_len > INT_MAX))
709 map->m_len = INT_MAX;
711 /* We can handle the block number less than EXT_MAX_BLOCKS */
712 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
713 return -EFSCORRUPTED;
716 * Callers from the context of data submission are the only exceptions
717 * for regular files that do not hold the i_rwsem or invalidate_lock.
718 * However, caching unrelated ranges is not permitted.
720 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
721 WARN_ON_ONCE(!(flags & EXT4_EX_NOCACHE));
723 ext4_check_map_extents_env(inode);
725 /* Lookup extent status tree firstly */
726 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
727 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
728 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
729 map->m_pblk = ext4_es_pblock(&es) +
730 map->m_lblk - es.es_lblk;
731 map->m_flags |= ext4_es_is_written(&es) ?
732 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
733 retval = es.es_len - (map->m_lblk - es.es_lblk);
734 if (retval > map->m_len)
737 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
739 map->m_flags |= ext4_es_is_delayed(&es) ?
740 EXT4_MAP_DELAYED : 0;
741 retval = es.es_len - (map->m_lblk - es.es_lblk);
742 if (retval > map->m_len)
750 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
752 #ifdef ES_AGGRESSIVE_TEST
753 ext4_map_blocks_es_recheck(handle, inode, map,
756 if (!(flags & EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF) ||
757 orig_mlen == map->m_len)
760 if (flags & EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF)
761 map->m_len = orig_mlen;
764 * In the query cache no-wait mode, nothing we can do more if we
765 * cannot find extent in the cache.
767 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
771 * Try to see if we can get the block without requesting a new
774 down_read(&EXT4_I(inode)->i_data_sem);
775 retval = ext4_map_query_blocks(handle, inode, map, flags);
776 up_read((&EXT4_I(inode)->i_data_sem));
779 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
780 ret = check_block_validity(inode, map);
785 /* If it is only a block(s) look up */
786 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
790 * Returns if the blocks have already allocated
792 * Note that if blocks have been preallocated
793 * ext4_ext_map_blocks() returns with buffer head unmapped
795 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
797 * If we need to convert extent to unwritten
798 * we continue and do the actual work in
799 * ext4_ext_map_blocks()
801 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
805 ext4_fc_track_inode(handle, inode);
807 * New blocks allocate and/or writing to unwritten extent
808 * will possibly result in updating i_data, so we take
809 * the write lock of i_data_sem, and call get_block()
810 * with create == 1 flag.
812 down_write(&EXT4_I(inode)->i_data_sem);
813 retval = ext4_map_create_blocks(handle, inode, map, flags);
814 up_write((&EXT4_I(inode)->i_data_sem));
815 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
816 ret = check_block_validity(inode, map);
821 * Inodes with freshly allocated blocks where contents will be
822 * visible after transaction commit must be on transaction's
825 if (map->m_flags & EXT4_MAP_NEW &&
826 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
827 !(flags & EXT4_GET_BLOCKS_ZERO) &&
828 !ext4_is_quota_file(inode) &&
829 ext4_should_order_data(inode)) {
831 (loff_t)map->m_lblk << inode->i_blkbits;
832 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
834 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
835 ret = ext4_jbd2_inode_add_wait(handle, inode,
838 ret = ext4_jbd2_inode_add_write(handle, inode,
844 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
845 map->m_flags & EXT4_MAP_MAPPED))
846 ext4_fc_track_range(handle, inode, map->m_lblk,
847 map->m_lblk + map->m_len - 1);
849 ext_debug(inode, "failed with err %d\n", retval);
854 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
855 * we have to be careful as someone else may be manipulating b_state as well.
857 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
859 unsigned long old_state;
860 unsigned long new_state;
862 flags &= EXT4_MAP_FLAGS;
864 /* Dummy buffer_head? Set non-atomically. */
866 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
870 * Someone else may be modifying b_state. Be careful! This is ugly but
871 * once we get rid of using bh as a container for mapping information
872 * to pass to / from get_block functions, this can go away.
874 old_state = READ_ONCE(bh->b_state);
876 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
877 } while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
880 static int _ext4_get_block(struct inode *inode, sector_t iblock,
881 struct buffer_head *bh, int flags)
883 struct ext4_map_blocks map;
886 if (ext4_has_inline_data(inode))
890 map.m_len = bh->b_size >> inode->i_blkbits;
892 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
895 map_bh(bh, inode->i_sb, map.m_pblk);
896 ext4_update_bh_state(bh, map.m_flags);
897 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
899 } else if (ret == 0) {
900 /* hole case, need to fill in bh->b_size */
901 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
906 int ext4_get_block(struct inode *inode, sector_t iblock,
907 struct buffer_head *bh, int create)
909 return _ext4_get_block(inode, iblock, bh,
910 create ? EXT4_GET_BLOCKS_CREATE : 0);
914 * Get block function used when preparing for buffered write if we require
915 * creating an unwritten extent if blocks haven't been allocated. The extent
916 * will be converted to written after the IO is complete.
918 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
919 struct buffer_head *bh_result, int create)
923 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
924 inode->i_ino, create);
925 ret = _ext4_get_block(inode, iblock, bh_result,
926 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
929 * If the buffer is marked unwritten, mark it as new to make sure it is
930 * zeroed out correctly in case of partial writes. Otherwise, there is
931 * a chance of stale data getting exposed.
933 if (ret == 0 && buffer_unwritten(bh_result))
934 set_buffer_new(bh_result);
939 /* Maximum number of blocks we map for direct IO at once. */
940 #define DIO_MAX_BLOCKS 4096
943 * `handle' can be NULL if create is zero
945 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
946 ext4_lblk_t block, int map_flags)
948 struct ext4_map_blocks map;
949 struct buffer_head *bh;
950 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
951 bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
954 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
955 || handle != NULL || create == 0);
956 ASSERT(create == 0 || !nowait);
960 err = ext4_map_blocks(handle, inode, &map, map_flags);
963 return create ? ERR_PTR(-ENOSPC) : NULL;
968 return sb_find_get_block(inode->i_sb, map.m_pblk);
971 * Since bh could introduce extra ref count such as referred by
972 * journal_head etc. Try to avoid using __GFP_MOVABLE here
973 * as it may fail the migration when journal_head remains.
975 bh = getblk_unmovable(inode->i_sb->s_bdev, map.m_pblk,
976 inode->i_sb->s_blocksize);
979 return ERR_PTR(-ENOMEM);
980 if (map.m_flags & EXT4_MAP_NEW) {
982 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
983 || (handle != NULL));
986 * Now that we do not always journal data, we should
987 * keep in mind whether this should always journal the
988 * new buffer as metadata. For now, regular file
989 * writes use ext4_get_block instead, so it's not a
993 BUFFER_TRACE(bh, "call get_create_access");
994 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
1000 if (!buffer_uptodate(bh)) {
1001 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1002 set_buffer_uptodate(bh);
1005 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1006 err = ext4_handle_dirty_metadata(handle, inode, bh);
1010 BUFFER_TRACE(bh, "not a new buffer");
1014 return ERR_PTR(err);
1017 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1018 ext4_lblk_t block, int map_flags)
1020 struct buffer_head *bh;
1023 bh = ext4_getblk(handle, inode, block, map_flags);
1026 if (!bh || ext4_buffer_uptodate(bh))
1029 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
1032 return ERR_PTR(ret);
1037 /* Read a contiguous batch of blocks. */
1038 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
1039 bool wait, struct buffer_head **bhs)
1043 for (i = 0; i < bh_count; i++) {
1044 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
1045 if (IS_ERR(bhs[i])) {
1046 err = PTR_ERR(bhs[i]);
1052 for (i = 0; i < bh_count; i++)
1053 /* Note that NULL bhs[i] is valid because of holes. */
1054 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
1055 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
1060 for (i = 0; i < bh_count; i++)
1062 wait_on_buffer(bhs[i]);
1064 for (i = 0; i < bh_count; i++) {
1065 if (bhs[i] && !buffer_uptodate(bhs[i])) {
1073 for (i = 0; i < bh_count; i++) {
1080 int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
1081 struct buffer_head *head,
1085 int (*fn)(handle_t *handle, struct inode *inode,
1086 struct buffer_head *bh))
1088 struct buffer_head *bh;
1089 unsigned block_start, block_end;
1090 unsigned blocksize = head->b_size;
1092 struct buffer_head *next;
1094 for (bh = head, block_start = 0;
1095 ret == 0 && (bh != head || !block_start);
1096 block_start = block_end, bh = next) {
1097 next = bh->b_this_page;
1098 block_end = block_start + blocksize;
1099 if (block_end <= from || block_start >= to) {
1100 if (partial && !buffer_uptodate(bh))
1104 err = (*fn)(handle, inode, bh);
1112 * Helper for handling dirtying of journalled data. We also mark the folio as
1113 * dirty so that writeback code knows about this page (and inode) contains
1114 * dirty data. ext4_writepages() then commits appropriate transaction to
1117 static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
1119 struct folio *folio = bh->b_folio;
1120 struct inode *inode = folio->mapping->host;
1122 /* only regular files have a_ops */
1123 if (S_ISREG(inode->i_mode))
1124 folio_mark_dirty(folio);
1125 return ext4_handle_dirty_metadata(handle, NULL, bh);
1128 int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1129 struct buffer_head *bh)
1131 if (!buffer_mapped(bh) || buffer_freed(bh))
1133 BUFFER_TRACE(bh, "get write access");
1134 return ext4_journal_get_write_access(handle, inode->i_sb, bh,
1138 int ext4_block_write_begin(handle_t *handle, struct folio *folio,
1139 loff_t pos, unsigned len,
1140 get_block_t *get_block)
1142 unsigned int from = offset_in_folio(folio, pos);
1143 unsigned to = from + len;
1144 struct inode *inode = folio->mapping->host;
1145 unsigned block_start, block_end;
1148 unsigned blocksize = inode->i_sb->s_blocksize;
1150 struct buffer_head *bh, *head, *wait[2];
1153 bool should_journal_data = ext4_should_journal_data(inode);
1155 BUG_ON(!folio_test_locked(folio));
1156 BUG_ON(to > folio_size(folio));
1159 head = folio_buffers(folio);
1161 head = create_empty_buffers(folio, blocksize, 0);
1162 bbits = ilog2(blocksize);
1163 block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
1165 for (bh = head, block_start = 0; bh != head || !block_start;
1166 block++, block_start = block_end, bh = bh->b_this_page) {
1167 block_end = block_start + blocksize;
1168 if (block_end <= from || block_start >= to) {
1169 if (folio_test_uptodate(folio)) {
1170 set_buffer_uptodate(bh);
1175 clear_buffer_new(bh);
1176 if (!buffer_mapped(bh)) {
1177 WARN_ON(bh->b_size != blocksize);
1178 err = get_block(inode, block, bh, 1);
1181 if (buffer_new(bh)) {
1183 * We may be zeroing partial buffers or all new
1184 * buffers in case of failure. Prepare JBD2 for
1187 if (should_journal_data)
1188 do_journal_get_write_access(handle,
1190 if (folio_test_uptodate(folio)) {
1192 * Unlike __block_write_begin() we leave
1193 * dirtying of new uptodate buffers to
1194 * ->write_end() time or
1195 * folio_zero_new_buffers().
1197 set_buffer_uptodate(bh);
1200 if (block_end > to || block_start < from)
1201 folio_zero_segments(folio, to,
1207 if (folio_test_uptodate(folio)) {
1208 set_buffer_uptodate(bh);
1211 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1212 !buffer_unwritten(bh) &&
1213 (block_start < from || block_end > to)) {
1214 ext4_read_bh_lock(bh, 0, false);
1215 wait[nr_wait++] = bh;
1219 * If we issued read requests, let them complete.
1221 for (i = 0; i < nr_wait; i++) {
1222 wait_on_buffer(wait[i]);
1223 if (!buffer_uptodate(wait[i]))
1226 if (unlikely(err)) {
1227 if (should_journal_data)
1228 ext4_journalled_zero_new_buffers(handle, inode, folio,
1231 folio_zero_new_buffers(folio, from, to);
1232 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1233 for (i = 0; i < nr_wait; i++) {
1236 err2 = fscrypt_decrypt_pagecache_blocks(folio,
1237 blocksize, bh_offset(wait[i]));
1239 clear_buffer_uptodate(wait[i]);
1249 * To preserve ordering, it is essential that the hole instantiation and
1250 * the data write be encapsulated in a single transaction. We cannot
1251 * close off a transaction and start a new one between the ext4_get_block()
1252 * and the ext4_write_end(). So doing the jbd2_journal_start at the start of
1253 * ext4_write_begin() is the right place.
1255 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1256 loff_t pos, unsigned len,
1257 struct folio **foliop, void **fsdata)
1259 struct inode *inode = mapping->host;
1260 int ret, needed_blocks;
1263 struct folio *folio;
1266 fgf_t fgp = FGP_WRITEBEGIN;
1268 ret = ext4_emergency_state(inode->i_sb);
1272 trace_ext4_write_begin(inode, pos, len);
1274 * Reserve one block more for addition to orphan list in case
1275 * we allocate blocks but write fails for some reason
1277 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1278 index = pos >> PAGE_SHIFT;
1280 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1281 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1290 * __filemap_get_folio() can take a long time if the
1291 * system is thrashing due to memory pressure, or if the folio
1292 * is being written back. So grab it first before we start
1293 * the transaction handle. This also allows us to allocate
1294 * the folio (if needed) without using GFP_NOFS.
1297 fgp |= fgf_set_order(len);
1298 folio = __filemap_get_folio(mapping, index, fgp,
1299 mapping_gfp_mask(mapping));
1301 return PTR_ERR(folio);
1303 if (pos + len > folio_pos(folio) + folio_size(folio))
1304 len = folio_pos(folio) + folio_size(folio) - pos;
1306 from = offset_in_folio(folio, pos);
1310 * The same as page allocation, we prealloc buffer heads before
1311 * starting the handle.
1313 if (!folio_buffers(folio))
1314 create_empty_buffers(folio, inode->i_sb->s_blocksize, 0);
1316 folio_unlock(folio);
1319 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1320 if (IS_ERR(handle)) {
1322 return PTR_ERR(handle);
1326 if (folio->mapping != mapping) {
1327 /* The folio got truncated from under us */
1328 folio_unlock(folio);
1330 ext4_journal_stop(handle);
1333 /* In case writeback began while the folio was unlocked */
1334 folio_wait_stable(folio);
1336 if (ext4_should_dioread_nolock(inode))
1337 ret = ext4_block_write_begin(handle, folio, pos, len,
1338 ext4_get_block_unwritten);
1340 ret = ext4_block_write_begin(handle, folio, pos, len,
1342 if (!ret && ext4_should_journal_data(inode)) {
1343 ret = ext4_walk_page_buffers(handle, inode,
1344 folio_buffers(folio), from, to,
1345 NULL, do_journal_get_write_access);
1349 bool extended = (pos + len > inode->i_size) &&
1350 !ext4_verity_in_progress(inode);
1352 folio_unlock(folio);
1354 * ext4_block_write_begin may have instantiated a few blocks
1355 * outside i_size. Trim these off again. Don't need
1356 * i_size_read because we hold i_rwsem.
1358 * Add inode to orphan list in case we crash before
1361 if (extended && ext4_can_truncate(inode))
1362 ext4_orphan_add(handle, inode);
1364 ext4_journal_stop(handle);
1366 ext4_truncate_failed_write(inode);
1368 * If truncate failed early the inode might
1369 * still be on the orphan list; we need to
1370 * make sure the inode is removed from the
1371 * orphan list in that case.
1374 ext4_orphan_del(NULL, inode);
1377 if (ret == -ENOSPC &&
1378 ext4_should_retry_alloc(inode->i_sb, &retries))
1387 /* For write_end() in data=journal mode */
1388 static int write_end_fn(handle_t *handle, struct inode *inode,
1389 struct buffer_head *bh)
1392 if (!buffer_mapped(bh) || buffer_freed(bh))
1394 set_buffer_uptodate(bh);
1395 ret = ext4_dirty_journalled_data(handle, bh);
1396 clear_buffer_meta(bh);
1397 clear_buffer_prio(bh);
1402 * We need to pick up the new inode size which generic_commit_write gave us
1403 * `file' can be NULL - eg, when called from page_symlink().
1405 * ext4 never places buffers on inode->i_mapping->i_private_list. metadata
1406 * buffers are managed internally.
1408 static int ext4_write_end(struct file *file,
1409 struct address_space *mapping,
1410 loff_t pos, unsigned len, unsigned copied,
1411 struct folio *folio, void *fsdata)
1413 handle_t *handle = ext4_journal_current_handle();
1414 struct inode *inode = mapping->host;
1415 loff_t old_size = inode->i_size;
1417 int i_size_changed = 0;
1418 bool verity = ext4_verity_in_progress(inode);
1420 trace_ext4_write_end(inode, pos, len, copied);
1422 if (ext4_has_inline_data(inode) &&
1423 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1424 return ext4_write_inline_data_end(inode, pos, len, copied,
1427 copied = block_write_end(file, mapping, pos, len, copied, folio, fsdata);
1429 * it's important to update i_size while still holding folio lock:
1430 * page writeout could otherwise come in and zero beyond i_size.
1432 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1433 * blocks are being written past EOF, so skip the i_size update.
1436 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1437 folio_unlock(folio);
1440 if (old_size < pos && !verity) {
1441 pagecache_isize_extended(inode, old_size, pos);
1442 ext4_zero_partial_blocks(handle, inode, old_size, pos - old_size);
1445 * Don't mark the inode dirty under folio lock. First, it unnecessarily
1446 * makes the holding time of folio lock longer. Second, it forces lock
1447 * ordering of folio lock and transaction start for journaling
1451 ret = ext4_mark_inode_dirty(handle, inode);
1453 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1454 /* if we have allocated more blocks and copied
1455 * less. We will have blocks allocated outside
1456 * inode->i_size. So truncate them
1458 ext4_orphan_add(handle, inode);
1460 ret2 = ext4_journal_stop(handle);
1464 if (pos + len > inode->i_size && !verity) {
1465 ext4_truncate_failed_write(inode);
1467 * If truncate failed early the inode might still be
1468 * on the orphan list; we need to make sure the inode
1469 * is removed from the orphan list in that case.
1472 ext4_orphan_del(NULL, inode);
1475 return ret ? ret : copied;
1479 * This is a private version of folio_zero_new_buffers() which doesn't
1480 * set the buffer to be dirty, since in data=journalled mode we need
1481 * to call ext4_dirty_journalled_data() instead.
1483 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1484 struct inode *inode,
1485 struct folio *folio,
1486 unsigned from, unsigned to)
1488 unsigned int block_start = 0, block_end;
1489 struct buffer_head *head, *bh;
1491 bh = head = folio_buffers(folio);
1493 block_end = block_start + bh->b_size;
1494 if (buffer_new(bh)) {
1495 if (block_end > from && block_start < to) {
1496 if (!folio_test_uptodate(folio)) {
1497 unsigned start, size;
1499 start = max(from, block_start);
1500 size = min(to, block_end) - start;
1502 folio_zero_range(folio, start, size);
1504 clear_buffer_new(bh);
1505 write_end_fn(handle, inode, bh);
1508 block_start = block_end;
1509 bh = bh->b_this_page;
1510 } while (bh != head);
1513 static int ext4_journalled_write_end(struct file *file,
1514 struct address_space *mapping,
1515 loff_t pos, unsigned len, unsigned copied,
1516 struct folio *folio, void *fsdata)
1518 handle_t *handle = ext4_journal_current_handle();
1519 struct inode *inode = mapping->host;
1520 loff_t old_size = inode->i_size;
1524 int size_changed = 0;
1525 bool verity = ext4_verity_in_progress(inode);
1527 trace_ext4_journalled_write_end(inode, pos, len, copied);
1528 from = pos & (PAGE_SIZE - 1);
1531 BUG_ON(!ext4_handle_valid(handle));
1533 if (ext4_has_inline_data(inode))
1534 return ext4_write_inline_data_end(inode, pos, len, copied,
1537 if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
1539 ext4_journalled_zero_new_buffers(handle, inode, folio,
1542 if (unlikely(copied < len))
1543 ext4_journalled_zero_new_buffers(handle, inode, folio,
1545 ret = ext4_walk_page_buffers(handle, inode,
1546 folio_buffers(folio),
1547 from, from + copied, &partial,
1550 folio_mark_uptodate(folio);
1553 size_changed = ext4_update_inode_size(inode, pos + copied);
1554 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1555 folio_unlock(folio);
1558 if (old_size < pos && !verity) {
1559 pagecache_isize_extended(inode, old_size, pos);
1560 ext4_zero_partial_blocks(handle, inode, old_size, pos - old_size);
1564 ret2 = ext4_mark_inode_dirty(handle, inode);
1569 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1570 /* if we have allocated more blocks and copied
1571 * less. We will have blocks allocated outside
1572 * inode->i_size. So truncate them
1574 ext4_orphan_add(handle, inode);
1576 ret2 = ext4_journal_stop(handle);
1579 if (pos + len > inode->i_size && !verity) {
1580 ext4_truncate_failed_write(inode);
1582 * If truncate failed early the inode might still be
1583 * on the orphan list; we need to make sure the inode
1584 * is removed from the orphan list in that case.
1587 ext4_orphan_del(NULL, inode);
1590 return ret ? ret : copied;
1594 * Reserve space for 'nr_resv' clusters
1596 static int ext4_da_reserve_space(struct inode *inode, int nr_resv)
1598 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1599 struct ext4_inode_info *ei = EXT4_I(inode);
1603 * We will charge metadata quota at writeout time; this saves
1604 * us from metadata over-estimation, though we may go over by
1605 * a small amount in the end. Here we just reserve for data.
1607 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, nr_resv));
1611 spin_lock(&ei->i_block_reservation_lock);
1612 if (ext4_claim_free_clusters(sbi, nr_resv, 0)) {
1613 spin_unlock(&ei->i_block_reservation_lock);
1614 dquot_release_reservation_block(inode, EXT4_C2B(sbi, nr_resv));
1617 ei->i_reserved_data_blocks += nr_resv;
1618 trace_ext4_da_reserve_space(inode, nr_resv);
1619 spin_unlock(&ei->i_block_reservation_lock);
1621 return 0; /* success */
1624 void ext4_da_release_space(struct inode *inode, int to_free)
1626 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1627 struct ext4_inode_info *ei = EXT4_I(inode);
1630 return; /* Nothing to release, exit */
1632 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1634 trace_ext4_da_release_space(inode, to_free);
1635 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1637 * if there aren't enough reserved blocks, then the
1638 * counter is messed up somewhere. Since this
1639 * function is called from invalidate page, it's
1640 * harmless to return without any action.
1642 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1643 "ino %lu, to_free %d with only %d reserved "
1644 "data blocks", inode->i_ino, to_free,
1645 ei->i_reserved_data_blocks);
1647 to_free = ei->i_reserved_data_blocks;
1649 ei->i_reserved_data_blocks -= to_free;
1651 /* update fs dirty data blocks counter */
1652 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1654 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1656 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1660 * Delayed allocation stuff
1663 struct mpage_da_data {
1664 /* These are input fields for ext4_do_writepages() */
1665 struct inode *inode;
1666 struct writeback_control *wbc;
1667 unsigned int can_map:1; /* Can writepages call map blocks? */
1669 /* These are internal state of ext4_do_writepages() */
1670 pgoff_t first_page; /* The first page to write */
1671 pgoff_t next_page; /* Current page to examine */
1672 pgoff_t last_page; /* Last page to examine */
1674 * Extent to map - this can be after first_page because that can be
1675 * fully mapped. We somewhat abuse m_flags to store whether the extent
1676 * is delalloc or unwritten.
1678 struct ext4_map_blocks map;
1679 struct ext4_io_submit io_submit; /* IO submission data */
1680 unsigned int do_map:1;
1681 unsigned int scanned_until_end:1;
1682 unsigned int journalled_more_data:1;
1685 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1690 struct folio_batch fbatch;
1691 struct inode *inode = mpd->inode;
1692 struct address_space *mapping = inode->i_mapping;
1694 /* This is necessary when next_page == 0. */
1695 if (mpd->first_page >= mpd->next_page)
1698 mpd->scanned_until_end = 0;
1699 index = mpd->first_page;
1700 end = mpd->next_page - 1;
1702 ext4_lblk_t start, last;
1703 start = index << (PAGE_SHIFT - inode->i_blkbits);
1704 last = end << (PAGE_SHIFT - inode->i_blkbits);
1707 * avoid racing with extent status tree scans made by
1708 * ext4_insert_delayed_block()
1710 down_write(&EXT4_I(inode)->i_data_sem);
1711 ext4_es_remove_extent(inode, start, last - start + 1);
1712 up_write(&EXT4_I(inode)->i_data_sem);
1715 folio_batch_init(&fbatch);
1716 while (index <= end) {
1717 nr = filemap_get_folios(mapping, &index, end, &fbatch);
1720 for (i = 0; i < nr; i++) {
1721 struct folio *folio = fbatch.folios[i];
1723 if (folio->index < mpd->first_page)
1725 if (folio_next_index(folio) - 1 > end)
1727 BUG_ON(!folio_test_locked(folio));
1728 BUG_ON(folio_test_writeback(folio));
1730 if (folio_mapped(folio))
1731 folio_clear_dirty_for_io(folio);
1732 block_invalidate_folio(folio, 0,
1734 folio_clear_uptodate(folio);
1736 folio_unlock(folio);
1738 folio_batch_release(&fbatch);
1742 static void ext4_print_free_blocks(struct inode *inode)
1744 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1745 struct super_block *sb = inode->i_sb;
1746 struct ext4_inode_info *ei = EXT4_I(inode);
1748 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1749 EXT4_C2B(EXT4_SB(inode->i_sb),
1750 ext4_count_free_clusters(sb)));
1751 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1752 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1753 (long long) EXT4_C2B(EXT4_SB(sb),
1754 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1755 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1756 (long long) EXT4_C2B(EXT4_SB(sb),
1757 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1758 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1759 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1760 ei->i_reserved_data_blocks);
1765 * Check whether the cluster containing lblk has been allocated or has
1766 * delalloc reservation.
1768 * Returns 0 if the cluster doesn't have either, 1 if it has delalloc
1769 * reservation, 2 if it's already been allocated, negative error code on
1772 static int ext4_clu_alloc_state(struct inode *inode, ext4_lblk_t lblk)
1774 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1777 /* Has delalloc reservation? */
1778 if (ext4_es_scan_clu(inode, &ext4_es_is_delayed, lblk))
1781 /* Already been allocated? */
1782 if (ext4_es_scan_clu(inode, &ext4_es_is_mapped, lblk))
1784 ret = ext4_clu_mapped(inode, EXT4_B2C(sbi, lblk));
1794 * ext4_insert_delayed_blocks - adds a multiple delayed blocks to the extents
1795 * status tree, incrementing the reserved
1796 * cluster/block count or making pending
1797 * reservations where needed
1799 * @inode - file containing the newly added block
1800 * @lblk - start logical block to be added
1801 * @len - length of blocks to be added
1803 * Returns 0 on success, negative error code on failure.
1805 static int ext4_insert_delayed_blocks(struct inode *inode, ext4_lblk_t lblk,
1808 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1810 bool lclu_allocated = false;
1811 bool end_allocated = false;
1812 ext4_lblk_t resv_clu;
1813 ext4_lblk_t end = lblk + len - 1;
1816 * If the cluster containing lblk or end is shared with a delayed,
1817 * written, or unwritten extent in a bigalloc file system, it's
1818 * already been accounted for and does not need to be reserved.
1819 * A pending reservation must be made for the cluster if it's
1820 * shared with a written or unwritten extent and doesn't already
1821 * have one. Written and unwritten extents can be purged from the
1822 * extents status tree if the system is under memory pressure, so
1823 * it's necessary to examine the extent tree if a search of the
1824 * extents status tree doesn't get a match.
1826 if (sbi->s_cluster_ratio == 1) {
1827 ret = ext4_da_reserve_space(inode, len);
1828 if (ret != 0) /* ENOSPC */
1830 } else { /* bigalloc */
1831 resv_clu = EXT4_B2C(sbi, end) - EXT4_B2C(sbi, lblk) + 1;
1833 ret = ext4_clu_alloc_state(inode, lblk);
1838 lclu_allocated = (ret == 2);
1841 if (EXT4_B2C(sbi, lblk) != EXT4_B2C(sbi, end)) {
1842 ret = ext4_clu_alloc_state(inode, end);
1847 end_allocated = (ret == 2);
1852 ret = ext4_da_reserve_space(inode, resv_clu);
1853 if (ret != 0) /* ENOSPC */
1858 ext4_es_insert_delayed_extent(inode, lblk, len, lclu_allocated,
1864 * Looks up the requested blocks and sets the delalloc extent map.
1865 * First try to look up for the extent entry that contains the requested
1866 * blocks in the extent status tree without i_data_sem, then try to look
1867 * up for the ondisk extent mapping with i_data_sem in read mode,
1868 * finally hold i_data_sem in write mode, looks up again and add a
1869 * delalloc extent entry if it still couldn't find any extent. Pass out
1870 * the mapped extent through @map and return 0 on success.
1872 static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map)
1874 struct extent_status es;
1876 #ifdef ES_AGGRESSIVE_TEST
1877 struct ext4_map_blocks orig_map;
1879 memcpy(&orig_map, map, sizeof(*map));
1883 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1884 (unsigned long) map->m_lblk);
1886 ext4_check_map_extents_env(inode);
1888 /* Lookup extent status tree firstly */
1889 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
1890 map->m_len = min_t(unsigned int, map->m_len,
1891 es.es_len - (map->m_lblk - es.es_lblk));
1893 if (ext4_es_is_hole(&es))
1898 * Delayed extent could be allocated by fallocate.
1899 * So we need to check it.
1901 if (ext4_es_is_delayed(&es)) {
1902 map->m_flags |= EXT4_MAP_DELAYED;
1906 map->m_pblk = ext4_es_pblock(&es) + map->m_lblk - es.es_lblk;
1907 if (ext4_es_is_written(&es))
1908 map->m_flags |= EXT4_MAP_MAPPED;
1909 else if (ext4_es_is_unwritten(&es))
1910 map->m_flags |= EXT4_MAP_UNWRITTEN;
1914 #ifdef ES_AGGRESSIVE_TEST
1915 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1921 * Try to see if we can get the block without requesting a new
1922 * file system block.
1924 down_read(&EXT4_I(inode)->i_data_sem);
1925 if (ext4_has_inline_data(inode))
1928 retval = ext4_map_query_blocks(NULL, inode, map, 0);
1929 up_read(&EXT4_I(inode)->i_data_sem);
1931 return retval < 0 ? retval : 0;
1934 down_write(&EXT4_I(inode)->i_data_sem);
1936 * Page fault path (ext4_page_mkwrite does not take i_rwsem)
1937 * and fallocate path (no folio lock) can race. Make sure we
1938 * lookup the extent status tree here again while i_data_sem
1939 * is held in write mode, before inserting a new da entry in
1940 * the extent status tree.
1942 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
1943 map->m_len = min_t(unsigned int, map->m_len,
1944 es.es_len - (map->m_lblk - es.es_lblk));
1946 if (!ext4_es_is_hole(&es)) {
1947 up_write(&EXT4_I(inode)->i_data_sem);
1950 } else if (!ext4_has_inline_data(inode)) {
1951 retval = ext4_map_query_blocks(NULL, inode, map, 0);
1953 up_write(&EXT4_I(inode)->i_data_sem);
1954 return retval < 0 ? retval : 0;
1958 map->m_flags |= EXT4_MAP_DELAYED;
1959 retval = ext4_insert_delayed_blocks(inode, map->m_lblk, map->m_len);
1960 up_write(&EXT4_I(inode)->i_data_sem);
1966 * This is a special get_block_t callback which is used by
1967 * ext4_da_write_begin(). It will either return mapped block or
1968 * reserve space for a single block.
1970 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1971 * We also have b_blocknr = -1 and b_bdev initialized properly
1973 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1974 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1975 * initialized properly.
1977 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1978 struct buffer_head *bh, int create)
1980 struct ext4_map_blocks map;
1981 sector_t invalid_block = ~((sector_t) 0xffff);
1984 BUG_ON(create == 0);
1985 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1987 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1990 map.m_lblk = iblock;
1994 * first, we need to know whether the block is allocated already
1995 * preallocated blocks are unmapped but should treated
1996 * the same as allocated blocks.
1998 ret = ext4_da_map_blocks(inode, &map);
2002 if (map.m_flags & EXT4_MAP_DELAYED) {
2003 map_bh(bh, inode->i_sb, invalid_block);
2005 set_buffer_delay(bh);
2009 map_bh(bh, inode->i_sb, map.m_pblk);
2010 ext4_update_bh_state(bh, map.m_flags);
2012 if (buffer_unwritten(bh)) {
2013 /* A delayed write to unwritten bh should be marked
2014 * new and mapped. Mapped ensures that we don't do
2015 * get_block multiple times when we write to the same
2016 * offset and new ensures that we do proper zero out
2017 * for partial write.
2020 set_buffer_mapped(bh);
2025 static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
2027 mpd->first_page += folio_nr_pages(folio);
2028 folio_unlock(folio);
2031 static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
2037 BUG_ON(folio->index != mpd->first_page);
2038 folio_clear_dirty_for_io(folio);
2040 * We have to be very careful here! Nothing protects writeback path
2041 * against i_size changes and the page can be writeably mapped into
2042 * page tables. So an application can be growing i_size and writing
2043 * data through mmap while writeback runs. folio_clear_dirty_for_io()
2044 * write-protects our page in page tables and the page cannot get
2045 * written to again until we release folio lock. So only after
2046 * folio_clear_dirty_for_io() we are safe to sample i_size for
2047 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
2048 * on the barrier provided by folio_test_clear_dirty() in
2049 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
2050 * after page tables are updated.
2052 size = i_size_read(mpd->inode);
2053 len = folio_size(folio);
2054 if (folio_pos(folio) + len > size &&
2055 !ext4_verity_in_progress(mpd->inode))
2056 len = size & (len - 1);
2057 err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
2059 mpd->wbc->nr_to_write -= folio_nr_pages(folio);
2064 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2067 * mballoc gives us at most this number of blocks...
2068 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2069 * The rest of mballoc seems to handle chunks up to full group size.
2071 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2074 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2076 * @mpd - extent of blocks
2077 * @lblk - logical number of the block in the file
2078 * @bh - buffer head we want to add to the extent
2080 * The function is used to collect contig. blocks in the same state. If the
2081 * buffer doesn't require mapping for writeback and we haven't started the
2082 * extent of buffers to map yet, the function returns 'true' immediately - the
2083 * caller can write the buffer right away. Otherwise the function returns true
2084 * if the block has been added to the extent, false if the block couldn't be
2087 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2088 struct buffer_head *bh)
2090 struct ext4_map_blocks *map = &mpd->map;
2092 /* Buffer that doesn't need mapping for writeback? */
2093 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2094 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2095 /* So far no extent to map => we write the buffer right away */
2096 if (map->m_len == 0)
2101 /* First block in the extent? */
2102 if (map->m_len == 0) {
2103 /* We cannot map unless handle is started... */
2108 map->m_flags = bh->b_state & BH_FLAGS;
2112 /* Don't go larger than mballoc is willing to allocate */
2113 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2116 /* Can we merge the block to our big extent? */
2117 if (lblk == map->m_lblk + map->m_len &&
2118 (bh->b_state & BH_FLAGS) == map->m_flags) {
2126 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2128 * @mpd - extent of blocks for mapping
2129 * @head - the first buffer in the page
2130 * @bh - buffer we should start processing from
2131 * @lblk - logical number of the block in the file corresponding to @bh
2133 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2134 * the page for IO if all buffers in this page were mapped and there's no
2135 * accumulated extent of buffers to map or add buffers in the page to the
2136 * extent of buffers to map. The function returns 1 if the caller can continue
2137 * by processing the next page, 0 if it should stop adding buffers to the
2138 * extent to map because we cannot extend it anymore. It can also return value
2139 * < 0 in case of error during IO submission.
2141 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2142 struct buffer_head *head,
2143 struct buffer_head *bh,
2146 struct inode *inode = mpd->inode;
2148 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2149 >> inode->i_blkbits;
2151 if (ext4_verity_in_progress(inode))
2152 blocks = EXT_MAX_BLOCKS;
2155 BUG_ON(buffer_locked(bh));
2157 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2158 /* Found extent to map? */
2161 /* Buffer needs mapping and handle is not started? */
2164 /* Everything mapped so far and we hit EOF */
2167 } while (lblk++, (bh = bh->b_this_page) != head);
2168 /* So far everything mapped? Submit the page for IO. */
2169 if (mpd->map.m_len == 0) {
2170 err = mpage_submit_folio(mpd, head->b_folio);
2173 mpage_folio_done(mpd, head->b_folio);
2175 if (lblk >= blocks) {
2176 mpd->scanned_until_end = 1;
2183 * mpage_process_folio - update folio buffers corresponding to changed extent
2184 * and may submit fully mapped page for IO
2185 * @mpd: description of extent to map, on return next extent to map
2186 * @folio: Contains these buffers.
2187 * @m_lblk: logical block mapping.
2188 * @m_pblk: corresponding physical mapping.
2189 * @map_bh: determines on return whether this page requires any further
2192 * Scan given folio buffers corresponding to changed extent and update buffer
2193 * state according to new extent state.
2194 * We map delalloc buffers to their physical location, clear unwritten bits.
2195 * If the given folio is not fully mapped, we update @mpd to the next extent in
2196 * the given folio that needs mapping & return @map_bh as true.
2198 static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
2199 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2202 struct buffer_head *head, *bh;
2203 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2204 ext4_lblk_t lblk = *m_lblk;
2205 ext4_fsblk_t pblock = *m_pblk;
2207 int blkbits = mpd->inode->i_blkbits;
2208 ssize_t io_end_size = 0;
2209 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2211 bh = head = folio_buffers(folio);
2213 if (lblk < mpd->map.m_lblk)
2215 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2217 * Buffer after end of mapped extent.
2218 * Find next buffer in the folio to map.
2221 mpd->map.m_flags = 0;
2222 io_end_vec->size += io_end_size;
2224 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2227 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2228 io_end_vec = ext4_alloc_io_end_vec(io_end);
2229 if (IS_ERR(io_end_vec)) {
2230 err = PTR_ERR(io_end_vec);
2233 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2238 if (buffer_delay(bh)) {
2239 clear_buffer_delay(bh);
2240 bh->b_blocknr = pblock++;
2242 clear_buffer_unwritten(bh);
2243 io_end_size += (1 << blkbits);
2244 } while (lblk++, (bh = bh->b_this_page) != head);
2246 io_end_vec->size += io_end_size;
2255 * mpage_map_buffers - update buffers corresponding to changed extent and
2256 * submit fully mapped pages for IO
2258 * @mpd - description of extent to map, on return next extent to map
2260 * Scan buffers corresponding to changed extent (we expect corresponding pages
2261 * to be already locked) and update buffer state according to new extent state.
2262 * We map delalloc buffers to their physical location, clear unwritten bits,
2263 * and mark buffers as uninit when we perform writes to unwritten extents
2264 * and do extent conversion after IO is finished. If the last page is not fully
2265 * mapped, we update @map to the next extent in the last page that needs
2266 * mapping. Otherwise we submit the page for IO.
2268 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2270 struct folio_batch fbatch;
2272 struct inode *inode = mpd->inode;
2273 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2276 ext4_fsblk_t pblock;
2278 bool map_bh = false;
2280 start = mpd->map.m_lblk >> bpp_bits;
2281 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2282 pblock = mpd->map.m_pblk;
2284 folio_batch_init(&fbatch);
2285 while (start <= end) {
2286 nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
2289 for (i = 0; i < nr; i++) {
2290 struct folio *folio = fbatch.folios[i];
2292 lblk = folio->index << bpp_bits;
2293 err = mpage_process_folio(mpd, folio, &lblk, &pblock,
2296 * If map_bh is true, means page may require further bh
2297 * mapping, or maybe the page was submitted for IO.
2298 * So we return to call further extent mapping.
2300 if (err < 0 || map_bh)
2302 /* Page fully mapped - let IO run! */
2303 err = mpage_submit_folio(mpd, folio);
2306 mpage_folio_done(mpd, folio);
2308 folio_batch_release(&fbatch);
2310 /* Extent fully mapped and matches with page boundary. We are done. */
2312 mpd->map.m_flags = 0;
2315 folio_batch_release(&fbatch);
2319 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2321 struct inode *inode = mpd->inode;
2322 struct ext4_map_blocks *map = &mpd->map;
2323 int get_blocks_flags;
2324 int err, dioread_nolock;
2326 trace_ext4_da_write_pages_extent(inode, map);
2328 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2329 * to convert an unwritten extent to be initialized (in the case
2330 * where we have written into one or more preallocated blocks). It is
2331 * possible that we're going to need more metadata blocks than
2332 * previously reserved. However we must not fail because we're in
2333 * writeback and there is nothing we can do about it so it might result
2334 * in data loss. So use reserved blocks to allocate metadata if
2335 * possible. In addition, do not cache any unrelated extents, as it
2336 * only holds the folio lock but does not hold the i_rwsem or
2337 * invalidate_lock, which could corrupt the extent status tree.
2339 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2340 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2341 EXT4_GET_BLOCKS_IO_SUBMIT |
2344 dioread_nolock = ext4_should_dioread_nolock(inode);
2346 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2348 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2351 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2352 if (!mpd->io_submit.io_end->handle &&
2353 ext4_handle_valid(handle)) {
2354 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2355 handle->h_rsv_handle = NULL;
2357 ext4_set_io_unwritten_flag(mpd->io_submit.io_end);
2360 BUG_ON(map->m_len == 0);
2365 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2366 * mpd->len and submit pages underlying it for IO
2368 * @handle - handle for journal operations
2369 * @mpd - extent to map
2370 * @give_up_on_write - we set this to true iff there is a fatal error and there
2371 * is no hope of writing the data. The caller should discard
2372 * dirty pages to avoid infinite loops.
2374 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2375 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2376 * them to initialized or split the described range from larger unwritten
2377 * extent. Note that we need not map all the described range since allocation
2378 * can return less blocks or the range is covered by more unwritten extents. We
2379 * cannot map more because we are limited by reserved transaction credits. On
2380 * the other hand we always make sure that the last touched page is fully
2381 * mapped so that it can be written out (and thus forward progress is
2382 * guaranteed). After mapping we submit all mapped pages for IO.
2384 static int mpage_map_and_submit_extent(handle_t *handle,
2385 struct mpage_da_data *mpd,
2386 bool *give_up_on_write)
2388 struct inode *inode = mpd->inode;
2389 struct ext4_map_blocks *map = &mpd->map;
2393 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2394 struct ext4_io_end_vec *io_end_vec;
2396 io_end_vec = ext4_alloc_io_end_vec(io_end);
2397 if (IS_ERR(io_end_vec))
2398 return PTR_ERR(io_end_vec);
2399 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2401 err = mpage_map_one_extent(handle, mpd);
2403 struct super_block *sb = inode->i_sb;
2405 if (ext4_emergency_state(sb))
2406 goto invalidate_dirty_pages;
2408 * Let the uper layers retry transient errors.
2409 * In the case of ENOSPC, if ext4_count_free_blocks()
2410 * is non-zero, a commit should free up blocks.
2412 if ((err == -ENOMEM) ||
2413 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2415 goto update_disksize;
2418 ext4_msg(sb, KERN_CRIT,
2419 "Delayed block allocation failed for "
2420 "inode %lu at logical offset %llu with"
2421 " max blocks %u with error %d",
2423 (unsigned long long)map->m_lblk,
2424 (unsigned)map->m_len, -err);
2425 ext4_msg(sb, KERN_CRIT,
2426 "This should not happen!! Data will "
2429 ext4_print_free_blocks(inode);
2430 invalidate_dirty_pages:
2431 *give_up_on_write = true;
2436 * Update buffer state, submit mapped pages, and get us new
2439 err = mpage_map_and_submit_buffers(mpd);
2441 goto update_disksize;
2442 } while (map->m_len);
2446 * Update on-disk size after IO is submitted. Races with
2447 * truncate are avoided by checking i_size under i_data_sem.
2449 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2450 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2454 down_write(&EXT4_I(inode)->i_data_sem);
2455 i_size = i_size_read(inode);
2456 if (disksize > i_size)
2458 if (disksize > EXT4_I(inode)->i_disksize)
2459 EXT4_I(inode)->i_disksize = disksize;
2460 up_write(&EXT4_I(inode)->i_data_sem);
2461 err2 = ext4_mark_inode_dirty(handle, inode);
2463 ext4_error_err(inode->i_sb, -err2,
2464 "Failed to mark inode %lu dirty",
2474 * Calculate the total number of credits to reserve for one writepages
2475 * iteration. This is called from ext4_writepages(). We map an extent of
2476 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2477 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2478 * bpp - 1 blocks in bpp different extents.
2480 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2482 int bpp = ext4_journal_blocks_per_folio(inode);
2484 return ext4_meta_trans_blocks(inode,
2485 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2488 static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
2491 struct buffer_head *page_bufs = folio_buffers(folio);
2492 struct inode *inode = folio->mapping->host;
2495 ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2496 NULL, do_journal_get_write_access);
2497 err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2498 NULL, write_end_fn);
2501 err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
2504 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2509 static int mpage_journal_page_buffers(handle_t *handle,
2510 struct mpage_da_data *mpd,
2511 struct folio *folio)
2513 struct inode *inode = mpd->inode;
2514 loff_t size = i_size_read(inode);
2515 size_t len = folio_size(folio);
2517 folio_clear_checked(folio);
2518 mpd->wbc->nr_to_write -= folio_nr_pages(folio);
2520 if (folio_pos(folio) + len > size &&
2521 !ext4_verity_in_progress(inode))
2522 len = size & (len - 1);
2524 return ext4_journal_folio_buffers(handle, folio, len);
2528 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2529 * needing mapping, submit mapped pages
2531 * @mpd - where to look for pages
2533 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2534 * IO immediately. If we cannot map blocks, we submit just already mapped
2535 * buffers in the page for IO and keep page dirty. When we can map blocks and
2536 * we find a page which isn't mapped we start accumulating extent of buffers
2537 * underlying these pages that needs mapping (formed by either delayed or
2538 * unwritten buffers). We also lock the pages containing these buffers. The
2539 * extent found is returned in @mpd structure (starting at mpd->lblk with
2540 * length mpd->len blocks).
2542 * Note that this function can attach bios to one io_end structure which are
2543 * neither logically nor physically contiguous. Although it may seem as an
2544 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2545 * case as we need to track IO to all buffers underlying a page in one io_end.
2547 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2549 struct address_space *mapping = mpd->inode->i_mapping;
2550 struct folio_batch fbatch;
2551 unsigned int nr_folios;
2552 pgoff_t index = mpd->first_page;
2553 pgoff_t end = mpd->last_page;
2556 int blkbits = mpd->inode->i_blkbits;
2558 struct buffer_head *head;
2559 handle_t *handle = NULL;
2560 int bpp = ext4_journal_blocks_per_folio(mpd->inode);
2562 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2563 tag = PAGECACHE_TAG_TOWRITE;
2565 tag = PAGECACHE_TAG_DIRTY;
2568 mpd->next_page = index;
2569 if (ext4_should_journal_data(mpd->inode)) {
2570 handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
2573 return PTR_ERR(handle);
2575 folio_batch_init(&fbatch);
2576 while (index <= end) {
2577 nr_folios = filemap_get_folios_tag(mapping, &index, end,
2582 for (i = 0; i < nr_folios; i++) {
2583 struct folio *folio = fbatch.folios[i];
2586 * Accumulated enough dirty pages? This doesn't apply
2587 * to WB_SYNC_ALL mode. For integrity sync we have to
2588 * keep going because someone may be concurrently
2589 * dirtying pages, and we might have synced a lot of
2590 * newly appeared dirty pages, but have not synced all
2591 * of the old dirty pages.
2593 if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2594 mpd->wbc->nr_to_write <=
2595 mpd->map.m_len >> (PAGE_SHIFT - blkbits))
2598 /* If we can't merge this page, we are done. */
2599 if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
2603 err = ext4_journal_ensure_credits(handle, bpp,
2611 * If the page is no longer dirty, or its mapping no
2612 * longer corresponds to inode we are writing (which
2613 * means it has been truncated or invalidated), or the
2614 * page is already under writeback and we are not doing
2615 * a data integrity writeback, skip the page
2617 if (!folio_test_dirty(folio) ||
2618 (folio_test_writeback(folio) &&
2619 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2620 unlikely(folio->mapping != mapping)) {
2621 folio_unlock(folio);
2625 folio_wait_writeback(folio);
2626 BUG_ON(folio_test_writeback(folio));
2629 * Should never happen but for buggy code in
2630 * other subsystems that call
2631 * set_page_dirty() without properly warning
2632 * the file system first. See [1] for more
2635 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2637 if (!folio_buffers(folio)) {
2638 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
2639 folio_clear_dirty(folio);
2640 folio_unlock(folio);
2644 if (mpd->map.m_len == 0)
2645 mpd->first_page = folio->index;
2646 mpd->next_page = folio_next_index(folio);
2648 * Writeout when we cannot modify metadata is simple.
2649 * Just submit the page. For data=journal mode we
2650 * first handle writeout of the page for checkpoint and
2651 * only after that handle delayed page dirtying. This
2652 * makes sure current data is checkpointed to the final
2653 * location before possibly journalling it again which
2654 * is desirable when the page is frequently dirtied
2657 if (!mpd->can_map) {
2658 err = mpage_submit_folio(mpd, folio);
2661 /* Pending dirtying of journalled data? */
2662 if (folio_test_checked(folio)) {
2663 err = mpage_journal_page_buffers(handle,
2667 mpd->journalled_more_data = 1;
2669 mpage_folio_done(mpd, folio);
2671 /* Add all dirty buffers to mpd */
2672 lblk = ((ext4_lblk_t)folio->index) <<
2673 (PAGE_SHIFT - blkbits);
2674 head = folio_buffers(folio);
2675 err = mpage_process_page_bufs(mpd, head, head,
2682 folio_batch_release(&fbatch);
2685 mpd->scanned_until_end = 1;
2687 ext4_journal_stop(handle);
2690 folio_batch_release(&fbatch);
2692 ext4_journal_stop(handle);
2696 static int ext4_do_writepages(struct mpage_da_data *mpd)
2698 struct writeback_control *wbc = mpd->wbc;
2699 pgoff_t writeback_index = 0;
2700 long nr_to_write = wbc->nr_to_write;
2701 int range_whole = 0;
2703 handle_t *handle = NULL;
2704 struct inode *inode = mpd->inode;
2705 struct address_space *mapping = inode->i_mapping;
2706 int needed_blocks, rsv_blocks = 0, ret = 0;
2707 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2708 struct blk_plug plug;
2709 bool give_up_on_write = false;
2711 trace_ext4_writepages(inode, wbc);
2714 * No pages to write? This is mainly a kludge to avoid starting
2715 * a transaction for special inodes like journal inode on last iput()
2716 * because that could violate lock ordering on umount
2718 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2719 goto out_writepages;
2722 * If the filesystem has aborted, it is read-only, so return
2723 * right away instead of dumping stack traces later on that
2724 * will obscure the real source of the problem. We test
2725 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
2726 * the latter could be true if the filesystem is mounted
2727 * read-only, and in that case, ext4_writepages should
2728 * *never* be called, so if that ever happens, we would want
2731 ret = ext4_emergency_state(mapping->host->i_sb);
2733 goto out_writepages;
2736 * If we have inline data and arrive here, it means that
2737 * we will soon create the block for the 1st page, so
2738 * we'd better clear the inline data here.
2740 if (ext4_has_inline_data(inode)) {
2741 /* Just inode will be modified... */
2742 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2743 if (IS_ERR(handle)) {
2744 ret = PTR_ERR(handle);
2745 goto out_writepages;
2747 BUG_ON(ext4_test_inode_state(inode,
2748 EXT4_STATE_MAY_INLINE_DATA));
2749 ext4_destroy_inline_data(handle, inode);
2750 ext4_journal_stop(handle);
2754 * data=journal mode does not do delalloc so we just need to writeout /
2755 * journal already mapped buffers. On the other hand we need to commit
2756 * transaction to make data stable. We expect all the data to be
2757 * already in the journal (the only exception are DMA pinned pages
2758 * dirtied behind our back) so we commit transaction here and run the
2759 * writeback loop to checkpoint them. The checkpointing is not actually
2760 * necessary to make data persistent *but* quite a few places (extent
2761 * shifting operations, fsverity, ...) depend on being able to drop
2762 * pagecache pages after calling filemap_write_and_wait() and for that
2763 * checkpointing needs to happen.
2765 if (ext4_should_journal_data(inode)) {
2767 if (wbc->sync_mode == WB_SYNC_ALL)
2768 ext4_fc_commit(sbi->s_journal,
2769 EXT4_I(inode)->i_datasync_tid);
2771 mpd->journalled_more_data = 0;
2773 if (ext4_should_dioread_nolock(inode)) {
2775 * We may need to convert up to one extent per block in
2776 * the page and we may dirty the inode.
2778 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2779 PAGE_SIZE >> inode->i_blkbits);
2782 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2785 if (wbc->range_cyclic) {
2786 writeback_index = mapping->writeback_index;
2787 if (writeback_index)
2789 mpd->first_page = writeback_index;
2790 mpd->last_page = -1;
2792 mpd->first_page = wbc->range_start >> PAGE_SHIFT;
2793 mpd->last_page = wbc->range_end >> PAGE_SHIFT;
2796 ext4_io_submit_init(&mpd->io_submit, wbc);
2798 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2799 tag_pages_for_writeback(mapping, mpd->first_page,
2801 blk_start_plug(&plug);
2804 * First writeback pages that don't need mapping - we can avoid
2805 * starting a transaction unnecessarily and also avoid being blocked
2806 * in the block layer on device congestion while having transaction
2810 mpd->scanned_until_end = 0;
2811 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2812 if (!mpd->io_submit.io_end) {
2816 ret = mpage_prepare_extent_to_map(mpd);
2817 /* Unlock pages we didn't use */
2818 mpage_release_unused_pages(mpd, false);
2819 /* Submit prepared bio */
2820 ext4_io_submit(&mpd->io_submit);
2821 ext4_put_io_end_defer(mpd->io_submit.io_end);
2822 mpd->io_submit.io_end = NULL;
2826 while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
2827 /* For each extent of pages we use new io_end */
2828 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2829 if (!mpd->io_submit.io_end) {
2834 WARN_ON_ONCE(!mpd->can_map);
2836 * We have two constraints: We find one extent to map and we
2837 * must always write out whole page (makes a difference when
2838 * blocksize < pagesize) so that we don't block on IO when we
2839 * try to write out the rest of the page. Journalled mode is
2840 * not supported by delalloc.
2842 BUG_ON(ext4_should_journal_data(inode));
2843 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2845 /* start a new transaction */
2846 handle = ext4_journal_start_with_reserve(inode,
2847 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2848 if (IS_ERR(handle)) {
2849 ret = PTR_ERR(handle);
2850 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2851 "%ld pages, ino %lu; err %d", __func__,
2852 wbc->nr_to_write, inode->i_ino, ret);
2853 /* Release allocated io_end */
2854 ext4_put_io_end(mpd->io_submit.io_end);
2855 mpd->io_submit.io_end = NULL;
2860 trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
2861 ret = mpage_prepare_extent_to_map(mpd);
2862 if (!ret && mpd->map.m_len)
2863 ret = mpage_map_and_submit_extent(handle, mpd,
2866 * Caution: If the handle is synchronous,
2867 * ext4_journal_stop() can wait for transaction commit
2868 * to finish which may depend on writeback of pages to
2869 * complete or on page lock to be released. In that
2870 * case, we have to wait until after we have
2871 * submitted all the IO, released page locks we hold,
2872 * and dropped io_end reference (for extent conversion
2873 * to be able to complete) before stopping the handle.
2875 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2876 ext4_journal_stop(handle);
2880 /* Unlock pages we didn't use */
2881 mpage_release_unused_pages(mpd, give_up_on_write);
2882 /* Submit prepared bio */
2883 ext4_io_submit(&mpd->io_submit);
2886 * Drop our io_end reference we got from init. We have
2887 * to be careful and use deferred io_end finishing if
2888 * we are still holding the transaction as we can
2889 * release the last reference to io_end which may end
2890 * up doing unwritten extent conversion.
2893 ext4_put_io_end_defer(mpd->io_submit.io_end);
2894 ext4_journal_stop(handle);
2896 ext4_put_io_end(mpd->io_submit.io_end);
2897 mpd->io_submit.io_end = NULL;
2899 if (ret == -ENOSPC && sbi->s_journal) {
2901 * Commit the transaction which would
2902 * free blocks released in the transaction
2905 jbd2_journal_force_commit_nested(sbi->s_journal);
2909 /* Fatal error - ENOMEM, EIO... */
2914 blk_finish_plug(&plug);
2915 if (!ret && !cycled && wbc->nr_to_write > 0) {
2917 mpd->last_page = writeback_index - 1;
2918 mpd->first_page = 0;
2923 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2925 * Set the writeback_index so that range_cyclic
2926 * mode will write it back later
2928 mapping->writeback_index = mpd->first_page;
2931 trace_ext4_writepages_result(inode, wbc, ret,
2932 nr_to_write - wbc->nr_to_write);
2936 static int ext4_writepages(struct address_space *mapping,
2937 struct writeback_control *wbc)
2939 struct super_block *sb = mapping->host->i_sb;
2940 struct mpage_da_data mpd = {
2941 .inode = mapping->host,
2948 ret = ext4_emergency_state(sb);
2952 alloc_ctx = ext4_writepages_down_read(sb);
2953 ret = ext4_do_writepages(&mpd);
2955 * For data=journal writeback we could have come across pages marked
2956 * for delayed dirtying (PageChecked) which were just added to the
2957 * running transaction. Try once more to get them to stable storage.
2959 if (!ret && mpd.journalled_more_data)
2960 ret = ext4_do_writepages(&mpd);
2961 ext4_writepages_up_read(sb, alloc_ctx);
2966 int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
2968 struct writeback_control wbc = {
2969 .sync_mode = WB_SYNC_ALL,
2970 .nr_to_write = LONG_MAX,
2971 .range_start = jinode->i_dirty_start,
2972 .range_end = jinode->i_dirty_end,
2974 struct mpage_da_data mpd = {
2975 .inode = jinode->i_vfs_inode,
2979 return ext4_do_writepages(&mpd);
2982 static int ext4_dax_writepages(struct address_space *mapping,
2983 struct writeback_control *wbc)
2986 long nr_to_write = wbc->nr_to_write;
2987 struct inode *inode = mapping->host;
2990 ret = ext4_emergency_state(inode->i_sb);
2994 alloc_ctx = ext4_writepages_down_read(inode->i_sb);
2995 trace_ext4_writepages(inode, wbc);
2997 ret = dax_writeback_mapping_range(mapping,
2998 EXT4_SB(inode->i_sb)->s_daxdev, wbc);
2999 trace_ext4_writepages_result(inode, wbc, ret,
3000 nr_to_write - wbc->nr_to_write);
3001 ext4_writepages_up_read(inode->i_sb, alloc_ctx);
3005 static int ext4_nonda_switch(struct super_block *sb)
3007 s64 free_clusters, dirty_clusters;
3008 struct ext4_sb_info *sbi = EXT4_SB(sb);
3011 * switch to non delalloc mode if we are running low
3012 * on free block. The free block accounting via percpu
3013 * counters can get slightly wrong with percpu_counter_batch getting
3014 * accumulated on each CPU without updating global counters
3015 * Delalloc need an accurate free block accounting. So switch
3016 * to non delalloc when we are near to error range.
3019 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
3021 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
3023 * Start pushing delalloc when 1/2 of free blocks are dirty.
3025 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
3026 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
3028 if (2 * free_clusters < 3 * dirty_clusters ||
3029 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
3031 * free block count is less than 150% of dirty blocks
3032 * or free blocks is less than watermark
3039 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3040 loff_t pos, unsigned len,
3041 struct folio **foliop, void **fsdata)
3043 int ret, retries = 0;
3044 struct folio *folio;
3046 struct inode *inode = mapping->host;
3047 fgf_t fgp = FGP_WRITEBEGIN;
3049 ret = ext4_emergency_state(inode->i_sb);
3053 index = pos >> PAGE_SHIFT;
3055 if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
3056 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3057 return ext4_write_begin(file, mapping, pos,
3058 len, foliop, fsdata);
3060 *fsdata = (void *)0;
3061 trace_ext4_da_write_begin(inode, pos, len);
3063 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3064 ret = ext4_generic_write_inline_data(mapping, inode, pos, len,
3065 foliop, fsdata, true);
3073 fgp |= fgf_set_order(len);
3074 folio = __filemap_get_folio(mapping, index, fgp,
3075 mapping_gfp_mask(mapping));
3077 return PTR_ERR(folio);
3079 if (pos + len > folio_pos(folio) + folio_size(folio))
3080 len = folio_pos(folio) + folio_size(folio) - pos;
3082 ret = ext4_block_write_begin(NULL, folio, pos, len,
3083 ext4_da_get_block_prep);
3085 folio_unlock(folio);
3088 * block_write_begin may have instantiated a few blocks
3089 * outside i_size. Trim these off again. Don't need
3090 * i_size_read because we hold inode lock.
3092 if (pos + len > inode->i_size)
3093 ext4_truncate_failed_write(inode);
3095 if (ret == -ENOSPC &&
3096 ext4_should_retry_alloc(inode->i_sb, &retries))
3106 * Check if we should update i_disksize
3107 * when write to the end of file but not require block allocation
3109 static int ext4_da_should_update_i_disksize(struct folio *folio,
3110 unsigned long offset)
3112 struct buffer_head *bh;
3113 struct inode *inode = folio->mapping->host;
3117 bh = folio_buffers(folio);
3118 idx = offset >> inode->i_blkbits;
3120 for (i = 0; i < idx; i++)
3121 bh = bh->b_this_page;
3123 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3128 static int ext4_da_do_write_end(struct address_space *mapping,
3129 loff_t pos, unsigned len, unsigned copied,
3130 struct folio *folio)
3132 struct inode *inode = mapping->host;
3133 loff_t old_size = inode->i_size;
3134 bool disksize_changed = false;
3135 loff_t new_i_size, zero_len = 0;
3138 if (unlikely(!folio_buffers(folio))) {
3139 folio_unlock(folio);
3144 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
3145 * flag, which all that's needed to trigger page writeback.
3147 copied = block_write_end(NULL, mapping, pos, len, copied,
3149 new_i_size = pos + copied;
3152 * It's important to update i_size while still holding folio lock,
3153 * because folio writeout could otherwise come in and zero beyond
3156 * Since we are holding inode lock, we are sure i_disksize <=
3157 * i_size. We also know that if i_disksize < i_size, there are
3158 * delalloc writes pending in the range up to i_size. If the end of
3159 * the current write is <= i_size, there's no need to touch
3160 * i_disksize since writeback will push i_disksize up to i_size
3161 * eventually. If the end of the current write is > i_size and
3162 * inside an allocated block which ext4_da_should_update_i_disksize()
3163 * checked, we need to update i_disksize here as certain
3164 * ext4_writepages() paths not allocating blocks and update i_disksize.
3166 if (new_i_size > inode->i_size) {
3169 i_size_write(inode, new_i_size);
3170 end = offset_in_folio(folio, new_i_size - 1);
3171 if (copied && ext4_da_should_update_i_disksize(folio, end)) {
3172 ext4_update_i_disksize(inode, new_i_size);
3173 disksize_changed = true;
3177 folio_unlock(folio);
3180 if (pos > old_size) {
3181 pagecache_isize_extended(inode, old_size, pos);
3182 zero_len = pos - old_size;
3185 if (!disksize_changed && !zero_len)
3188 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3190 return PTR_ERR(handle);
3192 ext4_zero_partial_blocks(handle, inode, old_size, zero_len);
3193 ext4_mark_inode_dirty(handle, inode);
3194 ext4_journal_stop(handle);
3199 static int ext4_da_write_end(struct file *file,
3200 struct address_space *mapping,
3201 loff_t pos, unsigned len, unsigned copied,
3202 struct folio *folio, void *fsdata)
3204 struct inode *inode = mapping->host;
3205 int write_mode = (int)(unsigned long)fsdata;
3207 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3208 return ext4_write_end(file, mapping, pos,
3209 len, copied, folio, fsdata);
3211 trace_ext4_da_write_end(inode, pos, len, copied);
3213 if (write_mode != CONVERT_INLINE_DATA &&
3214 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3215 ext4_has_inline_data(inode))
3216 return ext4_write_inline_data_end(inode, pos, len, copied,
3219 if (unlikely(copied < len) && !folio_test_uptodate(folio))
3222 return ext4_da_do_write_end(mapping, pos, len, copied, folio);
3226 * Force all delayed allocation blocks to be allocated for a given inode.
3228 int ext4_alloc_da_blocks(struct inode *inode)
3230 trace_ext4_alloc_da_blocks(inode);
3232 if (!EXT4_I(inode)->i_reserved_data_blocks)
3236 * We do something simple for now. The filemap_flush() will
3237 * also start triggering a write of the data blocks, which is
3238 * not strictly speaking necessary (and for users of
3239 * laptop_mode, not even desirable). However, to do otherwise
3240 * would require replicating code paths in:
3242 * ext4_writepages() ->
3243 * write_cache_pages() ---> (via passed in callback function)
3244 * __mpage_da_writepage() -->
3245 * mpage_add_bh_to_extent()
3246 * mpage_da_map_blocks()
3248 * The problem is that write_cache_pages(), located in
3249 * mm/page-writeback.c, marks pages clean in preparation for
3250 * doing I/O, which is not desirable if we're not planning on
3253 * We could call write_cache_pages(), and then redirty all of
3254 * the pages by calling redirty_page_for_writepage() but that
3255 * would be ugly in the extreme. So instead we would need to
3256 * replicate parts of the code in the above functions,
3257 * simplifying them because we wouldn't actually intend to
3258 * write out the pages, but rather only collect contiguous
3259 * logical block extents, call the multi-block allocator, and
3260 * then update the buffer heads with the block allocations.
3262 * For now, though, we'll cheat by calling filemap_flush(),
3263 * which will map the blocks, and start the I/O, but not
3264 * actually wait for the I/O to complete.
3266 return filemap_flush(inode->i_mapping);
3270 * bmap() is special. It gets used by applications such as lilo and by
3271 * the swapper to find the on-disk block of a specific piece of data.
3273 * Naturally, this is dangerous if the block concerned is still in the
3274 * journal. If somebody makes a swapfile on an ext4 data-journaling
3275 * filesystem and enables swap, then they may get a nasty shock when the
3276 * data getting swapped to that swapfile suddenly gets overwritten by
3277 * the original zero's written out previously to the journal and
3278 * awaiting writeback in the kernel's buffer cache.
3280 * So, if we see any bmap calls here on a modified, data-journaled file,
3281 * take extra steps to flush any blocks which might be in the cache.
3283 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3285 struct inode *inode = mapping->host;
3288 inode_lock_shared(inode);
3290 * We can get here for an inline file via the FIBMAP ioctl
3292 if (ext4_has_inline_data(inode))
3295 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3296 (test_opt(inode->i_sb, DELALLOC) ||
3297 ext4_should_journal_data(inode))) {
3299 * With delalloc or journalled data we want to sync the file so
3300 * that we can make sure we allocate blocks for file and data
3301 * is in place for the user to see it
3303 filemap_write_and_wait(mapping);
3306 ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3309 inode_unlock_shared(inode);
3313 static int ext4_read_folio(struct file *file, struct folio *folio)
3316 struct inode *inode = folio->mapping->host;
3318 trace_ext4_read_folio(inode, folio);
3320 if (ext4_has_inline_data(inode))
3321 ret = ext4_readpage_inline(inode, folio);
3324 return ext4_mpage_readpages(inode, NULL, folio);
3329 static void ext4_readahead(struct readahead_control *rac)
3331 struct inode *inode = rac->mapping->host;
3333 /* If the file has inline data, no need to do readahead. */
3334 if (ext4_has_inline_data(inode))
3337 ext4_mpage_readpages(inode, rac, NULL);
3340 static void ext4_invalidate_folio(struct folio *folio, size_t offset,
3343 trace_ext4_invalidate_folio(folio, offset, length);
3345 /* No journalling happens on data buffers when this function is used */
3346 WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
3348 block_invalidate_folio(folio, offset, length);
3351 static int __ext4_journalled_invalidate_folio(struct folio *folio,
3352 size_t offset, size_t length)
3354 journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3356 trace_ext4_journalled_invalidate_folio(folio, offset, length);
3359 * If it's a full truncate we just forget about the pending dirtying
3361 if (offset == 0 && length == folio_size(folio))
3362 folio_clear_checked(folio);
3364 return jbd2_journal_invalidate_folio(journal, folio, offset, length);
3367 /* Wrapper for aops... */
3368 static void ext4_journalled_invalidate_folio(struct folio *folio,
3372 WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3375 static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3377 struct inode *inode = folio->mapping->host;
3378 journal_t *journal = EXT4_JOURNAL(inode);
3380 trace_ext4_release_folio(inode, folio);
3382 /* Page has dirty journalled data -> cannot release */
3383 if (folio_test_checked(folio))
3386 return jbd2_journal_try_to_free_buffers(journal, folio);
3388 return try_to_free_buffers(folio);
3391 static bool ext4_inode_datasync_dirty(struct inode *inode)
3393 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3396 if (jbd2_transaction_committed(journal,
3397 EXT4_I(inode)->i_datasync_tid))
3399 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3400 return !list_empty(&EXT4_I(inode)->i_fc_list);
3404 /* Any metadata buffers to write? */
3405 if (!list_empty(&inode->i_mapping->i_private_list))
3407 return inode->i_state & I_DIRTY_DATASYNC;
3410 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3411 struct ext4_map_blocks *map, loff_t offset,
3412 loff_t length, unsigned int flags)
3414 u8 blkbits = inode->i_blkbits;
3417 * Writes that span EOF might trigger an I/O size update on completion,
3418 * so consider them to be dirty for the purpose of O_DSYNC, even if
3419 * there is no other metadata changes being made or are pending.
3422 if (ext4_inode_datasync_dirty(inode) ||
3423 offset + length > i_size_read(inode))
3424 iomap->flags |= IOMAP_F_DIRTY;
3426 if (map->m_flags & EXT4_MAP_NEW)
3427 iomap->flags |= IOMAP_F_NEW;
3429 /* HW-offload atomics are always used */
3430 if (flags & IOMAP_ATOMIC)
3431 iomap->flags |= IOMAP_F_ATOMIC_BIO;
3433 if (flags & IOMAP_DAX)
3434 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3436 iomap->bdev = inode->i_sb->s_bdev;
3437 iomap->offset = (u64) map->m_lblk << blkbits;
3438 iomap->length = (u64) map->m_len << blkbits;
3440 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3441 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3442 iomap->flags |= IOMAP_F_MERGED;
3445 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3446 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3447 * set. In order for any allocated unwritten extents to be converted
3448 * into written extents correctly within the ->end_io() handler, we
3449 * need to ensure that the iomap->type is set appropriately. Hence, the
3450 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3453 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3454 iomap->type = IOMAP_UNWRITTEN;
3455 iomap->addr = (u64) map->m_pblk << blkbits;
3456 if (flags & IOMAP_DAX)
3457 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3458 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3459 iomap->type = IOMAP_MAPPED;
3460 iomap->addr = (u64) map->m_pblk << blkbits;
3461 if (flags & IOMAP_DAX)
3462 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3463 } else if (map->m_flags & EXT4_MAP_DELAYED) {
3464 iomap->type = IOMAP_DELALLOC;
3465 iomap->addr = IOMAP_NULL_ADDR;
3467 iomap->type = IOMAP_HOLE;
3468 iomap->addr = IOMAP_NULL_ADDR;
3472 static int ext4_map_blocks_atomic_write_slow(handle_t *handle,
3473 struct inode *inode, struct ext4_map_blocks *map)
3475 ext4_lblk_t m_lblk = map->m_lblk;
3476 unsigned int m_len = map->m_len;
3477 unsigned int mapped_len = 0, m_flags = 0;
3478 ext4_fsblk_t next_pblk;
3479 bool check_next_pblk = false;
3482 WARN_ON_ONCE(!ext4_has_feature_bigalloc(inode->i_sb));
3485 * This is a slow path in case of mixed mapping. We use
3486 * EXT4_GET_BLOCKS_CREATE_ZERO flag here to make sure we get a single
3487 * contiguous mapped mapping. This will ensure any unwritten or hole
3488 * regions within the requested range is zeroed out and we return
3489 * a single contiguous mapped extent.
3491 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3494 ret = ext4_map_blocks(handle, inode, map, m_flags);
3495 if (ret < 0 && ret != -ENOSPC)
3498 * This should never happen, but let's return an error code to
3499 * avoid an infinite loop in here.
3502 ret = -EFSCORRUPTED;
3503 ext4_warning_inode(inode,
3504 "ext4_map_blocks() couldn't allocate blocks m_flags: 0x%x, ret:%d",
3509 * With bigalloc we should never get ENOSPC nor discontiguous
3512 if ((check_next_pblk && next_pblk != map->m_pblk) ||
3514 ext4_warning_inode(inode,
3515 "Non-contiguous allocation detected: expected %llu, got %llu, "
3516 "or ext4_map_blocks() returned out of space ret: %d",
3517 next_pblk, map->m_pblk, ret);
3518 ret = -EFSCORRUPTED;
3521 next_pblk = map->m_pblk + map->m_len;
3522 check_next_pblk = true;
3524 mapped_len += map->m_len;
3525 map->m_lblk += map->m_len;
3526 map->m_len = m_len - mapped_len;
3527 } while (mapped_len < m_len);
3530 * We might have done some work in above loop, so we need to query the
3531 * start of the physical extent, based on the origin m_lblk and m_len.
3532 * Let's also ensure we were able to allocate the required range for
3533 * mixed mapping case.
3535 map->m_lblk = m_lblk;
3539 ret = ext4_map_blocks(handle, inode, map,
3540 EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF);
3542 ext4_warning_inode(inode,
3543 "allocation failed for atomic write request m_lblk:%u, m_len:%u, ret:%d\n",
3544 m_lblk, m_len, ret);
3550 /* reset map before returning an error */
3551 map->m_lblk = m_lblk;
3558 * ext4_map_blocks_atomic: Helper routine to ensure the entire requested
3559 * range in @map [lblk, lblk + len) is one single contiguous extent with no
3562 * We first use m_flags passed to us by our caller (ext4_iomap_alloc()).
3563 * We only call EXT4_GET_BLOCKS_ZERO in the slow path, when the underlying
3564 * physical extent for the requested range does not have a single contiguous
3565 * mapping type i.e. (Hole, Mapped, or Unwritten) throughout.
3566 * In that case we will loop over the requested range to allocate and zero out
3567 * the unwritten / holes in between, to get a single mapped extent from
3568 * [m_lblk, m_lblk + m_len). Note that this is only possible because we know
3569 * this can be called only with bigalloc enabled filesystem where the underlying
3570 * cluster is already allocated. This avoids allocating discontiguous extents
3571 * in the slow path due to multiple calls to ext4_map_blocks().
3572 * The slow path is mostly non-performance critical path, so it should be ok to
3573 * loop using ext4_map_blocks() with appropriate flags to allocate & zero the
3574 * underlying short holes/unwritten extents within the requested range.
3576 static int ext4_map_blocks_atomic_write(handle_t *handle, struct inode *inode,
3577 struct ext4_map_blocks *map, int m_flags,
3580 ext4_lblk_t m_lblk = map->m_lblk;
3581 unsigned int m_len = map->m_len;
3584 WARN_ON_ONCE(m_len > 1 && !ext4_has_feature_bigalloc(inode->i_sb));
3586 ret = ext4_map_blocks(handle, inode, map, m_flags);
3587 if (ret < 0 || ret == m_len)
3590 * This is a mixed mapping case where we were not able to allocate
3591 * a single contiguous extent. In that case let's reset requested
3592 * mapping and call the slow path.
3594 map->m_lblk = m_lblk;
3599 * slow path means we have mixed mapping, that means we will need
3600 * to force txn commit.
3602 *force_commit = true;
3603 return ext4_map_blocks_atomic_write_slow(handle, inode, map);
3608 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3612 u8 blkbits = inode->i_blkbits;
3613 int ret, dio_credits, m_flags = 0, retries = 0;
3614 bool force_commit = false;
3617 * Trim the mapping request to the maximum value that we can map at
3618 * once for direct I/O.
3620 if (map->m_len > DIO_MAX_BLOCKS)
3621 map->m_len = DIO_MAX_BLOCKS;
3624 * journal credits estimation for atomic writes. We call
3625 * ext4_map_blocks(), to find if there could be a mixed mapping. If yes,
3626 * then let's assume the no. of pextents required can be m_len i.e.
3627 * every alternate block can be unwritten and hole.
3629 if (flags & IOMAP_ATOMIC) {
3630 unsigned int orig_mlen = map->m_len;
3632 ret = ext4_map_blocks(NULL, inode, map, 0);
3635 if (map->m_len < orig_mlen) {
3636 map->m_len = orig_mlen;
3637 dio_credits = ext4_meta_trans_blocks(inode, orig_mlen,
3640 dio_credits = ext4_chunk_trans_blocks(inode,
3644 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3649 * Either we allocate blocks and then don't get an unwritten extent, so
3650 * in that case we have reserved enough credits. Or, the blocks are
3651 * already allocated and unwritten. In that case, the extent conversion
3652 * fits into the credits as well.
3654 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3656 return PTR_ERR(handle);
3659 * DAX and direct I/O are the only two operations that are currently
3660 * supported with IOMAP_WRITE.
3662 WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3663 if (flags & IOMAP_DAX)
3664 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3666 * We use i_size instead of i_disksize here because delalloc writeback
3667 * can complete at any point during the I/O and subsequently push the
3668 * i_disksize out to i_size. This could be beyond where direct I/O is
3669 * happening and thus expose allocated blocks to direct I/O reads.
3671 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3672 m_flags = EXT4_GET_BLOCKS_CREATE;
3673 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3674 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3676 if (flags & IOMAP_ATOMIC)
3677 ret = ext4_map_blocks_atomic_write(handle, inode, map, m_flags,
3680 ret = ext4_map_blocks(handle, inode, map, m_flags);
3683 * We cannot fill holes in indirect tree based inodes as that could
3684 * expose stale data in the case of a crash. Use the magic error code
3685 * to fallback to buffered I/O.
3687 if (!m_flags && !ret)
3690 ext4_journal_stop(handle);
3691 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3695 * Force commit the current transaction if the allocation spans a mixed
3696 * mapping range. This ensures any pending metadata updates (like
3697 * unwritten to written extents conversion) in this range are in
3698 * consistent state with the file data blocks, before performing the
3699 * actual write I/O. If the commit fails, the whole I/O must be aborted
3700 * to prevent any possible torn writes.
3702 if (ret > 0 && force_commit) {
3705 ret2 = ext4_force_commit(inode->i_sb);
3714 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3715 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3718 struct ext4_map_blocks map;
3719 u8 blkbits = inode->i_blkbits;
3720 unsigned int orig_mlen;
3722 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3725 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3729 * Calculate the first and last logical blocks respectively.
3731 map.m_lblk = offset >> blkbits;
3732 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3733 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3734 orig_mlen = map.m_len;
3736 if (flags & IOMAP_WRITE) {
3738 * We check here if the blocks are already allocated, then we
3739 * don't need to start a journal txn and we can directly return
3740 * the mapping information. This could boost performance
3741 * especially in multi-threaded overwrite requests.
3743 if (offset + length <= i_size_read(inode)) {
3744 ret = ext4_map_blocks(NULL, inode, &map, 0);
3746 * For atomic writes the entire requested length should
3749 if (map.m_flags & EXT4_MAP_MAPPED) {
3750 if ((!(flags & IOMAP_ATOMIC) && ret > 0) ||
3751 (flags & IOMAP_ATOMIC && ret >= orig_mlen))
3754 map.m_len = orig_mlen;
3756 ret = ext4_iomap_alloc(inode, &map, flags);
3759 * This can be called for overwrites path from
3760 * ext4_iomap_overwrite_begin().
3762 ret = ext4_map_blocks(NULL, inode, &map, 0);
3769 * When inline encryption is enabled, sometimes I/O to an encrypted file
3770 * has to be broken up to guarantee DUN contiguity. Handle this by
3771 * limiting the length of the mapping returned.
3773 map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
3776 * Before returning to iomap, let's ensure the allocated mapping
3777 * covers the entire requested length for atomic writes.
3779 if (flags & IOMAP_ATOMIC) {
3780 if (map.m_len < (length >> blkbits)) {
3785 ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3790 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3791 loff_t length, unsigned flags, struct iomap *iomap,
3792 struct iomap *srcmap)
3797 * Even for writes we don't need to allocate blocks, so just pretend
3798 * we are reading to save overhead of starting a transaction.
3800 flags &= ~IOMAP_WRITE;
3801 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3802 WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
3806 static inline bool ext4_want_directio_fallback(unsigned flags, ssize_t written)
3808 /* must be a directio to fall back to buffered */
3809 if ((flags & (IOMAP_WRITE | IOMAP_DIRECT)) !=
3810 (IOMAP_WRITE | IOMAP_DIRECT))
3813 /* atomic writes are all-or-nothing */
3814 if (flags & IOMAP_ATOMIC)
3817 /* can only try again if we wrote nothing */
3818 return written == 0;
3821 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3822 ssize_t written, unsigned flags, struct iomap *iomap)
3825 * Check to see whether an error occurred while writing out the data to
3826 * the allocated blocks. If so, return the magic error code for
3827 * non-atomic write so that we fallback to buffered I/O and attempt to
3828 * complete the remainder of the I/O.
3829 * For non-atomic writes, any blocks that may have been
3830 * allocated in preparation for the direct I/O will be reused during
3831 * buffered I/O. For atomic write, we never fallback to buffered-io.
3833 if (ext4_want_directio_fallback(flags, written))
3839 const struct iomap_ops ext4_iomap_ops = {
3840 .iomap_begin = ext4_iomap_begin,
3841 .iomap_end = ext4_iomap_end,
3844 const struct iomap_ops ext4_iomap_overwrite_ops = {
3845 .iomap_begin = ext4_iomap_overwrite_begin,
3846 .iomap_end = ext4_iomap_end,
3849 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3850 loff_t length, unsigned int flags,
3851 struct iomap *iomap, struct iomap *srcmap)
3854 struct ext4_map_blocks map;
3855 u8 blkbits = inode->i_blkbits;
3857 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3860 if (ext4_has_inline_data(inode)) {
3861 ret = ext4_inline_data_iomap(inode, iomap);
3862 if (ret != -EAGAIN) {
3863 if (ret == 0 && offset >= iomap->length)
3870 * Calculate the first and last logical block respectively.
3872 map.m_lblk = offset >> blkbits;
3873 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3874 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3877 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3878 * So handle it here itself instead of querying ext4_map_blocks().
3879 * Since ext4_map_blocks() will warn about it and will return
3882 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3883 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3885 if (offset >= sbi->s_bitmap_maxbytes) {
3891 ret = ext4_map_blocks(NULL, inode, &map, 0);
3895 ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3900 const struct iomap_ops ext4_iomap_report_ops = {
3901 .iomap_begin = ext4_iomap_begin_report,
3905 * For data=journal mode, folio should be marked dirty only when it was
3906 * writeably mapped. When that happens, it was already attached to the
3907 * transaction and marked as jbddirty (we take care of this in
3908 * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
3909 * so we should have nothing to do here, except for the case when someone
3910 * had the page pinned and dirtied the page through this pin (e.g. by doing
3911 * direct IO to it). In that case we'd need to attach buffers here to the
3912 * transaction but we cannot due to lock ordering. We cannot just dirty the
3913 * folio and leave attached buffers clean, because the buffers' dirty state is
3914 * "definitive". We cannot just set the buffers dirty or jbddirty because all
3915 * the journalling code will explode. So what we do is to mark the folio
3916 * "pending dirty" and next time ext4_writepages() is called, attach buffers
3917 * to the transaction appropriately.
3919 static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3920 struct folio *folio)
3922 WARN_ON_ONCE(!folio_buffers(folio));
3923 if (folio_maybe_dma_pinned(folio))
3924 folio_set_checked(folio);
3925 return filemap_dirty_folio(mapping, folio);
3928 static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
3930 WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3931 WARN_ON_ONCE(!folio_buffers(folio));
3932 return block_dirty_folio(mapping, folio);
3935 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3936 struct file *file, sector_t *span)
3938 return iomap_swapfile_activate(sis, file, span,
3939 &ext4_iomap_report_ops);
3942 static const struct address_space_operations ext4_aops = {
3943 .read_folio = ext4_read_folio,
3944 .readahead = ext4_readahead,
3945 .writepages = ext4_writepages,
3946 .write_begin = ext4_write_begin,
3947 .write_end = ext4_write_end,
3948 .dirty_folio = ext4_dirty_folio,
3950 .invalidate_folio = ext4_invalidate_folio,
3951 .release_folio = ext4_release_folio,
3952 .migrate_folio = buffer_migrate_folio,
3953 .is_partially_uptodate = block_is_partially_uptodate,
3954 .error_remove_folio = generic_error_remove_folio,
3955 .swap_activate = ext4_iomap_swap_activate,
3958 static const struct address_space_operations ext4_journalled_aops = {
3959 .read_folio = ext4_read_folio,
3960 .readahead = ext4_readahead,
3961 .writepages = ext4_writepages,
3962 .write_begin = ext4_write_begin,
3963 .write_end = ext4_journalled_write_end,
3964 .dirty_folio = ext4_journalled_dirty_folio,
3966 .invalidate_folio = ext4_journalled_invalidate_folio,
3967 .release_folio = ext4_release_folio,
3968 .migrate_folio = buffer_migrate_folio_norefs,
3969 .is_partially_uptodate = block_is_partially_uptodate,
3970 .error_remove_folio = generic_error_remove_folio,
3971 .swap_activate = ext4_iomap_swap_activate,
3974 static const struct address_space_operations ext4_da_aops = {
3975 .read_folio = ext4_read_folio,
3976 .readahead = ext4_readahead,
3977 .writepages = ext4_writepages,
3978 .write_begin = ext4_da_write_begin,
3979 .write_end = ext4_da_write_end,
3980 .dirty_folio = ext4_dirty_folio,
3982 .invalidate_folio = ext4_invalidate_folio,
3983 .release_folio = ext4_release_folio,
3984 .migrate_folio = buffer_migrate_folio,
3985 .is_partially_uptodate = block_is_partially_uptodate,
3986 .error_remove_folio = generic_error_remove_folio,
3987 .swap_activate = ext4_iomap_swap_activate,
3990 static const struct address_space_operations ext4_dax_aops = {
3991 .writepages = ext4_dax_writepages,
3992 .dirty_folio = noop_dirty_folio,
3994 .swap_activate = ext4_iomap_swap_activate,
3997 void ext4_set_aops(struct inode *inode)
3999 switch (ext4_inode_journal_mode(inode)) {
4000 case EXT4_INODE_ORDERED_DATA_MODE:
4001 case EXT4_INODE_WRITEBACK_DATA_MODE:
4003 case EXT4_INODE_JOURNAL_DATA_MODE:
4004 inode->i_mapping->a_ops = &ext4_journalled_aops;
4010 inode->i_mapping->a_ops = &ext4_dax_aops;
4011 else if (test_opt(inode->i_sb, DELALLOC))
4012 inode->i_mapping->a_ops = &ext4_da_aops;
4014 inode->i_mapping->a_ops = &ext4_aops;
4018 * Here we can't skip an unwritten buffer even though it usually reads zero
4019 * because it might have data in pagecache (eg, if called from ext4_zero_range,
4020 * ext4_punch_hole, etc) which needs to be properly zeroed out. Otherwise a
4021 * racing writeback can come later and flush the stale pagecache to disk.
4023 static int __ext4_block_zero_page_range(handle_t *handle,
4024 struct address_space *mapping, loff_t from, loff_t length)
4026 unsigned int offset, blocksize, pos;
4028 struct inode *inode = mapping->host;
4029 struct buffer_head *bh;
4030 struct folio *folio;
4033 folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
4034 FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
4035 mapping_gfp_constraint(mapping, ~__GFP_FS));
4037 return PTR_ERR(folio);
4039 blocksize = inode->i_sb->s_blocksize;
4041 iblock = folio->index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
4043 bh = folio_buffers(folio);
4045 bh = create_empty_buffers(folio, blocksize, 0);
4047 /* Find the buffer that contains "offset" */
4048 offset = offset_in_folio(folio, from);
4050 while (offset >= pos) {
4051 bh = bh->b_this_page;
4055 if (buffer_freed(bh)) {
4056 BUFFER_TRACE(bh, "freed: skip");
4059 if (!buffer_mapped(bh)) {
4060 BUFFER_TRACE(bh, "unmapped");
4061 ext4_get_block(inode, iblock, bh, 0);
4062 /* unmapped? It's a hole - nothing to do */
4063 if (!buffer_mapped(bh)) {
4064 BUFFER_TRACE(bh, "still unmapped");
4069 /* Ok, it's mapped. Make sure it's up-to-date */
4070 if (folio_test_uptodate(folio))
4071 set_buffer_uptodate(bh);
4073 if (!buffer_uptodate(bh)) {
4074 err = ext4_read_bh_lock(bh, 0, true);
4077 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
4078 /* We expect the key to be set. */
4079 BUG_ON(!fscrypt_has_encryption_key(inode));
4080 err = fscrypt_decrypt_pagecache_blocks(folio,
4084 clear_buffer_uptodate(bh);
4089 if (ext4_should_journal_data(inode)) {
4090 BUFFER_TRACE(bh, "get write access");
4091 err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
4096 folio_zero_range(folio, offset, length);
4097 BUFFER_TRACE(bh, "zeroed end of block");
4099 if (ext4_should_journal_data(inode)) {
4100 err = ext4_dirty_journalled_data(handle, bh);
4103 mark_buffer_dirty(bh);
4104 if (ext4_should_order_data(inode))
4105 err = ext4_jbd2_inode_add_write(handle, inode, from,
4110 folio_unlock(folio);
4116 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4117 * starting from file offset 'from'. The range to be zero'd must
4118 * be contained with in one block. If the specified range exceeds
4119 * the end of the block it will be shortened to end of the block
4120 * that corresponds to 'from'
4122 static int ext4_block_zero_page_range(handle_t *handle,
4123 struct address_space *mapping, loff_t from, loff_t length)
4125 struct inode *inode = mapping->host;
4126 unsigned offset = from & (PAGE_SIZE-1);
4127 unsigned blocksize = inode->i_sb->s_blocksize;
4128 unsigned max = blocksize - (offset & (blocksize - 1));
4131 * correct length if it does not fall between
4132 * 'from' and the end of the block
4134 if (length > max || length < 0)
4137 if (IS_DAX(inode)) {
4138 return dax_zero_range(inode, from, length, NULL,
4141 return __ext4_block_zero_page_range(handle, mapping, from, length);
4145 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4146 * up to the end of the block which corresponds to `from'.
4147 * This required during truncate. We need to physically zero the tail end
4148 * of that block so it doesn't yield old data if the file is later grown.
4150 static int ext4_block_truncate_page(handle_t *handle,
4151 struct address_space *mapping, loff_t from)
4153 unsigned offset = from & (PAGE_SIZE-1);
4156 struct inode *inode = mapping->host;
4158 /* If we are processing an encrypted inode during orphan list handling */
4159 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
4162 blocksize = inode->i_sb->s_blocksize;
4163 length = blocksize - (offset & (blocksize - 1));
4165 return ext4_block_zero_page_range(handle, mapping, from, length);
4168 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4169 loff_t lstart, loff_t length)
4171 struct super_block *sb = inode->i_sb;
4172 struct address_space *mapping = inode->i_mapping;
4173 unsigned partial_start, partial_end;
4174 ext4_fsblk_t start, end;
4175 loff_t byte_end = (lstart + length - 1);
4178 partial_start = lstart & (sb->s_blocksize - 1);
4179 partial_end = byte_end & (sb->s_blocksize - 1);
4181 start = lstart >> sb->s_blocksize_bits;
4182 end = byte_end >> sb->s_blocksize_bits;
4184 /* Handle partial zero within the single block */
4186 (partial_start || (partial_end != sb->s_blocksize - 1))) {
4187 err = ext4_block_zero_page_range(handle, mapping,
4191 /* Handle partial zero out on the start of the range */
4192 if (partial_start) {
4193 err = ext4_block_zero_page_range(handle, mapping,
4194 lstart, sb->s_blocksize);
4198 /* Handle partial zero out on the end of the range */
4199 if (partial_end != sb->s_blocksize - 1)
4200 err = ext4_block_zero_page_range(handle, mapping,
4201 byte_end - partial_end,
4206 int ext4_can_truncate(struct inode *inode)
4208 if (S_ISREG(inode->i_mode))
4210 if (S_ISDIR(inode->i_mode))
4212 if (S_ISLNK(inode->i_mode))
4213 return !ext4_inode_is_fast_symlink(inode);
4218 * We have to make sure i_disksize gets properly updated before we truncate
4219 * page cache due to hole punching or zero range. Otherwise i_disksize update
4220 * can get lost as it may have been postponed to submission of writeback but
4221 * that will never happen after we truncate page cache.
4223 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4229 loff_t size = i_size_read(inode);
4231 WARN_ON(!inode_is_locked(inode));
4232 if (offset > size || offset + len < size)
4235 if (EXT4_I(inode)->i_disksize >= size)
4238 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4240 return PTR_ERR(handle);
4241 ext4_update_i_disksize(inode, size);
4242 ret = ext4_mark_inode_dirty(handle, inode);
4243 ext4_journal_stop(handle);
4248 static inline void ext4_truncate_folio(struct inode *inode,
4249 loff_t start, loff_t end)
4251 unsigned long blocksize = i_blocksize(inode);
4252 struct folio *folio;
4254 /* Nothing to be done if no complete block needs to be truncated. */
4255 if (round_up(start, blocksize) >= round_down(end, blocksize))
4258 folio = filemap_lock_folio(inode->i_mapping, start >> PAGE_SHIFT);
4262 if (folio_mkclean(folio))
4263 folio_mark_dirty(folio);
4264 folio_unlock(folio);
4268 int ext4_truncate_page_cache_block_range(struct inode *inode,
4269 loff_t start, loff_t end)
4271 unsigned long blocksize = i_blocksize(inode);
4275 * For journalled data we need to write (and checkpoint) pages
4276 * before discarding page cache to avoid inconsitent data on disk
4277 * in case of crash before freeing or unwritten converting trans
4280 if (ext4_should_journal_data(inode)) {
4281 ret = filemap_write_and_wait_range(inode->i_mapping, start,
4285 goto truncate_pagecache;
4289 * If the block size is less than the page size, the file's mapped
4290 * blocks within one page could be freed or converted to unwritten.
4291 * So it's necessary to remove writable userspace mappings, and then
4292 * ext4_page_mkwrite() can be called during subsequent write access
4293 * to these partial folios.
4295 if (!IS_ALIGNED(start | end, PAGE_SIZE) &&
4296 blocksize < PAGE_SIZE && start < inode->i_size) {
4297 loff_t page_boundary = round_up(start, PAGE_SIZE);
4299 ext4_truncate_folio(inode, start, min(page_boundary, end));
4300 if (end > page_boundary)
4301 ext4_truncate_folio(inode,
4302 round_down(end, PAGE_SIZE), end);
4306 truncate_pagecache_range(inode, start, end - 1);
4310 static void ext4_wait_dax_page(struct inode *inode)
4312 filemap_invalidate_unlock(inode->i_mapping);
4314 filemap_invalidate_lock(inode->i_mapping);
4317 int ext4_break_layouts(struct inode *inode)
4319 if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
4322 return dax_break_layout_inode(inode, ext4_wait_dax_page);
4326 * ext4_punch_hole: punches a hole in a file by releasing the blocks
4327 * associated with the given offset and length
4329 * @inode: File inode
4330 * @offset: The offset where the hole will begin
4331 * @len: The length of the hole
4333 * Returns: 0 on success or negative on failure
4336 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
4338 struct inode *inode = file_inode(file);
4339 struct super_block *sb = inode->i_sb;
4340 ext4_lblk_t start_lblk, end_lblk;
4341 loff_t max_end = sb->s_maxbytes;
4342 loff_t end = offset + length;
4344 unsigned int credits;
4347 trace_ext4_punch_hole(inode, offset, length, 0);
4348 WARN_ON_ONCE(!inode_is_locked(inode));
4351 * For indirect-block based inodes, make sure that the hole within
4352 * one block before last range.
4354 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4355 max_end = EXT4_SB(sb)->s_bitmap_maxbytes - sb->s_blocksize;
4357 /* No need to punch hole beyond i_size */
4358 if (offset >= inode->i_size || offset >= max_end)
4362 * If the hole extends beyond i_size, set the hole to end after
4363 * the page that contains i_size.
4365 if (end > inode->i_size)
4366 end = round_up(inode->i_size, PAGE_SIZE);
4369 length = end - offset;
4372 * Attach jinode to inode for jbd2 if we do any zeroing of partial
4375 if (!IS_ALIGNED(offset | end, sb->s_blocksize)) {
4376 ret = ext4_inode_attach_jinode(inode);
4382 ret = ext4_update_disksize_before_punch(inode, offset, length);
4386 /* Now release the pages and zero block aligned part of pages*/
4387 ret = ext4_truncate_page_cache_block_range(inode, offset, end);
4391 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4392 credits = ext4_writepage_trans_blocks(inode);
4394 credits = ext4_blocks_for_truncate(inode);
4395 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4396 if (IS_ERR(handle)) {
4397 ret = PTR_ERR(handle);
4398 ext4_std_error(sb, ret);
4402 ret = ext4_zero_partial_blocks(handle, inode, offset, length);
4406 /* If there are blocks to remove, do it */
4407 start_lblk = EXT4_B_TO_LBLK(inode, offset);
4408 end_lblk = end >> inode->i_blkbits;
4410 if (end_lblk > start_lblk) {
4411 ext4_lblk_t hole_len = end_lblk - start_lblk;
4413 ext4_fc_track_inode(handle, inode);
4414 ext4_check_map_extents_env(inode);
4415 down_write(&EXT4_I(inode)->i_data_sem);
4416 ext4_discard_preallocations(inode);
4418 ext4_es_remove_extent(inode, start_lblk, hole_len);
4420 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4421 ret = ext4_ext_remove_space(inode, start_lblk,
4424 ret = ext4_ind_remove_space(handle, inode, start_lblk,
4427 up_write(&EXT4_I(inode)->i_data_sem);
4431 ext4_es_insert_extent(inode, start_lblk, hole_len, ~0,
4432 EXTENT_STATUS_HOLE, 0);
4433 up_write(&EXT4_I(inode)->i_data_sem);
4435 ext4_fc_track_range(handle, inode, start_lblk, end_lblk);
4437 ret = ext4_mark_inode_dirty(handle, inode);
4441 ext4_update_inode_fsync_trans(handle, inode, 1);
4443 ext4_handle_sync(handle);
4445 ext4_journal_stop(handle);
4449 int ext4_inode_attach_jinode(struct inode *inode)
4451 struct ext4_inode_info *ei = EXT4_I(inode);
4452 struct jbd2_inode *jinode;
4454 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4457 jinode = jbd2_alloc_inode(GFP_KERNEL);
4458 spin_lock(&inode->i_lock);
4461 spin_unlock(&inode->i_lock);
4464 ei->jinode = jinode;
4465 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4468 spin_unlock(&inode->i_lock);
4469 if (unlikely(jinode != NULL))
4470 jbd2_free_inode(jinode);
4477 * We block out ext4_get_block() block instantiations across the entire
4478 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4479 * simultaneously on behalf of the same inode.
4481 * As we work through the truncate and commit bits of it to the journal there
4482 * is one core, guiding principle: the file's tree must always be consistent on
4483 * disk. We must be able to restart the truncate after a crash.
4485 * The file's tree may be transiently inconsistent in memory (although it
4486 * probably isn't), but whenever we close off and commit a journal transaction,
4487 * the contents of (the filesystem + the journal) must be consistent and
4488 * restartable. It's pretty simple, really: bottom up, right to left (although
4489 * left-to-right works OK too).
4491 * Note that at recovery time, journal replay occurs *before* the restart of
4492 * truncate against the orphan inode list.
4494 * The committed inode has the new, desired i_size (which is the same as
4495 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4496 * that this inode's truncate did not complete and it will again call
4497 * ext4_truncate() to have another go. So there will be instantiated blocks
4498 * to the right of the truncation point in a crashed ext4 filesystem. But
4499 * that's fine - as long as they are linked from the inode, the post-crash
4500 * ext4_truncate() run will find them and release them.
4502 int ext4_truncate(struct inode *inode)
4504 struct ext4_inode_info *ei = EXT4_I(inode);
4505 unsigned int credits;
4508 struct address_space *mapping = inode->i_mapping;
4511 * There is a possibility that we're either freeing the inode
4512 * or it's a completely new inode. In those cases we might not
4513 * have i_rwsem locked because it's not necessary.
4515 if (!(inode->i_state & (I_NEW|I_FREEING)))
4516 WARN_ON(!inode_is_locked(inode));
4517 trace_ext4_truncate_enter(inode);
4519 if (!ext4_can_truncate(inode))
4522 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4523 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4525 if (ext4_has_inline_data(inode)) {
4528 err = ext4_inline_data_truncate(inode, &has_inline);
4529 if (err || has_inline)
4533 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4534 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4535 err = ext4_inode_attach_jinode(inode);
4540 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4541 credits = ext4_writepage_trans_blocks(inode);
4543 credits = ext4_blocks_for_truncate(inode);
4545 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4546 if (IS_ERR(handle)) {
4547 err = PTR_ERR(handle);
4551 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4552 ext4_block_truncate_page(handle, mapping, inode->i_size);
4555 * We add the inode to the orphan list, so that if this
4556 * truncate spans multiple transactions, and we crash, we will
4557 * resume the truncate when the filesystem recovers. It also
4558 * marks the inode dirty, to catch the new size.
4560 * Implication: the file must always be in a sane, consistent
4561 * truncatable state while each transaction commits.
4563 err = ext4_orphan_add(handle, inode);
4567 ext4_fc_track_inode(handle, inode);
4568 ext4_check_map_extents_env(inode);
4570 down_write(&EXT4_I(inode)->i_data_sem);
4571 ext4_discard_preallocations(inode);
4573 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4574 err = ext4_ext_truncate(handle, inode);
4576 ext4_ind_truncate(handle, inode);
4578 up_write(&ei->i_data_sem);
4583 ext4_handle_sync(handle);
4587 * If this was a simple ftruncate() and the file will remain alive,
4588 * then we need to clear up the orphan record which we created above.
4589 * However, if this was a real unlink then we were called by
4590 * ext4_evict_inode(), and we allow that function to clean up the
4591 * orphan info for us.
4594 ext4_orphan_del(handle, inode);
4596 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
4597 err2 = ext4_mark_inode_dirty(handle, inode);
4598 if (unlikely(err2 && !err))
4600 ext4_journal_stop(handle);
4603 trace_ext4_truncate_exit(inode);
4607 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4609 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4610 return inode_peek_iversion_raw(inode);
4612 return inode_peek_iversion(inode);
4615 static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
4616 struct ext4_inode_info *ei)
4618 struct inode *inode = &(ei->vfs_inode);
4619 u64 i_blocks = READ_ONCE(inode->i_blocks);
4620 struct super_block *sb = inode->i_sb;
4622 if (i_blocks <= ~0U) {
4624 * i_blocks can be represented in a 32 bit variable
4625 * as multiple of 512 bytes
4627 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4628 raw_inode->i_blocks_high = 0;
4629 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4634 * This should never happen since sb->s_maxbytes should not have
4635 * allowed this, sb->s_maxbytes was set according to the huge_file
4636 * feature in ext4_fill_super().
4638 if (!ext4_has_feature_huge_file(sb))
4639 return -EFSCORRUPTED;
4641 if (i_blocks <= 0xffffffffffffULL) {
4643 * i_blocks can be represented in a 48 bit variable
4644 * as multiple of 512 bytes
4646 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4647 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4648 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4650 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4651 /* i_block is stored in file system block size */
4652 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4653 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4654 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4659 static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
4661 struct ext4_inode_info *ei = EXT4_I(inode);
4668 err = ext4_inode_blocks_set(raw_inode, ei);
4670 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4671 i_uid = i_uid_read(inode);
4672 i_gid = i_gid_read(inode);
4673 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4674 if (!(test_opt(inode->i_sb, NO_UID32))) {
4675 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4676 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4678 * Fix up interoperability with old kernels. Otherwise,
4679 * old inodes get re-used with the upper 16 bits of the
4682 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4683 raw_inode->i_uid_high = 0;
4684 raw_inode->i_gid_high = 0;
4686 raw_inode->i_uid_high =
4687 cpu_to_le16(high_16_bits(i_uid));
4688 raw_inode->i_gid_high =
4689 cpu_to_le16(high_16_bits(i_gid));
4692 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4693 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4694 raw_inode->i_uid_high = 0;
4695 raw_inode->i_gid_high = 0;
4697 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4699 EXT4_INODE_SET_CTIME(inode, raw_inode);
4700 EXT4_INODE_SET_MTIME(inode, raw_inode);
4701 EXT4_INODE_SET_ATIME(inode, raw_inode);
4702 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4704 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4705 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4706 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4707 raw_inode->i_file_acl_high =
4708 cpu_to_le16(ei->i_file_acl >> 32);
4709 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4710 ext4_isize_set(raw_inode, ei->i_disksize);
4712 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4713 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4714 if (old_valid_dev(inode->i_rdev)) {
4715 raw_inode->i_block[0] =
4716 cpu_to_le32(old_encode_dev(inode->i_rdev));
4717 raw_inode->i_block[1] = 0;
4719 raw_inode->i_block[0] = 0;
4720 raw_inode->i_block[1] =
4721 cpu_to_le32(new_encode_dev(inode->i_rdev));
4722 raw_inode->i_block[2] = 0;
4724 } else if (!ext4_has_inline_data(inode)) {
4725 for (block = 0; block < EXT4_N_BLOCKS; block++)
4726 raw_inode->i_block[block] = ei->i_data[block];
4729 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4730 u64 ivers = ext4_inode_peek_iversion(inode);
4732 raw_inode->i_disk_version = cpu_to_le32(ivers);
4733 if (ei->i_extra_isize) {
4734 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4735 raw_inode->i_version_hi =
4736 cpu_to_le32(ivers >> 32);
4737 raw_inode->i_extra_isize =
4738 cpu_to_le16(ei->i_extra_isize);
4742 if (i_projid != EXT4_DEF_PROJID &&
4743 !ext4_has_feature_project(inode->i_sb))
4744 err = err ?: -EFSCORRUPTED;
4746 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4747 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4748 raw_inode->i_projid = cpu_to_le32(i_projid);
4750 ext4_inode_csum_set(inode, raw_inode, ei);
4755 * ext4_get_inode_loc returns with an extra refcount against the inode's
4756 * underlying buffer_head on success. If we pass 'inode' and it does not
4757 * have in-inode xattr, we have all inode data in memory that is needed
4758 * to recreate the on-disk version of this inode.
4760 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4761 struct inode *inode, struct ext4_iloc *iloc,
4762 ext4_fsblk_t *ret_block)
4764 struct ext4_group_desc *gdp;
4765 struct buffer_head *bh;
4767 struct blk_plug plug;
4768 int inodes_per_block, inode_offset;
4771 if (ino < EXT4_ROOT_INO ||
4772 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4773 return -EFSCORRUPTED;
4775 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4776 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4781 * Figure out the offset within the block group inode table
4783 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4784 inode_offset = ((ino - 1) %
4785 EXT4_INODES_PER_GROUP(sb));
4786 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4788 block = ext4_inode_table(sb, gdp);
4789 if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4790 (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4791 ext4_error(sb, "Invalid inode table block %llu in "
4792 "block_group %u", block, iloc->block_group);
4793 return -EFSCORRUPTED;
4795 block += (inode_offset / inodes_per_block);
4797 bh = sb_getblk(sb, block);
4800 if (ext4_buffer_uptodate(bh))
4804 if (ext4_buffer_uptodate(bh)) {
4805 /* Someone brought it uptodate while we waited */
4811 * If we have all information of the inode in memory and this
4812 * is the only valid inode in the block, we need not read the
4815 if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4816 struct buffer_head *bitmap_bh;
4819 start = inode_offset & ~(inodes_per_block - 1);
4821 /* Is the inode bitmap in cache? */
4822 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4823 if (unlikely(!bitmap_bh))
4827 * If the inode bitmap isn't in cache then the
4828 * optimisation may end up performing two reads instead
4829 * of one, so skip it.
4831 if (!buffer_uptodate(bitmap_bh)) {
4835 for (i = start; i < start + inodes_per_block; i++) {
4836 if (i == inode_offset)
4838 if (ext4_test_bit(i, bitmap_bh->b_data))
4842 if (i == start + inodes_per_block) {
4843 struct ext4_inode *raw_inode =
4844 (struct ext4_inode *) (bh->b_data + iloc->offset);
4846 /* all other inodes are free, so skip I/O */
4847 memset(bh->b_data, 0, bh->b_size);
4848 if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4849 ext4_fill_raw_inode(inode, raw_inode);
4850 set_buffer_uptodate(bh);
4858 * If we need to do any I/O, try to pre-readahead extra
4859 * blocks from the inode table.
4861 blk_start_plug(&plug);
4862 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4863 ext4_fsblk_t b, end, table;
4865 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4867 table = ext4_inode_table(sb, gdp);
4868 /* s_inode_readahead_blks is always a power of 2 */
4869 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4873 num = EXT4_INODES_PER_GROUP(sb);
4874 if (ext4_has_group_desc_csum(sb))
4875 num -= ext4_itable_unused_count(sb, gdp);
4876 table += num / inodes_per_block;
4880 ext4_sb_breadahead_unmovable(sb, b++);
4884 * There are other valid inodes in the buffer, this inode
4885 * has in-inode xattrs, or we don't have this inode in memory.
4886 * Read the block from disk.
4888 trace_ext4_load_inode(sb, ino);
4889 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL,
4890 ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO));
4891 blk_finish_plug(&plug);
4893 if (!buffer_uptodate(bh)) {
4904 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4905 struct ext4_iloc *iloc)
4907 ext4_fsblk_t err_blk = 0;
4910 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
4914 ext4_error_inode_block(inode, err_blk, EIO,
4915 "unable to read itable block");
4920 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4922 ext4_fsblk_t err_blk = 0;
4925 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4929 ext4_error_inode_block(inode, err_blk, EIO,
4930 "unable to read itable block");
4936 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4937 struct ext4_iloc *iloc)
4939 return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4942 static bool ext4_should_enable_dax(struct inode *inode)
4944 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4946 if (test_opt2(inode->i_sb, DAX_NEVER))
4948 if (!S_ISREG(inode->i_mode))
4950 if (ext4_should_journal_data(inode))
4952 if (ext4_has_inline_data(inode))
4954 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4956 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4958 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4960 if (test_opt(inode->i_sb, DAX_ALWAYS))
4963 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4966 void ext4_set_inode_flags(struct inode *inode, bool init)
4968 unsigned int flags = EXT4_I(inode)->i_flags;
4969 unsigned int new_fl = 0;
4971 WARN_ON_ONCE(IS_DAX(inode) && init);
4973 if (flags & EXT4_SYNC_FL)
4975 if (flags & EXT4_APPEND_FL)
4977 if (flags & EXT4_IMMUTABLE_FL)
4978 new_fl |= S_IMMUTABLE;
4979 if (flags & EXT4_NOATIME_FL)
4980 new_fl |= S_NOATIME;
4981 if (flags & EXT4_DIRSYNC_FL)
4982 new_fl |= S_DIRSYNC;
4984 /* Because of the way inode_set_flags() works we must preserve S_DAX
4985 * here if already set. */
4986 new_fl |= (inode->i_flags & S_DAX);
4987 if (init && ext4_should_enable_dax(inode))
4990 if (flags & EXT4_ENCRYPT_FL)
4991 new_fl |= S_ENCRYPTED;
4992 if (flags & EXT4_CASEFOLD_FL)
4993 new_fl |= S_CASEFOLD;
4994 if (flags & EXT4_VERITY_FL)
4996 inode_set_flags(inode, new_fl,
4997 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4998 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
5001 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
5002 struct ext4_inode_info *ei)
5005 struct inode *inode = &(ei->vfs_inode);
5006 struct super_block *sb = inode->i_sb;
5008 if (ext4_has_feature_huge_file(sb)) {
5009 /* we are using combined 48 bit field */
5010 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
5011 le32_to_cpu(raw_inode->i_blocks_lo);
5012 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
5013 /* i_blocks represent file system block size */
5014 return i_blocks << (inode->i_blkbits - 9);
5019 return le32_to_cpu(raw_inode->i_blocks_lo);
5023 static inline int ext4_iget_extra_inode(struct inode *inode,
5024 struct ext4_inode *raw_inode,
5025 struct ext4_inode_info *ei)
5027 __le32 *magic = (void *)raw_inode +
5028 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
5030 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
5031 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
5034 err = xattr_check_inode(inode, IHDR(inode, raw_inode),
5035 ITAIL(inode, raw_inode));
5039 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
5040 err = ext4_find_inline_data_nolock(inode);
5041 if (!err && ext4_has_inline_data(inode))
5042 ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
5045 EXT4_I(inode)->i_inline_off = 0;
5049 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
5051 if (!ext4_has_feature_project(inode->i_sb))
5053 *projid = EXT4_I(inode)->i_projid;
5058 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
5059 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
5062 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
5064 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
5065 inode_set_iversion_raw(inode, val);
5067 inode_set_iversion_queried(inode, val);
5070 static int check_igot_inode(struct inode *inode, ext4_iget_flags flags,
5071 const char *function, unsigned int line)
5073 const char *err_str;
5075 if (flags & EXT4_IGET_EA_INODE) {
5076 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
5077 err_str = "missing EA_INODE flag";
5080 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5081 EXT4_I(inode)->i_file_acl) {
5082 err_str = "ea_inode with extended attributes";
5086 if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
5088 * open_by_handle_at() could provide an old inode number
5089 * that has since been reused for an ea_inode; this does
5090 * not indicate filesystem corruption
5092 if (flags & EXT4_IGET_HANDLE)
5094 err_str = "unexpected EA_INODE flag";
5098 if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD)) {
5099 err_str = "unexpected bad inode w/o EXT4_IGET_BAD";
5105 ext4_error_inode(inode, function, line, 0, "%s", err_str);
5106 return -EFSCORRUPTED;
5109 bool ext4_should_enable_large_folio(struct inode *inode)
5111 struct super_block *sb = inode->i_sb;
5113 if (!S_ISREG(inode->i_mode))
5115 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
5116 ext4_test_inode_flag(inode, EXT4_INODE_JOURNAL_DATA))
5118 if (ext4_has_feature_verity(sb))
5120 if (ext4_has_feature_encrypt(sb))
5126 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
5127 ext4_iget_flags flags, const char *function,
5130 struct ext4_iloc iloc;
5131 struct ext4_inode *raw_inode;
5132 struct ext4_inode_info *ei;
5133 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
5134 struct inode *inode;
5135 journal_t *journal = EXT4_SB(sb)->s_journal;
5143 if ((!(flags & EXT4_IGET_SPECIAL) && is_special_ino(sb, ino)) ||
5144 (ino < EXT4_ROOT_INO) ||
5145 (ino > le32_to_cpu(es->s_inodes_count))) {
5146 if (flags & EXT4_IGET_HANDLE)
5147 return ERR_PTR(-ESTALE);
5148 __ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
5149 "inode #%lu: comm %s: iget: illegal inode #",
5150 ino, current->comm);
5151 return ERR_PTR(-EFSCORRUPTED);
5154 inode = iget_locked(sb, ino);
5156 return ERR_PTR(-ENOMEM);
5157 if (!(inode->i_state & I_NEW)) {
5158 ret = check_igot_inode(inode, flags, function, line);
5161 return ERR_PTR(ret);
5169 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
5172 raw_inode = ext4_raw_inode(&iloc);
5174 if ((flags & EXT4_IGET_HANDLE) &&
5175 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
5180 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5181 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
5182 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
5183 EXT4_INODE_SIZE(inode->i_sb) ||
5184 (ei->i_extra_isize & 3)) {
5185 ext4_error_inode(inode, function, line, 0,
5186 "iget: bad extra_isize %u "
5189 EXT4_INODE_SIZE(inode->i_sb));
5190 ret = -EFSCORRUPTED;
5194 ei->i_extra_isize = 0;
5196 /* Precompute checksum seed for inode metadata */
5197 if (ext4_has_feature_metadata_csum(sb)) {
5198 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5200 __le32 inum = cpu_to_le32(inode->i_ino);
5201 __le32 gen = raw_inode->i_generation;
5202 csum = ext4_chksum(sbi->s_csum_seed, (__u8 *)&inum,
5204 ei->i_csum_seed = ext4_chksum(csum, (__u8 *)&gen, sizeof(gen));
5207 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
5208 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
5209 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
5210 ext4_error_inode_err(inode, function, line, 0,
5211 EFSBADCRC, "iget: checksum invalid");
5216 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
5217 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
5218 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
5219 if (ext4_has_feature_project(sb) &&
5220 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5221 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5222 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
5224 i_projid = EXT4_DEF_PROJID;
5226 if (!(test_opt(inode->i_sb, NO_UID32))) {
5227 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
5228 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
5230 i_uid_write(inode, i_uid);
5231 i_gid_write(inode, i_gid);
5232 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
5233 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
5235 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
5236 ei->i_inline_off = 0;
5237 ei->i_dir_start_lookup = 0;
5238 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
5239 /* We now have enough fields to check if the inode was active or not.
5240 * This is needed because nfsd might try to access dead inodes
5241 * the test is that same one that e2fsck uses
5242 * NeilBrown 1999oct15
5244 if (inode->i_nlink == 0) {
5245 if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
5246 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
5247 ino != EXT4_BOOT_LOADER_INO) {
5248 /* this inode is deleted or unallocated */
5249 if (flags & EXT4_IGET_SPECIAL) {
5250 ext4_error_inode(inode, function, line, 0,
5251 "iget: special inode unallocated");
5252 ret = -EFSCORRUPTED;
5257 /* The only unlinked inodes we let through here have
5258 * valid i_mode and are being read by the orphan
5259 * recovery code: that's fine, we're about to complete
5260 * the process of deleting those.
5261 * OR it is the EXT4_BOOT_LOADER_INO which is
5262 * not initialized on a new filesystem. */
5264 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
5265 ext4_set_inode_flags(inode, true);
5266 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
5267 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
5268 if (ext4_has_feature_64bit(sb))
5270 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
5271 inode->i_size = ext4_isize(sb, raw_inode);
5272 size = i_size_read(inode);
5273 if (size < 0 || size > ext4_get_maxbytes(inode)) {
5274 ext4_error_inode(inode, function, line, 0,
5275 "iget: bad i_size value: %lld", size);
5276 ret = -EFSCORRUPTED;
5280 * If dir_index is not enabled but there's dir with INDEX flag set,
5281 * we'd normally treat htree data as empty space. But with metadata
5282 * checksumming that corrupts checksums so forbid that.
5284 if (!ext4_has_feature_dir_index(sb) &&
5285 ext4_has_feature_metadata_csum(sb) &&
5286 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
5287 ext4_error_inode(inode, function, line, 0,
5288 "iget: Dir with htree data on filesystem without dir_index feature.");
5289 ret = -EFSCORRUPTED;
5292 ei->i_disksize = inode->i_size;
5294 ei->i_reserved_quota = 0;
5296 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
5297 ei->i_block_group = iloc.block_group;
5298 ei->i_last_alloc_group = ~0;
5300 * NOTE! The in-memory inode i_data array is in little-endian order
5301 * even on big-endian machines: we do NOT byteswap the block numbers!
5303 for (block = 0; block < EXT4_N_BLOCKS; block++)
5304 ei->i_data[block] = raw_inode->i_block[block];
5305 INIT_LIST_HEAD(&ei->i_orphan);
5306 ext4_fc_init_inode(&ei->vfs_inode);
5309 * Set transaction id's of transactions that have to be committed
5310 * to finish f[data]sync. We set them to currently running transaction
5311 * as we cannot be sure that the inode or some of its metadata isn't
5312 * part of the transaction - the inode could have been reclaimed and
5313 * now it is reread from disk.
5316 transaction_t *transaction;
5319 read_lock(&journal->j_state_lock);
5320 if (journal->j_running_transaction)
5321 transaction = journal->j_running_transaction;
5323 transaction = journal->j_committing_transaction;
5325 tid = transaction->t_tid;
5327 tid = journal->j_commit_sequence;
5328 read_unlock(&journal->j_state_lock);
5329 ei->i_sync_tid = tid;
5330 ei->i_datasync_tid = tid;
5333 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5334 if (ei->i_extra_isize == 0) {
5335 /* The extra space is currently unused. Use it. */
5336 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
5337 ei->i_extra_isize = sizeof(struct ext4_inode) -
5338 EXT4_GOOD_OLD_INODE_SIZE;
5340 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
5346 EXT4_INODE_GET_CTIME(inode, raw_inode);
5347 EXT4_INODE_GET_ATIME(inode, raw_inode);
5348 EXT4_INODE_GET_MTIME(inode, raw_inode);
5349 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5351 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5352 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
5354 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5355 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5357 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5359 ext4_inode_set_iversion_queried(inode, ivers);
5363 if (ei->i_file_acl &&
5364 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
5365 ext4_error_inode(inode, function, line, 0,
5366 "iget: bad extended attribute block %llu",
5368 ret = -EFSCORRUPTED;
5370 } else if (!ext4_has_inline_data(inode)) {
5371 /* validate the block references in the inode */
5372 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
5373 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5374 (S_ISLNK(inode->i_mode) &&
5375 !ext4_inode_is_fast_symlink(inode)))) {
5376 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5377 ret = ext4_ext_check_inode(inode);
5379 ret = ext4_ind_check_inode(inode);
5385 if (S_ISREG(inode->i_mode)) {
5386 inode->i_op = &ext4_file_inode_operations;
5387 inode->i_fop = &ext4_file_operations;
5388 ext4_set_aops(inode);
5389 } else if (S_ISDIR(inode->i_mode)) {
5390 inode->i_op = &ext4_dir_inode_operations;
5391 inode->i_fop = &ext4_dir_operations;
5392 } else if (S_ISLNK(inode->i_mode)) {
5393 /* VFS does not allow setting these so must be corruption */
5394 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
5395 ext4_error_inode(inode, function, line, 0,
5396 "iget: immutable or append flags "
5397 "not allowed on symlinks");
5398 ret = -EFSCORRUPTED;
5401 if (IS_ENCRYPTED(inode)) {
5402 inode->i_op = &ext4_encrypted_symlink_inode_operations;
5403 } else if (ext4_inode_is_fast_symlink(inode)) {
5404 inode->i_op = &ext4_fast_symlink_inode_operations;
5405 if (inode->i_size == 0 ||
5406 inode->i_size >= sizeof(ei->i_data) ||
5407 strnlen((char *)ei->i_data, inode->i_size + 1) !=
5409 ext4_error_inode(inode, function, line, 0,
5410 "invalid fast symlink length %llu",
5411 (unsigned long long)inode->i_size);
5412 ret = -EFSCORRUPTED;
5415 inode_set_cached_link(inode, (char *)ei->i_data,
5418 inode->i_op = &ext4_symlink_inode_operations;
5420 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5421 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5422 inode->i_op = &ext4_special_inode_operations;
5423 if (raw_inode->i_block[0])
5424 init_special_inode(inode, inode->i_mode,
5425 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5427 init_special_inode(inode, inode->i_mode,
5428 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5429 } else if (ino == EXT4_BOOT_LOADER_INO) {
5430 make_bad_inode(inode);
5432 ret = -EFSCORRUPTED;
5433 ext4_error_inode(inode, function, line, 0,
5434 "iget: bogus i_mode (%o)", inode->i_mode);
5437 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
5438 ext4_error_inode(inode, function, line, 0,
5439 "casefold flag without casefold feature");
5440 ret = -EFSCORRUPTED;
5443 if (ext4_should_enable_large_folio(inode))
5444 mapping_set_large_folios(inode->i_mapping);
5446 ret = check_igot_inode(inode, flags, function, line);
5448 * -ESTALE here means there is nothing inherently wrong with the inode,
5449 * it's just not an inode we can return for an fhandle lookup.
5451 if (ret == -ESTALE) {
5453 unlock_new_inode(inode);
5455 return ERR_PTR(-ESTALE);
5461 unlock_new_inode(inode);
5467 return ERR_PTR(ret);
5470 static void __ext4_update_other_inode_time(struct super_block *sb,
5471 unsigned long orig_ino,
5473 struct ext4_inode *raw_inode)
5475 struct inode *inode;
5477 inode = find_inode_by_ino_rcu(sb, ino);
5481 if (!inode_is_dirtytime_only(inode))
5484 spin_lock(&inode->i_lock);
5485 if (inode_is_dirtytime_only(inode)) {
5486 struct ext4_inode_info *ei = EXT4_I(inode);
5488 inode->i_state &= ~I_DIRTY_TIME;
5489 spin_unlock(&inode->i_lock);
5491 spin_lock(&ei->i_raw_lock);
5492 EXT4_INODE_SET_CTIME(inode, raw_inode);
5493 EXT4_INODE_SET_MTIME(inode, raw_inode);
5494 EXT4_INODE_SET_ATIME(inode, raw_inode);
5495 ext4_inode_csum_set(inode, raw_inode, ei);
5496 spin_unlock(&ei->i_raw_lock);
5497 trace_ext4_other_inode_update_time(inode, orig_ino);
5500 spin_unlock(&inode->i_lock);
5504 * Opportunistically update the other time fields for other inodes in
5505 * the same inode table block.
5507 static void ext4_update_other_inodes_time(struct super_block *sb,
5508 unsigned long orig_ino, char *buf)
5511 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5512 int inode_size = EXT4_INODE_SIZE(sb);
5515 * Calculate the first inode in the inode table block. Inode
5516 * numbers are one-based. That is, the first inode in a block
5517 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5519 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5521 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5522 if (ino == orig_ino)
5524 __ext4_update_other_inode_time(sb, orig_ino, ino,
5525 (struct ext4_inode *)buf);
5531 * Post the struct inode info into an on-disk inode location in the
5532 * buffer-cache. This gobbles the caller's reference to the
5533 * buffer_head in the inode location struct.
5535 * The caller must have write access to iloc->bh.
5537 static int ext4_do_update_inode(handle_t *handle,
5538 struct inode *inode,
5539 struct ext4_iloc *iloc)
5541 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5542 struct ext4_inode_info *ei = EXT4_I(inode);
5543 struct buffer_head *bh = iloc->bh;
5544 struct super_block *sb = inode->i_sb;
5546 int need_datasync = 0, set_large_file = 0;
5548 spin_lock(&ei->i_raw_lock);
5551 * For fields not tracked in the in-memory inode, initialise them
5552 * to zero for new inodes.
5554 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5555 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5557 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5559 if (ei->i_disksize > 0x7fffffffULL) {
5560 if (!ext4_has_feature_large_file(sb) ||
5561 EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5565 err = ext4_fill_raw_inode(inode, raw_inode);
5566 spin_unlock(&ei->i_raw_lock);
5568 EXT4_ERROR_INODE(inode, "corrupted inode contents");
5572 if (inode->i_sb->s_flags & SB_LAZYTIME)
5573 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5576 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5577 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5580 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5581 if (set_large_file) {
5582 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5583 err = ext4_journal_get_write_access(handle, sb,
5588 lock_buffer(EXT4_SB(sb)->s_sbh);
5589 ext4_set_feature_large_file(sb);
5590 ext4_superblock_csum_set(sb);
5591 unlock_buffer(EXT4_SB(sb)->s_sbh);
5592 ext4_handle_sync(handle);
5593 err = ext4_handle_dirty_metadata(handle, NULL,
5594 EXT4_SB(sb)->s_sbh);
5596 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5598 ext4_std_error(inode->i_sb, err);
5605 * ext4_write_inode()
5607 * We are called from a few places:
5609 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5610 * Here, there will be no transaction running. We wait for any running
5611 * transaction to commit.
5613 * - Within flush work (sys_sync(), kupdate and such).
5614 * We wait on commit, if told to.
5616 * - Within iput_final() -> write_inode_now()
5617 * We wait on commit, if told to.
5619 * In all cases it is actually safe for us to return without doing anything,
5620 * because the inode has been copied into a raw inode buffer in
5621 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5624 * Note that we are absolutely dependent upon all inode dirtiers doing the
5625 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5626 * which we are interested.
5628 * It would be a bug for them to not do this. The code:
5630 * mark_inode_dirty(inode)
5632 * inode->i_size = expr;
5634 * is in error because write_inode() could occur while `stuff()' is running,
5635 * and the new i_size will be lost. Plus the inode will no longer be on the
5636 * superblock's dirty inode list.
5638 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5642 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5645 err = ext4_emergency_state(inode->i_sb);
5649 if (EXT4_SB(inode->i_sb)->s_journal) {
5650 if (ext4_journal_current_handle()) {
5651 ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5657 * No need to force transaction in WB_SYNC_NONE mode. Also
5658 * ext4_sync_fs() will force the commit after everything is
5661 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5664 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5665 EXT4_I(inode)->i_sync_tid);
5667 struct ext4_iloc iloc;
5669 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5673 * sync(2) will flush the whole buffer cache. No need to do
5674 * it here separately for each inode.
5676 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5677 sync_dirty_buffer(iloc.bh);
5678 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5679 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5680 "IO error syncing inode");
5689 * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5690 * buffers that are attached to a folio straddling i_size and are undergoing
5691 * commit. In that case we have to wait for commit to finish and try again.
5693 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5696 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5699 bool has_transaction;
5701 offset = inode->i_size & (PAGE_SIZE - 1);
5703 * If the folio is fully truncated, we don't need to wait for any commit
5704 * (and we even should not as __ext4_journalled_invalidate_folio() may
5705 * strip all buffers from the folio but keep the folio dirty which can then
5706 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5707 * buffers). Also we don't need to wait for any commit if all buffers in
5708 * the folio remain valid. This is most beneficial for the common case of
5709 * blocksize == PAGESIZE.
5711 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5714 struct folio *folio = filemap_lock_folio(inode->i_mapping,
5715 inode->i_size >> PAGE_SHIFT);
5718 ret = __ext4_journalled_invalidate_folio(folio, offset,
5719 folio_size(folio) - offset);
5720 folio_unlock(folio);
5724 has_transaction = false;
5725 read_lock(&journal->j_state_lock);
5726 if (journal->j_committing_transaction) {
5727 commit_tid = journal->j_committing_transaction->t_tid;
5728 has_transaction = true;
5730 read_unlock(&journal->j_state_lock);
5731 if (has_transaction)
5732 jbd2_log_wait_commit(journal, commit_tid);
5739 * Called from notify_change.
5741 * We want to trap VFS attempts to truncate the file as soon as
5742 * possible. In particular, we want to make sure that when the VFS
5743 * shrinks i_size, we put the inode on the orphan list and modify
5744 * i_disksize immediately, so that during the subsequent flushing of
5745 * dirty pages and freeing of disk blocks, we can guarantee that any
5746 * commit will leave the blocks being flushed in an unused state on
5747 * disk. (On recovery, the inode will get truncated and the blocks will
5748 * be freed, so we have a strong guarantee that no future commit will
5749 * leave these blocks visible to the user.)
5751 * Another thing we have to assure is that if we are in ordered mode
5752 * and inode is still attached to the committing transaction, we must
5753 * we start writeout of all the dirty pages which are being truncated.
5754 * This way we are sure that all the data written in the previous
5755 * transaction are already on disk (truncate waits for pages under
5758 * Called with inode->i_rwsem down.
5760 int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5763 struct inode *inode = d_inode(dentry);
5766 const unsigned int ia_valid = attr->ia_valid;
5767 bool inc_ivers = true;
5769 error = ext4_emergency_state(inode->i_sb);
5770 if (unlikely(error))
5773 if (unlikely(IS_IMMUTABLE(inode)))
5776 if (unlikely(IS_APPEND(inode) &&
5777 (ia_valid & (ATTR_MODE | ATTR_UID |
5778 ATTR_GID | ATTR_TIMES_SET))))
5781 error = setattr_prepare(idmap, dentry, attr);
5785 error = fscrypt_prepare_setattr(dentry, attr);
5789 error = fsverity_prepare_setattr(dentry, attr);
5793 if (is_quota_modification(idmap, inode, attr)) {
5794 error = dquot_initialize(inode);
5799 if (i_uid_needs_update(idmap, attr, inode) ||
5800 i_gid_needs_update(idmap, attr, inode)) {
5803 /* (user+group)*(old+new) structure, inode write (sb,
5804 * inode block, ? - but truncate inode update has it) */
5805 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5806 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5807 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5808 if (IS_ERR(handle)) {
5809 error = PTR_ERR(handle);
5813 /* dquot_transfer() calls back ext4_get_inode_usage() which
5814 * counts xattr inode references.
5816 down_read(&EXT4_I(inode)->xattr_sem);
5817 error = dquot_transfer(idmap, inode, attr);
5818 up_read(&EXT4_I(inode)->xattr_sem);
5821 ext4_journal_stop(handle);
5824 /* Update corresponding info in inode so that everything is in
5825 * one transaction */
5826 i_uid_update(idmap, attr, inode);
5827 i_gid_update(idmap, attr, inode);
5828 error = ext4_mark_inode_dirty(handle, inode);
5829 ext4_journal_stop(handle);
5830 if (unlikely(error)) {
5835 if (attr->ia_valid & ATTR_SIZE) {
5837 loff_t oldsize = inode->i_size;
5838 loff_t old_disksize;
5839 int shrink = (attr->ia_size < inode->i_size);
5841 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5842 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5844 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5848 if (!S_ISREG(inode->i_mode)) {
5852 if (attr->ia_size == inode->i_size)
5856 if (ext4_should_order_data(inode)) {
5857 error = ext4_begin_ordered_truncate(inode,
5863 * Blocks are going to be removed from the inode. Wait
5864 * for dio in flight.
5866 inode_dio_wait(inode);
5869 filemap_invalidate_lock(inode->i_mapping);
5871 rc = ext4_break_layouts(inode);
5873 filemap_invalidate_unlock(inode->i_mapping);
5877 if (attr->ia_size != inode->i_size) {
5878 /* attach jbd2 jinode for EOF folio tail zeroing */
5879 if (attr->ia_size & (inode->i_sb->s_blocksize - 1) ||
5880 oldsize & (inode->i_sb->s_blocksize - 1)) {
5881 error = ext4_inode_attach_jinode(inode);
5886 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5887 if (IS_ERR(handle)) {
5888 error = PTR_ERR(handle);
5891 if (ext4_handle_valid(handle) && shrink) {
5892 error = ext4_orphan_add(handle, inode);
5896 * Update c/mtime and tail zero the EOF folio on
5897 * truncate up. ext4_truncate() handles the shrink case
5901 inode_set_mtime_to_ts(inode,
5902 inode_set_ctime_current(inode));
5903 if (oldsize & (inode->i_sb->s_blocksize - 1))
5904 ext4_block_truncate_page(handle,
5905 inode->i_mapping, oldsize);
5909 ext4_fc_track_range(handle, inode,
5910 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5911 inode->i_sb->s_blocksize_bits,
5912 EXT_MAX_BLOCKS - 1);
5914 ext4_fc_track_range(
5916 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5917 inode->i_sb->s_blocksize_bits,
5918 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5919 inode->i_sb->s_blocksize_bits);
5921 down_write(&EXT4_I(inode)->i_data_sem);
5922 old_disksize = EXT4_I(inode)->i_disksize;
5923 EXT4_I(inode)->i_disksize = attr->ia_size;
5926 * We have to update i_size under i_data_sem together
5927 * with i_disksize to avoid races with writeback code
5928 * running ext4_wb_update_i_disksize().
5931 i_size_write(inode, attr->ia_size);
5933 EXT4_I(inode)->i_disksize = old_disksize;
5934 up_write(&EXT4_I(inode)->i_data_sem);
5935 rc = ext4_mark_inode_dirty(handle, inode);
5938 ext4_journal_stop(handle);
5942 pagecache_isize_extended(inode, oldsize,
5944 } else if (ext4_should_journal_data(inode)) {
5945 ext4_wait_for_tail_page_commit(inode);
5950 * Truncate pagecache after we've waited for commit
5951 * in data=journal mode to make pages freeable.
5953 truncate_pagecache(inode, inode->i_size);
5955 * Call ext4_truncate() even if i_size didn't change to
5956 * truncate possible preallocated blocks.
5958 if (attr->ia_size <= oldsize) {
5959 rc = ext4_truncate(inode);
5964 filemap_invalidate_unlock(inode->i_mapping);
5969 inode_inc_iversion(inode);
5970 setattr_copy(idmap, inode, attr);
5971 mark_inode_dirty(inode);
5975 * If the call to ext4_truncate failed to get a transaction handle at
5976 * all, we need to clean up the in-core orphan list manually.
5978 if (orphan && inode->i_nlink)
5979 ext4_orphan_del(NULL, inode);
5981 if (!error && (ia_valid & ATTR_MODE))
5982 rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
5986 ext4_std_error(inode->i_sb, error);
5992 u32 ext4_dio_alignment(struct inode *inode)
5994 if (fsverity_active(inode))
5996 if (ext4_should_journal_data(inode))
5998 if (ext4_has_inline_data(inode))
6000 if (IS_ENCRYPTED(inode)) {
6001 if (!fscrypt_dio_supported(inode))
6003 return i_blocksize(inode);
6005 return 1; /* use the iomap defaults */
6008 int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
6009 struct kstat *stat, u32 request_mask, unsigned int query_flags)
6011 struct inode *inode = d_inode(path->dentry);
6012 struct ext4_inode *raw_inode;
6013 struct ext4_inode_info *ei = EXT4_I(inode);
6016 if ((request_mask & STATX_BTIME) &&
6017 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
6018 stat->result_mask |= STATX_BTIME;
6019 stat->btime.tv_sec = ei->i_crtime.tv_sec;
6020 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
6024 * Return the DIO alignment restrictions if requested. We only return
6025 * this information when requested, since on encrypted files it might
6026 * take a fair bit of work to get if the file wasn't opened recently.
6028 if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
6029 u32 dio_align = ext4_dio_alignment(inode);
6031 stat->result_mask |= STATX_DIOALIGN;
6032 if (dio_align == 1) {
6033 struct block_device *bdev = inode->i_sb->s_bdev;
6035 /* iomap defaults */
6036 stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
6037 stat->dio_offset_align = bdev_logical_block_size(bdev);
6039 stat->dio_mem_align = dio_align;
6040 stat->dio_offset_align = dio_align;
6044 if ((request_mask & STATX_WRITE_ATOMIC) && S_ISREG(inode->i_mode)) {
6045 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6046 unsigned int awu_min = 0, awu_max = 0;
6048 if (ext4_inode_can_atomic_write(inode)) {
6049 awu_min = sbi->s_awu_min;
6050 awu_max = sbi->s_awu_max;
6053 generic_fill_statx_atomic_writes(stat, awu_min, awu_max, 0);
6056 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
6057 if (flags & EXT4_APPEND_FL)
6058 stat->attributes |= STATX_ATTR_APPEND;
6059 if (flags & EXT4_COMPR_FL)
6060 stat->attributes |= STATX_ATTR_COMPRESSED;
6061 if (flags & EXT4_ENCRYPT_FL)
6062 stat->attributes |= STATX_ATTR_ENCRYPTED;
6063 if (flags & EXT4_IMMUTABLE_FL)
6064 stat->attributes |= STATX_ATTR_IMMUTABLE;
6065 if (flags & EXT4_NODUMP_FL)
6066 stat->attributes |= STATX_ATTR_NODUMP;
6067 if (flags & EXT4_VERITY_FL)
6068 stat->attributes |= STATX_ATTR_VERITY;
6070 stat->attributes_mask |= (STATX_ATTR_APPEND |
6071 STATX_ATTR_COMPRESSED |
6072 STATX_ATTR_ENCRYPTED |
6073 STATX_ATTR_IMMUTABLE |
6077 generic_fillattr(idmap, request_mask, inode, stat);
6081 int ext4_file_getattr(struct mnt_idmap *idmap,
6082 const struct path *path, struct kstat *stat,
6083 u32 request_mask, unsigned int query_flags)
6085 struct inode *inode = d_inode(path->dentry);
6086 u64 delalloc_blocks;
6088 ext4_getattr(idmap, path, stat, request_mask, query_flags);
6091 * If there is inline data in the inode, the inode will normally not
6092 * have data blocks allocated (it may have an external xattr block).
6093 * Report at least one sector for such files, so tools like tar, rsync,
6094 * others don't incorrectly think the file is completely sparse.
6096 if (unlikely(ext4_has_inline_data(inode)))
6097 stat->blocks += (stat->size + 511) >> 9;
6100 * We can't update i_blocks if the block allocation is delayed
6101 * otherwise in the case of system crash before the real block
6102 * allocation is done, we will have i_blocks inconsistent with
6103 * on-disk file blocks.
6104 * We always keep i_blocks updated together with real
6105 * allocation. But to not confuse with user, stat
6106 * will return the blocks that include the delayed allocation
6107 * blocks for this file.
6109 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
6110 EXT4_I(inode)->i_reserved_data_blocks);
6111 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
6115 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
6118 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
6119 return ext4_ind_trans_blocks(inode, lblocks);
6120 return ext4_ext_index_trans_blocks(inode, pextents);
6124 * Account for index blocks, block groups bitmaps and block group
6125 * descriptor blocks if modify datablocks and index blocks
6126 * worse case, the indexs blocks spread over different block groups
6128 * If datablocks are discontiguous, they are possible to spread over
6129 * different block groups too. If they are contiguous, with flexbg,
6130 * they could still across block group boundary.
6132 * Also account for superblock, inode, quota and xattr blocks
6134 int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents)
6136 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
6142 * How many index and lead blocks need to touch to map @lblocks
6143 * logical blocks to @pextents physical extents?
6145 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
6148 * Now let's see how many group bitmaps and group descriptors need
6153 if (groups > ngroups)
6155 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
6156 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
6158 /* bitmaps and block group descriptor blocks */
6159 ret = idxblocks + groups + gdpblocks;
6161 /* Blocks for super block, inode, quota and xattr blocks */
6162 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
6168 * Calculate the total number of credits to reserve to fit
6169 * the modification of a single pages into a single transaction,
6170 * which may include multiple chunks of block allocations.
6172 * This could be called via ext4_write_begin()
6174 * We need to consider the worse case, when
6175 * one new block per extent.
6177 int ext4_writepage_trans_blocks(struct inode *inode)
6179 int bpp = ext4_journal_blocks_per_folio(inode);
6182 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
6184 /* Account for data blocks for journalled mode */
6185 if (ext4_should_journal_data(inode))
6191 * Calculate the journal credits for a chunk of data modification.
6193 * This is called from DIO, fallocate or whoever calling
6194 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
6196 * journal buffers for data blocks are not included here, as DIO
6197 * and fallocate do no need to journal data buffers.
6199 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
6201 return ext4_meta_trans_blocks(inode, nrblocks, 1);
6205 * The caller must have previously called ext4_reserve_inode_write().
6206 * Give this, we know that the caller already has write access to iloc->bh.
6208 int ext4_mark_iloc_dirty(handle_t *handle,
6209 struct inode *inode, struct ext4_iloc *iloc)
6213 err = ext4_emergency_state(inode->i_sb);
6214 if (unlikely(err)) {
6218 ext4_fc_track_inode(handle, inode);
6220 /* the do_update_inode consumes one bh->b_count */
6223 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
6224 err = ext4_do_update_inode(handle, inode, iloc);
6230 * On success, We end up with an outstanding reference count against
6231 * iloc->bh. This _must_ be cleaned up later.
6235 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
6236 struct ext4_iloc *iloc)
6240 err = ext4_emergency_state(inode->i_sb);
6244 err = ext4_get_inode_loc(inode, iloc);
6246 BUFFER_TRACE(iloc->bh, "get_write_access");
6247 err = ext4_journal_get_write_access(handle, inode->i_sb,
6248 iloc->bh, EXT4_JTR_NONE);
6253 ext4_fc_track_inode(handle, inode);
6255 ext4_std_error(inode->i_sb, err);
6259 static int __ext4_expand_extra_isize(struct inode *inode,
6260 unsigned int new_extra_isize,
6261 struct ext4_iloc *iloc,
6262 handle_t *handle, int *no_expand)
6264 struct ext4_inode *raw_inode;
6265 struct ext4_xattr_ibody_header *header;
6266 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
6267 struct ext4_inode_info *ei = EXT4_I(inode);
6270 /* this was checked at iget time, but double check for good measure */
6271 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
6272 (ei->i_extra_isize & 3)) {
6273 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
6275 EXT4_INODE_SIZE(inode->i_sb));
6276 return -EFSCORRUPTED;
6278 if ((new_extra_isize < ei->i_extra_isize) ||
6279 (new_extra_isize < 4) ||
6280 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
6281 return -EINVAL; /* Should never happen */
6283 raw_inode = ext4_raw_inode(iloc);
6285 header = IHDR(inode, raw_inode);
6287 /* No extended attributes present */
6288 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
6289 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
6290 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
6291 EXT4_I(inode)->i_extra_isize, 0,
6292 new_extra_isize - EXT4_I(inode)->i_extra_isize);
6293 EXT4_I(inode)->i_extra_isize = new_extra_isize;
6298 * We may need to allocate external xattr block so we need quotas
6299 * initialized. Here we can be called with various locks held so we
6300 * cannot affort to initialize quotas ourselves. So just bail.
6302 if (dquot_initialize_needed(inode))
6305 /* try to expand with EAs present */
6306 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
6310 * Inode size expansion failed; don't try again
6319 * Expand an inode by new_extra_isize bytes.
6320 * Returns 0 on success or negative error number on failure.
6322 static int ext4_try_to_expand_extra_isize(struct inode *inode,
6323 unsigned int new_extra_isize,
6324 struct ext4_iloc iloc,
6330 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
6334 * In nojournal mode, we can immediately attempt to expand
6335 * the inode. When journaled, we first need to obtain extra
6336 * buffer credits since we may write into the EA block
6337 * with this same handle. If journal_extend fails, then it will
6338 * only result in a minor loss of functionality for that inode.
6339 * If this is felt to be critical, then e2fsck should be run to
6340 * force a large enough s_min_extra_isize.
6342 if (ext4_journal_extend(handle,
6343 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
6346 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
6349 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
6350 handle, &no_expand);
6351 ext4_write_unlock_xattr(inode, &no_expand);
6356 int ext4_expand_extra_isize(struct inode *inode,
6357 unsigned int new_extra_isize,
6358 struct ext4_iloc *iloc)
6364 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
6369 handle = ext4_journal_start(inode, EXT4_HT_INODE,
6370 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
6371 if (IS_ERR(handle)) {
6372 error = PTR_ERR(handle);
6377 ext4_write_lock_xattr(inode, &no_expand);
6379 BUFFER_TRACE(iloc->bh, "get_write_access");
6380 error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
6387 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
6388 handle, &no_expand);
6390 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
6395 ext4_write_unlock_xattr(inode, &no_expand);
6396 ext4_journal_stop(handle);
6401 * What we do here is to mark the in-core inode as clean with respect to inode
6402 * dirtiness (it may still be data-dirty).
6403 * This means that the in-core inode may be reaped by prune_icache
6404 * without having to perform any I/O. This is a very good thing,
6405 * because *any* task may call prune_icache - even ones which
6406 * have a transaction open against a different journal.
6408 * Is this cheating? Not really. Sure, we haven't written the
6409 * inode out, but prune_icache isn't a user-visible syncing function.
6410 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
6411 * we start and wait on commits.
6413 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
6414 const char *func, unsigned int line)
6416 struct ext4_iloc iloc;
6417 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6421 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
6422 err = ext4_reserve_inode_write(handle, inode, &iloc);
6426 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6427 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
6430 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
6433 ext4_error_inode_err(inode, func, line, 0, err,
6434 "mark_inode_dirty error");
6439 * ext4_dirty_inode() is called from __mark_inode_dirty()
6441 * We're really interested in the case where a file is being extended.
6442 * i_size has been changed by generic_commit_write() and we thus need
6443 * to include the updated inode in the current transaction.
6445 * Also, dquot_alloc_block() will always dirty the inode when blocks
6446 * are allocated to the file.
6448 * If the inode is marked synchronous, we don't honour that here - doing
6449 * so would cause a commit on atime updates, which we don't bother doing.
6450 * We handle synchronous inodes at the highest possible level.
6452 void ext4_dirty_inode(struct inode *inode, int flags)
6456 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6459 ext4_mark_inode_dirty(handle, inode);
6460 ext4_journal_stop(handle);
6463 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6471 * We have to be very careful here: changing a data block's
6472 * journaling status dynamically is dangerous. If we write a
6473 * data block to the journal, change the status and then delete
6474 * that block, we risk forgetting to revoke the old log record
6475 * from the journal and so a subsequent replay can corrupt data.
6476 * So, first we make sure that the journal is empty and that
6477 * nobody is changing anything.
6480 journal = EXT4_JOURNAL(inode);
6483 if (is_journal_aborted(journal))
6486 /* Wait for all existing dio workers */
6487 inode_dio_wait(inode);
6490 * Before flushing the journal and switching inode's aops, we have
6491 * to flush all dirty data the inode has. There can be outstanding
6492 * delayed allocations, there can be unwritten extents created by
6493 * fallocate or buffered writes in dioread_nolock mode covered by
6494 * dirty data which can be converted only after flushing the dirty
6495 * data (and journalled aops don't know how to handle these cases).
6498 filemap_invalidate_lock(inode->i_mapping);
6499 err = filemap_write_and_wait(inode->i_mapping);
6501 filemap_invalidate_unlock(inode->i_mapping);
6506 alloc_ctx = ext4_writepages_down_write(inode->i_sb);
6507 jbd2_journal_lock_updates(journal);
6510 * OK, there are no updates running now, and all cached data is
6511 * synced to disk. We are now in a completely consistent state
6512 * which doesn't have anything in the journal, and we know that
6513 * no filesystem updates are running, so it is safe to modify
6514 * the inode's in-core data-journaling state flag now.
6518 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6520 err = jbd2_journal_flush(journal, 0);
6522 jbd2_journal_unlock_updates(journal);
6523 ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6526 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6528 ext4_set_aops(inode);
6530 jbd2_journal_unlock_updates(journal);
6531 ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6534 filemap_invalidate_unlock(inode->i_mapping);
6536 /* Finally we can mark the inode as dirty. */
6538 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6540 return PTR_ERR(handle);
6542 ext4_fc_mark_ineligible(inode->i_sb,
6543 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6544 err = ext4_mark_inode_dirty(handle, inode);
6545 ext4_handle_sync(handle);
6546 ext4_journal_stop(handle);
6547 ext4_std_error(inode->i_sb, err);
6552 static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6553 struct buffer_head *bh)
6555 return !buffer_mapped(bh);
6558 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6560 struct vm_area_struct *vma = vmf->vma;
6561 struct folio *folio = page_folio(vmf->page);
6566 struct file *file = vma->vm_file;
6567 struct inode *inode = file_inode(file);
6568 struct address_space *mapping = inode->i_mapping;
6570 get_block_t *get_block;
6573 if (unlikely(IS_IMMUTABLE(inode)))
6574 return VM_FAULT_SIGBUS;
6576 sb_start_pagefault(inode->i_sb);
6577 file_update_time(vma->vm_file);
6579 filemap_invalidate_lock_shared(mapping);
6581 err = ext4_convert_inline_data(inode);
6586 * On data journalling we skip straight to the transaction handle:
6587 * there's no delalloc; page truncated will be checked later; the
6588 * early return w/ all buffers mapped (calculates size/len) can't
6589 * be used; and there's no dioread_nolock, so only ext4_get_block.
6591 if (ext4_should_journal_data(inode))
6594 /* Delalloc case is easy... */
6595 if (test_opt(inode->i_sb, DELALLOC) &&
6596 !ext4_nonda_switch(inode->i_sb)) {
6598 err = block_page_mkwrite(vma, vmf,
6599 ext4_da_get_block_prep);
6600 } while (err == -ENOSPC &&
6601 ext4_should_retry_alloc(inode->i_sb, &retries));
6606 size = i_size_read(inode);
6607 /* Page got truncated from under us? */
6608 if (folio->mapping != mapping || folio_pos(folio) > size) {
6609 folio_unlock(folio);
6610 ret = VM_FAULT_NOPAGE;
6614 len = folio_size(folio);
6615 if (folio_pos(folio) + len > size)
6616 len = size - folio_pos(folio);
6618 * Return if we have all the buffers mapped. This avoids the need to do
6619 * journal_start/journal_stop which can block and take a long time
6621 * This cannot be done for data journalling, as we have to add the
6622 * inode to the transaction's list to writeprotect pages on commit.
6624 if (folio_buffers(folio)) {
6625 if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6627 ext4_bh_unmapped)) {
6628 /* Wait so that we don't change page under IO */
6629 folio_wait_stable(folio);
6630 ret = VM_FAULT_LOCKED;
6634 folio_unlock(folio);
6635 /* OK, we need to fill the hole... */
6636 if (ext4_should_dioread_nolock(inode))
6637 get_block = ext4_get_block_unwritten;
6639 get_block = ext4_get_block;
6641 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6642 ext4_writepage_trans_blocks(inode));
6643 if (IS_ERR(handle)) {
6644 ret = VM_FAULT_SIGBUS;
6648 * Data journalling can't use block_page_mkwrite() because it
6649 * will set_buffer_dirty() before do_journal_get_write_access()
6650 * thus might hit warning messages for dirty metadata buffers.
6652 if (!ext4_should_journal_data(inode)) {
6653 err = block_page_mkwrite(vma, vmf, get_block);
6656 size = i_size_read(inode);
6657 /* Page got truncated from under us? */
6658 if (folio->mapping != mapping || folio_pos(folio) > size) {
6659 ret = VM_FAULT_NOPAGE;
6663 len = folio_size(folio);
6664 if (folio_pos(folio) + len > size)
6665 len = size - folio_pos(folio);
6667 err = ext4_block_write_begin(handle, folio, 0, len,
6670 ret = VM_FAULT_SIGBUS;
6671 if (ext4_journal_folio_buffers(handle, folio, len))
6674 folio_unlock(folio);
6677 ext4_journal_stop(handle);
6678 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6681 ret = vmf_fs_error(err);
6683 filemap_invalidate_unlock_shared(mapping);
6684 sb_end_pagefault(inode->i_sb);
6687 folio_unlock(folio);
6688 ext4_journal_stop(handle);