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