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