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