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