File Index
Files and directories
Sign in
FILE

inode.c

File preview with syntax highlighting.

linux-6.19.14/fs/ext4/inode.c C
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *  linux/fs/ext4/inode.c
   4 *
   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)
   9 *
  10 *  from
  11 *
  12 *  linux/fs/minix/inode.c
  13 *
  14 *  Copyright (C) 1991, 1992  Linus Torvalds
  15 *
  16 *  64-bit file support on 64-bit platforms by Jakub Jelinek
  17 *	(jj@sunsite.ms.mff.cuni.cz)
  18 *
  19 *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
  20 */
  21
  22#include <linux/fs.h>
  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>
  45
  46#include "ext4_jbd2.h"
  47#include "xattr.h"
  48#include "acl.h"
  49#include "truncate.h"
  50
  51#include <trace/events/ext4.h>
  52
  53static void ext4_journalled_zero_new_buffers(handle_t *handle,
  54					    struct inode *inode,
  55					    struct folio *folio,
  56					    unsigned from, unsigned to);
  57
  58static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
  59			      struct ext4_inode_info *ei)
  60{
  61	__u32 csum;
  62	__u16 dummy_csum = 0;
  63	int offset = offsetof(struct ext4_inode, i_checksum_lo);
  64	unsigned int csum_size = sizeof(dummy_csum);
  65
  66	csum = ext4_chksum(ei->i_csum_seed, (__u8 *)raw, offset);
  67	csum = ext4_chksum(csum, (__u8 *)&dummy_csum, csum_size);
  68	offset += csum_size;
  69	csum = ext4_chksum(csum, (__u8 *)raw + offset,
  70			   EXT4_GOOD_OLD_INODE_SIZE - offset);
  71
  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,
  78					   csum_size);
  79			offset += csum_size;
  80		}
  81		csum = ext4_chksum(csum, (__u8 *)raw + offset,
  82				   EXT4_INODE_SIZE(inode->i_sb) - offset);
  83	}
  84
  85	return csum;
  86}
  87
  88static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
  89				  struct ext4_inode_info *ei)
  90{
  91	__u32 provided, calculated;
  92
  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))
  96		return 1;
  97
  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;
 103	else
 104		calculated &= 0xFFFF;
 105
 106	return provided == calculated;
 107}
 108
 109void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
 110			 struct ext4_inode_info *ei)
 111{
 112	__u32 csum;
 113
 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))
 117		return;
 118
 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);
 124}
 125
 126static inline int ext4_begin_ordered_truncate(struct inode *inode,
 127					      loff_t new_size)
 128{
 129	struct jbd2_inode *jinode = READ_ONCE(EXT4_I(inode)->jinode);
 130
 131	trace_ext4_begin_ordered_truncate(inode, new_size);
 132	/*
 133	 * If jinode is zero, then we never opened the file for
 134	 * writing, so there's no need to call
 135	 * jbd2_journal_begin_ordered_truncate() since there's no
 136	 * outstanding writes we need to flush.
 137	 */
 138	if (!jinode)
 139		return 0;
 140	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
 141						   jinode,
 142						   new_size);
 143}
 144
 145/*
 146 * Test whether an inode is a fast symlink.
 147 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
 148 */
 149int ext4_inode_is_fast_symlink(struct inode *inode)
 150{
 151	if (!ext4_has_feature_ea_inode(inode->i_sb)) {
 152		int ea_blocks = EXT4_I(inode)->i_file_acl ?
 153				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
 154
 155		if (ext4_has_inline_data(inode))
 156			return 0;
 157
 158		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
 159	}
 160	return S_ISLNK(inode->i_mode) && inode->i_size &&
 161	       (inode->i_size < EXT4_N_BLOCKS * 4);
 162}
 163
 164/*
 165 * Called at the last iput() if i_nlink is zero.
 166 */
 167void ext4_evict_inode(struct inode *inode)
 168{
 169	handle_t *handle;
 170	int err;
 171	/*
 172	 * Credits for final inode cleanup and freeing:
 173	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
 174	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
 175	 */
 176	int extra_credits = 6;
 177	struct ext4_xattr_inode_array *ea_inode_array = NULL;
 178	bool freeze_protected = false;
 179
 180	trace_ext4_evict_inode(inode);
 181
 182	dax_break_layout_final(inode);
 183
 184	if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
 185		ext4_evict_ea_inode(inode);
 186	if (inode->i_nlink) {
 187		/*
 188		 * If there's dirty page will lead to data loss, user
 189		 * could see stale data.
 190		 */
 191		if (unlikely(!ext4_emergency_state(inode->i_sb) &&
 192		    mapping_tagged(&inode->i_data, PAGECACHE_TAG_DIRTY)))
 193			ext4_warning_inode(inode, "data will be lost");
 194
 195		truncate_inode_pages_final(&inode->i_data);
 196
 197		goto no_delete;
 198	}
 199
 200	if (is_bad_inode(inode))
 201		goto no_delete;
 202	dquot_initialize(inode);
 203
 204	if (ext4_should_order_data(inode))
 205		ext4_begin_ordered_truncate(inode, 0);
 206	truncate_inode_pages_final(&inode->i_data);
 207
 208	/*
 209	 * For inodes with journalled data, transaction commit could have
 210	 * dirtied the inode. And for inodes with dioread_nolock, unwritten
 211	 * extents converting worker could merge extents and also have dirtied
 212	 * the inode. Flush worker is ignoring it because of I_FREEING flag but
 213	 * we still need to remove the inode from the writeback lists.
 214	 */
 215	inode_io_list_del(inode);
 216
 217	/*
 218	 * Protect us against freezing - iput() caller didn't have to have any
 219	 * protection against it. When we are in a running transaction though,
 220	 * we are already protected against freezing and we cannot grab further
 221	 * protection due to lock ordering constraints.
 222	 */
 223	if (!ext4_journal_current_handle()) {
 224		sb_start_intwrite(inode->i_sb);
 225		freeze_protected = true;
 226	}
 227
 228	if (!IS_NOQUOTA(inode))
 229		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
 230
 231	/*
 232	 * Block bitmap, group descriptor, and inode are accounted in both
 233	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
 234	 */
 235	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
 236			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
 237	if (IS_ERR(handle)) {
 238		ext4_std_error(inode->i_sb, PTR_ERR(handle));
 239		/*
 240		 * If we're going to skip the normal cleanup, we still need to
 241		 * make sure that the in-core orphan linked list is properly
 242		 * cleaned up.
 243		 */
 244		ext4_orphan_del(NULL, inode);
 245		if (freeze_protected)
 246			sb_end_intwrite(inode->i_sb);
 247		goto no_delete;
 248	}
 249
 250	if (IS_SYNC(inode))
 251		ext4_handle_sync(handle);
 252
 253	/*
 254	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
 255	 * special handling of symlinks here because i_size is used to
 256	 * determine whether ext4_inode_info->i_data contains symlink data or
 257	 * block mappings. Setting i_size to 0 will remove its fast symlink
 258	 * status. Erase i_data so that it becomes a valid empty block map.
 259	 */
 260	if (ext4_inode_is_fast_symlink(inode))
 261		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
 262	inode->i_size = 0;
 263	err = ext4_mark_inode_dirty(handle, inode);
 264	if (err) {
 265		ext4_warning(inode->i_sb,
 266			     "couldn't mark inode dirty (err %d)", err);
 267		goto stop_handle;
 268	}
 269	if (inode->i_blocks) {
 270		err = ext4_truncate(inode);
 271		if (err) {
 272			ext4_error_err(inode->i_sb, -err,
 273				       "couldn't truncate inode %lu (err %d)",
 274				       inode->i_ino, err);
 275			goto stop_handle;
 276		}
 277	}
 278
 279	/* Remove xattr references. */
 280	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
 281				      extra_credits);
 282	if (err) {
 283		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
 284stop_handle:
 285		ext4_journal_stop(handle);
 286		ext4_orphan_del(NULL, inode);
 287		if (freeze_protected)
 288			sb_end_intwrite(inode->i_sb);
 289		ext4_xattr_inode_array_free(ea_inode_array);
 290		goto no_delete;
 291	}
 292
 293	/*
 294	 * Kill off the orphan record which ext4_truncate created.
 295	 * AKPM: I think this can be inside the above `if'.
 296	 * Note that ext4_orphan_del() has to be able to cope with the
 297	 * deletion of a non-existent orphan - this is because we don't
 298	 * know if ext4_truncate() actually created an orphan record.
 299	 * (Well, we could do this if we need to, but heck - it works)
 300	 */
 301	ext4_orphan_del(handle, inode);
 302	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
 303
 304	/*
 305	 * One subtle ordering requirement: if anything has gone wrong
 306	 * (transaction abort, IO errors, whatever), then we can still
 307	 * do these next steps (the fs will already have been marked as
 308	 * having errors), but we can't free the inode if the mark_dirty
 309	 * fails.
 310	 */
 311	if (ext4_mark_inode_dirty(handle, inode))
 312		/* If that failed, just do the required in-core inode clear. */
 313		ext4_clear_inode(inode);
 314	else
 315		ext4_free_inode(handle, inode);
 316	ext4_journal_stop(handle);
 317	if (freeze_protected)
 318		sb_end_intwrite(inode->i_sb);
 319	ext4_xattr_inode_array_free(ea_inode_array);
 320	return;
 321no_delete:
 322	/*
 323	 * Check out some where else accidentally dirty the evicting inode,
 324	 * which may probably cause inode use-after-free issues later.
 325	 */
 326	WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
 327
 328	if (!list_empty(&EXT4_I(inode)->i_fc_list))
 329		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
 330	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
 331}
 332
 333#ifdef CONFIG_QUOTA
 334qsize_t *ext4_get_reserved_space(struct inode *inode)
 335{
 336	return &EXT4_I(inode)->i_reserved_quota;
 337}
 338#endif
 339
 340/*
 341 * Called with i_data_sem down, which is important since we can call
 342 * ext4_discard_preallocations() from here.
 343 */
 344void ext4_da_update_reserve_space(struct inode *inode,
 345					int used, int quota_claim)
 346{
 347	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
 348	struct ext4_inode_info *ei = EXT4_I(inode);
 349
 350	spin_lock(&ei->i_block_reservation_lock);
 351	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
 352	if (unlikely(used > ei->i_reserved_data_blocks)) {
 353		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
 354			 "with only %d reserved data blocks",
 355			 __func__, inode->i_ino, used,
 356			 ei->i_reserved_data_blocks);
 357		WARN_ON(1);
 358		used = ei->i_reserved_data_blocks;
 359	}
 360
 361	/* Update per-inode reservations */
 362	ei->i_reserved_data_blocks -= used;
 363	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
 364
 365	spin_unlock(&ei->i_block_reservation_lock);
 366
 367	/* Update quota subsystem for data blocks */
 368	if (quota_claim)
 369		dquot_claim_block(inode, EXT4_C2B(sbi, used));
 370	else {
 371		/*
 372		 * We did fallocate with an offset that is already delayed
 373		 * allocated. So on delayed allocated writeback we should
 374		 * not re-claim the quota for fallocated blocks.
 375		 */
 376		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
 377	}
 378
 379	/*
 380	 * If we have done all the pending block allocations and if
 381	 * there aren't any writers on the inode, we can discard the
 382	 * inode's preallocations.
 383	 */
 384	if ((ei->i_reserved_data_blocks == 0) &&
 385	    !inode_is_open_for_write(inode))
 386		ext4_discard_preallocations(inode);
 387}
 388
 389static int __check_block_validity(struct inode *inode, const char *func,
 390				unsigned int line,
 391				struct ext4_map_blocks *map)
 392{
 393	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
 394
 395	if (journal && inode == journal->j_inode)
 396		return 0;
 397
 398	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
 399		ext4_error_inode(inode, func, line, map->m_pblk,
 400				 "lblock %lu mapped to illegal pblock %llu "
 401				 "(length %d)", (unsigned long) map->m_lblk,
 402				 map->m_pblk, map->m_len);
 403		return -EFSCORRUPTED;
 404	}
 405	return 0;
 406}
 407
 408int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
 409		       ext4_lblk_t len)
 410{
 411	int ret;
 412
 413	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
 414		return fscrypt_zeroout_range(inode, lblk, pblk, len);
 415
 416	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
 417	if (ret > 0)
 418		ret = 0;
 419
 420	return ret;
 421}
 422
 423/*
 424 * For generic regular files, when updating the extent tree, Ext4 should
 425 * hold the i_rwsem and invalidate_lock exclusively. This ensures
 426 * exclusion against concurrent page faults, as well as reads and writes.
 427 */
 428#ifdef CONFIG_EXT4_DEBUG
 429void ext4_check_map_extents_env(struct inode *inode)
 430{
 431	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
 432		return;
 433
 434	if (!S_ISREG(inode->i_mode) ||
 435	    IS_NOQUOTA(inode) || IS_VERITY(inode) ||
 436	    is_special_ino(inode->i_sb, inode->i_ino) ||
 437	    (inode_state_read_once(inode) & (I_FREEING | I_WILL_FREE | I_NEW)) ||
 438	    ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE) ||
 439	    ext4_verity_in_progress(inode))
 440		return;
 441
 442	WARN_ON_ONCE(!inode_is_locked(inode) &&
 443		     !rwsem_is_locked(&inode->i_mapping->invalidate_lock));
 444}
 445#else
 446void ext4_check_map_extents_env(struct inode *inode) {}
 447#endif
 448
 449#define check_block_validity(inode, map)	\
 450	__check_block_validity((inode), __func__, __LINE__, (map))
 451
 452#ifdef ES_AGGRESSIVE_TEST
 453static void ext4_map_blocks_es_recheck(handle_t *handle,
 454				       struct inode *inode,
 455				       struct ext4_map_blocks *es_map,
 456				       struct ext4_map_blocks *map,
 457				       int flags)
 458{
 459	int retval;
 460
 461	map->m_flags = 0;
 462	/*
 463	 * There is a race window that the result is not the same.
 464	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
 465	 * is that we lookup a block mapping in extent status tree with
 466	 * out taking i_data_sem.  So at the time the unwritten extent
 467	 * could be converted.
 468	 */
 469	down_read(&EXT4_I(inode)->i_data_sem);
 470	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
 471		retval = ext4_ext_map_blocks(handle, inode, map, 0);
 472	} else {
 473		retval = ext4_ind_map_blocks(handle, inode, map, 0);
 474	}
 475	up_read((&EXT4_I(inode)->i_data_sem));
 476
 477	/*
 478	 * We don't check m_len because extent will be collpased in status
 479	 * tree.  So the m_len might not equal.
 480	 */
 481	if (es_map->m_lblk != map->m_lblk ||
 482	    es_map->m_flags != map->m_flags ||
 483	    es_map->m_pblk != map->m_pblk) {
 484		printk("ES cache assertion failed for inode: %lu "
 485		       "es_cached ex [%d/%d/%llu/%x] != "
 486		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
 487		       inode->i_ino, es_map->m_lblk, es_map->m_len,
 488		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
 489		       map->m_len, map->m_pblk, map->m_flags,
 490		       retval, flags);
 491	}
 492}
 493#endif /* ES_AGGRESSIVE_TEST */
 494
 495static int ext4_map_query_blocks_next_in_leaf(handle_t *handle,
 496			struct inode *inode, struct ext4_map_blocks *map,
 497			unsigned int orig_mlen)
 498{
 499	struct ext4_map_blocks map2;
 500	unsigned int status, status2;
 501	int retval;
 502
 503	status = map->m_flags & EXT4_MAP_UNWRITTEN ?
 504		EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
 505
 506	WARN_ON_ONCE(!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF));
 507	WARN_ON_ONCE(orig_mlen <= map->m_len);
 508
 509	/* Prepare map2 for lookup in next leaf block */
 510	map2.m_lblk = map->m_lblk + map->m_len;
 511	map2.m_len = orig_mlen - map->m_len;
 512	map2.m_flags = 0;
 513	retval = ext4_ext_map_blocks(handle, inode, &map2, 0);
 514
 515	if (retval <= 0) {
 516		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
 517				      map->m_pblk, status, false);
 518		return map->m_len;
 519	}
 520
 521	if (unlikely(retval != map2.m_len)) {
 522		ext4_warning(inode->i_sb,
 523			     "ES len assertion failed for inode "
 524			     "%lu: retval %d != map->m_len %d",
 525			     inode->i_ino, retval, map2.m_len);
 526		WARN_ON(1);
 527	}
 528
 529	status2 = map2.m_flags & EXT4_MAP_UNWRITTEN ?
 530		EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
 531
 532	/*
 533	 * If map2 is contiguous with map, then let's insert it as a single
 534	 * extent in es cache and return the combined length of both the maps.
 535	 */
 536	if (map->m_pblk + map->m_len == map2.m_pblk &&
 537			status == status2) {
 538		ext4_es_insert_extent(inode, map->m_lblk,
 539				      map->m_len + map2.m_len, map->m_pblk,
 540				      status, false);
 541		map->m_len += map2.m_len;
 542	} else {
 543		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
 544				      map->m_pblk, status, false);
 545	}
 546
 547	return map->m_len;
 548}
 549
 550static int ext4_map_query_blocks(handle_t *handle, struct inode *inode,
 551				 struct ext4_map_blocks *map, int flags)
 552{
 553	unsigned int status;
 554	int retval;
 555	unsigned int orig_mlen = map->m_len;
 556
 557	flags &= EXT4_EX_QUERY_FILTER;
 558	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
 559		retval = ext4_ext_map_blocks(handle, inode, map, flags);
 560	else
 561		retval = ext4_ind_map_blocks(handle, inode, map, flags);
 562	if (retval < 0)
 563		return retval;
 564
 565	/* A hole? */
 566	if (retval == 0)
 567		goto out;
 568
 569	if (unlikely(retval != map->m_len)) {
 570		ext4_warning(inode->i_sb,
 571			     "ES len assertion failed for inode "
 572			     "%lu: retval %d != map->m_len %d",
 573			     inode->i_ino, retval, map->m_len);
 574		WARN_ON(1);
 575	}
 576
 577	/*
 578	 * No need to query next in leaf:
 579	 * - if returned extent is not last in leaf or
 580	 * - if the last in leaf is the full requested range
 581	 */
 582	if (!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) ||
 583			map->m_len == orig_mlen) {
 584		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
 585				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
 586		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
 587				      map->m_pblk, status, false);
 588	} else {
 589		retval = ext4_map_query_blocks_next_in_leaf(handle, inode, map,
 590							    orig_mlen);
 591	}
 592out:
 593	map->m_seq = READ_ONCE(EXT4_I(inode)->i_es_seq);
 594	return retval;
 595}
 596
 597static int ext4_map_create_blocks(handle_t *handle, struct inode *inode,
 598				  struct ext4_map_blocks *map, int flags)
 599{
 600	struct extent_status es;
 601	unsigned int status;
 602	int err, retval = 0;
 603
 604	/*
 605	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE
 606	 * indicates that the blocks and quotas has already been
 607	 * checked when the data was copied into the page cache.
 608	 */
 609	if (map->m_flags & EXT4_MAP_DELAYED)
 610		flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
 611
 612	/*
 613	 * Here we clear m_flags because after allocating an new extent,
 614	 * it will be set again.
 615	 */
 616	map->m_flags &= ~EXT4_MAP_FLAGS;
 617
 618	/*
 619	 * We need to check for EXT4 here because migrate could have
 620	 * changed the inode type in between.
 621	 */
 622	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
 623		retval = ext4_ext_map_blocks(handle, inode, map, flags);
 624	} else {
 625		retval = ext4_ind_map_blocks(handle, inode, map, flags);
 626
 627		/*
 628		 * We allocated new blocks which will result in i_data's
 629		 * format changing. Force the migrate to fail by clearing
 630		 * migrate flags.
 631		 */
 632		if (retval > 0 && map->m_flags & EXT4_MAP_NEW)
 633			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
 634	}
 635	if (retval <= 0)
 636		return retval;
 637
 638	if (unlikely(retval != map->m_len)) {
 639		ext4_warning(inode->i_sb,
 640			     "ES len assertion failed for inode %lu: "
 641			     "retval %d != map->m_len %d",
 642			     inode->i_ino, retval, map->m_len);
 643		WARN_ON(1);
 644	}
 645
 646	/*
 647	 * We have to zeroout blocks before inserting them into extent
 648	 * status tree. Otherwise someone could look them up there and
 649	 * use them before they are really zeroed. We also have to
 650	 * unmap metadata before zeroing as otherwise writeback can
 651	 * overwrite zeros with stale data from block device.
 652	 */
 653	if (flags & EXT4_GET_BLOCKS_ZERO &&
 654	    map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) {
 655		err = ext4_issue_zeroout(inode, map->m_lblk, map->m_pblk,
 656					 map->m_len);
 657		if (err)
 658			return err;
 659	}
 660
 661	/*
 662	 * If the extent has been zeroed out, we don't need to update
 663	 * extent status tree.
 664	 */
 665	if (flags & EXT4_GET_BLOCKS_SPLIT_NOMERGE &&
 666	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es, &map->m_seq)) {
 667		if (ext4_es_is_written(&es))
 668			return retval;
 669	}
 670
 671	status = map->m_flags & EXT4_MAP_UNWRITTEN ?
 672			EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
 673	ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk,
 674			      status, flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE);
 675	map->m_seq = READ_ONCE(EXT4_I(inode)->i_es_seq);
 676
 677	return retval;
 678}
 679
 680/*
 681 * The ext4_map_blocks() function tries to look up the requested blocks,
 682 * and returns if the blocks are already mapped.
 683 *
 684 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
 685 * and store the allocated blocks in the result buffer head and mark it
 686 * mapped.
 687 *
 688 * If file type is extents based, it will call ext4_ext_map_blocks(),
 689 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
 690 * based files
 691 *
 692 * On success, it returns the number of blocks being mapped or allocated.
 693 * If flags doesn't contain EXT4_GET_BLOCKS_CREATE the blocks are
 694 * pre-allocated and unwritten, the resulting @map is marked as unwritten.
 695 * If the flags contain EXT4_GET_BLOCKS_CREATE, it will mark @map as mapped.
 696 *
 697 * It returns 0 if plain look up failed (blocks have not been allocated), in
 698 * that case, @map is returned as unmapped but we still do fill map->m_len to
 699 * indicate the length of a hole starting at map->m_lblk.
 700 *
 701 * It returns the error in case of allocation failure.
 702 */
 703int ext4_map_blocks(handle_t *handle, struct inode *inode,
 704		    struct ext4_map_blocks *map, int flags)
 705{
 706	struct extent_status es;
 707	int retval;
 708	int ret = 0;
 709	unsigned int orig_mlen = map->m_len;
 710#ifdef ES_AGGRESSIVE_TEST
 711	struct ext4_map_blocks orig_map;
 712
 713	memcpy(&orig_map, map, sizeof(*map));
 714#endif
 715
 716	map->m_flags = 0;
 717	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
 718		  flags, map->m_len, (unsigned long) map->m_lblk);
 719
 720	/*
 721	 * ext4_map_blocks returns an int, and m_len is an unsigned int
 722	 */
 723	if (unlikely(map->m_len > INT_MAX))
 724		map->m_len = INT_MAX;
 725
 726	/* We can handle the block number less than EXT_MAX_BLOCKS */
 727	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
 728		return -EFSCORRUPTED;
 729
 730	/*
 731	 * Callers from the context of data submission are the only exceptions
 732	 * for regular files that do not hold the i_rwsem or invalidate_lock.
 733	 * However, caching unrelated ranges is not permitted.
 734	 */
 735	if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
 736		WARN_ON_ONCE(!(flags & EXT4_EX_NOCACHE));
 737	else
 738		ext4_check_map_extents_env(inode);
 739
 740	/* Lookup extent status tree firstly */
 741	if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es, &map->m_seq)) {
 742		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
 743			map->m_pblk = ext4_es_pblock(&es) +
 744					map->m_lblk - es.es_lblk;
 745			map->m_flags |= ext4_es_is_written(&es) ?
 746					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
 747			retval = es.es_len - (map->m_lblk - es.es_lblk);
 748			if (retval > map->m_len)
 749				retval = map->m_len;
 750			map->m_len = retval;
 751		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
 752			map->m_pblk = 0;
 753			map->m_flags |= ext4_es_is_delayed(&es) ?
 754					EXT4_MAP_DELAYED : 0;
 755			retval = es.es_len - (map->m_lblk - es.es_lblk);
 756			if (retval > map->m_len)
 757				retval = map->m_len;
 758			map->m_len = retval;
 759			retval = 0;
 760		} else {
 761			BUG();
 762		}
 763
 764		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
 765			return retval;
 766#ifdef ES_AGGRESSIVE_TEST
 767		ext4_map_blocks_es_recheck(handle, inode, map,
 768					   &orig_map, flags);
 769#endif
 770		if (!(flags & EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF) ||
 771				orig_mlen == map->m_len)
 772			goto found;
 773
 774		map->m_len = orig_mlen;
 775	}
 776	/*
 777	 * In the query cache no-wait mode, nothing we can do more if we
 778	 * cannot find extent in the cache.
 779	 */
 780	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
 781		return 0;
 782
 783	/*
 784	 * Try to see if we can get the block without requesting a new
 785	 * file system block.
 786	 */
 787	down_read(&EXT4_I(inode)->i_data_sem);
 788	retval = ext4_map_query_blocks(handle, inode, map, flags);
 789	up_read((&EXT4_I(inode)->i_data_sem));
 790
 791found:
 792	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
 793		ret = check_block_validity(inode, map);
 794		if (ret != 0)
 795			return ret;
 796	}
 797
 798	/* If it is only a block(s) look up */
 799	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
 800		return retval;
 801
 802	/*
 803	 * Returns if the blocks have already allocated
 804	 *
 805	 * Note that if blocks have been preallocated
 806	 * ext4_ext_map_blocks() returns with buffer head unmapped
 807	 */
 808	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
 809		/*
 810		 * If we need to convert extent to unwritten
 811		 * we continue and do the actual work in
 812		 * ext4_ext_map_blocks()
 813		 */
 814		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
 815			return retval;
 816
 817
 818	ext4_fc_track_inode(handle, inode);
 819	/*
 820	 * New blocks allocate and/or writing to unwritten extent
 821	 * will possibly result in updating i_data, so we take
 822	 * the write lock of i_data_sem, and call get_block()
 823	 * with create == 1 flag.
 824	 */
 825	down_write(&EXT4_I(inode)->i_data_sem);
 826	retval = ext4_map_create_blocks(handle, inode, map, flags);
 827	up_write((&EXT4_I(inode)->i_data_sem));
 828
 829	if (retval < 0)
 830		ext_debug(inode, "failed with err %d\n", retval);
 831	if (retval <= 0)
 832		return retval;
 833
 834	if (map->m_flags & EXT4_MAP_MAPPED) {
 835		ret = check_block_validity(inode, map);
 836		if (ret != 0)
 837			return ret;
 838
 839		/*
 840		 * Inodes with freshly allocated blocks where contents will be
 841		 * visible after transaction commit must be on transaction's
 842		 * ordered data list.
 843		 */
 844		if (map->m_flags & EXT4_MAP_NEW &&
 845		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
 846		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
 847		    !ext4_is_quota_file(inode) &&
 848		    ext4_should_order_data(inode)) {
 849			loff_t start_byte = EXT4_LBLK_TO_B(inode, map->m_lblk);
 850			loff_t length = EXT4_LBLK_TO_B(inode, map->m_len);
 851
 852			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
 853				ret = ext4_jbd2_inode_add_wait(handle, inode,
 854						start_byte, length);
 855			else
 856				ret = ext4_jbd2_inode_add_write(handle, inode,
 857						start_byte, length);
 858			if (ret)
 859				return ret;
 860		}
 861	}
 862	ext4_fc_track_range(handle, inode, map->m_lblk, map->m_lblk +
 863			    map->m_len - 1);
 864	return retval;
 865}
 866
 867/*
 868 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
 869 * we have to be careful as someone else may be manipulating b_state as well.
 870 */
 871static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
 872{
 873	unsigned long old_state;
 874	unsigned long new_state;
 875
 876	flags &= EXT4_MAP_FLAGS;
 877
 878	/* Dummy buffer_head? Set non-atomically. */
 879	if (!bh->b_folio) {
 880		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
 881		return;
 882	}
 883	/*
 884	 * Someone else may be modifying b_state. Be careful! This is ugly but
 885	 * once we get rid of using bh as a container for mapping information
 886	 * to pass to / from get_block functions, this can go away.
 887	 */
 888	old_state = READ_ONCE(bh->b_state);
 889	do {
 890		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
 891	} while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
 892}
 893
 894/*
 895 * Make sure that the current journal transaction has enough credits to map
 896 * one extent. Return -EAGAIN if it cannot extend the current running
 897 * transaction.
 898 */
 899static inline int ext4_journal_ensure_extent_credits(handle_t *handle,
 900						     struct inode *inode)
 901{
 902	int credits;
 903	int ret;
 904
 905	/* Called from ext4_da_write_begin() which has no handle started? */
 906	if (!handle)
 907		return 0;
 908
 909	credits = ext4_chunk_trans_blocks(inode, 1);
 910	ret = __ext4_journal_ensure_credits(handle, credits, credits, 0);
 911	return ret <= 0 ? ret : -EAGAIN;
 912}
 913
 914static int _ext4_get_block(struct inode *inode, sector_t iblock,
 915			   struct buffer_head *bh, int flags)
 916{
 917	struct ext4_map_blocks map;
 918	int ret = 0;
 919
 920	if (ext4_has_inline_data(inode))
 921		return -ERANGE;
 922
 923	map.m_lblk = iblock;
 924	map.m_len = bh->b_size >> inode->i_blkbits;
 925
 926	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
 927			      flags);
 928	if (ret > 0) {
 929		map_bh(bh, inode->i_sb, map.m_pblk);
 930		ext4_update_bh_state(bh, map.m_flags);
 931		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
 932		ret = 0;
 933	} else if (ret == 0) {
 934		/* hole case, need to fill in bh->b_size */
 935		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
 936	}
 937	return ret;
 938}
 939
 940int ext4_get_block(struct inode *inode, sector_t iblock,
 941		   struct buffer_head *bh, int create)
 942{
 943	return _ext4_get_block(inode, iblock, bh,
 944			       create ? EXT4_GET_BLOCKS_CREATE : 0);
 945}
 946
 947/*
 948 * Get block function used when preparing for buffered write if we require
 949 * creating an unwritten extent if blocks haven't been allocated.  The extent
 950 * will be converted to written after the IO is complete.
 951 */
 952int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
 953			     struct buffer_head *bh_result, int create)
 954{
 955	int ret = 0;
 956
 957	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
 958		   inode->i_ino, create);
 959	ret = _ext4_get_block(inode, iblock, bh_result,
 960			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
 961
 962	/*
 963	 * If the buffer is marked unwritten, mark it as new to make sure it is
 964	 * zeroed out correctly in case of partial writes. Otherwise, there is
 965	 * a chance of stale data getting exposed.
 966	 */
 967	if (ret == 0 && buffer_unwritten(bh_result))
 968		set_buffer_new(bh_result);
 969
 970	return ret;
 971}
 972
 973/* Maximum number of blocks we map for direct IO at once. */
 974#define DIO_MAX_BLOCKS 4096
 975
 976/*
 977 * `handle' can be NULL if create is zero
 978 */
 979struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
 980				ext4_lblk_t block, int map_flags)
 981{
 982	struct ext4_map_blocks map;
 983	struct buffer_head *bh;
 984	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
 985	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
 986	int err;
 987
 988	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
 989		    || handle != NULL || create == 0);
 990	ASSERT(create == 0 || !nowait);
 991
 992	map.m_lblk = block;
 993	map.m_len = 1;
 994	err = ext4_map_blocks(handle, inode, &map, map_flags);
 995
 996	if (err == 0)
 997		return create ? ERR_PTR(-ENOSPC) : NULL;
 998	if (err < 0)
 999		return ERR_PTR(err);
