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