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