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