xref: /freebsd/sys/contrib/openzfs/module/os/linux/zfs/zpl_file.c (revision b1c1ee4429fcca8f69873a8be66184e68e1b19d7)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 2011, Lawrence Livermore National Security, LLC.
24  * Copyright (c) 2015 by Chunwei Chen. All rights reserved.
25  */
26 
27 
28 #ifdef CONFIG_COMPAT
29 #include <linux/compat.h>
30 #endif
31 #include <linux/fs.h>
32 #include <linux/migrate.h>
33 #include <sys/file.h>
34 #include <sys/dmu_objset.h>
35 #include <sys/zfs_znode.h>
36 #include <sys/zfs_vfsops.h>
37 #include <sys/zfs_vnops.h>
38 #include <sys/zfs_project.h>
39 #if defined(HAVE_VFS_SET_PAGE_DIRTY_NOBUFFERS) || \
40     defined(HAVE_VFS_FILEMAP_DIRTY_FOLIO)
41 #include <linux/pagemap.h>
42 #endif
43 #include <linux/fadvise.h>
44 #ifdef HAVE_VFS_FILEMAP_DIRTY_FOLIO
45 #include <linux/writeback.h>
46 #endif
47 
48 /*
49  * When using fallocate(2) to preallocate space, inflate the requested
50  * capacity check by 10% to account for the required metadata blocks.
51  */
52 static unsigned int zfs_fallocate_reserve_percent = 110;
53 
54 static int
zpl_open(struct inode * ip,struct file * filp)55 zpl_open(struct inode *ip, struct file *filp)
56 {
57 	cred_t *cr = CRED();
58 	int error;
59 	fstrans_cookie_t cookie;
60 
61 	error = generic_file_open(ip, filp);
62 	if (error)
63 		return (error);
64 
65 	crhold(cr);
66 	cookie = spl_fstrans_mark();
67 	error = -zfs_open(ip, filp->f_mode, filp->f_flags, cr);
68 	spl_fstrans_unmark(cookie);
69 	crfree(cr);
70 	ASSERT3S(error, <=, 0);
71 
72 	return (error);
73 }
74 
75 static int
zpl_release(struct inode * ip,struct file * filp)76 zpl_release(struct inode *ip, struct file *filp)
77 {
78 	cred_t *cr = CRED();
79 	int error;
80 	fstrans_cookie_t cookie;
81 
82 	cookie = spl_fstrans_mark();
83 	if (ITOZ(ip)->z_atime_dirty)
84 		zfs_mark_inode_dirty(ip);
85 
86 	crhold(cr);
87 	error = -zfs_close(ip, filp->f_flags, cr);
88 	spl_fstrans_unmark(cookie);
89 	crfree(cr);
90 	ASSERT3S(error, <=, 0);
91 
92 	return (error);
93 }
94 
95 static int
zpl_iterate(struct file * filp,struct dir_context * ctx)96 zpl_iterate(struct file *filp, struct dir_context *ctx)
97 {
98 	cred_t *cr = CRED();
99 	int error;
100 	fstrans_cookie_t cookie;
101 
102 	crhold(cr);
103 	cookie = spl_fstrans_mark();
104 	error = -zfs_readdir(file_inode(filp), ctx, cr);
105 	spl_fstrans_unmark(cookie);
106 	crfree(cr);
107 	ASSERT3S(error, <=, 0);
108 
109 	return (error);
110 }
111 
112 static int
zpl_fsync(struct file * filp,loff_t start,loff_t end,int datasync)113 zpl_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
114 {
115 	struct inode *inode = filp->f_mapping->host;
116 	znode_t *zp = ITOZ(inode);
117 	zfsvfs_t *zfsvfs = ITOZSB(inode);
118 	cred_t *cr = CRED();
119 	int error;
120 	fstrans_cookie_t cookie;
121 
122 	/*
123 	 * The variables z_sync_writes_cnt and z_async_writes_cnt work in
124 	 * tandem so that sync writes can detect if there are any non-sync
125 	 * writes going on and vice-versa. The "vice-versa" part to this logic
126 	 * is located in zfs_putpage() where non-sync writes check if there are
127 	 * any ongoing sync writes. If any sync and non-sync writes overlap,
128 	 * we do a commit to complete the non-sync writes since the latter can
129 	 * potentially take several seconds to complete and thus block sync
130 	 * writes in the upcoming call to filemap_write_and_wait_range().
131 	 */
132 	atomic_inc_32(&zp->z_sync_writes_cnt);
133 	/*
134 	 * If the following check does not detect an overlapping non-sync write
135 	 * (say because it's just about to start), then it is guaranteed that
136 	 * the non-sync write will detect this sync write. This is because we
137 	 * always increment z_sync_writes_cnt / z_async_writes_cnt before doing
138 	 * the check on z_async_writes_cnt / z_sync_writes_cnt here and in
139 	 * zfs_putpage() respectively.
140 	 */
141 	if (atomic_load_32(&zp->z_async_writes_cnt) > 0) {
142 		if ((error = zpl_enter(zfsvfs, FTAG)) != 0) {
143 			atomic_dec_32(&zp->z_sync_writes_cnt);
144 			return (error);
145 		}
146 		zil_commit(zfsvfs->z_log, zp->z_id);
147 		zpl_exit(zfsvfs, FTAG);
148 	}
149 
150 	error = filemap_write_and_wait_range(inode->i_mapping, start, end);
151 
152 	/*
153 	 * The sync write is not complete yet but we decrement
154 	 * z_sync_writes_cnt since zfs_fsync() increments and decrements
155 	 * it internally. If a non-sync write starts just after the decrement
156 	 * operation but before we call zfs_fsync(), it may not detect this
157 	 * overlapping sync write but it does not matter since we have already
158 	 * gone past filemap_write_and_wait_range() and we won't block due to
159 	 * the non-sync write.
160 	 */
161 	atomic_dec_32(&zp->z_sync_writes_cnt);
162 
163 	if (error)
164 		return (error);
165 
166 	crhold(cr);
167 	cookie = spl_fstrans_mark();
168 	error = -zfs_fsync(zp, datasync, cr);
169 	spl_fstrans_unmark(cookie);
170 	crfree(cr);
171 	ASSERT3S(error, <=, 0);
172 
173 	return (error);
174 }
175 
176 static inline int
zfs_io_flags(struct kiocb * kiocb)177 zfs_io_flags(struct kiocb *kiocb)
178 {
179 	int flags = 0;
180 
181 #if defined(IOCB_DSYNC)
182 	if (kiocb->ki_flags & IOCB_DSYNC)
183 		flags |= O_DSYNC;
184 #endif
185 #if defined(IOCB_SYNC)
186 	if (kiocb->ki_flags & IOCB_SYNC)
187 		flags |= O_SYNC;
188 #endif
189 #if defined(IOCB_APPEND)
190 	if (kiocb->ki_flags & IOCB_APPEND)
191 		flags |= O_APPEND;
192 #endif
193 #if defined(IOCB_DIRECT)
194 	if (kiocb->ki_flags & IOCB_DIRECT)
195 		flags |= O_DIRECT;
196 #endif
197 	return (flags);
198 }
199 
200 /*
201  * If relatime is enabled, call file_accessed() if zfs_relatime_need_update()
202  * is true.  This is needed since datasets with inherited "relatime" property
203  * aren't necessarily mounted with the MNT_RELATIME flag (e.g. after
204  * `zfs set relatime=...`), which is what relatime test in VFS by
205  * relatime_need_update() is based on.
206  */
207 static inline void
zpl_file_accessed(struct file * filp)208 zpl_file_accessed(struct file *filp)
209 {
210 	struct inode *ip = filp->f_mapping->host;
211 
212 	if (!IS_NOATIME(ip) && ITOZSB(ip)->z_relatime) {
213 		if (zfs_relatime_need_update(ip))
214 			file_accessed(filp);
215 	} else {
216 		file_accessed(filp);
217 	}
218 }
219 
220 static ssize_t
zpl_iter_read(struct kiocb * kiocb,struct iov_iter * to)221 zpl_iter_read(struct kiocb *kiocb, struct iov_iter *to)
222 {
223 	cred_t *cr = CRED();
224 	fstrans_cookie_t cookie;
225 	struct file *filp = kiocb->ki_filp;
226 	ssize_t count = iov_iter_count(to);
227 	zfs_uio_t uio;
228 
229 	zfs_uio_iov_iter_init(&uio, to, kiocb->ki_pos, count);
230 
231 	crhold(cr);
232 	cookie = spl_fstrans_mark();
233 
234 	ssize_t ret = -zfs_read(ITOZ(filp->f_mapping->host), &uio,
235 	    filp->f_flags | zfs_io_flags(kiocb), cr);
236 
237 	spl_fstrans_unmark(cookie);
238 	crfree(cr);
239 
240 	if (ret < 0)
241 		return (ret);
242 
243 	ssize_t read = count - uio.uio_resid;
244 	kiocb->ki_pos += read;
245 
246 	zpl_file_accessed(filp);
247 
248 	return (read);
249 }
250 
251 static inline ssize_t
zpl_generic_write_checks(struct kiocb * kiocb,struct iov_iter * from,size_t * countp)252 zpl_generic_write_checks(struct kiocb *kiocb, struct iov_iter *from,
253     size_t *countp)
254 {
255 	ssize_t ret = generic_write_checks(kiocb, from);
256 	if (ret <= 0)
257 		return (ret);
258 
259 	*countp = ret;
260 
261 	return (0);
262 }
263 
264 static ssize_t
zpl_iter_write(struct kiocb * kiocb,struct iov_iter * from)265 zpl_iter_write(struct kiocb *kiocb, struct iov_iter *from)
266 {
267 	cred_t *cr = CRED();
268 	fstrans_cookie_t cookie;
269 	struct file *filp = kiocb->ki_filp;
270 	struct inode *ip = filp->f_mapping->host;
271 	zfs_uio_t uio;
272 	size_t count = 0;
273 	ssize_t ret;
274 
275 	ret = zpl_generic_write_checks(kiocb, from, &count);
276 	if (ret)
277 		return (ret);
278 
279 	zfs_uio_iov_iter_init(&uio, from, kiocb->ki_pos, count);
280 
281 	crhold(cr);
282 	cookie = spl_fstrans_mark();
283 
284 	ret = -zfs_write(ITOZ(ip), &uio,
285 	    filp->f_flags | zfs_io_flags(kiocb), cr);
286 
287 	spl_fstrans_unmark(cookie);
288 	crfree(cr);
289 
290 	if (ret < 0)
291 		return (ret);
292 
293 	ssize_t wrote = count - uio.uio_resid;
294 	kiocb->ki_pos += wrote;
295 
296 	return (wrote);
297 }
298 
299 static ssize_t
zpl_direct_IO(struct kiocb * kiocb,struct iov_iter * iter)300 zpl_direct_IO(struct kiocb *kiocb, struct iov_iter *iter)
301 {
302 	/*
303 	 * All O_DIRECT requests should be handled by
304 	 * zpl_iter_write/read}(). There is no way kernel generic code should
305 	 * call the direct_IO address_space_operations function. We set this
306 	 * code path to be fatal if it is executed.
307 	 */
308 	PANIC(0);
309 	return (0);
310 }
311 
312 static loff_t
zpl_llseek(struct file * filp,loff_t offset,int whence)313 zpl_llseek(struct file *filp, loff_t offset, int whence)
314 {
315 #if defined(SEEK_HOLE) && defined(SEEK_DATA)
316 	fstrans_cookie_t cookie;
317 
318 	if (whence == SEEK_DATA || whence == SEEK_HOLE) {
319 		struct inode *ip = filp->f_mapping->host;
320 		loff_t maxbytes = ip->i_sb->s_maxbytes;
321 		loff_t error;
322 
323 		spl_inode_lock_shared(ip);
324 		cookie = spl_fstrans_mark();
325 		error = -zfs_holey(ITOZ(ip), whence, &offset);
326 		spl_fstrans_unmark(cookie);
327 		if (error == 0)
328 			error = lseek_execute(filp, ip, offset, maxbytes);
329 		spl_inode_unlock_shared(ip);
330 
331 		return (error);
332 	}
333 #endif /* SEEK_HOLE && SEEK_DATA */
334 
335 	return (generic_file_llseek(filp, offset, whence));
336 }
337 
338 /*
339  * It's worth taking a moment to describe how mmap is implemented
340  * for zfs because it differs considerably from other Linux filesystems.
341  * However, this issue is handled the same way under OpenSolaris.
342  *
343  * The issue is that by design zfs bypasses the Linux page cache and
344  * leaves all caching up to the ARC.  This has been shown to work
345  * well for the common read(2)/write(2) case.  However, mmap(2)
346  * is problem because it relies on being tightly integrated with the
347  * page cache.  To handle this we cache mmap'ed files twice, once in
348  * the ARC and a second time in the page cache.  The code is careful
349  * to keep both copies synchronized.
350  *
351  * When a file with an mmap'ed region is written to using write(2)
352  * both the data in the ARC and existing pages in the page cache
353  * are updated.  For a read(2) data will be read first from the page
354  * cache then the ARC if needed.  Neither a write(2) or read(2) will
355  * will ever result in new pages being added to the page cache.
356  *
357  * New pages are added to the page cache only via .readpage() which
358  * is called when the vfs needs to read a page off disk to back the
359  * virtual memory region.  These pages may be modified without
360  * notifying the ARC and will be written out periodically via
361  * .writepage().  This will occur due to either a sync or the usual
362  * page aging behavior.  Note because a read(2) of a mmap'ed file
363  * will always check the page cache first even when the ARC is out
364  * of date correct data will still be returned.
365  *
366  * While this implementation ensures correct behavior it does have
367  * have some drawbacks.  The most obvious of which is that it
368  * increases the required memory footprint when access mmap'ed
369  * files.  It also adds additional complexity to the code keeping
370  * both caches synchronized.
371  *
372  * Longer term it may be possible to cleanly resolve this wart by
373  * mapping page cache pages directly on to the ARC buffers.  The
374  * Linux address space operations are flexible enough to allow
375  * selection of which pages back a particular index.  The trick
376  * would be working out the details of which subsystem is in
377  * charge, the ARC, the page cache, or both.  It may also prove
378  * helpful to move the ARC buffers to a scatter-gather lists
379  * rather than a vmalloc'ed region.
380  */
381 static int
zpl_mmap(struct file * filp,struct vm_area_struct * vma)382 zpl_mmap(struct file *filp, struct vm_area_struct *vma)
383 {
384 	struct inode *ip = filp->f_mapping->host;
385 	int error;
386 	fstrans_cookie_t cookie;
387 
388 	cookie = spl_fstrans_mark();
389 	error = -zfs_map(ip, vma->vm_pgoff, (caddr_t *)vma->vm_start,
390 	    (size_t)(vma->vm_end - vma->vm_start), vma->vm_flags);
391 	spl_fstrans_unmark(cookie);
392 
393 	if (error)
394 		return (error);
395 
396 	error = generic_file_mmap(filp, vma);
397 	if (error)
398 		return (error);
399 
400 	return (error);
401 }
402 
403 /*
404  * Populate a page with data for the Linux page cache.  This function is
405  * only used to support mmap(2).  There will be an identical copy of the
406  * data in the ARC which is kept up to date via .write() and .writepage().
407  */
408 static inline int
zpl_readpage_common(struct page * pp)409 zpl_readpage_common(struct page *pp)
410 {
411 	fstrans_cookie_t cookie;
412 
413 	ASSERT(PageLocked(pp));
414 
415 	cookie = spl_fstrans_mark();
416 	int error = -zfs_getpage(pp->mapping->host, pp);
417 	spl_fstrans_unmark(cookie);
418 
419 	unlock_page(pp);
420 
421 	return (error);
422 }
423 
424 #ifdef HAVE_VFS_READ_FOLIO
425 static int
zpl_read_folio(struct file * filp,struct folio * folio)426 zpl_read_folio(struct file *filp, struct folio *folio)
427 {
428 	return (zpl_readpage_common(&folio->page));
429 }
430 #else
431 static int
zpl_readpage(struct file * filp,struct page * pp)432 zpl_readpage(struct file *filp, struct page *pp)
433 {
434 	return (zpl_readpage_common(pp));
435 }
436 #endif
437 
438 static int
zpl_readpage_filler(void * data,struct page * pp)439 zpl_readpage_filler(void *data, struct page *pp)
440 {
441 	return (zpl_readpage_common(pp));
442 }
443 
444 /*
445  * Populate a set of pages with data for the Linux page cache.  This
446  * function will only be called for read ahead and never for demand
447  * paging.  For simplicity, the code relies on read_cache_pages() to
448  * correctly lock each page for IO and call zpl_readpage().
449  */
450 #ifdef HAVE_VFS_READPAGES
451 static int
zpl_readpages(struct file * filp,struct address_space * mapping,struct list_head * pages,unsigned nr_pages)452 zpl_readpages(struct file *filp, struct address_space *mapping,
453     struct list_head *pages, unsigned nr_pages)
454 {
455 	return (read_cache_pages(mapping, pages, zpl_readpage_filler, NULL));
456 }
457 #else
458 static void
zpl_readahead(struct readahead_control * ractl)459 zpl_readahead(struct readahead_control *ractl)
460 {
461 	struct page *page;
462 
463 	while ((page = readahead_page(ractl)) != NULL) {
464 		int ret;
465 
466 		ret = zpl_readpage_filler(NULL, page);
467 		put_page(page);
468 		if (ret)
469 			break;
470 	}
471 }
472 #endif
473 
474 static int
zpl_putpage(struct page * pp,struct writeback_control * wbc,void * data)475 zpl_putpage(struct page *pp, struct writeback_control *wbc, void *data)
476 {
477 	boolean_t *for_sync = data;
478 	fstrans_cookie_t cookie;
479 	int ret;
480 
481 	ASSERT(PageLocked(pp));
482 	ASSERT(!PageWriteback(pp));
483 
484 	cookie = spl_fstrans_mark();
485 	ret = zfs_putpage(pp->mapping->host, pp, wbc, *for_sync);
486 	spl_fstrans_unmark(cookie);
487 
488 	return (ret);
489 }
490 
491 #ifdef HAVE_WRITEPAGE_T_FOLIO
492 static int
zpl_putfolio(struct folio * pp,struct writeback_control * wbc,void * data)493 zpl_putfolio(struct folio *pp, struct writeback_control *wbc, void *data)
494 {
495 	return (zpl_putpage(&pp->page, wbc, data));
496 }
497 #endif
498 
499 static inline int
zpl_write_cache_pages(struct address_space * mapping,struct writeback_control * wbc,void * data)500 zpl_write_cache_pages(struct address_space *mapping,
501     struct writeback_control *wbc, void *data)
502 {
503 	int result;
504 
505 #ifdef HAVE_WRITEPAGE_T_FOLIO
506 	result = write_cache_pages(mapping, wbc, zpl_putfolio, data);
507 #else
508 	result = write_cache_pages(mapping, wbc, zpl_putpage, data);
509 #endif
510 	return (result);
511 }
512 
513 static int
zpl_writepages(struct address_space * mapping,struct writeback_control * wbc)514 zpl_writepages(struct address_space *mapping, struct writeback_control *wbc)
515 {
516 	znode_t		*zp = ITOZ(mapping->host);
517 	zfsvfs_t	*zfsvfs = ITOZSB(mapping->host);
518 	enum writeback_sync_modes sync_mode;
519 	int result;
520 
521 	if ((result = zpl_enter(zfsvfs, FTAG)) != 0)
522 		return (result);
523 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
524 		wbc->sync_mode = WB_SYNC_ALL;
525 	zpl_exit(zfsvfs, FTAG);
526 	sync_mode = wbc->sync_mode;
527 
528 	/*
529 	 * We don't want to run write_cache_pages() in SYNC mode here, because
530 	 * that would make putpage() wait for a single page to be committed to
531 	 * disk every single time, resulting in atrocious performance. Instead
532 	 * we run it once in non-SYNC mode so that the ZIL gets all the data,
533 	 * and then we commit it all in one go.
534 	 */
535 	boolean_t for_sync = (sync_mode == WB_SYNC_ALL);
536 	wbc->sync_mode = WB_SYNC_NONE;
537 	result = zpl_write_cache_pages(mapping, wbc, &for_sync);
538 	if (sync_mode != wbc->sync_mode) {
539 		if ((result = zpl_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
540 			return (result);
541 		if (zfsvfs->z_log != NULL)
542 			zil_commit(zfsvfs->z_log, zp->z_id);
543 		zpl_exit(zfsvfs, FTAG);
544 
545 		/*
546 		 * We need to call write_cache_pages() again (we can't just
547 		 * return after the commit) because the previous call in
548 		 * non-SYNC mode does not guarantee that we got all the dirty
549 		 * pages (see the implementation of write_cache_pages() for
550 		 * details). That being said, this is a no-op in most cases.
551 		 */
552 		wbc->sync_mode = sync_mode;
553 		result = zpl_write_cache_pages(mapping, wbc, &for_sync);
554 	}
555 	return (result);
556 }
557 
558 /*
559  * Write out dirty pages to the ARC, this function is only required to
560  * support mmap(2).  Mapped pages may be dirtied by memory operations
561  * which never call .write().  These dirty pages are kept in sync with
562  * the ARC buffers via this hook.
563  */
564 static int
zpl_writepage(struct page * pp,struct writeback_control * wbc)565 zpl_writepage(struct page *pp, struct writeback_control *wbc)
566 {
567 	if (ITOZSB(pp->mapping->host)->z_os->os_sync == ZFS_SYNC_ALWAYS)
568 		wbc->sync_mode = WB_SYNC_ALL;
569 
570 	boolean_t for_sync = (wbc->sync_mode == WB_SYNC_ALL);
571 
572 	return (zpl_putpage(pp, wbc, &for_sync));
573 }
574 
575 /*
576  * The flag combination which matches the behavior of zfs_space() is
577  * FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE.  The FALLOC_FL_PUNCH_HOLE
578  * flag was introduced in the 2.6.38 kernel.
579  *
580  * The original mode=0 (allocate space) behavior can be reasonably emulated
581  * by checking if enough space exists and creating a sparse file, as real
582  * persistent space reservation is not possible due to COW, snapshots, etc.
583  */
584 static long
zpl_fallocate_common(struct inode * ip,int mode,loff_t offset,loff_t len)585 zpl_fallocate_common(struct inode *ip, int mode, loff_t offset, loff_t len)
586 {
587 	cred_t *cr = CRED();
588 	loff_t olen;
589 	fstrans_cookie_t cookie;
590 	int error = 0;
591 
592 	int test_mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE;
593 
594 	if ((mode & ~(FALLOC_FL_KEEP_SIZE | test_mode)) != 0)
595 		return (-EOPNOTSUPP);
596 
597 	if (offset < 0 || len <= 0)
598 		return (-EINVAL);
599 
600 	spl_inode_lock(ip);
601 	olen = i_size_read(ip);
602 
603 	crhold(cr);
604 	cookie = spl_fstrans_mark();
605 	if (mode & (test_mode)) {
606 		flock64_t bf;
607 
608 		if (mode & FALLOC_FL_KEEP_SIZE) {
609 			if (offset > olen)
610 				goto out_unmark;
611 
612 			if (offset + len > olen)
613 				len = olen - offset;
614 		}
615 		bf.l_type = F_WRLCK;
616 		bf.l_whence = SEEK_SET;
617 		bf.l_start = offset;
618 		bf.l_len = len;
619 		bf.l_pid = 0;
620 
621 		error = -zfs_space(ITOZ(ip), F_FREESP, &bf, O_RDWR, offset, cr);
622 	} else if ((mode & ~FALLOC_FL_KEEP_SIZE) == 0) {
623 		unsigned int percent = zfs_fallocate_reserve_percent;
624 		struct kstatfs statfs;
625 
626 		/* Legacy mode, disable fallocate compatibility. */
627 		if (percent == 0) {
628 			error = -EOPNOTSUPP;
629 			goto out_unmark;
630 		}
631 
632 		/*
633 		 * Use zfs_statvfs() instead of dmu_objset_space() since it
634 		 * also checks project quota limits, which are relevant here.
635 		 */
636 		error = zfs_statvfs(ip, &statfs);
637 		if (error)
638 			goto out_unmark;
639 
640 		/*
641 		 * Shrink available space a bit to account for overhead/races.
642 		 * We know the product previously fit into availbytes from
643 		 * dmu_objset_space(), so the smaller product will also fit.
644 		 */
645 		if (len > statfs.f_bavail * (statfs.f_bsize * 100 / percent)) {
646 			error = -ENOSPC;
647 			goto out_unmark;
648 		}
649 		if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > olen)
650 			error = zfs_freesp(ITOZ(ip), offset + len, 0, 0, FALSE);
651 	}
652 out_unmark:
653 	spl_fstrans_unmark(cookie);
654 	spl_inode_unlock(ip);
655 
656 	crfree(cr);
657 
658 	return (error);
659 }
660 
661 static long
zpl_fallocate(struct file * filp,int mode,loff_t offset,loff_t len)662 zpl_fallocate(struct file *filp, int mode, loff_t offset, loff_t len)
663 {
664 	return zpl_fallocate_common(file_inode(filp),
665 	    mode, offset, len);
666 }
667 
668 static int
zpl_ioctl_getversion(struct file * filp,void __user * arg)669 zpl_ioctl_getversion(struct file *filp, void __user *arg)
670 {
671 	uint32_t generation = file_inode(filp)->i_generation;
672 
673 	return (copy_to_user(arg, &generation, sizeof (generation)));
674 }
675 
676 static int
zpl_fadvise(struct file * filp,loff_t offset,loff_t len,int advice)677 zpl_fadvise(struct file *filp, loff_t offset, loff_t len, int advice)
678 {
679 	struct inode *ip = file_inode(filp);
680 	znode_t *zp = ITOZ(ip);
681 	zfsvfs_t *zfsvfs = ITOZSB(ip);
682 	objset_t *os = zfsvfs->z_os;
683 	int error = 0;
684 
685 	if (S_ISFIFO(ip->i_mode))
686 		return (-ESPIPE);
687 
688 	if (offset < 0 || len < 0)
689 		return (-EINVAL);
690 
691 	if ((error = zpl_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
692 		return (error);
693 
694 	switch (advice) {
695 	case POSIX_FADV_SEQUENTIAL:
696 	case POSIX_FADV_WILLNEED:
697 #ifdef HAVE_GENERIC_FADVISE
698 		if (zn_has_cached_data(zp, offset, offset + len - 1))
699 			error = generic_fadvise(filp, offset, len, advice);
700 #endif
701 		/*
702 		 * Pass on the caller's size directly, but note that
703 		 * dmu_prefetch_max will effectively cap it.  If there
704 		 * really is a larger sequential access pattern, perhaps
705 		 * dmu_zfetch will detect it.
706 		 */
707 		if (len == 0)
708 			len = i_size_read(ip) - offset;
709 
710 		dmu_prefetch(os, zp->z_id, 0, offset, len,
711 		    ZIO_PRIORITY_ASYNC_READ);
712 		break;
713 	case POSIX_FADV_NORMAL:
714 	case POSIX_FADV_RANDOM:
715 	case POSIX_FADV_DONTNEED:
716 	case POSIX_FADV_NOREUSE:
717 		/* ignored for now */
718 		break;
719 	default:
720 		error = -EINVAL;
721 		break;
722 	}
723 
724 	zfs_exit(zfsvfs, FTAG);
725 
726 	return (error);
727 }
728 
729 #define	ZFS_FL_USER_VISIBLE	(FS_FL_USER_VISIBLE | ZFS_PROJINHERIT_FL)
730 #define	ZFS_FL_USER_MODIFIABLE	(FS_FL_USER_MODIFIABLE | ZFS_PROJINHERIT_FL)
731 
732 static uint32_t
__zpl_ioctl_getflags(struct inode * ip)733 __zpl_ioctl_getflags(struct inode *ip)
734 {
735 	uint64_t zfs_flags = ITOZ(ip)->z_pflags;
736 	uint32_t ioctl_flags = 0;
737 
738 	if (zfs_flags & ZFS_IMMUTABLE)
739 		ioctl_flags |= FS_IMMUTABLE_FL;
740 
741 	if (zfs_flags & ZFS_APPENDONLY)
742 		ioctl_flags |= FS_APPEND_FL;
743 
744 	if (zfs_flags & ZFS_NODUMP)
745 		ioctl_flags |= FS_NODUMP_FL;
746 
747 	if (zfs_flags & ZFS_PROJINHERIT)
748 		ioctl_flags |= ZFS_PROJINHERIT_FL;
749 
750 	return (ioctl_flags & ZFS_FL_USER_VISIBLE);
751 }
752 
753 /*
754  * Map zfs file z_pflags (xvattr_t) to linux file attributes. Only file
755  * attributes common to both Linux and Solaris are mapped.
756  */
757 static int
zpl_ioctl_getflags(struct file * filp,void __user * arg)758 zpl_ioctl_getflags(struct file *filp, void __user *arg)
759 {
760 	uint32_t flags;
761 	int err;
762 
763 	flags = __zpl_ioctl_getflags(file_inode(filp));
764 	err = copy_to_user(arg, &flags, sizeof (flags));
765 
766 	return (err);
767 }
768 
769 /*
770  * fchange() is a helper macro to detect if we have been asked to change a
771  * flag. This is ugly, but the requirement that we do this is a consequence of
772  * how the Linux file attribute interface was designed. Another consequence is
773  * that concurrent modification of files suffers from a TOCTOU race. Neither
774  * are things we can fix without modifying the kernel-userland interface, which
775  * is outside of our jurisdiction.
776  */
777 
778 #define	fchange(f0, f1, b0, b1) (!((f0) & (b0)) != !((f1) & (b1)))
779 
780 static int
__zpl_ioctl_setflags(struct inode * ip,uint32_t ioctl_flags,xvattr_t * xva)781 __zpl_ioctl_setflags(struct inode *ip, uint32_t ioctl_flags, xvattr_t *xva)
782 {
783 	uint64_t zfs_flags = ITOZ(ip)->z_pflags;
784 	xoptattr_t *xoap;
785 
786 	if (ioctl_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | FS_NODUMP_FL |
787 	    ZFS_PROJINHERIT_FL))
788 		return (-EOPNOTSUPP);
789 
790 	if (ioctl_flags & ~ZFS_FL_USER_MODIFIABLE)
791 		return (-EACCES);
792 
793 	if ((fchange(ioctl_flags, zfs_flags, FS_IMMUTABLE_FL, ZFS_IMMUTABLE) ||
794 	    fchange(ioctl_flags, zfs_flags, FS_APPEND_FL, ZFS_APPENDONLY)) &&
795 	    !capable(CAP_LINUX_IMMUTABLE))
796 		return (-EPERM);
797 
798 	if (!zpl_inode_owner_or_capable(zfs_init_idmap, ip))
799 		return (-EACCES);
800 
801 	xva_init(xva);
802 	xoap = xva_getxoptattr(xva);
803 
804 #define	FLAG_CHANGE(iflag, zflag, xflag, xfield)	do {	\
805 	if (((ioctl_flags & (iflag)) && !(zfs_flags & (zflag))) ||	\
806 	    ((zfs_flags & (zflag)) && !(ioctl_flags & (iflag)))) {	\
807 		XVA_SET_REQ(xva, (xflag));	\
808 		(xfield) = ((ioctl_flags & (iflag)) != 0);	\
809 	}	\
810 } while (0)
811 
812 	FLAG_CHANGE(FS_IMMUTABLE_FL, ZFS_IMMUTABLE, XAT_IMMUTABLE,
813 	    xoap->xoa_immutable);
814 	FLAG_CHANGE(FS_APPEND_FL, ZFS_APPENDONLY, XAT_APPENDONLY,
815 	    xoap->xoa_appendonly);
816 	FLAG_CHANGE(FS_NODUMP_FL, ZFS_NODUMP, XAT_NODUMP,
817 	    xoap->xoa_nodump);
818 	FLAG_CHANGE(ZFS_PROJINHERIT_FL, ZFS_PROJINHERIT, XAT_PROJINHERIT,
819 	    xoap->xoa_projinherit);
820 
821 #undef	FLAG_CHANGE
822 
823 	return (0);
824 }
825 
826 static int
zpl_ioctl_setflags(struct file * filp,void __user * arg)827 zpl_ioctl_setflags(struct file *filp, void __user *arg)
828 {
829 	struct inode *ip = file_inode(filp);
830 	uint32_t flags;
831 	cred_t *cr = CRED();
832 	xvattr_t xva;
833 	int err;
834 	fstrans_cookie_t cookie;
835 
836 	if (copy_from_user(&flags, arg, sizeof (flags)))
837 		return (-EFAULT);
838 
839 	err = __zpl_ioctl_setflags(ip, flags, &xva);
840 	if (err)
841 		return (err);
842 
843 	crhold(cr);
844 	cookie = spl_fstrans_mark();
845 	err = -zfs_setattr(ITOZ(ip), (vattr_t *)&xva, 0, cr, zfs_init_idmap);
846 	spl_fstrans_unmark(cookie);
847 	crfree(cr);
848 
849 	return (err);
850 }
851 
852 static int
zpl_ioctl_getxattr(struct file * filp,void __user * arg)853 zpl_ioctl_getxattr(struct file *filp, void __user *arg)
854 {
855 	zfsxattr_t fsx = { 0 };
856 	struct inode *ip = file_inode(filp);
857 	int err;
858 
859 	fsx.fsx_xflags = __zpl_ioctl_getflags(ip);
860 	fsx.fsx_projid = ITOZ(ip)->z_projid;
861 	err = copy_to_user(arg, &fsx, sizeof (fsx));
862 
863 	return (err);
864 }
865 
866 static int
zpl_ioctl_setxattr(struct file * filp,void __user * arg)867 zpl_ioctl_setxattr(struct file *filp, void __user *arg)
868 {
869 	struct inode *ip = file_inode(filp);
870 	zfsxattr_t fsx;
871 	cred_t *cr = CRED();
872 	xvattr_t xva;
873 	xoptattr_t *xoap;
874 	int err;
875 	fstrans_cookie_t cookie;
876 
877 	if (copy_from_user(&fsx, arg, sizeof (fsx)))
878 		return (-EFAULT);
879 
880 	if (!zpl_is_valid_projid(fsx.fsx_projid))
881 		return (-EINVAL);
882 
883 	err = __zpl_ioctl_setflags(ip, fsx.fsx_xflags, &xva);
884 	if (err)
885 		return (err);
886 
887 	xoap = xva_getxoptattr(&xva);
888 	XVA_SET_REQ(&xva, XAT_PROJID);
889 	xoap->xoa_projid = fsx.fsx_projid;
890 
891 	crhold(cr);
892 	cookie = spl_fstrans_mark();
893 	err = -zfs_setattr(ITOZ(ip), (vattr_t *)&xva, 0, cr, zfs_init_idmap);
894 	spl_fstrans_unmark(cookie);
895 	crfree(cr);
896 
897 	return (err);
898 }
899 
900 /*
901  * Expose Additional File Level Attributes of ZFS.
902  */
903 static int
zpl_ioctl_getdosflags(struct file * filp,void __user * arg)904 zpl_ioctl_getdosflags(struct file *filp, void __user *arg)
905 {
906 	struct inode *ip = file_inode(filp);
907 	uint64_t dosflags = ITOZ(ip)->z_pflags;
908 	dosflags &= ZFS_DOS_FL_USER_VISIBLE;
909 	int err = copy_to_user(arg, &dosflags, sizeof (dosflags));
910 
911 	return (err);
912 }
913 
914 static int
__zpl_ioctl_setdosflags(struct inode * ip,uint64_t ioctl_flags,xvattr_t * xva)915 __zpl_ioctl_setdosflags(struct inode *ip, uint64_t ioctl_flags, xvattr_t *xva)
916 {
917 	uint64_t zfs_flags = ITOZ(ip)->z_pflags;
918 	xoptattr_t *xoap;
919 
920 	if (ioctl_flags & (~ZFS_DOS_FL_USER_VISIBLE))
921 		return (-EOPNOTSUPP);
922 
923 	if ((fchange(ioctl_flags, zfs_flags, ZFS_IMMUTABLE, ZFS_IMMUTABLE) ||
924 	    fchange(ioctl_flags, zfs_flags, ZFS_APPENDONLY, ZFS_APPENDONLY)) &&
925 	    !capable(CAP_LINUX_IMMUTABLE))
926 		return (-EPERM);
927 
928 	if (!zpl_inode_owner_or_capable(zfs_init_idmap, ip))
929 		return (-EACCES);
930 
931 	xva_init(xva);
932 	xoap = xva_getxoptattr(xva);
933 
934 #define	FLAG_CHANGE(iflag, xflag, xfield)	do {	\
935 	if (((ioctl_flags & (iflag)) && !(zfs_flags & (iflag))) ||	\
936 	    ((zfs_flags & (iflag)) && !(ioctl_flags & (iflag)))) {	\
937 		XVA_SET_REQ(xva, (xflag));	\
938 		(xfield) = ((ioctl_flags & (iflag)) != 0);	\
939 	}	\
940 } while (0)
941 
942 	FLAG_CHANGE(ZFS_IMMUTABLE, XAT_IMMUTABLE, xoap->xoa_immutable);
943 	FLAG_CHANGE(ZFS_APPENDONLY, XAT_APPENDONLY, xoap->xoa_appendonly);
944 	FLAG_CHANGE(ZFS_NODUMP, XAT_NODUMP, xoap->xoa_nodump);
945 	FLAG_CHANGE(ZFS_READONLY, XAT_READONLY, xoap->xoa_readonly);
946 	FLAG_CHANGE(ZFS_HIDDEN, XAT_HIDDEN, xoap->xoa_hidden);
947 	FLAG_CHANGE(ZFS_SYSTEM, XAT_SYSTEM, xoap->xoa_system);
948 	FLAG_CHANGE(ZFS_ARCHIVE, XAT_ARCHIVE, xoap->xoa_archive);
949 	FLAG_CHANGE(ZFS_NOUNLINK, XAT_NOUNLINK, xoap->xoa_nounlink);
950 	FLAG_CHANGE(ZFS_REPARSE, XAT_REPARSE, xoap->xoa_reparse);
951 	FLAG_CHANGE(ZFS_OFFLINE, XAT_OFFLINE, xoap->xoa_offline);
952 	FLAG_CHANGE(ZFS_SPARSE, XAT_SPARSE, xoap->xoa_sparse);
953 
954 #undef	FLAG_CHANGE
955 
956 	return (0);
957 }
958 
959 /*
960  * Set Additional File Level Attributes of ZFS.
961  */
962 static int
zpl_ioctl_setdosflags(struct file * filp,void __user * arg)963 zpl_ioctl_setdosflags(struct file *filp, void __user *arg)
964 {
965 	struct inode *ip = file_inode(filp);
966 	uint64_t dosflags;
967 	cred_t *cr = CRED();
968 	xvattr_t xva;
969 	int err;
970 	fstrans_cookie_t cookie;
971 
972 	if (copy_from_user(&dosflags, arg, sizeof (dosflags)))
973 		return (-EFAULT);
974 
975 	err = __zpl_ioctl_setdosflags(ip, dosflags, &xva);
976 	if (err)
977 		return (err);
978 
979 	crhold(cr);
980 	cookie = spl_fstrans_mark();
981 	err = -zfs_setattr(ITOZ(ip), (vattr_t *)&xva, 0, cr, zfs_init_idmap);
982 	spl_fstrans_unmark(cookie);
983 	crfree(cr);
984 
985 	return (err);
986 }
987 
988 static int
zpl_ioctl_rewrite(struct file * filp,void __user * arg)989 zpl_ioctl_rewrite(struct file *filp, void __user *arg)
990 {
991 	struct inode *ip = file_inode(filp);
992 	zfs_rewrite_args_t args;
993 	fstrans_cookie_t cookie;
994 	int err;
995 
996 	if (copy_from_user(&args, arg, sizeof (args)))
997 		return (-EFAULT);
998 
999 	if (unlikely(!(filp->f_mode & FMODE_WRITE)))
1000 		return (-EBADF);
1001 
1002 	cookie = spl_fstrans_mark();
1003 	err = -zfs_rewrite(ITOZ(ip), args.off, args.len, args.flags, args.arg);
1004 	spl_fstrans_unmark(cookie);
1005 
1006 	return (err);
1007 }
1008 
1009 static long
zpl_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)1010 zpl_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1011 {
1012 	switch (cmd) {
1013 	case FS_IOC_GETVERSION:
1014 		return (zpl_ioctl_getversion(filp, (void *)arg));
1015 	case FS_IOC_GETFLAGS:
1016 		return (zpl_ioctl_getflags(filp, (void *)arg));
1017 	case FS_IOC_SETFLAGS:
1018 		return (zpl_ioctl_setflags(filp, (void *)arg));
1019 	case ZFS_IOC_FSGETXATTR:
1020 		return (zpl_ioctl_getxattr(filp, (void *)arg));
1021 	case ZFS_IOC_FSSETXATTR:
1022 		return (zpl_ioctl_setxattr(filp, (void *)arg));
1023 	case ZFS_IOC_GETDOSFLAGS:
1024 		return (zpl_ioctl_getdosflags(filp, (void *)arg));
1025 	case ZFS_IOC_SETDOSFLAGS:
1026 		return (zpl_ioctl_setdosflags(filp, (void *)arg));
1027 	case ZFS_IOC_REWRITE:
1028 		return (zpl_ioctl_rewrite(filp, (void *)arg));
1029 	default:
1030 		return (-ENOTTY);
1031 	}
1032 }
1033 
1034 #ifdef CONFIG_COMPAT
1035 static long
zpl_compat_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)1036 zpl_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1037 {
1038 	switch (cmd) {
1039 	case FS_IOC32_GETVERSION:
1040 		cmd = FS_IOC_GETVERSION;
1041 		break;
1042 	case FS_IOC32_GETFLAGS:
1043 		cmd = FS_IOC_GETFLAGS;
1044 		break;
1045 	case FS_IOC32_SETFLAGS:
1046 		cmd = FS_IOC_SETFLAGS;
1047 		break;
1048 	default:
1049 		return (-ENOTTY);
1050 	}
1051 	return (zpl_ioctl(filp, cmd, (unsigned long)compat_ptr(arg)));
1052 }
1053 #endif /* CONFIG_COMPAT */
1054 
1055 const struct address_space_operations zpl_address_space_operations = {
1056 #ifdef HAVE_VFS_READPAGES
1057 	.readpages	= zpl_readpages,
1058 #else
1059 	.readahead	= zpl_readahead,
1060 #endif
1061 #ifdef HAVE_VFS_READ_FOLIO
1062 	.read_folio	= zpl_read_folio,
1063 #else
1064 	.readpage	= zpl_readpage,
1065 #endif
1066 	.writepage	= zpl_writepage,
1067 	.writepages	= zpl_writepages,
1068 	.direct_IO	= zpl_direct_IO,
1069 #ifdef HAVE_VFS_SET_PAGE_DIRTY_NOBUFFERS
1070 	.set_page_dirty = __set_page_dirty_nobuffers,
1071 #endif
1072 #ifdef HAVE_VFS_FILEMAP_DIRTY_FOLIO
1073 	.dirty_folio	= filemap_dirty_folio,
1074 #endif
1075 #ifdef HAVE_VFS_MIGRATE_FOLIO
1076 	.migrate_folio	= migrate_folio,
1077 #elif defined(HAVE_VFS_MIGRATEPAGE)
1078 	.migratepage	= migrate_page,
1079 #endif
1080 };
1081 
1082 const struct file_operations zpl_file_operations = {
1083 	.open		= zpl_open,
1084 	.release	= zpl_release,
1085 	.llseek		= zpl_llseek,
1086 	.read_iter	= zpl_iter_read,
1087 	.write_iter	= zpl_iter_write,
1088 #ifdef HAVE_COPY_SPLICE_READ
1089 	.splice_read	= copy_splice_read,
1090 #else
1091 	.splice_read	= generic_file_splice_read,
1092 #endif
1093 	.splice_write	= iter_file_splice_write,
1094 	.mmap		= zpl_mmap,
1095 	.fsync		= zpl_fsync,
1096 	.fallocate	= zpl_fallocate,
1097 	.copy_file_range	= zpl_copy_file_range,
1098 #ifdef HAVE_VFS_CLONE_FILE_RANGE
1099 	.clone_file_range	= zpl_clone_file_range,
1100 #endif
1101 #ifdef HAVE_VFS_REMAP_FILE_RANGE
1102 	.remap_file_range	= zpl_remap_file_range,
1103 #endif
1104 #ifdef HAVE_VFS_DEDUPE_FILE_RANGE
1105 	.dedupe_file_range	= zpl_dedupe_file_range,
1106 #endif
1107 	.fadvise	= zpl_fadvise,
1108 	.unlocked_ioctl	= zpl_ioctl,
1109 #ifdef CONFIG_COMPAT
1110 	.compat_ioctl	= zpl_compat_ioctl,
1111 #endif
1112 };
1113 
1114 const struct file_operations zpl_dir_file_operations = {
1115 	.llseek		= generic_file_llseek,
1116 	.read		= generic_read_dir,
1117 	.iterate_shared	= zpl_iterate,
1118 	.fsync		= zpl_fsync,
1119 	.unlocked_ioctl = zpl_ioctl,
1120 #ifdef CONFIG_COMPAT
1121 	.compat_ioctl   = zpl_compat_ioctl,
1122 #endif
1123 };
1124 
1125 module_param(zfs_fallocate_reserve_percent, uint, 0644);
1126 MODULE_PARM_DESC(zfs_fallocate_reserve_percent,
1127 	"Percentage of length to use for the available capacity check");
1128