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