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