1000
1001	if (nowait)
1002		return sb_find_get_block(inode->i_sb, map.m_pblk);
1003
1004	/*
1005	 * Since bh could introduce extra ref count such as referred by
1006	 * journal_head etc. Try to avoid using __GFP_MOVABLE here
1007	 * as it may fail the migration when journal_head remains.
1008	 */
1009	bh = getblk_unmovable(inode->i_sb->s_bdev, map.m_pblk,
1010				inode->i_sb->s_blocksize);
1011
1012	if (unlikely(!bh))
1013		return ERR_PTR(-ENOMEM);
1014	if (map.m_flags & EXT4_MAP_NEW) {
1015		ASSERT(create != 0);
1016		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
1017			    || (handle != NULL));
1018
1019		/*
1020		 * Now that we do not always journal data, we should
1021		 * keep in mind whether this should always journal the
1022		 * new buffer as metadata.  For now, regular file
1023		 * writes use ext4_get_block instead, so it's not a
1024		 * problem.
1025		 */
1026		lock_buffer(bh);
1027		BUFFER_TRACE(bh, "call get_create_access");
1028		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
1029						     EXT4_JTR_NONE);
1030		if (unlikely(err)) {
1031			unlock_buffer(bh);
1032			goto errout;
1033		}
1034		if (!buffer_uptodate(bh)) {
1035			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1036			set_buffer_uptodate(bh);
1037		}
1038		unlock_buffer(bh);
1039		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1040		err = ext4_handle_dirty_metadata(handle, inode, bh);
1041		if (unlikely(err))
1042			goto errout;
1043	} else
1044		BUFFER_TRACE(bh, "not a new buffer");
1045	return bh;
1046errout:
1047	brelse(bh);
1048	return ERR_PTR(err);
1049}
1050
1051struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1052			       ext4_lblk_t block, int map_flags)
1053{
1054	struct buffer_head *bh;
1055	int ret;
1056
1057	bh = ext4_getblk(handle, inode, block, map_flags);
1058	if (IS_ERR(bh))
1059		return bh;
1060	if (!bh || ext4_buffer_uptodate(bh))
1061		return bh;
1062
1063	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
1064	if (ret) {
1065		put_bh(bh);
1066		return ERR_PTR(ret);
1067	}
1068	return bh;
1069}
1070
1071/* Read a contiguous batch of blocks. */
1072int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
1073		     bool wait, struct buffer_head **bhs)
1074{
1075	int i, err;
1076
1077	for (i = 0; i < bh_count; i++) {
1078		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
1079		if (IS_ERR(bhs[i])) {
1080			err = PTR_ERR(bhs[i]);
1081			bh_count = i;
1082			goto out_brelse;
1083		}
1084	}
1085
1086	for (i = 0; i < bh_count; i++)
1087		/* Note that NULL bhs[i] is valid because of holes. */
1088		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
1089			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
1090
1091	if (!wait)
1092		return 0;
1093
1094	for (i = 0; i < bh_count; i++)
1095		if (bhs[i])
1096			wait_on_buffer(bhs[i]);
1097
1098	for (i = 0; i < bh_count; i++) {
1099		if (bhs[i] && !buffer_uptodate(bhs[i])) {
1100			err = -EIO;
1101			goto out_brelse;
1102		}
1103	}
1104	return 0;
1105
1106out_brelse:
1107	for (i = 0; i < bh_count; i++) {
1108		brelse(bhs[i]);
1109		bhs[i] = NULL;
1110	}
1111	return err;
1112}
1113
1114int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
1115			   struct buffer_head *head,
1116			   unsigned from,
1117			   unsigned to,
1118			   int *partial,
1119			   int (*fn)(handle_t *handle, struct inode *inode,
1120				     struct buffer_head *bh))
1121{
1122	struct buffer_head *bh;
1123	unsigned block_start, block_end;
1124	unsigned blocksize = head->b_size;
1125	int err, ret = 0;
1126	struct buffer_head *next;
1127
1128	for (bh = head, block_start = 0;
1129	     ret == 0 && (bh != head || !block_start);
1130	     block_start = block_end, bh = next) {
1131		next = bh->b_this_page;
1132		block_end = block_start + blocksize;
1133		if (block_end <= from || block_start >= to) {
1134			if (partial && !buffer_uptodate(bh))
1135				*partial = 1;
1136			continue;
1137		}
1138		err = (*fn)(handle, inode, bh);
1139		if (!ret)
1140			ret = err;
1141	}
1142	return ret;
1143}
1144
1145/*
1146 * Helper for handling dirtying of journalled data. We also mark the folio as
1147 * dirty so that writeback code knows about this page (and inode) contains
1148 * dirty data. ext4_writepages() then commits appropriate transaction to
1149 * make data stable.
1150 */
1151static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
1152{
1153	struct folio *folio = bh->b_folio;
1154	struct inode *inode = folio->mapping->host;
1155
1156	/* only regular files have a_ops */
1157	if (S_ISREG(inode->i_mode))
1158		folio_mark_dirty(folio);
1159	return ext4_handle_dirty_metadata(handle, NULL, bh);
1160}
1161
1162int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1163				struct buffer_head *bh)
1164{
1165	if (!buffer_mapped(bh) || buffer_freed(bh))
1166		return 0;
1167	BUFFER_TRACE(bh, "get write access");
1168	return ext4_journal_get_write_access(handle, inode->i_sb, bh,
1169					    EXT4_JTR_NONE);
1170}
1171
1172int ext4_block_write_begin(handle_t *handle, struct folio *folio,
1173			   loff_t pos, unsigned len,
1174			   get_block_t *get_block)
1175{
1176	unsigned int from = offset_in_folio(folio, pos);
1177	unsigned to = from + len;
1178	struct inode *inode = folio->mapping->host;
1179	unsigned block_start, block_end;
1180	sector_t block;
1181	int err = 0;
1182	unsigned int blocksize = i_blocksize(inode);
1183	struct buffer_head *bh, *head, *wait[2];
1184	int nr_wait = 0;
1185	int i;
1186	bool should_journal_data = ext4_should_journal_data(inode);
1187
1188	BUG_ON(!folio_test_locked(folio));
1189	BUG_ON(to > folio_size(folio));
1190	BUG_ON(from > to);
1191	WARN_ON_ONCE(blocksize > folio_size(folio));
1192
1193	head = folio_buffers(folio);
1194	if (!head)
1195		head = create_empty_buffers(folio, blocksize, 0);
1196	block = EXT4_PG_TO_LBLK(inode, folio->index);
1197
1198	for (bh = head, block_start = 0; bh != head || !block_start;
1199	    block++, block_start = block_end, bh = bh->b_this_page) {
1200		block_end = block_start + blocksize;
1201		if (block_end <= from || block_start >= to) {
1202			if (folio_test_uptodate(folio)) {
1203				set_buffer_uptodate(bh);
1204			}
1205			continue;
1206		}
1207		if (WARN_ON_ONCE(buffer_new(bh)))
1208			clear_buffer_new(bh);
1209		if (!buffer_mapped(bh)) {
1210			WARN_ON(bh->b_size != blocksize);
1211			err = ext4_journal_ensure_extent_credits(handle, inode);
1212			if (!err)
1213				err = get_block(inode, block, bh, 1);
1214			if (err)
1215				break;
1216			if (buffer_new(bh)) {
1217				/*
1218				 * We may be zeroing partial buffers or all new
1219				 * buffers in case of failure. Prepare JBD2 for
1220				 * that.
1221				 */
1222				if (should_journal_data)
1223					do_journal_get_write_access(handle,
1224								    inode, bh);
1225				if (folio_test_uptodate(folio)) {
1226					/*
1227					 * Unlike __block_write_begin() we leave
1228					 * dirtying of new uptodate buffers to
1229					 * ->write_end() time or
1230					 * folio_zero_new_buffers().
1231					 */
1232					set_buffer_uptodate(bh);
1233					continue;
1234				}
1235				if (block_end > to || block_start < from)
1236					folio_zero_segments(folio, to,
1237							    block_end,
1238							    block_start, from);
1239				continue;
1240			}
1241		}
1242		if (folio_test_uptodate(folio)) {
1243			set_buffer_uptodate(bh);
1244			continue;
1245		}
1246		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1247		    !buffer_unwritten(bh) &&
1248		    (block_start < from || block_end > to)) {
1249			ext4_read_bh_lock(bh, 0, false);
1250			wait[nr_wait++] = bh;
1251		}
1252	}
1253	/*
1254	 * If we issued read requests, let them complete.
1255	 */
1256	for (i = 0; i < nr_wait; i++) {
1257		wait_on_buffer(wait[i]);
1258		if (!buffer_uptodate(wait[i]))
1259			err = -EIO;
1260	}
1261	if (unlikely(err)) {
1262		if (should_journal_data)
1263			ext4_journalled_zero_new_buffers(handle, inode, folio,
1264							 from, to);
1265		else
1266			folio_zero_new_buffers(folio, from, to);
1267	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1268		for (i = 0; i < nr_wait; i++) {
1269			int err2;
1270
1271			err2 = fscrypt_decrypt_pagecache_blocks(folio,
1272						blocksize, bh_offset(wait[i]));
1273			if (err2) {
1274				clear_buffer_uptodate(wait[i]);
1275				err = err2;
1276			}
1277		}
1278	}
1279
1280	return err;
1281}
1282
1283/*
1284 * To preserve ordering, it is essential that the hole instantiation and
1285 * the data write be encapsulated in a single transaction.  We cannot
1286 * close off a transaction and start a new one between the ext4_get_block()
1287 * and the ext4_write_end().  So doing the jbd2_journal_start at the start of
1288 * ext4_write_begin() is the right place.
1289 */
1290static int ext4_write_begin(const struct kiocb *iocb,
1291			    struct address_space *mapping,
1292			    loff_t pos, unsigned len,
1293			    struct folio **foliop, void **fsdata)
1294{
1295	struct inode *inode = mapping->host;
1296	int ret, needed_blocks;
1297	handle_t *handle;
1298	int retries = 0;
1299	struct folio *folio;
1300	pgoff_t index;
1301	unsigned from, to;
1302
1303	ret = ext4_emergency_state(inode->i_sb);
1304	if (unlikely(ret))
1305		return ret;
1306
1307	trace_ext4_write_begin(inode, pos, len);
1308	/*
1309	 * Reserve one block more for addition to orphan list in case
1310	 * we allocate blocks but write fails for some reason
1311	 */
1312	needed_blocks = ext4_chunk_trans_extent(inode,
1313			ext4_journal_blocks_per_folio(inode)) + 1;
1314	index = pos >> PAGE_SHIFT;
1315
1316	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1317		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1318						    foliop);
1319		if (ret < 0)
1320			return ret;
1321		if (ret == 1)
1322			return 0;
1323	}
1324
1325	/*
1326	 * write_begin_get_folio() can take a long time if the
1327	 * system is thrashing due to memory pressure, or if the folio
1328	 * is being written back.  So grab it first before we start
1329	 * the transaction handle.  This also allows us to allocate
1330	 * the folio (if needed) without using GFP_NOFS.
1331	 */
1332retry_grab:
1333	folio = write_begin_get_folio(iocb, mapping, index, len);
1334	if (IS_ERR(folio))
1335		return PTR_ERR(folio);
1336
1337	if (len > folio_next_pos(folio) - pos)
1338		len = folio_next_pos(folio) - pos;
1339
1340	from = offset_in_folio(folio, pos);
1341	to = from + len;
1342
1343	/*
1344	 * The same as page allocation, we prealloc buffer heads before
1345	 * starting the handle.
1346	 */
1347	if (!folio_buffers(folio))
1348		create_empty_buffers(folio, inode->i_sb->s_blocksize, 0);
1349
1350	folio_unlock(folio);
1351
1352retry_journal:
1353	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1354	if (IS_ERR(handle)) {
1355		folio_put(folio);
1356		return PTR_ERR(handle);
1357	}
1358
1359	folio_lock(folio);
1360	if (folio->mapping != mapping) {
1361		/* The folio got truncated from under us */
1362		folio_unlock(folio);
1363		folio_put(folio);
1364		ext4_journal_stop(handle);
1365		goto retry_grab;
1366	}
1367	/* In case writeback began while the folio was unlocked */
1368	folio_wait_stable(folio);
1369
1370	if (ext4_should_dioread_nolock(inode))
1371		ret = ext4_block_write_begin(handle, folio, pos, len,
1372					     ext4_get_block_unwritten);
1373	else
1374		ret = ext4_block_write_begin(handle, folio, pos, len,
1375					     ext4_get_block);
1376	if (!ret && ext4_should_journal_data(inode)) {
1377		ret = ext4_walk_page_buffers(handle, inode,
1378					     folio_buffers(folio), from, to,
1379					     NULL, do_journal_get_write_access);
1380	}
1381
1382	if (ret) {
1383		bool extended = (pos + len > inode->i_size) &&
1384				!ext4_verity_in_progress(inode);
1385
1386		folio_unlock(folio);
1387		/*
1388		 * ext4_block_write_begin may have instantiated a few blocks
1389		 * outside i_size.  Trim these off again. Don't need
1390		 * i_size_read because we hold i_rwsem.
1391		 *
1392		 * Add inode to orphan list in case we crash before
1393		 * truncate finishes
1394		 */
1395		if (extended && ext4_can_truncate(inode))
1396			ext4_orphan_add(handle, inode);
1397
1398		ext4_journal_stop(handle);
1399		if (extended) {
1400			ext4_truncate_failed_write(inode);
1401			/*
1402			 * If truncate failed early the inode might
1403			 * still be on the orphan list; we need to
1404			 * make sure the inode is removed from the
1405			 * orphan list in that case.
1406			 */
1407			if (inode->i_nlink)
1408				ext4_orphan_del(NULL, inode);
1409		}
1410
1411		if (ret == -EAGAIN ||
1412		    (ret == -ENOSPC &&
1413		     ext4_should_retry_alloc(inode->i_sb, &retries)))
1414			goto retry_journal;
1415		folio_put(folio);
1416		return ret;
1417	}
1418	*foliop = folio;
1419	return ret;
1420}
1421
1422/* For write_end() in data=journal mode */
1423static int write_end_fn(handle_t *handle, struct inode *inode,
1424			struct buffer_head *bh)
1425{
1426	int ret;
1427	if (!buffer_mapped(bh) || buffer_freed(bh))
1428		return 0;
1429	set_buffer_uptodate(bh);
1430	ret = ext4_dirty_journalled_data(handle, bh);
1431	clear_buffer_meta(bh);
1432	clear_buffer_prio(bh);
1433	clear_buffer_new(bh);
1434	return ret;
1435}
1436
1437/*
1438 * We need to pick up the new inode size which generic_commit_write gave us
1439 * `iocb` can be NULL - eg, when called from page_symlink().
1440 *
1441 * ext4 never places buffers on inode->i_mapping->i_private_list.  metadata
1442 * buffers are managed internally.
1443 */
1444static int ext4_write_end(const struct kiocb *iocb,
1445			  struct address_space *mapping,
1446			  loff_t pos, unsigned len, unsigned copied,
1447			  struct folio *folio, void *fsdata)
1448{
1449	handle_t *handle = ext4_journal_current_handle();
1450	struct inode *inode = mapping->host;
1451	loff_t old_size = inode->i_size;
1452	int ret = 0, ret2;
1453	int i_size_changed = 0;
1454	bool verity = ext4_verity_in_progress(inode);
1455
1456	trace_ext4_write_end(inode, pos, len, copied);
1457
1458	if (ext4_has_inline_data(inode) &&
1459	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1460		return ext4_write_inline_data_end(inode, pos, len, copied,
1461						  folio);
1462
1463	copied = block_write_end(pos, len, copied, folio);
1464	/*
1465	 * it's important to update i_size while still holding folio lock:
1466	 * page writeout could otherwise come in and zero beyond i_size.
1467	 *
1468	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1469	 * blocks are being written past EOF, so skip the i_size update.
1470	 */
1471	if (!verity)
1472		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1473	folio_unlock(folio);
1474	folio_put(folio);
1475
1476	if (old_size < pos && !verity) {
1477		pagecache_isize_extended(inode, old_size, pos);
1478		ext4_zero_partial_blocks(handle, inode, old_size, pos - old_size);
1479	}
1480	/*
1481	 * Don't mark the inode dirty under folio lock. First, it unnecessarily
1482	 * makes the holding time of folio lock longer. Second, it forces lock
1483	 * ordering of folio lock and transaction start for journaling
1484	 * filesystems.
1485	 */
1486	if (i_size_changed)
1487		ret = ext4_mark_inode_dirty(handle, inode);
1488
1489	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1490		/* if we have allocated more blocks and copied
1491		 * less. We will have blocks allocated outside
1492		 * inode->i_size. So truncate them
1493		 */
1494		ext4_orphan_add(handle, inode);
1495
1496	ret2 = ext4_journal_stop(handle);
1497	if (!ret)
1498		ret = ret2;
1499
1500	if (pos + len > inode->i_size && !verity) {
1501		ext4_truncate_failed_write(inode);
1502		/*
1503		 * If truncate failed early the inode might still be
1504		 * on the orphan list; we need to make sure the inode
1505		 * is removed from the orphan list in that case.
1506		 */
1507		if (inode->i_nlink)
1508			ext4_orphan_del(NULL, inode);
1509	}
1510
1511	return ret ? ret : copied;
1512}
1513
1514/*
1515 * This is a private version of folio_zero_new_buffers() which doesn't
1516 * set the buffer to be dirty, since in data=journalled mode we need
1517 * to call ext4_dirty_journalled_data() instead.
1518 */
1519static void ext4_journalled_zero_new_buffers(handle_t *handle,
1520					    struct inode *inode,
1521					    struct folio *folio,
1522					    unsigned from, unsigned to)
1523{
1524	unsigned int block_start = 0, block_end;
1525	struct buffer_head *head, *bh;
1526
1527	bh = head = folio_buffers(folio);
1528	do {
1529		block_end = block_start + bh->b_size;
1530		if (buffer_new(bh)) {
1531			if (block_end > from && block_start < to) {
1532				if (!folio_test_uptodate(folio)) {
1533					unsigned start, size;
1534
1535					start = max(from, block_start);
1536					size = min(to, block_end) - start;
1537
1538					folio_zero_range(folio, start, size);
1539				}
1540				clear_buffer_new(bh);
1541				write_end_fn(handle, inode, bh);
1542			}
1543		}
1544		block_start = block_end;
1545		bh = bh->b_this_page;
1546	} while (bh != head);
1547}
1548
1549static int ext4_journalled_write_end(const struct kiocb *iocb,
1550				     struct address_space *mapping,
1551				     loff_t pos, unsigned len, unsigned copied,
1552				     struct folio *folio, void *fsdata)
1553{
1554	handle_t *handle = ext4_journal_current_handle();
1555	struct inode *inode = mapping->host;
1556	loff_t old_size = inode->i_size;
1557	int ret = 0, ret2;
1558	int partial = 0;
1559	unsigned from, to;
1560	int size_changed = 0;
1561	bool verity = ext4_verity_in_progress(inode);
1562
1563	trace_ext4_journalled_write_end(inode, pos, len, copied);
1564	from = pos & (PAGE_SIZE - 1);
1565	to = from + len;
1566
1567	BUG_ON(!ext4_handle_valid(handle));
1568
1569	if (ext4_has_inline_data(inode))
1570		return ext4_write_inline_data_end(inode, pos, len, copied,
1571						  folio);
1572
1573	if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
1574		copied = 0;
1575		ext4_journalled_zero_new_buffers(handle, inode, folio,
1576						 from, to);
1577	} else {
1578		if (unlikely(copied < len))
1579			ext4_journalled_zero_new_buffers(handle, inode, folio,
1580							 from + copied, to);
1581		ret = ext4_walk_page_buffers(handle, inode,
1582					     folio_buffers(folio),
1583					     from, from + copied, &partial,
1584					     write_end_fn);
1585		if (!partial)
1586			folio_mark_uptodate(folio);
1587	}
1588	if (!verity)
1589		size_changed = ext4_update_inode_size(inode, pos + copied);
1590	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1591	folio_unlock(folio);
1592	folio_put(folio);
1593
1594	if (old_size < pos && !verity) {
1595		pagecache_isize_extended(inode, old_size, pos);
1596		ext4_zero_partial_blocks(handle, inode, old_size, pos - old_size);
1597	}
1598
1599	if (size_changed) {
1600		ret2 = ext4_mark_inode_dirty(handle, inode);
1601		if (!ret)
1602			ret = ret2;
1603	}
1604
1605	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1606		/* if we have allocated more blocks and copied
1607		 * less. We will have blocks allocated outside
1608		 * inode->i_size. So truncate them
1609		 */
1610		ext4_orphan_add(handle, inode);
1611
1612	ret2 = ext4_journal_stop(handle);
1613	if (!ret)
1614		ret = ret2;
1615	if (pos + len > inode->i_size && !verity) {
1616		ext4_truncate_failed_write(inode);
1617		/*
1618		 * If truncate failed early the inode might still be
1619		 * on the orphan list; we need to make sure the inode
1620		 * is removed from the orphan list in that case.
1621		 */
1622		if (inode->i_nlink)
1623			ext4_orphan_del(NULL, inode);
1624	}
1625
1626	return ret ? ret : copied;
1627}
1628
1629/*
1630 * Reserve space for 'nr_resv' clusters
1631 */
1632static int ext4_da_reserve_space(struct inode *inode, int nr_resv)
1633{
1634	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1635	struct ext4_inode_info *ei = EXT4_I(inode);
1636	int ret;
1637
1638	/*
1639	 * We will charge metadata quota at writeout time; this saves
1640	 * us from metadata over-estimation, though we may go over by
1641	 * a small amount in the end.  Here we just reserve for data.
1642	 */
1643	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, nr_resv));
1644	if (ret)
1645		return ret;
1646
1647	spin_lock(&ei->i_block_reservation_lock);
1648	if (ext4_claim_free_clusters(sbi, nr_resv, 0)) {
1649		spin_unlock(&ei->i_block_reservation_lock);
1650		dquot_release_reservation_block(inode, EXT4_C2B(sbi, nr_resv));
1651		return -ENOSPC;
1652	}
1653	ei->i_reserved_data_blocks += nr_resv;
1654	trace_ext4_da_reserve_space(inode, nr_resv);
1655	spin_unlock(&ei->i_block_reservation_lock);
1656
1657	return 0;       /* success */
1658}
1659
1660void ext4_da_release_space(struct inode *inode, int to_free)
1661{
1662	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1663	struct ext4_inode_info *ei = EXT4_I(inode);
1664
1665	if (!to_free)
1666		return;		/* Nothing to release, exit */
1667
1668	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1669
1670	trace_ext4_da_release_space(inode, to_free);
1671	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1672		/*
1673		 * if there aren't enough reserved blocks, then the
1674		 * counter is messed up somewhere.  Since this
1675		 * function is called from invalidate page, it's
1676		 * harmless to return without any action.
1677		 */
1678		ext4_warning(inode->i_sb, "ext4_da_release_space: "
1679			 "ino %lu, to_free %d with only %d reserved "
1680			 "data blocks", inode->i_ino, to_free,
1681			 ei->i_reserved_data_blocks);
1682		WARN_ON(1);
1683		to_free = ei->i_reserved_data_blocks;
1684	}
1685	ei->i_reserved_data_blocks -= to_free;
1686
1687	/* update fs dirty data blocks counter */
1688	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1689
1690	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1691
1692	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1693}
1694
1695/*
1696 * Delayed allocation stuff
1697 */
1698
1699struct mpage_da_data {
1700	/* These are input fields for ext4_do_writepages() */
1701	struct inode *inode;
1702	struct writeback_control *wbc;
1703	unsigned int can_map:1;	/* Can writepages call map blocks? */
1704
1705	/* These are internal state of ext4_do_writepages() */
1706	loff_t start_pos;	/* The start pos to write */
1707	loff_t next_pos;	/* Current pos to examine */
1708	loff_t end_pos;		/* Last pos to examine */
1709
1710	/*
1711	 * Extent to map - this can be after start_pos because that can be
1712	 * fully mapped. We somewhat abuse m_flags to store whether the extent
1713	 * is delalloc or unwritten.
1714	 */
1715	struct ext4_map_blocks map;
1716	struct ext4_io_submit io_submit;	/* IO submission data */
1717	unsigned int do_map:1;
1718	unsigned int scanned_until_end:1;
1719	unsigned int journalled_more_data:1;
1720};
1721
1722static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1723				       bool invalidate)
1724{
1725	unsigned nr, i;
1726	pgoff_t index, end;
1727	struct folio_batch fbatch;
1728	struct inode *inode = mpd->inode;
1729	struct address_space *mapping = inode->i_mapping;
1730
1731	/* This is necessary when next_pos == 0. */
1732	if (mpd->start_pos >= mpd->next_pos)
1733		return;
1734
1735	mpd->scanned_until_end = 0;
1736	if (invalidate) {
1737		ext4_lblk_t start, last;
1738		start = EXT4_B_TO_LBLK(inode, mpd->start_pos);
1739		last = mpd->next_pos >> inode->i_blkbits;
1740
1741		/*
1742		 * avoid racing with extent status tree scans made by
1743		 * ext4_insert_delayed_block()
1744		 */
1745		down_write(&EXT4_I(inode)->i_data_sem);
1746		ext4_es_remove_extent(inode, start, last - start);
1747		up_write(&EXT4_I(inode)->i_data_sem);
1748	}
1749
1750	folio_batch_init(&fbatch);
1751	index = mpd->start_pos >> PAGE_SHIFT;
1752	end = mpd->next_pos >> PAGE_SHIFT;
1753	while (index < end) {
1754		nr = filemap_get_folios(mapping, &index, end - 1, &fbatch);
1755		if (nr == 0)
1756			break;
1757		for (i = 0; i < nr; i++) {
1758			struct folio *folio = fbatch.folios[i];
1759
1760			if (folio_pos(folio) < mpd->start_pos)
1761				continue;
1762			if (folio_next_index(folio) > end)
1763				continue;
1764			BUG_ON(!folio_test_locked(folio));
1765			BUG_ON(folio_test_writeback(folio));
1766			if (invalidate) {
1767				if (folio_mapped(folio))
1768					folio_clear_dirty_for_io(folio);
1769				block_invalidate_folio(folio, 0,
1770						folio_size(folio));
1771				folio_clear_uptodate(folio);
1772			}
1773			folio_unlock(folio);
1774		}
1775		folio_batch_release(&fbatch);
1776	}
1777}
1778
1779static void ext4_print_free_blocks(struct inode *inode)
1780{
1781	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1782	struct super_block *sb = inode->i_sb;
1783	struct ext4_inode_info *ei = EXT4_I(inode);
1784
1785	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1786	       EXT4_C2B(EXT4_SB(inode->i_sb),
1787			ext4_count_free_clusters(sb)));
1788	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1789	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1790	       (long long) EXT4_C2B(EXT4_SB(sb),
1791		percpu_counter_sum(&sbi->s_freeclusters_counter)));
1792	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1793	       (long long) EXT4_C2B(EXT4_SB(sb),
1794		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1795	ext4_msg(sb, KERN_CRIT, "Block reservation details");
1796	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1797		 ei->i_reserved_data_blocks);
1798	return;
1799}
1800
1801/*
1802 * Check whether the cluster containing lblk has been allocated or has
1803 * delalloc reservation.
1804 *
1805 * Returns 0 if the cluster doesn't have either, 1 if it has delalloc
1806 * reservation, 2 if it's already been allocated, negative error code on
1807 * failure.
1808 */
1809static int ext4_clu_alloc_state(struct inode *inode, ext4_lblk_t lblk)
1810{
1811	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1812	int ret;
1813
1814	/* Has delalloc reservation? */
1815	if (ext4_es_scan_clu(inode, &ext4_es_is_delayed, lblk))
1816		return 1;
1817
1818	/* Already been allocated? */
1819	if (ext4_es_scan_clu(inode, &ext4_es_is_mapped, lblk))
1820		return 2;
1821	ret = ext4_clu_mapped(inode, EXT4_B2C(sbi, lblk));
1822	if (ret < 0)
1823		return ret;
1824	if (ret > 0)
1825		return 2;
1826
1827	return 0;
1828}
1829
1830/*
1831 * ext4_insert_delayed_blocks - adds a multiple delayed blocks to the extents
1832 *                              status tree, incrementing the reserved
1833 *                              cluster/block count or making pending
1834 *                              reservations where needed
1835 *
1836 * @inode - file containing the newly added block
1837 * @lblk - start logical block to be added
1838 * @len - length of blocks to be added
1839 *
1840 * Returns 0 on success, negative error code on failure.
1841 */
1842static int ext4_insert_delayed_blocks(struct inode *inode, ext4_lblk_t lblk,
1843				      ext4_lblk_t len)
1844{
1845	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1846	int ret;
1847	bool lclu_allocated = false;
1848	bool end_allocated = false;
1849	ext4_lblk_t resv_clu;
1850	ext4_lblk_t end = lblk + len - 1;
1851
1852	/*
1853	 * If the cluster containing lblk or end is shared with a delayed,
1854	 * written, or unwritten extent in a bigalloc file system, it's
1855	 * already been accounted for and does not need to be reserved.
1856	 * A pending reservation must be made for the cluster if it's
1857	 * shared with a written or unwritten extent and doesn't already
1858	 * have one.  Written and unwritten extents can be purged from the
1859	 * extents status tree if the system is under memory pressure, so
1860	 * it's necessary to examine the extent tree if a search of the
1861	 * extents status tree doesn't get a match.
1862	 */
1863	if (sbi->s_cluster_ratio == 1) {
1864		ret = ext4_da_reserve_space(inode, len);
1865		if (ret != 0)   /* ENOSPC */
1866			return ret;
1867	} else {   /* bigalloc */
1868		resv_clu = EXT4_B2C(sbi, end) - EXT4_B2C(sbi, lblk) + 1;
1869
1870		ret = ext4_clu_alloc_state(inode, lblk);
1871		if (ret < 0)
1872			return ret;
1873		if (ret > 0) {
1874			resv_clu--;
1875			lclu_allocated = (ret == 2);
1876		}
1877
1878		if (EXT4_B2C(sbi, lblk) != EXT4_B2C(sbi, end)) {
1879			ret = ext4_clu_alloc_state(inode, end);
1880			if (ret < 0)
1881				return ret;
1882			if (ret > 0) {
1883				resv_clu--;
1884				end_allocated = (ret == 2);
1885			}
1886		}
1887
1888		if (resv_clu) {
1889			ret = ext4_da_reserve_space(inode, resv_clu);
1890			if (ret != 0)   /* ENOSPC */
1891				return ret;
1892		}
1893	}
1894
1895	ext4_es_insert_delayed_extent(inode, lblk, len, lclu_allocated,
1896				      end_allocated);
1897	return 0;
1898}
1899
1900/*
1901 * Looks up the requested blocks and sets the delalloc extent map.
1902 * First try to look up for the extent entry that contains the requested
1903 * blocks in the extent status tree without i_data_sem, then try to look
1904 * up for the ondisk extent mapping with i_data_sem in read mode,
1905 * finally hold i_data_sem in write mode, looks up again and add a
1906 * delalloc extent entry if it still couldn't find any extent. Pass out
1907 * the mapped extent through @map and return 0 on success.
1908 */
1909static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map)
1910{
1911	struct extent_status es;
1912	int retval;
1913#ifdef ES_AGGRESSIVE_TEST
1914	struct ext4_map_blocks orig_map;
1915
1916	memcpy(&orig_map, map, sizeof(*map));
1917#endif
1918
1919	map->m_flags = 0;
1920	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1921		  (unsigned long) map->m_lblk);
1922
1923	ext4_check_map_extents_env(inode);
1924
1925	/* Lookup extent status tree firstly */
1926	if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es, NULL)) {
1927		map->m_len = min_t(unsigned int, map->m_len,
1928				   es.es_len - (map->m_lblk - es.es_lblk));
1929
1930		if (ext4_es_is_hole(&es))
1931			goto add_delayed;
1932
1933found:
1934		/*
1935		 * Delayed extent could be allocated by fallocate.
1936		 * So we need to check it.
1937		 */
1938		if (ext4_es_is_delayed(&es)) {
1939			map->m_flags |= EXT4_MAP_DELAYED;
1940			return 0;
1941		}
1942
1943		map->m_pblk = ext4_es_pblock(&es) + map->m_lblk - es.es_lblk;
1944		if (ext4_es_is_written(&es))
1945			map->m_flags |= EXT4_MAP_MAPPED;
1946		else if (ext4_es_is_unwritten(&es))
1947			map->m_flags |= EXT4_MAP_UNWRITTEN;
1948		else
1949			BUG();
1950
1951#ifdef ES_AGGRESSIVE_TEST
1952		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1953#endif
1954		return 0;
1955	}
1956
1957	/*
1958	 * Try to see if we can get the block without requesting a new
1959	 * file system block.
1960	 */
1961	down_read(&EXT4_I(inode)->i_data_sem);
1962	if (ext4_has_inline_data(inode))
1963		retval = 0;
1964	else
1965		retval = ext4_map_query_blocks(NULL, inode, map, 0);
1966	up_read(&EXT4_I(inode)->i_data_sem);
1967	if (retval)
1968		return retval < 0 ? retval : 0;
1969
1970add_delayed:
1971	down_write(&EXT4_I(inode)->i_data_sem);
1972	/*
1973	 * Page fault path (ext4_page_mkwrite does not take i_rwsem)
1974	 * and fallocate path (no folio lock) can race. Make sure we
1975	 * lookup the extent status tree here again while i_data_sem
1976	 * is held in write mode, before inserting a new da entry in
1977	 * the extent status tree.
1978	 */
1979	if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es, NULL)) {
1980		map->m_len = min_t(unsigned int, map->m_len,
1981				   es.es_len - (map->m_lblk - es.es_lblk));
1982
1983		if (!ext4_es_is_hole(&es)) {
1984			up_write(&EXT4_I(inode)->i_data_sem);
1985			goto found;
1986		}
1987	} else if (!ext4_has_inline_data(inode)) {
1988		retval = ext4_map_query_blocks(NULL, inode, map, 0);
1989		if (retval) {
1990			up_write(&EXT4_I(inode)->i_data_sem);
1991			return retval < 0 ? retval : 0;
1992		}
1993	}
1994
1995	map->m_flags |= EXT4_MAP_DELAYED;
1996	retval = ext4_insert_delayed_blocks(inode, map->m_lblk, map->m_len);
1997	if (!retval)
1998		map->m_seq = READ_ONCE(EXT4_I(inode)->i_es_seq);
1999	up_write(&EXT4_I(inode)->i_data_sem);
2000
2001	return retval;
2002}
2003
2004/*
2005 * This is a special get_block_t callback which is used by
2006 * ext4_da_write_begin().  It will either return mapped block or
2007 * reserve space for a single block.
2008 *
2009 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2010 * We also have b_blocknr = -1 and b_bdev initialized properly
2011 *
2012 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2013 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2014 * initialized properly.
2015 */
2016int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2017			   struct buffer_head *bh, int create)
2018{
2019	struct ext4_map_blocks map;
2020	sector_t invalid_block = ~((sector_t) 0xffff);
2021	int ret = 0;
2022
2023	BUG_ON(create == 0);
2024	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
2025
2026	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2027		invalid_block = ~0;
2028
2029	map.m_lblk = iblock;
2030	map.m_len = 1;
2031
2032	/*
2033	 * first, we need to know whether the block is allocated already
2034	 * preallocated blocks are unmapped but should treated
2035	 * the same as allocated blocks.
2036	 */
2037	ret = ext4_da_map_blocks(inode, &map);
2038	if (ret < 0)
2039		return ret;
2040
2041	if (map.m_flags & EXT4_MAP_DELAYED) {
2042		map_bh(bh, inode->i_sb, invalid_block);
2043		set_buffer_new(bh);
2044		set_buffer_delay(bh);
2045		return 0;
2046	}
2047
2048	map_bh(bh, inode->i_sb, map.m_pblk);
2049	ext4_update_bh_state(bh, map.m_flags);
2050
2051	if (buffer_unwritten(bh)) {
2052		/* A delayed write to unwritten bh should be marked
2053		 * new and mapped.  Mapped ensures that we don't do
2054		 * get_block multiple times when we write to the same
2055		 * offset and new ensures that we do proper zero out
2056		 * for partial write.
2057		 */
2058		set_buffer_new(bh);
2059		set_buffer_mapped(bh);
2060	}
2061	return 0;
2062}
2063
2064static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
2065{
2066	mpd->start_pos += folio_size(folio);
2067	mpd->wbc->nr_to_write -= folio_nr_pages(folio);
2068	folio_unlock(folio);
2069}
2070
2071static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
2072{
2073	size_t len;
2074	loff_t size;
2075	int err;
2076
2077	WARN_ON_ONCE(folio_pos(folio) != mpd->start_pos);
2078	folio_clear_dirty_for_io(folio);
2079	/*
2080	 * We have to be very careful here!  Nothing protects writeback path
2081	 * against i_size changes and the page can be writeably mapped into
2082	 * page tables. So an application can be growing i_size and writing
2083	 * data through mmap while writeback runs. folio_clear_dirty_for_io()
2084	 * write-protects our page in page tables and the page cannot get
2085	 * written to again until we release folio lock. So only after
2086	 * folio_clear_dirty_for_io() we are safe to sample i_size for
2087	 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
2088	 * on the barrier provided by folio_test_clear_dirty() in
2089	 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
2090	 * after page tables are updated.
2091	 */
2092	size = i_size_read(mpd->inode);
2093	len = folio_size(folio);
2094	if (folio_pos(folio) + len > size &&
2095	    !ext4_verity_in_progress(mpd->inode))
2096		len = size & (len - 1);
2097	err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
2098
2099	return err;
2100}
2101
2102#define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2103
2104/*
2105 * mballoc gives us at most this number of blocks...
2106 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2107 * The rest of mballoc seems to handle chunks up to full group size.
2108 */
2109#define MAX_WRITEPAGES_EXTENT_LEN 2048
2110
2111/*
2112 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2113 *
2114 * @mpd - extent of blocks
2115 * @lblk - logical number of the block in the file
2116 * @bh - buffer head we want to add to the extent
2117 *
2118 * The function is used to collect contig. blocks in the same state. If the
2119 * buffer doesn't require mapping for writeback and we haven't started the
2120 * extent of buffers to map yet, the function returns 'true' immediately - the
2121 * caller can write the buffer right away. Otherwise the function returns true
2122 * if the block has been added to the extent, false if the block couldn't be
2123 * added.
2124 */
2125static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2126				   struct buffer_head *bh)
2127{
2128	struct ext4_map_blocks *map = &mpd->map;
2129
2130	/* Buffer that doesn't need mapping for writeback? */
2131	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2132	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2133		/* So far no extent to map => we write the buffer right away */
2134		if (map->m_len == 0)
2135			return true;
2136		return false;
2137	}
2138
2139	/* First block in the extent? */
2140	if (map->m_len == 0) {
2141		/* We cannot map unless handle is started... */
2142		if (!mpd->do_map)
2143			return false;
2144		map->m_lblk = lblk;
2145		map->m_len = 1;
2146		map->m_flags = bh->b_state & BH_FLAGS;
2147		return true;
2148	}
2149
2150	/* Don't go larger than mballoc is willing to allocate */
2151	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2152		return false;
2153
2154	/* Can we merge the block to our big extent? */
2155	if (lblk == map->m_lblk + map->m_len &&
2156	    (bh->b_state & BH_FLAGS) == map->m_flags) {
2157		map->m_len++;
2158		return true;
2159	}
2160	return false;
2161}
2162
2163/*
2164 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2165 *
2166 * @mpd - extent of blocks for mapping
2167 * @head - the first buffer in the page
2168 * @bh - buffer we should start processing from
2169 * @lblk - logical number of the block in the file corresponding to @bh
2170 *
2171 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2172 * the page for IO if all buffers in this page were mapped and there's no
2173 * accumulated extent of buffers to map or add buffers in the page to the
2174 * extent of buffers to map. The function returns 1 if the caller can continue
2175 * by processing the next page, 0 if it should stop adding buffers to the
2176 * extent to map because we cannot extend it anymore. It can also return value
2177 * < 0 in case of error during IO submission.
2178 */
2179static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2180				   struct buffer_head *head,
2181				   struct buffer_head *bh,
2182				   ext4_lblk_t lblk)
2183{
2184	struct inode *inode = mpd->inode;
2185	int err;
2186	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2187							>> inode->i_blkbits;
2188
2189	if (ext4_verity_in_progress(inode))
2190		blocks = EXT_MAX_BLOCKS;
2191
2192	do {
2193		BUG_ON(buffer_locked(bh));
2194
2195		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2196			/* Found extent to map? */
2197			if (mpd->map.m_len)
2198				return 0;
2199			/* Buffer needs mapping and handle is not started? */
2200			if (!mpd->do_map)
2201				return 0;
2202			/* Everything mapped so far and we hit EOF */
2203			break;
2204		}
2205	} while (lblk++, (bh = bh->b_this_page) != head);
2206	/* So far everything mapped? Submit the page for IO. */
2207	if (mpd->map.m_len == 0) {
2208		err = mpage_submit_folio(mpd, head->b_folio);
2209		if (err < 0)
2210			return err;
2211		mpage_folio_done(mpd, head->b_folio);
2212	}
2213	if (lblk >= blocks) {
2214		mpd->scanned_until_end = 1;
2215		return 0;
2216	}
2217	return 1;
2218}
2219
2220/*
2221 * mpage_process_folio - update folio buffers corresponding to changed extent
2222 *			 and may submit fully mapped page for IO
2223 * @mpd: description of extent to map, on return next extent to map
2224 * @folio: Contains these buffers.
2225 * @m_lblk: logical block mapping.
2226 * @m_pblk: corresponding physical mapping.
2227 * @map_bh: determines on return whether this page requires any further
2228 *		  mapping or not.
2229 *
2230 * Scan given folio buffers corresponding to changed extent and update buffer
2231 * state according to new extent state.
2232 * We map delalloc buffers to their physical location, clear unwritten bits.
2233 * If the given folio is not fully mapped, we update @mpd to the next extent in
2234 * the given folio that needs mapping & return @map_bh as true.
2235 */
2236static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
2237			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2238			      bool *map_bh)
2239{
2240	struct buffer_head *head, *bh;
2241	ext4_io_end_t *io_end = mpd->io_submit.io_end;
2242	ext4_lblk_t lblk = *m_lblk;
2243	ext4_fsblk_t pblock = *m_pblk;
2244	int err = 0;
2245	ssize_t io_end_size = 0;
2246	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2247
2248	bh = head = folio_buffers(folio);
2249	do {
2250		if (lblk < mpd->map.m_lblk)
2251			continue;
2252		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2253			/*
2254			 * Buffer after end of mapped extent.
2255			 * Find next buffer in the folio to map.
2256			 */
2257			mpd->map.m_len = 0;
2258			mpd->map.m_flags = 0;
2259			io_end_vec->size += io_end_size;
2260
2261			err = mpage_process_page_bufs(mpd, head, bh, lblk);
2262			if (err > 0)
2263				err = 0;
2264			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2265				io_end_vec = ext4_alloc_io_end_vec(io_end);
2266				if (IS_ERR(io_end_vec)) {
2267					err = PTR_ERR(io_end_vec);
2268					goto out;
2269				}
2270				io_end_vec->offset = EXT4_LBLK_TO_B(mpd->inode,
2271								mpd->map.m_lblk);
2272			}
2273			*map_bh = true;
2274			goto out;
2275		}
2276		if (buffer_delay(bh)) {
2277			clear_buffer_delay(bh);
2278			bh->b_blocknr = pblock++;
2279		}
2280		clear_buffer_unwritten(bh);
2281		io_end_size += i_blocksize(mpd->inode);
2282	} while (lblk++, (bh = bh->b_this_page) != head);
2283
2284	io_end_vec->size += io_end_size;
2285	*map_bh = false;
2286out:
2287	*m_lblk = lblk;
2288	*m_pblk = pblock;
2289	return err;
2290}
2291
2292/*
2293 * mpage_map_buffers - update buffers corresponding to changed extent and
2294 *		       submit fully mapped pages for IO
2295 *
2296 * @mpd - description of extent to map, on return next extent to map
2297 *
2298 * Scan buffers corresponding to changed extent (we expect corresponding pages
2299 * to be already locked) and update buffer state according to new extent state.
2300 * We map delalloc buffers to their physical location, clear unwritten bits,
2301 * and mark buffers as uninit when we perform writes to unwritten extents
2302 * and do extent conversion after IO is finished. If the last page is not fully
2303 * mapped, we update @map to the next extent in the last page that needs
2304 * mapping. Otherwise we submit the page for IO.
2305 */
2306static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2307{
2308	struct folio_batch fbatch;
2309	unsigned nr, i;
2310	struct inode *inode = mpd->inode;
2311	pgoff_t start, end;
2312	ext4_lblk_t lblk;
2313	ext4_fsblk_t pblock;
2314	int err;
2315	bool map_bh = false;
2316
2317	start = EXT4_LBLK_TO_PG(inode, mpd->map.m_lblk);
2318	end = EXT4_LBLK_TO_PG(inode, mpd->map.m_lblk + mpd->map.m_len - 1);
2319	pblock = mpd->map.m_pblk;
2320
2321	folio_batch_init(&fbatch);
2322	while (start <= end) {
2323		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
2324		if (nr == 0)
2325			break;
2326		for (i = 0; i < nr; i++) {
2327			struct folio *folio = fbatch.folios[i];
2328
2329			lblk = EXT4_PG_TO_LBLK(inode, folio->index);
2330			err = mpage_process_folio(mpd, folio, &lblk, &pblock,
2331						 &map_bh);
2332			/*
2333			 * If map_bh is true, means page may require further bh
2334			 * mapping, or maybe the page was submitted for IO.
2335			 * So we return to call further extent mapping.
2336			 */
2337			if (err < 0 || map_bh)
2338				goto out;
2339			/* Page fully mapped - let IO run! */
2340			err = mpage_submit_folio(mpd, folio);
2341			if (err < 0)
2342				goto out;
2343			mpage_folio_done(mpd, folio);
2344		}
2345		folio_batch_release(&fbatch);
2346	}
2347	/* Extent fully mapped and matches with page boundary. We are done. */
2348	mpd->map.m_len = 0;
2349	mpd->map.m_flags = 0;
2350	return 0;
2351out:
2352	folio_batch_release(&fbatch);
2353	return err;
2354}
2355
2356static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2357{
2358	struct inode *inode = mpd->inode;
2359	struct ext4_map_blocks *map = &mpd->map;
2360	int get_blocks_flags;
2361	int err, dioread_nolock;
2362
2363	/* Make sure transaction has enough credits for this extent */
2364	err = ext4_journal_ensure_extent_credits(handle, inode);
2365	if (err < 0)
2366		return err;
2367
2368	trace_ext4_da_write_pages_extent(inode, map);
2369	/*
2370	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2371	 * to convert an unwritten extent to be initialized (in the case
2372	 * where we have written into one or more preallocated blocks).  It is
2373	 * possible that we're going to need more metadata blocks than
2374	 * previously reserved. However we must not fail because we're in
2375	 * writeback and there is nothing we can do about it so it might result
2376	 * in data loss.  So use reserved blocks to allocate metadata if
2377	 * possible. In addition, do not cache any unrelated extents, as it
2378	 * only holds the folio lock but does not hold the i_rwsem or
2379	 * invalidate_lock, which could corrupt the extent status tree.
2380	 */
2381	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2382			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2383			   EXT4_GET_BLOCKS_IO_SUBMIT |
2384			   EXT4_EX_NOCACHE;
2385
2386	dioread_nolock = ext4_should_dioread_nolock(inode);
2387	if (dioread_nolock)
2388		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2389
2390	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2391	if (err < 0)
2392		return err;
2393	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2394		if (!mpd->io_submit.io_end->handle &&
2395		    ext4_handle_valid(handle)) {
2396			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2397			handle->h_rsv_handle = NULL;
2398		}
2399		ext4_set_io_unwritten_flag(mpd->io_submit.io_end);
2400	}
2401
2402	BUG_ON(map->m_len == 0);
2403	return 0;
2404}
2405
2406/*
2407 * This is used to submit mapped buffers in a single folio that is not fully
2408 * mapped for various reasons, such as insufficient space or journal credits.
2409 */
2410static int mpage_submit_partial_folio(struct mpage_da_data *mpd)
2411{
2412	struct inode *inode = mpd->inode;
2413	struct folio *folio;
2414	loff_t pos;
2415	int ret;
2416
2417	folio = filemap_get_folio(inode->i_mapping,
2418				  mpd->start_pos >> PAGE_SHIFT);
2419	if (IS_ERR(folio))
2420		return PTR_ERR(folio);
2421	/*
2422	 * The mapped position should be within the current processing folio
2423	 * but must not be the folio start position.
2424	 */
2425	pos = ((loff_t)mpd->map.m_lblk) << inode->i_blkbits;
2426	if (WARN_ON_ONCE((folio_pos(folio) == pos) ||
2427			 !folio_contains(folio, pos >> PAGE_SHIFT)))
2428		return -EINVAL;
2429
2430	ret = mpage_submit_folio(mpd, folio);
2431	if (ret)
2432		goto out;
2433	/*
2434	 * Update start_pos to prevent this folio from being released in
2435	 * mpage_release_unused_pages(), it will be reset to the aligned folio
2436	 * pos when this folio is written again in the next round. Additionally,
2437	 * do not update wbc->nr_to_write here, as it will be updated once the
2438	 * entire folio has finished processing.
2439	 */
2440	mpd->start_pos = pos;
2441out:
2442	folio_unlock(folio);
2443	folio_put(folio);
2444	return ret;
2445}
2446
2447/*
2448 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2449 *				 mpd->len and submit pages underlying it for IO
2450 *
2451 * @handle - handle for journal operations
2452 * @mpd - extent to map
2453 * @give_up_on_write - we set this to true iff there is a fatal error and there
2454 *                     is no hope of writing the data. The caller should discard
2455 *                     dirty pages to avoid infinite loops.
2456 *
2457 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2458 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2459 * them to initialized or split the described range from larger unwritten
2460 * extent. Note that we need not map all the described range since allocation
2461 * can return less blocks or the range is covered by more unwritten extents. We
2462 * cannot map more because we are limited by reserved transaction credits. On
2463 * the other hand we always make sure that the last touched page is fully
2464 * mapped so that it can be written out (and thus forward progress is
2465 * guaranteed). After mapping we submit all mapped pages for IO.
2466 */
2467static int mpage_map_and_submit_extent(handle_t *handle,
2468				       struct mpage_da_data *mpd,
2469				       bool *give_up_on_write)
2470{
2471	struct inode *inode = mpd->inode;
2472	struct ext4_map_blocks *map = &mpd->map;
2473	int err;
2474	loff_t disksize;
2475	int progress = 0;
2476	ext4_io_end_t *io_end = mpd->io_submit.io_end;
2477	struct ext4_io_end_vec *io_end_vec;
2478
2479	io_end_vec = ext4_alloc_io_end_vec(io_end);
2480	if (IS_ERR(io_end_vec))
2481		return PTR_ERR(io_end_vec);
2482	io_end_vec->offset = EXT4_LBLK_TO_B(inode, map->m_lblk);
2483	do {
2484		err = mpage_map_one_extent(handle, mpd);
2485		if (err < 0) {
2486			struct super_block *sb = inode->i_sb;
2487
2488			if (ext4_emergency_state(sb))
2489				goto invalidate_dirty_pages;
2490			/*
2491			 * Let the uper layers retry transient errors.
2492			 * In the case of ENOSPC, if ext4_count_free_blocks()
2493			 * is non-zero, a commit should free up blocks.
2494			 */
2495			if ((err == -ENOMEM) || (err == -EAGAIN) ||
2496			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2497				/*
2498				 * We may have already allocated extents for
2499				 * some bhs inside the folio, issue the
2500				 * corresponding data to prevent stale data.
2501				 */
2502				if (progress) {
2503					if (mpage_submit_partial_folio(mpd))
2504						goto invalidate_dirty_pages;
2505					goto update_disksize;
2506				}
2507				return err;
2508			}
2509			ext4_msg(sb, KERN_CRIT,
2510				 "Delayed block allocation failed for "
2511				 "inode %lu at logical offset %llu with"
2512				 " max blocks %u with error %d",
2513				 inode->i_ino,
2514				 (unsigned long long)map->m_lblk,
2515				 (unsigned)map->m_len, -err);
2516			ext4_msg(sb, KERN_CRIT,
2517				 "This should not happen!! Data will "
2518				 "be lost\n");
2519			if (err == -ENOSPC)
2520				ext4_print_free_blocks(inode);
2521		invalidate_dirty_pages:
2522			*give_up_on_write = true;
2523			return err;
2524		}
2525		progress = 1;
2526		/*
2527		 * Update buffer state, submit mapped pages, and get us new
2528		 * extent to map
2529		 */
2530		err = mpage_map_and_submit_buffers(mpd);
2531		if (err < 0)
2532			goto update_disksize;
2533	} while (map->m_len);
2534
2535update_disksize:
2536	/*
2537	 * Update on-disk size after IO is submitted.  Races with
2538	 * truncate are avoided by checking i_size under i_data_sem.
2539	 */
2540	disksize = mpd->start_pos;
2541	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2542		int err2;
2543		loff_t i_size;
2544
2545		down_write(&EXT4_I(inode)->i_data_sem);
2546		i_size = i_size_read(inode);
2547		if (disksize > i_size)
2548			disksize = i_size;
2549		if (disksize > EXT4_I(inode)->i_disksize)
2550			EXT4_I(inode)->i_disksize = disksize;
2551		up_write(&EXT4_I(inode)->i_data_sem);
2552		err2 = ext4_mark_inode_dirty(handle, inode);
2553		if (err2) {
2554			ext4_error_err(inode->i_sb, -err2,
2555				       "Failed to mark inode %lu dirty",
2556				       inode->i_ino);
2557		}
2558		if (!err)
2559			err = err2;
2560	}
2561	return err;
2562}
2563
2564static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
2565				     size_t len)
2566{
2567	struct buffer_head *page_bufs = folio_buffers(folio);
2568	struct inode *inode = folio->mapping->host;
2569	int ret, err;
2570
2571	ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2572				     NULL, do_journal_get_write_access);
2573	err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2574				     NULL, write_end_fn);
2575	if (ret == 0)
2576		ret = err;
2577	err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
2578	if (ret == 0)
2579		ret = err;
2580	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2581
2582	return ret;
2583}
2584
2585static int mpage_journal_page_buffers(handle_t *handle,
2586				      struct mpage_da_data *mpd,
2587				      struct folio *folio)
2588{
2589	struct inode *inode = mpd->inode;
2590	loff_t size = i_size_read(inode);
2591	size_t len = folio_size(folio);
2592
2593	folio_clear_checked(folio);
2594	mpd->wbc->nr_to_write -= folio_nr_pages(folio);
2595
2596	if (folio_pos(folio) + len > size &&
2597	    !ext4_verity_in_progress(inode))
2598		len = size & (len - 1);
2599
2600	return ext4_journal_folio_buffers(handle, folio, len);
2601}
2602
2603/*
2604 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2605 * 				 needing mapping, submit mapped pages
2606 *
2607 * @mpd - where to look for pages
2608 *
2609 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2610 * IO immediately. If we cannot map blocks, we submit just already mapped
2611 * buffers in the page for IO and keep page dirty. When we can map blocks and
2612 * we find a page which isn't mapped we start accumulating extent of buffers
2613 * underlying these pages that needs mapping (formed by either delayed or
2614 * unwritten buffers). We also lock the pages containing these buffers. The
2615 * extent found is returned in @mpd structure (starting at mpd->lblk with
2616 * length mpd->len blocks).
2617 *
2618 * Note that this function can attach bios to one io_end structure which are
2619 * neither logically nor physically contiguous. Although it may seem as an
2620 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2621 * case as we need to track IO to all buffers underlying a page in one io_end.
2622 */
2623static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2624{
2625	struct address_space *mapping = mpd->inode->i_mapping;
2626	struct folio_batch fbatch;
2627	unsigned int nr_folios;
2628	pgoff_t index = mpd->start_pos >> PAGE_SHIFT;
2629	pgoff_t end = mpd->end_pos >> PAGE_SHIFT;
2630	xa_mark_t tag;
2631	int i, err = 0;
2632	ext4_lblk_t lblk;
2633	struct buffer_head *head;
2634	handle_t *handle = NULL;
2635	int bpp = ext4_journal_blocks_per_folio(mpd->inode);
2636
2637	tag = wbc_to_tag(mpd->wbc);
2638
2639	mpd->map.m_len = 0;
2640	mpd->next_pos = mpd->start_pos;
2641	if (ext4_should_journal_data(mpd->inode)) {
2642		handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
2643					    bpp);
2644		if (IS_ERR(handle))
2645			return PTR_ERR(handle);
2646	}
2647	folio_batch_init(&fbatch);
2648	while (index <= end) {
2649		nr_folios = filemap_get_folios_tag(mapping, &index, end,
2650				tag, &fbatch);
2651		if (nr_folios == 0)
2652			break;
2653
2654		for (i = 0; i < nr_folios; i++) {
2655			struct folio *folio = fbatch.folios[i];
2656
2657			/*
2658			 * Accumulated enough dirty pages? This doesn't apply
2659			 * to WB_SYNC_ALL mode. For integrity sync we have to
2660			 * keep going because someone may be concurrently
2661			 * dirtying pages, and we might have synced a lot of
2662			 * newly appeared dirty pages, but have not synced all
2663			 * of the old dirty pages.
2664			 */
2665			if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2666			    mpd->wbc->nr_to_write <=
2667			    EXT4_LBLK_TO_PG(mpd->inode, mpd->map.m_len))
2668				goto out;
2669
2670			/* If we can't merge this page, we are done. */
2671			if (mpd->map.m_len > 0 &&
2672			    mpd->next_pos != folio_pos(folio))
2673				goto out;
2674
2675			if (handle) {
2676				err = ext4_journal_ensure_credits(handle, bpp,
2677								  0);
2678				if (err < 0)
2679					goto out;
2680			}
2681
2682			folio_lock(folio);
2683			/*
2684			 * If the page is no longer dirty, or its mapping no
2685			 * longer corresponds to inode we are writing (which
2686			 * means it has been truncated or invalidated), or the
2687			 * page is already under writeback and we are not doing
2688			 * a data integrity writeback, skip the page
2689			 */
2690			if (!folio_test_dirty(folio) ||
2691			    (folio_test_writeback(folio) &&
2692			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2693			    unlikely(folio->mapping != mapping)) {
2694				folio_unlock(folio);
2695				continue;
2696			}
2697
2698			folio_wait_writeback(folio);
2699			BUG_ON(folio_test_writeback(folio));
2700
2701			/*
2702			 * Should never happen but for buggy code in
2703			 * other subsystems that call
2704			 * set_page_dirty() without properly warning
2705			 * the file system first.  See [1] for more
2706			 * information.
2707			 *
2708			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2709			 */
2710			if (!folio_buffers(folio)) {
2711				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
2712				folio_clear_dirty(folio);
2713				folio_unlock(folio);
2714				continue;
2715			}
2716
2717			if (mpd->map.m_len == 0)
2718				mpd->start_pos = folio_pos(folio);
2719			mpd->next_pos = folio_next_pos(folio);
2720			/*
2721			 * Writeout when we cannot modify metadata is simple.
2722			 * Just submit the page. For data=journal mode we
2723			 * first handle writeout of the page for checkpoint and
2724			 * only after that handle delayed page dirtying. This
2725			 * makes sure current data is checkpointed to the final
2726			 * location before possibly journalling it again which
2727			 * is desirable when the page is frequently dirtied
2728			 * through a pin.
2729			 */
2730			if (!mpd->can_map) {
2731				err = mpage_submit_folio(mpd, folio);
2732				if (err < 0)
2733					goto out;
2734				/* Pending dirtying of journalled data? */
2735				if (folio_test_checked(folio)) {
2736					err = mpage_journal_page_buffers(handle,
2737						mpd, folio);
2738					if (err < 0)
2739						goto out;
2740					mpd->journalled_more_data = 1;
2741				}
2742				mpage_folio_done(mpd, folio);
2743			} else {
2744				/* Add all dirty buffers to mpd */
2745				lblk = EXT4_PG_TO_LBLK(mpd->inode, folio->index);
2746				head = folio_buffers(folio);
2747				err = mpage_process_page_bufs(mpd, head, head,
2748						lblk);
2749				if (err <= 0)
2750					goto out;
2751				err = 0;
2752			}
2753		}
2754		folio_batch_release(&fbatch);
2755		cond_resched();
2756	}
2757	mpd->scanned_until_end = 1;
2758	if (handle)
2759		ext4_journal_stop(handle);
2760	return 0;
2761out:
2762	folio_batch_release(&fbatch);
2763	if (handle)
2764		ext4_journal_stop(handle);
2765	return err;
2766}
2767
2768static int ext4_do_writepages(struct mpage_da_data *mpd)
2769{
2770	struct writeback_control *wbc = mpd->wbc;
2771	pgoff_t	writeback_index = 0;
2772	long nr_to_write = wbc->nr_to_write;
2773	int range_whole = 0;
2774	int cycled = 1;
2775	handle_t *handle = NULL;
2776	struct inode *inode = mpd->inode;
2777	struct address_space *mapping = inode->i_mapping;
2778	int needed_blocks, rsv_blocks = 0, ret = 0;
2779	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2780	struct blk_plug plug;
2781	bool give_up_on_write = false;
2782
2783	trace_ext4_writepages(inode, wbc);
2784
2785	/*
2786	 * No pages to write? This is mainly a kludge to avoid starting
2787	 * a transaction for special inodes like journal inode on last iput()
2788	 * because that could violate lock ordering on umount
2789	 */
2790	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2791		goto out_writepages;
2792
2793	/*
2794	 * If the filesystem has aborted, it is read-only, so return
2795	 * right away instead of dumping stack traces later on that
2796	 * will obscure the real source of the problem.  We test
2797	 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
2798	 * the latter could be true if the filesystem is mounted
2799	 * read-only, and in that case, ext4_writepages should
2800	 * *never* be called, so if that ever happens, we would want
2801	 * the stack trace.
2802	 */
2803	ret = ext4_emergency_state(mapping->host->i_sb);
2804	if (unlikely(ret))
2805		goto out_writepages;
2806
2807	/*
2808	 * If we have inline data and arrive here, it means that
2809	 * we will soon create the block for the 1st page, so
2810	 * we'd better clear the inline data here.
2811	 */
2812	if (ext4_has_inline_data(inode)) {
2813		/* Just inode will be modified... */
2814		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2815		if (IS_ERR(handle)) {
2816			ret = PTR_ERR(handle);
2817			goto out_writepages;
2818		}
2819		BUG_ON(ext4_test_inode_state(inode,
2820				EXT4_STATE_MAY_INLINE_DATA));
2821		ext4_destroy_inline_data(handle, inode);
2822		ext4_journal_stop(handle);
2823	}
2824
2825	/*
2826	 * data=journal mode does not do delalloc so we just need to writeout /
2827	 * journal already mapped buffers. On the other hand we need to commit
2828	 * transaction to make data stable. We expect all the data to be
2829	 * already in the journal (the only exception are DMA pinned pages
2830	 * dirtied behind our back) so we commit transaction here and run the
2831	 * writeback loop to checkpoint them. The checkpointing is not actually
2832	 * necessary to make data persistent *but* quite a few places (extent
2833	 * shifting operations, fsverity, ...) depend on being able to drop
2834	 * pagecache pages after calling filemap_write_and_wait() and for that
2835	 * checkpointing needs to happen.
2836	 */
2837	if (ext4_should_journal_data(inode)) {
2838		mpd->can_map = 0;
2839		if (wbc->sync_mode == WB_SYNC_ALL)
2840			ext4_fc_commit(sbi->s_journal,
2841				       EXT4_I(inode)->i_datasync_tid);
2842	}
2843	mpd->journalled_more_data = 0;
2844
2845	if (ext4_should_dioread_nolock(inode)) {
2846		int bpf = ext4_journal_blocks_per_folio(inode);
2847		/*
2848		 * We may need to convert up to one extent per block in
2849		 * the folio and we may dirty the inode.
2850		 */
2851		rsv_blocks = 1 + ext4_ext_index_trans_blocks(inode, bpf);
2852	}
2853
2854	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2855		range_whole = 1;
2856
2857	if (wbc->range_cyclic) {
2858		writeback_index = mapping->writeback_index;
2859		if (writeback_index)
2860			cycled = 0;
2861		mpd->start_pos = writeback_index << PAGE_SHIFT;
2862		mpd->end_pos = LLONG_MAX;
2863	} else {
2864		mpd->start_pos = wbc->range_start;
2865		mpd->end_pos = wbc->range_end;
2866	}
2867
2868	ext4_io_submit_init(&mpd->io_submit, wbc);
2869retry:
2870	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2871		tag_pages_for_writeback(mapping, mpd->start_pos >> PAGE_SHIFT,
2872					mpd->end_pos >> PAGE_SHIFT);
2873	blk_start_plug(&plug);
2874
2875	/*
2876	 * First writeback pages that don't need mapping - we can avoid
2877	 * starting a transaction unnecessarily and also avoid being blocked
2878	 * in the block layer on device congestion while having transaction
2879	 * started.
2880	 */
2881	mpd->do_map = 0;
2882	mpd->scanned_until_end = 0;
2883	mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2884	if (!mpd->io_submit.io_end) {
2885		ret = -ENOMEM;
2886		goto unplug;
2887	}
2888	ret = mpage_prepare_extent_to_map(mpd);
2889	/* Unlock pages we didn't use */
2890	mpage_release_unused_pages(mpd, false);
2891	/* Submit prepared bio */
2892	ext4_io_submit(&mpd->io_submit);
2893	ext4_put_io_end_defer(mpd->io_submit.io_end);
2894	mpd->io_submit.io_end = NULL;
2895	if (ret < 0)
2896		goto unplug;
2897
2898	while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
2899		/* For each extent of pages we use new io_end */
2900		mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2901		if (!mpd->io_submit.io_end) {
2902			ret = -ENOMEM;
2903			break;
2904		}
2905
2906		WARN_ON_ONCE(!mpd->can_map);
2907		/*
2908		 * We have two constraints: We find one extent to map and we
2909		 * must always write out whole page (makes a difference when
2910		 * blocksize < pagesize) so that we don't block on IO when we
2911		 * try to write out the rest of the page. Journalled mode is
2912		 * not supported by delalloc.
2913		 */
2914		BUG_ON(ext4_should_journal_data(inode));
2915		/*
2916		 * Calculate the number of credits needed to reserve for one
2917		 * extent of up to MAX_WRITEPAGES_EXTENT_LEN blocks. It will
2918		 * attempt to extend the transaction or start a new iteration
2919		 * if the reserved credits are insufficient.
2920		 */
2921		needed_blocks = ext4_chunk_trans_blocks(inode,
2922						MAX_WRITEPAGES_EXTENT_LEN);
2923		/* start a new transaction */
2924		handle = ext4_journal_start_with_reserve(inode,
2925				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2926		if (IS_ERR(handle)) {
2927			ret = PTR_ERR(handle);
2928			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2929			       "%ld pages, ino %lu; err %d", __func__,
2930				wbc->nr_to_write, inode->i_ino, ret);
2931			/* Release allocated io_end */
2932			ext4_put_io_end(mpd->io_submit.io_end);
2933			mpd->io_submit.io_end = NULL;
2934			break;
2935		}
2936		mpd->do_map = 1;
2937
2938		trace_ext4_da_write_folios_start(inode, mpd->start_pos,
2939				mpd->next_pos, wbc);
2940		ret = mpage_prepare_extent_to_map(mpd);
2941		if (!ret && mpd->map.m_len)
2942			ret = mpage_map_and_submit_extent(handle, mpd,
2943					&give_up_on_write);
2944		/*
2945		 * Caution: If the handle is synchronous,
2946		 * ext4_journal_stop() can wait for transaction commit
2947		 * to finish which may depend on writeback of pages to
2948		 * complete or on page lock to be released.  In that
2949		 * case, we have to wait until after we have
2950		 * submitted all the IO, released page locks we hold,
2951		 * and dropped io_end reference (for extent conversion
2952		 * to be able to complete) before stopping the handle.
2953		 */
2954		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2955			ext4_journal_stop(handle);
2956			handle = NULL;
2957			mpd->do_map = 0;
2958		}
2959		/* Unlock pages we didn't use */
2960		mpage_release_unused_pages(mpd, give_up_on_write);
2961		/* Submit prepared bio */
2962		ext4_io_submit(&mpd->io_submit);
2963
2964		/*
2965		 * Drop our io_end reference we got from init. We have
2966		 * to be careful and use deferred io_end finishing if
2967		 * we are still holding the transaction as we can
2968		 * release the last reference to io_end which may end
2969		 * up doing unwritten extent conversion.
2970		 */
2971		if (handle) {
2972			ext4_put_io_end_defer(mpd->io_submit.io_end);
2973			ext4_journal_stop(handle);
2974		} else
2975			ext4_put_io_end(mpd->io_submit.io_end);
2976		mpd->io_submit.io_end = NULL;
2977		trace_ext4_da_write_folios_end(inode, mpd->start_pos,
2978				mpd->next_pos, wbc, ret);
2979
2980		if (ret == -ENOSPC && sbi->s_journal) {
2981			/*
2982			 * Commit the transaction which would
2983			 * free blocks released in the transaction
2984			 * and try again
2985			 */
2986			jbd2_journal_force_commit_nested(sbi->s_journal);
2987			ret = 0;
2988			continue;
2989		}
2990		if (ret == -EAGAIN)
2991			ret = 0;
2992		/* Fatal error - ENOMEM, EIO... */
2993		if (ret)
2994			break;
2995	}
2996unplug:
2997	blk_finish_plug(&plug);
2998	if (!ret && !cycled && wbc->nr_to_write > 0) {
2999		cycled = 1;
3000		mpd->end_pos = (writeback_index << PAGE_SHIFT) - 1;
3001		mpd->start_pos = 0;
3002		goto retry;
3003	}
3004
3005	/* Update index */
3006	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3007		/*
3008		 * Set the writeback_index so that range_cyclic
3009		 * mode will write it back later
3010		 */
3011		mapping->writeback_index = mpd->start_pos >> PAGE_SHIFT;
3012
3013out_writepages:
3014	trace_ext4_writepages_result(inode, wbc, ret,
3015				     nr_to_write - wbc->nr_to_write);
3016	return ret;
3017}
3018
3019static int ext4_writepages(struct address_space *mapping,
3020			   struct writeback_control *wbc)
3021{
3022	struct super_block *sb = mapping->host->i_sb;
3023	struct mpage_da_data mpd = {
3024		.inode = mapping->host,
3025		.wbc = wbc,
3026		.can_map = 1,
3027	};
3028	int ret;
3029	int alloc_ctx;
3030
3031	ret = ext4_emergency_state(sb);
3032	if (unlikely(ret))
3033		return ret;
3034
3035	alloc_ctx = ext4_writepages_down_read(sb);
3036	ret = ext4_do_writepages(&mpd);
3037	/*
3038	 * For data=journal writeback we could have come across pages marked
3039	 * for delayed dirtying (PageChecked) which were just added to the
3040	 * running transaction. Try once more to get them to stable storage.
3041	 */
3042	if (!ret && mpd.journalled_more_data)
3043		ret = ext4_do_writepages(&mpd);
3044	ext4_writepages_up_read(sb, alloc_ctx);
3045
3046	return ret;
3047}
3048
3049int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
3050{
3051	struct writeback_control wbc = {
3052		.sync_mode = WB_SYNC_ALL,
3053		.nr_to_write = LONG_MAX,
3054		.range_start = jinode->i_dirty_start,
3055		.range_end = jinode->i_dirty_end,
3056	};
3057	struct mpage_da_data mpd = {
3058		.inode = jinode->i_vfs_inode,
3059		.wbc = &wbc,
3060		.can_map = 0,
3061	};
3062	return ext4_do_writepages(&mpd);
3063}
3064
3065static int ext4_dax_writepages(struct address_space *mapping,
3066			       struct writeback_control *wbc)
3067{
3068	int ret;
3069	long nr_to_write = wbc->nr_to_write;
3070	struct inode *inode = mapping->host;
3071	int alloc_ctx;
3072
3073	ret = ext4_emergency_state(inode->i_sb);
3074	if (unlikely(ret))
3075		return ret;
3076
3077	alloc_ctx = ext4_writepages_down_read(inode->i_sb);
3078	trace_ext4_writepages(inode, wbc);
3079
3080	ret = dax_writeback_mapping_range(mapping,
3081					  EXT4_SB(inode->i_sb)->s_daxdev, wbc);
3082	trace_ext4_writepages_result(inode, wbc, ret,
3083				     nr_to_write - wbc->nr_to_write);
3084	ext4_writepages_up_read(inode->i_sb, alloc_ctx);
3085	return ret;
3086}
3087
3088static int ext4_nonda_switch(struct super_block *sb)
3089{
3090	s64 free_clusters, dirty_clusters;
3091	struct ext4_sb_info *sbi = EXT4_SB(sb);
3092
3093	/*
3094	 * switch to non delalloc mode if we are running low
3095	 * on free block. The free block accounting via percpu
3096	 * counters can get slightly wrong with percpu_counter_batch getting
3097	 * accumulated on each CPU without updating global counters
3098	 * Delalloc need an accurate free block accounting. So switch
3099	 * to non delalloc when we are near to error range.
3100	 */
3101	free_clusters =
3102		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
3103	dirty_clusters =
3104		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
3105	/*
3106	 * Start pushing delalloc when 1/2 of free blocks are dirty.
3107	 */
3108	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
3109		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
3110
3111	if (2 * free_clusters < 3 * dirty_clusters ||
3112	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
3113		/*
3114		 * free block count is less than 150% of dirty blocks
3115		 * or free blocks is less than watermark
3116		 */
3117		return 1;
3118	}
3119	return 0;
3120}
3121
3122static int ext4_da_write_begin(const struct kiocb *iocb,
3123			       struct address_space *mapping,
3124			       loff_t pos, unsigned len,
3125			       struct folio **foliop, void **fsdata)
3126{
3127	int ret, retries = 0;
3128	struct folio *folio;
3129	pgoff_t index;
3130	struct inode *inode = mapping->host;
3131
3132	ret = ext4_emergency_state(inode->i_sb);
3133	if (unlikely(ret))
3134		return ret;
3135
3136	index = pos >> PAGE_SHIFT;
3137
3138	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
3139		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3140		return ext4_write_begin(iocb, mapping, pos,
3141					len, foliop, fsdata);
3142	}
3143	*fsdata = (void *)0;
3144	trace_ext4_da_write_begin(inode, pos, len);
3145
3146	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3147		ret = ext4_generic_write_inline_data(mapping, inode, pos, len,
3148						     foliop, fsdata, true);
3149		if (ret < 0)
3150			return ret;
3151		if (ret == 1)
3152			return 0;
3153	}
3154
3155retry:
3156	folio = write_begin_get_folio(iocb, mapping, index, len);
3157	if (IS_ERR(folio))
3158		return PTR_ERR(folio);
3159
3160	if (len > folio_next_pos(folio) - pos)
3161		len = folio_next_pos(folio) - pos;
3162
3163	ret = ext4_block_write_begin(NULL, folio, pos, len,
3164				     ext4_da_get_block_prep);
3165	if (ret < 0) {
3166		folio_unlock(folio);
3167		folio_put(folio);
3168		/*
3169		 * ext4_block_write_begin may have instantiated a few blocks
3170		 * outside i_size.  Trim these off again. Don't need
3171		 * i_size_read because we hold inode lock.
3172		 */
3173		if (pos + len > inode->i_size)
3174			ext4_truncate_failed_write(inode);
3175
3176		if (ret == -ENOSPC &&
3177		    ext4_should_retry_alloc(inode->i_sb, &retries))
3178			goto retry;
3179		return ret;
3180	}
3181
3182	*foliop = folio;
3183	return ret;
3184}
3185
3186/*
3187 * Check if we should update i_disksize
3188 * when write to the end of file but not require block allocation
3189 */
3190static int ext4_da_should_update_i_disksize(struct folio *folio,
3191					    unsigned long offset)
3192{
3193	struct buffer_head *bh;
3194	struct inode *inode = folio->mapping->host;
3195	unsigned int idx;
3196	int i;
3197
3198	bh = folio_buffers(folio);
3199	idx = offset >> inode->i_blkbits;
3200
3201	for (i = 0; i < idx; i++)
3202		bh = bh->b_this_page;
3203
3204	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3205		return 0;
3206	return 1;
3207}
3208
3209static int ext4_da_do_write_end(struct address_space *mapping,
3210			loff_t pos, unsigned len, unsigned copied,
3211			struct folio *folio)
3212{
3213	struct inode *inode = mapping->host;
3214	loff_t old_size = inode->i_size;
3215	bool disksize_changed = false;
3216	loff_t new_i_size, zero_len = 0;
3217	handle_t *handle;
3218
3219	if (unlikely(!folio_buffers(folio))) {
3220		folio_unlock(folio);
3221		folio_put(folio);
3222		return -EIO;
3223	}
3224	/*
3225	 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
3226	 * flag, which all that's needed to trigger page writeback.
3227	 */
3228	copied = block_write_end(pos, len, copied, folio);
3229	new_i_size = pos + copied;
3230
3231	/*
3232	 * It's important to update i_size while still holding folio lock,
3233	 * because folio writeout could otherwise come in and zero beyond
3234	 * i_size.
3235	 *
3236	 * Since we are holding inode lock, we are sure i_disksize <=
3237	 * i_size. We also know that if i_disksize < i_size, there are
3238	 * delalloc writes pending in the range up to i_size. If the end of
3239	 * the current write is <= i_size, there's no need to touch
3240	 * i_disksize since writeback will push i_disksize up to i_size
3241	 * eventually. If the end of the current write is > i_size and
3242	 * inside an allocated block which ext4_da_should_update_i_disksize()
3243	 * checked, we need to update i_disksize here as certain
3244	 * ext4_writepages() paths not allocating blocks and update i_disksize.
3245	 */
3246	if (new_i_size > inode->i_size) {
3247		unsigned long end;
3248
3249		i_size_write(inode, new_i_size);
3250		end = offset_in_folio(folio, new_i_size - 1);
3251		if (copied && ext4_da_should_update_i_disksize(folio, end)) {
3252			ext4_update_i_disksize(inode, new_i_size);
3253			disksize_changed = true;
3254		}
3255	}
3256
3257	folio_unlock(folio);
3258	folio_put(folio);
3259
3260	if (pos > old_size) {
3261		pagecache_isize_extended(inode, old_size, pos);
3262		zero_len = pos - old_size;
3263	}
3264
3265	if (!disksize_changed && !zero_len)
3266		return copied;
3267
3268	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3269	if (IS_ERR(handle))
3270		return PTR_ERR(handle);
3271	if (zero_len)
3272		ext4_zero_partial_blocks(handle, inode, old_size, zero_len);
3273	ext4_mark_inode_dirty(handle, inode);
3274	ext4_journal_stop(handle);
3275
3276	return copied;
3277}
3278
3279static int ext4_da_write_end(const struct kiocb *iocb,
3280			     struct address_space *mapping,
3281			     loff_t pos, unsigned len, unsigned copied,
3282			     struct folio *folio, void *fsdata)
3283{
3284	struct inode *inode = mapping->host;
3285	int write_mode = (int)(unsigned long)fsdata;
3286
3287	if (write_mode == FALL_BACK_TO_NONDELALLOC)
3288		return ext4_write_end(iocb, mapping, pos,
3289				      len, copied, folio, fsdata);
3290
3291	trace_ext4_da_write_end(inode, pos, len, copied);
3292
3293	if (write_mode != CONVERT_INLINE_DATA &&
3294	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3295	    ext4_has_inline_data(inode))
3296		return ext4_write_inline_data_end(inode, pos, len, copied,
3297						  folio);
3298
3299	if (unlikely(copied < len) && !folio_test_uptodate(folio))
3300		copied = 0;
3301
3302	return ext4_da_do_write_end(mapping, pos, len, copied, folio);
3303}
3304
3305/*
3306 * Force all delayed allocation blocks to be allocated for a given inode.
3307 */
3308int ext4_alloc_da_blocks(struct inode *inode)
3309{
3310	trace_ext4_alloc_da_blocks(inode);
3311
3312	if (!EXT4_I(inode)->i_reserved_data_blocks)
3313		return 0;
3314
3315	/*
3316	 * We do something simple for now.  The filemap_flush() will
3317	 * also start triggering a write of the data blocks, which is
3318	 * not strictly speaking necessary (and for users of
3319	 * laptop_mode, not even desirable).  However, to do otherwise
3320	 * would require replicating code paths in:
3321	 *
3322	 * ext4_writepages() ->
3323	 *    write_cache_pages() ---> (via passed in callback function)
3324	 *        __mpage_da_writepage() -->
3325	 *           mpage_add_bh_to_extent()
3326	 *           mpage_da_map_blocks()
3327	 *
3328	 * The problem is that write_cache_pages(), located in
3329	 * mm/page-writeback.c, marks pages clean in preparation for
3330	 * doing I/O, which is not desirable if we're not planning on
3331	 * doing I/O at all.
3332	 *
3333	 * We could call write_cache_pages(), and then redirty all of
3334	 * the pages by calling redirty_page_for_writepage() but that
3335	 * would be ugly in the extreme.  So instead we would need to
3336	 * replicate parts of the code in the above functions,
3337	 * simplifying them because we wouldn't actually intend to
3338	 * write out the pages, but rather only collect contiguous
3339	 * logical block extents, call the multi-block allocator, and
3340	 * then update the buffer heads with the block allocations.
3341	 *
3342	 * For now, though, we'll cheat by calling filemap_flush(),
3343	 * which will map the blocks, and start the I/O, but not
3344	 * actually wait for the I/O to complete.
3345	 */
3346	return filemap_flush(inode->i_mapping);
3347}
3348
3349/*
3350 * bmap() is special.  It gets used by applications such as lilo and by
3351 * the swapper to find the on-disk block of a specific piece of data.
3352 *
3353 * Naturally, this is dangerous if the block concerned is still in the
3354 * journal.  If somebody makes a swapfile on an ext4 data-journaling
3355 * filesystem and enables swap, then they may get a nasty shock when the
3356 * data getting swapped to that swapfile suddenly gets overwritten by
3357 * the original zero's written out previously to the journal and
3358 * awaiting writeback in the kernel's buffer cache.
3359 *
3360 * So, if we see any bmap calls here on a modified, data-journaled file,
3361 * take extra steps to flush any blocks which might be in the cache.
3362 */
3363static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3364{
3365	struct inode *inode = mapping->host;
3366	sector_t ret = 0;
3367
3368	inode_lock_shared(inode);
3369	/*
3370	 * We can get here for an inline file via the FIBMAP ioctl
3371	 */
3372	if (ext4_has_inline_data(inode))
3373		goto out;
3374
3375	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3376	    (test_opt(inode->i_sb, DELALLOC) ||
3377	     ext4_should_journal_data(inode))) {
3378		/*
3379		 * With delalloc or journalled data we want to sync the file so
3380		 * that we can make sure we allocate blocks for file and data
3381		 * is in place for the user to see it
3382		 */
3383		filemap_write_and_wait(mapping);
3384	}
3385
3386	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3387
3388out:
3389	inode_unlock_shared(inode);
3390	return ret;
3391}
3392
3393static int ext4_read_folio(struct file *file, struct folio *folio)
3394{
3395	int ret = -EAGAIN;
3396	struct inode *inode = folio->mapping->host;
3397
3398	trace_ext4_read_folio(inode, folio);
3399
3400	if (ext4_has_inline_data(inode))
3401		ret = ext4_readpage_inline(inode, folio);
3402
3403	if (ret == -EAGAIN)
3404		return ext4_mpage_readpages(inode, NULL, folio);
3405
3406	return ret;
3407}
3408
3409static void ext4_readahead(struct readahead_control *rac)
3410{
3411	struct inode *inode = rac->mapping->host;
3412
3413	/* If the file has inline data, no need to do readahead. */
3414	if (ext4_has_inline_data(inode))
3415		return;
3416
3417	ext4_mpage_readpages(inode, rac, NULL);
3418}
3419
3420static void ext4_invalidate_folio(struct folio *folio, size_t offset,
3421				size_t length)
3422{
3423	trace_ext4_invalidate_folio(folio, offset, length);
3424
3425	/* No journalling happens on data buffers when this function is used */
3426	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
3427
3428	block_invalidate_folio(folio, offset, length);
3429}
3430
3431static int __ext4_journalled_invalidate_folio(struct folio *folio,
3432					    size_t offset, size_t length)
3433{
3434	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3435
3436	trace_ext4_journalled_invalidate_folio(folio, offset, length);
3437
3438	/*
3439	 * If it's a full truncate we just forget about the pending dirtying
3440	 */
3441	if (offset == 0 && length == folio_size(folio))
3442		folio_clear_checked(folio);
3443
3444	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
3445}
3446
3447/* Wrapper for aops... */
3448static void ext4_journalled_invalidate_folio(struct folio *folio,
3449					   size_t offset,
3450					   size_t length)
3451{
3452	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3453}
3454
3455static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3456{
3457	struct inode *inode = folio->mapping->host;
3458	journal_t *journal = EXT4_JOURNAL(inode);
3459
3460	trace_ext4_release_folio(inode, folio);
3461
3462	/* Page has dirty journalled data -> cannot release */
3463	if (folio_test_checked(folio))
3464		return false;
3465	if (journal)
3466		return jbd2_journal_try_to_free_buffers(journal, folio);
3467	else
3468		return try_to_free_buffers(folio);
3469}
3470
3471static bool ext4_inode_datasync_dirty(struct inode *inode)
3472{
3473	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3474
3475	if (journal) {
3476		if (jbd2_transaction_committed(journal,
3477			EXT4_I(inode)->i_datasync_tid))
3478			return false;
3479		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3480			return !list_empty(&EXT4_I(inode)->i_fc_list);
3481		return true;
3482	}
3483
3484	/* Any metadata buffers to write? */
3485	if (!list_empty(&inode->i_mapping->i_private_list))
3486		return true;
3487	return inode_state_read_once(inode) & I_DIRTY_DATASYNC;
3488}
3489
3490static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3491			   struct ext4_map_blocks *map, loff_t offset,
3492			   loff_t length, unsigned int flags)
3493{
3494	u8 blkbits = inode->i_blkbits;
3495
3496	/*
3497	 * Writes that span EOF might trigger an I/O size update on completion,
3498	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3499	 * there is no other metadata changes being made or are pending.
3500	 */
3501	iomap->flags = 0;
3502	if (ext4_inode_datasync_dirty(inode) ||
3503	    offset + length > i_size_read(inode))
3504		iomap->flags |= IOMAP_F_DIRTY;
3505
3506	if (map->m_flags & EXT4_MAP_NEW)
3507		iomap->flags |= IOMAP_F_NEW;
3508
3509	/* HW-offload atomics are always used */
3510	if (flags & IOMAP_ATOMIC)
3511		iomap->flags |= IOMAP_F_ATOMIC_BIO;
3512
3513	if (flags & IOMAP_DAX)
3514		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3515	else
3516		iomap->bdev = inode->i_sb->s_bdev;
3517	iomap->offset = EXT4_LBLK_TO_B(inode, map->m_lblk);
3518	iomap->length = EXT4_LBLK_TO_B(inode, map->m_len);
3519
3520	if ((map->m_flags & EXT4_MAP_MAPPED) &&
3521	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3522		iomap->flags |= IOMAP_F_MERGED;
3523
3524	/*
3525	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3526	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3527	 * set. In order for any allocated unwritten extents to be converted
3528	 * into written extents correctly within the ->end_io() handler, we
3529	 * need to ensure that the iomap->type is set appropriately. Hence, the
3530	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3531	 * been set first.
3532	 */
3533	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3534		iomap->type = IOMAP_UNWRITTEN;
3535		iomap->addr = (u64) map->m_pblk << blkbits;
3536		if (flags & IOMAP_DAX)
3537			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3538	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3539		iomap->type = IOMAP_MAPPED;
3540		iomap->addr = (u64) map->m_pblk << blkbits;
3541		if (flags & IOMAP_DAX)
3542			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3543	} else if (map->m_flags & EXT4_MAP_DELAYED) {
3544		iomap->type = IOMAP_DELALLOC;
3545		iomap->addr = IOMAP_NULL_ADDR;
3546	} else {
3547		iomap->type = IOMAP_HOLE;
3548		iomap->addr = IOMAP_NULL_ADDR;
3549	}
3550}
3551
3552static int ext4_map_blocks_atomic_write_slow(handle_t *handle,
3553			struct inode *inode, struct ext4_map_blocks *map)
3554{
3555	ext4_lblk_t m_lblk = map->m_lblk;
3556	unsigned int m_len = map->m_len;
3557	unsigned int mapped_len = 0, m_flags = 0;
3558	ext4_fsblk_t next_pblk = 0;
3559	bool check_next_pblk = false;
3560	int ret = 0;
3561
3562	WARN_ON_ONCE(!ext4_has_feature_bigalloc(inode->i_sb));
3563
3564	/*
3565	 * This is a slow path in case of mixed mapping. We use
3566	 * EXT4_GET_BLOCKS_CREATE_ZERO flag here to make sure we get a single
3567	 * contiguous mapped mapping. This will ensure any unwritten or hole
3568	 * regions within the requested range is zeroed out and we return
3569	 * a single contiguous mapped extent.
3570	 */
3571	m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3572
3573	do {
3574		ret = ext4_map_blocks(handle, inode, map, m_flags);
3575		if (ret < 0 && ret != -ENOSPC)
3576			goto out_err;
3577		/*
3578		 * This should never happen, but let's return an error code to
3579		 * avoid an infinite loop in here.
3580		 */
3581		if (ret == 0) {
3582			ret = -EFSCORRUPTED;
3583			ext4_warning_inode(inode,
3584				"ext4_map_blocks() couldn't allocate blocks m_flags: 0x%x, ret:%d",
3585				m_flags, ret);
3586			goto out_err;
3587		}
3588		/*
3589		 * With bigalloc we should never get ENOSPC nor discontiguous
3590		 * physical extents.
3591		 */
3592		if ((check_next_pblk && next_pblk != map->m_pblk) ||
3593				ret == -ENOSPC) {
3594			ext4_warning_inode(inode,
3595				"Non-contiguous allocation detected: expected %llu, got %llu, "
3596				"or ext4_map_blocks() returned out of space ret: %d",
3597				next_pblk, map->m_pblk, ret);
3598			ret = -EFSCORRUPTED;
3599			goto out_err;
3600		}
3601		next_pblk = map->m_pblk + map->m_len;
3602		check_next_pblk = true;
3603
3604		mapped_len += map->m_len;
3605		map->m_lblk += map->m_len;
3606		map->m_len = m_len - mapped_len;
3607	} while (mapped_len < m_len);
3608
3609	/*
3610	 * We might have done some work in above loop, so we need to query the
3611	 * start of the physical extent, based on the origin m_lblk and m_len.
3612	 * Let's also ensure we were able to allocate the required range for
3613	 * mixed mapping case.
3614	 */
3615	map->m_lblk = m_lblk;
3616	map->m_len = m_len;
3617	map->m_flags = 0;
3618
3619	ret = ext4_map_blocks(handle, inode, map,
3620			      EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF);
3621	if (ret != m_len) {
3622		ext4_warning_inode(inode,
3623			"allocation failed for atomic write request m_lblk:%u, m_len:%u, ret:%d\n",
3624			m_lblk, m_len, ret);
3625		ret = -EINVAL;
3626	}
3627	return ret;
3628
3629out_err:
3630	/* reset map before returning an error */
3631	map->m_lblk = m_lblk;
3632	map->m_len = m_len;
3633	map->m_flags = 0;
3634	return ret;
3635}
3636
3637/*
3638 * ext4_map_blocks_atomic: Helper routine to ensure the entire requested
3639 * range in @map [lblk, lblk + len) is one single contiguous extent with no
3640 * mixed mappings.
3641 *
3642 * We first use m_flags passed to us by our caller (ext4_iomap_alloc()).
3643 * We only call EXT4_GET_BLOCKS_ZERO in the slow path, when the underlying
3644 * physical extent for the requested range does not have a single contiguous
3645 * mapping type i.e. (Hole, Mapped, or Unwritten) throughout.
3646 * In that case we will loop over the requested range to allocate and zero out
3647 * the unwritten / holes in between, to get a single mapped extent from
3648 * [m_lblk, m_lblk +  m_len). Note that this is only possible because we know
3649 * this can be called only with bigalloc enabled filesystem where the underlying
3650 * cluster is already allocated. This avoids allocating discontiguous extents
3651 * in the slow path due to multiple calls to ext4_map_blocks().
3652 * The slow path is mostly non-performance critical path, so it should be ok to
3653 * loop using ext4_map_blocks() with appropriate flags to allocate & zero the
3654 * underlying short holes/unwritten extents within the requested range.
3655 */
3656static int ext4_map_blocks_atomic_write(handle_t *handle, struct inode *inode,
3657				struct ext4_map_blocks *map, int m_flags,
3658				bool *force_commit)
3659{
3660	ext4_lblk_t m_lblk = map->m_lblk;
3661	unsigned int m_len = map->m_len;
3662	int ret = 0;
3663
3664	WARN_ON_ONCE(m_len > 1 && !ext4_has_feature_bigalloc(inode->i_sb));
3665
3666	ret = ext4_map_blocks(handle, inode, map, m_flags);
3667	if (ret < 0 || ret == m_len)
3668		goto out;
3669	/*
3670	 * This is a mixed mapping case where we were not able to allocate
3671	 * a single contiguous extent. In that case let's reset requested
3672	 * mapping and call the slow path.
3673	 */
3674	map->m_lblk = m_lblk;
3675	map->m_len = m_len;
3676	map->m_flags = 0;
3677
3678	/*
3679	 * slow path means we have mixed mapping, that means we will need
3680	 * to force txn commit.
3681	 */
3682	*force_commit = true;
3683	return ext4_map_blocks_atomic_write_slow(handle, inode, map);
3684out:
3685	return ret;
3686}
3687
3688static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3689			    unsigned int flags)
3690{
3691	handle_t *handle;
3692	int ret, dio_credits, m_flags = 0, retries = 0;
3693	bool force_commit = false;
3694
3695	/*
3696	 * Trim the mapping request to the maximum value that we can map at
3697	 * once for direct I/O.
3698	 */
3699	if (map->m_len > DIO_MAX_BLOCKS)
3700		map->m_len = DIO_MAX_BLOCKS;
3701
3702	/*
3703	 * journal credits estimation for atomic writes. We call
3704	 * ext4_map_blocks(), to find if there could be a mixed mapping. If yes,
3705	 * then let's assume the no. of pextents required can be m_len i.e.
3706	 * every alternate block can be unwritten and hole.
3707	 */
3708	if (flags & IOMAP_ATOMIC) {
3709		unsigned int orig_mlen = map->m_len;
3710
3711		ret = ext4_map_blocks(NULL, inode, map, 0);
3712		if (ret < 0)
3713			return ret;
3714		if (map->m_len < orig_mlen) {
3715			map->m_len = orig_mlen;
3716			dio_credits = ext4_meta_trans_blocks(inode, orig_mlen,
3717							     map->m_len);
3718		} else {
3719			dio_credits = ext4_chunk_trans_blocks(inode,
3720							      map->m_len);
3721		}
3722	} else {
3723		dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3724	}
3725
3726retry:
3727	/*
3728	 * Either we allocate blocks and then don't get an unwritten extent, so
3729	 * in that case we have reserved enough credits. Or, the blocks are
3730	 * already allocated and unwritten. In that case, the extent conversion
3731	 * fits into the credits as well.
3732	 */
3733	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3734	if (IS_ERR(handle))
3735		return PTR_ERR(handle);
3736
3737	/*
3738	 * DAX and direct I/O are the only two operations that are currently
3739	 * supported with IOMAP_WRITE.
3740	 */
3741	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3742	if (flags & IOMAP_DAX)
3743		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3744	/*
3745	 * We use i_size instead of i_disksize here because delalloc writeback
3746	 * can complete at any point during the I/O and subsequently push the
3747	 * i_disksize out to i_size. This could be beyond where direct I/O is
3748	 * happening and thus expose allocated blocks to direct I/O reads.
3749	 */
3750	else if (EXT4_LBLK_TO_B(inode, map->m_lblk) >= i_size_read(inode))
3751		m_flags = EXT4_GET_BLOCKS_CREATE;
3752	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3753		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3754
3755	if (flags & IOMAP_ATOMIC)
3756		ret = ext4_map_blocks_atomic_write(handle, inode, map, m_flags,
3757						   &force_commit);
3758	else
3759		ret = ext4_map_blocks(handle, inode, map, m_flags);
3760
3761	/*
3762	 * We cannot fill holes in indirect tree based inodes as that could
3763	 * expose stale data in the case of a crash. Use the magic error code
3764	 * to fallback to buffered I/O.
3765	 */
3766	if (!m_flags && !ret)
3767		ret = -ENOTBLK;
3768
3769	ext4_journal_stop(handle);
3770	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3771		goto retry;
3772
3773	/*
3774	 * Force commit the current transaction if the allocation spans a mixed
3775	 * mapping range. This ensures any pending metadata updates (like
3776	 * unwritten to written extents conversion) in this range are in
3777	 * consistent state with the file data blocks, before performing the
3778	 * actual write I/O. If the commit fails, the whole I/O must be aborted
3779	 * to prevent any possible torn writes.
3780	 */
3781	if (ret > 0 && force_commit) {
3782		int ret2;
3783
3784		ret2 = ext4_force_commit(inode->i_sb);
3785		if (ret2)
3786			return ret2;
3787	}
3788
3789	return ret;
3790}
3791
3792
3793static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3794		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3795{
3796	int ret;
3797	struct ext4_map_blocks map;
3798	u8 blkbits = inode->i_blkbits;
3799	unsigned int orig_mlen;
3800
3801	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3802		return -EINVAL;
3803
3804	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3805		return -ERANGE;
3806
3807	/*
3808	 * Calculate the first and last logical blocks respectively.
3809	 */
3810	map.m_lblk = offset >> blkbits;
3811	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3812			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3813	orig_mlen = map.m_len;
3814
3815	if (flags & IOMAP_WRITE) {
3816		/*
3817		 * We check here if the blocks are already allocated, then we
3818		 * don't need to start a journal txn and we can directly return
3819		 * the mapping information. This could boost performance
3820		 * especially in multi-threaded overwrite requests.
3821		 */
3822		if (offset + length <= i_size_read(inode)) {
3823			ret = ext4_map_blocks(NULL, inode, &map, 0);
3824			/*
3825			 * For atomic writes the entire requested length should
3826			 * be mapped.
3827			 */
3828			if (map.m_flags & EXT4_MAP_MAPPED) {
3829				if ((!(flags & IOMAP_ATOMIC) && ret > 0) ||
3830				   (flags & IOMAP_ATOMIC && ret >= orig_mlen))
3831					goto out;
3832			}
3833			map.m_len = orig_mlen;
3834		}
3835		ret = ext4_iomap_alloc(inode, &map, flags);
3836	} else {
3837		/*
3838		 * This can be called for overwrites path from
3839		 * ext4_iomap_overwrite_begin().
3840		 */
3841		ret = ext4_map_blocks(NULL, inode, &map, 0);
3842	}
3843
3844	if (ret < 0)
3845		return ret;
3846out:
3847	/*
3848	 * When inline encryption is enabled, sometimes I/O to an encrypted file
3849	 * has to be broken up to guarantee DUN contiguity.  Handle this by
3850	 * limiting the length of the mapping returned.
3851	 */
3852	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
3853
3854	/*
3855	 * Before returning to iomap, let's ensure the allocated mapping
3856	 * covers the entire requested length for atomic writes.
3857	 */
3858	if (flags & IOMAP_ATOMIC) {
3859		if (map.m_len < (length >> blkbits)) {
3860			WARN_ON_ONCE(1);
3861			return -EINVAL;
3862		}
3863	}
3864	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3865
3866	return 0;
3867}
3868
3869static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3870		loff_t length, unsigned flags, struct iomap *iomap,
3871		struct iomap *srcmap)
3872{
3873	int ret;
3874
3875	/*
3876	 * Even for writes we don't need to allocate blocks, so just pretend
3877	 * we are reading to save overhead of starting a transaction.
3878	 */
3879	flags &= ~IOMAP_WRITE;
3880	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3881	WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
3882	return ret;
3883}
3884
3885const struct iomap_ops ext4_iomap_ops = {
3886	.iomap_begin		= ext4_iomap_begin,
3887};
3888
3889const struct iomap_ops ext4_iomap_overwrite_ops = {
3890	.iomap_begin		= ext4_iomap_overwrite_begin,
3891};
3892
3893static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3894				   loff_t length, unsigned int flags,
3895				   struct iomap *iomap, struct iomap *srcmap)
3896{
3897	int ret;
3898	struct ext4_map_blocks map;
3899	u8 blkbits = inode->i_blkbits;
3900
3901	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3902		return -EINVAL;
3903
3904	if (ext4_has_inline_data(inode)) {
3905		ret = ext4_inline_data_iomap(inode, iomap);
3906		if (ret != -EAGAIN) {
3907			if (ret == 0 && offset >= iomap->length)
3908				ret = -ENOENT;
3909			return ret;
3910		}
3911	}
3912
3913	/*
3914	 * Calculate the first and last logical block respectively.
3915	 */
3916	map.m_lblk = offset >> blkbits;
3917	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3918			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3919
3920	/*
3921	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3922	 * So handle it here itself instead of querying ext4_map_blocks().
3923	 * Since ext4_map_blocks() will warn about it and will return
3924	 * -EIO error.
3925	 */
3926	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3927		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3928
3929		if (offset >= sbi->s_bitmap_maxbytes) {
3930			map.m_flags = 0;
3931			goto set_iomap;
3932		}
3933	}
3934
3935	ret = ext4_map_blocks(NULL, inode, &map, 0);
3936	if (ret < 0)
3937		return ret;
3938set_iomap:
3939	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3940
3941	return 0;
3942}
3943
3944const struct iomap_ops ext4_iomap_report_ops = {
3945	.iomap_begin = ext4_iomap_begin_report,
3946};
3947
3948/*
3949 * For data=journal mode, folio should be marked dirty only when it was
3950 * writeably mapped. When that happens, it was already attached to the
3951 * transaction and marked as jbddirty (we take care of this in
3952 * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
3953 * so we should have nothing to do here, except for the case when someone
3954 * had the page pinned and dirtied the page through this pin (e.g. by doing
3955 * direct IO to it). In that case we'd need to attach buffers here to the
3956 * transaction but we cannot due to lock ordering.  We cannot just dirty the
3957 * folio and leave attached buffers clean, because the buffers' dirty state is
3958 * "definitive".  We cannot just set the buffers dirty or jbddirty because all
3959 * the journalling code will explode.  So what we do is to mark the folio
3960 * "pending dirty" and next time ext4_writepages() is called, attach buffers
3961 * to the transaction appropriately.
3962 */
3963static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3964		struct folio *folio)
3965{
3966	WARN_ON_ONCE(!folio_buffers(folio));
3967	if (folio_maybe_dma_pinned(folio))
3968		folio_set_checked(folio);
3969	return filemap_dirty_folio(mapping, folio);
3970}
3971
3972static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
3973{
3974	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3975	WARN_ON_ONCE(!folio_buffers(folio));
3976	return block_dirty_folio(mapping, folio);
3977}
3978
3979static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3980				    struct file *file, sector_t *span)
3981{
3982	return iomap_swapfile_activate(sis, file, span,
3983				       &ext4_iomap_report_ops);
3984}
3985
3986static const struct address_space_operations ext4_aops = {
3987	.read_folio		= ext4_read_folio,
3988	.readahead		= ext4_readahead,
3989	.writepages		= ext4_writepages,
3990	.write_begin		= ext4_write_begin,
3991	.write_end		= ext4_write_end,
3992	.dirty_folio		= ext4_dirty_folio,
3993	.bmap			= ext4_bmap,
3994	.invalidate_folio	= ext4_invalidate_folio,
3995	.release_folio		= ext4_release_folio,
3996	.migrate_folio		= buffer_migrate_folio,
3997	.is_partially_uptodate  = block_is_partially_uptodate,
3998	.error_remove_folio	= generic_error_remove_folio,
3999	.swap_activate		= ext4_iomap_swap_activate,
4000};
4001
4002static const struct address_space_operations ext4_journalled_aops = {
4003	.read_folio		= ext4_read_folio,
4004	.readahead		= ext4_readahead,
4005	.writepages		= ext4_writepages,
4006	.write_begin		= ext4_write_begin,
4007	.write_end		= ext4_journalled_write_end,
4008	.dirty_folio		= ext4_journalled_dirty_folio,
4009	.bmap			= ext4_bmap,
4010	.invalidate_folio	= ext4_journalled_invalidate_folio,
4011	.release_folio		= ext4_release_folio,
4012	.migrate_folio		= buffer_migrate_folio_norefs,
4013	.is_partially_uptodate  = block_is_partially_uptodate,
4014	.error_remove_folio	= generic_error_remove_folio,
4015	.swap_activate		= ext4_iomap_swap_activate,
4016};
4017
4018static const struct address_space_operations ext4_da_aops = {
4019	.read_folio		= ext4_read_folio,
4020	.readahead		= ext4_readahead,
4021	.writepages		= ext4_writepages,
4022	.write_begin		= ext4_da_write_begin,
4023	.write_end		= ext4_da_write_end,
4024	.dirty_folio		= ext4_dirty_folio,
4025	.bmap			= ext4_bmap,
4026	.invalidate_folio	= ext4_invalidate_folio,
4027	.release_folio		= ext4_release_folio,
4028	.migrate_folio		= buffer_migrate_folio,
4029	.is_partially_uptodate  = block_is_partially_uptodate,
4030	.error_remove_folio	= generic_error_remove_folio,
4031	.swap_activate		= ext4_iomap_swap_activate,
4032};
4033
4034static const struct address_space_operations ext4_dax_aops = {
4035	.writepages		= ext4_dax_writepages,
4036	.dirty_folio		= noop_dirty_folio,
4037	.bmap			= ext4_bmap,
4038	.swap_activate		= ext4_iomap_swap_activate,
4039};
4040
4041void ext4_set_aops(struct inode *inode)
4042{
4043	switch (ext4_inode_journal_mode(inode)) {
4044	case EXT4_INODE_ORDERED_DATA_MODE:
4045	case EXT4_INODE_WRITEBACK_DATA_MODE:
4046		break;
4047	case EXT4_INODE_JOURNAL_DATA_MODE:
4048		inode->i_mapping->a_ops = &ext4_journalled_aops;
4049		return;
4050	default:
4051		BUG();
4052	}
4053	if (IS_DAX(inode))
4054		inode->i_mapping->a_ops = &ext4_dax_aops;
4055	else if (test_opt(inode->i_sb, DELALLOC))
4056		inode->i_mapping->a_ops = &ext4_da_aops;
4057	else
4058		inode->i_mapping->a_ops = &ext4_aops;
4059}
4060
4061/*
4062 * Here we can't skip an unwritten buffer even though it usually reads zero
4063 * because it might have data in pagecache (eg, if called from ext4_zero_range,
4064 * ext4_punch_hole, etc) which needs to be properly zeroed out. Otherwise a
4065 * racing writeback can come later and flush the stale pagecache to disk.
4066 */
4067static int __ext4_block_zero_page_range(handle_t *handle,
4068		struct address_space *mapping, loff_t from, loff_t length)
4069{
4070	unsigned int offset, blocksize, pos;
4071	ext4_lblk_t iblock;
4072	struct inode *inode = mapping->host;
4073	struct buffer_head *bh;
4074	struct folio *folio;
4075	int err = 0;
4076
4077	folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
4078				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
4079				    mapping_gfp_constraint(mapping, ~__GFP_FS));
4080	if (IS_ERR(folio))
4081		return PTR_ERR(folio);
4082
4083	blocksize = inode->i_sb->s_blocksize;
4084
4085	iblock = EXT4_PG_TO_LBLK(inode, folio->index);
4086
4087	bh = folio_buffers(folio);
4088	if (!bh)
4089		bh = create_empty_buffers(folio, blocksize, 0);
4090
4091	/* Find the buffer that contains "offset" */
4092	offset = offset_in_folio(folio, from);
4093	pos = blocksize;
4094	while (offset >= pos) {
4095		bh = bh->b_this_page;
4096		iblock++;
4097		pos += blocksize;
4098	}
4099	if (buffer_freed(bh)) {
4100		BUFFER_TRACE(bh, "freed: skip");
4101		goto unlock;
4102	}
4103	if (!buffer_mapped(bh)) {
4104		BUFFER_TRACE(bh, "unmapped");
4105		ext4_get_block(inode, iblock, bh, 0);
4106		/* unmapped? It's a hole - nothing to do */
4107		if (!buffer_mapped(bh)) {
4108			BUFFER_TRACE(bh, "still unmapped");
4109			goto unlock;
4110		}
4111	}
4112
4113	/* Ok, it's mapped. Make sure it's up-to-date */
4114	if (folio_test_uptodate(folio))
4115		set_buffer_uptodate(bh);
4116
4117	if (!buffer_uptodate(bh)) {
4118		err = ext4_read_bh_lock(bh, 0, true);
4119		if (err)
4120			goto unlock;
4121		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
4122			/* We expect the key to be set. */
4123			BUG_ON(!fscrypt_has_encryption_key(inode));
4124			err = fscrypt_decrypt_pagecache_blocks(folio,
4125							       blocksize,
4126							       bh_offset(bh));
4127			if (err) {
4128				clear_buffer_uptodate(bh);
4129				goto unlock;
4130			}
4131		}
4132	}
4133	if (ext4_should_journal_data(inode)) {
4134		BUFFER_TRACE(bh, "get write access");
4135		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
4136						    EXT4_JTR_NONE);
4137		if (err)
4138			goto unlock;
4139	}
4140	folio_zero_range(folio, offset, length);
4141	BUFFER_TRACE(bh, "zeroed end of block");
4142
4143	if (ext4_should_journal_data(inode)) {
4144		err = ext4_dirty_journalled_data(handle, bh);
4145	} else {
4146		err = 0;
4147		mark_buffer_dirty(bh);
4148		if (ext4_should_order_data(inode))
4149			err = ext4_jbd2_inode_add_write(handle, inode, from,
4150					length);
4151	}
4152
4153unlock:
4154	folio_unlock(folio);
4155	folio_put(folio);
4156	return err;
4157}
4158
4159/*
4160 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4161 * starting from file offset 'from'.  The range to be zero'd must
4162 * be contained with in one block.  If the specified range exceeds
4163 * the end of the block it will be shortened to end of the block
4164 * that corresponds to 'from'
4165 */
4166static int ext4_block_zero_page_range(handle_t *handle,
4167		struct address_space *mapping, loff_t from, loff_t length)
4168{
4169	struct inode *inode = mapping->host;
4170	unsigned blocksize = inode->i_sb->s_blocksize;
4171	unsigned int max = blocksize - (from & (blocksize - 1));
4172
4173	/*
4174	 * correct length if it does not fall between
4175	 * 'from' and the end of the block
4176	 */
4177	if (length > max || length < 0)
4178		length = max;
4179
4180	if (IS_DAX(inode)) {
4181		return dax_zero_range(inode, from, length, NULL,
4182				      &ext4_iomap_ops);
4183	}
4184	return __ext4_block_zero_page_range(handle, mapping, from, length);
4185}
4186
4187/*
4188 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4189 * up to the end of the block which corresponds to `from'.
4190 * This required during truncate. We need to physically zero the tail end
4191 * of that block so it doesn't yield old data if the file is later grown.
4192 */
4193static int ext4_block_truncate_page(handle_t *handle,
4194		struct address_space *mapping, loff_t from)
4195{
4196	unsigned length;
4197	unsigned blocksize;
4198	struct inode *inode = mapping->host;
4199
4200	/* If we are processing an encrypted inode during orphan list handling */
4201	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
4202		return 0;
4203
4204	blocksize = i_blocksize(inode);
4205	length = blocksize - (from & (blocksize - 1));
4206
4207	return ext4_block_zero_page_range(handle, mapping, from, length);
4208}
4209
4210int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4211			     loff_t lstart, loff_t length)
4212{
4213	struct super_block *sb = inode->i_sb;
4214	struct address_space *mapping = inode->i_mapping;
4215	unsigned partial_start, partial_end;
4216	ext4_fsblk_t start, end;
4217	loff_t byte_end = (lstart + length - 1);
4218	int err = 0;
4219
4220	partial_start = lstart & (sb->s_blocksize - 1);
4221	partial_end = byte_end & (sb->s_blocksize - 1);
4222
4223	start = lstart >> sb->s_blocksize_bits;
4224	end = byte_end >> sb->s_blocksize_bits;
4225
4226	/* Handle partial zero within the single block */
4227	if (start == end &&
4228	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
4229		err = ext4_block_zero_page_range(handle, mapping,
4230						 lstart, length);
4231		return err;
4232	}
4233	/* Handle partial zero out on the start of the range */
4234	if (partial_start) {
4235		err = ext4_block_zero_page_range(handle, mapping,
4236						 lstart, sb->s_blocksize);
4237		if (err)
4238			return err;
4239	}
4240	/* Handle partial zero out on the end of the range */
4241	if (partial_end != sb->s_blocksize - 1)
4242		err = ext4_block_zero_page_range(handle, mapping,
4243						 byte_end - partial_end,
4244						 partial_end + 1);
4245	return err;
4246}
4247
4248int ext4_can_truncate(struct inode *inode)
4249{
4250	if (S_ISREG(inode->i_mode))
4251		return 1;
4252	if (S_ISDIR(inode->i_mode))
4253		return 1;
4254	if (S_ISLNK(inode->i_mode))
4255		return !ext4_inode_is_fast_symlink(inode);
4256	return 0;
4257}
4258
4259/*
4260 * We have to make sure i_disksize gets properly updated before we truncate
4261 * page cache due to hole punching or zero range. Otherwise i_disksize update
4262 * can get lost as it may have been postponed to submission of writeback but
4263 * that will never happen if we remove the folio containing i_size from the
4264 * page cache. Also if we punch hole within i_size but above i_disksize,
4265 * following ext4_page_mkwrite() may mistakenly allocate written blocks over
4266 * the hole and thus introduce allocated blocks beyond i_disksize which is
4267 * not allowed (e2fsck would complain in case of crash).
4268 */
4269int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4270				      loff_t len)
4271{
4272	handle_t *handle;
4273	int ret;
4274
4275	loff_t size = i_size_read(inode);
4276
4277	WARN_ON(!inode_is_locked(inode));
4278	if (offset > size)
4279		return 0;
4280
4281	if (offset + len < size)
4282		size = offset + len;
4283	if (EXT4_I(inode)->i_disksize >= size)
4284		return 0;
4285
4286	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4287	if (IS_ERR(handle))
4288		return PTR_ERR(handle);
4289	ext4_update_i_disksize(inode, size);
4290	ret = ext4_mark_inode_dirty(handle, inode);
4291	ext4_journal_stop(handle);
4292
4293	return ret;
4294}
4295
4296static inline void ext4_truncate_folio(struct inode *inode,
4297				       loff_t start, loff_t end)
4298{
4299	unsigned long blocksize = i_blocksize(inode);
4300	struct folio *folio;
4301
4302	/* Nothing to be done if no complete block needs to be truncated. */
4303	if (round_up(start, blocksize) >= round_down(end, blocksize))
4304		return;
4305
4306	folio = filemap_lock_folio(inode->i_mapping, start >> PAGE_SHIFT);
4307	if (IS_ERR(folio))
4308		return;
4309
4310	if (folio_mkclean(folio))
4311		folio_mark_dirty(folio);
4312	folio_unlock(folio);
4313	folio_put(folio);
4314}
4315
4316int ext4_truncate_page_cache_block_range(struct inode *inode,
4317					 loff_t start, loff_t end)
4318{
4319	unsigned long blocksize = i_blocksize(inode);
4320	int ret;
4321
4322	/*
4323	 * For journalled data we need to write (and checkpoint) pages
4324	 * before discarding page cache to avoid inconsitent data on disk
4325	 * in case of crash before freeing or unwritten converting trans
4326	 * is committed.
4327	 */
4328	if (ext4_should_journal_data(inode)) {
4329		ret = filemap_write_and_wait_range(inode->i_mapping, start,
4330						   end - 1);
4331		if (ret)
4332			return ret;
4333		goto truncate_pagecache;
4334	}
4335
4336	/*
4337	 * If the block size is less than the page size, the file's mapped
4338	 * blocks within one page could be freed or converted to unwritten.
4339	 * So it's necessary to remove writable userspace mappings, and then
4340	 * ext4_page_mkwrite() can be called during subsequent write access
4341	 * to these partial folios.
4342	 */
4343	if (!IS_ALIGNED(start | end, PAGE_SIZE) &&
4344	    blocksize < PAGE_SIZE && start < inode->i_size) {
4345		loff_t page_boundary = round_up(start, PAGE_SIZE);
4346
4347		ext4_truncate_folio(inode, start, min(page_boundary, end));
4348		if (end > page_boundary)
4349			ext4_truncate_folio(inode,
4350					    round_down(end, PAGE_SIZE), end);
4351	}
4352
4353truncate_pagecache:
4354	truncate_pagecache_range(inode, start, end - 1);
4355	return 0;
4356}
4357
4358static void ext4_wait_dax_page(struct inode *inode)
4359{
4360	filemap_invalidate_unlock(inode->i_mapping);
4361	schedule();
4362	filemap_invalidate_lock(inode->i_mapping);
4363}
4364
4365int ext4_break_layouts(struct inode *inode)
4366{
4367	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
4368		return -EINVAL;
4369
4370	return dax_break_layout_inode(inode, ext4_wait_dax_page);
4371}
4372
4373/*
4374 * ext4_punch_hole: punches a hole in a file by releasing the blocks
4375 * associated with the given offset and length
4376 *
4377 * @inode:  File inode
4378 * @offset: The offset where the hole will begin
4379 * @len:    The length of the hole
4380 *
4381 * Returns: 0 on success or negative on failure
4382 */
4383
4384int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
4385{
4386	struct inode *inode = file_inode(file);
4387	struct super_block *sb = inode->i_sb;
4388	ext4_lblk_t start_lblk, end_lblk;
4389	loff_t max_end = sb->s_maxbytes;
4390	loff_t end = offset + length;
4391	handle_t *handle;
4392	unsigned int credits;
4393	int ret;
4394
4395	trace_ext4_punch_hole(inode, offset, length, 0);
4396	WARN_ON_ONCE(!inode_is_locked(inode));
4397
4398	/*
4399	 * For indirect-block based inodes, make sure that the hole within
4400	 * one block before last range.
4401	 */
4402	if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4403		max_end = EXT4_SB(sb)->s_bitmap_maxbytes - sb->s_blocksize;
4404
4405	/* No need to punch hole beyond i_size */
4406	if (offset >= inode->i_size || offset >= max_end)
4407		return 0;
4408
4409	/*
4410	 * If the hole extends beyond i_size, set the hole to end after
4411	 * the block that contains i_size to save pointless tail block zeroing.
4412	 */
4413	if (end >= inode->i_size)
4414		end = round_up(inode->i_size, sb->s_blocksize);
4415	if (end > max_end)
4416		end = max_end;
4417	length = end - offset;
4418
4419	/*
4420	 * Attach jinode to inode for jbd2 if we do any zeroing of partial
4421	 * block.
4422	 */
4423	if (!IS_ALIGNED(offset | end, sb->s_blocksize)) {
4424		ret = ext4_inode_attach_jinode(inode);
4425		if (ret < 0)
4426			return ret;
4427	}
4428
4429
4430	ret = ext4_update_disksize_before_punch(inode, offset, length);
4431	if (ret)
4432		return ret;
4433
4434	/* Now release the pages and zero block aligned part of pages*/
4435	ret = ext4_truncate_page_cache_block_range(inode, offset, end);
4436	if (ret)
4437		return ret;
4438
4439	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4440		credits = ext4_chunk_trans_extent(inode, 2);
4441	else
4442		credits = ext4_blocks_for_truncate(inode);
4443	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4444	if (IS_ERR(handle)) {
4445		ret = PTR_ERR(handle);
4446		ext4_std_error(sb, ret);
4447		return ret;
4448	}
4449
4450	ret = ext4_zero_partial_blocks(handle, inode, offset, length);
4451	if (ret)
4452		goto out_handle;
4453
4454	/* If there are blocks to remove, do it */
4455	start_lblk = EXT4_B_TO_LBLK(inode, offset);
4456	end_lblk = end >> inode->i_blkbits;
4457
4458	if (end_lblk > start_lblk) {
4459		ext4_lblk_t hole_len = end_lblk - start_lblk;
4460
4461		ext4_fc_track_inode(handle, inode);
4462		ext4_check_map_extents_env(inode);
4463		down_write(&EXT4_I(inode)->i_data_sem);
4464		ext4_discard_preallocations(inode);
4465
4466		ext4_es_remove_extent(inode, start_lblk, hole_len);
4467
4468		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4469			ret = ext4_ext_remove_space(inode, start_lblk,
4470						    end_lblk - 1);
4471		else
4472			ret = ext4_ind_remove_space(handle, inode, start_lblk,
4473						    end_lblk);
4474		if (ret) {
4475			up_write(&EXT4_I(inode)->i_data_sem);
4476			goto out_handle;
4477		}
4478
4479		ext4_es_insert_extent(inode, start_lblk, hole_len, ~0,
4480				      EXTENT_STATUS_HOLE, 0);
4481		up_write(&EXT4_I(inode)->i_data_sem);
4482	}
4483	ext4_fc_track_range(handle, inode, start_lblk, end_lblk);
4484
4485	ret = ext4_mark_inode_dirty(handle, inode);
4486	if (unlikely(ret))
4487		goto out_handle;
4488
4489	ext4_update_inode_fsync_trans(handle, inode, 1);
4490	if (IS_SYNC(inode))
4491		ext4_handle_sync(handle);
4492out_handle:
4493	ext4_journal_stop(handle);
4494	return ret;
4495}
4496
4497int ext4_inode_attach_jinode(struct inode *inode)
4498{
4499	struct ext4_inode_info *ei = EXT4_I(inode);
4500	struct jbd2_inode *jinode;
4501
4502	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4503		return 0;
4504
4505	jinode = jbd2_alloc_inode(GFP_KERNEL);
4506	spin_lock(&inode->i_lock);
4507	if (!ei->jinode) {
4508		if (!jinode) {
4509			spin_unlock(&inode->i_lock);
4510			return -ENOMEM;
4511		}
4512		jbd2_journal_init_jbd_inode(jinode, inode);
4513		/*
4514		 * Publish ->jinode only after it is fully initialized so that
4515		 * readers never observe a partially initialized jbd2_inode.
4516		 */
4517		smp_wmb();
4518		WRITE_ONCE(ei->jinode, jinode);
4519		jinode = NULL;
4520	}
4521	spin_unlock(&inode->i_lock);
4522	if (unlikely(jinode != NULL))
4523		jbd2_free_inode(jinode);
4524	return 0;
4525}
4526
4527/*
4528 * ext4_truncate()
4529 *
4530 * We block out ext4_get_block() block instantiations across the entire
4531 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4532 * simultaneously on behalf of the same inode.
4533 *
4534 * As we work through the truncate and commit bits of it to the journal there
4535 * is one core, guiding principle: the file's tree must always be consistent on
4536 * disk.  We must be able to restart the truncate after a crash.
4537 *
4538 * The file's tree may be transiently inconsistent in memory (although it
4539 * probably isn't), but whenever we close off and commit a journal transaction,
4540 * the contents of (the filesystem + the journal) must be consistent and
4541 * restartable.  It's pretty simple, really: bottom up, right to left (although
4542 * left-to-right works OK too).
4543 *
4544 * Note that at recovery time, journal replay occurs *before* the restart of
4545 * truncate against the orphan inode list.
4546 *
4547 * The committed inode has the new, desired i_size (which is the same as
4548 * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4549 * that this inode's truncate did not complete and it will again call
4550 * ext4_truncate() to have another go.  So there will be instantiated blocks
4551 * to the right of the truncation point in a crashed ext4 filesystem.  But
4552 * that's fine - as long as they are linked from the inode, the post-crash
4553 * ext4_truncate() run will find them and release them.
4554 */
4555int ext4_truncate(struct inode *inode)
4556{
4557	struct ext4_inode_info *ei = EXT4_I(inode);
4558	unsigned int credits;
4559	int err = 0, err2;
4560	handle_t *handle;
4561	struct address_space *mapping = inode->i_mapping;
4562
4563	/*
4564	 * There is a possibility that we're either freeing the inode
4565	 * or it's a completely new inode. In those cases we might not
4566	 * have i_rwsem locked because it's not necessary.
4567	 */
4568	if (!(inode_state_read_once(inode) & (I_NEW | I_FREEING)))
4569		WARN_ON(!inode_is_locked(inode));
4570	trace_ext4_truncate_enter(inode);
4571
4572	if (!ext4_can_truncate(inode))
4573		goto out_trace;
4574
4575	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4576		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4577
4578	if (ext4_has_inline_data(inode)) {
4579		int has_inline = 1;
4580
4581		err = ext4_inline_data_truncate(inode, &has_inline);
4582		if (err || has_inline)
4583			goto out_trace;
4584	}
4585
4586	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4587	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4588		err = ext4_inode_attach_jinode(inode);
4589		if (err)
4590			goto out_trace;
4591	}
4592
4593	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4594		credits = ext4_chunk_trans_extent(inode, 1);
4595	else
4596		credits = ext4_blocks_for_truncate(inode);
4597
4598	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4599	if (IS_ERR(handle)) {
4600		err = PTR_ERR(handle);
4601		goto out_trace;
4602	}
4603
4604	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4605		ext4_block_truncate_page(handle, mapping, inode->i_size);
4606
4607	/*
4608	 * We add the inode to the orphan list, so that if this
4609	 * truncate spans multiple transactions, and we crash, we will
4610	 * resume the truncate when the filesystem recovers.  It also
4611	 * marks the inode dirty, to catch the new size.
4612	 *
4613	 * Implication: the file must always be in a sane, consistent
4614	 * truncatable state while each transaction commits.
4615	 */
4616	err = ext4_orphan_add(handle, inode);
4617	if (err)
4618		goto out_stop;
4619
4620	ext4_fc_track_inode(handle, inode);
4621	ext4_check_map_extents_env(inode);
4622
4623	down_write(&EXT4_I(inode)->i_data_sem);
4624	ext4_discard_preallocations(inode);
4625
4626	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4627		err = ext4_ext_truncate(handle, inode);
4628	else
4629		ext4_ind_truncate(handle, inode);
4630
4631	up_write(&ei->i_data_sem);
4632	if (err)
4633		goto out_stop;
4634
4635	if (IS_SYNC(inode))
4636		ext4_handle_sync(handle);
4637
4638out_stop:
4639	/*
4640	 * If this was a simple ftruncate() and the file will remain alive,
4641	 * then we need to clear up the orphan record which we created above.
4642	 * However, if this was a real unlink then we were called by
4643	 * ext4_evict_inode(), and we allow that function to clean up the
4644	 * orphan info for us.
4645	 */
4646	if (inode->i_nlink)
4647		ext4_orphan_del(handle, inode);
4648
4649	inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
4650	err2 = ext4_mark_inode_dirty(handle, inode);
4651	if (unlikely(err2 && !err))
4652		err = err2;
4653	ext4_journal_stop(handle);
4654
4655out_trace:
4656	trace_ext4_truncate_exit(inode);
4657	return err;
4658}
4659
4660static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4661{
4662	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4663		return inode_peek_iversion_raw(inode);
4664	else
4665		return inode_peek_iversion(inode);
4666}
4667
4668static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
4669				 struct ext4_inode_info *ei)
4670{
4671	struct inode *inode = &(ei->vfs_inode);
4672	u64 i_blocks = READ_ONCE(inode->i_blocks);
4673	struct super_block *sb = inode->i_sb;
4674
4675	if (i_blocks <= ~0U) {
4676		/*
4677		 * i_blocks can be represented in a 32 bit variable
4678		 * as multiple of 512 bytes
4679		 */
4680		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4681		raw_inode->i_blocks_high = 0;
4682		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4683		return 0;
4684	}
4685
4686	/*
4687	 * This should never happen since sb->s_maxbytes should not have
4688	 * allowed this, sb->s_maxbytes was set according to the huge_file
4689	 * feature in ext4_fill_super().
4690	 */
4691	if (!ext4_has_feature_huge_file(sb))
4692		return -EFSCORRUPTED;
4693
4694	if (i_blocks <= 0xffffffffffffULL) {
4695		/*
4696		 * i_blocks can be represented in a 48 bit variable
4697		 * as multiple of 512 bytes
4698		 */
4699		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4700		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4701		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4702	} else {
4703		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4704		/* i_block is stored in file system block size */
4705		i_blocks = i_blocks >> (inode->i_blkbits - 9);
4706		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4707		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4708	}
4709	return 0;
4710}
4711
4712static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
4713{
4714	struct ext4_inode_info *ei = EXT4_I(inode);
4715	uid_t i_uid;
4716	gid_t i_gid;
4717	projid_t i_projid;
4718	int block;
4719	int err;
4720
4721	err = ext4_inode_blocks_set(raw_inode, ei);
4722
4723	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4724	i_uid = i_uid_read(inode);
4725	i_gid = i_gid_read(inode);
4726	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4727	if (!(test_opt(inode->i_sb, NO_UID32))) {
4728		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4729		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4730		/*
4731		 * Fix up interoperability with old kernels. Otherwise,
4732		 * old inodes get re-used with the upper 16 bits of the
4733		 * uid/gid intact.
4734		 */
4735		if (ei->i_dtime && !ext4_inode_orphan_tracked(inode)) {
4736			raw_inode->i_uid_high = 0;
4737			raw_inode->i_gid_high = 0;
4738		} else {
4739			raw_inode->i_uid_high =
4740				cpu_to_le16(high_16_bits(i_uid));
4741			raw_inode->i_gid_high =
4742				cpu_to_le16(high_16_bits(i_gid));
4743		}
4744	} else {
4745		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4746		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4747		raw_inode->i_uid_high = 0;
4748		raw_inode->i_gid_high = 0;
4749	}
4750	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4751
4752	EXT4_INODE_SET_CTIME(inode, raw_inode);
4753	EXT4_INODE_SET_MTIME(inode, raw_inode);
4754	EXT4_INODE_SET_ATIME(inode, raw_inode);
4755	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4756
4757	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4758	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4759	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4760		raw_inode->i_file_acl_high =
4761			cpu_to_le16(ei->i_file_acl >> 32);
4762	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4763	ext4_isize_set(raw_inode, ei->i_disksize);
4764
4765	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4766	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4767		if (old_valid_dev(inode->i_rdev)) {
4768			raw_inode->i_block[0] =
4769				cpu_to_le32(old_encode_dev(inode->i_rdev));
4770			raw_inode->i_block[1] = 0;
4771		} else {
4772			raw_inode->i_block[0] = 0;
4773			raw_inode->i_block[1] =
4774				cpu_to_le32(new_encode_dev(inode->i_rdev));
4775			raw_inode->i_block[2] = 0;
4776		}
4777	} else if (!ext4_has_inline_data(inode)) {
4778		for (block = 0; block < EXT4_N_BLOCKS; block++)
4779			raw_inode->i_block[block] = ei->i_data[block];
4780	}
4781
4782	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4783		u64 ivers = ext4_inode_peek_iversion(inode);
4784
4785		raw_inode->i_disk_version = cpu_to_le32(ivers);
4786		if (ei->i_extra_isize) {
4787			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4788				raw_inode->i_version_hi =
4789					cpu_to_le32(ivers >> 32);
4790			raw_inode->i_extra_isize =
4791				cpu_to_le16(ei->i_extra_isize);
4792		}
4793	}
4794
4795	if (i_projid != EXT4_DEF_PROJID &&
4796	    !ext4_has_feature_project(inode->i_sb))
4797		err = err ?: -EFSCORRUPTED;
4798
4799	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4800	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4801		raw_inode->i_projid = cpu_to_le32(i_projid);
4802
4803	ext4_inode_csum_set(inode, raw_inode, ei);
4804	return err;
4805}
4806
4807/*
4808 * ext4_get_inode_loc returns with an extra refcount against the inode's
4809 * underlying buffer_head on success. If we pass 'inode' and it does not
4810 * have in-inode xattr, we have all inode data in memory that is needed
4811 * to recreate the on-disk version of this inode.
4812 */
4813static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4814				struct inode *inode, struct ext4_iloc *iloc,
4815				ext4_fsblk_t *ret_block)
4816{
4817	struct ext4_group_desc	*gdp;
4818	struct buffer_head	*bh;
4819	ext4_fsblk_t		block;
4820	struct blk_plug		plug;
4821	int			inodes_per_block, inode_offset;
4822
4823	iloc->bh = NULL;
4824	if (ino < EXT4_ROOT_INO ||
4825	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4826		return -EFSCORRUPTED;
4827
4828	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4829	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4830	if (!gdp)
4831		return -EIO;
4832
4833	/*
4834	 * Figure out the offset within the block group inode table
4835	 */
4836	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4837	inode_offset = ((ino - 1) %
4838			EXT4_INODES_PER_GROUP(sb));
4839	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4840
4841	block = ext4_inode_table(sb, gdp);
4842	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4843	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4844		ext4_error(sb, "Invalid inode table block %llu in "
4845			   "block_group %u", block, iloc->block_group);
4846		return -EFSCORRUPTED;
4847	}
4848	block += (inode_offset / inodes_per_block);
4849
4850	bh = sb_getblk(sb, block);
4851	if (unlikely(!bh))
4852		return -ENOMEM;
4853	if (ext4_buffer_uptodate(bh))
4854		goto has_buffer;
4855
4856	lock_buffer(bh);
4857	if (ext4_buffer_uptodate(bh)) {
4858		/* Someone brought it uptodate while we waited */
4859		unlock_buffer(bh);
4860		goto has_buffer;
4861	}
4862
4863	/*
4864	 * If we have all information of the inode in memory and this
4865	 * is the only valid inode in the block, we need not read the
4866	 * block.
4867	 */
4868	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4869		struct buffer_head *bitmap_bh;
4870		int i, start;
4871
4872		start = inode_offset & ~(inodes_per_block - 1);
4873
4874		/* Is the inode bitmap in cache? */
4875		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4876		if (unlikely(!bitmap_bh))
4877			goto make_io;
4878
4879		/*
4880		 * If the inode bitmap isn't in cache then the
4881		 * optimisation may end up performing two reads instead
4882		 * of one, so skip it.
4883		 */
4884		if (!buffer_uptodate(bitmap_bh)) {
4885			brelse(bitmap_bh);
4886			goto make_io;
4887		}
4888		for (i = start; i < start + inodes_per_block; i++) {
4889			if (i == inode_offset)
4890				continue;
4891			if (ext4_test_bit(i, bitmap_bh->b_data))
4892				break;
4893		}
4894		brelse(bitmap_bh);
4895		if (i == start + inodes_per_block) {
4896			struct ext4_inode *raw_inode =
4897				(struct ext4_inode *) (bh->b_data + iloc->offset);
4898
4899			/* all other inodes are free, so skip I/O */
4900			memset(bh->b_data, 0, bh->b_size);
4901			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4902				ext4_fill_raw_inode(inode, raw_inode);
4903			set_buffer_uptodate(bh);
4904			unlock_buffer(bh);
4905			goto has_buffer;
4906		}
4907	}
4908
4909make_io:
4910	/*
4911	 * If we need to do any I/O, try to pre-readahead extra
4912	 * blocks from the inode table.
4913	 */
4914	blk_start_plug(&plug);
4915	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4916		ext4_fsblk_t b, end, table;
4917		unsigned num;
4918		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4919
4920		table = ext4_inode_table(sb, gdp);
4921		/* s_inode_readahead_blks is always a power of 2 */
4922		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4923		if (table > b)
4924			b = table;
4925		end = b + ra_blks;
4926		num = EXT4_INODES_PER_GROUP(sb);
4927		if (ext4_has_group_desc_csum(sb))
4928			num -= ext4_itable_unused_count(sb, gdp);
4929		table += num / inodes_per_block;
4930		if (end > table)
4931			end = table;
4932		while (b <= end)
4933			ext4_sb_breadahead_unmovable(sb, b++);
4934	}
4935
4936	/*
4937	 * There are other valid inodes in the buffer, this inode
4938	 * has in-inode xattrs, or we don't have this inode in memory.
4939	 * Read the block from disk.
4940	 */
4941	trace_ext4_load_inode(sb, ino);
4942	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL,
4943			    ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO));
4944	blk_finish_plug(&plug);
4945	wait_on_buffer(bh);
4946	if (!buffer_uptodate(bh)) {
4947		if (ret_block)
4948			*ret_block = block;
4949		brelse(bh);
4950		return -EIO;
4951	}
4952has_buffer:
4953	iloc->bh = bh;
4954	return 0;
4955}
4956
4957static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4958					struct ext4_iloc *iloc)
4959{
4960	ext4_fsblk_t err_blk = 0;
4961	int ret;
4962
4963	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
4964					&err_blk);
4965
4966	if (ret == -EIO)
4967		ext4_error_inode_block(inode, err_blk, EIO,
4968					"unable to read itable block");
4969
4970	return ret;
4971}
4972
4973int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4974{
4975	ext4_fsblk_t err_blk = 0;
4976	int ret;
4977
4978	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4979					&err_blk);
4980
4981	if (ret == -EIO)
4982		ext4_error_inode_block(inode, err_blk, EIO,
4983					"unable to read itable block");
4984
4985	return ret;
4986}
4987
4988
4989int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4990			  struct ext4_iloc *iloc)
4991{
4992	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4993}
4994
4995static bool ext4_should_enable_dax(struct inode *inode)
4996{
4997	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4998
4999	if (test_opt2(inode->i_sb, DAX_NEVER))
5000		return false;
5001	if (!S_ISREG(inode->i_mode))
5002		return false;
5003	if (ext4_should_journal_data(inode))
5004		return false;
5005	if (ext4_has_inline_data(inode))
5006		return false;
5007	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
5008		return false;
5009	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
5010		return false;
5011	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
5012		return false;
5013	if (test_opt(inode->i_sb, DAX_ALWAYS))
5014		return true;
5015
5016	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
5017}
5018
5019void ext4_set_inode_flags(struct inode *inode, bool init)
5020{
5021	unsigned int flags = EXT4_I(inode)->i_flags;
5022	unsigned int new_fl = 0;
5023
5024	WARN_ON_ONCE(IS_DAX(inode) && init);
5025
5026	if (flags & EXT4_SYNC_FL)
5027		new_fl |= S_SYNC;
5028	if (flags & EXT4_APPEND_FL)
5029		new_fl |= S_APPEND;
5030	if (flags & EXT4_IMMUTABLE_FL)
5031		new_fl |= S_IMMUTABLE;
5032	if (flags & EXT4_NOATIME_FL)
5033		new_fl |= S_NOATIME;
5034	if (flags & EXT4_DIRSYNC_FL)
5035		new_fl |= S_DIRSYNC;
5036
5037	/* Because of the way inode_set_flags() works we must preserve S_DAX
5038	 * here if already set. */
5039	new_fl |= (inode->i_flags & S_DAX);
5040	if (init && ext4_should_enable_dax(inode))
5041		new_fl |= S_DAX;
5042
5043	if (flags & EXT4_ENCRYPT_FL)
5044		new_fl |= S_ENCRYPTED;
5045	if (flags & EXT4_CASEFOLD_FL)
5046		new_fl |= S_CASEFOLD;
5047	if (flags & EXT4_VERITY_FL)
5048		new_fl |= S_VERITY;
5049	inode_set_flags(inode, new_fl,
5050			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
5051			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
5052}
5053
5054static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
5055				  struct ext4_inode_info *ei)
5056{
5057	blkcnt_t i_blocks ;
5058	struct inode *inode = &(ei->vfs_inode);
5059	struct super_block *sb = inode->i_sb;
5060
5061	if (ext4_has_feature_huge_file(sb)) {
5062		/* we are using combined 48 bit field */
5063		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
5064					le32_to_cpu(raw_inode->i_blocks_lo);
5065		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
5066			/* i_blocks represent file system block size */
5067			return i_blocks  << (inode->i_blkbits - 9);
5068		} else {
5069			return i_blocks;
5070		}
5071	} else {
5072		return le32_to_cpu(raw_inode->i_blocks_lo);
5073	}
5074}
5075
5076static inline int ext4_iget_extra_inode(struct inode *inode,
5077					 struct ext4_inode *raw_inode,
5078					 struct ext4_inode_info *ei)
5079{
5080	__le32 *magic = (void *)raw_inode +
5081			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
5082
5083	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
5084	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
5085		int err;
5086
5087		err = xattr_check_inode(inode, IHDR(inode, raw_inode),
5088					ITAIL(inode, raw_inode));
5089		if (err)
5090			return err;
5091
5092		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
5093		err = ext4_find_inline_data_nolock(inode);
5094		if (!err && ext4_has_inline_data(inode))
5095			ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
5096		return err;
5097	} else
5098		EXT4_I(inode)->i_inline_off = 0;
5099	return 0;
5100}
5101
5102int ext4_get_projid(struct inode *inode, kprojid_t *projid)
5103{
5104	if (!ext4_has_feature_project(inode->i_sb))
5105		return -EOPNOTSUPP;
5106	*projid = EXT4_I(inode)->i_projid;
5107	return 0;
5108}
5109
5110/*
5111 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
5112 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
5113 * set.
5114 */
5115static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
5116{
5117	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
5118		inode_set_iversion_raw(inode, val);
5119	else
5120		inode_set_iversion_queried(inode, val);
5121}
5122
5123static int check_igot_inode(struct inode *inode, ext4_iget_flags flags,
5124			    const char *function, unsigned int line)
5125{
5126	const char *err_str;
5127
5128	if (flags & EXT4_IGET_EA_INODE) {
5129		if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
5130			err_str = "missing EA_INODE flag";
5131			goto error;
5132		}
5133		if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5134		    EXT4_I(inode)->i_file_acl) {
5135			err_str = "ea_inode with extended attributes";
5136			goto error;
5137		}
5138	} else {
5139		if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
5140			/*
5141			 * open_by_handle_at() could provide an old inode number
5142			 * that has since been reused for an ea_inode; this does
5143			 * not indicate filesystem corruption
5144			 */
5145			if (flags & EXT4_IGET_HANDLE)
5146				return -ESTALE;
5147			err_str = "unexpected EA_INODE flag";
5148			goto error;
5149		}
5150	}
5151	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD)) {
5152		err_str = "unexpected bad inode w/o EXT4_IGET_BAD";
5153		goto error;
5154	}
5155	return 0;
5156
5157error:
5158	ext4_error_inode(inode, function, line, 0, "%s", err_str);
5159	return -EFSCORRUPTED;
5160}
5161
5162void ext4_set_inode_mapping_order(struct inode *inode)
5163{
5164	struct super_block *sb = inode->i_sb;
5165	u16 min_order, max_order;
5166
5167	max_order = EXT4_SB(sb)->s_max_folio_order;
5168	if (!max_order)
5169		return;
5170
5171	min_order = EXT4_SB(sb)->s_min_folio_order;
5172	if (!min_order && !S_ISREG(inode->i_mode))
5173		return;
5174
5175	if (ext4_test_inode_flag(inode, EXT4_INODE_JOURNAL_DATA))
5176		max_order = min_order;
5177
5178	mapping_set_folio_order_range(inode->i_mapping, min_order, max_order);
5179}
5180
5181struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
5182			  ext4_iget_flags flags, const char *function,
5183			  unsigned int line)
5184{
5185	struct ext4_iloc iloc;
5186	struct ext4_inode *raw_inode;
5187	struct ext4_inode_info *ei;
5188	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
5189	struct inode *inode;
5190	journal_t *journal = EXT4_SB(sb)->s_journal;
5191	long ret;
5192	loff_t size;
5193	int block;
5194	uid_t i_uid;
5195	gid_t i_gid;
5196	projid_t i_projid;
5197
5198	if ((!(flags & EXT4_IGET_SPECIAL) && is_special_ino(sb, ino)) ||
5199	    (ino < EXT4_ROOT_INO) ||
5200	    (ino > le32_to_cpu(es->s_inodes_count))) {
5201		if (flags & EXT4_IGET_HANDLE)
5202			return ERR_PTR(-ESTALE);
5203		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
5204			     "inode #%lu: comm %s: iget: illegal inode #",
5205			     ino, current->comm);
5206		return ERR_PTR(-EFSCORRUPTED);
5207	}
5208
5209	inode = iget_locked(sb, ino);
5210	if (!inode)
5211		return ERR_PTR(-ENOMEM);
5212	if (!(inode_state_read_once(inode) & I_NEW)) {
5213		ret = check_igot_inode(inode, flags, function, line);
5214		if (ret) {
5215			iput(inode);
5216			return ERR_PTR(ret);
5217		}
5218		return inode;
5219	}
5220
5221	ei = EXT4_I(inode);
5222	iloc.bh = NULL;
5223
5224	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
5225	if (ret < 0)
5226		goto bad_inode;
5227	raw_inode = ext4_raw_inode(&iloc);
5228
5229	if ((flags & EXT4_IGET_HANDLE) &&
5230	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
5231		ret = -ESTALE;
5232		goto bad_inode;
5233	}
5234
5235	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5236		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
5237		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
5238			EXT4_INODE_SIZE(inode->i_sb) ||
5239		    (ei->i_extra_isize & 3)) {
5240			ext4_error_inode(inode, function, line, 0,
5241					 "iget: bad extra_isize %u "
5242					 "(inode size %u)",
5243					 ei->i_extra_isize,
5244					 EXT4_INODE_SIZE(inode->i_sb));
5245			ret = -EFSCORRUPTED;
5246			goto bad_inode;
5247		}
5248	} else
5249		ei->i_extra_isize = 0;
5250
5251	/* Precompute checksum seed for inode metadata */
5252	if (ext4_has_feature_metadata_csum(sb)) {
5253		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5254		__u32 csum;
5255		__le32 inum = cpu_to_le32(inode->i_ino);
5256		__le32 gen = raw_inode->i_generation;
5257		csum = ext4_chksum(sbi->s_csum_seed, (__u8 *)&inum,
5258				   sizeof(inum));
5259		ei->i_csum_seed = ext4_chksum(csum, (__u8 *)&gen, sizeof(gen));
5260	}
5261
5262	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
5263	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
5264	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
5265		ext4_error_inode_err(inode, function, line, 0,
5266				EFSBADCRC, "iget: checksum invalid");
5267		ret = -EFSBADCRC;
5268		goto bad_inode;
5269	}
5270
5271	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
5272	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
5273	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
5274	if (ext4_has_feature_project(sb) &&
5275	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5276	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5277		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
5278	else
5279		i_projid = EXT4_DEF_PROJID;
5280
5281	if (!(test_opt(inode->i_sb, NO_UID32))) {
5282		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
5283		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
5284	}
5285	i_uid_write(inode, i_uid);
5286	i_gid_write(inode, i_gid);
5287	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
5288	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
5289
5290	ei->i_inline_off = 0;
5291	ei->i_dir_start_lookup = 0;
5292	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
5293	/* We now have enough fields to check if the inode was active or not.
5294	 * This is needed because nfsd might try to access dead inodes
5295	 * the test is that same one that e2fsck uses
5296	 * NeilBrown 1999oct15
5297	 */
5298	if (inode->i_nlink == 0) {
5299		if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
5300		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
5301		    ino != EXT4_BOOT_LOADER_INO) {
5302			/* this inode is deleted or unallocated */
5303			if (flags & EXT4_IGET_SPECIAL) {
5304				ext4_error_inode(inode, function, line, 0,
5305						 "iget: special inode unallocated");
5306				ret = -EFSCORRUPTED;
5307			} else
5308				ret = -ESTALE;
5309			goto bad_inode;
5310		}
5311		/* The only unlinked inodes we let through here have
5312		 * valid i_mode and are being read by the orphan
5313		 * recovery code: that's fine, we're about to complete
5314		 * the process of deleting those.
5315		 * OR it is the EXT4_BOOT_LOADER_INO which is
5316		 * not initialized on a new filesystem. */
5317	}
5318	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
5319	ext4_set_inode_flags(inode, true);
5320	/* Detect invalid flag combination - can't have both inline data and extents */
5321	if (ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA) &&
5322	    ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5323		ext4_error_inode(inode, function, line, 0,
5324			"inode has both inline data and extents flags");
5325		ret = -EFSCORRUPTED;
5326		goto bad_inode;
5327	}
5328	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
5329	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
5330	if (ext4_has_feature_64bit(sb))
5331		ei->i_file_acl |=
5332			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
5333	inode->i_size = ext4_isize(sb, raw_inode);
5334	size = i_size_read(inode);
5335	if (size < 0 || size > ext4_get_maxbytes(inode)) {
5336		ext4_error_inode(inode, function, line, 0,
5337				 "iget: bad i_size value: %lld", size);
5338		ret = -EFSCORRUPTED;
5339		goto bad_inode;
5340	}
5341	/*
5342	 * If dir_index is not enabled but there's dir with INDEX flag set,
5343	 * we'd normally treat htree data as empty space. But with metadata
5344	 * checksumming that corrupts checksums so forbid that.
5345	 */
5346	if (!ext4_has_feature_dir_index(sb) &&
5347	    ext4_has_feature_metadata_csum(sb) &&
5348	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
5349		ext4_error_inode(inode, function, line, 0,
5350			 "iget: Dir with htree data on filesystem without dir_index feature.");
5351		ret = -EFSCORRUPTED;
5352		goto bad_inode;
5353	}
5354	ei->i_disksize = inode->i_size;
5355#ifdef CONFIG_QUOTA
5356	ei->i_reserved_quota = 0;
5357#endif
5358	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
5359	ei->i_block_group = iloc.block_group;
5360	ei->i_last_alloc_group = ~0;
5361	/*
5362	 * NOTE! The in-memory inode i_data array is in little-endian order
5363	 * even on big-endian machines: we do NOT byteswap the block numbers!
5364	 */
5365	for (block = 0; block < EXT4_N_BLOCKS; block++)
5366		ei->i_data[block] = raw_inode->i_block[block];
5367	INIT_LIST_HEAD(&ei->i_orphan);
5368	ext4_fc_init_inode(&ei->vfs_inode);
5369
5370	/*
5371	 * Set transaction id's of transactions that have to be committed
5372	 * to finish f[data]sync. We set them to currently running transaction
5373	 * as we cannot be sure that the inode or some of its metadata isn't
5374	 * part of the transaction - the inode could have been reclaimed and
5375	 * now it is reread from disk.
5376	 */
5377	if (journal) {
5378		transaction_t *transaction;
5379		tid_t tid;
5380
5381		read_lock(&journal->j_state_lock);
5382		if (journal->j_running_transaction)
5383			transaction = journal->j_running_transaction;
5384		else
5385			transaction = journal->j_committing_transaction;
5386		if (transaction)
5387			tid = transaction->t_tid;
5388		else
5389			tid = journal->j_commit_sequence;
5390		read_unlock(&journal->j_state_lock);
5391		ei->i_sync_tid = tid;
5392		ei->i_datasync_tid = tid;
5393	}
5394
5395	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5396		if (ei->i_extra_isize == 0) {
5397			/* The extra space is currently unused. Use it. */
5398			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
5399			ei->i_extra_isize = sizeof(struct ext4_inode) -
5400					    EXT4_GOOD_OLD_INODE_SIZE;
5401		} else {
5402			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
5403			if (ret)
5404				goto bad_inode;
5405		}
5406	}
5407
5408	EXT4_INODE_GET_CTIME(inode, raw_inode);
5409	EXT4_INODE_GET_ATIME(inode, raw_inode);
5410	EXT4_INODE_GET_MTIME(inode, raw_inode);
5411	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5412
5413	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5414		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
5415
5416		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5417			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5418				ivers |=
5419		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5420		}
5421		ext4_inode_set_iversion_queried(inode, ivers);
5422	}
5423
5424	ret = 0;
5425	if (ei->i_file_acl &&
5426	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
5427		ext4_error_inode(inode, function, line, 0,
5428				 "iget: bad extended attribute block %llu",
5429				 ei->i_file_acl);
5430		ret = -EFSCORRUPTED;
5431		goto bad_inode;
5432	} else if (!ext4_has_inline_data(inode)) {
5433		/* validate the block references in the inode */
5434		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
5435			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5436			(S_ISLNK(inode->i_mode) &&
5437			!ext4_inode_is_fast_symlink(inode)))) {
5438			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5439				ret = ext4_ext_check_inode(inode);
5440			else
5441				ret = ext4_ind_check_inode(inode);
5442		}
5443	}
5444	if (ret)
5445		goto bad_inode;
5446
5447	if (S_ISREG(inode->i_mode)) {
5448		inode->i_op = &ext4_file_inode_operations;
5449		inode->i_fop = &ext4_file_operations;
5450		ext4_set_aops(inode);
5451	} else if (S_ISDIR(inode->i_mode)) {
5452		inode->i_op = &ext4_dir_inode_operations;
5453		inode->i_fop = &ext4_dir_operations;
5454	} else if (S_ISLNK(inode->i_mode)) {
5455		/* VFS does not allow setting these so must be corruption */
5456		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
5457			ext4_error_inode(inode, function, line, 0,
5458					 "iget: immutable or append flags "
5459					 "not allowed on symlinks");
5460			ret = -EFSCORRUPTED;
5461			goto bad_inode;
5462		}
5463		if (IS_ENCRYPTED(inode)) {
5464			inode->i_op = &ext4_encrypted_symlink_inode_operations;
5465		} else if (ext4_inode_is_fast_symlink(inode)) {
5466			inode->i_op = &ext4_fast_symlink_inode_operations;
5467
5468			/*
5469			 * Orphan cleanup can see inodes with i_size == 0
5470			 * and i_data uninitialized. Skip size checks in
5471			 * that case. This is safe because the first thing
5472			 * ext4_evict_inode() does for fast symlinks is
5473			 * clearing of i_data and i_size.
5474			 */
5475			if ((EXT4_SB(sb)->s_mount_state & EXT4_ORPHAN_FS)) {
5476				if (inode->i_nlink != 0) {
5477					ext4_error_inode(inode, function, line, 0,
5478						"invalid orphan symlink nlink %d",
5479						inode->i_nlink);
5480					ret = -EFSCORRUPTED;
5481					goto bad_inode;
5482				}
5483			} else {
5484				if (inode->i_size == 0 ||
5485				    inode->i_size >= sizeof(ei->i_data) ||
5486				    strnlen((char *)ei->i_data, inode->i_size + 1) !=
5487						inode->i_size) {
5488					ext4_error_inode(inode, function, line, 0,
5489						"invalid fast symlink length %llu",
5490						(unsigned long long)inode->i_size);
5491					ret = -EFSCORRUPTED;
5492					goto bad_inode;
5493				}
5494				inode_set_cached_link(inode, (char *)ei->i_data,
5495						      inode->i_size);
5496			}
5497		} else {
5498			inode->i_op = &ext4_symlink_inode_operations;
5499		}
5500	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5501	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5502		inode->i_op = &ext4_special_inode_operations;
5503		if (raw_inode->i_block[0])
5504			init_special_inode(inode, inode->i_mode,
5505			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5506		else
5507			init_special_inode(inode, inode->i_mode,
5508			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5509	} else if (ino == EXT4_BOOT_LOADER_INO) {
5510		make_bad_inode(inode);
5511	} else {
5512		ret = -EFSCORRUPTED;
5513		ext4_error_inode(inode, function, line, 0,
5514				 "iget: bogus i_mode (%o)", inode->i_mode);
5515		goto bad_inode;
5516	}
5517	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
5518		ext4_error_inode(inode, function, line, 0,
5519				 "casefold flag without casefold feature");
5520		ret = -EFSCORRUPTED;
5521		goto bad_inode;
5522	}
5523
5524	ext4_set_inode_mapping_order(inode);
5525
5526	ret = check_igot_inode(inode, flags, function, line);
5527	/*
5528	 * -ESTALE here means there is nothing inherently wrong with the inode,
5529	 * it's just not an inode we can return for an fhandle lookup.
5530	 */
5531	if (ret == -ESTALE) {
5532		brelse(iloc.bh);
5533		unlock_new_inode(inode);
5534		iput(inode);
5535		return ERR_PTR(-ESTALE);
5536	}
5537	if (ret)
5538		goto bad_inode;
5539	brelse(iloc.bh);
5540	/* Initialize the "no ACL's" state for the simple cases */
5541	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) && !ei->i_file_acl)
5542		cache_no_acl(inode);
5543	unlock_new_inode(inode);
5544	return inode;
5545
5546bad_inode:
5547	brelse(iloc.bh);
5548	iget_failed(inode);
5549	return ERR_PTR(ret);
5550}
5551
5552static void __ext4_update_other_inode_time(struct super_block *sb,
5553					   unsigned long orig_ino,
5554					   unsigned long ino,
5555					   struct ext4_inode *raw_inode)
5556{
5557	struct inode *inode;
5558
5559	inode = find_inode_by_ino_rcu(sb, ino);
5560	if (!inode)
5561		return;
5562
5563	if (!inode_is_dirtytime_only(inode))
5564		return;
5565
5566	spin_lock(&inode->i_lock);
5567	if (inode_is_dirtytime_only(inode)) {
5568		struct ext4_inode_info	*ei = EXT4_I(inode);
5569
5570		inode_state_clear(inode, I_DIRTY_TIME);
5571		spin_unlock(&inode->i_lock);
5572
5573		spin_lock(&ei->i_raw_lock);
5574		EXT4_INODE_SET_CTIME(inode, raw_inode);
5575		EXT4_INODE_SET_MTIME(inode, raw_inode);
5576		EXT4_INODE_SET_ATIME(inode, raw_inode);
5577		ext4_inode_csum_set(inode, raw_inode, ei);
5578		spin_unlock(&ei->i_raw_lock);
5579		trace_ext4_other_inode_update_time(inode, orig_ino);
5580		return;
5581	}
5582	spin_unlock(&inode->i_lock);
5583}
5584
5585/*
5586 * Opportunistically update the other time fields for other inodes in
5587 * the same inode table block.
5588 */
5589static void ext4_update_other_inodes_time(struct super_block *sb,
5590					  unsigned long orig_ino, char *buf)
5591{
5592	unsigned long ino;
5593	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5594	int inode_size = EXT4_INODE_SIZE(sb);
5595
5596	/*
5597	 * Calculate the first inode in the inode table block.  Inode
5598	 * numbers are one-based.  That is, the first inode in a block
5599	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5600	 */
5601	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5602	rcu_read_lock();
5603	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5604		if (ino == orig_ino)
5605			continue;
5606		__ext4_update_other_inode_time(sb, orig_ino, ino,
5607					       (struct ext4_inode *)buf);
5608	}
5609	rcu_read_unlock();
5610}
5611
5612/*
5613 * Post the struct inode info into an on-disk inode location in the
5614 * buffer-cache.  This gobbles the caller's reference to the
5615 * buffer_head in the inode location struct.
5616 *
5617 * The caller must have write access to iloc->bh.
5618 */
5619static int ext4_do_update_inode(handle_t *handle,
5620				struct inode *inode,
5621				struct ext4_iloc *iloc)
5622{
5623	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5624	struct ext4_inode_info *ei = EXT4_I(inode);
5625	struct buffer_head *bh = iloc->bh;
5626	struct super_block *sb = inode->i_sb;
5627	int err;
5628	int need_datasync = 0, set_large_file = 0;
5629
5630	spin_lock(&ei->i_raw_lock);
5631
5632	/*
5633	 * For fields not tracked in the in-memory inode, initialise them
5634	 * to zero for new inodes.
5635	 */
5636	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5637		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5638
5639	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5640		need_datasync = 1;
5641	if (ei->i_disksize > 0x7fffffffULL) {
5642		if (!ext4_has_feature_large_file(sb) ||
5643		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5644			set_large_file = 1;
5645	}
5646
5647	err = ext4_fill_raw_inode(inode, raw_inode);
5648	spin_unlock(&ei->i_raw_lock);
5649	if (err) {
5650		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5651		goto out_brelse;
5652	}
5653
5654	if (inode->i_sb->s_flags & SB_LAZYTIME)
5655		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5656					      bh->b_data);
5657
5658	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5659	err = ext4_handle_dirty_metadata(handle, NULL, bh);
5660	if (err)
5661		goto out_error;
5662	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5663	if (set_large_file) {
5664		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5665		err = ext4_journal_get_write_access(handle, sb,
5666						    EXT4_SB(sb)->s_sbh,
5667						    EXT4_JTR_NONE);
5668		if (err)
5669			goto out_error;
5670		lock_buffer(EXT4_SB(sb)->s_sbh);
5671		ext4_set_feature_large_file(sb);
5672		ext4_superblock_csum_set(sb);
5673		unlock_buffer(EXT4_SB(sb)->s_sbh);
5674		ext4_handle_sync(handle);
5675		err = ext4_handle_dirty_metadata(handle, NULL,
5676						 EXT4_SB(sb)->s_sbh);
5677	}
5678	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5679out_error:
5680	ext4_std_error(inode->i_sb, err);
5681out_brelse:
5682	brelse(bh);
5683	return err;
5684}
5685
5686/*
5687 * ext4_write_inode()
5688 *
5689 * We are called from a few places:
5690 *
5691 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5692 *   Here, there will be no transaction running. We wait for any running
5693 *   transaction to commit.
5694 *
5695 * - Within flush work (sys_sync(), kupdate and such).
5696 *   We wait on commit, if told to.
5697 *
5698 * - Within iput_final() -> write_inode_now()
5699 *   We wait on commit, if told to.
5700 *
5701 * In all cases it is actually safe for us to return without doing anything,
5702 * because the inode has been copied into a raw inode buffer in
5703 * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
5704 * writeback.
5705 *
5706 * Note that we are absolutely dependent upon all inode dirtiers doing the
5707 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5708 * which we are interested.
5709 *
5710 * It would be a bug for them to not do this.  The code:
5711 *
5712 *	mark_inode_dirty(inode)
5713 *	stuff();
5714 *	inode->i_size = expr;
5715 *
5716 * is in error because write_inode() could occur while `stuff()' is running,
5717 * and the new i_size will be lost.  Plus the inode will no longer be on the
5718 * superblock's dirty inode list.
5719 */
5720int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5721{
5722	int err;
5723
5724	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5725		return 0;
5726
5727	err = ext4_emergency_state(inode->i_sb);
5728	if (unlikely(err))
5729		return err;
5730
5731	if (EXT4_SB(inode->i_sb)->s_journal) {
5732		if (ext4_journal_current_handle()) {
5733			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5734			dump_stack();
5735			return -EIO;
5736		}
5737
5738		/*
5739		 * No need to force transaction in WB_SYNC_NONE mode. Also
5740		 * ext4_sync_fs() will force the commit after everything is
5741		 * written.
5742		 */
5743		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5744			return 0;
5745
5746		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5747						EXT4_I(inode)->i_sync_tid);
5748	} else {
5749		struct ext4_iloc iloc;
5750
5751		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5752		if (err)
5753			return err;
5754		/*
5755		 * sync(2) will flush the whole buffer cache. No need to do
5756		 * it here separately for each inode.
5757		 */
5758		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5759			sync_dirty_buffer(iloc.bh);
5760		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5761			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5762					       "IO error syncing inode");
5763			err = -EIO;
5764		}
5765		brelse(iloc.bh);
5766	}
5767	return err;
5768}
5769
5770/*
5771 * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5772 * buffers that are attached to a folio straddling i_size and are undergoing
5773 * commit. In that case we have to wait for commit to finish and try again.
5774 */
5775static void ext4_wait_for_tail_page_commit(struct inode *inode)
5776{
5777	unsigned offset;
5778	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5779	tid_t commit_tid;
5780	int ret;
5781	bool has_transaction;
5782
5783	offset = inode->i_size & (PAGE_SIZE - 1);
5784	/*
5785	 * If the folio is fully truncated, we don't need to wait for any commit
5786	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5787	 * strip all buffers from the folio but keep the folio dirty which can then
5788	 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5789	 * buffers). Also we don't need to wait for any commit if all buffers in
5790	 * the folio remain valid. This is most beneficial for the common case of
5791	 * blocksize == PAGESIZE.
5792	 */
5793	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5794		return;
5795	while (1) {
5796		struct folio *folio = filemap_lock_folio(inode->i_mapping,
5797				      inode->i_size >> PAGE_SHIFT);
5798		if (IS_ERR(folio))
5799			return;
5800		ret = __ext4_journalled_invalidate_folio(folio, offset,
5801						folio_size(folio) - offset);
5802		folio_unlock(folio);
5803		folio_put(folio);
5804		if (ret != -EBUSY)
5805			return;
5806		has_transaction = false;
5807		read_lock(&journal->j_state_lock);
5808		if (journal->j_committing_transaction) {
5809			commit_tid = journal->j_committing_transaction->t_tid;
5810			has_transaction = true;
5811		}
5812		read_unlock(&journal->j_state_lock);
5813		if (has_transaction)
5814			jbd2_log_wait_commit(journal, commit_tid);
5815	}
5816}
5817
5818/*
5819 * ext4_setattr()
5820 *
5821 * Called from notify_change.
5822 *
5823 * We want to trap VFS attempts to truncate the file as soon as
5824 * possible.  In particular, we want to make sure that when the VFS
5825 * shrinks i_size, we put the inode on the orphan list and modify
5826 * i_disksize immediately, so that during the subsequent flushing of
5827 * dirty pages and freeing of disk blocks, we can guarantee that any
5828 * commit will leave the blocks being flushed in an unused state on
5829 * disk.  (On recovery, the inode will get truncated and the blocks will
5830 * be freed, so we have a strong guarantee that no future commit will
5831 * leave these blocks visible to the user.)
5832 *
5833 * Another thing we have to assure is that if we are in ordered mode
5834 * and inode is still attached to the committing transaction, we must
5835 * we start writeout of all the dirty pages which are being truncated.
5836 * This way we are sure that all the data written in the previous
5837 * transaction are already on disk (truncate waits for pages under
5838 * writeback).
5839 *
5840 * Called with inode->i_rwsem down.
5841 */
5842int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5843		 struct iattr *attr)
5844{
5845	struct inode *inode = d_inode(dentry);
5846	int error, rc = 0;
5847	int orphan = 0;
5848	const unsigned int ia_valid = attr->ia_valid;
5849	bool inc_ivers = true;
5850
5851	error = ext4_emergency_state(inode->i_sb);
5852	if (unlikely(error))
5853		return error;
5854
5855	if (unlikely(IS_IMMUTABLE(inode)))
5856		return -EPERM;
5857
5858	if (unlikely(IS_APPEND(inode) &&
5859		     (ia_valid & (ATTR_MODE | ATTR_UID |
5860				  ATTR_GID | ATTR_TIMES_SET))))
5861		return -EPERM;
5862
5863	error = setattr_prepare(idmap, dentry, attr);
5864	if (error)
5865		return error;
5866
5867	error = fscrypt_prepare_setattr(dentry, attr);
5868	if (error)
5869		return error;
5870
5871	error = fsverity_prepare_setattr(dentry, attr);
5872	if (error)
5873		return error;
5874
5875	if (is_quota_modification(idmap, inode, attr)) {
5876		error = dquot_initialize(inode);
5877		if (error)
5878			return error;
5879	}
5880
5881	if (i_uid_needs_update(idmap, attr, inode) ||
5882	    i_gid_needs_update(idmap, attr, inode)) {
5883		handle_t *handle;
5884
5885		/* (user+group)*(old+new) structure, inode write (sb,
5886		 * inode block, ? - but truncate inode update has it) */
5887		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5888			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5889			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5890		if (IS_ERR(handle)) {
5891			error = PTR_ERR(handle);
5892			goto err_out;
5893		}
5894
5895		/* dquot_transfer() calls back ext4_get_inode_usage() which
5896		 * counts xattr inode references.
5897		 */
5898		down_read(&EXT4_I(inode)->xattr_sem);
5899		error = dquot_transfer(idmap, inode, attr);
5900		up_read(&EXT4_I(inode)->xattr_sem);
5901
5902		if (error) {
5903			ext4_journal_stop(handle);
5904			return error;
5905		}
5906		/* Update corresponding info in inode so that everything is in
5907		 * one transaction */
5908		i_uid_update(idmap, attr, inode);
5909		i_gid_update(idmap, attr, inode);
5910		error = ext4_mark_inode_dirty(handle, inode);
5911		ext4_journal_stop(handle);
5912		if (unlikely(error)) {
5913			return error;
5914		}
5915	}
5916
5917	if (attr->ia_valid & ATTR_SIZE) {
5918		handle_t *handle;
5919		loff_t oldsize = inode->i_size;
5920		loff_t old_disksize;
5921		int shrink = (attr->ia_size < inode->i_size);
5922
5923		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5924			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5925
5926			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5927				return -EFBIG;
5928			}
5929		}
5930		if (!S_ISREG(inode->i_mode)) {
5931			return -EINVAL;
5932		}
5933
5934		if (attr->ia_size == inode->i_size)
5935			inc_ivers = false;
5936
5937		/*
5938		 * If file has inline data but new size exceeds inline capacity,
5939		 * convert to extent-based storage first to prevent inconsistent
5940		 * state (inline flag set but size exceeds inline capacity).
5941		 */
5942		if (ext4_has_inline_data(inode) &&
5943		    attr->ia_size > EXT4_I(inode)->i_inline_size) {
5944			error = ext4_convert_inline_data(inode);
5945			if (error)
5946				goto err_out;
5947		}
5948
5949		if (shrink) {
5950			if (ext4_should_order_data(inode)) {
5951				error = ext4_begin_ordered_truncate(inode,
5952							    attr->ia_size);
5953				if (error)
5954					goto err_out;
5955			}
5956			/*
5957			 * Blocks are going to be removed from the inode. Wait
5958			 * for dio in flight.
5959			 */
5960			inode_dio_wait(inode);
5961		}
5962
5963		filemap_invalidate_lock(inode->i_mapping);
5964
5965		rc = ext4_break_layouts(inode);
5966		if (rc) {
5967			filemap_invalidate_unlock(inode->i_mapping);
5968			goto err_out;
5969		}
5970
5971		if (attr->ia_size != inode->i_size) {
5972			/* attach jbd2 jinode for EOF folio tail zeroing */
5973			if (attr->ia_size & (inode->i_sb->s_blocksize - 1) ||
5974			    oldsize & (inode->i_sb->s_blocksize - 1)) {
5975				error = ext4_inode_attach_jinode(inode);
5976				if (error)
5977					goto out_mmap_sem;
5978			}
5979
5980			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5981			if (IS_ERR(handle)) {
5982				error = PTR_ERR(handle);
5983				goto out_mmap_sem;
5984			}
5985			if (ext4_handle_valid(handle) && shrink) {
5986				error = ext4_orphan_add(handle, inode);
5987				orphan = 1;
5988			}
5989			/*
5990			 * Update c/mtime and tail zero the EOF folio on
5991			 * truncate up. ext4_truncate() handles the shrink case
5992			 * below.
5993			 */
5994			if (!shrink) {
5995				inode_set_mtime_to_ts(inode,
5996						      inode_set_ctime_current(inode));
5997				if (oldsize & (inode->i_sb->s_blocksize - 1))
5998					ext4_block_truncate_page(handle,
5999							inode->i_mapping, oldsize);
6000			}
6001
6002			if (shrink)
6003				ext4_fc_track_range(handle, inode,
6004					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
6005					inode->i_sb->s_blocksize_bits,
6006					EXT_MAX_BLOCKS - 1);
6007			else
6008				ext4_fc_track_range(
6009					handle, inode,
6010					(oldsize > 0 ? oldsize - 1 : oldsize) >>
6011					inode->i_sb->s_blocksize_bits,
6012					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
6013					inode->i_sb->s_blocksize_bits);
6014
6015			down_write(&EXT4_I(inode)->i_data_sem);
6016			old_disksize = EXT4_I(inode)->i_disksize;
6017			EXT4_I(inode)->i_disksize = attr->ia_size;
6018
6019			/*
6020			 * We have to update i_size under i_data_sem together
6021			 * with i_disksize to avoid races with writeback code
6022			 * running ext4_wb_update_i_disksize().
6023			 */
6024			if (!error)
6025				i_size_write(inode, attr->ia_size);
6026			else
6027				EXT4_I(inode)->i_disksize = old_disksize;
6028			up_write(&EXT4_I(inode)->i_data_sem);
6029			rc = ext4_mark_inode_dirty(handle, inode);
6030			if (!error)
6031				error = rc;
6032			ext4_journal_stop(handle);
6033			if (error)
6034				goto out_mmap_sem;
6035			if (!shrink) {
6036				pagecache_isize_extended(inode, oldsize,
6037							 inode->i_size);
6038			} else if (ext4_should_journal_data(inode)) {
6039				ext4_wait_for_tail_page_commit(inode);
6040			}
6041		}
6042
6043		/*
6044		 * Truncate pagecache after we've waited for commit
6045		 * in data=journal mode to make pages freeable.
6046		 */
6047		truncate_pagecache(inode, inode->i_size);
6048		/*
6049		 * Call ext4_truncate() even if i_size didn't change to
6050		 * truncate possible preallocated blocks.
6051		 */
6052		if (attr->ia_size <= oldsize) {
6053			rc = ext4_truncate(inode);
6054			if (rc)
6055				error = rc;
6056		}
6057out_mmap_sem:
6058		filemap_invalidate_unlock(inode->i_mapping);
6059	}
6060
6061	if (!error) {
6062		if (inc_ivers)
6063			inode_inc_iversion(inode);
6064		setattr_copy(idmap, inode, attr);
6065		mark_inode_dirty(inode);
6066	}
6067
6068	/*
6069	 * If the call to ext4_truncate failed to get a transaction handle at
6070	 * all, we need to clean up the in-core orphan list manually.
6071	 */
6072	if (orphan && inode->i_nlink)
6073		ext4_orphan_del(NULL, inode);
6074
6075	if (!error && (ia_valid & ATTR_MODE))
6076		rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
6077
6078err_out:
6079	if  (error)
6080		ext4_std_error(inode->i_sb, error);
6081	if (!error)
6082		error = rc;
6083	return error;
6084}
6085
6086u32 ext4_dio_alignment(struct inode *inode)
6087{
6088	if (fsverity_active(inode))
6089		return 0;
6090	if (ext4_should_journal_data(inode))
6091		return 0;
6092	if (ext4_has_inline_data(inode))
6093		return 0;
6094	if (IS_ENCRYPTED(inode)) {
6095		if (!fscrypt_dio_supported(inode))
6096			return 0;
6097		return i_blocksize(inode);
6098	}
6099	return 1; /* use the iomap defaults */
6100}
6101
6102int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
6103		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
6104{
6105	struct inode *inode = d_inode(path->dentry);
6106	struct ext4_inode *raw_inode;
6107	struct ext4_inode_info *ei = EXT4_I(inode);
6108	unsigned int flags;
6109
6110	if ((request_mask & STATX_BTIME) &&
6111	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
6112		stat->result_mask |= STATX_BTIME;
6113		stat->btime.tv_sec = ei->i_crtime.tv_sec;
6114		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
6115	}
6116
6117	/*
6118	 * Return the DIO alignment restrictions if requested.  We only return
6119	 * this information when requested, since on encrypted files it might
6120	 * take a fair bit of work to get if the file wasn't opened recently.
6121	 */
6122	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
6123		u32 dio_align = ext4_dio_alignment(inode);
6124
6125		stat->result_mask |= STATX_DIOALIGN;
6126		if (dio_align == 1) {
6127			struct block_device *bdev = inode->i_sb->s_bdev;
6128
6129			/* iomap defaults */
6130			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
6131			stat->dio_offset_align = bdev_logical_block_size(bdev);
6132		} else {
6133			stat->dio_mem_align = dio_align;
6134			stat->dio_offset_align = dio_align;
6135		}
6136	}
6137
6138	if ((request_mask & STATX_WRITE_ATOMIC) && S_ISREG(inode->i_mode)) {
6139		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6140		unsigned int awu_min = 0, awu_max = 0;
6141
6142		if (ext4_inode_can_atomic_write(inode)) {
6143			awu_min = sbi->s_awu_min;
6144			awu_max = sbi->s_awu_max;
6145		}
6146
6147		generic_fill_statx_atomic_writes(stat, awu_min, awu_max, 0);
6148	}
6149
6150	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
6151	if (flags & EXT4_APPEND_FL)
6152		stat->attributes |= STATX_ATTR_APPEND;
6153	if (flags & EXT4_COMPR_FL)
6154		stat->attributes |= STATX_ATTR_COMPRESSED;
6155	if (flags & EXT4_ENCRYPT_FL)
6156		stat->attributes |= STATX_ATTR_ENCRYPTED;
6157	if (flags & EXT4_IMMUTABLE_FL)
6158		stat->attributes |= STATX_ATTR_IMMUTABLE;
6159	if (flags & EXT4_NODUMP_FL)
6160		stat->attributes |= STATX_ATTR_NODUMP;
6161	if (flags & EXT4_VERITY_FL)
6162		stat->attributes |= STATX_ATTR_VERITY;
6163
6164	stat->attributes_mask |= (STATX_ATTR_APPEND |
6165				  STATX_ATTR_COMPRESSED |
6166				  STATX_ATTR_ENCRYPTED |
6167				  STATX_ATTR_IMMUTABLE |
6168				  STATX_ATTR_NODUMP |
6169				  STATX_ATTR_VERITY);
6170
6171	generic_fillattr(idmap, request_mask, inode, stat);
6172	return 0;
6173}
6174
6175int ext4_file_getattr(struct mnt_idmap *idmap,
6176		      const struct path *path, struct kstat *stat,
6177		      u32 request_mask, unsigned int query_flags)
6178{
6179	struct inode *inode = d_inode(path->dentry);
6180	u64 delalloc_blocks;
6181
6182	ext4_getattr(idmap, path, stat, request_mask, query_flags);
6183
6184	/*
6185	 * If there is inline data in the inode, the inode will normally not
6186	 * have data blocks allocated (it may have an external xattr block).
6187	 * Report at least one sector for such files, so tools like tar, rsync,
6188	 * others don't incorrectly think the file is completely sparse.
6189	 */
6190	if (unlikely(ext4_has_inline_data(inode)))
6191		stat->blocks += (stat->size + 511) >> 9;
6192
6193	/*
6194	 * We can't update i_blocks if the block allocation is delayed
6195	 * otherwise in the case of system crash before the real block
6196	 * allocation is done, we will have i_blocks inconsistent with
6197	 * on-disk file blocks.
6198	 * We always keep i_blocks updated together with real
6199	 * allocation. But to not confuse with user, stat
6200	 * will return the blocks that include the delayed allocation
6201	 * blocks for this file.
6202	 */
6203	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
6204				   EXT4_I(inode)->i_reserved_data_blocks);
6205	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
6206	return 0;
6207}
6208
6209static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
6210				   int pextents)
6211{
6212	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
6213		return ext4_ind_trans_blocks(inode, lblocks);
6214	return ext4_ext_index_trans_blocks(inode, pextents);
6215}
6216
6217/*
6218 * Account for index blocks, block groups bitmaps and block group
6219 * descriptor blocks if modify datablocks and index blocks
6220 * worse case, the indexs blocks spread over different block groups
6221 *
6222 * If datablocks are discontiguous, they are possible to spread over
6223 * different block groups too. If they are contiguous, with flexbg,
6224 * they could still across block group boundary.
6225 *
6226 * Also account for superblock, inode, quota and xattr blocks
6227 */
6228int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents)
6229{
6230	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
6231	int gdpblocks;
6232	int idxblocks;
6233	int ret;
6234
6235	/*
6236	 * How many index and leaf blocks need to touch to map @lblocks
6237	 * logical blocks to @pextents physical extents?
6238	 */
6239	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
6240
6241	/*
6242	 * Now let's see how many group bitmaps and group descriptors need
6243	 * to account
6244	 */
6245	groups = idxblocks + pextents;
6246	gdpblocks = groups;
6247	if (groups > ngroups)
6248		groups = ngroups;
6249	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
6250		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
6251
6252	/* bitmaps and block group descriptor blocks */
6253	ret = idxblocks + groups + gdpblocks;
6254
6255	/* Blocks for super block, inode, quota and xattr blocks */
6256	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
6257
6258	return ret;
6259}
6260
6261/*
6262 * Calculate the journal credits for modifying the number of blocks
6263 * in a single extent within one transaction. 'nrblocks' is used only
6264 * for non-extent inodes. For extent type inodes, 'nrblocks' can be
6265 * zero if the exact number of blocks is unknown.
6266 */
6267int ext4_chunk_trans_extent(struct inode *inode, int nrblocks)
6268{
6269	int ret;
6270
6271	ret = ext4_meta_trans_blocks(inode, nrblocks, 1);
6272	/* Account for data blocks for journalled mode */
6273	if (ext4_should_journal_data(inode))
6274		ret += nrblocks;
6275	return ret;
6276}
6277
6278/*
6279 * Calculate the journal credits for a chunk of data modification.
6280 *
6281 * This is called from DIO, fallocate or whoever calling
6282 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
6283 *
6284 * journal buffers for data blocks are not included here, as DIO
6285 * and fallocate do no need to journal data buffers.
6286 */
6287int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
6288{
6289	return ext4_meta_trans_blocks(inode, nrblocks, 1);
6290}
6291
6292/*
6293 * The caller must have previously called ext4_reserve_inode_write().
6294 * Give this, we know that the caller already has write access to iloc->bh.
6295 */
6296int ext4_mark_iloc_dirty(handle_t *handle,
6297			 struct inode *inode, struct ext4_iloc *iloc)
6298{
6299	int err = 0;
6300
6301	err = ext4_emergency_state(inode->i_sb);
6302	if (unlikely(err)) {
6303		put_bh(iloc->bh);
6304		return err;
6305	}
6306	ext4_fc_track_inode(handle, inode);
6307
6308	/* the do_update_inode consumes one bh->b_count */
6309	get_bh(iloc->bh);
6310
6311	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
6312	err = ext4_do_update_inode(handle, inode, iloc);
6313	put_bh(iloc->bh);
6314	return err;
6315}
6316
6317/*
6318 * On success, We end up with an outstanding reference count against
6319 * iloc->bh.  This _must_ be cleaned up later.
6320 */
6321
6322int
6323ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
6324			 struct ext4_iloc *iloc)
6325{
6326	int err;
6327
6328	err = ext4_emergency_state(inode->i_sb);
6329	if (unlikely(err))
6330		return err;
6331
6332	err = ext4_get_inode_loc(inode, iloc);
6333	if (!err) {
6334		BUFFER_TRACE(iloc->bh, "get_write_access");
6335		err = ext4_journal_get_write_access(handle, inode->i_sb,
6336						    iloc->bh, EXT4_JTR_NONE);
6337		if (err) {
6338			brelse(iloc->bh);
6339			iloc->bh = NULL;
6340		}
6341		ext4_fc_track_inode(handle, inode);
6342	}
6343	ext4_std_error(inode->i_sb, err);
6344	return err;
6345}
6346
6347static int __ext4_expand_extra_isize(struct inode *inode,
6348				     unsigned int new_extra_isize,
6349				     struct ext4_iloc *iloc,
6350				     handle_t *handle, int *no_expand)
6351{
6352	struct ext4_inode *raw_inode;
6353	struct ext4_xattr_ibody_header *header;
6354	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
6355	struct ext4_inode_info *ei = EXT4_I(inode);
6356	int error;
6357
6358	/* this was checked at iget time, but double check for good measure */
6359	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
6360	    (ei->i_extra_isize & 3)) {
6361		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
6362				 ei->i_extra_isize,
6363				 EXT4_INODE_SIZE(inode->i_sb));
6364		return -EFSCORRUPTED;
6365	}
6366	if ((new_extra_isize < ei->i_extra_isize) ||
6367	    (new_extra_isize < 4) ||
6368	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
6369		return -EINVAL;	/* Should never happen */
6370
6371	raw_inode = ext4_raw_inode(iloc);
6372
6373	header = IHDR(inode, raw_inode);
6374
6375	/* No extended attributes present */
6376	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
6377	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
6378		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
6379		       EXT4_I(inode)->i_extra_isize, 0,
6380		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
6381		EXT4_I(inode)->i_extra_isize = new_extra_isize;
6382		return 0;
6383	}
6384
6385	/*
6386	 * We may need to allocate external xattr block so we need quotas
6387	 * initialized. Here we can be called with various locks held so we
6388	 * cannot affort to initialize quotas ourselves. So just bail.
6389	 */
6390	if (dquot_initialize_needed(inode))
6391		return -EAGAIN;
6392
6393	/* try to expand with EAs present */
6394	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
6395					   raw_inode, handle);
6396	if (error) {
6397		/*
6398		 * Inode size expansion failed; don't try again
6399		 */
6400		*no_expand = 1;
6401	}
6402
6403	return error;
6404}
6405
6406/*
6407 * Expand an inode by new_extra_isize bytes.
6408 * Returns 0 on success or negative error number on failure.
6409 */
6410static int ext4_try_to_expand_extra_isize(struct inode *inode,
6411					  unsigned int new_extra_isize,
6412					  struct ext4_iloc iloc,
6413					  handle_t *handle)
6414{
6415	int no_expand;
6416	int error;
6417
6418	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
6419		return -EOVERFLOW;
6420
6421	/*
6422	 * In nojournal mode, we can immediately attempt to expand
6423	 * the inode.  When journaled, we first need to obtain extra
6424	 * buffer credits since we may write into the EA block
6425	 * with this same handle. If journal_extend fails, then it will
6426	 * only result in a minor loss of functionality for that inode.
6427	 * If this is felt to be critical, then e2fsck should be run to
6428	 * force a large enough s_min_extra_isize.
6429	 */
6430	if (ext4_journal_extend(handle,
6431				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
6432		return -ENOSPC;
6433
6434	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
6435		return -EBUSY;
6436
6437	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
6438					  handle, &no_expand);
6439	ext4_write_unlock_xattr(inode, &no_expand);
6440
6441	return error;
6442}
6443
6444int ext4_expand_extra_isize(struct inode *inode,
6445			    unsigned int new_extra_isize,
6446			    struct ext4_iloc *iloc)
6447{
6448	handle_t *handle;
6449	int no_expand;
6450	int error, rc;
6451
6452	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
6453		brelse(iloc->bh);
6454		return -EOVERFLOW;
6455	}
6456
6457	handle = ext4_journal_start(inode, EXT4_HT_INODE,
6458				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
6459	if (IS_ERR(handle)) {
6460		error = PTR_ERR(handle);
6461		brelse(iloc->bh);
6462		return error;
6463	}
6464
6465	ext4_write_lock_xattr(inode, &no_expand);
6466
6467	BUFFER_TRACE(iloc->bh, "get_write_access");
6468	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
6469					      EXT4_JTR_NONE);
6470	if (error) {
6471		brelse(iloc->bh);
6472		goto out_unlock;
6473	}
6474
6475	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
6476					  handle, &no_expand);
6477
6478	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
6479	if (!error)
6480		error = rc;
6481
6482out_unlock:
6483	ext4_write_unlock_xattr(inode, &no_expand);
6484	ext4_journal_stop(handle);
6485	return error;
6486}
6487
6488/*
6489 * What we do here is to mark the in-core inode as clean with respect to inode
6490 * dirtiness (it may still be data-dirty).
6491 * This means that the in-core inode may be reaped by prune_icache
6492 * without having to perform any I/O.  This is a very good thing,
6493 * because *any* task may call prune_icache - even ones which
6494 * have a transaction open against a different journal.
6495 *
6496 * Is this cheating?  Not really.  Sure, we haven't written the
6497 * inode out, but prune_icache isn't a user-visible syncing function.
6498 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
6499 * we start and wait on commits.
6500 */
6501int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
6502				const char *func, unsigned int line)
6503{
6504	struct ext4_iloc iloc;
6505	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6506	int err;
6507
6508	might_sleep();
6509	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
6510	err = ext4_reserve_inode_write(handle, inode, &iloc);
6511	if (err)
6512		goto out;
6513
6514	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6515		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
6516					       iloc, handle);
6517
6518	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
6519out:
6520	if (unlikely(err))
6521		ext4_error_inode_err(inode, func, line, 0, err,
6522					"mark_inode_dirty error");
6523	return err;
6524}
6525
6526/*
6527 * ext4_dirty_inode() is called from __mark_inode_dirty()
6528 *
6529 * We're really interested in the case where a file is being extended.
6530 * i_size has been changed by generic_commit_write() and we thus need
6531 * to include the updated inode in the current transaction.
6532 *
6533 * Also, dquot_alloc_block() will always dirty the inode when blocks
6534 * are allocated to the file.
6535 *
6536 * If the inode is marked synchronous, we don't honour that here - doing
6537 * so would cause a commit on atime updates, which we don't bother doing.
6538 * We handle synchronous inodes at the highest possible level.
6539 */
6540void ext4_dirty_inode(struct inode *inode, int flags)
6541{
6542	handle_t *handle;
6543
6544	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6545	if (IS_ERR(handle))
6546		return;
6547	ext4_mark_inode_dirty(handle, inode);
6548	ext4_journal_stop(handle);
6549}
6550
6551int ext4_change_inode_journal_flag(struct inode *inode, int val)
6552{
6553	journal_t *journal;
6554	handle_t *handle;
6555	int err;
6556	int alloc_ctx;
6557
6558	/*
6559	 * We have to be very careful here: changing a data block's
6560	 * journaling status dynamically is dangerous.  If we write a
6561	 * data block to the journal, change the status and then delete
6562	 * that block, we risk forgetting to revoke the old log record
6563	 * from the journal and so a subsequent replay can corrupt data.
6564	 * So, first we make sure that the journal is empty and that
6565	 * nobody is changing anything.
6566	 */
6567
6568	journal = EXT4_JOURNAL(inode);
6569	if (!journal)
6570		return 0;
6571	if (is_journal_aborted(journal))
6572		return -EROFS;
6573
6574	/* Wait for all existing dio workers */
6575	inode_dio_wait(inode);
6576
6577	/*
6578	 * Before flushing the journal and switching inode's aops, we have
6579	 * to flush all dirty data the inode has. There can be outstanding
6580	 * delayed allocations, there can be unwritten extents created by
6581	 * fallocate or buffered writes in dioread_nolock mode covered by
6582	 * dirty data which can be converted only after flushing the dirty
6583	 * data (and journalled aops don't know how to handle these cases).
6584	 */
6585	filemap_invalidate_lock(inode->i_mapping);
6586	err = filemap_write_and_wait(inode->i_mapping);
6587	if (err < 0) {
6588		filemap_invalidate_unlock(inode->i_mapping);
6589		return err;
6590	}
6591	/* Before switch the inode journalling mode evict all the page cache. */
6592	truncate_pagecache(inode, 0);
6593
6594	alloc_ctx = ext4_writepages_down_write(inode->i_sb);
6595	jbd2_journal_lock_updates(journal);
6596
6597	/*
6598	 * OK, there are no updates running now, and all cached data is
6599	 * synced to disk.  We are now in a completely consistent state
6600	 * which doesn't have anything in the journal, and we know that
6601	 * no filesystem updates are running, so it is safe to modify
6602	 * the inode's in-core data-journaling state flag now.
6603	 */
6604
6605	if (val)
6606		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6607	else {
6608		err = jbd2_journal_flush(journal, 0);
6609		if (err < 0) {
6610			jbd2_journal_unlock_updates(journal);
6611			ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6612			filemap_invalidate_unlock(inode->i_mapping);
6613			return err;
6614		}
6615		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6616	}
6617	ext4_set_aops(inode);
6618	ext4_set_inode_mapping_order(inode);
6619
6620	jbd2_journal_unlock_updates(journal);
6621	ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6622	filemap_invalidate_unlock(inode->i_mapping);
6623
6624	/* Finally we can mark the inode as dirty. */
6625
6626	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6627	if (IS_ERR(handle))
6628		return PTR_ERR(handle);
6629
6630	ext4_fc_mark_ineligible(inode->i_sb,
6631		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6632	err = ext4_mark_inode_dirty(handle, inode);
6633	ext4_handle_sync(handle);
6634	ext4_journal_stop(handle);
6635	ext4_std_error(inode->i_sb, err);
6636
6637	return err;
6638}
6639
6640static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6641			    struct buffer_head *bh)
6642{
6643	return !buffer_mapped(bh);
6644}
6645
6646static int ext4_block_page_mkwrite(struct inode *inode, struct folio *folio,
6647				   get_block_t get_block)
6648{
6649	handle_t *handle;
6650	loff_t size;
6651	unsigned long len;
6652	int credits;
6653	int ret;
6654
6655	credits = ext4_chunk_trans_extent(inode,
6656			ext4_journal_blocks_per_folio(inode));
6657	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, credits);
6658	if (IS_ERR(handle))
6659		return PTR_ERR(handle);
6660
6661	folio_lock(folio);
6662	size = i_size_read(inode);
6663	/* Page got truncated from under us? */
6664	if (folio->mapping != inode->i_mapping || folio_pos(folio) > size) {
6665		ret = -EFAULT;
6666		goto out_error;
6667	}
6668
6669	len = folio_size(folio);
6670	if (folio_pos(folio) + len > size)
6671		len = size - folio_pos(folio);
6672
6673	ret = ext4_block_write_begin(handle, folio, 0, len, get_block);
6674	if (ret)
6675		goto out_error;
6676
6677	if (!ext4_should_journal_data(inode)) {
6678		block_commit_write(folio, 0, len);
6679		folio_mark_dirty(folio);
6680	} else {
6681		ret = ext4_journal_folio_buffers(handle, folio, len);
6682		if (ret)
6683			goto out_error;
6684	}
6685	ext4_journal_stop(handle);
6686	folio_wait_stable(folio);
6687	return ret;
6688
6689out_error:
6690	folio_unlock(folio);
6691	ext4_journal_stop(handle);
6692	return ret;
6693}
6694
6695vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6696{
6697	struct vm_area_struct *vma = vmf->vma;
6698	struct folio *folio = page_folio(vmf->page);
6699	loff_t size;
6700	unsigned long len;
6701	int err;
6702	vm_fault_t ret;
6703	struct file *file = vma->vm_file;
6704	struct inode *inode = file_inode(file);
6705	struct address_space *mapping = inode->i_mapping;
6706	get_block_t *get_block = ext4_get_block;
6707	int retries = 0;
6708
6709	if (unlikely(IS_IMMUTABLE(inode)))
6710		return VM_FAULT_SIGBUS;
6711
6712	sb_start_pagefault(inode->i_sb);
6713	file_update_time(vma->vm_file);
6714
6715	filemap_invalidate_lock_shared(mapping);
6716
6717	err = ext4_convert_inline_data(inode);
6718	if (err)
6719		goto out_ret;
6720
6721	/*
6722	 * On data journalling we skip straight to the transaction handle:
6723	 * there's no delalloc; page truncated will be checked later; the
6724	 * early return w/ all buffers mapped (calculates size/len) can't
6725	 * be used; and there's no dioread_nolock, so only ext4_get_block.
6726	 */
6727	if (ext4_should_journal_data(inode))
6728		goto retry_alloc;
6729
6730	/* Delalloc case is easy... */
6731	if (test_opt(inode->i_sb, DELALLOC) &&
6732	    !ext4_nonda_switch(inode->i_sb)) {
6733		do {
6734			err = block_page_mkwrite(vma, vmf,
6735						   ext4_da_get_block_prep);
6736		} while (err == -ENOSPC &&
6737		       ext4_should_retry_alloc(inode->i_sb, &retries));
6738		goto out_ret;
6739	}
6740
6741	folio_lock(folio);
6742	size = i_size_read(inode);
6743	/* Page got truncated from under us? */
6744	if (folio->mapping != mapping || folio_pos(folio) > size) {
6745		folio_unlock(folio);
6746		ret = VM_FAULT_NOPAGE;
6747		goto out;
6748	}
6749
6750	len = folio_size(folio);
6751	if (folio_pos(folio) + len > size)
6752		len = size - folio_pos(folio);
6753	/*
6754	 * Return if we have all the buffers mapped. This avoids the need to do
6755	 * journal_start/journal_stop which can block and take a long time
6756	 *
6757	 * This cannot be done for data journalling, as we have to add the
6758	 * inode to the transaction's list to writeprotect pages on commit.
6759	 */
6760	if (folio_buffers(folio)) {
6761		if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6762					    0, len, NULL,
6763					    ext4_bh_unmapped)) {
6764			/* Wait so that we don't change page under IO */
6765			folio_wait_stable(folio);
6766			ret = VM_FAULT_LOCKED;
6767			goto out;
6768		}
6769	}
6770	folio_unlock(folio);
6771	/* OK, we need to fill the hole... */
6772	if (ext4_should_dioread_nolock(inode))
6773		get_block = ext4_get_block_unwritten;
6774retry_alloc:
6775	/* Start journal and allocate blocks */
6776	err = ext4_block_page_mkwrite(inode, folio, get_block);
6777	if (err == -EAGAIN ||
6778	    (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)))
6779		goto retry_alloc;
6780out_ret:
6781	ret = vmf_fs_error(err);
6782out:
6783	filemap_invalidate_unlock_shared(mapping);
6784	sb_end_pagefault(inode->i_sb);
6785	return ret;
6786}
~/ Read-only file preview.