xref: /freebsd/sys/contrib/openzfs/module/os/linux/zfs/zpl_file.c (revision dd21556857e8d40f66bf5ad54754d9d52669ebf7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2011, Lawrence Livermore National Security, LLC.
23  * Copyright (c) 2015 by Chunwei Chen. All rights reserved.
24  */
25 
26 
27 #ifdef CONFIG_COMPAT
28 #include <linux/compat.h>
29 #endif
30 #include <linux/fs.h>
31 #include <linux/migrate.h>
32 #include <sys/file.h>
33 #include <sys/dmu_objset.h>
34 #include <sys/zfs_znode.h>
35 #include <sys/zfs_vfsops.h>
36 #include <sys/zfs_vnops.h>
37 #include <sys/zfs_project.h>
38 #if defined(HAVE_VFS_SET_PAGE_DIRTY_NOBUFFERS) || \
39     defined(HAVE_VFS_FILEMAP_DIRTY_FOLIO)
40 #include <linux/pagemap.h>
41 #endif
42 #include <linux/fadvise.h>
43 #ifdef HAVE_VFS_FILEMAP_DIRTY_FOLIO
44 #include <linux/writeback.h>
45 #endif
46 
47 /*
48  * When using fallocate(2) to preallocate space, inflate the requested
49  * capacity check by 10% to account for the required metadata blocks.
50  */
51 static unsigned int zfs_fallocate_reserve_percent = 110;
52 
53 static int
zpl_open(struct inode * ip,struct file * filp)54 zpl_open(struct inode *ip, struct file *filp)
55 {
56 	cred_t *cr = CRED();
57 	int error;
58 	fstrans_cookie_t cookie;
59 
60 	error = generic_file_open(ip, filp);
61 	if (error)
62 		return (error);
63 
64 	crhold(cr);
65 	cookie = spl_fstrans_mark();
66 	error = -zfs_open(ip, filp->f_mode, filp->f_flags, cr);
67 	spl_fstrans_unmark(cookie);
68 	crfree(cr);
69 	ASSERT3S(error, <=, 0);
70 
71 	return (error);
72 }
73 
74 static int
zpl_release(struct inode * ip,struct file * filp)75 zpl_release(struct inode *ip, struct file *filp)
76 {
77 	cred_t *cr = CRED();
78 	int error;
79 	fstrans_cookie_t cookie;
80 
81 	cookie = spl_fstrans_mark();
82 	if (ITOZ(ip)->z_atime_dirty)
83 		zfs_mark_inode_dirty(ip);
84 
85 	crhold(cr);
86 	error = -zfs_close(ip, filp->f_flags, cr);
87 	spl_fstrans_unmark(cookie);
88 	crfree(cr);
89 	ASSERT3S(error, <=, 0);
90 
91 	return (error);
92 }
93 
94 static int
zpl_iterate(struct file * filp,struct dir_context * ctx)95 zpl_iterate(struct file *filp, struct dir_context *ctx)
96 {
97 	cred_t *cr = CRED();
98 	int error;
99 	fstrans_cookie_t cookie;
100 
101 	crhold(cr);
102 	cookie = spl_fstrans_mark();
103 	error = -zfs_readdir(file_inode(filp), ctx, cr);
104 	spl_fstrans_unmark(cookie);
105 	crfree(cr);
106 	ASSERT3S(error, <=, 0);
107 
108 	return (error);
109 }
110 
111 static int
zpl_fsync(struct file * filp,loff_t start,loff_t end,int datasync)112 zpl_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
113 {
114 	struct inode *inode = filp->f_mapping->host;
115 	znode_t *zp = ITOZ(inode);
116 	zfsvfs_t *zfsvfs = ITOZSB(inode);
117 	cred_t *cr = CRED();
118 	int error;
119 	fstrans_cookie_t cookie;
120 
121 	/*
122 	 * The variables z_sync_writes_cnt and z_async_writes_cnt work in
123 	 * tandem so that sync writes can detect if there are any non-sync
124 	 * writes going on and vice-versa. The "vice-versa" part to this logic
125 	 * is located in zfs_putpage() where non-sync writes check if there are
126 	 * any ongoing sync writes. If any sync and non-sync writes overlap,
127 	 * we do a commit to complete the non-sync writes since the latter can
128 	 * potentially take several seconds to complete and thus block sync
129 	 * writes in the upcoming call to filemap_write_and_wait_range().
130 	 */
131 	atomic_inc_32(&zp->z_sync_writes_cnt);
132 	/*
133 	 * If the following check does not detect an overlapping non-sync write
134 	 * (say because it's just about to start), then it is guaranteed that
135 	 * the non-sync write will detect this sync write. This is because we
136 	 * always increment z_sync_writes_cnt / z_async_writes_cnt before doing
137 	 * the check on z_async_writes_cnt / z_sync_writes_cnt here and in
138 	 * zfs_putpage() respectively.
139 	 */
140 	if (atomic_load_32(&zp->z_async_writes_cnt) > 0) {
141 		if ((error = zpl_enter(zfsvfs, FTAG)) != 0) {
142 			atomic_dec_32(&zp->z_sync_writes_cnt);
143 			return (error);
144 		}
145 		zil_commit(zfsvfs->z_log, zp->z_id);
146 		zpl_exit(zfsvfs, FTAG);
147 	}
148 
149 	error = filemap_write_and_wait_range(inode->i_mapping, start, end);
150 
151 	/*
152 	 * The sync write is not complete yet but we decrement
153 	 * z_sync_writes_cnt since zfs_fsync() increments and decrements
154 	 * it internally. If a non-sync write starts just after the decrement
155 	 * operation but before we call zfs_fsync(), it may not detect this
156 	 * overlapping sync write but it does not matter since we have already
157 	 * gone past filemap_write_and_wait_range() and we won't block due to
158 	 * the non-sync write.
159 	 */
160 	atomic_dec_32(&zp->z_sync_writes_cnt);
161 
162 	if (error)
163 		return (error);
164 
165 	crhold(cr);
166 	cookie = spl_fstrans_mark();
167 	error = -zfs_fsync(zp, datasync, cr);
168 	spl_fstrans_unmark(cookie);
169 	crfree(cr);
170 	ASSERT3S(error, <=, 0);
171 
172 	return (error);
173 }
174 
175 static inline int
zfs_io_flags(struct kiocb * kiocb)176 zfs_io_flags(struct kiocb *kiocb)
177 {
178 	int flags = 0;
179 
180 #if defined(IOCB_DSYNC)
181 	if (kiocb->ki_flags & IOCB_DSYNC)
182 		flags |= O_DSYNC;
183 #endif
184 #if defined(IOCB_SYNC)
185 	if (kiocb->ki_flags & IOCB_SYNC)
186 		flags |= O_SYNC;
187 #endif
188 #if defined(IOCB_APPEND)
189 	if (kiocb->ki_flags & IOCB_APPEND)
190 		flags |= O_APPEND;
191 #endif
192 #if defined(IOCB_DIRECT)
193 	if (kiocb->ki_flags & IOCB_DIRECT)
194 		flags |= O_DIRECT;
195 #endif
196 	return (flags);
197 }
198 
199 /*
200  * If relatime is enabled, call file_accessed() if zfs_relatime_need_update()
201  * is true.  This is needed since datasets with inherited "relatime" property
202  * aren't necessarily mounted with the MNT_RELATIME flag (e.g. after
203  * `zfs set relatime=...`), which is what relatime test in VFS by
204  * relatime_need_update() is based on.
205  */
206 static inline void
zpl_file_accessed(struct file * filp)207 zpl_file_accessed(struct file *filp)
208 {
209 	struct inode *ip = filp->f_mapping->host;
210 
211 	if (!IS_NOATIME(ip) && ITOZSB(ip)->z_relatime) {
212 		if (zfs_relatime_need_update(ip))
213 			file_accessed(filp);
214 	} else {
215 		file_accessed(filp);
216 	}
217 }
218 
219 static ssize_t
zpl_iter_read(struct kiocb * kiocb,struct iov_iter * to)220 zpl_iter_read(struct kiocb *kiocb, struct iov_iter *to)
221 {
222 	cred_t *cr = CRED();
223 	fstrans_cookie_t cookie;
224 	struct file *filp = kiocb->ki_filp;
225 	ssize_t count = iov_iter_count(to);
226 	zfs_uio_t uio;
227 
228 	zfs_uio_iov_iter_init(&uio, to, kiocb->ki_pos, count, 0);
229 
230 	crhold(cr);
231 	cookie = spl_fstrans_mark();
232 
233 	ssize_t ret = -zfs_read(ITOZ(filp->f_mapping->host), &uio,
234 	    filp->f_flags | zfs_io_flags(kiocb), cr);
235 
236 	spl_fstrans_unmark(cookie);
237 	crfree(cr);
238 
239 	if (ret < 0)
240 		return (ret);
241 
242 	ssize_t read = count - uio.uio_resid;
243 	kiocb->ki_pos += read;
244 
245 	zpl_file_accessed(filp);
246 
247 	return (read);
248 }
249 
250 static inline ssize_t
zpl_generic_write_checks(struct kiocb * kiocb,struct iov_iter * from,size_t * countp)251 zpl_generic_write_checks(struct kiocb *kiocb, struct iov_iter *from,
252     size_t *countp)
253 {
254 	ssize_t ret = generic_write_checks(kiocb, from);
255 	if (ret <= 0)
256 		return (ret);
257 
258 	*countp = ret;
259 
260 	return (0);
261 }
262 
263 static ssize_t
zpl_iter_write(struct kiocb * kiocb,struct iov_iter * from)264 zpl_iter_write(struct kiocb *kiocb, struct iov_iter *from)
265 {
266 	cred_t *cr = CRED();
267 	fstrans_cookie_t cookie;
268 	struct file *filp = kiocb->ki_filp;
269 	struct inode *ip = filp->f_mapping->host;
270 	zfs_uio_t uio;
271 	size_t count = 0;
272 	ssize_t ret;
273 
274 	ret = zpl_generic_write_checks(kiocb, from, &count);
275 	if (ret)
276 		return (ret);
277 
278 	zfs_uio_iov_iter_init(&uio, from, kiocb->ki_pos, count,
279 	    from->iov_offset);
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 long
zpl_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)989 zpl_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
990 {
991 	switch (cmd) {
992 	case FS_IOC_GETVERSION:
993 		return (zpl_ioctl_getversion(filp, (void *)arg));
994 	case FS_IOC_GETFLAGS:
995 		return (zpl_ioctl_getflags(filp, (void *)arg));
996 	case FS_IOC_SETFLAGS:
997 		return (zpl_ioctl_setflags(filp, (void *)arg));
998 	case ZFS_IOC_FSGETXATTR:
999 		return (zpl_ioctl_getxattr(filp, (void *)arg));
1000 	case ZFS_IOC_FSSETXATTR:
1001 		return (zpl_ioctl_setxattr(filp, (void *)arg));
1002 	case ZFS_IOC_GETDOSFLAGS:
1003 		return (zpl_ioctl_getdosflags(filp, (void *)arg));
1004 	case ZFS_IOC_SETDOSFLAGS:
1005 		return (zpl_ioctl_setdosflags(filp, (void *)arg));
1006 	case ZFS_IOC_COMPAT_FICLONE:
1007 		return (zpl_ioctl_ficlone(filp, (void *)arg));
1008 	case ZFS_IOC_COMPAT_FICLONERANGE:
1009 		return (zpl_ioctl_ficlonerange(filp, (void *)arg));
1010 	case ZFS_IOC_COMPAT_FIDEDUPERANGE:
1011 		return (zpl_ioctl_fideduperange(filp, (void *)arg));
1012 	default:
1013 		return (-ENOTTY);
1014 	}
1015 }
1016 
1017 #ifdef CONFIG_COMPAT
1018 static long
zpl_compat_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)1019 zpl_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1020 {
1021 	switch (cmd) {
1022 	case FS_IOC32_GETVERSION:
1023 		cmd = FS_IOC_GETVERSION;
1024 		break;
1025 	case FS_IOC32_GETFLAGS:
1026 		cmd = FS_IOC_GETFLAGS;
1027 		break;
1028 	case FS_IOC32_SETFLAGS:
1029 		cmd = FS_IOC_SETFLAGS;
1030 		break;
1031 	default:
1032 		return (-ENOTTY);
1033 	}
1034 	return (zpl_ioctl(filp, cmd, (unsigned long)compat_ptr(arg)));
1035 }
1036 #endif /* CONFIG_COMPAT */
1037 
1038 const struct address_space_operations zpl_address_space_operations = {
1039 #ifdef HAVE_VFS_READPAGES
1040 	.readpages	= zpl_readpages,
1041 #else
1042 	.readahead	= zpl_readahead,
1043 #endif
1044 #ifdef HAVE_VFS_READ_FOLIO
1045 	.read_folio	= zpl_read_folio,
1046 #else
1047 	.readpage	= zpl_readpage,
1048 #endif
1049 	.writepage	= zpl_writepage,
1050 	.writepages	= zpl_writepages,
1051 	.direct_IO	= zpl_direct_IO,
1052 #ifdef HAVE_VFS_SET_PAGE_DIRTY_NOBUFFERS
1053 	.set_page_dirty = __set_page_dirty_nobuffers,
1054 #endif
1055 #ifdef HAVE_VFS_FILEMAP_DIRTY_FOLIO
1056 	.dirty_folio	= filemap_dirty_folio,
1057 #endif
1058 #ifdef HAVE_VFS_MIGRATE_FOLIO
1059 	.migrate_folio	= migrate_folio,
1060 #else
1061 	.migratepage	= migrate_page,
1062 #endif
1063 };
1064 
1065 const struct file_operations zpl_file_operations = {
1066 	.open		= zpl_open,
1067 	.release	= zpl_release,
1068 	.llseek		= zpl_llseek,
1069 	.read_iter	= zpl_iter_read,
1070 	.write_iter	= zpl_iter_write,
1071 #ifdef HAVE_COPY_SPLICE_READ
1072 	.splice_read	= copy_splice_read,
1073 #else
1074 	.splice_read	= generic_file_splice_read,
1075 #endif
1076 	.splice_write	= iter_file_splice_write,
1077 	.mmap		= zpl_mmap,
1078 	.fsync		= zpl_fsync,
1079 	.fallocate	= zpl_fallocate,
1080 	.copy_file_range	= zpl_copy_file_range,
1081 #ifdef HAVE_VFS_CLONE_FILE_RANGE
1082 	.clone_file_range	= zpl_clone_file_range,
1083 #endif
1084 #ifdef HAVE_VFS_REMAP_FILE_RANGE
1085 	.remap_file_range	= zpl_remap_file_range,
1086 #endif
1087 #ifdef HAVE_VFS_DEDUPE_FILE_RANGE
1088 	.dedupe_file_range	= zpl_dedupe_file_range,
1089 #endif
1090 	.fadvise	= zpl_fadvise,
1091 	.unlocked_ioctl	= zpl_ioctl,
1092 #ifdef CONFIG_COMPAT
1093 	.compat_ioctl	= zpl_compat_ioctl,
1094 #endif
1095 };
1096 
1097 const struct file_operations zpl_dir_file_operations = {
1098 	.llseek		= generic_file_llseek,
1099 	.read		= generic_read_dir,
1100 	.iterate_shared	= zpl_iterate,
1101 	.fsync		= zpl_fsync,
1102 	.unlocked_ioctl = zpl_ioctl,
1103 #ifdef CONFIG_COMPAT
1104 	.compat_ioctl   = zpl_compat_ioctl,
1105 #endif
1106 };
1107 
1108 module_param(zfs_fallocate_reserve_percent, uint, 0644);
1109 MODULE_PARM_DESC(zfs_fallocate_reserve_percent,
1110 	"Percentage of length to use for the available capacity check");
1111