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