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