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