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