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