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