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