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