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