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