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