xref: /openbmc/linux/fs/ext4/inode.c (revision f12fbb9599e2ecca734d194e502fc1ac6822c85e)
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 		/*
1741 		 * Delayed extent could be allocated by fallocate.
1742 		 * So we need to check it.
1743 		 */
1744 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1745 			map_bh(bh, inode->i_sb, invalid_block);
1746 			set_buffer_new(bh);
1747 			set_buffer_delay(bh);
1748 			return 0;
1749 		}
1750 
1751 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1752 		retval = es.es_len - (iblock - es.es_lblk);
1753 		if (retval > map->m_len)
1754 			retval = map->m_len;
1755 		map->m_len = retval;
1756 		if (ext4_es_is_written(&es))
1757 			map->m_flags |= EXT4_MAP_MAPPED;
1758 		else if (ext4_es_is_unwritten(&es))
1759 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1760 		else
1761 			BUG();
1762 
1763 #ifdef ES_AGGRESSIVE_TEST
1764 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1765 #endif
1766 		return retval;
1767 	}
1768 
1769 	/*
1770 	 * Try to see if we can get the block without requesting a new
1771 	 * file system block.
1772 	 */
1773 	down_read(&EXT4_I(inode)->i_data_sem);
1774 	if (ext4_has_inline_data(inode))
1775 		retval = 0;
1776 	else
1777 		retval = ext4_map_query_blocks(NULL, inode, map);
1778 	up_read(&EXT4_I(inode)->i_data_sem);
1779 	if (retval)
1780 		return retval;
1781 
1782 add_delayed:
1783 	down_write(&EXT4_I(inode)->i_data_sem);
1784 	retval = ext4_insert_delayed_block(inode, map->m_lblk);
1785 	up_write(&EXT4_I(inode)->i_data_sem);
1786 	if (retval)
1787 		return retval;
1788 
1789 	map_bh(bh, inode->i_sb, invalid_block);
1790 	set_buffer_new(bh);
1791 	set_buffer_delay(bh);
1792 	return retval;
1793 }
1794 
1795 /*
1796  * This is a special get_block_t callback which is used by
1797  * ext4_da_write_begin().  It will either return mapped block or
1798  * reserve space for a single block.
1799  *
1800  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1801  * We also have b_blocknr = -1 and b_bdev initialized properly
1802  *
1803  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1804  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1805  * initialized properly.
1806  */
1807 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1808 			   struct buffer_head *bh, int create)
1809 {
1810 	struct ext4_map_blocks map;
1811 	int ret = 0;
1812 
1813 	BUG_ON(create == 0);
1814 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1815 
1816 	map.m_lblk = iblock;
1817 	map.m_len = 1;
1818 
1819 	/*
1820 	 * first, we need to know whether the block is allocated already
1821 	 * preallocated blocks are unmapped but should treated
1822 	 * the same as allocated blocks.
1823 	 */
1824 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1825 	if (ret <= 0)
1826 		return ret;
1827 
1828 	map_bh(bh, inode->i_sb, map.m_pblk);
1829 	ext4_update_bh_state(bh, map.m_flags);
1830 
1831 	if (buffer_unwritten(bh)) {
1832 		/* A delayed write to unwritten bh should be marked
1833 		 * new and mapped.  Mapped ensures that we don't do
1834 		 * get_block multiple times when we write to the same
1835 		 * offset and new ensures that we do proper zero out
1836 		 * for partial write.
1837 		 */
1838 		set_buffer_new(bh);
1839 		set_buffer_mapped(bh);
1840 	}
1841 	return 0;
1842 }
1843 
1844 static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
1845 {
1846 	mpd->first_page += folio_nr_pages(folio);
1847 	folio_unlock(folio);
1848 }
1849 
1850 static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
1851 {
1852 	size_t len;
1853 	loff_t size;
1854 	int err;
1855 
1856 	BUG_ON(folio->index != mpd->first_page);
1857 	folio_clear_dirty_for_io(folio);
1858 	/*
1859 	 * We have to be very careful here!  Nothing protects writeback path
1860 	 * against i_size changes and the page can be writeably mapped into
1861 	 * page tables. So an application can be growing i_size and writing
1862 	 * data through mmap while writeback runs. folio_clear_dirty_for_io()
1863 	 * write-protects our page in page tables and the page cannot get
1864 	 * written to again until we release folio lock. So only after
1865 	 * folio_clear_dirty_for_io() we are safe to sample i_size for
1866 	 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
1867 	 * on the barrier provided by folio_test_clear_dirty() in
1868 	 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
1869 	 * after page tables are updated.
1870 	 */
1871 	size = i_size_read(mpd->inode);
1872 	len = folio_size(folio);
1873 	if (folio_pos(folio) + len > size &&
1874 	    !ext4_verity_in_progress(mpd->inode))
1875 		len = size & ~PAGE_MASK;
1876 	err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
1877 	if (!err)
1878 		mpd->wbc->nr_to_write--;
1879 
1880 	return err;
1881 }
1882 
1883 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
1884 
1885 /*
1886  * mballoc gives us at most this number of blocks...
1887  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1888  * The rest of mballoc seems to handle chunks up to full group size.
1889  */
1890 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1891 
1892 /*
1893  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1894  *
1895  * @mpd - extent of blocks
1896  * @lblk - logical number of the block in the file
1897  * @bh - buffer head we want to add to the extent
1898  *
1899  * The function is used to collect contig. blocks in the same state. If the
1900  * buffer doesn't require mapping for writeback and we haven't started the
1901  * extent of buffers to map yet, the function returns 'true' immediately - the
1902  * caller can write the buffer right away. Otherwise the function returns true
1903  * if the block has been added to the extent, false if the block couldn't be
1904  * added.
1905  */
1906 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1907 				   struct buffer_head *bh)
1908 {
1909 	struct ext4_map_blocks *map = &mpd->map;
1910 
1911 	/* Buffer that doesn't need mapping for writeback? */
1912 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1913 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1914 		/* So far no extent to map => we write the buffer right away */
1915 		if (map->m_len == 0)
1916 			return true;
1917 		return false;
1918 	}
1919 
1920 	/* First block in the extent? */
1921 	if (map->m_len == 0) {
1922 		/* We cannot map unless handle is started... */
1923 		if (!mpd->do_map)
1924 			return false;
1925 		map->m_lblk = lblk;
1926 		map->m_len = 1;
1927 		map->m_flags = bh->b_state & BH_FLAGS;
1928 		return true;
1929 	}
1930 
1931 	/* Don't go larger than mballoc is willing to allocate */
1932 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
1933 		return false;
1934 
1935 	/* Can we merge the block to our big extent? */
1936 	if (lblk == map->m_lblk + map->m_len &&
1937 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
1938 		map->m_len++;
1939 		return true;
1940 	}
1941 	return false;
1942 }
1943 
1944 /*
1945  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
1946  *
1947  * @mpd - extent of blocks for mapping
1948  * @head - the first buffer in the page
1949  * @bh - buffer we should start processing from
1950  * @lblk - logical number of the block in the file corresponding to @bh
1951  *
1952  * Walk through page buffers from @bh upto @head (exclusive) and either submit
1953  * the page for IO if all buffers in this page were mapped and there's no
1954  * accumulated extent of buffers to map or add buffers in the page to the
1955  * extent of buffers to map. The function returns 1 if the caller can continue
1956  * by processing the next page, 0 if it should stop adding buffers to the
1957  * extent to map because we cannot extend it anymore. It can also return value
1958  * < 0 in case of error during IO submission.
1959  */
1960 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
1961 				   struct buffer_head *head,
1962 				   struct buffer_head *bh,
1963 				   ext4_lblk_t lblk)
1964 {
1965 	struct inode *inode = mpd->inode;
1966 	int err;
1967 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
1968 							>> inode->i_blkbits;
1969 
1970 	if (ext4_verity_in_progress(inode))
1971 		blocks = EXT_MAX_BLOCKS;
1972 
1973 	do {
1974 		BUG_ON(buffer_locked(bh));
1975 
1976 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
1977 			/* Found extent to map? */
1978 			if (mpd->map.m_len)
1979 				return 0;
1980 			/* Buffer needs mapping and handle is not started? */
1981 			if (!mpd->do_map)
1982 				return 0;
1983 			/* Everything mapped so far and we hit EOF */
1984 			break;
1985 		}
1986 	} while (lblk++, (bh = bh->b_this_page) != head);
1987 	/* So far everything mapped? Submit the page for IO. */
1988 	if (mpd->map.m_len == 0) {
1989 		err = mpage_submit_folio(mpd, head->b_folio);
1990 		if (err < 0)
1991 			return err;
1992 		mpage_folio_done(mpd, head->b_folio);
1993 	}
1994 	if (lblk >= blocks) {
1995 		mpd->scanned_until_end = 1;
1996 		return 0;
1997 	}
1998 	return 1;
1999 }
2000 
2001 /*
2002  * mpage_process_folio - update folio buffers corresponding to changed extent
2003  *			 and may submit fully mapped page for IO
2004  * @mpd: description of extent to map, on return next extent to map
2005  * @folio: Contains these buffers.
2006  * @m_lblk: logical block mapping.
2007  * @m_pblk: corresponding physical mapping.
2008  * @map_bh: determines on return whether this page requires any further
2009  *		  mapping or not.
2010  *
2011  * Scan given folio buffers corresponding to changed extent and update buffer
2012  * state according to new extent state.
2013  * We map delalloc buffers to their physical location, clear unwritten bits.
2014  * If the given folio is not fully mapped, we update @mpd to the next extent in
2015  * the given folio that needs mapping & return @map_bh as true.
2016  */
2017 static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
2018 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2019 			      bool *map_bh)
2020 {
2021 	struct buffer_head *head, *bh;
2022 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
2023 	ext4_lblk_t lblk = *m_lblk;
2024 	ext4_fsblk_t pblock = *m_pblk;
2025 	int err = 0;
2026 	int blkbits = mpd->inode->i_blkbits;
2027 	ssize_t io_end_size = 0;
2028 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2029 
2030 	bh = head = folio_buffers(folio);
2031 	do {
2032 		if (lblk < mpd->map.m_lblk)
2033 			continue;
2034 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2035 			/*
2036 			 * Buffer after end of mapped extent.
2037 			 * Find next buffer in the folio to map.
2038 			 */
2039 			mpd->map.m_len = 0;
2040 			mpd->map.m_flags = 0;
2041 			io_end_vec->size += io_end_size;
2042 
2043 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
2044 			if (err > 0)
2045 				err = 0;
2046 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2047 				io_end_vec = ext4_alloc_io_end_vec(io_end);
2048 				if (IS_ERR(io_end_vec)) {
2049 					err = PTR_ERR(io_end_vec);
2050 					goto out;
2051 				}
2052 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2053 			}
2054 			*map_bh = true;
2055 			goto out;
2056 		}
2057 		if (buffer_delay(bh)) {
2058 			clear_buffer_delay(bh);
2059 			bh->b_blocknr = pblock++;
2060 		}
2061 		clear_buffer_unwritten(bh);
2062 		io_end_size += (1 << blkbits);
2063 	} while (lblk++, (bh = bh->b_this_page) != head);
2064 
2065 	io_end_vec->size += io_end_size;
2066 	*map_bh = false;
2067 out:
2068 	*m_lblk = lblk;
2069 	*m_pblk = pblock;
2070 	return err;
2071 }
2072 
2073 /*
2074  * mpage_map_buffers - update buffers corresponding to changed extent and
2075  *		       submit fully mapped pages for IO
2076  *
2077  * @mpd - description of extent to map, on return next extent to map
2078  *
2079  * Scan buffers corresponding to changed extent (we expect corresponding pages
2080  * to be already locked) and update buffer state according to new extent state.
2081  * We map delalloc buffers to their physical location, clear unwritten bits,
2082  * and mark buffers as uninit when we perform writes to unwritten extents
2083  * and do extent conversion after IO is finished. If the last page is not fully
2084  * mapped, we update @map to the next extent in the last page that needs
2085  * mapping. Otherwise we submit the page for IO.
2086  */
2087 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2088 {
2089 	struct folio_batch fbatch;
2090 	unsigned nr, i;
2091 	struct inode *inode = mpd->inode;
2092 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2093 	pgoff_t start, end;
2094 	ext4_lblk_t lblk;
2095 	ext4_fsblk_t pblock;
2096 	int err;
2097 	bool map_bh = false;
2098 
2099 	start = mpd->map.m_lblk >> bpp_bits;
2100 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2101 	lblk = start << bpp_bits;
2102 	pblock = mpd->map.m_pblk;
2103 
2104 	folio_batch_init(&fbatch);
2105 	while (start <= end) {
2106 		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
2107 		if (nr == 0)
2108 			break;
2109 		for (i = 0; i < nr; i++) {
2110 			struct folio *folio = fbatch.folios[i];
2111 
2112 			err = mpage_process_folio(mpd, folio, &lblk, &pblock,
2113 						 &map_bh);
2114 			/*
2115 			 * If map_bh is true, means page may require further bh
2116 			 * mapping, or maybe the page was submitted for IO.
2117 			 * So we return to call further extent mapping.
2118 			 */
2119 			if (err < 0 || map_bh)
2120 				goto out;
2121 			/* Page fully mapped - let IO run! */
2122 			err = mpage_submit_folio(mpd, folio);
2123 			if (err < 0)
2124 				goto out;
2125 			mpage_folio_done(mpd, folio);
2126 		}
2127 		folio_batch_release(&fbatch);
2128 	}
2129 	/* Extent fully mapped and matches with page boundary. We are done. */
2130 	mpd->map.m_len = 0;
2131 	mpd->map.m_flags = 0;
2132 	return 0;
2133 out:
2134 	folio_batch_release(&fbatch);
2135 	return err;
2136 }
2137 
2138 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2139 {
2140 	struct inode *inode = mpd->inode;
2141 	struct ext4_map_blocks *map = &mpd->map;
2142 	int get_blocks_flags;
2143 	int err, dioread_nolock;
2144 
2145 	trace_ext4_da_write_pages_extent(inode, map);
2146 	/*
2147 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2148 	 * to convert an unwritten extent to be initialized (in the case
2149 	 * where we have written into one or more preallocated blocks).  It is
2150 	 * possible that we're going to need more metadata blocks than
2151 	 * previously reserved. However we must not fail because we're in
2152 	 * writeback and there is nothing we can do about it so it might result
2153 	 * in data loss.  So use reserved blocks to allocate metadata if
2154 	 * possible.
2155 	 *
2156 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2157 	 * the blocks in question are delalloc blocks.  This indicates
2158 	 * that the blocks and quotas has already been checked when
2159 	 * the data was copied into the page cache.
2160 	 */
2161 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2162 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2163 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2164 	dioread_nolock = ext4_should_dioread_nolock(inode);
2165 	if (dioread_nolock)
2166 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2167 	if (map->m_flags & BIT(BH_Delay))
2168 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2169 
2170 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2171 	if (err < 0)
2172 		return err;
2173 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2174 		if (!mpd->io_submit.io_end->handle &&
2175 		    ext4_handle_valid(handle)) {
2176 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2177 			handle->h_rsv_handle = NULL;
2178 		}
2179 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2180 	}
2181 
2182 	BUG_ON(map->m_len == 0);
2183 	return 0;
2184 }
2185 
2186 /*
2187  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2188  *				 mpd->len and submit pages underlying it for IO
2189  *
2190  * @handle - handle for journal operations
2191  * @mpd - extent to map
2192  * @give_up_on_write - we set this to true iff there is a fatal error and there
2193  *                     is no hope of writing the data. The caller should discard
2194  *                     dirty pages to avoid infinite loops.
2195  *
2196  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2197  * delayed, blocks are allocated, if it is unwritten, we may need to convert
2198  * them to initialized or split the described range from larger unwritten
2199  * extent. Note that we need not map all the described range since allocation
2200  * can return less blocks or the range is covered by more unwritten extents. We
2201  * cannot map more because we are limited by reserved transaction credits. On
2202  * the other hand we always make sure that the last touched page is fully
2203  * mapped so that it can be written out (and thus forward progress is
2204  * guaranteed). After mapping we submit all mapped pages for IO.
2205  */
2206 static int mpage_map_and_submit_extent(handle_t *handle,
2207 				       struct mpage_da_data *mpd,
2208 				       bool *give_up_on_write)
2209 {
2210 	struct inode *inode = mpd->inode;
2211 	struct ext4_map_blocks *map = &mpd->map;
2212 	int err;
2213 	loff_t disksize;
2214 	int progress = 0;
2215 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
2216 	struct ext4_io_end_vec *io_end_vec;
2217 
2218 	io_end_vec = ext4_alloc_io_end_vec(io_end);
2219 	if (IS_ERR(io_end_vec))
2220 		return PTR_ERR(io_end_vec);
2221 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2222 	do {
2223 		err = mpage_map_one_extent(handle, mpd);
2224 		if (err < 0) {
2225 			struct super_block *sb = inode->i_sb;
2226 
2227 			if (ext4_forced_shutdown(sb))
2228 				goto invalidate_dirty_pages;
2229 			/*
2230 			 * Let the uper layers retry transient errors.
2231 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2232 			 * is non-zero, a commit should free up blocks.
2233 			 */
2234 			if ((err == -ENOMEM) ||
2235 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2236 				if (progress)
2237 					goto update_disksize;
2238 				return err;
2239 			}
2240 			ext4_msg(sb, KERN_CRIT,
2241 				 "Delayed block allocation failed for "
2242 				 "inode %lu at logical offset %llu with"
2243 				 " max blocks %u with error %d",
2244 				 inode->i_ino,
2245 				 (unsigned long long)map->m_lblk,
2246 				 (unsigned)map->m_len, -err);
2247 			ext4_msg(sb, KERN_CRIT,
2248 				 "This should not happen!! Data will "
2249 				 "be lost\n");
2250 			if (err == -ENOSPC)
2251 				ext4_print_free_blocks(inode);
2252 		invalidate_dirty_pages:
2253 			*give_up_on_write = true;
2254 			return err;
2255 		}
2256 		progress = 1;
2257 		/*
2258 		 * Update buffer state, submit mapped pages, and get us new
2259 		 * extent to map
2260 		 */
2261 		err = mpage_map_and_submit_buffers(mpd);
2262 		if (err < 0)
2263 			goto update_disksize;
2264 	} while (map->m_len);
2265 
2266 update_disksize:
2267 	/*
2268 	 * Update on-disk size after IO is submitted.  Races with
2269 	 * truncate are avoided by checking i_size under i_data_sem.
2270 	 */
2271 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2272 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2273 		int err2;
2274 		loff_t i_size;
2275 
2276 		down_write(&EXT4_I(inode)->i_data_sem);
2277 		i_size = i_size_read(inode);
2278 		if (disksize > i_size)
2279 			disksize = i_size;
2280 		if (disksize > EXT4_I(inode)->i_disksize)
2281 			EXT4_I(inode)->i_disksize = disksize;
2282 		up_write(&EXT4_I(inode)->i_data_sem);
2283 		err2 = ext4_mark_inode_dirty(handle, inode);
2284 		if (err2) {
2285 			ext4_error_err(inode->i_sb, -err2,
2286 				       "Failed to mark inode %lu dirty",
2287 				       inode->i_ino);
2288 		}
2289 		if (!err)
2290 			err = err2;
2291 	}
2292 	return err;
2293 }
2294 
2295 /*
2296  * Calculate the total number of credits to reserve for one writepages
2297  * iteration. This is called from ext4_writepages(). We map an extent of
2298  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2299  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2300  * bpp - 1 blocks in bpp different extents.
2301  */
2302 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2303 {
2304 	int bpp = ext4_journal_blocks_per_page(inode);
2305 
2306 	return ext4_meta_trans_blocks(inode,
2307 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2308 }
2309 
2310 static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
2311 				     size_t len)
2312 {
2313 	struct buffer_head *page_bufs = folio_buffers(folio);
2314 	struct inode *inode = folio->mapping->host;
2315 	int ret, err;
2316 
2317 	ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2318 				     NULL, do_journal_get_write_access);
2319 	err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2320 				     NULL, write_end_fn);
2321 	if (ret == 0)
2322 		ret = err;
2323 	err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
2324 	if (ret == 0)
2325 		ret = err;
2326 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2327 
2328 	return ret;
2329 }
2330 
2331 static int mpage_journal_page_buffers(handle_t *handle,
2332 				      struct mpage_da_data *mpd,
2333 				      struct folio *folio)
2334 {
2335 	struct inode *inode = mpd->inode;
2336 	loff_t size = i_size_read(inode);
2337 	size_t len = folio_size(folio);
2338 
2339 	folio_clear_checked(folio);
2340 	mpd->wbc->nr_to_write--;
2341 
2342 	if (folio_pos(folio) + len > size &&
2343 	    !ext4_verity_in_progress(inode))
2344 		len = size & (len - 1);
2345 
2346 	return ext4_journal_folio_buffers(handle, folio, len);
2347 }
2348 
2349 /*
2350  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2351  * 				 needing mapping, submit mapped pages
2352  *
2353  * @mpd - where to look for pages
2354  *
2355  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2356  * IO immediately. If we cannot map blocks, we submit just already mapped
2357  * buffers in the page for IO and keep page dirty. When we can map blocks and
2358  * we find a page which isn't mapped we start accumulating extent of buffers
2359  * underlying these pages that needs mapping (formed by either delayed or
2360  * unwritten buffers). We also lock the pages containing these buffers. The
2361  * extent found is returned in @mpd structure (starting at mpd->lblk with
2362  * length mpd->len blocks).
2363  *
2364  * Note that this function can attach bios to one io_end structure which are
2365  * neither logically nor physically contiguous. Although it may seem as an
2366  * unnecessary complication, it is actually inevitable in blocksize < pagesize
2367  * case as we need to track IO to all buffers underlying a page in one io_end.
2368  */
2369 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2370 {
2371 	struct address_space *mapping = mpd->inode->i_mapping;
2372 	struct folio_batch fbatch;
2373 	unsigned int nr_folios;
2374 	pgoff_t index = mpd->first_page;
2375 	pgoff_t end = mpd->last_page;
2376 	xa_mark_t tag;
2377 	int i, err = 0;
2378 	int blkbits = mpd->inode->i_blkbits;
2379 	ext4_lblk_t lblk;
2380 	struct buffer_head *head;
2381 	handle_t *handle = NULL;
2382 	int bpp = ext4_journal_blocks_per_page(mpd->inode);
2383 
2384 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2385 		tag = PAGECACHE_TAG_TOWRITE;
2386 	else
2387 		tag = PAGECACHE_TAG_DIRTY;
2388 
2389 	mpd->map.m_len = 0;
2390 	mpd->next_page = index;
2391 	if (ext4_should_journal_data(mpd->inode)) {
2392 		handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
2393 					    bpp);
2394 		if (IS_ERR(handle))
2395 			return PTR_ERR(handle);
2396 	}
2397 	folio_batch_init(&fbatch);
2398 	while (index <= end) {
2399 		nr_folios = filemap_get_folios_tag(mapping, &index, end,
2400 				tag, &fbatch);
2401 		if (nr_folios == 0)
2402 			break;
2403 
2404 		for (i = 0; i < nr_folios; i++) {
2405 			struct folio *folio = fbatch.folios[i];
2406 
2407 			/*
2408 			 * Accumulated enough dirty pages? This doesn't apply
2409 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2410 			 * keep going because someone may be concurrently
2411 			 * dirtying pages, and we might have synced a lot of
2412 			 * newly appeared dirty pages, but have not synced all
2413 			 * of the old dirty pages.
2414 			 */
2415 			if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2416 			    mpd->wbc->nr_to_write <=
2417 			    mpd->map.m_len >> (PAGE_SHIFT - blkbits))
2418 				goto out;
2419 
2420 			/* If we can't merge this page, we are done. */
2421 			if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
2422 				goto out;
2423 
2424 			if (handle) {
2425 				err = ext4_journal_ensure_credits(handle, bpp,
2426 								  0);
2427 				if (err < 0)
2428 					goto out;
2429 			}
2430 
2431 			folio_lock(folio);
2432 			/*
2433 			 * If the page is no longer dirty, or its mapping no
2434 			 * longer corresponds to inode we are writing (which
2435 			 * means it has been truncated or invalidated), or the
2436 			 * page is already under writeback and we are not doing
2437 			 * a data integrity writeback, skip the page
2438 			 */
2439 			if (!folio_test_dirty(folio) ||
2440 			    (folio_test_writeback(folio) &&
2441 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2442 			    unlikely(folio->mapping != mapping)) {
2443 				folio_unlock(folio);
2444 				continue;
2445 			}
2446 
2447 			folio_wait_writeback(folio);
2448 			BUG_ON(folio_test_writeback(folio));
2449 
2450 			/*
2451 			 * Should never happen but for buggy code in
2452 			 * other subsystems that call
2453 			 * set_page_dirty() without properly warning
2454 			 * the file system first.  See [1] for more
2455 			 * information.
2456 			 *
2457 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2458 			 */
2459 			if (!folio_buffers(folio)) {
2460 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
2461 				folio_clear_dirty(folio);
2462 				folio_unlock(folio);
2463 				continue;
2464 			}
2465 
2466 			if (mpd->map.m_len == 0)
2467 				mpd->first_page = folio->index;
2468 			mpd->next_page = folio_next_index(folio);
2469 			/*
2470 			 * Writeout when we cannot modify metadata is simple.
2471 			 * Just submit the page. For data=journal mode we
2472 			 * first handle writeout of the page for checkpoint and
2473 			 * only after that handle delayed page dirtying. This
2474 			 * makes sure current data is checkpointed to the final
2475 			 * location before possibly journalling it again which
2476 			 * is desirable when the page is frequently dirtied
2477 			 * through a pin.
2478 			 */
2479 			if (!mpd->can_map) {
2480 				err = mpage_submit_folio(mpd, folio);
2481 				if (err < 0)
2482 					goto out;
2483 				/* Pending dirtying of journalled data? */
2484 				if (folio_test_checked(folio)) {
2485 					err = mpage_journal_page_buffers(handle,
2486 						mpd, folio);
2487 					if (err < 0)
2488 						goto out;
2489 					mpd->journalled_more_data = 1;
2490 				}
2491 				mpage_folio_done(mpd, folio);
2492 			} else {
2493 				/* Add all dirty buffers to mpd */
2494 				lblk = ((ext4_lblk_t)folio->index) <<
2495 					(PAGE_SHIFT - blkbits);
2496 				head = folio_buffers(folio);
2497 				err = mpage_process_page_bufs(mpd, head, head,
2498 						lblk);
2499 				if (err <= 0)
2500 					goto out;
2501 				err = 0;
2502 			}
2503 		}
2504 		folio_batch_release(&fbatch);
2505 		cond_resched();
2506 	}
2507 	mpd->scanned_until_end = 1;
2508 	if (handle)
2509 		ext4_journal_stop(handle);
2510 	return 0;
2511 out:
2512 	folio_batch_release(&fbatch);
2513 	if (handle)
2514 		ext4_journal_stop(handle);
2515 	return err;
2516 }
2517 
2518 static int ext4_do_writepages(struct mpage_da_data *mpd)
2519 {
2520 	struct writeback_control *wbc = mpd->wbc;
2521 	pgoff_t	writeback_index = 0;
2522 	long nr_to_write = wbc->nr_to_write;
2523 	int range_whole = 0;
2524 	int cycled = 1;
2525 	handle_t *handle = NULL;
2526 	struct inode *inode = mpd->inode;
2527 	struct address_space *mapping = inode->i_mapping;
2528 	int needed_blocks, rsv_blocks = 0, ret = 0;
2529 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2530 	struct blk_plug plug;
2531 	bool give_up_on_write = false;
2532 
2533 	trace_ext4_writepages(inode, wbc);
2534 
2535 	/*
2536 	 * No pages to write? This is mainly a kludge to avoid starting
2537 	 * a transaction for special inodes like journal inode on last iput()
2538 	 * because that could violate lock ordering on umount
2539 	 */
2540 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2541 		goto out_writepages;
2542 
2543 	/*
2544 	 * If the filesystem has aborted, it is read-only, so return
2545 	 * right away instead of dumping stack traces later on that
2546 	 * will obscure the real source of the problem.  We test
2547 	 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
2548 	 * the latter could be true if the filesystem is mounted
2549 	 * read-only, and in that case, ext4_writepages should
2550 	 * *never* be called, so if that ever happens, we would want
2551 	 * the stack trace.
2552 	 */
2553 	if (unlikely(ext4_forced_shutdown(mapping->host->i_sb))) {
2554 		ret = -EROFS;
2555 		goto out_writepages;
2556 	}
2557 
2558 	/*
2559 	 * If we have inline data and arrive here, it means that
2560 	 * we will soon create the block for the 1st page, so
2561 	 * we'd better clear the inline data here.
2562 	 */
2563 	if (ext4_has_inline_data(inode)) {
2564 		/* Just inode will be modified... */
2565 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2566 		if (IS_ERR(handle)) {
2567 			ret = PTR_ERR(handle);
2568 			goto out_writepages;
2569 		}
2570 		BUG_ON(ext4_test_inode_state(inode,
2571 				EXT4_STATE_MAY_INLINE_DATA));
2572 		ext4_destroy_inline_data(handle, inode);
2573 		ext4_journal_stop(handle);
2574 	}
2575 
2576 	/*
2577 	 * data=journal mode does not do delalloc so we just need to writeout /
2578 	 * journal already mapped buffers. On the other hand we need to commit
2579 	 * transaction to make data stable. We expect all the data to be
2580 	 * already in the journal (the only exception are DMA pinned pages
2581 	 * dirtied behind our back) so we commit transaction here and run the
2582 	 * writeback loop to checkpoint them. The checkpointing is not actually
2583 	 * necessary to make data persistent *but* quite a few places (extent
2584 	 * shifting operations, fsverity, ...) depend on being able to drop
2585 	 * pagecache pages after calling filemap_write_and_wait() and for that
2586 	 * checkpointing needs to happen.
2587 	 */
2588 	if (ext4_should_journal_data(inode)) {
2589 		mpd->can_map = 0;
2590 		if (wbc->sync_mode == WB_SYNC_ALL)
2591 			ext4_fc_commit(sbi->s_journal,
2592 				       EXT4_I(inode)->i_datasync_tid);
2593 	}
2594 	mpd->journalled_more_data = 0;
2595 
2596 	if (ext4_should_dioread_nolock(inode)) {
2597 		/*
2598 		 * We may need to convert up to one extent per block in
2599 		 * the page and we may dirty the inode.
2600 		 */
2601 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2602 						PAGE_SIZE >> inode->i_blkbits);
2603 	}
2604 
2605 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2606 		range_whole = 1;
2607 
2608 	if (wbc->range_cyclic) {
2609 		writeback_index = mapping->writeback_index;
2610 		if (writeback_index)
2611 			cycled = 0;
2612 		mpd->first_page = writeback_index;
2613 		mpd->last_page = -1;
2614 	} else {
2615 		mpd->first_page = wbc->range_start >> PAGE_SHIFT;
2616 		mpd->last_page = wbc->range_end >> PAGE_SHIFT;
2617 	}
2618 
2619 	ext4_io_submit_init(&mpd->io_submit, wbc);
2620 retry:
2621 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2622 		tag_pages_for_writeback(mapping, mpd->first_page,
2623 					mpd->last_page);
2624 	blk_start_plug(&plug);
2625 
2626 	/*
2627 	 * First writeback pages that don't need mapping - we can avoid
2628 	 * starting a transaction unnecessarily and also avoid being blocked
2629 	 * in the block layer on device congestion while having transaction
2630 	 * started.
2631 	 */
2632 	mpd->do_map = 0;
2633 	mpd->scanned_until_end = 0;
2634 	mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2635 	if (!mpd->io_submit.io_end) {
2636 		ret = -ENOMEM;
2637 		goto unplug;
2638 	}
2639 	ret = mpage_prepare_extent_to_map(mpd);
2640 	/* Unlock pages we didn't use */
2641 	mpage_release_unused_pages(mpd, false);
2642 	/* Submit prepared bio */
2643 	ext4_io_submit(&mpd->io_submit);
2644 	ext4_put_io_end_defer(mpd->io_submit.io_end);
2645 	mpd->io_submit.io_end = NULL;
2646 	if (ret < 0)
2647 		goto unplug;
2648 
2649 	while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
2650 		/* For each extent of pages we use new io_end */
2651 		mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2652 		if (!mpd->io_submit.io_end) {
2653 			ret = -ENOMEM;
2654 			break;
2655 		}
2656 
2657 		WARN_ON_ONCE(!mpd->can_map);
2658 		/*
2659 		 * We have two constraints: We find one extent to map and we
2660 		 * must always write out whole page (makes a difference when
2661 		 * blocksize < pagesize) so that we don't block on IO when we
2662 		 * try to write out the rest of the page. Journalled mode is
2663 		 * not supported by delalloc.
2664 		 */
2665 		BUG_ON(ext4_should_journal_data(inode));
2666 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2667 
2668 		/* start a new transaction */
2669 		handle = ext4_journal_start_with_reserve(inode,
2670 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2671 		if (IS_ERR(handle)) {
2672 			ret = PTR_ERR(handle);
2673 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2674 			       "%ld pages, ino %lu; err %d", __func__,
2675 				wbc->nr_to_write, inode->i_ino, ret);
2676 			/* Release allocated io_end */
2677 			ext4_put_io_end(mpd->io_submit.io_end);
2678 			mpd->io_submit.io_end = NULL;
2679 			break;
2680 		}
2681 		mpd->do_map = 1;
2682 
2683 		trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
2684 		ret = mpage_prepare_extent_to_map(mpd);
2685 		if (!ret && mpd->map.m_len)
2686 			ret = mpage_map_and_submit_extent(handle, mpd,
2687 					&give_up_on_write);
2688 		/*
2689 		 * Caution: If the handle is synchronous,
2690 		 * ext4_journal_stop() can wait for transaction commit
2691 		 * to finish which may depend on writeback of pages to
2692 		 * complete or on page lock to be released.  In that
2693 		 * case, we have to wait until after we have
2694 		 * submitted all the IO, released page locks we hold,
2695 		 * and dropped io_end reference (for extent conversion
2696 		 * to be able to complete) before stopping the handle.
2697 		 */
2698 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2699 			ext4_journal_stop(handle);
2700 			handle = NULL;
2701 			mpd->do_map = 0;
2702 		}
2703 		/* Unlock pages we didn't use */
2704 		mpage_release_unused_pages(mpd, give_up_on_write);
2705 		/* Submit prepared bio */
2706 		ext4_io_submit(&mpd->io_submit);
2707 
2708 		/*
2709 		 * Drop our io_end reference we got from init. We have
2710 		 * to be careful and use deferred io_end finishing if
2711 		 * we are still holding the transaction as we can
2712 		 * release the last reference to io_end which may end
2713 		 * up doing unwritten extent conversion.
2714 		 */
2715 		if (handle) {
2716 			ext4_put_io_end_defer(mpd->io_submit.io_end);
2717 			ext4_journal_stop(handle);
2718 		} else
2719 			ext4_put_io_end(mpd->io_submit.io_end);
2720 		mpd->io_submit.io_end = NULL;
2721 
2722 		if (ret == -ENOSPC && sbi->s_journal) {
2723 			/*
2724 			 * Commit the transaction which would
2725 			 * free blocks released in the transaction
2726 			 * and try again
2727 			 */
2728 			jbd2_journal_force_commit_nested(sbi->s_journal);
2729 			ret = 0;
2730 			continue;
2731 		}
2732 		/* Fatal error - ENOMEM, EIO... */
2733 		if (ret)
2734 			break;
2735 	}
2736 unplug:
2737 	blk_finish_plug(&plug);
2738 	if (!ret && !cycled && wbc->nr_to_write > 0) {
2739 		cycled = 1;
2740 		mpd->last_page = writeback_index - 1;
2741 		mpd->first_page = 0;
2742 		goto retry;
2743 	}
2744 
2745 	/* Update index */
2746 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2747 		/*
2748 		 * Set the writeback_index so that range_cyclic
2749 		 * mode will write it back later
2750 		 */
2751 		mapping->writeback_index = mpd->first_page;
2752 
2753 out_writepages:
2754 	trace_ext4_writepages_result(inode, wbc, ret,
2755 				     nr_to_write - wbc->nr_to_write);
2756 	return ret;
2757 }
2758 
2759 static int ext4_writepages(struct address_space *mapping,
2760 			   struct writeback_control *wbc)
2761 {
2762 	struct super_block *sb = mapping->host->i_sb;
2763 	struct mpage_da_data mpd = {
2764 		.inode = mapping->host,
2765 		.wbc = wbc,
2766 		.can_map = 1,
2767 	};
2768 	int ret;
2769 	int alloc_ctx;
2770 
2771 	if (unlikely(ext4_forced_shutdown(sb)))
2772 		return -EIO;
2773 
2774 	alloc_ctx = ext4_writepages_down_read(sb);
2775 	ret = ext4_do_writepages(&mpd);
2776 	/*
2777 	 * For data=journal writeback we could have come across pages marked
2778 	 * for delayed dirtying (PageChecked) which were just added to the
2779 	 * running transaction. Try once more to get them to stable storage.
2780 	 */
2781 	if (!ret && mpd.journalled_more_data)
2782 		ret = ext4_do_writepages(&mpd);
2783 	ext4_writepages_up_read(sb, alloc_ctx);
2784 
2785 	return ret;
2786 }
2787 
2788 int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
2789 {
2790 	struct writeback_control wbc = {
2791 		.sync_mode = WB_SYNC_ALL,
2792 		.nr_to_write = LONG_MAX,
2793 		.range_start = jinode->i_dirty_start,
2794 		.range_end = jinode->i_dirty_end,
2795 	};
2796 	struct mpage_da_data mpd = {
2797 		.inode = jinode->i_vfs_inode,
2798 		.wbc = &wbc,
2799 		.can_map = 0,
2800 	};
2801 	return ext4_do_writepages(&mpd);
2802 }
2803 
2804 static int ext4_dax_writepages(struct address_space *mapping,
2805 			       struct writeback_control *wbc)
2806 {
2807 	int ret;
2808 	long nr_to_write = wbc->nr_to_write;
2809 	struct inode *inode = mapping->host;
2810 	int alloc_ctx;
2811 
2812 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
2813 		return -EIO;
2814 
2815 	alloc_ctx = ext4_writepages_down_read(inode->i_sb);
2816 	trace_ext4_writepages(inode, wbc);
2817 
2818 	ret = dax_writeback_mapping_range(mapping,
2819 					  EXT4_SB(inode->i_sb)->s_daxdev, wbc);
2820 	trace_ext4_writepages_result(inode, wbc, ret,
2821 				     nr_to_write - wbc->nr_to_write);
2822 	ext4_writepages_up_read(inode->i_sb, alloc_ctx);
2823 	return ret;
2824 }
2825 
2826 static int ext4_nonda_switch(struct super_block *sb)
2827 {
2828 	s64 free_clusters, dirty_clusters;
2829 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2830 
2831 	/*
2832 	 * switch to non delalloc mode if we are running low
2833 	 * on free block. The free block accounting via percpu
2834 	 * counters can get slightly wrong with percpu_counter_batch getting
2835 	 * accumulated on each CPU without updating global counters
2836 	 * Delalloc need an accurate free block accounting. So switch
2837 	 * to non delalloc when we are near to error range.
2838 	 */
2839 	free_clusters =
2840 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2841 	dirty_clusters =
2842 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2843 	/*
2844 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
2845 	 */
2846 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2847 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2848 
2849 	if (2 * free_clusters < 3 * dirty_clusters ||
2850 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2851 		/*
2852 		 * free block count is less than 150% of dirty blocks
2853 		 * or free blocks is less than watermark
2854 		 */
2855 		return 1;
2856 	}
2857 	return 0;
2858 }
2859 
2860 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2861 			       loff_t pos, unsigned len,
2862 			       struct page **pagep, void **fsdata)
2863 {
2864 	int ret, retries = 0;
2865 	struct folio *folio;
2866 	pgoff_t index;
2867 	struct inode *inode = mapping->host;
2868 
2869 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
2870 		return -EIO;
2871 
2872 	index = pos >> PAGE_SHIFT;
2873 
2874 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
2875 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2876 		return ext4_write_begin(file, mapping, pos,
2877 					len, pagep, fsdata);
2878 	}
2879 	*fsdata = (void *)0;
2880 	trace_ext4_da_write_begin(inode, pos, len);
2881 
2882 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2883 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
2884 						      pagep, fsdata);
2885 		if (ret < 0)
2886 			return ret;
2887 		if (ret == 1)
2888 			return 0;
2889 	}
2890 
2891 retry:
2892 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
2893 			mapping_gfp_mask(mapping));
2894 	if (IS_ERR(folio))
2895 		return PTR_ERR(folio);
2896 
2897 #ifdef CONFIG_FS_ENCRYPTION
2898 	ret = ext4_block_write_begin(folio, pos, len, ext4_da_get_block_prep);
2899 #else
2900 	ret = __block_write_begin(&folio->page, pos, len, ext4_da_get_block_prep);
2901 #endif
2902 	if (ret < 0) {
2903 		folio_unlock(folio);
2904 		folio_put(folio);
2905 		/*
2906 		 * block_write_begin may have instantiated a few blocks
2907 		 * outside i_size.  Trim these off again. Don't need
2908 		 * i_size_read because we hold inode lock.
2909 		 */
2910 		if (pos + len > inode->i_size)
2911 			ext4_truncate_failed_write(inode);
2912 
2913 		if (ret == -ENOSPC &&
2914 		    ext4_should_retry_alloc(inode->i_sb, &retries))
2915 			goto retry;
2916 		return ret;
2917 	}
2918 
2919 	*pagep = &folio->page;
2920 	return ret;
2921 }
2922 
2923 /*
2924  * Check if we should update i_disksize
2925  * when write to the end of file but not require block allocation
2926  */
2927 static int ext4_da_should_update_i_disksize(struct folio *folio,
2928 					    unsigned long offset)
2929 {
2930 	struct buffer_head *bh;
2931 	struct inode *inode = folio->mapping->host;
2932 	unsigned int idx;
2933 	int i;
2934 
2935 	bh = folio_buffers(folio);
2936 	idx = offset >> inode->i_blkbits;
2937 
2938 	for (i = 0; i < idx; i++)
2939 		bh = bh->b_this_page;
2940 
2941 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2942 		return 0;
2943 	return 1;
2944 }
2945 
2946 static int ext4_da_do_write_end(struct address_space *mapping,
2947 			loff_t pos, unsigned len, unsigned copied,
2948 			struct page *page)
2949 {
2950 	struct inode *inode = mapping->host;
2951 	loff_t old_size = inode->i_size;
2952 	bool disksize_changed = false;
2953 	loff_t new_i_size;
2954 
2955 	/*
2956 	 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
2957 	 * flag, which all that's needed to trigger page writeback.
2958 	 */
2959 	copied = block_write_end(NULL, mapping, pos, len, copied, page, NULL);
2960 	new_i_size = pos + copied;
2961 
2962 	/*
2963 	 * It's important to update i_size while still holding page lock,
2964 	 * because page writeout could otherwise come in and zero beyond
2965 	 * i_size.
2966 	 *
2967 	 * Since we are holding inode lock, we are sure i_disksize <=
2968 	 * i_size. We also know that if i_disksize < i_size, there are
2969 	 * delalloc writes pending in the range up to i_size. If the end of
2970 	 * the current write is <= i_size, there's no need to touch
2971 	 * i_disksize since writeback will push i_disksize up to i_size
2972 	 * eventually. If the end of the current write is > i_size and
2973 	 * inside an allocated block which ext4_da_should_update_i_disksize()
2974 	 * checked, we need to update i_disksize here as certain
2975 	 * ext4_writepages() paths not allocating blocks and update i_disksize.
2976 	 */
2977 	if (new_i_size > inode->i_size) {
2978 		unsigned long end;
2979 
2980 		i_size_write(inode, new_i_size);
2981 		end = (new_i_size - 1) & (PAGE_SIZE - 1);
2982 		if (copied && ext4_da_should_update_i_disksize(page_folio(page), end)) {
2983 			ext4_update_i_disksize(inode, new_i_size);
2984 			disksize_changed = true;
2985 		}
2986 	}
2987 
2988 	unlock_page(page);
2989 	put_page(page);
2990 
2991 	if (old_size < pos)
2992 		pagecache_isize_extended(inode, old_size, pos);
2993 
2994 	if (disksize_changed) {
2995 		handle_t *handle;
2996 
2997 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
2998 		if (IS_ERR(handle))
2999 			return PTR_ERR(handle);
3000 		ext4_mark_inode_dirty(handle, inode);
3001 		ext4_journal_stop(handle);
3002 	}
3003 
3004 	return copied;
3005 }
3006 
3007 static int ext4_da_write_end(struct file *file,
3008 			     struct address_space *mapping,
3009 			     loff_t pos, unsigned len, unsigned copied,
3010 			     struct page *page, void *fsdata)
3011 {
3012 	struct inode *inode = mapping->host;
3013 	int write_mode = (int)(unsigned long)fsdata;
3014 	struct folio *folio = page_folio(page);
3015 
3016 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
3017 		return ext4_write_end(file, mapping, pos,
3018 				      len, copied, &folio->page, fsdata);
3019 
3020 	trace_ext4_da_write_end(inode, pos, len, copied);
3021 
3022 	if (write_mode != CONVERT_INLINE_DATA &&
3023 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3024 	    ext4_has_inline_data(inode))
3025 		return ext4_write_inline_data_end(inode, pos, len, copied,
3026 						  folio);
3027 
3028 	if (unlikely(copied < len) && !PageUptodate(page))
3029 		copied = 0;
3030 
3031 	return ext4_da_do_write_end(mapping, pos, len, copied, &folio->page);
3032 }
3033 
3034 /*
3035  * Force all delayed allocation blocks to be allocated for a given inode.
3036  */
3037 int ext4_alloc_da_blocks(struct inode *inode)
3038 {
3039 	trace_ext4_alloc_da_blocks(inode);
3040 
3041 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3042 		return 0;
3043 
3044 	/*
3045 	 * We do something simple for now.  The filemap_flush() will
3046 	 * also start triggering a write of the data blocks, which is
3047 	 * not strictly speaking necessary (and for users of
3048 	 * laptop_mode, not even desirable).  However, to do otherwise
3049 	 * would require replicating code paths in:
3050 	 *
3051 	 * ext4_writepages() ->
3052 	 *    write_cache_pages() ---> (via passed in callback function)
3053 	 *        __mpage_da_writepage() -->
3054 	 *           mpage_add_bh_to_extent()
3055 	 *           mpage_da_map_blocks()
3056 	 *
3057 	 * The problem is that write_cache_pages(), located in
3058 	 * mm/page-writeback.c, marks pages clean in preparation for
3059 	 * doing I/O, which is not desirable if we're not planning on
3060 	 * doing I/O at all.
3061 	 *
3062 	 * We could call write_cache_pages(), and then redirty all of
3063 	 * the pages by calling redirty_page_for_writepage() but that
3064 	 * would be ugly in the extreme.  So instead we would need to
3065 	 * replicate parts of the code in the above functions,
3066 	 * simplifying them because we wouldn't actually intend to
3067 	 * write out the pages, but rather only collect contiguous
3068 	 * logical block extents, call the multi-block allocator, and
3069 	 * then update the buffer heads with the block allocations.
3070 	 *
3071 	 * For now, though, we'll cheat by calling filemap_flush(),
3072 	 * which will map the blocks, and start the I/O, but not
3073 	 * actually wait for the I/O to complete.
3074 	 */
3075 	return filemap_flush(inode->i_mapping);
3076 }
3077 
3078 /*
3079  * bmap() is special.  It gets used by applications such as lilo and by
3080  * the swapper to find the on-disk block of a specific piece of data.
3081  *
3082  * Naturally, this is dangerous if the block concerned is still in the
3083  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3084  * filesystem and enables swap, then they may get a nasty shock when the
3085  * data getting swapped to that swapfile suddenly gets overwritten by
3086  * the original zero's written out previously to the journal and
3087  * awaiting writeback in the kernel's buffer cache.
3088  *
3089  * So, if we see any bmap calls here on a modified, data-journaled file,
3090  * take extra steps to flush any blocks which might be in the cache.
3091  */
3092 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3093 {
3094 	struct inode *inode = mapping->host;
3095 	sector_t ret = 0;
3096 
3097 	inode_lock_shared(inode);
3098 	/*
3099 	 * We can get here for an inline file via the FIBMAP ioctl
3100 	 */
3101 	if (ext4_has_inline_data(inode))
3102 		goto out;
3103 
3104 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3105 	    (test_opt(inode->i_sb, DELALLOC) ||
3106 	     ext4_should_journal_data(inode))) {
3107 		/*
3108 		 * With delalloc or journalled data we want to sync the file so
3109 		 * that we can make sure we allocate blocks for file and data
3110 		 * is in place for the user to see it
3111 		 */
3112 		filemap_write_and_wait(mapping);
3113 	}
3114 
3115 	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3116 
3117 out:
3118 	inode_unlock_shared(inode);
3119 	return ret;
3120 }
3121 
3122 static int ext4_read_folio(struct file *file, struct folio *folio)
3123 {
3124 	int ret = -EAGAIN;
3125 	struct inode *inode = folio->mapping->host;
3126 
3127 	trace_ext4_read_folio(inode, folio);
3128 
3129 	if (ext4_has_inline_data(inode))
3130 		ret = ext4_readpage_inline(inode, folio);
3131 
3132 	if (ret == -EAGAIN)
3133 		return ext4_mpage_readpages(inode, NULL, folio);
3134 
3135 	return ret;
3136 }
3137 
3138 static void ext4_readahead(struct readahead_control *rac)
3139 {
3140 	struct inode *inode = rac->mapping->host;
3141 
3142 	/* If the file has inline data, no need to do readahead. */
3143 	if (ext4_has_inline_data(inode))
3144 		return;
3145 
3146 	ext4_mpage_readpages(inode, rac, NULL);
3147 }
3148 
3149 static void ext4_invalidate_folio(struct folio *folio, size_t offset,
3150 				size_t length)
3151 {
3152 	trace_ext4_invalidate_folio(folio, offset, length);
3153 
3154 	/* No journalling happens on data buffers when this function is used */
3155 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
3156 
3157 	block_invalidate_folio(folio, offset, length);
3158 }
3159 
3160 static int __ext4_journalled_invalidate_folio(struct folio *folio,
3161 					    size_t offset, size_t length)
3162 {
3163 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3164 
3165 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
3166 
3167 	/*
3168 	 * If it's a full truncate we just forget about the pending dirtying
3169 	 */
3170 	if (offset == 0 && length == folio_size(folio))
3171 		folio_clear_checked(folio);
3172 
3173 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
3174 }
3175 
3176 /* Wrapper for aops... */
3177 static void ext4_journalled_invalidate_folio(struct folio *folio,
3178 					   size_t offset,
3179 					   size_t length)
3180 {
3181 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3182 }
3183 
3184 static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3185 {
3186 	struct inode *inode = folio->mapping->host;
3187 	journal_t *journal = EXT4_JOURNAL(inode);
3188 
3189 	trace_ext4_release_folio(inode, folio);
3190 
3191 	/* Page has dirty journalled data -> cannot release */
3192 	if (folio_test_checked(folio))
3193 		return false;
3194 	if (journal)
3195 		return jbd2_journal_try_to_free_buffers(journal, folio);
3196 	else
3197 		return try_to_free_buffers(folio);
3198 }
3199 
3200 static bool ext4_inode_datasync_dirty(struct inode *inode)
3201 {
3202 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3203 
3204 	if (journal) {
3205 		if (jbd2_transaction_committed(journal,
3206 			EXT4_I(inode)->i_datasync_tid))
3207 			return false;
3208 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3209 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3210 		return true;
3211 	}
3212 
3213 	/* Any metadata buffers to write? */
3214 	if (!list_empty(&inode->i_mapping->private_list))
3215 		return true;
3216 	return inode->i_state & I_DIRTY_DATASYNC;
3217 }
3218 
3219 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3220 			   struct ext4_map_blocks *map, loff_t offset,
3221 			   loff_t length, unsigned int flags)
3222 {
3223 	u8 blkbits = inode->i_blkbits;
3224 
3225 	/*
3226 	 * Writes that span EOF might trigger an I/O size update on completion,
3227 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3228 	 * there is no other metadata changes being made or are pending.
3229 	 */
3230 	iomap->flags = 0;
3231 	if (ext4_inode_datasync_dirty(inode) ||
3232 	    offset + length > i_size_read(inode))
3233 		iomap->flags |= IOMAP_F_DIRTY;
3234 
3235 	if (map->m_flags & EXT4_MAP_NEW)
3236 		iomap->flags |= IOMAP_F_NEW;
3237 
3238 	if (flags & IOMAP_DAX)
3239 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3240 	else
3241 		iomap->bdev = inode->i_sb->s_bdev;
3242 	iomap->offset = (u64) map->m_lblk << blkbits;
3243 	iomap->length = (u64) map->m_len << blkbits;
3244 
3245 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
3246 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3247 		iomap->flags |= IOMAP_F_MERGED;
3248 
3249 	/*
3250 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3251 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3252 	 * set. In order for any allocated unwritten extents to be converted
3253 	 * into written extents correctly within the ->end_io() handler, we
3254 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3255 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3256 	 * been set first.
3257 	 */
3258 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3259 		iomap->type = IOMAP_UNWRITTEN;
3260 		iomap->addr = (u64) map->m_pblk << blkbits;
3261 		if (flags & IOMAP_DAX)
3262 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3263 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3264 		iomap->type = IOMAP_MAPPED;
3265 		iomap->addr = (u64) map->m_pblk << blkbits;
3266 		if (flags & IOMAP_DAX)
3267 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3268 	} else {
3269 		iomap->type = IOMAP_HOLE;
3270 		iomap->addr = IOMAP_NULL_ADDR;
3271 	}
3272 }
3273 
3274 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3275 			    unsigned int flags)
3276 {
3277 	handle_t *handle;
3278 	u8 blkbits = inode->i_blkbits;
3279 	int ret, dio_credits, m_flags = 0, retries = 0;
3280 
3281 	/*
3282 	 * Trim the mapping request to the maximum value that we can map at
3283 	 * once for direct I/O.
3284 	 */
3285 	if (map->m_len > DIO_MAX_BLOCKS)
3286 		map->m_len = DIO_MAX_BLOCKS;
3287 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3288 
3289 retry:
3290 	/*
3291 	 * Either we allocate blocks and then don't get an unwritten extent, so
3292 	 * in that case we have reserved enough credits. Or, the blocks are
3293 	 * already allocated and unwritten. In that case, the extent conversion
3294 	 * fits into the credits as well.
3295 	 */
3296 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3297 	if (IS_ERR(handle))
3298 		return PTR_ERR(handle);
3299 
3300 	/*
3301 	 * DAX and direct I/O are the only two operations that are currently
3302 	 * supported with IOMAP_WRITE.
3303 	 */
3304 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3305 	if (flags & IOMAP_DAX)
3306 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3307 	/*
3308 	 * We use i_size instead of i_disksize here because delalloc writeback
3309 	 * can complete at any point during the I/O and subsequently push the
3310 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3311 	 * happening and thus expose allocated blocks to direct I/O reads.
3312 	 */
3313 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3314 		m_flags = EXT4_GET_BLOCKS_CREATE;
3315 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3316 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3317 
3318 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3319 
3320 	/*
3321 	 * We cannot fill holes in indirect tree based inodes as that could
3322 	 * expose stale data in the case of a crash. Use the magic error code
3323 	 * to fallback to buffered I/O.
3324 	 */
3325 	if (!m_flags && !ret)
3326 		ret = -ENOTBLK;
3327 
3328 	ext4_journal_stop(handle);
3329 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3330 		goto retry;
3331 
3332 	return ret;
3333 }
3334 
3335 
3336 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3337 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3338 {
3339 	int ret;
3340 	struct ext4_map_blocks map;
3341 	u8 blkbits = inode->i_blkbits;
3342 
3343 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3344 		return -EINVAL;
3345 
3346 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3347 		return -ERANGE;
3348 
3349 	/*
3350 	 * Calculate the first and last logical blocks respectively.
3351 	 */
3352 	map.m_lblk = offset >> blkbits;
3353 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3354 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3355 
3356 	if (flags & IOMAP_WRITE) {
3357 		/*
3358 		 * We check here if the blocks are already allocated, then we
3359 		 * don't need to start a journal txn and we can directly return
3360 		 * the mapping information. This could boost performance
3361 		 * especially in multi-threaded overwrite requests.
3362 		 */
3363 		if (offset + length <= i_size_read(inode)) {
3364 			ret = ext4_map_blocks(NULL, inode, &map, 0);
3365 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3366 				goto out;
3367 		}
3368 		ret = ext4_iomap_alloc(inode, &map, flags);
3369 	} else {
3370 		ret = ext4_map_blocks(NULL, inode, &map, 0);
3371 	}
3372 
3373 	if (ret < 0)
3374 		return ret;
3375 out:
3376 	/*
3377 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
3378 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
3379 	 * limiting the length of the mapping returned.
3380 	 */
3381 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
3382 
3383 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3384 
3385 	return 0;
3386 }
3387 
3388 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3389 		loff_t length, unsigned flags, struct iomap *iomap,
3390 		struct iomap *srcmap)
3391 {
3392 	int ret;
3393 
3394 	/*
3395 	 * Even for writes we don't need to allocate blocks, so just pretend
3396 	 * we are reading to save overhead of starting a transaction.
3397 	 */
3398 	flags &= ~IOMAP_WRITE;
3399 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3400 	WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
3401 	return ret;
3402 }
3403 
3404 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3405 			  ssize_t written, unsigned flags, struct iomap *iomap)
3406 {
3407 	/*
3408 	 * Check to see whether an error occurred while writing out the data to
3409 	 * the allocated blocks. If so, return the magic error code so that we
3410 	 * fallback to buffered I/O and attempt to complete the remainder of
3411 	 * the I/O. Any blocks that may have been allocated in preparation for
3412 	 * the direct I/O will be reused during buffered I/O.
3413 	 */
3414 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3415 		return -ENOTBLK;
3416 
3417 	return 0;
3418 }
3419 
3420 const struct iomap_ops ext4_iomap_ops = {
3421 	.iomap_begin		= ext4_iomap_begin,
3422 	.iomap_end		= ext4_iomap_end,
3423 };
3424 
3425 const struct iomap_ops ext4_iomap_overwrite_ops = {
3426 	.iomap_begin		= ext4_iomap_overwrite_begin,
3427 	.iomap_end		= ext4_iomap_end,
3428 };
3429 
3430 static bool ext4_iomap_is_delalloc(struct inode *inode,
3431 				   struct ext4_map_blocks *map)
3432 {
3433 	struct extent_status es;
3434 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3435 
3436 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3437 				  map->m_lblk, end, &es);
3438 
3439 	if (!es.es_len || es.es_lblk > end)
3440 		return false;
3441 
3442 	if (es.es_lblk > map->m_lblk) {
3443 		map->m_len = es.es_lblk - map->m_lblk;
3444 		return false;
3445 	}
3446 
3447 	offset = map->m_lblk - es.es_lblk;
3448 	map->m_len = es.es_len - offset;
3449 
3450 	return true;
3451 }
3452 
3453 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3454 				   loff_t length, unsigned int flags,
3455 				   struct iomap *iomap, struct iomap *srcmap)
3456 {
3457 	int ret;
3458 	bool delalloc = false;
3459 	struct ext4_map_blocks map;
3460 	u8 blkbits = inode->i_blkbits;
3461 
3462 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3463 		return -EINVAL;
3464 
3465 	if (ext4_has_inline_data(inode)) {
3466 		ret = ext4_inline_data_iomap(inode, iomap);
3467 		if (ret != -EAGAIN) {
3468 			if (ret == 0 && offset >= iomap->length)
3469 				ret = -ENOENT;
3470 			return ret;
3471 		}
3472 	}
3473 
3474 	/*
3475 	 * Calculate the first and last logical block respectively.
3476 	 */
3477 	map.m_lblk = offset >> blkbits;
3478 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3479 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3480 
3481 	/*
3482 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3483 	 * So handle it here itself instead of querying ext4_map_blocks().
3484 	 * Since ext4_map_blocks() will warn about it and will return
3485 	 * -EIO error.
3486 	 */
3487 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3488 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3489 
3490 		if (offset >= sbi->s_bitmap_maxbytes) {
3491 			map.m_flags = 0;
3492 			goto set_iomap;
3493 		}
3494 	}
3495 
3496 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3497 	if (ret < 0)
3498 		return ret;
3499 	if (ret == 0)
3500 		delalloc = ext4_iomap_is_delalloc(inode, &map);
3501 
3502 set_iomap:
3503 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3504 	if (delalloc && iomap->type == IOMAP_HOLE)
3505 		iomap->type = IOMAP_DELALLOC;
3506 
3507 	return 0;
3508 }
3509 
3510 const struct iomap_ops ext4_iomap_report_ops = {
3511 	.iomap_begin = ext4_iomap_begin_report,
3512 };
3513 
3514 /*
3515  * For data=journal mode, folio should be marked dirty only when it was
3516  * writeably mapped. When that happens, it was already attached to the
3517  * transaction and marked as jbddirty (we take care of this in
3518  * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
3519  * so we should have nothing to do here, except for the case when someone
3520  * had the page pinned and dirtied the page through this pin (e.g. by doing
3521  * direct IO to it). In that case we'd need to attach buffers here to the
3522  * transaction but we cannot due to lock ordering.  We cannot just dirty the
3523  * folio and leave attached buffers clean, because the buffers' dirty state is
3524  * "definitive".  We cannot just set the buffers dirty or jbddirty because all
3525  * the journalling code will explode.  So what we do is to mark the folio
3526  * "pending dirty" and next time ext4_writepages() is called, attach buffers
3527  * to the transaction appropriately.
3528  */
3529 static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3530 		struct folio *folio)
3531 {
3532 	WARN_ON_ONCE(!folio_buffers(folio));
3533 	if (folio_maybe_dma_pinned(folio))
3534 		folio_set_checked(folio);
3535 	return filemap_dirty_folio(mapping, folio);
3536 }
3537 
3538 static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
3539 {
3540 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3541 	WARN_ON_ONCE(!folio_buffers(folio));
3542 	return block_dirty_folio(mapping, folio);
3543 }
3544 
3545 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3546 				    struct file *file, sector_t *span)
3547 {
3548 	return iomap_swapfile_activate(sis, file, span,
3549 				       &ext4_iomap_report_ops);
3550 }
3551 
3552 static const struct address_space_operations ext4_aops = {
3553 	.read_folio		= ext4_read_folio,
3554 	.readahead		= ext4_readahead,
3555 	.writepages		= ext4_writepages,
3556 	.write_begin		= ext4_write_begin,
3557 	.write_end		= ext4_write_end,
3558 	.dirty_folio		= ext4_dirty_folio,
3559 	.bmap			= ext4_bmap,
3560 	.invalidate_folio	= ext4_invalidate_folio,
3561 	.release_folio		= ext4_release_folio,
3562 	.direct_IO		= noop_direct_IO,
3563 	.migrate_folio		= buffer_migrate_folio,
3564 	.is_partially_uptodate  = block_is_partially_uptodate,
3565 	.error_remove_page	= generic_error_remove_page,
3566 	.swap_activate		= ext4_iomap_swap_activate,
3567 };
3568 
3569 static const struct address_space_operations ext4_journalled_aops = {
3570 	.read_folio		= ext4_read_folio,
3571 	.readahead		= ext4_readahead,
3572 	.writepages		= ext4_writepages,
3573 	.write_begin		= ext4_write_begin,
3574 	.write_end		= ext4_journalled_write_end,
3575 	.dirty_folio		= ext4_journalled_dirty_folio,
3576 	.bmap			= ext4_bmap,
3577 	.invalidate_folio	= ext4_journalled_invalidate_folio,
3578 	.release_folio		= ext4_release_folio,
3579 	.direct_IO		= noop_direct_IO,
3580 	.migrate_folio		= buffer_migrate_folio_norefs,
3581 	.is_partially_uptodate  = block_is_partially_uptodate,
3582 	.error_remove_page	= generic_error_remove_page,
3583 	.swap_activate		= ext4_iomap_swap_activate,
3584 };
3585 
3586 static const struct address_space_operations ext4_da_aops = {
3587 	.read_folio		= ext4_read_folio,
3588 	.readahead		= ext4_readahead,
3589 	.writepages		= ext4_writepages,
3590 	.write_begin		= ext4_da_write_begin,
3591 	.write_end		= ext4_da_write_end,
3592 	.dirty_folio		= ext4_dirty_folio,
3593 	.bmap			= ext4_bmap,
3594 	.invalidate_folio	= ext4_invalidate_folio,
3595 	.release_folio		= ext4_release_folio,
3596 	.direct_IO		= noop_direct_IO,
3597 	.migrate_folio		= buffer_migrate_folio,
3598 	.is_partially_uptodate  = block_is_partially_uptodate,
3599 	.error_remove_page	= generic_error_remove_page,
3600 	.swap_activate		= ext4_iomap_swap_activate,
3601 };
3602 
3603 static const struct address_space_operations ext4_dax_aops = {
3604 	.writepages		= ext4_dax_writepages,
3605 	.direct_IO		= noop_direct_IO,
3606 	.dirty_folio		= noop_dirty_folio,
3607 	.bmap			= ext4_bmap,
3608 	.swap_activate		= ext4_iomap_swap_activate,
3609 };
3610 
3611 void ext4_set_aops(struct inode *inode)
3612 {
3613 	switch (ext4_inode_journal_mode(inode)) {
3614 	case EXT4_INODE_ORDERED_DATA_MODE:
3615 	case EXT4_INODE_WRITEBACK_DATA_MODE:
3616 		break;
3617 	case EXT4_INODE_JOURNAL_DATA_MODE:
3618 		inode->i_mapping->a_ops = &ext4_journalled_aops;
3619 		return;
3620 	default:
3621 		BUG();
3622 	}
3623 	if (IS_DAX(inode))
3624 		inode->i_mapping->a_ops = &ext4_dax_aops;
3625 	else if (test_opt(inode->i_sb, DELALLOC))
3626 		inode->i_mapping->a_ops = &ext4_da_aops;
3627 	else
3628 		inode->i_mapping->a_ops = &ext4_aops;
3629 }
3630 
3631 static int __ext4_block_zero_page_range(handle_t *handle,
3632 		struct address_space *mapping, loff_t from, loff_t length)
3633 {
3634 	ext4_fsblk_t index = from >> PAGE_SHIFT;
3635 	unsigned offset = from & (PAGE_SIZE-1);
3636 	unsigned blocksize, pos;
3637 	ext4_lblk_t iblock;
3638 	struct inode *inode = mapping->host;
3639 	struct buffer_head *bh;
3640 	struct folio *folio;
3641 	int err = 0;
3642 
3643 	folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
3644 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3645 				    mapping_gfp_constraint(mapping, ~__GFP_FS));
3646 	if (IS_ERR(folio))
3647 		return PTR_ERR(folio);
3648 
3649 	blocksize = inode->i_sb->s_blocksize;
3650 
3651 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3652 
3653 	bh = folio_buffers(folio);
3654 	if (!bh) {
3655 		create_empty_buffers(&folio->page, blocksize, 0);
3656 		bh = folio_buffers(folio);
3657 	}
3658 
3659 	/* Find the buffer that contains "offset" */
3660 	pos = blocksize;
3661 	while (offset >= pos) {
3662 		bh = bh->b_this_page;
3663 		iblock++;
3664 		pos += blocksize;
3665 	}
3666 	if (buffer_freed(bh)) {
3667 		BUFFER_TRACE(bh, "freed: skip");
3668 		goto unlock;
3669 	}
3670 	if (!buffer_mapped(bh)) {
3671 		BUFFER_TRACE(bh, "unmapped");
3672 		ext4_get_block(inode, iblock, bh, 0);
3673 		/* unmapped? It's a hole - nothing to do */
3674 		if (!buffer_mapped(bh)) {
3675 			BUFFER_TRACE(bh, "still unmapped");
3676 			goto unlock;
3677 		}
3678 	}
3679 
3680 	/* Ok, it's mapped. Make sure it's up-to-date */
3681 	if (folio_test_uptodate(folio))
3682 		set_buffer_uptodate(bh);
3683 
3684 	if (!buffer_uptodate(bh)) {
3685 		err = ext4_read_bh_lock(bh, 0, true);
3686 		if (err)
3687 			goto unlock;
3688 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3689 			/* We expect the key to be set. */
3690 			BUG_ON(!fscrypt_has_encryption_key(inode));
3691 			err = fscrypt_decrypt_pagecache_blocks(folio,
3692 							       blocksize,
3693 							       bh_offset(bh));
3694 			if (err) {
3695 				clear_buffer_uptodate(bh);
3696 				goto unlock;
3697 			}
3698 		}
3699 	}
3700 	if (ext4_should_journal_data(inode)) {
3701 		BUFFER_TRACE(bh, "get write access");
3702 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3703 						    EXT4_JTR_NONE);
3704 		if (err)
3705 			goto unlock;
3706 	}
3707 	folio_zero_range(folio, offset, length);
3708 	BUFFER_TRACE(bh, "zeroed end of block");
3709 
3710 	if (ext4_should_journal_data(inode)) {
3711 		err = ext4_dirty_journalled_data(handle, bh);
3712 	} else {
3713 		err = 0;
3714 		mark_buffer_dirty(bh);
3715 		if (ext4_should_order_data(inode))
3716 			err = ext4_jbd2_inode_add_write(handle, inode, from,
3717 					length);
3718 	}
3719 
3720 unlock:
3721 	folio_unlock(folio);
3722 	folio_put(folio);
3723 	return err;
3724 }
3725 
3726 /*
3727  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3728  * starting from file offset 'from'.  The range to be zero'd must
3729  * be contained with in one block.  If the specified range exceeds
3730  * the end of the block it will be shortened to end of the block
3731  * that corresponds to 'from'
3732  */
3733 static int ext4_block_zero_page_range(handle_t *handle,
3734 		struct address_space *mapping, loff_t from, loff_t length)
3735 {
3736 	struct inode *inode = mapping->host;
3737 	unsigned offset = from & (PAGE_SIZE-1);
3738 	unsigned blocksize = inode->i_sb->s_blocksize;
3739 	unsigned max = blocksize - (offset & (blocksize - 1));
3740 
3741 	/*
3742 	 * correct length if it does not fall between
3743 	 * 'from' and the end of the block
3744 	 */
3745 	if (length > max || length < 0)
3746 		length = max;
3747 
3748 	if (IS_DAX(inode)) {
3749 		return dax_zero_range(inode, from, length, NULL,
3750 				      &ext4_iomap_ops);
3751 	}
3752 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3753 }
3754 
3755 /*
3756  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3757  * up to the end of the block which corresponds to `from'.
3758  * This required during truncate. We need to physically zero the tail end
3759  * of that block so it doesn't yield old data if the file is later grown.
3760  */
3761 static int ext4_block_truncate_page(handle_t *handle,
3762 		struct address_space *mapping, loff_t from)
3763 {
3764 	unsigned offset = from & (PAGE_SIZE-1);
3765 	unsigned length;
3766 	unsigned blocksize;
3767 	struct inode *inode = mapping->host;
3768 
3769 	/* If we are processing an encrypted inode during orphan list handling */
3770 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3771 		return 0;
3772 
3773 	blocksize = inode->i_sb->s_blocksize;
3774 	length = blocksize - (offset & (blocksize - 1));
3775 
3776 	return ext4_block_zero_page_range(handle, mapping, from, length);
3777 }
3778 
3779 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3780 			     loff_t lstart, loff_t length)
3781 {
3782 	struct super_block *sb = inode->i_sb;
3783 	struct address_space *mapping = inode->i_mapping;
3784 	unsigned partial_start, partial_end;
3785 	ext4_fsblk_t start, end;
3786 	loff_t byte_end = (lstart + length - 1);
3787 	int err = 0;
3788 
3789 	partial_start = lstart & (sb->s_blocksize - 1);
3790 	partial_end = byte_end & (sb->s_blocksize - 1);
3791 
3792 	start = lstart >> sb->s_blocksize_bits;
3793 	end = byte_end >> sb->s_blocksize_bits;
3794 
3795 	/* Handle partial zero within the single block */
3796 	if (start == end &&
3797 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3798 		err = ext4_block_zero_page_range(handle, mapping,
3799 						 lstart, length);
3800 		return err;
3801 	}
3802 	/* Handle partial zero out on the start of the range */
3803 	if (partial_start) {
3804 		err = ext4_block_zero_page_range(handle, mapping,
3805 						 lstart, sb->s_blocksize);
3806 		if (err)
3807 			return err;
3808 	}
3809 	/* Handle partial zero out on the end of the range */
3810 	if (partial_end != sb->s_blocksize - 1)
3811 		err = ext4_block_zero_page_range(handle, mapping,
3812 						 byte_end - partial_end,
3813 						 partial_end + 1);
3814 	return err;
3815 }
3816 
3817 int ext4_can_truncate(struct inode *inode)
3818 {
3819 	if (S_ISREG(inode->i_mode))
3820 		return 1;
3821 	if (S_ISDIR(inode->i_mode))
3822 		return 1;
3823 	if (S_ISLNK(inode->i_mode))
3824 		return !ext4_inode_is_fast_symlink(inode);
3825 	return 0;
3826 }
3827 
3828 /*
3829  * We have to make sure i_disksize gets properly updated before we truncate
3830  * page cache due to hole punching or zero range. Otherwise i_disksize update
3831  * can get lost as it may have been postponed to submission of writeback but
3832  * that will never happen after we truncate page cache.
3833  */
3834 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3835 				      loff_t len)
3836 {
3837 	handle_t *handle;
3838 	int ret;
3839 
3840 	loff_t size = i_size_read(inode);
3841 
3842 	WARN_ON(!inode_is_locked(inode));
3843 	if (offset > size || offset + len < size)
3844 		return 0;
3845 
3846 	if (EXT4_I(inode)->i_disksize >= size)
3847 		return 0;
3848 
3849 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3850 	if (IS_ERR(handle))
3851 		return PTR_ERR(handle);
3852 	ext4_update_i_disksize(inode, size);
3853 	ret = ext4_mark_inode_dirty(handle, inode);
3854 	ext4_journal_stop(handle);
3855 
3856 	return ret;
3857 }
3858 
3859 static void ext4_wait_dax_page(struct inode *inode)
3860 {
3861 	filemap_invalidate_unlock(inode->i_mapping);
3862 	schedule();
3863 	filemap_invalidate_lock(inode->i_mapping);
3864 }
3865 
3866 int ext4_break_layouts(struct inode *inode)
3867 {
3868 	struct page *page;
3869 	int error;
3870 
3871 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3872 		return -EINVAL;
3873 
3874 	do {
3875 		page = dax_layout_busy_page(inode->i_mapping);
3876 		if (!page)
3877 			return 0;
3878 
3879 		error = ___wait_var_event(&page->_refcount,
3880 				atomic_read(&page->_refcount) == 1,
3881 				TASK_INTERRUPTIBLE, 0, 0,
3882 				ext4_wait_dax_page(inode));
3883 	} while (error == 0);
3884 
3885 	return error;
3886 }
3887 
3888 /*
3889  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3890  * associated with the given offset and length
3891  *
3892  * @inode:  File inode
3893  * @offset: The offset where the hole will begin
3894  * @len:    The length of the hole
3895  *
3896  * Returns: 0 on success or negative on failure
3897  */
3898 
3899 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3900 {
3901 	struct inode *inode = file_inode(file);
3902 	struct super_block *sb = inode->i_sb;
3903 	ext4_lblk_t first_block, stop_block;
3904 	struct address_space *mapping = inode->i_mapping;
3905 	loff_t first_block_offset, last_block_offset, max_length;
3906 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3907 	handle_t *handle;
3908 	unsigned int credits;
3909 	int ret = 0, ret2 = 0;
3910 
3911 	trace_ext4_punch_hole(inode, offset, length, 0);
3912 
3913 	/*
3914 	 * Write out all dirty pages to avoid race conditions
3915 	 * Then release them.
3916 	 */
3917 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3918 		ret = filemap_write_and_wait_range(mapping, offset,
3919 						   offset + length - 1);
3920 		if (ret)
3921 			return ret;
3922 	}
3923 
3924 	inode_lock(inode);
3925 
3926 	/* No need to punch hole beyond i_size */
3927 	if (offset >= inode->i_size)
3928 		goto out_mutex;
3929 
3930 	/*
3931 	 * If the hole extends beyond i_size, set the hole
3932 	 * to end after the page that contains i_size
3933 	 */
3934 	if (offset + length > inode->i_size) {
3935 		length = inode->i_size +
3936 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
3937 		   offset;
3938 	}
3939 
3940 	/*
3941 	 * For punch hole the length + offset needs to be within one block
3942 	 * before last range. Adjust the length if it goes beyond that limit.
3943 	 */
3944 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
3945 	if (offset + length > max_length)
3946 		length = max_length - offset;
3947 
3948 	if (offset & (sb->s_blocksize - 1) ||
3949 	    (offset + length) & (sb->s_blocksize - 1)) {
3950 		/*
3951 		 * Attach jinode to inode for jbd2 if we do any zeroing of
3952 		 * partial block
3953 		 */
3954 		ret = ext4_inode_attach_jinode(inode);
3955 		if (ret < 0)
3956 			goto out_mutex;
3957 
3958 	}
3959 
3960 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
3961 	inode_dio_wait(inode);
3962 
3963 	ret = file_modified(file);
3964 	if (ret)
3965 		goto out_mutex;
3966 
3967 	/*
3968 	 * Prevent page faults from reinstantiating pages we have released from
3969 	 * page cache.
3970 	 */
3971 	filemap_invalidate_lock(mapping);
3972 
3973 	ret = ext4_break_layouts(inode);
3974 	if (ret)
3975 		goto out_dio;
3976 
3977 	first_block_offset = round_up(offset, sb->s_blocksize);
3978 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3979 
3980 	/* Now release the pages and zero block aligned part of pages*/
3981 	if (last_block_offset > first_block_offset) {
3982 		ret = ext4_update_disksize_before_punch(inode, offset, length);
3983 		if (ret)
3984 			goto out_dio;
3985 		truncate_pagecache_range(inode, first_block_offset,
3986 					 last_block_offset);
3987 	}
3988 
3989 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3990 		credits = ext4_writepage_trans_blocks(inode);
3991 	else
3992 		credits = ext4_blocks_for_truncate(inode);
3993 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3994 	if (IS_ERR(handle)) {
3995 		ret = PTR_ERR(handle);
3996 		ext4_std_error(sb, ret);
3997 		goto out_dio;
3998 	}
3999 
4000 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4001 				       length);
4002 	if (ret)
4003 		goto out_stop;
4004 
4005 	first_block = (offset + sb->s_blocksize - 1) >>
4006 		EXT4_BLOCK_SIZE_BITS(sb);
4007 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4008 
4009 	/* If there are blocks to remove, do it */
4010 	if (stop_block > first_block) {
4011 
4012 		down_write(&EXT4_I(inode)->i_data_sem);
4013 		ext4_discard_preallocations(inode, 0);
4014 
4015 		ext4_es_remove_extent(inode, first_block,
4016 				      stop_block - first_block);
4017 
4018 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4019 			ret = ext4_ext_remove_space(inode, first_block,
4020 						    stop_block - 1);
4021 		else
4022 			ret = ext4_ind_remove_space(handle, inode, first_block,
4023 						    stop_block);
4024 
4025 		up_write(&EXT4_I(inode)->i_data_sem);
4026 	}
4027 	ext4_fc_track_range(handle, inode, first_block, stop_block);
4028 	if (IS_SYNC(inode))
4029 		ext4_handle_sync(handle);
4030 
4031 	inode->i_mtime = inode_set_ctime_current(inode);
4032 	ret2 = ext4_mark_inode_dirty(handle, inode);
4033 	if (unlikely(ret2))
4034 		ret = ret2;
4035 	if (ret >= 0)
4036 		ext4_update_inode_fsync_trans(handle, inode, 1);
4037 out_stop:
4038 	ext4_journal_stop(handle);
4039 out_dio:
4040 	filemap_invalidate_unlock(mapping);
4041 out_mutex:
4042 	inode_unlock(inode);
4043 	return ret;
4044 }
4045 
4046 int ext4_inode_attach_jinode(struct inode *inode)
4047 {
4048 	struct ext4_inode_info *ei = EXT4_I(inode);
4049 	struct jbd2_inode *jinode;
4050 
4051 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4052 		return 0;
4053 
4054 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4055 	spin_lock(&inode->i_lock);
4056 	if (!ei->jinode) {
4057 		if (!jinode) {
4058 			spin_unlock(&inode->i_lock);
4059 			return -ENOMEM;
4060 		}
4061 		ei->jinode = jinode;
4062 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4063 		jinode = NULL;
4064 	}
4065 	spin_unlock(&inode->i_lock);
4066 	if (unlikely(jinode != NULL))
4067 		jbd2_free_inode(jinode);
4068 	return 0;
4069 }
4070 
4071 /*
4072  * ext4_truncate()
4073  *
4074  * We block out ext4_get_block() block instantiations across the entire
4075  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4076  * simultaneously on behalf of the same inode.
4077  *
4078  * As we work through the truncate and commit bits of it to the journal there
4079  * is one core, guiding principle: the file's tree must always be consistent on
4080  * disk.  We must be able to restart the truncate after a crash.
4081  *
4082  * The file's tree may be transiently inconsistent in memory (although it
4083  * probably isn't), but whenever we close off and commit a journal transaction,
4084  * the contents of (the filesystem + the journal) must be consistent and
4085  * restartable.  It's pretty simple, really: bottom up, right to left (although
4086  * left-to-right works OK too).
4087  *
4088  * Note that at recovery time, journal replay occurs *before* the restart of
4089  * truncate against the orphan inode list.
4090  *
4091  * The committed inode has the new, desired i_size (which is the same as
4092  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4093  * that this inode's truncate did not complete and it will again call
4094  * ext4_truncate() to have another go.  So there will be instantiated blocks
4095  * to the right of the truncation point in a crashed ext4 filesystem.  But
4096  * that's fine - as long as they are linked from the inode, the post-crash
4097  * ext4_truncate() run will find them and release them.
4098  */
4099 int ext4_truncate(struct inode *inode)
4100 {
4101 	struct ext4_inode_info *ei = EXT4_I(inode);
4102 	unsigned int credits;
4103 	int err = 0, err2;
4104 	handle_t *handle;
4105 	struct address_space *mapping = inode->i_mapping;
4106 
4107 	/*
4108 	 * There is a possibility that we're either freeing the inode
4109 	 * or it's a completely new inode. In those cases we might not
4110 	 * have i_rwsem locked because it's not necessary.
4111 	 */
4112 	if (!(inode->i_state & (I_NEW|I_FREEING)))
4113 		WARN_ON(!inode_is_locked(inode));
4114 	trace_ext4_truncate_enter(inode);
4115 
4116 	if (!ext4_can_truncate(inode))
4117 		goto out_trace;
4118 
4119 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4120 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4121 
4122 	if (ext4_has_inline_data(inode)) {
4123 		int has_inline = 1;
4124 
4125 		err = ext4_inline_data_truncate(inode, &has_inline);
4126 		if (err || has_inline)
4127 			goto out_trace;
4128 	}
4129 
4130 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4131 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4132 		err = ext4_inode_attach_jinode(inode);
4133 		if (err)
4134 			goto out_trace;
4135 	}
4136 
4137 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4138 		credits = ext4_writepage_trans_blocks(inode);
4139 	else
4140 		credits = ext4_blocks_for_truncate(inode);
4141 
4142 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4143 	if (IS_ERR(handle)) {
4144 		err = PTR_ERR(handle);
4145 		goto out_trace;
4146 	}
4147 
4148 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4149 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4150 
4151 	/*
4152 	 * We add the inode to the orphan list, so that if this
4153 	 * truncate spans multiple transactions, and we crash, we will
4154 	 * resume the truncate when the filesystem recovers.  It also
4155 	 * marks the inode dirty, to catch the new size.
4156 	 *
4157 	 * Implication: the file must always be in a sane, consistent
4158 	 * truncatable state while each transaction commits.
4159 	 */
4160 	err = ext4_orphan_add(handle, inode);
4161 	if (err)
4162 		goto out_stop;
4163 
4164 	down_write(&EXT4_I(inode)->i_data_sem);
4165 
4166 	ext4_discard_preallocations(inode, 0);
4167 
4168 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4169 		err = ext4_ext_truncate(handle, inode);
4170 	else
4171 		ext4_ind_truncate(handle, inode);
4172 
4173 	up_write(&ei->i_data_sem);
4174 	if (err)
4175 		goto out_stop;
4176 
4177 	if (IS_SYNC(inode))
4178 		ext4_handle_sync(handle);
4179 
4180 out_stop:
4181 	/*
4182 	 * If this was a simple ftruncate() and the file will remain alive,
4183 	 * then we need to clear up the orphan record which we created above.
4184 	 * However, if this was a real unlink then we were called by
4185 	 * ext4_evict_inode(), and we allow that function to clean up the
4186 	 * orphan info for us.
4187 	 */
4188 	if (inode->i_nlink)
4189 		ext4_orphan_del(handle, inode);
4190 
4191 	inode->i_mtime = inode_set_ctime_current(inode);
4192 	err2 = ext4_mark_inode_dirty(handle, inode);
4193 	if (unlikely(err2 && !err))
4194 		err = err2;
4195 	ext4_journal_stop(handle);
4196 
4197 out_trace:
4198 	trace_ext4_truncate_exit(inode);
4199 	return err;
4200 }
4201 
4202 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4203 {
4204 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4205 		return inode_peek_iversion_raw(inode);
4206 	else
4207 		return inode_peek_iversion(inode);
4208 }
4209 
4210 static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
4211 				 struct ext4_inode_info *ei)
4212 {
4213 	struct inode *inode = &(ei->vfs_inode);
4214 	u64 i_blocks = READ_ONCE(inode->i_blocks);
4215 	struct super_block *sb = inode->i_sb;
4216 
4217 	if (i_blocks <= ~0U) {
4218 		/*
4219 		 * i_blocks can be represented in a 32 bit variable
4220 		 * as multiple of 512 bytes
4221 		 */
4222 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4223 		raw_inode->i_blocks_high = 0;
4224 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4225 		return 0;
4226 	}
4227 
4228 	/*
4229 	 * This should never happen since sb->s_maxbytes should not have
4230 	 * allowed this, sb->s_maxbytes was set according to the huge_file
4231 	 * feature in ext4_fill_super().
4232 	 */
4233 	if (!ext4_has_feature_huge_file(sb))
4234 		return -EFSCORRUPTED;
4235 
4236 	if (i_blocks <= 0xffffffffffffULL) {
4237 		/*
4238 		 * i_blocks can be represented in a 48 bit variable
4239 		 * as multiple of 512 bytes
4240 		 */
4241 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4242 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4243 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4244 	} else {
4245 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4246 		/* i_block is stored in file system block size */
4247 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
4248 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4249 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4250 	}
4251 	return 0;
4252 }
4253 
4254 static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
4255 {
4256 	struct ext4_inode_info *ei = EXT4_I(inode);
4257 	uid_t i_uid;
4258 	gid_t i_gid;
4259 	projid_t i_projid;
4260 	int block;
4261 	int err;
4262 
4263 	err = ext4_inode_blocks_set(raw_inode, ei);
4264 
4265 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4266 	i_uid = i_uid_read(inode);
4267 	i_gid = i_gid_read(inode);
4268 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4269 	if (!(test_opt(inode->i_sb, NO_UID32))) {
4270 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4271 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4272 		/*
4273 		 * Fix up interoperability with old kernels. Otherwise,
4274 		 * old inodes get re-used with the upper 16 bits of the
4275 		 * uid/gid intact.
4276 		 */
4277 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4278 			raw_inode->i_uid_high = 0;
4279 			raw_inode->i_gid_high = 0;
4280 		} else {
4281 			raw_inode->i_uid_high =
4282 				cpu_to_le16(high_16_bits(i_uid));
4283 			raw_inode->i_gid_high =
4284 				cpu_to_le16(high_16_bits(i_gid));
4285 		}
4286 	} else {
4287 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4288 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4289 		raw_inode->i_uid_high = 0;
4290 		raw_inode->i_gid_high = 0;
4291 	}
4292 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4293 
4294 	EXT4_INODE_SET_CTIME(inode, raw_inode);
4295 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4296 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4297 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4298 
4299 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4300 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4301 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4302 		raw_inode->i_file_acl_high =
4303 			cpu_to_le16(ei->i_file_acl >> 32);
4304 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4305 	ext4_isize_set(raw_inode, ei->i_disksize);
4306 
4307 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4308 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4309 		if (old_valid_dev(inode->i_rdev)) {
4310 			raw_inode->i_block[0] =
4311 				cpu_to_le32(old_encode_dev(inode->i_rdev));
4312 			raw_inode->i_block[1] = 0;
4313 		} else {
4314 			raw_inode->i_block[0] = 0;
4315 			raw_inode->i_block[1] =
4316 				cpu_to_le32(new_encode_dev(inode->i_rdev));
4317 			raw_inode->i_block[2] = 0;
4318 		}
4319 	} else if (!ext4_has_inline_data(inode)) {
4320 		for (block = 0; block < EXT4_N_BLOCKS; block++)
4321 			raw_inode->i_block[block] = ei->i_data[block];
4322 	}
4323 
4324 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4325 		u64 ivers = ext4_inode_peek_iversion(inode);
4326 
4327 		raw_inode->i_disk_version = cpu_to_le32(ivers);
4328 		if (ei->i_extra_isize) {
4329 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4330 				raw_inode->i_version_hi =
4331 					cpu_to_le32(ivers >> 32);
4332 			raw_inode->i_extra_isize =
4333 				cpu_to_le16(ei->i_extra_isize);
4334 		}
4335 	}
4336 
4337 	if (i_projid != EXT4_DEF_PROJID &&
4338 	    !ext4_has_feature_project(inode->i_sb))
4339 		err = err ?: -EFSCORRUPTED;
4340 
4341 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4342 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4343 		raw_inode->i_projid = cpu_to_le32(i_projid);
4344 
4345 	ext4_inode_csum_set(inode, raw_inode, ei);
4346 	return err;
4347 }
4348 
4349 /*
4350  * ext4_get_inode_loc returns with an extra refcount against the inode's
4351  * underlying buffer_head on success. If we pass 'inode' and it does not
4352  * have in-inode xattr, we have all inode data in memory that is needed
4353  * to recreate the on-disk version of this inode.
4354  */
4355 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4356 				struct inode *inode, struct ext4_iloc *iloc,
4357 				ext4_fsblk_t *ret_block)
4358 {
4359 	struct ext4_group_desc	*gdp;
4360 	struct buffer_head	*bh;
4361 	ext4_fsblk_t		block;
4362 	struct blk_plug		plug;
4363 	int			inodes_per_block, inode_offset;
4364 
4365 	iloc->bh = NULL;
4366 	if (ino < EXT4_ROOT_INO ||
4367 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4368 		return -EFSCORRUPTED;
4369 
4370 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4371 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4372 	if (!gdp)
4373 		return -EIO;
4374 
4375 	/*
4376 	 * Figure out the offset within the block group inode table
4377 	 */
4378 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4379 	inode_offset = ((ino - 1) %
4380 			EXT4_INODES_PER_GROUP(sb));
4381 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4382 
4383 	block = ext4_inode_table(sb, gdp);
4384 	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4385 	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4386 		ext4_error(sb, "Invalid inode table block %llu in "
4387 			   "block_group %u", block, iloc->block_group);
4388 		return -EFSCORRUPTED;
4389 	}
4390 	block += (inode_offset / inodes_per_block);
4391 
4392 	bh = sb_getblk(sb, block);
4393 	if (unlikely(!bh))
4394 		return -ENOMEM;
4395 	if (ext4_buffer_uptodate(bh))
4396 		goto has_buffer;
4397 
4398 	lock_buffer(bh);
4399 	if (ext4_buffer_uptodate(bh)) {
4400 		/* Someone brought it uptodate while we waited */
4401 		unlock_buffer(bh);
4402 		goto has_buffer;
4403 	}
4404 
4405 	/*
4406 	 * If we have all information of the inode in memory and this
4407 	 * is the only valid inode in the block, we need not read the
4408 	 * block.
4409 	 */
4410 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4411 		struct buffer_head *bitmap_bh;
4412 		int i, start;
4413 
4414 		start = inode_offset & ~(inodes_per_block - 1);
4415 
4416 		/* Is the inode bitmap in cache? */
4417 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4418 		if (unlikely(!bitmap_bh))
4419 			goto make_io;
4420 
4421 		/*
4422 		 * If the inode bitmap isn't in cache then the
4423 		 * optimisation may end up performing two reads instead
4424 		 * of one, so skip it.
4425 		 */
4426 		if (!buffer_uptodate(bitmap_bh)) {
4427 			brelse(bitmap_bh);
4428 			goto make_io;
4429 		}
4430 		for (i = start; i < start + inodes_per_block; i++) {
4431 			if (i == inode_offset)
4432 				continue;
4433 			if (ext4_test_bit(i, bitmap_bh->b_data))
4434 				break;
4435 		}
4436 		brelse(bitmap_bh);
4437 		if (i == start + inodes_per_block) {
4438 			struct ext4_inode *raw_inode =
4439 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4440 
4441 			/* all other inodes are free, so skip I/O */
4442 			memset(bh->b_data, 0, bh->b_size);
4443 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4444 				ext4_fill_raw_inode(inode, raw_inode);
4445 			set_buffer_uptodate(bh);
4446 			unlock_buffer(bh);
4447 			goto has_buffer;
4448 		}
4449 	}
4450 
4451 make_io:
4452 	/*
4453 	 * If we need to do any I/O, try to pre-readahead extra
4454 	 * blocks from the inode table.
4455 	 */
4456 	blk_start_plug(&plug);
4457 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4458 		ext4_fsblk_t b, end, table;
4459 		unsigned num;
4460 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4461 
4462 		table = ext4_inode_table(sb, gdp);
4463 		/* s_inode_readahead_blks is always a power of 2 */
4464 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4465 		if (table > b)
4466 			b = table;
4467 		end = b + ra_blks;
4468 		num = EXT4_INODES_PER_GROUP(sb);
4469 		if (ext4_has_group_desc_csum(sb))
4470 			num -= ext4_itable_unused_count(sb, gdp);
4471 		table += num / inodes_per_block;
4472 		if (end > table)
4473 			end = table;
4474 		while (b <= end)
4475 			ext4_sb_breadahead_unmovable(sb, b++);
4476 	}
4477 
4478 	/*
4479 	 * There are other valid inodes in the buffer, this inode
4480 	 * has in-inode xattrs, or we don't have this inode in memory.
4481 	 * Read the block from disk.
4482 	 */
4483 	trace_ext4_load_inode(sb, ino);
4484 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4485 	blk_finish_plug(&plug);
4486 	wait_on_buffer(bh);
4487 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4488 	if (!buffer_uptodate(bh)) {
4489 		if (ret_block)
4490 			*ret_block = block;
4491 		brelse(bh);
4492 		return -EIO;
4493 	}
4494 has_buffer:
4495 	iloc->bh = bh;
4496 	return 0;
4497 }
4498 
4499 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4500 					struct ext4_iloc *iloc)
4501 {
4502 	ext4_fsblk_t err_blk = 0;
4503 	int ret;
4504 
4505 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
4506 					&err_blk);
4507 
4508 	if (ret == -EIO)
4509 		ext4_error_inode_block(inode, err_blk, EIO,
4510 					"unable to read itable block");
4511 
4512 	return ret;
4513 }
4514 
4515 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4516 {
4517 	ext4_fsblk_t err_blk = 0;
4518 	int ret;
4519 
4520 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4521 					&err_blk);
4522 
4523 	if (ret == -EIO)
4524 		ext4_error_inode_block(inode, err_blk, EIO,
4525 					"unable to read itable block");
4526 
4527 	return ret;
4528 }
4529 
4530 
4531 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4532 			  struct ext4_iloc *iloc)
4533 {
4534 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4535 }
4536 
4537 static bool ext4_should_enable_dax(struct inode *inode)
4538 {
4539 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4540 
4541 	if (test_opt2(inode->i_sb, DAX_NEVER))
4542 		return false;
4543 	if (!S_ISREG(inode->i_mode))
4544 		return false;
4545 	if (ext4_should_journal_data(inode))
4546 		return false;
4547 	if (ext4_has_inline_data(inode))
4548 		return false;
4549 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4550 		return false;
4551 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4552 		return false;
4553 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4554 		return false;
4555 	if (test_opt(inode->i_sb, DAX_ALWAYS))
4556 		return true;
4557 
4558 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4559 }
4560 
4561 void ext4_set_inode_flags(struct inode *inode, bool init)
4562 {
4563 	unsigned int flags = EXT4_I(inode)->i_flags;
4564 	unsigned int new_fl = 0;
4565 
4566 	WARN_ON_ONCE(IS_DAX(inode) && init);
4567 
4568 	if (flags & EXT4_SYNC_FL)
4569 		new_fl |= S_SYNC;
4570 	if (flags & EXT4_APPEND_FL)
4571 		new_fl |= S_APPEND;
4572 	if (flags & EXT4_IMMUTABLE_FL)
4573 		new_fl |= S_IMMUTABLE;
4574 	if (flags & EXT4_NOATIME_FL)
4575 		new_fl |= S_NOATIME;
4576 	if (flags & EXT4_DIRSYNC_FL)
4577 		new_fl |= S_DIRSYNC;
4578 
4579 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4580 	 * here if already set. */
4581 	new_fl |= (inode->i_flags & S_DAX);
4582 	if (init && ext4_should_enable_dax(inode))
4583 		new_fl |= S_DAX;
4584 
4585 	if (flags & EXT4_ENCRYPT_FL)
4586 		new_fl |= S_ENCRYPTED;
4587 	if (flags & EXT4_CASEFOLD_FL)
4588 		new_fl |= S_CASEFOLD;
4589 	if (flags & EXT4_VERITY_FL)
4590 		new_fl |= S_VERITY;
4591 	inode_set_flags(inode, new_fl,
4592 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4593 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4594 }
4595 
4596 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4597 				  struct ext4_inode_info *ei)
4598 {
4599 	blkcnt_t i_blocks ;
4600 	struct inode *inode = &(ei->vfs_inode);
4601 	struct super_block *sb = inode->i_sb;
4602 
4603 	if (ext4_has_feature_huge_file(sb)) {
4604 		/* we are using combined 48 bit field */
4605 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4606 					le32_to_cpu(raw_inode->i_blocks_lo);
4607 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4608 			/* i_blocks represent file system block size */
4609 			return i_blocks  << (inode->i_blkbits - 9);
4610 		} else {
4611 			return i_blocks;
4612 		}
4613 	} else {
4614 		return le32_to_cpu(raw_inode->i_blocks_lo);
4615 	}
4616 }
4617 
4618 static inline int ext4_iget_extra_inode(struct inode *inode,
4619 					 struct ext4_inode *raw_inode,
4620 					 struct ext4_inode_info *ei)
4621 {
4622 	__le32 *magic = (void *)raw_inode +
4623 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4624 
4625 	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4626 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4627 		int err;
4628 
4629 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4630 		err = ext4_find_inline_data_nolock(inode);
4631 		if (!err && ext4_has_inline_data(inode))
4632 			ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4633 		return err;
4634 	} else
4635 		EXT4_I(inode)->i_inline_off = 0;
4636 	return 0;
4637 }
4638 
4639 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4640 {
4641 	if (!ext4_has_feature_project(inode->i_sb))
4642 		return -EOPNOTSUPP;
4643 	*projid = EXT4_I(inode)->i_projid;
4644 	return 0;
4645 }
4646 
4647 /*
4648  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4649  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4650  * set.
4651  */
4652 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4653 {
4654 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4655 		inode_set_iversion_raw(inode, val);
4656 	else
4657 		inode_set_iversion_queried(inode, val);
4658 }
4659 
4660 static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)
4661 
4662 {
4663 	if (flags & EXT4_IGET_EA_INODE) {
4664 		if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4665 			return "missing EA_INODE flag";
4666 		if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4667 		    EXT4_I(inode)->i_file_acl)
4668 			return "ea_inode with extended attributes";
4669 	} else {
4670 		if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4671 			return "unexpected EA_INODE flag";
4672 	}
4673 	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
4674 		return "unexpected bad inode w/o EXT4_IGET_BAD";
4675 	return NULL;
4676 }
4677 
4678 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4679 			  ext4_iget_flags flags, const char *function,
4680 			  unsigned int line)
4681 {
4682 	struct ext4_iloc iloc;
4683 	struct ext4_inode *raw_inode;
4684 	struct ext4_inode_info *ei;
4685 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
4686 	struct inode *inode;
4687 	const char *err_str;
4688 	journal_t *journal = EXT4_SB(sb)->s_journal;
4689 	long ret;
4690 	loff_t size;
4691 	int block;
4692 	uid_t i_uid;
4693 	gid_t i_gid;
4694 	projid_t i_projid;
4695 
4696 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4697 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4698 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4699 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
4700 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
4701 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
4702 	    (ino < EXT4_ROOT_INO) ||
4703 	    (ino > le32_to_cpu(es->s_inodes_count))) {
4704 		if (flags & EXT4_IGET_HANDLE)
4705 			return ERR_PTR(-ESTALE);
4706 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
4707 			     "inode #%lu: comm %s: iget: illegal inode #",
4708 			     ino, current->comm);
4709 		return ERR_PTR(-EFSCORRUPTED);
4710 	}
4711 
4712 	inode = iget_locked(sb, ino);
4713 	if (!inode)
4714 		return ERR_PTR(-ENOMEM);
4715 	if (!(inode->i_state & I_NEW)) {
4716 		if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4717 			ext4_error_inode(inode, function, line, 0, err_str);
4718 			iput(inode);
4719 			return ERR_PTR(-EFSCORRUPTED);
4720 		}
4721 		return inode;
4722 	}
4723 
4724 	ei = EXT4_I(inode);
4725 	iloc.bh = NULL;
4726 
4727 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4728 	if (ret < 0)
4729 		goto bad_inode;
4730 	raw_inode = ext4_raw_inode(&iloc);
4731 
4732 	if ((flags & EXT4_IGET_HANDLE) &&
4733 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4734 		ret = -ESTALE;
4735 		goto bad_inode;
4736 	}
4737 
4738 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4739 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4740 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4741 			EXT4_INODE_SIZE(inode->i_sb) ||
4742 		    (ei->i_extra_isize & 3)) {
4743 			ext4_error_inode(inode, function, line, 0,
4744 					 "iget: bad extra_isize %u "
4745 					 "(inode size %u)",
4746 					 ei->i_extra_isize,
4747 					 EXT4_INODE_SIZE(inode->i_sb));
4748 			ret = -EFSCORRUPTED;
4749 			goto bad_inode;
4750 		}
4751 	} else
4752 		ei->i_extra_isize = 0;
4753 
4754 	/* Precompute checksum seed for inode metadata */
4755 	if (ext4_has_metadata_csum(sb)) {
4756 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4757 		__u32 csum;
4758 		__le32 inum = cpu_to_le32(inode->i_ino);
4759 		__le32 gen = raw_inode->i_generation;
4760 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4761 				   sizeof(inum));
4762 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4763 					      sizeof(gen));
4764 	}
4765 
4766 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4767 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4768 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4769 		ext4_error_inode_err(inode, function, line, 0,
4770 				EFSBADCRC, "iget: checksum invalid");
4771 		ret = -EFSBADCRC;
4772 		goto bad_inode;
4773 	}
4774 
4775 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4776 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4777 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4778 	if (ext4_has_feature_project(sb) &&
4779 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4780 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4781 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4782 	else
4783 		i_projid = EXT4_DEF_PROJID;
4784 
4785 	if (!(test_opt(inode->i_sb, NO_UID32))) {
4786 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4787 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4788 	}
4789 	i_uid_write(inode, i_uid);
4790 	i_gid_write(inode, i_gid);
4791 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4792 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4793 
4794 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
4795 	ei->i_inline_off = 0;
4796 	ei->i_dir_start_lookup = 0;
4797 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4798 	/* We now have enough fields to check if the inode was active or not.
4799 	 * This is needed because nfsd might try to access dead inodes
4800 	 * the test is that same one that e2fsck uses
4801 	 * NeilBrown 1999oct15
4802 	 */
4803 	if (inode->i_nlink == 0) {
4804 		if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4805 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4806 		    ino != EXT4_BOOT_LOADER_INO) {
4807 			/* this inode is deleted or unallocated */
4808 			if (flags & EXT4_IGET_SPECIAL) {
4809 				ext4_error_inode(inode, function, line, 0,
4810 						 "iget: special inode unallocated");
4811 				ret = -EFSCORRUPTED;
4812 			} else
4813 				ret = -ESTALE;
4814 			goto bad_inode;
4815 		}
4816 		/* The only unlinked inodes we let through here have
4817 		 * valid i_mode and are being read by the orphan
4818 		 * recovery code: that's fine, we're about to complete
4819 		 * the process of deleting those.
4820 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4821 		 * not initialized on a new filesystem. */
4822 	}
4823 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4824 	ext4_set_inode_flags(inode, true);
4825 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4826 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4827 	if (ext4_has_feature_64bit(sb))
4828 		ei->i_file_acl |=
4829 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4830 	inode->i_size = ext4_isize(sb, raw_inode);
4831 	if ((size = i_size_read(inode)) < 0) {
4832 		ext4_error_inode(inode, function, line, 0,
4833 				 "iget: bad i_size value: %lld", size);
4834 		ret = -EFSCORRUPTED;
4835 		goto bad_inode;
4836 	}
4837 	/*
4838 	 * If dir_index is not enabled but there's dir with INDEX flag set,
4839 	 * we'd normally treat htree data as empty space. But with metadata
4840 	 * checksumming that corrupts checksums so forbid that.
4841 	 */
4842 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4843 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4844 		ext4_error_inode(inode, function, line, 0,
4845 			 "iget: Dir with htree data on filesystem without dir_index feature.");
4846 		ret = -EFSCORRUPTED;
4847 		goto bad_inode;
4848 	}
4849 	ei->i_disksize = inode->i_size;
4850 #ifdef CONFIG_QUOTA
4851 	ei->i_reserved_quota = 0;
4852 #endif
4853 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4854 	ei->i_block_group = iloc.block_group;
4855 	ei->i_last_alloc_group = ~0;
4856 	/*
4857 	 * NOTE! The in-memory inode i_data array is in little-endian order
4858 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4859 	 */
4860 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4861 		ei->i_data[block] = raw_inode->i_block[block];
4862 	INIT_LIST_HEAD(&ei->i_orphan);
4863 	ext4_fc_init_inode(&ei->vfs_inode);
4864 
4865 	/*
4866 	 * Set transaction id's of transactions that have to be committed
4867 	 * to finish f[data]sync. We set them to currently running transaction
4868 	 * as we cannot be sure that the inode or some of its metadata isn't
4869 	 * part of the transaction - the inode could have been reclaimed and
4870 	 * now it is reread from disk.
4871 	 */
4872 	if (journal) {
4873 		transaction_t *transaction;
4874 		tid_t tid;
4875 
4876 		read_lock(&journal->j_state_lock);
4877 		if (journal->j_running_transaction)
4878 			transaction = journal->j_running_transaction;
4879 		else
4880 			transaction = journal->j_committing_transaction;
4881 		if (transaction)
4882 			tid = transaction->t_tid;
4883 		else
4884 			tid = journal->j_commit_sequence;
4885 		read_unlock(&journal->j_state_lock);
4886 		ei->i_sync_tid = tid;
4887 		ei->i_datasync_tid = tid;
4888 	}
4889 
4890 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4891 		if (ei->i_extra_isize == 0) {
4892 			/* The extra space is currently unused. Use it. */
4893 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4894 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4895 					    EXT4_GOOD_OLD_INODE_SIZE;
4896 		} else {
4897 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4898 			if (ret)
4899 				goto bad_inode;
4900 		}
4901 	}
4902 
4903 	EXT4_INODE_GET_CTIME(inode, raw_inode);
4904 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4905 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4906 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4907 
4908 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4909 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4910 
4911 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4912 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4913 				ivers |=
4914 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4915 		}
4916 		ext4_inode_set_iversion_queried(inode, ivers);
4917 	}
4918 
4919 	ret = 0;
4920 	if (ei->i_file_acl &&
4921 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4922 		ext4_error_inode(inode, function, line, 0,
4923 				 "iget: bad extended attribute block %llu",
4924 				 ei->i_file_acl);
4925 		ret = -EFSCORRUPTED;
4926 		goto bad_inode;
4927 	} else if (!ext4_has_inline_data(inode)) {
4928 		/* validate the block references in the inode */
4929 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4930 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4931 			(S_ISLNK(inode->i_mode) &&
4932 			!ext4_inode_is_fast_symlink(inode)))) {
4933 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4934 				ret = ext4_ext_check_inode(inode);
4935 			else
4936 				ret = ext4_ind_check_inode(inode);
4937 		}
4938 	}
4939 	if (ret)
4940 		goto bad_inode;
4941 
4942 	if (S_ISREG(inode->i_mode)) {
4943 		inode->i_op = &ext4_file_inode_operations;
4944 		inode->i_fop = &ext4_file_operations;
4945 		ext4_set_aops(inode);
4946 	} else if (S_ISDIR(inode->i_mode)) {
4947 		inode->i_op = &ext4_dir_inode_operations;
4948 		inode->i_fop = &ext4_dir_operations;
4949 	} else if (S_ISLNK(inode->i_mode)) {
4950 		/* VFS does not allow setting these so must be corruption */
4951 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
4952 			ext4_error_inode(inode, function, line, 0,
4953 					 "iget: immutable or append flags "
4954 					 "not allowed on symlinks");
4955 			ret = -EFSCORRUPTED;
4956 			goto bad_inode;
4957 		}
4958 		if (IS_ENCRYPTED(inode)) {
4959 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4960 		} else if (ext4_inode_is_fast_symlink(inode)) {
4961 			inode->i_link = (char *)ei->i_data;
4962 			inode->i_op = &ext4_fast_symlink_inode_operations;
4963 			nd_terminate_link(ei->i_data, inode->i_size,
4964 				sizeof(ei->i_data) - 1);
4965 		} else {
4966 			inode->i_op = &ext4_symlink_inode_operations;
4967 		}
4968 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4969 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4970 		inode->i_op = &ext4_special_inode_operations;
4971 		if (raw_inode->i_block[0])
4972 			init_special_inode(inode, inode->i_mode,
4973 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4974 		else
4975 			init_special_inode(inode, inode->i_mode,
4976 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4977 	} else if (ino == EXT4_BOOT_LOADER_INO) {
4978 		make_bad_inode(inode);
4979 	} else {
4980 		ret = -EFSCORRUPTED;
4981 		ext4_error_inode(inode, function, line, 0,
4982 				 "iget: bogus i_mode (%o)", inode->i_mode);
4983 		goto bad_inode;
4984 	}
4985 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
4986 		ext4_error_inode(inode, function, line, 0,
4987 				 "casefold flag without casefold feature");
4988 		ret = -EFSCORRUPTED;
4989 		goto bad_inode;
4990 	}
4991 	if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4992 		ext4_error_inode(inode, function, line, 0, err_str);
4993 		ret = -EFSCORRUPTED;
4994 		goto bad_inode;
4995 	}
4996 
4997 	brelse(iloc.bh);
4998 	unlock_new_inode(inode);
4999 	return inode;
5000 
5001 bad_inode:
5002 	brelse(iloc.bh);
5003 	iget_failed(inode);
5004 	return ERR_PTR(ret);
5005 }
5006 
5007 static void __ext4_update_other_inode_time(struct super_block *sb,
5008 					   unsigned long orig_ino,
5009 					   unsigned long ino,
5010 					   struct ext4_inode *raw_inode)
5011 {
5012 	struct inode *inode;
5013 
5014 	inode = find_inode_by_ino_rcu(sb, ino);
5015 	if (!inode)
5016 		return;
5017 
5018 	if (!inode_is_dirtytime_only(inode))
5019 		return;
5020 
5021 	spin_lock(&inode->i_lock);
5022 	if (inode_is_dirtytime_only(inode)) {
5023 		struct ext4_inode_info	*ei = EXT4_I(inode);
5024 
5025 		inode->i_state &= ~I_DIRTY_TIME;
5026 		spin_unlock(&inode->i_lock);
5027 
5028 		spin_lock(&ei->i_raw_lock);
5029 		EXT4_INODE_SET_CTIME(inode, raw_inode);
5030 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5031 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5032 		ext4_inode_csum_set(inode, raw_inode, ei);
5033 		spin_unlock(&ei->i_raw_lock);
5034 		trace_ext4_other_inode_update_time(inode, orig_ino);
5035 		return;
5036 	}
5037 	spin_unlock(&inode->i_lock);
5038 }
5039 
5040 /*
5041  * Opportunistically update the other time fields for other inodes in
5042  * the same inode table block.
5043  */
5044 static void ext4_update_other_inodes_time(struct super_block *sb,
5045 					  unsigned long orig_ino, char *buf)
5046 {
5047 	unsigned long ino;
5048 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5049 	int inode_size = EXT4_INODE_SIZE(sb);
5050 
5051 	/*
5052 	 * Calculate the first inode in the inode table block.  Inode
5053 	 * numbers are one-based.  That is, the first inode in a block
5054 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5055 	 */
5056 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5057 	rcu_read_lock();
5058 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5059 		if (ino == orig_ino)
5060 			continue;
5061 		__ext4_update_other_inode_time(sb, orig_ino, ino,
5062 					       (struct ext4_inode *)buf);
5063 	}
5064 	rcu_read_unlock();
5065 }
5066 
5067 /*
5068  * Post the struct inode info into an on-disk inode location in the
5069  * buffer-cache.  This gobbles the caller's reference to the
5070  * buffer_head in the inode location struct.
5071  *
5072  * The caller must have write access to iloc->bh.
5073  */
5074 static int ext4_do_update_inode(handle_t *handle,
5075 				struct inode *inode,
5076 				struct ext4_iloc *iloc)
5077 {
5078 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5079 	struct ext4_inode_info *ei = EXT4_I(inode);
5080 	struct buffer_head *bh = iloc->bh;
5081 	struct super_block *sb = inode->i_sb;
5082 	int err;
5083 	int need_datasync = 0, set_large_file = 0;
5084 
5085 	spin_lock(&ei->i_raw_lock);
5086 
5087 	/*
5088 	 * For fields not tracked in the in-memory inode, initialise them
5089 	 * to zero for new inodes.
5090 	 */
5091 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5092 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5093 
5094 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5095 		need_datasync = 1;
5096 	if (ei->i_disksize > 0x7fffffffULL) {
5097 		if (!ext4_has_feature_large_file(sb) ||
5098 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5099 			set_large_file = 1;
5100 	}
5101 
5102 	err = ext4_fill_raw_inode(inode, raw_inode);
5103 	spin_unlock(&ei->i_raw_lock);
5104 	if (err) {
5105 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5106 		goto out_brelse;
5107 	}
5108 
5109 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5110 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5111 					      bh->b_data);
5112 
5113 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5114 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
5115 	if (err)
5116 		goto out_error;
5117 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5118 	if (set_large_file) {
5119 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5120 		err = ext4_journal_get_write_access(handle, sb,
5121 						    EXT4_SB(sb)->s_sbh,
5122 						    EXT4_JTR_NONE);
5123 		if (err)
5124 			goto out_error;
5125 		lock_buffer(EXT4_SB(sb)->s_sbh);
5126 		ext4_set_feature_large_file(sb);
5127 		ext4_superblock_csum_set(sb);
5128 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5129 		ext4_handle_sync(handle);
5130 		err = ext4_handle_dirty_metadata(handle, NULL,
5131 						 EXT4_SB(sb)->s_sbh);
5132 	}
5133 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5134 out_error:
5135 	ext4_std_error(inode->i_sb, err);
5136 out_brelse:
5137 	brelse(bh);
5138 	return err;
5139 }
5140 
5141 /*
5142  * ext4_write_inode()
5143  *
5144  * We are called from a few places:
5145  *
5146  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5147  *   Here, there will be no transaction running. We wait for any running
5148  *   transaction to commit.
5149  *
5150  * - Within flush work (sys_sync(), kupdate and such).
5151  *   We wait on commit, if told to.
5152  *
5153  * - Within iput_final() -> write_inode_now()
5154  *   We wait on commit, if told to.
5155  *
5156  * In all cases it is actually safe for us to return without doing anything,
5157  * because the inode has been copied into a raw inode buffer in
5158  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
5159  * writeback.
5160  *
5161  * Note that we are absolutely dependent upon all inode dirtiers doing the
5162  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5163  * which we are interested.
5164  *
5165  * It would be a bug for them to not do this.  The code:
5166  *
5167  *	mark_inode_dirty(inode)
5168  *	stuff();
5169  *	inode->i_size = expr;
5170  *
5171  * is in error because write_inode() could occur while `stuff()' is running,
5172  * and the new i_size will be lost.  Plus the inode will no longer be on the
5173  * superblock's dirty inode list.
5174  */
5175 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5176 {
5177 	int err;
5178 
5179 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5180 		return 0;
5181 
5182 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5183 		return -EIO;
5184 
5185 	if (EXT4_SB(inode->i_sb)->s_journal) {
5186 		if (ext4_journal_current_handle()) {
5187 			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5188 			dump_stack();
5189 			return -EIO;
5190 		}
5191 
5192 		/*
5193 		 * No need to force transaction in WB_SYNC_NONE mode. Also
5194 		 * ext4_sync_fs() will force the commit after everything is
5195 		 * written.
5196 		 */
5197 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5198 			return 0;
5199 
5200 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5201 						EXT4_I(inode)->i_sync_tid);
5202 	} else {
5203 		struct ext4_iloc iloc;
5204 
5205 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5206 		if (err)
5207 			return err;
5208 		/*
5209 		 * sync(2) will flush the whole buffer cache. No need to do
5210 		 * it here separately for each inode.
5211 		 */
5212 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5213 			sync_dirty_buffer(iloc.bh);
5214 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5215 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5216 					       "IO error syncing inode");
5217 			err = -EIO;
5218 		}
5219 		brelse(iloc.bh);
5220 	}
5221 	return err;
5222 }
5223 
5224 /*
5225  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5226  * buffers that are attached to a folio straddling i_size and are undergoing
5227  * commit. In that case we have to wait for commit to finish and try again.
5228  */
5229 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5230 {
5231 	unsigned offset;
5232 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5233 	tid_t commit_tid = 0;
5234 	int ret;
5235 
5236 	offset = inode->i_size & (PAGE_SIZE - 1);
5237 	/*
5238 	 * If the folio is fully truncated, we don't need to wait for any commit
5239 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5240 	 * strip all buffers from the folio but keep the folio dirty which can then
5241 	 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5242 	 * buffers). Also we don't need to wait for any commit if all buffers in
5243 	 * the folio remain valid. This is most beneficial for the common case of
5244 	 * blocksize == PAGESIZE.
5245 	 */
5246 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5247 		return;
5248 	while (1) {
5249 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
5250 				      inode->i_size >> PAGE_SHIFT);
5251 		if (IS_ERR(folio))
5252 			return;
5253 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5254 						folio_size(folio) - offset);
5255 		folio_unlock(folio);
5256 		folio_put(folio);
5257 		if (ret != -EBUSY)
5258 			return;
5259 		commit_tid = 0;
5260 		read_lock(&journal->j_state_lock);
5261 		if (journal->j_committing_transaction)
5262 			commit_tid = journal->j_committing_transaction->t_tid;
5263 		read_unlock(&journal->j_state_lock);
5264 		if (commit_tid)
5265 			jbd2_log_wait_commit(journal, commit_tid);
5266 	}
5267 }
5268 
5269 /*
5270  * ext4_setattr()
5271  *
5272  * Called from notify_change.
5273  *
5274  * We want to trap VFS attempts to truncate the file as soon as
5275  * possible.  In particular, we want to make sure that when the VFS
5276  * shrinks i_size, we put the inode on the orphan list and modify
5277  * i_disksize immediately, so that during the subsequent flushing of
5278  * dirty pages and freeing of disk blocks, we can guarantee that any
5279  * commit will leave the blocks being flushed in an unused state on
5280  * disk.  (On recovery, the inode will get truncated and the blocks will
5281  * be freed, so we have a strong guarantee that no future commit will
5282  * leave these blocks visible to the user.)
5283  *
5284  * Another thing we have to assure is that if we are in ordered mode
5285  * and inode is still attached to the committing transaction, we must
5286  * we start writeout of all the dirty pages which are being truncated.
5287  * This way we are sure that all the data written in the previous
5288  * transaction are already on disk (truncate waits for pages under
5289  * writeback).
5290  *
5291  * Called with inode->i_rwsem down.
5292  */
5293 int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5294 		 struct iattr *attr)
5295 {
5296 	struct inode *inode = d_inode(dentry);
5297 	int error, rc = 0;
5298 	int orphan = 0;
5299 	const unsigned int ia_valid = attr->ia_valid;
5300 	bool inc_ivers = true;
5301 
5302 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5303 		return -EIO;
5304 
5305 	if (unlikely(IS_IMMUTABLE(inode)))
5306 		return -EPERM;
5307 
5308 	if (unlikely(IS_APPEND(inode) &&
5309 		     (ia_valid & (ATTR_MODE | ATTR_UID |
5310 				  ATTR_GID | ATTR_TIMES_SET))))
5311 		return -EPERM;
5312 
5313 	error = setattr_prepare(idmap, dentry, attr);
5314 	if (error)
5315 		return error;
5316 
5317 	error = fscrypt_prepare_setattr(dentry, attr);
5318 	if (error)
5319 		return error;
5320 
5321 	error = fsverity_prepare_setattr(dentry, attr);
5322 	if (error)
5323 		return error;
5324 
5325 	if (is_quota_modification(idmap, inode, attr)) {
5326 		error = dquot_initialize(inode);
5327 		if (error)
5328 			return error;
5329 	}
5330 
5331 	if (i_uid_needs_update(idmap, attr, inode) ||
5332 	    i_gid_needs_update(idmap, attr, inode)) {
5333 		handle_t *handle;
5334 
5335 		/* (user+group)*(old+new) structure, inode write (sb,
5336 		 * inode block, ? - but truncate inode update has it) */
5337 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5338 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5339 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5340 		if (IS_ERR(handle)) {
5341 			error = PTR_ERR(handle);
5342 			goto err_out;
5343 		}
5344 
5345 		/* dquot_transfer() calls back ext4_get_inode_usage() which
5346 		 * counts xattr inode references.
5347 		 */
5348 		down_read(&EXT4_I(inode)->xattr_sem);
5349 		error = dquot_transfer(idmap, inode, attr);
5350 		up_read(&EXT4_I(inode)->xattr_sem);
5351 
5352 		if (error) {
5353 			ext4_journal_stop(handle);
5354 			return error;
5355 		}
5356 		/* Update corresponding info in inode so that everything is in
5357 		 * one transaction */
5358 		i_uid_update(idmap, attr, inode);
5359 		i_gid_update(idmap, attr, inode);
5360 		error = ext4_mark_inode_dirty(handle, inode);
5361 		ext4_journal_stop(handle);
5362 		if (unlikely(error)) {
5363 			return error;
5364 		}
5365 	}
5366 
5367 	if (attr->ia_valid & ATTR_SIZE) {
5368 		handle_t *handle;
5369 		loff_t oldsize = inode->i_size;
5370 		loff_t old_disksize;
5371 		int shrink = (attr->ia_size < inode->i_size);
5372 
5373 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5374 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5375 
5376 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5377 				return -EFBIG;
5378 			}
5379 		}
5380 		if (!S_ISREG(inode->i_mode)) {
5381 			return -EINVAL;
5382 		}
5383 
5384 		if (attr->ia_size == inode->i_size)
5385 			inc_ivers = false;
5386 
5387 		if (shrink) {
5388 			if (ext4_should_order_data(inode)) {
5389 				error = ext4_begin_ordered_truncate(inode,
5390 							    attr->ia_size);
5391 				if (error)
5392 					goto err_out;
5393 			}
5394 			/*
5395 			 * Blocks are going to be removed from the inode. Wait
5396 			 * for dio in flight.
5397 			 */
5398 			inode_dio_wait(inode);
5399 		}
5400 
5401 		filemap_invalidate_lock(inode->i_mapping);
5402 
5403 		rc = ext4_break_layouts(inode);
5404 		if (rc) {
5405 			filemap_invalidate_unlock(inode->i_mapping);
5406 			goto err_out;
5407 		}
5408 
5409 		if (attr->ia_size != inode->i_size) {
5410 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5411 			if (IS_ERR(handle)) {
5412 				error = PTR_ERR(handle);
5413 				goto out_mmap_sem;
5414 			}
5415 			if (ext4_handle_valid(handle) && shrink) {
5416 				error = ext4_orphan_add(handle, inode);
5417 				orphan = 1;
5418 			}
5419 			/*
5420 			 * Update c/mtime on truncate up, ext4_truncate() will
5421 			 * update c/mtime in shrink case below
5422 			 */
5423 			if (!shrink)
5424 				inode->i_mtime = inode_set_ctime_current(inode);
5425 
5426 			if (shrink)
5427 				ext4_fc_track_range(handle, inode,
5428 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5429 					inode->i_sb->s_blocksize_bits,
5430 					EXT_MAX_BLOCKS - 1);
5431 			else
5432 				ext4_fc_track_range(
5433 					handle, inode,
5434 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5435 					inode->i_sb->s_blocksize_bits,
5436 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5437 					inode->i_sb->s_blocksize_bits);
5438 
5439 			down_write(&EXT4_I(inode)->i_data_sem);
5440 			old_disksize = EXT4_I(inode)->i_disksize;
5441 			EXT4_I(inode)->i_disksize = attr->ia_size;
5442 			rc = ext4_mark_inode_dirty(handle, inode);
5443 			if (!error)
5444 				error = rc;
5445 			/*
5446 			 * We have to update i_size under i_data_sem together
5447 			 * with i_disksize to avoid races with writeback code
5448 			 * running ext4_wb_update_i_disksize().
5449 			 */
5450 			if (!error)
5451 				i_size_write(inode, attr->ia_size);
5452 			else
5453 				EXT4_I(inode)->i_disksize = old_disksize;
5454 			up_write(&EXT4_I(inode)->i_data_sem);
5455 			ext4_journal_stop(handle);
5456 			if (error)
5457 				goto out_mmap_sem;
5458 			if (!shrink) {
5459 				pagecache_isize_extended(inode, oldsize,
5460 							 inode->i_size);
5461 			} else if (ext4_should_journal_data(inode)) {
5462 				ext4_wait_for_tail_page_commit(inode);
5463 			}
5464 		}
5465 
5466 		/*
5467 		 * Truncate pagecache after we've waited for commit
5468 		 * in data=journal mode to make pages freeable.
5469 		 */
5470 		truncate_pagecache(inode, inode->i_size);
5471 		/*
5472 		 * Call ext4_truncate() even if i_size didn't change to
5473 		 * truncate possible preallocated blocks.
5474 		 */
5475 		if (attr->ia_size <= oldsize) {
5476 			rc = ext4_truncate(inode);
5477 			if (rc)
5478 				error = rc;
5479 		}
5480 out_mmap_sem:
5481 		filemap_invalidate_unlock(inode->i_mapping);
5482 	}
5483 
5484 	if (!error) {
5485 		if (inc_ivers)
5486 			inode_inc_iversion(inode);
5487 		setattr_copy(idmap, inode, attr);
5488 		mark_inode_dirty(inode);
5489 	}
5490 
5491 	/*
5492 	 * If the call to ext4_truncate failed to get a transaction handle at
5493 	 * all, we need to clean up the in-core orphan list manually.
5494 	 */
5495 	if (orphan && inode->i_nlink)
5496 		ext4_orphan_del(NULL, inode);
5497 
5498 	if (!error && (ia_valid & ATTR_MODE))
5499 		rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
5500 
5501 err_out:
5502 	if  (error)
5503 		ext4_std_error(inode->i_sb, error);
5504 	if (!error)
5505 		error = rc;
5506 	return error;
5507 }
5508 
5509 u32 ext4_dio_alignment(struct inode *inode)
5510 {
5511 	if (fsverity_active(inode))
5512 		return 0;
5513 	if (ext4_should_journal_data(inode))
5514 		return 0;
5515 	if (ext4_has_inline_data(inode))
5516 		return 0;
5517 	if (IS_ENCRYPTED(inode)) {
5518 		if (!fscrypt_dio_supported(inode))
5519 			return 0;
5520 		return i_blocksize(inode);
5521 	}
5522 	return 1; /* use the iomap defaults */
5523 }
5524 
5525 int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
5526 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
5527 {
5528 	struct inode *inode = d_inode(path->dentry);
5529 	struct ext4_inode *raw_inode;
5530 	struct ext4_inode_info *ei = EXT4_I(inode);
5531 	unsigned int flags;
5532 
5533 	if ((request_mask & STATX_BTIME) &&
5534 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5535 		stat->result_mask |= STATX_BTIME;
5536 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
5537 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5538 	}
5539 
5540 	/*
5541 	 * Return the DIO alignment restrictions if requested.  We only return
5542 	 * this information when requested, since on encrypted files it might
5543 	 * take a fair bit of work to get if the file wasn't opened recently.
5544 	 */
5545 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
5546 		u32 dio_align = ext4_dio_alignment(inode);
5547 
5548 		stat->result_mask |= STATX_DIOALIGN;
5549 		if (dio_align == 1) {
5550 			struct block_device *bdev = inode->i_sb->s_bdev;
5551 
5552 			/* iomap defaults */
5553 			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
5554 			stat->dio_offset_align = bdev_logical_block_size(bdev);
5555 		} else {
5556 			stat->dio_mem_align = dio_align;
5557 			stat->dio_offset_align = dio_align;
5558 		}
5559 	}
5560 
5561 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5562 	if (flags & EXT4_APPEND_FL)
5563 		stat->attributes |= STATX_ATTR_APPEND;
5564 	if (flags & EXT4_COMPR_FL)
5565 		stat->attributes |= STATX_ATTR_COMPRESSED;
5566 	if (flags & EXT4_ENCRYPT_FL)
5567 		stat->attributes |= STATX_ATTR_ENCRYPTED;
5568 	if (flags & EXT4_IMMUTABLE_FL)
5569 		stat->attributes |= STATX_ATTR_IMMUTABLE;
5570 	if (flags & EXT4_NODUMP_FL)
5571 		stat->attributes |= STATX_ATTR_NODUMP;
5572 	if (flags & EXT4_VERITY_FL)
5573 		stat->attributes |= STATX_ATTR_VERITY;
5574 
5575 	stat->attributes_mask |= (STATX_ATTR_APPEND |
5576 				  STATX_ATTR_COMPRESSED |
5577 				  STATX_ATTR_ENCRYPTED |
5578 				  STATX_ATTR_IMMUTABLE |
5579 				  STATX_ATTR_NODUMP |
5580 				  STATX_ATTR_VERITY);
5581 
5582 	generic_fillattr(idmap, request_mask, inode, stat);
5583 	return 0;
5584 }
5585 
5586 int ext4_file_getattr(struct mnt_idmap *idmap,
5587 		      const struct path *path, struct kstat *stat,
5588 		      u32 request_mask, unsigned int query_flags)
5589 {
5590 	struct inode *inode = d_inode(path->dentry);
5591 	u64 delalloc_blocks;
5592 
5593 	ext4_getattr(idmap, path, stat, request_mask, query_flags);
5594 
5595 	/*
5596 	 * If there is inline data in the inode, the inode will normally not
5597 	 * have data blocks allocated (it may have an external xattr block).
5598 	 * Report at least one sector for such files, so tools like tar, rsync,
5599 	 * others don't incorrectly think the file is completely sparse.
5600 	 */
5601 	if (unlikely(ext4_has_inline_data(inode)))
5602 		stat->blocks += (stat->size + 511) >> 9;
5603 
5604 	/*
5605 	 * We can't update i_blocks if the block allocation is delayed
5606 	 * otherwise in the case of system crash before the real block
5607 	 * allocation is done, we will have i_blocks inconsistent with
5608 	 * on-disk file blocks.
5609 	 * We always keep i_blocks updated together with real
5610 	 * allocation. But to not confuse with user, stat
5611 	 * will return the blocks that include the delayed allocation
5612 	 * blocks for this file.
5613 	 */
5614 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5615 				   EXT4_I(inode)->i_reserved_data_blocks);
5616 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5617 	return 0;
5618 }
5619 
5620 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5621 				   int pextents)
5622 {
5623 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5624 		return ext4_ind_trans_blocks(inode, lblocks);
5625 	return ext4_ext_index_trans_blocks(inode, pextents);
5626 }
5627 
5628 /*
5629  * Account for index blocks, block groups bitmaps and block group
5630  * descriptor blocks if modify datablocks and index blocks
5631  * worse case, the indexs blocks spread over different block groups
5632  *
5633  * If datablocks are discontiguous, they are possible to spread over
5634  * different block groups too. If they are contiguous, with flexbg,
5635  * they could still across block group boundary.
5636  *
5637  * Also account for superblock, inode, quota and xattr blocks
5638  */
5639 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5640 				  int pextents)
5641 {
5642 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5643 	int gdpblocks;
5644 	int idxblocks;
5645 	int ret;
5646 
5647 	/*
5648 	 * How many index blocks need to touch to map @lblocks logical blocks
5649 	 * to @pextents physical extents?
5650 	 */
5651 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5652 
5653 	ret = idxblocks;
5654 
5655 	/*
5656 	 * Now let's see how many group bitmaps and group descriptors need
5657 	 * to account
5658 	 */
5659 	groups = idxblocks + pextents;
5660 	gdpblocks = groups;
5661 	if (groups > ngroups)
5662 		groups = ngroups;
5663 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5664 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5665 
5666 	/* bitmaps and block group descriptor blocks */
5667 	ret += groups + gdpblocks;
5668 
5669 	/* Blocks for super block, inode, quota and xattr blocks */
5670 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5671 
5672 	return ret;
5673 }
5674 
5675 /*
5676  * Calculate the total number of credits to reserve to fit
5677  * the modification of a single pages into a single transaction,
5678  * which may include multiple chunks of block allocations.
5679  *
5680  * This could be called via ext4_write_begin()
5681  *
5682  * We need to consider the worse case, when
5683  * one new block per extent.
5684  */
5685 int ext4_writepage_trans_blocks(struct inode *inode)
5686 {
5687 	int bpp = ext4_journal_blocks_per_page(inode);
5688 	int ret;
5689 
5690 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5691 
5692 	/* Account for data blocks for journalled mode */
5693 	if (ext4_should_journal_data(inode))
5694 		ret += bpp;
5695 	return ret;
5696 }
5697 
5698 /*
5699  * Calculate the journal credits for a chunk of data modification.
5700  *
5701  * This is called from DIO, fallocate or whoever calling
5702  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5703  *
5704  * journal buffers for data blocks are not included here, as DIO
5705  * and fallocate do no need to journal data buffers.
5706  */
5707 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5708 {
5709 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5710 }
5711 
5712 /*
5713  * The caller must have previously called ext4_reserve_inode_write().
5714  * Give this, we know that the caller already has write access to iloc->bh.
5715  */
5716 int ext4_mark_iloc_dirty(handle_t *handle,
5717 			 struct inode *inode, struct ext4_iloc *iloc)
5718 {
5719 	int err = 0;
5720 
5721 	if (unlikely(ext4_forced_shutdown(inode->i_sb))) {
5722 		put_bh(iloc->bh);
5723 		return -EIO;
5724 	}
5725 	ext4_fc_track_inode(handle, inode);
5726 
5727 	/* the do_update_inode consumes one bh->b_count */
5728 	get_bh(iloc->bh);
5729 
5730 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5731 	err = ext4_do_update_inode(handle, inode, iloc);
5732 	put_bh(iloc->bh);
5733 	return err;
5734 }
5735 
5736 /*
5737  * On success, We end up with an outstanding reference count against
5738  * iloc->bh.  This _must_ be cleaned up later.
5739  */
5740 
5741 int
5742 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5743 			 struct ext4_iloc *iloc)
5744 {
5745 	int err;
5746 
5747 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5748 		return -EIO;
5749 
5750 	err = ext4_get_inode_loc(inode, iloc);
5751 	if (!err) {
5752 		BUFFER_TRACE(iloc->bh, "get_write_access");
5753 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5754 						    iloc->bh, EXT4_JTR_NONE);
5755 		if (err) {
5756 			brelse(iloc->bh);
5757 			iloc->bh = NULL;
5758 		}
5759 	}
5760 	ext4_std_error(inode->i_sb, err);
5761 	return err;
5762 }
5763 
5764 static int __ext4_expand_extra_isize(struct inode *inode,
5765 				     unsigned int new_extra_isize,
5766 				     struct ext4_iloc *iloc,
5767 				     handle_t *handle, int *no_expand)
5768 {
5769 	struct ext4_inode *raw_inode;
5770 	struct ext4_xattr_ibody_header *header;
5771 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5772 	struct ext4_inode_info *ei = EXT4_I(inode);
5773 	int error;
5774 
5775 	/* this was checked at iget time, but double check for good measure */
5776 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5777 	    (ei->i_extra_isize & 3)) {
5778 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5779 				 ei->i_extra_isize,
5780 				 EXT4_INODE_SIZE(inode->i_sb));
5781 		return -EFSCORRUPTED;
5782 	}
5783 	if ((new_extra_isize < ei->i_extra_isize) ||
5784 	    (new_extra_isize < 4) ||
5785 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5786 		return -EINVAL;	/* Should never happen */
5787 
5788 	raw_inode = ext4_raw_inode(iloc);
5789 
5790 	header = IHDR(inode, raw_inode);
5791 
5792 	/* No extended attributes present */
5793 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5794 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5795 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5796 		       EXT4_I(inode)->i_extra_isize, 0,
5797 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5798 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5799 		return 0;
5800 	}
5801 
5802 	/*
5803 	 * We may need to allocate external xattr block so we need quotas
5804 	 * initialized. Here we can be called with various locks held so we
5805 	 * cannot affort to initialize quotas ourselves. So just bail.
5806 	 */
5807 	if (dquot_initialize_needed(inode))
5808 		return -EAGAIN;
5809 
5810 	/* try to expand with EAs present */
5811 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5812 					   raw_inode, handle);
5813 	if (error) {
5814 		/*
5815 		 * Inode size expansion failed; don't try again
5816 		 */
5817 		*no_expand = 1;
5818 	}
5819 
5820 	return error;
5821 }
5822 
5823 /*
5824  * Expand an inode by new_extra_isize bytes.
5825  * Returns 0 on success or negative error number on failure.
5826  */
5827 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5828 					  unsigned int new_extra_isize,
5829 					  struct ext4_iloc iloc,
5830 					  handle_t *handle)
5831 {
5832 	int no_expand;
5833 	int error;
5834 
5835 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5836 		return -EOVERFLOW;
5837 
5838 	/*
5839 	 * In nojournal mode, we can immediately attempt to expand
5840 	 * the inode.  When journaled, we first need to obtain extra
5841 	 * buffer credits since we may write into the EA block
5842 	 * with this same handle. If journal_extend fails, then it will
5843 	 * only result in a minor loss of functionality for that inode.
5844 	 * If this is felt to be critical, then e2fsck should be run to
5845 	 * force a large enough s_min_extra_isize.
5846 	 */
5847 	if (ext4_journal_extend(handle,
5848 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5849 		return -ENOSPC;
5850 
5851 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5852 		return -EBUSY;
5853 
5854 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5855 					  handle, &no_expand);
5856 	ext4_write_unlock_xattr(inode, &no_expand);
5857 
5858 	return error;
5859 }
5860 
5861 int ext4_expand_extra_isize(struct inode *inode,
5862 			    unsigned int new_extra_isize,
5863 			    struct ext4_iloc *iloc)
5864 {
5865 	handle_t *handle;
5866 	int no_expand;
5867 	int error, rc;
5868 
5869 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5870 		brelse(iloc->bh);
5871 		return -EOVERFLOW;
5872 	}
5873 
5874 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5875 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5876 	if (IS_ERR(handle)) {
5877 		error = PTR_ERR(handle);
5878 		brelse(iloc->bh);
5879 		return error;
5880 	}
5881 
5882 	ext4_write_lock_xattr(inode, &no_expand);
5883 
5884 	BUFFER_TRACE(iloc->bh, "get_write_access");
5885 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5886 					      EXT4_JTR_NONE);
5887 	if (error) {
5888 		brelse(iloc->bh);
5889 		goto out_unlock;
5890 	}
5891 
5892 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5893 					  handle, &no_expand);
5894 
5895 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5896 	if (!error)
5897 		error = rc;
5898 
5899 out_unlock:
5900 	ext4_write_unlock_xattr(inode, &no_expand);
5901 	ext4_journal_stop(handle);
5902 	return error;
5903 }
5904 
5905 /*
5906  * What we do here is to mark the in-core inode as clean with respect to inode
5907  * dirtiness (it may still be data-dirty).
5908  * This means that the in-core inode may be reaped by prune_icache
5909  * without having to perform any I/O.  This is a very good thing,
5910  * because *any* task may call prune_icache - even ones which
5911  * have a transaction open against a different journal.
5912  *
5913  * Is this cheating?  Not really.  Sure, we haven't written the
5914  * inode out, but prune_icache isn't a user-visible syncing function.
5915  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5916  * we start and wait on commits.
5917  */
5918 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5919 				const char *func, unsigned int line)
5920 {
5921 	struct ext4_iloc iloc;
5922 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5923 	int err;
5924 
5925 	might_sleep();
5926 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5927 	err = ext4_reserve_inode_write(handle, inode, &iloc);
5928 	if (err)
5929 		goto out;
5930 
5931 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5932 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5933 					       iloc, handle);
5934 
5935 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5936 out:
5937 	if (unlikely(err))
5938 		ext4_error_inode_err(inode, func, line, 0, err,
5939 					"mark_inode_dirty error");
5940 	return err;
5941 }
5942 
5943 /*
5944  * ext4_dirty_inode() is called from __mark_inode_dirty()
5945  *
5946  * We're really interested in the case where a file is being extended.
5947  * i_size has been changed by generic_commit_write() and we thus need
5948  * to include the updated inode in the current transaction.
5949  *
5950  * Also, dquot_alloc_block() will always dirty the inode when blocks
5951  * are allocated to the file.
5952  *
5953  * If the inode is marked synchronous, we don't honour that here - doing
5954  * so would cause a commit on atime updates, which we don't bother doing.
5955  * We handle synchronous inodes at the highest possible level.
5956  */
5957 void ext4_dirty_inode(struct inode *inode, int flags)
5958 {
5959 	handle_t *handle;
5960 
5961 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5962 	if (IS_ERR(handle))
5963 		return;
5964 	ext4_mark_inode_dirty(handle, inode);
5965 	ext4_journal_stop(handle);
5966 }
5967 
5968 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5969 {
5970 	journal_t *journal;
5971 	handle_t *handle;
5972 	int err;
5973 	int alloc_ctx;
5974 
5975 	/*
5976 	 * We have to be very careful here: changing a data block's
5977 	 * journaling status dynamically is dangerous.  If we write a
5978 	 * data block to the journal, change the status and then delete
5979 	 * that block, we risk forgetting to revoke the old log record
5980 	 * from the journal and so a subsequent replay can corrupt data.
5981 	 * So, first we make sure that the journal is empty and that
5982 	 * nobody is changing anything.
5983 	 */
5984 
5985 	journal = EXT4_JOURNAL(inode);
5986 	if (!journal)
5987 		return 0;
5988 	if (is_journal_aborted(journal))
5989 		return -EROFS;
5990 
5991 	/* Wait for all existing dio workers */
5992 	inode_dio_wait(inode);
5993 
5994 	/*
5995 	 * Before flushing the journal and switching inode's aops, we have
5996 	 * to flush all dirty data the inode has. There can be outstanding
5997 	 * delayed allocations, there can be unwritten extents created by
5998 	 * fallocate or buffered writes in dioread_nolock mode covered by
5999 	 * dirty data which can be converted only after flushing the dirty
6000 	 * data (and journalled aops don't know how to handle these cases).
6001 	 */
6002 	if (val) {
6003 		filemap_invalidate_lock(inode->i_mapping);
6004 		err = filemap_write_and_wait(inode->i_mapping);
6005 		if (err < 0) {
6006 			filemap_invalidate_unlock(inode->i_mapping);
6007 			return err;
6008 		}
6009 	}
6010 
6011 	alloc_ctx = ext4_writepages_down_write(inode->i_sb);
6012 	jbd2_journal_lock_updates(journal);
6013 
6014 	/*
6015 	 * OK, there are no updates running now, and all cached data is
6016 	 * synced to disk.  We are now in a completely consistent state
6017 	 * which doesn't have anything in the journal, and we know that
6018 	 * no filesystem updates are running, so it is safe to modify
6019 	 * the inode's in-core data-journaling state flag now.
6020 	 */
6021 
6022 	if (val)
6023 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6024 	else {
6025 		err = jbd2_journal_flush(journal, 0);
6026 		if (err < 0) {
6027 			jbd2_journal_unlock_updates(journal);
6028 			ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6029 			return err;
6030 		}
6031 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6032 	}
6033 	ext4_set_aops(inode);
6034 
6035 	jbd2_journal_unlock_updates(journal);
6036 	ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6037 
6038 	if (val)
6039 		filemap_invalidate_unlock(inode->i_mapping);
6040 
6041 	/* Finally we can mark the inode as dirty. */
6042 
6043 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6044 	if (IS_ERR(handle))
6045 		return PTR_ERR(handle);
6046 
6047 	ext4_fc_mark_ineligible(inode->i_sb,
6048 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6049 	err = ext4_mark_inode_dirty(handle, inode);
6050 	ext4_handle_sync(handle);
6051 	ext4_journal_stop(handle);
6052 	ext4_std_error(inode->i_sb, err);
6053 
6054 	return err;
6055 }
6056 
6057 static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6058 			    struct buffer_head *bh)
6059 {
6060 	return !buffer_mapped(bh);
6061 }
6062 
6063 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6064 {
6065 	struct vm_area_struct *vma = vmf->vma;
6066 	struct folio *folio = page_folio(vmf->page);
6067 	loff_t size;
6068 	unsigned long len;
6069 	int err;
6070 	vm_fault_t ret;
6071 	struct file *file = vma->vm_file;
6072 	struct inode *inode = file_inode(file);
6073 	struct address_space *mapping = inode->i_mapping;
6074 	handle_t *handle;
6075 	get_block_t *get_block;
6076 	int retries = 0;
6077 
6078 	if (unlikely(IS_IMMUTABLE(inode)))
6079 		return VM_FAULT_SIGBUS;
6080 
6081 	sb_start_pagefault(inode->i_sb);
6082 	file_update_time(vma->vm_file);
6083 
6084 	filemap_invalidate_lock_shared(mapping);
6085 
6086 	err = ext4_convert_inline_data(inode);
6087 	if (err)
6088 		goto out_ret;
6089 
6090 	/*
6091 	 * On data journalling we skip straight to the transaction handle:
6092 	 * there's no delalloc; page truncated will be checked later; the
6093 	 * early return w/ all buffers mapped (calculates size/len) can't
6094 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
6095 	 */
6096 	if (ext4_should_journal_data(inode))
6097 		goto retry_alloc;
6098 
6099 	/* Delalloc case is easy... */
6100 	if (test_opt(inode->i_sb, DELALLOC) &&
6101 	    !ext4_nonda_switch(inode->i_sb)) {
6102 		do {
6103 			err = block_page_mkwrite(vma, vmf,
6104 						   ext4_da_get_block_prep);
6105 		} while (err == -ENOSPC &&
6106 		       ext4_should_retry_alloc(inode->i_sb, &retries));
6107 		goto out_ret;
6108 	}
6109 
6110 	folio_lock(folio);
6111 	size = i_size_read(inode);
6112 	/* Page got truncated from under us? */
6113 	if (folio->mapping != mapping || folio_pos(folio) > size) {
6114 		folio_unlock(folio);
6115 		ret = VM_FAULT_NOPAGE;
6116 		goto out;
6117 	}
6118 
6119 	len = folio_size(folio);
6120 	if (folio_pos(folio) + len > size)
6121 		len = size - folio_pos(folio);
6122 	/*
6123 	 * Return if we have all the buffers mapped. This avoids the need to do
6124 	 * journal_start/journal_stop which can block and take a long time
6125 	 *
6126 	 * This cannot be done for data journalling, as we have to add the
6127 	 * inode to the transaction's list to writeprotect pages on commit.
6128 	 */
6129 	if (folio_buffers(folio)) {
6130 		if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6131 					    0, len, NULL,
6132 					    ext4_bh_unmapped)) {
6133 			/* Wait so that we don't change page under IO */
6134 			folio_wait_stable(folio);
6135 			ret = VM_FAULT_LOCKED;
6136 			goto out;
6137 		}
6138 	}
6139 	folio_unlock(folio);
6140 	/* OK, we need to fill the hole... */
6141 	if (ext4_should_dioread_nolock(inode))
6142 		get_block = ext4_get_block_unwritten;
6143 	else
6144 		get_block = ext4_get_block;
6145 retry_alloc:
6146 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6147 				    ext4_writepage_trans_blocks(inode));
6148 	if (IS_ERR(handle)) {
6149 		ret = VM_FAULT_SIGBUS;
6150 		goto out;
6151 	}
6152 	/*
6153 	 * Data journalling can't use block_page_mkwrite() because it
6154 	 * will set_buffer_dirty() before do_journal_get_write_access()
6155 	 * thus might hit warning messages for dirty metadata buffers.
6156 	 */
6157 	if (!ext4_should_journal_data(inode)) {
6158 		err = block_page_mkwrite(vma, vmf, get_block);
6159 	} else {
6160 		folio_lock(folio);
6161 		size = i_size_read(inode);
6162 		/* Page got truncated from under us? */
6163 		if (folio->mapping != mapping || folio_pos(folio) > size) {
6164 			ret = VM_FAULT_NOPAGE;
6165 			goto out_error;
6166 		}
6167 
6168 		len = folio_size(folio);
6169 		if (folio_pos(folio) + len > size)
6170 			len = size - folio_pos(folio);
6171 
6172 		err = __block_write_begin(&folio->page, 0, len, ext4_get_block);
6173 		if (!err) {
6174 			ret = VM_FAULT_SIGBUS;
6175 			if (ext4_journal_folio_buffers(handle, folio, len))
6176 				goto out_error;
6177 		} else {
6178 			folio_unlock(folio);
6179 		}
6180 	}
6181 	ext4_journal_stop(handle);
6182 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6183 		goto retry_alloc;
6184 out_ret:
6185 	ret = vmf_fs_error(err);
6186 out:
6187 	filemap_invalidate_unlock_shared(mapping);
6188 	sb_end_pagefault(inode->i_sb);
6189 	return ret;
6190 out_error:
6191 	folio_unlock(folio);
6192 	ext4_journal_stop(handle);
6193 	goto out;
6194 }
6195