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