093039dee99206715c9b878838cdcfdc7a4b289e
[platform/kernel/linux-starfive.git] / fs / f2fs / file.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/file.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/stat.h>
11 #include <linux/buffer_head.h>
12 #include <linux/writeback.h>
13 #include <linux/blkdev.h>
14 #include <linux/falloc.h>
15 #include <linux/types.h>
16 #include <linux/compat.h>
17 #include <linux/uaccess.h>
18 #include <linux/mount.h>
19 #include <linux/pagevec.h>
20 #include <linux/uio.h>
21 #include <linux/uuid.h>
22 #include <linux/file.h>
23 #include <linux/nls.h>
24 #include <linux/sched/signal.h>
25 #include <linux/fileattr.h>
26 #include <linux/fadvise.h>
27 #include <linux/iomap.h>
28
29 #include "f2fs.h"
30 #include "node.h"
31 #include "segment.h"
32 #include "xattr.h"
33 #include "acl.h"
34 #include "gc.h"
35 #include "iostat.h"
36 #include <trace/events/f2fs.h>
37 #include <uapi/linux/f2fs.h>
38
39 static vm_fault_t f2fs_filemap_fault(struct vm_fault *vmf)
40 {
41         struct inode *inode = file_inode(vmf->vma->vm_file);
42         vm_fault_t ret;
43
44         ret = filemap_fault(vmf);
45         if (!ret)
46                 f2fs_update_iostat(F2FS_I_SB(inode), inode,
47                                         APP_MAPPED_READ_IO, F2FS_BLKSIZE);
48
49         trace_f2fs_filemap_fault(inode, vmf->pgoff, (unsigned long)ret);
50
51         return ret;
52 }
53
54 static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)
55 {
56         struct page *page = vmf->page;
57         struct inode *inode = file_inode(vmf->vma->vm_file);
58         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
59         struct dnode_of_data dn;
60         bool need_alloc = true;
61         int err = 0;
62
63         if (unlikely(IS_IMMUTABLE(inode)))
64                 return VM_FAULT_SIGBUS;
65
66         if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED))
67                 return VM_FAULT_SIGBUS;
68
69         if (unlikely(f2fs_cp_error(sbi))) {
70                 err = -EIO;
71                 goto err;
72         }
73
74         if (!f2fs_is_checkpoint_ready(sbi)) {
75                 err = -ENOSPC;
76                 goto err;
77         }
78
79         err = f2fs_convert_inline_inode(inode);
80         if (err)
81                 goto err;
82
83 #ifdef CONFIG_F2FS_FS_COMPRESSION
84         if (f2fs_compressed_file(inode)) {
85                 int ret = f2fs_is_compressed_cluster(inode, page->index);
86
87                 if (ret < 0) {
88                         err = ret;
89                         goto err;
90                 } else if (ret) {
91                         need_alloc = false;
92                 }
93         }
94 #endif
95         /* should do out of any locked page */
96         if (need_alloc)
97                 f2fs_balance_fs(sbi, true);
98
99         sb_start_pagefault(inode->i_sb);
100
101         f2fs_bug_on(sbi, f2fs_has_inline_data(inode));
102
103         file_update_time(vmf->vma->vm_file);
104         filemap_invalidate_lock_shared(inode->i_mapping);
105         lock_page(page);
106         if (unlikely(page->mapping != inode->i_mapping ||
107                         page_offset(page) > i_size_read(inode) ||
108                         !PageUptodate(page))) {
109                 unlock_page(page);
110                 err = -EFAULT;
111                 goto out_sem;
112         }
113
114         if (need_alloc) {
115                 /* block allocation */
116                 set_new_dnode(&dn, inode, NULL, NULL, 0);
117                 err = f2fs_get_block_locked(&dn, page->index);
118         }
119
120 #ifdef CONFIG_F2FS_FS_COMPRESSION
121         if (!need_alloc) {
122                 set_new_dnode(&dn, inode, NULL, NULL, 0);
123                 err = f2fs_get_dnode_of_data(&dn, page->index, LOOKUP_NODE);
124                 f2fs_put_dnode(&dn);
125         }
126 #endif
127         if (err) {
128                 unlock_page(page);
129                 goto out_sem;
130         }
131
132         f2fs_wait_on_page_writeback(page, DATA, false, true);
133
134         /* wait for GCed page writeback via META_MAPPING */
135         f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
136
137         /*
138          * check to see if the page is mapped already (no holes)
139          */
140         if (PageMappedToDisk(page))
141                 goto out_sem;
142
143         /* page is wholly or partially inside EOF */
144         if (((loff_t)(page->index + 1) << PAGE_SHIFT) >
145                                                 i_size_read(inode)) {
146                 loff_t offset;
147
148                 offset = i_size_read(inode) & ~PAGE_MASK;
149                 zero_user_segment(page, offset, PAGE_SIZE);
150         }
151         set_page_dirty(page);
152
153         f2fs_update_iostat(sbi, inode, APP_MAPPED_IO, F2FS_BLKSIZE);
154         f2fs_update_time(sbi, REQ_TIME);
155
156         trace_f2fs_vm_page_mkwrite(page, DATA);
157 out_sem:
158         filemap_invalidate_unlock_shared(inode->i_mapping);
159
160         sb_end_pagefault(inode->i_sb);
161 err:
162         return block_page_mkwrite_return(err);
163 }
164
165 static const struct vm_operations_struct f2fs_file_vm_ops = {
166         .fault          = f2fs_filemap_fault,
167         .map_pages      = filemap_map_pages,
168         .page_mkwrite   = f2fs_vm_page_mkwrite,
169 };
170
171 static int get_parent_ino(struct inode *inode, nid_t *pino)
172 {
173         struct dentry *dentry;
174
175         /*
176          * Make sure to get the non-deleted alias.  The alias associated with
177          * the open file descriptor being fsync()'ed may be deleted already.
178          */
179         dentry = d_find_alias(inode);
180         if (!dentry)
181                 return 0;
182
183         *pino = parent_ino(dentry);
184         dput(dentry);
185         return 1;
186 }
187
188 static inline enum cp_reason_type need_do_checkpoint(struct inode *inode)
189 {
190         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
191         enum cp_reason_type cp_reason = CP_NO_NEEDED;
192
193         if (!S_ISREG(inode->i_mode))
194                 cp_reason = CP_NON_REGULAR;
195         else if (f2fs_compressed_file(inode))
196                 cp_reason = CP_COMPRESSED;
197         else if (inode->i_nlink != 1)
198                 cp_reason = CP_HARDLINK;
199         else if (is_sbi_flag_set(sbi, SBI_NEED_CP))
200                 cp_reason = CP_SB_NEED_CP;
201         else if (file_wrong_pino(inode))
202                 cp_reason = CP_WRONG_PINO;
203         else if (!f2fs_space_for_roll_forward(sbi))
204                 cp_reason = CP_NO_SPC_ROLL;
205         else if (!f2fs_is_checkpointed_node(sbi, F2FS_I(inode)->i_pino))
206                 cp_reason = CP_NODE_NEED_CP;
207         else if (test_opt(sbi, FASTBOOT))
208                 cp_reason = CP_FASTBOOT_MODE;
209         else if (F2FS_OPTION(sbi).active_logs == 2)
210                 cp_reason = CP_SPEC_LOG_NUM;
211         else if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_STRICT &&
212                 f2fs_need_dentry_mark(sbi, inode->i_ino) &&
213                 f2fs_exist_written_data(sbi, F2FS_I(inode)->i_pino,
214                                                         TRANS_DIR_INO))
215                 cp_reason = CP_RECOVER_DIR;
216
217         return cp_reason;
218 }
219
220 static bool need_inode_page_update(struct f2fs_sb_info *sbi, nid_t ino)
221 {
222         struct page *i = find_get_page(NODE_MAPPING(sbi), ino);
223         bool ret = false;
224         /* But we need to avoid that there are some inode updates */
225         if ((i && PageDirty(i)) || f2fs_need_inode_block_update(sbi, ino))
226                 ret = true;
227         f2fs_put_page(i, 0);
228         return ret;
229 }
230
231 static void try_to_fix_pino(struct inode *inode)
232 {
233         struct f2fs_inode_info *fi = F2FS_I(inode);
234         nid_t pino;
235
236         f2fs_down_write(&fi->i_sem);
237         if (file_wrong_pino(inode) && inode->i_nlink == 1 &&
238                         get_parent_ino(inode, &pino)) {
239                 f2fs_i_pino_write(inode, pino);
240                 file_got_pino(inode);
241         }
242         f2fs_up_write(&fi->i_sem);
243 }
244
245 static int f2fs_do_sync_file(struct file *file, loff_t start, loff_t end,
246                                                 int datasync, bool atomic)
247 {
248         struct inode *inode = file->f_mapping->host;
249         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
250         nid_t ino = inode->i_ino;
251         int ret = 0;
252         enum cp_reason_type cp_reason = 0;
253         struct writeback_control wbc = {
254                 .sync_mode = WB_SYNC_ALL,
255                 .nr_to_write = LONG_MAX,
256                 .for_reclaim = 0,
257         };
258         unsigned int seq_id = 0;
259
260         if (unlikely(f2fs_readonly(inode->i_sb)))
261                 return 0;
262
263         trace_f2fs_sync_file_enter(inode);
264
265         if (S_ISDIR(inode->i_mode))
266                 goto go_write;
267
268         /* if fdatasync is triggered, let's do in-place-update */
269         if (datasync || get_dirty_pages(inode) <= SM_I(sbi)->min_fsync_blocks)
270                 set_inode_flag(inode, FI_NEED_IPU);
271         ret = file_write_and_wait_range(file, start, end);
272         clear_inode_flag(inode, FI_NEED_IPU);
273
274         if (ret || is_sbi_flag_set(sbi, SBI_CP_DISABLED)) {
275                 trace_f2fs_sync_file_exit(inode, cp_reason, datasync, ret);
276                 return ret;
277         }
278
279         /* if the inode is dirty, let's recover all the time */
280         if (!f2fs_skip_inode_update(inode, datasync)) {
281                 f2fs_write_inode(inode, NULL);
282                 goto go_write;
283         }
284
285         /*
286          * if there is no written data, don't waste time to write recovery info.
287          */
288         if (!is_inode_flag_set(inode, FI_APPEND_WRITE) &&
289                         !f2fs_exist_written_data(sbi, ino, APPEND_INO)) {
290
291                 /* it may call write_inode just prior to fsync */
292                 if (need_inode_page_update(sbi, ino))
293                         goto go_write;
294
295                 if (is_inode_flag_set(inode, FI_UPDATE_WRITE) ||
296                                 f2fs_exist_written_data(sbi, ino, UPDATE_INO))
297                         goto flush_out;
298                 goto out;
299         } else {
300                 /*
301                  * for OPU case, during fsync(), node can be persisted before
302                  * data when lower device doesn't support write barrier, result
303                  * in data corruption after SPO.
304                  * So for strict fsync mode, force to use atomic write semantics
305                  * to keep write order in between data/node and last node to
306                  * avoid potential data corruption.
307                  */
308                 if (F2FS_OPTION(sbi).fsync_mode ==
309                                 FSYNC_MODE_STRICT && !atomic)
310                         atomic = true;
311         }
312 go_write:
313         /*
314          * Both of fdatasync() and fsync() are able to be recovered from
315          * sudden-power-off.
316          */
317         f2fs_down_read(&F2FS_I(inode)->i_sem);
318         cp_reason = need_do_checkpoint(inode);
319         f2fs_up_read(&F2FS_I(inode)->i_sem);
320
321         if (cp_reason) {
322                 /* all the dirty node pages should be flushed for POR */
323                 ret = f2fs_sync_fs(inode->i_sb, 1);
324
325                 /*
326                  * We've secured consistency through sync_fs. Following pino
327                  * will be used only for fsynced inodes after checkpoint.
328                  */
329                 try_to_fix_pino(inode);
330                 clear_inode_flag(inode, FI_APPEND_WRITE);
331                 clear_inode_flag(inode, FI_UPDATE_WRITE);
332                 goto out;
333         }
334 sync_nodes:
335         atomic_inc(&sbi->wb_sync_req[NODE]);
336         ret = f2fs_fsync_node_pages(sbi, inode, &wbc, atomic, &seq_id);
337         atomic_dec(&sbi->wb_sync_req[NODE]);
338         if (ret)
339                 goto out;
340
341         /* if cp_error was enabled, we should avoid infinite loop */
342         if (unlikely(f2fs_cp_error(sbi))) {
343                 ret = -EIO;
344                 goto out;
345         }
346
347         if (f2fs_need_inode_block_update(sbi, ino)) {
348                 f2fs_mark_inode_dirty_sync(inode, true);
349                 f2fs_write_inode(inode, NULL);
350                 goto sync_nodes;
351         }
352
353         /*
354          * If it's atomic_write, it's just fine to keep write ordering. So
355          * here we don't need to wait for node write completion, since we use
356          * node chain which serializes node blocks. If one of node writes are
357          * reordered, we can see simply broken chain, resulting in stopping
358          * roll-forward recovery. It means we'll recover all or none node blocks
359          * given fsync mark.
360          */
361         if (!atomic) {
362                 ret = f2fs_wait_on_node_pages_writeback(sbi, seq_id);
363                 if (ret)
364                         goto out;
365         }
366
367         /* once recovery info is written, don't need to tack this */
368         f2fs_remove_ino_entry(sbi, ino, APPEND_INO);
369         clear_inode_flag(inode, FI_APPEND_WRITE);
370 flush_out:
371         if ((!atomic && F2FS_OPTION(sbi).fsync_mode != FSYNC_MODE_NOBARRIER) ||
372             (atomic && !test_opt(sbi, NOBARRIER) && f2fs_sb_has_blkzoned(sbi)))
373                 ret = f2fs_issue_flush(sbi, inode->i_ino);
374         if (!ret) {
375                 f2fs_remove_ino_entry(sbi, ino, UPDATE_INO);
376                 clear_inode_flag(inode, FI_UPDATE_WRITE);
377                 f2fs_remove_ino_entry(sbi, ino, FLUSH_INO);
378         }
379         f2fs_update_time(sbi, REQ_TIME);
380 out:
381         trace_f2fs_sync_file_exit(inode, cp_reason, datasync, ret);
382         return ret;
383 }
384
385 int f2fs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
386 {
387         if (unlikely(f2fs_cp_error(F2FS_I_SB(file_inode(file)))))
388                 return -EIO;
389         return f2fs_do_sync_file(file, start, end, datasync, false);
390 }
391
392 static bool __found_offset(struct address_space *mapping, block_t blkaddr,
393                                 pgoff_t index, int whence)
394 {
395         switch (whence) {
396         case SEEK_DATA:
397                 if (__is_valid_data_blkaddr(blkaddr))
398                         return true;
399                 if (blkaddr == NEW_ADDR &&
400                     xa_get_mark(&mapping->i_pages, index, PAGECACHE_TAG_DIRTY))
401                         return true;
402                 break;
403         case SEEK_HOLE:
404                 if (blkaddr == NULL_ADDR)
405                         return true;
406                 break;
407         }
408         return false;
409 }
410
411 static loff_t f2fs_seek_block(struct file *file, loff_t offset, int whence)
412 {
413         struct inode *inode = file->f_mapping->host;
414         loff_t maxbytes = inode->i_sb->s_maxbytes;
415         struct dnode_of_data dn;
416         pgoff_t pgofs, end_offset;
417         loff_t data_ofs = offset;
418         loff_t isize;
419         int err = 0;
420
421         inode_lock(inode);
422
423         isize = i_size_read(inode);
424         if (offset >= isize)
425                 goto fail;
426
427         /* handle inline data case */
428         if (f2fs_has_inline_data(inode)) {
429                 if (whence == SEEK_HOLE) {
430                         data_ofs = isize;
431                         goto found;
432                 } else if (whence == SEEK_DATA) {
433                         data_ofs = offset;
434                         goto found;
435                 }
436         }
437
438         pgofs = (pgoff_t)(offset >> PAGE_SHIFT);
439
440         for (; data_ofs < isize; data_ofs = (loff_t)pgofs << PAGE_SHIFT) {
441                 set_new_dnode(&dn, inode, NULL, NULL, 0);
442                 err = f2fs_get_dnode_of_data(&dn, pgofs, LOOKUP_NODE);
443                 if (err && err != -ENOENT) {
444                         goto fail;
445                 } else if (err == -ENOENT) {
446                         /* direct node does not exists */
447                         if (whence == SEEK_DATA) {
448                                 pgofs = f2fs_get_next_page_offset(&dn, pgofs);
449                                 continue;
450                         } else {
451                                 goto found;
452                         }
453                 }
454
455                 end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
456
457                 /* find data/hole in dnode block */
458                 for (; dn.ofs_in_node < end_offset;
459                                 dn.ofs_in_node++, pgofs++,
460                                 data_ofs = (loff_t)pgofs << PAGE_SHIFT) {
461                         block_t blkaddr;
462
463                         blkaddr = f2fs_data_blkaddr(&dn);
464
465                         if (__is_valid_data_blkaddr(blkaddr) &&
466                                 !f2fs_is_valid_blkaddr(F2FS_I_SB(inode),
467                                         blkaddr, DATA_GENERIC_ENHANCE)) {
468                                 f2fs_put_dnode(&dn);
469                                 goto fail;
470                         }
471
472                         if (__found_offset(file->f_mapping, blkaddr,
473                                                         pgofs, whence)) {
474                                 f2fs_put_dnode(&dn);
475                                 goto found;
476                         }
477                 }
478                 f2fs_put_dnode(&dn);
479         }
480
481         if (whence == SEEK_DATA)
482                 goto fail;
483 found:
484         if (whence == SEEK_HOLE && data_ofs > isize)
485                 data_ofs = isize;
486         inode_unlock(inode);
487         return vfs_setpos(file, data_ofs, maxbytes);
488 fail:
489         inode_unlock(inode);
490         return -ENXIO;
491 }
492
493 static loff_t f2fs_llseek(struct file *file, loff_t offset, int whence)
494 {
495         struct inode *inode = file->f_mapping->host;
496         loff_t maxbytes = inode->i_sb->s_maxbytes;
497
498         if (f2fs_compressed_file(inode))
499                 maxbytes = max_file_blocks(inode) << F2FS_BLKSIZE_BITS;
500
501         switch (whence) {
502         case SEEK_SET:
503         case SEEK_CUR:
504         case SEEK_END:
505                 return generic_file_llseek_size(file, offset, whence,
506                                                 maxbytes, i_size_read(inode));
507         case SEEK_DATA:
508         case SEEK_HOLE:
509                 if (offset < 0)
510                         return -ENXIO;
511                 return f2fs_seek_block(file, offset, whence);
512         }
513
514         return -EINVAL;
515 }
516
517 static int f2fs_file_mmap(struct file *file, struct vm_area_struct *vma)
518 {
519         struct inode *inode = file_inode(file);
520
521         if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
522                 return -EIO;
523
524         if (!f2fs_is_compress_backend_ready(inode))
525                 return -EOPNOTSUPP;
526
527         file_accessed(file);
528         vma->vm_ops = &f2fs_file_vm_ops;
529         set_inode_flag(inode, FI_MMAP_FILE);
530         return 0;
531 }
532
533 static int f2fs_file_open(struct inode *inode, struct file *filp)
534 {
535         int err = fscrypt_file_open(inode, filp);
536
537         if (err)
538                 return err;
539
540         if (!f2fs_is_compress_backend_ready(inode))
541                 return -EOPNOTSUPP;
542
543         err = fsverity_file_open(inode, filp);
544         if (err)
545                 return err;
546
547         filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
548         filp->f_mode |= FMODE_CAN_ODIRECT;
549
550         return dquot_file_open(inode, filp);
551 }
552
553 void f2fs_truncate_data_blocks_range(struct dnode_of_data *dn, int count)
554 {
555         struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
556         struct f2fs_node *raw_node;
557         int nr_free = 0, ofs = dn->ofs_in_node, len = count;
558         __le32 *addr;
559         int base = 0;
560         bool compressed_cluster = false;
561         int cluster_index = 0, valid_blocks = 0;
562         int cluster_size = F2FS_I(dn->inode)->i_cluster_size;
563         bool released = !atomic_read(&F2FS_I(dn->inode)->i_compr_blocks);
564
565         if (IS_INODE(dn->node_page) && f2fs_has_extra_attr(dn->inode))
566                 base = get_extra_isize(dn->inode);
567
568         raw_node = F2FS_NODE(dn->node_page);
569         addr = blkaddr_in_node(raw_node) + base + ofs;
570
571         /* Assumption: truncation starts with cluster */
572         for (; count > 0; count--, addr++, dn->ofs_in_node++, cluster_index++) {
573                 block_t blkaddr = le32_to_cpu(*addr);
574
575                 if (f2fs_compressed_file(dn->inode) &&
576                                         !(cluster_index & (cluster_size - 1))) {
577                         if (compressed_cluster)
578                                 f2fs_i_compr_blocks_update(dn->inode,
579                                                         valid_blocks, false);
580                         compressed_cluster = (blkaddr == COMPRESS_ADDR);
581                         valid_blocks = 0;
582                 }
583
584                 if (blkaddr == NULL_ADDR)
585                         continue;
586
587                 dn->data_blkaddr = NULL_ADDR;
588                 f2fs_set_data_blkaddr(dn);
589
590                 if (__is_valid_data_blkaddr(blkaddr)) {
591                         if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
592                                         DATA_GENERIC_ENHANCE))
593                                 continue;
594                         if (compressed_cluster)
595                                 valid_blocks++;
596                 }
597
598                 if (dn->ofs_in_node == 0 && IS_INODE(dn->node_page))
599                         clear_inode_flag(dn->inode, FI_FIRST_BLOCK_WRITTEN);
600
601                 f2fs_invalidate_blocks(sbi, blkaddr);
602
603                 if (!released || blkaddr != COMPRESS_ADDR)
604                         nr_free++;
605         }
606
607         if (compressed_cluster)
608                 f2fs_i_compr_blocks_update(dn->inode, valid_blocks, false);
609
610         if (nr_free) {
611                 pgoff_t fofs;
612                 /*
613                  * once we invalidate valid blkaddr in range [ofs, ofs + count],
614                  * we will invalidate all blkaddr in the whole range.
615                  */
616                 fofs = f2fs_start_bidx_of_node(ofs_of_node(dn->node_page),
617                                                         dn->inode) + ofs;
618                 f2fs_update_read_extent_cache_range(dn, fofs, 0, len);
619                 f2fs_update_age_extent_cache_range(dn, fofs, len);
620                 dec_valid_block_count(sbi, dn->inode, nr_free);
621         }
622         dn->ofs_in_node = ofs;
623
624         f2fs_update_time(sbi, REQ_TIME);
625         trace_f2fs_truncate_data_blocks_range(dn->inode, dn->nid,
626                                          dn->ofs_in_node, nr_free);
627 }
628
629 static int truncate_partial_data_page(struct inode *inode, u64 from,
630                                                                 bool cache_only)
631 {
632         loff_t offset = from & (PAGE_SIZE - 1);
633         pgoff_t index = from >> PAGE_SHIFT;
634         struct address_space *mapping = inode->i_mapping;
635         struct page *page;
636
637         if (!offset && !cache_only)
638                 return 0;
639
640         if (cache_only) {
641                 page = find_lock_page(mapping, index);
642                 if (page && PageUptodate(page))
643                         goto truncate_out;
644                 f2fs_put_page(page, 1);
645                 return 0;
646         }
647
648         page = f2fs_get_lock_data_page(inode, index, true);
649         if (IS_ERR(page))
650                 return PTR_ERR(page) == -ENOENT ? 0 : PTR_ERR(page);
651 truncate_out:
652         f2fs_wait_on_page_writeback(page, DATA, true, true);
653         zero_user(page, offset, PAGE_SIZE - offset);
654
655         /* An encrypted inode should have a key and truncate the last page. */
656         f2fs_bug_on(F2FS_I_SB(inode), cache_only && IS_ENCRYPTED(inode));
657         if (!cache_only)
658                 set_page_dirty(page);
659         f2fs_put_page(page, 1);
660         return 0;
661 }
662
663 int f2fs_do_truncate_blocks(struct inode *inode, u64 from, bool lock)
664 {
665         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
666         struct dnode_of_data dn;
667         pgoff_t free_from;
668         int count = 0, err = 0;
669         struct page *ipage;
670         bool truncate_page = false;
671
672         trace_f2fs_truncate_blocks_enter(inode, from);
673
674         free_from = (pgoff_t)F2FS_BLK_ALIGN(from);
675
676         if (free_from >= max_file_blocks(inode))
677                 goto free_partial;
678
679         if (lock)
680                 f2fs_lock_op(sbi);
681
682         ipage = f2fs_get_node_page(sbi, inode->i_ino);
683         if (IS_ERR(ipage)) {
684                 err = PTR_ERR(ipage);
685                 goto out;
686         }
687
688         if (f2fs_has_inline_data(inode)) {
689                 f2fs_truncate_inline_inode(inode, ipage, from);
690                 f2fs_put_page(ipage, 1);
691                 truncate_page = true;
692                 goto out;
693         }
694
695         set_new_dnode(&dn, inode, ipage, NULL, 0);
696         err = f2fs_get_dnode_of_data(&dn, free_from, LOOKUP_NODE_RA);
697         if (err) {
698                 if (err == -ENOENT)
699                         goto free_next;
700                 goto out;
701         }
702
703         count = ADDRS_PER_PAGE(dn.node_page, inode);
704
705         count -= dn.ofs_in_node;
706         f2fs_bug_on(sbi, count < 0);
707
708         if (dn.ofs_in_node || IS_INODE(dn.node_page)) {
709                 f2fs_truncate_data_blocks_range(&dn, count);
710                 free_from += count;
711         }
712
713         f2fs_put_dnode(&dn);
714 free_next:
715         err = f2fs_truncate_inode_blocks(inode, free_from);
716 out:
717         if (lock)
718                 f2fs_unlock_op(sbi);
719 free_partial:
720         /* lastly zero out the first data page */
721         if (!err)
722                 err = truncate_partial_data_page(inode, from, truncate_page);
723
724         trace_f2fs_truncate_blocks_exit(inode, err);
725         return err;
726 }
727
728 int f2fs_truncate_blocks(struct inode *inode, u64 from, bool lock)
729 {
730         u64 free_from = from;
731         int err;
732
733 #ifdef CONFIG_F2FS_FS_COMPRESSION
734         /*
735          * for compressed file, only support cluster size
736          * aligned truncation.
737          */
738         if (f2fs_compressed_file(inode))
739                 free_from = round_up(from,
740                                 F2FS_I(inode)->i_cluster_size << PAGE_SHIFT);
741 #endif
742
743         err = f2fs_do_truncate_blocks(inode, free_from, lock);
744         if (err)
745                 return err;
746
747 #ifdef CONFIG_F2FS_FS_COMPRESSION
748         /*
749          * For compressed file, after release compress blocks, don't allow write
750          * direct, but we should allow write direct after truncate to zero.
751          */
752         if (f2fs_compressed_file(inode) && !free_from
753                         && is_inode_flag_set(inode, FI_COMPRESS_RELEASED))
754                 clear_inode_flag(inode, FI_COMPRESS_RELEASED);
755
756         if (from != free_from) {
757                 err = f2fs_truncate_partial_cluster(inode, from, lock);
758                 if (err)
759                         return err;
760         }
761 #endif
762
763         return 0;
764 }
765
766 int f2fs_truncate(struct inode *inode)
767 {
768         int err;
769
770         if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
771                 return -EIO;
772
773         if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
774                                 S_ISLNK(inode->i_mode)))
775                 return 0;
776
777         trace_f2fs_truncate(inode);
778
779         if (time_to_inject(F2FS_I_SB(inode), FAULT_TRUNCATE))
780                 return -EIO;
781
782         err = f2fs_dquot_initialize(inode);
783         if (err)
784                 return err;
785
786         /* we should check inline_data size */
787         if (!f2fs_may_inline_data(inode)) {
788                 err = f2fs_convert_inline_inode(inode);
789                 if (err)
790                         return err;
791         }
792
793         err = f2fs_truncate_blocks(inode, i_size_read(inode), true);
794         if (err)
795                 return err;
796
797         inode->i_mtime = inode->i_ctime = current_time(inode);
798         f2fs_mark_inode_dirty_sync(inode, false);
799         return 0;
800 }
801
802 static bool f2fs_force_buffered_io(struct inode *inode, int rw)
803 {
804         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
805
806         if (!fscrypt_dio_supported(inode))
807                 return true;
808         if (fsverity_active(inode))
809                 return true;
810         if (f2fs_compressed_file(inode))
811                 return true;
812
813         /* disallow direct IO if any of devices has unaligned blksize */
814         if (f2fs_is_multi_device(sbi) && !sbi->aligned_blksize)
815                 return true;
816         /*
817          * for blkzoned device, fallback direct IO to buffered IO, so
818          * all IOs can be serialized by log-structured write.
819          */
820         if (f2fs_sb_has_blkzoned(sbi) && (rw == WRITE))
821                 return true;
822         if (f2fs_lfs_mode(sbi) && rw == WRITE && F2FS_IO_ALIGNED(sbi))
823                 return true;
824         if (is_sbi_flag_set(sbi, SBI_CP_DISABLED))
825                 return true;
826
827         return false;
828 }
829
830 int f2fs_getattr(struct mnt_idmap *idmap, const struct path *path,
831                  struct kstat *stat, u32 request_mask, unsigned int query_flags)
832 {
833         struct inode *inode = d_inode(path->dentry);
834         struct f2fs_inode_info *fi = F2FS_I(inode);
835         struct f2fs_inode *ri = NULL;
836         unsigned int flags;
837
838         if (f2fs_has_extra_attr(inode) &&
839                         f2fs_sb_has_inode_crtime(F2FS_I_SB(inode)) &&
840                         F2FS_FITS_IN_INODE(ri, fi->i_extra_isize, i_crtime)) {
841                 stat->result_mask |= STATX_BTIME;
842                 stat->btime.tv_sec = fi->i_crtime.tv_sec;
843                 stat->btime.tv_nsec = fi->i_crtime.tv_nsec;
844         }
845
846         /*
847          * Return the DIO alignment restrictions if requested.  We only return
848          * this information when requested, since on encrypted files it might
849          * take a fair bit of work to get if the file wasn't opened recently.
850          *
851          * f2fs sometimes supports DIO reads but not DIO writes.  STATX_DIOALIGN
852          * cannot represent that, so in that case we report no DIO support.
853          */
854         if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
855                 unsigned int bsize = i_blocksize(inode);
856
857                 stat->result_mask |= STATX_DIOALIGN;
858                 if (!f2fs_force_buffered_io(inode, WRITE)) {
859                         stat->dio_mem_align = bsize;
860                         stat->dio_offset_align = bsize;
861                 }
862         }
863
864         flags = fi->i_flags;
865         if (flags & F2FS_COMPR_FL)
866                 stat->attributes |= STATX_ATTR_COMPRESSED;
867         if (flags & F2FS_APPEND_FL)
868                 stat->attributes |= STATX_ATTR_APPEND;
869         if (IS_ENCRYPTED(inode))
870                 stat->attributes |= STATX_ATTR_ENCRYPTED;
871         if (flags & F2FS_IMMUTABLE_FL)
872                 stat->attributes |= STATX_ATTR_IMMUTABLE;
873         if (flags & F2FS_NODUMP_FL)
874                 stat->attributes |= STATX_ATTR_NODUMP;
875         if (IS_VERITY(inode))
876                 stat->attributes |= STATX_ATTR_VERITY;
877
878         stat->attributes_mask |= (STATX_ATTR_COMPRESSED |
879                                   STATX_ATTR_APPEND |
880                                   STATX_ATTR_ENCRYPTED |
881                                   STATX_ATTR_IMMUTABLE |
882                                   STATX_ATTR_NODUMP |
883                                   STATX_ATTR_VERITY);
884
885         generic_fillattr(idmap, inode, stat);
886
887         /* we need to show initial sectors used for inline_data/dentries */
888         if ((S_ISREG(inode->i_mode) && f2fs_has_inline_data(inode)) ||
889                                         f2fs_has_inline_dentry(inode))
890                 stat->blocks += (stat->size + 511) >> 9;
891
892         return 0;
893 }
894
895 #ifdef CONFIG_F2FS_FS_POSIX_ACL
896 static void __setattr_copy(struct mnt_idmap *idmap,
897                            struct inode *inode, const struct iattr *attr)
898 {
899         unsigned int ia_valid = attr->ia_valid;
900
901         i_uid_update(idmap, attr, inode);
902         i_gid_update(idmap, attr, inode);
903         if (ia_valid & ATTR_ATIME)
904                 inode->i_atime = attr->ia_atime;
905         if (ia_valid & ATTR_MTIME)
906                 inode->i_mtime = attr->ia_mtime;
907         if (ia_valid & ATTR_CTIME)
908                 inode->i_ctime = attr->ia_ctime;
909         if (ia_valid & ATTR_MODE) {
910                 umode_t mode = attr->ia_mode;
911                 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
912
913                 if (!vfsgid_in_group_p(vfsgid) &&
914                     !capable_wrt_inode_uidgid(idmap, inode, CAP_FSETID))
915                         mode &= ~S_ISGID;
916                 set_acl_inode(inode, mode);
917         }
918 }
919 #else
920 #define __setattr_copy setattr_copy
921 #endif
922
923 int f2fs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
924                  struct iattr *attr)
925 {
926         struct inode *inode = d_inode(dentry);
927         int err;
928
929         if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
930                 return -EIO;
931
932         if (unlikely(IS_IMMUTABLE(inode)))
933                 return -EPERM;
934
935         if (unlikely(IS_APPEND(inode) &&
936                         (attr->ia_valid & (ATTR_MODE | ATTR_UID |
937                                   ATTR_GID | ATTR_TIMES_SET))))
938                 return -EPERM;
939
940         if ((attr->ia_valid & ATTR_SIZE) &&
941                 !f2fs_is_compress_backend_ready(inode))
942                 return -EOPNOTSUPP;
943
944         err = setattr_prepare(idmap, dentry, attr);
945         if (err)
946                 return err;
947
948         err = fscrypt_prepare_setattr(dentry, attr);
949         if (err)
950                 return err;
951
952         err = fsverity_prepare_setattr(dentry, attr);
953         if (err)
954                 return err;
955
956         if (is_quota_modification(idmap, inode, attr)) {
957                 err = f2fs_dquot_initialize(inode);
958                 if (err)
959                         return err;
960         }
961         if (i_uid_needs_update(idmap, attr, inode) ||
962             i_gid_needs_update(idmap, attr, inode)) {
963                 f2fs_lock_op(F2FS_I_SB(inode));
964                 err = dquot_transfer(idmap, inode, attr);
965                 if (err) {
966                         set_sbi_flag(F2FS_I_SB(inode),
967                                         SBI_QUOTA_NEED_REPAIR);
968                         f2fs_unlock_op(F2FS_I_SB(inode));
969                         return err;
970                 }
971                 /*
972                  * update uid/gid under lock_op(), so that dquot and inode can
973                  * be updated atomically.
974                  */
975                 i_uid_update(idmap, attr, inode);
976                 i_gid_update(idmap, attr, inode);
977                 f2fs_mark_inode_dirty_sync(inode, true);
978                 f2fs_unlock_op(F2FS_I_SB(inode));
979         }
980
981         if (attr->ia_valid & ATTR_SIZE) {
982                 loff_t old_size = i_size_read(inode);
983
984                 if (attr->ia_size > MAX_INLINE_DATA(inode)) {
985                         /*
986                          * should convert inline inode before i_size_write to
987                          * keep smaller than inline_data size with inline flag.
988                          */
989                         err = f2fs_convert_inline_inode(inode);
990                         if (err)
991                                 return err;
992                 }
993
994                 f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
995                 filemap_invalidate_lock(inode->i_mapping);
996
997                 truncate_setsize(inode, attr->ia_size);
998
999                 if (attr->ia_size <= old_size)
1000                         err = f2fs_truncate(inode);
1001                 /*
1002                  * do not trim all blocks after i_size if target size is
1003                  * larger than i_size.
1004                  */
1005                 filemap_invalidate_unlock(inode->i_mapping);
1006                 f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1007                 if (err)
1008                         return err;
1009
1010                 spin_lock(&F2FS_I(inode)->i_size_lock);
1011                 inode->i_mtime = inode->i_ctime = current_time(inode);
1012                 F2FS_I(inode)->last_disk_size = i_size_read(inode);
1013                 spin_unlock(&F2FS_I(inode)->i_size_lock);
1014         }
1015
1016         __setattr_copy(idmap, inode, attr);
1017
1018         if (attr->ia_valid & ATTR_MODE) {
1019                 err = posix_acl_chmod(idmap, dentry, f2fs_get_inode_mode(inode));
1020
1021                 if (is_inode_flag_set(inode, FI_ACL_MODE)) {
1022                         if (!err)
1023                                 inode->i_mode = F2FS_I(inode)->i_acl_mode;
1024                         clear_inode_flag(inode, FI_ACL_MODE);
1025                 }
1026         }
1027
1028         /* file size may changed here */
1029         f2fs_mark_inode_dirty_sync(inode, true);
1030
1031         /* inode change will produce dirty node pages flushed by checkpoint */
1032         f2fs_balance_fs(F2FS_I_SB(inode), true);
1033
1034         return err;
1035 }
1036
1037 const struct inode_operations f2fs_file_inode_operations = {
1038         .getattr        = f2fs_getattr,
1039         .setattr        = f2fs_setattr,
1040         .get_inode_acl  = f2fs_get_acl,
1041         .set_acl        = f2fs_set_acl,
1042         .listxattr      = f2fs_listxattr,
1043         .fiemap         = f2fs_fiemap,
1044         .fileattr_get   = f2fs_fileattr_get,
1045         .fileattr_set   = f2fs_fileattr_set,
1046 };
1047
1048 static int fill_zero(struct inode *inode, pgoff_t index,
1049                                         loff_t start, loff_t len)
1050 {
1051         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1052         struct page *page;
1053
1054         if (!len)
1055                 return 0;
1056
1057         f2fs_balance_fs(sbi, true);
1058
1059         f2fs_lock_op(sbi);
1060         page = f2fs_get_new_data_page(inode, NULL, index, false);
1061         f2fs_unlock_op(sbi);
1062
1063         if (IS_ERR(page))
1064                 return PTR_ERR(page);
1065
1066         f2fs_wait_on_page_writeback(page, DATA, true, true);
1067         zero_user(page, start, len);
1068         set_page_dirty(page);
1069         f2fs_put_page(page, 1);
1070         return 0;
1071 }
1072
1073 int f2fs_truncate_hole(struct inode *inode, pgoff_t pg_start, pgoff_t pg_end)
1074 {
1075         int err;
1076
1077         while (pg_start < pg_end) {
1078                 struct dnode_of_data dn;
1079                 pgoff_t end_offset, count;
1080
1081                 set_new_dnode(&dn, inode, NULL, NULL, 0);
1082                 err = f2fs_get_dnode_of_data(&dn, pg_start, LOOKUP_NODE);
1083                 if (err) {
1084                         if (err == -ENOENT) {
1085                                 pg_start = f2fs_get_next_page_offset(&dn,
1086                                                                 pg_start);
1087                                 continue;
1088                         }
1089                         return err;
1090                 }
1091
1092                 end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
1093                 count = min(end_offset - dn.ofs_in_node, pg_end - pg_start);
1094
1095                 f2fs_bug_on(F2FS_I_SB(inode), count == 0 || count > end_offset);
1096
1097                 f2fs_truncate_data_blocks_range(&dn, count);
1098                 f2fs_put_dnode(&dn);
1099
1100                 pg_start += count;
1101         }
1102         return 0;
1103 }
1104
1105 static int f2fs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
1106 {
1107         pgoff_t pg_start, pg_end;
1108         loff_t off_start, off_end;
1109         int ret;
1110
1111         ret = f2fs_convert_inline_inode(inode);
1112         if (ret)
1113                 return ret;
1114
1115         pg_start = ((unsigned long long) offset) >> PAGE_SHIFT;
1116         pg_end = ((unsigned long long) offset + len) >> PAGE_SHIFT;
1117
1118         off_start = offset & (PAGE_SIZE - 1);
1119         off_end = (offset + len) & (PAGE_SIZE - 1);
1120
1121         if (pg_start == pg_end) {
1122                 ret = fill_zero(inode, pg_start, off_start,
1123                                                 off_end - off_start);
1124                 if (ret)
1125                         return ret;
1126         } else {
1127                 if (off_start) {
1128                         ret = fill_zero(inode, pg_start++, off_start,
1129                                                 PAGE_SIZE - off_start);
1130                         if (ret)
1131                                 return ret;
1132                 }
1133                 if (off_end) {
1134                         ret = fill_zero(inode, pg_end, 0, off_end);
1135                         if (ret)
1136                                 return ret;
1137                 }
1138
1139                 if (pg_start < pg_end) {
1140                         loff_t blk_start, blk_end;
1141                         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1142
1143                         f2fs_balance_fs(sbi, true);
1144
1145                         blk_start = (loff_t)pg_start << PAGE_SHIFT;
1146                         blk_end = (loff_t)pg_end << PAGE_SHIFT;
1147
1148                         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1149                         filemap_invalidate_lock(inode->i_mapping);
1150
1151                         truncate_pagecache_range(inode, blk_start, blk_end - 1);
1152
1153                         f2fs_lock_op(sbi);
1154                         ret = f2fs_truncate_hole(inode, pg_start, pg_end);
1155                         f2fs_unlock_op(sbi);
1156
1157                         filemap_invalidate_unlock(inode->i_mapping);
1158                         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1159                 }
1160         }
1161
1162         return ret;
1163 }
1164
1165 static int __read_out_blkaddrs(struct inode *inode, block_t *blkaddr,
1166                                 int *do_replace, pgoff_t off, pgoff_t len)
1167 {
1168         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1169         struct dnode_of_data dn;
1170         int ret, done, i;
1171
1172 next_dnode:
1173         set_new_dnode(&dn, inode, NULL, NULL, 0);
1174         ret = f2fs_get_dnode_of_data(&dn, off, LOOKUP_NODE_RA);
1175         if (ret && ret != -ENOENT) {
1176                 return ret;
1177         } else if (ret == -ENOENT) {
1178                 if (dn.max_level == 0)
1179                         return -ENOENT;
1180                 done = min((pgoff_t)ADDRS_PER_BLOCK(inode) -
1181                                                 dn.ofs_in_node, len);
1182                 blkaddr += done;
1183                 do_replace += done;
1184                 goto next;
1185         }
1186
1187         done = min((pgoff_t)ADDRS_PER_PAGE(dn.node_page, inode) -
1188                                                         dn.ofs_in_node, len);
1189         for (i = 0; i < done; i++, blkaddr++, do_replace++, dn.ofs_in_node++) {
1190                 *blkaddr = f2fs_data_blkaddr(&dn);
1191
1192                 if (__is_valid_data_blkaddr(*blkaddr) &&
1193                         !f2fs_is_valid_blkaddr(sbi, *blkaddr,
1194                                         DATA_GENERIC_ENHANCE)) {
1195                         f2fs_put_dnode(&dn);
1196                         f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
1197                         return -EFSCORRUPTED;
1198                 }
1199
1200                 if (!f2fs_is_checkpointed_data(sbi, *blkaddr)) {
1201
1202                         if (f2fs_lfs_mode(sbi)) {
1203                                 f2fs_put_dnode(&dn);
1204                                 return -EOPNOTSUPP;
1205                         }
1206
1207                         /* do not invalidate this block address */
1208                         f2fs_update_data_blkaddr(&dn, NULL_ADDR);
1209                         *do_replace = 1;
1210                 }
1211         }
1212         f2fs_put_dnode(&dn);
1213 next:
1214         len -= done;
1215         off += done;
1216         if (len)
1217                 goto next_dnode;
1218         return 0;
1219 }
1220
1221 static int __roll_back_blkaddrs(struct inode *inode, block_t *blkaddr,
1222                                 int *do_replace, pgoff_t off, int len)
1223 {
1224         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1225         struct dnode_of_data dn;
1226         int ret, i;
1227
1228         for (i = 0; i < len; i++, do_replace++, blkaddr++) {
1229                 if (*do_replace == 0)
1230                         continue;
1231
1232                 set_new_dnode(&dn, inode, NULL, NULL, 0);
1233                 ret = f2fs_get_dnode_of_data(&dn, off + i, LOOKUP_NODE_RA);
1234                 if (ret) {
1235                         dec_valid_block_count(sbi, inode, 1);
1236                         f2fs_invalidate_blocks(sbi, *blkaddr);
1237                 } else {
1238                         f2fs_update_data_blkaddr(&dn, *blkaddr);
1239                 }
1240                 f2fs_put_dnode(&dn);
1241         }
1242         return 0;
1243 }
1244
1245 static int __clone_blkaddrs(struct inode *src_inode, struct inode *dst_inode,
1246                         block_t *blkaddr, int *do_replace,
1247                         pgoff_t src, pgoff_t dst, pgoff_t len, bool full)
1248 {
1249         struct f2fs_sb_info *sbi = F2FS_I_SB(src_inode);
1250         pgoff_t i = 0;
1251         int ret;
1252
1253         while (i < len) {
1254                 if (blkaddr[i] == NULL_ADDR && !full) {
1255                         i++;
1256                         continue;
1257                 }
1258
1259                 if (do_replace[i] || blkaddr[i] == NULL_ADDR) {
1260                         struct dnode_of_data dn;
1261                         struct node_info ni;
1262                         size_t new_size;
1263                         pgoff_t ilen;
1264
1265                         set_new_dnode(&dn, dst_inode, NULL, NULL, 0);
1266                         ret = f2fs_get_dnode_of_data(&dn, dst + i, ALLOC_NODE);
1267                         if (ret)
1268                                 return ret;
1269
1270                         ret = f2fs_get_node_info(sbi, dn.nid, &ni, false);
1271                         if (ret) {
1272                                 f2fs_put_dnode(&dn);
1273                                 return ret;
1274                         }
1275
1276                         ilen = min((pgoff_t)
1277                                 ADDRS_PER_PAGE(dn.node_page, dst_inode) -
1278                                                 dn.ofs_in_node, len - i);
1279                         do {
1280                                 dn.data_blkaddr = f2fs_data_blkaddr(&dn);
1281                                 f2fs_truncate_data_blocks_range(&dn, 1);
1282
1283                                 if (do_replace[i]) {
1284                                         f2fs_i_blocks_write(src_inode,
1285                                                         1, false, false);
1286                                         f2fs_i_blocks_write(dst_inode,
1287                                                         1, true, false);
1288                                         f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
1289                                         blkaddr[i], ni.version, true, false);
1290
1291                                         do_replace[i] = 0;
1292                                 }
1293                                 dn.ofs_in_node++;
1294                                 i++;
1295                                 new_size = (loff_t)(dst + i) << PAGE_SHIFT;
1296                                 if (dst_inode->i_size < new_size)
1297                                         f2fs_i_size_write(dst_inode, new_size);
1298                         } while (--ilen && (do_replace[i] || blkaddr[i] == NULL_ADDR));
1299
1300                         f2fs_put_dnode(&dn);
1301                 } else {
1302                         struct page *psrc, *pdst;
1303
1304                         psrc = f2fs_get_lock_data_page(src_inode,
1305                                                         src + i, true);
1306                         if (IS_ERR(psrc))
1307                                 return PTR_ERR(psrc);
1308                         pdst = f2fs_get_new_data_page(dst_inode, NULL, dst + i,
1309                                                                 true);
1310                         if (IS_ERR(pdst)) {
1311                                 f2fs_put_page(psrc, 1);
1312                                 return PTR_ERR(pdst);
1313                         }
1314                         memcpy_page(pdst, 0, psrc, 0, PAGE_SIZE);
1315                         set_page_dirty(pdst);
1316                         f2fs_put_page(pdst, 1);
1317                         f2fs_put_page(psrc, 1);
1318
1319                         ret = f2fs_truncate_hole(src_inode,
1320                                                 src + i, src + i + 1);
1321                         if (ret)
1322                                 return ret;
1323                         i++;
1324                 }
1325         }
1326         return 0;
1327 }
1328
1329 static int __exchange_data_block(struct inode *src_inode,
1330                         struct inode *dst_inode, pgoff_t src, pgoff_t dst,
1331                         pgoff_t len, bool full)
1332 {
1333         block_t *src_blkaddr;
1334         int *do_replace;
1335         pgoff_t olen;
1336         int ret;
1337
1338         while (len) {
1339                 olen = min((pgoff_t)4 * ADDRS_PER_BLOCK(src_inode), len);
1340
1341                 src_blkaddr = f2fs_kvzalloc(F2FS_I_SB(src_inode),
1342                                         array_size(olen, sizeof(block_t)),
1343                                         GFP_NOFS);
1344                 if (!src_blkaddr)
1345                         return -ENOMEM;
1346
1347                 do_replace = f2fs_kvzalloc(F2FS_I_SB(src_inode),
1348                                         array_size(olen, sizeof(int)),
1349                                         GFP_NOFS);
1350                 if (!do_replace) {
1351                         kvfree(src_blkaddr);
1352                         return -ENOMEM;
1353                 }
1354
1355                 ret = __read_out_blkaddrs(src_inode, src_blkaddr,
1356                                         do_replace, src, olen);
1357                 if (ret)
1358                         goto roll_back;
1359
1360                 ret = __clone_blkaddrs(src_inode, dst_inode, src_blkaddr,
1361                                         do_replace, src, dst, olen, full);
1362                 if (ret)
1363                         goto roll_back;
1364
1365                 src += olen;
1366                 dst += olen;
1367                 len -= olen;
1368
1369                 kvfree(src_blkaddr);
1370                 kvfree(do_replace);
1371         }
1372         return 0;
1373
1374 roll_back:
1375         __roll_back_blkaddrs(src_inode, src_blkaddr, do_replace, src, olen);
1376         kvfree(src_blkaddr);
1377         kvfree(do_replace);
1378         return ret;
1379 }
1380
1381 static int f2fs_do_collapse(struct inode *inode, loff_t offset, loff_t len)
1382 {
1383         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1384         pgoff_t nrpages = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
1385         pgoff_t start = offset >> PAGE_SHIFT;
1386         pgoff_t end = (offset + len) >> PAGE_SHIFT;
1387         int ret;
1388
1389         f2fs_balance_fs(sbi, true);
1390
1391         /* avoid gc operation during block exchange */
1392         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1393         filemap_invalidate_lock(inode->i_mapping);
1394
1395         f2fs_lock_op(sbi);
1396         f2fs_drop_extent_tree(inode);
1397         truncate_pagecache(inode, offset);
1398         ret = __exchange_data_block(inode, inode, end, start, nrpages - end, true);
1399         f2fs_unlock_op(sbi);
1400
1401         filemap_invalidate_unlock(inode->i_mapping);
1402         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1403         return ret;
1404 }
1405
1406 static int f2fs_collapse_range(struct inode *inode, loff_t offset, loff_t len)
1407 {
1408         loff_t new_size;
1409         int ret;
1410
1411         if (offset + len >= i_size_read(inode))
1412                 return -EINVAL;
1413
1414         /* collapse range should be aligned to block size of f2fs. */
1415         if (offset & (F2FS_BLKSIZE - 1) || len & (F2FS_BLKSIZE - 1))
1416                 return -EINVAL;
1417
1418         ret = f2fs_convert_inline_inode(inode);
1419         if (ret)
1420                 return ret;
1421
1422         /* write out all dirty pages from offset */
1423         ret = filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
1424         if (ret)
1425                 return ret;
1426
1427         ret = f2fs_do_collapse(inode, offset, len);
1428         if (ret)
1429                 return ret;
1430
1431         /* write out all moved pages, if possible */
1432         filemap_invalidate_lock(inode->i_mapping);
1433         filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
1434         truncate_pagecache(inode, offset);
1435
1436         new_size = i_size_read(inode) - len;
1437         ret = f2fs_truncate_blocks(inode, new_size, true);
1438         filemap_invalidate_unlock(inode->i_mapping);
1439         if (!ret)
1440                 f2fs_i_size_write(inode, new_size);
1441         return ret;
1442 }
1443
1444 static int f2fs_do_zero_range(struct dnode_of_data *dn, pgoff_t start,
1445                                                                 pgoff_t end)
1446 {
1447         struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1448         pgoff_t index = start;
1449         unsigned int ofs_in_node = dn->ofs_in_node;
1450         blkcnt_t count = 0;
1451         int ret;
1452
1453         for (; index < end; index++, dn->ofs_in_node++) {
1454                 if (f2fs_data_blkaddr(dn) == NULL_ADDR)
1455                         count++;
1456         }
1457
1458         dn->ofs_in_node = ofs_in_node;
1459         ret = f2fs_reserve_new_blocks(dn, count);
1460         if (ret)
1461                 return ret;
1462
1463         dn->ofs_in_node = ofs_in_node;
1464         for (index = start; index < end; index++, dn->ofs_in_node++) {
1465                 dn->data_blkaddr = f2fs_data_blkaddr(dn);
1466                 /*
1467                  * f2fs_reserve_new_blocks will not guarantee entire block
1468                  * allocation.
1469                  */
1470                 if (dn->data_blkaddr == NULL_ADDR) {
1471                         ret = -ENOSPC;
1472                         break;
1473                 }
1474
1475                 if (dn->data_blkaddr == NEW_ADDR)
1476                         continue;
1477
1478                 if (!f2fs_is_valid_blkaddr(sbi, dn->data_blkaddr,
1479                                         DATA_GENERIC_ENHANCE)) {
1480                         ret = -EFSCORRUPTED;
1481                         f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
1482                         break;
1483                 }
1484
1485                 f2fs_invalidate_blocks(sbi, dn->data_blkaddr);
1486                 dn->data_blkaddr = NEW_ADDR;
1487                 f2fs_set_data_blkaddr(dn);
1488         }
1489
1490         f2fs_update_read_extent_cache_range(dn, start, 0, index - start);
1491         f2fs_update_age_extent_cache_range(dn, start, index - start);
1492
1493         return ret;
1494 }
1495
1496 static int f2fs_zero_range(struct inode *inode, loff_t offset, loff_t len,
1497                                                                 int mode)
1498 {
1499         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1500         struct address_space *mapping = inode->i_mapping;
1501         pgoff_t index, pg_start, pg_end;
1502         loff_t new_size = i_size_read(inode);
1503         loff_t off_start, off_end;
1504         int ret = 0;
1505
1506         ret = inode_newsize_ok(inode, (len + offset));
1507         if (ret)
1508                 return ret;
1509
1510         ret = f2fs_convert_inline_inode(inode);
1511         if (ret)
1512                 return ret;
1513
1514         ret = filemap_write_and_wait_range(mapping, offset, offset + len - 1);
1515         if (ret)
1516                 return ret;
1517
1518         pg_start = ((unsigned long long) offset) >> PAGE_SHIFT;
1519         pg_end = ((unsigned long long) offset + len) >> PAGE_SHIFT;
1520
1521         off_start = offset & (PAGE_SIZE - 1);
1522         off_end = (offset + len) & (PAGE_SIZE - 1);
1523
1524         if (pg_start == pg_end) {
1525                 ret = fill_zero(inode, pg_start, off_start,
1526                                                 off_end - off_start);
1527                 if (ret)
1528                         return ret;
1529
1530                 new_size = max_t(loff_t, new_size, offset + len);
1531         } else {
1532                 if (off_start) {
1533                         ret = fill_zero(inode, pg_start++, off_start,
1534                                                 PAGE_SIZE - off_start);
1535                         if (ret)
1536                                 return ret;
1537
1538                         new_size = max_t(loff_t, new_size,
1539                                         (loff_t)pg_start << PAGE_SHIFT);
1540                 }
1541
1542                 for (index = pg_start; index < pg_end;) {
1543                         struct dnode_of_data dn;
1544                         unsigned int end_offset;
1545                         pgoff_t end;
1546
1547                         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1548                         filemap_invalidate_lock(mapping);
1549
1550                         truncate_pagecache_range(inode,
1551                                 (loff_t)index << PAGE_SHIFT,
1552                                 ((loff_t)pg_end << PAGE_SHIFT) - 1);
1553
1554                         f2fs_lock_op(sbi);
1555
1556                         set_new_dnode(&dn, inode, NULL, NULL, 0);
1557                         ret = f2fs_get_dnode_of_data(&dn, index, ALLOC_NODE);
1558                         if (ret) {
1559                                 f2fs_unlock_op(sbi);
1560                                 filemap_invalidate_unlock(mapping);
1561                                 f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1562                                 goto out;
1563                         }
1564
1565                         end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
1566                         end = min(pg_end, end_offset - dn.ofs_in_node + index);
1567
1568                         ret = f2fs_do_zero_range(&dn, index, end);
1569                         f2fs_put_dnode(&dn);
1570
1571                         f2fs_unlock_op(sbi);
1572                         filemap_invalidate_unlock(mapping);
1573                         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1574
1575                         f2fs_balance_fs(sbi, dn.node_changed);
1576
1577                         if (ret)
1578                                 goto out;
1579
1580                         index = end;
1581                         new_size = max_t(loff_t, new_size,
1582                                         (loff_t)index << PAGE_SHIFT);
1583                 }
1584
1585                 if (off_end) {
1586                         ret = fill_zero(inode, pg_end, 0, off_end);
1587                         if (ret)
1588                                 goto out;
1589
1590                         new_size = max_t(loff_t, new_size, offset + len);
1591                 }
1592         }
1593
1594 out:
1595         if (new_size > i_size_read(inode)) {
1596                 if (mode & FALLOC_FL_KEEP_SIZE)
1597                         file_set_keep_isize(inode);
1598                 else
1599                         f2fs_i_size_write(inode, new_size);
1600         }
1601         return ret;
1602 }
1603
1604 static int f2fs_insert_range(struct inode *inode, loff_t offset, loff_t len)
1605 {
1606         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1607         struct address_space *mapping = inode->i_mapping;
1608         pgoff_t nr, pg_start, pg_end, delta, idx;
1609         loff_t new_size;
1610         int ret = 0;
1611
1612         new_size = i_size_read(inode) + len;
1613         ret = inode_newsize_ok(inode, new_size);
1614         if (ret)
1615                 return ret;
1616
1617         if (offset >= i_size_read(inode))
1618                 return -EINVAL;
1619
1620         /* insert range should be aligned to block size of f2fs. */
1621         if (offset & (F2FS_BLKSIZE - 1) || len & (F2FS_BLKSIZE - 1))
1622                 return -EINVAL;
1623
1624         ret = f2fs_convert_inline_inode(inode);
1625         if (ret)
1626                 return ret;
1627
1628         f2fs_balance_fs(sbi, true);
1629
1630         filemap_invalidate_lock(mapping);
1631         ret = f2fs_truncate_blocks(inode, i_size_read(inode), true);
1632         filemap_invalidate_unlock(mapping);
1633         if (ret)
1634                 return ret;
1635
1636         /* write out all dirty pages from offset */
1637         ret = filemap_write_and_wait_range(mapping, offset, LLONG_MAX);
1638         if (ret)
1639                 return ret;
1640
1641         pg_start = offset >> PAGE_SHIFT;
1642         pg_end = (offset + len) >> PAGE_SHIFT;
1643         delta = pg_end - pg_start;
1644         idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
1645
1646         /* avoid gc operation during block exchange */
1647         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1648         filemap_invalidate_lock(mapping);
1649         truncate_pagecache(inode, offset);
1650
1651         while (!ret && idx > pg_start) {
1652                 nr = idx - pg_start;
1653                 if (nr > delta)
1654                         nr = delta;
1655                 idx -= nr;
1656
1657                 f2fs_lock_op(sbi);
1658                 f2fs_drop_extent_tree(inode);
1659
1660                 ret = __exchange_data_block(inode, inode, idx,
1661                                         idx + delta, nr, false);
1662                 f2fs_unlock_op(sbi);
1663         }
1664         filemap_invalidate_unlock(mapping);
1665         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1666
1667         /* write out all moved pages, if possible */
1668         filemap_invalidate_lock(mapping);
1669         filemap_write_and_wait_range(mapping, offset, LLONG_MAX);
1670         truncate_pagecache(inode, offset);
1671         filemap_invalidate_unlock(mapping);
1672
1673         if (!ret)
1674                 f2fs_i_size_write(inode, new_size);
1675         return ret;
1676 }
1677
1678 static int f2fs_expand_inode_data(struct inode *inode, loff_t offset,
1679                                         loff_t len, int mode)
1680 {
1681         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1682         struct f2fs_map_blocks map = { .m_next_pgofs = NULL,
1683                         .m_next_extent = NULL, .m_seg_type = NO_CHECK_TYPE,
1684                         .m_may_create = true };
1685         struct f2fs_gc_control gc_control = { .victim_segno = NULL_SEGNO,
1686                         .init_gc_type = FG_GC,
1687                         .should_migrate_blocks = false,
1688                         .err_gc_skipped = true,
1689                         .nr_free_secs = 0 };
1690         pgoff_t pg_start, pg_end;
1691         loff_t new_size;
1692         loff_t off_end;
1693         block_t expanded = 0;
1694         int err;
1695
1696         err = inode_newsize_ok(inode, (len + offset));
1697         if (err)
1698                 return err;
1699
1700         err = f2fs_convert_inline_inode(inode);
1701         if (err)
1702                 return err;
1703
1704         f2fs_balance_fs(sbi, true);
1705
1706         pg_start = ((unsigned long long)offset) >> PAGE_SHIFT;
1707         pg_end = ((unsigned long long)offset + len) >> PAGE_SHIFT;
1708         off_end = (offset + len) & (PAGE_SIZE - 1);
1709
1710         map.m_lblk = pg_start;
1711         map.m_len = pg_end - pg_start;
1712         if (off_end)
1713                 map.m_len++;
1714
1715         if (!map.m_len)
1716                 return 0;
1717
1718         if (f2fs_is_pinned_file(inode)) {
1719                 block_t sec_blks = CAP_BLKS_PER_SEC(sbi);
1720                 block_t sec_len = roundup(map.m_len, sec_blks);
1721
1722                 map.m_len = sec_blks;
1723 next_alloc:
1724                 if (has_not_enough_free_secs(sbi, 0,
1725                         GET_SEC_FROM_SEG(sbi, overprovision_segments(sbi)))) {
1726                         f2fs_down_write(&sbi->gc_lock);
1727                         err = f2fs_gc(sbi, &gc_control);
1728                         if (err && err != -ENODATA)
1729                                 goto out_err;
1730                 }
1731
1732                 f2fs_down_write(&sbi->pin_sem);
1733
1734                 f2fs_lock_op(sbi);
1735                 f2fs_allocate_new_section(sbi, CURSEG_COLD_DATA_PINNED, false);
1736                 f2fs_unlock_op(sbi);
1737
1738                 map.m_seg_type = CURSEG_COLD_DATA_PINNED;
1739                 err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_PRE_DIO);
1740                 file_dont_truncate(inode);
1741
1742                 f2fs_up_write(&sbi->pin_sem);
1743
1744                 expanded += map.m_len;
1745                 sec_len -= map.m_len;
1746                 map.m_lblk += map.m_len;
1747                 if (!err && sec_len)
1748                         goto next_alloc;
1749
1750                 map.m_len = expanded;
1751         } else {
1752                 err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_PRE_AIO);
1753                 expanded = map.m_len;
1754         }
1755 out_err:
1756         if (err) {
1757                 pgoff_t last_off;
1758
1759                 if (!expanded)
1760                         return err;
1761
1762                 last_off = pg_start + expanded - 1;
1763
1764                 /* update new size to the failed position */
1765                 new_size = (last_off == pg_end) ? offset + len :
1766                                         (loff_t)(last_off + 1) << PAGE_SHIFT;
1767         } else {
1768                 new_size = ((loff_t)pg_end << PAGE_SHIFT) + off_end;
1769         }
1770
1771         if (new_size > i_size_read(inode)) {
1772                 if (mode & FALLOC_FL_KEEP_SIZE)
1773                         file_set_keep_isize(inode);
1774                 else
1775                         f2fs_i_size_write(inode, new_size);
1776         }
1777
1778         return err;
1779 }
1780
1781 static long f2fs_fallocate(struct file *file, int mode,
1782                                 loff_t offset, loff_t len)
1783 {
1784         struct inode *inode = file_inode(file);
1785         long ret = 0;
1786
1787         if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
1788                 return -EIO;
1789         if (!f2fs_is_checkpoint_ready(F2FS_I_SB(inode)))
1790                 return -ENOSPC;
1791         if (!f2fs_is_compress_backend_ready(inode))
1792                 return -EOPNOTSUPP;
1793
1794         /* f2fs only support ->fallocate for regular file */
1795         if (!S_ISREG(inode->i_mode))
1796                 return -EINVAL;
1797
1798         if (IS_ENCRYPTED(inode) &&
1799                 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
1800                 return -EOPNOTSUPP;
1801
1802         /*
1803          * Pinned file should not support partial truncation since the block
1804          * can be used by applications.
1805          */
1806         if ((f2fs_compressed_file(inode) || f2fs_is_pinned_file(inode)) &&
1807                 (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_COLLAPSE_RANGE |
1808                         FALLOC_FL_ZERO_RANGE | FALLOC_FL_INSERT_RANGE)))
1809                 return -EOPNOTSUPP;
1810
1811         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
1812                         FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
1813                         FALLOC_FL_INSERT_RANGE))
1814                 return -EOPNOTSUPP;
1815
1816         inode_lock(inode);
1817
1818         ret = file_modified(file);
1819         if (ret)
1820                 goto out;
1821
1822         if (mode & FALLOC_FL_PUNCH_HOLE) {
1823                 if (offset >= inode->i_size)
1824                         goto out;
1825
1826                 ret = f2fs_punch_hole(inode, offset, len);
1827         } else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
1828                 ret = f2fs_collapse_range(inode, offset, len);
1829         } else if (mode & FALLOC_FL_ZERO_RANGE) {
1830                 ret = f2fs_zero_range(inode, offset, len, mode);
1831         } else if (mode & FALLOC_FL_INSERT_RANGE) {
1832                 ret = f2fs_insert_range(inode, offset, len);
1833         } else {
1834                 ret = f2fs_expand_inode_data(inode, offset, len, mode);
1835         }
1836
1837         if (!ret) {
1838                 inode->i_mtime = inode->i_ctime = current_time(inode);
1839                 f2fs_mark_inode_dirty_sync(inode, false);
1840                 f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1841         }
1842
1843 out:
1844         inode_unlock(inode);
1845
1846         trace_f2fs_fallocate(inode, mode, offset, len, ret);
1847         return ret;
1848 }
1849
1850 static int f2fs_release_file(struct inode *inode, struct file *filp)
1851 {
1852         /*
1853          * f2fs_release_file is called at every close calls. So we should
1854          * not drop any inmemory pages by close called by other process.
1855          */
1856         if (!(filp->f_mode & FMODE_WRITE) ||
1857                         atomic_read(&inode->i_writecount) != 1)
1858                 return 0;
1859
1860         inode_lock(inode);
1861         f2fs_abort_atomic_write(inode, true);
1862         inode_unlock(inode);
1863
1864         return 0;
1865 }
1866
1867 static int f2fs_file_flush(struct file *file, fl_owner_t id)
1868 {
1869         struct inode *inode = file_inode(file);
1870
1871         /*
1872          * If the process doing a transaction is crashed, we should do
1873          * roll-back. Otherwise, other reader/write can see corrupted database
1874          * until all the writers close its file. Since this should be done
1875          * before dropping file lock, it needs to do in ->flush.
1876          */
1877         if (F2FS_I(inode)->atomic_write_task == current &&
1878                                 (current->flags & PF_EXITING)) {
1879                 inode_lock(inode);
1880                 f2fs_abort_atomic_write(inode, true);
1881                 inode_unlock(inode);
1882         }
1883
1884         return 0;
1885 }
1886
1887 static int f2fs_setflags_common(struct inode *inode, u32 iflags, u32 mask)
1888 {
1889         struct f2fs_inode_info *fi = F2FS_I(inode);
1890         u32 masked_flags = fi->i_flags & mask;
1891
1892         /* mask can be shrunk by flags_valid selector */
1893         iflags &= mask;
1894
1895         /* Is it quota file? Do not allow user to mess with it */
1896         if (IS_NOQUOTA(inode))
1897                 return -EPERM;
1898
1899         if ((iflags ^ masked_flags) & F2FS_CASEFOLD_FL) {
1900                 if (!f2fs_sb_has_casefold(F2FS_I_SB(inode)))
1901                         return -EOPNOTSUPP;
1902                 if (!f2fs_empty_dir(inode))
1903                         return -ENOTEMPTY;
1904         }
1905
1906         if (iflags & (F2FS_COMPR_FL | F2FS_NOCOMP_FL)) {
1907                 if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
1908                         return -EOPNOTSUPP;
1909                 if ((iflags & F2FS_COMPR_FL) && (iflags & F2FS_NOCOMP_FL))
1910                         return -EINVAL;
1911         }
1912
1913         if ((iflags ^ masked_flags) & F2FS_COMPR_FL) {
1914                 if (masked_flags & F2FS_COMPR_FL) {
1915                         if (!f2fs_disable_compressed_file(inode))
1916                                 return -EINVAL;
1917                 } else {
1918                         /* try to convert inline_data to support compression */
1919                         int err = f2fs_convert_inline_inode(inode);
1920                         if (err)
1921                                 return err;
1922                         if (!f2fs_may_compress(inode))
1923                                 return -EINVAL;
1924                         if (S_ISREG(inode->i_mode) && F2FS_HAS_BLOCKS(inode))
1925                                 return -EINVAL;
1926                         if (set_compress_context(inode))
1927                                 return -EOPNOTSUPP;
1928                 }
1929         }
1930
1931         fi->i_flags = iflags | (fi->i_flags & ~mask);
1932         f2fs_bug_on(F2FS_I_SB(inode), (fi->i_flags & F2FS_COMPR_FL) &&
1933                                         (fi->i_flags & F2FS_NOCOMP_FL));
1934
1935         if (fi->i_flags & F2FS_PROJINHERIT_FL)
1936                 set_inode_flag(inode, FI_PROJ_INHERIT);
1937         else
1938                 clear_inode_flag(inode, FI_PROJ_INHERIT);
1939
1940         inode->i_ctime = current_time(inode);
1941         f2fs_set_inode_flags(inode);
1942         f2fs_mark_inode_dirty_sync(inode, true);
1943         return 0;
1944 }
1945
1946 /* FS_IOC_[GS]ETFLAGS and FS_IOC_FS[GS]ETXATTR support */
1947
1948 /*
1949  * To make a new on-disk f2fs i_flag gettable via FS_IOC_GETFLAGS, add an entry
1950  * for it to f2fs_fsflags_map[], and add its FS_*_FL equivalent to
1951  * F2FS_GETTABLE_FS_FL.  To also make it settable via FS_IOC_SETFLAGS, also add
1952  * its FS_*_FL equivalent to F2FS_SETTABLE_FS_FL.
1953  *
1954  * Translating flags to fsx_flags value used by FS_IOC_FSGETXATTR and
1955  * FS_IOC_FSSETXATTR is done by the VFS.
1956  */
1957
1958 static const struct {
1959         u32 iflag;
1960         u32 fsflag;
1961 } f2fs_fsflags_map[] = {
1962         { F2FS_COMPR_FL,        FS_COMPR_FL },
1963         { F2FS_SYNC_FL,         FS_SYNC_FL },
1964         { F2FS_IMMUTABLE_FL,    FS_IMMUTABLE_FL },
1965         { F2FS_APPEND_FL,       FS_APPEND_FL },
1966         { F2FS_NODUMP_FL,       FS_NODUMP_FL },
1967         { F2FS_NOATIME_FL,      FS_NOATIME_FL },
1968         { F2FS_NOCOMP_FL,       FS_NOCOMP_FL },
1969         { F2FS_INDEX_FL,        FS_INDEX_FL },
1970         { F2FS_DIRSYNC_FL,      FS_DIRSYNC_FL },
1971         { F2FS_PROJINHERIT_FL,  FS_PROJINHERIT_FL },
1972         { F2FS_CASEFOLD_FL,     FS_CASEFOLD_FL },
1973 };
1974
1975 #define F2FS_GETTABLE_FS_FL (           \
1976                 FS_COMPR_FL |           \
1977                 FS_SYNC_FL |            \
1978                 FS_IMMUTABLE_FL |       \
1979                 FS_APPEND_FL |          \
1980                 FS_NODUMP_FL |          \
1981                 FS_NOATIME_FL |         \
1982                 FS_NOCOMP_FL |          \
1983                 FS_INDEX_FL |           \
1984                 FS_DIRSYNC_FL |         \
1985                 FS_PROJINHERIT_FL |     \
1986                 FS_ENCRYPT_FL |         \
1987                 FS_INLINE_DATA_FL |     \
1988                 FS_NOCOW_FL |           \
1989                 FS_VERITY_FL |          \
1990                 FS_CASEFOLD_FL)
1991
1992 #define F2FS_SETTABLE_FS_FL (           \
1993                 FS_COMPR_FL |           \
1994                 FS_SYNC_FL |            \
1995                 FS_IMMUTABLE_FL |       \
1996                 FS_APPEND_FL |          \
1997                 FS_NODUMP_FL |          \
1998                 FS_NOATIME_FL |         \
1999                 FS_NOCOMP_FL |          \
2000                 FS_DIRSYNC_FL |         \
2001                 FS_PROJINHERIT_FL |     \
2002                 FS_CASEFOLD_FL)
2003
2004 /* Convert f2fs on-disk i_flags to FS_IOC_{GET,SET}FLAGS flags */
2005 static inline u32 f2fs_iflags_to_fsflags(u32 iflags)
2006 {
2007         u32 fsflags = 0;
2008         int i;
2009
2010         for (i = 0; i < ARRAY_SIZE(f2fs_fsflags_map); i++)
2011                 if (iflags & f2fs_fsflags_map[i].iflag)
2012                         fsflags |= f2fs_fsflags_map[i].fsflag;
2013
2014         return fsflags;
2015 }
2016
2017 /* Convert FS_IOC_{GET,SET}FLAGS flags to f2fs on-disk i_flags */
2018 static inline u32 f2fs_fsflags_to_iflags(u32 fsflags)
2019 {
2020         u32 iflags = 0;
2021         int i;
2022
2023         for (i = 0; i < ARRAY_SIZE(f2fs_fsflags_map); i++)
2024                 if (fsflags & f2fs_fsflags_map[i].fsflag)
2025                         iflags |= f2fs_fsflags_map[i].iflag;
2026
2027         return iflags;
2028 }
2029
2030 static int f2fs_ioc_getversion(struct file *filp, unsigned long arg)
2031 {
2032         struct inode *inode = file_inode(filp);
2033
2034         return put_user(inode->i_generation, (int __user *)arg);
2035 }
2036
2037 static int f2fs_ioc_start_atomic_write(struct file *filp, bool truncate)
2038 {
2039         struct inode *inode = file_inode(filp);
2040         struct mnt_idmap *idmap = file_mnt_idmap(filp);
2041         struct f2fs_inode_info *fi = F2FS_I(inode);
2042         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2043         struct inode *pinode;
2044         loff_t isize;
2045         int ret;
2046
2047         if (!inode_owner_or_capable(idmap, inode))
2048                 return -EACCES;
2049
2050         if (!S_ISREG(inode->i_mode))
2051                 return -EINVAL;
2052
2053         if (filp->f_flags & O_DIRECT)
2054                 return -EINVAL;
2055
2056         ret = mnt_want_write_file(filp);
2057         if (ret)
2058                 return ret;
2059
2060         inode_lock(inode);
2061
2062         if (!f2fs_disable_compressed_file(inode)) {
2063                 ret = -EINVAL;
2064                 goto out;
2065         }
2066
2067         if (f2fs_is_atomic_file(inode))
2068                 goto out;
2069
2070         ret = f2fs_convert_inline_inode(inode);
2071         if (ret)
2072                 goto out;
2073
2074         f2fs_down_write(&fi->i_gc_rwsem[WRITE]);
2075
2076         /*
2077          * Should wait end_io to count F2FS_WB_CP_DATA correctly by
2078          * f2fs_is_atomic_file.
2079          */
2080         if (get_dirty_pages(inode))
2081                 f2fs_warn(sbi, "Unexpected flush for atomic writes: ino=%lu, npages=%u",
2082                           inode->i_ino, get_dirty_pages(inode));
2083         ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
2084         if (ret) {
2085                 f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2086                 goto out;
2087         }
2088
2089         /* Check if the inode already has a COW inode */
2090         if (fi->cow_inode == NULL) {
2091                 /* Create a COW inode for atomic write */
2092                 pinode = f2fs_iget(inode->i_sb, fi->i_pino);
2093                 if (IS_ERR(pinode)) {
2094                         f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2095                         ret = PTR_ERR(pinode);
2096                         goto out;
2097                 }
2098
2099                 ret = f2fs_get_tmpfile(idmap, pinode, &fi->cow_inode);
2100                 iput(pinode);
2101                 if (ret) {
2102                         f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2103                         goto out;
2104                 }
2105
2106                 set_inode_flag(fi->cow_inode, FI_COW_FILE);
2107                 clear_inode_flag(fi->cow_inode, FI_INLINE_DATA);
2108         } else {
2109                 /* Reuse the already created COW inode */
2110                 ret = f2fs_do_truncate_blocks(fi->cow_inode, 0, true);
2111                 if (ret) {
2112                         f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2113                         goto out;
2114                 }
2115         }
2116
2117         f2fs_write_inode(inode, NULL);
2118
2119         stat_inc_atomic_inode(inode);
2120
2121         set_inode_flag(inode, FI_ATOMIC_FILE);
2122
2123         isize = i_size_read(inode);
2124         fi->original_i_size = isize;
2125         if (truncate) {
2126                 set_inode_flag(inode, FI_ATOMIC_REPLACE);
2127                 truncate_inode_pages_final(inode->i_mapping);
2128                 f2fs_i_size_write(inode, 0);
2129                 isize = 0;
2130         }
2131         f2fs_i_size_write(fi->cow_inode, isize);
2132
2133         f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2134
2135         f2fs_update_time(sbi, REQ_TIME);
2136         fi->atomic_write_task = current;
2137         stat_update_max_atomic_write(inode);
2138         fi->atomic_write_cnt = 0;
2139 out:
2140         inode_unlock(inode);
2141         mnt_drop_write_file(filp);
2142         return ret;
2143 }
2144
2145 static int f2fs_ioc_commit_atomic_write(struct file *filp)
2146 {
2147         struct inode *inode = file_inode(filp);
2148         struct mnt_idmap *idmap = file_mnt_idmap(filp);
2149         int ret;
2150
2151         if (!inode_owner_or_capable(idmap, inode))
2152                 return -EACCES;
2153
2154         ret = mnt_want_write_file(filp);
2155         if (ret)
2156                 return ret;
2157
2158         f2fs_balance_fs(F2FS_I_SB(inode), true);
2159
2160         inode_lock(inode);
2161
2162         if (f2fs_is_atomic_file(inode)) {
2163                 ret = f2fs_commit_atomic_write(inode);
2164                 if (!ret)
2165                         ret = f2fs_do_sync_file(filp, 0, LLONG_MAX, 0, true);
2166
2167                 f2fs_abort_atomic_write(inode, ret);
2168         } else {
2169                 ret = f2fs_do_sync_file(filp, 0, LLONG_MAX, 1, false);
2170         }
2171
2172         inode_unlock(inode);
2173         mnt_drop_write_file(filp);
2174         return ret;
2175 }
2176
2177 static int f2fs_ioc_abort_atomic_write(struct file *filp)
2178 {
2179         struct inode *inode = file_inode(filp);
2180         struct mnt_idmap *idmap = file_mnt_idmap(filp);
2181         int ret;
2182
2183         if (!inode_owner_or_capable(idmap, inode))
2184                 return -EACCES;
2185
2186         ret = mnt_want_write_file(filp);
2187         if (ret)
2188                 return ret;
2189
2190         inode_lock(inode);
2191
2192         f2fs_abort_atomic_write(inode, true);
2193
2194         inode_unlock(inode);
2195
2196         mnt_drop_write_file(filp);
2197         f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
2198         return ret;
2199 }
2200
2201 static int f2fs_ioc_shutdown(struct file *filp, unsigned long arg)
2202 {
2203         struct inode *inode = file_inode(filp);
2204         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2205         struct super_block *sb = sbi->sb;
2206         __u32 in;
2207         int ret = 0;
2208
2209         if (!capable(CAP_SYS_ADMIN))
2210                 return -EPERM;
2211
2212         if (get_user(in, (__u32 __user *)arg))
2213                 return -EFAULT;
2214
2215         if (in != F2FS_GOING_DOWN_FULLSYNC) {
2216                 ret = mnt_want_write_file(filp);
2217                 if (ret) {
2218                         if (ret == -EROFS) {
2219                                 ret = 0;
2220                                 f2fs_stop_checkpoint(sbi, false,
2221                                                 STOP_CP_REASON_SHUTDOWN);
2222                                 trace_f2fs_shutdown(sbi, in, ret);
2223                         }
2224                         return ret;
2225                 }
2226         }
2227
2228         switch (in) {
2229         case F2FS_GOING_DOWN_FULLSYNC:
2230                 ret = freeze_bdev(sb->s_bdev);
2231                 if (ret)
2232                         goto out;
2233                 f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2234                 thaw_bdev(sb->s_bdev);
2235                 break;
2236         case F2FS_GOING_DOWN_METASYNC:
2237                 /* do checkpoint only */
2238                 ret = f2fs_sync_fs(sb, 1);
2239                 if (ret)
2240                         goto out;
2241                 f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2242                 break;
2243         case F2FS_GOING_DOWN_NOSYNC:
2244                 f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2245                 break;
2246         case F2FS_GOING_DOWN_METAFLUSH:
2247                 f2fs_sync_meta_pages(sbi, META, LONG_MAX, FS_META_IO);
2248                 f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2249                 break;
2250         case F2FS_GOING_DOWN_NEED_FSCK:
2251                 set_sbi_flag(sbi, SBI_NEED_FSCK);
2252                 set_sbi_flag(sbi, SBI_CP_DISABLED_QUICK);
2253                 set_sbi_flag(sbi, SBI_IS_DIRTY);
2254                 /* do checkpoint only */
2255                 ret = f2fs_sync_fs(sb, 1);
2256                 goto out;
2257         default:
2258                 ret = -EINVAL;
2259                 goto out;
2260         }
2261
2262         f2fs_stop_gc_thread(sbi);
2263         f2fs_stop_discard_thread(sbi);
2264
2265         f2fs_drop_discard_cmd(sbi);
2266         clear_opt(sbi, DISCARD);
2267
2268         f2fs_update_time(sbi, REQ_TIME);
2269 out:
2270         if (in != F2FS_GOING_DOWN_FULLSYNC)
2271                 mnt_drop_write_file(filp);
2272
2273         trace_f2fs_shutdown(sbi, in, ret);
2274
2275         return ret;
2276 }
2277
2278 static int f2fs_ioc_fitrim(struct file *filp, unsigned long arg)
2279 {
2280         struct inode *inode = file_inode(filp);
2281         struct super_block *sb = inode->i_sb;
2282         struct fstrim_range range;
2283         int ret;
2284
2285         if (!capable(CAP_SYS_ADMIN))
2286                 return -EPERM;
2287
2288         if (!f2fs_hw_support_discard(F2FS_SB(sb)))
2289                 return -EOPNOTSUPP;
2290
2291         if (copy_from_user(&range, (struct fstrim_range __user *)arg,
2292                                 sizeof(range)))
2293                 return -EFAULT;
2294
2295         ret = mnt_want_write_file(filp);
2296         if (ret)
2297                 return ret;
2298
2299         range.minlen = max((unsigned int)range.minlen,
2300                            bdev_discard_granularity(sb->s_bdev));
2301         ret = f2fs_trim_fs(F2FS_SB(sb), &range);
2302         mnt_drop_write_file(filp);
2303         if (ret < 0)
2304                 return ret;
2305
2306         if (copy_to_user((struct fstrim_range __user *)arg, &range,
2307                                 sizeof(range)))
2308                 return -EFAULT;
2309         f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
2310         return 0;
2311 }
2312
2313 static bool uuid_is_nonzero(__u8 u[16])
2314 {
2315         int i;
2316
2317         for (i = 0; i < 16; i++)
2318                 if (u[i])
2319                         return true;
2320         return false;
2321 }
2322
2323 static int f2fs_ioc_set_encryption_policy(struct file *filp, unsigned long arg)
2324 {
2325         struct inode *inode = file_inode(filp);
2326
2327         if (!f2fs_sb_has_encrypt(F2FS_I_SB(inode)))
2328                 return -EOPNOTSUPP;
2329
2330         f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
2331
2332         return fscrypt_ioctl_set_policy(filp, (const void __user *)arg);
2333 }
2334
2335 static int f2fs_ioc_get_encryption_policy(struct file *filp, unsigned long arg)
2336 {
2337         if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2338                 return -EOPNOTSUPP;
2339         return fscrypt_ioctl_get_policy(filp, (void __user *)arg);
2340 }
2341
2342 static int f2fs_ioc_get_encryption_pwsalt(struct file *filp, unsigned long arg)
2343 {
2344         struct inode *inode = file_inode(filp);
2345         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2346         u8 encrypt_pw_salt[16];
2347         int err;
2348
2349         if (!f2fs_sb_has_encrypt(sbi))
2350                 return -EOPNOTSUPP;
2351
2352         err = mnt_want_write_file(filp);
2353         if (err)
2354                 return err;
2355
2356         f2fs_down_write(&sbi->sb_lock);
2357
2358         if (uuid_is_nonzero(sbi->raw_super->encrypt_pw_salt))
2359                 goto got_it;
2360
2361         /* update superblock with uuid */
2362         generate_random_uuid(sbi->raw_super->encrypt_pw_salt);
2363
2364         err = f2fs_commit_super(sbi, false);
2365         if (err) {
2366                 /* undo new data */
2367                 memset(sbi->raw_super->encrypt_pw_salt, 0, 16);
2368                 goto out_err;
2369         }
2370 got_it:
2371         memcpy(encrypt_pw_salt, sbi->raw_super->encrypt_pw_salt, 16);
2372 out_err:
2373         f2fs_up_write(&sbi->sb_lock);
2374         mnt_drop_write_file(filp);
2375
2376         if (!err && copy_to_user((__u8 __user *)arg, encrypt_pw_salt, 16))
2377                 err = -EFAULT;
2378
2379         return err;
2380 }
2381
2382 static int f2fs_ioc_get_encryption_policy_ex(struct file *filp,
2383                                              unsigned long arg)
2384 {
2385         if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2386                 return -EOPNOTSUPP;
2387
2388         return fscrypt_ioctl_get_policy_ex(filp, (void __user *)arg);
2389 }
2390
2391 static int f2fs_ioc_add_encryption_key(struct file *filp, unsigned long arg)
2392 {
2393         if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2394                 return -EOPNOTSUPP;
2395
2396         return fscrypt_ioctl_add_key(filp, (void __user *)arg);
2397 }
2398
2399 static int f2fs_ioc_remove_encryption_key(struct file *filp, unsigned long arg)
2400 {
2401         if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2402                 return -EOPNOTSUPP;
2403
2404         return fscrypt_ioctl_remove_key(filp, (void __user *)arg);
2405 }
2406
2407 static int f2fs_ioc_remove_encryption_key_all_users(struct file *filp,
2408                                                     unsigned long arg)
2409 {
2410         if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2411                 return -EOPNOTSUPP;
2412
2413         return fscrypt_ioctl_remove_key_all_users(filp, (void __user *)arg);
2414 }
2415
2416 static int f2fs_ioc_get_encryption_key_status(struct file *filp,
2417                                               unsigned long arg)
2418 {
2419         if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2420                 return -EOPNOTSUPP;
2421
2422         return fscrypt_ioctl_get_key_status(filp, (void __user *)arg);
2423 }
2424
2425 static int f2fs_ioc_get_encryption_nonce(struct file *filp, unsigned long arg)
2426 {
2427         if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2428                 return -EOPNOTSUPP;
2429
2430         return fscrypt_ioctl_get_nonce(filp, (void __user *)arg);
2431 }
2432
2433 static int f2fs_ioc_gc(struct file *filp, unsigned long arg)
2434 {
2435         struct inode *inode = file_inode(filp);
2436         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2437         struct f2fs_gc_control gc_control = { .victim_segno = NULL_SEGNO,
2438                         .no_bg_gc = false,
2439                         .should_migrate_blocks = false,
2440                         .nr_free_secs = 0 };
2441         __u32 sync;
2442         int ret;
2443
2444         if (!capable(CAP_SYS_ADMIN))
2445                 return -EPERM;
2446
2447         if (get_user(sync, (__u32 __user *)arg))
2448                 return -EFAULT;
2449
2450         if (f2fs_readonly(sbi->sb))
2451                 return -EROFS;
2452
2453         ret = mnt_want_write_file(filp);
2454         if (ret)
2455                 return ret;
2456
2457         if (!sync) {
2458                 if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
2459                         ret = -EBUSY;
2460                         goto out;
2461                 }
2462         } else {
2463                 f2fs_down_write(&sbi->gc_lock);
2464         }
2465
2466         gc_control.init_gc_type = sync ? FG_GC : BG_GC;
2467         gc_control.err_gc_skipped = sync;
2468         ret = f2fs_gc(sbi, &gc_control);
2469 out:
2470         mnt_drop_write_file(filp);
2471         return ret;
2472 }
2473
2474 static int __f2fs_ioc_gc_range(struct file *filp, struct f2fs_gc_range *range)
2475 {
2476         struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(filp));
2477         struct f2fs_gc_control gc_control = {
2478                         .init_gc_type = range->sync ? FG_GC : BG_GC,
2479                         .no_bg_gc = false,
2480                         .should_migrate_blocks = false,
2481                         .err_gc_skipped = range->sync,
2482                         .nr_free_secs = 0 };
2483         u64 end;
2484         int ret;
2485
2486         if (!capable(CAP_SYS_ADMIN))
2487                 return -EPERM;
2488         if (f2fs_readonly(sbi->sb))
2489                 return -EROFS;
2490
2491         end = range->start + range->len;
2492         if (end < range->start || range->start < MAIN_BLKADDR(sbi) ||
2493                                         end >= MAX_BLKADDR(sbi))
2494                 return -EINVAL;
2495
2496         ret = mnt_want_write_file(filp);
2497         if (ret)
2498                 return ret;
2499
2500 do_more:
2501         if (!range->sync) {
2502                 if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
2503                         ret = -EBUSY;
2504                         goto out;
2505                 }
2506         } else {
2507                 f2fs_down_write(&sbi->gc_lock);
2508         }
2509
2510         gc_control.victim_segno = GET_SEGNO(sbi, range->start);
2511         ret = f2fs_gc(sbi, &gc_control);
2512         if (ret) {
2513                 if (ret == -EBUSY)
2514                         ret = -EAGAIN;
2515                 goto out;
2516         }
2517         range->start += CAP_BLKS_PER_SEC(sbi);
2518         if (range->start <= end)
2519                 goto do_more;
2520 out:
2521         mnt_drop_write_file(filp);
2522         return ret;
2523 }
2524
2525 static int f2fs_ioc_gc_range(struct file *filp, unsigned long arg)
2526 {
2527         struct f2fs_gc_range range;
2528
2529         if (copy_from_user(&range, (struct f2fs_gc_range __user *)arg,
2530                                                         sizeof(range)))
2531                 return -EFAULT;
2532         return __f2fs_ioc_gc_range(filp, &range);
2533 }
2534
2535 static int f2fs_ioc_write_checkpoint(struct file *filp)
2536 {
2537         struct inode *inode = file_inode(filp);
2538         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2539         int ret;
2540
2541         if (!capable(CAP_SYS_ADMIN))
2542                 return -EPERM;
2543
2544         if (f2fs_readonly(sbi->sb))
2545                 return -EROFS;
2546
2547         if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
2548                 f2fs_info(sbi, "Skipping Checkpoint. Checkpoints currently disabled.");
2549                 return -EINVAL;
2550         }
2551
2552         ret = mnt_want_write_file(filp);
2553         if (ret)
2554                 return ret;
2555
2556         ret = f2fs_sync_fs(sbi->sb, 1);
2557
2558         mnt_drop_write_file(filp);
2559         return ret;
2560 }
2561
2562 static int f2fs_defragment_range(struct f2fs_sb_info *sbi,
2563                                         struct file *filp,
2564                                         struct f2fs_defragment *range)
2565 {
2566         struct inode *inode = file_inode(filp);
2567         struct f2fs_map_blocks map = { .m_next_extent = NULL,
2568                                         .m_seg_type = NO_CHECK_TYPE,
2569                                         .m_may_create = false };
2570         struct extent_info ei = {};
2571         pgoff_t pg_start, pg_end, next_pgofs;
2572         unsigned int blk_per_seg = sbi->blocks_per_seg;
2573         unsigned int total = 0, sec_num;
2574         block_t blk_end = 0;
2575         bool fragmented = false;
2576         int err;
2577
2578         pg_start = range->start >> PAGE_SHIFT;
2579         pg_end = (range->start + range->len) >> PAGE_SHIFT;
2580
2581         f2fs_balance_fs(sbi, true);
2582
2583         inode_lock(inode);
2584
2585         if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
2586                 err = -EINVAL;
2587                 goto unlock_out;
2588         }
2589
2590         /* if in-place-update policy is enabled, don't waste time here */
2591         set_inode_flag(inode, FI_OPU_WRITE);
2592         if (f2fs_should_update_inplace(inode, NULL)) {
2593                 err = -EINVAL;
2594                 goto out;
2595         }
2596
2597         /* writeback all dirty pages in the range */
2598         err = filemap_write_and_wait_range(inode->i_mapping, range->start,
2599                                                 range->start + range->len - 1);
2600         if (err)
2601                 goto out;
2602
2603         /*
2604          * lookup mapping info in extent cache, skip defragmenting if physical
2605          * block addresses are continuous.
2606          */
2607         if (f2fs_lookup_read_extent_cache(inode, pg_start, &ei)) {
2608                 if (ei.fofs + ei.len >= pg_end)
2609                         goto out;
2610         }
2611
2612         map.m_lblk = pg_start;
2613         map.m_next_pgofs = &next_pgofs;
2614
2615         /*
2616          * lookup mapping info in dnode page cache, skip defragmenting if all
2617          * physical block addresses are continuous even if there are hole(s)
2618          * in logical blocks.
2619          */
2620         while (map.m_lblk < pg_end) {
2621                 map.m_len = pg_end - map.m_lblk;
2622                 err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_DEFAULT);
2623                 if (err)
2624                         goto out;
2625
2626                 if (!(map.m_flags & F2FS_MAP_FLAGS)) {
2627                         map.m_lblk = next_pgofs;
2628                         continue;
2629                 }
2630
2631                 if (blk_end && blk_end != map.m_pblk)
2632                         fragmented = true;
2633
2634                 /* record total count of block that we're going to move */
2635                 total += map.m_len;
2636
2637                 blk_end = map.m_pblk + map.m_len;
2638
2639                 map.m_lblk += map.m_len;
2640         }
2641
2642         if (!fragmented) {
2643                 total = 0;
2644                 goto out;
2645         }
2646
2647         sec_num = DIV_ROUND_UP(total, CAP_BLKS_PER_SEC(sbi));
2648
2649         /*
2650          * make sure there are enough free section for LFS allocation, this can
2651          * avoid defragment running in SSR mode when free section are allocated
2652          * intensively
2653          */
2654         if (has_not_enough_free_secs(sbi, 0, sec_num)) {
2655                 err = -EAGAIN;
2656                 goto out;
2657         }
2658
2659         map.m_lblk = pg_start;
2660         map.m_len = pg_end - pg_start;
2661         total = 0;
2662
2663         while (map.m_lblk < pg_end) {
2664                 pgoff_t idx;
2665                 int cnt = 0;
2666
2667 do_map:
2668                 map.m_len = pg_end - map.m_lblk;
2669                 err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_DEFAULT);
2670                 if (err)
2671                         goto clear_out;
2672
2673                 if (!(map.m_flags & F2FS_MAP_FLAGS)) {
2674                         map.m_lblk = next_pgofs;
2675                         goto check;
2676                 }
2677
2678                 set_inode_flag(inode, FI_SKIP_WRITES);
2679
2680                 idx = map.m_lblk;
2681                 while (idx < map.m_lblk + map.m_len && cnt < blk_per_seg) {
2682                         struct page *page;
2683
2684                         page = f2fs_get_lock_data_page(inode, idx, true);
2685                         if (IS_ERR(page)) {
2686                                 err = PTR_ERR(page);
2687                                 goto clear_out;
2688                         }
2689
2690                         set_page_dirty(page);
2691                         set_page_private_gcing(page);
2692                         f2fs_put_page(page, 1);
2693
2694                         idx++;
2695                         cnt++;
2696                         total++;
2697                 }
2698
2699                 map.m_lblk = idx;
2700 check:
2701                 if (map.m_lblk < pg_end && cnt < blk_per_seg)
2702                         goto do_map;
2703
2704                 clear_inode_flag(inode, FI_SKIP_WRITES);
2705
2706                 err = filemap_fdatawrite(inode->i_mapping);
2707                 if (err)
2708                         goto out;
2709         }
2710 clear_out:
2711         clear_inode_flag(inode, FI_SKIP_WRITES);
2712 out:
2713         clear_inode_flag(inode, FI_OPU_WRITE);
2714 unlock_out:
2715         inode_unlock(inode);
2716         if (!err)
2717                 range->len = (u64)total << PAGE_SHIFT;
2718         return err;
2719 }
2720
2721 static int f2fs_ioc_defragment(struct file *filp, unsigned long arg)
2722 {
2723         struct inode *inode = file_inode(filp);
2724         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2725         struct f2fs_defragment range;
2726         int err;
2727
2728         if (!capable(CAP_SYS_ADMIN))
2729                 return -EPERM;
2730
2731         if (!S_ISREG(inode->i_mode) || f2fs_is_atomic_file(inode))
2732                 return -EINVAL;
2733
2734         if (f2fs_readonly(sbi->sb))
2735                 return -EROFS;
2736
2737         if (copy_from_user(&range, (struct f2fs_defragment __user *)arg,
2738                                                         sizeof(range)))
2739                 return -EFAULT;
2740
2741         /* verify alignment of offset & size */
2742         if (range.start & (F2FS_BLKSIZE - 1) || range.len & (F2FS_BLKSIZE - 1))
2743                 return -EINVAL;
2744
2745         if (unlikely((range.start + range.len) >> PAGE_SHIFT >
2746                                         max_file_blocks(inode)))
2747                 return -EINVAL;
2748
2749         err = mnt_want_write_file(filp);
2750         if (err)
2751                 return err;
2752
2753         err = f2fs_defragment_range(sbi, filp, &range);
2754         mnt_drop_write_file(filp);
2755
2756         f2fs_update_time(sbi, REQ_TIME);
2757         if (err < 0)
2758                 return err;
2759
2760         if (copy_to_user((struct f2fs_defragment __user *)arg, &range,
2761                                                         sizeof(range)))
2762                 return -EFAULT;
2763
2764         return 0;
2765 }
2766
2767 static int f2fs_move_file_range(struct file *file_in, loff_t pos_in,
2768                         struct file *file_out, loff_t pos_out, size_t len)
2769 {
2770         struct inode *src = file_inode(file_in);
2771         struct inode *dst = file_inode(file_out);
2772         struct f2fs_sb_info *sbi = F2FS_I_SB(src);
2773         size_t olen = len, dst_max_i_size = 0;
2774         size_t dst_osize;
2775         int ret;
2776
2777         if (file_in->f_path.mnt != file_out->f_path.mnt ||
2778                                 src->i_sb != dst->i_sb)
2779                 return -EXDEV;
2780
2781         if (unlikely(f2fs_readonly(src->i_sb)))
2782                 return -EROFS;
2783
2784         if (!S_ISREG(src->i_mode) || !S_ISREG(dst->i_mode))
2785                 return -EINVAL;
2786
2787         if (IS_ENCRYPTED(src) || IS_ENCRYPTED(dst))
2788                 return -EOPNOTSUPP;
2789
2790         if (pos_out < 0 || pos_in < 0)
2791                 return -EINVAL;
2792
2793         if (src == dst) {
2794                 if (pos_in == pos_out)
2795                         return 0;
2796                 if (pos_out > pos_in && pos_out < pos_in + len)
2797                         return -EINVAL;
2798         }
2799
2800         inode_lock(src);
2801         if (src != dst) {
2802                 ret = -EBUSY;
2803                 if (!inode_trylock(dst))
2804                         goto out;
2805         }
2806
2807         ret = -EINVAL;
2808         if (pos_in + len > src->i_size || pos_in + len < pos_in)
2809                 goto out_unlock;
2810         if (len == 0)
2811                 olen = len = src->i_size - pos_in;
2812         if (pos_in + len == src->i_size)
2813                 len = ALIGN(src->i_size, F2FS_BLKSIZE) - pos_in;
2814         if (len == 0) {
2815                 ret = 0;
2816                 goto out_unlock;
2817         }
2818
2819         dst_osize = dst->i_size;
2820         if (pos_out + olen > dst->i_size)
2821                 dst_max_i_size = pos_out + olen;
2822
2823         /* verify the end result is block aligned */
2824         if (!IS_ALIGNED(pos_in, F2FS_BLKSIZE) ||
2825                         !IS_ALIGNED(pos_in + len, F2FS_BLKSIZE) ||
2826                         !IS_ALIGNED(pos_out, F2FS_BLKSIZE))
2827                 goto out_unlock;
2828
2829         ret = f2fs_convert_inline_inode(src);
2830         if (ret)
2831                 goto out_unlock;
2832
2833         ret = f2fs_convert_inline_inode(dst);
2834         if (ret)
2835                 goto out_unlock;
2836
2837         /* write out all dirty pages from offset */
2838         ret = filemap_write_and_wait_range(src->i_mapping,
2839                                         pos_in, pos_in + len);
2840         if (ret)
2841                 goto out_unlock;
2842
2843         ret = filemap_write_and_wait_range(dst->i_mapping,
2844                                         pos_out, pos_out + len);
2845         if (ret)
2846                 goto out_unlock;
2847
2848         f2fs_balance_fs(sbi, true);
2849
2850         f2fs_down_write(&F2FS_I(src)->i_gc_rwsem[WRITE]);
2851         if (src != dst) {
2852                 ret = -EBUSY;
2853                 if (!f2fs_down_write_trylock(&F2FS_I(dst)->i_gc_rwsem[WRITE]))
2854                         goto out_src;
2855         }
2856
2857         f2fs_lock_op(sbi);
2858         ret = __exchange_data_block(src, dst, pos_in >> F2FS_BLKSIZE_BITS,
2859                                 pos_out >> F2FS_BLKSIZE_BITS,
2860                                 len >> F2FS_BLKSIZE_BITS, false);
2861
2862         if (!ret) {
2863                 if (dst_max_i_size)
2864                         f2fs_i_size_write(dst, dst_max_i_size);
2865                 else if (dst_osize != dst->i_size)
2866                         f2fs_i_size_write(dst, dst_osize);
2867         }
2868         f2fs_unlock_op(sbi);
2869
2870         if (src != dst)
2871                 f2fs_up_write(&F2FS_I(dst)->i_gc_rwsem[WRITE]);
2872 out_src:
2873         f2fs_up_write(&F2FS_I(src)->i_gc_rwsem[WRITE]);
2874         if (ret)
2875                 goto out_unlock;
2876
2877         src->i_mtime = src->i_ctime = current_time(src);
2878         f2fs_mark_inode_dirty_sync(src, false);
2879         if (src != dst) {
2880                 dst->i_mtime = dst->i_ctime = current_time(dst);
2881                 f2fs_mark_inode_dirty_sync(dst, false);
2882         }
2883         f2fs_update_time(sbi, REQ_TIME);
2884
2885 out_unlock:
2886         if (src != dst)
2887                 inode_unlock(dst);
2888 out:
2889         inode_unlock(src);
2890         return ret;
2891 }
2892
2893 static int __f2fs_ioc_move_range(struct file *filp,
2894                                 struct f2fs_move_range *range)
2895 {
2896         struct fd dst;
2897         int err;
2898
2899         if (!(filp->f_mode & FMODE_READ) ||
2900                         !(filp->f_mode & FMODE_WRITE))
2901                 return -EBADF;
2902
2903         dst = fdget(range->dst_fd);
2904         if (!dst.file)
2905                 return -EBADF;
2906
2907         if (!(dst.file->f_mode & FMODE_WRITE)) {
2908                 err = -EBADF;
2909                 goto err_out;
2910         }
2911
2912         err = mnt_want_write_file(filp);
2913         if (err)
2914                 goto err_out;
2915
2916         err = f2fs_move_file_range(filp, range->pos_in, dst.file,
2917                                         range->pos_out, range->len);
2918
2919         mnt_drop_write_file(filp);
2920 err_out:
2921         fdput(dst);
2922         return err;
2923 }
2924
2925 static int f2fs_ioc_move_range(struct file *filp, unsigned long arg)
2926 {
2927         struct f2fs_move_range range;
2928
2929         if (copy_from_user(&range, (struct f2fs_move_range __user *)arg,
2930                                                         sizeof(range)))
2931                 return -EFAULT;
2932         return __f2fs_ioc_move_range(filp, &range);
2933 }
2934
2935 static int f2fs_ioc_flush_device(struct file *filp, unsigned long arg)
2936 {
2937         struct inode *inode = file_inode(filp);
2938         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2939         struct sit_info *sm = SIT_I(sbi);
2940         unsigned int start_segno = 0, end_segno = 0;
2941         unsigned int dev_start_segno = 0, dev_end_segno = 0;
2942         struct f2fs_flush_device range;
2943         struct f2fs_gc_control gc_control = {
2944                         .init_gc_type = FG_GC,
2945                         .should_migrate_blocks = true,
2946                         .err_gc_skipped = true,
2947                         .nr_free_secs = 0 };
2948         int ret;
2949
2950         if (!capable(CAP_SYS_ADMIN))
2951                 return -EPERM;
2952
2953         if (f2fs_readonly(sbi->sb))
2954                 return -EROFS;
2955
2956         if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
2957                 return -EINVAL;
2958
2959         if (copy_from_user(&range, (struct f2fs_flush_device __user *)arg,
2960                                                         sizeof(range)))
2961                 return -EFAULT;
2962
2963         if (!f2fs_is_multi_device(sbi) || sbi->s_ndevs - 1 <= range.dev_num ||
2964                         __is_large_section(sbi)) {
2965                 f2fs_warn(sbi, "Can't flush %u in %d for segs_per_sec %u != 1",
2966                           range.dev_num, sbi->s_ndevs, sbi->segs_per_sec);
2967                 return -EINVAL;
2968         }
2969
2970         ret = mnt_want_write_file(filp);
2971         if (ret)
2972                 return ret;
2973
2974         if (range.dev_num != 0)
2975                 dev_start_segno = GET_SEGNO(sbi, FDEV(range.dev_num).start_blk);
2976         dev_end_segno = GET_SEGNO(sbi, FDEV(range.dev_num).end_blk);
2977
2978         start_segno = sm->last_victim[FLUSH_DEVICE];
2979         if (start_segno < dev_start_segno || start_segno >= dev_end_segno)
2980                 start_segno = dev_start_segno;
2981         end_segno = min(start_segno + range.segments, dev_end_segno);
2982
2983         while (start_segno < end_segno) {
2984                 if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
2985                         ret = -EBUSY;
2986                         goto out;
2987                 }
2988                 sm->last_victim[GC_CB] = end_segno + 1;
2989                 sm->last_victim[GC_GREEDY] = end_segno + 1;
2990                 sm->last_victim[ALLOC_NEXT] = end_segno + 1;
2991
2992                 gc_control.victim_segno = start_segno;
2993                 ret = f2fs_gc(sbi, &gc_control);
2994                 if (ret == -EAGAIN)
2995                         ret = 0;
2996                 else if (ret < 0)
2997                         break;
2998                 start_segno++;
2999         }
3000 out:
3001         mnt_drop_write_file(filp);
3002         return ret;
3003 }
3004
3005 static int f2fs_ioc_get_features(struct file *filp, unsigned long arg)
3006 {
3007         struct inode *inode = file_inode(filp);
3008         u32 sb_feature = le32_to_cpu(F2FS_I_SB(inode)->raw_super->feature);
3009
3010         /* Must validate to set it with SQLite behavior in Android. */
3011         sb_feature |= F2FS_FEATURE_ATOMIC_WRITE;
3012
3013         return put_user(sb_feature, (u32 __user *)arg);
3014 }
3015
3016 #ifdef CONFIG_QUOTA
3017 int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid)
3018 {
3019         struct dquot *transfer_to[MAXQUOTAS] = {};
3020         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3021         struct super_block *sb = sbi->sb;
3022         int err;
3023
3024         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3025         if (IS_ERR(transfer_to[PRJQUOTA]))
3026                 return PTR_ERR(transfer_to[PRJQUOTA]);
3027
3028         err = __dquot_transfer(inode, transfer_to);
3029         if (err)
3030                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
3031         dqput(transfer_to[PRJQUOTA]);
3032         return err;
3033 }
3034
3035 static int f2fs_ioc_setproject(struct inode *inode, __u32 projid)
3036 {
3037         struct f2fs_inode_info *fi = F2FS_I(inode);
3038         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3039         struct f2fs_inode *ri = NULL;
3040         kprojid_t kprojid;
3041         int err;
3042
3043         if (!f2fs_sb_has_project_quota(sbi)) {
3044                 if (projid != F2FS_DEF_PROJID)
3045                         return -EOPNOTSUPP;
3046                 else
3047                         return 0;
3048         }
3049
3050         if (!f2fs_has_extra_attr(inode))
3051                 return -EOPNOTSUPP;
3052
3053         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3054
3055         if (projid_eq(kprojid, fi->i_projid))
3056                 return 0;
3057
3058         err = -EPERM;
3059         /* Is it quota file? Do not allow user to mess with it */
3060         if (IS_NOQUOTA(inode))
3061                 return err;
3062
3063         if (!F2FS_FITS_IN_INODE(ri, fi->i_extra_isize, i_projid))
3064                 return -EOVERFLOW;
3065
3066         err = f2fs_dquot_initialize(inode);
3067         if (err)
3068                 return err;
3069
3070         f2fs_lock_op(sbi);
3071         err = f2fs_transfer_project_quota(inode, kprojid);
3072         if (err)
3073                 goto out_unlock;
3074
3075         fi->i_projid = kprojid;
3076         inode->i_ctime = current_time(inode);
3077         f2fs_mark_inode_dirty_sync(inode, true);
3078 out_unlock:
3079         f2fs_unlock_op(sbi);
3080         return err;
3081 }
3082 #else
3083 int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid)
3084 {
3085         return 0;
3086 }
3087
3088 static int f2fs_ioc_setproject(struct inode *inode, __u32 projid)
3089 {
3090         if (projid != F2FS_DEF_PROJID)
3091                 return -EOPNOTSUPP;
3092         return 0;
3093 }
3094 #endif
3095
3096 int f2fs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
3097 {
3098         struct inode *inode = d_inode(dentry);
3099         struct f2fs_inode_info *fi = F2FS_I(inode);
3100         u32 fsflags = f2fs_iflags_to_fsflags(fi->i_flags);
3101
3102         if (IS_ENCRYPTED(inode))
3103                 fsflags |= FS_ENCRYPT_FL;
3104         if (IS_VERITY(inode))
3105                 fsflags |= FS_VERITY_FL;
3106         if (f2fs_has_inline_data(inode) || f2fs_has_inline_dentry(inode))
3107                 fsflags |= FS_INLINE_DATA_FL;
3108         if (is_inode_flag_set(inode, FI_PIN_FILE))
3109                 fsflags |= FS_NOCOW_FL;
3110
3111         fileattr_fill_flags(fa, fsflags & F2FS_GETTABLE_FS_FL);
3112
3113         if (f2fs_sb_has_project_quota(F2FS_I_SB(inode)))
3114                 fa->fsx_projid = from_kprojid(&init_user_ns, fi->i_projid);
3115
3116         return 0;
3117 }
3118
3119 int f2fs_fileattr_set(struct mnt_idmap *idmap,
3120                       struct dentry *dentry, struct fileattr *fa)
3121 {
3122         struct inode *inode = d_inode(dentry);
3123         u32 fsflags = fa->flags, mask = F2FS_SETTABLE_FS_FL;
3124         u32 iflags;
3125         int err;
3126
3127         if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
3128                 return -EIO;
3129         if (!f2fs_is_checkpoint_ready(F2FS_I_SB(inode)))
3130                 return -ENOSPC;
3131         if (fsflags & ~F2FS_GETTABLE_FS_FL)
3132                 return -EOPNOTSUPP;
3133         fsflags &= F2FS_SETTABLE_FS_FL;
3134         if (!fa->flags_valid)
3135                 mask &= FS_COMMON_FL;
3136
3137         iflags = f2fs_fsflags_to_iflags(fsflags);
3138         if (f2fs_mask_flags(inode->i_mode, iflags) != iflags)
3139                 return -EOPNOTSUPP;
3140
3141         err = f2fs_setflags_common(inode, iflags, f2fs_fsflags_to_iflags(mask));
3142         if (!err)
3143                 err = f2fs_ioc_setproject(inode, fa->fsx_projid);
3144
3145         return err;
3146 }
3147
3148 int f2fs_pin_file_control(struct inode *inode, bool inc)
3149 {
3150         struct f2fs_inode_info *fi = F2FS_I(inode);
3151         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3152
3153         /* Use i_gc_failures for normal file as a risk signal. */
3154         if (inc)
3155                 f2fs_i_gc_failures_write(inode,
3156                                 fi->i_gc_failures[GC_FAILURE_PIN] + 1);
3157
3158         if (fi->i_gc_failures[GC_FAILURE_PIN] > sbi->gc_pin_file_threshold) {
3159                 f2fs_warn(sbi, "%s: Enable GC = ino %lx after %x GC trials",
3160                           __func__, inode->i_ino,
3161                           fi->i_gc_failures[GC_FAILURE_PIN]);
3162                 clear_inode_flag(inode, FI_PIN_FILE);
3163                 return -EAGAIN;
3164         }
3165         return 0;
3166 }
3167
3168 static int f2fs_ioc_set_pin_file(struct file *filp, unsigned long arg)
3169 {
3170         struct inode *inode = file_inode(filp);
3171         __u32 pin;
3172         int ret = 0;
3173
3174         if (get_user(pin, (__u32 __user *)arg))
3175                 return -EFAULT;
3176
3177         if (!S_ISREG(inode->i_mode))
3178                 return -EINVAL;
3179
3180         if (f2fs_readonly(F2FS_I_SB(inode)->sb))
3181                 return -EROFS;
3182
3183         ret = mnt_want_write_file(filp);
3184         if (ret)
3185                 return ret;
3186
3187         inode_lock(inode);
3188
3189         if (!pin) {
3190                 clear_inode_flag(inode, FI_PIN_FILE);
3191                 f2fs_i_gc_failures_write(inode, 0);
3192                 goto done;
3193         }
3194
3195         if (f2fs_should_update_outplace(inode, NULL)) {
3196                 ret = -EINVAL;
3197                 goto out;
3198         }
3199
3200         if (f2fs_pin_file_control(inode, false)) {
3201                 ret = -EAGAIN;
3202                 goto out;
3203         }
3204
3205         ret = f2fs_convert_inline_inode(inode);
3206         if (ret)
3207                 goto out;
3208
3209         if (!f2fs_disable_compressed_file(inode)) {
3210                 ret = -EOPNOTSUPP;
3211                 goto out;
3212         }
3213
3214         set_inode_flag(inode, FI_PIN_FILE);
3215         ret = F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN];
3216 done:
3217         f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
3218 out:
3219         inode_unlock(inode);
3220         mnt_drop_write_file(filp);
3221         return ret;
3222 }
3223
3224 static int f2fs_ioc_get_pin_file(struct file *filp, unsigned long arg)
3225 {
3226         struct inode *inode = file_inode(filp);
3227         __u32 pin = 0;
3228
3229         if (is_inode_flag_set(inode, FI_PIN_FILE))
3230                 pin = F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN];
3231         return put_user(pin, (u32 __user *)arg);
3232 }
3233
3234 int f2fs_precache_extents(struct inode *inode)
3235 {
3236         struct f2fs_inode_info *fi = F2FS_I(inode);
3237         struct f2fs_map_blocks map;
3238         pgoff_t m_next_extent;
3239         loff_t end;
3240         int err;
3241
3242         if (is_inode_flag_set(inode, FI_NO_EXTENT))
3243                 return -EOPNOTSUPP;
3244
3245         map.m_lblk = 0;
3246         map.m_next_pgofs = NULL;
3247         map.m_next_extent = &m_next_extent;
3248         map.m_seg_type = NO_CHECK_TYPE;
3249         map.m_may_create = false;
3250         end = max_file_blocks(inode);
3251
3252         while (map.m_lblk < end) {
3253                 map.m_len = end - map.m_lblk;
3254
3255                 f2fs_down_write(&fi->i_gc_rwsem[WRITE]);
3256                 err = f2fs_map_blocks(inode, &map, F2FS_GET_BLOCK_PRECACHE);
3257                 f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
3258                 if (err)
3259                         return err;
3260
3261                 map.m_lblk = m_next_extent;
3262         }
3263
3264         return 0;
3265 }
3266
3267 static int f2fs_ioc_precache_extents(struct file *filp)
3268 {
3269         return f2fs_precache_extents(file_inode(filp));
3270 }
3271
3272 static int f2fs_ioc_resize_fs(struct file *filp, unsigned long arg)
3273 {
3274         struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(filp));
3275         __u64 block_count;
3276
3277         if (!capable(CAP_SYS_ADMIN))
3278                 return -EPERM;
3279
3280         if (f2fs_readonly(sbi->sb))
3281                 return -EROFS;
3282
3283         if (copy_from_user(&block_count, (void __user *)arg,
3284                            sizeof(block_count)))
3285                 return -EFAULT;
3286
3287         return f2fs_resize_fs(filp, block_count);
3288 }
3289
3290 static int f2fs_ioc_enable_verity(struct file *filp, unsigned long arg)
3291 {
3292         struct inode *inode = file_inode(filp);
3293
3294         f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
3295
3296         if (!f2fs_sb_has_verity(F2FS_I_SB(inode))) {
3297                 f2fs_warn(F2FS_I_SB(inode),
3298                           "Can't enable fs-verity on inode %lu: the verity feature is not enabled on this filesystem",
3299                           inode->i_ino);
3300                 return -EOPNOTSUPP;
3301         }
3302
3303         return fsverity_ioctl_enable(filp, (const void __user *)arg);
3304 }
3305
3306 static int f2fs_ioc_measure_verity(struct file *filp, unsigned long arg)
3307 {
3308         if (!f2fs_sb_has_verity(F2FS_I_SB(file_inode(filp))))
3309                 return -EOPNOTSUPP;
3310
3311         return fsverity_ioctl_measure(filp, (void __user *)arg);
3312 }
3313
3314 static int f2fs_ioc_read_verity_metadata(struct file *filp, unsigned long arg)
3315 {
3316         if (!f2fs_sb_has_verity(F2FS_I_SB(file_inode(filp))))
3317                 return -EOPNOTSUPP;
3318
3319         return fsverity_ioctl_read_metadata(filp, (const void __user *)arg);
3320 }
3321
3322 static int f2fs_ioc_getfslabel(struct file *filp, unsigned long arg)
3323 {
3324         struct inode *inode = file_inode(filp);
3325         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3326         char *vbuf;
3327         int count;
3328         int err = 0;
3329
3330         vbuf = f2fs_kzalloc(sbi, MAX_VOLUME_NAME, GFP_KERNEL);
3331         if (!vbuf)
3332                 return -ENOMEM;
3333
3334         f2fs_down_read(&sbi->sb_lock);
3335         count = utf16s_to_utf8s(sbi->raw_super->volume_name,
3336                         ARRAY_SIZE(sbi->raw_super->volume_name),
3337                         UTF16_LITTLE_ENDIAN, vbuf, MAX_VOLUME_NAME);
3338         f2fs_up_read(&sbi->sb_lock);
3339
3340         if (copy_to_user((char __user *)arg, vbuf,
3341                                 min(FSLABEL_MAX, count)))
3342                 err = -EFAULT;
3343
3344         kfree(vbuf);
3345         return err;
3346 }
3347
3348 static int f2fs_ioc_setfslabel(struct file *filp, unsigned long arg)
3349 {
3350         struct inode *inode = file_inode(filp);
3351         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3352         char *vbuf;
3353         int err = 0;
3354
3355         if (!capable(CAP_SYS_ADMIN))
3356                 return -EPERM;
3357
3358         vbuf = strndup_user((const char __user *)arg, FSLABEL_MAX);
3359         if (IS_ERR(vbuf))
3360                 return PTR_ERR(vbuf);
3361
3362         err = mnt_want_write_file(filp);
3363         if (err)
3364                 goto out;
3365
3366         f2fs_down_write(&sbi->sb_lock);
3367
3368         memset(sbi->raw_super->volume_name, 0,
3369                         sizeof(sbi->raw_super->volume_name));
3370         utf8s_to_utf16s(vbuf, strlen(vbuf), UTF16_LITTLE_ENDIAN,
3371                         sbi->raw_super->volume_name,
3372                         ARRAY_SIZE(sbi->raw_super->volume_name));
3373
3374         err = f2fs_commit_super(sbi, false);
3375
3376         f2fs_up_write(&sbi->sb_lock);
3377
3378         mnt_drop_write_file(filp);
3379 out:
3380         kfree(vbuf);
3381         return err;
3382 }
3383
3384 static int f2fs_get_compress_blocks(struct inode *inode, __u64 *blocks)
3385 {
3386         if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
3387                 return -EOPNOTSUPP;
3388
3389         if (!f2fs_compressed_file(inode))
3390                 return -EINVAL;
3391
3392         *blocks = atomic_read(&F2FS_I(inode)->i_compr_blocks);
3393
3394         return 0;
3395 }
3396
3397 static int f2fs_ioc_get_compress_blocks(struct file *filp, unsigned long arg)
3398 {
3399         struct inode *inode = file_inode(filp);
3400         __u64 blocks;
3401         int ret;
3402
3403         ret = f2fs_get_compress_blocks(inode, &blocks);
3404         if (ret < 0)
3405                 return ret;
3406
3407         return put_user(blocks, (u64 __user *)arg);
3408 }
3409
3410 static int release_compress_blocks(struct dnode_of_data *dn, pgoff_t count)
3411 {
3412         struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
3413         unsigned int released_blocks = 0;
3414         int cluster_size = F2FS_I(dn->inode)->i_cluster_size;
3415         block_t blkaddr;
3416         int i;
3417
3418         for (i = 0; i < count; i++) {
3419                 blkaddr = data_blkaddr(dn->inode, dn->node_page,
3420                                                 dn->ofs_in_node + i);
3421
3422                 if (!__is_valid_data_blkaddr(blkaddr))
3423                         continue;
3424                 if (unlikely(!f2fs_is_valid_blkaddr(sbi, blkaddr,
3425                                         DATA_GENERIC_ENHANCE))) {
3426                         f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
3427                         return -EFSCORRUPTED;
3428                 }
3429         }
3430
3431         while (count) {
3432                 int compr_blocks = 0;
3433
3434                 for (i = 0; i < cluster_size; i++, dn->ofs_in_node++) {
3435                         blkaddr = f2fs_data_blkaddr(dn);
3436
3437                         if (i == 0) {
3438                                 if (blkaddr == COMPRESS_ADDR)
3439                                         continue;
3440                                 dn->ofs_in_node += cluster_size;
3441                                 goto next;
3442                         }
3443
3444                         if (__is_valid_data_blkaddr(blkaddr))
3445                                 compr_blocks++;
3446
3447                         if (blkaddr != NEW_ADDR)
3448                                 continue;
3449
3450                         dn->data_blkaddr = NULL_ADDR;
3451                         f2fs_set_data_blkaddr(dn);
3452                 }
3453
3454                 f2fs_i_compr_blocks_update(dn->inode, compr_blocks, false);
3455                 dec_valid_block_count(sbi, dn->inode,
3456                                         cluster_size - compr_blocks);
3457
3458                 released_blocks += cluster_size - compr_blocks;
3459 next:
3460                 count -= cluster_size;
3461         }
3462
3463         return released_blocks;
3464 }
3465
3466 static int f2fs_release_compress_blocks(struct file *filp, unsigned long arg)
3467 {
3468         struct inode *inode = file_inode(filp);
3469         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3470         pgoff_t page_idx = 0, last_idx;
3471         unsigned int released_blocks = 0;
3472         int ret;
3473         int writecount;
3474
3475         if (!f2fs_sb_has_compression(sbi))
3476                 return -EOPNOTSUPP;
3477
3478         if (!f2fs_compressed_file(inode))
3479                 return -EINVAL;
3480
3481         if (f2fs_readonly(sbi->sb))
3482                 return -EROFS;
3483
3484         ret = mnt_want_write_file(filp);
3485         if (ret)
3486                 return ret;
3487
3488         f2fs_balance_fs(sbi, true);
3489
3490         inode_lock(inode);
3491
3492         writecount = atomic_read(&inode->i_writecount);
3493         if ((filp->f_mode & FMODE_WRITE && writecount != 1) ||
3494                         (!(filp->f_mode & FMODE_WRITE) && writecount)) {
3495                 ret = -EBUSY;
3496                 goto out;
3497         }
3498
3499         if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
3500                 ret = -EINVAL;
3501                 goto out;
3502         }
3503
3504         ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
3505         if (ret)
3506                 goto out;
3507
3508         if (!atomic_read(&F2FS_I(inode)->i_compr_blocks)) {
3509                 ret = -EPERM;
3510                 goto out;
3511         }
3512
3513         set_inode_flag(inode, FI_COMPRESS_RELEASED);
3514         inode->i_ctime = current_time(inode);
3515         f2fs_mark_inode_dirty_sync(inode, true);
3516
3517         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3518         filemap_invalidate_lock(inode->i_mapping);
3519
3520         last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3521
3522         while (page_idx < last_idx) {
3523                 struct dnode_of_data dn;
3524                 pgoff_t end_offset, count;
3525
3526                 set_new_dnode(&dn, inode, NULL, NULL, 0);
3527                 ret = f2fs_get_dnode_of_data(&dn, page_idx, LOOKUP_NODE);
3528                 if (ret) {
3529                         if (ret == -ENOENT) {
3530                                 page_idx = f2fs_get_next_page_offset(&dn,
3531                                                                 page_idx);
3532                                 ret = 0;
3533                                 continue;
3534                         }
3535                         break;
3536                 }
3537
3538                 end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
3539                 count = min(end_offset - dn.ofs_in_node, last_idx - page_idx);
3540                 count = round_up(count, F2FS_I(inode)->i_cluster_size);
3541
3542                 ret = release_compress_blocks(&dn, count);
3543
3544                 f2fs_put_dnode(&dn);
3545
3546                 if (ret < 0)
3547                         break;
3548
3549                 page_idx += count;
3550                 released_blocks += ret;
3551         }
3552
3553         filemap_invalidate_unlock(inode->i_mapping);
3554         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3555 out:
3556         inode_unlock(inode);
3557
3558         mnt_drop_write_file(filp);
3559
3560         if (ret >= 0) {
3561                 ret = put_user(released_blocks, (u64 __user *)arg);
3562         } else if (released_blocks &&
3563                         atomic_read(&F2FS_I(inode)->i_compr_blocks)) {
3564                 set_sbi_flag(sbi, SBI_NEED_FSCK);
3565                 f2fs_warn(sbi, "%s: partial blocks were released i_ino=%lx "
3566                         "iblocks=%llu, released=%u, compr_blocks=%u, "
3567                         "run fsck to fix.",
3568                         __func__, inode->i_ino, inode->i_blocks,
3569                         released_blocks,
3570                         atomic_read(&F2FS_I(inode)->i_compr_blocks));
3571         }
3572
3573         return ret;
3574 }
3575
3576 static int reserve_compress_blocks(struct dnode_of_data *dn, pgoff_t count)
3577 {
3578         struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
3579         unsigned int reserved_blocks = 0;
3580         int cluster_size = F2FS_I(dn->inode)->i_cluster_size;
3581         block_t blkaddr;
3582         int i;
3583
3584         for (i = 0; i < count; i++) {
3585                 blkaddr = data_blkaddr(dn->inode, dn->node_page,
3586                                                 dn->ofs_in_node + i);
3587
3588                 if (!__is_valid_data_blkaddr(blkaddr))
3589                         continue;
3590                 if (unlikely(!f2fs_is_valid_blkaddr(sbi, blkaddr,
3591                                         DATA_GENERIC_ENHANCE))) {
3592                         f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
3593                         return -EFSCORRUPTED;
3594                 }
3595         }
3596
3597         while (count) {
3598                 int compr_blocks = 0;
3599                 blkcnt_t reserved;
3600                 int ret;
3601
3602                 for (i = 0; i < cluster_size; i++, dn->ofs_in_node++) {
3603                         blkaddr = f2fs_data_blkaddr(dn);
3604
3605                         if (i == 0) {
3606                                 if (blkaddr == COMPRESS_ADDR)
3607                                         continue;
3608                                 dn->ofs_in_node += cluster_size;
3609                                 goto next;
3610                         }
3611
3612                         if (__is_valid_data_blkaddr(blkaddr)) {
3613                                 compr_blocks++;
3614                                 continue;
3615                         }
3616
3617                         dn->data_blkaddr = NEW_ADDR;
3618                         f2fs_set_data_blkaddr(dn);
3619                 }
3620
3621                 reserved = cluster_size - compr_blocks;
3622                 ret = inc_valid_block_count(sbi, dn->inode, &reserved);
3623                 if (ret)
3624                         return ret;
3625
3626                 if (reserved != cluster_size - compr_blocks)
3627                         return -ENOSPC;
3628
3629                 f2fs_i_compr_blocks_update(dn->inode, compr_blocks, true);
3630
3631                 reserved_blocks += reserved;
3632 next:
3633                 count -= cluster_size;
3634         }
3635
3636         return reserved_blocks;
3637 }
3638
3639 static int f2fs_reserve_compress_blocks(struct file *filp, unsigned long arg)
3640 {
3641         struct inode *inode = file_inode(filp);
3642         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3643         pgoff_t page_idx = 0, last_idx;
3644         unsigned int reserved_blocks = 0;
3645         int ret;
3646
3647         if (!f2fs_sb_has_compression(sbi))
3648                 return -EOPNOTSUPP;
3649
3650         if (!f2fs_compressed_file(inode))
3651                 return -EINVAL;
3652
3653         if (f2fs_readonly(sbi->sb))
3654                 return -EROFS;
3655
3656         ret = mnt_want_write_file(filp);
3657         if (ret)
3658                 return ret;
3659
3660         if (atomic_read(&F2FS_I(inode)->i_compr_blocks))
3661                 goto out;
3662
3663         f2fs_balance_fs(sbi, true);
3664
3665         inode_lock(inode);
3666
3667         if (!is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
3668                 ret = -EINVAL;
3669                 goto unlock_inode;
3670         }
3671
3672         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3673         filemap_invalidate_lock(inode->i_mapping);
3674
3675         last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3676
3677         while (page_idx < last_idx) {
3678                 struct dnode_of_data dn;
3679                 pgoff_t end_offset, count;
3680
3681                 set_new_dnode(&dn, inode, NULL, NULL, 0);
3682                 ret = f2fs_get_dnode_of_data(&dn, page_idx, LOOKUP_NODE);
3683                 if (ret) {
3684                         if (ret == -ENOENT) {
3685                                 page_idx = f2fs_get_next_page_offset(&dn,
3686                                                                 page_idx);
3687                                 ret = 0;
3688                                 continue;
3689                         }
3690                         break;
3691                 }
3692
3693                 end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
3694                 count = min(end_offset - dn.ofs_in_node, last_idx - page_idx);
3695                 count = round_up(count, F2FS_I(inode)->i_cluster_size);
3696
3697                 ret = reserve_compress_blocks(&dn, count);
3698
3699                 f2fs_put_dnode(&dn);
3700
3701                 if (ret < 0)
3702                         break;
3703
3704                 page_idx += count;
3705                 reserved_blocks += ret;
3706         }
3707
3708         filemap_invalidate_unlock(inode->i_mapping);
3709         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3710
3711         if (ret >= 0) {
3712                 clear_inode_flag(inode, FI_COMPRESS_RELEASED);
3713                 inode->i_ctime = current_time(inode);
3714                 f2fs_mark_inode_dirty_sync(inode, true);
3715         }
3716 unlock_inode:
3717         inode_unlock(inode);
3718 out:
3719         mnt_drop_write_file(filp);
3720
3721         if (ret >= 0) {
3722                 ret = put_user(reserved_blocks, (u64 __user *)arg);
3723         } else if (reserved_blocks &&
3724                         atomic_read(&F2FS_I(inode)->i_compr_blocks)) {
3725                 set_sbi_flag(sbi, SBI_NEED_FSCK);
3726                 f2fs_warn(sbi, "%s: partial blocks were released i_ino=%lx "
3727                         "iblocks=%llu, reserved=%u, compr_blocks=%u, "
3728                         "run fsck to fix.",
3729                         __func__, inode->i_ino, inode->i_blocks,
3730                         reserved_blocks,
3731                         atomic_read(&F2FS_I(inode)->i_compr_blocks));
3732         }
3733
3734         return ret;
3735 }
3736
3737 static int f2fs_secure_erase(struct block_device *bdev, struct inode *inode,
3738                 pgoff_t off, block_t block, block_t len, u32 flags)
3739 {
3740         sector_t sector = SECTOR_FROM_BLOCK(block);
3741         sector_t nr_sects = SECTOR_FROM_BLOCK(len);
3742         int ret = 0;
3743
3744         if (flags & F2FS_TRIM_FILE_DISCARD) {
3745                 if (bdev_max_secure_erase_sectors(bdev))
3746                         ret = blkdev_issue_secure_erase(bdev, sector, nr_sects,
3747                                         GFP_NOFS);
3748                 else
3749                         ret = blkdev_issue_discard(bdev, sector, nr_sects,
3750                                         GFP_NOFS);
3751         }
3752
3753         if (!ret && (flags & F2FS_TRIM_FILE_ZEROOUT)) {
3754                 if (IS_ENCRYPTED(inode))
3755                         ret = fscrypt_zeroout_range(inode, off, block, len);
3756                 else
3757                         ret = blkdev_issue_zeroout(bdev, sector, nr_sects,
3758                                         GFP_NOFS, 0);
3759         }
3760
3761         return ret;
3762 }
3763
3764 static int f2fs_sec_trim_file(struct file *filp, unsigned long arg)
3765 {
3766         struct inode *inode = file_inode(filp);
3767         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3768         struct address_space *mapping = inode->i_mapping;
3769         struct block_device *prev_bdev = NULL;
3770         struct f2fs_sectrim_range range;
3771         pgoff_t index, pg_end, prev_index = 0;
3772         block_t prev_block = 0, len = 0;
3773         loff_t end_addr;
3774         bool to_end = false;
3775         int ret = 0;
3776
3777         if (!(filp->f_mode & FMODE_WRITE))
3778                 return -EBADF;
3779
3780         if (copy_from_user(&range, (struct f2fs_sectrim_range __user *)arg,
3781                                 sizeof(range)))
3782                 return -EFAULT;
3783
3784         if (range.flags == 0 || (range.flags & ~F2FS_TRIM_FILE_MASK) ||
3785                         !S_ISREG(inode->i_mode))
3786                 return -EINVAL;
3787
3788         if (((range.flags & F2FS_TRIM_FILE_DISCARD) &&
3789                         !f2fs_hw_support_discard(sbi)) ||
3790                         ((range.flags & F2FS_TRIM_FILE_ZEROOUT) &&
3791                          IS_ENCRYPTED(inode) && f2fs_is_multi_device(sbi)))
3792                 return -EOPNOTSUPP;
3793
3794         file_start_write(filp);
3795         inode_lock(inode);
3796
3797         if (f2fs_is_atomic_file(inode) || f2fs_compressed_file(inode) ||
3798                         range.start >= inode->i_size) {
3799                 ret = -EINVAL;
3800                 goto err;
3801         }
3802
3803         if (range.len == 0)
3804                 goto err;
3805
3806         if (inode->i_size - range.start > range.len) {
3807                 end_addr = range.start + range.len;
3808         } else {
3809                 end_addr = range.len == (u64)-1 ?
3810                         sbi->sb->s_maxbytes : inode->i_size;
3811                 to_end = true;
3812         }
3813
3814         if (!IS_ALIGNED(range.start, F2FS_BLKSIZE) ||
3815                         (!to_end && !IS_ALIGNED(end_addr, F2FS_BLKSIZE))) {
3816                 ret = -EINVAL;
3817                 goto err;
3818         }
3819
3820         index = F2FS_BYTES_TO_BLK(range.start);
3821         pg_end = DIV_ROUND_UP(end_addr, F2FS_BLKSIZE);
3822
3823         ret = f2fs_convert_inline_inode(inode);
3824         if (ret)
3825                 goto err;
3826
3827         f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3828         filemap_invalidate_lock(mapping);
3829
3830         ret = filemap_write_and_wait_range(mapping, range.start,
3831                         to_end ? LLONG_MAX : end_addr - 1);
3832         if (ret)
3833                 goto out;
3834
3835         truncate_inode_pages_range(mapping, range.start,
3836                         to_end ? -1 : end_addr - 1);
3837
3838         while (index < pg_end) {
3839                 struct dnode_of_data dn;
3840                 pgoff_t end_offset, count;
3841                 int i;
3842
3843                 set_new_dnode(&dn, inode, NULL, NULL, 0);
3844                 ret = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
3845                 if (ret) {
3846                         if (ret == -ENOENT) {
3847                                 index = f2fs_get_next_page_offset(&dn, index);
3848                                 continue;
3849                         }
3850                         goto out;
3851                 }
3852
3853                 end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
3854                 count = min(end_offset - dn.ofs_in_node, pg_end - index);
3855                 for (i = 0; i < count; i++, index++, dn.ofs_in_node++) {
3856                         struct block_device *cur_bdev;
3857                         block_t blkaddr = f2fs_data_blkaddr(&dn);
3858
3859                         if (!__is_valid_data_blkaddr(blkaddr))
3860                                 continue;
3861
3862                         if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
3863                                                 DATA_GENERIC_ENHANCE)) {
3864                                 ret = -EFSCORRUPTED;
3865                                 f2fs_put_dnode(&dn);
3866                                 f2fs_handle_error(sbi,
3867                                                 ERROR_INVALID_BLKADDR);
3868                                 goto out;
3869                         }
3870
3871                         cur_bdev = f2fs_target_device(sbi, blkaddr, NULL);
3872                         if (f2fs_is_multi_device(sbi)) {
3873                                 int di = f2fs_target_device_index(sbi, blkaddr);
3874
3875                                 blkaddr -= FDEV(di).start_blk;
3876                         }
3877
3878                         if (len) {
3879                                 if (prev_bdev == cur_bdev &&
3880                                                 index == prev_index + len &&
3881                                                 blkaddr == prev_block + len) {
3882                                         len++;
3883                                 } else {
3884                                         ret = f2fs_secure_erase(prev_bdev,
3885                                                 inode, prev_index, prev_block,
3886                                                 len, range.flags);
3887                                         if (ret) {
3888                                                 f2fs_put_dnode(&dn);
3889                                                 goto out;
3890                                         }
3891
3892                                         len = 0;
3893                                 }
3894                         }
3895
3896                         if (!len) {
3897                                 prev_bdev = cur_bdev;
3898                                 prev_index = index;
3899                                 prev_block = blkaddr;
3900                                 len = 1;
3901                         }
3902                 }
3903
3904                 f2fs_put_dnode(&dn);
3905
3906                 if (fatal_signal_pending(current)) {
3907                         ret = -EINTR;
3908                         goto out;
3909                 }
3910                 cond_resched();
3911         }
3912
3913         if (len)
3914                 ret = f2fs_secure_erase(prev_bdev, inode, prev_index,
3915                                 prev_block, len, range.flags);
3916 out:
3917         filemap_invalidate_unlock(mapping);
3918         f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3919 err:
3920         inode_unlock(inode);
3921         file_end_write(filp);
3922
3923         return ret;
3924 }
3925
3926 static int f2fs_ioc_get_compress_option(struct file *filp, unsigned long arg)
3927 {
3928         struct inode *inode = file_inode(filp);
3929         struct f2fs_comp_option option;
3930
3931         if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
3932                 return -EOPNOTSUPP;
3933
3934         inode_lock_shared(inode);
3935
3936         if (!f2fs_compressed_file(inode)) {
3937                 inode_unlock_shared(inode);
3938                 return -ENODATA;
3939         }
3940
3941         option.algorithm = F2FS_I(inode)->i_compress_algorithm;
3942         option.log_cluster_size = F2FS_I(inode)->i_log_cluster_size;
3943
3944         inode_unlock_shared(inode);
3945
3946         if (copy_to_user((struct f2fs_comp_option __user *)arg, &option,
3947                                 sizeof(option)))
3948                 return -EFAULT;
3949
3950         return 0;
3951 }
3952
3953 static int f2fs_ioc_set_compress_option(struct file *filp, unsigned long arg)
3954 {
3955         struct inode *inode = file_inode(filp);
3956         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3957         struct f2fs_comp_option option;
3958         int ret = 0;
3959
3960         if (!f2fs_sb_has_compression(sbi))
3961                 return -EOPNOTSUPP;
3962
3963         if (!(filp->f_mode & FMODE_WRITE))
3964                 return -EBADF;
3965
3966         if (copy_from_user(&option, (struct f2fs_comp_option __user *)arg,
3967                                 sizeof(option)))
3968                 return -EFAULT;
3969
3970         if (!f2fs_compressed_file(inode) ||
3971                         option.log_cluster_size < MIN_COMPRESS_LOG_SIZE ||
3972                         option.log_cluster_size > MAX_COMPRESS_LOG_SIZE ||
3973                         option.algorithm >= COMPRESS_MAX)
3974                 return -EINVAL;
3975
3976         file_start_write(filp);
3977         inode_lock(inode);
3978
3979         if (f2fs_is_mmap_file(inode) || get_dirty_pages(inode)) {
3980                 ret = -EBUSY;
3981                 goto out;
3982         }
3983
3984         if (F2FS_HAS_BLOCKS(inode)) {
3985                 ret = -EFBIG;
3986                 goto out;
3987         }
3988
3989         F2FS_I(inode)->i_compress_algorithm = option.algorithm;
3990         F2FS_I(inode)->i_log_cluster_size = option.log_cluster_size;
3991         F2FS_I(inode)->i_cluster_size = BIT(option.log_cluster_size);
3992         f2fs_mark_inode_dirty_sync(inode, true);
3993
3994         if (!f2fs_is_compress_backend_ready(inode))
3995                 f2fs_warn(sbi, "compression algorithm is successfully set, "
3996                         "but current kernel doesn't support this algorithm.");
3997 out:
3998         inode_unlock(inode);
3999         file_end_write(filp);
4000
4001         return ret;
4002 }
4003
4004 static int redirty_blocks(struct inode *inode, pgoff_t page_idx, int len)
4005 {
4006         DEFINE_READAHEAD(ractl, NULL, NULL, inode->i_mapping, page_idx);
4007         struct address_space *mapping = inode->i_mapping;
4008         struct page *page;
4009         pgoff_t redirty_idx = page_idx;
4010         int i, page_len = 0, ret = 0;
4011
4012         page_cache_ra_unbounded(&ractl, len, 0);
4013
4014         for (i = 0; i < len; i++, page_idx++) {
4015                 page = read_cache_page(mapping, page_idx, NULL, NULL);
4016                 if (IS_ERR(page)) {
4017                         ret = PTR_ERR(page);
4018                         break;
4019                 }
4020                 page_len++;
4021         }
4022
4023         for (i = 0; i < page_len; i++, redirty_idx++) {
4024                 page = find_lock_page(mapping, redirty_idx);
4025
4026                 /* It will never fail, when page has pinned above */
4027                 f2fs_bug_on(F2FS_I_SB(inode), !page);
4028
4029                 set_page_dirty(page);
4030                 f2fs_put_page(page, 1);
4031                 f2fs_put_page(page, 0);
4032         }
4033
4034         return ret;
4035 }
4036
4037 static int f2fs_ioc_decompress_file(struct file *filp)
4038 {
4039         struct inode *inode = file_inode(filp);
4040         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4041         struct f2fs_inode_info *fi = F2FS_I(inode);
4042         pgoff_t page_idx = 0, last_idx;
4043         unsigned int blk_per_seg = sbi->blocks_per_seg;
4044         int cluster_size = fi->i_cluster_size;
4045         int count, ret;
4046
4047         if (!f2fs_sb_has_compression(sbi) ||
4048                         F2FS_OPTION(sbi).compress_mode != COMPR_MODE_USER)
4049                 return -EOPNOTSUPP;
4050
4051         if (!(filp->f_mode & FMODE_WRITE))
4052                 return -EBADF;
4053
4054         if (!f2fs_compressed_file(inode))
4055                 return -EINVAL;
4056
4057         f2fs_balance_fs(sbi, true);
4058
4059         file_start_write(filp);
4060         inode_lock(inode);
4061
4062         if (!f2fs_is_compress_backend_ready(inode)) {
4063                 ret = -EOPNOTSUPP;
4064                 goto out;
4065         }
4066
4067         if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
4068                 ret = -EINVAL;
4069                 goto out;
4070         }
4071
4072         ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
4073         if (ret)
4074                 goto out;
4075
4076         if (!atomic_read(&fi->i_compr_blocks))
4077                 goto out;
4078
4079         last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
4080
4081         count = last_idx - page_idx;
4082         while (count) {
4083                 int len = min(cluster_size, count);
4084
4085                 ret = redirty_blocks(inode, page_idx, len);
4086                 if (ret < 0)
4087                         break;
4088
4089                 if (get_dirty_pages(inode) >= blk_per_seg) {
4090                         ret = filemap_fdatawrite(inode->i_mapping);
4091                         if (ret < 0)
4092                                 break;
4093                 }
4094
4095                 count -= len;
4096                 page_idx += len;
4097         }
4098
4099         if (!ret)
4100                 ret = filemap_write_and_wait_range(inode->i_mapping, 0,
4101                                                         LLONG_MAX);
4102
4103         if (ret)
4104                 f2fs_warn(sbi, "%s: The file might be partially decompressed (errno=%d). Please delete the file.",
4105                           __func__, ret);
4106 out:
4107         inode_unlock(inode);
4108         file_end_write(filp);
4109
4110         return ret;
4111 }
4112
4113 static int f2fs_ioc_compress_file(struct file *filp)
4114 {
4115         struct inode *inode = file_inode(filp);
4116         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4117         pgoff_t page_idx = 0, last_idx;
4118         unsigned int blk_per_seg = sbi->blocks_per_seg;
4119         int cluster_size = F2FS_I(inode)->i_cluster_size;
4120         int count, ret;
4121
4122         if (!f2fs_sb_has_compression(sbi) ||
4123                         F2FS_OPTION(sbi).compress_mode != COMPR_MODE_USER)
4124                 return -EOPNOTSUPP;
4125
4126         if (!(filp->f_mode & FMODE_WRITE))
4127                 return -EBADF;
4128
4129         if (!f2fs_compressed_file(inode))
4130                 return -EINVAL;
4131
4132         f2fs_balance_fs(sbi, true);
4133
4134         file_start_write(filp);
4135         inode_lock(inode);
4136
4137         if (!f2fs_is_compress_backend_ready(inode)) {
4138                 ret = -EOPNOTSUPP;
4139                 goto out;
4140         }
4141
4142         if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
4143                 ret = -EINVAL;
4144                 goto out;
4145         }
4146
4147         ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
4148         if (ret)
4149                 goto out;
4150
4151         set_inode_flag(inode, FI_ENABLE_COMPRESS);
4152
4153         last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
4154
4155         count = last_idx - page_idx;
4156         while (count) {
4157                 int len = min(cluster_size, count);
4158
4159                 ret = redirty_blocks(inode, page_idx, len);
4160                 if (ret < 0)
4161                         break;
4162
4163                 if (get_dirty_pages(inode) >= blk_per_seg) {
4164                         ret = filemap_fdatawrite(inode->i_mapping);
4165                         if (ret < 0)
4166                                 break;
4167                 }
4168
4169                 count -= len;
4170                 page_idx += len;
4171         }
4172
4173         if (!ret)
4174                 ret = filemap_write_and_wait_range(inode->i_mapping, 0,
4175                                                         LLONG_MAX);
4176
4177         clear_inode_flag(inode, FI_ENABLE_COMPRESS);
4178
4179         if (ret)
4180                 f2fs_warn(sbi, "%s: The file might be partially compressed (errno=%d). Please delete the file.",
4181                           __func__, ret);
4182 out:
4183         inode_unlock(inode);
4184         file_end_write(filp);
4185
4186         return ret;
4187 }
4188
4189 static long __f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
4190 {
4191         switch (cmd) {
4192         case FS_IOC_GETVERSION:
4193                 return f2fs_ioc_getversion(filp, arg);
4194         case F2FS_IOC_START_ATOMIC_WRITE:
4195                 return f2fs_ioc_start_atomic_write(filp, false);
4196         case F2FS_IOC_START_ATOMIC_REPLACE:
4197                 return f2fs_ioc_start_atomic_write(filp, true);
4198         case F2FS_IOC_COMMIT_ATOMIC_WRITE:
4199                 return f2fs_ioc_commit_atomic_write(filp);
4200         case F2FS_IOC_ABORT_ATOMIC_WRITE:
4201                 return f2fs_ioc_abort_atomic_write(filp);
4202         case F2FS_IOC_START_VOLATILE_WRITE:
4203         case F2FS_IOC_RELEASE_VOLATILE_WRITE:
4204                 return -EOPNOTSUPP;
4205         case F2FS_IOC_SHUTDOWN:
4206                 return f2fs_ioc_shutdown(filp, arg);
4207         case FITRIM:
4208                 return f2fs_ioc_fitrim(filp, arg);
4209         case FS_IOC_SET_ENCRYPTION_POLICY:
4210                 return f2fs_ioc_set_encryption_policy(filp, arg);
4211         case FS_IOC_GET_ENCRYPTION_POLICY:
4212                 return f2fs_ioc_get_encryption_policy(filp, arg);
4213         case FS_IOC_GET_ENCRYPTION_PWSALT:
4214                 return f2fs_ioc_get_encryption_pwsalt(filp, arg);
4215         case FS_IOC_GET_ENCRYPTION_POLICY_EX:
4216                 return f2fs_ioc_get_encryption_policy_ex(filp, arg);
4217         case FS_IOC_ADD_ENCRYPTION_KEY:
4218                 return f2fs_ioc_add_encryption_key(filp, arg);
4219         case FS_IOC_REMOVE_ENCRYPTION_KEY:
4220                 return f2fs_ioc_remove_encryption_key(filp, arg);
4221         case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
4222                 return f2fs_ioc_remove_encryption_key_all_users(filp, arg);
4223         case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
4224                 return f2fs_ioc_get_encryption_key_status(filp, arg);
4225         case FS_IOC_GET_ENCRYPTION_NONCE:
4226                 return f2fs_ioc_get_encryption_nonce(filp, arg);
4227         case F2FS_IOC_GARBAGE_COLLECT:
4228                 return f2fs_ioc_gc(filp, arg);
4229         case F2FS_IOC_GARBAGE_COLLECT_RANGE:
4230                 return f2fs_ioc_gc_range(filp, arg);
4231         case F2FS_IOC_WRITE_CHECKPOINT:
4232                 return f2fs_ioc_write_checkpoint(filp);
4233         case F2FS_IOC_DEFRAGMENT:
4234                 return f2fs_ioc_defragment(filp, arg);
4235         case F2FS_IOC_MOVE_RANGE:
4236                 return f2fs_ioc_move_range(filp, arg);
4237         case F2FS_IOC_FLUSH_DEVICE:
4238                 return f2fs_ioc_flush_device(filp, arg);
4239         case F2FS_IOC_GET_FEATURES:
4240                 return f2fs_ioc_get_features(filp, arg);
4241         case F2FS_IOC_GET_PIN_FILE:
4242                 return f2fs_ioc_get_pin_file(filp, arg);
4243         case F2FS_IOC_SET_PIN_FILE:
4244                 return f2fs_ioc_set_pin_file(filp, arg);
4245         case F2FS_IOC_PRECACHE_EXTENTS:
4246                 return f2fs_ioc_precache_extents(filp);
4247         case F2FS_IOC_RESIZE_FS:
4248                 return f2fs_ioc_resize_fs(filp, arg);
4249         case FS_IOC_ENABLE_VERITY:
4250                 return f2fs_ioc_enable_verity(filp, arg);
4251         case FS_IOC_MEASURE_VERITY:
4252                 return f2fs_ioc_measure_verity(filp, arg);
4253         case FS_IOC_READ_VERITY_METADATA:
4254                 return f2fs_ioc_read_verity_metadata(filp, arg);
4255         case FS_IOC_GETFSLABEL:
4256                 return f2fs_ioc_getfslabel(filp, arg);
4257         case FS_IOC_SETFSLABEL:
4258                 return f2fs_ioc_setfslabel(filp, arg);
4259         case F2FS_IOC_GET_COMPRESS_BLOCKS:
4260                 return f2fs_ioc_get_compress_blocks(filp, arg);
4261         case F2FS_IOC_RELEASE_COMPRESS_BLOCKS:
4262                 return f2fs_release_compress_blocks(filp, arg);
4263         case F2FS_IOC_RESERVE_COMPRESS_BLOCKS:
4264                 return f2fs_reserve_compress_blocks(filp, arg);
4265         case F2FS_IOC_SEC_TRIM_FILE:
4266                 return f2fs_sec_trim_file(filp, arg);
4267         case F2FS_IOC_GET_COMPRESS_OPTION:
4268                 return f2fs_ioc_get_compress_option(filp, arg);
4269         case F2FS_IOC_SET_COMPRESS_OPTION:
4270                 return f2fs_ioc_set_compress_option(filp, arg);
4271         case F2FS_IOC_DECOMPRESS_FILE:
4272                 return f2fs_ioc_decompress_file(filp);
4273         case F2FS_IOC_COMPRESS_FILE:
4274                 return f2fs_ioc_compress_file(filp);
4275         default:
4276                 return -ENOTTY;
4277         }
4278 }
4279
4280 long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
4281 {
4282         if (unlikely(f2fs_cp_error(F2FS_I_SB(file_inode(filp)))))
4283                 return -EIO;
4284         if (!f2fs_is_checkpoint_ready(F2FS_I_SB(file_inode(filp))))
4285                 return -ENOSPC;
4286
4287         return __f2fs_ioctl(filp, cmd, arg);
4288 }
4289
4290 /*
4291  * Return %true if the given read or write request should use direct I/O, or
4292  * %false if it should use buffered I/O.
4293  */
4294 static bool f2fs_should_use_dio(struct inode *inode, struct kiocb *iocb,
4295                                 struct iov_iter *iter)
4296 {
4297         unsigned int align;
4298
4299         if (!(iocb->ki_flags & IOCB_DIRECT))
4300                 return false;
4301
4302         if (f2fs_force_buffered_io(inode, iov_iter_rw(iter)))
4303                 return false;
4304
4305         /*
4306          * Direct I/O not aligned to the disk's logical_block_size will be
4307          * attempted, but will fail with -EINVAL.
4308          *
4309          * f2fs additionally requires that direct I/O be aligned to the
4310          * filesystem block size, which is often a stricter requirement.
4311          * However, f2fs traditionally falls back to buffered I/O on requests
4312          * that are logical_block_size-aligned but not fs-block aligned.
4313          *
4314          * The below logic implements this behavior.
4315          */
4316         align = iocb->ki_pos | iov_iter_alignment(iter);
4317         if (!IS_ALIGNED(align, i_blocksize(inode)) &&
4318             IS_ALIGNED(align, bdev_logical_block_size(inode->i_sb->s_bdev)))
4319                 return false;
4320
4321         return true;
4322 }
4323
4324 static int f2fs_dio_read_end_io(struct kiocb *iocb, ssize_t size, int error,
4325                                 unsigned int flags)
4326 {
4327         struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(iocb->ki_filp));
4328
4329         dec_page_count(sbi, F2FS_DIO_READ);
4330         if (error)
4331                 return error;
4332         f2fs_update_iostat(sbi, NULL, APP_DIRECT_READ_IO, size);
4333         return 0;
4334 }
4335
4336 static const struct iomap_dio_ops f2fs_iomap_dio_read_ops = {
4337         .end_io = f2fs_dio_read_end_io,
4338 };
4339
4340 static ssize_t f2fs_dio_read_iter(struct kiocb *iocb, struct iov_iter *to)
4341 {
4342         struct file *file = iocb->ki_filp;
4343         struct inode *inode = file_inode(file);
4344         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4345         struct f2fs_inode_info *fi = F2FS_I(inode);
4346         const loff_t pos = iocb->ki_pos;
4347         const size_t count = iov_iter_count(to);
4348         struct iomap_dio *dio;
4349         ssize_t ret;
4350
4351         if (count == 0)
4352                 return 0; /* skip atime update */
4353
4354         trace_f2fs_direct_IO_enter(inode, iocb, count, READ);
4355
4356         if (iocb->ki_flags & IOCB_NOWAIT) {
4357                 if (!f2fs_down_read_trylock(&fi->i_gc_rwsem[READ])) {
4358                         ret = -EAGAIN;
4359                         goto out;
4360                 }
4361         } else {
4362                 f2fs_down_read(&fi->i_gc_rwsem[READ]);
4363         }
4364
4365         /*
4366          * We have to use __iomap_dio_rw() and iomap_dio_complete() instead of
4367          * the higher-level function iomap_dio_rw() in order to ensure that the
4368          * F2FS_DIO_READ counter will be decremented correctly in all cases.
4369          */
4370         inc_page_count(sbi, F2FS_DIO_READ);
4371         dio = __iomap_dio_rw(iocb, to, &f2fs_iomap_ops,
4372                              &f2fs_iomap_dio_read_ops, 0, NULL, 0);
4373         if (IS_ERR_OR_NULL(dio)) {
4374                 ret = PTR_ERR_OR_ZERO(dio);
4375                 if (ret != -EIOCBQUEUED)
4376                         dec_page_count(sbi, F2FS_DIO_READ);
4377         } else {
4378                 ret = iomap_dio_complete(dio);
4379         }
4380
4381         f2fs_up_read(&fi->i_gc_rwsem[READ]);
4382
4383         file_accessed(file);
4384 out:
4385         trace_f2fs_direct_IO_exit(inode, pos, count, READ, ret);
4386         return ret;
4387 }
4388
4389 static void f2fs_trace_rw_file_path(struct file *file, loff_t pos, size_t count,
4390                                     int rw)
4391 {
4392         struct inode *inode = file_inode(file);
4393         char *buf, *path;
4394
4395         buf = f2fs_getname(F2FS_I_SB(inode));
4396         if (!buf)
4397                 return;
4398         path = dentry_path_raw(file_dentry(file), buf, PATH_MAX);
4399         if (IS_ERR(path))
4400                 goto free_buf;
4401         if (rw == WRITE)
4402                 trace_f2fs_datawrite_start(inode, pos, count,
4403                                 current->pid, path, current->comm);
4404         else
4405                 trace_f2fs_dataread_start(inode, pos, count,
4406                                 current->pid, path, current->comm);
4407 free_buf:
4408         f2fs_putname(buf);
4409 }
4410
4411 static ssize_t f2fs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
4412 {
4413         struct inode *inode = file_inode(iocb->ki_filp);
4414         const loff_t pos = iocb->ki_pos;
4415         ssize_t ret;
4416
4417         if (!f2fs_is_compress_backend_ready(inode))
4418                 return -EOPNOTSUPP;
4419
4420         if (trace_f2fs_dataread_start_enabled())
4421                 f2fs_trace_rw_file_path(iocb->ki_filp, iocb->ki_pos,
4422                                         iov_iter_count(to), READ);
4423
4424         if (f2fs_should_use_dio(inode, iocb, to)) {
4425                 ret = f2fs_dio_read_iter(iocb, to);
4426         } else {
4427                 ret = filemap_read(iocb, to, 0);
4428                 if (ret > 0)
4429                         f2fs_update_iostat(F2FS_I_SB(inode), inode,
4430                                                 APP_BUFFERED_READ_IO, ret);
4431         }
4432         if (trace_f2fs_dataread_end_enabled())
4433                 trace_f2fs_dataread_end(inode, pos, ret);
4434         return ret;
4435 }
4436
4437 static ssize_t f2fs_file_splice_read(struct file *in, loff_t *ppos,
4438                                      struct pipe_inode_info *pipe,
4439                                      size_t len, unsigned int flags)
4440 {
4441         struct inode *inode = file_inode(in);
4442         const loff_t pos = *ppos;
4443         ssize_t ret;
4444
4445         if (!f2fs_is_compress_backend_ready(inode))
4446                 return -EOPNOTSUPP;
4447
4448         if (trace_f2fs_dataread_start_enabled())
4449                 f2fs_trace_rw_file_path(in, pos, len, READ);
4450
4451         ret = filemap_splice_read(in, ppos, pipe, len, flags);
4452         if (ret > 0)
4453                 f2fs_update_iostat(F2FS_I_SB(inode), inode,
4454                                    APP_BUFFERED_READ_IO, ret);
4455
4456         if (trace_f2fs_dataread_end_enabled())
4457                 trace_f2fs_dataread_end(inode, pos, ret);
4458         return ret;
4459 }
4460
4461 static ssize_t f2fs_write_checks(struct kiocb *iocb, struct iov_iter *from)
4462 {
4463         struct file *file = iocb->ki_filp;
4464         struct inode *inode = file_inode(file);
4465         ssize_t count;
4466         int err;
4467
4468         if (IS_IMMUTABLE(inode))
4469                 return -EPERM;
4470
4471         if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED))
4472                 return -EPERM;
4473
4474         count = generic_write_checks(iocb, from);
4475         if (count <= 0)
4476                 return count;
4477
4478         err = file_modified(file);
4479         if (err)
4480                 return err;
4481         return count;
4482 }
4483
4484 /*
4485  * Preallocate blocks for a write request, if it is possible and helpful to do
4486  * so.  Returns a positive number if blocks may have been preallocated, 0 if no
4487  * blocks were preallocated, or a negative errno value if something went
4488  * seriously wrong.  Also sets FI_PREALLOCATED_ALL on the inode if *all* the
4489  * requested blocks (not just some of them) have been allocated.
4490  */
4491 static int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *iter,
4492                                    bool dio)
4493 {
4494         struct inode *inode = file_inode(iocb->ki_filp);
4495         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4496         const loff_t pos = iocb->ki_pos;
4497         const size_t count = iov_iter_count(iter);
4498         struct f2fs_map_blocks map = {};
4499         int flag;
4500         int ret;
4501
4502         /* If it will be an out-of-place direct write, don't bother. */
4503         if (dio && f2fs_lfs_mode(sbi))
4504                 return 0;
4505         /*
4506          * Don't preallocate holes aligned to DIO_SKIP_HOLES which turns into
4507          * buffered IO, if DIO meets any holes.
4508          */
4509         if (dio && i_size_read(inode) &&
4510                 (F2FS_BYTES_TO_BLK(pos) < F2FS_BLK_ALIGN(i_size_read(inode))))
4511                 return 0;
4512
4513         /* No-wait I/O can't allocate blocks. */
4514         if (iocb->ki_flags & IOCB_NOWAIT)
4515                 return 0;
4516
4517         /* If it will be a short write, don't bother. */
4518         if (fault_in_iov_iter_readable(iter, count))
4519                 return 0;
4520
4521         if (f2fs_has_inline_data(inode)) {
4522                 /* If the data will fit inline, don't bother. */
4523                 if (pos + count <= MAX_INLINE_DATA(inode))
4524                         return 0;
4525                 ret = f2fs_convert_inline_inode(inode);
4526                 if (ret)
4527                         return ret;
4528         }
4529
4530         /* Do not preallocate blocks that will be written partially in 4KB. */
4531         map.m_lblk = F2FS_BLK_ALIGN(pos);
4532         map.m_len = F2FS_BYTES_TO_BLK(pos + count);
4533         if (map.m_len > map.m_lblk)
4534                 map.m_len -= map.m_lblk;
4535         else
4536                 map.m_len = 0;
4537         map.m_may_create = true;
4538         if (dio) {
4539                 map.m_seg_type = f2fs_rw_hint_to_seg_type(inode->i_write_hint);
4540                 flag = F2FS_GET_BLOCK_PRE_DIO;
4541         } else {
4542                 map.m_seg_type = NO_CHECK_TYPE;
4543                 flag = F2FS_GET_BLOCK_PRE_AIO;
4544         }
4545
4546         ret = f2fs_map_blocks(inode, &map, flag);
4547         /* -ENOSPC|-EDQUOT are fine to report the number of allocated blocks. */
4548         if (ret < 0 && !((ret == -ENOSPC || ret == -EDQUOT) && map.m_len > 0))
4549                 return ret;
4550         if (ret == 0)
4551                 set_inode_flag(inode, FI_PREALLOCATED_ALL);
4552         return map.m_len;
4553 }
4554
4555 static ssize_t f2fs_buffered_write_iter(struct kiocb *iocb,
4556                                         struct iov_iter *from)
4557 {
4558         struct file *file = iocb->ki_filp;
4559         struct inode *inode = file_inode(file);
4560         ssize_t ret;
4561
4562         if (iocb->ki_flags & IOCB_NOWAIT)
4563                 return -EOPNOTSUPP;
4564
4565         ret = generic_perform_write(iocb, from);
4566
4567         if (ret > 0) {
4568                 f2fs_update_iostat(F2FS_I_SB(inode), inode,
4569                                                 APP_BUFFERED_IO, ret);
4570         }
4571         return ret;
4572 }
4573
4574 static int f2fs_dio_write_end_io(struct kiocb *iocb, ssize_t size, int error,
4575                                  unsigned int flags)
4576 {
4577         struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(iocb->ki_filp));
4578
4579         dec_page_count(sbi, F2FS_DIO_WRITE);
4580         if (error)
4581                 return error;
4582         f2fs_update_iostat(sbi, NULL, APP_DIRECT_IO, size);
4583         return 0;
4584 }
4585
4586 static const struct iomap_dio_ops f2fs_iomap_dio_write_ops = {
4587         .end_io = f2fs_dio_write_end_io,
4588 };
4589
4590 static void f2fs_flush_buffered_write(struct address_space *mapping,
4591                                       loff_t start_pos, loff_t end_pos)
4592 {
4593         int ret;
4594
4595         ret = filemap_write_and_wait_range(mapping, start_pos, end_pos);
4596         if (ret < 0)
4597                 return;
4598         invalidate_mapping_pages(mapping,
4599                                  start_pos >> PAGE_SHIFT,
4600                                  end_pos >> PAGE_SHIFT);
4601 }
4602
4603 static ssize_t f2fs_dio_write_iter(struct kiocb *iocb, struct iov_iter *from,
4604                                    bool *may_need_sync)
4605 {
4606         struct file *file = iocb->ki_filp;
4607         struct inode *inode = file_inode(file);
4608         struct f2fs_inode_info *fi = F2FS_I(inode);
4609         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4610         const bool do_opu = f2fs_lfs_mode(sbi);
4611         const loff_t pos = iocb->ki_pos;
4612         const ssize_t count = iov_iter_count(from);
4613         unsigned int dio_flags;
4614         struct iomap_dio *dio;
4615         ssize_t ret;
4616
4617         trace_f2fs_direct_IO_enter(inode, iocb, count, WRITE);
4618
4619         if (iocb->ki_flags & IOCB_NOWAIT) {
4620                 /* f2fs_convert_inline_inode() and block allocation can block */
4621                 if (f2fs_has_inline_data(inode) ||
4622                     !f2fs_overwrite_io(inode, pos, count)) {
4623                         ret = -EAGAIN;
4624                         goto out;
4625                 }
4626
4627                 if (!f2fs_down_read_trylock(&fi->i_gc_rwsem[WRITE])) {
4628                         ret = -EAGAIN;
4629                         goto out;
4630                 }
4631                 if (do_opu && !f2fs_down_read_trylock(&fi->i_gc_rwsem[READ])) {
4632                         f2fs_up_read(&fi->i_gc_rwsem[WRITE]);
4633                         ret = -EAGAIN;
4634                         goto out;
4635                 }
4636         } else {
4637                 ret = f2fs_convert_inline_inode(inode);
4638                 if (ret)
4639                         goto out;
4640
4641                 f2fs_down_read(&fi->i_gc_rwsem[WRITE]);
4642                 if (do_opu)
4643                         f2fs_down_read(&fi->i_gc_rwsem[READ]);
4644         }
4645
4646         /*
4647          * We have to use __iomap_dio_rw() and iomap_dio_complete() instead of
4648          * the higher-level function iomap_dio_rw() in order to ensure that the
4649          * F2FS_DIO_WRITE counter will be decremented correctly in all cases.
4650          */
4651         inc_page_count(sbi, F2FS_DIO_WRITE);
4652         dio_flags = 0;
4653         if (pos + count > inode->i_size)
4654                 dio_flags |= IOMAP_DIO_FORCE_WAIT;
4655         dio = __iomap_dio_rw(iocb, from, &f2fs_iomap_ops,
4656                              &f2fs_iomap_dio_write_ops, dio_flags, NULL, 0);
4657         if (IS_ERR_OR_NULL(dio)) {
4658                 ret = PTR_ERR_OR_ZERO(dio);
4659                 if (ret == -ENOTBLK)
4660                         ret = 0;
4661                 if (ret != -EIOCBQUEUED)
4662                         dec_page_count(sbi, F2FS_DIO_WRITE);
4663         } else {
4664                 ret = iomap_dio_complete(dio);
4665         }
4666
4667         if (do_opu)
4668                 f2fs_up_read(&fi->i_gc_rwsem[READ]);
4669         f2fs_up_read(&fi->i_gc_rwsem[WRITE]);
4670
4671         if (ret < 0)
4672                 goto out;
4673         if (pos + ret > inode->i_size)
4674                 f2fs_i_size_write(inode, pos + ret);
4675         if (!do_opu)
4676                 set_inode_flag(inode, FI_UPDATE_WRITE);
4677
4678         if (iov_iter_count(from)) {
4679                 ssize_t ret2;
4680                 loff_t bufio_start_pos = iocb->ki_pos;
4681
4682                 /*
4683                  * The direct write was partial, so we need to fall back to a
4684                  * buffered write for the remainder.
4685                  */
4686
4687                 ret2 = f2fs_buffered_write_iter(iocb, from);
4688                 if (iov_iter_count(from))
4689                         f2fs_write_failed(inode, iocb->ki_pos);
4690                 if (ret2 < 0)
4691                         goto out;
4692
4693                 /*
4694                  * Ensure that the pagecache pages are written to disk and
4695                  * invalidated to preserve the expected O_DIRECT semantics.
4696                  */
4697                 if (ret2 > 0) {
4698                         loff_t bufio_end_pos = bufio_start_pos + ret2 - 1;
4699
4700                         ret += ret2;
4701
4702                         f2fs_flush_buffered_write(file->f_mapping,
4703                                                   bufio_start_pos,
4704                                                   bufio_end_pos);
4705                 }
4706         } else {
4707                 /* iomap_dio_rw() already handled the generic_write_sync(). */
4708                 *may_need_sync = false;
4709         }
4710 out:
4711         trace_f2fs_direct_IO_exit(inode, pos, count, WRITE, ret);
4712         return ret;
4713 }
4714
4715 static ssize_t f2fs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
4716 {
4717         struct inode *inode = file_inode(iocb->ki_filp);
4718         const loff_t orig_pos = iocb->ki_pos;
4719         const size_t orig_count = iov_iter_count(from);
4720         loff_t target_size;
4721         bool dio;
4722         bool may_need_sync = true;
4723         int preallocated;
4724         ssize_t ret;
4725
4726         if (unlikely(f2fs_cp_error(F2FS_I_SB(inode)))) {
4727                 ret = -EIO;
4728                 goto out;
4729         }
4730
4731         if (!f2fs_is_compress_backend_ready(inode)) {
4732                 ret = -EOPNOTSUPP;
4733                 goto out;
4734         }
4735
4736         if (iocb->ki_flags & IOCB_NOWAIT) {
4737                 if (!inode_trylock(inode)) {
4738                         ret = -EAGAIN;
4739                         goto out;
4740                 }
4741         } else {
4742                 inode_lock(inode);
4743         }
4744
4745         ret = f2fs_write_checks(iocb, from);
4746         if (ret <= 0)
4747                 goto out_unlock;
4748
4749         /* Determine whether we will do a direct write or a buffered write. */
4750         dio = f2fs_should_use_dio(inode, iocb, from);
4751
4752         /* Possibly preallocate the blocks for the write. */
4753         target_size = iocb->ki_pos + iov_iter_count(from);
4754         preallocated = f2fs_preallocate_blocks(iocb, from, dio);
4755         if (preallocated < 0) {
4756                 ret = preallocated;
4757         } else {
4758                 if (trace_f2fs_datawrite_start_enabled())
4759                         f2fs_trace_rw_file_path(iocb->ki_filp, iocb->ki_pos,
4760                                                 orig_count, WRITE);
4761
4762                 /* Do the actual write. */
4763                 ret = dio ?
4764                         f2fs_dio_write_iter(iocb, from, &may_need_sync) :
4765                         f2fs_buffered_write_iter(iocb, from);
4766
4767                 if (trace_f2fs_datawrite_end_enabled())
4768                         trace_f2fs_datawrite_end(inode, orig_pos, ret);
4769         }
4770
4771         /* Don't leave any preallocated blocks around past i_size. */
4772         if (preallocated && i_size_read(inode) < target_size) {
4773                 f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
4774                 filemap_invalidate_lock(inode->i_mapping);
4775                 if (!f2fs_truncate(inode))
4776                         file_dont_truncate(inode);
4777                 filemap_invalidate_unlock(inode->i_mapping);
4778                 f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
4779         } else {
4780                 file_dont_truncate(inode);
4781         }
4782
4783         clear_inode_flag(inode, FI_PREALLOCATED_ALL);
4784 out_unlock:
4785         inode_unlock(inode);
4786 out:
4787         trace_f2fs_file_write_iter(inode, orig_pos, orig_count, ret);
4788
4789         if (ret > 0 && may_need_sync)
4790                 ret = generic_write_sync(iocb, ret);
4791
4792         /* If buffered IO was forced, flush and drop the data from
4793          * the page cache to preserve O_DIRECT semantics
4794          */
4795         if (ret > 0 && !dio && (iocb->ki_flags & IOCB_DIRECT))
4796                 f2fs_flush_buffered_write(iocb->ki_filp->f_mapping,
4797                                           orig_pos,
4798                                           orig_pos + ret - 1);
4799
4800         return ret;
4801 }
4802
4803 static int f2fs_file_fadvise(struct file *filp, loff_t offset, loff_t len,
4804                 int advice)
4805 {
4806         struct address_space *mapping;
4807         struct backing_dev_info *bdi;
4808         struct inode *inode = file_inode(filp);
4809         int err;
4810
4811         if (advice == POSIX_FADV_SEQUENTIAL) {
4812                 if (S_ISFIFO(inode->i_mode))
4813                         return -ESPIPE;
4814
4815                 mapping = filp->f_mapping;
4816                 if (!mapping || len < 0)
4817                         return -EINVAL;
4818
4819                 bdi = inode_to_bdi(mapping->host);
4820                 filp->f_ra.ra_pages = bdi->ra_pages *
4821                         F2FS_I_SB(inode)->seq_file_ra_mul;
4822                 spin_lock(&filp->f_lock);
4823                 filp->f_mode &= ~FMODE_RANDOM;
4824                 spin_unlock(&filp->f_lock);
4825                 return 0;
4826         }
4827
4828         err = generic_fadvise(filp, offset, len, advice);
4829         if (!err && advice == POSIX_FADV_DONTNEED &&
4830                 test_opt(F2FS_I_SB(inode), COMPRESS_CACHE) &&
4831                 f2fs_compressed_file(inode))
4832                 f2fs_invalidate_compress_pages(F2FS_I_SB(inode), inode->i_ino);
4833
4834         return err;
4835 }
4836
4837 #ifdef CONFIG_COMPAT
4838 struct compat_f2fs_gc_range {
4839         u32 sync;
4840         compat_u64 start;
4841         compat_u64 len;
4842 };
4843 #define F2FS_IOC32_GARBAGE_COLLECT_RANGE        _IOW(F2FS_IOCTL_MAGIC, 11,\
4844                                                 struct compat_f2fs_gc_range)
4845
4846 static int f2fs_compat_ioc_gc_range(struct file *file, unsigned long arg)
4847 {
4848         struct compat_f2fs_gc_range __user *urange;
4849         struct f2fs_gc_range range;
4850         int err;
4851
4852         urange = compat_ptr(arg);
4853         err = get_user(range.sync, &urange->sync);
4854         err |= get_user(range.start, &urange->start);
4855         err |= get_user(range.len, &urange->len);
4856         if (err)
4857                 return -EFAULT;
4858
4859         return __f2fs_ioc_gc_range(file, &range);
4860 }
4861
4862 struct compat_f2fs_move_range {
4863         u32 dst_fd;
4864         compat_u64 pos_in;
4865         compat_u64 pos_out;
4866         compat_u64 len;
4867 };
4868 #define F2FS_IOC32_MOVE_RANGE           _IOWR(F2FS_IOCTL_MAGIC, 9,      \
4869                                         struct compat_f2fs_move_range)
4870
4871 static int f2fs_compat_ioc_move_range(struct file *file, unsigned long arg)
4872 {
4873         struct compat_f2fs_move_range __user *urange;
4874         struct f2fs_move_range range;
4875         int err;
4876
4877         urange = compat_ptr(arg);
4878         err = get_user(range.dst_fd, &urange->dst_fd);
4879         err |= get_user(range.pos_in, &urange->pos_in);
4880         err |= get_user(range.pos_out, &urange->pos_out);
4881         err |= get_user(range.len, &urange->len);
4882         if (err)
4883                 return -EFAULT;
4884
4885         return __f2fs_ioc_move_range(file, &range);
4886 }
4887
4888 long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4889 {
4890         if (unlikely(f2fs_cp_error(F2FS_I_SB(file_inode(file)))))
4891                 return -EIO;
4892         if (!f2fs_is_checkpoint_ready(F2FS_I_SB(file_inode(file))))
4893                 return -ENOSPC;
4894
4895         switch (cmd) {
4896         case FS_IOC32_GETVERSION:
4897                 cmd = FS_IOC_GETVERSION;
4898                 break;
4899         case F2FS_IOC32_GARBAGE_COLLECT_RANGE:
4900                 return f2fs_compat_ioc_gc_range(file, arg);
4901         case F2FS_IOC32_MOVE_RANGE:
4902                 return f2fs_compat_ioc_move_range(file, arg);
4903         case F2FS_IOC_START_ATOMIC_WRITE:
4904         case F2FS_IOC_START_ATOMIC_REPLACE:
4905         case F2FS_IOC_COMMIT_ATOMIC_WRITE:
4906         case F2FS_IOC_START_VOLATILE_WRITE:
4907         case F2FS_IOC_RELEASE_VOLATILE_WRITE:
4908         case F2FS_IOC_ABORT_ATOMIC_WRITE:
4909         case F2FS_IOC_SHUTDOWN:
4910         case FITRIM:
4911         case FS_IOC_SET_ENCRYPTION_POLICY:
4912         case FS_IOC_GET_ENCRYPTION_PWSALT:
4913         case FS_IOC_GET_ENCRYPTION_POLICY:
4914         case FS_IOC_GET_ENCRYPTION_POLICY_EX:
4915         case FS_IOC_ADD_ENCRYPTION_KEY:
4916         case FS_IOC_REMOVE_ENCRYPTION_KEY:
4917         case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
4918         case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
4919         case FS_IOC_GET_ENCRYPTION_NONCE:
4920         case F2FS_IOC_GARBAGE_COLLECT:
4921         case F2FS_IOC_WRITE_CHECKPOINT:
4922         case F2FS_IOC_DEFRAGMENT:
4923         case F2FS_IOC_FLUSH_DEVICE:
4924         case F2FS_IOC_GET_FEATURES:
4925         case F2FS_IOC_GET_PIN_FILE:
4926         case F2FS_IOC_SET_PIN_FILE:
4927         case F2FS_IOC_PRECACHE_EXTENTS:
4928         case F2FS_IOC_RESIZE_FS:
4929         case FS_IOC_ENABLE_VERITY:
4930         case FS_IOC_MEASURE_VERITY:
4931         case FS_IOC_READ_VERITY_METADATA:
4932         case FS_IOC_GETFSLABEL:
4933         case FS_IOC_SETFSLABEL:
4934         case F2FS_IOC_GET_COMPRESS_BLOCKS:
4935         case F2FS_IOC_RELEASE_COMPRESS_BLOCKS:
4936         case F2FS_IOC_RESERVE_COMPRESS_BLOCKS:
4937         case F2FS_IOC_SEC_TRIM_FILE:
4938         case F2FS_IOC_GET_COMPRESS_OPTION:
4939         case F2FS_IOC_SET_COMPRESS_OPTION:
4940         case F2FS_IOC_DECOMPRESS_FILE:
4941         case F2FS_IOC_COMPRESS_FILE:
4942                 break;
4943         default:
4944                 return -ENOIOCTLCMD;
4945         }
4946         return __f2fs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
4947 }
4948 #endif
4949
4950 const struct file_operations f2fs_file_operations = {
4951         .llseek         = f2fs_llseek,
4952         .read_iter      = f2fs_file_read_iter,
4953         .write_iter     = f2fs_file_write_iter,
4954         .iopoll         = iocb_bio_iopoll,
4955         .open           = f2fs_file_open,
4956         .release        = f2fs_release_file,
4957         .mmap           = f2fs_file_mmap,
4958         .flush          = f2fs_file_flush,
4959         .fsync          = f2fs_sync_file,
4960         .fallocate      = f2fs_fallocate,
4961         .unlocked_ioctl = f2fs_ioctl,
4962 #ifdef CONFIG_COMPAT
4963         .compat_ioctl   = f2fs_compat_ioctl,
4964 #endif
4965         .splice_read    = f2fs_file_splice_read,
4966         .splice_write   = iter_file_splice_write,
4967         .fadvise        = f2fs_file_fadvise,
4968 };