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