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