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