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