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