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