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