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