xref: /freebsd/sys/contrib/openzfs/module/os/freebsd/zfs/zfs_vnops_os.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
16  * Copyright (c) 2014 Integros [integros.com]
17  * Copyright 2017 Nexenta Systems, Inc.
18  * Copyright (c) 2025, Klara, Inc.
19  * Copyright (c) 2026, TrueNAS.
20  */
21 
22 /* Portions Copyright 2007 Jeremy Teo */
23 /* Portions Copyright 2010 Robert Milkowski */
24 
25 #include <sys/param.h>
26 #include <sys/time.h>
27 #include <sys/systm.h>
28 #include <sys/sysmacros.h>
29 #include <sys/resource.h>
30 #include <security/mac/mac_framework.h>
31 #include <sys/vfs.h>
32 #include <sys/endian.h>
33 #include <sys/vm.h>
34 #include <sys/vnode.h>
35 #include <sys/smr.h>
36 #include <sys/dirent.h>
37 #include <sys/file.h>
38 #include <sys/stat.h>
39 #include <sys/kmem.h>
40 #include <sys/taskq.h>
41 #include <sys/uio.h>
42 #include <sys/atomic.h>
43 #include <sys/namei.h>
44 #include <sys/mman.h>
45 #include <sys/cmn_err.h>
46 #include <sys/kdb.h>
47 #include <sys/sysproto.h>
48 #include <sys/errno.h>
49 #include <sys/unistd.h>
50 #include <sys/zfs_dir.h>
51 #include <sys/zfs_ioctl.h>
52 #include <sys/fs/zfs.h>
53 #include <sys/dmu.h>
54 #include <sys/dmu_objset.h>
55 #include <sys/dsl_dataset.h>
56 #include <sys/spa.h>
57 #include <sys/txg.h>
58 #include <sys/dbuf.h>
59 #include <sys/zap.h>
60 #include <sys/sa.h>
61 #include <sys/policy.h>
62 #include <sys/sunddi.h>
63 #include <sys/filio.h>
64 #include <sys/sid.h>
65 #include <sys/zfs_ctldir.h>
66 #include <sys/zfs_fuid.h>
67 #include <sys/zfs_quota.h>
68 #include <sys/zfs_sa.h>
69 #include <sys/zfs_rlock.h>
70 #include <sys/zfs_project.h>
71 #include <sys/bio.h>
72 #include <sys/buf.h>
73 #include <sys/sched.h>
74 #include <sys/acl.h>
75 #include <sys/vmmeter.h>
76 #include <vm/vm_param.h>
77 #include <sys/zil.h>
78 #include <sys/zfs_vnops.h>
79 #include <sys/module.h>
80 #include <sys/sysent.h>
81 #include <sys/dmu_impl.h>
82 #include <sys/brt.h>
83 #include <sys/zfeature.h>
84 
85 #include <vm/vm_object.h>
86 
87 #include <sys/extattr.h>
88 #include <sys/priv.h>
89 
90 #ifndef VN_OPEN_INVFS
91 #define	VN_OPEN_INVFS	0x0
92 #endif
93 
94 VFS_SMR_DECLARE;
95 
96 #if __FreeBSD_version >= 1400045
97 typedef uint64_t cookie_t;
98 #else
99 typedef ulong_t cookie_t;
100 #endif
101 
102 static int zfs_check_attrname(const char *name);
103 
104 /*
105  * Programming rules.
106  *
107  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
108  * properly lock its in-core state, create a DMU transaction, do the work,
109  * record this work in the intent log (ZIL), commit the DMU transaction,
110  * and wait for the intent log to commit if it is a synchronous operation.
111  * Moreover, the vnode ops must work in both normal and log replay context.
112  * The ordering of events is important to avoid deadlocks and references
113  * to freed memory.  The example below illustrates the following Big Rules:
114  *
115  *  (1)	A check must be made in each zfs thread for a mounted file system.
116  *	This is done avoiding races using zfs_enter(zfsvfs).
117  *	A zfs_exit(zfsvfs) is needed before all returns.  Any znodes
118  *	must be checked with zfs_verify_zp(zp).  Both of these macros
119  *	can return EIO from the calling function.
120  *
121  *  (2)	VN_RELE() should always be the last thing except for zil_commit()
122  *	(if necessary) and zfs_exit(). This is for 3 reasons:
123  *	First, if it's the last reference, the vnode/znode
124  *	can be freed, so the zp may point to freed memory.  Second, the last
125  *	reference will call zfs_zinactive(), which may induce a lot of work --
126  *	pushing cached pages (which acquires range locks) and syncing out
127  *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
128  *	which could deadlock the system if you were already holding one.
129  *	If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
130  *
131  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
132  *	as they can span dmu_tx_assign() calls.
133  *
134  *  (4) If ZPL locks are held, pass DMU_TX_NOWAIT as the second argument to
135  *      dmu_tx_assign().  This is critical because we don't want to block
136  *      while holding locks.
137  *
138  *	If no ZPL locks are held (aside from zfs_enter()), use DMU_TX_WAIT.
139  *	This reduces lock contention and CPU usage when we must wait (note
140  *	that if throughput is constrained by the storage, nearly every
141  *	transaction must wait).
142  *
143  *      Note, in particular, that if a lock is sometimes acquired before
144  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
145  *      to use a non-blocking assign can deadlock the system.  The scenario:
146  *
147  *	Thread A has grabbed a lock before calling dmu_tx_assign().
148  *	Thread B is in an already-assigned tx, and blocks for this lock.
149  *	Thread A calls dmu_tx_assign(DMU_TX_WAIT) and blocks in
150  *	txg_wait_open() forever, because the previous txg can't quiesce
151  *	until B's tx commits.
152  *
153  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is
154  *	DMU_TX_NOWAIT, then drop all locks, call dmu_tx_wait(), and try
155  *	again.  On subsequent calls to dmu_tx_assign(), pass
156  *	DMU_TX_NOTHROTTLE in addition to DMU_TX_NOWAIT, to indicate that
157  *	this operation has already called dmu_tx_wait().  This will ensure
158  *	that we don't retry forever, waiting a short bit each time.
159  *
160  *  (5)	If the operation succeeded, generate the intent log entry for it
161  *	before dropping locks.  This ensures that the ordering of events
162  *	in the intent log matches the order in which they actually occurred.
163  *	During ZIL replay the zfs_log_* functions will update the sequence
164  *	number to indicate the zil transaction has replayed.
165  *
166  *  (6)	At the end of each vnode op, the DMU tx must always commit,
167  *	regardless of whether there were any errors.
168  *
169  *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
170  *	to ensure that synchronous semantics are provided when necessary.
171  *
172  * In general, this is how things should be ordered in each vnode op:
173  *
174  *	zfs_enter(zfsvfs);		// exit if unmounted
175  * top:
176  *	zfs_dirent_lookup(&dl, ...)	// lock directory entry (may VN_HOLD())
177  *	rw_enter(...);			// grab any other locks you need
178  *	tx = dmu_tx_create(...);	// get DMU tx
179  *	dmu_tx_hold_*();		// hold each object you might modify
180  *	error = dmu_tx_assign(tx,
181  *	    (waited ? DMU_TX_NOTHROTTLE : 0) | DMU_TX_NOWAIT);
182  *	if (error) {
183  *		rw_exit(...);		// drop locks
184  *		zfs_dirent_unlock(dl);	// unlock directory entry
185  *		VN_RELE(...);		// release held vnodes
186  *		if (error == ERESTART) {
187  *			waited = B_TRUE;
188  *			dmu_tx_wait(tx);
189  *			dmu_tx_abort(tx);
190  *			goto top;
191  *		}
192  *		dmu_tx_abort(tx);	// abort DMU tx
193  *		zfs_exit(zfsvfs);	// finished in zfs
194  *		return (error);		// really out of space
195  *	}
196  *	error = do_real_work();		// do whatever this VOP does
197  *	if (error == 0)
198  *		zfs_log_*(...);		// on success, make ZIL entry
199  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
200  *	rw_exit(...);			// drop locks
201  *	zfs_dirent_unlock(dl);		// unlock directory entry
202  *	VN_RELE(...);			// release held vnodes
203  *	zil_commit(zilog, foid);	// synchronous when necessary
204  *	zfs_exit(zfsvfs);		// finished in zfs
205  *	return (error);			// done, report error
206  */
207 static int
zfs_open(vnode_t ** vpp,int flag,cred_t * cr)208 zfs_open(vnode_t **vpp, int flag, cred_t *cr)
209 {
210 	(void) cr;
211 	znode_t	*zp = VTOZ(*vpp);
212 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
213 	int error;
214 
215 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
216 		return (error);
217 
218 	if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
219 	    ((flag & FAPPEND) == 0)) {
220 		zfs_exit(zfsvfs, FTAG);
221 		return (SET_ERROR(EPERM));
222 	}
223 
224 	/*
225 	 * Keep a count of the synchronous opens in the znode.  On first
226 	 * synchronous open we must convert all previous async transactions
227 	 * into sync to keep correct ordering.
228 	 * Skip it for snapshot, as it won't have any transactions.
229 	 */
230 	if (!zfsvfs->z_issnap && (flag & O_SYNC)) {
231 		if (atomic_inc_32_nv(&zp->z_sync_cnt) == 1)
232 			zil_async_to_sync(zfsvfs->z_log, zp->z_id);
233 	}
234 
235 	zfs_exit(zfsvfs, FTAG);
236 	return (0);
237 }
238 
239 static int
zfs_close(vnode_t * vp,int flag,int count,offset_t offset,cred_t * cr)240 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
241 {
242 	(void) offset, (void) cr;
243 	znode_t	*zp = VTOZ(vp);
244 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
245 	int error;
246 
247 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
248 		return (error);
249 
250 	/* Decrement the synchronous opens in the znode */
251 	if (!zfsvfs->z_issnap && (flag & O_SYNC) && (count == 1))
252 		atomic_dec_32(&zp->z_sync_cnt);
253 
254 	zfs_exit(zfsvfs, FTAG);
255 	return (0);
256 }
257 
258 static int
zfs_ioctl_getxattr(vnode_t * vp,zfsxattr_t * fsx)259 zfs_ioctl_getxattr(vnode_t *vp, zfsxattr_t *fsx)
260 {
261 	znode_t *zp = VTOZ(vp);
262 
263 	memset(fsx, 0, sizeof (*fsx));
264 	fsx->fsx_xflags = (zp->z_pflags & ZFS_PROJINHERIT) ?
265 	    FS_PROJINHERIT_FL : 0;
266 	fsx->fsx_projid = zp->z_projid;
267 
268 	return (0);
269 }
270 
271 static int
zfs_ioctl_setflags(vnode_t * vp,uint32_t ioctl_flags,xvattr_t * xva)272 zfs_ioctl_setflags(vnode_t *vp, uint32_t ioctl_flags, xvattr_t *xva)
273 {
274 	uint64_t zfs_flags = VTOZ(vp)->z_pflags;
275 	xoptattr_t *xoap;
276 
277 	if (ioctl_flags & ~(FS_PROJINHERIT_FL))
278 		return (SET_ERROR(EOPNOTSUPP));
279 
280 	xva_init(xva);
281 	xoap = xva_getxoptattr(xva);
282 
283 #define	FLAG_CHANGE(iflag, zflag, xflag, xfield)	do {		\
284 	if (((ioctl_flags & (iflag)) && !(zfs_flags & (zflag))) ||	\
285 	    ((zfs_flags & (zflag)) && !(ioctl_flags & (iflag)))) {	\
286 		XVA_SET_REQ(xva, (xflag));				\
287 		(xfield) = ((ioctl_flags & (iflag)) != 0);		\
288 	}								\
289 } while (0)
290 
291 	FLAG_CHANGE(FS_PROJINHERIT_FL, ZFS_PROJINHERIT, XAT_PROJINHERIT,
292 	    xoap->xoa_projinherit);
293 
294 #undef	FLAG_CHANGE
295 
296 	return (0);
297 }
298 
299 static int
zfs_ioctl_setxattr(vnode_t * vp,zfsxattr_t * fsx,cred_t * cr)300 zfs_ioctl_setxattr(vnode_t *vp, zfsxattr_t *fsx, cred_t *cr)
301 {
302 	znode_t *zp = VTOZ(vp);
303 	xvattr_t xva;
304 	xoptattr_t *xoap;
305 	int err;
306 
307 	if (!zpl_is_valid_projid(fsx->fsx_projid))
308 		return (SET_ERROR(EINVAL));
309 
310 	err = zfs_ioctl_setflags(vp, fsx->fsx_xflags, &xva);
311 	if (err)
312 		return (err);
313 
314 	xoap = xva_getxoptattr(&xva);
315 	XVA_SET_REQ(&xva, XAT_PROJID);
316 	xoap->xoa_projid = fsx->fsx_projid;
317 
318 	err = zfs_setattr(zp, (vattr_t *)&xva, 0, cr);
319 
320 	return (err);
321 }
322 
323 static int
zfs_ioctl(vnode_t * vp,ulong_t com,intptr_t data,int flag,cred_t * cred,int * rvalp)324 zfs_ioctl(vnode_t *vp, ulong_t com, intptr_t data, int flag, cred_t *cred,
325     int *rvalp)
326 {
327 	(void) flag, (void) cred, (void) rvalp;
328 	loff_t off;
329 	int error;
330 
331 	switch (com) {
332 	case _FIOFFS:
333 	{
334 		return (0);
335 
336 		/*
337 		 * The following two ioctls are used by bfu.  Faking out,
338 		 * necessary to avoid bfu errors.
339 		 */
340 	}
341 	case _FIOGDIO:
342 	case _FIOSDIO:
343 	{
344 		return (0);
345 	}
346 
347 	case F_SEEK_DATA:
348 	case F_SEEK_HOLE:
349 	{
350 		off = *(offset_t *)data;
351 		error = vn_lock(vp, LK_SHARED);
352 		if (error)
353 			return (error);
354 		/* offset parameter is in/out */
355 		error = zfs_holey(VTOZ(vp), com, &off);
356 		VOP_UNLOCK(vp);
357 		if (error)
358 			return (error);
359 		*(offset_t *)data = off;
360 		return (0);
361 	}
362 	case ZFS_IOC_FSGETXATTR: {
363 		zfsxattr_t *fsx = (zfsxattr_t *)data;
364 		error = vn_lock(vp, LK_SHARED);
365 		if (error)
366 			return (error);
367 		error = zfs_ioctl_getxattr(vp, fsx);
368 		VOP_UNLOCK(vp);
369 		return (error);
370 	}
371 	case ZFS_IOC_FSSETXATTR: {
372 		zfsxattr_t *fsx = (zfsxattr_t *)data;
373 		error = vn_lock(vp, LK_EXCLUSIVE);
374 		if (error)
375 			return (error);
376 		vn_seqc_write_begin(vp);
377 		error = zfs_ioctl_setxattr(vp, fsx, cred);
378 		vn_seqc_write_end(vp);
379 		VOP_UNLOCK(vp);
380 		return (error);
381 	}
382 	case ZFS_IOC_REWRITE: {
383 		zfs_rewrite_args_t *args = (zfs_rewrite_args_t *)data;
384 		if ((flag & FWRITE) == 0)
385 			return (SET_ERROR(EBADF));
386 		error = vn_lock(vp, LK_SHARED);
387 		if (error)
388 			return (error);
389 		error = zfs_rewrite(VTOZ(vp), args->off, args->len,
390 		    args->flags, args->arg);
391 		VOP_UNLOCK(vp);
392 		return (error);
393 	}
394 	}
395 	return (SET_ERROR(ENOTTY));
396 }
397 
398 static vm_page_t
page_busy(vnode_t * vp,int64_t start,int64_t off,int64_t nbytes)399 page_busy(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
400 {
401 	vm_object_t obj;
402 	vm_page_t pp;
403 	int64_t end;
404 
405 	/*
406 	 * At present vm_page_clear_dirty extends the cleared range to DEV_BSIZE
407 	 * aligned boundaries, if the range is not aligned.  As a result a
408 	 * DEV_BSIZE subrange with partially dirty data may get marked as clean.
409 	 * It may happen that all DEV_BSIZE subranges are marked clean and thus
410 	 * the whole page would be considered clean despite have some
411 	 * dirty data.
412 	 * For this reason we should shrink the range to DEV_BSIZE aligned
413 	 * boundaries before calling vm_page_clear_dirty.
414 	 */
415 	end = rounddown2(off + nbytes, DEV_BSIZE);
416 	off = roundup2(off, DEV_BSIZE);
417 	nbytes = end - off;
418 
419 	obj = vp->v_object;
420 	vm_page_grab_valid_unlocked(&pp, obj, OFF_TO_IDX(start),
421 	    VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_NORMAL |
422 	    VM_ALLOC_IGN_SBUSY);
423 	if (pp != NULL) {
424 		ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
425 		vm_object_pip_add(obj, 1);
426 		pmap_remove_write(pp);
427 		if (nbytes != 0)
428 			vm_page_clear_dirty(pp, off, nbytes);
429 	}
430 	return (pp);
431 }
432 
433 static void
page_unbusy(vm_page_t pp)434 page_unbusy(vm_page_t pp)
435 {
436 
437 	vm_page_sunbusy(pp);
438 	vm_object_pip_wakeup(pp->object);
439 }
440 
441 static vm_page_t
page_hold(vnode_t * vp,int64_t start)442 page_hold(vnode_t *vp, int64_t start)
443 {
444 	vm_object_t obj;
445 	vm_page_t m;
446 
447 	obj = vp->v_object;
448 	vm_page_grab_valid_unlocked(&m, obj, OFF_TO_IDX(start),
449 	    VM_ALLOC_NOCREAT | VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY |
450 	    VM_ALLOC_NOBUSY);
451 	return (m);
452 }
453 
454 static void
page_unhold(vm_page_t pp)455 page_unhold(vm_page_t pp)
456 {
457 	vm_page_unwire(pp, PQ_ACTIVE);
458 }
459 
460 /*
461  * When a file is memory mapped, we must keep the IO data synchronized
462  * between the DMU cache and the memory mapped pages.  What this means:
463  *
464  * On Write:	If we find a memory mapped page, we write to *both*
465  *		the page and the dmu buffer.
466  */
467 void
update_pages(znode_t * zp,int64_t start,int len,objset_t * os)468 update_pages(znode_t *zp, int64_t start, int len, objset_t *os)
469 {
470 	vm_object_t obj;
471 	struct sf_buf *sf;
472 	vnode_t *vp = ZTOV(zp);
473 	caddr_t va;
474 	int off;
475 
476 	ASSERT3P(vp->v_mount, !=, NULL);
477 	obj = vp->v_object;
478 	ASSERT3P(obj, !=, NULL);
479 
480 	off = start & PAGEOFFSET;
481 	vm_object_pip_add(obj, 1);
482 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
483 		vm_page_t pp;
484 		int nbytes = imin(PAGESIZE - off, len);
485 
486 		if ((pp = page_busy(vp, start, off, nbytes)) != NULL) {
487 			va = zfs_map_page(pp, &sf);
488 			(void) dmu_read(os, zp->z_id, start + off, nbytes,
489 			    va + off, DMU_READ_PREFETCH);
490 			zfs_unmap_page(sf);
491 			page_unbusy(pp);
492 		}
493 		len -= nbytes;
494 		off = 0;
495 	}
496 	vm_object_pip_wakeup(obj);
497 }
498 
499 /*
500  * Read with UIO_NOCOPY flag means that sendfile(2) requests
501  * ZFS to populate a range of page cache pages with data.
502  *
503  * NOTE: this function could be optimized to pre-allocate
504  * all pages in advance, drain exclusive busy on all of them,
505  * map them into contiguous KVA region and populate them
506  * in one single dmu_read() call.
507  */
508 int
mappedread_sf(znode_t * zp,int nbytes,zfs_uio_t * uio)509 mappedread_sf(znode_t *zp, int nbytes, zfs_uio_t *uio)
510 {
511 	vnode_t *vp = ZTOV(zp);
512 	objset_t *os = zp->z_zfsvfs->z_os;
513 	struct sf_buf *sf;
514 	vm_object_t obj;
515 	vm_page_t pp;
516 	int64_t start;
517 	caddr_t va;
518 	int len = nbytes;
519 	int error = 0;
520 
521 	ASSERT3U(zfs_uio_segflg(uio), ==, UIO_NOCOPY);
522 	ASSERT3P(vp->v_mount, !=, NULL);
523 	obj = vp->v_object;
524 	ASSERT3P(obj, !=, NULL);
525 	ASSERT0(zfs_uio_offset(uio) & PAGEOFFSET);
526 
527 	for (start = zfs_uio_offset(uio); len > 0; start += PAGESIZE) {
528 		int bytes = MIN(PAGESIZE, len);
529 
530 		pp = vm_page_grab_unlocked(obj, OFF_TO_IDX(start),
531 		    VM_ALLOC_SBUSY | VM_ALLOC_NORMAL | VM_ALLOC_IGN_SBUSY);
532 		if (vm_page_none_valid(pp)) {
533 			va = zfs_map_page(pp, &sf);
534 			error = dmu_read(os, zp->z_id, start, bytes, va,
535 			    DMU_READ_PREFETCH);
536 			if (bytes != PAGESIZE && error == 0)
537 				memset(va + bytes, 0, PAGESIZE - bytes);
538 			zfs_unmap_page(sf);
539 			if (error == 0) {
540 				vm_page_valid(pp);
541 				vm_page_activate(pp);
542 				vm_page_sunbusy(pp);
543 			} else {
544 				zfs_vmobject_wlock(obj);
545 				if (!vm_page_wired(pp) && pp->valid == 0 &&
546 				    vm_page_busy_tryupgrade(pp))
547 					vm_page_free(pp);
548 				else {
549 					vm_page_deactivate_noreuse(pp);
550 					vm_page_sunbusy(pp);
551 				}
552 				zfs_vmobject_wunlock(obj);
553 			}
554 		} else {
555 			ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
556 			vm_page_sunbusy(pp);
557 		}
558 		if (error)
559 			break;
560 		zfs_uio_advance(uio, bytes);
561 		len -= bytes;
562 	}
563 	return (error);
564 }
565 
566 /*
567  * When a file is memory mapped, we must keep the IO data synchronized
568  * between the DMU cache and the memory mapped pages.  What this means:
569  *
570  * On Read:	We "read" preferentially from memory mapped pages,
571  *		else we default from the dmu buffer.
572  *
573  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
574  *	 the file is memory mapped.
575  */
576 int
mappedread(znode_t * zp,int nbytes,zfs_uio_t * uio)577 mappedread(znode_t *zp, int nbytes, zfs_uio_t *uio)
578 {
579 	vnode_t *vp = ZTOV(zp);
580 	vm_object_t obj;
581 	int64_t start;
582 	int len = nbytes;
583 	int off;
584 	int error = 0;
585 
586 	ASSERT3P(vp->v_mount, !=, NULL);
587 	obj = vp->v_object;
588 	ASSERT3P(obj, !=, NULL);
589 
590 	start = zfs_uio_offset(uio);
591 	off = start & PAGEOFFSET;
592 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
593 		vm_page_t pp;
594 		uint64_t bytes = MIN(PAGESIZE - off, len);
595 
596 		if ((pp = page_hold(vp, start))) {
597 			struct sf_buf *sf;
598 			caddr_t va;
599 
600 			va = zfs_map_page(pp, &sf);
601 			error = vn_io_fault_uiomove(va + off, bytes,
602 			    GET_UIO_STRUCT(uio));
603 			zfs_unmap_page(sf);
604 			page_unhold(pp);
605 		} else {
606 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
607 			    uio, bytes, DMU_READ_PREFETCH);
608 		}
609 		len -= bytes;
610 		off = 0;
611 		if (error)
612 			break;
613 	}
614 	return (error);
615 }
616 
617 int
zfs_write_simple(znode_t * zp,const void * data,size_t len,loff_t pos,size_t * presid)618 zfs_write_simple(znode_t *zp, const void *data, size_t len,
619     loff_t pos, size_t *presid)
620 {
621 	int error = 0;
622 	ssize_t resid;
623 
624 	error = vn_rdwr(UIO_WRITE, ZTOV(zp), __DECONST(void *, data), len, pos,
625 	    UIO_SYSSPACE, IO_SYNC, kcred, NOCRED, &resid, curthread);
626 
627 	if (error) {
628 		return (SET_ERROR(error));
629 	} else if (presid == NULL) {
630 		if (resid != 0) {
631 			error = SET_ERROR(EIO);
632 		}
633 	} else {
634 		*presid = resid;
635 	}
636 	return (error);
637 }
638 
639 void
zfs_zrele_async(znode_t * zp)640 zfs_zrele_async(znode_t *zp)
641 {
642 	vnode_t *vp = ZTOV(zp);
643 	objset_t *os = ITOZSB(vp)->z_os;
644 
645 	VN_RELE_ASYNC(vp, dsl_pool_zrele_taskq(dmu_objset_pool(os)));
646 }
647 
648 static int
zfs_dd_callback(struct mount * mp,void * arg,int lkflags,struct vnode ** vpp)649 zfs_dd_callback(struct mount *mp, void *arg, int lkflags, struct vnode **vpp)
650 {
651 	int error;
652 
653 	*vpp = arg;
654 	error = vn_lock(*vpp, lkflags);
655 	if (error != 0)
656 		vrele(*vpp);
657 	return (error);
658 }
659 
660 static int
zfs_lookup_lock(vnode_t * dvp,vnode_t * vp,const char * name,int lkflags)661 zfs_lookup_lock(vnode_t *dvp, vnode_t *vp, const char *name, int lkflags)
662 {
663 	znode_t *zdp = VTOZ(dvp);
664 	zfsvfs_t *zfsvfs __unused = zdp->z_zfsvfs;
665 	int error;
666 	int ltype;
667 
668 	if (zfsvfs->z_replay == B_FALSE)
669 		ASSERT_VOP_LOCKED(dvp, __func__);
670 
671 	if (name[0] == 0 || (name[0] == '.' && name[1] == 0)) {
672 		ASSERT3P(dvp, ==, vp);
673 		vref(dvp);
674 		ltype = lkflags & LK_TYPE_MASK;
675 		if (ltype != VOP_ISLOCKED(dvp)) {
676 			if (ltype == LK_EXCLUSIVE)
677 				vn_lock(dvp, LK_UPGRADE | LK_RETRY);
678 			else /* if (ltype == LK_SHARED) */
679 				vn_lock(dvp, LK_DOWNGRADE | LK_RETRY);
680 
681 			/*
682 			 * Relock for the "." case could leave us with
683 			 * reclaimed vnode.
684 			 */
685 			if (VN_IS_DOOMED(dvp)) {
686 				vrele(dvp);
687 				return (SET_ERROR(ENOENT));
688 			}
689 		}
690 		return (0);
691 	} else if (name[0] == '.' && name[1] == '.' && name[2] == 0) {
692 		/*
693 		 * Note that in this case, dvp is the child vnode, and we
694 		 * are looking up the parent vnode - exactly reverse from
695 		 * normal operation.  Unlocking dvp requires some rather
696 		 * tricky unlock/relock dance to prevent mp from being freed;
697 		 * use vn_vget_ino_gen() which takes care of all that.
698 		 *
699 		 * XXX Note that there is a time window when both vnodes are
700 		 * unlocked.  It is possible, although highly unlikely, that
701 		 * during that window the parent-child relationship between
702 		 * the vnodes may change, for example, get reversed.
703 		 * In that case we would have a wrong lock order for the vnodes.
704 		 * All other filesystems seem to ignore this problem, so we
705 		 * do the same here.
706 		 * A potential solution could be implemented as follows:
707 		 * - using LK_NOWAIT when locking the second vnode and retrying
708 		 *   if necessary
709 		 * - checking that the parent-child relationship still holds
710 		 *   after locking both vnodes and retrying if it doesn't
711 		 */
712 		error = vn_vget_ino_gen(dvp, zfs_dd_callback, vp, lkflags, &vp);
713 		return (error);
714 	} else {
715 		error = vn_lock(vp, lkflags);
716 		if (error != 0)
717 			vrele(vp);
718 		return (error);
719 	}
720 }
721 
722 /*
723  * Lookup an entry in a directory, or an extended attribute directory.
724  * If it exists, return a held vnode reference for it.
725  *
726  *	IN:	dvp	- vnode of directory to search.
727  *		nm	- name of entry to lookup.
728  *		pnp	- full pathname to lookup [UNUSED].
729  *		flags	- LOOKUP_XATTR set if looking for an attribute.
730  *		rdir	- root directory vnode [UNUSED].
731  *		cr	- credentials of caller.
732  *		ct	- caller context
733  *
734  *	OUT:	vpp	- vnode of located entry, NULL if not found.
735  *
736  *	RETURN:	0 on success, error code on failure.
737  *
738  * Timestamps:
739  *	NA
740  */
741 static int
zfs_lookup(vnode_t * dvp,const char * nm,vnode_t ** vpp,struct componentname * cnp,int nameiop,cred_t * cr,int flags,boolean_t cached)742 zfs_lookup(vnode_t *dvp, const char *nm, vnode_t **vpp,
743     struct componentname *cnp, int nameiop, cred_t *cr, int flags,
744     boolean_t cached)
745 {
746 	znode_t *zdp = VTOZ(dvp);
747 	znode_t *zp;
748 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
749 	seqc_t dvp_seqc;
750 	int	error = 0;
751 
752 	/*
753 	 * Fast path lookup, however we must skip DNLC lookup
754 	 * for case folding or normalizing lookups because the
755 	 * DNLC code only stores the passed in name.  This means
756 	 * creating 'a' and removing 'A' on a case insensitive
757 	 * file system would work, but DNLC still thinks 'a'
758 	 * exists and won't let you create it again on the next
759 	 * pass through fast path.
760 	 */
761 	if (!(flags & LOOKUP_XATTR)) {
762 		if (dvp->v_type != VDIR) {
763 			return (SET_ERROR(ENOTDIR));
764 		} else if (zdp->z_sa_hdl == NULL) {
765 			return (SET_ERROR(EIO));
766 		}
767 	}
768 
769 	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp,
770 	    const char *, nm);
771 
772 	if ((error = zfs_enter_verify_zp(zfsvfs, zdp, FTAG)) != 0)
773 		return (error);
774 
775 	dvp_seqc = vn_seqc_read_notmodify(dvp);
776 
777 	*vpp = NULL;
778 
779 	if (flags & LOOKUP_XATTR) {
780 		/*
781 		 * If the xattr property is off, refuse the lookup request.
782 		 */
783 		if (!(zfsvfs->z_flags & ZSB_XATTR)) {
784 			zfs_exit(zfsvfs, FTAG);
785 			return (SET_ERROR(EOPNOTSUPP));
786 		}
787 
788 		/*
789 		 * We don't allow recursive attributes..
790 		 * Maybe someday we will.
791 		 */
792 		if (zdp->z_pflags & ZFS_XATTR) {
793 			zfs_exit(zfsvfs, FTAG);
794 			return (SET_ERROR(EINVAL));
795 		}
796 
797 		if ((error = zfs_get_xattrdir(VTOZ(dvp), &zp, cr, flags))) {
798 			zfs_exit(zfsvfs, FTAG);
799 			return (error);
800 		}
801 		*vpp = ZTOV(zp);
802 
803 		/*
804 		 * Do we have permission to get into attribute directory?
805 		 */
806 		if (flags & LOOKUP_NAMED_ATTR)
807 			error = zfs_zaccess(zp, ACE_EXECUTE, V_NAMEDATTR,
808 			    B_FALSE, cr);
809 		else
810 			error = zfs_zaccess(zp, ACE_EXECUTE, 0, B_FALSE, cr);
811 		if (error) {
812 			vrele(ZTOV(zp));
813 		}
814 
815 		zfs_exit(zfsvfs, FTAG);
816 		return (error);
817 	}
818 
819 	/*
820 	 * Check accessibility of directory if we're not coming in via
821 	 * VOP_CACHEDLOOKUP.
822 	 */
823 	if (!cached) {
824 #ifdef NOEXECCHECK
825 		if ((cnp->cn_flags & NOEXECCHECK) != 0) {
826 			cnp->cn_flags &= ~NOEXECCHECK;
827 		} else
828 #endif
829 		if ((error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr))) {
830 			zfs_exit(zfsvfs, FTAG);
831 			return (error);
832 		}
833 	}
834 
835 	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
836 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
837 		zfs_exit(zfsvfs, FTAG);
838 		return (SET_ERROR(EILSEQ));
839 	}
840 
841 
842 	/*
843 	 * First handle the special cases.
844 	 */
845 	if ((cnp->cn_flags & ISDOTDOT) != 0) {
846 		/*
847 		 * If we are a snapshot mounted under .zfs, return
848 		 * the vp for the snapshot directory.
849 		 */
850 		if (zdp->z_id == zfsvfs->z_root && zfsvfs->z_parent != zfsvfs) {
851 			struct componentname cn;
852 			vnode_t *zfsctl_vp;
853 			int ltype;
854 
855 			zfs_exit(zfsvfs, FTAG);
856 			ltype = VOP_ISLOCKED(dvp);
857 			VOP_UNLOCK(dvp);
858 			error = zfsctl_root(zfsvfs->z_parent, LK_SHARED,
859 			    &zfsctl_vp);
860 			if (error == 0) {
861 				cn.cn_nameptr = "snapshot";
862 				cn.cn_namelen = strlen(cn.cn_nameptr);
863 				cn.cn_nameiop = cnp->cn_nameiop;
864 				cn.cn_flags = cnp->cn_flags & ~ISDOTDOT;
865 				cn.cn_lkflags = cnp->cn_lkflags;
866 				error = VOP_LOOKUP(zfsctl_vp, vpp, &cn);
867 				vput(zfsctl_vp);
868 			}
869 			vn_lock(dvp, ltype | LK_RETRY);
870 			return (error);
871 		}
872 	}
873 	if (zfs_has_ctldir(zdp) && strcmp(nm, ZFS_CTLDIR_NAME) == 0) {
874 		zfs_exit(zfsvfs, FTAG);
875 		if (zfsvfs->z_show_ctldir == ZFS_SNAPDIR_DISABLED)
876 			return (SET_ERROR(ENOENT));
877 		if ((cnp->cn_flags & ISLASTCN) != 0 && nameiop != LOOKUP)
878 			return (SET_ERROR(ENOTSUP));
879 		error = zfsctl_root(zfsvfs, cnp->cn_lkflags, vpp);
880 		return (error);
881 	}
882 
883 	/*
884 	 * The loop is retry the lookup if the parent-child relationship
885 	 * changes during the dot-dot locking complexities.
886 	 */
887 	for (;;) {
888 		uint64_t parent;
889 
890 		error = zfs_dirlook(zdp, nm, &zp);
891 		if (error == 0)
892 			*vpp = ZTOV(zp);
893 
894 		zfs_exit(zfsvfs, FTAG);
895 		if (error != 0)
896 			break;
897 
898 		error = zfs_lookup_lock(dvp, *vpp, nm, cnp->cn_lkflags);
899 		if (error != 0) {
900 			/*
901 			 * If we've got a locking error, then the vnode
902 			 * got reclaimed because of a force unmount.
903 			 * We never enter doomed vnodes into the name cache.
904 			 */
905 			*vpp = NULL;
906 			return (error);
907 		}
908 
909 		if ((cnp->cn_flags & ISDOTDOT) == 0)
910 			break;
911 
912 		if ((error = zfs_enter(zfsvfs, FTAG)) != 0) {
913 			vput(ZTOV(zp));
914 			*vpp = NULL;
915 			return (error);
916 		}
917 		if (zdp->z_sa_hdl == NULL) {
918 			error = SET_ERROR(EIO);
919 		} else {
920 			error = sa_lookup(zdp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
921 			    &parent, sizeof (parent));
922 		}
923 		if (error != 0) {
924 			zfs_exit(zfsvfs, FTAG);
925 			vput(ZTOV(zp));
926 			break;
927 		}
928 		if (zp->z_id == parent) {
929 			zfs_exit(zfsvfs, FTAG);
930 			break;
931 		}
932 		vput(ZTOV(zp));
933 	}
934 
935 	if (error != 0)
936 		*vpp = NULL;
937 
938 	/* Translate errors and add SAVENAME when needed. */
939 	if (cnp->cn_flags & ISLASTCN) {
940 		switch (nameiop) {
941 		case CREATE:
942 		case RENAME:
943 			if (error == ENOENT) {
944 				error = EJUSTRETURN;
945 #if __FreeBSD_version < 1400068
946 				cnp->cn_flags |= SAVENAME;
947 #endif
948 				break;
949 			}
950 			zfs_fallthrough;
951 		case DELETE:
952 #if __FreeBSD_version < 1400068
953 			if (error == 0)
954 				cnp->cn_flags |= SAVENAME;
955 #endif
956 			break;
957 		}
958 	}
959 
960 	if ((cnp->cn_flags & ISDOTDOT) != 0) {
961 		/*
962 		 * FIXME: zfs_lookup_lock relocks vnodes and does nothing to
963 		 * handle races. In particular different callers may end up
964 		 * with different vnodes and will try to add conflicting
965 		 * entries to the namecache.
966 		 *
967 		 * While finding different result may be acceptable in face
968 		 * of concurrent modification, adding conflicting entries
969 		 * trips over an assert in the namecache.
970 		 *
971 		 * Ultimately let an entry through once everything settles.
972 		 */
973 		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
974 			cnp->cn_flags &= ~MAKEENTRY;
975 		}
976 	}
977 
978 	/* Insert name into cache (as non-existent) if appropriate. */
979 	if (zfsvfs->z_use_namecache && !zfsvfs->z_replay &&
980 	    error == ENOENT && (cnp->cn_flags & MAKEENTRY) != 0)
981 		cache_enter(dvp, NULL, cnp);
982 
983 	/* Insert name into cache if appropriate. */
984 	if (zfsvfs->z_use_namecache && !zfsvfs->z_replay &&
985 	    error == 0 && (cnp->cn_flags & MAKEENTRY)) {
986 		if (!(cnp->cn_flags & ISLASTCN) ||
987 		    (nameiop != DELETE && nameiop != RENAME)) {
988 			cache_enter(dvp, *vpp, cnp);
989 		}
990 	}
991 
992 	return (error);
993 }
994 
995 static inline bool
is_nametoolong(zfsvfs_t * zfsvfs,const char * name)996 is_nametoolong(zfsvfs_t *zfsvfs, const char *name)
997 {
998 	size_t dlen = strlen(name);
999 	return ((!zfsvfs->z_longname && dlen >= ZAP_MAXNAMELEN) ||
1000 	    dlen >= ZAP_MAXNAMELEN_NEW);
1001 }
1002 
1003 /*
1004  * Attempt to create a new entry in a directory.  If the entry
1005  * already exists, truncate the file if permissible, else return
1006  * an error.  Return the vp of the created or trunc'd file.
1007  *
1008  *	IN:	dvp	- vnode of directory to put new file entry in.
1009  *		name	- name of new file entry.
1010  *		vap	- attributes of new file.
1011  *		excl	- flag indicating exclusive or non-exclusive mode.
1012  *		mode	- mode to open file with.
1013  *		cr	- credentials of caller.
1014  *		flag	- large file flag [UNUSED].
1015  *		ct	- caller context
1016  *		vsecp	- ACL to be set
1017  *
1018  *	OUT:	vpp	- vnode of created or trunc'd entry.
1019  *
1020  *	RETURN:	0 on success, error code on failure.
1021  *
1022  * Timestamps:
1023  *	dvp - ctime|mtime updated if new entry created
1024  *	 vp - ctime|mtime always, atime if new
1025  */
1026 int
zfs_create(znode_t * dzp,const char * name,vattr_t * vap,int excl,int mode,znode_t ** zpp,cred_t * cr,int flag,vsecattr_t * vsecp)1027 zfs_create(znode_t *dzp, const char *name, vattr_t *vap, int excl, int mode,
1028     znode_t **zpp, cred_t *cr, int flag, vsecattr_t *vsecp)
1029 {
1030 	(void) excl, (void) mode, (void) flag;
1031 	znode_t		*zp;
1032 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1033 	zilog_t		*zilog;
1034 	objset_t	*os;
1035 	dmu_tx_t	*tx;
1036 	int		error;
1037 	uid_t		uid = crgetuid(cr);
1038 	gid_t		gid = crgetgid(cr);
1039 	uint64_t	projid = ZFS_DEFAULT_PROJID;
1040 	zfs_acl_ids_t   acl_ids;
1041 	boolean_t	fuid_dirtied;
1042 	uint64_t	txtype;
1043 
1044 	if (is_nametoolong(zfsvfs, name))
1045 		return (SET_ERROR(ENAMETOOLONG));
1046 
1047 	/*
1048 	 * If we have an ephemeral id, ACL, or XVATTR then
1049 	 * make sure file system is at proper version
1050 	 */
1051 	if (zfsvfs->z_use_fuids == B_FALSE &&
1052 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1053 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1054 		return (SET_ERROR(EINVAL));
1055 
1056 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1057 		return (error);
1058 	os = zfsvfs->z_os;
1059 	zilog = zfsvfs->z_log;
1060 
1061 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1062 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1063 		zfs_exit(zfsvfs, FTAG);
1064 		return (SET_ERROR(EILSEQ));
1065 	}
1066 
1067 	if (vap->va_mask & AT_XVATTR) {
1068 		if ((error = secpolicy_xvattr(ZTOV(dzp), (xvattr_t *)vap,
1069 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1070 			zfs_exit(zfsvfs, FTAG);
1071 			return (error);
1072 		}
1073 	}
1074 
1075 	*zpp = NULL;
1076 
1077 	if ((vap->va_mode & S_ISVTX) && secpolicy_vnode_stky_modify(cr))
1078 		vap->va_mode &= ~S_ISVTX;
1079 
1080 	error = zfs_dirent_lookup(dzp, name, &zp, ZNEW);
1081 	if (error) {
1082 		zfs_exit(zfsvfs, FTAG);
1083 		return (error);
1084 	}
1085 	ASSERT0P(zp);
1086 
1087 	/*
1088 	 * Create a new file object and update the directory
1089 	 * to reference it.
1090 	 */
1091 	if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
1092 		goto out;
1093 	}
1094 
1095 	/*
1096 	 * We only support the creation of regular files in
1097 	 * extended attribute directories.
1098 	 */
1099 
1100 	if ((dzp->z_pflags & ZFS_XATTR) &&
1101 	    (vap->va_type != VREG)) {
1102 		error = SET_ERROR(EINVAL);
1103 		goto out;
1104 	}
1105 
1106 	if ((error = zfs_acl_ids_create(dzp, 0, vap,
1107 	    cr, vsecp, &acl_ids)) != 0)
1108 		goto out;
1109 
1110 	projid = zfs_inherit_projid(dzp);
1111 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, projid)) {
1112 		zfs_acl_ids_free(&acl_ids);
1113 		error = SET_ERROR(EDQUOT);
1114 		goto out;
1115 	}
1116 
1117 	getnewvnode_reserve();
1118 
1119 	tx = dmu_tx_create(os);
1120 
1121 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1122 	    ZFS_SA_BASE_ATTR_SIZE);
1123 
1124 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1125 	if (fuid_dirtied)
1126 		zfs_fuid_txhold(zfsvfs, tx);
1127 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1128 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1129 	if (!zfsvfs->z_use_sa &&
1130 	    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1131 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1132 		    0, acl_ids.z_aclp->z_acl_bytes);
1133 	}
1134 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1135 	if (error) {
1136 		zfs_acl_ids_free(&acl_ids);
1137 		dmu_tx_abort(tx);
1138 		getnewvnode_drop_reserve();
1139 		zfs_exit(zfsvfs, FTAG);
1140 		return (error);
1141 	}
1142 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1143 
1144 	error = zfs_link_create(dzp, name, zp, tx, ZNEW);
1145 	if (error != 0) {
1146 		/*
1147 		 * Since, we failed to add the directory entry for it,
1148 		 * delete the newly created dnode.
1149 		 */
1150 		zfs_znode_delete(zp, tx);
1151 		VOP_UNLOCK(ZTOV(zp));
1152 		zrele(zp);
1153 		zfs_acl_ids_free(&acl_ids);
1154 		dmu_tx_commit(tx);
1155 		getnewvnode_drop_reserve();
1156 		goto out;
1157 	}
1158 
1159 	if (fuid_dirtied)
1160 		zfs_fuid_sync(zfsvfs, tx);
1161 
1162 	txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1163 	zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1164 	    vsecp, acl_ids.z_fuidp, vap);
1165 	zfs_acl_ids_free(&acl_ids);
1166 	dmu_tx_commit(tx);
1167 
1168 	getnewvnode_drop_reserve();
1169 
1170 out:
1171 	VNASSERT(ZTOV(dzp)->v_holdcnt > 0 && ZTOV(dzp)->v_usecount > 0,
1172 	    ZTOV(dzp), ("%s: wrong ref counts", __func__));
1173 	if (error == 0) {
1174 		*zpp = zp;
1175 	}
1176 
1177 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1178 		error = zil_commit(zilog, 0);
1179 
1180 	zfs_exit(zfsvfs, FTAG);
1181 	return (error);
1182 }
1183 
1184 /*
1185  * Remove an entry from a directory.
1186  *
1187  *	IN:	dvp	- vnode of directory to remove entry from.
1188  *		name	- name of entry to remove.
1189  *		cr	- credentials of caller.
1190  *		ct	- caller context
1191  *		flags	- case flags
1192  *
1193  *	RETURN:	0 on success, error code on failure.
1194  *
1195  * Timestamps:
1196  *	dvp - ctime|mtime
1197  *	 vp - ctime (if nlink > 0)
1198  */
1199 static int
zfs_remove_(vnode_t * dvp,vnode_t * vp,const char * name,cred_t * cr)1200 zfs_remove_(vnode_t *dvp, vnode_t *vp, const char *name, cred_t *cr)
1201 {
1202 	znode_t		*dzp = VTOZ(dvp);
1203 	znode_t		*zp;
1204 	znode_t		*xzp;
1205 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1206 	zilog_t		*zilog;
1207 	uint64_t	xattr_obj;
1208 	uint64_t	obj = 0;
1209 	dmu_tx_t	*tx;
1210 	boolean_t	unlinked;
1211 	uint64_t	txtype;
1212 	int		error;
1213 
1214 
1215 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1216 		return (error);
1217 	zp = VTOZ(vp);
1218 	if ((error = zfs_verify_zp(zp)) != 0) {
1219 		zfs_exit(zfsvfs, FTAG);
1220 		return (error);
1221 	}
1222 	zilog = zfsvfs->z_log;
1223 
1224 	xattr_obj = 0;
1225 	xzp = NULL;
1226 
1227 	if ((error = zfs_zaccess_delete(dzp, zp, cr))) {
1228 		goto out;
1229 	}
1230 
1231 	/*
1232 	 * Need to use rmdir for removing directories.
1233 	 */
1234 	if (vp->v_type == VDIR) {
1235 		error = SET_ERROR(EPERM);
1236 		goto out;
1237 	}
1238 
1239 	vnevent_remove(vp, dvp, name, ct);
1240 
1241 	obj = zp->z_id;
1242 
1243 	/* are there any extended attributes? */
1244 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1245 	    &xattr_obj, sizeof (xattr_obj));
1246 	if (error == 0 && xattr_obj) {
1247 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1248 		ASSERT0(error);
1249 	}
1250 
1251 	/*
1252 	 * We may delete the znode now, or we may put it in the unlinked set;
1253 	 * it depends on whether we're the last link, and on whether there are
1254 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1255 	 * allow for either case.
1256 	 */
1257 	tx = dmu_tx_create(zfsvfs->z_os);
1258 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1259 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
1260 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1261 	zfs_sa_upgrade_txholds(tx, zp);
1262 	zfs_sa_upgrade_txholds(tx, dzp);
1263 
1264 	if (xzp) {
1265 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1266 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1267 	}
1268 
1269 	/* charge as an update -- would be nice not to charge at all */
1270 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1271 
1272 	/*
1273 	 * Mark this transaction as typically resulting in a net free of space
1274 	 */
1275 	dmu_tx_mark_netfree(tx);
1276 
1277 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1278 	if (error) {
1279 		dmu_tx_abort(tx);
1280 		zfs_exit(zfsvfs, FTAG);
1281 		return (error);
1282 	}
1283 
1284 	/*
1285 	 * Remove the directory entry.
1286 	 */
1287 	error = zfs_link_destroy(dzp, name, zp, tx, ZEXISTS, &unlinked);
1288 
1289 	if (error) {
1290 		dmu_tx_commit(tx);
1291 		goto out;
1292 	}
1293 
1294 	if (unlinked) {
1295 		zfs_unlinked_add(zp, tx);
1296 		vp->v_vflag |= VV_NOSYNC;
1297 	}
1298 	/* XXX check changes to linux vnops */
1299 	txtype = TX_REMOVE;
1300 	zfs_log_remove(zilog, tx, txtype, dzp, name, obj, unlinked);
1301 
1302 	dmu_tx_commit(tx);
1303 out:
1304 
1305 	if (xzp)
1306 		vrele(ZTOV(xzp));
1307 
1308 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1309 		error = zil_commit(zilog, 0);
1310 
1311 	zfs_exit(zfsvfs, FTAG);
1312 	return (error);
1313 }
1314 
1315 
1316 static int
zfs_lookup_internal(znode_t * dzp,const char * name,vnode_t ** vpp,struct componentname * cnp,int nameiop)1317 zfs_lookup_internal(znode_t *dzp, const char *name, vnode_t **vpp,
1318     struct componentname *cnp, int nameiop)
1319 {
1320 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1321 	int error;
1322 
1323 	cnp->cn_nameptr = __DECONST(char *, name);
1324 	cnp->cn_namelen = strlen(name);
1325 	cnp->cn_nameiop = nameiop;
1326 	cnp->cn_flags = ISLASTCN;
1327 #if __FreeBSD_version < 1400068
1328 	cnp->cn_flags |= SAVENAME;
1329 #endif
1330 	cnp->cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
1331 	cnp->cn_cred = kcred;
1332 #if __FreeBSD_version < 1400037
1333 	cnp->cn_thread = curthread;
1334 #endif
1335 
1336 	if (zfsvfs->z_use_namecache && !zfsvfs->z_replay) {
1337 		struct vop_lookup_args a;
1338 
1339 		a.a_gen.a_desc = &vop_lookup_desc;
1340 		a.a_dvp = ZTOV(dzp);
1341 		a.a_vpp = vpp;
1342 		a.a_cnp = cnp;
1343 		error = vfs_cache_lookup(&a);
1344 	} else {
1345 		error = zfs_lookup(ZTOV(dzp), name, vpp, cnp, nameiop, kcred, 0,
1346 		    B_FALSE);
1347 	}
1348 #ifdef ZFS_DEBUG
1349 	if (error) {
1350 		printf("got error %d on name %s on op %d\n", error, name,
1351 		    nameiop);
1352 		kdb_backtrace();
1353 	}
1354 #endif
1355 	return (error);
1356 }
1357 
1358 int
zfs_remove(znode_t * dzp,const char * name,cred_t * cr,int flags)1359 zfs_remove(znode_t *dzp, const char *name, cred_t *cr, int flags)
1360 {
1361 	vnode_t *vp;
1362 	int error;
1363 	struct componentname cn;
1364 
1365 	if ((error = zfs_lookup_internal(dzp, name, &vp, &cn, DELETE)))
1366 		return (error);
1367 
1368 	error = zfs_remove_(ZTOV(dzp), vp, name, cr);
1369 	vput(vp);
1370 	return (error);
1371 }
1372 /*
1373  * Create a new directory and insert it into dvp using the name
1374  * provided.  Return a pointer to the inserted directory.
1375  *
1376  *	IN:	dvp	- vnode of directory to add subdir to.
1377  *		dirname	- name of new directory.
1378  *		vap	- attributes of new directory.
1379  *		cr	- credentials of caller.
1380  *		ct	- caller context
1381  *		flags	- case flags
1382  *		vsecp	- ACL to be set
1383  *
1384  *	OUT:	vpp	- vnode of created directory.
1385  *
1386  *	RETURN:	0 on success, error code on failure.
1387  *
1388  * Timestamps:
1389  *	dvp - ctime|mtime updated
1390  *	 vp - ctime|mtime|atime updated
1391  */
1392 int
zfs_mkdir(znode_t * dzp,const char * dirname,vattr_t * vap,znode_t ** zpp,cred_t * cr,int flags,vsecattr_t * vsecp)1393 zfs_mkdir(znode_t *dzp, const char *dirname, vattr_t *vap, znode_t **zpp,
1394     cred_t *cr, int flags, vsecattr_t *vsecp)
1395 {
1396 	(void) flags, (void) vsecp;
1397 	znode_t		*zp;
1398 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1399 	zilog_t		*zilog;
1400 	uint64_t	txtype;
1401 	dmu_tx_t	*tx;
1402 	int		error;
1403 	uid_t		uid = crgetuid(cr);
1404 	gid_t		gid = crgetgid(cr);
1405 	zfs_acl_ids_t   acl_ids;
1406 	boolean_t	fuid_dirtied;
1407 
1408 	ASSERT3U(vap->va_type, ==, VDIR);
1409 
1410 	if (is_nametoolong(zfsvfs, dirname))
1411 		return (SET_ERROR(ENAMETOOLONG));
1412 
1413 	/*
1414 	 * If we have an ephemeral id, ACL, or XVATTR then
1415 	 * make sure file system is at proper version
1416 	 */
1417 	if (zfsvfs->z_use_fuids == B_FALSE &&
1418 	    ((vap->va_mask & AT_XVATTR) ||
1419 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1420 		return (SET_ERROR(EINVAL));
1421 
1422 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1423 		return (error);
1424 	zilog = zfsvfs->z_log;
1425 
1426 	if (dzp->z_pflags & ZFS_XATTR) {
1427 		zfs_exit(zfsvfs, FTAG);
1428 		return (SET_ERROR(EINVAL));
1429 	}
1430 
1431 	if (zfsvfs->z_utf8 && u8_validate(dirname,
1432 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1433 		zfs_exit(zfsvfs, FTAG);
1434 		return (SET_ERROR(EILSEQ));
1435 	}
1436 
1437 	if (vap->va_mask & AT_XVATTR) {
1438 		if ((error = secpolicy_xvattr(ZTOV(dzp), (xvattr_t *)vap,
1439 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1440 			zfs_exit(zfsvfs, FTAG);
1441 			return (error);
1442 		}
1443 	}
1444 
1445 	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1446 	    NULL, &acl_ids)) != 0) {
1447 		zfs_exit(zfsvfs, FTAG);
1448 		return (error);
1449 	}
1450 
1451 	/*
1452 	 * First make sure the new directory doesn't exist.
1453 	 *
1454 	 * Existence is checked first to make sure we don't return
1455 	 * EACCES instead of EEXIST which can cause some applications
1456 	 * to fail.
1457 	 */
1458 	*zpp = NULL;
1459 
1460 	if ((error = zfs_dirent_lookup(dzp, dirname, &zp, ZNEW))) {
1461 		zfs_acl_ids_free(&acl_ids);
1462 		zfs_exit(zfsvfs, FTAG);
1463 		return (error);
1464 	}
1465 	ASSERT0P(zp);
1466 
1467 	if ((error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr))) {
1468 		zfs_acl_ids_free(&acl_ids);
1469 		zfs_exit(zfsvfs, FTAG);
1470 		return (error);
1471 	}
1472 
1473 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zfs_inherit_projid(dzp))) {
1474 		zfs_acl_ids_free(&acl_ids);
1475 		zfs_exit(zfsvfs, FTAG);
1476 		return (SET_ERROR(EDQUOT));
1477 	}
1478 
1479 	/*
1480 	 * Add a new entry to the directory.
1481 	 */
1482 	getnewvnode_reserve();
1483 	tx = dmu_tx_create(zfsvfs->z_os);
1484 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1485 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1486 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1487 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1488 	if (fuid_dirtied)
1489 		zfs_fuid_txhold(zfsvfs, tx);
1490 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1491 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1492 		    acl_ids.z_aclp->z_acl_bytes);
1493 	}
1494 
1495 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1496 	    ZFS_SA_BASE_ATTR_SIZE);
1497 
1498 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1499 	if (error) {
1500 		zfs_acl_ids_free(&acl_ids);
1501 		dmu_tx_abort(tx);
1502 		getnewvnode_drop_reserve();
1503 		zfs_exit(zfsvfs, FTAG);
1504 		return (error);
1505 	}
1506 
1507 	/*
1508 	 * Create new node.
1509 	 */
1510 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1511 
1512 	/*
1513 	 * Now put new name in parent dir.
1514 	 */
1515 	error = zfs_link_create(dzp, dirname, zp, tx, ZNEW);
1516 	if (error != 0) {
1517 		zfs_znode_delete(zp, tx);
1518 		VOP_UNLOCK(ZTOV(zp));
1519 		zrele(zp);
1520 		goto out;
1521 	}
1522 
1523 	if (fuid_dirtied)
1524 		zfs_fuid_sync(zfsvfs, tx);
1525 
1526 	*zpp = zp;
1527 
1528 	txtype = zfs_log_create_txtype(Z_DIR, NULL, vap);
1529 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, NULL,
1530 	    acl_ids.z_fuidp, vap);
1531 
1532 out:
1533 	zfs_acl_ids_free(&acl_ids);
1534 
1535 	dmu_tx_commit(tx);
1536 
1537 	getnewvnode_drop_reserve();
1538 
1539 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1540 		error = zil_commit(zilog, 0);
1541 
1542 	zfs_exit(zfsvfs, FTAG);
1543 	return (error);
1544 }
1545 
1546 /*
1547  * Remove a directory subdir entry.  If the current working
1548  * directory is the same as the subdir to be removed, the
1549  * remove will fail.
1550  *
1551  *	IN:	dvp	- vnode of directory to remove from.
1552  *		name	- name of directory to be removed.
1553  *		cwd	- vnode of current working directory.
1554  *		cr	- credentials of caller.
1555  *		ct	- caller context
1556  *		flags	- case flags
1557  *
1558  *	RETURN:	0 on success, error code on failure.
1559  *
1560  * Timestamps:
1561  *	dvp - ctime|mtime updated
1562  */
1563 static int
zfs_rmdir_(vnode_t * dvp,vnode_t * vp,const char * name,cred_t * cr)1564 zfs_rmdir_(vnode_t *dvp, vnode_t *vp, const char *name, cred_t *cr)
1565 {
1566 	znode_t		*dzp = VTOZ(dvp);
1567 	znode_t		*zp = VTOZ(vp);
1568 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1569 	zilog_t		*zilog;
1570 	dmu_tx_t	*tx;
1571 	int		error;
1572 
1573 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1574 		return (error);
1575 	if ((error = zfs_verify_zp(zp)) != 0) {
1576 		zfs_exit(zfsvfs, FTAG);
1577 		return (error);
1578 	}
1579 	zilog = zfsvfs->z_log;
1580 
1581 
1582 	if ((error = zfs_zaccess_delete(dzp, zp, cr))) {
1583 		goto out;
1584 	}
1585 
1586 	if (vp->v_type != VDIR) {
1587 		error = SET_ERROR(ENOTDIR);
1588 		goto out;
1589 	}
1590 
1591 	vnevent_rmdir(vp, dvp, name, ct);
1592 
1593 	tx = dmu_tx_create(zfsvfs->z_os);
1594 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1595 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
1596 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1597 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1598 	zfs_sa_upgrade_txholds(tx, zp);
1599 	zfs_sa_upgrade_txholds(tx, dzp);
1600 	dmu_tx_mark_netfree(tx);
1601 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1602 	if (error) {
1603 		dmu_tx_abort(tx);
1604 		zfs_exit(zfsvfs, FTAG);
1605 		return (error);
1606 	}
1607 
1608 	error = zfs_link_destroy(dzp, name, zp, tx, ZEXISTS, NULL);
1609 
1610 	if (error == 0) {
1611 		uint64_t txtype = TX_RMDIR;
1612 		zfs_log_remove(zilog, tx, txtype, dzp, name,
1613 		    ZFS_NO_OBJECT, B_FALSE);
1614 	}
1615 
1616 	dmu_tx_commit(tx);
1617 
1618 	if (zfsvfs->z_use_namecache)
1619 		cache_vop_rmdir(dvp, vp);
1620 out:
1621 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1622 		error = zil_commit(zilog, 0);
1623 
1624 	zfs_exit(zfsvfs, FTAG);
1625 	return (error);
1626 }
1627 
1628 int
zfs_rmdir(znode_t * dzp,const char * name,znode_t * cwd,cred_t * cr,int flags)1629 zfs_rmdir(znode_t *dzp, const char *name, znode_t *cwd, cred_t *cr, int flags)
1630 {
1631 	struct componentname cn;
1632 	vnode_t *vp;
1633 	int error;
1634 
1635 	if ((error = zfs_lookup_internal(dzp, name, &vp, &cn, DELETE)))
1636 		return (error);
1637 
1638 	error = zfs_rmdir_(ZTOV(dzp), vp, name, cr);
1639 	vput(vp);
1640 	return (error);
1641 }
1642 
1643 /*
1644  * Read as many directory entries as will fit into the provided
1645  * buffer from the given directory cursor position (specified in
1646  * the uio structure).
1647  *
1648  *	IN:	vp	- vnode of directory to read.
1649  *		uio	- structure supplying read location, range info,
1650  *			  and return buffer.
1651  *		cr	- credentials of caller.
1652  *		ct	- caller context
1653  *
1654  *	OUT:	uio	- updated offset and range, buffer filled.
1655  *		eofp	- set to true if end-of-file detected.
1656  *		ncookies- number of entries in cookies
1657  *		cookies	- offsets to directory entries
1658  *
1659  *	RETURN:	0 on success, error code on failure.
1660  *
1661  * Timestamps:
1662  *	vp - atime updated
1663  *
1664  * Note that the low 4 bits of the cookie returned by zap is always zero.
1665  * This allows us to use the low range for "special" directory entries:
1666  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1667  * we use the offset 2 for the '.zfs' directory.
1668  */
1669 static int
zfs_readdir(vnode_t * vp,zfs_uio_t * uio,cred_t * cr,int * eofp,int * ncookies,cookie_t ** cookies)1670 zfs_readdir(vnode_t *vp, zfs_uio_t *uio, cred_t *cr, int *eofp,
1671     int *ncookies, cookie_t **cookies)
1672 {
1673 	znode_t		*zp = VTOZ(vp);
1674 	iovec_t		*iovp;
1675 	dirent64_t	*odp;
1676 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1677 	objset_t	*os;
1678 	caddr_t		outbuf;
1679 	size_t		bufsize;
1680 	zap_cursor_t	zc;
1681 	zap_attribute_t	*zap;
1682 	uint_t		bytes_wanted;
1683 	uint64_t	offset; /* must be unsigned; checks for < 1 */
1684 	uint64_t	parent;
1685 	int		local_eof;
1686 	int		outcount;
1687 	int		error;
1688 	uint8_t		prefetch;
1689 	uint8_t		type;
1690 	int		ncooks;
1691 	cookie_t	*cooks = NULL;
1692 
1693 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1694 		return (error);
1695 
1696 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
1697 	    &parent, sizeof (parent))) != 0) {
1698 		zfs_exit(zfsvfs, FTAG);
1699 		return (error);
1700 	}
1701 
1702 	/*
1703 	 * If we are not given an eof variable,
1704 	 * use a local one.
1705 	 */
1706 	if (eofp == NULL)
1707 		eofp = &local_eof;
1708 
1709 	/*
1710 	 * Check for valid iov_len.
1711 	 */
1712 	if (GET_UIO_STRUCT(uio)->uio_iov->iov_len <= 0) {
1713 		zfs_exit(zfsvfs, FTAG);
1714 		return (SET_ERROR(EINVAL));
1715 	}
1716 
1717 	/*
1718 	 * Quit if directory has been removed (posix)
1719 	 */
1720 	if ((*eofp = (zp->z_unlinked != 0)) != 0) {
1721 		zfs_exit(zfsvfs, FTAG);
1722 		return (0);
1723 	}
1724 
1725 	error = 0;
1726 	os = zfsvfs->z_os;
1727 	offset = zfs_uio_offset(uio);
1728 	prefetch = zp->z_zn_prefetch;
1729 	zap = zap_attribute_long_alloc();
1730 
1731 	/*
1732 	 * Initialize the iterator cursor.
1733 	 */
1734 	if (offset <= 3) {
1735 		/*
1736 		 * Start iteration from the beginning of the directory.
1737 		 */
1738 		zap_cursor_init(&zc, os, zp->z_id);
1739 	} else {
1740 		/*
1741 		 * The offset is a serialized cursor.
1742 		 */
1743 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1744 	}
1745 
1746 	/*
1747 	 * Get space to change directory entries into fs independent format.
1748 	 */
1749 	iovp = GET_UIO_STRUCT(uio)->uio_iov;
1750 	bytes_wanted = iovp->iov_len;
1751 	if (zfs_uio_segflg(uio) != UIO_SYSSPACE || zfs_uio_iovcnt(uio) != 1) {
1752 		bufsize = bytes_wanted;
1753 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
1754 		odp = (struct dirent64 *)outbuf;
1755 	} else {
1756 		bufsize = bytes_wanted;
1757 		outbuf = NULL;
1758 		odp = (struct dirent64 *)iovp->iov_base;
1759 	}
1760 
1761 	if (ncookies != NULL) {
1762 		/*
1763 		 * Minimum entry size is dirent size and 1 byte for a file name.
1764 		 */
1765 		ncooks = zfs_uio_resid(uio) / (sizeof (struct dirent) -
1766 		    sizeof (((struct dirent *)NULL)->d_name) + 1);
1767 		cooks = malloc(ncooks * sizeof (*cooks), M_TEMP, M_WAITOK);
1768 		*cookies = cooks;
1769 		*ncookies = ncooks;
1770 	}
1771 
1772 	/*
1773 	 * Transform to file-system independent format
1774 	 */
1775 	outcount = 0;
1776 	while (outcount < bytes_wanted) {
1777 		ino64_t objnum;
1778 		ushort_t reclen;
1779 		off64_t *next = NULL;
1780 
1781 		/*
1782 		 * Special case `.', `..', and `.zfs'.
1783 		 */
1784 		if (offset == 0) {
1785 			(void) strcpy(zap->za_name, ".");
1786 			zap->za_normalization_conflict = 0;
1787 			objnum = zp->z_id;
1788 			type = DT_DIR;
1789 		} else if (offset == 1) {
1790 			(void) strcpy(zap->za_name, "..");
1791 			zap->za_normalization_conflict = 0;
1792 			objnum = parent;
1793 			type = DT_DIR;
1794 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
1795 			(void) strcpy(zap->za_name, ZFS_CTLDIR_NAME);
1796 			zap->za_normalization_conflict = 0;
1797 			objnum = ZFSCTL_INO_ROOT;
1798 			type = DT_DIR;
1799 		} else {
1800 			/*
1801 			 * Grab next entry.
1802 			 */
1803 			if ((error = zap_cursor_retrieve(&zc, zap))) {
1804 				if ((*eofp = (error == ENOENT)) != 0)
1805 					break;
1806 				else
1807 					goto update;
1808 			}
1809 
1810 			if (zap->za_integer_length != 8 ||
1811 			    zap->za_num_integers != 1) {
1812 				cmn_err(CE_WARN, "zap_readdir: bad directory "
1813 				    "entry, obj = %lld, offset = %lld\n",
1814 				    (u_longlong_t)zp->z_id,
1815 				    (u_longlong_t)offset);
1816 				error = SET_ERROR(ENXIO);
1817 				goto update;
1818 			}
1819 
1820 			objnum = ZFS_DIRENT_OBJ(zap->za_first_integer);
1821 			/*
1822 			 * MacOS X can extract the object type here such as:
1823 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1824 			 */
1825 			type = ZFS_DIRENT_TYPE(zap->za_first_integer);
1826 		}
1827 
1828 		reclen = DIRENT64_RECLEN(strlen(zap->za_name));
1829 
1830 		/*
1831 		 * Will this entry fit in the buffer?
1832 		 */
1833 		if (outcount + reclen > bufsize) {
1834 			/*
1835 			 * Did we manage to fit anything in the buffer?
1836 			 */
1837 			if (!outcount) {
1838 				error = SET_ERROR(EINVAL);
1839 				goto update;
1840 			}
1841 			break;
1842 		}
1843 		/*
1844 		 * Add normal entry:
1845 		 */
1846 		odp->d_ino = objnum;
1847 		odp->d_reclen = reclen;
1848 		odp->d_namlen = strlen(zap->za_name);
1849 		/* NOTE: d_off is the offset for the *next* entry. */
1850 		next = &odp->d_off;
1851 		strlcpy(odp->d_name, zap->za_name, odp->d_namlen + 1);
1852 		odp->d_type = type;
1853 		dirent_terminate(odp);
1854 		odp = (dirent64_t *)((intptr_t)odp + reclen);
1855 
1856 		outcount += reclen;
1857 
1858 		ASSERT3S(outcount, <=, bufsize);
1859 
1860 		if (prefetch)
1861 			dmu_prefetch_dnode(os, objnum, ZIO_PRIORITY_SYNC_READ);
1862 
1863 		/*
1864 		 * Move to the next entry, fill in the previous offset.
1865 		 */
1866 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
1867 			zap_cursor_advance(&zc);
1868 			offset = zap_cursor_serialize(&zc);
1869 		} else {
1870 			offset += 1;
1871 		}
1872 
1873 		/* Fill the offset right after advancing the cursor. */
1874 		if (next != NULL)
1875 			*next = offset;
1876 		if (cooks != NULL) {
1877 			*cooks++ = offset;
1878 			ncooks--;
1879 			KASSERT(ncooks >= 0, ("ncookies=%d", ncooks));
1880 		}
1881 	}
1882 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
1883 
1884 	/* Subtract unused cookies */
1885 	if (ncookies != NULL)
1886 		*ncookies -= ncooks;
1887 
1888 	if (zfs_uio_segflg(uio) == UIO_SYSSPACE && zfs_uio_iovcnt(uio) == 1) {
1889 		iovp->iov_base += outcount;
1890 		iovp->iov_len -= outcount;
1891 		zfs_uio_resid(uio) -= outcount;
1892 	} else if ((error =
1893 	    zfs_uiomove(outbuf, (long)outcount, UIO_READ, uio))) {
1894 		/*
1895 		 * Reset the pointer.
1896 		 */
1897 		offset = zfs_uio_offset(uio);
1898 	}
1899 
1900 update:
1901 	zap_cursor_fini(&zc);
1902 	zap_attribute_free(zap);
1903 	if (zfs_uio_segflg(uio) != UIO_SYSSPACE || zfs_uio_iovcnt(uio) != 1)
1904 		kmem_free(outbuf, bufsize);
1905 
1906 	if (error == ENOENT)
1907 		error = 0;
1908 
1909 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
1910 
1911 	zfs_uio_setoffset(uio, offset);
1912 	zfs_exit(zfsvfs, FTAG);
1913 	if (error != 0 && cookies != NULL) {
1914 		free(*cookies, M_TEMP);
1915 		*cookies = NULL;
1916 		*ncookies = 0;
1917 	}
1918 	return (error);
1919 }
1920 
1921 /*
1922  * Get the requested file attributes and place them in the provided
1923  * vattr structure.
1924  *
1925  *	IN:	vp	- vnode of file.
1926  *		vap	- va_mask identifies requested attributes.
1927  *			  If AT_XVATTR set, then optional attrs are requested
1928  *		flags	- ATTR_NOACLCHECK (CIFS server context)
1929  *		cr	- credentials of caller.
1930  *
1931  *	OUT:	vap	- attribute values.
1932  *
1933  *	RETURN:	0 (always succeeds).
1934  */
1935 static int
zfs_getattr(vnode_t * vp,vattr_t * vap,int flags,cred_t * cr)1936 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr)
1937 {
1938 	znode_t *zp = VTOZ(vp);
1939 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1940 	int	error = 0;
1941 	uint32_t blksize;
1942 	u_longlong_t nblocks;
1943 	uint64_t mtime[2], ctime[2], crtime[2], rdev;
1944 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
1945 	xoptattr_t *xoap = NULL;
1946 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
1947 	sa_bulk_attr_t bulk[4];
1948 	int count = 0;
1949 
1950 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1951 		return (error);
1952 
1953 	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
1954 
1955 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
1956 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
1957 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16);
1958 	if (vp->v_type == VBLK || vp->v_type == VCHR)
1959 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_RDEV(zfsvfs), NULL,
1960 		    &rdev, 8);
1961 
1962 	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
1963 		zfs_exit(zfsvfs, FTAG);
1964 		return (error);
1965 	}
1966 
1967 	/*
1968 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
1969 	 * Also, if we are the owner don't bother, since owner should
1970 	 * always be allowed to read basic attributes of file.
1971 	 */
1972 	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
1973 	    (vap->va_uid != crgetuid(cr))) {
1974 		if ((error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
1975 		    skipaclchk, cr))) {
1976 			zfs_exit(zfsvfs, FTAG);
1977 			return (error);
1978 		}
1979 	}
1980 
1981 	/*
1982 	 * Return all attributes.  It's cheaper to provide the answer
1983 	 * than to determine whether we were asked the question.
1984 	 */
1985 
1986 	vap->va_type = IFTOVT(zp->z_mode);
1987 	vap->va_mode = zp->z_mode & ~S_IFMT;
1988 	vn_fsid(vp, vap);
1989 	vap->va_nodeid = zp->z_id;
1990 	vap->va_nlink = zp->z_links;
1991 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp) &&
1992 	    zp->z_links < ZFS_LINK_MAX)
1993 		vap->va_nlink++;
1994 	vap->va_size = zp->z_size;
1995 	if (vp->v_type == VBLK || vp->v_type == VCHR)
1996 		vap->va_rdev = zfs_cmpldev(rdev);
1997 	else
1998 		vap->va_rdev = NODEV;
1999 	vap->va_gen = zp->z_gen;
2000 	vap->va_flags = 0;	/* FreeBSD: Reset chflags(2) flags. */
2001 	vap->va_filerev = atomic_load_64(&zp->z_seq);
2002 
2003 	/*
2004 	 * Add in any requested optional attributes and the create time.
2005 	 * Also set the corresponding bits in the returned attribute bitmap.
2006 	 */
2007 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2008 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2009 			xoap->xoa_archive =
2010 			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2011 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2012 		}
2013 
2014 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2015 			xoap->xoa_readonly =
2016 			    ((zp->z_pflags & ZFS_READONLY) != 0);
2017 			XVA_SET_RTN(xvap, XAT_READONLY);
2018 		}
2019 
2020 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2021 			xoap->xoa_system =
2022 			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2023 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2024 		}
2025 
2026 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2027 			xoap->xoa_hidden =
2028 			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2029 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2030 		}
2031 
2032 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2033 			xoap->xoa_nounlink =
2034 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2035 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2036 		}
2037 
2038 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2039 			xoap->xoa_immutable =
2040 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2041 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2042 		}
2043 
2044 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2045 			xoap->xoa_appendonly =
2046 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2047 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2048 		}
2049 
2050 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2051 			xoap->xoa_nodump =
2052 			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2053 			XVA_SET_RTN(xvap, XAT_NODUMP);
2054 		}
2055 
2056 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2057 			xoap->xoa_opaque =
2058 			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2059 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2060 		}
2061 
2062 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2063 			xoap->xoa_av_quarantined =
2064 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2065 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2066 		}
2067 
2068 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2069 			xoap->xoa_av_modified =
2070 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2071 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2072 		}
2073 
2074 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2075 		    vp->v_type == VREG) {
2076 			zfs_sa_get_scanstamp(zp, xvap);
2077 		}
2078 
2079 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2080 			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2081 			XVA_SET_RTN(xvap, XAT_REPARSE);
2082 		}
2083 		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2084 			xoap->xoa_generation = zp->z_gen;
2085 			XVA_SET_RTN(xvap, XAT_GEN);
2086 		}
2087 
2088 		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2089 			xoap->xoa_offline =
2090 			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2091 			XVA_SET_RTN(xvap, XAT_OFFLINE);
2092 		}
2093 
2094 		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2095 			xoap->xoa_sparse =
2096 			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2097 			XVA_SET_RTN(xvap, XAT_SPARSE);
2098 		}
2099 
2100 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2101 			xoap->xoa_projinherit =
2102 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0);
2103 			XVA_SET_RTN(xvap, XAT_PROJINHERIT);
2104 		}
2105 
2106 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2107 			xoap->xoa_projid = zp->z_projid;
2108 			XVA_SET_RTN(xvap, XAT_PROJID);
2109 		}
2110 	}
2111 
2112 	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2113 	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2114 	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2115 	ZFS_TIME_DECODE(&vap->va_birthtime, crtime);
2116 
2117 
2118 	sa_object_size(zp->z_sa_hdl, &blksize, &nblocks);
2119 	vap->va_blksize = blksize;
2120 	vap->va_bytes = nblocks << 9;	/* nblocks * 512 */
2121 
2122 	if (zp->z_blksz == 0) {
2123 		/*
2124 		 * Block size hasn't been set; suggest maximal I/O transfers.
2125 		 */
2126 		vap->va_blksize = zfsvfs->z_max_blksz;
2127 	}
2128 
2129 	zfs_exit(zfsvfs, FTAG);
2130 	return (0);
2131 }
2132 
2133 /*
2134  * For the operation of changing file's user/group/project, we need to
2135  * handle not only the main object that is assigned to the file directly,
2136  * but also the ones that are used by the file via hidden xattr directory.
2137  *
2138  * Because the xattr directory may contains many EA entries, as to it may
2139  * be impossible to change all of them via the transaction of changing the
2140  * main object's user/group/project attributes. Then we have to change them
2141  * via other multiple independent transactions one by one. It may be not good
2142  * solution, but we have no better idea yet.
2143  */
2144 static int
zfs_setattr_dir(znode_t * dzp)2145 zfs_setattr_dir(znode_t *dzp)
2146 {
2147 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2148 	objset_t	*os = zfsvfs->z_os;
2149 	zap_cursor_t	zc;
2150 	zap_attribute_t	*zap;
2151 	znode_t		*zp = NULL;
2152 	dmu_tx_t	*tx = NULL;
2153 	uint64_t	uid, gid;
2154 	sa_bulk_attr_t	bulk[4];
2155 	int		count;
2156 	int		err;
2157 
2158 	zap = zap_attribute_alloc();
2159 	zap_cursor_init(&zc, os, dzp->z_id);
2160 	while ((err = zap_cursor_retrieve(&zc, zap)) == 0) {
2161 		count = 0;
2162 		if (zap->za_integer_length != 8 || zap->za_num_integers != 1) {
2163 			err = ENXIO;
2164 			break;
2165 		}
2166 
2167 		err = zfs_dirent_lookup(dzp, zap->za_name, &zp, ZEXISTS);
2168 		if (err == ENOENT)
2169 			goto next;
2170 		if (err)
2171 			break;
2172 
2173 		if (zp->z_uid == dzp->z_uid &&
2174 		    zp->z_gid == dzp->z_gid &&
2175 		    zp->z_projid == dzp->z_projid)
2176 			goto next;
2177 
2178 		tx = dmu_tx_create(os);
2179 		if (!(zp->z_pflags & ZFS_PROJID))
2180 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2181 		else
2182 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2183 
2184 		err = dmu_tx_assign(tx, DMU_TX_WAIT);
2185 		if (err)
2186 			break;
2187 
2188 		vn_seqc_write_begin(ZTOV(zp));
2189 		mutex_enter(&dzp->z_lock);
2190 
2191 		if (zp->z_uid != dzp->z_uid) {
2192 			uid = dzp->z_uid;
2193 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2194 			    &uid, sizeof (uid));
2195 			zp->z_uid = uid;
2196 		}
2197 
2198 		if (zp->z_gid != dzp->z_gid) {
2199 			gid = dzp->z_gid;
2200 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
2201 			    &gid, sizeof (gid));
2202 			zp->z_gid = gid;
2203 		}
2204 
2205 		uint64_t projid = dzp->z_projid;
2206 		if (zp->z_projid != projid) {
2207 			if (!(zp->z_pflags & ZFS_PROJID)) {
2208 				err = sa_add_projid(zp->z_sa_hdl, tx, projid);
2209 				if (unlikely(err == EEXIST)) {
2210 					err = 0;
2211 				} else if (err != 0) {
2212 					goto sa_add_projid_err;
2213 				} else {
2214 					projid = ZFS_INVALID_PROJID;
2215 				}
2216 			}
2217 
2218 			if (projid != ZFS_INVALID_PROJID) {
2219 				zp->z_projid = projid;
2220 				SA_ADD_BULK_ATTR(bulk, count,
2221 				    SA_ZPL_PROJID(zfsvfs), NULL, &zp->z_projid,
2222 				    sizeof (zp->z_projid));
2223 			}
2224 		}
2225 
2226 sa_add_projid_err:
2227 		mutex_exit(&dzp->z_lock);
2228 
2229 		if (likely(count > 0)) {
2230 			err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2231 			dmu_tx_commit(tx);
2232 		} else if (projid == ZFS_INVALID_PROJID) {
2233 			dmu_tx_commit(tx);
2234 		} else {
2235 			dmu_tx_abort(tx);
2236 		}
2237 		tx = NULL;
2238 		vn_seqc_write_end(ZTOV(zp));
2239 		if (err != 0 && err != ENOENT)
2240 			break;
2241 
2242 next:
2243 		if (zp) {
2244 			zrele(zp);
2245 			zp = NULL;
2246 		}
2247 		zap_cursor_advance(&zc);
2248 	}
2249 
2250 	if (tx)
2251 		dmu_tx_abort(tx);
2252 	if (zp) {
2253 		zrele(zp);
2254 	}
2255 	zap_cursor_fini(&zc);
2256 	zap_attribute_free(zap);
2257 
2258 	return (err == ENOENT ? 0 : err);
2259 }
2260 
2261 /*
2262  * Set the file attributes to the values contained in the
2263  * vattr structure.
2264  *
2265  *	IN:	zp	- znode of file to be modified.
2266  *		vap	- new attribute values.
2267  *			  If AT_XVATTR set, then optional attrs are being set
2268  *		flags	- ATTR_UTIME set if non-default time values provided.
2269  *			- ATTR_NOACLCHECK (CIFS context only).
2270  *		cr	- credentials of caller.
2271  *
2272  *	RETURN:	0 on success, error code on failure.
2273  *
2274  * Timestamps:
2275  *	vp - ctime updated, mtime updated if size changed.
2276  */
2277 int
zfs_setattr(znode_t * zp,vattr_t * vap,int flags,cred_t * cr)2278 zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr)
2279 {
2280 	vnode_t		*vp = ZTOV(zp);
2281 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2282 	objset_t	*os;
2283 	zilog_t		*zilog;
2284 	dmu_tx_t	*tx;
2285 	vattr_t		oldva;
2286 	xvattr_t	tmpxvattr;
2287 	uint_t		mask = vap->va_mask;
2288 	uint_t		saved_mask = 0;
2289 	uint64_t	saved_mode;
2290 	int		trim_mask = 0;
2291 	uint64_t	new_mode;
2292 	uint64_t	new_uid, new_gid;
2293 	uint64_t	xattr_obj;
2294 	uint64_t	mtime[2], ctime[2];
2295 	uint64_t	projid = ZFS_INVALID_PROJID;
2296 	znode_t		*attrzp;
2297 	int		need_policy = FALSE;
2298 	int		err, err2;
2299 	zfs_fuid_info_t *fuidp = NULL;
2300 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2301 	xoptattr_t	*xoap;
2302 	zfs_acl_t	*aclp;
2303 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2304 	boolean_t	fuid_dirtied = B_FALSE;
2305 	boolean_t	handle_eadir = B_FALSE;
2306 	sa_bulk_attr_t	bulk[9], xattr_bulk[6];
2307 	int		count = 0, xattr_count = 0;
2308 
2309 	if (mask == 0)
2310 		return (0);
2311 
2312 	if (mask & AT_NOSET)
2313 		return (SET_ERROR(EINVAL));
2314 
2315 	if ((err = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
2316 		return (err);
2317 
2318 	os = zfsvfs->z_os;
2319 	zilog = zfsvfs->z_log;
2320 
2321 	/*
2322 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
2323 	 * that file system is at proper version level
2324 	 */
2325 
2326 	if (zfsvfs->z_use_fuids == B_FALSE &&
2327 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2328 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2329 	    (mask & AT_XVATTR))) {
2330 		zfs_exit(zfsvfs, FTAG);
2331 		return (SET_ERROR(EINVAL));
2332 	}
2333 
2334 	if (mask & AT_SIZE && vp->v_type == VDIR) {
2335 		zfs_exit(zfsvfs, FTAG);
2336 		return (SET_ERROR(EISDIR));
2337 	}
2338 
2339 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2340 		zfs_exit(zfsvfs, FTAG);
2341 		return (SET_ERROR(EINVAL));
2342 	}
2343 
2344 	/*
2345 	 * If this is an xvattr_t, then get a pointer to the structure of
2346 	 * optional attributes.  If this is NULL, then we have a vattr_t.
2347 	 */
2348 	xoap = xva_getxoptattr(xvap);
2349 
2350 	xva_init(&tmpxvattr);
2351 
2352 	/*
2353 	 * Immutable files can only alter immutable bit and atime
2354 	 */
2355 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2356 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2357 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2358 		zfs_exit(zfsvfs, FTAG);
2359 		return (SET_ERROR(EPERM));
2360 	}
2361 
2362 	/*
2363 	 * Note: ZFS_READONLY is handled in zfs_zaccess_common.
2364 	 */
2365 
2366 	/*
2367 	 * Verify timestamps doesn't overflow 32 bits.
2368 	 * ZFS can handle large timestamps, but 32bit syscalls can't
2369 	 * handle times greater than 2039.  This check should be removed
2370 	 * once large timestamps are fully supported.
2371 	 */
2372 	if (mask & (AT_ATIME | AT_MTIME)) {
2373 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2374 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2375 			zfs_exit(zfsvfs, FTAG);
2376 			return (SET_ERROR(EOVERFLOW));
2377 		}
2378 	}
2379 	if (xoap != NULL && (mask & AT_XVATTR)) {
2380 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME) &&
2381 		    TIMESPEC_OVERFLOW(&vap->va_birthtime)) {
2382 			zfs_exit(zfsvfs, FTAG);
2383 			return (SET_ERROR(EOVERFLOW));
2384 		}
2385 
2386 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2387 			if (!dmu_objset_projectquota_enabled(os) ||
2388 			    (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode))) {
2389 				zfs_exit(zfsvfs, FTAG);
2390 				return (SET_ERROR(EOPNOTSUPP));
2391 			}
2392 
2393 			projid = xoap->xoa_projid;
2394 			if (unlikely(projid == ZFS_INVALID_PROJID)) {
2395 				zfs_exit(zfsvfs, FTAG);
2396 				return (SET_ERROR(EINVAL));
2397 			}
2398 
2399 			if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID)
2400 				projid = ZFS_INVALID_PROJID;
2401 			else
2402 				need_policy = TRUE;
2403 		}
2404 
2405 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) &&
2406 		    (xoap->xoa_projinherit !=
2407 		    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) &&
2408 		    (!dmu_objset_projectquota_enabled(os) ||
2409 		    (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode)))) {
2410 			zfs_exit(zfsvfs, FTAG);
2411 			return (SET_ERROR(EOPNOTSUPP));
2412 		}
2413 	}
2414 
2415 	attrzp = NULL;
2416 	aclp = NULL;
2417 
2418 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2419 		zfs_exit(zfsvfs, FTAG);
2420 		return (SET_ERROR(EROFS));
2421 	}
2422 
2423 	/*
2424 	 * First validate permissions
2425 	 */
2426 
2427 	if (mask & AT_SIZE) {
2428 		/*
2429 		 * XXX - Note, we are not providing any open
2430 		 * mode flags here (like FNDELAY), so we may
2431 		 * block if there are locks present... this
2432 		 * should be addressed in openat().
2433 		 */
2434 		/* XXX - would it be OK to generate a log record here? */
2435 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2436 		if (err) {
2437 			zfs_exit(zfsvfs, FTAG);
2438 			return (err);
2439 		}
2440 	}
2441 
2442 	if (mask & (AT_ATIME|AT_MTIME) ||
2443 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2444 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2445 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2446 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2447 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2448 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2449 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2450 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2451 		    skipaclchk, cr);
2452 	}
2453 
2454 	if (mask & (AT_UID|AT_GID)) {
2455 		int	idmask = (mask & (AT_UID|AT_GID));
2456 		int	take_owner;
2457 		int	take_group;
2458 
2459 		/*
2460 		 * NOTE: even if a new mode is being set,
2461 		 * we may clear S_ISUID/S_ISGID bits.
2462 		 */
2463 
2464 		if (!(mask & AT_MODE))
2465 			vap->va_mode = zp->z_mode;
2466 
2467 		/*
2468 		 * Take ownership or chgrp to group we are a member of
2469 		 */
2470 
2471 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2472 		take_group = (mask & AT_GID) &&
2473 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
2474 
2475 		/*
2476 		 * If both AT_UID and AT_GID are set then take_owner and
2477 		 * take_group must both be set in order to allow taking
2478 		 * ownership.
2479 		 *
2480 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2481 		 *
2482 		 */
2483 
2484 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2485 		    ((idmask == AT_UID) && take_owner) ||
2486 		    ((idmask == AT_GID) && take_group)) {
2487 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2488 			    skipaclchk, cr) == 0) {
2489 				/*
2490 				 * Remove setuid/setgid for non-privileged users
2491 				 */
2492 				secpolicy_setid_clear(vap, vp, cr);
2493 				trim_mask = (mask & (AT_UID|AT_GID));
2494 			} else {
2495 				need_policy =  TRUE;
2496 			}
2497 		} else {
2498 			need_policy =  TRUE;
2499 		}
2500 	}
2501 
2502 	oldva.va_mode = zp->z_mode;
2503 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2504 	if (mask & AT_XVATTR) {
2505 		/*
2506 		 * Update xvattr mask to include only those attributes
2507 		 * that are actually changing.
2508 		 *
2509 		 * the bits will be restored prior to actually setting
2510 		 * the attributes so the caller thinks they were set.
2511 		 */
2512 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2513 			if (xoap->xoa_appendonly !=
2514 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2515 				need_policy = TRUE;
2516 			} else {
2517 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2518 				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2519 			}
2520 		}
2521 
2522 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2523 			if (xoap->xoa_projinherit !=
2524 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) {
2525 				need_policy = TRUE;
2526 			} else {
2527 				XVA_CLR_REQ(xvap, XAT_PROJINHERIT);
2528 				XVA_SET_REQ(&tmpxvattr, XAT_PROJINHERIT);
2529 			}
2530 		}
2531 
2532 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2533 			if (xoap->xoa_nounlink !=
2534 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2535 				need_policy = TRUE;
2536 			} else {
2537 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2538 				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2539 			}
2540 		}
2541 
2542 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2543 			if (xoap->xoa_immutable !=
2544 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2545 				need_policy = TRUE;
2546 			} else {
2547 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2548 				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2549 			}
2550 		}
2551 
2552 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2553 			if (xoap->xoa_nodump !=
2554 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2555 				need_policy = TRUE;
2556 			} else {
2557 				XVA_CLR_REQ(xvap, XAT_NODUMP);
2558 				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
2559 			}
2560 		}
2561 
2562 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2563 			if (xoap->xoa_av_modified !=
2564 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2565 				need_policy = TRUE;
2566 			} else {
2567 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2568 				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
2569 			}
2570 		}
2571 
2572 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2573 			if ((vp->v_type != VREG &&
2574 			    xoap->xoa_av_quarantined) ||
2575 			    xoap->xoa_av_quarantined !=
2576 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2577 				need_policy = TRUE;
2578 			} else {
2579 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2580 				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
2581 			}
2582 		}
2583 
2584 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2585 			zfs_exit(zfsvfs, FTAG);
2586 			return (SET_ERROR(EPERM));
2587 		}
2588 
2589 		if (need_policy == FALSE &&
2590 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2591 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2592 			need_policy = TRUE;
2593 		}
2594 	}
2595 
2596 	if (mask & AT_MODE) {
2597 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
2598 			err = secpolicy_setid_setsticky_clear(vp, vap,
2599 			    &oldva, cr);
2600 			if (err) {
2601 				zfs_exit(zfsvfs, FTAG);
2602 				return (err);
2603 			}
2604 			trim_mask |= AT_MODE;
2605 		} else {
2606 			need_policy = TRUE;
2607 		}
2608 	}
2609 
2610 	if (need_policy) {
2611 		/*
2612 		 * If trim_mask is set then take ownership
2613 		 * has been granted or write_acl is present and user
2614 		 * has the ability to modify mode.  In that case remove
2615 		 * UID|GID and or MODE from mask so that
2616 		 * secpolicy_vnode_setattr() doesn't revoke it.
2617 		 */
2618 
2619 		if (trim_mask) {
2620 			saved_mask = vap->va_mask;
2621 			vap->va_mask &= ~trim_mask;
2622 			if (trim_mask & AT_MODE) {
2623 				/*
2624 				 * Save the mode, as secpolicy_vnode_setattr()
2625 				 * will overwrite it with ova.va_mode.
2626 				 */
2627 				saved_mode = vap->va_mode;
2628 			}
2629 		}
2630 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2631 		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
2632 		if (err) {
2633 			zfs_exit(zfsvfs, FTAG);
2634 			return (err);
2635 		}
2636 
2637 		if (trim_mask) {
2638 			vap->va_mask |= saved_mask;
2639 			if (trim_mask & AT_MODE) {
2640 				/*
2641 				 * Recover the mode after
2642 				 * secpolicy_vnode_setattr().
2643 				 */
2644 				vap->va_mode = saved_mode;
2645 			}
2646 		}
2647 	}
2648 
2649 	/*
2650 	 * secpolicy_vnode_setattr, or take ownership may have
2651 	 * changed va_mask
2652 	 */
2653 	mask = vap->va_mask;
2654 
2655 	if ((mask & (AT_UID | AT_GID)) || projid != ZFS_INVALID_PROJID) {
2656 		handle_eadir = B_TRUE;
2657 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
2658 		    &xattr_obj, sizeof (xattr_obj));
2659 
2660 		if (err == 0 && xattr_obj) {
2661 			err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
2662 			if (err == 0) {
2663 				err = vn_lock(ZTOV(attrzp), LK_EXCLUSIVE);
2664 				if (err != 0)
2665 					vrele(ZTOV(attrzp));
2666 			}
2667 			if (err)
2668 				goto out2;
2669 		}
2670 		if (mask & AT_UID) {
2671 			new_uid = zfs_fuid_create(zfsvfs,
2672 			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
2673 			if (new_uid != zp->z_uid &&
2674 			    zfs_id_overquota(zfsvfs, DMU_USERUSED_OBJECT,
2675 			    new_uid)) {
2676 				if (attrzp)
2677 					vput(ZTOV(attrzp));
2678 				err = SET_ERROR(EDQUOT);
2679 				goto out2;
2680 			}
2681 		}
2682 
2683 		if (mask & AT_GID) {
2684 			new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
2685 			    cr, ZFS_GROUP, &fuidp);
2686 			if (new_gid != zp->z_gid &&
2687 			    zfs_id_overquota(zfsvfs, DMU_GROUPUSED_OBJECT,
2688 			    new_gid)) {
2689 				if (attrzp)
2690 					vput(ZTOV(attrzp));
2691 				err = SET_ERROR(EDQUOT);
2692 				goto out2;
2693 			}
2694 		}
2695 
2696 		if (projid != ZFS_INVALID_PROJID &&
2697 		    zfs_id_overquota(zfsvfs, DMU_PROJECTUSED_OBJECT, projid)) {
2698 			if (attrzp)
2699 				vput(ZTOV(attrzp));
2700 			err = SET_ERROR(EDQUOT);
2701 			goto out2;
2702 		}
2703 	}
2704 	tx = dmu_tx_create(os);
2705 
2706 	if (mask & AT_MODE) {
2707 		uint64_t pmode = zp->z_mode;
2708 		uint64_t acl_obj;
2709 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2710 
2711 		if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
2712 		    !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
2713 			err = SET_ERROR(EPERM);
2714 			goto out;
2715 		}
2716 
2717 		if ((err = zfs_acl_chmod_setattr(zp, &aclp, new_mode)))
2718 			goto out;
2719 
2720 		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
2721 			/*
2722 			 * Are we upgrading ACL from old V0 format
2723 			 * to V1 format?
2724 			 */
2725 			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
2726 			    zfs_znode_acl_version(zp) ==
2727 			    ZFS_ACL_VERSION_INITIAL) {
2728 				dmu_tx_hold_free(tx, acl_obj, 0,
2729 				    DMU_OBJECT_END);
2730 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2731 				    0, aclp->z_acl_bytes);
2732 			} else {
2733 				dmu_tx_hold_write(tx, acl_obj, 0,
2734 				    aclp->z_acl_bytes);
2735 			}
2736 		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2737 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2738 			    0, aclp->z_acl_bytes);
2739 		}
2740 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2741 	} else {
2742 		if (((mask & AT_XVATTR) &&
2743 		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) ||
2744 		    (projid != ZFS_INVALID_PROJID &&
2745 		    !(zp->z_pflags & ZFS_PROJID)) ||
2746 		    !zp->z_has_seq)
2747 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2748 		else
2749 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2750 	}
2751 
2752 	if (attrzp) {
2753 		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(attrzp));
2754 	}
2755 
2756 	fuid_dirtied = zfsvfs->z_fuid_dirty;
2757 	if (fuid_dirtied)
2758 		zfs_fuid_txhold(zfsvfs, tx);
2759 
2760 	zfs_sa_upgrade_txholds(tx, zp);
2761 
2762 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
2763 	if (err)
2764 		goto out;
2765 
2766 	count = 0;
2767 	/*
2768 	 * Set each attribute requested.
2769 	 * We group settings according to the locks they need to acquire.
2770 	 *
2771 	 * Note: you cannot set ctime directly, although it will be
2772 	 * updated as a side-effect of calling this function.
2773 	 */
2774 
2775 	if (projid != ZFS_INVALID_PROJID && !(zp->z_pflags & ZFS_PROJID)) {
2776 		/*
2777 		 * For the existed object that is upgraded from old system,
2778 		 * its on-disk layout has no slot for the project ID attribute.
2779 		 * But quota accounting logic needs to access related slots by
2780 		 * offset directly. So we need to adjust old objects' layout
2781 		 * to make the project ID to some unified and fixed offset.
2782 		 */
2783 		if (attrzp)
2784 			err = sa_add_projid(attrzp->z_sa_hdl, tx, projid);
2785 		if (err == 0)
2786 			err = sa_add_projid(zp->z_sa_hdl, tx, projid);
2787 
2788 		if (unlikely(err == EEXIST))
2789 			err = 0;
2790 		else if (err != 0)
2791 			goto out;
2792 		else
2793 			projid = ZFS_INVALID_PROJID;
2794 	}
2795 
2796 	if (mask & (AT_UID|AT_GID|AT_MODE))
2797 		mutex_enter(&zp->z_acl_lock);
2798 
2799 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
2800 	    &zp->z_pflags, sizeof (zp->z_pflags));
2801 
2802 	if (attrzp) {
2803 		if (mask & (AT_UID|AT_GID|AT_MODE))
2804 			mutex_enter(&attrzp->z_acl_lock);
2805 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2806 		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
2807 		    sizeof (attrzp->z_pflags));
2808 		if (projid != ZFS_INVALID_PROJID) {
2809 			attrzp->z_projid = projid;
2810 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2811 			    SA_ZPL_PROJID(zfsvfs), NULL, &attrzp->z_projid,
2812 			    sizeof (attrzp->z_projid));
2813 		}
2814 	}
2815 
2816 	if (mask & (AT_UID|AT_GID)) {
2817 
2818 		if (mask & AT_UID) {
2819 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2820 			    &new_uid, sizeof (new_uid));
2821 			zp->z_uid = new_uid;
2822 			if (attrzp) {
2823 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2824 				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
2825 				    sizeof (new_uid));
2826 				attrzp->z_uid = new_uid;
2827 			}
2828 		}
2829 
2830 		if (mask & AT_GID) {
2831 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
2832 			    NULL, &new_gid, sizeof (new_gid));
2833 			zp->z_gid = new_gid;
2834 			if (attrzp) {
2835 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2836 				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
2837 				    sizeof (new_gid));
2838 				attrzp->z_gid = new_gid;
2839 			}
2840 		}
2841 		if (!(mask & AT_MODE)) {
2842 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
2843 			    NULL, &new_mode, sizeof (new_mode));
2844 			new_mode = zp->z_mode;
2845 		}
2846 		err = zfs_acl_chown_setattr(zp);
2847 		ASSERT0(err);
2848 		if (attrzp) {
2849 			vn_seqc_write_begin(ZTOV(attrzp));
2850 			err = zfs_acl_chown_setattr(attrzp);
2851 			vn_seqc_write_end(ZTOV(attrzp));
2852 			ASSERT0(err);
2853 		}
2854 	}
2855 
2856 	if (mask & AT_MODE) {
2857 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
2858 		    &new_mode, sizeof (new_mode));
2859 		zp->z_mode = new_mode;
2860 		ASSERT3P(aclp, !=, NULL);
2861 		err = zfs_aclset_common(zp, aclp, cr, tx);
2862 		ASSERT0(err);
2863 		if (zp->z_acl_cached)
2864 			zfs_acl_free(zp->z_acl_cached);
2865 		zp->z_acl_cached = aclp;
2866 		aclp = NULL;
2867 	}
2868 
2869 
2870 	if (mask & AT_ATIME) {
2871 		ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
2872 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
2873 		    &zp->z_atime, sizeof (zp->z_atime));
2874 	}
2875 
2876 	if (mask & AT_MTIME) {
2877 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
2878 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
2879 		    mtime, sizeof (mtime));
2880 	}
2881 
2882 	if (projid != ZFS_INVALID_PROJID) {
2883 		zp->z_projid = projid;
2884 		SA_ADD_BULK_ATTR(bulk, count,
2885 		    SA_ZPL_PROJID(zfsvfs), NULL, &zp->z_projid,
2886 		    sizeof (zp->z_projid));
2887 	}
2888 
2889 	/* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
2890 	if (mask & AT_SIZE && !(mask & AT_MTIME)) {
2891 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
2892 		    NULL, mtime, sizeof (mtime));
2893 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
2894 		    &ctime, sizeof (ctime));
2895 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
2896 		ZFS_PERSIST_SEQ(zp, bulk, count);
2897 	} else if (mask != 0) {
2898 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
2899 		    &ctime, sizeof (ctime));
2900 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime);
2901 		ZFS_PERSIST_SEQ(zp, bulk, count);
2902 		if (attrzp) {
2903 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2904 			    SA_ZPL_CTIME(zfsvfs), NULL,
2905 			    &ctime, sizeof (ctime));
2906 			zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
2907 			    mtime, ctime);
2908 			ZFS_PERSIST_SEQ(attrzp, xattr_bulk, xattr_count);
2909 		}
2910 	}
2911 
2912 	/*
2913 	 * Do this after setting timestamps to prevent timestamp
2914 	 * update from toggling bit
2915 	 */
2916 
2917 	if (xoap && (mask & AT_XVATTR)) {
2918 
2919 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME))
2920 			xoap->xoa_createtime = vap->va_birthtime;
2921 		/*
2922 		 * restore trimmed off masks
2923 		 * so that return masks can be set for caller.
2924 		 */
2925 
2926 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
2927 			XVA_SET_REQ(xvap, XAT_APPENDONLY);
2928 		}
2929 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
2930 			XVA_SET_REQ(xvap, XAT_NOUNLINK);
2931 		}
2932 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
2933 			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
2934 		}
2935 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
2936 			XVA_SET_REQ(xvap, XAT_NODUMP);
2937 		}
2938 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
2939 			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
2940 		}
2941 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
2942 			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
2943 		}
2944 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_PROJINHERIT)) {
2945 			XVA_SET_REQ(xvap, XAT_PROJINHERIT);
2946 		}
2947 
2948 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
2949 			ASSERT3S(vp->v_type, ==, VREG);
2950 
2951 		zfs_xvattr_set(zp, xvap, tx);
2952 	}
2953 
2954 	if (fuid_dirtied)
2955 		zfs_fuid_sync(zfsvfs, tx);
2956 
2957 	if (mask != 0)
2958 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
2959 
2960 	if (mask & (AT_UID|AT_GID|AT_MODE))
2961 		mutex_exit(&zp->z_acl_lock);
2962 
2963 	if (attrzp) {
2964 		if (mask & (AT_UID|AT_GID|AT_MODE))
2965 			mutex_exit(&attrzp->z_acl_lock);
2966 	}
2967 out:
2968 	if (err == 0 && attrzp) {
2969 		ASSERT3S(xattr_count, <=, ARRAY_SIZE(xattr_bulk));
2970 		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
2971 		    xattr_count, tx);
2972 		ASSERT0(err2);
2973 	}
2974 
2975 	if (aclp)
2976 		zfs_acl_free(aclp);
2977 
2978 	if (fuidp) {
2979 		zfs_fuid_info_free(fuidp);
2980 		fuidp = NULL;
2981 	}
2982 
2983 	if (err) {
2984 		dmu_tx_abort(tx);
2985 		if (attrzp)
2986 			vput(ZTOV(attrzp));
2987 	} else {
2988 		ASSERT3S(count, <=, ARRAY_SIZE(bulk));
2989 		err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2990 		dmu_tx_commit(tx);
2991 		if (attrzp) {
2992 			if (err2 == 0 && handle_eadir)
2993 				err = zfs_setattr_dir(attrzp);
2994 			vput(ZTOV(attrzp));
2995 		}
2996 	}
2997 
2998 out2:
2999 	if (err == 0 && os->os_sync == ZFS_SYNC_ALWAYS)
3000 		err = zil_commit(zilog, 0);
3001 
3002 	zfs_exit(zfsvfs, FTAG);
3003 	return (err);
3004 }
3005 
3006 /*
3007  * Look up the directory entries corresponding to the source and target
3008  * directory/name pairs.
3009  */
3010 static int
zfs_rename_relock_lookup(znode_t * sdzp,const struct componentname * scnp,znode_t ** szpp,znode_t * tdzp,const struct componentname * tcnp,znode_t ** tzpp)3011 zfs_rename_relock_lookup(znode_t *sdzp, const struct componentname *scnp,
3012     znode_t **szpp, znode_t *tdzp, const struct componentname *tcnp,
3013     znode_t **tzpp)
3014 {
3015 	zfsvfs_t *zfsvfs;
3016 	znode_t *szp, *tzp;
3017 	int error;
3018 
3019 	/*
3020 	 * Before using sdzp and tdzp we must ensure that they are live.
3021 	 * As a porting legacy from illumos we have two things to worry
3022 	 * about.  One is typical for FreeBSD and it is that the vnode is
3023 	 * not reclaimed (doomed).  The other is that the znode is live.
3024 	 * The current code can invalidate the znode without acquiring the
3025 	 * corresponding vnode lock if the object represented by the znode
3026 	 * and vnode is no longer valid after a rollback or receive operation.
3027 	 * z_teardown_lock hidden behind zfs_enter and zfs_exit is the lock
3028 	 * that protects the znodes from the invalidation.
3029 	 */
3030 	zfsvfs = sdzp->z_zfsvfs;
3031 	ASSERT3P(zfsvfs, ==, tdzp->z_zfsvfs);
3032 	if ((error = zfs_enter_verify_zp(zfsvfs, sdzp, FTAG)) != 0)
3033 		return (error);
3034 	if ((error = zfs_verify_zp(tdzp)) != 0) {
3035 		zfs_exit(zfsvfs, FTAG);
3036 		return (error);
3037 	}
3038 
3039 	/*
3040 	 * Re-resolve svp to be certain it still exists and fetch the
3041 	 * correct vnode.
3042 	 */
3043 	error = zfs_dirent_lookup(sdzp, scnp->cn_nameptr, &szp, ZEXISTS);
3044 	if (error != 0) {
3045 		/* Source entry invalid or not there. */
3046 		if ((scnp->cn_flags & ISDOTDOT) != 0 ||
3047 		    (scnp->cn_namelen == 1 && scnp->cn_nameptr[0] == '.'))
3048 			error = SET_ERROR(EINVAL);
3049 		goto out;
3050 	}
3051 	*szpp = szp;
3052 
3053 	/*
3054 	 * Re-resolve tvp, if it disappeared we just carry on.
3055 	 */
3056 	error = zfs_dirent_lookup(tdzp, tcnp->cn_nameptr, &tzp, 0);
3057 	if (error != 0) {
3058 		vrele(ZTOV(szp));
3059 		if ((tcnp->cn_flags & ISDOTDOT) != 0)
3060 			error = SET_ERROR(EINVAL);
3061 		goto out;
3062 	}
3063 	*tzpp = tzp;
3064 out:
3065 	zfs_exit(zfsvfs, FTAG);
3066 	return (error);
3067 }
3068 
3069 /*
3070  * We acquire all but fdvp locks using non-blocking acquisitions.  If we
3071  * fail to acquire any lock in the path we will drop all held locks,
3072  * acquire the new lock in a blocking fashion, and then release it and
3073  * restart the rename.  This acquire/release step ensures that we do not
3074  * spin on a lock waiting for release.  On error release all vnode locks
3075  * and decrement references the way tmpfs_rename() would do.
3076  */
3077 static int
zfs_rename_relock(struct vnode * sdvp,struct vnode ** svpp,struct vnode * tdvp,struct vnode ** tvpp,const struct componentname * scnp,const struct componentname * tcnp)3078 zfs_rename_relock(struct vnode *sdvp, struct vnode **svpp,
3079     struct vnode *tdvp, struct vnode **tvpp,
3080     const struct componentname *scnp, const struct componentname *tcnp)
3081 {
3082 	struct vnode	*nvp, *svp, *tvp;
3083 	znode_t		*sdzp, *tdzp, *szp, *tzp;
3084 	int		error;
3085 
3086 	VOP_UNLOCK(tdvp);
3087 	if (*tvpp != NULL && *tvpp != tdvp)
3088 		VOP_UNLOCK(*tvpp);
3089 
3090 relock:
3091 	error = vn_lock(sdvp, LK_EXCLUSIVE);
3092 	if (error)
3093 		goto out;
3094 	error = vn_lock(tdvp, LK_EXCLUSIVE | LK_NOWAIT);
3095 	if (error != 0) {
3096 		VOP_UNLOCK(sdvp);
3097 		if (error != EBUSY)
3098 			goto out;
3099 		error = vn_lock(tdvp, LK_EXCLUSIVE);
3100 		if (error)
3101 			goto out;
3102 		VOP_UNLOCK(tdvp);
3103 		goto relock;
3104 	}
3105 	tdzp = VTOZ(tdvp);
3106 	sdzp = VTOZ(sdvp);
3107 
3108 	error = zfs_rename_relock_lookup(sdzp, scnp, &szp, tdzp, tcnp, &tzp);
3109 	if (error != 0) {
3110 		VOP_UNLOCK(sdvp);
3111 		VOP_UNLOCK(tdvp);
3112 		goto out;
3113 	}
3114 	svp = ZTOV(szp);
3115 	tvp = tzp != NULL ? ZTOV(tzp) : NULL;
3116 
3117 	/*
3118 	 * Now try acquire locks on svp and tvp.
3119 	 */
3120 	nvp = svp;
3121 	error = vn_lock(nvp, LK_EXCLUSIVE | LK_NOWAIT);
3122 	if (error != 0) {
3123 		VOP_UNLOCK(sdvp);
3124 		VOP_UNLOCK(tdvp);
3125 		if (tvp != NULL)
3126 			vrele(tvp);
3127 		if (error != EBUSY) {
3128 			vrele(nvp);
3129 			goto out;
3130 		}
3131 		error = vn_lock(nvp, LK_EXCLUSIVE);
3132 		if (error != 0) {
3133 			vrele(nvp);
3134 			goto out;
3135 		}
3136 		VOP_UNLOCK(nvp);
3137 		/*
3138 		 * Concurrent rename race.
3139 		 * XXX ?
3140 		 */
3141 		if (nvp == tdvp) {
3142 			vrele(nvp);
3143 			error = SET_ERROR(EINVAL);
3144 			goto out;
3145 		}
3146 		vrele(*svpp);
3147 		*svpp = nvp;
3148 		goto relock;
3149 	}
3150 	vrele(*svpp);
3151 	*svpp = nvp;
3152 
3153 	if (*tvpp != NULL)
3154 		vrele(*tvpp);
3155 	*tvpp = NULL;
3156 	if (tvp != NULL) {
3157 		nvp = tvp;
3158 		error = vn_lock(nvp, LK_EXCLUSIVE | LK_NOWAIT);
3159 		if (error != 0) {
3160 			VOP_UNLOCK(sdvp);
3161 			VOP_UNLOCK(tdvp);
3162 			VOP_UNLOCK(*svpp);
3163 			if (error != EBUSY) {
3164 				vrele(nvp);
3165 				goto out;
3166 			}
3167 			error = vn_lock(nvp, LK_EXCLUSIVE);
3168 			if (error != 0) {
3169 				vrele(nvp);
3170 				goto out;
3171 			}
3172 			vput(nvp);
3173 			goto relock;
3174 		}
3175 		*tvpp = nvp;
3176 	}
3177 
3178 	return (0);
3179 
3180 out:
3181 	return (error);
3182 }
3183 
3184 /*
3185  * Note that we must use VRELE_ASYNC in this function as it walks
3186  * up the directory tree and vrele may need to acquire an exclusive
3187  * lock if a last reference to a vnode is dropped.
3188  */
3189 static int
zfs_rename_check(znode_t * szp,znode_t * sdzp,znode_t * tdzp)3190 zfs_rename_check(znode_t *szp, znode_t *sdzp, znode_t *tdzp)
3191 {
3192 	zfsvfs_t	*zfsvfs;
3193 	znode_t		*zp, *zp1;
3194 	uint64_t	parent;
3195 	int		error;
3196 
3197 	zfsvfs = tdzp->z_zfsvfs;
3198 	if (tdzp == szp)
3199 		return (SET_ERROR(EINVAL));
3200 	if (tdzp == sdzp)
3201 		return (0);
3202 	if (tdzp->z_id == zfsvfs->z_root)
3203 		return (0);
3204 	zp = tdzp;
3205 	for (;;) {
3206 		ASSERT(!zp->z_unlinked);
3207 		if ((error = sa_lookup(zp->z_sa_hdl,
3208 		    SA_ZPL_PARENT(zfsvfs), &parent, sizeof (parent))) != 0)
3209 			break;
3210 
3211 		if (parent == szp->z_id) {
3212 			error = SET_ERROR(EINVAL);
3213 			break;
3214 		}
3215 		if (parent == zfsvfs->z_root)
3216 			break;
3217 		if (parent == sdzp->z_id)
3218 			break;
3219 
3220 		error = zfs_zget(zfsvfs, parent, &zp1);
3221 		if (error != 0)
3222 			break;
3223 
3224 		if (zp != tdzp)
3225 			VN_RELE_ASYNC(ZTOV(zp),
3226 			    dsl_pool_zrele_taskq(
3227 			    dmu_objset_pool(zfsvfs->z_os)));
3228 		zp = zp1;
3229 	}
3230 
3231 	if (error == ENOTDIR)
3232 		panic("checkpath: .. not a directory\n");
3233 	if (zp != tdzp)
3234 		VN_RELE_ASYNC(ZTOV(zp),
3235 		    dsl_pool_zrele_taskq(dmu_objset_pool(zfsvfs->z_os)));
3236 	return (error);
3237 }
3238 
3239 static int
3240 zfs_do_rename_impl(vnode_t *sdvp, vnode_t **svpp, struct componentname *scnp,
3241     vnode_t *tdvp, vnode_t **tvpp, struct componentname *tcnp,
3242     cred_t *cr, u_int at_flags);
3243 
3244 /*
3245  * Move an entry from the provided source directory to the target
3246  * directory.  Change the entry name as indicated.
3247  *
3248  *	IN:	sdvp	- Source directory containing the "old entry".
3249  *		scnp	- Old entry name.
3250  *		tdvp	- Target directory to contain the "new entry".
3251  *		tcnp	- New entry name.
3252  *		cr	- credentials of caller.
3253  *		at_flags - AT_RENAME_*
3254  *	INOUT:	svpp	- Source file
3255  *		tvpp	- Target file, may point to NULL initially
3256  *
3257  *	RETURN:	0 on success, error code on failure.
3258  *
3259  * Timestamps:
3260  *	sdvp,tdvp - ctime|mtime updated
3261  */
3262 static int
zfs_do_rename(vnode_t * sdvp,vnode_t ** svpp,struct componentname * scnp,vnode_t * tdvp,vnode_t ** tvpp,struct componentname * tcnp,cred_t * cr,u_int at_flags)3263 zfs_do_rename(vnode_t *sdvp, vnode_t **svpp, struct componentname *scnp,
3264     vnode_t *tdvp, vnode_t **tvpp, struct componentname *tcnp,
3265     cred_t *cr, u_int at_flags)
3266 {
3267 	int	error;
3268 
3269 	ASSERT_VOP_ELOCKED(tdvp, __func__);
3270 	if (*tvpp != NULL)
3271 		ASSERT_VOP_ELOCKED(*tvpp, __func__);
3272 
3273 	/* Reject renames across filesystems. */
3274 	if ((*svpp)->v_mount != tdvp->v_mount ||
3275 	    ((*tvpp) != NULL && (*svpp)->v_mount != (*tvpp)->v_mount)) {
3276 		error = SET_ERROR(EXDEV);
3277 		goto out;
3278 	}
3279 
3280 	if (zfsctl_is_node(tdvp)) {
3281 		error = SET_ERROR(EXDEV);
3282 		goto out;
3283 	}
3284 
3285 	/*
3286 	 * Lock all four vnodes to ensure safety and semantics of renaming.
3287 	 */
3288 	error = zfs_rename_relock(sdvp, svpp, tdvp, tvpp, scnp, tcnp);
3289 	if (error != 0) {
3290 		/* no vnodes are locked in the case of error here */
3291 		return (error);
3292 	}
3293 
3294 	error = zfs_do_rename_impl(sdvp, svpp, scnp, tdvp, tvpp, tcnp, cr,
3295 	    at_flags);
3296 	VOP_UNLOCK(sdvp);
3297 	VOP_UNLOCK(*svpp);
3298 out:
3299 	if (*tvpp != NULL)
3300 		VOP_UNLOCK(*tvpp);
3301 	if (tdvp != *tvpp)
3302 		VOP_UNLOCK(tdvp);
3303 
3304 	return (error);
3305 }
3306 
3307 static int
zfs_do_rename_impl(vnode_t * sdvp,vnode_t ** svpp,struct componentname * scnp,vnode_t * tdvp,vnode_t ** tvpp,struct componentname * tcnp,cred_t * cr,u_int at_flags)3308 zfs_do_rename_impl(vnode_t *sdvp, vnode_t **svpp, struct componentname *scnp,
3309     vnode_t *tdvp, vnode_t **tvpp, struct componentname *tcnp,
3310     cred_t *cr, u_int at_flags)
3311 {
3312 	dmu_tx_t	*tx;
3313 	zfsvfs_t	*zfsvfs;
3314 	zilog_t		*zilog;
3315 	znode_t		*tdzp, *sdzp, *tzp, *szp;
3316 	const char	*snm = scnp->cn_nameptr;
3317 	const char	*tnm = tcnp->cn_nameptr;
3318 	int		error;
3319 
3320 	tdzp = VTOZ(tdvp);
3321 	sdzp = VTOZ(sdvp);
3322 	zfsvfs = tdzp->z_zfsvfs;
3323 
3324 	if ((error = zfs_enter_verify_zp(zfsvfs, tdzp, FTAG)) != 0)
3325 		return (error);
3326 	if ((error = zfs_verify_zp(sdzp)) != 0) {
3327 		zfs_exit(zfsvfs, FTAG);
3328 		return (error);
3329 	}
3330 	zilog = zfsvfs->z_log;
3331 
3332 	if (zfsvfs->z_utf8 && u8_validate(tnm,
3333 	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3334 		error = SET_ERROR(EILSEQ);
3335 		goto out;
3336 	}
3337 
3338 	/* If source and target are the same file, there is nothing to do. */
3339 	if ((*svpp) == (*tvpp)) {
3340 		error = 0;
3341 		goto out;
3342 	}
3343 
3344 	if (((*svpp)->v_type == VDIR && (*svpp)->v_mountedhere != NULL) ||
3345 	    ((*tvpp) != NULL && (*tvpp)->v_type == VDIR &&
3346 	    (*tvpp)->v_mountedhere != NULL)) {
3347 		error = SET_ERROR(EXDEV);
3348 		goto out;
3349 	}
3350 
3351 	szp = VTOZ(*svpp);
3352 	if ((error = zfs_verify_zp(szp)) != 0) {
3353 		zfs_exit(zfsvfs, FTAG);
3354 		return (error);
3355 	}
3356 	tzp = *tvpp == NULL ? NULL : VTOZ(*tvpp);
3357 	if (tzp != NULL) {
3358 		if ((error = zfs_verify_zp(tzp)) != 0) {
3359 			zfs_exit(zfsvfs, FTAG);
3360 			return (error);
3361 		}
3362 	}
3363 
3364 	/*
3365 	 * This is to prevent the creation of links into attribute space
3366 	 * by renaming a linked file into/outof an attribute directory.
3367 	 * See the comment in zfs_link() for why this is considered bad.
3368 	 */
3369 	if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3370 		error = SET_ERROR(EINVAL);
3371 		goto out;
3372 	}
3373 
3374 	/*
3375 	 * If we are using project inheritance, means if the directory has
3376 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
3377 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3378 	 * such case, we only allow renames into our tree when the project
3379 	 * IDs are the same.
3380 	 *
3381 	 * A rename within a single directory leaves the object exactly where
3382 	 * it already is, so it cannot move it between projects and is always
3383 	 * allowed.  Objects created before symlinks and other non-regular
3384 	 * files began inheriting a project ID carry none of their own, and
3385 	 * would otherwise not be renameable within the very directory that
3386 	 * holds them -- which breaks "ln -sfn", implemented as
3387 	 * create-under-a-temporary-name-then-rename.
3388 	 */
3389 	if (sdzp != tdzp && tdzp->z_pflags & ZFS_PROJINHERIT &&
3390 	    tdzp->z_projid != szp->z_projid) {
3391 		error = SET_ERROR(EXDEV);
3392 		goto out;
3393 	}
3394 
3395 	/*
3396 	 * Must have write access at the source to remove the old entry
3397 	 * and write access at the target to create the new entry.
3398 	 * Note that if target and source are the same, this can be
3399 	 * done in a single check.
3400 	 */
3401 	if ((error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr)))
3402 		goto out;
3403 
3404 	if ((*svpp)->v_type == VDIR) {
3405 		/*
3406 		 * Avoid ".", "..", and aliases of "." for obvious reasons.
3407 		 */
3408 		if ((scnp->cn_namelen == 1 && scnp->cn_nameptr[0] == '.') ||
3409 		    sdzp == szp ||
3410 		    (scnp->cn_flags | tcnp->cn_flags) & ISDOTDOT) {
3411 			error = EINVAL;
3412 			goto out;
3413 		}
3414 
3415 		/*
3416 		 * Check to make sure rename is valid.
3417 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3418 		 */
3419 		if ((error = zfs_rename_check(szp, sdzp, tdzp)))
3420 			goto out;
3421 	}
3422 
3423 	/*
3424 	 * Does target exist?
3425 	 */
3426 	if (tzp) {
3427 		if ((at_flags & AT_RENAME_NOREPLACE) != 0) {
3428 			error = SET_ERROR(EEXIST);
3429 			goto out;
3430 		}
3431 
3432 		/*
3433 		 * Source and target must be the same type.
3434 		 */
3435 		if ((*svpp)->v_type == VDIR) {
3436 			if ((*tvpp)->v_type != VDIR) {
3437 				error = SET_ERROR(ENOTDIR);
3438 				goto out;
3439 			} else {
3440 				cache_purge(tdvp);
3441 				if (sdvp != tdvp)
3442 					cache_purge(sdvp);
3443 			}
3444 		} else {
3445 			if ((*tvpp)->v_type == VDIR) {
3446 				error = SET_ERROR(EISDIR);
3447 				goto out;
3448 			}
3449 		}
3450 	}
3451 
3452 	vn_seqc_write_begin(*svpp);
3453 	vn_seqc_write_begin(sdvp);
3454 	if (*tvpp != NULL)
3455 		vn_seqc_write_begin(*tvpp);
3456 	if (tdvp != *tvpp)
3457 		vn_seqc_write_begin(tdvp);
3458 
3459 	vnevent_rename_src(*svpp, sdvp, scnp->cn_nameptr, ct);
3460 	if (tzp)
3461 		vnevent_rename_dest(*tvpp, tdvp, tnm, ct);
3462 
3463 	/*
3464 	 * notify the target directory if it is not the same
3465 	 * as source directory.
3466 	 */
3467 	if (tdvp != sdvp) {
3468 		vnevent_rename_dest_dir(tdvp, ct);
3469 	}
3470 
3471 	tx = dmu_tx_create(zfsvfs->z_os);
3472 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, ZFS_SEQ_MAY_GROW(szp));
3473 	dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(sdzp));
3474 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3475 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3476 	if (sdzp != tdzp) {
3477 		dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(tdzp));
3478 		zfs_sa_upgrade_txholds(tx, tdzp);
3479 	}
3480 	if (tzp) {
3481 		dmu_tx_hold_sa(tx, tzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(tzp));
3482 		zfs_sa_upgrade_txholds(tx, tzp);
3483 	}
3484 
3485 	zfs_sa_upgrade_txholds(tx, szp);
3486 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3487 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
3488 	if (error) {
3489 		dmu_tx_abort(tx);
3490 		goto out_seq;
3491 	}
3492 
3493 	if (tzp)	/* Attempt to remove the existing target */
3494 		error = zfs_link_destroy(tdzp, tnm, tzp, tx, 0, NULL);
3495 
3496 	if (error == 0) {
3497 		error = zfs_link_create(tdzp, tnm, szp, tx, ZRENAMING);
3498 		if (error == 0) {
3499 			szp->z_pflags |= ZFS_AV_MODIFIED;
3500 
3501 			error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3502 			    (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3503 			ASSERT0(error);
3504 
3505 			error = zfs_link_destroy(sdzp, snm, szp, tx, ZRENAMING,
3506 			    NULL);
3507 			if (error == 0) {
3508 				zfs_log_rename(zilog, tx, TX_RENAME, sdzp,
3509 				    snm, tdzp, tnm, szp);
3510 			} else {
3511 				/*
3512 				 * At this point, we have successfully created
3513 				 * the target name, but have failed to remove
3514 				 * the source name.  Since the create was done
3515 				 * with the ZRENAMING flag, there are
3516 				 * complications; for one, the link count is
3517 				 * wrong.  The easiest way to deal with this
3518 				 * is to remove the newly created target, and
3519 				 * return the original error.  This must
3520 				 * succeed; fortunately, it is very unlikely to
3521 				 * fail, since we just created it.
3522 				 */
3523 				VERIFY0(zfs_link_destroy(tdzp, tnm, szp, tx,
3524 				    ZRENAMING, NULL));
3525 			}
3526 		}
3527 		if (error == 0 && zfsvfs->z_use_namecache) {
3528 			cache_vop_rename(sdvp, *svpp, tdvp, *tvpp, scnp, tcnp);
3529 		}
3530 	}
3531 
3532 	dmu_tx_commit(tx);
3533 
3534 out_seq:
3535 	vn_seqc_write_end(*svpp);
3536 	vn_seqc_write_end(sdvp);
3537 	if (*tvpp != NULL)
3538 		vn_seqc_write_end(*tvpp);
3539 	if (tdvp != *tvpp)
3540 		vn_seqc_write_end(tdvp);
3541 
3542 out:
3543 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3544 		error = zil_commit(zilog, 0);
3545 	zfs_exit(zfsvfs, FTAG);
3546 
3547 	return (error);
3548 }
3549 
3550 int
zfs_rename(znode_t * sdzp,const char * sname,znode_t * tdzp,const char * tname,cred_t * cr,int flags,uint64_t rflags,u_int at_flags,vattr_t * wo_vap)3551 zfs_rename(znode_t *sdzp, const char *sname, znode_t *tdzp, const char *tname,
3552     cred_t *cr, int flags, uint64_t rflags, u_int at_flags, vattr_t *wo_vap)
3553 {
3554 	struct componentname scn, tcn;
3555 	vnode_t *sdvp, *tdvp;
3556 	vnode_t *svp, *tvp;
3557 	int error;
3558 	svp = tvp = NULL;
3559 
3560 	if (is_nametoolong(tdzp->z_zfsvfs, tname))
3561 		return (SET_ERROR(ENAMETOOLONG));
3562 
3563 	if (rflags != 0 || wo_vap != NULL)
3564 		return (SET_ERROR(EINVAL));
3565 
3566 	sdvp = ZTOV(sdzp);
3567 	tdvp = ZTOV(tdzp);
3568 	error = zfs_lookup_internal(sdzp, sname, &svp, &scn, DELETE);
3569 	if (sdzp->z_zfsvfs->z_replay == B_FALSE)
3570 		VOP_UNLOCK(sdvp);
3571 	if (error != 0)
3572 		goto fail;
3573 	VOP_UNLOCK(svp);
3574 
3575 	vn_lock(tdvp, LK_EXCLUSIVE | LK_RETRY);
3576 	error = zfs_lookup_internal(tdzp, tname, &tvp, &tcn, RENAME);
3577 	if (error == EJUSTRETURN)
3578 		tvp = NULL;
3579 	else if (error != 0) {
3580 		VOP_UNLOCK(tdvp);
3581 		goto fail;
3582 	}
3583 
3584 	error = zfs_do_rename(sdvp, &svp, &scn, tdvp, &tvp, &tcn, cr,
3585 	    at_flags);
3586 fail:
3587 	if (svp != NULL)
3588 		vrele(svp);
3589 	if (tvp != NULL)
3590 		vrele(tvp);
3591 
3592 	return (error);
3593 }
3594 
3595 /*
3596  * Insert the indicated symbolic reference entry into the directory.
3597  *
3598  *	IN:	dvp	- Directory to contain new symbolic link.
3599  *		link	- Name for new symlink entry.
3600  *		vap	- Attributes of new entry.
3601  *		cr	- credentials of caller.
3602  *		ct	- caller context
3603  *		flags	- case flags
3604  *
3605  *	RETURN:	0 on success, error code on failure.
3606  *
3607  * Timestamps:
3608  *	dvp - ctime|mtime updated
3609  */
3610 int
zfs_symlink(znode_t * dzp,const char * name,vattr_t * vap,const char * link,znode_t ** zpp,cred_t * cr,int flags)3611 zfs_symlink(znode_t *dzp, const char *name, vattr_t *vap,
3612     const char *link, znode_t **zpp, cred_t *cr, int flags)
3613 {
3614 	(void) flags;
3615 	znode_t		*zp;
3616 	dmu_tx_t	*tx;
3617 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3618 	zilog_t		*zilog;
3619 	uint64_t	len = strlen(link);
3620 	int		error;
3621 	zfs_acl_ids_t	acl_ids;
3622 	boolean_t	fuid_dirtied;
3623 	uint64_t	txtype = TX_SYMLINK;
3624 
3625 	ASSERT3S(vap->va_type, ==, VLNK);
3626 
3627 	if (is_nametoolong(zfsvfs, name))
3628 		return (SET_ERROR(ENAMETOOLONG));
3629 
3630 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
3631 		return (error);
3632 	zilog = zfsvfs->z_log;
3633 
3634 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3635 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3636 		zfs_exit(zfsvfs, FTAG);
3637 		return (SET_ERROR(EILSEQ));
3638 	}
3639 
3640 	if (len > MAXPATHLEN) {
3641 		zfs_exit(zfsvfs, FTAG);
3642 		return (SET_ERROR(ENAMETOOLONG));
3643 	}
3644 
3645 	if ((error = zfs_acl_ids_create(dzp, 0,
3646 	    vap, cr, NULL, &acl_ids)) != 0) {
3647 		zfs_exit(zfsvfs, FTAG);
3648 		return (error);
3649 	}
3650 
3651 	/*
3652 	 * Attempt to lock directory; fail if entry already exists.
3653 	 */
3654 	error = zfs_dirent_lookup(dzp, name, &zp, ZNEW);
3655 	if (error) {
3656 		zfs_acl_ids_free(&acl_ids);
3657 		zfs_exit(zfsvfs, FTAG);
3658 		return (error);
3659 	}
3660 
3661 	if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3662 		zfs_acl_ids_free(&acl_ids);
3663 		zfs_exit(zfsvfs, FTAG);
3664 		return (error);
3665 	}
3666 
3667 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zfs_inherit_projid(dzp))) {
3668 		zfs_acl_ids_free(&acl_ids);
3669 		zfs_exit(zfsvfs, FTAG);
3670 		return (SET_ERROR(EDQUOT));
3671 	}
3672 
3673 	getnewvnode_reserve();
3674 	tx = dmu_tx_create(zfsvfs->z_os);
3675 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3676 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3677 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3678 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3679 	    ZFS_SA_BASE_ATTR_SIZE + len);
3680 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
3681 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3682 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3683 		    acl_ids.z_aclp->z_acl_bytes);
3684 	}
3685 	if (fuid_dirtied)
3686 		zfs_fuid_txhold(zfsvfs, tx);
3687 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
3688 	if (error) {
3689 		zfs_acl_ids_free(&acl_ids);
3690 		dmu_tx_abort(tx);
3691 		getnewvnode_drop_reserve();
3692 		zfs_exit(zfsvfs, FTAG);
3693 		return (error);
3694 	}
3695 
3696 	/*
3697 	 * Create a new object for the symlink.
3698 	 * for version 4 ZPL datasets the symlink will be an SA attribute
3699 	 */
3700 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3701 
3702 	if (fuid_dirtied)
3703 		zfs_fuid_sync(zfsvfs, tx);
3704 
3705 	if (zp->z_is_sa)
3706 		error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
3707 		    __DECONST(void *, link), len, tx);
3708 	else
3709 		zfs_sa_symlink(zp, __DECONST(char *, link), len, tx);
3710 
3711 	zp->z_size = len;
3712 	(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
3713 	    &zp->z_size, sizeof (zp->z_size), tx);
3714 	/*
3715 	 * Insert the new object into the directory.
3716 	 */
3717 	error = zfs_link_create(dzp, name, zp, tx, ZNEW);
3718 	if (error != 0) {
3719 		zfs_znode_delete(zp, tx);
3720 		VOP_UNLOCK(ZTOV(zp));
3721 		zrele(zp);
3722 	} else {
3723 		zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3724 	}
3725 
3726 	zfs_acl_ids_free(&acl_ids);
3727 
3728 	dmu_tx_commit(tx);
3729 
3730 	getnewvnode_drop_reserve();
3731 
3732 	if (error == 0) {
3733 		*zpp = zp;
3734 
3735 		if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3736 			error = zil_commit(zilog, 0);
3737 	}
3738 
3739 	zfs_exit(zfsvfs, FTAG);
3740 	return (error);
3741 }
3742 
3743 /*
3744  * Return, in the buffer contained in the provided uio structure,
3745  * the symbolic path referred to by vp.
3746  *
3747  *	IN:	vp	- vnode of symbolic link.
3748  *		uio	- structure to contain the link path.
3749  *		cr	- credentials of caller.
3750  *		ct	- caller context
3751  *
3752  *	OUT:	uio	- structure containing the link path.
3753  *
3754  *	RETURN:	0 on success, error code on failure.
3755  *
3756  * Timestamps:
3757  *	vp - atime updated
3758  */
3759 static int
zfs_readlink(vnode_t * vp,zfs_uio_t * uio,cred_t * cr,caller_context_t * ct)3760 zfs_readlink(vnode_t *vp, zfs_uio_t *uio, cred_t *cr, caller_context_t *ct)
3761 {
3762 	(void) cr, (void) ct;
3763 	znode_t		*zp = VTOZ(vp);
3764 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3765 	int		error;
3766 
3767 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
3768 		return (error);
3769 
3770 	if (zp->z_is_sa)
3771 		error = sa_lookup_uio(zp->z_sa_hdl,
3772 		    SA_ZPL_SYMLINK(zfsvfs), uio);
3773 	else
3774 		error = zfs_sa_readlink(zp, uio);
3775 
3776 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3777 
3778 	zfs_exit(zfsvfs, FTAG);
3779 	return (error);
3780 }
3781 
3782 /*
3783  * Insert a new entry into directory tdvp referencing svp.
3784  *
3785  *	IN:	tdvp	- Directory to contain new entry.
3786  *		svp	- vnode of new entry.
3787  *		name	- name of new entry.
3788  *		cr	- credentials of caller.
3789  *
3790  *	RETURN:	0 on success, error code on failure.
3791  *
3792  * Timestamps:
3793  *	tdvp - ctime|mtime updated
3794  *	 svp - ctime updated
3795  */
3796 int
zfs_link(znode_t * tdzp,znode_t * szp,const char * name,cred_t * cr,int flags)3797 zfs_link(znode_t *tdzp, znode_t *szp, const char *name, cred_t *cr,
3798     int flags)
3799 {
3800 	(void) flags;
3801 	znode_t		*tzp;
3802 	zfsvfs_t	*zfsvfs = tdzp->z_zfsvfs;
3803 	zilog_t		*zilog;
3804 	dmu_tx_t	*tx;
3805 	int		error;
3806 	uint64_t	parent;
3807 	uid_t		owner;
3808 
3809 	ASSERT3S(ZTOV(tdzp)->v_type, ==, VDIR);
3810 
3811 	if (is_nametoolong(zfsvfs, name))
3812 		return (SET_ERROR(ENAMETOOLONG));
3813 
3814 	if ((error = zfs_enter_verify_zp(zfsvfs, tdzp, FTAG)) != 0)
3815 		return (error);
3816 	zilog = zfsvfs->z_log;
3817 
3818 	/*
3819 	 * POSIX dictates that we return EPERM here.
3820 	 * Better choices include ENOTSUP or EISDIR.
3821 	 */
3822 	if (ZTOV(szp)->v_type == VDIR) {
3823 		zfs_exit(zfsvfs, FTAG);
3824 		return (SET_ERROR(EPERM));
3825 	}
3826 
3827 	if ((error = zfs_verify_zp(szp)) != 0) {
3828 		zfs_exit(zfsvfs, FTAG);
3829 		return (error);
3830 	}
3831 
3832 	/*
3833 	 * If we are using project inheritance, means if the directory has
3834 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
3835 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3836 	 * such case, we only allow hard link creation in our tree when the
3837 	 * project IDs are the same.
3838 	 */
3839 	if (tdzp->z_pflags & ZFS_PROJINHERIT &&
3840 	    tdzp->z_projid != szp->z_projid) {
3841 		zfs_exit(zfsvfs, FTAG);
3842 		return (SET_ERROR(EXDEV));
3843 	}
3844 
3845 	if (szp->z_pflags & (ZFS_APPENDONLY |
3846 	    ZFS_IMMUTABLE | ZFS_READONLY)) {
3847 		zfs_exit(zfsvfs, FTAG);
3848 		return (SET_ERROR(EPERM));
3849 	}
3850 
3851 	/* Prevent links to .zfs/shares files */
3852 
3853 	if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
3854 	    &parent, sizeof (uint64_t))) != 0) {
3855 		zfs_exit(zfsvfs, FTAG);
3856 		return (error);
3857 	}
3858 	if (parent == zfsvfs->z_shares_dir) {
3859 		zfs_exit(zfsvfs, FTAG);
3860 		return (SET_ERROR(EPERM));
3861 	}
3862 
3863 	if (zfsvfs->z_utf8 && u8_validate(name,
3864 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3865 		zfs_exit(zfsvfs, FTAG);
3866 		return (SET_ERROR(EILSEQ));
3867 	}
3868 
3869 	/*
3870 	 * We do not support links between attributes and non-attributes
3871 	 * because of the potential security risk of creating links
3872 	 * into "normal" file space in order to circumvent restrictions
3873 	 * imposed in attribute space.
3874 	 */
3875 	if ((szp->z_pflags & ZFS_XATTR) != (tdzp->z_pflags & ZFS_XATTR)) {
3876 		zfs_exit(zfsvfs, FTAG);
3877 		return (SET_ERROR(EINVAL));
3878 	}
3879 
3880 
3881 	owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
3882 	if (owner != crgetuid(cr) && secpolicy_basic_link(ZTOV(szp), cr) != 0) {
3883 		zfs_exit(zfsvfs, FTAG);
3884 		return (SET_ERROR(EPERM));
3885 	}
3886 
3887 	if ((error = zfs_zaccess(tdzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3888 		zfs_exit(zfsvfs, FTAG);
3889 		return (error);
3890 	}
3891 
3892 	/*
3893 	 * Attempt to lock directory; fail if entry already exists.
3894 	 */
3895 	error = zfs_dirent_lookup(tdzp, name, &tzp, ZNEW);
3896 	if (error) {
3897 		zfs_exit(zfsvfs, FTAG);
3898 		return (error);
3899 	}
3900 
3901 	tx = dmu_tx_create(zfsvfs->z_os);
3902 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, ZFS_SEQ_MAY_GROW(szp));
3903 	dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(tdzp));
3904 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, name);
3905 	zfs_sa_upgrade_txholds(tx, szp);
3906 	zfs_sa_upgrade_txholds(tx, tdzp);
3907 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
3908 	if (error) {
3909 		dmu_tx_abort(tx);
3910 		zfs_exit(zfsvfs, FTAG);
3911 		return (error);
3912 	}
3913 
3914 	error = zfs_link_create(tdzp, name, szp, tx, 0);
3915 
3916 	if (error == 0) {
3917 		uint64_t txtype = TX_LINK;
3918 		zfs_log_link(zilog, tx, txtype, tdzp, szp, name);
3919 	}
3920 
3921 	dmu_tx_commit(tx);
3922 
3923 	if (error == 0) {
3924 		vnevent_link(ZTOV(szp), ct);
3925 	}
3926 
3927 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3928 		error = zil_commit(zilog, 0);
3929 
3930 	zfs_exit(zfsvfs, FTAG);
3931 	return (error);
3932 }
3933 
3934 /*
3935  * Free or allocate space in a file.  Currently, this function only
3936  * supports the `F_FREESP' command.  However, this command is somewhat
3937  * misnamed, as its functionality includes the ability to allocate as
3938  * well as free space.
3939  *
3940  *	IN:	ip	- inode of file to free data in.
3941  *		cmd	- action to take (only F_FREESP supported).
3942  *		bfp	- section of file to free/alloc.
3943  *		flag	- current file open mode flags.
3944  *		offset	- current file offset.
3945  *		cr	- credentials of caller.
3946  *
3947  *	RETURN:	0 on success, error code on failure.
3948  *
3949  * Timestamps:
3950  *	ip - ctime|mtime updated
3951  */
3952 int
zfs_space(znode_t * zp,int cmd,flock64_t * bfp,int flag,offset_t offset,cred_t * cr)3953 zfs_space(znode_t *zp, int cmd, flock64_t *bfp, int flag,
3954     offset_t offset, cred_t *cr)
3955 {
3956 	(void) offset;
3957 	zfsvfs_t	*zfsvfs = ZTOZSB(zp);
3958 	uint64_t	off, len;
3959 	int		error;
3960 
3961 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
3962 		return (error);
3963 
3964 	if (cmd != F_FREESP) {
3965 		zfs_exit(zfsvfs, FTAG);
3966 		return (SET_ERROR(EINVAL));
3967 	}
3968 
3969 	/*
3970 	 * Callers might not be able to detect properly that we are read-only,
3971 	 * so check it explicitly here.
3972 	 */
3973 	if (zfs_is_readonly(zfsvfs)) {
3974 		zfs_exit(zfsvfs, FTAG);
3975 		return (SET_ERROR(EROFS));
3976 	}
3977 
3978 	if (bfp->l_len < 0) {
3979 		zfs_exit(zfsvfs, FTAG);
3980 		return (SET_ERROR(EINVAL));
3981 	}
3982 
3983 	/*
3984 	 * Permissions aren't checked on Solaris because on this OS
3985 	 * zfs_space() can only be called with an opened file handle.
3986 	 * On Linux we can get here through truncate_range() which
3987 	 * operates directly on inodes, so we need to check access rights.
3988 	 */
3989 	if ((error = zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr))) {
3990 		zfs_exit(zfsvfs, FTAG);
3991 		return (error);
3992 	}
3993 
3994 	off = bfp->l_start;
3995 	len = bfp->l_len; /* 0 means from off to end of file */
3996 
3997 	error = zfs_freesp(zp, off, len, flag, TRUE);
3998 
3999 	zfs_exit(zfsvfs, FTAG);
4000 	return (error);
4001 }
4002 
4003 static void
zfs_inactive(vnode_t * vp,cred_t * cr,caller_context_t * ct)4004 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4005 {
4006 	(void) cr, (void) ct;
4007 	znode_t	*zp = VTOZ(vp);
4008 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4009 	int error;
4010 
4011 	ZFS_TEARDOWN_INACTIVE_ENTER_READ(zfsvfs);
4012 	if (zp->z_sa_hdl == NULL) {
4013 		/*
4014 		 * The fs has been unmounted, or we did a
4015 		 * suspend/resume and this file no longer exists.
4016 		 */
4017 		ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
4018 		vrecycle(vp);
4019 		return;
4020 	}
4021 
4022 	if (zp->z_unlinked) {
4023 		/*
4024 		 * Fast path to recycle a vnode of a removed file.
4025 		 */
4026 		ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
4027 		vrecycle(vp);
4028 		return;
4029 	}
4030 
4031 	if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4032 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4033 
4034 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4035 		zfs_sa_upgrade_txholds(tx, zp);
4036 		error = dmu_tx_assign(tx, DMU_TX_WAIT);
4037 		if (error) {
4038 			dmu_tx_abort(tx);
4039 		} else {
4040 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4041 			    (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4042 			zp->z_atime_dirty = 0;
4043 			dmu_tx_commit(tx);
4044 		}
4045 	}
4046 	ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
4047 }
4048 
4049 
4050 _Static_assert(sizeof (struct zfid_short) <= sizeof (struct fid),
4051 	"struct zfid_short bigger than struct fid");
4052 _Static_assert(sizeof (struct zfid_long) <= sizeof (struct fid),
4053 	"struct zfid_long bigger than struct fid");
4054 
4055 static int
zfs_fid(vnode_t * vp,fid_t * fidp,caller_context_t * ct)4056 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
4057 {
4058 	(void) ct;
4059 	znode_t		*zp = VTOZ(vp);
4060 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4061 	uint32_t	gen;
4062 	uint64_t	gen64;
4063 	uint64_t	object = zp->z_id;
4064 	zfid_short_t	*zfid;
4065 	int		size, i, error;
4066 
4067 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4068 		return (error);
4069 
4070 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
4071 	    &gen64, sizeof (uint64_t))) != 0) {
4072 		zfs_exit(zfsvfs, FTAG);
4073 		return (error);
4074 	}
4075 
4076 	gen = (uint32_t)gen64;
4077 
4078 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
4079 	fidp->fid_len = size;
4080 
4081 	zfid = (zfid_short_t *)fidp;
4082 
4083 	zfid->zf_len = size;
4084 
4085 	for (i = 0; i < sizeof (zfid->zf_object); i++)
4086 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4087 
4088 	/* Must have a non-zero generation number to distinguish from .zfs */
4089 	if (gen == 0)
4090 		gen = 1;
4091 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
4092 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4093 
4094 	if (size == LONG_FID_LEN) {
4095 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
4096 		zfid_long_t	*zlfid;
4097 
4098 		zlfid = (zfid_long_t *)fidp;
4099 
4100 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4101 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4102 
4103 		/* XXX - this should be the generation number for the objset */
4104 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4105 			zlfid->zf_setgen[i] = 0;
4106 	}
4107 
4108 	zfs_exit(zfsvfs, FTAG);
4109 	return (0);
4110 }
4111 
4112 static int
zfs_pathconf(vnode_t * vp,int cmd,ulong_t * valp,cred_t * cr,caller_context_t * ct)4113 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
4114     caller_context_t *ct)
4115 {
4116 	znode_t *zp;
4117 	zfsvfs_t *zfsvfs;
4118 	uint_t blksize, iosize;
4119 	int error;
4120 
4121 	switch (cmd) {
4122 	case _PC_LINK_MAX:
4123 		*valp = MIN(LONG_MAX, ZFS_LINK_MAX);
4124 		return (0);
4125 
4126 	case _PC_FILESIZEBITS:
4127 		*valp = 64;
4128 		return (0);
4129 	case _PC_MIN_HOLE_SIZE:
4130 		iosize = vp->v_mount->mnt_stat.f_iosize;
4131 		if (vp->v_type == VREG) {
4132 			zp = VTOZ(vp);
4133 			blksize = zp->z_blksz;
4134 			if (zp->z_size <= blksize)
4135 				blksize = MAX(blksize, iosize);
4136 			*valp = (int)blksize;
4137 			return (0);
4138 		}
4139 		if (vp->v_type == VDIR) {
4140 			*valp = (int)iosize;
4141 			return (0);
4142 		}
4143 		return (EINVAL);
4144 	case _PC_ACL_EXTENDED:
4145 #if 0		/* POSIX ACLs are not implemented for ZFS on FreeBSD yet. */
4146 		zp = VTOZ(vp);
4147 		zfsvfs = zp->z_zfsvfs;
4148 		if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4149 			return (error);
4150 		*valp = zfsvfs->z_acl_type == ZFSACLTYPE_POSIX ? 1 : 0;
4151 		zfs_exit(zfsvfs, FTAG);
4152 #else
4153 		*valp = 0;
4154 #endif
4155 		return (0);
4156 
4157 	case _PC_ACL_NFS4:
4158 		zp = VTOZ(vp);
4159 		zfsvfs = zp->z_zfsvfs;
4160 		if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4161 			return (error);
4162 		*valp = zfsvfs->z_acl_type == ZFS_ACLTYPE_NFSV4 ? 1 : 0;
4163 		zfs_exit(zfsvfs, FTAG);
4164 		return (0);
4165 
4166 	case _PC_ACL_PATH_MAX:
4167 		*valp = ACL_MAX_ENTRIES;
4168 		return (0);
4169 
4170 	default:
4171 		return (EOPNOTSUPP);
4172 	}
4173 }
4174 
4175 static int
zfs_getpages(struct vnode * vp,vm_page_t * ma,int count,int * rbehind,int * rahead)4176 zfs_getpages(struct vnode *vp, vm_page_t *ma, int count, int *rbehind,
4177     int *rahead)
4178 {
4179 	znode_t *zp = VTOZ(vp);
4180 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4181 	zfs_locked_range_t *lr;
4182 	vm_object_t object;
4183 	off_t start, end, obj_size;
4184 	uint_t blksz;
4185 	int pgsin_b, pgsin_a;
4186 	int error;
4187 
4188 	if (zfs_enter_verify_zp(zfsvfs, zp, FTAG) != 0)
4189 		return (zfs_vm_pagerret_error);
4190 
4191 	object = ma[0]->object;
4192 	start = IDX_TO_OFF(ma[0]->pindex);
4193 	end = IDX_TO_OFF(ma[count - 1]->pindex + 1);
4194 
4195 	/*
4196 	 * Lock a range covering all required and optional pages.
4197 	 * Note that we need to handle the case of the block size growing.
4198 	 */
4199 	for (;;) {
4200 		uint64_t len;
4201 
4202 		blksz = zp->z_blksz;
4203 		len = roundup(end, blksz) - rounddown(start, blksz);
4204 
4205 		lr = zfs_rangelock_tryenter(&zp->z_rangelock,
4206 		    rounddown(start, blksz), len, RL_READER);
4207 		if (lr == NULL) {
4208 			/*
4209 			 * Avoid a deadlock with update_pages().  We need to
4210 			 * hold the range lock when copying from the DMU, so
4211 			 * give up the busy lock to allow update_pages() to
4212 			 * proceed.  We might need to allocate new pages, which
4213 			 * isn't quite right since this allocation isn't subject
4214 			 * to the page fault handler's OOM logic, but this is
4215 			 * the best we can do for now.
4216 			 */
4217 			for (int i = 0; i < count; i++)
4218 				vm_page_xunbusy(ma[i]);
4219 
4220 			lr = zfs_rangelock_enter(&zp->z_rangelock,
4221 			    rounddown(start, blksz), len, RL_READER);
4222 
4223 			zfs_vmobject_wlock(object);
4224 			(void) vm_page_grab_pages(object, OFF_TO_IDX(start),
4225 			    VM_ALLOC_NORMAL | VM_ALLOC_WAITOK,
4226 			    ma, count);
4227 			if (!vm_page_all_valid(ma[count - 1])) {
4228 				/*
4229 				 * Later in this function, we copy DMU data to
4230 				 * invalid pages only. The last page may not be
4231 				 * entirely filled though, if the file does not
4232 				 * end on a page boundary. Therefore, we zero
4233 				 * that last page here to make sure it does not
4234 				 * contain garbage after the end of file.
4235 				 */
4236 				ASSERT(vm_page_none_valid(ma[count - 1]));
4237 				vm_page_zero_invalid(ma[count - 1], FALSE);
4238 			}
4239 			zfs_vmobject_wunlock(object);
4240 		}
4241 		if (blksz == zp->z_blksz)
4242 			break;
4243 		zfs_rangelock_exit(lr);
4244 	}
4245 
4246 	zfs_vmobject_wlock(object);
4247 	obj_size = object->un_pager.vnp.vnp_size;
4248 	zfs_vmobject_wunlock(object);
4249 	if (IDX_TO_OFF(ma[count - 1]->pindex) >= obj_size) {
4250 		zfs_rangelock_exit(lr);
4251 		zfs_exit(zfsvfs, FTAG);
4252 		return (zfs_vm_pagerret_bad);
4253 	}
4254 
4255 	pgsin_b = 0;
4256 	if (rbehind != NULL) {
4257 		pgsin_b = OFF_TO_IDX(start - rounddown(start, blksz));
4258 		pgsin_b = MIN(*rbehind, pgsin_b);
4259 	}
4260 
4261 	pgsin_a = 0;
4262 	if (rahead != NULL) {
4263 		pgsin_a = OFF_TO_IDX(roundup(end, blksz) - end);
4264 		if (end + IDX_TO_OFF(pgsin_a) >= obj_size)
4265 			pgsin_a = OFF_TO_IDX(round_page(obj_size) - end);
4266 		pgsin_a = MIN(*rahead, pgsin_a);
4267 	}
4268 
4269 	/*
4270 	 * NB: we need to pass the exact byte size of the data that we expect
4271 	 * to read after accounting for the file size.  This is required because
4272 	 * ZFS will panic if we request DMU to read beyond the end of the last
4273 	 * allocated block.
4274 	 */
4275 	for (int i = 0; i < count; i++) {
4276 		int dummypgsin, count1, j, last_size;
4277 
4278 		if (vm_page_any_valid(ma[i])) {
4279 			ASSERT(vm_page_all_valid(ma[i]));
4280 			continue;
4281 		}
4282 		for (j = i + 1; j < count; j++) {
4283 			if (vm_page_any_valid(ma[j])) {
4284 				ASSERT(vm_page_all_valid(ma[j]));
4285 				break;
4286 			}
4287 		}
4288 		count1 = j - i;
4289 		dummypgsin = 0;
4290 		last_size = j == count ?
4291 		    MIN(end, obj_size) - (end - PAGE_SIZE) : PAGE_SIZE;
4292 		error = dmu_read_pages(zfsvfs->z_os, zp->z_id, &ma[i], count1,
4293 		    i == 0 ? &pgsin_b : &dummypgsin,
4294 		    j == count ? &pgsin_a : &dummypgsin,
4295 		    last_size);
4296 		if (error != 0)
4297 			break;
4298 		i += count1 - 1;
4299 	}
4300 
4301 	zfs_rangelock_exit(lr);
4302 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4303 
4304 	dataset_kstats_update_read_kstats(&zfsvfs->z_kstat, count*PAGE_SIZE);
4305 
4306 	zfs_exit(zfsvfs, FTAG);
4307 
4308 	if (error != 0)
4309 		return (zfs_vm_pagerret_error);
4310 
4311 	VM_CNT_INC(v_vnodein);
4312 	VM_CNT_ADD(v_vnodepgsin, count + pgsin_b + pgsin_a);
4313 	if (rbehind != NULL)
4314 		*rbehind = pgsin_b;
4315 	if (rahead != NULL)
4316 		*rahead = pgsin_a;
4317 	return (zfs_vm_pagerret_ok);
4318 }
4319 
4320 #ifndef _SYS_SYSPROTO_H_
4321 struct vop_getpages_args {
4322 	struct vnode *a_vp;
4323 	vm_page_t *a_m;
4324 	int a_count;
4325 	int *a_rbehind;
4326 	int *a_rahead;
4327 };
4328 #endif
4329 
4330 static int
zfs_freebsd_getpages(struct vop_getpages_args * ap)4331 zfs_freebsd_getpages(struct vop_getpages_args *ap)
4332 {
4333 
4334 	return (zfs_getpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_rbehind,
4335 	    ap->a_rahead));
4336 }
4337 
4338 typedef struct {
4339 	uint_t		pca_npages;
4340 	vm_page_t	pca_pages[];
4341 } putpage_commit_arg_t;
4342 
4343 static void
zfs_putpage_commit_cb(void * arg,int err)4344 zfs_putpage_commit_cb(void *arg, int err)
4345 {
4346 	putpage_commit_arg_t *pca = arg;
4347 	vm_object_t object = pca->pca_pages[0]->object;
4348 
4349 	zfs_vmobject_wlock(object);
4350 
4351 	for (uint_t i = 0; i < pca->pca_npages; i++) {
4352 		vm_page_t pp = pca->pca_pages[i];
4353 
4354 		if (err == 0) {
4355 			/*
4356 			 * Writeback succeeded, so undirty the page. If it
4357 			 * fails, we leave it in the same state it was. That's
4358 			 * most likely dirty, so it will get tried again some
4359 			 * other time.
4360 			 */
4361 			vm_page_undirty(pp);
4362 		}
4363 
4364 		vm_page_sunbusy(pp);
4365 	}
4366 
4367 	vm_object_pip_wakeupn(object, pca->pca_npages);
4368 
4369 	zfs_vmobject_wunlock(object);
4370 
4371 	kmem_free(pca,
4372 	    offsetof(putpage_commit_arg_t, pca_pages[pca->pca_npages]));
4373 }
4374 
4375 static int
zfs_putpages(struct vnode * vp,vm_page_t * ma,size_t len,int flags,int * rtvals)4376 zfs_putpages(struct vnode *vp, vm_page_t *ma, size_t len, int flags,
4377     int *rtvals)
4378 {
4379 	znode_t		*zp = VTOZ(vp);
4380 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4381 	zfs_locked_range_t		*lr;
4382 	dmu_tx_t	*tx;
4383 	struct sf_buf	*sf;
4384 	vm_object_t	object;
4385 	vm_page_t	m;
4386 	caddr_t		va;
4387 	size_t		tocopy;
4388 	size_t		lo_len;
4389 	vm_ooffset_t	lo_off;
4390 	vm_ooffset_t	off;
4391 	uint_t		blksz;
4392 	int		ncount;
4393 	int		pcount;
4394 	int		err;
4395 	int		i;
4396 
4397 	object = vp->v_object;
4398 	KASSERT(ma[0]->object == object, ("mismatching object"));
4399 	KASSERT(len > 0 && (len & PAGE_MASK) == 0, ("unexpected length"));
4400 
4401 	pcount = btoc(len);
4402 	ncount = pcount;
4403 	for (i = 0; i < pcount; i++)
4404 		rtvals[i] = zfs_vm_pagerret_error;
4405 
4406 	if (zfs_enter_verify_zp(zfsvfs, zp, FTAG) != 0)
4407 		return (zfs_vm_pagerret_error);
4408 
4409 	off = IDX_TO_OFF(ma[0]->pindex);
4410 	blksz = zp->z_blksz;
4411 	lo_off = rounddown(off, blksz);
4412 	lo_len = roundup(len + (off - lo_off), blksz);
4413 	lr = zfs_rangelock_enter(&zp->z_rangelock, lo_off, lo_len, RL_WRITER);
4414 
4415 	zfs_vmobject_wlock(object);
4416 	if (len + off > object->un_pager.vnp.vnp_size) {
4417 		if (object->un_pager.vnp.vnp_size > off) {
4418 			int pgoff;
4419 
4420 			len = object->un_pager.vnp.vnp_size - off;
4421 			ncount = btoc(len);
4422 			if ((pgoff = (int)len & PAGE_MASK) != 0) {
4423 				/*
4424 				 * If the object is locked and the following
4425 				 * conditions hold, then the page's dirty
4426 				 * field cannot be concurrently changed by a
4427 				 * pmap operation.
4428 				 */
4429 				m = ma[ncount - 1];
4430 				vm_page_assert_sbusied(m);
4431 				KASSERT(!pmap_page_is_write_mapped(m),
4432 				    ("zfs_putpages: page %p is not read-only",
4433 				    m));
4434 				vm_page_clear_dirty(m, pgoff, PAGE_SIZE -
4435 				    pgoff);
4436 			}
4437 		} else {
4438 			len = 0;
4439 			ncount = 0;
4440 		}
4441 		if (ncount < pcount) {
4442 			for (i = ncount; i < pcount; i++) {
4443 				rtvals[i] = zfs_vm_pagerret_bad;
4444 			}
4445 		}
4446 	}
4447 	zfs_vmobject_wunlock(object);
4448 
4449 	boolean_t commit = (flags & (zfs_vm_pagerput_sync |
4450 	    zfs_vm_pagerput_inval)) != 0 ||
4451 	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS;
4452 
4453 	if (ncount == 0)
4454 		goto out;
4455 
4456 	if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, zp->z_uid) ||
4457 	    zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, zp->z_gid) ||
4458 	    (zp->z_projid != ZFS_DEFAULT_PROJID &&
4459 	    zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
4460 	    zp->z_projid))) {
4461 		goto out;
4462 	}
4463 
4464 	tx = dmu_tx_create(zfsvfs->z_os);
4465 	dmu_tx_hold_write(tx, zp->z_id, off, len);
4466 
4467 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
4468 	zfs_sa_upgrade_txholds(tx, zp);
4469 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
4470 	if (err != 0) {
4471 		dmu_tx_abort(tx);
4472 		goto out;
4473 	}
4474 
4475 	if (zp->z_blksz < PAGE_SIZE) {
4476 		vm_ooffset_t woff = off;
4477 		size_t wlen = len;
4478 		for (i = 0; wlen > 0; woff += tocopy, wlen -= tocopy, i++) {
4479 			tocopy = MIN(PAGE_SIZE, wlen);
4480 			va = zfs_map_page(ma[i], &sf);
4481 			dmu_write(zfsvfs->z_os, zp->z_id, woff, tocopy, va, tx,
4482 			    DMU_READ_PREFETCH);
4483 			zfs_unmap_page(sf);
4484 		}
4485 	} else {
4486 		err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, ma, tx);
4487 	}
4488 
4489 	if (err == 0) {
4490 		uint64_t mtime[2], ctime[2];
4491 		sa_bulk_attr_t bulk[4];
4492 		int count = 0;
4493 
4494 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4495 		    &mtime, 16);
4496 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4497 		    &ctime, 16);
4498 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4499 		    &zp->z_pflags, 8);
4500 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
4501 		ZFS_PERSIST_SEQ(zp, bulk, count);
4502 		ASSERT3S(count, <=, ARRAY_SIZE(bulk));
4503 		err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
4504 		ASSERT0(err);
4505 
4506 		if (commit) {
4507 			/*
4508 			 * Caller requested that we commit immediately. We set
4509 			 * a callback on the log entry, to be called once its
4510 			 * on disk after the call to zil_commit() below. The
4511 			 * pages will be undirtied and unbusied there.
4512 			 */
4513 			putpage_commit_arg_t *pca = kmem_alloc(
4514 			    offsetof(putpage_commit_arg_t, pca_pages[ncount]),
4515 			    KM_SLEEP);
4516 			pca->pca_npages = ncount;
4517 			memcpy(pca->pca_pages, ma, sizeof (vm_page_t) * ncount);
4518 
4519 			zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len,
4520 			    B_TRUE, B_FALSE, zfs_putpage_commit_cb, pca);
4521 
4522 			for (i = 0; i < ncount; i++)
4523 				rtvals[i] = zfs_vm_pagerret_pend;
4524 		} else {
4525 			/*
4526 			 * Caller just wants the page written back somewhere,
4527 			 * but doesn't need it committed yet. We've already
4528 			 * written it back to the DMU, so we just need to put
4529 			 * it on the async log, then undirty the page and
4530 			 * return.
4531 			 *
4532 			 * We cannot use a callback here, because it would keep
4533 			 * the page busy (locked) until it is eventually
4534 			 * written down at txg sync.
4535 			 */
4536 			zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len,
4537 			    B_FALSE, B_FALSE, NULL, NULL);
4538 
4539 			zfs_vmobject_wlock(object);
4540 			for (i = 0; i < ncount; i++) {
4541 				rtvals[i] = zfs_vm_pagerret_ok;
4542 				vm_page_undirty(ma[i]);
4543 			}
4544 			zfs_vmobject_wunlock(object);
4545 		}
4546 
4547 		VM_CNT_INC(v_vnodeout);
4548 		VM_CNT_ADD(v_vnodepgsout, ncount);
4549 	}
4550 	dmu_tx_commit(tx);
4551 
4552 out:
4553 	zfs_rangelock_exit(lr);
4554 	if (commit) {
4555 		err = zil_commit(zfsvfs->z_log, zp->z_id);
4556 		if (err != 0) {
4557 			zfs_exit(zfsvfs, FTAG);
4558 			return (err);
4559 		}
4560 	}
4561 
4562 	dataset_kstats_update_write_kstats(&zfsvfs->z_kstat, len);
4563 
4564 	zfs_exit(zfsvfs, FTAG);
4565 	return (rtvals[0]);
4566 }
4567 
4568 #ifndef _SYS_SYSPROTO_H_
4569 struct vop_putpages_args {
4570 	struct vnode *a_vp;
4571 	vm_page_t *a_m;
4572 	int a_count;
4573 	int a_sync;
4574 	int *a_rtvals;
4575 };
4576 #endif
4577 
4578 static int
zfs_freebsd_putpages(struct vop_putpages_args * ap)4579 zfs_freebsd_putpages(struct vop_putpages_args *ap)
4580 {
4581 
4582 	return (zfs_putpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_sync,
4583 	    ap->a_rtvals));
4584 }
4585 
4586 #ifndef _SYS_SYSPROTO_H_
4587 struct vop_bmap_args {
4588 	struct vnode *a_vp;
4589 	daddr_t  a_bn;
4590 	struct bufobj **a_bop;
4591 	daddr_t *a_bnp;
4592 	int *a_runp;
4593 	int *a_runb;
4594 };
4595 #endif
4596 
4597 static int
zfs_freebsd_bmap(struct vop_bmap_args * ap)4598 zfs_freebsd_bmap(struct vop_bmap_args *ap)
4599 {
4600 
4601 	if (ap->a_bop != NULL)
4602 		*ap->a_bop = &ap->a_vp->v_bufobj;
4603 	if (ap->a_bnp != NULL)
4604 		*ap->a_bnp = ap->a_bn;
4605 	if (ap->a_runp != NULL)
4606 		*ap->a_runp = 0;
4607 	if (ap->a_runb != NULL)
4608 		*ap->a_runb = 0;
4609 
4610 	return (0);
4611 }
4612 
4613 #ifndef _SYS_SYSPROTO_H_
4614 struct vop_open_args {
4615 	struct vnode *a_vp;
4616 	int a_mode;
4617 	struct ucred *a_cred;
4618 	struct thread *a_td;
4619 };
4620 #endif
4621 
4622 static int
zfs_freebsd_open(struct vop_open_args * ap)4623 zfs_freebsd_open(struct vop_open_args *ap)
4624 {
4625 	vnode_t	*vp = ap->a_vp;
4626 	znode_t *zp = VTOZ(vp);
4627 	int error;
4628 
4629 	error = zfs_open(&vp, ap->a_mode, ap->a_cred);
4630 	if (error == 0)
4631 		vnode_create_vobject(vp, zp->z_size, ap->a_td);
4632 	return (error);
4633 }
4634 
4635 #ifndef _SYS_SYSPROTO_H_
4636 struct vop_close_args {
4637 	struct vnode *a_vp;
4638 	int  a_fflag;
4639 	struct ucred *a_cred;
4640 	struct thread *a_td;
4641 };
4642 #endif
4643 
4644 static int
zfs_freebsd_close(struct vop_close_args * ap)4645 zfs_freebsd_close(struct vop_close_args *ap)
4646 {
4647 
4648 	return (zfs_close(ap->a_vp, ap->a_fflag, 1, 0, ap->a_cred));
4649 }
4650 
4651 #ifndef _SYS_SYSPROTO_H_
4652 struct vop_ioctl_args {
4653 	struct vnode *a_vp;
4654 	ulong_t a_command;
4655 	caddr_t a_data;
4656 	int a_fflag;
4657 	struct ucred *cred;
4658 	struct thread *td;
4659 };
4660 #endif
4661 
4662 static int
zfs_freebsd_ioctl(struct vop_ioctl_args * ap)4663 zfs_freebsd_ioctl(struct vop_ioctl_args *ap)
4664 {
4665 
4666 	return (zfs_ioctl(ap->a_vp, ap->a_command, (intptr_t)ap->a_data,
4667 	    ap->a_fflag, ap->a_cred, NULL));
4668 }
4669 
4670 static int
ioflags(int ioflags)4671 ioflags(int ioflags)
4672 {
4673 	int flags = 0;
4674 
4675 	if (ioflags & IO_APPEND)
4676 		flags |= O_APPEND;
4677 	if (ioflags & IO_NDELAY)
4678 		flags |= O_NONBLOCK;
4679 	if (ioflags & IO_DIRECT)
4680 		flags |= O_DIRECT;
4681 	if (ioflags & IO_SYNC)
4682 		flags |= O_SYNC;
4683 
4684 	return (flags);
4685 }
4686 
4687 #ifndef _SYS_SYSPROTO_H_
4688 struct vop_read_args {
4689 	struct vnode *a_vp;
4690 	struct uio *a_uio;
4691 	int a_ioflag;
4692 	struct ucred *a_cred;
4693 };
4694 #endif
4695 
4696 static int
zfs_freebsd_read(struct vop_read_args * ap)4697 zfs_freebsd_read(struct vop_read_args *ap)
4698 {
4699 	zfs_uio_t uio;
4700 	int error = 0;
4701 	zfs_uio_init(&uio, ap->a_uio);
4702 	error = zfs_read(VTOZ(ap->a_vp), &uio, ioflags(ap->a_ioflag),
4703 	    ap->a_cred);
4704 	/*
4705 	 * XXX We occasionally get an EFAULT for Direct I/O reads on
4706 	 * FreeBSD 13. This still needs to be resolved. The EFAULT comes
4707 	 * from:
4708 	 * zfs_uio_get__dio_pages_alloc() ->
4709 	 * zfs_uio_get_dio_pages_impl() ->
4710 	 * zfs_uio_iov_step() ->
4711 	 * zfs_uio_get_user_pages().
4712 	 * We return EFAULT from zfs_uio_iov_step(). When a Direct I/O
4713 	 * read fails to map in the user pages (returning EFAULT) the
4714 	 * Direct I/O request is broken up into two separate IO requests
4715 	 * and issued separately using Direct I/O.
4716 	 */
4717 #ifdef ZFS_DEBUG
4718 	if (error == EFAULT && uio.uio_extflg & UIO_DIRECT) {
4719 #if 0
4720 		printf("%s(%d): Direct I/O read returning EFAULT "
4721 		    "uio = %p, zfs_uio_offset(uio) = %lu "
4722 		    "zfs_uio_resid(uio) = %lu\n",
4723 		    __FUNCTION__, __LINE__, &uio, zfs_uio_offset(&uio),
4724 		    zfs_uio_resid(&uio));
4725 #endif
4726 	}
4727 
4728 #endif
4729 	return (error);
4730 }
4731 
4732 #ifndef _SYS_SYSPROTO_H_
4733 struct vop_write_args {
4734 	struct vnode *a_vp;
4735 	struct uio *a_uio;
4736 	int a_ioflag;
4737 	struct ucred *a_cred;
4738 };
4739 #endif
4740 
4741 static int
zfs_freebsd_write(struct vop_write_args * ap)4742 zfs_freebsd_write(struct vop_write_args *ap)
4743 {
4744 	zfs_uio_t uio;
4745 	zfs_uio_init(&uio, ap->a_uio);
4746 	return (zfs_write(VTOZ(ap->a_vp), &uio, ioflags(ap->a_ioflag),
4747 	    ap->a_cred));
4748 }
4749 
4750 /*
4751  * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
4752  * the comment above cache_fplookup for details.
4753  */
4754 static int
zfs_freebsd_fplookup_vexec(struct vop_fplookup_vexec_args * v)4755 zfs_freebsd_fplookup_vexec(struct vop_fplookup_vexec_args *v)
4756 {
4757 	vnode_t *vp;
4758 	znode_t *zp;
4759 	uint64_t pflags;
4760 
4761 	vp = v->a_vp;
4762 	zp = VTOZ_SMR(vp);
4763 	if (__predict_false(zp == NULL))
4764 		return (EAGAIN);
4765 	pflags = atomic_load_64(&zp->z_pflags);
4766 	if (pflags & ZFS_AV_QUARANTINED)
4767 		return (EAGAIN);
4768 	if (pflags & ZFS_XATTR)
4769 		return (EAGAIN);
4770 	if ((pflags & ZFS_NO_EXECS_DENIED) == 0)
4771 		return (EAGAIN);
4772 	return (0);
4773 }
4774 
4775 static int
zfs_freebsd_fplookup_symlink(struct vop_fplookup_symlink_args * v)4776 zfs_freebsd_fplookup_symlink(struct vop_fplookup_symlink_args *v)
4777 {
4778 	vnode_t *vp;
4779 	znode_t *zp;
4780 	char *target;
4781 
4782 	vp = v->a_vp;
4783 	zp = VTOZ_SMR(vp);
4784 	if (__predict_false(zp == NULL)) {
4785 		return (EAGAIN);
4786 	}
4787 
4788 	target = atomic_load_consume_ptr(&zp->z_cached_symlink);
4789 	if (target == NULL) {
4790 		return (EAGAIN);
4791 	}
4792 	return (cache_symlink_resolve(v->a_fpl, target, strlen(target)));
4793 }
4794 
4795 #ifndef _SYS_SYSPROTO_H_
4796 struct vop_access_args {
4797 	struct vnode *a_vp;
4798 	accmode_t a_accmode;
4799 	struct ucred *a_cred;
4800 	struct thread *a_td;
4801 };
4802 #endif
4803 
4804 static int
zfs_freebsd_access(struct vop_access_args * ap)4805 zfs_freebsd_access(struct vop_access_args *ap)
4806 {
4807 	vnode_t *vp = ap->a_vp;
4808 	znode_t *zp = VTOZ(vp);
4809 	accmode_t accmode;
4810 	int error = 0;
4811 
4812 
4813 	if (ap->a_accmode == VEXEC) {
4814 		if (zfs_fastaccesschk_execute(zp, ap->a_cred) == 0)
4815 			return (0);
4816 	}
4817 
4818 	/*
4819 	 * ZFS itself only knowns about VREAD, VWRITE, VEXEC and VAPPEND,
4820 	 */
4821 	accmode = ap->a_accmode & (VREAD|VWRITE|VEXEC|VAPPEND);
4822 	if (accmode != 0) {
4823 #if __FreeBSD_version >= 1500040
4824 		/* For named attributes, do the checks. */
4825 		if ((vn_irflag_read(vp) & VIRF_NAMEDATTR) != 0)
4826 			error = zfs_access(zp, accmode, V_NAMEDATTR,
4827 			    ap->a_cred);
4828 		else
4829 #endif
4830 			error = zfs_access(zp, accmode, 0, ap->a_cred);
4831 	}
4832 
4833 	/*
4834 	 * VADMIN has to be handled by vaccess().
4835 	 */
4836 	if (error == 0) {
4837 		accmode = ap->a_accmode & ~(VREAD|VWRITE|VEXEC|VAPPEND);
4838 		if (accmode != 0) {
4839 			error = vaccess(vp->v_type, zp->z_mode, zp->z_uid,
4840 			    zp->z_gid, accmode, ap->a_cred);
4841 		}
4842 	}
4843 
4844 	/*
4845 	 * For VEXEC, ensure that at least one execute bit is set for
4846 	 * non-directories.
4847 	 */
4848 	if (error == 0 && (ap->a_accmode & VEXEC) != 0 && vp->v_type != VDIR &&
4849 	    (zp->z_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
4850 		error = EACCES;
4851 	}
4852 
4853 	return (error);
4854 }
4855 
4856 #ifndef _SYS_SYSPROTO_H_
4857 struct vop_lookup_args {
4858 	struct vnode *a_dvp;
4859 	struct vnode **a_vpp;
4860 	struct componentname *a_cnp;
4861 };
4862 #endif
4863 
4864 #if __FreeBSD_version >= 1500040
4865 static int
zfs_lookup_nameddir(struct vnode * dvp,struct componentname * cnp,struct vnode ** vpp)4866 zfs_lookup_nameddir(struct vnode *dvp, struct componentname *cnp,
4867     struct vnode **vpp)
4868 {
4869 	struct vnode *xvp;
4870 	int error, flags;
4871 
4872 	*vpp = NULL;
4873 	flags = LOOKUP_XATTR | LOOKUP_NAMED_ATTR;
4874 	if ((cnp->cn_flags & CREATENAMED) != 0)
4875 		flags |= CREATE_XATTR_DIR;
4876 	error = zfs_lookup(dvp, NULL, &xvp, NULL, 0, cnp->cn_cred, flags,
4877 	    B_FALSE);
4878 	if (error == 0) {
4879 		if ((cnp->cn_flags & LOCKLEAF) != 0)
4880 			error = vn_lock(xvp, cnp->cn_lkflags);
4881 		if (error == 0) {
4882 			vn_irflag_set_cond(xvp, VIRF_NAMEDDIR);
4883 			*vpp = xvp;
4884 		} else {
4885 			vrele(xvp);
4886 		}
4887 	}
4888 	return (error);
4889 }
4890 
4891 static ssize_t
zfs_readdir_named(struct vnode * vp,char * buf,ssize_t blen,off_t * offp,int * eofflagp,struct ucred * cred,struct thread * td)4892 zfs_readdir_named(struct vnode *vp, char *buf, ssize_t blen, off_t *offp,
4893     int *eofflagp, struct ucred *cred, struct thread *td)
4894 {
4895 	struct uio io;
4896 	struct iovec iv;
4897 	zfs_uio_t uio;
4898 	int error;
4899 
4900 	io.uio_offset = *offp;
4901 	io.uio_segflg = UIO_SYSSPACE;
4902 	io.uio_rw = UIO_READ;
4903 	io.uio_td = td;
4904 	iv.iov_base = buf;
4905 	iv.iov_len = blen;
4906 	io.uio_iov = &iv;
4907 	io.uio_iovcnt = 1;
4908 	io.uio_resid = blen;
4909 	zfs_uio_init(&uio, &io);
4910 	error = zfs_readdir(vp, &uio, cred, eofflagp, NULL, NULL);
4911 	if (error != 0)
4912 		return (-1);
4913 	*offp = io.uio_offset;
4914 	return (blen - io.uio_resid);
4915 }
4916 
4917 static bool
zfs_has_namedattr(struct vnode * vp,struct ucred * cred)4918 zfs_has_namedattr(struct vnode *vp, struct ucred *cred)
4919 {
4920 	struct componentname cn;
4921 	struct vnode *xvp;
4922 	struct dirent *dp;
4923 	off_t offs;
4924 	ssize_t rsize;
4925 	char *buf, *cp, *endcp;
4926 	int eofflag, error;
4927 	bool ret;
4928 
4929 	MNT_ILOCK(vp->v_mount);
4930 	if ((vp->v_mount->mnt_flag & MNT_NAMEDATTR) == 0) {
4931 		MNT_IUNLOCK(vp->v_mount);
4932 		return (false);
4933 	}
4934 	MNT_IUNLOCK(vp->v_mount);
4935 
4936 	/* Now see if a named attribute directory exists. */
4937 	cn.cn_flags = LOCKLEAF;
4938 	cn.cn_lkflags = LK_SHARED;
4939 	cn.cn_cred = cred;
4940 	error = zfs_lookup_nameddir(vp, &cn, &xvp);
4941 	if (error != 0)
4942 		return (false);
4943 
4944 	/* It exists, so see if there is any entry other than "." and "..". */
4945 	buf = malloc(DEV_BSIZE, M_TEMP, M_WAITOK);
4946 	ret = false;
4947 	offs = 0;
4948 	do {
4949 		rsize = zfs_readdir_named(xvp, buf, DEV_BSIZE, &offs, &eofflag,
4950 		    cred, curthread);
4951 		if (rsize <= 0)
4952 			break;
4953 		cp = buf;
4954 		endcp = &buf[rsize];
4955 		while (cp < endcp) {
4956 			dp = (struct dirent *)cp;
4957 			if (dp->d_fileno != 0 && (dp->d_type == DT_REG ||
4958 			    dp->d_type == DT_UNKNOWN) &&
4959 			    !ZFS_XA_NS_PREFIX_FORBIDDEN(dp->d_name) &&
4960 			    ((dp->d_namlen == 1 && dp->d_name[0] != '.') ||
4961 			    (dp->d_namlen == 2 && (dp->d_name[0] != '.' ||
4962 			    dp->d_name[1] != '.')) || dp->d_namlen > 2)) {
4963 				ret = true;
4964 				break;
4965 			}
4966 			cp += dp->d_reclen;
4967 		}
4968 	} while (!ret && rsize > 0 && eofflag == 0);
4969 	vput(xvp);
4970 	free(buf, M_TEMP);
4971 	return (ret);
4972 }
4973 
4974 static int
zfs_freebsd_lookup(struct vop_lookup_args * ap,boolean_t cached)4975 zfs_freebsd_lookup(struct vop_lookup_args *ap, boolean_t cached)
4976 {
4977 	struct componentname *cnp = ap->a_cnp;
4978 	char nm[NAME_MAX + 1];
4979 	int error;
4980 	struct vnode **vpp = ap->a_vpp, *dvp = ap->a_dvp, *xvp;
4981 	bool is_nameddir, needs_nameddir, opennamed = false;
4982 
4983 	/*
4984 	 * These variables are used to handle the named attribute cases:
4985 	 * opennamed - Is true when this is a call from open with O_NAMEDATTR
4986 	 *    specified and it is the last component.
4987 	 * is_nameddir - Is true when the directory is a named attribute dir.
4988 	 * needs_nameddir - Is set when the lookup needs to look for/create
4989 	 *    a named attribute directory.  It is only set when is_nameddir
4990 	 *    is_nameddir is false and opennamed is true.
4991 	 * xvp - Is the directory that the lookup needs to be done in.
4992 	 *    Usually dvp, unless needs_nameddir is true where it is the
4993 	 *    result of the first non-named directory lookup.
4994 	 * Note that name caching must be disabled for named attribute
4995 	 * handling.
4996 	 */
4997 	needs_nameddir = false;
4998 	xvp = dvp;
4999 	opennamed = (cnp->cn_flags & (OPENNAMED | ISLASTCN)) ==
5000 	    (OPENNAMED | ISLASTCN);
5001 	is_nameddir = (vn_irflag_read(dvp) & VIRF_NAMEDDIR) != 0;
5002 	if (is_nameddir && (cnp->cn_flags & ISLASTCN) == 0)
5003 		return (ENOATTR);
5004 	if (opennamed && !is_nameddir && (cnp->cn_flags & ISDOTDOT) != 0)
5005 		return (ENOATTR);
5006 	if (opennamed || is_nameddir)
5007 		cnp->cn_flags &= ~MAKEENTRY;
5008 	if (opennamed && !is_nameddir)
5009 		needs_nameddir = true;
5010 	ASSERT3U(cnp->cn_namelen, <, sizeof (nm));
5011 	error = 0;
5012 	*vpp = NULL;
5013 	if (needs_nameddir) {
5014 		if (VOP_ISLOCKED(dvp) != LK_EXCLUSIVE)
5015 			vn_lock(dvp, LK_UPGRADE | LK_RETRY);
5016 		error = zfs_lookup_nameddir(dvp, cnp, &xvp);
5017 		if (error == 0)
5018 			is_nameddir = true;
5019 	}
5020 	if (error == 0) {
5021 		if (!needs_nameddir || cnp->cn_namelen != 1 ||
5022 		    *cnp->cn_nameptr != '.') {
5023 			strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1,
5024 			    sizeof (nm)));
5025 			error = zfs_lookup(xvp, nm, vpp, cnp, cnp->cn_nameiop,
5026 			    cnp->cn_cred, 0, cached);
5027 			if (is_nameddir && error == 0 &&
5028 			    (cnp->cn_namelen != 1 || *cnp->cn_nameptr != '.') &&
5029 			    (cnp->cn_flags & ISDOTDOT) == 0) {
5030 				if ((*vpp)->v_type == VDIR)
5031 					vn_irflag_set_cond(*vpp, VIRF_NAMEDDIR);
5032 				else
5033 					vn_irflag_set_cond(*vpp,
5034 					    VIRF_NAMEDATTR);
5035 			}
5036 			if (needs_nameddir && xvp != *vpp)
5037 				vput(xvp);
5038 		} else {
5039 			/*
5040 			 * Lookup of "." when a named attribute dir is needed.
5041 			 */
5042 			*vpp = xvp;
5043 		}
5044 	}
5045 	return (error);
5046 }
5047 #else
5048 static int
zfs_freebsd_lookup(struct vop_lookup_args * ap,boolean_t cached)5049 zfs_freebsd_lookup(struct vop_lookup_args *ap, boolean_t cached)
5050 {
5051 	struct componentname *cnp = ap->a_cnp;
5052 	char nm[NAME_MAX + 1];
5053 
5054 	ASSERT3U(cnp->cn_namelen, <, sizeof (nm));
5055 	strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1, sizeof (nm)));
5056 
5057 	return (zfs_lookup(ap->a_dvp, nm, ap->a_vpp, cnp, cnp->cn_nameiop,
5058 	    cnp->cn_cred, 0, cached));
5059 }
5060 #endif
5061 
5062 static int
zfs_freebsd_cachedlookup(struct vop_cachedlookup_args * ap)5063 zfs_freebsd_cachedlookup(struct vop_cachedlookup_args *ap)
5064 {
5065 
5066 	return (zfs_freebsd_lookup((struct vop_lookup_args *)ap, B_TRUE));
5067 }
5068 
5069 #ifndef _SYS_SYSPROTO_H_
5070 struct vop_lookup_args {
5071 	struct vnode *a_dvp;
5072 	struct vnode **a_vpp;
5073 	struct componentname *a_cnp;
5074 };
5075 #endif
5076 
5077 static int
zfs_cache_lookup(struct vop_lookup_args * ap)5078 zfs_cache_lookup(struct vop_lookup_args *ap)
5079 {
5080 	zfsvfs_t *zfsvfs;
5081 
5082 	zfsvfs = ap->a_dvp->v_mount->mnt_data;
5083 #if __FreeBSD_version >= 1500040
5084 	if (zfsvfs->z_use_namecache && (ap->a_cnp->cn_flags & OPENNAMED) == 0)
5085 #else
5086 	if (zfsvfs->z_use_namecache)
5087 #endif
5088 		return (vfs_cache_lookup(ap));
5089 	else
5090 		return (zfs_freebsd_lookup(ap, B_FALSE));
5091 }
5092 
5093 #ifndef _SYS_SYSPROTO_H_
5094 struct vop_create_args {
5095 	struct vnode *a_dvp;
5096 	struct vnode **a_vpp;
5097 	struct componentname *a_cnp;
5098 	struct vattr *a_vap;
5099 };
5100 #endif
5101 
5102 static int
zfs_freebsd_create(struct vop_create_args * ap)5103 zfs_freebsd_create(struct vop_create_args *ap)
5104 {
5105 	zfsvfs_t *zfsvfs;
5106 	struct componentname *cnp = ap->a_cnp;
5107 	vattr_t *vap = ap->a_vap;
5108 	znode_t *zp = NULL;
5109 	int rc, mode;
5110 	struct vnode *dvp = ap->a_dvp;
5111 #if __FreeBSD_version >= 1500040
5112 	struct vnode *xvp;
5113 	bool is_nameddir;
5114 #endif
5115 
5116 #if __FreeBSD_version < 1400068
5117 	ASSERT(cnp->cn_flags & SAVENAME);
5118 #endif
5119 
5120 	vattr_init_mask(vap);
5121 	mode = vap->va_mode & ALLPERMS;
5122 	zfsvfs = ap->a_dvp->v_mount->mnt_data;
5123 	*ap->a_vpp = NULL;
5124 
5125 	rc = 0;
5126 #if __FreeBSD_version >= 1500040
5127 	xvp = NULL;
5128 	is_nameddir = (vn_irflag_read(dvp) & VIRF_NAMEDDIR) != 0;
5129 	if (!is_nameddir && (cnp->cn_flags & OPENNAMED) != 0) {
5130 		/* Needs a named attribute directory. */
5131 		rc = zfs_lookup_nameddir(dvp, cnp, &xvp);
5132 		if (rc == 0) {
5133 			dvp = xvp;
5134 			is_nameddir = true;
5135 		}
5136 	}
5137 	if (is_nameddir && rc == 0)
5138 		rc = zfs_check_attrname(cnp->cn_nameptr);
5139 #endif
5140 
5141 	if (rc == 0)
5142 		rc = zfs_create(VTOZ(dvp), cnp->cn_nameptr, vap, 0, mode,
5143 		    &zp, cnp->cn_cred, 0 /* flag */, NULL /* vsecattr */);
5144 #if __FreeBSD_version >= 1500040
5145 	if (xvp != NULL)
5146 		vput(xvp);
5147 #endif
5148 	if (rc == 0) {
5149 		*ap->a_vpp = ZTOV(zp);
5150 #if __FreeBSD_version >= 1500040
5151 		if (is_nameddir)
5152 			vn_irflag_set_cond(*ap->a_vpp, VIRF_NAMEDATTR);
5153 #endif
5154 	}
5155 	if (zfsvfs->z_use_namecache &&
5156 	    rc == 0 && (cnp->cn_flags & MAKEENTRY) != 0)
5157 		cache_enter(ap->a_dvp, *ap->a_vpp, cnp);
5158 
5159 	return (rc);
5160 }
5161 
5162 #ifndef _SYS_SYSPROTO_H_
5163 struct vop_remove_args {
5164 	struct vnode *a_dvp;
5165 	struct vnode *a_vp;
5166 	struct componentname *a_cnp;
5167 };
5168 #endif
5169 
5170 static int
zfs_freebsd_remove(struct vop_remove_args * ap)5171 zfs_freebsd_remove(struct vop_remove_args *ap)
5172 {
5173 	int error = 0;
5174 
5175 #if __FreeBSD_version < 1400068
5176 	ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5177 #endif
5178 
5179 #if __FreeBSD_version >= 1500040
5180 	if ((vn_irflag_read(ap->a_dvp) & VIRF_NAMEDDIR) != 0)
5181 		error = zfs_check_attrname(ap->a_cnp->cn_nameptr);
5182 #endif
5183 
5184 	if (error == 0)
5185 		error = zfs_remove_(ap->a_dvp, ap->a_vp, ap->a_cnp->cn_nameptr,
5186 		    ap->a_cnp->cn_cred);
5187 	return (error);
5188 }
5189 
5190 #ifndef _SYS_SYSPROTO_H_
5191 struct vop_mkdir_args {
5192 	struct vnode *a_dvp;
5193 	struct vnode **a_vpp;
5194 	struct componentname *a_cnp;
5195 	struct vattr *a_vap;
5196 };
5197 #endif
5198 
5199 static int
zfs_freebsd_mkdir(struct vop_mkdir_args * ap)5200 zfs_freebsd_mkdir(struct vop_mkdir_args *ap)
5201 {
5202 	vattr_t *vap = ap->a_vap;
5203 	znode_t *zp = NULL;
5204 	int rc;
5205 
5206 #if __FreeBSD_version < 1400068
5207 	ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5208 #endif
5209 
5210 	vattr_init_mask(vap);
5211 	*ap->a_vpp = NULL;
5212 
5213 	rc = zfs_mkdir(VTOZ(ap->a_dvp), ap->a_cnp->cn_nameptr, vap, &zp,
5214 	    ap->a_cnp->cn_cred, 0, NULL);
5215 
5216 	if (rc == 0)
5217 		*ap->a_vpp = ZTOV(zp);
5218 	return (rc);
5219 }
5220 
5221 #ifndef _SYS_SYSPROTO_H_
5222 struct vop_rmdir_args {
5223 	struct vnode *a_dvp;
5224 	struct vnode *a_vp;
5225 	struct componentname *a_cnp;
5226 };
5227 #endif
5228 
5229 static int
zfs_freebsd_rmdir(struct vop_rmdir_args * ap)5230 zfs_freebsd_rmdir(struct vop_rmdir_args *ap)
5231 {
5232 	struct componentname *cnp = ap->a_cnp;
5233 
5234 #if __FreeBSD_version < 1400068
5235 	ASSERT(cnp->cn_flags & SAVENAME);
5236 #endif
5237 
5238 	return (zfs_rmdir_(ap->a_dvp, ap->a_vp, cnp->cn_nameptr, cnp->cn_cred));
5239 }
5240 
5241 #ifndef _SYS_SYSPROTO_H_
5242 struct vop_readdir_args {
5243 	struct vnode *a_vp;
5244 	struct uio *a_uio;
5245 	struct ucred *a_cred;
5246 	int *a_eofflag;
5247 	int *a_ncookies;
5248 	cookie_t **a_cookies;
5249 };
5250 #endif
5251 
5252 static int
zfs_freebsd_readdir(struct vop_readdir_args * ap)5253 zfs_freebsd_readdir(struct vop_readdir_args *ap)
5254 {
5255 	zfs_uio_t uio;
5256 	zfs_uio_init(&uio, ap->a_uio);
5257 	return (zfs_readdir(ap->a_vp, &uio, ap->a_cred, ap->a_eofflag,
5258 	    ap->a_ncookies, ap->a_cookies));
5259 }
5260 
5261 #ifndef _SYS_SYSPROTO_H_
5262 struct vop_fsync_args {
5263 	struct vnode *a_vp;
5264 	int a_waitfor;
5265 	struct thread *a_td;
5266 };
5267 #endif
5268 
5269 static int
zfs_freebsd_fsync(struct vop_fsync_args * ap)5270 zfs_freebsd_fsync(struct vop_fsync_args *ap)
5271 {
5272 	vnode_t *vp = ap->a_vp;
5273 	int err = 0;
5274 
5275 	/*
5276 	 * Push any dirty mmap()'d data out to the DMU and ZIL, ready for
5277 	 * zil_commit() to be called in zfs_fsync().
5278 	 */
5279 	if (vp->v_object != NULL && vm_object_mightbedirty(vp->v_object)) {
5280 		zfs_vmobject_wlock(vp->v_object);
5281 		if (!vm_object_page_clean(vp->v_object, 0, 0, 0))
5282 			err = SET_ERROR(EIO);
5283 		zfs_vmobject_wunlock(vp->v_object);
5284 		if (err) {
5285 			/*
5286 			 * Unclear what state things are in. zfs_putpages()
5287 			 * will ensure the pages remain dirty if they haven't
5288 			 * been written down to the DMU, but because there may
5289 			 * be nothing logged, we can't assume that zfs_sync()
5290 			 * -> zil_commit() will give us a useful error. It's
5291 			 *  safest if we just error out here.
5292 			 */
5293 			return (err);
5294 		}
5295 	}
5296 
5297 	return (zfs_fsync(VTOZ(vp), 0, ap->a_td->td_ucred));
5298 }
5299 
5300 #ifndef _SYS_SYSPROTO_H_
5301 struct vop_getattr_args {
5302 	struct vnode *a_vp;
5303 	struct vattr *a_vap;
5304 	struct ucred *a_cred;
5305 };
5306 #endif
5307 
5308 static int
zfs_freebsd_getattr(struct vop_getattr_args * ap)5309 zfs_freebsd_getattr(struct vop_getattr_args *ap)
5310 {
5311 	vattr_t *vap = ap->a_vap;
5312 	xvattr_t xvap;
5313 	ulong_t fflags = 0;
5314 	int error;
5315 
5316 	xva_init(&xvap);
5317 	xvap.xva_vattr = *vap;
5318 	xvap.xva_vattr.va_mask |= AT_XVATTR;
5319 
5320 	/* Convert chflags into ZFS-type flags. */
5321 	/* XXX: what about SF_SETTABLE?. */
5322 	XVA_SET_REQ(&xvap, XAT_IMMUTABLE);
5323 	XVA_SET_REQ(&xvap, XAT_APPENDONLY);
5324 	XVA_SET_REQ(&xvap, XAT_NOUNLINK);
5325 	XVA_SET_REQ(&xvap, XAT_NODUMP);
5326 	XVA_SET_REQ(&xvap, XAT_READONLY);
5327 	XVA_SET_REQ(&xvap, XAT_ARCHIVE);
5328 	XVA_SET_REQ(&xvap, XAT_SYSTEM);
5329 	XVA_SET_REQ(&xvap, XAT_HIDDEN);
5330 	XVA_SET_REQ(&xvap, XAT_REPARSE);
5331 	XVA_SET_REQ(&xvap, XAT_OFFLINE);
5332 	XVA_SET_REQ(&xvap, XAT_SPARSE);
5333 
5334 	error = zfs_getattr(ap->a_vp, (vattr_t *)&xvap, 0, ap->a_cred);
5335 	if (error != 0)
5336 		return (error);
5337 
5338 	/* Convert ZFS xattr into chflags. */
5339 #define	FLAG_CHECK(fflag, xflag, xfield)	do {			\
5340 	if (XVA_ISSET_RTN(&xvap, (xflag)) && (xfield) != 0)		\
5341 		fflags |= (fflag);					\
5342 } while (0)
5343 	FLAG_CHECK(SF_IMMUTABLE, XAT_IMMUTABLE,
5344 	    xvap.xva_xoptattrs.xoa_immutable);
5345 	FLAG_CHECK(SF_APPEND, XAT_APPENDONLY,
5346 	    xvap.xva_xoptattrs.xoa_appendonly);
5347 	FLAG_CHECK(SF_NOUNLINK, XAT_NOUNLINK,
5348 	    xvap.xva_xoptattrs.xoa_nounlink);
5349 	FLAG_CHECK(UF_ARCHIVE, XAT_ARCHIVE,
5350 	    xvap.xva_xoptattrs.xoa_archive);
5351 	FLAG_CHECK(UF_NODUMP, XAT_NODUMP,
5352 	    xvap.xva_xoptattrs.xoa_nodump);
5353 	FLAG_CHECK(UF_READONLY, XAT_READONLY,
5354 	    xvap.xva_xoptattrs.xoa_readonly);
5355 	FLAG_CHECK(UF_SYSTEM, XAT_SYSTEM,
5356 	    xvap.xva_xoptattrs.xoa_system);
5357 	FLAG_CHECK(UF_HIDDEN, XAT_HIDDEN,
5358 	    xvap.xva_xoptattrs.xoa_hidden);
5359 	FLAG_CHECK(UF_REPARSE, XAT_REPARSE,
5360 	    xvap.xva_xoptattrs.xoa_reparse);
5361 	FLAG_CHECK(UF_OFFLINE, XAT_OFFLINE,
5362 	    xvap.xva_xoptattrs.xoa_offline);
5363 	FLAG_CHECK(UF_SPARSE, XAT_SPARSE,
5364 	    xvap.xva_xoptattrs.xoa_sparse);
5365 
5366 #undef	FLAG_CHECK
5367 	*vap = xvap.xva_vattr;
5368 	vap->va_flags = fflags;
5369 
5370 #if __FreeBSD_version >= 1500040
5371 	if ((vn_irflag_read(ap->a_vp) & (VIRF_NAMEDDIR | VIRF_NAMEDATTR)) != 0)
5372 		vap->va_bsdflags |= SFBSD_NAMEDATTR;
5373 #endif
5374 	return (0);
5375 }
5376 
5377 #ifndef _SYS_SYSPROTO_H_
5378 struct vop_setattr_args {
5379 	struct vnode *a_vp;
5380 	struct vattr *a_vap;
5381 	struct ucred *a_cred;
5382 };
5383 #endif
5384 
5385 static int
zfs_freebsd_setattr(struct vop_setattr_args * ap)5386 zfs_freebsd_setattr(struct vop_setattr_args *ap)
5387 {
5388 	vnode_t *vp = ap->a_vp;
5389 	vattr_t *vap = ap->a_vap;
5390 	cred_t *cred = ap->a_cred;
5391 	xvattr_t xvap;
5392 	ulong_t fflags;
5393 	uint64_t zflags;
5394 
5395 	vattr_init_mask(vap);
5396 	vap->va_mask &= ~AT_NOSET;
5397 
5398 	xva_init(&xvap);
5399 	xvap.xva_vattr = *vap;
5400 
5401 	zflags = VTOZ(vp)->z_pflags;
5402 
5403 	if (vap->va_flags != VNOVAL) {
5404 		zfsvfs_t *zfsvfs = VTOZ(vp)->z_zfsvfs;
5405 		int error;
5406 
5407 		if (zfsvfs->z_use_fuids == B_FALSE)
5408 			return (EOPNOTSUPP);
5409 
5410 		fflags = vap->va_flags;
5411 		/*
5412 		 * XXX KDM
5413 		 * We need to figure out whether it makes sense to allow
5414 		 * UF_REPARSE through, since we don't really have other
5415 		 * facilities to handle reparse points and zfs_setattr()
5416 		 * doesn't currently allow setting that attribute anyway.
5417 		 */
5418 		if ((fflags & ~(SF_IMMUTABLE|SF_APPEND|SF_NOUNLINK|UF_ARCHIVE|
5419 		    UF_NODUMP|UF_SYSTEM|UF_HIDDEN|UF_READONLY|UF_REPARSE|
5420 		    UF_OFFLINE|UF_SPARSE)) != 0)
5421 			return (EOPNOTSUPP);
5422 		/*
5423 		 * Unprivileged processes are not permitted to unset system
5424 		 * flags, or modify flags if any system flags are set.
5425 		 * Privileged non-jail processes may not modify system flags
5426 		 * if securelevel > 0 and any existing system flags are set.
5427 		 * Privileged jail processes behave like privileged non-jail
5428 		 * processes if the PR_ALLOW_CHFLAGS permission bit is set;
5429 		 * otherwise, they behave like unprivileged processes.
5430 		 */
5431 		if (secpolicy_fs_owner(vp->v_mount, cred) == 0 ||
5432 		    priv_check_cred(cred, PRIV_VFS_SYSFLAGS) == 0) {
5433 			if (zflags &
5434 			    (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
5435 				error = securelevel_gt(cred, 0);
5436 				if (error != 0)
5437 					return (error);
5438 			}
5439 		} else {
5440 			/*
5441 			 * Callers may only modify the file flags on
5442 			 * objects they have VADMIN rights for.
5443 			 */
5444 			if ((error = VOP_ACCESS(vp, VADMIN, cred,
5445 			    curthread)) != 0)
5446 				return (error);
5447 			if (zflags &
5448 			    (ZFS_IMMUTABLE | ZFS_APPENDONLY |
5449 			    ZFS_NOUNLINK)) {
5450 				return (EPERM);
5451 			}
5452 			if (fflags &
5453 			    (SF_IMMUTABLE | SF_APPEND | SF_NOUNLINK)) {
5454 				return (EPERM);
5455 			}
5456 		}
5457 
5458 #define	FLAG_CHANGE(fflag, zflag, xflag, xfield)	do {		\
5459 	if (((fflags & (fflag)) && !(zflags & (zflag))) ||		\
5460 	    ((zflags & (zflag)) && !(fflags & (fflag)))) {		\
5461 		XVA_SET_REQ(&xvap, (xflag));				\
5462 		(xfield) = ((fflags & (fflag)) != 0);			\
5463 	}								\
5464 } while (0)
5465 		/* Convert chflags into ZFS-type flags. */
5466 		/* XXX: what about SF_SETTABLE?. */
5467 		FLAG_CHANGE(SF_IMMUTABLE, ZFS_IMMUTABLE, XAT_IMMUTABLE,
5468 		    xvap.xva_xoptattrs.xoa_immutable);
5469 		FLAG_CHANGE(SF_APPEND, ZFS_APPENDONLY, XAT_APPENDONLY,
5470 		    xvap.xva_xoptattrs.xoa_appendonly);
5471 		FLAG_CHANGE(SF_NOUNLINK, ZFS_NOUNLINK, XAT_NOUNLINK,
5472 		    xvap.xva_xoptattrs.xoa_nounlink);
5473 		FLAG_CHANGE(UF_ARCHIVE, ZFS_ARCHIVE, XAT_ARCHIVE,
5474 		    xvap.xva_xoptattrs.xoa_archive);
5475 		FLAG_CHANGE(UF_NODUMP, ZFS_NODUMP, XAT_NODUMP,
5476 		    xvap.xva_xoptattrs.xoa_nodump);
5477 		FLAG_CHANGE(UF_READONLY, ZFS_READONLY, XAT_READONLY,
5478 		    xvap.xva_xoptattrs.xoa_readonly);
5479 		FLAG_CHANGE(UF_SYSTEM, ZFS_SYSTEM, XAT_SYSTEM,
5480 		    xvap.xva_xoptattrs.xoa_system);
5481 		FLAG_CHANGE(UF_HIDDEN, ZFS_HIDDEN, XAT_HIDDEN,
5482 		    xvap.xva_xoptattrs.xoa_hidden);
5483 		FLAG_CHANGE(UF_REPARSE, ZFS_REPARSE, XAT_REPARSE,
5484 		    xvap.xva_xoptattrs.xoa_reparse);
5485 		FLAG_CHANGE(UF_OFFLINE, ZFS_OFFLINE, XAT_OFFLINE,
5486 		    xvap.xva_xoptattrs.xoa_offline);
5487 		FLAG_CHANGE(UF_SPARSE, ZFS_SPARSE, XAT_SPARSE,
5488 		    xvap.xva_xoptattrs.xoa_sparse);
5489 #undef	FLAG_CHANGE
5490 	}
5491 	if (vap->va_birthtime.tv_sec != VNOVAL) {
5492 		xvap.xva_vattr.va_mask |= AT_XVATTR;
5493 		XVA_SET_REQ(&xvap, XAT_CREATETIME);
5494 	}
5495 	return (zfs_setattr(VTOZ(vp), (vattr_t *)&xvap, 0, cred));
5496 }
5497 
5498 #ifndef _SYS_SYSPROTO_H_
5499 struct vop_rename_args {
5500 	struct vnode *a_fdvp;
5501 	struct vnode *a_fvp;
5502 	struct componentname *a_fcnp;
5503 	struct vnode *a_tdvp;
5504 	struct vnode *a_tvp;
5505 	struct componentname *a_tcnp;
5506 };
5507 #endif
5508 
5509 static int
zfs_freebsd_rename(struct vop_rename_args * ap)5510 zfs_freebsd_rename(struct vop_rename_args *ap)
5511 {
5512 	vnode_t *fdvp = ap->a_fdvp;
5513 	vnode_t *fvp = ap->a_fvp;
5514 	vnode_t *tdvp = ap->a_tdvp;
5515 	vnode_t *tvp = ap->a_tvp;
5516 	int error = 0;
5517 
5518 #if __FreeBSD_version < 1400068
5519 	ASSERT(ap->a_fcnp->cn_flags & (SAVENAME|SAVESTART));
5520 	ASSERT(ap->a_tcnp->cn_flags & (SAVENAME|SAVESTART));
5521 #endif
5522 
5523 #if __FreeBSD_version >= 1500040
5524 	if ((vn_irflag_read(fdvp) & VIRF_NAMEDDIR) != 0) {
5525 		error = zfs_check_attrname(ap->a_fcnp->cn_nameptr);
5526 		if (error == 0)
5527 			error = zfs_check_attrname(ap->a_tcnp->cn_nameptr);
5528 	}
5529 #endif
5530 
5531 	if (error == 0 && (ap->a_flags & ~(AT_RENAME_NOREPLACE)) != 0)
5532 		error = EOPNOTSUPP;
5533 
5534 	if (error == 0) {
5535 		error = zfs_do_rename(fdvp, &fvp, ap->a_fcnp, tdvp, &tvp,
5536 		    ap->a_tcnp, ap->a_fcnp->cn_cred, ap->a_flags);
5537 		vrele(fdvp);
5538 		vrele(fvp);
5539 		vrele(tdvp);
5540 		if (tvp != NULL)
5541 			vrele(tvp);
5542 	} else {
5543 		if (tdvp == tvp)
5544 			vrele(tdvp);
5545 		else
5546 			vput(tdvp);
5547 		if (tvp != NULL)
5548 			vput(tvp);
5549 		vrele(fdvp);
5550 		vrele(fvp);
5551 	}
5552 
5553 	return (error);
5554 }
5555 
5556 #ifndef _SYS_SYSPROTO_H_
5557 struct vop_symlink_args {
5558 	struct vnode *a_dvp;
5559 	struct vnode **a_vpp;
5560 	struct componentname *a_cnp;
5561 	struct vattr *a_vap;
5562 	char *a_target;
5563 };
5564 #endif
5565 
5566 static int
zfs_freebsd_symlink(struct vop_symlink_args * ap)5567 zfs_freebsd_symlink(struct vop_symlink_args *ap)
5568 {
5569 	struct componentname *cnp = ap->a_cnp;
5570 	vattr_t *vap = ap->a_vap;
5571 	znode_t *zp = NULL;
5572 	char *symlink;
5573 	size_t symlink_len;
5574 	int rc;
5575 
5576 #if __FreeBSD_version < 1400068
5577 	ASSERT(cnp->cn_flags & SAVENAME);
5578 #endif
5579 
5580 	vap->va_type = VLNK;	/* FreeBSD: Syscall only sets va_mode. */
5581 	vattr_init_mask(vap);
5582 	*ap->a_vpp = NULL;
5583 
5584 	rc = zfs_symlink(VTOZ(ap->a_dvp), cnp->cn_nameptr, vap,
5585 	    ap->a_target, &zp, cnp->cn_cred, 0 /* flags */);
5586 	if (rc == 0) {
5587 		*ap->a_vpp = ZTOV(zp);
5588 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
5589 		MPASS(zp->z_cached_symlink == NULL);
5590 		symlink_len = strlen(ap->a_target);
5591 		symlink = cache_symlink_alloc(symlink_len + 1, M_WAITOK);
5592 		if (symlink != NULL) {
5593 			memcpy(symlink, ap->a_target, symlink_len);
5594 			symlink[symlink_len] = '\0';
5595 			atomic_store_rel_ptr((uintptr_t *)&zp->z_cached_symlink,
5596 			    (uintptr_t)symlink);
5597 		}
5598 	}
5599 	return (rc);
5600 }
5601 
5602 #ifndef _SYS_SYSPROTO_H_
5603 struct vop_readlink_args {
5604 	struct vnode *a_vp;
5605 	struct uio *a_uio;
5606 	struct ucred *a_cred;
5607 };
5608 #endif
5609 
5610 static int
zfs_freebsd_readlink(struct vop_readlink_args * ap)5611 zfs_freebsd_readlink(struct vop_readlink_args *ap)
5612 {
5613 	zfs_uio_t uio;
5614 	int error;
5615 	znode_t	*zp = VTOZ(ap->a_vp);
5616 	char *symlink, *base;
5617 	size_t symlink_len;
5618 	bool trycache;
5619 
5620 	zfs_uio_init(&uio, ap->a_uio);
5621 	trycache = false;
5622 	if (zfs_uio_segflg(&uio) == UIO_SYSSPACE &&
5623 	    zfs_uio_iovcnt(&uio) == 1) {
5624 		base = zfs_uio_iovbase(&uio, 0);
5625 		symlink_len = zfs_uio_iovlen(&uio, 0);
5626 		trycache = true;
5627 	}
5628 	error = zfs_readlink(ap->a_vp, &uio, ap->a_cred, NULL);
5629 	if (atomic_load_ptr(&zp->z_cached_symlink) != NULL ||
5630 	    error != 0 || !trycache) {
5631 		return (error);
5632 	}
5633 	symlink_len -= zfs_uio_resid(&uio);
5634 	symlink = cache_symlink_alloc(symlink_len + 1, M_WAITOK);
5635 	if (symlink != NULL) {
5636 		memcpy(symlink, base, symlink_len);
5637 		symlink[symlink_len] = '\0';
5638 		if (!atomic_cmpset_rel_ptr((uintptr_t *)&zp->z_cached_symlink,
5639 		    (uintptr_t)NULL, (uintptr_t)symlink)) {
5640 			cache_symlink_free(symlink, symlink_len + 1);
5641 		}
5642 	}
5643 	return (error);
5644 }
5645 
5646 #ifndef _SYS_SYSPROTO_H_
5647 struct vop_link_args {
5648 	struct vnode *a_tdvp;
5649 	struct vnode *a_vp;
5650 	struct componentname *a_cnp;
5651 };
5652 #endif
5653 
5654 static int
zfs_freebsd_link(struct vop_link_args * ap)5655 zfs_freebsd_link(struct vop_link_args *ap)
5656 {
5657 	struct componentname *cnp = ap->a_cnp;
5658 	vnode_t *vp = ap->a_vp;
5659 	vnode_t *tdvp = ap->a_tdvp;
5660 
5661 	if (tdvp->v_mount != vp->v_mount)
5662 		return (EXDEV);
5663 
5664 #if __FreeBSD_version < 1400068
5665 	ASSERT(cnp->cn_flags & SAVENAME);
5666 #endif
5667 
5668 	return (zfs_link(VTOZ(tdvp), VTOZ(vp),
5669 	    cnp->cn_nameptr, cnp->cn_cred, 0));
5670 }
5671 
5672 #ifndef _SYS_SYSPROTO_H_
5673 struct vop_inactive_args {
5674 	struct vnode *a_vp;
5675 	struct thread *a_td;
5676 };
5677 #endif
5678 
5679 static int
zfs_freebsd_inactive(struct vop_inactive_args * ap)5680 zfs_freebsd_inactive(struct vop_inactive_args *ap)
5681 {
5682 	vnode_t *vp = ap->a_vp;
5683 
5684 	zfs_inactive(vp, curthread->td_ucred, NULL);
5685 	return (0);
5686 }
5687 
5688 #ifndef _SYS_SYSPROTO_H_
5689 struct vop_need_inactive_args {
5690 	struct vnode *a_vp;
5691 	struct thread *a_td;
5692 };
5693 #endif
5694 
5695 static int
zfs_freebsd_need_inactive(struct vop_need_inactive_args * ap)5696 zfs_freebsd_need_inactive(struct vop_need_inactive_args *ap)
5697 {
5698 	vnode_t *vp = ap->a_vp;
5699 	znode_t	*zp = VTOZ(vp);
5700 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5701 	int need;
5702 
5703 	if (vn_need_pageq_flush(vp))
5704 		return (1);
5705 
5706 	if (!ZFS_TEARDOWN_INACTIVE_TRY_ENTER_READ(zfsvfs))
5707 		return (1);
5708 	need = (zp->z_sa_hdl == NULL || zp->z_unlinked || zp->z_atime_dirty);
5709 	ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
5710 
5711 	return (need);
5712 }
5713 
5714 #ifndef _SYS_SYSPROTO_H_
5715 struct vop_reclaim_args {
5716 	struct vnode *a_vp;
5717 	struct thread *a_td;
5718 };
5719 #endif
5720 
5721 static int
zfs_freebsd_reclaim(struct vop_reclaim_args * ap)5722 zfs_freebsd_reclaim(struct vop_reclaim_args *ap)
5723 {
5724 	vnode_t	*vp = ap->a_vp;
5725 	znode_t	*zp = VTOZ(vp);
5726 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5727 
5728 	ASSERT3P(zp, !=, NULL);
5729 
5730 	/*
5731 	 * z_teardown_inactive_lock protects from a race with
5732 	 * zfs_znode_dmu_fini in zfsvfs_teardown during
5733 	 * force unmount.
5734 	 */
5735 	ZFS_TEARDOWN_INACTIVE_ENTER_READ(zfsvfs);
5736 	if (zp->z_sa_hdl == NULL)
5737 		zfs_znode_free(zp);
5738 	else
5739 		zfs_zinactive(zp);
5740 	ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
5741 
5742 	vp->v_data = NULL;
5743 	return (0);
5744 }
5745 
5746 #ifndef _SYS_SYSPROTO_H_
5747 struct vop_fid_args {
5748 	struct vnode *a_vp;
5749 	struct fid *a_fid;
5750 };
5751 #endif
5752 
5753 static int
zfs_freebsd_fid(struct vop_fid_args * ap)5754 zfs_freebsd_fid(struct vop_fid_args *ap)
5755 {
5756 
5757 	return (zfs_fid(ap->a_vp, (void *)ap->a_fid, NULL));
5758 }
5759 
5760 
5761 #ifndef _SYS_SYSPROTO_H_
5762 struct vop_pathconf_args {
5763 	struct vnode *a_vp;
5764 	int a_name;
5765 	register_t *a_retval;
5766 } *ap;
5767 #endif
5768 
5769 static int
zfs_freebsd_pathconf(struct vop_pathconf_args * ap)5770 zfs_freebsd_pathconf(struct vop_pathconf_args *ap)
5771 {
5772 	ulong_t val;
5773 	int error;
5774 #if defined(_PC_CLONE_BLKSIZE) || defined(_PC_CASE_INSENSITIVE) || \
5775 	defined(_PC_HAS_HIDDENSYSTEM)
5776 	zfsvfs_t *zfsvfs;
5777 #endif
5778 
5779 	error = zfs_pathconf(ap->a_vp, ap->a_name, &val,
5780 	    curthread->td_ucred, NULL);
5781 	if (error == 0) {
5782 		*ap->a_retval = val;
5783 		return (error);
5784 	}
5785 	if (error != EOPNOTSUPP)
5786 		return (error);
5787 
5788 	switch (ap->a_name) {
5789 	case _PC_NAME_MAX:
5790 		*ap->a_retval = NAME_MAX;
5791 		return (0);
5792 #if __FreeBSD_version >= 1400032
5793 	case _PC_DEALLOC_PRESENT:
5794 		*ap->a_retval = 1;
5795 		return (0);
5796 #endif
5797 	case _PC_PIPE_BUF:
5798 		if (ap->a_vp->v_type == VDIR || ap->a_vp->v_type == VFIFO) {
5799 			*ap->a_retval = PIPE_BUF;
5800 			return (0);
5801 		}
5802 		return (EINVAL);
5803 #if __FreeBSD_version >= 1500040
5804 	case _PC_NAMEDATTR_ENABLED:
5805 		MNT_ILOCK(ap->a_vp->v_mount);
5806 		if ((ap->a_vp->v_mount->mnt_flag & MNT_NAMEDATTR) != 0)
5807 			*ap->a_retval = 1;
5808 		else
5809 			*ap->a_retval = 0;
5810 		MNT_IUNLOCK(ap->a_vp->v_mount);
5811 		return (0);
5812 	case _PC_HAS_NAMEDATTR:
5813 		if (zfs_has_namedattr(ap->a_vp, curthread->td_ucred))
5814 			*ap->a_retval = 1;
5815 		else
5816 			*ap->a_retval = 0;
5817 		return (0);
5818 #endif
5819 #ifdef _PC_HAS_HIDDENSYSTEM
5820 	case _PC_HAS_HIDDENSYSTEM:
5821 		zfsvfs = (zfsvfs_t *)ap->a_vp->v_mount->mnt_data;
5822 		if (zfsvfs->z_use_fuids == B_TRUE)
5823 			*ap->a_retval = 1;
5824 		else
5825 			*ap->a_retval = 0;
5826 		return (0);
5827 #endif
5828 #ifdef _PC_CLONE_BLKSIZE
5829 	case _PC_CLONE_BLKSIZE:
5830 		zfsvfs = (zfsvfs_t *)ap->a_vp->v_mount->mnt_data;
5831 		if (zfs_bclone_enabled &&
5832 		    spa_feature_is_enabled(dmu_objset_spa(zfsvfs->z_os),
5833 		    SPA_FEATURE_BLOCK_CLONING))
5834 			*ap->a_retval = dsl_dataset_feature_is_active(
5835 			    zfsvfs->z_os->os_dsl_dataset,
5836 			    SPA_FEATURE_LARGE_BLOCKS) ?
5837 			    SPA_MAXBLOCKSIZE :
5838 			    SPA_OLD_MAXBLOCKSIZE;
5839 		else
5840 			*ap->a_retval = 0;
5841 		return (0);
5842 #endif
5843 #ifdef _PC_CASE_INSENSITIVE
5844 	case _PC_CASE_INSENSITIVE:
5845 		zfsvfs = (zfsvfs_t *)ap->a_vp->v_mount->mnt_data;
5846 		if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE)
5847 			*ap->a_retval = 1;
5848 		else
5849 			*ap->a_retval = 0;
5850 		return (0);
5851 #endif
5852 	default:
5853 		return (vop_stdpathconf(ap));
5854 	}
5855 }
5856 
5857 int zfs_xattr_compat = 1;
5858 
5859 static int
zfs_check_attrname(const char * name)5860 zfs_check_attrname(const char *name)
5861 {
5862 	/* We don't allow '/' character in attribute name. */
5863 	if (strchr(name, '/') != NULL)
5864 		return (SET_ERROR(EINVAL));
5865 	/* We don't allow attribute names that start with a namespace prefix. */
5866 	if (ZFS_XA_NS_PREFIX_FORBIDDEN(name))
5867 		return (SET_ERROR(EINVAL));
5868 	return (0);
5869 }
5870 
5871 /*
5872  * FreeBSD's extended attributes namespace defines file name prefix for ZFS'
5873  * extended attribute name:
5874  *
5875  *	NAMESPACE	XATTR_COMPAT	PREFIX
5876  *	system		*		freebsd:system:
5877  *	user		1		(none, can be used to access ZFS
5878  *					fsattr(5) attributes created on Solaris)
5879  *	user		0		user.
5880  */
5881 static int
zfs_create_attrname(int attrnamespace,const char * name,char * attrname,size_t size,boolean_t compat)5882 zfs_create_attrname(int attrnamespace, const char *name, char *attrname,
5883     size_t size, boolean_t compat)
5884 {
5885 	const char *namespace, *prefix, *suffix;
5886 
5887 	memset(attrname, 0, size);
5888 
5889 	switch (attrnamespace) {
5890 	case EXTATTR_NAMESPACE_USER:
5891 		if (compat) {
5892 			/*
5893 			 * This is the default namespace by which we can access
5894 			 * all attributes created on Solaris.
5895 			 */
5896 			prefix = namespace = suffix = "";
5897 		} else {
5898 			/*
5899 			 * This is compatible with the user namespace encoding
5900 			 * on Linux prior to xattr_compat, but nothing
5901 			 * else.
5902 			 */
5903 			prefix = "";
5904 			namespace = "user";
5905 			suffix = ".";
5906 		}
5907 		break;
5908 	case EXTATTR_NAMESPACE_SYSTEM:
5909 		prefix = "freebsd:";
5910 		namespace = EXTATTR_NAMESPACE_SYSTEM_STRING;
5911 		suffix = ":";
5912 		break;
5913 	case EXTATTR_NAMESPACE_EMPTY:
5914 	default:
5915 		return (SET_ERROR(EINVAL));
5916 	}
5917 	if (snprintf(attrname, size, "%s%s%s%s", prefix, namespace, suffix,
5918 	    name) >= size) {
5919 		return (SET_ERROR(ENAMETOOLONG));
5920 	}
5921 	return (0);
5922 }
5923 
5924 static int
zfs_ensure_xattr_cached(znode_t * zp)5925 zfs_ensure_xattr_cached(znode_t *zp)
5926 {
5927 	int error = 0;
5928 
5929 	ASSERT(RW_LOCK_HELD(&zp->z_xattr_lock));
5930 
5931 	if (zp->z_xattr_cached != NULL)
5932 		return (0);
5933 
5934 	if (rw_write_held(&zp->z_xattr_lock))
5935 		return (zfs_sa_get_xattr(zp));
5936 
5937 	if (!rw_tryupgrade(&zp->z_xattr_lock)) {
5938 		rw_exit(&zp->z_xattr_lock);
5939 		rw_enter(&zp->z_xattr_lock, RW_WRITER);
5940 	}
5941 	if (zp->z_xattr_cached == NULL)
5942 		error = zfs_sa_get_xattr(zp);
5943 	rw_downgrade(&zp->z_xattr_lock);
5944 	return (error);
5945 }
5946 
5947 #ifndef _SYS_SYSPROTO_H_
5948 struct vop_getextattr {
5949 	IN struct vnode *a_vp;
5950 	IN int a_attrnamespace;
5951 	IN const char *a_name;
5952 	INOUT struct uio *a_uio;
5953 	OUT size_t *a_size;
5954 	IN struct ucred *a_cred;
5955 	IN struct thread *a_td;
5956 };
5957 #endif
5958 
5959 static int
zfs_getextattr_dir(struct vop_getextattr_args * ap,const char * attrname)5960 zfs_getextattr_dir(struct vop_getextattr_args *ap, const char *attrname)
5961 {
5962 	struct thread *td = ap->a_td;
5963 	struct nameidata nd;
5964 	struct vattr va;
5965 	vnode_t *xvp = NULL, *vp;
5966 	int error, flags;
5967 
5968 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
5969 	    LOOKUP_XATTR, B_FALSE);
5970 	if (error != 0)
5971 		return (error);
5972 
5973 	flags = FREAD;
5974 #if __FreeBSD_version < 1400043
5975 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname,
5976 	    xvp, td);
5977 #else
5978 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname, xvp);
5979 #endif
5980 	error = vn_open_cred(&nd, &flags, 0, VN_OPEN_INVFS, ap->a_cred, NULL);
5981 	if (error != 0)
5982 		return (SET_ERROR(error));
5983 	vp = nd.ni_vp;
5984 	NDFREE_PNBUF(&nd);
5985 
5986 	if (ap->a_size != NULL) {
5987 		error = VOP_GETATTR(vp, &va, ap->a_cred);
5988 		if (error == 0)
5989 			*ap->a_size = (size_t)va.va_size;
5990 	} else if (ap->a_uio != NULL)
5991 		error = VOP_READ(vp, ap->a_uio, IO_UNIT, ap->a_cred);
5992 
5993 	VOP_UNLOCK(vp);
5994 	vn_close(vp, flags, ap->a_cred, td);
5995 	return (error);
5996 }
5997 
5998 static int
zfs_getextattr_sa(struct vop_getextattr_args * ap,const char * attrname)5999 zfs_getextattr_sa(struct vop_getextattr_args *ap, const char *attrname)
6000 {
6001 	znode_t *zp = VTOZ(ap->a_vp);
6002 	uchar_t *nv_value;
6003 	uint_t nv_size;
6004 	int error;
6005 
6006 	error = zfs_ensure_xattr_cached(zp);
6007 	if (error != 0)
6008 		return (error);
6009 
6010 	ASSERT(RW_LOCK_HELD(&zp->z_xattr_lock));
6011 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6012 
6013 	error = nvlist_lookup_byte_array(zp->z_xattr_cached, attrname,
6014 	    &nv_value, &nv_size);
6015 	if (error != 0)
6016 		return (SET_ERROR(error));
6017 
6018 	if (ap->a_size != NULL)
6019 		*ap->a_size = nv_size;
6020 	else if (ap->a_uio != NULL)
6021 		error = uiomove(nv_value, nv_size, ap->a_uio);
6022 	if (error != 0)
6023 		return (SET_ERROR(error));
6024 
6025 	return (0);
6026 }
6027 
6028 static int
zfs_getextattr_impl(struct vop_getextattr_args * ap,boolean_t compat)6029 zfs_getextattr_impl(struct vop_getextattr_args *ap, boolean_t compat)
6030 {
6031 	znode_t *zp = VTOZ(ap->a_vp);
6032 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6033 	char attrname[EXTATTR_MAXNAMELEN+1];
6034 	int error;
6035 
6036 	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6037 	    sizeof (attrname), compat);
6038 	if (error != 0)
6039 		return (error);
6040 
6041 	error = ENOENT;
6042 	if (zfsvfs->z_use_sa && zp->z_is_sa)
6043 		error = zfs_getextattr_sa(ap, attrname);
6044 	if (error == ENOENT && !zp->z_xattr_dir_absent)
6045 		error = zfs_getextattr_dir(ap, attrname);
6046 	return (error);
6047 }
6048 
6049 /*
6050  * Vnode operation to retrieve a named extended attribute.
6051  */
6052 static int
zfs_getextattr(struct vop_getextattr_args * ap)6053 zfs_getextattr(struct vop_getextattr_args *ap)
6054 {
6055 	znode_t *zp = VTOZ(ap->a_vp);
6056 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6057 	int error;
6058 
6059 	/*
6060 	 * If the xattr property is off, refuse the request.
6061 	 */
6062 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6063 		return (SET_ERROR(EOPNOTSUPP));
6064 
6065 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6066 	    ap->a_cred, ap->a_td, VREAD);
6067 	if (error != 0)
6068 		return (SET_ERROR(error));
6069 
6070 	error = zfs_check_attrname(ap->a_name);
6071 	if (error != 0)
6072 		return (error);
6073 
6074 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6075 		return (error);
6076 	error = ENOENT;
6077 	rw_enter(&zp->z_xattr_lock, RW_READER);
6078 
6079 	error = zfs_getextattr_impl(ap, zfs_xattr_compat);
6080 	if ((error == ENOENT || error == ENOATTR) &&
6081 	    ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6082 		/*
6083 		 * Fall back to the alternate namespace format if we failed to
6084 		 * find a user xattr.
6085 		 */
6086 		error = zfs_getextattr_impl(ap, !zfs_xattr_compat);
6087 	}
6088 
6089 	rw_exit(&zp->z_xattr_lock);
6090 	zfs_exit(zfsvfs, FTAG);
6091 	if (error == ENOENT)
6092 		error = SET_ERROR(ENOATTR);
6093 	return (error);
6094 }
6095 
6096 #ifndef _SYS_SYSPROTO_H_
6097 struct vop_deleteextattr {
6098 	IN struct vnode *a_vp;
6099 	IN int a_attrnamespace;
6100 	IN const char *a_name;
6101 	IN struct ucred *a_cred;
6102 	IN struct thread *a_td;
6103 };
6104 #endif
6105 
6106 static int
zfs_deleteextattr_dir(struct vop_deleteextattr_args * ap,const char * attrname)6107 zfs_deleteextattr_dir(struct vop_deleteextattr_args *ap, const char *attrname)
6108 {
6109 	struct nameidata nd;
6110 	vnode_t *xvp = NULL, *vp;
6111 	int error;
6112 
6113 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
6114 	    LOOKUP_XATTR, B_FALSE);
6115 	if (error != 0)
6116 		return (error);
6117 
6118 #if __FreeBSD_version < 1400043
6119 	NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF,
6120 	    UIO_SYSSPACE, attrname, xvp, ap->a_td);
6121 #else
6122 	NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF,
6123 	    UIO_SYSSPACE, attrname, xvp);
6124 #endif
6125 	error = namei(&nd);
6126 	if (error != 0)
6127 		return (SET_ERROR(error));
6128 
6129 	vp = nd.ni_vp;
6130 	error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
6131 	NDFREE_PNBUF(&nd);
6132 
6133 	vput(nd.ni_dvp);
6134 	if (vp == nd.ni_dvp)
6135 		vrele(vp);
6136 	else
6137 		vput(vp);
6138 
6139 	return (error);
6140 }
6141 
6142 static int
zfs_deleteextattr_sa(struct vop_deleteextattr_args * ap,const char * attrname)6143 zfs_deleteextattr_sa(struct vop_deleteextattr_args *ap, const char *attrname)
6144 {
6145 	znode_t *zp = VTOZ(ap->a_vp);
6146 	nvlist_t *nvl;
6147 	int error;
6148 
6149 	error = zfs_ensure_xattr_cached(zp);
6150 	if (error != 0)
6151 		return (error);
6152 
6153 	ASSERT(RW_WRITE_HELD(&zp->z_xattr_lock));
6154 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6155 
6156 	nvl = zp->z_xattr_cached;
6157 	error = nvlist_remove(nvl, attrname, DATA_TYPE_BYTE_ARRAY);
6158 	if (error != 0)
6159 		error = SET_ERROR(error);
6160 	else
6161 		error = zfs_sa_set_xattr(zp, attrname, NULL, 0);
6162 	if (error != 0) {
6163 		zp->z_xattr_cached = NULL;
6164 		nvlist_free(nvl);
6165 	}
6166 	return (error);
6167 }
6168 
6169 static int
zfs_deleteextattr_impl(struct vop_deleteextattr_args * ap,boolean_t compat)6170 zfs_deleteextattr_impl(struct vop_deleteextattr_args *ap, boolean_t compat)
6171 {
6172 	znode_t *zp = VTOZ(ap->a_vp);
6173 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6174 	char attrname[EXTATTR_MAXNAMELEN+1];
6175 	int error;
6176 
6177 	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6178 	    sizeof (attrname), compat);
6179 	if (error != 0)
6180 		return (error);
6181 
6182 	error = ENOENT;
6183 	if (zfsvfs->z_use_sa && zp->z_is_sa)
6184 		error = zfs_deleteextattr_sa(ap, attrname);
6185 	if (error == ENOENT)
6186 		error = zfs_deleteextattr_dir(ap, attrname);
6187 	return (error);
6188 }
6189 
6190 /*
6191  * Vnode operation to remove a named attribute.
6192  */
6193 static int
zfs_deleteextattr(struct vop_deleteextattr_args * ap)6194 zfs_deleteextattr(struct vop_deleteextattr_args *ap)
6195 {
6196 	znode_t *zp = VTOZ(ap->a_vp);
6197 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6198 	int error;
6199 
6200 	/*
6201 	 * If the xattr property is off, refuse the request.
6202 	 */
6203 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6204 		return (SET_ERROR(EOPNOTSUPP));
6205 
6206 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6207 	    ap->a_cred, ap->a_td, VWRITE);
6208 	if (error != 0)
6209 		return (SET_ERROR(error));
6210 
6211 	error = zfs_check_attrname(ap->a_name);
6212 	if (error != 0)
6213 		return (error);
6214 
6215 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6216 		return (error);
6217 	rw_enter(&zp->z_xattr_lock, RW_WRITER);
6218 
6219 	error = zfs_deleteextattr_impl(ap, zfs_xattr_compat);
6220 	if ((error == ENOENT || error == ENOATTR) &&
6221 	    ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6222 		/*
6223 		 * Fall back to the alternate namespace format if we failed to
6224 		 * find a user xattr.
6225 		 */
6226 		error = zfs_deleteextattr_impl(ap, !zfs_xattr_compat);
6227 	}
6228 
6229 	rw_exit(&zp->z_xattr_lock);
6230 	zfs_exit(zfsvfs, FTAG);
6231 	if (error == ENOENT)
6232 		error = SET_ERROR(ENOATTR);
6233 	return (error);
6234 }
6235 
6236 #ifndef _SYS_SYSPROTO_H_
6237 struct vop_setextattr {
6238 	IN struct vnode *a_vp;
6239 	IN int a_attrnamespace;
6240 	IN const char *a_name;
6241 	INOUT struct uio *a_uio;
6242 	IN struct ucred *a_cred;
6243 	IN struct thread *a_td;
6244 };
6245 #endif
6246 
6247 static int
zfs_setextattr_dir(struct vop_setextattr_args * ap,const char * attrname)6248 zfs_setextattr_dir(struct vop_setextattr_args *ap, const char *attrname)
6249 {
6250 	struct thread *td = ap->a_td;
6251 	struct nameidata nd;
6252 	struct vattr va;
6253 	vnode_t *xvp = NULL, *vp;
6254 	int error, flags;
6255 
6256 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
6257 	    LOOKUP_XATTR | CREATE_XATTR_DIR, B_FALSE);
6258 	if (error != 0)
6259 		return (error);
6260 
6261 	flags = FFLAGS(O_WRONLY | O_CREAT);
6262 #if __FreeBSD_version < 1400043
6263 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname, xvp, td);
6264 #else
6265 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname, xvp);
6266 #endif
6267 	error = vn_open_cred(&nd, &flags, 0600, VN_OPEN_INVFS, ap->a_cred,
6268 	    NULL);
6269 	if (error != 0)
6270 		return (SET_ERROR(error));
6271 	vp = nd.ni_vp;
6272 	NDFREE_PNBUF(&nd);
6273 
6274 	VATTR_NULL(&va);
6275 	va.va_size = 0;
6276 	error = VOP_SETATTR(vp, &va, ap->a_cred);
6277 	if (error == 0)
6278 		VOP_WRITE(vp, ap->a_uio, IO_UNIT, ap->a_cred);
6279 
6280 	VOP_UNLOCK(vp);
6281 	vn_close(vp, flags, ap->a_cred, td);
6282 	return (error);
6283 }
6284 
6285 static int
zfs_setextattr_sa(struct vop_setextattr_args * ap,const char * attrname)6286 zfs_setextattr_sa(struct vop_setextattr_args *ap, const char *attrname)
6287 {
6288 	znode_t *zp = VTOZ(ap->a_vp);
6289 	nvlist_t *nvl;
6290 	size_t sa_size;
6291 	int error;
6292 
6293 	error = zfs_ensure_xattr_cached(zp);
6294 	if (error != 0)
6295 		return (error);
6296 
6297 	ASSERT(RW_WRITE_HELD(&zp->z_xattr_lock));
6298 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6299 
6300 	nvl = zp->z_xattr_cached;
6301 	size_t entry_size = ap->a_uio->uio_resid;
6302 	if (entry_size > DXATTR_MAX_ENTRY_SIZE)
6303 		return (SET_ERROR(EFBIG));
6304 	error = nvlist_size(nvl, &sa_size, NV_ENCODE_XDR);
6305 	if (error != 0)
6306 		return (SET_ERROR(error));
6307 	if (sa_size > DXATTR_MAX_SA_SIZE)
6308 		return (SET_ERROR(EFBIG));
6309 	uchar_t *buf = kmem_alloc(entry_size, KM_SLEEP);
6310 	error = uiomove(buf, entry_size, ap->a_uio);
6311 	if (error != 0) {
6312 		error = SET_ERROR(error);
6313 	} else {
6314 		error = nvlist_add_byte_array(nvl, attrname, buf, entry_size);
6315 		if (error != 0)
6316 			error = SET_ERROR(error);
6317 	}
6318 	if (error == 0)
6319 		error = zfs_sa_set_xattr(zp, attrname, buf, entry_size);
6320 	kmem_free(buf, entry_size);
6321 	if (error != 0) {
6322 		zp->z_xattr_cached = NULL;
6323 		nvlist_free(nvl);
6324 	}
6325 	return (error);
6326 }
6327 
6328 static int
zfs_setextattr_impl(struct vop_setextattr_args * ap,boolean_t compat)6329 zfs_setextattr_impl(struct vop_setextattr_args *ap, boolean_t compat)
6330 {
6331 	znode_t *zp = VTOZ(ap->a_vp);
6332 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6333 	char attrname[EXTATTR_MAXNAMELEN+1];
6334 	int error;
6335 
6336 	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6337 	    sizeof (attrname), compat);
6338 	if (error != 0)
6339 		return (error);
6340 
6341 	struct vop_deleteextattr_args vda = {
6342 		.a_vp = ap->a_vp,
6343 		.a_attrnamespace = ap->a_attrnamespace,
6344 		.a_name = ap->a_name,
6345 		.a_cred = ap->a_cred,
6346 		.a_td = ap->a_td,
6347 	};
6348 	error = ENOENT;
6349 	if (zfsvfs->z_use_sa && zp->z_is_sa && zfsvfs->z_xattr_sa) {
6350 		error = zfs_setextattr_sa(ap, attrname);
6351 		if (error == 0) {
6352 			/*
6353 			 * Successfully put into SA, we need to clear the one
6354 			 * in dir if present.
6355 			 */
6356 			zfs_deleteextattr_dir(&vda, attrname);
6357 		}
6358 	}
6359 	if (error != 0) {
6360 		error = zfs_setextattr_dir(ap, attrname);
6361 		if (error == 0 && zp->z_is_sa) {
6362 			/*
6363 			 * Successfully put into dir, we need to clear the one
6364 			 * in SA if present.
6365 			 */
6366 			zfs_deleteextattr_sa(&vda, attrname);
6367 		}
6368 	}
6369 	if (error == 0 && ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6370 		/*
6371 		 * Also clear all versions of the alternate compat name.
6372 		 */
6373 		zfs_deleteextattr_impl(&vda, !compat);
6374 	}
6375 	return (error);
6376 }
6377 
6378 /*
6379  * Vnode operation to set a named attribute.
6380  */
6381 static int
zfs_setextattr(struct vop_setextattr_args * ap)6382 zfs_setextattr(struct vop_setextattr_args *ap)
6383 {
6384 	znode_t *zp = VTOZ(ap->a_vp);
6385 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6386 	int error;
6387 
6388 	/*
6389 	 * If the xattr property is off, refuse the request.
6390 	 */
6391 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6392 		return (SET_ERROR(EOPNOTSUPP));
6393 
6394 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6395 	    ap->a_cred, ap->a_td, VWRITE);
6396 	if (error != 0)
6397 		return (SET_ERROR(error));
6398 
6399 	error = zfs_check_attrname(ap->a_name);
6400 	if (error != 0)
6401 		return (error);
6402 
6403 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6404 		return (error);
6405 	rw_enter(&zp->z_xattr_lock, RW_WRITER);
6406 
6407 	error = zfs_setextattr_impl(ap, zfs_xattr_compat);
6408 
6409 	rw_exit(&zp->z_xattr_lock);
6410 	zfs_exit(zfsvfs, FTAG);
6411 	return (error);
6412 }
6413 
6414 #ifndef _SYS_SYSPROTO_H_
6415 struct vop_listextattr {
6416 	IN struct vnode *a_vp;
6417 	IN int a_attrnamespace;
6418 	INOUT struct uio *a_uio;
6419 	OUT size_t *a_size;
6420 	IN struct ucred *a_cred;
6421 	IN struct thread *a_td;
6422 };
6423 #endif
6424 
6425 static int
zfs_listextattr_dir(struct vop_listextattr_args * ap,const char * attrprefix)6426 zfs_listextattr_dir(struct vop_listextattr_args *ap, const char *attrprefix)
6427 {
6428 	struct thread *td = ap->a_td;
6429 	struct nameidata nd;
6430 	uint8_t dirbuf[sizeof (struct dirent)];
6431 	struct iovec aiov;
6432 	struct uio auio;
6433 	vnode_t *xvp = NULL, *vp;
6434 	int error, eof;
6435 
6436 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
6437 	    LOOKUP_XATTR, B_FALSE);
6438 	if (error != 0) {
6439 		/*
6440 		 * ENOATTR means that the EA directory does not yet exist,
6441 		 * i.e. there are no extended attributes there.
6442 		 */
6443 		if (error == ENOATTR)
6444 			error = 0;
6445 		return (error);
6446 	}
6447 
6448 #if __FreeBSD_version < 1400043
6449 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED,
6450 	    UIO_SYSSPACE, ".", xvp, td);
6451 #else
6452 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED,
6453 	    UIO_SYSSPACE, ".", xvp);
6454 #endif
6455 	error = namei(&nd);
6456 	if (error != 0)
6457 		return (SET_ERROR(error));
6458 	vp = nd.ni_vp;
6459 	NDFREE_PNBUF(&nd);
6460 
6461 	auio.uio_iov = &aiov;
6462 	auio.uio_iovcnt = 1;
6463 	auio.uio_segflg = UIO_SYSSPACE;
6464 	auio.uio_td = td;
6465 	auio.uio_rw = UIO_READ;
6466 	auio.uio_offset = 0;
6467 
6468 	size_t plen = strlen(attrprefix);
6469 
6470 	do {
6471 		aiov.iov_base = (void *)dirbuf;
6472 		aiov.iov_len = sizeof (dirbuf);
6473 		auio.uio_resid = sizeof (dirbuf);
6474 		error = VOP_READDIR(vp, &auio, ap->a_cred, &eof, NULL, NULL);
6475 		if (error != 0)
6476 			break;
6477 		int done = sizeof (dirbuf) - auio.uio_resid;
6478 		for (int pos = 0; pos < done; ) {
6479 			struct dirent *dp = (struct dirent *)(dirbuf + pos);
6480 			pos += dp->d_reclen;
6481 			/*
6482 			 * XXX: Temporarily we also accept DT_UNKNOWN, as this
6483 			 * is what we get when attribute was created on Solaris.
6484 			 */
6485 			if (dp->d_type != DT_REG && dp->d_type != DT_UNKNOWN)
6486 				continue;
6487 			else if (plen == 0 &&
6488 			    ZFS_XA_NS_PREFIX_FORBIDDEN(dp->d_name))
6489 				continue;
6490 			else if (strncmp(dp->d_name, attrprefix, plen) != 0)
6491 				continue;
6492 			uint8_t nlen = dp->d_namlen - plen;
6493 			if (ap->a_size != NULL) {
6494 				*ap->a_size += 1 + nlen;
6495 			} else if (ap->a_uio != NULL) {
6496 				/*
6497 				 * Format of extattr name entry is one byte for
6498 				 * length and the rest for name.
6499 				 */
6500 				error = uiomove(&nlen, 1, ap->a_uio);
6501 				if (error == 0) {
6502 					char *namep = dp->d_name + plen;
6503 					error = uiomove(namep, nlen, ap->a_uio);
6504 				}
6505 				if (error != 0) {
6506 					error = SET_ERROR(error);
6507 					break;
6508 				}
6509 			}
6510 		}
6511 	} while (!eof && error == 0);
6512 
6513 	vput(vp);
6514 	return (error);
6515 }
6516 
6517 static int
zfs_listextattr_sa(struct vop_listextattr_args * ap,const char * attrprefix)6518 zfs_listextattr_sa(struct vop_listextattr_args *ap, const char *attrprefix)
6519 {
6520 	znode_t *zp = VTOZ(ap->a_vp);
6521 	int error;
6522 
6523 	error = zfs_ensure_xattr_cached(zp);
6524 	if (error != 0)
6525 		return (error);
6526 
6527 	ASSERT(RW_LOCK_HELD(&zp->z_xattr_lock));
6528 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6529 
6530 	size_t plen = strlen(attrprefix);
6531 	nvpair_t *nvp = NULL;
6532 	while ((nvp = nvlist_next_nvpair(zp->z_xattr_cached, nvp)) != NULL) {
6533 		ASSERT3U(nvpair_type(nvp), ==, DATA_TYPE_BYTE_ARRAY);
6534 
6535 		const char *name = nvpair_name(nvp);
6536 		if (plen == 0 && ZFS_XA_NS_PREFIX_FORBIDDEN(name))
6537 			continue;
6538 		else if (strncmp(name, attrprefix, plen) != 0)
6539 			continue;
6540 		uint8_t nlen = strlen(name) - plen;
6541 		if (ap->a_size != NULL) {
6542 			*ap->a_size += 1 + nlen;
6543 		} else if (ap->a_uio != NULL) {
6544 			/*
6545 			 * Format of extattr name entry is one byte for
6546 			 * length and the rest for name.
6547 			 */
6548 			error = uiomove(&nlen, 1, ap->a_uio);
6549 			if (error == 0) {
6550 				char *namep = __DECONST(char *, name) + plen;
6551 				error = uiomove(namep, nlen, ap->a_uio);
6552 			}
6553 			if (error != 0) {
6554 				error = SET_ERROR(error);
6555 				break;
6556 			}
6557 		}
6558 	}
6559 
6560 	return (error);
6561 }
6562 
6563 static int
zfs_listextattr_impl(struct vop_listextattr_args * ap,boolean_t compat)6564 zfs_listextattr_impl(struct vop_listextattr_args *ap, boolean_t compat)
6565 {
6566 	znode_t *zp = VTOZ(ap->a_vp);
6567 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6568 	char attrprefix[16];
6569 	int error;
6570 
6571 	error = zfs_create_attrname(ap->a_attrnamespace, "", attrprefix,
6572 	    sizeof (attrprefix), compat);
6573 	if (error != 0)
6574 		return (error);
6575 
6576 	if (zfsvfs->z_use_sa && zp->z_is_sa)
6577 		error = zfs_listextattr_sa(ap, attrprefix);
6578 	if (error == 0)
6579 		error = zfs_listextattr_dir(ap, attrprefix);
6580 	return (error);
6581 }
6582 
6583 /*
6584  * Vnode operation to retrieve extended attributes on a vnode.
6585  */
6586 static int
zfs_listextattr(struct vop_listextattr_args * ap)6587 zfs_listextattr(struct vop_listextattr_args *ap)
6588 {
6589 	znode_t *zp = VTOZ(ap->a_vp);
6590 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6591 	int error;
6592 
6593 	if (ap->a_size != NULL)
6594 		*ap->a_size = 0;
6595 
6596 	/*
6597 	 * If the xattr property is off, refuse the request.
6598 	 */
6599 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6600 		return (SET_ERROR(EOPNOTSUPP));
6601 
6602 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6603 	    ap->a_cred, ap->a_td, VREAD);
6604 	if (error != 0)
6605 		return (SET_ERROR(error));
6606 
6607 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6608 		return (error);
6609 	rw_enter(&zp->z_xattr_lock, RW_READER);
6610 
6611 	error = zfs_listextattr_impl(ap, zfs_xattr_compat);
6612 	if (error == 0 && ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6613 		/* Also list user xattrs with the alternate format. */
6614 		error = zfs_listextattr_impl(ap, !zfs_xattr_compat);
6615 	}
6616 
6617 	rw_exit(&zp->z_xattr_lock);
6618 	zfs_exit(zfsvfs, FTAG);
6619 	return (error);
6620 }
6621 
6622 #ifndef _SYS_SYSPROTO_H_
6623 struct vop_getacl_args {
6624 	struct vnode *vp;
6625 	acl_type_t type;
6626 	struct acl *aclp;
6627 	struct ucred *cred;
6628 	struct thread *td;
6629 };
6630 #endif
6631 
6632 static int
zfs_freebsd_getacl(struct vop_getacl_args * ap)6633 zfs_freebsd_getacl(struct vop_getacl_args *ap)
6634 {
6635 	int		error;
6636 	vsecattr_t	vsecattr;
6637 
6638 	if (ap->a_type != ACL_TYPE_NFS4)
6639 		return (EINVAL);
6640 
6641 	vsecattr.vsa_mask = VSA_ACE | VSA_ACECNT;
6642 	if ((error = zfs_getsecattr(VTOZ(ap->a_vp),
6643 	    &vsecattr, 0, ap->a_cred)))
6644 		return (error);
6645 
6646 	error = acl_from_aces(ap->a_aclp, vsecattr.vsa_aclentp,
6647 	    vsecattr.vsa_aclcnt);
6648 	if (vsecattr.vsa_aclentp != NULL)
6649 		kmem_free(vsecattr.vsa_aclentp, vsecattr.vsa_aclentsz);
6650 
6651 	return (error);
6652 }
6653 
6654 #ifndef _SYS_SYSPROTO_H_
6655 struct vop_setacl_args {
6656 	struct vnode *vp;
6657 	acl_type_t type;
6658 	struct acl *aclp;
6659 	struct ucred *cred;
6660 	struct thread *td;
6661 };
6662 #endif
6663 
6664 static int
zfs_freebsd_setacl(struct vop_setacl_args * ap)6665 zfs_freebsd_setacl(struct vop_setacl_args *ap)
6666 {
6667 	int		error;
6668 	vsecattr_t vsecattr;
6669 	int		aclbsize;	/* size of acl list in bytes */
6670 	aclent_t	*aaclp;
6671 
6672 	if (ap->a_type != ACL_TYPE_NFS4)
6673 		return (EINVAL);
6674 
6675 	if (ap->a_aclp == NULL)
6676 		return (EINVAL);
6677 
6678 	if (ap->a_aclp->acl_cnt < 1 || ap->a_aclp->acl_cnt > MAX_ACL_ENTRIES)
6679 		return (EINVAL);
6680 
6681 	/*
6682 	 * With NFSv4 ACLs, chmod(2) may need to add additional entries,
6683 	 * splitting every entry into two and appending "canonical six"
6684 	 * entries at the end.  Don't allow for setting an ACL that would
6685 	 * cause chmod(2) to run out of ACL entries.
6686 	 */
6687 	if (ap->a_aclp->acl_cnt * 2 + 6 > ACL_MAX_ENTRIES)
6688 		return (ENOSPC);
6689 
6690 	error = acl_nfs4_check(ap->a_aclp, ap->a_vp->v_type == VDIR);
6691 	if (error != 0)
6692 		return (error);
6693 
6694 	vsecattr.vsa_mask = VSA_ACE;
6695 	aclbsize = ap->a_aclp->acl_cnt * sizeof (ace_t);
6696 	vsecattr.vsa_aclentp = kmem_alloc(aclbsize, KM_SLEEP);
6697 	aaclp = vsecattr.vsa_aclentp;
6698 	vsecattr.vsa_aclentsz = aclbsize;
6699 
6700 	aces_from_acl(vsecattr.vsa_aclentp, &vsecattr.vsa_aclcnt, ap->a_aclp);
6701 	error = zfs_setsecattr(VTOZ(ap->a_vp), &vsecattr, 0, ap->a_cred);
6702 	kmem_free(aaclp, aclbsize);
6703 
6704 	return (error);
6705 }
6706 
6707 #ifndef _SYS_SYSPROTO_H_
6708 struct vop_aclcheck_args {
6709 	struct vnode *vp;
6710 	acl_type_t type;
6711 	struct acl *aclp;
6712 	struct ucred *cred;
6713 	struct thread *td;
6714 };
6715 #endif
6716 
6717 static int
zfs_freebsd_aclcheck(struct vop_aclcheck_args * ap)6718 zfs_freebsd_aclcheck(struct vop_aclcheck_args *ap)
6719 {
6720 
6721 	return (EOPNOTSUPP);
6722 }
6723 
6724 #ifndef _SYS_SYSPROTO_H_
6725 struct vop_advise_args {
6726 	struct vnode *a_vp;
6727 	off_t a_start;
6728 	off_t a_end;
6729 	int a_advice;
6730 };
6731 #endif
6732 
6733 static int
zfs_freebsd_advise(struct vop_advise_args * ap)6734 zfs_freebsd_advise(struct vop_advise_args *ap)
6735 {
6736 	vnode_t *vp = ap->a_vp;
6737 	off_t start = ap->a_start;
6738 	off_t end = ap->a_end;
6739 	int advice = ap->a_advice;
6740 	off_t len;
6741 	znode_t *zp;
6742 	zfsvfs_t *zfsvfs;
6743 	objset_t *os;
6744 	int error = 0;
6745 
6746 	if (end < start)
6747 		return (EINVAL);
6748 
6749 	error = vn_lock(vp, LK_SHARED);
6750 	if (error)
6751 		return (error);
6752 
6753 	zp = VTOZ(vp);
6754 	zfsvfs = zp->z_zfsvfs;
6755 	os = zp->z_zfsvfs->z_os;
6756 
6757 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6758 		goto out_unlock;
6759 
6760 	/* kern_posix_fadvise points to the last byte, we want one past */
6761 	if (end != OFF_MAX)
6762 		end += 1;
6763 	len = end - start;
6764 
6765 	switch (advice) {
6766 	case POSIX_FADV_WILLNEED:
6767 		/*
6768 		 * Pass on the caller's size directly, but note that
6769 		 * dmu_prefetch_max will effectively cap it.  If there really
6770 		 * is a larger sequential access pattern, perhaps dmu_zfetch
6771 		 * will detect it.
6772 		 */
6773 		dmu_prefetch_user(os, zp->z_id, 0, start, len,
6774 		    ZIO_PRIORITY_ASYNC_READ);
6775 		break;
6776 	case POSIX_FADV_DONTNEED:
6777 		dmu_evict_range(os, zp->z_id, start, len);
6778 		break;
6779 	case POSIX_FADV_NORMAL:
6780 	case POSIX_FADV_RANDOM:
6781 	case POSIX_FADV_SEQUENTIAL:
6782 	case POSIX_FADV_NOREUSE:
6783 		/* ignored for now */
6784 		break;
6785 	default:
6786 		error = EINVAL;
6787 		break;
6788 	}
6789 
6790 	zfs_exit(zfsvfs, FTAG);
6791 
6792 out_unlock:
6793 	VOP_UNLOCK(vp);
6794 
6795 	return (error);
6796 }
6797 
6798 static int
zfs_vptocnp(struct vop_vptocnp_args * ap)6799 zfs_vptocnp(struct vop_vptocnp_args *ap)
6800 {
6801 	vnode_t *covered_vp;
6802 	vnode_t *vp = ap->a_vp;
6803 	zfsvfs_t *zfsvfs = vp->v_vfsp->vfs_data;
6804 	znode_t *zp = VTOZ(vp);
6805 	int ltype;
6806 	int error;
6807 
6808 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6809 		return (error);
6810 
6811 	/*
6812 	 * If we are a snapshot mounted under .zfs, run the operation
6813 	 * on the covered vnode.
6814 	 */
6815 	if (zp->z_id != zfsvfs->z_root || zfsvfs->z_parent == zfsvfs) {
6816 		char name[MAXNAMLEN + 1];
6817 		znode_t *dzp;
6818 		size_t len;
6819 
6820 		error = zfs_znode_parent_and_name(zp, &dzp, name,
6821 		    sizeof (name));
6822 		if (error == 0) {
6823 			len = strlen(name);
6824 			if (*ap->a_buflen < len)
6825 				error = SET_ERROR(ENOMEM);
6826 		}
6827 		if (error == 0) {
6828 			*ap->a_buflen -= len;
6829 			memcpy(ap->a_buf + *ap->a_buflen, name, len);
6830 			*ap->a_vpp = ZTOV(dzp);
6831 		}
6832 		zfs_exit(zfsvfs, FTAG);
6833 		return (error);
6834 	}
6835 	zfs_exit(zfsvfs, FTAG);
6836 
6837 	covered_vp = vp->v_mount->mnt_vnodecovered;
6838 	enum vgetstate vs = vget_prep(covered_vp);
6839 	ltype = VOP_ISLOCKED(vp);
6840 	VOP_UNLOCK(vp);
6841 	error = vget_finish(covered_vp, LK_SHARED, vs);
6842 	if (error == 0) {
6843 		error = VOP_VPTOCNP(covered_vp, ap->a_vpp, ap->a_buf,
6844 		    ap->a_buflen);
6845 		vput(covered_vp);
6846 	}
6847 	vn_lock(vp, ltype | LK_RETRY);
6848 	if (VN_IS_DOOMED(vp))
6849 		error = SET_ERROR(ENOENT);
6850 	return (error);
6851 }
6852 
6853 #if __FreeBSD_version >= 1400032
6854 static int
zfs_deallocate(struct vop_deallocate_args * ap)6855 zfs_deallocate(struct vop_deallocate_args *ap)
6856 {
6857 	znode_t *zp = VTOZ(ap->a_vp);
6858 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
6859 	zilog_t *zilog;
6860 	off_t off, len, file_sz;
6861 	int error;
6862 
6863 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6864 		return (error);
6865 
6866 	/*
6867 	 * Callers might not be able to detect properly that we are read-only,
6868 	 * so check it explicitly here.
6869 	 */
6870 	if (zfs_is_readonly(zfsvfs)) {
6871 		zfs_exit(zfsvfs, FTAG);
6872 		return (SET_ERROR(EROFS));
6873 	}
6874 
6875 	zilog = zfsvfs->z_log;
6876 	off = *ap->a_offset;
6877 	len = *ap->a_len;
6878 	file_sz = zp->z_size;
6879 	if (off + len > file_sz)
6880 		len = file_sz - off;
6881 	/* Fast path for out-of-range request. */
6882 	if (len <= 0) {
6883 		*ap->a_len = 0;
6884 		zfs_exit(zfsvfs, FTAG);
6885 		return (0);
6886 	}
6887 
6888 	error = zfs_freesp(zp, off, len, O_RDWR, TRUE);
6889 	if (error == 0) {
6890 		if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS ||
6891 		    (ap->a_ioflag & IO_SYNC) != 0)
6892 			error = zil_commit(zilog, zp->z_id);
6893 		if (error == 0) {
6894 			*ap->a_offset = off + len;
6895 			*ap->a_len = 0;
6896 		}
6897 	}
6898 
6899 	zfs_exit(zfsvfs, FTAG);
6900 	return (error);
6901 }
6902 #endif
6903 
6904 #ifndef _SYS_SYSPROTO_H_
6905 struct vop_copy_file_range_args {
6906 	struct vnode *a_invp;
6907 	off_t *a_inoffp;
6908 	struct vnode *a_outvp;
6909 	off_t *a_outoffp;
6910 	size_t *a_lenp;
6911 	unsigned int a_flags;
6912 	struct ucred *a_incred;
6913 	struct ucred *a_outcred;
6914 	struct thread *a_fsizetd;
6915 }
6916 #endif
6917 /*
6918  * TODO: FreeBSD will only call file system-specific copy_file_range() if both
6919  * files resides under the same mountpoint. In case of ZFS we want to be called
6920  * even is files are in different datasets (but on the same pools, but we need
6921  * to check that ourselves).
6922  */
6923 static int
zfs_freebsd_copy_file_range(struct vop_copy_file_range_args * ap)6924 zfs_freebsd_copy_file_range(struct vop_copy_file_range_args *ap)
6925 {
6926 	zfsvfs_t *outzfsvfs;
6927 	struct vnode *invp = ap->a_invp;
6928 	struct vnode *outvp = ap->a_outvp;
6929 	struct mount *mp;
6930 	int error;
6931 	uint64_t len = *ap->a_lenp;
6932 
6933 	if (!zfs_bclone_enabled) {
6934 		mp = NULL;
6935 		goto bad_write_fallback;
6936 	}
6937 
6938 	/*
6939 	 * TODO: If offset/length is not aligned to recordsize, use
6940 	 * vn_generic_copy_file_range() on this fragment.
6941 	 * It would be better to do this after we lock the vnodes, but then we
6942 	 * need something else than vn_generic_copy_file_range().
6943 	 */
6944 
6945 	vn_start_write(outvp, &mp, V_WAIT);
6946 	if (__predict_true(mp == outvp->v_mount)) {
6947 		outzfsvfs = (zfsvfs_t *)mp->mnt_data;
6948 		if (!spa_feature_is_enabled(dmu_objset_spa(outzfsvfs->z_os),
6949 		    SPA_FEATURE_BLOCK_CLONING)) {
6950 			goto bad_write_fallback;
6951 		}
6952 	}
6953 	if (invp == outvp) {
6954 		if (vn_lock(outvp, LK_EXCLUSIVE) != 0) {
6955 			goto bad_write_fallback;
6956 		}
6957 	} else {
6958 #if (__FreeBSD_version >= 1302506 && __FreeBSD_version < 1400000) || \
6959 	__FreeBSD_version >= 1400086
6960 		vn_lock_pair(invp, false, LK_SHARED, outvp, false,
6961 		    LK_EXCLUSIVE);
6962 #else
6963 		vn_lock_pair(invp, false, outvp, false);
6964 #endif
6965 		if (VN_IS_DOOMED(invp) || VN_IS_DOOMED(outvp)) {
6966 			goto bad_locked_fallback;
6967 		}
6968 	}
6969 
6970 #ifdef MAC
6971 	error = mac_vnode_check_write(curthread->td_ucred, ap->a_outcred,
6972 	    outvp);
6973 	if (error != 0)
6974 		goto out_locked;
6975 #endif
6976 
6977 	error = zfs_clone_range(VTOZ(invp), ap->a_inoffp, VTOZ(outvp),
6978 	    ap->a_outoffp, &len, ap->a_outcred);
6979 	if (error == EXDEV || error == EAGAIN || error == EINVAL ||
6980 	    error == EOPNOTSUPP)
6981 		goto bad_locked_fallback;
6982 	*ap->a_lenp = (size_t)len;
6983 #ifdef MAC
6984 out_locked:
6985 #endif
6986 	if (invp != outvp)
6987 		VOP_UNLOCK(invp);
6988 	VOP_UNLOCK(outvp);
6989 	if (mp != NULL)
6990 		vn_finished_write(mp);
6991 	return (error);
6992 
6993 bad_locked_fallback:
6994 	if (invp != outvp)
6995 		VOP_UNLOCK(invp);
6996 	VOP_UNLOCK(outvp);
6997 bad_write_fallback:
6998 	if (mp != NULL)
6999 		vn_finished_write(mp);
7000 	error = ENOSYS;
7001 	return (error);
7002 }
7003 
7004 struct vop_vector zfs_vnodeops;
7005 struct vop_vector zfs_fifoops;
7006 struct vop_vector zfs_shareops;
7007 
7008 struct vop_vector zfs_vnodeops = {
7009 	.vop_default =		&default_vnodeops,
7010 	.vop_inactive =		zfs_freebsd_inactive,
7011 	.vop_need_inactive =	zfs_freebsd_need_inactive,
7012 	.vop_reclaim =		zfs_freebsd_reclaim,
7013 	.vop_fplookup_vexec = zfs_freebsd_fplookup_vexec,
7014 	.vop_fplookup_symlink = zfs_freebsd_fplookup_symlink,
7015 	.vop_access =		zfs_freebsd_access,
7016 	.vop_allocate =		VOP_EOPNOTSUPP,
7017 #if __FreeBSD_version >= 1400032
7018 	.vop_deallocate =	zfs_deallocate,
7019 #endif
7020 	.vop_lookup =		zfs_cache_lookup,
7021 	.vop_cachedlookup =	zfs_freebsd_cachedlookup,
7022 	.vop_getattr =		zfs_freebsd_getattr,
7023 	.vop_setattr =		zfs_freebsd_setattr,
7024 	.vop_create =		zfs_freebsd_create,
7025 	.vop_mknod =		(vop_mknod_t *)zfs_freebsd_create,
7026 	.vop_mkdir =		zfs_freebsd_mkdir,
7027 	.vop_readdir =		zfs_freebsd_readdir,
7028 	.vop_fsync =		zfs_freebsd_fsync,
7029 	.vop_open =		zfs_freebsd_open,
7030 	.vop_close =		zfs_freebsd_close,
7031 	.vop_rmdir =		zfs_freebsd_rmdir,
7032 	.vop_ioctl =		zfs_freebsd_ioctl,
7033 	.vop_link =		zfs_freebsd_link,
7034 	.vop_symlink =		zfs_freebsd_symlink,
7035 	.vop_readlink =		zfs_freebsd_readlink,
7036 	.vop_advise =		zfs_freebsd_advise,
7037 	.vop_read =		zfs_freebsd_read,
7038 	.vop_write =		zfs_freebsd_write,
7039 	.vop_remove =		zfs_freebsd_remove,
7040 	.vop_rename =		zfs_freebsd_rename,
7041 	.vop_pathconf =		zfs_freebsd_pathconf,
7042 	.vop_bmap =		zfs_freebsd_bmap,
7043 	.vop_fid =		zfs_freebsd_fid,
7044 	.vop_getextattr =	zfs_getextattr,
7045 	.vop_deleteextattr =	zfs_deleteextattr,
7046 	.vop_setextattr =	zfs_setextattr,
7047 	.vop_listextattr =	zfs_listextattr,
7048 	.vop_getacl =		zfs_freebsd_getacl,
7049 	.vop_setacl =		zfs_freebsd_setacl,
7050 	.vop_aclcheck =		zfs_freebsd_aclcheck,
7051 	.vop_getpages =		zfs_freebsd_getpages,
7052 	.vop_putpages =		zfs_freebsd_putpages,
7053 	.vop_vptocnp =		zfs_vptocnp,
7054 	.vop_lock1 =		vop_lock,
7055 	.vop_unlock =		vop_unlock,
7056 	.vop_islocked =		vop_islocked,
7057 #if __FreeBSD_version >= 1400043
7058 	.vop_add_writecount =	vop_stdadd_writecount_nomsync,
7059 #endif
7060 	.vop_copy_file_range =	zfs_freebsd_copy_file_range,
7061 };
7062 VFS_VOP_VECTOR_REGISTER(zfs_vnodeops);
7063 
7064 struct vop_vector zfs_fifoops = {
7065 	.vop_default =		&fifo_specops,
7066 	.vop_fsync =		zfs_freebsd_fsync,
7067 	.vop_fplookup_vexec =	zfs_freebsd_fplookup_vexec,
7068 	.vop_fplookup_symlink = zfs_freebsd_fplookup_symlink,
7069 	.vop_access =		zfs_freebsd_access,
7070 	.vop_getattr =		zfs_freebsd_getattr,
7071 	.vop_inactive =		zfs_freebsd_inactive,
7072 	.vop_read =		VOP_PANIC,
7073 	.vop_reclaim =		zfs_freebsd_reclaim,
7074 	.vop_setattr =		zfs_freebsd_setattr,
7075 	.vop_write =		VOP_PANIC,
7076 	.vop_pathconf = 	zfs_freebsd_pathconf,
7077 	.vop_fid =		zfs_freebsd_fid,
7078 	.vop_getacl =		zfs_freebsd_getacl,
7079 	.vop_setacl =		zfs_freebsd_setacl,
7080 	.vop_aclcheck =		zfs_freebsd_aclcheck,
7081 #if __FreeBSD_version >= 1400043
7082 	.vop_add_writecount =	vop_stdadd_writecount_nomsync,
7083 #endif
7084 };
7085 VFS_VOP_VECTOR_REGISTER(zfs_fifoops);
7086 
7087 /*
7088  * special share hidden files vnode operations template
7089  */
7090 struct vop_vector zfs_shareops = {
7091 	.vop_default =		&default_vnodeops,
7092 	.vop_fplookup_vexec =	VOP_EAGAIN,
7093 	.vop_fplookup_symlink =	VOP_EAGAIN,
7094 	.vop_access =		zfs_freebsd_access,
7095 	.vop_inactive =		zfs_freebsd_inactive,
7096 	.vop_reclaim =		zfs_freebsd_reclaim,
7097 	.vop_fid =		zfs_freebsd_fid,
7098 	.vop_pathconf =		zfs_freebsd_pathconf,
7099 #if __FreeBSD_version >= 1400043
7100 	.vop_add_writecount =	vop_stdadd_writecount_nomsync,
7101 #endif
7102 };
7103 VFS_VOP_VECTOR_REGISTER(zfs_shareops);
7104 
7105 ZFS_MODULE_PARAM(zfs, zfs_, xattr_compat, INT, ZMOD_RW,
7106 	"Use legacy ZFS xattr naming for writing new user namespace xattrs");
7107