fanotify: disallow mount/sb marks on kernel internal pseudo fs
[sfrench/cifs-2.6.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                 goto out;
2811         }
2812
2813         if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
2814                 goto redirty_out;
2815
2816         if (page->index < end_index ||
2817                         f2fs_verity_in_progress(inode) ||
2818                         compr_blocks)
2819                 goto write;
2820
2821         /*
2822          * If the offset is out-of-range of file size,
2823          * this page does not have to be written to disk.
2824          */
2825         offset = i_size & (PAGE_SIZE - 1);
2826         if ((page->index >= end_index + 1) || !offset)
2827                 goto out;
2828
2829         zero_user_segment(page, offset, PAGE_SIZE);
2830 write:
2831         if (f2fs_is_drop_cache(inode))
2832                 goto out;
2833
2834         /* Dentry/quota blocks are controlled by checkpoint */
2835         if (S_ISDIR(inode->i_mode) || IS_NOQUOTA(inode)) {
2836                 /*
2837                  * We need to wait for node_write to avoid block allocation during
2838                  * checkpoint. This can only happen to quota writes which can cause
2839                  * the below discard race condition.
2840                  */
2841                 if (IS_NOQUOTA(inode))
2842                         f2fs_down_read(&sbi->node_write);
2843
2844                 fio.need_lock = LOCK_DONE;
2845                 err = f2fs_do_write_data_page(&fio);
2846
2847                 if (IS_NOQUOTA(inode))
2848                         f2fs_up_read(&sbi->node_write);
2849
2850                 goto done;
2851         }
2852
2853         if (!wbc->for_reclaim)
2854                 need_balance_fs = true;
2855         else if (has_not_enough_free_secs(sbi, 0, 0))
2856                 goto redirty_out;
2857         else
2858                 set_inode_flag(inode, FI_HOT_DATA);
2859
2860         err = -EAGAIN;
2861         if (f2fs_has_inline_data(inode)) {
2862                 err = f2fs_write_inline_data(inode, page);
2863                 if (!err)
2864                         goto out;
2865         }
2866
2867         if (err == -EAGAIN) {
2868                 err = f2fs_do_write_data_page(&fio);
2869                 if (err == -EAGAIN) {
2870                         fio.need_lock = LOCK_REQ;
2871                         err = f2fs_do_write_data_page(&fio);
2872                 }
2873         }
2874
2875         if (err) {
2876                 file_set_keep_isize(inode);
2877         } else {
2878                 spin_lock(&F2FS_I(inode)->i_size_lock);
2879                 if (F2FS_I(inode)->last_disk_size < psize)
2880                         F2FS_I(inode)->last_disk_size = psize;
2881                 spin_unlock(&F2FS_I(inode)->i_size_lock);
2882         }
2883
2884 done:
2885         if (err && err != -ENOENT)
2886                 goto redirty_out;
2887
2888 out:
2889         inode_dec_dirty_pages(inode);
2890         if (err) {
2891                 ClearPageUptodate(page);
2892                 clear_page_private_gcing(page);
2893         }
2894
2895         if (wbc->for_reclaim) {
2896                 f2fs_submit_merged_write_cond(sbi, NULL, page, 0, DATA);
2897                 clear_inode_flag(inode, FI_HOT_DATA);
2898                 f2fs_remove_dirty_inode(inode);
2899                 submitted = NULL;
2900         }
2901         unlock_page(page);
2902         if (!S_ISDIR(inode->i_mode) && !IS_NOQUOTA(inode) &&
2903                         !F2FS_I(inode)->wb_task && allow_balance)
2904                 f2fs_balance_fs(sbi, need_balance_fs);
2905
2906         if (unlikely(f2fs_cp_error(sbi))) {
2907                 f2fs_submit_merged_write(sbi, DATA);
2908                 if (bio && *bio)
2909                         f2fs_submit_merged_ipu_write(sbi, bio, NULL);
2910                 submitted = NULL;
2911         }
2912
2913         if (submitted)
2914                 *submitted = fio.submitted;
2915
2916         return 0;
2917
2918 redirty_out:
2919         redirty_page_for_writepage(wbc, page);
2920         /*
2921          * pageout() in MM translates EAGAIN, so calls handle_write_error()
2922          * -> mapping_set_error() -> set_bit(AS_EIO, ...).
2923          * file_write_and_wait_range() will see EIO error, which is critical
2924          * to return value of fsync() followed by atomic_write failure to user.
2925          */
2926         if (!err || wbc->for_reclaim)
2927                 return AOP_WRITEPAGE_ACTIVATE;
2928         unlock_page(page);
2929         return err;
2930 }
2931
2932 static int f2fs_write_data_page(struct page *page,
2933                                         struct writeback_control *wbc)
2934 {
2935 #ifdef CONFIG_F2FS_FS_COMPRESSION
2936         struct inode *inode = page->mapping->host;
2937
2938         if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
2939                 goto out;
2940
2941         if (f2fs_compressed_file(inode)) {
2942                 if (f2fs_is_compressed_cluster(inode, page->index)) {
2943                         redirty_page_for_writepage(wbc, page);
2944                         return AOP_WRITEPAGE_ACTIVATE;
2945                 }
2946         }
2947 out:
2948 #endif
2949
2950         return f2fs_write_single_data_page(page, NULL, NULL, NULL,
2951                                                 wbc, FS_DATA_IO, 0, true);
2952 }
2953
2954 /*
2955  * This function was copied from write_cache_pages from mm/page-writeback.c.
2956  * The major change is making write step of cold data page separately from
2957  * warm/hot data page.
2958  */
2959 static int f2fs_write_cache_pages(struct address_space *mapping,
2960                                         struct writeback_control *wbc,
2961                                         enum iostat_type io_type)
2962 {
2963         int ret = 0;
2964         int done = 0, retry = 0;
2965         struct page *pages[F2FS_ONSTACK_PAGES];
2966         struct folio_batch fbatch;
2967         struct f2fs_sb_info *sbi = F2FS_M_SB(mapping);
2968         struct bio *bio = NULL;
2969         sector_t last_block;
2970 #ifdef CONFIG_F2FS_FS_COMPRESSION
2971         struct inode *inode = mapping->host;
2972         struct compress_ctx cc = {
2973                 .inode = inode,
2974                 .log_cluster_size = F2FS_I(inode)->i_log_cluster_size,
2975                 .cluster_size = F2FS_I(inode)->i_cluster_size,
2976                 .cluster_idx = NULL_CLUSTER,
2977                 .rpages = NULL,
2978                 .nr_rpages = 0,
2979                 .cpages = NULL,
2980                 .valid_nr_cpages = 0,
2981                 .rbuf = NULL,
2982                 .cbuf = NULL,
2983                 .rlen = PAGE_SIZE * F2FS_I(inode)->i_cluster_size,
2984                 .private = NULL,
2985         };
2986 #endif
2987         int nr_folios, p, idx;
2988         int nr_pages;
2989         pgoff_t index;
2990         pgoff_t end;            /* Inclusive */
2991         pgoff_t done_index;
2992         int range_whole = 0;
2993         xa_mark_t tag;
2994         int nwritten = 0;
2995         int submitted = 0;
2996         int i;
2997
2998         folio_batch_init(&fbatch);
2999
3000         if (get_dirty_pages(mapping->host) <=
3001                                 SM_I(F2FS_M_SB(mapping))->min_hot_blocks)
3002                 set_inode_flag(mapping->host, FI_HOT_DATA);
3003         else
3004                 clear_inode_flag(mapping->host, FI_HOT_DATA);
3005
3006         if (wbc->range_cyclic) {
3007                 index = mapping->writeback_index; /* prev offset */
3008                 end = -1;
3009         } else {
3010                 index = wbc->range_start >> PAGE_SHIFT;
3011                 end = wbc->range_end >> PAGE_SHIFT;
3012                 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
3013                         range_whole = 1;
3014         }
3015         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3016                 tag = PAGECACHE_TAG_TOWRITE;
3017         else
3018                 tag = PAGECACHE_TAG_DIRTY;
3019 retry:
3020         retry = 0;
3021         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3022                 tag_pages_for_writeback(mapping, index, end);
3023         done_index = index;
3024         while (!done && !retry && (index <= end)) {
3025                 nr_pages = 0;
3026 again:
3027                 nr_folios = filemap_get_folios_tag(mapping, &index, end,
3028                                 tag, &fbatch);
3029                 if (nr_folios == 0) {
3030                         if (nr_pages)
3031                                 goto write;
3032                         break;
3033                 }
3034
3035                 for (i = 0; i < nr_folios; i++) {
3036                         struct folio *folio = fbatch.folios[i];
3037
3038                         idx = 0;
3039                         p = folio_nr_pages(folio);
3040 add_more:
3041                         pages[nr_pages] = folio_page(folio, idx);
3042                         folio_get(folio);
3043                         if (++nr_pages == F2FS_ONSTACK_PAGES) {
3044                                 index = folio->index + idx + 1;
3045                                 folio_batch_release(&fbatch);
3046                                 goto write;
3047                         }
3048                         if (++idx < p)
3049                                 goto add_more;
3050                 }
3051                 folio_batch_release(&fbatch);
3052                 goto again;
3053 write:
3054                 for (i = 0; i < nr_pages; i++) {
3055                         struct page *page = pages[i];
3056                         struct folio *folio = page_folio(page);
3057                         bool need_readd;
3058 readd:
3059                         need_readd = false;
3060 #ifdef CONFIG_F2FS_FS_COMPRESSION
3061                         if (f2fs_compressed_file(inode)) {
3062                                 void *fsdata = NULL;
3063                                 struct page *pagep;
3064                                 int ret2;
3065
3066                                 ret = f2fs_init_compress_ctx(&cc);
3067                                 if (ret) {
3068                                         done = 1;
3069                                         break;
3070                                 }
3071
3072                                 if (!f2fs_cluster_can_merge_page(&cc,
3073                                                                 folio->index)) {
3074                                         ret = f2fs_write_multi_pages(&cc,
3075                                                 &submitted, wbc, io_type);
3076                                         if (!ret)
3077                                                 need_readd = true;
3078                                         goto result;
3079                                 }
3080
3081                                 if (unlikely(f2fs_cp_error(sbi)))
3082                                         goto lock_folio;
3083
3084                                 if (!f2fs_cluster_is_empty(&cc))
3085                                         goto lock_folio;
3086
3087                                 if (f2fs_all_cluster_page_ready(&cc,
3088                                         pages, i, nr_pages, true))
3089                                         goto lock_folio;
3090
3091                                 ret2 = f2fs_prepare_compress_overwrite(
3092                                                         inode, &pagep,
3093                                                         folio->index, &fsdata);
3094                                 if (ret2 < 0) {
3095                                         ret = ret2;
3096                                         done = 1;
3097                                         break;
3098                                 } else if (ret2 &&
3099                                         (!f2fs_compress_write_end(inode,
3100                                                 fsdata, folio->index, 1) ||
3101                                          !f2fs_all_cluster_page_ready(&cc,
3102                                                 pages, i, nr_pages,
3103                                                 false))) {
3104                                         retry = 1;
3105                                         break;
3106                                 }
3107                         }
3108 #endif
3109                         /* give a priority to WB_SYNC threads */
3110                         if (atomic_read(&sbi->wb_sync_req[DATA]) &&
3111                                         wbc->sync_mode == WB_SYNC_NONE) {
3112                                 done = 1;
3113                                 break;
3114                         }
3115 #ifdef CONFIG_F2FS_FS_COMPRESSION
3116 lock_folio:
3117 #endif
3118                         done_index = folio->index;
3119 retry_write:
3120                         folio_lock(folio);
3121
3122                         if (unlikely(folio->mapping != mapping)) {
3123 continue_unlock:
3124                                 folio_unlock(folio);
3125                                 continue;
3126                         }
3127
3128                         if (!folio_test_dirty(folio)) {
3129                                 /* someone wrote it for us */
3130                                 goto continue_unlock;
3131                         }
3132
3133                         if (folio_test_writeback(folio)) {
3134                                 if (wbc->sync_mode == WB_SYNC_NONE)
3135                                         goto continue_unlock;
3136                                 f2fs_wait_on_page_writeback(&folio->page, DATA, true, true);
3137                         }
3138
3139                         if (!folio_clear_dirty_for_io(folio))
3140                                 goto continue_unlock;
3141
3142 #ifdef CONFIG_F2FS_FS_COMPRESSION
3143                         if (f2fs_compressed_file(inode)) {
3144                                 folio_get(folio);
3145                                 f2fs_compress_ctx_add_page(&cc, &folio->page);
3146                                 continue;
3147                         }
3148 #endif
3149                         ret = f2fs_write_single_data_page(&folio->page,
3150                                         &submitted, &bio, &last_block,
3151                                         wbc, io_type, 0, true);
3152                         if (ret == AOP_WRITEPAGE_ACTIVATE)
3153                                 folio_unlock(folio);
3154 #ifdef CONFIG_F2FS_FS_COMPRESSION
3155 result:
3156 #endif
3157                         nwritten += submitted;
3158                         wbc->nr_to_write -= submitted;
3159
3160                         if (unlikely(ret)) {
3161                                 /*
3162                                  * keep nr_to_write, since vfs uses this to
3163                                  * get # of written pages.
3164                                  */
3165                                 if (ret == AOP_WRITEPAGE_ACTIVATE) {
3166                                         ret = 0;
3167                                         goto next;
3168                                 } else if (ret == -EAGAIN) {
3169                                         ret = 0;
3170                                         if (wbc->sync_mode == WB_SYNC_ALL) {
3171                                                 f2fs_io_schedule_timeout(
3172                                                         DEFAULT_IO_TIMEOUT);
3173                                                 goto retry_write;
3174                                         }
3175                                         goto next;
3176                                 }
3177                                 done_index = folio->index +
3178                                         folio_nr_pages(folio);
3179                                 done = 1;
3180                                 break;
3181                         }
3182
3183                         if (wbc->nr_to_write <= 0 &&
3184                                         wbc->sync_mode == WB_SYNC_NONE) {
3185                                 done = 1;
3186                                 break;
3187                         }
3188 next:
3189                         if (need_readd)
3190                                 goto readd;
3191                 }
3192                 release_pages(pages, nr_pages);
3193                 cond_resched();
3194         }
3195 #ifdef CONFIG_F2FS_FS_COMPRESSION
3196         /* flush remained pages in compress cluster */
3197         if (f2fs_compressed_file(inode) && !f2fs_cluster_is_empty(&cc)) {
3198                 ret = f2fs_write_multi_pages(&cc, &submitted, wbc, io_type);
3199                 nwritten += submitted;
3200                 wbc->nr_to_write -= submitted;
3201                 if (ret) {
3202                         done = 1;
3203                         retry = 0;
3204                 }
3205         }
3206         if (f2fs_compressed_file(inode))
3207                 f2fs_destroy_compress_ctx(&cc, false);
3208 #endif
3209         if (retry) {
3210                 index = 0;
3211                 end = -1;
3212                 goto retry;
3213         }
3214         if (wbc->range_cyclic && !done)
3215                 done_index = 0;
3216         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3217                 mapping->writeback_index = done_index;
3218
3219         if (nwritten)
3220                 f2fs_submit_merged_write_cond(F2FS_M_SB(mapping), mapping->host,
3221                                                                 NULL, 0, DATA);
3222         /* submit cached bio of IPU write */
3223         if (bio)
3224                 f2fs_submit_merged_ipu_write(sbi, &bio, NULL);
3225
3226         return ret;
3227 }
3228
3229 static inline bool __should_serialize_io(struct inode *inode,
3230                                         struct writeback_control *wbc)
3231 {
3232         /* to avoid deadlock in path of data flush */
3233         if (F2FS_I(inode)->wb_task)
3234                 return false;
3235
3236         if (!S_ISREG(inode->i_mode))
3237                 return false;
3238         if (IS_NOQUOTA(inode))
3239                 return false;
3240
3241         if (f2fs_need_compress_data(inode))
3242                 return true;
3243         if (wbc->sync_mode != WB_SYNC_ALL)
3244                 return true;
3245         if (get_dirty_pages(inode) >= SM_I(F2FS_I_SB(inode))->min_seq_blocks)
3246                 return true;
3247         return false;
3248 }
3249
3250 static int __f2fs_write_data_pages(struct address_space *mapping,
3251                                                 struct writeback_control *wbc,
3252                                                 enum iostat_type io_type)
3253 {
3254         struct inode *inode = mapping->host;
3255         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3256         struct blk_plug plug;
3257         int ret;
3258         bool locked = false;
3259
3260         /* deal with chardevs and other special file */
3261         if (!mapping->a_ops->writepage)
3262                 return 0;
3263
3264         /* skip writing if there is no dirty page in this inode */
3265         if (!get_dirty_pages(inode) && wbc->sync_mode == WB_SYNC_NONE)
3266                 return 0;
3267
3268         /* during POR, we don't need to trigger writepage at all. */
3269         if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
3270                 goto skip_write;
3271
3272         if ((S_ISDIR(inode->i_mode) || IS_NOQUOTA(inode)) &&
3273                         wbc->sync_mode == WB_SYNC_NONE &&
3274                         get_dirty_pages(inode) < nr_pages_to_skip(sbi, DATA) &&
3275                         f2fs_available_free_memory(sbi, DIRTY_DENTS))
3276                 goto skip_write;
3277
3278         /* skip writing in file defragment preparing stage */
3279         if (is_inode_flag_set(inode, FI_SKIP_WRITES))
3280                 goto skip_write;
3281
3282         trace_f2fs_writepages(mapping->host, wbc, DATA);
3283
3284         /* to avoid spliting IOs due to mixed WB_SYNC_ALL and WB_SYNC_NONE */
3285         if (wbc->sync_mode == WB_SYNC_ALL)
3286                 atomic_inc(&sbi->wb_sync_req[DATA]);
3287         else if (atomic_read(&sbi->wb_sync_req[DATA])) {
3288                 /* to avoid potential deadlock */
3289                 if (current->plug)
3290                         blk_finish_plug(current->plug);
3291                 goto skip_write;
3292         }
3293
3294         if (__should_serialize_io(inode, wbc)) {
3295                 mutex_lock(&sbi->writepages);
3296                 locked = true;
3297         }
3298
3299         blk_start_plug(&plug);
3300         ret = f2fs_write_cache_pages(mapping, wbc, io_type);
3301         blk_finish_plug(&plug);
3302
3303         if (locked)
3304                 mutex_unlock(&sbi->writepages);
3305
3306         if (wbc->sync_mode == WB_SYNC_ALL)
3307                 atomic_dec(&sbi->wb_sync_req[DATA]);
3308         /*
3309          * if some pages were truncated, we cannot guarantee its mapping->host
3310          * to detect pending bios.
3311          */
3312
3313         f2fs_remove_dirty_inode(inode);
3314         return ret;
3315
3316 skip_write:
3317         wbc->pages_skipped += get_dirty_pages(inode);
3318         trace_f2fs_writepages(mapping->host, wbc, DATA);
3319         return 0;
3320 }
3321
3322 static int f2fs_write_data_pages(struct address_space *mapping,
3323                             struct writeback_control *wbc)
3324 {
3325         struct inode *inode = mapping->host;
3326
3327         return __f2fs_write_data_pages(mapping, wbc,
3328                         F2FS_I(inode)->cp_task == current ?
3329                         FS_CP_DATA_IO : FS_DATA_IO);
3330 }
3331
3332 void f2fs_write_failed(struct inode *inode, loff_t to)
3333 {
3334         loff_t i_size = i_size_read(inode);
3335
3336         if (IS_NOQUOTA(inode))
3337                 return;
3338
3339         /* In the fs-verity case, f2fs_end_enable_verity() does the truncate */
3340         if (to > i_size && !f2fs_verity_in_progress(inode)) {
3341                 f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3342                 filemap_invalidate_lock(inode->i_mapping);
3343
3344                 truncate_pagecache(inode, i_size);
3345                 f2fs_truncate_blocks(inode, i_size, true);
3346
3347                 filemap_invalidate_unlock(inode->i_mapping);
3348                 f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3349         }
3350 }
3351
3352 static int prepare_write_begin(struct f2fs_sb_info *sbi,
3353                         struct page *page, loff_t pos, unsigned len,
3354                         block_t *blk_addr, bool *node_changed)
3355 {
3356         struct inode *inode = page->mapping->host;
3357         pgoff_t index = page->index;
3358         struct dnode_of_data dn;
3359         struct page *ipage;
3360         bool locked = false;
3361         int flag = F2FS_GET_BLOCK_PRE_AIO;
3362         int err = 0;
3363
3364         /*
3365          * If a whole page is being written and we already preallocated all the
3366          * blocks, then there is no need to get a block address now.
3367          */
3368         if (len == PAGE_SIZE && is_inode_flag_set(inode, FI_PREALLOCATED_ALL))
3369                 return 0;
3370
3371         /* f2fs_lock_op avoids race between write CP and convert_inline_page */
3372         if (f2fs_has_inline_data(inode)) {
3373                 if (pos + len > MAX_INLINE_DATA(inode))
3374                         flag = F2FS_GET_BLOCK_DEFAULT;
3375                 f2fs_map_lock(sbi, flag);
3376                 locked = true;
3377         } else if ((pos & PAGE_MASK) >= i_size_read(inode)) {
3378                 f2fs_map_lock(sbi, flag);
3379                 locked = true;
3380         }
3381
3382 restart:
3383         /* check inline_data */
3384         ipage = f2fs_get_node_page(sbi, inode->i_ino);
3385         if (IS_ERR(ipage)) {
3386                 err = PTR_ERR(ipage);
3387                 goto unlock_out;
3388         }
3389
3390         set_new_dnode(&dn, inode, ipage, ipage, 0);
3391
3392         if (f2fs_has_inline_data(inode)) {
3393                 if (pos + len <= MAX_INLINE_DATA(inode)) {
3394                         f2fs_do_read_inline_data(page, ipage);
3395                         set_inode_flag(inode, FI_DATA_EXIST);
3396                         if (inode->i_nlink)
3397                                 set_page_private_inline(ipage);
3398                         goto out;
3399                 }
3400                 err = f2fs_convert_inline_page(&dn, page);
3401                 if (err || dn.data_blkaddr != NULL_ADDR)
3402                         goto out;
3403         }
3404
3405         if (!f2fs_lookup_read_extent_cache_block(inode, index,
3406                                                  &dn.data_blkaddr)) {
3407                 if (locked) {
3408                         err = f2fs_reserve_block(&dn, index);
3409                         goto out;
3410                 }
3411
3412                 /* hole case */
3413                 err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
3414                 if (!err && dn.data_blkaddr != NULL_ADDR)
3415                         goto out;
3416                 f2fs_put_dnode(&dn);
3417                 f2fs_map_lock(sbi, F2FS_GET_BLOCK_PRE_AIO);
3418                 WARN_ON(flag != F2FS_GET_BLOCK_PRE_AIO);
3419                 locked = true;
3420                 goto restart;
3421         }
3422 out:
3423         if (!err) {
3424                 /* convert_inline_page can make node_changed */
3425                 *blk_addr = dn.data_blkaddr;
3426                 *node_changed = dn.node_changed;
3427         }
3428         f2fs_put_dnode(&dn);
3429 unlock_out:
3430         if (locked)
3431                 f2fs_map_unlock(sbi, flag);
3432         return err;
3433 }
3434
3435 static int __find_data_block(struct inode *inode, pgoff_t index,
3436                                 block_t *blk_addr)
3437 {
3438         struct dnode_of_data dn;
3439         struct page *ipage;
3440         int err = 0;
3441
3442         ipage = f2fs_get_node_page(F2FS_I_SB(inode), inode->i_ino);
3443         if (IS_ERR(ipage))
3444                 return PTR_ERR(ipage);
3445
3446         set_new_dnode(&dn, inode, ipage, ipage, 0);
3447
3448         if (!f2fs_lookup_read_extent_cache_block(inode, index,
3449                                                  &dn.data_blkaddr)) {
3450                 /* hole case */
3451                 err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
3452                 if (err) {
3453                         dn.data_blkaddr = NULL_ADDR;
3454                         err = 0;
3455                 }
3456         }
3457         *blk_addr = dn.data_blkaddr;
3458         f2fs_put_dnode(&dn);
3459         return err;
3460 }
3461
3462 static int __reserve_data_block(struct inode *inode, pgoff_t index,
3463                                 block_t *blk_addr, bool *node_changed)
3464 {
3465         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3466         struct dnode_of_data dn;
3467         struct page *ipage;
3468         int err = 0;
3469
3470         f2fs_map_lock(sbi, F2FS_GET_BLOCK_PRE_AIO);
3471
3472         ipage = f2fs_get_node_page(sbi, inode->i_ino);
3473         if (IS_ERR(ipage)) {
3474                 err = PTR_ERR(ipage);
3475                 goto unlock_out;
3476         }
3477         set_new_dnode(&dn, inode, ipage, ipage, 0);
3478
3479         if (!f2fs_lookup_read_extent_cache_block(dn.inode, index,
3480                                                 &dn.data_blkaddr))
3481                 err = f2fs_reserve_block(&dn, index);
3482
3483         *blk_addr = dn.data_blkaddr;
3484         *node_changed = dn.node_changed;
3485         f2fs_put_dnode(&dn);
3486
3487 unlock_out:
3488         f2fs_map_unlock(sbi, F2FS_GET_BLOCK_PRE_AIO);
3489         return err;
3490 }
3491
3492 static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi,
3493                         struct page *page, loff_t pos, unsigned int len,
3494                         block_t *blk_addr, bool *node_changed, bool *use_cow)
3495 {
3496         struct inode *inode = page->mapping->host;
3497         struct inode *cow_inode = F2FS_I(inode)->cow_inode;
3498         pgoff_t index = page->index;
3499         int err = 0;
3500         block_t ori_blk_addr = NULL_ADDR;
3501
3502         /* If pos is beyond the end of file, reserve a new block in COW inode */
3503         if ((pos & PAGE_MASK) >= i_size_read(inode))
3504                 goto reserve_block;
3505
3506         /* Look for the block in COW inode first */
3507         err = __find_data_block(cow_inode, index, blk_addr);
3508         if (err) {
3509                 return err;
3510         } else if (*blk_addr != NULL_ADDR) {
3511                 *use_cow = true;
3512                 return 0;
3513         }
3514
3515         if (is_inode_flag_set(inode, FI_ATOMIC_REPLACE))
3516                 goto reserve_block;
3517
3518         /* Look for the block in the original inode */
3519         err = __find_data_block(inode, index, &ori_blk_addr);
3520         if (err)
3521                 return err;
3522
3523 reserve_block:
3524         /* Finally, we should reserve a new block in COW inode for the update */
3525         err = __reserve_data_block(cow_inode, index, blk_addr, node_changed);
3526         if (err)
3527                 return err;
3528         inc_atomic_write_cnt(inode);
3529
3530         if (ori_blk_addr != NULL_ADDR)
3531                 *blk_addr = ori_blk_addr;
3532         return 0;
3533 }
3534
3535 static int f2fs_write_begin(struct file *file, struct address_space *mapping,
3536                 loff_t pos, unsigned len, struct page **pagep, void **fsdata)
3537 {
3538         struct inode *inode = mapping->host;
3539         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3540         struct page *page = NULL;
3541         pgoff_t index = ((unsigned long long) pos) >> PAGE_SHIFT;
3542         bool need_balance = false;
3543         bool use_cow = false;
3544         block_t blkaddr = NULL_ADDR;
3545         int err = 0;
3546
3547         trace_f2fs_write_begin(inode, pos, len);
3548
3549         if (!f2fs_is_checkpoint_ready(sbi)) {
3550                 err = -ENOSPC;
3551                 goto fail;
3552         }
3553
3554         /*
3555          * We should check this at this moment to avoid deadlock on inode page
3556          * and #0 page. The locking rule for inline_data conversion should be:
3557          * lock_page(page #0) -> lock_page(inode_page)
3558          */
3559         if (index != 0) {
3560                 err = f2fs_convert_inline_inode(inode);
3561                 if (err)
3562                         goto fail;
3563         }
3564
3565 #ifdef CONFIG_F2FS_FS_COMPRESSION
3566         if (f2fs_compressed_file(inode)) {
3567                 int ret;
3568
3569                 *fsdata = NULL;
3570
3571                 if (len == PAGE_SIZE && !(f2fs_is_atomic_file(inode)))
3572                         goto repeat;
3573
3574                 ret = f2fs_prepare_compress_overwrite(inode, pagep,
3575                                                         index, fsdata);
3576                 if (ret < 0) {
3577                         err = ret;
3578                         goto fail;
3579                 } else if (ret) {
3580                         return 0;
3581                 }
3582         }
3583 #endif
3584
3585 repeat:
3586         /*
3587          * Do not use grab_cache_page_write_begin() to avoid deadlock due to
3588          * wait_for_stable_page. Will wait that below with our IO control.
3589          */
3590         page = f2fs_pagecache_get_page(mapping, index,
3591                                 FGP_LOCK | FGP_WRITE | FGP_CREAT, GFP_NOFS);
3592         if (!page) {
3593                 err = -ENOMEM;
3594                 goto fail;
3595         }
3596
3597         /* TODO: cluster can be compressed due to race with .writepage */
3598
3599         *pagep = page;
3600
3601         if (f2fs_is_atomic_file(inode))
3602                 err = prepare_atomic_write_begin(sbi, page, pos, len,
3603                                         &blkaddr, &need_balance, &use_cow);
3604         else
3605                 err = prepare_write_begin(sbi, page, pos, len,
3606                                         &blkaddr, &need_balance);
3607         if (err)
3608                 goto fail;
3609
3610         if (need_balance && !IS_NOQUOTA(inode) &&
3611                         has_not_enough_free_secs(sbi, 0, 0)) {
3612                 unlock_page(page);
3613                 f2fs_balance_fs(sbi, true);
3614                 lock_page(page);
3615                 if (page->mapping != mapping) {
3616                         /* The page got truncated from under us */
3617                         f2fs_put_page(page, 1);
3618                         goto repeat;
3619                 }
3620         }
3621
3622         f2fs_wait_on_page_writeback(page, DATA, false, true);
3623
3624         if (len == PAGE_SIZE || PageUptodate(page))
3625                 return 0;
3626
3627         if (!(pos & (PAGE_SIZE - 1)) && (pos + len) >= i_size_read(inode) &&
3628             !f2fs_verity_in_progress(inode)) {
3629                 zero_user_segment(page, len, PAGE_SIZE);
3630                 return 0;
3631         }
3632
3633         if (blkaddr == NEW_ADDR) {
3634                 zero_user_segment(page, 0, PAGE_SIZE);
3635                 SetPageUptodate(page);
3636         } else {
3637                 if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
3638                                 DATA_GENERIC_ENHANCE_READ)) {
3639                         err = -EFSCORRUPTED;
3640                         f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
3641                         goto fail;
3642                 }
3643                 err = f2fs_submit_page_read(use_cow ?
3644                                 F2FS_I(inode)->cow_inode : inode, page,
3645                                 blkaddr, 0, true);
3646                 if (err)
3647                         goto fail;
3648
3649                 lock_page(page);
3650                 if (unlikely(page->mapping != mapping)) {
3651                         f2fs_put_page(page, 1);
3652                         goto repeat;
3653                 }
3654                 if (unlikely(!PageUptodate(page))) {
3655                         err = -EIO;
3656                         goto fail;
3657                 }
3658         }
3659         return 0;
3660
3661 fail:
3662         f2fs_put_page(page, 1);
3663         f2fs_write_failed(inode, pos + len);
3664         return err;
3665 }
3666
3667 static int f2fs_write_end(struct file *file,
3668                         struct address_space *mapping,
3669                         loff_t pos, unsigned len, unsigned copied,
3670                         struct page *page, void *fsdata)
3671 {
3672         struct inode *inode = page->mapping->host;
3673
3674         trace_f2fs_write_end(inode, pos, len, copied);
3675
3676         /*
3677          * This should be come from len == PAGE_SIZE, and we expect copied
3678          * should be PAGE_SIZE. Otherwise, we treat it with zero copied and
3679          * let generic_perform_write() try to copy data again through copied=0.
3680          */
3681         if (!PageUptodate(page)) {
3682                 if (unlikely(copied != len))
3683                         copied = 0;
3684                 else
3685                         SetPageUptodate(page);
3686         }
3687
3688 #ifdef CONFIG_F2FS_FS_COMPRESSION
3689         /* overwrite compressed file */
3690         if (f2fs_compressed_file(inode) && fsdata) {
3691                 f2fs_compress_write_end(inode, fsdata, page->index, copied);
3692                 f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
3693
3694                 if (pos + copied > i_size_read(inode) &&
3695                                 !f2fs_verity_in_progress(inode))
3696                         f2fs_i_size_write(inode, pos + copied);
3697                 return copied;
3698         }
3699 #endif
3700
3701         if (!copied)
3702                 goto unlock_out;
3703
3704         set_page_dirty(page);
3705
3706         if (pos + copied > i_size_read(inode) &&
3707             !f2fs_verity_in_progress(inode)) {
3708                 f2fs_i_size_write(inode, pos + copied);
3709                 if (f2fs_is_atomic_file(inode))
3710                         f2fs_i_size_write(F2FS_I(inode)->cow_inode,
3711                                         pos + copied);
3712         }
3713 unlock_out:
3714         f2fs_put_page(page, 1);
3715         f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
3716         return copied;
3717 }
3718
3719 void f2fs_invalidate_folio(struct folio *folio, size_t offset, size_t length)
3720 {
3721         struct inode *inode = folio->mapping->host;
3722         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3723
3724         if (inode->i_ino >= F2FS_ROOT_INO(sbi) &&
3725                                 (offset || length != folio_size(folio)))
3726                 return;
3727
3728         if (folio_test_dirty(folio)) {
3729                 if (inode->i_ino == F2FS_META_INO(sbi)) {
3730                         dec_page_count(sbi, F2FS_DIRTY_META);
3731                 } else if (inode->i_ino == F2FS_NODE_INO(sbi)) {
3732                         dec_page_count(sbi, F2FS_DIRTY_NODES);
3733                 } else {
3734                         inode_dec_dirty_pages(inode);
3735                         f2fs_remove_dirty_inode(inode);
3736                 }
3737         }
3738         clear_page_private_all(&folio->page);
3739 }
3740
3741 bool f2fs_release_folio(struct folio *folio, gfp_t wait)
3742 {
3743         /* If this is dirty folio, keep private data */
3744         if (folio_test_dirty(folio))
3745                 return false;
3746
3747         clear_page_private_all(&folio->page);
3748         return true;
3749 }
3750
3751 static bool f2fs_dirty_data_folio(struct address_space *mapping,
3752                 struct folio *folio)
3753 {
3754         struct inode *inode = mapping->host;
3755
3756         trace_f2fs_set_page_dirty(&folio->page, DATA);
3757
3758         if (!folio_test_uptodate(folio))
3759                 folio_mark_uptodate(folio);
3760         BUG_ON(folio_test_swapcache(folio));
3761
3762         if (filemap_dirty_folio(mapping, folio)) {
3763                 f2fs_update_dirty_folio(inode, folio);
3764                 return true;
3765         }
3766         return false;
3767 }
3768
3769
3770 static sector_t f2fs_bmap_compress(struct inode *inode, sector_t block)
3771 {
3772 #ifdef CONFIG_F2FS_FS_COMPRESSION
3773         struct dnode_of_data dn;
3774         sector_t start_idx, blknr = 0;
3775         int ret;
3776
3777         start_idx = round_down(block, F2FS_I(inode)->i_cluster_size);
3778
3779         set_new_dnode(&dn, inode, NULL, NULL, 0);
3780         ret = f2fs_get_dnode_of_data(&dn, start_idx, LOOKUP_NODE);
3781         if (ret)
3782                 return 0;
3783
3784         if (dn.data_blkaddr != COMPRESS_ADDR) {
3785                 dn.ofs_in_node += block - start_idx;
3786                 blknr = f2fs_data_blkaddr(&dn);
3787                 if (!__is_valid_data_blkaddr(blknr))
3788                         blknr = 0;
3789         }
3790
3791         f2fs_put_dnode(&dn);
3792         return blknr;
3793 #else
3794         return 0;
3795 #endif
3796 }
3797
3798
3799 static sector_t f2fs_bmap(struct address_space *mapping, sector_t block)
3800 {
3801         struct inode *inode = mapping->host;
3802         sector_t blknr = 0;
3803
3804         if (f2fs_has_inline_data(inode))
3805                 goto out;
3806
3807         /* make sure allocating whole blocks */
3808         if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
3809                 filemap_write_and_wait(mapping);
3810
3811         /* Block number less than F2FS MAX BLOCKS */
3812         if (unlikely(block >= max_file_blocks(inode)))
3813                 goto out;
3814
3815         if (f2fs_compressed_file(inode)) {
3816                 blknr = f2fs_bmap_compress(inode, block);
3817         } else {
3818                 struct f2fs_map_blocks map;
3819
3820                 memset(&map, 0, sizeof(map));
3821                 map.m_lblk = block;
3822                 map.m_len = 1;
3823                 map.m_next_pgofs = NULL;
3824                 map.m_seg_type = NO_CHECK_TYPE;
3825
3826                 if (!f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_BMAP))
3827                         blknr = map.m_pblk;
3828         }
3829 out:
3830         trace_f2fs_bmap(inode, block, blknr);
3831         return blknr;
3832 }
3833
3834 #ifdef CONFIG_SWAP
3835 static int f2fs_migrate_blocks(struct inode *inode, block_t start_blk,
3836                                                         unsigned int blkcnt)
3837 {
3838         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3839         unsigned int blkofs;
3840         unsigned int blk_per_sec = BLKS_PER_SEC(sbi);
3841         unsigned int secidx = start_blk / blk_per_sec;
3842         unsigned int end_sec = secidx + blkcnt / blk_per_sec;
3843         int ret = 0;
3844
3845         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3846         filemap_invalidate_lock(inode->i_mapping);
3847
3848         set_inode_flag(inode, FI_ALIGNED_WRITE);
3849         set_inode_flag(inode, FI_OPU_WRITE);
3850
3851         for (; secidx < end_sec; secidx++) {
3852                 f2fs_down_write(&sbi->pin_sem);
3853
3854                 f2fs_lock_op(sbi);
3855                 f2fs_allocate_new_section(sbi, CURSEG_COLD_DATA_PINNED, false);
3856                 f2fs_unlock_op(sbi);
3857
3858                 set_inode_flag(inode, FI_SKIP_WRITES);
3859
3860                 for (blkofs = 0; blkofs < blk_per_sec; blkofs++) {
3861                         struct page *page;
3862                         unsigned int blkidx = secidx * blk_per_sec + blkofs;
3863
3864                         page = f2fs_get_lock_data_page(inode, blkidx, true);
3865                         if (IS_ERR(page)) {
3866                                 f2fs_up_write(&sbi->pin_sem);
3867                                 ret = PTR_ERR(page);
3868                                 goto done;
3869                         }
3870
3871                         set_page_dirty(page);
3872                         f2fs_put_page(page, 1);
3873                 }
3874
3875                 clear_inode_flag(inode, FI_SKIP_WRITES);
3876
3877                 ret = filemap_fdatawrite(inode->i_mapping);
3878
3879                 f2fs_up_write(&sbi->pin_sem);
3880
3881                 if (ret)
3882                         break;
3883         }
3884
3885 done:
3886         clear_inode_flag(inode, FI_SKIP_WRITES);
3887         clear_inode_flag(inode, FI_OPU_WRITE);
3888         clear_inode_flag(inode, FI_ALIGNED_WRITE);
3889
3890         filemap_invalidate_unlock(inode->i_mapping);
3891         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3892
3893         return ret;
3894 }
3895
3896 static int check_swap_activate(struct swap_info_struct *sis,
3897                                 struct file *swap_file, sector_t *span)
3898 {
3899         struct address_space *mapping = swap_file->f_mapping;
3900         struct inode *inode = mapping->host;
3901         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3902         sector_t cur_lblock;
3903         sector_t last_lblock;
3904         sector_t pblock;
3905         sector_t lowest_pblock = -1;
3906         sector_t highest_pblock = 0;
3907         int nr_extents = 0;
3908         unsigned long nr_pblocks;
3909         unsigned int blks_per_sec = BLKS_PER_SEC(sbi);
3910         unsigned int sec_blks_mask = BLKS_PER_SEC(sbi) - 1;
3911         unsigned int not_aligned = 0;
3912         int ret = 0;
3913
3914         /*
3915          * Map all the blocks into the extent list.  This code doesn't try
3916          * to be very smart.
3917          */
3918         cur_lblock = 0;
3919         last_lblock = bytes_to_blks(inode, i_size_read(inode));
3920
3921         while (cur_lblock < last_lblock && cur_lblock < sis->max) {
3922                 struct f2fs_map_blocks map;
3923 retry:
3924                 cond_resched();
3925
3926                 memset(&map, 0, sizeof(map));
3927                 map.m_lblk = cur_lblock;
3928                 map.m_len = last_lblock - cur_lblock;
3929                 map.m_next_pgofs = NULL;
3930                 map.m_next_extent = NULL;
3931                 map.m_seg_type = NO_CHECK_TYPE;
3932                 map.m_may_create = false;
3933
3934                 ret = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_FIEMAP);
3935                 if (ret)
3936                         goto out;
3937
3938                 /* hole */
3939                 if (!(map.m_flags & F2FS_MAP_FLAGS)) {
3940                         f2fs_err(sbi, "Swapfile has holes");
3941                         ret = -EINVAL;
3942                         goto out;
3943                 }
3944
3945                 pblock = map.m_pblk;
3946                 nr_pblocks = map.m_len;
3947
3948                 if ((pblock - SM_I(sbi)->main_blkaddr) & sec_blks_mask ||
3949                                 nr_pblocks & sec_blks_mask) {
3950                         not_aligned++;
3951
3952                         nr_pblocks = roundup(nr_pblocks, blks_per_sec);
3953                         if (cur_lblock + nr_pblocks > sis->max)
3954                                 nr_pblocks -= blks_per_sec;
3955
3956                         if (!nr_pblocks) {
3957                                 /* this extent is last one */
3958                                 nr_pblocks = map.m_len;
3959                                 f2fs_warn(sbi, "Swapfile: last extent is not aligned to section");
3960                                 goto next;
3961                         }
3962
3963                         ret = f2fs_migrate_blocks(inode, cur_lblock,
3964                                                         nr_pblocks);
3965                         if (ret)
3966                                 goto out;
3967                         goto retry;
3968                 }
3969 next:
3970                 if (cur_lblock + nr_pblocks >= sis->max)
3971                         nr_pblocks = sis->max - cur_lblock;
3972
3973                 if (cur_lblock) {       /* exclude the header page */
3974                         if (pblock < lowest_pblock)
3975                                 lowest_pblock = pblock;
3976                         if (pblock + nr_pblocks - 1 > highest_pblock)
3977                                 highest_pblock = pblock + nr_pblocks - 1;
3978                 }
3979
3980                 /*
3981                  * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
3982                  */
3983                 ret = add_swap_extent(sis, cur_lblock, nr_pblocks, pblock);
3984                 if (ret < 0)
3985                         goto out;
3986                 nr_extents += ret;
3987                 cur_lblock += nr_pblocks;
3988         }
3989         ret = nr_extents;
3990         *span = 1 + highest_pblock - lowest_pblock;
3991         if (cur_lblock == 0)
3992                 cur_lblock = 1; /* force Empty message */
3993         sis->max = cur_lblock;
3994         sis->pages = cur_lblock - 1;
3995         sis->highest_bit = cur_lblock - 1;
3996 out:
3997         if (not_aligned)
3998                 f2fs_warn(sbi, "Swapfile (%u) is not align to section: 1) creat(), 2) ioctl(F2FS_IOC_SET_PIN_FILE), 3) fallocate(%u * N)",
3999                           not_aligned, blks_per_sec * F2FS_BLKSIZE);
4000         return ret;
4001 }
4002
4003 static int f2fs_swap_activate(struct swap_info_struct *sis, struct file *file,
4004                                 sector_t *span)
4005 {
4006         struct inode *inode = file_inode(file);
4007         int ret;
4008
4009         if (!S_ISREG(inode->i_mode))
4010                 return -EINVAL;
4011
4012         if (f2fs_readonly(F2FS_I_SB(inode)->sb))
4013                 return -EROFS;
4014
4015         if (f2fs_lfs_mode(F2FS_I_SB(inode))) {
4016                 f2fs_err(F2FS_I_SB(inode),
4017                         "Swapfile not supported in LFS mode");
4018                 return -EINVAL;
4019         }
4020
4021         ret = f2fs_convert_inline_inode(inode);
4022         if (ret)
4023                 return ret;
4024
4025         if (!f2fs_disable_compressed_file(inode))
4026                 return -EINVAL;
4027
4028         f2fs_precache_extents(inode);
4029
4030         ret = check_swap_activate(sis, file, span);
4031         if (ret < 0)
4032                 return ret;
4033
4034         stat_inc_swapfile_inode(inode);
4035         set_inode_flag(inode, FI_PIN_FILE);
4036         f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
4037         return ret;
4038 }
4039
4040 static void f2fs_swap_deactivate(struct file *file)
4041 {
4042         struct inode *inode = file_inode(file);
4043
4044         stat_dec_swapfile_inode(inode);
4045         clear_inode_flag(inode, FI_PIN_FILE);
4046 }
4047 #else
4048 static int f2fs_swap_activate(struct swap_info_struct *sis, struct file *file,
4049                                 sector_t *span)
4050 {
4051         return -EOPNOTSUPP;
4052 }
4053
4054 static void f2fs_swap_deactivate(struct file *file)
4055 {
4056 }
4057 #endif
4058
4059 const struct address_space_operations f2fs_dblock_aops = {
4060         .read_folio     = f2fs_read_data_folio,
4061         .readahead      = f2fs_readahead,
4062         .writepage      = f2fs_write_data_page,
4063         .writepages     = f2fs_write_data_pages,
4064         .write_begin    = f2fs_write_begin,
4065         .write_end      = f2fs_write_end,
4066         .dirty_folio    = f2fs_dirty_data_folio,
4067         .migrate_folio  = filemap_migrate_folio,
4068         .invalidate_folio = f2fs_invalidate_folio,
4069         .release_folio  = f2fs_release_folio,
4070         .direct_IO      = noop_direct_IO,
4071         .bmap           = f2fs_bmap,
4072         .swap_activate  = f2fs_swap_activate,
4073         .swap_deactivate = f2fs_swap_deactivate,
4074 };
4075
4076 void f2fs_clear_page_cache_dirty_tag(struct page *page)
4077 {
4078         struct address_space *mapping = page_mapping(page);
4079         unsigned long flags;
4080
4081         xa_lock_irqsave(&mapping->i_pages, flags);
4082         __xa_clear_mark(&mapping->i_pages, page_index(page),
4083                                                 PAGECACHE_TAG_DIRTY);
4084         xa_unlock_irqrestore(&mapping->i_pages, flags);
4085 }
4086
4087 int __init f2fs_init_post_read_processing(void)
4088 {
4089         bio_post_read_ctx_cache =
4090                 kmem_cache_create("f2fs_bio_post_read_ctx",
4091                                   sizeof(struct bio_post_read_ctx), 0, 0, NULL);
4092         if (!bio_post_read_ctx_cache)
4093                 goto fail;
4094         bio_post_read_ctx_pool =
4095                 mempool_create_slab_pool(NUM_PREALLOC_POST_READ_CTXS,
4096                                          bio_post_read_ctx_cache);
4097         if (!bio_post_read_ctx_pool)
4098                 goto fail_free_cache;
4099         return 0;
4100
4101 fail_free_cache:
4102         kmem_cache_destroy(bio_post_read_ctx_cache);
4103 fail:
4104         return -ENOMEM;
4105 }
4106
4107 void f2fs_destroy_post_read_processing(void)
4108 {
4109         mempool_destroy(bio_post_read_ctx_pool);
4110         kmem_cache_destroy(bio_post_read_ctx_cache);
4111 }
4112
4113 int f2fs_init_post_read_wq(struct f2fs_sb_info *sbi)
4114 {
4115         if (!f2fs_sb_has_encrypt(sbi) &&
4116                 !f2fs_sb_has_verity(sbi) &&
4117                 !f2fs_sb_has_compression(sbi))
4118                 return 0;
4119
4120         sbi->post_read_wq = alloc_workqueue("f2fs_post_read_wq",
4121                                                  WQ_UNBOUND | WQ_HIGHPRI,
4122                                                  num_online_cpus());
4123         return sbi->post_read_wq ? 0 : -ENOMEM;
4124 }
4125
4126 void f2fs_destroy_post_read_wq(struct f2fs_sb_info *sbi)
4127 {
4128         if (sbi->post_read_wq)
4129                 destroy_workqueue(sbi->post_read_wq);
4130 }
4131
4132 int __init f2fs_init_bio_entry_cache(void)
4133 {
4134         bio_entry_slab = f2fs_kmem_cache_create("f2fs_bio_entry_slab",
4135                         sizeof(struct bio_entry));
4136         return bio_entry_slab ? 0 : -ENOMEM;
4137 }
4138
4139 void f2fs_destroy_bio_entry_cache(void)
4140 {
4141         kmem_cache_destroy(bio_entry_slab);
4142 }
4143
4144 static int f2fs_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
4145                             unsigned int flags, struct iomap *iomap,
4146                             struct iomap *srcmap)
4147 {
4148         struct f2fs_map_blocks map = {};
4149         pgoff_t next_pgofs = 0;
4150         int err;
4151
4152         map.m_lblk = bytes_to_blks(inode, offset);
4153         map.m_len = bytes_to_blks(inode, offset + length - 1) - map.m_lblk + 1;
4154         map.m_next_pgofs = &next_pgofs;
4155         map.m_seg_type = f2fs_rw_hint_to_seg_type(inode->i_write_hint);
4156         if (flags & IOMAP_WRITE)
4157                 map.m_may_create = true;
4158
4159         err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_DIO);
4160         if (err)
4161                 return err;
4162
4163         iomap->offset = blks_to_bytes(inode, map.m_lblk);
4164
4165         /*
4166          * When inline encryption is enabled, sometimes I/O to an encrypted file
4167          * has to be broken up to guarantee DUN contiguity.  Handle this by
4168          * limiting the length of the mapping returned.
4169          */
4170         map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
4171
4172         /*
4173          * We should never see delalloc or compressed extents here based on
4174          * prior flushing and checks.
4175          */
4176         if (WARN_ON_ONCE(map.m_pblk == NEW_ADDR))
4177                 return -EINVAL;
4178         if (WARN_ON_ONCE(map.m_pblk == COMPRESS_ADDR))
4179                 return -EINVAL;
4180
4181         if (map.m_pblk != NULL_ADDR) {
4182                 iomap->length = blks_to_bytes(inode, map.m_len);
4183                 iomap->type = IOMAP_MAPPED;
4184                 iomap->flags |= IOMAP_F_MERGED;
4185                 iomap->bdev = map.m_bdev;
4186                 iomap->addr = blks_to_bytes(inode, map.m_pblk);
4187         } else {
4188                 if (flags & IOMAP_WRITE)
4189                         return -ENOTBLK;
4190                 iomap->length = blks_to_bytes(inode, next_pgofs) -
4191                                 iomap->offset;
4192                 iomap->type = IOMAP_HOLE;
4193                 iomap->addr = IOMAP_NULL_ADDR;
4194         }
4195
4196         if (map.m_flags & F2FS_MAP_NEW)
4197                 iomap->flags |= IOMAP_F_NEW;
4198         if ((inode->i_state & I_DIRTY_DATASYNC) ||
4199             offset + length > i_size_read(inode))
4200                 iomap->flags |= IOMAP_F_DIRTY;
4201
4202         return 0;
4203 }
4204
4205 const struct iomap_ops f2fs_iomap_ops = {
4206         .iomap_begin    = f2fs_iomap_begin,
4207 };