xref: /linux/fs/f2fs/data.c (revision 995832b2cebe6969d1b42635db698803ee31294d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/data.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/fs.h>
9 #include <linux/f2fs_fs.h>
10 #include <linux/sched/mm.h>
11 #include <linux/mpage.h>
12 #include <linux/writeback.h>
13 #include <linux/folio_batch.h>
14 #include <linux/blkdev.h>
15 #include <linux/bio.h>
16 #include <linux/blk-crypto.h>
17 #include <linux/swap.h>
18 #include <linux/prefetch.h>
19 #include <linux/uio.h>
20 #include <linux/sched/signal.h>
21 #include <linux/fiemap.h>
22 #include <linux/iomap.h>
23 #include <linux/fserror.h>
24 
25 #include "f2fs.h"
26 #include "node.h"
27 #include "segment.h"
28 #include "iostat.h"
29 #include <trace/events/f2fs.h>
30 
31 #define NUM_PREALLOC_POST_READ_CTXS	128
32 
33 static struct kmem_cache *bio_post_read_ctx_cache;
34 static struct kmem_cache *bio_entry_slab;
35 static struct kmem_cache *ffs_entry_slab;
36 static mempool_t *bio_post_read_ctx_pool;
37 static struct bio_set f2fs_bioset;
38 
39 struct f2fs_folio_state {
40 	spinlock_t		state_lock;
41 	unsigned int		read_pages_pending;
42 };
43 
44 struct f2fs_bio {
45 	struct work_struct work;
46 	struct bio bio;
47 };
48 
49 #define	F2FS_BIO_POOL_SIZE	NR_CURSEG_TYPE
50 
51 int __init f2fs_init_bioset(void)
52 {
53 	return bioset_init(&f2fs_bioset, F2FS_BIO_POOL_SIZE,
54 			   offsetof(struct f2fs_bio, bio), BIOSET_NEED_BVECS);
55 }
56 
57 void f2fs_destroy_bioset(void)
58 {
59 	bioset_exit(&f2fs_bioset);
60 }
61 
62 bool f2fs_is_cp_guaranteed(const struct folio *folio)
63 {
64 	struct address_space *mapping = folio->mapping;
65 	struct inode *inode;
66 	struct f2fs_sb_info *sbi;
67 
68 	if (fscrypt_is_bounce_folio(folio))
69 		return folio_test_f2fs_gcing(fscrypt_pagecache_folio(folio));
70 
71 	inode = mapping->host;
72 	sbi = F2FS_I_SB(inode);
73 
74 	if (inode->i_ino == F2FS_META_INO(sbi) ||
75 			inode->i_ino == F2FS_NODE_INO(sbi) ||
76 			S_ISDIR(inode->i_mode))
77 		return true;
78 
79 	if ((S_ISREG(inode->i_mode) && IS_NOQUOTA(inode)) ||
80 			folio_test_f2fs_gcing(folio))
81 		return true;
82 	return false;
83 }
84 
85 static enum count_type __read_io_type(struct folio *folio)
86 {
87 	struct address_space *mapping = folio->mapping;
88 
89 	if (mapping) {
90 		struct inode *inode = mapping->host;
91 		struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
92 
93 		if (inode->i_ino == F2FS_META_INO(sbi))
94 			return F2FS_RD_META;
95 
96 		if (inode->i_ino == F2FS_NODE_INO(sbi))
97 			return F2FS_RD_NODE;
98 	}
99 	return F2FS_RD_DATA;
100 }
101 
102 /* postprocessing steps for read bios */
103 enum bio_post_read_step {
104 #ifdef CONFIG_FS_ENCRYPTION
105 	STEP_DECRYPT	= BIT(0),
106 #else
107 	STEP_DECRYPT	= 0,	/* compile out the decryption-related code */
108 #endif
109 #ifdef CONFIG_F2FS_FS_COMPRESSION
110 	STEP_DECOMPRESS	= BIT(1),
111 #else
112 	STEP_DECOMPRESS	= 0,	/* compile out the decompression-related code */
113 #endif
114 #ifdef CONFIG_FS_VERITY
115 	STEP_VERITY	= BIT(2),
116 #else
117 	STEP_VERITY	= 0,	/* compile out the verity-related code */
118 #endif
119 };
120 
121 struct bio_post_read_ctx {
122 	struct bio *bio;
123 	struct f2fs_sb_info *sbi;
124 	struct fsverity_info *vi;
125 	struct work_struct work;
126 	unsigned int enabled_steps;
127 	/*
128 	 * decompression_attempted keeps track of whether
129 	 * f2fs_end_read_compressed_page() has been called on the pages in the
130 	 * bio that belong to a compressed cluster yet.
131 	 */
132 	bool decompression_attempted;
133 	block_t fs_blkaddr;
134 };
135 
136 /*
137  * Update and unlock a bio's pages, and free the bio.
138  *
139  * This marks pages up-to-date only if there was no error in the bio (I/O error,
140  * decryption error, or verity error), as indicated by bio->bi_status.
141  *
142  * "Compressed pages" (pagecache pages backed by a compressed cluster on-disk)
143  * aren't marked up-to-date here, as decompression is done on a per-compression-
144  * cluster basis rather than a per-bio basis.  Instead, we only must do two
145  * things for each compressed page here: call f2fs_end_read_compressed_page()
146  * with failed=true if an error occurred before it would have normally gotten
147  * called (i.e., I/O error or decryption error, but *not* verity error), and
148  * release the bio's reference to the decompress_io_ctx of the page's cluster.
149  */
150 static void f2fs_finish_read_bio(struct bio *bio, bool in_task)
151 {
152 	struct folio_iter fi;
153 	struct bio_post_read_ctx *ctx = bio->bi_private;
154 	unsigned long flags;
155 
156 	bio_for_each_folio_all(fi, bio) {
157 		struct folio *folio = fi.folio;
158 		unsigned nr_pages = fi.length >> PAGE_SHIFT;
159 		bool finished = true;
160 
161 		if (!folio_test_large(folio) &&
162 		    f2fs_is_compressed_page(folio)) {
163 			if (ctx && !ctx->decompression_attempted)
164 				f2fs_end_read_compressed_page(folio, true, 0,
165 							in_task);
166 			f2fs_put_folio_dic(folio, in_task);
167 			continue;
168 		}
169 
170 		if (folio_test_large(folio)) {
171 			struct f2fs_folio_state *ffs = folio->private;
172 
173 			spin_lock_irqsave(&ffs->state_lock, flags);
174 			ffs->read_pages_pending -= nr_pages;
175 			finished = !ffs->read_pages_pending;
176 			spin_unlock_irqrestore(&ffs->state_lock, flags);
177 		}
178 
179 		while (nr_pages--)
180 			dec_page_count(F2FS_F_SB(folio), __read_io_type(folio));
181 
182 		if (bio->bi_status == BLK_STS_OK &&
183 			F2FS_F_SB(folio)->node_inode && is_node_folio(folio) &&
184 			f2fs_sanity_check_node_footer(F2FS_F_SB(folio),
185 				folio, folio->index, NODE_TYPE_REGULAR, true))
186 			bio->bi_status = BLK_STS_IOERR;
187 
188 		if (finished)
189 			folio_end_read(folio, bio->bi_status == BLK_STS_OK);
190 	}
191 
192 	if (ctx)
193 		mempool_free(ctx, bio_post_read_ctx_pool);
194 	bio_put(bio);
195 }
196 
197 static void f2fs_verify_bio(struct work_struct *work)
198 {
199 	struct bio_post_read_ctx *ctx =
200 		container_of(work, struct bio_post_read_ctx, work);
201 	struct bio *bio = ctx->bio;
202 	bool may_have_compressed_pages = (ctx->enabled_steps & STEP_DECOMPRESS);
203 	struct fsverity_info *vi = ctx->vi;
204 
205 	/*
206 	 * fsverity_verify_bio() may call readahead() again, and while verity
207 	 * will be disabled for this, decryption and/or decompression may still
208 	 * be needed, resulting in another bio_post_read_ctx being allocated.
209 	 * So to prevent deadlocks we need to release the current ctx to the
210 	 * mempool first.  This assumes that verity is the last post-read step.
211 	 */
212 	mempool_free(ctx, bio_post_read_ctx_pool);
213 	bio->bi_private = NULL;
214 
215 	/*
216 	 * Verify the bio's pages with fs-verity.  Exclude compressed pages,
217 	 * as those were handled separately by f2fs_end_read_compressed_page().
218 	 */
219 	if (may_have_compressed_pages) {
220 		struct folio_iter fi;
221 
222 		bio_for_each_folio_all(fi, bio) {
223 			struct folio *folio = fi.folio;
224 
225 			if (!f2fs_is_compressed_page(folio) &&
226 			    !fsverity_verify_folio(vi, folio)) {
227 				bio->bi_status = BLK_STS_IOERR;
228 				break;
229 			}
230 		}
231 	} else {
232 		fsverity_verify_bio(vi, bio);
233 	}
234 
235 	f2fs_finish_read_bio(bio, true);
236 }
237 
238 /*
239  * If the bio's data needs to be verified with fs-verity, then enqueue the
240  * verity work for the bio.  Otherwise finish the bio now.
241  *
242  * Note that to avoid deadlocks, the verity work can't be done on the
243  * decryption/decompression workqueue.  This is because verifying the data pages
244  * can involve reading verity metadata pages from the file, and these verity
245  * metadata pages may be encrypted and/or compressed.
246  */
247 static void f2fs_verify_and_finish_bio(struct bio *bio, bool in_task)
248 {
249 	struct bio_post_read_ctx *ctx = bio->bi_private;
250 
251 	if (ctx && (ctx->enabled_steps & STEP_VERITY)) {
252 		INIT_WORK(&ctx->work, f2fs_verify_bio);
253 		fsverity_enqueue_verify_work(&ctx->work);
254 	} else {
255 		f2fs_finish_read_bio(bio, in_task);
256 	}
257 }
258 
259 /*
260  * Handle STEP_DECOMPRESS by decompressing any compressed clusters whose last
261  * remaining page was read by @ctx->bio.
262  *
263  * Note that a bio may span clusters (even a mix of compressed and uncompressed
264  * clusters) or be for just part of a cluster.  STEP_DECOMPRESS just indicates
265  * that the bio includes at least one compressed page.  The actual decompression
266  * is done on a per-cluster basis, not a per-bio basis.
267  */
268 static void f2fs_handle_step_decompress(struct bio_post_read_ctx *ctx,
269 		bool in_task)
270 {
271 	struct folio_iter fi;
272 	bool all_compressed = true;
273 	block_t blkaddr = ctx->fs_blkaddr;
274 
275 	bio_for_each_folio_all(fi, ctx->bio) {
276 		struct folio *folio = fi.folio;
277 
278 		if (f2fs_is_compressed_page(folio))
279 			f2fs_end_read_compressed_page(folio, false, blkaddr,
280 						      in_task);
281 		else
282 			all_compressed = false;
283 
284 		blkaddr++;
285 	}
286 
287 	ctx->decompression_attempted = true;
288 
289 	/*
290 	 * Optimization: if all the bio's pages are compressed, then scheduling
291 	 * the per-bio verity work is unnecessary, as verity will be fully
292 	 * handled at the compression cluster level.
293 	 */
294 	if (all_compressed)
295 		ctx->enabled_steps &= ~STEP_VERITY;
296 }
297 
298 static void f2fs_post_read_work(struct work_struct *work)
299 {
300 	struct bio_post_read_ctx *ctx =
301 		container_of(work, struct bio_post_read_ctx, work);
302 	struct bio *bio = ctx->bio;
303 
304 	if ((ctx->enabled_steps & STEP_DECRYPT) && !fscrypt_decrypt_bio(bio)) {
305 		f2fs_finish_read_bio(bio, true);
306 		return;
307 	}
308 
309 	if (ctx->enabled_steps & STEP_DECOMPRESS)
310 		f2fs_handle_step_decompress(ctx, true);
311 
312 	f2fs_verify_and_finish_bio(bio, true);
313 }
314 
315 static void f2fs_read_end_io(struct bio *bio)
316 {
317 	struct f2fs_sb_info *sbi = F2FS_F_SB(bio_first_folio_all(bio));
318 	struct bio_post_read_ctx *ctx;
319 	bool intask = in_task() && !irqs_disabled();
320 
321 	iostat_update_and_unbind_ctx(bio);
322 	ctx = bio->bi_private;
323 
324 	if (time_to_inject(sbi, FAULT_READ_IO))
325 		bio->bi_status = BLK_STS_IOERR;
326 
327 	if (bio->bi_status != BLK_STS_OK) {
328 		f2fs_finish_read_bio(bio, intask);
329 		return;
330 	}
331 
332 	if (ctx) {
333 		unsigned int enabled_steps = ctx->enabled_steps &
334 					(STEP_DECRYPT | STEP_DECOMPRESS);
335 
336 		/*
337 		 * If we have only decompression step between decompression and
338 		 * decrypt, we don't need post processing for this.
339 		 */
340 		if (enabled_steps == STEP_DECOMPRESS &&
341 				!f2fs_low_mem_mode(sbi)) {
342 			f2fs_handle_step_decompress(ctx, intask);
343 		} else if (enabled_steps) {
344 			INIT_WORK(&ctx->work, f2fs_post_read_work);
345 			queue_work(ctx->sbi->wq, &ctx->work);
346 			return;
347 		}
348 	}
349 
350 	f2fs_verify_and_finish_bio(bio, intask);
351 }
352 
353 static void f2fs_write_end_bio(struct bio *bio)
354 {
355 	struct f2fs_sb_info *sbi = bio->bi_private;
356 	struct folio_iter fi;
357 
358 	if (time_to_inject(sbi, FAULT_WRITE_IO))
359 		bio->bi_status = BLK_STS_IOERR;
360 
361 	bio_for_each_folio_all(fi, bio) {
362 		struct folio *folio = fi.folio;
363 		enum count_type type;
364 
365 		if (fscrypt_is_bounce_folio(folio)) {
366 			struct folio *io_folio = folio;
367 
368 			folio = fscrypt_pagecache_folio(io_folio);
369 			fscrypt_free_bounce_page(&io_folio->page);
370 		}
371 
372 #ifdef CONFIG_F2FS_FS_COMPRESSION
373 		if (f2fs_is_compressed_page(folio)) {
374 			f2fs_compress_write_end_io(bio, folio);
375 			continue;
376 		}
377 #endif
378 
379 		type = WB_DATA_TYPE(folio, false);
380 
381 		if (unlikely(bio->bi_status != BLK_STS_OK)) {
382 			mapping_set_error(folio->mapping, -EIO);
383 			if (type == F2FS_WB_CP_DATA) {
384 				f2fs_stop_checkpoint(sbi, true,
385 						STOP_CP_REASON_WRITE_FAIL);
386 			}
387 		}
388 
389 		if (is_node_folio(folio)) {
390 			f2fs_sanity_check_node_footer(sbi, folio,
391 				folio->index, NODE_TYPE_REGULAR, true);
392 			f2fs_bug_on(sbi, folio->index != nid_of_node(folio));
393 		}
394 		if (f2fs_in_warm_node_list(folio))
395 			f2fs_del_fsync_node_entry(sbi, folio);
396 
397 		dec_page_count(sbi, type);
398 
399 		/*
400 		 * we should access sbi before folio_end_writeback() to
401 		 * avoid racing w/ kill_f2fs_super()
402 		 */
403 		if (type == F2FS_WB_CP_DATA && !get_pages(sbi, type) &&
404 				wq_has_sleeper(&sbi->cp_wait))
405 			wake_up(&sbi->cp_wait);
406 
407 		folio_clear_f2fs_gcing(folio);
408 		folio_end_writeback(folio);
409 	}
410 
411 	bio_put(bio);
412 }
413 
414 static void f2fs_write_end_io(struct bio *bio)
415 {
416 	iostat_update_and_unbind_ctx(bio);
417 
418 	f2fs_write_end_bio(bio);
419 }
420 
421 #ifdef CONFIG_BLK_DEV_ZONED
422 static void f2fs_zone_write_end_io(struct bio *bio)
423 {
424 	struct f2fs_bio_info *io = (struct f2fs_bio_info *)bio->bi_private;
425 
426 	bio->bi_private = io->bi_private;
427 	complete(&io->zone_wait);
428 	f2fs_write_end_io(bio);
429 }
430 #endif
431 
432 struct block_device *f2fs_target_device(struct f2fs_sb_info *sbi,
433 		block_t blk_addr, sector_t *sector)
434 {
435 	struct block_device *bdev = sbi->sb->s_bdev;
436 	int i;
437 
438 	if (f2fs_is_multi_device(sbi)) {
439 		for (i = 0; i < sbi->s_ndevs; i++) {
440 			if (FDEV(i).start_blk <= blk_addr &&
441 			    FDEV(i).end_blk >= blk_addr) {
442 				blk_addr -= FDEV(i).start_blk;
443 				bdev = FDEV(i).bdev;
444 				break;
445 			}
446 		}
447 	}
448 
449 	if (sector)
450 		*sector = SECTOR_FROM_BLOCK(blk_addr);
451 	return bdev;
452 }
453 
454 int f2fs_target_device_index(struct f2fs_sb_info *sbi, block_t blkaddr)
455 {
456 	int i;
457 
458 	if (!f2fs_is_multi_device(sbi))
459 		return 0;
460 
461 	for (i = 0; i < sbi->s_ndevs; i++)
462 		if (FDEV(i).start_blk <= blkaddr && FDEV(i).end_blk >= blkaddr)
463 			return i;
464 	return 0;
465 }
466 
467 static blk_opf_t f2fs_io_flags(struct f2fs_io_info *fio)
468 {
469 	unsigned int temp_mask = GENMASK(NR_TEMP_TYPE - 1, 0);
470 	unsigned int fua_flag, meta_flag, io_flag;
471 	blk_opf_t op_flags = 0;
472 
473 	if (fio->op != REQ_OP_WRITE)
474 		return 0;
475 	if (fio->type == DATA)
476 		io_flag = fio->sbi->data_io_flag;
477 	else if (fio->type == NODE)
478 		io_flag = fio->sbi->node_io_flag;
479 	else
480 		return 0;
481 
482 	fua_flag = io_flag & temp_mask;
483 	meta_flag = (io_flag >> NR_TEMP_TYPE) & temp_mask;
484 
485 	/*
486 	 * data/node io flag bits per temp:
487 	 *      REQ_META     |      REQ_FUA      |
488 	 *    5 |    4 |   3 |    2 |    1 |   0 |
489 	 * Cold | Warm | Hot | Cold | Warm | Hot |
490 	 */
491 	if (BIT(fio->temp) & meta_flag)
492 		op_flags |= REQ_META;
493 	if (BIT(fio->temp) & fua_flag)
494 		op_flags |= REQ_FUA;
495 
496 	if (fio->type == DATA &&
497 	    F2FS_I(fio->folio->mapping->host)->ioprio_hint == F2FS_IOPRIO_WRITE)
498 		op_flags |= REQ_PRIO;
499 
500 	return op_flags;
501 }
502 
503 static struct bio *__bio_alloc(struct f2fs_io_info *fio, int npages)
504 {
505 	struct f2fs_sb_info *sbi = fio->sbi;
506 	struct block_device *bdev;
507 	sector_t sector;
508 	struct bio *bio;
509 
510 	bdev = f2fs_target_device(sbi, fio->new_blkaddr, &sector);
511 	bio = bio_alloc_bioset(bdev, npages,
512 				fio->op | fio->op_flags | f2fs_io_flags(fio),
513 				GFP_NOIO, &f2fs_bioset);
514 	bio->bi_iter.bi_sector = sector;
515 	if (is_read_io(fio->op)) {
516 		bio->bi_end_io = f2fs_read_end_io;
517 		bio->bi_private = NULL;
518 	} else {
519 		bio->bi_end_io = f2fs_write_end_io;
520 		bio->bi_private = sbi;
521 		bio->bi_write_hint = f2fs_io_type_to_rw_hint(sbi,
522 						fio->type, fio->temp);
523 		bio->bi_write_stream = f2fs_io_type_to_write_stream(bdev, fio->type,
524 								    fio->temp);
525 	}
526 	iostat_alloc_and_bind_ctx(sbi, bio, NULL);
527 
528 	if (fio->io_wbc)
529 		wbc_init_bio(fio->io_wbc, bio);
530 
531 	return bio;
532 }
533 
534 static void f2fs_set_bio_crypt_ctx(struct bio *bio, const struct inode *inode,
535 				  pgoff_t first_idx,
536 				  const struct f2fs_io_info *fio,
537 				  gfp_t gfp_mask)
538 {
539 	/*
540 	 * The f2fs garbage collector sets ->encrypted_page when it wants to
541 	 * read/write raw data without encryption.
542 	 */
543 	if (!fio || !fio->encrypted_page)
544 		fscrypt_set_bio_crypt_ctx(bio, inode,
545 				(loff_t)first_idx << inode->i_blkbits,
546 				gfp_mask);
547 }
548 
549 static bool f2fs_crypt_mergeable_bio(struct bio *bio, const struct inode *inode,
550 				     pgoff_t next_idx,
551 				     const struct f2fs_io_info *fio)
552 {
553 	/*
554 	 * The f2fs garbage collector sets ->encrypted_page when it wants to
555 	 * read/write raw data without encryption.
556 	 */
557 	if (fio && fio->encrypted_page)
558 		return !bio_has_crypt_ctx(bio);
559 
560 	return fscrypt_mergeable_bio(bio, inode,
561 			(loff_t)next_idx << inode->i_blkbits);
562 }
563 
564 void f2fs_submit_read_bio(struct f2fs_sb_info *sbi, struct bio *bio,
565 				 enum page_type type)
566 {
567 	if (!bio)
568 		return;
569 
570 	WARN_ON_ONCE(!is_read_io(bio_op(bio)));
571 	trace_f2fs_submit_read_bio(sbi->sb, type, bio);
572 
573 	iostat_update_submit_ctx(bio, type);
574 	blk_crypto_submit_bio(bio);
575 }
576 
577 static void f2fs_submit_write_bio(struct f2fs_sb_info *sbi, struct bio *bio,
578 				  enum page_type type)
579 {
580 	WARN_ON_ONCE(is_read_io(bio_op(bio)));
581 	trace_f2fs_submit_write_bio(sbi->sb, type, bio);
582 	iostat_update_submit_ctx(bio, type);
583 	blk_crypto_submit_bio(bio);
584 }
585 
586 static void __submit_merged_bio(struct f2fs_bio_info *io)
587 {
588 	struct f2fs_io_info *fio = &io->fio;
589 
590 	if (!io->bio)
591 		return;
592 
593 	if (is_read_io(fio->op)) {
594 		trace_f2fs_prepare_read_bio(io->sbi->sb, fio->type, io->bio);
595 		f2fs_submit_read_bio(io->sbi, io->bio, fio->type);
596 	} else {
597 		trace_f2fs_prepare_write_bio(io->sbi->sb, fio->type, io->bio);
598 		f2fs_submit_write_bio(io->sbi, io->bio, fio->type);
599 	}
600 	io->bio = NULL;
601 }
602 
603 static bool __has_merged_page(struct bio *bio, struct inode *inode,
604 						struct folio *folio, nid_t ino)
605 {
606 	struct folio_iter fi;
607 
608 	if (!bio)
609 		return false;
610 
611 	if (!inode && !folio && !ino)
612 		return true;
613 
614 	bio_for_each_folio_all(fi, bio) {
615 		struct folio *target = fi.folio;
616 
617 		if (fscrypt_is_bounce_folio(target)) {
618 			target = fscrypt_pagecache_folio(target);
619 			if (IS_ERR(target))
620 				continue;
621 		}
622 		if (f2fs_is_compressed_page(target)) {
623 			target = f2fs_compress_control_folio(target);
624 			if (IS_ERR(target))
625 				continue;
626 		}
627 
628 		if (inode && inode == target->mapping->host)
629 			return true;
630 		if (folio && folio == target)
631 			return true;
632 		if (ino && ino == ino_of_node(target))
633 			return true;
634 	}
635 
636 	return false;
637 }
638 
639 int f2fs_init_write_merge_io(struct f2fs_sb_info *sbi)
640 {
641 	int i;
642 
643 	for (i = 0; i < NR_PAGE_TYPE; i++) {
644 		int n = (i == META) ? 1 : NR_TEMP_TYPE;
645 		int j;
646 
647 		sbi->write_io[i] = f2fs_kmalloc(sbi,
648 				array_size(n, sizeof(struct f2fs_bio_info)),
649 				GFP_KERNEL);
650 		if (!sbi->write_io[i])
651 			return -ENOMEM;
652 
653 		for (j = HOT; j < n; j++) {
654 			struct f2fs_bio_info *io = &sbi->write_io[i][j];
655 
656 			init_f2fs_rwsem_trace(&io->io_rwsem, sbi,
657 						LOCK_NAME_IO_RWSEM);
658 			io->sbi = sbi;
659 			io->bio = NULL;
660 			io->last_block_in_bio = 0;
661 			spin_lock_init(&io->io_lock);
662 			INIT_LIST_HEAD(&io->io_list);
663 			INIT_LIST_HEAD(&io->bio_list);
664 			init_f2fs_rwsem(&io->bio_list_lock);
665 #ifdef CONFIG_BLK_DEV_ZONED
666 			init_completion(&io->zone_wait);
667 			io->zone_pending_bio = NULL;
668 			io->bi_private = NULL;
669 #endif
670 		}
671 	}
672 
673 	return 0;
674 }
675 
676 static void __f2fs_submit_merged_write(struct f2fs_sb_info *sbi,
677 				enum page_type type, enum temp_type temp)
678 {
679 	enum page_type btype = PAGE_TYPE_OF_BIO(type);
680 	struct f2fs_bio_info *io = sbi->write_io[btype] + temp;
681 	struct f2fs_lock_context lc;
682 
683 	f2fs_down_write_trace(&io->io_rwsem, &lc);
684 
685 	if (!io->bio)
686 		goto unlock_out;
687 
688 	/* change META to META_FLUSH in the checkpoint procedure */
689 	if (type >= META_FLUSH) {
690 		io->fio.type = META_FLUSH;
691 		io->bio->bi_opf |= REQ_META | REQ_PRIO | REQ_SYNC;
692 		if (!test_opt(sbi, NOBARRIER))
693 			io->bio->bi_opf |= REQ_PREFLUSH | REQ_FUA;
694 	}
695 	__submit_merged_bio(io);
696 unlock_out:
697 	f2fs_up_write_trace(&io->io_rwsem, &lc);
698 }
699 
700 static void __submit_merged_write_cond(struct f2fs_sb_info *sbi,
701 				struct inode *inode, struct folio *folio,
702 				nid_t ino, enum page_type type, bool writeback)
703 {
704 	enum temp_type temp;
705 	bool ret = true;
706 	bool force = !inode && !folio && !ino;
707 
708 	for (temp = HOT; temp < NR_TEMP_TYPE; temp++) {
709 		if (!force)	{
710 			enum page_type btype = PAGE_TYPE_OF_BIO(type);
711 			struct f2fs_bio_info *io = sbi->write_io[btype] + temp;
712 			struct f2fs_lock_context lc;
713 
714 			f2fs_down_read_trace(&io->io_rwsem, &lc);
715 			ret = __has_merged_page(io->bio, inode, folio, ino);
716 			f2fs_up_read_trace(&io->io_rwsem, &lc);
717 		}
718 		if (ret) {
719 			__f2fs_submit_merged_write(sbi, type, temp);
720 			/*
721 			 * For waitting writebck case, if the bio owned by the
722 			 * folio is already submitted, we do not need to submit
723 			 * other types of bios.
724 			 */
725 			if (writeback)
726 				break;
727 		}
728 
729 		/* TODO: use HOT temp only for meta pages now. */
730 		if (type >= META)
731 			break;
732 	}
733 }
734 
735 void f2fs_submit_merged_write(struct f2fs_sb_info *sbi, enum page_type type)
736 {
737 	__submit_merged_write_cond(sbi, NULL, NULL, 0, type, false);
738 }
739 
740 void f2fs_submit_merged_write_cond(struct f2fs_sb_info *sbi,
741 				struct inode *inode, struct folio *folio,
742 				nid_t ino, enum page_type type)
743 {
744 	__submit_merged_write_cond(sbi, inode, folio, ino, type, false);
745 }
746 
747 void f2fs_submit_merged_write_folio(struct f2fs_sb_info *sbi,
748 				struct folio *folio, enum page_type type)
749 {
750 	__submit_merged_write_cond(sbi, NULL, folio, 0, type, true);
751 }
752 
753 void f2fs_flush_merged_writes(struct f2fs_sb_info *sbi)
754 {
755 	f2fs_submit_merged_write(sbi, DATA);
756 	f2fs_submit_merged_write(sbi, NODE);
757 	f2fs_submit_merged_write(sbi, META);
758 }
759 
760 /*
761  * Fill the locked page with data located in the block address.
762  * A caller needs to unlock the page on failure.
763  */
764 int f2fs_submit_page_bio(struct f2fs_io_info *fio)
765 {
766 	struct bio *bio;
767 	struct folio *fio_folio = fio->folio;
768 	struct folio *data_folio = fio->encrypted_page ?
769 			page_folio(fio->encrypted_page) : fio_folio;
770 
771 	if (!f2fs_is_valid_blkaddr(fio->sbi, fio->new_blkaddr,
772 			fio->is_por ? META_POR : (__is_meta_io(fio) ?
773 			META_GENERIC : DATA_GENERIC_ENHANCE)))
774 		return -EFSCORRUPTED;
775 
776 	trace_f2fs_submit_folio_bio(data_folio, fio);
777 
778 	/* Allocate a new bio */
779 	bio = __bio_alloc(fio, 1);
780 
781 	f2fs_set_bio_crypt_ctx(bio, fio_folio->mapping->host,
782 			fio_folio->index, fio, GFP_NOIO);
783 	bio_add_folio_nofail(bio, data_folio, folio_size(data_folio), 0);
784 
785 	if (fio->io_wbc && !is_read_io(fio->op))
786 		wbc_account_cgroup_owner(fio->io_wbc, fio_folio, PAGE_SIZE);
787 
788 	inc_page_count(fio->sbi, is_read_io(fio->op) ?
789 			__read_io_type(data_folio) : WB_DATA_TYPE(fio->folio, false));
790 
791 	if (is_read_io(bio_op(bio)))
792 		f2fs_submit_read_bio(fio->sbi, bio, fio->type);
793 	else
794 		f2fs_submit_write_bio(fio->sbi, bio, fio->type);
795 	return 0;
796 }
797 
798 static bool page_is_mergeable(struct f2fs_sb_info *sbi, struct bio *bio,
799 				block_t last_blkaddr, block_t cur_blkaddr)
800 {
801 	if (unlikely(sbi->max_io_bytes &&
802 			bio->bi_iter.bi_size >= sbi->max_io_bytes))
803 		return false;
804 	if (last_blkaddr + 1 != cur_blkaddr)
805 		return false;
806 	return bio->bi_bdev == f2fs_target_device(sbi, cur_blkaddr, NULL);
807 }
808 
809 static bool io_type_is_mergeable(struct f2fs_bio_info *io,
810 						struct f2fs_io_info *fio)
811 {
812 	blk_opf_t mask = ~(REQ_PREFLUSH | REQ_FUA);
813 
814 	if (io->fio.op != fio->op)
815 		return false;
816 	return (io->fio.op_flags & mask) == (fio->op_flags & mask);
817 }
818 
819 static bool io_is_mergeable(struct f2fs_sb_info *sbi, struct bio *bio,
820 					struct f2fs_bio_info *io,
821 					struct f2fs_io_info *fio,
822 					block_t last_blkaddr,
823 					block_t cur_blkaddr)
824 {
825 	if (!page_is_mergeable(sbi, bio, last_blkaddr, cur_blkaddr))
826 		return false;
827 	return io_type_is_mergeable(io, fio);
828 }
829 
830 static void add_bio_entry(struct f2fs_sb_info *sbi, struct bio *bio,
831 				struct folio *folio, enum temp_type temp)
832 {
833 	struct f2fs_bio_info *io = sbi->write_io[DATA] + temp;
834 	struct bio_entry *be;
835 
836 	be = f2fs_kmem_cache_alloc(bio_entry_slab, GFP_NOFS, true, NULL);
837 	be->bio = bio;
838 	bio_get(bio);
839 
840 	bio_add_folio_nofail(bio, folio, folio_size(folio), 0);
841 
842 	f2fs_down_write(&io->bio_list_lock);
843 	list_add_tail(&be->list, &io->bio_list);
844 	f2fs_up_write(&io->bio_list_lock);
845 }
846 
847 static void del_bio_entry(struct bio_entry *be)
848 {
849 	list_del(&be->list);
850 	kmem_cache_free(bio_entry_slab, be);
851 }
852 
853 static int add_ipu_page(struct f2fs_io_info *fio, struct bio **bio,
854 							struct folio *folio)
855 {
856 	struct folio *fio_folio = fio->folio;
857 	struct f2fs_sb_info *sbi = fio->sbi;
858 	enum temp_type temp;
859 	bool found = false;
860 	int ret = -EAGAIN;
861 
862 	for (temp = HOT; temp < NR_TEMP_TYPE && !found; temp++) {
863 		struct f2fs_bio_info *io = sbi->write_io[DATA] + temp;
864 		struct list_head *head = &io->bio_list;
865 		struct bio_entry *be;
866 
867 		f2fs_down_write(&io->bio_list_lock);
868 		list_for_each_entry(be, head, list) {
869 			if (be->bio != *bio)
870 				continue;
871 
872 			found = true;
873 
874 			f2fs_bug_on(sbi, !page_is_mergeable(sbi, *bio,
875 							    *fio->last_block,
876 							    fio->new_blkaddr));
877 			if (f2fs_crypt_mergeable_bio(*bio,
878 					fio_folio->mapping->host,
879 					fio_folio->index, fio) &&
880 			    bio_add_folio(*bio, folio, folio_size(folio), 0)) {
881 				ret = 0;
882 				break;
883 			}
884 
885 			/* page can't be merged into bio; submit the bio */
886 			del_bio_entry(be);
887 			f2fs_submit_write_bio(sbi, *bio, DATA);
888 			break;
889 		}
890 		f2fs_up_write(&io->bio_list_lock);
891 	}
892 
893 	if (ret) {
894 		bio_put(*bio);
895 		*bio = NULL;
896 	}
897 
898 	return ret;
899 }
900 
901 void f2fs_submit_merged_ipu_write(struct f2fs_sb_info *sbi,
902 					struct bio **bio, struct folio *folio)
903 {
904 	enum temp_type temp;
905 	bool found = false;
906 	struct bio *target = bio ? *bio : NULL;
907 
908 	f2fs_bug_on(sbi, !target && !folio);
909 
910 	for (temp = HOT; temp < NR_TEMP_TYPE && !found; temp++) {
911 		struct f2fs_bio_info *io = sbi->write_io[DATA] + temp;
912 		struct list_head *head = &io->bio_list;
913 		struct bio_entry *be;
914 
915 		if (list_empty(head))
916 			continue;
917 
918 		f2fs_down_read(&io->bio_list_lock);
919 		list_for_each_entry(be, head, list) {
920 			if (target)
921 				found = (target == be->bio);
922 			else
923 				found = __has_merged_page(be->bio, NULL,
924 							folio, 0);
925 			if (found)
926 				break;
927 		}
928 		f2fs_up_read(&io->bio_list_lock);
929 
930 		if (!found)
931 			continue;
932 
933 		found = false;
934 
935 		f2fs_down_write(&io->bio_list_lock);
936 		list_for_each_entry(be, head, list) {
937 			if (target)
938 				found = (target == be->bio);
939 			else
940 				found = __has_merged_page(be->bio, NULL,
941 							folio, 0);
942 			if (found) {
943 				target = be->bio;
944 				del_bio_entry(be);
945 				break;
946 			}
947 		}
948 		f2fs_up_write(&io->bio_list_lock);
949 	}
950 
951 	if (found)
952 		f2fs_submit_write_bio(sbi, target, DATA);
953 	if (bio && *bio) {
954 		bio_put(*bio);
955 		*bio = NULL;
956 	}
957 }
958 
959 void f2fs_submit_all_merged_ipu_writes(struct f2fs_sb_info *sbi)
960 {
961 	struct bio_entry *be, *tmp;
962 	struct f2fs_bio_info *io;
963 	enum temp_type temp;
964 
965 	for (temp = HOT; temp < NR_TEMP_TYPE; temp++) {
966 		LIST_HEAD(list);
967 
968 		io = sbi->write_io[DATA] + temp;
969 
970 		/* A lockless list_empty() check is safe here: any bios from
971 		 * other kworkers that we miss will be submitted by those
972 		 * kworkers accordingly.
973 		 */
974 		if (list_empty(&io->bio_list))
975 			continue;
976 
977 		f2fs_down_write(&io->bio_list_lock);
978 		list_splice_init(&io->bio_list, &list);
979 		f2fs_up_write(&io->bio_list_lock);
980 
981 		list_for_each_entry_safe(be, tmp, &list, list) {
982 			f2fs_submit_write_bio(sbi, be->bio, DATA);
983 			del_bio_entry(be);
984 		}
985 	}
986 }
987 
988 int f2fs_merge_page_bio(struct f2fs_io_info *fio)
989 {
990 	struct bio *bio = *fio->bio;
991 	struct folio *data_folio = fio->encrypted_page ?
992 			page_folio(fio->encrypted_page) : fio->folio;
993 	struct folio *folio = fio->folio;
994 
995 	if (!f2fs_is_valid_blkaddr(fio->sbi, fio->new_blkaddr,
996 			__is_meta_io(fio) ? META_GENERIC : DATA_GENERIC))
997 		return -EFSCORRUPTED;
998 
999 	trace_f2fs_submit_folio_bio(data_folio, fio);
1000 
1001 	if (bio && !page_is_mergeable(fio->sbi, bio, *fio->last_block,
1002 						fio->new_blkaddr))
1003 		f2fs_submit_merged_ipu_write(fio->sbi, &bio, NULL);
1004 alloc_new:
1005 	if (!bio) {
1006 		bio = __bio_alloc(fio, BIO_MAX_VECS);
1007 		f2fs_set_bio_crypt_ctx(bio, folio->mapping->host,
1008 				folio->index, fio, GFP_NOIO);
1009 
1010 		add_bio_entry(fio->sbi, bio, data_folio, fio->temp);
1011 	} else {
1012 		if (add_ipu_page(fio, &bio, data_folio))
1013 			goto alloc_new;
1014 	}
1015 
1016 	if (fio->io_wbc)
1017 		wbc_account_cgroup_owner(fio->io_wbc, folio, folio_size(folio));
1018 
1019 	inc_page_count(fio->sbi, WB_DATA_TYPE(folio, false));
1020 
1021 	*fio->last_block = fio->new_blkaddr;
1022 	*fio->bio = bio;
1023 
1024 	return 0;
1025 }
1026 
1027 #ifdef CONFIG_BLK_DEV_ZONED
1028 static bool is_end_zone_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr)
1029 {
1030 	struct block_device *bdev = sbi->sb->s_bdev;
1031 	int devi = 0;
1032 
1033 	if (f2fs_is_multi_device(sbi)) {
1034 		devi = f2fs_target_device_index(sbi, blkaddr);
1035 		if (blkaddr < FDEV(devi).start_blk ||
1036 		    blkaddr > FDEV(devi).end_blk) {
1037 			f2fs_err(sbi, "Invalid block %x", blkaddr);
1038 			return false;
1039 		}
1040 		blkaddr -= FDEV(devi).start_blk;
1041 		bdev = FDEV(devi).bdev;
1042 	}
1043 	return bdev_is_zoned(bdev) &&
1044 		f2fs_blkz_is_seq(sbi, devi, blkaddr) &&
1045 		(blkaddr % sbi->blocks_per_blkz == sbi->blocks_per_blkz - 1);
1046 }
1047 #endif
1048 
1049 void f2fs_submit_page_write(struct f2fs_io_info *fio)
1050 {
1051 	struct f2fs_sb_info *sbi = fio->sbi;
1052 	enum page_type btype = PAGE_TYPE_OF_BIO(fio->type);
1053 	struct f2fs_bio_info *io = sbi->write_io[btype] + fio->temp;
1054 	struct folio *bio_folio;
1055 	struct f2fs_lock_context lc;
1056 	enum count_type type;
1057 
1058 	f2fs_bug_on(sbi, is_read_io(fio->op));
1059 
1060 	f2fs_down_write_trace(&io->io_rwsem, &lc);
1061 next:
1062 #ifdef CONFIG_BLK_DEV_ZONED
1063 	if (f2fs_sb_has_blkzoned(sbi) && btype < META && io->zone_pending_bio) {
1064 		wait_for_completion_io(&io->zone_wait);
1065 		bio_put(io->zone_pending_bio);
1066 		io->zone_pending_bio = NULL;
1067 		io->bi_private = NULL;
1068 	}
1069 #endif
1070 
1071 	if (fio->in_list) {
1072 		spin_lock(&io->io_lock);
1073 		if (list_empty(&io->io_list)) {
1074 			spin_unlock(&io->io_lock);
1075 			goto out;
1076 		}
1077 		fio = list_first_entry(&io->io_list,
1078 						struct f2fs_io_info, list);
1079 		list_del(&fio->list);
1080 		spin_unlock(&io->io_lock);
1081 	}
1082 
1083 	verify_fio_blkaddr(fio);
1084 
1085 	if (fio->encrypted_page)
1086 		bio_folio = page_folio(fio->encrypted_page);
1087 	else if (fio->compressed_page)
1088 		bio_folio = page_folio(fio->compressed_page);
1089 	else
1090 		bio_folio = fio->folio;
1091 
1092 	/* set submitted = true as a return value */
1093 	fio->submitted = 1;
1094 
1095 	type = WB_DATA_TYPE(bio_folio, fio->compressed_page);
1096 	inc_page_count(sbi, type);
1097 
1098 	if (io->bio &&
1099 	    (!io_is_mergeable(sbi, io->bio, io, fio, io->last_block_in_bio,
1100 			      fio->new_blkaddr) ||
1101 	     !f2fs_crypt_mergeable_bio(io->bio, fio_inode(fio),
1102 				bio_folio->index, fio)))
1103 		__submit_merged_bio(io);
1104 alloc_new:
1105 	if (io->bio == NULL) {
1106 		io->bio = __bio_alloc(fio, BIO_MAX_VECS);
1107 		f2fs_set_bio_crypt_ctx(io->bio, fio_inode(fio),
1108 				bio_folio->index, fio, GFP_NOIO);
1109 		io->fio = *fio;
1110 	}
1111 
1112 	if (!bio_add_folio(io->bio, bio_folio, folio_size(bio_folio), 0)) {
1113 		__submit_merged_bio(io);
1114 		goto alloc_new;
1115 	}
1116 
1117 	if (fio->io_wbc)
1118 		wbc_account_cgroup_owner(fio->io_wbc, fio->folio,
1119 				folio_size(fio->folio));
1120 
1121 	io->last_block_in_bio = fio->new_blkaddr;
1122 
1123 	trace_f2fs_submit_folio_write(fio->folio, fio);
1124 #ifdef CONFIG_BLK_DEV_ZONED
1125 	if (f2fs_sb_has_blkzoned(sbi) && btype < META &&
1126 			is_end_zone_blkaddr(sbi, fio->new_blkaddr)) {
1127 		bio_get(io->bio);
1128 		reinit_completion(&io->zone_wait);
1129 		io->bi_private = io->bio->bi_private;
1130 		io->bio->bi_private = io;
1131 		io->bio->bi_end_io = f2fs_zone_write_end_io;
1132 		io->zone_pending_bio = io->bio;
1133 		__submit_merged_bio(io);
1134 	}
1135 #endif
1136 	if (fio->in_list)
1137 		goto next;
1138 out:
1139 	if (is_sbi_flag_set(sbi, SBI_IS_SHUTDOWN) ||
1140 				!f2fs_is_checkpoint_ready(sbi))
1141 		__submit_merged_bio(io);
1142 	f2fs_up_write_trace(&io->io_rwsem, &lc);
1143 }
1144 
1145 static struct bio *f2fs_grab_read_bio(struct inode *inode,
1146 				      struct fsverity_info *vi, block_t blkaddr,
1147 				      unsigned nr_pages, blk_opf_t op_flag,
1148 				      pgoff_t first_idx, bool for_write)
1149 {
1150 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1151 	struct bio *bio;
1152 	struct bio_post_read_ctx *ctx = NULL;
1153 	unsigned int post_read_steps = 0;
1154 	sector_t sector;
1155 	struct block_device *bdev = f2fs_target_device(sbi, blkaddr, &sector);
1156 
1157 	bio = bio_alloc_bioset(bdev, bio_max_segs(nr_pages),
1158 			       REQ_OP_READ | op_flag,
1159 			       for_write ? GFP_NOIO : GFP_KERNEL, &f2fs_bioset);
1160 	bio->bi_iter.bi_sector = sector;
1161 	f2fs_set_bio_crypt_ctx(bio, inode, first_idx, NULL, GFP_NOFS);
1162 	bio->bi_end_io = f2fs_read_end_io;
1163 
1164 	if (fscrypt_inode_uses_fs_layer_crypto(inode))
1165 		post_read_steps |= STEP_DECRYPT;
1166 
1167 	if (vi)
1168 		post_read_steps |= STEP_VERITY;
1169 
1170 	/*
1171 	 * STEP_DECOMPRESS is handled specially, since a compressed file might
1172 	 * contain both compressed and uncompressed clusters.  We'll allocate a
1173 	 * bio_post_read_ctx if the file is compressed, but the caller is
1174 	 * responsible for enabling STEP_DECOMPRESS if it's actually needed.
1175 	 */
1176 
1177 	if (post_read_steps || f2fs_compressed_file(inode)) {
1178 		/* Due to the mempool, this never fails. */
1179 		ctx = mempool_alloc(bio_post_read_ctx_pool, GFP_NOFS);
1180 		ctx->bio = bio;
1181 		ctx->sbi = sbi;
1182 		ctx->vi = vi;
1183 		ctx->enabled_steps = post_read_steps;
1184 		ctx->fs_blkaddr = blkaddr;
1185 		ctx->decompression_attempted = false;
1186 		bio->bi_private = ctx;
1187 	}
1188 	iostat_alloc_and_bind_ctx(sbi, bio, ctx);
1189 
1190 	return bio;
1191 }
1192 
1193 /* This can handle encryption stuffs */
1194 static void f2fs_submit_page_read(struct inode *inode, struct fsverity_info *vi,
1195 				  struct folio *folio, block_t blkaddr,
1196 				  blk_opf_t op_flags, bool for_write)
1197 {
1198 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1199 	struct bio *bio;
1200 
1201 	bio = f2fs_grab_read_bio(inode, vi, blkaddr, 1, op_flags, folio->index,
1202 				 for_write);
1203 
1204 	/* wait for GCed page writeback via META_MAPPING */
1205 	f2fs_wait_on_block_writeback(inode, blkaddr);
1206 
1207 	if (!bio_add_folio(bio, folio, PAGE_SIZE, 0))
1208 		f2fs_bug_on(sbi, 1);
1209 
1210 	inc_page_count(sbi, F2FS_RD_DATA);
1211 	f2fs_update_iostat(sbi, NULL, FS_DATA_READ_IO, F2FS_BLKSIZE);
1212 	f2fs_submit_read_bio(sbi, bio, DATA);
1213 }
1214 
1215 static void __set_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr)
1216 {
1217 	__le32 *addr = get_dnode_addr(dn->inode, dn->node_folio);
1218 
1219 	dn->data_blkaddr = blkaddr;
1220 	addr[dn->ofs_in_node] = cpu_to_le32(dn->data_blkaddr);
1221 }
1222 
1223 /*
1224  * Lock ordering for the change of data block address:
1225  * ->data_page
1226  *  ->node_folio
1227  *    update block addresses in the node page
1228  */
1229 void f2fs_set_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr)
1230 {
1231 	f2fs_folio_wait_writeback(dn->node_folio, NODE, true, true);
1232 	__set_data_blkaddr(dn, blkaddr);
1233 	if (folio_mark_dirty(dn->node_folio))
1234 		dn->node_changed = true;
1235 }
1236 
1237 void f2fs_update_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr)
1238 {
1239 	f2fs_set_data_blkaddr(dn, blkaddr);
1240 	f2fs_update_read_extent_cache(dn);
1241 }
1242 
1243 /* dn->ofs_in_node will be returned with up-to-date last block pointer */
1244 int f2fs_reserve_new_blocks(struct dnode_of_data *dn, blkcnt_t count)
1245 {
1246 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1247 	int err;
1248 
1249 	if (!count)
1250 		return 0;
1251 
1252 	if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
1253 		return -EPERM;
1254 	err = inc_valid_block_count(sbi, dn->inode, &count, true);
1255 	if (unlikely(err))
1256 		return err;
1257 
1258 	trace_f2fs_reserve_new_blocks(dn->inode, dn->nid,
1259 						dn->ofs_in_node, count);
1260 
1261 	f2fs_folio_wait_writeback(dn->node_folio, NODE, true, true);
1262 
1263 	for (; count > 0; dn->ofs_in_node++) {
1264 		block_t blkaddr = f2fs_data_blkaddr(dn);
1265 
1266 		if (blkaddr == NULL_ADDR) {
1267 			__set_data_blkaddr(dn, NEW_ADDR);
1268 			count--;
1269 		}
1270 	}
1271 
1272 	if (folio_mark_dirty(dn->node_folio))
1273 		dn->node_changed = true;
1274 	return 0;
1275 }
1276 
1277 /* Should keep dn->ofs_in_node unchanged */
1278 int f2fs_reserve_new_block(struct dnode_of_data *dn)
1279 {
1280 	unsigned int ofs_in_node = dn->ofs_in_node;
1281 	int ret;
1282 
1283 	ret = f2fs_reserve_new_blocks(dn, 1);
1284 	dn->ofs_in_node = ofs_in_node;
1285 	return ret;
1286 }
1287 
1288 int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index)
1289 {
1290 	bool need_put = dn->inode_folio ? false : true;
1291 	int err;
1292 
1293 	err = f2fs_get_dnode_of_data(dn, index, ALLOC_NODE);
1294 	if (err)
1295 		return err;
1296 
1297 	if (dn->data_blkaddr == NULL_ADDR)
1298 		err = f2fs_reserve_new_block(dn);
1299 	if (err || need_put)
1300 		f2fs_put_dnode(dn);
1301 	return err;
1302 }
1303 
1304 static inline struct fsverity_info *f2fs_need_verity(const struct inode *inode,
1305 						     pgoff_t idx)
1306 {
1307 	if (idx < DIV_ROUND_UP(inode->i_size, PAGE_SIZE))
1308 		return fsverity_get_info(inode);
1309 	return NULL;
1310 }
1311 
1312 struct folio *f2fs_get_read_data_folio(struct inode *inode, pgoff_t index,
1313 		blk_opf_t op_flags, bool for_write, pgoff_t *next_pgofs)
1314 {
1315 	struct address_space *mapping = inode->i_mapping;
1316 	struct dnode_of_data dn;
1317 	struct folio *folio;
1318 	int err;
1319 retry:
1320 	folio = f2fs_grab_cache_folio(mapping, index, for_write);
1321 	if (IS_ERR(folio))
1322 		return folio;
1323 
1324 	if (folio_test_large(folio)) {
1325 		pgoff_t folio_index = mapping_align_index(mapping, index);
1326 
1327 		f2fs_folio_put(folio, true);
1328 		invalidate_inode_pages2_range(mapping, folio_index,
1329 				folio_index + folio_nr_pages(folio) - 1);
1330 		f2fs_schedule_timeout(DEFAULT_SCHEDULE_TIMEOUT);
1331 		goto retry;
1332 	}
1333 
1334 	if (f2fs_lookup_read_extent_cache_block(inode, index,
1335 						&dn.data_blkaddr)) {
1336 		if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), dn.data_blkaddr,
1337 						DATA_GENERIC_ENHANCE_READ)) {
1338 			err = -EFSCORRUPTED;
1339 			goto put_err;
1340 		}
1341 		goto got_it;
1342 	}
1343 
1344 	set_new_dnode(&dn, inode, NULL, NULL, 0);
1345 	err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
1346 	if (err) {
1347 		if (err == -ENOENT && next_pgofs)
1348 			*next_pgofs = f2fs_get_next_page_offset(&dn, index);
1349 		goto put_err;
1350 	}
1351 	f2fs_put_dnode(&dn);
1352 
1353 	if (unlikely(dn.data_blkaddr == NULL_ADDR)) {
1354 		err = -ENOENT;
1355 		if (next_pgofs)
1356 			*next_pgofs = index + 1;
1357 		goto put_err;
1358 	}
1359 	if (dn.data_blkaddr != NEW_ADDR &&
1360 			!f2fs_is_valid_blkaddr(F2FS_I_SB(inode),
1361 						dn.data_blkaddr,
1362 						DATA_GENERIC_ENHANCE)) {
1363 		err = -EFSCORRUPTED;
1364 		goto put_err;
1365 	}
1366 got_it:
1367 	if (folio_test_uptodate(folio)) {
1368 		folio_unlock(folio);
1369 		return folio;
1370 	}
1371 
1372 	/*
1373 	 * A new dentry page is allocated but not able to be written, since its
1374 	 * new inode page couldn't be allocated due to -ENOSPC.
1375 	 * In such the case, its blkaddr can be remained as NEW_ADDR.
1376 	 * see, f2fs_add_link -> f2fs_get_new_data_folio ->
1377 	 * f2fs_init_inode_metadata.
1378 	 */
1379 	if (dn.data_blkaddr == NEW_ADDR) {
1380 		folio_zero_segment(folio, 0, folio_size(folio));
1381 		if (!folio_test_uptodate(folio))
1382 			folio_mark_uptodate(folio);
1383 		folio_unlock(folio);
1384 		return folio;
1385 	}
1386 
1387 	f2fs_submit_page_read(inode, f2fs_need_verity(inode, folio->index),
1388 			      folio, dn.data_blkaddr, op_flags, for_write);
1389 	return folio;
1390 
1391 put_err:
1392 	f2fs_folio_put(folio, true);
1393 	return ERR_PTR(err);
1394 }
1395 
1396 struct folio *f2fs_find_data_folio(struct inode *inode, pgoff_t index,
1397 					pgoff_t *next_pgofs)
1398 {
1399 	struct address_space *mapping = inode->i_mapping;
1400 	struct folio *folio;
1401 
1402 	folio = f2fs_filemap_get_folio(mapping, index, FGP_ACCESSED, 0);
1403 	if (IS_ERR(folio))
1404 		goto read;
1405 	if (folio_test_uptodate(folio))
1406 		return folio;
1407 	f2fs_folio_put(folio, false);
1408 
1409 read:
1410 	folio = f2fs_get_read_data_folio(inode, index, 0, false, next_pgofs);
1411 	if (IS_ERR(folio))
1412 		return folio;
1413 
1414 	if (folio_test_uptodate(folio))
1415 		return folio;
1416 
1417 	folio_wait_locked(folio);
1418 	if (unlikely(!folio_test_uptodate(folio))) {
1419 		f2fs_folio_put(folio, false);
1420 		return ERR_PTR(-EIO);
1421 	}
1422 	return folio;
1423 }
1424 
1425 /*
1426  * If it tries to access a hole, return an error.
1427  * Because, the callers, functions in dir.c and GC, should be able to know
1428  * whether this page exists or not.
1429  */
1430 struct folio *f2fs_get_lock_data_folio(struct inode *inode, pgoff_t index,
1431 							bool for_write)
1432 {
1433 	struct address_space *mapping = inode->i_mapping;
1434 	struct folio *folio;
1435 
1436 	folio = f2fs_get_read_data_folio(inode, index, 0, for_write, NULL);
1437 	if (IS_ERR(folio))
1438 		return folio;
1439 
1440 	/* wait for read completion */
1441 	folio_lock(folio);
1442 	if (unlikely(folio->mapping != mapping || !folio_test_uptodate(folio))) {
1443 		f2fs_folio_put(folio, true);
1444 		return ERR_PTR(-EIO);
1445 	}
1446 	return folio;
1447 }
1448 
1449 /*
1450  * Caller ensures that this data page is never allocated.
1451  * A new zero-filled data page is allocated in the page cache.
1452  *
1453  * Also, caller should grab and release a rwsem by calling f2fs_lock_op() and
1454  * f2fs_unlock_op().
1455  * Note that, ifolio is set only by make_empty_dir, and if any error occur,
1456  * ifolio should be released by this function.
1457  */
1458 struct folio *f2fs_get_new_data_folio(struct inode *inode,
1459 		struct folio *ifolio, pgoff_t index, bool new_i_size)
1460 {
1461 	struct address_space *mapping = inode->i_mapping;
1462 	struct folio *folio;
1463 	struct dnode_of_data dn;
1464 	int err;
1465 
1466 	folio = f2fs_grab_cache_folio(mapping, index, true);
1467 	if (IS_ERR(folio)) {
1468 		/*
1469 		 * before exiting, we should make sure ifolio will be released
1470 		 * if any error occur.
1471 		 */
1472 		f2fs_folio_put(ifolio, true);
1473 		return ERR_PTR(-ENOMEM);
1474 	}
1475 
1476 	set_new_dnode(&dn, inode, ifolio, NULL, 0);
1477 	err = f2fs_reserve_block(&dn, index);
1478 	if (err) {
1479 		f2fs_folio_put(folio, true);
1480 		return ERR_PTR(err);
1481 	}
1482 	if (!ifolio)
1483 		f2fs_put_dnode(&dn);
1484 
1485 	if (folio_test_uptodate(folio))
1486 		goto got_it;
1487 
1488 	if (dn.data_blkaddr == NEW_ADDR) {
1489 		folio_zero_segment(folio, 0, folio_size(folio));
1490 		if (!folio_test_uptodate(folio))
1491 			folio_mark_uptodate(folio);
1492 	} else {
1493 		f2fs_folio_put(folio, true);
1494 
1495 		/* if ifolio exists, blkaddr should be NEW_ADDR */
1496 		f2fs_bug_on(F2FS_I_SB(inode), ifolio);
1497 		folio = f2fs_get_lock_data_folio(inode, index, true);
1498 		if (IS_ERR(folio))
1499 			return folio;
1500 	}
1501 got_it:
1502 	if (new_i_size && i_size_read(inode) <
1503 				((loff_t)(index + 1) << PAGE_SHIFT))
1504 		f2fs_i_size_write(inode, ((loff_t)(index + 1) << PAGE_SHIFT));
1505 	return folio;
1506 }
1507 
1508 static int __allocate_data_block(struct dnode_of_data *dn, int seg_type)
1509 {
1510 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1511 	struct f2fs_summary sum;
1512 	struct node_info ni;
1513 	block_t old_blkaddr;
1514 	blkcnt_t count = 1;
1515 	int err;
1516 
1517 	if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
1518 		return -EPERM;
1519 
1520 	err = f2fs_get_node_info(sbi, dn->nid, &ni, false);
1521 	if (err)
1522 		return err;
1523 
1524 	dn->data_blkaddr = f2fs_data_blkaddr(dn);
1525 	if (dn->data_blkaddr == NULL_ADDR) {
1526 		err = inc_valid_block_count(sbi, dn->inode, &count, true);
1527 		if (unlikely(err))
1528 			return err;
1529 	}
1530 
1531 	set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
1532 	old_blkaddr = dn->data_blkaddr;
1533 	err = f2fs_allocate_data_block(sbi, NULL, old_blkaddr,
1534 				&dn->data_blkaddr, &sum, seg_type, NULL);
1535 	if (err)
1536 		return err;
1537 
1538 	if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
1539 		f2fs_invalidate_internal_cache(sbi, old_blkaddr, 1);
1540 
1541 	f2fs_update_data_blkaddr(dn, dn->data_blkaddr);
1542 	return 0;
1543 }
1544 
1545 static void f2fs_map_lock(struct f2fs_sb_info *sbi,
1546 				struct f2fs_lock_context *lc,
1547 				int flag)
1548 {
1549 	if (flag == F2FS_GET_BLOCK_PRE_AIO)
1550 		f2fs_down_read_trace(&sbi->node_change, lc);
1551 	else
1552 		f2fs_lock_op(sbi, lc);
1553 }
1554 
1555 static void f2fs_map_unlock(struct f2fs_sb_info *sbi,
1556 				struct f2fs_lock_context *lc,
1557 				int flag)
1558 {
1559 	if (flag == F2FS_GET_BLOCK_PRE_AIO)
1560 		f2fs_up_read_trace(&sbi->node_change, lc);
1561 	else
1562 		f2fs_unlock_op(sbi, lc);
1563 }
1564 
1565 int f2fs_get_block_locked(struct dnode_of_data *dn, pgoff_t index)
1566 {
1567 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1568 	struct f2fs_lock_context lc;
1569 	int err = 0;
1570 
1571 	f2fs_map_lock(sbi, &lc, F2FS_GET_BLOCK_PRE_AIO);
1572 	if (!f2fs_lookup_read_extent_cache_block(dn->inode, index,
1573 						&dn->data_blkaddr))
1574 		err = f2fs_reserve_block(dn, index);
1575 	f2fs_map_unlock(sbi, &lc, F2FS_GET_BLOCK_PRE_AIO);
1576 
1577 	return err;
1578 }
1579 
1580 static int f2fs_map_no_dnode(struct inode *inode,
1581 		struct f2fs_map_blocks *map, struct dnode_of_data *dn,
1582 		pgoff_t pgoff)
1583 {
1584 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1585 
1586 	/*
1587 	 * There is one exceptional case that read_node_page() may return
1588 	 * -ENOENT due to filesystem has been shutdown or cp_error, return
1589 	 * -EIO in that case.
1590 	 */
1591 	if (map->m_may_create &&
1592 	    (is_sbi_flag_set(sbi, SBI_IS_SHUTDOWN) || f2fs_cp_error(sbi)))
1593 		return -EIO;
1594 
1595 	if (map->m_next_pgofs)
1596 		*map->m_next_pgofs = f2fs_get_next_page_offset(dn, pgoff);
1597 	if (map->m_next_extent)
1598 		*map->m_next_extent = f2fs_get_next_page_offset(dn, pgoff);
1599 	return 0;
1600 }
1601 
1602 static bool f2fs_map_blocks_cached(struct inode *inode,
1603 		struct f2fs_map_blocks *map, int flag)
1604 {
1605 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1606 	unsigned int maxblocks = map->m_len;
1607 	pgoff_t pgoff = (pgoff_t)map->m_lblk;
1608 	struct extent_info ei = {};
1609 
1610 	if (!f2fs_lookup_read_extent_cache(inode, pgoff, &ei))
1611 		return false;
1612 
1613 	map->m_pblk = ei.blk + pgoff - ei.fofs;
1614 	map->m_len = min((pgoff_t)maxblocks, ei.fofs + ei.len - pgoff);
1615 	map->m_flags = F2FS_MAP_MAPPED;
1616 	if (map->m_next_extent)
1617 		*map->m_next_extent = pgoff + map->m_len;
1618 
1619 	/* for hardware encryption, but to avoid potential issue in future */
1620 	if (flag == F2FS_GET_BLOCK_DIO)
1621 		f2fs_wait_on_block_writeback_range(inode,
1622 					map->m_pblk, map->m_len);
1623 
1624 	map->m_multidev_dio = f2fs_allow_multi_device_dio(sbi, flag);
1625 	if (map->m_multidev_dio) {
1626 		int bidx = f2fs_target_device_index(sbi, map->m_pblk);
1627 		struct f2fs_dev_info *dev = &sbi->devs[bidx];
1628 
1629 		map->m_bdev = dev->bdev;
1630 		map->m_len = min(map->m_len, dev->end_blk + 1 - map->m_pblk);
1631 		map->m_pblk -= dev->start_blk;
1632 	} else {
1633 		map->m_bdev = inode->i_sb->s_bdev;
1634 	}
1635 	return true;
1636 }
1637 
1638 static bool map_is_mergeable(struct f2fs_sb_info *sbi,
1639 				struct f2fs_map_blocks *map,
1640 				block_t blkaddr, int flag, int bidx,
1641 				int ofs)
1642 {
1643 	if (map->m_multidev_dio && map->m_bdev != FDEV(bidx).bdev)
1644 		return false;
1645 	if (map->m_pblk != NEW_ADDR && blkaddr == (map->m_pblk + ofs))
1646 		return true;
1647 	if (map->m_pblk == NEW_ADDR && blkaddr == NEW_ADDR)
1648 		return true;
1649 	if (flag == F2FS_GET_BLOCK_PRE_DIO)
1650 		return true;
1651 	if (flag == F2FS_GET_BLOCK_DIO &&
1652 		map->m_pblk == NULL_ADDR && blkaddr == NULL_ADDR)
1653 		return true;
1654 	return false;
1655 }
1656 
1657 /*
1658  * f2fs_map_blocks() tries to find or build mapping relationship which
1659  * maps continuous logical blocks to physical blocks, and return such
1660  * info via f2fs_map_blocks structure.
1661  */
1662 int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map, int flag)
1663 {
1664 	unsigned int maxblocks = map->m_len;
1665 	struct dnode_of_data dn;
1666 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1667 	struct f2fs_lock_context lc;
1668 	int mode = map->m_may_create ? ALLOC_NODE : LOOKUP_NODE;
1669 	pgoff_t pgofs, end_offset, end;
1670 	int err = 0, ofs = 1;
1671 	unsigned int ofs_in_node, last_ofs_in_node;
1672 	blkcnt_t prealloc;
1673 	block_t blkaddr;
1674 	unsigned int start_pgofs;
1675 	int bidx = 0;
1676 	bool is_hole;
1677 	bool lfs_dio_write;
1678 
1679 	if (!maxblocks)
1680 		return 0;
1681 
1682 	lfs_dio_write = (flag == F2FS_GET_BLOCK_DIO && f2fs_lfs_mode(sbi) &&
1683 				map->m_may_create);
1684 
1685 	if (!map->m_may_create && f2fs_map_blocks_cached(inode, map, flag)) {
1686 		struct extent_info ei;
1687 
1688 		/*
1689 		 * 1. If map->m_multidev_dio is true, map->m_pblk cannot be
1690 		 * waitted by f2fs_wait_on_block_writeback_range() and are not
1691 		 * mergeable.
1692 		 * 2. If pgofs hits the read extent cache, it means the mapping
1693 		 * is already cached in the extent cache, but it is not
1694 		 * mergeable, and there is no need to query the mapping again
1695 		 * via f2fs_get_dnode_of_data().
1696 		 */
1697 		pgofs =	(pgoff_t)map->m_lblk + map->m_len;
1698 		if (map->m_len == maxblocks ||
1699 			map->m_multidev_dio ||
1700 			f2fs_lookup_read_extent_cache(inode, pgofs, &ei))
1701 			goto out;
1702 		ofs = map->m_len;
1703 		goto map_more;
1704 	}
1705 
1706 	map->m_bdev = inode->i_sb->s_bdev;
1707 	map->m_multidev_dio =
1708 		f2fs_allow_multi_device_dio(F2FS_I_SB(inode), flag);
1709 
1710 	map->m_len = 0;
1711 	map->m_flags = 0;
1712 
1713 	/* it only supports block size == page size */
1714 	pgofs =	(pgoff_t)map->m_lblk;
1715 map_more:
1716 	end = (pgoff_t)map->m_lblk + maxblocks;
1717 
1718 	if (flag == F2FS_GET_BLOCK_PRECACHE)
1719 		mode = LOOKUP_NODE_RA;
1720 
1721 next_dnode:
1722 	if (map->m_may_create) {
1723 		if (f2fs_lfs_mode(sbi))
1724 			f2fs_balance_fs(sbi, true);
1725 		f2fs_map_lock(sbi, &lc, flag);
1726 	}
1727 
1728 	/* When reading holes, we need its node page */
1729 	set_new_dnode(&dn, inode, NULL, NULL, 0);
1730 	err = f2fs_get_dnode_of_data(&dn, pgofs, mode);
1731 	if (err) {
1732 		if (flag == F2FS_GET_BLOCK_BMAP)
1733 			map->m_pblk = 0;
1734 		if (err == -ENOENT)
1735 			err = f2fs_map_no_dnode(inode, map, &dn, pgofs);
1736 		goto unlock_out;
1737 	}
1738 
1739 	start_pgofs = pgofs;
1740 	prealloc = 0;
1741 	last_ofs_in_node = ofs_in_node = dn.ofs_in_node;
1742 	end_offset = ADDRS_PER_PAGE(dn.node_folio, inode);
1743 
1744 next_block:
1745 	blkaddr = f2fs_data_blkaddr(&dn);
1746 	is_hole = !__is_valid_data_blkaddr(blkaddr);
1747 	if (!is_hole &&
1748 	    !f2fs_is_valid_blkaddr(sbi, blkaddr, DATA_GENERIC_ENHANCE)) {
1749 		err = -EFSCORRUPTED;
1750 		goto sync_out;
1751 	}
1752 
1753 	/* use out-place-update for direct IO under LFS mode */
1754 	if (map->m_may_create && (is_hole ||
1755 		(flag == F2FS_GET_BLOCK_DIO && f2fs_lfs_mode(sbi) &&
1756 		!f2fs_is_pinned_file(inode) && map->m_last_pblk != blkaddr))) {
1757 		if (unlikely(f2fs_cp_error(sbi))) {
1758 			err = -EIO;
1759 			goto sync_out;
1760 		}
1761 
1762 		switch (flag) {
1763 		case F2FS_GET_BLOCK_PRE_AIO:
1764 			if (blkaddr == NULL_ADDR) {
1765 				prealloc++;
1766 				last_ofs_in_node = dn.ofs_in_node;
1767 			}
1768 			break;
1769 		case F2FS_GET_BLOCK_PRE_DIO:
1770 		case F2FS_GET_BLOCK_DIO:
1771 			err = __allocate_data_block(&dn, map->m_seg_type);
1772 			if (err)
1773 				goto sync_out;
1774 			if (flag == F2FS_GET_BLOCK_PRE_DIO)
1775 				file_need_truncate(inode);
1776 			set_inode_flag(inode, FI_APPEND_WRITE);
1777 			break;
1778 		default:
1779 			WARN_ON_ONCE(1);
1780 			err = -EIO;
1781 			goto sync_out;
1782 		}
1783 
1784 		blkaddr = dn.data_blkaddr;
1785 		if (is_hole)
1786 			map->m_flags |= F2FS_MAP_NEW;
1787 	} else if (is_hole) {
1788 		if (f2fs_compressed_file(inode) &&
1789 		    f2fs_sanity_check_cluster(&dn)) {
1790 			err = -EFSCORRUPTED;
1791 			f2fs_handle_error(sbi,
1792 					ERROR_CORRUPTED_CLUSTER);
1793 			fserror_report_file_metadata(inode, err, GFP_NOFS);
1794 			goto sync_out;
1795 		}
1796 
1797 		switch (flag) {
1798 		case F2FS_GET_BLOCK_PRECACHE:
1799 			goto sync_out;
1800 		case F2FS_GET_BLOCK_BMAP:
1801 			map->m_pblk = 0;
1802 			goto sync_out;
1803 		case F2FS_GET_BLOCK_FIEMAP:
1804 			if (blkaddr == NULL_ADDR) {
1805 				if (map->m_next_pgofs)
1806 					*map->m_next_pgofs = pgofs + 1;
1807 				goto sync_out;
1808 			}
1809 			break;
1810 		case F2FS_GET_BLOCK_DIO:
1811 			if (map->m_next_pgofs)
1812 				*map->m_next_pgofs = pgofs + 1;
1813 			break;
1814 		default:
1815 			/* for defragment case */
1816 			if (map->m_next_pgofs)
1817 				*map->m_next_pgofs = pgofs + 1;
1818 			goto sync_out;
1819 		}
1820 	}
1821 
1822 	if (flag == F2FS_GET_BLOCK_PRE_AIO)
1823 		goto skip;
1824 
1825 	if (map->m_multidev_dio)
1826 		bidx = f2fs_target_device_index(sbi, blkaddr);
1827 
1828 	if (map->m_len == 0) {
1829 		/* reserved delalloc block should be mapped for fiemap. */
1830 		if (blkaddr == NEW_ADDR)
1831 			map->m_flags |= F2FS_MAP_DELALLOC;
1832 		/* DIO READ and hole case, should not map the blocks. */
1833 		if (!(flag == F2FS_GET_BLOCK_DIO && is_hole && !map->m_may_create))
1834 			map->m_flags |= F2FS_MAP_MAPPED;
1835 
1836 		map->m_pblk = blkaddr;
1837 		map->m_len = 1;
1838 
1839 		if (map->m_multidev_dio)
1840 			map->m_bdev = FDEV(bidx).bdev;
1841 
1842 		if (lfs_dio_write)
1843 			map->m_last_pblk = NULL_ADDR;
1844 	} else if (map_is_mergeable(sbi, map, blkaddr, flag, bidx, ofs)) {
1845 		ofs++;
1846 		map->m_len++;
1847 	} else {
1848 		if (lfs_dio_write && !f2fs_is_pinned_file(inode))
1849 			map->m_last_pblk = blkaddr;
1850 		goto sync_out;
1851 	}
1852 
1853 skip:
1854 	dn.ofs_in_node++;
1855 	pgofs++;
1856 
1857 	/* preallocate blocks in batch for one dnode page */
1858 	if (flag == F2FS_GET_BLOCK_PRE_AIO &&
1859 			(pgofs == end || dn.ofs_in_node == end_offset)) {
1860 
1861 		dn.ofs_in_node = ofs_in_node;
1862 		err = f2fs_reserve_new_blocks(&dn, prealloc);
1863 		if (err)
1864 			goto sync_out;
1865 
1866 		map->m_len += dn.ofs_in_node - ofs_in_node;
1867 		if (prealloc && dn.ofs_in_node != last_ofs_in_node + 1) {
1868 			err = -ENOSPC;
1869 			goto sync_out;
1870 		}
1871 		dn.ofs_in_node = end_offset;
1872 	}
1873 
1874 	if (pgofs >= end)
1875 		goto sync_out;
1876 	else if (dn.ofs_in_node < end_offset)
1877 		goto next_block;
1878 
1879 	if (flag == F2FS_GET_BLOCK_PRECACHE) {
1880 		if (map->m_flags & F2FS_MAP_MAPPED) {
1881 			unsigned int ofs = start_pgofs - map->m_lblk;
1882 
1883 			f2fs_update_read_extent_cache_range(&dn,
1884 				start_pgofs, map->m_pblk + ofs,
1885 				map->m_len - ofs);
1886 		}
1887 	}
1888 
1889 	f2fs_put_dnode(&dn);
1890 
1891 	if (map->m_may_create) {
1892 		f2fs_map_unlock(sbi, &lc, flag);
1893 		f2fs_balance_fs(sbi, dn.node_changed);
1894 	}
1895 	goto next_dnode;
1896 
1897 sync_out:
1898 
1899 	if (flag == F2FS_GET_BLOCK_DIO && map->m_flags & F2FS_MAP_MAPPED) {
1900 		/*
1901 		 * for hardware encryption, but to avoid potential issue
1902 		 * in future
1903 		 */
1904 		f2fs_wait_on_block_writeback_range(inode,
1905 						map->m_pblk, map->m_len);
1906 
1907 		if (map->m_multidev_dio) {
1908 			block_t blk_addr = map->m_pblk;
1909 
1910 			bidx = f2fs_target_device_index(sbi, map->m_pblk);
1911 
1912 			map->m_bdev = FDEV(bidx).bdev;
1913 			map->m_pblk -= FDEV(bidx).start_blk;
1914 
1915 			if (map->m_may_create)
1916 				f2fs_update_device_state(sbi, inode->i_ino,
1917 							blk_addr, map->m_len);
1918 
1919 			f2fs_bug_on(sbi, blk_addr + map->m_len >
1920 						FDEV(bidx).end_blk + 1);
1921 		}
1922 	}
1923 
1924 	if (flag == F2FS_GET_BLOCK_PRECACHE) {
1925 		if (map->m_flags & F2FS_MAP_MAPPED) {
1926 			unsigned int ofs = start_pgofs - map->m_lblk;
1927 
1928 			if (map->m_len > ofs)
1929 				f2fs_update_read_extent_cache_range(&dn,
1930 					start_pgofs, map->m_pblk + ofs,
1931 					map->m_len - ofs);
1932 		}
1933 		if (map->m_next_extent)
1934 			*map->m_next_extent = is_hole ? pgofs + 1 : pgofs;
1935 	}
1936 	f2fs_put_dnode(&dn);
1937 unlock_out:
1938 	if (map->m_may_create) {
1939 		f2fs_map_unlock(sbi, &lc, flag);
1940 		f2fs_balance_fs(sbi, dn.node_changed);
1941 	}
1942 out:
1943 	trace_f2fs_map_blocks(inode, map, flag, err);
1944 	return err;
1945 }
1946 
1947 static bool __f2fs_overwrite_io(struct inode *inode, loff_t pos, size_t len,
1948 				bool check_first)
1949 {
1950 	struct f2fs_map_blocks map;
1951 	block_t last_lblk;
1952 	int err;
1953 
1954 	if (pos + len > i_size_read(inode))
1955 		return false;
1956 
1957 	map.m_lblk = F2FS_BYTES_TO_BLK(pos);
1958 	map.m_next_pgofs = NULL;
1959 	map.m_next_extent = NULL;
1960 	map.m_seg_type = NO_CHECK_TYPE;
1961 	map.m_may_create = false;
1962 	last_lblk = F2FS_BLK_ALIGN(pos + len);
1963 
1964 	while (map.m_lblk < last_lblk) {
1965 		map.m_len = last_lblk - map.m_lblk;
1966 		err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_DEFAULT);
1967 		if (err || map.m_len == 0)
1968 			return false;
1969 		map.m_lblk += map.m_len;
1970 		if (check_first)
1971 			break;
1972 	}
1973 	return true;
1974 }
1975 
1976 bool f2fs_overwrite_io(struct inode *inode, loff_t pos, size_t len)
1977 {
1978 	return __f2fs_overwrite_io(inode, pos, len, false);
1979 }
1980 
1981 static int f2fs_xattr_fiemap(struct inode *inode,
1982 				struct fiemap_extent_info *fieinfo)
1983 {
1984 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1985 	struct node_info ni;
1986 	__u64 phys = 0, len;
1987 	__u32 flags;
1988 	nid_t xnid = F2FS_I(inode)->i_xattr_nid;
1989 	int err = 0;
1990 
1991 	if (f2fs_has_inline_xattr(inode)) {
1992 		int offset;
1993 		struct folio *folio = f2fs_grab_cache_folio(NODE_MAPPING(sbi),
1994 				inode->i_ino, false);
1995 
1996 		if (IS_ERR(folio))
1997 			return PTR_ERR(folio);
1998 
1999 		err = f2fs_get_node_info(sbi, inode->i_ino, &ni, false);
2000 		if (err) {
2001 			f2fs_folio_put(folio, true);
2002 			return err;
2003 		}
2004 
2005 		phys = F2FS_BLK_TO_BYTES(ni.blk_addr);
2006 		offset = offsetof(struct f2fs_inode, i_addr) +
2007 					sizeof(__le32) * (DEF_ADDRS_PER_INODE -
2008 					get_inline_xattr_addrs(inode));
2009 
2010 		phys += offset;
2011 		len = inline_xattr_size(inode);
2012 
2013 		f2fs_folio_put(folio, true);
2014 
2015 		flags = FIEMAP_EXTENT_DATA_INLINE | FIEMAP_EXTENT_NOT_ALIGNED;
2016 
2017 		if (!xnid)
2018 			flags |= FIEMAP_EXTENT_LAST;
2019 
2020 		err = fiemap_fill_next_extent(fieinfo, 0, phys, len, flags);
2021 		trace_f2fs_fiemap(inode, 0, phys, len, flags, err);
2022 		if (err)
2023 			return err;
2024 	}
2025 
2026 	if (xnid) {
2027 		struct folio *folio = f2fs_grab_cache_folio(NODE_MAPPING(sbi),
2028 				xnid, false);
2029 
2030 		if (IS_ERR(folio))
2031 			return PTR_ERR(folio);
2032 
2033 		err = f2fs_get_node_info(sbi, xnid, &ni, false);
2034 		if (err) {
2035 			f2fs_folio_put(folio, true);
2036 			return err;
2037 		}
2038 
2039 		phys = F2FS_BLK_TO_BYTES(ni.blk_addr);
2040 		len = inode->i_sb->s_blocksize;
2041 
2042 		f2fs_folio_put(folio, true);
2043 
2044 		flags = FIEMAP_EXTENT_LAST;
2045 	}
2046 
2047 	if (phys) {
2048 		err = fiemap_fill_next_extent(fieinfo, 0, phys, len, flags);
2049 		trace_f2fs_fiemap(inode, 0, phys, len, flags, err);
2050 	}
2051 
2052 	return (err < 0 ? err : 0);
2053 }
2054 
2055 int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
2056 		u64 start, u64 len)
2057 {
2058 	struct f2fs_map_blocks map;
2059 	sector_t start_blk, last_blk, blk_len, max_len;
2060 	pgoff_t next_pgofs;
2061 	u64 logical = 0, phys = 0, size = 0;
2062 	u32 flags = 0;
2063 	int ret = 0;
2064 	bool compr_cluster = false, compr_appended;
2065 	unsigned int cluster_size = F2FS_I(inode)->i_cluster_size;
2066 	unsigned int count_in_cluster = 0;
2067 	loff_t maxbytes;
2068 
2069 	if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
2070 		ret = f2fs_precache_extents(inode);
2071 		if (ret)
2072 			return ret;
2073 	}
2074 
2075 	ret = fiemap_prep(inode, fieinfo, start, &len, FIEMAP_FLAG_XATTR);
2076 	if (ret)
2077 		return ret;
2078 
2079 	inode_lock_shared(inode);
2080 
2081 	maxbytes = F2FS_BLK_TO_BYTES(max_file_blocks(inode));
2082 	if (start > maxbytes) {
2083 		ret = -EFBIG;
2084 		goto out;
2085 	}
2086 
2087 	if (len > maxbytes || (maxbytes - len) < start)
2088 		len = maxbytes - start;
2089 
2090 	if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
2091 		ret = f2fs_xattr_fiemap(inode, fieinfo);
2092 		goto out;
2093 	}
2094 
2095 	if (f2fs_has_inline_data(inode) || f2fs_has_inline_dentry(inode)) {
2096 		ret = f2fs_inline_data_fiemap(inode, fieinfo, start, len);
2097 		if (ret != -EAGAIN)
2098 			goto out;
2099 	}
2100 
2101 	start_blk = F2FS_BYTES_TO_BLK(start);
2102 	last_blk = F2FS_BYTES_TO_BLK(start + len - 1);
2103 	blk_len = last_blk - start_blk + 1;
2104 	max_len = F2FS_BYTES_TO_BLK(maxbytes) - start_blk;
2105 
2106 next:
2107 	memset(&map, 0, sizeof(map));
2108 	map.m_lblk = start_blk;
2109 	map.m_len = blk_len;
2110 	map.m_next_pgofs = &next_pgofs;
2111 	map.m_seg_type = NO_CHECK_TYPE;
2112 
2113 	if (compr_cluster) {
2114 		map.m_lblk += 1;
2115 		map.m_len = cluster_size - count_in_cluster;
2116 	}
2117 
2118 	ret = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_FIEMAP);
2119 	if (ret)
2120 		goto out;
2121 
2122 	/* HOLE */
2123 	if (!compr_cluster && !(map.m_flags & F2FS_MAP_FLAGS)) {
2124 		start_blk = next_pgofs;
2125 
2126 		if (F2FS_BLK_TO_BYTES(start_blk) < maxbytes)
2127 			goto prep_next;
2128 
2129 		flags |= FIEMAP_EXTENT_LAST;
2130 	}
2131 
2132 	/*
2133 	 * current extent may cross boundary of inquiry, increase len to
2134 	 * requery.
2135 	 */
2136 	if (!compr_cluster && (map.m_flags & F2FS_MAP_MAPPED) &&
2137 				map.m_lblk + map.m_len - 1 == last_blk &&
2138 				blk_len != max_len) {
2139 		blk_len = max_len;
2140 		goto next;
2141 	}
2142 
2143 	compr_appended = false;
2144 	/* In a case of compressed cluster, append this to the last extent */
2145 	if (compr_cluster && ((map.m_flags & F2FS_MAP_DELALLOC) ||
2146 			!(map.m_flags & F2FS_MAP_FLAGS))) {
2147 		compr_appended = true;
2148 		goto skip_fill;
2149 	}
2150 
2151 	if (size) {
2152 		flags |= FIEMAP_EXTENT_MERGED;
2153 		if (IS_ENCRYPTED(inode))
2154 			flags |= FIEMAP_EXTENT_DATA_ENCRYPTED;
2155 
2156 		ret = fiemap_fill_next_extent(fieinfo, logical,
2157 				phys, size, flags);
2158 		trace_f2fs_fiemap(inode, logical, phys, size, flags, ret);
2159 		if (ret)
2160 			goto out;
2161 		size = 0;
2162 	}
2163 
2164 	if (start_blk > last_blk)
2165 		goto out;
2166 
2167 skip_fill:
2168 	if (map.m_pblk == COMPRESS_ADDR) {
2169 		compr_cluster = true;
2170 		count_in_cluster = 1;
2171 	} else if (compr_appended) {
2172 		unsigned int appended_blks = cluster_size -
2173 						count_in_cluster + 1;
2174 		size += F2FS_BLK_TO_BYTES(appended_blks);
2175 		start_blk += appended_blks;
2176 		compr_cluster = false;
2177 	} else {
2178 		logical = F2FS_BLK_TO_BYTES(start_blk);
2179 		phys = __is_valid_data_blkaddr(map.m_pblk) ?
2180 			F2FS_BLK_TO_BYTES(map.m_pblk) : 0;
2181 		size = F2FS_BLK_TO_BYTES(map.m_len);
2182 		flags = 0;
2183 
2184 		if (compr_cluster) {
2185 			flags = FIEMAP_EXTENT_ENCODED;
2186 			count_in_cluster += map.m_len;
2187 			if (count_in_cluster == cluster_size) {
2188 				compr_cluster = false;
2189 				size += F2FS_BLKSIZE;
2190 			}
2191 		} else if (map.m_flags & F2FS_MAP_DELALLOC) {
2192 			flags = FIEMAP_EXTENT_UNWRITTEN;
2193 		}
2194 
2195 		start_blk += F2FS_BYTES_TO_BLK(size);
2196 	}
2197 
2198 prep_next:
2199 	cond_resched();
2200 	if (fatal_signal_pending(current))
2201 		ret = -EINTR;
2202 	else
2203 		goto next;
2204 out:
2205 	if (ret == 1)
2206 		ret = 0;
2207 
2208 	inode_unlock_shared(inode);
2209 	return ret;
2210 }
2211 
2212 static inline loff_t f2fs_readpage_limit(struct inode *inode)
2213 {
2214 	if (IS_ENABLED(CONFIG_FS_VERITY) && IS_VERITY(inode))
2215 		return F2FS_BLK_TO_BYTES(max_file_blocks(inode));
2216 
2217 	return i_size_read(inode);
2218 }
2219 
2220 static inline blk_opf_t f2fs_ra_op_flags(struct readahead_control *rac)
2221 {
2222 	return rac ? REQ_RAHEAD : 0;
2223 }
2224 
2225 static int f2fs_read_single_page(struct inode *inode, struct fsverity_info *vi,
2226 				 struct folio *folio, unsigned int nr_pages,
2227 				 struct f2fs_map_blocks *map,
2228 				 struct bio **bio_ret,
2229 				 sector_t *last_block_in_bio,
2230 				 struct readahead_control *rac)
2231 {
2232 	struct bio *bio = *bio_ret;
2233 	const unsigned int blocksize = F2FS_BLKSIZE;
2234 	sector_t block_in_file;
2235 	sector_t last_block;
2236 	sector_t last_block_in_file;
2237 	sector_t block_nr;
2238 	pgoff_t index = folio->index;
2239 	int ret = 0;
2240 
2241 	block_in_file = (sector_t)index;
2242 	last_block = block_in_file + nr_pages;
2243 	last_block_in_file = F2FS_BYTES_TO_BLK(f2fs_readpage_limit(inode) +
2244 							blocksize - 1);
2245 	if (last_block > last_block_in_file)
2246 		last_block = last_block_in_file;
2247 
2248 	/* just zeroing out page which is beyond EOF */
2249 	if (block_in_file >= last_block)
2250 		goto zero_out;
2251 	/*
2252 	 * Map blocks using the previous result first.
2253 	 */
2254 	if (map->m_flags & F2FS_MAP_MAPPED) {
2255 		if (block_in_file > map->m_lblk &&
2256 			block_in_file < (map->m_lblk + map->m_len))
2257 			goto got_it;
2258 	} else if (block_in_file < *map->m_next_pgofs) {
2259 		goto got_it;
2260 	}
2261 
2262 	/*
2263 	 * Then do more f2fs_map_blocks() calls until we are
2264 	 * done with this page.
2265 	 */
2266 	map->m_lblk = block_in_file;
2267 	map->m_len = last_block - block_in_file;
2268 
2269 	ret = f2fs_map_blocks(inode, map, F2FS_GET_BLOCK_DEFAULT);
2270 	if (ret)
2271 		goto out;
2272 got_it:
2273 	if ((map->m_flags & F2FS_MAP_MAPPED)) {
2274 		block_nr = map->m_pblk + block_in_file - map->m_lblk;
2275 		folio_set_mappedtodisk(folio);
2276 
2277 		if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), block_nr,
2278 						DATA_GENERIC_ENHANCE_READ)) {
2279 			ret = -EFSCORRUPTED;
2280 			goto out;
2281 		}
2282 	} else {
2283 zero_out:
2284 		folio_zero_segment(folio, 0, folio_size(folio));
2285 		if (vi && !fsverity_verify_folio(vi, folio)) {
2286 			ret = -EIO;
2287 			goto out;
2288 		}
2289 		if (!folio_test_uptodate(folio))
2290 			folio_mark_uptodate(folio);
2291 		folio_unlock(folio);
2292 		goto out;
2293 	}
2294 
2295 	/*
2296 	 * This page will go to BIO.  Do we need to send this
2297 	 * BIO off first?
2298 	 */
2299 	if (bio && (!page_is_mergeable(F2FS_I_SB(inode), bio,
2300 				       *last_block_in_bio, block_nr) ||
2301 		    !f2fs_crypt_mergeable_bio(bio, inode, index, NULL))) {
2302 submit_and_realloc:
2303 		f2fs_submit_read_bio(F2FS_I_SB(inode), bio, DATA);
2304 		bio = NULL;
2305 	}
2306 	if (bio == NULL)
2307 		bio = f2fs_grab_read_bio(inode, vi, block_nr, nr_pages,
2308 					 f2fs_ra_op_flags(rac), index, false);
2309 
2310 	/*
2311 	 * If the page is under writeback, we need to wait for
2312 	 * its completion to see the correct decrypted data.
2313 	 */
2314 	f2fs_wait_on_block_writeback(inode, block_nr);
2315 
2316 	if (!bio_add_folio(bio, folio, blocksize, 0))
2317 		goto submit_and_realloc;
2318 
2319 	inc_page_count(F2FS_I_SB(inode), F2FS_RD_DATA);
2320 	f2fs_update_iostat(F2FS_I_SB(inode), NULL, FS_DATA_READ_IO,
2321 							F2FS_BLKSIZE);
2322 	*last_block_in_bio = block_nr;
2323 out:
2324 	*bio_ret = bio;
2325 	return ret;
2326 }
2327 
2328 #ifdef CONFIG_F2FS_FS_COMPRESSION
2329 int f2fs_read_multi_pages(struct compress_ctx *cc, struct bio **bio_ret,
2330 				unsigned nr_pages, sector_t *last_block_in_bio,
2331 				struct readahead_control *rac, bool for_write)
2332 {
2333 	struct dnode_of_data dn;
2334 	struct inode *inode = cc->inode;
2335 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2336 	struct bio *bio = *bio_ret;
2337 	unsigned int start_idx = cc->cluster_idx << cc->log_cluster_size;
2338 	sector_t last_block_in_file;
2339 	const unsigned int blocksize = F2FS_BLKSIZE;
2340 	struct decompress_io_ctx *dic = NULL;
2341 	struct extent_info ei = {};
2342 	bool from_dnode = true;
2343 	int i;
2344 	int ret = 0;
2345 
2346 	if (unlikely(f2fs_cp_error(sbi))) {
2347 		ret = -EIO;
2348 		from_dnode = false;
2349 		goto out_put_dnode;
2350 	}
2351 
2352 	f2fs_bug_on(sbi, f2fs_cluster_is_empty(cc));
2353 
2354 	last_block_in_file = F2FS_BYTES_TO_BLK(f2fs_readpage_limit(inode) +
2355 							blocksize - 1);
2356 
2357 	/* get rid of pages beyond EOF */
2358 	for (i = 0; i < cc->cluster_size; i++) {
2359 		struct page *page = cc->rpages[i];
2360 		struct folio *folio;
2361 
2362 		if (!page)
2363 			continue;
2364 
2365 		folio = page_folio(page);
2366 		if ((sector_t)folio->index >= last_block_in_file) {
2367 			folio_zero_segment(folio, 0, folio_size(folio));
2368 			if (!folio_test_uptodate(folio))
2369 				folio_mark_uptodate(folio);
2370 		} else if (!folio_test_uptodate(folio)) {
2371 			continue;
2372 		}
2373 		folio_unlock(folio);
2374 		if (for_write)
2375 			folio_put(folio);
2376 		cc->rpages[i] = NULL;
2377 		cc->nr_rpages--;
2378 	}
2379 
2380 	/* we are done since all pages are beyond EOF */
2381 	if (f2fs_cluster_is_empty(cc))
2382 		goto out;
2383 
2384 	if (f2fs_lookup_read_extent_cache(inode, start_idx, &ei))
2385 		from_dnode = false;
2386 
2387 	if (!from_dnode)
2388 		goto skip_reading_dnode;
2389 
2390 	set_new_dnode(&dn, inode, NULL, NULL, 0);
2391 	ret = f2fs_get_dnode_of_data(&dn, start_idx, LOOKUP_NODE);
2392 	if (ret)
2393 		goto out;
2394 
2395 	f2fs_bug_on(sbi, dn.data_blkaddr != COMPRESS_ADDR);
2396 
2397 skip_reading_dnode:
2398 	for (i = 1; i < cc->cluster_size; i++) {
2399 		block_t blkaddr;
2400 
2401 		blkaddr = from_dnode ? data_blkaddr(dn.inode, dn.node_folio,
2402 					dn.ofs_in_node + i) :
2403 					ei.blk + i - 1;
2404 
2405 		if (!__is_valid_data_blkaddr(blkaddr))
2406 			break;
2407 
2408 		if (!f2fs_is_valid_blkaddr(sbi, blkaddr, DATA_GENERIC)) {
2409 			ret = -EFAULT;
2410 			goto out_put_dnode;
2411 		}
2412 		cc->nr_cpages++;
2413 
2414 		if (!from_dnode && i >= ei.c_len)
2415 			break;
2416 	}
2417 
2418 	/* nothing to decompress */
2419 	if (cc->nr_cpages == 0) {
2420 		ret = 0;
2421 		goto out_put_dnode;
2422 	}
2423 
2424 	dic = f2fs_alloc_dic(cc);
2425 	if (IS_ERR(dic)) {
2426 		ret = PTR_ERR(dic);
2427 		goto out_put_dnode;
2428 	}
2429 
2430 	for (i = 0; i < cc->nr_cpages; i++) {
2431 		struct folio *folio = page_folio(dic->cpages[i]);
2432 		block_t blkaddr;
2433 		struct bio_post_read_ctx *ctx;
2434 
2435 		blkaddr = from_dnode ? data_blkaddr(dn.inode, dn.node_folio,
2436 					dn.ofs_in_node + i + 1) :
2437 					ei.blk + i;
2438 
2439 		f2fs_wait_on_block_writeback(inode, blkaddr);
2440 
2441 		if (f2fs_load_compressed_folio(sbi, folio, blkaddr)) {
2442 			if (atomic_dec_and_test(&dic->remaining_pages)) {
2443 				f2fs_decompress_cluster(dic, true);
2444 				break;
2445 			}
2446 			continue;
2447 		}
2448 
2449 		if (bio && (!page_is_mergeable(sbi, bio,
2450 					*last_block_in_bio, blkaddr) ||
2451 		    !f2fs_crypt_mergeable_bio(bio, inode, folio->index, NULL))) {
2452 submit_and_realloc:
2453 			f2fs_submit_read_bio(sbi, bio, DATA);
2454 			bio = NULL;
2455 		}
2456 
2457 		if (!bio)
2458 			bio = f2fs_grab_read_bio(inode, cc->vi, blkaddr,
2459 						 nr_pages - i,
2460 						 f2fs_ra_op_flags(rac),
2461 						 folio->index, for_write);
2462 
2463 		if (!bio_add_folio(bio, folio, blocksize, 0))
2464 			goto submit_and_realloc;
2465 
2466 		ctx = get_post_read_ctx(bio);
2467 		ctx->enabled_steps |= STEP_DECOMPRESS;
2468 		refcount_inc(&dic->refcnt);
2469 
2470 		inc_page_count(sbi, F2FS_RD_DATA);
2471 		f2fs_update_iostat(sbi, inode, FS_DATA_READ_IO, F2FS_BLKSIZE);
2472 		*last_block_in_bio = blkaddr;
2473 	}
2474 
2475 	if (from_dnode)
2476 		f2fs_put_dnode(&dn);
2477 
2478 	*bio_ret = bio;
2479 	return 0;
2480 
2481 out_put_dnode:
2482 	if (from_dnode)
2483 		f2fs_put_dnode(&dn);
2484 out:
2485 	for (i = 0; i < cc->cluster_size; i++) {
2486 		if (cc->rpages[i]) {
2487 			ClearPageUptodate(cc->rpages[i]);
2488 			unlock_page(cc->rpages[i]);
2489 		}
2490 	}
2491 	*bio_ret = bio;
2492 	return ret;
2493 }
2494 #endif
2495 
2496 static struct f2fs_folio_state *ffs_find_or_alloc(struct folio *folio)
2497 {
2498 	struct f2fs_folio_state *ffs = folio->private;
2499 
2500 	if (ffs)
2501 		return ffs;
2502 
2503 	ffs = f2fs_kmem_cache_alloc(ffs_entry_slab,
2504 			GFP_NOIO | __GFP_ZERO, true, NULL);
2505 
2506 	spin_lock_init(&ffs->state_lock);
2507 	folio_attach_private(folio, ffs);
2508 	return ffs;
2509 }
2510 
2511 static void ffs_detach_free(struct folio *folio)
2512 {
2513 	struct f2fs_folio_state *ffs;
2514 
2515 	if (!folio_test_large(folio)) {
2516 		folio_detach_private(folio);
2517 		return;
2518 	}
2519 
2520 	ffs = folio_detach_private(folio);
2521 	if (!ffs)
2522 		return;
2523 
2524 	WARN_ON_ONCE(ffs->read_pages_pending != 0);
2525 	kmem_cache_free(ffs_entry_slab, ffs);
2526 }
2527 
2528 static int f2fs_read_data_large_folio(struct inode *inode,
2529 		struct fsverity_info *vi,
2530 		struct readahead_control *rac, struct folio *folio)
2531 {
2532 	struct bio *bio = NULL;
2533 	sector_t last_block_in_bio = 0;
2534 	struct f2fs_map_blocks map = {0, };
2535 	pgoff_t index, offset, next_pgofs = 0;
2536 	unsigned max_nr_pages = rac ? readahead_count(rac) :
2537 				folio_nr_pages(folio);
2538 	unsigned nrpages;
2539 	struct f2fs_folio_state *ffs;
2540 	int ret = 0;
2541 	bool folio_in_bio = false;
2542 
2543 	if (!IS_IMMUTABLE(inode) || f2fs_compressed_file(inode)) {
2544 		if (folio)
2545 			folio_unlock(folio);
2546 		return -EOPNOTSUPP;
2547 	}
2548 
2549 	map.m_seg_type = NO_CHECK_TYPE;
2550 
2551 	if (rac)
2552 		folio = readahead_folio(rac);
2553 next_folio:
2554 	if (!folio)
2555 		goto out;
2556 
2557 	f2fs_update_read_folio_count(F2FS_I_SB(inode), folio);
2558 
2559 	folio_in_bio = false;
2560 	index = folio->index;
2561 	offset = 0;
2562 	ffs = NULL;
2563 	nrpages = folio_nr_pages(folio);
2564 
2565 	for (; nrpages; nrpages--, max_nr_pages--, index++, offset++) {
2566 		sector_t block_nr;
2567 		/*
2568 		 * Map blocks using the previous result first.
2569 		 */
2570 		if (map.m_flags & F2FS_MAP_MAPPED) {
2571 			if (index > map.m_lblk &&
2572 				index < (map.m_lblk + map.m_len))
2573 				goto got_it;
2574 		} else if (index < next_pgofs) {
2575 			/* hole case */
2576 			goto got_it;
2577 		}
2578 
2579 		/*
2580 		 * Then do more f2fs_map_blocks() calls until we are
2581 		 * done with this page.
2582 		 */
2583 		memset(&map, 0, sizeof(map));
2584 		map.m_next_pgofs = &next_pgofs;
2585 		map.m_seg_type = NO_CHECK_TYPE;
2586 		map.m_lblk = index;
2587 		map.m_len = max_nr_pages;
2588 
2589 		ret = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_DEFAULT);
2590 		if (ret)
2591 			goto err_out;
2592 got_it:
2593 		if ((map.m_flags & F2FS_MAP_MAPPED)) {
2594 			block_nr = map.m_pblk + index - map.m_lblk;
2595 			if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), block_nr,
2596 						DATA_GENERIC_ENHANCE_READ)) {
2597 				ret = -EFSCORRUPTED;
2598 				goto err_out;
2599 			}
2600 		} else {
2601 			size_t page_offset = offset << PAGE_SHIFT;
2602 			folio_zero_range(folio, page_offset, PAGE_SIZE);
2603 			if (vi && !fsverity_verify_blocks(vi, folio, PAGE_SIZE, page_offset)) {
2604 				ret = -EIO;
2605 				goto err_out;
2606 			}
2607 			continue;
2608 		}
2609 
2610 		/* We must increment read_pages_pending before possible BIOs submitting
2611 		 * to prevent from premature folio_end_read() call on folio
2612 		 */
2613 		if (folio_test_large(folio)) {
2614 			ffs = ffs_find_or_alloc(folio);
2615 
2616 			/* set the bitmap to wait */
2617 			spin_lock_irq(&ffs->state_lock);
2618 			ffs->read_pages_pending++;
2619 			spin_unlock_irq(&ffs->state_lock);
2620 		}
2621 
2622 		/*
2623 		 * This page will go to BIO.  Do we need to send this
2624 		 * BIO off first?
2625 		 */
2626 		if (bio && (!page_is_mergeable(F2FS_I_SB(inode), bio,
2627 						last_block_in_bio, block_nr) ||
2628 			!f2fs_crypt_mergeable_bio(bio, inode, index, NULL))) {
2629 submit_and_realloc:
2630 			f2fs_submit_read_bio(F2FS_I_SB(inode), bio, DATA);
2631 			bio = NULL;
2632 		}
2633 		if (bio == NULL)
2634 			bio = f2fs_grab_read_bio(inode, vi,
2635 					block_nr, max_nr_pages,
2636 					f2fs_ra_op_flags(rac),
2637 					index, false);
2638 
2639 		/*
2640 		 * If the page is under writeback, we need to wait for
2641 		 * its completion to see the correct decrypted data.
2642 		 */
2643 		f2fs_wait_on_block_writeback(inode, block_nr);
2644 
2645 		if (!bio_add_folio(bio, folio, F2FS_BLKSIZE,
2646 					offset << PAGE_SHIFT))
2647 			goto submit_and_realloc;
2648 
2649 		folio_in_bio = true;
2650 		inc_page_count(F2FS_I_SB(inode), F2FS_RD_DATA);
2651 		f2fs_update_iostat(F2FS_I_SB(inode), NULL, FS_DATA_READ_IO,
2652 				F2FS_BLKSIZE);
2653 		last_block_in_bio = block_nr;
2654 	}
2655 	trace_f2fs_read_folio(folio, DATA);
2656 err_out:
2657 	if (!folio_in_bio)
2658 		folio_end_read(folio, !ret);
2659 	if (ret)
2660 		goto out;
2661 	if (rac) {
2662 		folio = readahead_folio(rac);
2663 		goto next_folio;
2664 	}
2665 out:
2666 	f2fs_submit_read_bio(F2FS_I_SB(inode), bio, DATA);
2667 	if (ret && folio_in_bio) {
2668 		/* Wait bios and clear uptodate. */
2669 		folio_lock(folio);
2670 		folio_clear_uptodate(folio);
2671 		folio_unlock(folio);
2672 	}
2673 	return ret;
2674 }
2675 
2676 /*
2677  * This function was originally taken from fs/mpage.c, and customized for f2fs.
2678  * Major change was from block_size == page_size in f2fs by default.
2679  */
2680 static int f2fs_mpage_readpages(struct inode *inode, struct fsverity_info *vi,
2681 		struct readahead_control *rac, struct folio *folio)
2682 {
2683 	struct bio *bio = NULL;
2684 	sector_t last_block_in_bio = 0;
2685 	struct f2fs_map_blocks map;
2686 #ifdef CONFIG_F2FS_FS_COMPRESSION
2687 	struct compress_ctx cc = {
2688 		.inode = inode,
2689 		.log_cluster_size = F2FS_I(inode)->i_log_cluster_size,
2690 		.cluster_size = F2FS_I(inode)->i_cluster_size,
2691 		.cluster_idx = NULL_CLUSTER,
2692 		.rpages = NULL,
2693 		.cpages = NULL,
2694 		.nr_rpages = 0,
2695 		.nr_cpages = 0,
2696 	};
2697 	pgoff_t nc_cluster_idx = NULL_CLUSTER;
2698 	pgoff_t index;
2699 #endif
2700 	pgoff_t next_pgofs = 0;
2701 	unsigned nr_pages = rac ? readahead_count(rac) : 1;
2702 	struct address_space *mapping = rac ? rac->mapping : folio->mapping;
2703 	unsigned max_nr_pages = nr_pages;
2704 	int ret = 0;
2705 
2706 	if (mapping_large_folio_support(mapping))
2707 		return f2fs_read_data_large_folio(inode, vi, rac, folio);
2708 
2709 #ifdef CONFIG_F2FS_FS_COMPRESSION
2710 	if (f2fs_compressed_file(inode)) {
2711 		index = rac ? readahead_index(rac) : folio->index;
2712 		max_nr_pages = round_up(index + nr_pages, cc.cluster_size) -
2713 				round_down(index, cc.cluster_size);
2714 	}
2715 #endif
2716 
2717 	map.m_pblk = 0;
2718 	map.m_lblk = 0;
2719 	map.m_len = 0;
2720 	map.m_flags = 0;
2721 	map.m_next_pgofs = &next_pgofs;
2722 	map.m_next_extent = NULL;
2723 	map.m_seg_type = NO_CHECK_TYPE;
2724 	map.m_may_create = false;
2725 
2726 	for (; nr_pages; nr_pages--) {
2727 		if (rac) {
2728 			folio = readahead_folio(rac);
2729 			prefetchw(&folio->flags);
2730 		}
2731 
2732 		f2fs_update_read_folio_count(F2FS_I_SB(inode), folio);
2733 
2734 #ifdef CONFIG_F2FS_FS_COMPRESSION
2735 		index = folio->index;
2736 
2737 		if (!f2fs_compressed_file(inode))
2738 			goto read_single_page;
2739 
2740 		/* there are remained compressed pages, submit them */
2741 		if (!f2fs_cluster_can_merge_page(&cc, index)) {
2742 			cc.vi = vi;
2743 			ret = f2fs_read_multi_pages(&cc, &bio,
2744 						max_nr_pages,
2745 						&last_block_in_bio,
2746 						rac, false);
2747 			f2fs_destroy_compress_ctx(&cc, false);
2748 			if (ret)
2749 				goto set_error_page;
2750 		}
2751 		if (cc.cluster_idx == NULL_CLUSTER) {
2752 			if (nc_cluster_idx == index >> cc.log_cluster_size)
2753 				goto read_single_page;
2754 
2755 			ret = f2fs_is_compressed_cluster(inode, index);
2756 			if (ret < 0)
2757 				goto set_error_page;
2758 			else if (!ret) {
2759 				nc_cluster_idx =
2760 					index >> cc.log_cluster_size;
2761 				goto read_single_page;
2762 			}
2763 
2764 			nc_cluster_idx = NULL_CLUSTER;
2765 		}
2766 		ret = f2fs_init_compress_ctx(&cc);
2767 		if (ret)
2768 			goto set_error_page;
2769 
2770 		f2fs_compress_ctx_add_page(&cc, folio);
2771 
2772 		goto next_page;
2773 read_single_page:
2774 #endif
2775 
2776 		ret = f2fs_read_single_page(inode, vi, folio, max_nr_pages,
2777 					    &map, &bio, &last_block_in_bio,
2778 					    rac);
2779 		if (ret) {
2780 #ifdef CONFIG_F2FS_FS_COMPRESSION
2781 set_error_page:
2782 #endif
2783 			folio_zero_segment(folio, 0, folio_size(folio));
2784 			folio_unlock(folio);
2785 		}
2786 #ifdef CONFIG_F2FS_FS_COMPRESSION
2787 next_page:
2788 #endif
2789 
2790 #ifdef CONFIG_F2FS_FS_COMPRESSION
2791 		if (f2fs_compressed_file(inode)) {
2792 			/* last page */
2793 			if (nr_pages == 1 && !f2fs_cluster_is_empty(&cc)) {
2794 				cc.vi = vi;
2795 				ret = f2fs_read_multi_pages(&cc, &bio,
2796 							max_nr_pages,
2797 							&last_block_in_bio,
2798 							rac, false);
2799 				f2fs_destroy_compress_ctx(&cc, false);
2800 			}
2801 		}
2802 #endif
2803 	}
2804 	f2fs_submit_read_bio(F2FS_I_SB(inode), bio, DATA);
2805 	return ret;
2806 }
2807 
2808 static int f2fs_read_data_folio(struct file *file, struct folio *folio)
2809 {
2810 	struct inode *inode = folio->mapping->host;
2811 	struct fsverity_info *vi = NULL;
2812 	int ret;
2813 
2814 	trace_f2fs_readpage(folio, DATA);
2815 
2816 	if (!f2fs_is_compress_backend_ready(inode)) {
2817 		folio_unlock(folio);
2818 		return -EOPNOTSUPP;
2819 	}
2820 
2821 	/* If the file has inline data, try to read it directly */
2822 	if (f2fs_has_inline_data(inode)) {
2823 		ret = f2fs_read_inline_data(inode, folio);
2824 		if (ret != -EAGAIN)
2825 			return ret;
2826 	}
2827 
2828 	vi = f2fs_need_verity(inode, folio->index);
2829 	if (vi)
2830 		fsverity_readahead(vi, folio->index, folio_nr_pages(folio));
2831 	return f2fs_mpage_readpages(inode, vi, NULL, folio);
2832 }
2833 
2834 static void f2fs_readahead(struct readahead_control *rac)
2835 {
2836 	struct inode *inode = rac->mapping->host;
2837 	struct fsverity_info *vi = NULL;
2838 
2839 	trace_f2fs_readpages(inode, readahead_index(rac), readahead_count(rac));
2840 
2841 	if (!f2fs_is_compress_backend_ready(inode))
2842 		return;
2843 
2844 	/* If the file has inline data, skip readahead */
2845 	if (f2fs_has_inline_data(inode))
2846 		return;
2847 
2848 	vi = f2fs_need_verity(inode, readahead_index(rac));
2849 	if (vi)
2850 		fsverity_readahead(vi, readahead_index(rac),
2851 				   readahead_count(rac));
2852 	f2fs_mpage_readpages(inode, vi, rac, NULL);
2853 }
2854 
2855 int f2fs_encrypt_one_page(struct f2fs_io_info *fio)
2856 {
2857 	struct inode *inode = fio_inode(fio);
2858 	struct folio *mfolio;
2859 	struct page *page;
2860 
2861 	if (!f2fs_encrypted_file(inode))
2862 		return 0;
2863 
2864 	page = fio->compressed_page ? fio->compressed_page : fio->page;
2865 
2866 	if (fscrypt_inode_uses_inline_crypto(inode))
2867 		return 0;
2868 
2869 	fio->encrypted_page = fscrypt_encrypt_pagecache_blocks(page_folio(page),
2870 					PAGE_SIZE, 0, GFP_NOFS);
2871 	if (IS_ERR(fio->encrypted_page))
2872 		return PTR_ERR(fio->encrypted_page);
2873 
2874 	mfolio = filemap_lock_folio(META_MAPPING(fio->sbi), fio->old_blkaddr);
2875 	if (!IS_ERR(mfolio)) {
2876 		if (folio_test_uptodate(mfolio))
2877 			memcpy(folio_address(mfolio),
2878 				page_address(fio->encrypted_page), PAGE_SIZE);
2879 		f2fs_folio_put(mfolio, true);
2880 	}
2881 	return 0;
2882 }
2883 
2884 static inline bool check_inplace_update_policy(struct inode *inode,
2885 				struct f2fs_io_info *fio)
2886 {
2887 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2888 
2889 	if (IS_F2FS_IPU_HONOR_OPU_WRITE(sbi) &&
2890 	    is_inode_flag_set(inode, FI_OPU_WRITE))
2891 		return false;
2892 	if (IS_F2FS_IPU_FORCE(sbi))
2893 		return true;
2894 	if (IS_F2FS_IPU_SSR(sbi) && f2fs_need_SSR(sbi))
2895 		return true;
2896 	if (IS_F2FS_IPU_UTIL(sbi) && utilization(sbi) > SM_I(sbi)->min_ipu_util)
2897 		return true;
2898 	if (IS_F2FS_IPU_SSR_UTIL(sbi) && f2fs_need_SSR(sbi) &&
2899 	    utilization(sbi) > SM_I(sbi)->min_ipu_util)
2900 		return true;
2901 
2902 	/*
2903 	 * IPU for rewrite async pages
2904 	 */
2905 	if (IS_F2FS_IPU_ASYNC(sbi) && fio && fio->op == REQ_OP_WRITE &&
2906 	    !(fio->op_flags & REQ_SYNC) && !IS_ENCRYPTED(inode))
2907 		return true;
2908 
2909 	/* this is only set during fdatasync */
2910 	if (IS_F2FS_IPU_FSYNC(sbi) && is_inode_flag_set(inode, FI_NEED_IPU))
2911 		return true;
2912 
2913 	if (unlikely(fio && is_sbi_flag_set(sbi, SBI_CP_DISABLED) &&
2914 			!f2fs_is_checkpointed_data(sbi, fio->old_blkaddr)))
2915 		return true;
2916 
2917 	return false;
2918 }
2919 
2920 bool f2fs_should_update_inplace(struct inode *inode, struct f2fs_io_info *fio)
2921 {
2922 	/* swap file is migrating in aligned write mode */
2923 	if (is_inode_flag_set(inode, FI_ALIGNED_WRITE))
2924 		return false;
2925 
2926 	if (f2fs_is_pinned_file(inode))
2927 		return true;
2928 
2929 	/* if this is cold file, we should overwrite to avoid fragmentation */
2930 	if (file_is_cold(inode) && !is_inode_flag_set(inode, FI_OPU_WRITE))
2931 		return true;
2932 
2933 	return check_inplace_update_policy(inode, fio);
2934 }
2935 
2936 bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio)
2937 {
2938 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2939 
2940 	/* The below cases were checked when setting it. */
2941 	if (f2fs_is_pinned_file(inode))
2942 		return false;
2943 	if (fio && is_sbi_flag_set(sbi, SBI_NEED_FSCK))
2944 		return true;
2945 	if (f2fs_lfs_mode(sbi))
2946 		return true;
2947 	if (S_ISDIR(inode->i_mode))
2948 		return true;
2949 	if (IS_NOQUOTA(inode))
2950 		return true;
2951 	if (f2fs_used_in_atomic_write(inode))
2952 		return true;
2953 	/* rewrite low ratio compress data w/ OPU mode to avoid fragmentation */
2954 	if (f2fs_compressed_file(inode) &&
2955 		F2FS_OPTION(sbi).compress_mode == COMPR_MODE_USER &&
2956 		is_inode_flag_set(inode, FI_ENABLE_COMPRESS))
2957 		return true;
2958 
2959 	/* swap file is migrating in aligned write mode */
2960 	if (is_inode_flag_set(inode, FI_ALIGNED_WRITE))
2961 		return true;
2962 
2963 	if (is_inode_flag_set(inode, FI_OPU_WRITE))
2964 		return true;
2965 
2966 	if (fio) {
2967 		if (page_private_gcing(fio->page))
2968 			return true;
2969 		if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED) &&
2970 			f2fs_is_checkpointed_data(sbi, fio->old_blkaddr)))
2971 			return true;
2972 	}
2973 	return false;
2974 }
2975 
2976 static inline bool need_inplace_update(struct f2fs_io_info *fio)
2977 {
2978 	struct inode *inode = fio_inode(fio);
2979 
2980 	if (f2fs_should_update_outplace(inode, fio))
2981 		return false;
2982 
2983 	return f2fs_should_update_inplace(inode, fio);
2984 }
2985 
2986 int f2fs_do_write_data_page(struct f2fs_io_info *fio)
2987 {
2988 	struct folio *folio = fio->folio;
2989 	struct inode *inode = folio->mapping->host;
2990 	struct dnode_of_data dn;
2991 	struct node_info ni;
2992 	struct f2fs_lock_context lc;
2993 	bool ipu_force = false;
2994 	bool atomic_commit;
2995 	int err = 0;
2996 
2997 	/* Use COW inode to make dnode_of_data for atomic write */
2998 	atomic_commit = f2fs_is_atomic_file(inode) &&
2999 				folio_test_f2fs_atomic(folio);
3000 	if (atomic_commit)
3001 		set_new_dnode(&dn, F2FS_I(inode)->cow_inode, NULL, NULL, 0);
3002 	else
3003 		set_new_dnode(&dn, inode, NULL, NULL, 0);
3004 
3005 	if (need_inplace_update(fio) &&
3006 	    f2fs_lookup_read_extent_cache_block(inode, folio->index,
3007 						&fio->old_blkaddr)) {
3008 		if (!f2fs_is_valid_blkaddr(fio->sbi, fio->old_blkaddr,
3009 						DATA_GENERIC_ENHANCE))
3010 			return -EFSCORRUPTED;
3011 
3012 		ipu_force = true;
3013 		fio->need_lock = LOCK_DONE;
3014 		goto got_it;
3015 	}
3016 
3017 	if (is_sbi_flag_set(fio->sbi, SBI_ENABLE_CHECKPOINT) &&
3018 		time_to_inject(fio->sbi, FAULT_SKIP_WRITE))
3019 		return -EINVAL;
3020 
3021 	/* Deadlock due to between page->lock and f2fs_lock_op */
3022 	if (fio->need_lock == LOCK_REQ && !f2fs_trylock_op(fio->sbi, &lc))
3023 		return -EAGAIN;
3024 
3025 	err = f2fs_get_dnode_of_data(&dn, folio->index, LOOKUP_NODE);
3026 	if (err)
3027 		goto out;
3028 
3029 	fio->old_blkaddr = dn.data_blkaddr;
3030 
3031 	/* This page is already truncated */
3032 	if (fio->old_blkaddr == NULL_ADDR) {
3033 		folio_clear_uptodate(folio);
3034 		folio_clear_f2fs_gcing(folio);
3035 		goto out_writepage;
3036 	}
3037 got_it:
3038 	if (__is_valid_data_blkaddr(fio->old_blkaddr) &&
3039 		!f2fs_is_valid_blkaddr(fio->sbi, fio->old_blkaddr,
3040 						DATA_GENERIC_ENHANCE)) {
3041 		err = -EFSCORRUPTED;
3042 		goto out_writepage;
3043 	}
3044 
3045 	/* wait for GCed page writeback via META_MAPPING */
3046 	if (fio->meta_gc)
3047 		f2fs_wait_on_block_writeback(inode, fio->old_blkaddr);
3048 
3049 	/*
3050 	 * If current allocation needs SSR,
3051 	 * it had better in-place writes for updated data.
3052 	 */
3053 	if (ipu_force ||
3054 		(__is_valid_data_blkaddr(fio->old_blkaddr) &&
3055 					need_inplace_update(fio))) {
3056 		err = f2fs_encrypt_one_page(fio);
3057 		if (err)
3058 			goto out_writepage;
3059 
3060 		folio_start_writeback(folio);
3061 		f2fs_put_dnode(&dn);
3062 		if (fio->need_lock == LOCK_REQ)
3063 			f2fs_unlock_op(fio->sbi, &lc);
3064 		err = f2fs_inplace_write_data(fio);
3065 		if (err) {
3066 			if (fscrypt_inode_uses_fs_layer_crypto(inode))
3067 				fscrypt_finalize_bounce_page(&fio->encrypted_page);
3068 			folio_end_writeback(folio);
3069 		} else {
3070 			set_inode_flag(inode, FI_UPDATE_WRITE);
3071 		}
3072 		trace_f2fs_do_write_data_page(folio, IPU);
3073 		return err;
3074 	}
3075 
3076 	if (fio->need_lock == LOCK_RETRY) {
3077 		if (!f2fs_trylock_op(fio->sbi, &lc)) {
3078 			err = -EAGAIN;
3079 			goto out_writepage;
3080 		}
3081 		fio->need_lock = LOCK_REQ;
3082 	}
3083 
3084 	err = f2fs_get_node_info(fio->sbi, dn.nid, &ni, false);
3085 	if (err)
3086 		goto out_writepage;
3087 
3088 	fio->version = ni.version;
3089 
3090 	err = f2fs_encrypt_one_page(fio);
3091 	if (err)
3092 		goto out_writepage;
3093 
3094 	folio_start_writeback(folio);
3095 
3096 	if (fio->compr_blocks && fio->old_blkaddr == COMPRESS_ADDR)
3097 		f2fs_i_compr_blocks_update(inode, fio->compr_blocks - 1, false);
3098 
3099 	/* LFS mode write path */
3100 	f2fs_outplace_write_data(&dn, fio);
3101 	trace_f2fs_do_write_data_page(folio, OPU);
3102 	set_inode_flag(inode, FI_APPEND_WRITE);
3103 	if (atomic_commit)
3104 		folio_clear_f2fs_atomic(folio);
3105 out_writepage:
3106 	f2fs_put_dnode(&dn);
3107 out:
3108 	if (fio->need_lock == LOCK_REQ)
3109 		f2fs_unlock_op(fio->sbi, &lc);
3110 	return err;
3111 }
3112 
3113 int f2fs_write_single_data_page(struct folio *folio, int *submitted,
3114 				struct bio **bio,
3115 				sector_t *last_block,
3116 				struct writeback_control *wbc,
3117 				enum iostat_type io_type,
3118 				int compr_blocks,
3119 				bool allow_balance)
3120 {
3121 	struct inode *inode = folio->mapping->host;
3122 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3123 	loff_t i_size = i_size_read(inode);
3124 	const pgoff_t end_index = ((unsigned long long)i_size)
3125 							>> PAGE_SHIFT;
3126 	loff_t psize = (loff_t)(folio->index + 1) << PAGE_SHIFT;
3127 	unsigned offset = 0;
3128 	bool need_balance_fs = false;
3129 	bool quota_inode = IS_NOQUOTA(inode);
3130 	int err = 0;
3131 	struct f2fs_io_info fio = {
3132 		.sbi = sbi,
3133 		.ino = inode->i_ino,
3134 		.type = DATA,
3135 		.op = REQ_OP_WRITE,
3136 		.op_flags = wbc_to_write_flags(wbc),
3137 		.old_blkaddr = NULL_ADDR,
3138 		.folio = folio,
3139 		.encrypted_page = NULL,
3140 		.submitted = 0,
3141 		.compr_blocks = compr_blocks,
3142 		.need_lock = compr_blocks ? LOCK_DONE : LOCK_RETRY,
3143 		.meta_gc = f2fs_meta_inode_gc_required(inode) ? 1 : 0,
3144 		.io_type = io_type,
3145 		.io_wbc = wbc,
3146 		.bio = bio,
3147 		.last_block = last_block,
3148 	};
3149 
3150 	trace_f2fs_writepage(folio, DATA);
3151 
3152 	/* we should bypass data pages to proceed the kworker jobs */
3153 	if (unlikely(f2fs_cp_error(sbi))) {
3154 		mapping_set_error(folio->mapping, -EIO);
3155 		/*
3156 		 * don't drop any dirty dentry pages for keeping lastest
3157 		 * directory structure.
3158 		 */
3159 		if (S_ISDIR(inode->i_mode) &&
3160 				!is_sbi_flag_set(sbi, SBI_IS_CLOSE))
3161 			goto redirty_out;
3162 
3163 		/* keep data pages in remount-ro mode */
3164 		if (F2FS_OPTION(sbi).errors == MOUNT_ERRORS_READONLY)
3165 			goto redirty_out;
3166 		goto out;
3167 	}
3168 
3169 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
3170 		goto redirty_out;
3171 
3172 	if (folio->index < end_index ||
3173 			f2fs_verity_in_progress(inode) ||
3174 			compr_blocks)
3175 		goto write;
3176 
3177 	/*
3178 	 * If the offset is out-of-range of file size,
3179 	 * this page does not have to be written to disk.
3180 	 */
3181 	offset = i_size & (PAGE_SIZE - 1);
3182 	if ((folio->index >= end_index + 1) || !offset)
3183 		goto out;
3184 
3185 	folio_zero_segment(folio, offset, folio_size(folio));
3186 write:
3187 	/* Dentry/quota blocks are controlled by checkpoint */
3188 	if (S_ISDIR(inode->i_mode) || quota_inode) {
3189 		struct f2fs_lock_context lc;
3190 
3191 		/*
3192 		 * We need to wait for node_write to avoid block allocation during
3193 		 * checkpoint. This can only happen to quota writes which can cause
3194 		 * the below discard race condition.
3195 		 */
3196 		if (quota_inode)
3197 			f2fs_down_read_trace(&sbi->node_write, &lc);
3198 
3199 		fio.need_lock = LOCK_DONE;
3200 		err = f2fs_do_write_data_page(&fio);
3201 
3202 		if (quota_inode)
3203 			f2fs_up_read_trace(&sbi->node_write, &lc);
3204 
3205 		goto done;
3206 	}
3207 
3208 	need_balance_fs = true;
3209 	err = -EAGAIN;
3210 	if (f2fs_has_inline_data(inode)) {
3211 		err = f2fs_write_inline_data(inode, folio);
3212 		if (!err)
3213 			goto out;
3214 	}
3215 
3216 	if (err == -EAGAIN) {
3217 		err = f2fs_do_write_data_page(&fio);
3218 		if (err == -EAGAIN) {
3219 			f2fs_bug_on(sbi, compr_blocks);
3220 			fio.need_lock = LOCK_REQ;
3221 			err = f2fs_do_write_data_page(&fio);
3222 		}
3223 	}
3224 
3225 	if (err) {
3226 		file_set_keep_isize(inode);
3227 	} else {
3228 		spin_lock(&F2FS_I(inode)->i_size_lock);
3229 		if (F2FS_I(inode)->last_disk_size < psize)
3230 			F2FS_I(inode)->last_disk_size = psize;
3231 		spin_unlock(&F2FS_I(inode)->i_size_lock);
3232 	}
3233 
3234 done:
3235 	if (err && err != -ENOENT)
3236 		goto redirty_out;
3237 
3238 out:
3239 	inode_dec_dirty_pages(inode);
3240 	if (err) {
3241 		folio_clear_uptodate(folio);
3242 		folio_clear_f2fs_gcing(folio);
3243 	}
3244 	folio_unlock(folio);
3245 	if (!S_ISDIR(inode->i_mode) && !IS_NOQUOTA(inode) &&
3246 			!F2FS_I(inode)->wb_task && allow_balance)
3247 		f2fs_balance_fs(sbi, need_balance_fs);
3248 
3249 	if (unlikely(f2fs_cp_error(sbi))) {
3250 		f2fs_submit_merged_write(sbi, DATA);
3251 		if (bio && *bio)
3252 			f2fs_submit_merged_ipu_write(sbi, bio, NULL);
3253 		submitted = NULL;
3254 	}
3255 
3256 	if (submitted)
3257 		*submitted = fio.submitted;
3258 
3259 	return 0;
3260 
3261 redirty_out:
3262 	folio_redirty_for_writepage(wbc, folio);
3263 	/*
3264 	 * pageout() in MM translates EAGAIN, so calls handle_write_error()
3265 	 * -> mapping_set_error() -> set_bit(AS_EIO, ...).
3266 	 * file_write_and_wait_range() will see EIO error, which is critical
3267 	 * to return value of fsync() followed by atomic_write failure to user.
3268 	 */
3269 	folio_unlock(folio);
3270 	if (!err)
3271 		return 1;
3272 	return err;
3273 }
3274 
3275 /*
3276  * This function was copied from write_cache_pages from mm/page-writeback.c.
3277  * The major change is making write step of cold data page separately from
3278  * warm/hot data page.
3279  */
3280 static int f2fs_write_cache_pages(struct address_space *mapping,
3281 					struct writeback_control *wbc,
3282 					enum iostat_type io_type)
3283 {
3284 	int ret = 0;
3285 	int done = 0, retry = 0;
3286 	struct page *pages_local[F2FS_ONSTACK_PAGES];
3287 	struct page **pages = pages_local;
3288 	struct folio_batch fbatch;
3289 	struct f2fs_sb_info *sbi = F2FS_M_SB(mapping);
3290 	struct bio *bio = NULL;
3291 	sector_t last_block;
3292 #ifdef CONFIG_F2FS_FS_COMPRESSION
3293 	struct inode *inode = mapping->host;
3294 	struct compress_ctx cc = {
3295 		.inode = inode,
3296 		.log_cluster_size = F2FS_I(inode)->i_log_cluster_size,
3297 		.cluster_size = F2FS_I(inode)->i_cluster_size,
3298 		.cluster_idx = NULL_CLUSTER,
3299 		.rpages = NULL,
3300 		.nr_rpages = 0,
3301 		.cpages = NULL,
3302 		.valid_nr_cpages = 0,
3303 		.rbuf = NULL,
3304 		.cbuf = NULL,
3305 		.rlen = PAGE_SIZE * F2FS_I(inode)->i_cluster_size,
3306 		.private = NULL,
3307 	};
3308 #endif
3309 	int nr_folios, p, idx;
3310 	int nr_pages;
3311 	unsigned int max_pages = F2FS_ONSTACK_PAGES;
3312 	pgoff_t index;
3313 	pgoff_t end;		/* Inclusive */
3314 	pgoff_t done_index;
3315 	int range_whole = 0;
3316 	xa_mark_t tag;
3317 	int nwritten = 0;
3318 	int submitted = 0;
3319 	int i;
3320 
3321 #ifdef CONFIG_F2FS_FS_COMPRESSION
3322 	if (f2fs_compressed_file(inode) &&
3323 		1 << cc.log_cluster_size > F2FS_ONSTACK_PAGES) {
3324 		pages = f2fs_kzalloc(sbi, sizeof(struct page *) <<
3325 				cc.log_cluster_size, GFP_NOFS | __GFP_NOFAIL);
3326 		max_pages = 1 << cc.log_cluster_size;
3327 	}
3328 #endif
3329 
3330 	folio_batch_init(&fbatch);
3331 
3332 	if (get_dirty_pages(mapping->host) <=
3333 				SM_I(F2FS_M_SB(mapping))->min_hot_blocks)
3334 		set_inode_flag(mapping->host, FI_HOT_DATA);
3335 	else
3336 		clear_inode_flag(mapping->host, FI_HOT_DATA);
3337 
3338 	if (wbc->range_cyclic) {
3339 		index = mapping->writeback_index; /* prev offset */
3340 		end = -1;
3341 	} else {
3342 		index = wbc->range_start >> PAGE_SHIFT;
3343 		end = wbc->range_end >> PAGE_SHIFT;
3344 		if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
3345 			range_whole = 1;
3346 	}
3347 	tag = wbc_to_tag(wbc);
3348 retry:
3349 	retry = 0;
3350 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3351 		tag_pages_for_writeback(mapping, index, end);
3352 	done_index = index;
3353 	while (!done && !retry && (index <= end)) {
3354 		nr_pages = 0;
3355 again:
3356 		nr_folios = filemap_get_folios_tag(mapping, &index, end,
3357 				tag, &fbatch);
3358 		if (nr_folios == 0) {
3359 			if (nr_pages)
3360 				goto write;
3361 			break;
3362 		}
3363 
3364 		for (i = 0; i < nr_folios; i++) {
3365 			struct folio *folio = fbatch.folios[i];
3366 
3367 			idx = 0;
3368 			p = folio_nr_pages(folio);
3369 add_more:
3370 			pages[nr_pages] = folio_page(folio, idx);
3371 			folio_get(folio);
3372 			if (++nr_pages == max_pages) {
3373 				index = folio->index + idx + 1;
3374 				folio_batch_release(&fbatch);
3375 				goto write;
3376 			}
3377 			if (++idx < p)
3378 				goto add_more;
3379 		}
3380 		folio_batch_release(&fbatch);
3381 		goto again;
3382 write:
3383 		for (i = 0; i < nr_pages; i++) {
3384 			struct page *page = pages[i];
3385 			struct folio *folio = page_folio(page);
3386 			bool need_readd;
3387 readd:
3388 			need_readd = false;
3389 #ifdef CONFIG_F2FS_FS_COMPRESSION
3390 			if (f2fs_compressed_file(inode)) {
3391 				void *fsdata = NULL;
3392 				struct page *pagep;
3393 				int ret2;
3394 
3395 				ret = f2fs_init_compress_ctx(&cc);
3396 				if (ret) {
3397 					done = 1;
3398 					break;
3399 				}
3400 
3401 				if (!f2fs_cluster_can_merge_page(&cc,
3402 								folio->index)) {
3403 					ret = f2fs_write_multi_pages(&cc,
3404 						&submitted, wbc, io_type);
3405 					if (!ret)
3406 						need_readd = true;
3407 					goto result;
3408 				}
3409 
3410 				if (unlikely(f2fs_cp_error(sbi)))
3411 					goto lock_folio;
3412 
3413 				if (!f2fs_cluster_is_empty(&cc))
3414 					goto lock_folio;
3415 
3416 				if (f2fs_all_cluster_page_ready(&cc,
3417 					pages, i, nr_pages, true))
3418 					goto lock_folio;
3419 
3420 				ret2 = f2fs_prepare_compress_overwrite(
3421 							inode, &pagep,
3422 							folio->index, &fsdata);
3423 				if (ret2 < 0) {
3424 					ret = ret2;
3425 					done = 1;
3426 					break;
3427 				} else if (ret2 &&
3428 					(!f2fs_compress_write_end(inode,
3429 						fsdata, folio->index, 1) ||
3430 					 !f2fs_all_cluster_page_ready(&cc,
3431 						pages, i, nr_pages,
3432 						false))) {
3433 					retry = 1;
3434 					break;
3435 				}
3436 			}
3437 #endif
3438 			/* give a priority to WB_SYNC threads */
3439 			if (atomic_read(&sbi->wb_sync_req[DATA]) &&
3440 					wbc->sync_mode == WB_SYNC_NONE) {
3441 				done = 1;
3442 				break;
3443 			}
3444 #ifdef CONFIG_F2FS_FS_COMPRESSION
3445 lock_folio:
3446 #endif
3447 			done_index = folio->index;
3448 retry_write:
3449 			folio_lock(folio);
3450 
3451 			if (unlikely(folio->mapping != mapping)) {
3452 continue_unlock:
3453 				folio_unlock(folio);
3454 				continue;
3455 			}
3456 
3457 			if (!folio_test_dirty(folio)) {
3458 				/* someone wrote it for us */
3459 				goto continue_unlock;
3460 			}
3461 
3462 			if (folio_test_writeback(folio)) {
3463 				if (wbc->sync_mode == WB_SYNC_NONE)
3464 					goto continue_unlock;
3465 				f2fs_folio_wait_writeback(folio, DATA, true, true);
3466 			}
3467 
3468 			if (!folio_clear_dirty_for_io(folio))
3469 				goto continue_unlock;
3470 
3471 #ifdef CONFIG_F2FS_FS_COMPRESSION
3472 			if (f2fs_compressed_file(inode)) {
3473 				folio_get(folio);
3474 				f2fs_compress_ctx_add_page(&cc, folio);
3475 				continue;
3476 			}
3477 #endif
3478 			submitted = 0;
3479 			ret = f2fs_write_single_data_page(folio,
3480 					&submitted, &bio, &last_block,
3481 					wbc, io_type, 0, true);
3482 #ifdef CONFIG_F2FS_FS_COMPRESSION
3483 result:
3484 #endif
3485 			nwritten += submitted;
3486 			wbc->nr_to_write -= submitted;
3487 
3488 			if (unlikely(ret)) {
3489 				/*
3490 				 * keep nr_to_write, since vfs uses this to
3491 				 * get # of written pages.
3492 				 */
3493 				if (ret == 1) {
3494 					ret = 0;
3495 					goto next;
3496 				} else if (ret == -EAGAIN) {
3497 					ret = 0;
3498 					if (wbc->sync_mode == WB_SYNC_ALL) {
3499 						f2fs_schedule_timeout(
3500 							DEFAULT_SCHEDULE_TIMEOUT);
3501 						goto retry_write;
3502 					}
3503 					goto next;
3504 				}
3505 				done_index = folio_next_index(folio);
3506 				done = 1;
3507 				break;
3508 			}
3509 
3510 			if (wbc->nr_to_write <= 0 &&
3511 					wbc->sync_mode == WB_SYNC_NONE) {
3512 				done = 1;
3513 				break;
3514 			}
3515 next:
3516 			if (need_readd)
3517 				goto readd;
3518 		}
3519 		release_pages(pages, nr_pages);
3520 		cond_resched();
3521 	}
3522 #ifdef CONFIG_F2FS_FS_COMPRESSION
3523 	/* flush remained pages in compress cluster */
3524 	if (f2fs_compressed_file(inode) && !f2fs_cluster_is_empty(&cc)) {
3525 		ret = f2fs_write_multi_pages(&cc, &submitted, wbc, io_type);
3526 		nwritten += submitted;
3527 		wbc->nr_to_write -= submitted;
3528 		if (ret) {
3529 			done = 1;
3530 			retry = 0;
3531 		}
3532 	}
3533 	if (f2fs_compressed_file(inode))
3534 		f2fs_destroy_compress_ctx(&cc, false);
3535 #endif
3536 	if (retry) {
3537 		index = 0;
3538 		end = -1;
3539 		goto retry;
3540 	}
3541 	if (wbc->range_cyclic && !done)
3542 		done_index = 0;
3543 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3544 		mapping->writeback_index = done_index;
3545 
3546 	if (nwritten)
3547 		f2fs_submit_merged_write_cond(F2FS_M_SB(mapping), mapping->host,
3548 								NULL, 0, DATA);
3549 	/* submit cached bio of IPU write */
3550 	if (bio)
3551 		f2fs_submit_merged_ipu_write(sbi, &bio, NULL);
3552 
3553 #ifdef CONFIG_F2FS_FS_COMPRESSION
3554 	if (pages != pages_local)
3555 		kfree(pages);
3556 #endif
3557 
3558 	return ret;
3559 }
3560 
3561 static inline bool __should_serialize_io(struct inode *inode,
3562 					struct writeback_control *wbc)
3563 {
3564 	/* to avoid deadlock in path of data flush */
3565 	if (F2FS_I(inode)->wb_task)
3566 		return false;
3567 
3568 	if (!S_ISREG(inode->i_mode))
3569 		return false;
3570 	if (IS_NOQUOTA(inode))
3571 		return false;
3572 
3573 	if (f2fs_is_pinned_file(inode))
3574 		return false;
3575 	if (f2fs_need_compress_data(inode))
3576 		return true;
3577 	if (wbc->sync_mode != WB_SYNC_ALL)
3578 		return true;
3579 	if (get_dirty_pages(inode) >= SM_I(F2FS_I_SB(inode))->min_seq_blocks)
3580 		return true;
3581 	return false;
3582 }
3583 
3584 static inline void account_writeback(struct inode *inode, bool inc)
3585 {
3586 	if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
3587 		return;
3588 
3589 	f2fs_down_read(&F2FS_I(inode)->i_sem);
3590 	if (inc)
3591 		atomic_inc(&F2FS_I(inode)->writeback);
3592 	else
3593 		atomic_dec(&F2FS_I(inode)->writeback);
3594 	f2fs_up_read(&F2FS_I(inode)->i_sem);
3595 }
3596 
3597 static inline void update_skipped_write(struct f2fs_sb_info *sbi,
3598 						struct writeback_control *wbc)
3599 {
3600 	long skipped = wbc->pages_skipped;
3601 
3602 	if (is_sbi_flag_set(sbi, SBI_ENABLE_CHECKPOINT) && skipped &&
3603 		wbc->sync_mode == WB_SYNC_ALL)
3604 		atomic_add(skipped, &sbi->nr_pages[F2FS_SKIPPED_WRITE]);
3605 }
3606 
3607 static int __f2fs_write_data_pages(struct address_space *mapping,
3608 						struct writeback_control *wbc,
3609 						enum iostat_type io_type)
3610 {
3611 	struct inode *inode = mapping->host;
3612 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3613 	struct blk_plug plug;
3614 	int ret;
3615 	bool locked = false;
3616 
3617 	/* skip writing if there is no dirty page in this inode */
3618 	if (!get_dirty_pages(inode) && wbc->sync_mode == WB_SYNC_NONE)
3619 		return 0;
3620 
3621 	/* during POR, we don't need to trigger writepage at all. */
3622 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
3623 		goto skip_write;
3624 
3625 	if ((S_ISDIR(inode->i_mode) || IS_NOQUOTA(inode)) &&
3626 			wbc->sync_mode == WB_SYNC_NONE &&
3627 			get_dirty_pages(inode) < nr_pages_to_skip(sbi, DATA) &&
3628 			f2fs_available_free_memory(sbi, DIRTY_DENTS))
3629 		goto skip_write;
3630 
3631 	/* skip writing in file defragment preparing stage */
3632 	if (is_inode_flag_set(inode, FI_SKIP_WRITES))
3633 		goto skip_write;
3634 
3635 	trace_f2fs_writepages(mapping->host, wbc, DATA);
3636 
3637 	/* to avoid spliting IOs due to mixed WB_SYNC_ALL and WB_SYNC_NONE */
3638 	if (wbc->sync_mode == WB_SYNC_ALL)
3639 		atomic_inc(&sbi->wb_sync_req[DATA]);
3640 	else if (atomic_read(&sbi->wb_sync_req[DATA])) {
3641 		/* to avoid potential deadlock */
3642 		if (current->plug)
3643 			blk_finish_plug(current->plug);
3644 		goto skip_write;
3645 	}
3646 
3647 	if (__should_serialize_io(inode, wbc)) {
3648 		mutex_lock(&sbi->writepages);
3649 		locked = true;
3650 	}
3651 
3652 	account_writeback(inode, true);
3653 
3654 	blk_start_plug(&plug);
3655 	ret = f2fs_write_cache_pages(mapping, wbc, io_type);
3656 	blk_finish_plug(&plug);
3657 
3658 	account_writeback(inode, false);
3659 
3660 	if (locked)
3661 		mutex_unlock(&sbi->writepages);
3662 
3663 	if (wbc->sync_mode == WB_SYNC_ALL)
3664 		atomic_dec(&sbi->wb_sync_req[DATA]);
3665 	/*
3666 	 * if some pages were truncated, we cannot guarantee its mapping->host
3667 	 * to detect pending bios.
3668 	 */
3669 
3670 	f2fs_remove_dirty_inode(inode);
3671 
3672 	/*
3673 	 * f2fs_write_cache_pages() has retry logic for EAGAIN case which is
3674 	 * common when racing w/ checkpoint, so only update skipped write
3675 	 * when ret is non-zero.
3676 	 */
3677 	if (ret)
3678 		update_skipped_write(sbi, wbc);
3679 	return ret;
3680 
3681 skip_write:
3682 	wbc->pages_skipped += get_dirty_pages(inode);
3683 	update_skipped_write(sbi, wbc);
3684 	trace_f2fs_writepages(mapping->host, wbc, DATA);
3685 	return 0;
3686 }
3687 
3688 static int f2fs_write_data_pages(struct address_space *mapping,
3689 			    struct writeback_control *wbc)
3690 {
3691 	struct inode *inode = mapping->host;
3692 
3693 	return __f2fs_write_data_pages(mapping, wbc,
3694 			F2FS_I(inode)->cp_task == current ?
3695 			FS_CP_DATA_IO : FS_DATA_IO);
3696 }
3697 
3698 void f2fs_write_failed(struct inode *inode, loff_t to)
3699 {
3700 	loff_t i_size = i_size_read(inode);
3701 
3702 	if (IS_NOQUOTA(inode))
3703 		return;
3704 
3705 	/* In the fs-verity case, f2fs_end_enable_verity() does the truncate */
3706 	if (to > i_size && !f2fs_verity_in_progress(inode)) {
3707 		f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3708 		filemap_invalidate_lock(inode->i_mapping);
3709 
3710 		truncate_pagecache(inode, i_size);
3711 		f2fs_truncate_blocks(inode, i_size, true);
3712 
3713 		filemap_invalidate_unlock(inode->i_mapping);
3714 		f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3715 	}
3716 }
3717 
3718 static int prepare_write_begin(struct f2fs_sb_info *sbi,
3719 			struct folio *folio, loff_t pos, unsigned int len,
3720 			block_t *blk_addr, bool *node_changed)
3721 {
3722 	struct inode *inode = folio->mapping->host;
3723 	pgoff_t index = folio->index;
3724 	struct dnode_of_data dn;
3725 	struct f2fs_lock_context lc;
3726 	struct folio *ifolio;
3727 	bool locked = false;
3728 	int flag = F2FS_GET_BLOCK_PRE_AIO;
3729 	int err = 0;
3730 
3731 	if (!f2fs_has_inline_data(inode) && !f2fs_compressed_file(inode) &&
3732 	    (pos & PAGE_MASK) < i_size_read(inode) &&
3733 	    f2fs_lookup_read_extent_cache_block(inode, index, blk_addr))
3734 		return 0;
3735 
3736 	/*
3737 	 * If a whole page is being written and we already preallocated all the
3738 	 * blocks, then there is no need to get a block address now.
3739 	 */
3740 	if (len == PAGE_SIZE && is_inode_flag_set(inode, FI_PREALLOCATED_ALL))
3741 		return 0;
3742 
3743 	/* f2fs_lock_op avoids race between write CP and convert_inline_page */
3744 	if (f2fs_has_inline_data(inode)) {
3745 		if (pos + len > MAX_INLINE_DATA(inode))
3746 			flag = F2FS_GET_BLOCK_DEFAULT;
3747 		f2fs_map_lock(sbi, &lc, flag);
3748 		locked = true;
3749 	} else if ((pos & PAGE_MASK) >= i_size_read(inode)) {
3750 		f2fs_map_lock(sbi, &lc, flag);
3751 		locked = true;
3752 	}
3753 
3754 restart:
3755 	/* check inline_data */
3756 	ifolio = f2fs_get_inode_folio(sbi, inode->i_ino);
3757 	if (IS_ERR(ifolio)) {
3758 		err = PTR_ERR(ifolio);
3759 		goto unlock_out;
3760 	}
3761 
3762 	set_new_dnode(&dn, inode, ifolio, ifolio, 0);
3763 
3764 	if (f2fs_has_inline_data(inode)) {
3765 		if (pos + len <= MAX_INLINE_DATA(inode)) {
3766 			f2fs_do_read_inline_data(folio, ifolio);
3767 			set_inode_flag(inode, FI_DATA_EXIST);
3768 			if (inode->i_nlink)
3769 				folio_set_f2fs_inline(ifolio);
3770 			goto out;
3771 		}
3772 		err = f2fs_convert_inline_folio(&dn, folio);
3773 		if (err || dn.data_blkaddr != NULL_ADDR)
3774 			goto out;
3775 	}
3776 
3777 	if (!f2fs_lookup_read_extent_cache_block(inode, index,
3778 						 &dn.data_blkaddr)) {
3779 		if (IS_DEVICE_ALIASING(inode)) {
3780 			err = -ENODATA;
3781 			goto out;
3782 		}
3783 
3784 		if (locked) {
3785 			err = f2fs_reserve_block(&dn, index);
3786 			goto out;
3787 		}
3788 
3789 		/* hole case */
3790 		err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
3791 		if (!err && dn.data_blkaddr != NULL_ADDR)
3792 			goto out;
3793 		f2fs_put_dnode(&dn);
3794 		f2fs_map_lock(sbi, &lc, F2FS_GET_BLOCK_PRE_AIO);
3795 		WARN_ON(flag != F2FS_GET_BLOCK_PRE_AIO);
3796 		locked = true;
3797 		goto restart;
3798 	}
3799 out:
3800 	if (!err) {
3801 		/* convert_inline_page can make node_changed */
3802 		*blk_addr = dn.data_blkaddr;
3803 		*node_changed = dn.node_changed;
3804 	}
3805 	f2fs_put_dnode(&dn);
3806 unlock_out:
3807 	if (locked)
3808 		f2fs_map_unlock(sbi, &lc, flag);
3809 	return err;
3810 }
3811 
3812 static int __find_data_block(struct inode *inode, pgoff_t index,
3813 				block_t *blk_addr)
3814 {
3815 	struct dnode_of_data dn;
3816 	struct folio *ifolio;
3817 	int err = 0;
3818 
3819 	ifolio = f2fs_get_inode_folio(F2FS_I_SB(inode), inode->i_ino);
3820 	if (IS_ERR(ifolio))
3821 		return PTR_ERR(ifolio);
3822 
3823 	set_new_dnode(&dn, inode, ifolio, ifolio, 0);
3824 
3825 	if (!f2fs_lookup_read_extent_cache_block(inode, index,
3826 						 &dn.data_blkaddr)) {
3827 		/* hole case */
3828 		err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
3829 		if (err) {
3830 			dn.data_blkaddr = NULL_ADDR;
3831 			err = 0;
3832 		}
3833 	}
3834 	*blk_addr = dn.data_blkaddr;
3835 	f2fs_put_dnode(&dn);
3836 	return err;
3837 }
3838 
3839 static int __reserve_data_block(struct inode *inode, pgoff_t index,
3840 				block_t *blk_addr, bool *node_changed)
3841 {
3842 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3843 	struct dnode_of_data dn;
3844 	struct f2fs_lock_context lc;
3845 	struct folio *ifolio;
3846 	int err = 0;
3847 
3848 	f2fs_map_lock(sbi, &lc, F2FS_GET_BLOCK_PRE_AIO);
3849 
3850 	ifolio = f2fs_get_inode_folio(sbi, inode->i_ino);
3851 	if (IS_ERR(ifolio)) {
3852 		err = PTR_ERR(ifolio);
3853 		goto unlock_out;
3854 	}
3855 	set_new_dnode(&dn, inode, ifolio, ifolio, 0);
3856 
3857 	if (!f2fs_lookup_read_extent_cache_block(dn.inode, index,
3858 						&dn.data_blkaddr))
3859 		err = f2fs_reserve_block(&dn, index);
3860 
3861 	*blk_addr = dn.data_blkaddr;
3862 	*node_changed = dn.node_changed;
3863 	f2fs_put_dnode(&dn);
3864 
3865 unlock_out:
3866 	f2fs_map_unlock(sbi, &lc, F2FS_GET_BLOCK_PRE_AIO);
3867 	return err;
3868 }
3869 
3870 static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi,
3871 			struct folio *folio, loff_t pos, unsigned int len,
3872 			block_t *blk_addr, bool *node_changed)
3873 {
3874 	struct inode *inode = folio->mapping->host;
3875 	struct inode *cow_inode = F2FS_I(inode)->cow_inode;
3876 	pgoff_t index = folio->index;
3877 	int err = 0;
3878 	block_t ori_blk_addr = NULL_ADDR;
3879 	bool cow_has_reserved_block = false;
3880 
3881 	/* If pos is beyond the end of file, reserve a new block in COW inode */
3882 	if ((pos & PAGE_MASK) >= i_size_read(inode))
3883 		goto reserve_block;
3884 
3885 	/* Look for the block in COW inode first */
3886 	err = __find_data_block(cow_inode, index, blk_addr);
3887 	if (err)
3888 		return err;
3889 
3890 	if (__is_valid_data_blkaddr(*blk_addr))
3891 		return 0;
3892 
3893 	if (*blk_addr == NEW_ADDR)
3894 		cow_has_reserved_block = true;
3895 
3896 	if (is_inode_flag_set(inode, FI_ATOMIC_REPLACE))
3897 		goto reserve_block;
3898 
3899 	/* Look for the block in the original inode */
3900 	err = __find_data_block(inode, index, &ori_blk_addr);
3901 	if (err)
3902 		return err;
3903 
3904 reserve_block:
3905 	/* Finally, we should reserve a new block in COW inode for the update */
3906 	if (!cow_has_reserved_block) {
3907 		err = __reserve_data_block(cow_inode, index, blk_addr,
3908 					   node_changed);
3909 		if (err)
3910 			return err;
3911 		inc_atomic_write_cnt(inode);
3912 	}
3913 
3914 	if (ori_blk_addr != NULL_ADDR)
3915 		*blk_addr = ori_blk_addr;
3916 	return 0;
3917 }
3918 
3919 static int f2fs_write_begin(const struct kiocb *iocb,
3920 			    struct address_space *mapping,
3921 			    loff_t pos, unsigned len, struct folio **foliop,
3922 			    void **fsdata)
3923 {
3924 	struct inode *inode = mapping->host;
3925 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3926 	struct folio *folio;
3927 	pgoff_t index = pos >> PAGE_SHIFT;
3928 	bool need_balance = false;
3929 	block_t blkaddr = NULL_ADDR;
3930 	int err = 0;
3931 
3932 	trace_f2fs_write_begin(inode, pos, len);
3933 
3934 	if (!f2fs_is_checkpoint_ready(sbi)) {
3935 		err = -ENOSPC;
3936 		goto fail;
3937 	}
3938 
3939 	/*
3940 	 * We should check this at this moment to avoid deadlock on inode page
3941 	 * and #0 page. The locking rule for inline_data conversion should be:
3942 	 * folio_lock(folio #0) -> folio_lock(inode_page)
3943 	 */
3944 	if (index != 0) {
3945 		err = f2fs_convert_inline_inode(inode);
3946 		if (err)
3947 			goto fail;
3948 	}
3949 
3950 #ifdef CONFIG_F2FS_FS_COMPRESSION
3951 	if (f2fs_compressed_file(inode)) {
3952 		int ret;
3953 		struct page *page;
3954 
3955 		*fsdata = NULL;
3956 
3957 		if (len == PAGE_SIZE && !(f2fs_is_atomic_file(inode)))
3958 			goto repeat;
3959 
3960 		ret = f2fs_prepare_compress_overwrite(inode, &page,
3961 							index, fsdata);
3962 		if (ret < 0) {
3963 			err = ret;
3964 			goto fail;
3965 		} else if (ret) {
3966 			*foliop = page_folio(page);
3967 			return 0;
3968 		}
3969 	}
3970 #endif
3971 
3972 repeat:
3973 	/*
3974 	 * Do not use FGP_STABLE to avoid deadlock.
3975 	 * Will wait that below with our IO control.
3976 	 */
3977 	folio = f2fs_filemap_get_folio(mapping, index,
3978 				FGP_LOCK | FGP_WRITE | FGP_CREAT | FGP_NOFS,
3979 				mapping_gfp_mask(mapping));
3980 	if (IS_ERR(folio)) {
3981 		err = PTR_ERR(folio);
3982 		goto fail;
3983 	}
3984 
3985 	/* TODO: cluster can be compressed due to race with .writepage */
3986 
3987 	*foliop = folio;
3988 
3989 	if (f2fs_is_atomic_file(inode))
3990 		err = prepare_atomic_write_begin(sbi, folio, pos, len,
3991 					&blkaddr, &need_balance);
3992 	else
3993 		err = prepare_write_begin(sbi, folio, pos, len,
3994 					&blkaddr, &need_balance);
3995 	if (err)
3996 		goto put_folio;
3997 
3998 	if (need_balance && !IS_NOQUOTA(inode) &&
3999 			has_not_enough_free_secs(sbi, 0, 0)) {
4000 		folio_unlock(folio);
4001 		f2fs_balance_fs(sbi, true);
4002 		folio_lock(folio);
4003 		if (folio->mapping != mapping) {
4004 			/* The folio got truncated from under us */
4005 			folio_unlock(folio);
4006 			folio_put(folio);
4007 			goto repeat;
4008 		}
4009 	}
4010 
4011 	f2fs_folio_wait_writeback(folio, DATA, false, true);
4012 
4013 	if (len == folio_size(folio) || folio_test_uptodate(folio))
4014 		return 0;
4015 
4016 	if (!(pos & (PAGE_SIZE - 1)) && (pos + len) >= i_size_read(inode) &&
4017 	    !f2fs_verity_in_progress(inode)) {
4018 		folio_zero_segment(folio, len, folio_size(folio));
4019 		return 0;
4020 	}
4021 
4022 	if (blkaddr == NEW_ADDR) {
4023 		folio_zero_segment(folio, 0, folio_size(folio));
4024 		folio_mark_uptodate(folio);
4025 	} else {
4026 		if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
4027 				DATA_GENERIC_ENHANCE_READ)) {
4028 			err = -EFSCORRUPTED;
4029 			goto put_folio;
4030 		}
4031 		/*
4032 		 * Although the block may be stored in the COW inode, the folio
4033 		 * belongs to @inode and its data was encrypted (or not) using
4034 		 * @inode's context (see f2fs_encrypt_one_page()).  Read with
4035 		 * @inode so the post-read decryption decision matches the
4036 		 * folio's owner; otherwise an unencrypted @inode whose COW inode
4037 		 * is encrypted hits a NULL ->i_crypt_info on decryption.
4038 		 */
4039 		f2fs_submit_page_read(inode,
4040 				      NULL, /* can't write to fsverity files */
4041 				      folio, blkaddr, 0, true);
4042 
4043 		folio_lock(folio);
4044 		if (unlikely(folio->mapping != mapping)) {
4045 			folio_unlock(folio);
4046 			folio_put(folio);
4047 			goto repeat;
4048 		}
4049 		if (unlikely(!folio_test_uptodate(folio))) {
4050 			err = -EIO;
4051 			goto put_folio;
4052 		}
4053 	}
4054 	return 0;
4055 
4056 put_folio:
4057 	f2fs_folio_put(folio, true);
4058 fail:
4059 	f2fs_write_failed(inode, pos + len);
4060 	return err;
4061 }
4062 
4063 static int f2fs_write_end(const struct kiocb *iocb,
4064 			struct address_space *mapping,
4065 			loff_t pos, unsigned len, unsigned copied,
4066 			struct folio *folio, void *fsdata)
4067 {
4068 	struct inode *inode = folio->mapping->host;
4069 
4070 	trace_f2fs_write_end(inode, pos, len, copied);
4071 
4072 	/*
4073 	 * This should be come from len == PAGE_SIZE, and we expect copied
4074 	 * should be PAGE_SIZE. Otherwise, we treat it with zero copied and
4075 	 * let generic_perform_write() try to copy data again through copied=0.
4076 	 */
4077 	if (!folio_test_uptodate(folio)) {
4078 		if (unlikely(copied != len))
4079 			copied = 0;
4080 		else
4081 			folio_mark_uptodate(folio);
4082 	}
4083 
4084 #ifdef CONFIG_F2FS_FS_COMPRESSION
4085 	/* overwrite compressed file */
4086 	if (f2fs_compressed_file(inode) && fsdata) {
4087 		f2fs_compress_write_end(inode, fsdata, folio->index, copied);
4088 		f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
4089 
4090 		if (pos + copied > i_size_read(inode) &&
4091 				!f2fs_verity_in_progress(inode))
4092 			f2fs_i_size_write(inode, pos + copied);
4093 		return copied;
4094 	}
4095 #endif
4096 
4097 	if (!copied)
4098 		goto unlock_out;
4099 
4100 	folio_mark_dirty(folio);
4101 
4102 	if (f2fs_is_atomic_file(inode))
4103 		folio_set_f2fs_atomic(folio);
4104 
4105 	if (pos + copied > i_size_read(inode) &&
4106 	    !f2fs_verity_in_progress(inode)) {
4107 		f2fs_i_size_write(inode, pos + copied);
4108 		if (f2fs_is_atomic_file(inode))
4109 			f2fs_i_size_write(F2FS_I(inode)->cow_inode,
4110 					pos + copied);
4111 	}
4112 unlock_out:
4113 	f2fs_folio_put(folio, true);
4114 	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
4115 	return copied;
4116 }
4117 
4118 void f2fs_invalidate_folio(struct folio *folio, size_t offset, size_t length)
4119 {
4120 	struct inode *inode = folio->mapping->host;
4121 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4122 
4123 	if (inode->i_ino >= F2FS_ROOT_INO(sbi) &&
4124 				(offset || length != folio_size(folio)))
4125 		return;
4126 
4127 	if (folio_test_dirty(folio)) {
4128 		if (inode->i_ino == F2FS_META_INO(sbi)) {
4129 			dec_page_count(sbi, F2FS_DIRTY_META);
4130 		} else if (inode->i_ino == F2FS_NODE_INO(sbi)) {
4131 			dec_page_count(sbi, F2FS_DIRTY_NODES);
4132 		} else {
4133 			inode_dec_dirty_pages(inode);
4134 			f2fs_remove_dirty_inode(inode);
4135 		}
4136 	}
4137 
4138 	if (offset || length != folio_size(folio))
4139 		return;
4140 
4141 	folio_cancel_dirty(folio);
4142 	ffs_detach_free(folio);
4143 }
4144 
4145 bool f2fs_release_folio(struct folio *folio, gfp_t wait)
4146 {
4147 	/* If this is dirty folio, keep private data */
4148 	if (folio_test_dirty(folio))
4149 		return false;
4150 
4151 	ffs_detach_free(folio);
4152 	return true;
4153 }
4154 
4155 static bool f2fs_dirty_data_folio(struct address_space *mapping,
4156 		struct folio *folio)
4157 {
4158 	struct inode *inode = mapping->host;
4159 
4160 	trace_f2fs_set_page_dirty(folio, DATA);
4161 
4162 	if (!folio_test_uptodate(folio))
4163 		folio_mark_uptodate(folio);
4164 	BUG_ON(folio_test_swapcache(folio));
4165 
4166 	if (filemap_dirty_folio(mapping, folio)) {
4167 		f2fs_update_dirty_folio(inode, folio);
4168 		return true;
4169 	}
4170 	return false;
4171 }
4172 
4173 
4174 static sector_t f2fs_bmap_compress(struct inode *inode, sector_t block)
4175 {
4176 #ifdef CONFIG_F2FS_FS_COMPRESSION
4177 	struct dnode_of_data dn;
4178 	sector_t start_idx, blknr = 0;
4179 	int ret;
4180 
4181 	start_idx = round_down(block, F2FS_I(inode)->i_cluster_size);
4182 
4183 	set_new_dnode(&dn, inode, NULL, NULL, 0);
4184 	ret = f2fs_get_dnode_of_data(&dn, start_idx, LOOKUP_NODE);
4185 	if (ret)
4186 		return 0;
4187 
4188 	if (dn.data_blkaddr != COMPRESS_ADDR) {
4189 		dn.ofs_in_node += block - start_idx;
4190 		blknr = f2fs_data_blkaddr(&dn);
4191 		if (!__is_valid_data_blkaddr(blknr))
4192 			blknr = 0;
4193 	}
4194 
4195 	f2fs_put_dnode(&dn);
4196 	return blknr;
4197 #else
4198 	return 0;
4199 #endif
4200 }
4201 
4202 
4203 static sector_t f2fs_bmap(struct address_space *mapping, sector_t block)
4204 {
4205 	struct inode *inode = mapping->host;
4206 	sector_t blknr = 0;
4207 
4208 	if (f2fs_has_inline_data(inode))
4209 		goto out;
4210 
4211 	/* make sure allocating whole blocks */
4212 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
4213 		filemap_write_and_wait(mapping);
4214 
4215 	/* Block number less than F2FS MAX BLOCKS */
4216 	if (unlikely(block >= max_file_blocks(inode)))
4217 		goto out;
4218 
4219 	if (f2fs_compressed_file(inode)) {
4220 		blknr = f2fs_bmap_compress(inode, block);
4221 	} else {
4222 		struct f2fs_map_blocks map;
4223 
4224 		memset(&map, 0, sizeof(map));
4225 		map.m_lblk = block;
4226 		map.m_len = 1;
4227 		map.m_next_pgofs = NULL;
4228 		map.m_seg_type = NO_CHECK_TYPE;
4229 
4230 		if (!f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_BMAP))
4231 			blknr = map.m_pblk;
4232 	}
4233 out:
4234 	trace_f2fs_bmap(inode, block, blknr);
4235 	return blknr;
4236 }
4237 
4238 #ifdef CONFIG_SWAP
4239 static int f2fs_migrate_blocks(struct inode *inode, block_t start_blk,
4240 							unsigned int blkcnt)
4241 {
4242 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4243 	unsigned int blkofs;
4244 	unsigned int blk_per_sec = BLKS_PER_SEC(sbi);
4245 	unsigned int end_blk = start_blk + blkcnt - 1;
4246 	unsigned int secidx = start_blk / blk_per_sec;
4247 	unsigned int end_sec;
4248 	int ret = 0;
4249 
4250 	if (!blkcnt)
4251 		return 0;
4252 	end_sec = end_blk / blk_per_sec;
4253 
4254 	f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
4255 	filemap_invalidate_lock(inode->i_mapping);
4256 
4257 	set_inode_flag(inode, FI_ALIGNED_WRITE);
4258 	set_inode_flag(inode, FI_OPU_WRITE);
4259 
4260 	for (; secidx <= end_sec; secidx++) {
4261 		unsigned int blkofs_end = secidx == end_sec ?
4262 				end_blk % blk_per_sec : blk_per_sec - 1;
4263 
4264 		f2fs_down_write(&sbi->pin_sem);
4265 
4266 		ret = f2fs_allocate_pinning_section(sbi);
4267 		if (ret) {
4268 			f2fs_up_write(&sbi->pin_sem);
4269 			break;
4270 		}
4271 
4272 		set_inode_flag(inode, FI_SKIP_WRITES);
4273 
4274 		for (blkofs = 0; blkofs <= blkofs_end; blkofs++) {
4275 			struct folio *folio;
4276 			unsigned int blkidx = secidx * blk_per_sec + blkofs;
4277 
4278 			folio = f2fs_get_lock_data_folio(inode, blkidx, true);
4279 			if (IS_ERR(folio)) {
4280 				f2fs_up_write(&sbi->pin_sem);
4281 				ret = PTR_ERR(folio);
4282 				goto done;
4283 			}
4284 
4285 			folio_mark_dirty(folio);
4286 			f2fs_folio_put(folio, true);
4287 		}
4288 
4289 		clear_inode_flag(inode, FI_SKIP_WRITES);
4290 
4291 		ret = filemap_fdatawrite(inode->i_mapping);
4292 
4293 		f2fs_up_write(&sbi->pin_sem);
4294 
4295 		if (ret)
4296 			break;
4297 	}
4298 
4299 done:
4300 	clear_inode_flag(inode, FI_SKIP_WRITES);
4301 	clear_inode_flag(inode, FI_OPU_WRITE);
4302 	clear_inode_flag(inode, FI_ALIGNED_WRITE);
4303 
4304 	filemap_invalidate_unlock(inode->i_mapping);
4305 	f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
4306 
4307 	return ret;
4308 }
4309 
4310 static int check_swap_activate(struct swap_info_struct *sis,
4311 				struct file *swap_file, sector_t *span)
4312 {
4313 	struct address_space *mapping = swap_file->f_mapping;
4314 	struct inode *inode = mapping->host;
4315 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4316 	block_t cur_lblock;
4317 	block_t last_lblock;
4318 	block_t pblock;
4319 	block_t lowest_pblock = -1;
4320 	block_t highest_pblock = 0;
4321 	int nr_extents = 0;
4322 	unsigned int nr_pblocks;
4323 	unsigned int blks_per_sec = BLKS_PER_SEC(sbi);
4324 	unsigned int not_aligned = 0;
4325 	int ret = 0;
4326 
4327 	/*
4328 	 * Map all the blocks into the extent list.  This code doesn't try
4329 	 * to be very smart.
4330 	 */
4331 	cur_lblock = 0;
4332 	last_lblock = F2FS_BYTES_TO_BLK(i_size_read(inode));
4333 
4334 	while (cur_lblock < last_lblock && cur_lblock < sis->max) {
4335 		struct f2fs_map_blocks map;
4336 		bool last_extent = false;
4337 retry:
4338 		cond_resched();
4339 
4340 		memset(&map, 0, sizeof(map));
4341 		map.m_lblk = cur_lblock;
4342 		map.m_len = last_lblock - cur_lblock;
4343 		map.m_next_pgofs = NULL;
4344 		map.m_next_extent = NULL;
4345 		map.m_seg_type = NO_CHECK_TYPE;
4346 		map.m_may_create = false;
4347 
4348 		ret = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_FIEMAP);
4349 		if (ret)
4350 			goto out;
4351 
4352 		/* hole */
4353 		if (!(map.m_flags & F2FS_MAP_FLAGS)) {
4354 			f2fs_err(sbi, "Swapfile has holes");
4355 			ret = -EINVAL;
4356 			goto out;
4357 		}
4358 
4359 		pblock = map.m_pblk;
4360 		nr_pblocks = map.m_len;
4361 
4362 		if (!last_extent &&
4363 			((pblock - SM_I(sbi)->main_blkaddr) % blks_per_sec ||
4364 			nr_pblocks % blks_per_sec ||
4365 			f2fs_is_sequential_zone_area(sbi, pblock))) {
4366 			not_aligned++;
4367 
4368 			nr_pblocks = roundup(nr_pblocks, blks_per_sec);
4369 			if (cur_lblock + nr_pblocks > sis->max)
4370 				nr_pblocks -= blks_per_sec;
4371 
4372 			/* this extent is last one */
4373 			if (!nr_pblocks) {
4374 				nr_pblocks = last_lblock - cur_lblock;
4375 				last_extent = true;
4376 			}
4377 
4378 			ret = f2fs_migrate_blocks(inode, cur_lblock,
4379 							nr_pblocks);
4380 			if (ret) {
4381 				if (ret == -ENOENT)
4382 					ret = -EINVAL;
4383 				goto out;
4384 			}
4385 
4386 			/* lookup block mapping info after block migration */
4387 			goto retry;
4388 		}
4389 
4390 		if (cur_lblock + nr_pblocks >= sis->max)
4391 			nr_pblocks = sis->max - cur_lblock;
4392 
4393 		if (cur_lblock) {	/* exclude the header page */
4394 			if (pblock < lowest_pblock)
4395 				lowest_pblock = pblock;
4396 			if (pblock + nr_pblocks - 1 > highest_pblock)
4397 				highest_pblock = pblock + nr_pblocks - 1;
4398 		}
4399 
4400 		/*
4401 		 * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
4402 		 */
4403 		ret = add_swap_extent(sis, cur_lblock, nr_pblocks, pblock);
4404 		if (ret < 0)
4405 			goto out;
4406 		nr_extents += ret;
4407 		cur_lblock += nr_pblocks;
4408 	}
4409 	ret = nr_extents;
4410 	*span = 1 + highest_pblock - lowest_pblock;
4411 	if (cur_lblock == 0)
4412 		cur_lblock = 1;	/* force Empty message */
4413 	sis->max = cur_lblock;
4414 	sis->pages = cur_lblock - 1;
4415 out:
4416 	if (not_aligned)
4417 		f2fs_warn(sbi, "Swapfile (%u) is not align to section: 1) creat(), 2) ioctl(F2FS_IOC_SET_PIN_FILE), 3) fallocate(%lu * N)",
4418 			  not_aligned, blks_per_sec * F2FS_BLKSIZE);
4419 	return ret;
4420 }
4421 
4422 static int f2fs_swap_activate(struct swap_info_struct *sis, struct file *file,
4423 				sector_t *span)
4424 {
4425 	struct inode *inode = file_inode(file);
4426 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4427 	int ret;
4428 
4429 	if (!S_ISREG(inode->i_mode))
4430 		return -EINVAL;
4431 
4432 	if (f2fs_readonly(sbi->sb))
4433 		return -EROFS;
4434 
4435 	if (f2fs_lfs_mode(sbi) && !f2fs_sb_has_blkzoned(sbi)) {
4436 		f2fs_err(sbi, "Swapfile not supported in LFS mode");
4437 		return -EINVAL;
4438 	}
4439 
4440 	ret = f2fs_convert_inline_inode(inode);
4441 	if (ret)
4442 		return ret;
4443 
4444 	if (!f2fs_disable_compressed_file(inode))
4445 		return -EINVAL;
4446 
4447 	ret = filemap_fdatawrite(inode->i_mapping);
4448 	if (ret < 0)
4449 		return ret;
4450 
4451 	f2fs_precache_extents(inode);
4452 
4453 	ret = check_swap_activate(sis, file, span);
4454 	if (ret < 0)
4455 		return ret;
4456 
4457 	stat_inc_swapfile_inode(inode);
4458 	set_inode_flag(inode, FI_PIN_FILE);
4459 	f2fs_update_time(sbi, REQ_TIME);
4460 	return ret;
4461 }
4462 
4463 static void f2fs_swap_deactivate(struct file *file)
4464 {
4465 	struct inode *inode = file_inode(file);
4466 
4467 	stat_dec_swapfile_inode(inode);
4468 	clear_inode_flag(inode, FI_PIN_FILE);
4469 }
4470 #else
4471 static int f2fs_swap_activate(struct swap_info_struct *sis, struct file *file,
4472 				sector_t *span)
4473 {
4474 	return -EOPNOTSUPP;
4475 }
4476 
4477 static void f2fs_swap_deactivate(struct file *file)
4478 {
4479 }
4480 #endif
4481 
4482 const struct address_space_operations f2fs_dblock_aops = {
4483 	.read_folio	= f2fs_read_data_folio,
4484 	.readahead	= f2fs_readahead,
4485 	.writepages	= f2fs_write_data_pages,
4486 	.write_begin	= f2fs_write_begin,
4487 	.write_end	= f2fs_write_end,
4488 	.dirty_folio	= f2fs_dirty_data_folio,
4489 	.migrate_folio	= filemap_migrate_folio,
4490 	.invalidate_folio = f2fs_invalidate_folio,
4491 	.release_folio	= f2fs_release_folio,
4492 	.bmap		= f2fs_bmap,
4493 	.swap_activate  = f2fs_swap_activate,
4494 	.swap_deactivate = f2fs_swap_deactivate,
4495 };
4496 
4497 void f2fs_clear_page_cache_dirty_tag(struct folio *folio)
4498 {
4499 	struct address_space *mapping = folio->mapping;
4500 	unsigned long flags;
4501 
4502 	xa_lock_irqsave(&mapping->i_pages, flags);
4503 	__xa_clear_mark(&mapping->i_pages, folio->index,
4504 						PAGECACHE_TAG_DIRTY);
4505 	xa_unlock_irqrestore(&mapping->i_pages, flags);
4506 }
4507 
4508 int __init f2fs_init_post_read_processing(void)
4509 {
4510 	bio_post_read_ctx_cache =
4511 		kmem_cache_create("f2fs_bio_post_read_ctx",
4512 				  sizeof(struct bio_post_read_ctx), 0, 0, NULL);
4513 	if (!bio_post_read_ctx_cache)
4514 		goto fail;
4515 	bio_post_read_ctx_pool =
4516 		mempool_create_slab_pool(NUM_PREALLOC_POST_READ_CTXS,
4517 					 bio_post_read_ctx_cache);
4518 	if (!bio_post_read_ctx_pool)
4519 		goto fail_free_cache;
4520 	return 0;
4521 
4522 fail_free_cache:
4523 	kmem_cache_destroy(bio_post_read_ctx_cache);
4524 fail:
4525 	return -ENOMEM;
4526 }
4527 
4528 void f2fs_destroy_post_read_processing(void)
4529 {
4530 	mempool_destroy(bio_post_read_ctx_pool);
4531 	kmem_cache_destroy(bio_post_read_ctx_cache);
4532 }
4533 
4534 int f2fs_init_wq(struct f2fs_sb_info *sbi)
4535 {
4536 	sbi->wq = alloc_workqueue("f2fs_wq", WQ_UNBOUND | WQ_HIGHPRI,
4537 				  num_online_cpus());
4538 	return sbi->wq ? 0 : -ENOMEM;
4539 }
4540 
4541 void f2fs_destroy_wq(struct f2fs_sb_info *sbi)
4542 {
4543 	if (sbi->wq)
4544 		destroy_workqueue(sbi->wq);
4545 }
4546 
4547 int __init f2fs_init_bio_entry_cache(void)
4548 {
4549 	bio_entry_slab = f2fs_kmem_cache_create("f2fs_bio_entry_slab",
4550 			sizeof(struct bio_entry));
4551 
4552 	if (!bio_entry_slab)
4553 		return -ENOMEM;
4554 
4555 	ffs_entry_slab = f2fs_kmem_cache_create("f2fs_ffs_slab",
4556 			sizeof(struct f2fs_folio_state));
4557 
4558 	if (!ffs_entry_slab) {
4559 		kmem_cache_destroy(bio_entry_slab);
4560 		return -ENOMEM;
4561 	}
4562 
4563 	return 0;
4564 }
4565 
4566 void f2fs_destroy_bio_entry_cache(void)
4567 {
4568 	kmem_cache_destroy(bio_entry_slab);
4569 	kmem_cache_destroy(ffs_entry_slab);
4570 }
4571 
4572 static int f2fs_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
4573 			    unsigned int flags, struct iomap *iomap,
4574 			    struct iomap *srcmap)
4575 {
4576 	struct f2fs_map_blocks map = { NULL, };
4577 	pgoff_t next_pgofs = 0;
4578 	int err;
4579 
4580 	map.m_lblk = F2FS_BYTES_TO_BLK(offset);
4581 	map.m_len = F2FS_BYTES_TO_BLK(offset + length - 1) - map.m_lblk + 1;
4582 	map.m_next_pgofs = &next_pgofs;
4583 	map.m_seg_type = f2fs_rw_hint_to_seg_type(F2FS_I_SB(inode),
4584 						inode->i_write_hint);
4585 	if (flags & IOMAP_WRITE && iomap->private) {
4586 		map.m_last_pblk = (unsigned long)iomap->private;
4587 		iomap->private = NULL;
4588 	}
4589 
4590 	/*
4591 	 * If the blocks being overwritten are already allocated,
4592 	 * f2fs_map_lock and f2fs_balance_fs are not necessary.
4593 	 */
4594 	if ((flags & IOMAP_WRITE) &&
4595 		!__f2fs_overwrite_io(inode, offset, length, true))
4596 		map.m_may_create = true;
4597 
4598 	err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_DIO);
4599 	if (err)
4600 		return err;
4601 
4602 	iomap->offset = F2FS_BLK_TO_BYTES(map.m_lblk);
4603 
4604 	/*
4605 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
4606 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
4607 	 * limiting the length of the mapping returned.
4608 	 */
4609 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
4610 
4611 	/*
4612 	 * We should never see delalloc or compressed extents here based on
4613 	 * prior flushing and checks.
4614 	 */
4615 	if (WARN_ON_ONCE(map.m_pblk == COMPRESS_ADDR))
4616 		return -EINVAL;
4617 
4618 	if (map.m_flags & F2FS_MAP_MAPPED) {
4619 		if (WARN_ON_ONCE(map.m_pblk == NEW_ADDR))
4620 			return -EINVAL;
4621 
4622 		iomap->length = F2FS_BLK_TO_BYTES(map.m_len);
4623 		iomap->type = IOMAP_MAPPED;
4624 		iomap->flags |= IOMAP_F_MERGED;
4625 		iomap->bdev = map.m_bdev;
4626 		iomap->addr = F2FS_BLK_TO_BYTES(map.m_pblk);
4627 
4628 		if (flags & IOMAP_WRITE && map.m_last_pblk)
4629 			iomap->private = (void *)map.m_last_pblk;
4630 	} else {
4631 		if (flags & IOMAP_WRITE)
4632 			return -ENOTBLK;
4633 
4634 		if (map.m_pblk == NULL_ADDR) {
4635 			iomap->length = F2FS_BLK_TO_BYTES(next_pgofs) -
4636 							iomap->offset;
4637 			iomap->type = IOMAP_HOLE;
4638 		} else if (map.m_pblk == NEW_ADDR) {
4639 			iomap->length = F2FS_BLK_TO_BYTES(map.m_len);
4640 			iomap->type = IOMAP_UNWRITTEN;
4641 		} else {
4642 			f2fs_bug_on(F2FS_I_SB(inode), 1);
4643 		}
4644 		iomap->addr = IOMAP_NULL_ADDR;
4645 	}
4646 
4647 	if (map.m_flags & F2FS_MAP_NEW)
4648 		iomap->flags |= IOMAP_F_NEW;
4649 	if ((inode_state_read_once(inode) & I_DIRTY_DATASYNC) ||
4650 	    offset + length > i_size_read(inode))
4651 		iomap->flags |= IOMAP_F_DIRTY;
4652 
4653 	return 0;
4654 }
4655 
4656 const struct iomap_ops f2fs_iomap_ops = {
4657 	.iomap_begin	= f2fs_iomap_begin,
4658 };
4659