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