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