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