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