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