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