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