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