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