xref: /freebsd/sys/contrib/openzfs/module/os/linux/zfs/zpl_file.c (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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 http://www.opensolaris.org/os/licensing.
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 <sys/file.h>
31 #include <sys/dmu_objset.h>
32 #include <sys/zfs_znode.h>
33 #include <sys/zfs_vfsops.h>
34 #include <sys/zfs_vnops.h>
35 #include <sys/zfs_project.h>
36 
37 /*
38  * When using fallocate(2) to preallocate space, inflate the requested
39  * capacity check by 10% to account for the required metadata blocks.
40  */
41 unsigned int zfs_fallocate_reserve_percent = 110;
42 
43 static int
44 zpl_open(struct inode *ip, struct file *filp)
45 {
46 	cred_t *cr = CRED();
47 	int error;
48 	fstrans_cookie_t cookie;
49 
50 	error = generic_file_open(ip, filp);
51 	if (error)
52 		return (error);
53 
54 	crhold(cr);
55 	cookie = spl_fstrans_mark();
56 	error = -zfs_open(ip, filp->f_mode, filp->f_flags, cr);
57 	spl_fstrans_unmark(cookie);
58 	crfree(cr);
59 	ASSERT3S(error, <=, 0);
60 
61 	return (error);
62 }
63 
64 static int
65 zpl_release(struct inode *ip, struct file *filp)
66 {
67 	cred_t *cr = CRED();
68 	int error;
69 	fstrans_cookie_t cookie;
70 
71 	cookie = spl_fstrans_mark();
72 	if (ITOZ(ip)->z_atime_dirty)
73 		zfs_mark_inode_dirty(ip);
74 
75 	crhold(cr);
76 	error = -zfs_close(ip, filp->f_flags, cr);
77 	spl_fstrans_unmark(cookie);
78 	crfree(cr);
79 	ASSERT3S(error, <=, 0);
80 
81 	return (error);
82 }
83 
84 static int
85 zpl_iterate(struct file *filp, zpl_dir_context_t *ctx)
86 {
87 	cred_t *cr = CRED();
88 	int error;
89 	fstrans_cookie_t cookie;
90 
91 	crhold(cr);
92 	cookie = spl_fstrans_mark();
93 	error = -zfs_readdir(file_inode(filp), ctx, cr);
94 	spl_fstrans_unmark(cookie);
95 	crfree(cr);
96 	ASSERT3S(error, <=, 0);
97 
98 	return (error);
99 }
100 
101 #if !defined(HAVE_VFS_ITERATE) && !defined(HAVE_VFS_ITERATE_SHARED)
102 static int
103 zpl_readdir(struct file *filp, void *dirent, filldir_t filldir)
104 {
105 	zpl_dir_context_t ctx =
106 	    ZPL_DIR_CONTEXT_INIT(dirent, filldir, filp->f_pos);
107 	int error;
108 
109 	error = zpl_iterate(filp, &ctx);
110 	filp->f_pos = ctx.pos;
111 
112 	return (error);
113 }
114 #endif /* !HAVE_VFS_ITERATE && !HAVE_VFS_ITERATE_SHARED */
115 
116 #if defined(HAVE_FSYNC_WITHOUT_DENTRY)
117 /*
118  * Linux 2.6.35 - 3.0 API,
119  * As of 2.6.35 the dentry argument to the fops->fsync() hook was deemed
120  * redundant.  The dentry is still accessible via filp->f_path.dentry,
121  * and we are guaranteed that filp will never be NULL.
122  */
123 static int
124 zpl_fsync(struct file *filp, int datasync)
125 {
126 	struct inode *inode = filp->f_mapping->host;
127 	cred_t *cr = CRED();
128 	int error;
129 	fstrans_cookie_t cookie;
130 
131 	crhold(cr);
132 	cookie = spl_fstrans_mark();
133 	error = -zfs_fsync(ITOZ(inode), datasync, cr);
134 	spl_fstrans_unmark(cookie);
135 	crfree(cr);
136 	ASSERT3S(error, <=, 0);
137 
138 	return (error);
139 }
140 
141 #ifdef HAVE_FILE_AIO_FSYNC
142 static int
143 zpl_aio_fsync(struct kiocb *kiocb, int datasync)
144 {
145 	return (zpl_fsync(kiocb->ki_filp, datasync));
146 }
147 #endif
148 
149 #elif defined(HAVE_FSYNC_RANGE)
150 /*
151  * Linux 3.1 API,
152  * As of 3.1 the responsibility to call filemap_write_and_wait_range() has
153  * been pushed down in to the .fsync() vfs hook.  Additionally, the i_mutex
154  * lock is no longer held by the caller, for zfs we don't require the lock
155  * to be held so we don't acquire it.
156  */
157 static int
158 zpl_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
159 {
160 	struct inode *inode = filp->f_mapping->host;
161 	cred_t *cr = CRED();
162 	int error;
163 	fstrans_cookie_t cookie;
164 
165 	error = filemap_write_and_wait_range(inode->i_mapping, start, end);
166 	if (error)
167 		return (error);
168 
169 	crhold(cr);
170 	cookie = spl_fstrans_mark();
171 	error = -zfs_fsync(ITOZ(inode), datasync, cr);
172 	spl_fstrans_unmark(cookie);
173 	crfree(cr);
174 	ASSERT3S(error, <=, 0);
175 
176 	return (error);
177 }
178 
179 #ifdef HAVE_FILE_AIO_FSYNC
180 static int
181 zpl_aio_fsync(struct kiocb *kiocb, int datasync)
182 {
183 	return (zpl_fsync(kiocb->ki_filp, kiocb->ki_pos, -1, datasync));
184 }
185 #endif
186 
187 #else
188 #error "Unsupported fops->fsync() implementation"
189 #endif
190 
191 static inline int
192 zfs_io_flags(struct kiocb *kiocb)
193 {
194 	int flags = 0;
195 
196 #if defined(IOCB_DSYNC)
197 	if (kiocb->ki_flags & IOCB_DSYNC)
198 		flags |= O_DSYNC;
199 #endif
200 #if defined(IOCB_SYNC)
201 	if (kiocb->ki_flags & IOCB_SYNC)
202 		flags |= O_SYNC;
203 #endif
204 #if defined(IOCB_APPEND)
205 	if (kiocb->ki_flags & IOCB_APPEND)
206 		flags |= O_APPEND;
207 #endif
208 #if defined(IOCB_DIRECT)
209 	if (kiocb->ki_flags & IOCB_DIRECT)
210 		flags |= O_DIRECT;
211 #endif
212 	return (flags);
213 }
214 
215 /*
216  * If relatime is enabled, call file_accessed() if zfs_relatime_need_update()
217  * is true.  This is needed since datasets with inherited "relatime" property
218  * aren't necessarily mounted with the MNT_RELATIME flag (e.g. after
219  * `zfs set relatime=...`), which is what relatime test in VFS by
220  * relatime_need_update() is based on.
221  */
222 static inline void
223 zpl_file_accessed(struct file *filp)
224 {
225 	struct inode *ip = filp->f_mapping->host;
226 
227 	if (!IS_NOATIME(ip) && ITOZSB(ip)->z_relatime) {
228 		if (zfs_relatime_need_update(ip))
229 			file_accessed(filp);
230 	} else {
231 		file_accessed(filp);
232 	}
233 }
234 
235 #if defined(HAVE_VFS_RW_ITERATE)
236 
237 /*
238  * When HAVE_VFS_IOV_ITER is defined the iov_iter structure supports
239  * iovecs, kvevs, bvecs and pipes, plus all the required interfaces to
240  * manipulate the iov_iter are available.  In which case the full iov_iter
241  * can be attached to the uio and correctly handled in the lower layers.
242  * Otherwise, for older kernels extract the iovec and pass it instead.
243  */
244 static void
245 zpl_uio_init(zfs_uio_t *uio, struct kiocb *kiocb, struct iov_iter *to,
246     loff_t pos, ssize_t count, size_t skip)
247 {
248 #if defined(HAVE_VFS_IOV_ITER)
249 	zfs_uio_iov_iter_init(uio, to, pos, count, skip);
250 #else
251 	zfs_uio_iovec_init(uio, to->iov, to->nr_segs, pos,
252 	    to->type & ITER_KVEC ? UIO_SYSSPACE : UIO_USERSPACE,
253 	    count, skip);
254 #endif
255 }
256 
257 static ssize_t
258 zpl_iter_read(struct kiocb *kiocb, struct iov_iter *to)
259 {
260 	cred_t *cr = CRED();
261 	fstrans_cookie_t cookie;
262 	struct file *filp = kiocb->ki_filp;
263 	ssize_t count = iov_iter_count(to);
264 	zfs_uio_t uio;
265 
266 	zpl_uio_init(&uio, kiocb, to, kiocb->ki_pos, count, 0);
267 
268 	crhold(cr);
269 	cookie = spl_fstrans_mark();
270 
271 	int error = -zfs_read(ITOZ(filp->f_mapping->host), &uio,
272 	    filp->f_flags | zfs_io_flags(kiocb), cr);
273 
274 	spl_fstrans_unmark(cookie);
275 	crfree(cr);
276 
277 	if (error < 0)
278 		return (error);
279 
280 	ssize_t read = count - uio.uio_resid;
281 	kiocb->ki_pos += read;
282 
283 	zpl_file_accessed(filp);
284 
285 	return (read);
286 }
287 
288 static inline ssize_t
289 zpl_generic_write_checks(struct kiocb *kiocb, struct iov_iter *from,
290     size_t *countp)
291 {
292 #ifdef HAVE_GENERIC_WRITE_CHECKS_KIOCB
293 	ssize_t ret = generic_write_checks(kiocb, from);
294 	if (ret <= 0)
295 		return (ret);
296 
297 	*countp = ret;
298 #else
299 	struct file *file = kiocb->ki_filp;
300 	struct address_space *mapping = file->f_mapping;
301 	struct inode *ip = mapping->host;
302 	int isblk = S_ISBLK(ip->i_mode);
303 
304 	*countp = iov_iter_count(from);
305 	ssize_t ret = generic_write_checks(file, &kiocb->ki_pos, countp, isblk);
306 	if (ret)
307 		return (ret);
308 #endif
309 
310 	return (0);
311 }
312 
313 static ssize_t
314 zpl_iter_write(struct kiocb *kiocb, struct iov_iter *from)
315 {
316 	cred_t *cr = CRED();
317 	fstrans_cookie_t cookie;
318 	struct file *filp = kiocb->ki_filp;
319 	struct inode *ip = filp->f_mapping->host;
320 	zfs_uio_t uio;
321 	size_t count = 0;
322 	ssize_t ret;
323 
324 	ret = zpl_generic_write_checks(kiocb, from, &count);
325 	if (ret)
326 		return (ret);
327 
328 	zpl_uio_init(&uio, kiocb, from, kiocb->ki_pos, count, from->iov_offset);
329 
330 	crhold(cr);
331 	cookie = spl_fstrans_mark();
332 
333 	int error = -zfs_write(ITOZ(ip), &uio,
334 	    filp->f_flags | zfs_io_flags(kiocb), cr);
335 
336 	spl_fstrans_unmark(cookie);
337 	crfree(cr);
338 
339 	if (error < 0)
340 		return (error);
341 
342 	ssize_t wrote = count - uio.uio_resid;
343 	kiocb->ki_pos += wrote;
344 
345 	return (wrote);
346 }
347 
348 #else /* !HAVE_VFS_RW_ITERATE */
349 
350 static ssize_t
351 zpl_aio_read(struct kiocb *kiocb, const struct iovec *iov,
352     unsigned long nr_segs, loff_t pos)
353 {
354 	cred_t *cr = CRED();
355 	fstrans_cookie_t cookie;
356 	struct file *filp = kiocb->ki_filp;
357 	size_t count;
358 	ssize_t ret;
359 
360 	ret = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
361 	if (ret)
362 		return (ret);
363 
364 	zfs_uio_t uio;
365 	zfs_uio_iovec_init(&uio, iov, nr_segs, kiocb->ki_pos, UIO_USERSPACE,
366 	    count, 0);
367 
368 	crhold(cr);
369 	cookie = spl_fstrans_mark();
370 
371 	int error = -zfs_read(ITOZ(filp->f_mapping->host), &uio,
372 	    filp->f_flags | zfs_io_flags(kiocb), cr);
373 
374 	spl_fstrans_unmark(cookie);
375 	crfree(cr);
376 
377 	if (error < 0)
378 		return (error);
379 
380 	ssize_t read = count - uio.uio_resid;
381 	kiocb->ki_pos += read;
382 
383 	zpl_file_accessed(filp);
384 
385 	return (read);
386 }
387 
388 static ssize_t
389 zpl_aio_write(struct kiocb *kiocb, const struct iovec *iov,
390     unsigned long nr_segs, loff_t pos)
391 {
392 	cred_t *cr = CRED();
393 	fstrans_cookie_t cookie;
394 	struct file *filp = kiocb->ki_filp;
395 	struct inode *ip = filp->f_mapping->host;
396 	size_t count;
397 	ssize_t ret;
398 
399 	ret = generic_segment_checks(iov, &nr_segs, &count, VERIFY_READ);
400 	if (ret)
401 		return (ret);
402 
403 	ret = generic_write_checks(filp, &pos, &count, S_ISBLK(ip->i_mode));
404 	if (ret)
405 		return (ret);
406 
407 	zfs_uio_t uio;
408 	zfs_uio_iovec_init(&uio, iov, nr_segs, kiocb->ki_pos, UIO_USERSPACE,
409 	    count, 0);
410 
411 	crhold(cr);
412 	cookie = spl_fstrans_mark();
413 
414 	int error = -zfs_write(ITOZ(ip), &uio,
415 	    filp->f_flags | zfs_io_flags(kiocb), cr);
416 
417 	spl_fstrans_unmark(cookie);
418 	crfree(cr);
419 
420 	if (error < 0)
421 		return (error);
422 
423 	ssize_t wrote = count - uio.uio_resid;
424 	kiocb->ki_pos += wrote;
425 
426 	return (wrote);
427 }
428 #endif /* HAVE_VFS_RW_ITERATE */
429 
430 #if defined(HAVE_VFS_RW_ITERATE)
431 static ssize_t
432 zpl_direct_IO_impl(int rw, struct kiocb *kiocb, struct iov_iter *iter)
433 {
434 	if (rw == WRITE)
435 		return (zpl_iter_write(kiocb, iter));
436 	else
437 		return (zpl_iter_read(kiocb, iter));
438 }
439 #if defined(HAVE_VFS_DIRECT_IO_ITER)
440 static ssize_t
441 zpl_direct_IO(struct kiocb *kiocb, struct iov_iter *iter)
442 {
443 	return (zpl_direct_IO_impl(iov_iter_rw(iter), kiocb, iter));
444 }
445 #elif defined(HAVE_VFS_DIRECT_IO_ITER_OFFSET)
446 static ssize_t
447 zpl_direct_IO(struct kiocb *kiocb, struct iov_iter *iter, loff_t pos)
448 {
449 	ASSERT3S(pos, ==, kiocb->ki_pos);
450 	return (zpl_direct_IO_impl(iov_iter_rw(iter), kiocb, iter));
451 }
452 #elif defined(HAVE_VFS_DIRECT_IO_ITER_RW_OFFSET)
453 static ssize_t
454 zpl_direct_IO(int rw, struct kiocb *kiocb, struct iov_iter *iter, loff_t pos)
455 {
456 	ASSERT3S(pos, ==, kiocb->ki_pos);
457 	return (zpl_direct_IO_impl(rw, kiocb, iter));
458 }
459 #else
460 #error "Unknown direct IO interface"
461 #endif
462 
463 #else /* HAVE_VFS_RW_ITERATE */
464 
465 #if defined(HAVE_VFS_DIRECT_IO_IOVEC)
466 static ssize_t
467 zpl_direct_IO(int rw, struct kiocb *kiocb, const struct iovec *iov,
468     loff_t pos, unsigned long nr_segs)
469 {
470 	if (rw == WRITE)
471 		return (zpl_aio_write(kiocb, iov, nr_segs, pos));
472 	else
473 		return (zpl_aio_read(kiocb, iov, nr_segs, pos));
474 }
475 #elif defined(HAVE_VFS_DIRECT_IO_ITER_RW_OFFSET)
476 static ssize_t
477 zpl_direct_IO(int rw, struct kiocb *kiocb, struct iov_iter *iter, loff_t pos)
478 {
479 	const struct iovec *iovp = iov_iter_iovec(iter);
480 	unsigned long nr_segs = iter->nr_segs;
481 
482 	ASSERT3S(pos, ==, kiocb->ki_pos);
483 	if (rw == WRITE)
484 		return (zpl_aio_write(kiocb, iovp, nr_segs, pos));
485 	else
486 		return (zpl_aio_read(kiocb, iovp, nr_segs, pos));
487 }
488 #else
489 #error "Unknown direct IO interface"
490 #endif
491 
492 #endif /* HAVE_VFS_RW_ITERATE */
493 
494 static loff_t
495 zpl_llseek(struct file *filp, loff_t offset, int whence)
496 {
497 #if defined(SEEK_HOLE) && defined(SEEK_DATA)
498 	fstrans_cookie_t cookie;
499 
500 	if (whence == SEEK_DATA || whence == SEEK_HOLE) {
501 		struct inode *ip = filp->f_mapping->host;
502 		loff_t maxbytes = ip->i_sb->s_maxbytes;
503 		loff_t error;
504 
505 		spl_inode_lock_shared(ip);
506 		cookie = spl_fstrans_mark();
507 		error = -zfs_holey(ITOZ(ip), whence, &offset);
508 		spl_fstrans_unmark(cookie);
509 		if (error == 0)
510 			error = lseek_execute(filp, ip, offset, maxbytes);
511 		spl_inode_unlock_shared(ip);
512 
513 		return (error);
514 	}
515 #endif /* SEEK_HOLE && SEEK_DATA */
516 
517 	return (generic_file_llseek(filp, offset, whence));
518 }
519 
520 /*
521  * It's worth taking a moment to describe how mmap is implemented
522  * for zfs because it differs considerably from other Linux filesystems.
523  * However, this issue is handled the same way under OpenSolaris.
524  *
525  * The issue is that by design zfs bypasses the Linux page cache and
526  * leaves all caching up to the ARC.  This has been shown to work
527  * well for the common read(2)/write(2) case.  However, mmap(2)
528  * is problem because it relies on being tightly integrated with the
529  * page cache.  To handle this we cache mmap'ed files twice, once in
530  * the ARC and a second time in the page cache.  The code is careful
531  * to keep both copies synchronized.
532  *
533  * When a file with an mmap'ed region is written to using write(2)
534  * both the data in the ARC and existing pages in the page cache
535  * are updated.  For a read(2) data will be read first from the page
536  * cache then the ARC if needed.  Neither a write(2) or read(2) will
537  * will ever result in new pages being added to the page cache.
538  *
539  * New pages are added to the page cache only via .readpage() which
540  * is called when the vfs needs to read a page off disk to back the
541  * virtual memory region.  These pages may be modified without
542  * notifying the ARC and will be written out periodically via
543  * .writepage().  This will occur due to either a sync or the usual
544  * page aging behavior.  Note because a read(2) of a mmap'ed file
545  * will always check the page cache first even when the ARC is out
546  * of date correct data will still be returned.
547  *
548  * While this implementation ensures correct behavior it does have
549  * have some drawbacks.  The most obvious of which is that it
550  * increases the required memory footprint when access mmap'ed
551  * files.  It also adds additional complexity to the code keeping
552  * both caches synchronized.
553  *
554  * Longer term it may be possible to cleanly resolve this wart by
555  * mapping page cache pages directly on to the ARC buffers.  The
556  * Linux address space operations are flexible enough to allow
557  * selection of which pages back a particular index.  The trick
558  * would be working out the details of which subsystem is in
559  * charge, the ARC, the page cache, or both.  It may also prove
560  * helpful to move the ARC buffers to a scatter-gather lists
561  * rather than a vmalloc'ed region.
562  */
563 static int
564 zpl_mmap(struct file *filp, struct vm_area_struct *vma)
565 {
566 	struct inode *ip = filp->f_mapping->host;
567 	znode_t *zp = ITOZ(ip);
568 	int error;
569 	fstrans_cookie_t cookie;
570 
571 	cookie = spl_fstrans_mark();
572 	error = -zfs_map(ip, vma->vm_pgoff, (caddr_t *)vma->vm_start,
573 	    (size_t)(vma->vm_end - vma->vm_start), vma->vm_flags);
574 	spl_fstrans_unmark(cookie);
575 	if (error)
576 		return (error);
577 
578 	error = generic_file_mmap(filp, vma);
579 	if (error)
580 		return (error);
581 
582 	mutex_enter(&zp->z_lock);
583 	zp->z_is_mapped = B_TRUE;
584 	mutex_exit(&zp->z_lock);
585 
586 	return (error);
587 }
588 
589 /*
590  * Populate a page with data for the Linux page cache.  This function is
591  * only used to support mmap(2).  There will be an identical copy of the
592  * data in the ARC which is kept up to date via .write() and .writepage().
593  */
594 static inline int
595 zpl_readpage_common(struct page *pp)
596 {
597 	struct inode *ip;
598 	struct page *pl[1];
599 	int error = 0;
600 	fstrans_cookie_t cookie;
601 
602 	ASSERT(PageLocked(pp));
603 	ip = pp->mapping->host;
604 	pl[0] = pp;
605 
606 	cookie = spl_fstrans_mark();
607 	error = -zfs_getpage(ip, pl, 1);
608 	spl_fstrans_unmark(cookie);
609 
610 	if (error) {
611 		SetPageError(pp);
612 		ClearPageUptodate(pp);
613 	} else {
614 		ClearPageError(pp);
615 		SetPageUptodate(pp);
616 		flush_dcache_page(pp);
617 	}
618 
619 	unlock_page(pp);
620 	return (error);
621 }
622 
623 static int
624 zpl_readpage(struct file *filp, struct page *pp)
625 {
626 	return (zpl_readpage_common(pp));
627 }
628 
629 static int
630 zpl_readpage_filler(void *data, struct page *pp)
631 {
632 	return (zpl_readpage_common(pp));
633 }
634 
635 /*
636  * Populate a set of pages with data for the Linux page cache.  This
637  * function will only be called for read ahead and never for demand
638  * paging.  For simplicity, the code relies on read_cache_pages() to
639  * correctly lock each page for IO and call zpl_readpage().
640  */
641 static int
642 zpl_readpages(struct file *filp, struct address_space *mapping,
643     struct list_head *pages, unsigned nr_pages)
644 {
645 	return (read_cache_pages(mapping, pages, zpl_readpage_filler, NULL));
646 }
647 
648 static int
649 zpl_putpage(struct page *pp, struct writeback_control *wbc, void *data)
650 {
651 	struct address_space *mapping = data;
652 	fstrans_cookie_t cookie;
653 
654 	ASSERT(PageLocked(pp));
655 	ASSERT(!PageWriteback(pp));
656 
657 	cookie = spl_fstrans_mark();
658 	(void) zfs_putpage(mapping->host, pp, wbc);
659 	spl_fstrans_unmark(cookie);
660 
661 	return (0);
662 }
663 
664 static int
665 zpl_writepages(struct address_space *mapping, struct writeback_control *wbc)
666 {
667 	znode_t		*zp = ITOZ(mapping->host);
668 	zfsvfs_t	*zfsvfs = ITOZSB(mapping->host);
669 	enum writeback_sync_modes sync_mode;
670 	int result;
671 
672 	ZPL_ENTER(zfsvfs);
673 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
674 		wbc->sync_mode = WB_SYNC_ALL;
675 	ZPL_EXIT(zfsvfs);
676 	sync_mode = wbc->sync_mode;
677 
678 	/*
679 	 * We don't want to run write_cache_pages() in SYNC mode here, because
680 	 * that would make putpage() wait for a single page to be committed to
681 	 * disk every single time, resulting in atrocious performance. Instead
682 	 * we run it once in non-SYNC mode so that the ZIL gets all the data,
683 	 * and then we commit it all in one go.
684 	 */
685 	wbc->sync_mode = WB_SYNC_NONE;
686 	result = write_cache_pages(mapping, wbc, zpl_putpage, mapping);
687 	if (sync_mode != wbc->sync_mode) {
688 		ZPL_ENTER(zfsvfs);
689 		ZPL_VERIFY_ZP(zp);
690 		if (zfsvfs->z_log != NULL)
691 			zil_commit(zfsvfs->z_log, zp->z_id);
692 		ZPL_EXIT(zfsvfs);
693 
694 		/*
695 		 * We need to call write_cache_pages() again (we can't just
696 		 * return after the commit) because the previous call in
697 		 * non-SYNC mode does not guarantee that we got all the dirty
698 		 * pages (see the implementation of write_cache_pages() for
699 		 * details). That being said, this is a no-op in most cases.
700 		 */
701 		wbc->sync_mode = sync_mode;
702 		result = write_cache_pages(mapping, wbc, zpl_putpage, mapping);
703 	}
704 	return (result);
705 }
706 
707 /*
708  * Write out dirty pages to the ARC, this function is only required to
709  * support mmap(2).  Mapped pages may be dirtied by memory operations
710  * which never call .write().  These dirty pages are kept in sync with
711  * the ARC buffers via this hook.
712  */
713 static int
714 zpl_writepage(struct page *pp, struct writeback_control *wbc)
715 {
716 	if (ITOZSB(pp->mapping->host)->z_os->os_sync == ZFS_SYNC_ALWAYS)
717 		wbc->sync_mode = WB_SYNC_ALL;
718 
719 	return (zpl_putpage(pp, wbc, pp->mapping));
720 }
721 
722 /*
723  * The flag combination which matches the behavior of zfs_space() is
724  * FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE.  The FALLOC_FL_PUNCH_HOLE
725  * flag was introduced in the 2.6.38 kernel.
726  *
727  * The original mode=0 (allocate space) behavior can be reasonably emulated
728  * by checking if enough space exists and creating a sparse file, as real
729  * persistent space reservation is not possible due to COW, snapshots, etc.
730  */
731 static long
732 zpl_fallocate_common(struct inode *ip, int mode, loff_t offset, loff_t len)
733 {
734 	cred_t *cr = CRED();
735 	loff_t olen;
736 	fstrans_cookie_t cookie;
737 	int error = 0;
738 
739 	if ((mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE)) != 0)
740 		return (-EOPNOTSUPP);
741 
742 	if (offset < 0 || len <= 0)
743 		return (-EINVAL);
744 
745 	spl_inode_lock(ip);
746 	olen = i_size_read(ip);
747 
748 	crhold(cr);
749 	cookie = spl_fstrans_mark();
750 	if (mode & FALLOC_FL_PUNCH_HOLE) {
751 		flock64_t bf;
752 
753 		if (offset > olen)
754 			goto out_unmark;
755 
756 		if (offset + len > olen)
757 			len = olen - offset;
758 		bf.l_type = F_WRLCK;
759 		bf.l_whence = SEEK_SET;
760 		bf.l_start = offset;
761 		bf.l_len = len;
762 		bf.l_pid = 0;
763 
764 		error = -zfs_space(ITOZ(ip), F_FREESP, &bf, O_RDWR, offset, cr);
765 	} else if ((mode & ~FALLOC_FL_KEEP_SIZE) == 0) {
766 		unsigned int percent = zfs_fallocate_reserve_percent;
767 		struct kstatfs statfs;
768 
769 		/* Legacy mode, disable fallocate compatibility. */
770 		if (percent == 0) {
771 			error = -EOPNOTSUPP;
772 			goto out_unmark;
773 		}
774 
775 		/*
776 		 * Use zfs_statvfs() instead of dmu_objset_space() since it
777 		 * also checks project quota limits, which are relevant here.
778 		 */
779 		error = zfs_statvfs(ip, &statfs);
780 		if (error)
781 			goto out_unmark;
782 
783 		/*
784 		 * Shrink available space a bit to account for overhead/races.
785 		 * We know the product previously fit into availbytes from
786 		 * dmu_objset_space(), so the smaller product will also fit.
787 		 */
788 		if (len > statfs.f_bavail * (statfs.f_bsize * 100 / percent)) {
789 			error = -ENOSPC;
790 			goto out_unmark;
791 		}
792 		if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > olen)
793 			error = zfs_freesp(ITOZ(ip), offset + len, 0, 0, FALSE);
794 	}
795 out_unmark:
796 	spl_fstrans_unmark(cookie);
797 	spl_inode_unlock(ip);
798 
799 	crfree(cr);
800 
801 	return (error);
802 }
803 
804 static long
805 zpl_fallocate(struct file *filp, int mode, loff_t offset, loff_t len)
806 {
807 	return zpl_fallocate_common(file_inode(filp),
808 	    mode, offset, len);
809 }
810 
811 #define	ZFS_FL_USER_VISIBLE	(FS_FL_USER_VISIBLE | ZFS_PROJINHERIT_FL)
812 #define	ZFS_FL_USER_MODIFIABLE	(FS_FL_USER_MODIFIABLE | ZFS_PROJINHERIT_FL)
813 
814 static uint32_t
815 __zpl_ioctl_getflags(struct inode *ip)
816 {
817 	uint64_t zfs_flags = ITOZ(ip)->z_pflags;
818 	uint32_t ioctl_flags = 0;
819 
820 	if (zfs_flags & ZFS_IMMUTABLE)
821 		ioctl_flags |= FS_IMMUTABLE_FL;
822 
823 	if (zfs_flags & ZFS_APPENDONLY)
824 		ioctl_flags |= FS_APPEND_FL;
825 
826 	if (zfs_flags & ZFS_NODUMP)
827 		ioctl_flags |= FS_NODUMP_FL;
828 
829 	if (zfs_flags & ZFS_PROJINHERIT)
830 		ioctl_flags |= ZFS_PROJINHERIT_FL;
831 
832 	return (ioctl_flags & ZFS_FL_USER_VISIBLE);
833 }
834 
835 /*
836  * Map zfs file z_pflags (xvattr_t) to linux file attributes. Only file
837  * attributes common to both Linux and Solaris are mapped.
838  */
839 static int
840 zpl_ioctl_getflags(struct file *filp, void __user *arg)
841 {
842 	uint32_t flags;
843 	int err;
844 
845 	flags = __zpl_ioctl_getflags(file_inode(filp));
846 	err = copy_to_user(arg, &flags, sizeof (flags));
847 
848 	return (err);
849 }
850 
851 /*
852  * fchange() is a helper macro to detect if we have been asked to change a
853  * flag. This is ugly, but the requirement that we do this is a consequence of
854  * how the Linux file attribute interface was designed. Another consequence is
855  * that concurrent modification of files suffers from a TOCTOU race. Neither
856  * are things we can fix without modifying the kernel-userland interface, which
857  * is outside of our jurisdiction.
858  */
859 
860 #define	fchange(f0, f1, b0, b1) (!((f0) & (b0)) != !((f1) & (b1)))
861 
862 static int
863 __zpl_ioctl_setflags(struct inode *ip, uint32_t ioctl_flags, xvattr_t *xva)
864 {
865 	uint64_t zfs_flags = ITOZ(ip)->z_pflags;
866 	xoptattr_t *xoap;
867 
868 	if (ioctl_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | FS_NODUMP_FL |
869 	    ZFS_PROJINHERIT_FL))
870 		return (-EOPNOTSUPP);
871 
872 	if (ioctl_flags & ~ZFS_FL_USER_MODIFIABLE)
873 		return (-EACCES);
874 
875 	if ((fchange(ioctl_flags, zfs_flags, FS_IMMUTABLE_FL, ZFS_IMMUTABLE) ||
876 	    fchange(ioctl_flags, zfs_flags, FS_APPEND_FL, ZFS_APPENDONLY)) &&
877 	    !capable(CAP_LINUX_IMMUTABLE))
878 		return (-EPERM);
879 
880 	if (!zpl_inode_owner_or_capable(kcred->user_ns, ip))
881 		return (-EACCES);
882 
883 	xva_init(xva);
884 	xoap = xva_getxoptattr(xva);
885 
886 	XVA_SET_REQ(xva, XAT_IMMUTABLE);
887 	if (ioctl_flags & FS_IMMUTABLE_FL)
888 		xoap->xoa_immutable = B_TRUE;
889 
890 	XVA_SET_REQ(xva, XAT_APPENDONLY);
891 	if (ioctl_flags & FS_APPEND_FL)
892 		xoap->xoa_appendonly = B_TRUE;
893 
894 	XVA_SET_REQ(xva, XAT_NODUMP);
895 	if (ioctl_flags & FS_NODUMP_FL)
896 		xoap->xoa_nodump = B_TRUE;
897 
898 	XVA_SET_REQ(xva, XAT_PROJINHERIT);
899 	if (ioctl_flags & ZFS_PROJINHERIT_FL)
900 		xoap->xoa_projinherit = B_TRUE;
901 
902 	return (0);
903 }
904 
905 static int
906 zpl_ioctl_setflags(struct file *filp, void __user *arg)
907 {
908 	struct inode *ip = file_inode(filp);
909 	uint32_t flags;
910 	cred_t *cr = CRED();
911 	xvattr_t xva;
912 	int err;
913 	fstrans_cookie_t cookie;
914 
915 	if (copy_from_user(&flags, arg, sizeof (flags)))
916 		return (-EFAULT);
917 
918 	err = __zpl_ioctl_setflags(ip, flags, &xva);
919 	if (err)
920 		return (err);
921 
922 	crhold(cr);
923 	cookie = spl_fstrans_mark();
924 	err = -zfs_setattr(ITOZ(ip), (vattr_t *)&xva, 0, cr);
925 	spl_fstrans_unmark(cookie);
926 	crfree(cr);
927 
928 	return (err);
929 }
930 
931 static int
932 zpl_ioctl_getxattr(struct file *filp, void __user *arg)
933 {
934 	zfsxattr_t fsx = { 0 };
935 	struct inode *ip = file_inode(filp);
936 	int err;
937 
938 	fsx.fsx_xflags = __zpl_ioctl_getflags(ip);
939 	fsx.fsx_projid = ITOZ(ip)->z_projid;
940 	err = copy_to_user(arg, &fsx, sizeof (fsx));
941 
942 	return (err);
943 }
944 
945 static int
946 zpl_ioctl_setxattr(struct file *filp, void __user *arg)
947 {
948 	struct inode *ip = file_inode(filp);
949 	zfsxattr_t fsx;
950 	cred_t *cr = CRED();
951 	xvattr_t xva;
952 	xoptattr_t *xoap;
953 	int err;
954 	fstrans_cookie_t cookie;
955 
956 	if (copy_from_user(&fsx, arg, sizeof (fsx)))
957 		return (-EFAULT);
958 
959 	if (!zpl_is_valid_projid(fsx.fsx_projid))
960 		return (-EINVAL);
961 
962 	err = __zpl_ioctl_setflags(ip, fsx.fsx_xflags, &xva);
963 	if (err)
964 		return (err);
965 
966 	xoap = xva_getxoptattr(&xva);
967 	XVA_SET_REQ(&xva, XAT_PROJID);
968 	xoap->xoa_projid = fsx.fsx_projid;
969 
970 	crhold(cr);
971 	cookie = spl_fstrans_mark();
972 	err = -zfs_setattr(ITOZ(ip), (vattr_t *)&xva, 0, cr);
973 	spl_fstrans_unmark(cookie);
974 	crfree(cr);
975 
976 	return (err);
977 }
978 
979 static long
980 zpl_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
981 {
982 	switch (cmd) {
983 	case FS_IOC_GETFLAGS:
984 		return (zpl_ioctl_getflags(filp, (void *)arg));
985 	case FS_IOC_SETFLAGS:
986 		return (zpl_ioctl_setflags(filp, (void *)arg));
987 	case ZFS_IOC_FSGETXATTR:
988 		return (zpl_ioctl_getxattr(filp, (void *)arg));
989 	case ZFS_IOC_FSSETXATTR:
990 		return (zpl_ioctl_setxattr(filp, (void *)arg));
991 	default:
992 		return (-ENOTTY);
993 	}
994 }
995 
996 #ifdef CONFIG_COMPAT
997 static long
998 zpl_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
999 {
1000 	switch (cmd) {
1001 	case FS_IOC32_GETFLAGS:
1002 		cmd = FS_IOC_GETFLAGS;
1003 		break;
1004 	case FS_IOC32_SETFLAGS:
1005 		cmd = FS_IOC_SETFLAGS;
1006 		break;
1007 	default:
1008 		return (-ENOTTY);
1009 	}
1010 	return (zpl_ioctl(filp, cmd, (unsigned long)compat_ptr(arg)));
1011 }
1012 #endif /* CONFIG_COMPAT */
1013 
1014 
1015 const struct address_space_operations zpl_address_space_operations = {
1016 	.readpages	= zpl_readpages,
1017 	.readpage	= zpl_readpage,
1018 	.writepage	= zpl_writepage,
1019 	.writepages	= zpl_writepages,
1020 	.direct_IO	= zpl_direct_IO,
1021 };
1022 
1023 const struct file_operations zpl_file_operations = {
1024 	.open		= zpl_open,
1025 	.release	= zpl_release,
1026 	.llseek		= zpl_llseek,
1027 #ifdef HAVE_VFS_RW_ITERATE
1028 #ifdef HAVE_NEW_SYNC_READ
1029 	.read		= new_sync_read,
1030 	.write		= new_sync_write,
1031 #endif
1032 	.read_iter	= zpl_iter_read,
1033 	.write_iter	= zpl_iter_write,
1034 #ifdef HAVE_VFS_IOV_ITER
1035 	.splice_read	= generic_file_splice_read,
1036 	.splice_write	= iter_file_splice_write,
1037 #endif
1038 #else
1039 	.read		= do_sync_read,
1040 	.write		= do_sync_write,
1041 	.aio_read	= zpl_aio_read,
1042 	.aio_write	= zpl_aio_write,
1043 #endif
1044 	.mmap		= zpl_mmap,
1045 	.fsync		= zpl_fsync,
1046 #ifdef HAVE_FILE_AIO_FSYNC
1047 	.aio_fsync	= zpl_aio_fsync,
1048 #endif
1049 	.fallocate	= zpl_fallocate,
1050 	.unlocked_ioctl	= zpl_ioctl,
1051 #ifdef CONFIG_COMPAT
1052 	.compat_ioctl	= zpl_compat_ioctl,
1053 #endif
1054 };
1055 
1056 const struct file_operations zpl_dir_file_operations = {
1057 	.llseek		= generic_file_llseek,
1058 	.read		= generic_read_dir,
1059 #if defined(HAVE_VFS_ITERATE_SHARED)
1060 	.iterate_shared	= zpl_iterate,
1061 #elif defined(HAVE_VFS_ITERATE)
1062 	.iterate	= zpl_iterate,
1063 #else
1064 	.readdir	= zpl_readdir,
1065 #endif
1066 	.fsync		= zpl_fsync,
1067 	.unlocked_ioctl = zpl_ioctl,
1068 #ifdef CONFIG_COMPAT
1069 	.compat_ioctl   = zpl_compat_ioctl,
1070 #endif
1071 };
1072 
1073 /* BEGIN CSTYLED */
1074 module_param(zfs_fallocate_reserve_percent, uint, 0644);
1075 MODULE_PARM_DESC(zfs_fallocate_reserve_percent,
1076     "Percentage of length to use for the available capacity check");
1077 /* END CSTYLED */
1078