xref: /illumos-gate/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision 79315247)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2015 Joyent, Inc.
27  * Copyright 2017 Nexenta Systems, Inc.
28  */
29 
30 /* Portions Copyright 2007 Jeremy Teo */
31 /* Portions Copyright 2010 Robert Milkowski */
32 
33 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/time.h>
36 #include <sys/systm.h>
37 #include <sys/sysmacros.h>
38 #include <sys/resource.h>
39 #include <sys/vfs.h>
40 #include <sys/vfs_opreg.h>
41 #include <sys/vnode.h>
42 #include <sys/file.h>
43 #include <sys/stat.h>
44 #include <sys/kmem.h>
45 #include <sys/taskq.h>
46 #include <sys/uio.h>
47 #include <sys/vmsystm.h>
48 #include <sys/atomic.h>
49 #include <sys/vm.h>
50 #include <vm/seg_vn.h>
51 #include <vm/pvn.h>
52 #include <vm/as.h>
53 #include <vm/kpm.h>
54 #include <vm/seg_kpm.h>
55 #include <sys/mman.h>
56 #include <sys/pathname.h>
57 #include <sys/cmn_err.h>
58 #include <sys/errno.h>
59 #include <sys/unistd.h>
60 #include <sys/zfs_dir.h>
61 #include <sys/zfs_acl.h>
62 #include <sys/zfs_ioctl.h>
63 #include <sys/fs/zfs.h>
64 #include <sys/dmu.h>
65 #include <sys/dmu_objset.h>
66 #include <sys/spa.h>
67 #include <sys/txg.h>
68 #include <sys/dbuf.h>
69 #include <sys/zap.h>
70 #include <sys/sa.h>
71 #include <sys/dirent.h>
72 #include <sys/policy.h>
73 #include <sys/sunddi.h>
74 #include <sys/filio.h>
75 #include <sys/sid.h>
76 #include "fs/fs_subr.h"
77 #include <sys/zfs_ctldir.h>
78 #include <sys/zfs_fuid.h>
79 #include <sys/zfs_sa.h>
80 #include <sys/dnlc.h>
81 #include <sys/zfs_rlock.h>
82 #include <sys/extdirent.h>
83 #include <sys/kidmap.h>
84 #include <sys/cred.h>
85 #include <sys/attr.h>
86 #include <sys/zil.h>
87 
88 /*
89  * Programming rules.
90  *
91  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
92  * properly lock its in-core state, create a DMU transaction, do the work,
93  * record this work in the intent log (ZIL), commit the DMU transaction,
94  * and wait for the intent log to commit if it is a synchronous operation.
95  * Moreover, the vnode ops must work in both normal and log replay context.
96  * The ordering of events is important to avoid deadlocks and references
97  * to freed memory.  The example below illustrates the following Big Rules:
98  *
99  *  (1)	A check must be made in each zfs thread for a mounted file system.
100  *	This is done avoiding races using ZFS_ENTER(zfsvfs).
101  *	A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
102  *	must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
103  *	can return EIO from the calling function.
104  *
105  *  (2)	VN_RELE() should always be the last thing except for zil_commit()
106  *	(if necessary) and ZFS_EXIT(). This is for 3 reasons:
107  *	First, if it's the last reference, the vnode/znode
108  *	can be freed, so the zp may point to freed memory.  Second, the last
109  *	reference will call zfs_zinactive(), which may induce a lot of work --
110  *	pushing cached pages (which acquires range locks) and syncing out
111  *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
112  *	which could deadlock the system if you were already holding one.
113  *	If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
114  *
115  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
116  *	as they can span dmu_tx_assign() calls.
117  *
118  *  (4) If ZPL locks are held, pass TXG_NOWAIT as the second argument to
119  *      dmu_tx_assign().  This is critical because we don't want to block
120  *      while holding locks.
121  *
122  *	If no ZPL locks are held (aside from ZFS_ENTER()), use TXG_WAIT.  This
123  *	reduces lock contention and CPU usage when we must wait (note that if
124  *	throughput is constrained by the storage, nearly every transaction
125  *	must wait).
126  *
127  *      Note, in particular, that if a lock is sometimes acquired before
128  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
129  *      to use a non-blocking assign can deadlock the system.  The scenario:
130  *
131  *	Thread A has grabbed a lock before calling dmu_tx_assign().
132  *	Thread B is in an already-assigned tx, and blocks for this lock.
133  *	Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
134  *	forever, because the previous txg can't quiesce until B's tx commits.
135  *
136  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
137  *	then drop all locks, call dmu_tx_wait(), and try again.  On subsequent
138  *	calls to dmu_tx_assign(), pass TXG_NOTHROTTLE in addition to TXG_NOWAIT,
139  *	to indicate that this operation has already called dmu_tx_wait().
140  *	This will ensure that we don't retry forever, waiting a short bit
141  *	each time.
142  *
143  *  (5)	If the operation succeeded, generate the intent log entry for it
144  *	before dropping locks.  This ensures that the ordering of events
145  *	in the intent log matches the order in which they actually occurred.
146  *	During ZIL replay the zfs_log_* functions will update the sequence
147  *	number to indicate the zil transaction has replayed.
148  *
149  *  (6)	At the end of each vnode op, the DMU tx must always commit,
150  *	regardless of whether there were any errors.
151  *
152  *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
153  *	to ensure that synchronous semantics are provided when necessary.
154  *
155  * In general, this is how things should be ordered in each vnode op:
156  *
157  *	ZFS_ENTER(zfsvfs);		// exit if unmounted
158  * top:
159  *	zfs_dirent_lock(&dl, ...)	// lock directory entry (may VN_HOLD())
160  *	rw_enter(...);			// grab any other locks you need
161  *	tx = dmu_tx_create(...);	// get DMU tx
162  *	dmu_tx_hold_*();		// hold each object you might modify
163  *	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
164  *	if (error) {
165  *		rw_exit(...);		// drop locks
166  *		zfs_dirent_unlock(dl);	// unlock directory entry
167  *		VN_RELE(...);		// release held vnodes
168  *		if (error == ERESTART) {
169  *			waited = B_TRUE;
170  *			dmu_tx_wait(tx);
171  *			dmu_tx_abort(tx);
172  *			goto top;
173  *		}
174  *		dmu_tx_abort(tx);	// abort DMU tx
175  *		ZFS_EXIT(zfsvfs);	// finished in zfs
176  *		return (error);		// really out of space
177  *	}
178  *	error = do_real_work();		// do whatever this VOP does
179  *	if (error == 0)
180  *		zfs_log_*(...);		// on success, make ZIL entry
181  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
182  *	rw_exit(...);			// drop locks
183  *	zfs_dirent_unlock(dl);		// unlock directory entry
184  *	VN_RELE(...);			// release held vnodes
185  *	zil_commit(zilog, foid);	// synchronous when necessary
186  *	ZFS_EXIT(zfsvfs);		// finished in zfs
187  *	return (error);			// done, report error
188  */
189 
190 /* ARGSUSED */
191 static int
192 zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
193 {
194 	znode_t	*zp = VTOZ(*vpp);
195 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
196 
197 	ZFS_ENTER(zfsvfs);
198 	ZFS_VERIFY_ZP(zp);
199 
200 	if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
201 	    ((flag & FAPPEND) == 0)) {
202 		ZFS_EXIT(zfsvfs);
203 		return (SET_ERROR(EPERM));
204 	}
205 
206 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
207 	    ZTOV(zp)->v_type == VREG &&
208 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
209 		if (fs_vscan(*vpp, cr, 0) != 0) {
210 			ZFS_EXIT(zfsvfs);
211 			return (SET_ERROR(EACCES));
212 		}
213 	}
214 
215 	/* Keep a count of the synchronous opens in the znode */
216 	if (flag & (FSYNC | FDSYNC))
217 		atomic_inc_32(&zp->z_sync_cnt);
218 
219 	ZFS_EXIT(zfsvfs);
220 	return (0);
221 }
222 
223 /* ARGSUSED */
224 static int
225 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
226     caller_context_t *ct)
227 {
228 	znode_t	*zp = VTOZ(vp);
229 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
230 
231 	/*
232 	 * Clean up any locks held by this process on the vp.
233 	 */
234 	cleanlocks(vp, ddi_get_pid(), 0);
235 	cleanshares(vp, ddi_get_pid());
236 
237 	ZFS_ENTER(zfsvfs);
238 	ZFS_VERIFY_ZP(zp);
239 
240 	/* Decrement the synchronous opens in the znode */
241 	if ((flag & (FSYNC | FDSYNC)) && (count == 1))
242 		atomic_dec_32(&zp->z_sync_cnt);
243 
244 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
245 	    ZTOV(zp)->v_type == VREG &&
246 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
247 		VERIFY(fs_vscan(vp, cr, 1) == 0);
248 
249 	ZFS_EXIT(zfsvfs);
250 	return (0);
251 }
252 
253 /*
254  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
255  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
256  */
257 static int
258 zfs_holey(vnode_t *vp, int cmd, offset_t *off)
259 {
260 	znode_t	*zp = VTOZ(vp);
261 	uint64_t noff = (uint64_t)*off; /* new offset */
262 	uint64_t file_sz;
263 	int error;
264 	boolean_t hole;
265 
266 	file_sz = zp->z_size;
267 	if (noff >= file_sz)  {
268 		return (SET_ERROR(ENXIO));
269 	}
270 
271 	if (cmd == _FIO_SEEK_HOLE)
272 		hole = B_TRUE;
273 	else
274 		hole = B_FALSE;
275 
276 	error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
277 
278 	if (error == ESRCH)
279 		return (SET_ERROR(ENXIO));
280 
281 	/*
282 	 * We could find a hole that begins after the logical end-of-file,
283 	 * because dmu_offset_next() only works on whole blocks.  If the
284 	 * EOF falls mid-block, then indicate that the "virtual hole"
285 	 * at the end of the file begins at the logical EOF, rather than
286 	 * at the end of the last block.
287 	 */
288 	if (noff > file_sz) {
289 		ASSERT(hole);
290 		noff = file_sz;
291 	}
292 
293 	if (noff < *off)
294 		return (error);
295 	*off = noff;
296 	return (error);
297 }
298 
299 /* ARGSUSED */
300 static int
301 zfs_ioctl(vnode_t *vp, int com, intptr_t data, int flag, cred_t *cred,
302     int *rvalp, caller_context_t *ct)
303 {
304 	offset_t off;
305 	offset_t ndata;
306 	dmu_object_info_t doi;
307 	int error;
308 	zfsvfs_t *zfsvfs;
309 	znode_t *zp;
310 
311 	switch (com) {
312 	case _FIOFFS:
313 	{
314 		return (zfs_sync(vp->v_vfsp, 0, cred));
315 
316 		/*
317 		 * The following two ioctls are used by bfu.  Faking out,
318 		 * necessary to avoid bfu errors.
319 		 */
320 	}
321 	case _FIOGDIO:
322 	case _FIOSDIO:
323 	{
324 		return (0);
325 	}
326 
327 	case _FIO_SEEK_DATA:
328 	case _FIO_SEEK_HOLE:
329 	{
330 		if (ddi_copyin((void *)data, &off, sizeof (off), flag))
331 			return (SET_ERROR(EFAULT));
332 
333 		zp = VTOZ(vp);
334 		zfsvfs = zp->z_zfsvfs;
335 		ZFS_ENTER(zfsvfs);
336 		ZFS_VERIFY_ZP(zp);
337 
338 		/* offset parameter is in/out */
339 		error = zfs_holey(vp, com, &off);
340 		ZFS_EXIT(zfsvfs);
341 		if (error)
342 			return (error);
343 		if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
344 			return (SET_ERROR(EFAULT));
345 		return (0);
346 	}
347 	case _FIO_COUNT_FILLED:
348 	{
349 		/*
350 		 * _FIO_COUNT_FILLED adds a new ioctl command which
351 		 * exposes the number of filled blocks in a
352 		 * ZFS object.
353 		 */
354 		zp = VTOZ(vp);
355 		zfsvfs = zp->z_zfsvfs;
356 		ZFS_ENTER(zfsvfs);
357 		ZFS_VERIFY_ZP(zp);
358 
359 		/*
360 		 * Wait for all dirty blocks for this object
361 		 * to get synced out to disk, and the DMU info
362 		 * updated.
363 		 */
364 		error = dmu_object_wait_synced(zfsvfs->z_os, zp->z_id);
365 		if (error) {
366 			ZFS_EXIT(zfsvfs);
367 			return (error);
368 		}
369 
370 		/*
371 		 * Retrieve fill count from DMU object.
372 		 */
373 		error = dmu_object_info(zfsvfs->z_os, zp->z_id, &doi);
374 		if (error) {
375 			ZFS_EXIT(zfsvfs);
376 			return (error);
377 		}
378 
379 		ndata = doi.doi_fill_count;
380 
381 		ZFS_EXIT(zfsvfs);
382 		if (ddi_copyout(&ndata, (void *)data, sizeof (ndata), flag))
383 			return (SET_ERROR(EFAULT));
384 		return (0);
385 	}
386 	}
387 	return (SET_ERROR(ENOTTY));
388 }
389 
390 /*
391  * Utility functions to map and unmap a single physical page.  These
392  * are used to manage the mappable copies of ZFS file data, and therefore
393  * do not update ref/mod bits.
394  */
395 caddr_t
396 zfs_map_page(page_t *pp, enum seg_rw rw)
397 {
398 	if (kpm_enable)
399 		return (hat_kpm_mapin(pp, 0));
400 	ASSERT(rw == S_READ || rw == S_WRITE);
401 	return (ppmapin(pp, PROT_READ | ((rw == S_WRITE) ? PROT_WRITE : 0),
402 	    (caddr_t)-1));
403 }
404 
405 void
406 zfs_unmap_page(page_t *pp, caddr_t addr)
407 {
408 	if (kpm_enable) {
409 		hat_kpm_mapout(pp, 0, addr);
410 	} else {
411 		ppmapout(addr);
412 	}
413 }
414 
415 /*
416  * When a file is memory mapped, we must keep the IO data synchronized
417  * between the DMU cache and the memory mapped pages.  What this means:
418  *
419  * On Write:	If we find a memory mapped page, we write to *both*
420  *		the page and the dmu buffer.
421  */
422 static void
423 update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid)
424 {
425 	int64_t	off;
426 
427 	off = start & PAGEOFFSET;
428 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
429 		page_t *pp;
430 		uint64_t nbytes = MIN(PAGESIZE - off, len);
431 
432 		if (pp = page_lookup(vp, start, SE_SHARED)) {
433 			caddr_t va;
434 
435 			va = zfs_map_page(pp, S_WRITE);
436 			(void) dmu_read(os, oid, start+off, nbytes, va+off,
437 			    DMU_READ_PREFETCH);
438 			zfs_unmap_page(pp, va);
439 			page_unlock(pp);
440 		}
441 		len -= nbytes;
442 		off = 0;
443 	}
444 }
445 
446 /*
447  * When a file is memory mapped, we must keep the IO data synchronized
448  * between the DMU cache and the memory mapped pages.  What this means:
449  *
450  * On Read:	We "read" preferentially from memory mapped pages,
451  *		else we default from the dmu buffer.
452  *
453  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
454  *	 the file is memory mapped.
455  */
456 static int
457 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
458 {
459 	znode_t *zp = VTOZ(vp);
460 	int64_t	start, off;
461 	int len = nbytes;
462 	int error = 0;
463 
464 	start = uio->uio_loffset;
465 	off = start & PAGEOFFSET;
466 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
467 		page_t *pp;
468 		uint64_t bytes = MIN(PAGESIZE - off, len);
469 
470 		if (pp = page_lookup(vp, start, SE_SHARED)) {
471 			caddr_t va;
472 
473 			va = zfs_map_page(pp, S_READ);
474 			error = uiomove(va + off, bytes, UIO_READ, uio);
475 			zfs_unmap_page(pp, va);
476 			page_unlock(pp);
477 		} else {
478 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
479 			    uio, bytes);
480 		}
481 		len -= bytes;
482 		off = 0;
483 		if (error)
484 			break;
485 	}
486 	return (error);
487 }
488 
489 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
490 
491 /*
492  * Read bytes from specified file into supplied buffer.
493  *
494  *	IN:	vp	- vnode of file to be read from.
495  *		uio	- structure supplying read location, range info,
496  *			  and return buffer.
497  *		ioflag	- SYNC flags; used to provide FRSYNC semantics.
498  *		cr	- credentials of caller.
499  *		ct	- caller context
500  *
501  *	OUT:	uio	- updated offset and range, buffer filled.
502  *
503  *	RETURN:	0 on success, error code on failure.
504  *
505  * Side Effects:
506  *	vp - atime updated if byte count > 0
507  */
508 /* ARGSUSED */
509 static int
510 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
511 {
512 	znode_t		*zp = VTOZ(vp);
513 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
514 	ssize_t		n, nbytes;
515 	int		error = 0;
516 	xuio_t		*xuio = NULL;
517 
518 	ZFS_ENTER(zfsvfs);
519 	ZFS_VERIFY_ZP(zp);
520 
521 	if (zp->z_pflags & ZFS_AV_QUARANTINED) {
522 		ZFS_EXIT(zfsvfs);
523 		return (SET_ERROR(EACCES));
524 	}
525 
526 	/*
527 	 * Validate file offset
528 	 */
529 	if (uio->uio_loffset < (offset_t)0) {
530 		ZFS_EXIT(zfsvfs);
531 		return (SET_ERROR(EINVAL));
532 	}
533 
534 	/*
535 	 * Fasttrack empty reads
536 	 */
537 	if (uio->uio_resid == 0) {
538 		ZFS_EXIT(zfsvfs);
539 		return (0);
540 	}
541 
542 	/*
543 	 * Check for mandatory locks
544 	 */
545 	if (MANDMODE(zp->z_mode)) {
546 		if (error = chklock(vp, FREAD,
547 		    uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
548 			ZFS_EXIT(zfsvfs);
549 			return (error);
550 		}
551 	}
552 
553 	/*
554 	 * If we're in FRSYNC mode, sync out this znode before reading it.
555 	 */
556 	if (ioflag & FRSYNC || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
557 		zil_commit(zfsvfs->z_log, zp->z_id);
558 
559 	/*
560 	 * Lock the range against changes.
561 	 */
562 	locked_range_t *lr = rangelock_enter(&zp->z_rangelock,
563 	    uio->uio_loffset, uio->uio_resid, RL_READER);
564 
565 	/*
566 	 * If we are reading past end-of-file we can skip
567 	 * to the end; but we might still need to set atime.
568 	 */
569 	if (uio->uio_loffset >= zp->z_size) {
570 		error = 0;
571 		goto out;
572 	}
573 
574 	ASSERT(uio->uio_loffset < zp->z_size);
575 	n = MIN(uio->uio_resid, zp->z_size - uio->uio_loffset);
576 
577 	if ((uio->uio_extflg == UIO_XUIO) &&
578 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY)) {
579 		int nblk;
580 		int blksz = zp->z_blksz;
581 		uint64_t offset = uio->uio_loffset;
582 
583 		xuio = (xuio_t *)uio;
584 		if ((ISP2(blksz))) {
585 			nblk = (P2ROUNDUP(offset + n, blksz) - P2ALIGN(offset,
586 			    blksz)) / blksz;
587 		} else {
588 			ASSERT(offset + n <= blksz);
589 			nblk = 1;
590 		}
591 		(void) dmu_xuio_init(xuio, nblk);
592 
593 		if (vn_has_cached_data(vp)) {
594 			/*
595 			 * For simplicity, we always allocate a full buffer
596 			 * even if we only expect to read a portion of a block.
597 			 */
598 			while (--nblk >= 0) {
599 				(void) dmu_xuio_add(xuio,
600 				    dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
601 				    blksz), 0, blksz);
602 			}
603 		}
604 	}
605 
606 	while (n > 0) {
607 		nbytes = MIN(n, zfs_read_chunk_size -
608 		    P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
609 
610 		if (vn_has_cached_data(vp)) {
611 			error = mappedread(vp, nbytes, uio);
612 		} else {
613 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
614 			    uio, nbytes);
615 		}
616 		if (error) {
617 			/* convert checksum errors into IO errors */
618 			if (error == ECKSUM)
619 				error = SET_ERROR(EIO);
620 			break;
621 		}
622 
623 		n -= nbytes;
624 	}
625 out:
626 	rangelock_exit(lr);
627 
628 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
629 	ZFS_EXIT(zfsvfs);
630 	return (error);
631 }
632 
633 /*
634  * Write the bytes to a file.
635  *
636  *	IN:	vp	- vnode of file to be written to.
637  *		uio	- structure supplying write location, range info,
638  *			  and data buffer.
639  *		ioflag	- FAPPEND, FSYNC, and/or FDSYNC.  FAPPEND is
640  *			  set if in append mode.
641  *		cr	- credentials of caller.
642  *		ct	- caller context (NFS/CIFS fem monitor only)
643  *
644  *	OUT:	uio	- updated offset and range.
645  *
646  *	RETURN:	0 on success, error code on failure.
647  *
648  * Timestamps:
649  *	vp - ctime|mtime updated if byte count > 0
650  */
651 
652 /* ARGSUSED */
653 static int
654 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
655 {
656 	znode_t		*zp = VTOZ(vp);
657 	rlim64_t	limit = uio->uio_llimit;
658 	ssize_t		start_resid = uio->uio_resid;
659 	ssize_t		tx_bytes;
660 	uint64_t	end_size;
661 	dmu_tx_t	*tx;
662 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
663 	zilog_t		*zilog;
664 	offset_t	woff;
665 	ssize_t		n, nbytes;
666 	int		max_blksz = zfsvfs->z_max_blksz;
667 	int		error = 0;
668 	arc_buf_t	*abuf;
669 	iovec_t		*aiov = NULL;
670 	xuio_t		*xuio = NULL;
671 	int		i_iov = 0;
672 	int		iovcnt = uio->uio_iovcnt;
673 	iovec_t		*iovp = uio->uio_iov;
674 	int		write_eof;
675 	int		count = 0;
676 	sa_bulk_attr_t	bulk[4];
677 	uint64_t	mtime[2], ctime[2];
678 
679 	/*
680 	 * Fasttrack empty write
681 	 */
682 	n = start_resid;
683 	if (n == 0)
684 		return (0);
685 
686 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
687 		limit = MAXOFFSET_T;
688 
689 	ZFS_ENTER(zfsvfs);
690 	ZFS_VERIFY_ZP(zp);
691 
692 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
693 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
694 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
695 	    &zp->z_size, 8);
696 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
697 	    &zp->z_pflags, 8);
698 
699 	/*
700 	 * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
701 	 * callers might not be able to detect properly that we are read-only,
702 	 * so check it explicitly here.
703 	 */
704 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
705 		ZFS_EXIT(zfsvfs);
706 		return (SET_ERROR(EROFS));
707 	}
708 
709 	/*
710 	 * If immutable or not appending then return EPERM.
711 	 * Intentionally allow ZFS_READONLY through here.
712 	 * See zfs_zaccess_common()
713 	 */
714 	if ((zp->z_pflags & ZFS_IMMUTABLE) ||
715 	    ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
716 	    (uio->uio_loffset < zp->z_size))) {
717 		ZFS_EXIT(zfsvfs);
718 		return (SET_ERROR(EPERM));
719 	}
720 
721 	zilog = zfsvfs->z_log;
722 
723 	/*
724 	 * Validate file offset
725 	 */
726 	woff = ioflag & FAPPEND ? zp->z_size : uio->uio_loffset;
727 	if (woff < 0) {
728 		ZFS_EXIT(zfsvfs);
729 		return (SET_ERROR(EINVAL));
730 	}
731 
732 	/*
733 	 * Check for mandatory locks before calling rangelock_enter()
734 	 * in order to prevent a deadlock with locks set via fcntl().
735 	 */
736 	if (MANDMODE((mode_t)zp->z_mode) &&
737 	    (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
738 		ZFS_EXIT(zfsvfs);
739 		return (error);
740 	}
741 
742 	/*
743 	 * Pre-fault the pages to ensure slow (eg NFS) pages
744 	 * don't hold up txg.
745 	 * Skip this if uio contains loaned arc_buf.
746 	 */
747 	if ((uio->uio_extflg == UIO_XUIO) &&
748 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY))
749 		xuio = (xuio_t *)uio;
750 	else
751 		uio_prefaultpages(MIN(n, max_blksz), uio);
752 
753 	/*
754 	 * If in append mode, set the io offset pointer to eof.
755 	 */
756 	locked_range_t *lr;
757 	if (ioflag & FAPPEND) {
758 		/*
759 		 * Obtain an appending range lock to guarantee file append
760 		 * semantics.  We reset the write offset once we have the lock.
761 		 */
762 		lr = rangelock_enter(&zp->z_rangelock, 0, n, RL_APPEND);
763 		woff = lr->lr_offset;
764 		if (lr->lr_length == UINT64_MAX) {
765 			/*
766 			 * We overlocked the file because this write will cause
767 			 * the file block size to increase.
768 			 * Note that zp_size cannot change with this lock held.
769 			 */
770 			woff = zp->z_size;
771 		}
772 		uio->uio_loffset = woff;
773 	} else {
774 		/*
775 		 * Note that if the file block size will change as a result of
776 		 * this write, then this range lock will lock the entire file
777 		 * so that we can re-write the block safely.
778 		 */
779 		lr = rangelock_enter(&zp->z_rangelock, woff, n, RL_WRITER);
780 	}
781 
782 	if (woff >= limit) {
783 		rangelock_exit(lr);
784 		ZFS_EXIT(zfsvfs);
785 		return (SET_ERROR(EFBIG));
786 	}
787 
788 	if ((woff + n) > limit || woff > (limit - n))
789 		n = limit - woff;
790 
791 	/* Will this write extend the file length? */
792 	write_eof = (woff + n > zp->z_size);
793 
794 	end_size = MAX(zp->z_size, woff + n);
795 
796 	/*
797 	 * Write the file in reasonable size chunks.  Each chunk is written
798 	 * in a separate transaction; this keeps the intent log records small
799 	 * and allows us to do more fine-grained space accounting.
800 	 */
801 	while (n > 0) {
802 		abuf = NULL;
803 		woff = uio->uio_loffset;
804 		if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
805 		    zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
806 			if (abuf != NULL)
807 				dmu_return_arcbuf(abuf);
808 			error = SET_ERROR(EDQUOT);
809 			break;
810 		}
811 
812 		if (xuio && abuf == NULL) {
813 			ASSERT(i_iov < iovcnt);
814 			aiov = &iovp[i_iov];
815 			abuf = dmu_xuio_arcbuf(xuio, i_iov);
816 			dmu_xuio_clear(xuio, i_iov);
817 			DTRACE_PROBE3(zfs_cp_write, int, i_iov,
818 			    iovec_t *, aiov, arc_buf_t *, abuf);
819 			ASSERT((aiov->iov_base == abuf->b_data) ||
820 			    ((char *)aiov->iov_base - (char *)abuf->b_data +
821 			    aiov->iov_len == arc_buf_size(abuf)));
822 			i_iov++;
823 		} else if (abuf == NULL && n >= max_blksz &&
824 		    woff >= zp->z_size &&
825 		    P2PHASE(woff, max_blksz) == 0 &&
826 		    zp->z_blksz == max_blksz) {
827 			/*
828 			 * This write covers a full block.  "Borrow" a buffer
829 			 * from the dmu so that we can fill it before we enter
830 			 * a transaction.  This avoids the possibility of
831 			 * holding up the transaction if the data copy hangs
832 			 * up on a pagefault (e.g., from an NFS server mapping).
833 			 */
834 			size_t cbytes;
835 
836 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
837 			    max_blksz);
838 			ASSERT(abuf != NULL);
839 			ASSERT(arc_buf_size(abuf) == max_blksz);
840 			if (error = uiocopy(abuf->b_data, max_blksz,
841 			    UIO_WRITE, uio, &cbytes)) {
842 				dmu_return_arcbuf(abuf);
843 				break;
844 			}
845 			ASSERT(cbytes == max_blksz);
846 		}
847 
848 		/*
849 		 * Start a transaction.
850 		 */
851 		tx = dmu_tx_create(zfsvfs->z_os);
852 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
853 		dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
854 		zfs_sa_upgrade_txholds(tx, zp);
855 		error = dmu_tx_assign(tx, TXG_WAIT);
856 		if (error) {
857 			dmu_tx_abort(tx);
858 			if (abuf != NULL)
859 				dmu_return_arcbuf(abuf);
860 			break;
861 		}
862 
863 		/*
864 		 * If rangelock_enter() over-locked we grow the blocksize
865 		 * and then reduce the lock range.  This will only happen
866 		 * on the first iteration since rangelock_reduce() will
867 		 * shrink down lr_length to the appropriate size.
868 		 */
869 		if (lr->lr_length == UINT64_MAX) {
870 			uint64_t new_blksz;
871 
872 			if (zp->z_blksz > max_blksz) {
873 				/*
874 				 * File's blocksize is already larger than the
875 				 * "recordsize" property.  Only let it grow to
876 				 * the next power of 2.
877 				 */
878 				ASSERT(!ISP2(zp->z_blksz));
879 				new_blksz = MIN(end_size,
880 				    1 << highbit64(zp->z_blksz));
881 			} else {
882 				new_blksz = MIN(end_size, max_blksz);
883 			}
884 			zfs_grow_blocksize(zp, new_blksz, tx);
885 			rangelock_reduce(lr, woff, n);
886 		}
887 
888 		/*
889 		 * XXX - should we really limit each write to z_max_blksz?
890 		 * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
891 		 */
892 		nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
893 
894 		if (abuf == NULL) {
895 			tx_bytes = uio->uio_resid;
896 			error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
897 			    uio, nbytes, tx);
898 			tx_bytes -= uio->uio_resid;
899 		} else {
900 			tx_bytes = nbytes;
901 			ASSERT(xuio == NULL || tx_bytes == aiov->iov_len);
902 			/*
903 			 * If this is not a full block write, but we are
904 			 * extending the file past EOF and this data starts
905 			 * block-aligned, use assign_arcbuf().  Otherwise,
906 			 * write via dmu_write().
907 			 */
908 			if (tx_bytes < max_blksz && (!write_eof ||
909 			    aiov->iov_base != abuf->b_data)) {
910 				ASSERT(xuio);
911 				dmu_write(zfsvfs->z_os, zp->z_id, woff,
912 				    aiov->iov_len, aiov->iov_base, tx);
913 				dmu_return_arcbuf(abuf);
914 				xuio_stat_wbuf_copied();
915 			} else {
916 				ASSERT(xuio || tx_bytes == max_blksz);
917 				dmu_assign_arcbuf(sa_get_db(zp->z_sa_hdl),
918 				    woff, abuf, tx);
919 			}
920 			ASSERT(tx_bytes <= uio->uio_resid);
921 			uioskip(uio, tx_bytes);
922 		}
923 		if (tx_bytes && vn_has_cached_data(vp)) {
924 			update_pages(vp, woff,
925 			    tx_bytes, zfsvfs->z_os, zp->z_id);
926 		}
927 
928 		/*
929 		 * If we made no progress, we're done.  If we made even
930 		 * partial progress, update the znode and ZIL accordingly.
931 		 */
932 		if (tx_bytes == 0) {
933 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
934 			    (void *)&zp->z_size, sizeof (uint64_t), tx);
935 			dmu_tx_commit(tx);
936 			ASSERT(error != 0);
937 			break;
938 		}
939 
940 		/*
941 		 * Clear Set-UID/Set-GID bits on successful write if not
942 		 * privileged and at least one of the excute bits is set.
943 		 *
944 		 * It would be nice to to this after all writes have
945 		 * been done, but that would still expose the ISUID/ISGID
946 		 * to another app after the partial write is committed.
947 		 *
948 		 * Note: we don't call zfs_fuid_map_id() here because
949 		 * user 0 is not an ephemeral uid.
950 		 */
951 		mutex_enter(&zp->z_acl_lock);
952 		if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) |
953 		    (S_IXUSR >> 6))) != 0 &&
954 		    (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
955 		    secpolicy_vnode_setid_retain(cr,
956 		    (zp->z_mode & S_ISUID) != 0 && zp->z_uid == 0) != 0) {
957 			uint64_t newmode;
958 			zp->z_mode &= ~(S_ISUID | S_ISGID);
959 			newmode = zp->z_mode;
960 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
961 			    (void *)&newmode, sizeof (uint64_t), tx);
962 		}
963 		mutex_exit(&zp->z_acl_lock);
964 
965 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
966 		    B_TRUE);
967 
968 		/*
969 		 * Update the file size (zp_size) if it has changed;
970 		 * account for possible concurrent updates.
971 		 */
972 		while ((end_size = zp->z_size) < uio->uio_loffset) {
973 			(void) atomic_cas_64(&zp->z_size, end_size,
974 			    uio->uio_loffset);
975 			ASSERT(error == 0);
976 		}
977 		/*
978 		 * If we are replaying and eof is non zero then force
979 		 * the file size to the specified eof. Note, there's no
980 		 * concurrency during replay.
981 		 */
982 		if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
983 			zp->z_size = zfsvfs->z_replay_eof;
984 
985 		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
986 
987 		zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
988 		dmu_tx_commit(tx);
989 
990 		if (error != 0)
991 			break;
992 		ASSERT(tx_bytes == nbytes);
993 		n -= nbytes;
994 
995 		if (!xuio && n > 0)
996 			uio_prefaultpages(MIN(n, max_blksz), uio);
997 	}
998 
999 	rangelock_exit(lr);
1000 
1001 	/*
1002 	 * If we're in replay mode, or we made no progress, return error.
1003 	 * Otherwise, it's at least a partial write, so it's successful.
1004 	 */
1005 	if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
1006 		ZFS_EXIT(zfsvfs);
1007 		return (error);
1008 	}
1009 
1010 	if (ioflag & (FSYNC | FDSYNC) ||
1011 	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1012 		zil_commit(zilog, zp->z_id);
1013 
1014 	ZFS_EXIT(zfsvfs);
1015 	return (0);
1016 }
1017 
1018 /* ARGSUSED */
1019 void
1020 zfs_get_done(zgd_t *zgd, int error)
1021 {
1022 	znode_t *zp = zgd->zgd_private;
1023 	objset_t *os = zp->z_zfsvfs->z_os;
1024 
1025 	if (zgd->zgd_db)
1026 		dmu_buf_rele(zgd->zgd_db, zgd);
1027 
1028 	rangelock_exit(zgd->zgd_lr);
1029 
1030 	/*
1031 	 * Release the vnode asynchronously as we currently have the
1032 	 * txg stopped from syncing.
1033 	 */
1034 	VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1035 
1036 	kmem_free(zgd, sizeof (zgd_t));
1037 }
1038 
1039 #ifdef DEBUG
1040 static int zil_fault_io = 0;
1041 #endif
1042 
1043 /*
1044  * Get data to generate a TX_WRITE intent log record.
1045  */
1046 int
1047 zfs_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb, zio_t *zio)
1048 {
1049 	zfsvfs_t *zfsvfs = arg;
1050 	objset_t *os = zfsvfs->z_os;
1051 	znode_t *zp;
1052 	uint64_t object = lr->lr_foid;
1053 	uint64_t offset = lr->lr_offset;
1054 	uint64_t size = lr->lr_length;
1055 	dmu_buf_t *db;
1056 	zgd_t *zgd;
1057 	int error = 0;
1058 
1059 	ASSERT3P(lwb, !=, NULL);
1060 	ASSERT3P(zio, !=, NULL);
1061 	ASSERT3U(size, !=, 0);
1062 
1063 	/*
1064 	 * Nothing to do if the file has been removed
1065 	 */
1066 	if (zfs_zget(zfsvfs, object, &zp) != 0)
1067 		return (SET_ERROR(ENOENT));
1068 	if (zp->z_unlinked) {
1069 		/*
1070 		 * Release the vnode asynchronously as we currently have the
1071 		 * txg stopped from syncing.
1072 		 */
1073 		VN_RELE_ASYNC(ZTOV(zp),
1074 		    dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1075 		return (SET_ERROR(ENOENT));
1076 	}
1077 
1078 	zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1079 	zgd->zgd_lwb = lwb;
1080 	zgd->zgd_private = zp;
1081 
1082 	/*
1083 	 * Write records come in two flavors: immediate and indirect.
1084 	 * For small writes it's cheaper to store the data with the
1085 	 * log record (immediate); for large writes it's cheaper to
1086 	 * sync the data and get a pointer to it (indirect) so that
1087 	 * we don't have to write the data twice.
1088 	 */
1089 	if (buf != NULL) { /* immediate write */
1090 		zgd->zgd_lr = rangelock_enter(&zp->z_rangelock,
1091 		    offset, size, RL_READER);
1092 		/* test for truncation needs to be done while range locked */
1093 		if (offset >= zp->z_size) {
1094 			error = SET_ERROR(ENOENT);
1095 		} else {
1096 			error = dmu_read(os, object, offset, size, buf,
1097 			    DMU_READ_NO_PREFETCH);
1098 		}
1099 		ASSERT(error == 0 || error == ENOENT);
1100 	} else { /* indirect write */
1101 		/*
1102 		 * Have to lock the whole block to ensure when it's
1103 		 * written out and its checksum is being calculated
1104 		 * that no one can change the data. We need to re-check
1105 		 * blocksize after we get the lock in case it's changed!
1106 		 */
1107 		for (;;) {
1108 			uint64_t blkoff;
1109 			size = zp->z_blksz;
1110 			blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1111 			offset -= blkoff;
1112 			zgd->zgd_lr = rangelock_enter(&zp->z_rangelock,
1113 			    offset, size, RL_READER);
1114 			if (zp->z_blksz == size)
1115 				break;
1116 			offset += blkoff;
1117 			rangelock_exit(zgd->zgd_lr);
1118 		}
1119 		/* test for truncation needs to be done while range locked */
1120 		if (lr->lr_offset >= zp->z_size)
1121 			error = SET_ERROR(ENOENT);
1122 #ifdef DEBUG
1123 		if (zil_fault_io) {
1124 			error = SET_ERROR(EIO);
1125 			zil_fault_io = 0;
1126 		}
1127 #endif
1128 		if (error == 0)
1129 			error = dmu_buf_hold(os, object, offset, zgd, &db,
1130 			    DMU_READ_NO_PREFETCH);
1131 
1132 		if (error == 0) {
1133 			blkptr_t *bp = &lr->lr_blkptr;
1134 
1135 			zgd->zgd_db = db;
1136 			zgd->zgd_bp = bp;
1137 
1138 			ASSERT(db->db_offset == offset);
1139 			ASSERT(db->db_size == size);
1140 
1141 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1142 			    zfs_get_done, zgd);
1143 			ASSERT(error || lr->lr_length <= size);
1144 
1145 			/*
1146 			 * On success, we need to wait for the write I/O
1147 			 * initiated by dmu_sync() to complete before we can
1148 			 * release this dbuf.  We will finish everything up
1149 			 * in the zfs_get_done() callback.
1150 			 */
1151 			if (error == 0)
1152 				return (0);
1153 
1154 			if (error == EALREADY) {
1155 				lr->lr_common.lrc_txtype = TX_WRITE2;
1156 				/*
1157 				 * TX_WRITE2 relies on the data previously
1158 				 * written by the TX_WRITE that caused
1159 				 * EALREADY.  We zero out the BP because
1160 				 * it is the old, currently-on-disk BP.
1161 				 */
1162 				zgd->zgd_bp = NULL;
1163 				BP_ZERO(bp);
1164 				error = 0;
1165 			}
1166 		}
1167 	}
1168 
1169 	zfs_get_done(zgd, error);
1170 
1171 	return (error);
1172 }
1173 
1174 /*ARGSUSED*/
1175 static int
1176 zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1177     caller_context_t *ct)
1178 {
1179 	znode_t *zp = VTOZ(vp);
1180 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1181 	int error;
1182 
1183 	ZFS_ENTER(zfsvfs);
1184 	ZFS_VERIFY_ZP(zp);
1185 
1186 	if (flag & V_ACE_MASK)
1187 		error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1188 	else
1189 		error = zfs_zaccess_rwx(zp, mode, flag, cr);
1190 
1191 	ZFS_EXIT(zfsvfs);
1192 	return (error);
1193 }
1194 
1195 /*
1196  * If vnode is for a device return a specfs vnode instead.
1197  */
1198 static int
1199 specvp_check(vnode_t **vpp, cred_t *cr)
1200 {
1201 	int error = 0;
1202 
1203 	if (IS_DEVVP(*vpp)) {
1204 		struct vnode *svp;
1205 
1206 		svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1207 		VN_RELE(*vpp);
1208 		if (svp == NULL)
1209 			error = SET_ERROR(ENOSYS);
1210 		*vpp = svp;
1211 	}
1212 	return (error);
1213 }
1214 
1215 
1216 /*
1217  * Lookup an entry in a directory, or an extended attribute directory.
1218  * If it exists, return a held vnode reference for it.
1219  *
1220  *	IN:	dvp	- vnode of directory to search.
1221  *		nm	- name of entry to lookup.
1222  *		pnp	- full pathname to lookup [UNUSED].
1223  *		flags	- LOOKUP_XATTR set if looking for an attribute.
1224  *		rdir	- root directory vnode [UNUSED].
1225  *		cr	- credentials of caller.
1226  *		ct	- caller context
1227  *		direntflags - directory lookup flags
1228  *		realpnp - returned pathname.
1229  *
1230  *	OUT:	vpp	- vnode of located entry, NULL if not found.
1231  *
1232  *	RETURN:	0 on success, error code on failure.
1233  *
1234  * Timestamps:
1235  *	NA
1236  */
1237 /* ARGSUSED */
1238 static int
1239 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
1240     int flags, vnode_t *rdir, cred_t *cr,  caller_context_t *ct,
1241     int *direntflags, pathname_t *realpnp)
1242 {
1243 	znode_t *zdp = VTOZ(dvp);
1244 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1245 	int	error = 0;
1246 
1247 	/*
1248 	 * Fast path lookup, however we must skip DNLC lookup
1249 	 * for case folding or normalizing lookups because the
1250 	 * DNLC code only stores the passed in name.  This means
1251 	 * creating 'a' and removing 'A' on a case insensitive
1252 	 * file system would work, but DNLC still thinks 'a'
1253 	 * exists and won't let you create it again on the next
1254 	 * pass through fast path.
1255 	 */
1256 	if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1257 
1258 		if (dvp->v_type != VDIR) {
1259 			return (SET_ERROR(ENOTDIR));
1260 		} else if (zdp->z_sa_hdl == NULL) {
1261 			return (SET_ERROR(EIO));
1262 		}
1263 
1264 		if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1265 			error = zfs_fastaccesschk_execute(zdp, cr);
1266 			if (!error) {
1267 				*vpp = dvp;
1268 				VN_HOLD(*vpp);
1269 				return (0);
1270 			}
1271 			return (error);
1272 		} else if (!zdp->z_zfsvfs->z_norm &&
1273 		    (zdp->z_zfsvfs->z_case == ZFS_CASE_SENSITIVE)) {
1274 
1275 			vnode_t *tvp = dnlc_lookup(dvp, nm);
1276 
1277 			if (tvp) {
1278 				error = zfs_fastaccesschk_execute(zdp, cr);
1279 				if (error) {
1280 					VN_RELE(tvp);
1281 					return (error);
1282 				}
1283 				if (tvp == DNLC_NO_VNODE) {
1284 					VN_RELE(tvp);
1285 					return (SET_ERROR(ENOENT));
1286 				} else {
1287 					*vpp = tvp;
1288 					return (specvp_check(vpp, cr));
1289 				}
1290 			}
1291 		}
1292 	}
1293 
1294 	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1295 
1296 	ZFS_ENTER(zfsvfs);
1297 	ZFS_VERIFY_ZP(zdp);
1298 
1299 	*vpp = NULL;
1300 
1301 	if (flags & LOOKUP_XATTR) {
1302 		/*
1303 		 * If the xattr property is off, refuse the lookup request.
1304 		 */
1305 		if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1306 			ZFS_EXIT(zfsvfs);
1307 			return (SET_ERROR(EINVAL));
1308 		}
1309 
1310 		/*
1311 		 * We don't allow recursive attributes..
1312 		 * Maybe someday we will.
1313 		 */
1314 		if (zdp->z_pflags & ZFS_XATTR) {
1315 			ZFS_EXIT(zfsvfs);
1316 			return (SET_ERROR(EINVAL));
1317 		}
1318 
1319 		if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1320 			ZFS_EXIT(zfsvfs);
1321 			return (error);
1322 		}
1323 
1324 		/*
1325 		 * Do we have permission to get into attribute directory?
1326 		 */
1327 
1328 		if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1329 		    B_FALSE, cr)) {
1330 			VN_RELE(*vpp);
1331 			*vpp = NULL;
1332 		}
1333 
1334 		ZFS_EXIT(zfsvfs);
1335 		return (error);
1336 	}
1337 
1338 	if (dvp->v_type != VDIR) {
1339 		ZFS_EXIT(zfsvfs);
1340 		return (SET_ERROR(ENOTDIR));
1341 	}
1342 
1343 	/*
1344 	 * Check accessibility of directory.
1345 	 */
1346 
1347 	if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr)) {
1348 		ZFS_EXIT(zfsvfs);
1349 		return (error);
1350 	}
1351 
1352 	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1353 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1354 		ZFS_EXIT(zfsvfs);
1355 		return (SET_ERROR(EILSEQ));
1356 	}
1357 
1358 	error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1359 	if (error == 0)
1360 		error = specvp_check(vpp, cr);
1361 
1362 	ZFS_EXIT(zfsvfs);
1363 	return (error);
1364 }
1365 
1366 /*
1367  * Attempt to create a new entry in a directory.  If the entry
1368  * already exists, truncate the file if permissible, else return
1369  * an error.  Return the vp of the created or trunc'd file.
1370  *
1371  *	IN:	dvp	- vnode of directory to put new file entry in.
1372  *		name	- name of new file entry.
1373  *		vap	- attributes of new file.
1374  *		excl	- flag indicating exclusive or non-exclusive mode.
1375  *		mode	- mode to open file with.
1376  *		cr	- credentials of caller.
1377  *		flag	- large file flag [UNUSED].
1378  *		ct	- caller context
1379  *		vsecp	- ACL to be set
1380  *
1381  *	OUT:	vpp	- vnode of created or trunc'd entry.
1382  *
1383  *	RETURN:	0 on success, error code on failure.
1384  *
1385  * Timestamps:
1386  *	dvp - ctime|mtime updated if new entry created
1387  *	 vp - ctime|mtime always, atime if new
1388  */
1389 
1390 /* ARGSUSED */
1391 static int
1392 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, vcexcl_t excl,
1393     int mode, vnode_t **vpp, cred_t *cr, int flag, caller_context_t *ct,
1394     vsecattr_t *vsecp)
1395 {
1396 	znode_t		*zp, *dzp = VTOZ(dvp);
1397 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1398 	zilog_t		*zilog;
1399 	objset_t	*os;
1400 	zfs_dirlock_t	*dl;
1401 	dmu_tx_t	*tx;
1402 	int		error;
1403 	ksid_t		*ksid;
1404 	uid_t		uid;
1405 	gid_t		gid = crgetgid(cr);
1406 	zfs_acl_ids_t   acl_ids;
1407 	boolean_t	fuid_dirtied;
1408 	boolean_t	have_acl = B_FALSE;
1409 	boolean_t	waited = B_FALSE;
1410 
1411 	/*
1412 	 * If we have an ephemeral id, ACL, or XVATTR then
1413 	 * make sure file system is at proper version
1414 	 */
1415 
1416 	ksid = crgetsid(cr, KSID_OWNER);
1417 	if (ksid)
1418 		uid = ksid_getid(ksid);
1419 	else
1420 		uid = crgetuid(cr);
1421 
1422 	if (zfsvfs->z_use_fuids == B_FALSE &&
1423 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1424 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1425 		return (SET_ERROR(EINVAL));
1426 
1427 	ZFS_ENTER(zfsvfs);
1428 	ZFS_VERIFY_ZP(dzp);
1429 	os = zfsvfs->z_os;
1430 	zilog = zfsvfs->z_log;
1431 
1432 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1433 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1434 		ZFS_EXIT(zfsvfs);
1435 		return (SET_ERROR(EILSEQ));
1436 	}
1437 
1438 	if (vap->va_mask & AT_XVATTR) {
1439 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1440 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1441 			ZFS_EXIT(zfsvfs);
1442 			return (error);
1443 		}
1444 	}
1445 top:
1446 	*vpp = NULL;
1447 
1448 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1449 		vap->va_mode &= ~VSVTX;
1450 
1451 	if (*name == '\0') {
1452 		/*
1453 		 * Null component name refers to the directory itself.
1454 		 */
1455 		VN_HOLD(dvp);
1456 		zp = dzp;
1457 		dl = NULL;
1458 		error = 0;
1459 	} else {
1460 		/* possible VN_HOLD(zp) */
1461 		int zflg = 0;
1462 
1463 		if (flag & FIGNORECASE)
1464 			zflg |= ZCILOOK;
1465 
1466 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1467 		    NULL, NULL);
1468 		if (error) {
1469 			if (have_acl)
1470 				zfs_acl_ids_free(&acl_ids);
1471 			if (strcmp(name, "..") == 0)
1472 				error = SET_ERROR(EISDIR);
1473 			ZFS_EXIT(zfsvfs);
1474 			return (error);
1475 		}
1476 	}
1477 
1478 	if (zp == NULL) {
1479 		uint64_t txtype;
1480 
1481 		/*
1482 		 * Create a new file object and update the directory
1483 		 * to reference it.
1484 		 */
1485 		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1486 			if (have_acl)
1487 				zfs_acl_ids_free(&acl_ids);
1488 			goto out;
1489 		}
1490 
1491 		/*
1492 		 * We only support the creation of regular files in
1493 		 * extended attribute directories.
1494 		 */
1495 
1496 		if ((dzp->z_pflags & ZFS_XATTR) &&
1497 		    (vap->va_type != VREG)) {
1498 			if (have_acl)
1499 				zfs_acl_ids_free(&acl_ids);
1500 			error = SET_ERROR(EINVAL);
1501 			goto out;
1502 		}
1503 
1504 		if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
1505 		    cr, vsecp, &acl_ids)) != 0)
1506 			goto out;
1507 		have_acl = B_TRUE;
1508 
1509 		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1510 			zfs_acl_ids_free(&acl_ids);
1511 			error = SET_ERROR(EDQUOT);
1512 			goto out;
1513 		}
1514 
1515 		tx = dmu_tx_create(os);
1516 
1517 		dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1518 		    ZFS_SA_BASE_ATTR_SIZE);
1519 
1520 		fuid_dirtied = zfsvfs->z_fuid_dirty;
1521 		if (fuid_dirtied)
1522 			zfs_fuid_txhold(zfsvfs, tx);
1523 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1524 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1525 		if (!zfsvfs->z_use_sa &&
1526 		    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1527 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1528 			    0, acl_ids.z_aclp->z_acl_bytes);
1529 		}
1530 		error = dmu_tx_assign(tx,
1531 		    (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1532 		if (error) {
1533 			zfs_dirent_unlock(dl);
1534 			if (error == ERESTART) {
1535 				waited = B_TRUE;
1536 				dmu_tx_wait(tx);
1537 				dmu_tx_abort(tx);
1538 				goto top;
1539 			}
1540 			zfs_acl_ids_free(&acl_ids);
1541 			dmu_tx_abort(tx);
1542 			ZFS_EXIT(zfsvfs);
1543 			return (error);
1544 		}
1545 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1546 
1547 		if (fuid_dirtied)
1548 			zfs_fuid_sync(zfsvfs, tx);
1549 
1550 		(void) zfs_link_create(dl, zp, tx, ZNEW);
1551 		txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1552 		if (flag & FIGNORECASE)
1553 			txtype |= TX_CI;
1554 		zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1555 		    vsecp, acl_ids.z_fuidp, vap);
1556 		zfs_acl_ids_free(&acl_ids);
1557 		dmu_tx_commit(tx);
1558 	} else {
1559 		int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1560 
1561 		if (have_acl)
1562 			zfs_acl_ids_free(&acl_ids);
1563 		have_acl = B_FALSE;
1564 
1565 		/*
1566 		 * A directory entry already exists for this name.
1567 		 */
1568 		/*
1569 		 * Can't truncate an existing file if in exclusive mode.
1570 		 */
1571 		if (excl == EXCL) {
1572 			error = SET_ERROR(EEXIST);
1573 			goto out;
1574 		}
1575 		/*
1576 		 * Can't open a directory for writing.
1577 		 */
1578 		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1579 			error = SET_ERROR(EISDIR);
1580 			goto out;
1581 		}
1582 		/*
1583 		 * Verify requested access to file.
1584 		 */
1585 		if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1586 			goto out;
1587 		}
1588 
1589 		mutex_enter(&dzp->z_lock);
1590 		dzp->z_seq++;
1591 		mutex_exit(&dzp->z_lock);
1592 
1593 		/*
1594 		 * Truncate regular files if requested.
1595 		 */
1596 		if ((ZTOV(zp)->v_type == VREG) &&
1597 		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1598 			/* we can't hold any locks when calling zfs_freesp() */
1599 			zfs_dirent_unlock(dl);
1600 			dl = NULL;
1601 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1602 			if (error == 0) {
1603 				vnevent_create(ZTOV(zp), ct);
1604 			}
1605 		}
1606 	}
1607 out:
1608 
1609 	if (dl)
1610 		zfs_dirent_unlock(dl);
1611 
1612 	if (error) {
1613 		if (zp)
1614 			VN_RELE(ZTOV(zp));
1615 	} else {
1616 		*vpp = ZTOV(zp);
1617 		error = specvp_check(vpp, cr);
1618 	}
1619 
1620 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1621 		zil_commit(zilog, 0);
1622 
1623 	ZFS_EXIT(zfsvfs);
1624 	return (error);
1625 }
1626 
1627 /*
1628  * Remove an entry from a directory.
1629  *
1630  *	IN:	dvp	- vnode of directory to remove entry from.
1631  *		name	- name of entry to remove.
1632  *		cr	- credentials of caller.
1633  *		ct	- caller context
1634  *		flags	- case flags
1635  *
1636  *	RETURN:	0 on success, error code on failure.
1637  *
1638  * Timestamps:
1639  *	dvp - ctime|mtime
1640  *	 vp - ctime (if nlink > 0)
1641  */
1642 
1643 uint64_t null_xattr = 0;
1644 
1645 /*ARGSUSED*/
1646 static int
1647 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1648     int flags)
1649 {
1650 	znode_t		*zp, *dzp = VTOZ(dvp);
1651 	znode_t		*xzp;
1652 	vnode_t		*vp;
1653 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1654 	zilog_t		*zilog;
1655 	uint64_t	acl_obj, xattr_obj;
1656 	uint64_t	xattr_obj_unlinked = 0;
1657 	uint64_t	obj = 0;
1658 	zfs_dirlock_t	*dl;
1659 	dmu_tx_t	*tx;
1660 	boolean_t	may_delete_now, delete_now = FALSE;
1661 	boolean_t	unlinked, toobig = FALSE;
1662 	uint64_t	txtype;
1663 	pathname_t	*realnmp = NULL;
1664 	pathname_t	realnm;
1665 	int		error;
1666 	int		zflg = ZEXISTS;
1667 	boolean_t	waited = B_FALSE;
1668 
1669 	ZFS_ENTER(zfsvfs);
1670 	ZFS_VERIFY_ZP(dzp);
1671 	zilog = zfsvfs->z_log;
1672 
1673 	if (flags & FIGNORECASE) {
1674 		zflg |= ZCILOOK;
1675 		pn_alloc(&realnm);
1676 		realnmp = &realnm;
1677 	}
1678 
1679 top:
1680 	xattr_obj = 0;
1681 	xzp = NULL;
1682 	/*
1683 	 * Attempt to lock directory; fail if entry doesn't exist.
1684 	 */
1685 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1686 	    NULL, realnmp)) {
1687 		if (realnmp)
1688 			pn_free(realnmp);
1689 		ZFS_EXIT(zfsvfs);
1690 		return (error);
1691 	}
1692 
1693 	vp = ZTOV(zp);
1694 
1695 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1696 		goto out;
1697 	}
1698 
1699 	/*
1700 	 * Need to use rmdir for removing directories.
1701 	 */
1702 	if (vp->v_type == VDIR) {
1703 		error = SET_ERROR(EPERM);
1704 		goto out;
1705 	}
1706 
1707 	vnevent_remove(vp, dvp, name, ct);
1708 
1709 	if (realnmp)
1710 		dnlc_remove(dvp, realnmp->pn_buf);
1711 	else
1712 		dnlc_remove(dvp, name);
1713 
1714 	mutex_enter(&vp->v_lock);
1715 	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1716 	mutex_exit(&vp->v_lock);
1717 
1718 	/*
1719 	 * We may delete the znode now, or we may put it in the unlinked set;
1720 	 * it depends on whether we're the last link, and on whether there are
1721 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1722 	 * allow for either case.
1723 	 */
1724 	obj = zp->z_id;
1725 	tx = dmu_tx_create(zfsvfs->z_os);
1726 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1727 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1728 	zfs_sa_upgrade_txholds(tx, zp);
1729 	zfs_sa_upgrade_txholds(tx, dzp);
1730 	if (may_delete_now) {
1731 		toobig =
1732 		    zp->z_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1733 		/* if the file is too big, only hold_free a token amount */
1734 		dmu_tx_hold_free(tx, zp->z_id, 0,
1735 		    (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1736 	}
1737 
1738 	/* are there any extended attributes? */
1739 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1740 	    &xattr_obj, sizeof (xattr_obj));
1741 	if (error == 0 && xattr_obj) {
1742 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1743 		ASSERT0(error);
1744 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1745 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1746 	}
1747 
1748 	mutex_enter(&zp->z_lock);
1749 	if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1750 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1751 	mutex_exit(&zp->z_lock);
1752 
1753 	/* charge as an update -- would be nice not to charge at all */
1754 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1755 
1756 	/*
1757 	 * Mark this transaction as typically resulting in a net free of space
1758 	 */
1759 	dmu_tx_mark_netfree(tx);
1760 
1761 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1762 	if (error) {
1763 		zfs_dirent_unlock(dl);
1764 		VN_RELE(vp);
1765 		if (xzp)
1766 			VN_RELE(ZTOV(xzp));
1767 		if (error == ERESTART) {
1768 			waited = B_TRUE;
1769 			dmu_tx_wait(tx);
1770 			dmu_tx_abort(tx);
1771 			goto top;
1772 		}
1773 		if (realnmp)
1774 			pn_free(realnmp);
1775 		dmu_tx_abort(tx);
1776 		ZFS_EXIT(zfsvfs);
1777 		return (error);
1778 	}
1779 
1780 	/*
1781 	 * Remove the directory entry.
1782 	 */
1783 	error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1784 
1785 	if (error) {
1786 		dmu_tx_commit(tx);
1787 		goto out;
1788 	}
1789 
1790 	if (unlinked) {
1791 		/*
1792 		 * Hold z_lock so that we can make sure that the ACL obj
1793 		 * hasn't changed.  Could have been deleted due to
1794 		 * zfs_sa_upgrade().
1795 		 */
1796 		mutex_enter(&zp->z_lock);
1797 		mutex_enter(&vp->v_lock);
1798 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1799 		    &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1800 		delete_now = may_delete_now && !toobig &&
1801 		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1802 		    xattr_obj == xattr_obj_unlinked && zfs_external_acl(zp) ==
1803 		    acl_obj;
1804 		mutex_exit(&vp->v_lock);
1805 	}
1806 
1807 	if (delete_now) {
1808 		if (xattr_obj_unlinked) {
1809 			ASSERT3U(xzp->z_links, ==, 2);
1810 			mutex_enter(&xzp->z_lock);
1811 			xzp->z_unlinked = 1;
1812 			xzp->z_links = 0;
1813 			error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1814 			    &xzp->z_links, sizeof (xzp->z_links), tx);
1815 			ASSERT3U(error,  ==,  0);
1816 			mutex_exit(&xzp->z_lock);
1817 			zfs_unlinked_add(xzp, tx);
1818 
1819 			if (zp->z_is_sa)
1820 				error = sa_remove(zp->z_sa_hdl,
1821 				    SA_ZPL_XATTR(zfsvfs), tx);
1822 			else
1823 				error = sa_update(zp->z_sa_hdl,
1824 				    SA_ZPL_XATTR(zfsvfs), &null_xattr,
1825 				    sizeof (uint64_t), tx);
1826 			ASSERT0(error);
1827 		}
1828 		mutex_enter(&vp->v_lock);
1829 		VN_RELE_LOCKED(vp);
1830 		ASSERT0(vp->v_count);
1831 		mutex_exit(&vp->v_lock);
1832 		mutex_exit(&zp->z_lock);
1833 		zfs_znode_delete(zp, tx);
1834 	} else if (unlinked) {
1835 		mutex_exit(&zp->z_lock);
1836 		zfs_unlinked_add(zp, tx);
1837 	}
1838 
1839 	txtype = TX_REMOVE;
1840 	if (flags & FIGNORECASE)
1841 		txtype |= TX_CI;
1842 	zfs_log_remove(zilog, tx, txtype, dzp, name, obj);
1843 
1844 	dmu_tx_commit(tx);
1845 out:
1846 	if (realnmp)
1847 		pn_free(realnmp);
1848 
1849 	zfs_dirent_unlock(dl);
1850 
1851 	if (!delete_now)
1852 		VN_RELE(vp);
1853 	if (xzp)
1854 		VN_RELE(ZTOV(xzp));
1855 
1856 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1857 		zil_commit(zilog, 0);
1858 
1859 	ZFS_EXIT(zfsvfs);
1860 	return (error);
1861 }
1862 
1863 /*
1864  * Create a new directory and insert it into dvp using the name
1865  * provided.  Return a pointer to the inserted directory.
1866  *
1867  *	IN:	dvp	- vnode of directory to add subdir to.
1868  *		dirname	- name of new directory.
1869  *		vap	- attributes of new directory.
1870  *		cr	- credentials of caller.
1871  *		ct	- caller context
1872  *		flags	- case flags
1873  *		vsecp	- ACL to be set
1874  *
1875  *	OUT:	vpp	- vnode of created directory.
1876  *
1877  *	RETURN:	0 on success, error code on failure.
1878  *
1879  * Timestamps:
1880  *	dvp - ctime|mtime updated
1881  *	 vp - ctime|mtime|atime updated
1882  */
1883 /*ARGSUSED*/
1884 static int
1885 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1886     caller_context_t *ct, int flags, vsecattr_t *vsecp)
1887 {
1888 	znode_t		*zp, *dzp = VTOZ(dvp);
1889 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1890 	zilog_t		*zilog;
1891 	zfs_dirlock_t	*dl;
1892 	uint64_t	txtype;
1893 	dmu_tx_t	*tx;
1894 	int		error;
1895 	int		zf = ZNEW;
1896 	ksid_t		*ksid;
1897 	uid_t		uid;
1898 	gid_t		gid = crgetgid(cr);
1899 	zfs_acl_ids_t   acl_ids;
1900 	boolean_t	fuid_dirtied;
1901 	boolean_t	waited = B_FALSE;
1902 
1903 	ASSERT(vap->va_type == VDIR);
1904 
1905 	/*
1906 	 * If we have an ephemeral id, ACL, or XVATTR then
1907 	 * make sure file system is at proper version
1908 	 */
1909 
1910 	ksid = crgetsid(cr, KSID_OWNER);
1911 	if (ksid)
1912 		uid = ksid_getid(ksid);
1913 	else
1914 		uid = crgetuid(cr);
1915 	if (zfsvfs->z_use_fuids == B_FALSE &&
1916 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1917 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1918 		return (SET_ERROR(EINVAL));
1919 
1920 	ZFS_ENTER(zfsvfs);
1921 	ZFS_VERIFY_ZP(dzp);
1922 	zilog = zfsvfs->z_log;
1923 
1924 	if (dzp->z_pflags & ZFS_XATTR) {
1925 		ZFS_EXIT(zfsvfs);
1926 		return (SET_ERROR(EINVAL));
1927 	}
1928 
1929 	if (zfsvfs->z_utf8 && u8_validate(dirname,
1930 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1931 		ZFS_EXIT(zfsvfs);
1932 		return (SET_ERROR(EILSEQ));
1933 	}
1934 	if (flags & FIGNORECASE)
1935 		zf |= ZCILOOK;
1936 
1937 	if (vap->va_mask & AT_XVATTR) {
1938 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1939 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1940 			ZFS_EXIT(zfsvfs);
1941 			return (error);
1942 		}
1943 	}
1944 
1945 	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1946 	    vsecp, &acl_ids)) != 0) {
1947 		ZFS_EXIT(zfsvfs);
1948 		return (error);
1949 	}
1950 	/*
1951 	 * First make sure the new directory doesn't exist.
1952 	 *
1953 	 * Existence is checked first to make sure we don't return
1954 	 * EACCES instead of EEXIST which can cause some applications
1955 	 * to fail.
1956 	 */
1957 top:
1958 	*vpp = NULL;
1959 
1960 	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
1961 	    NULL, NULL)) {
1962 		zfs_acl_ids_free(&acl_ids);
1963 		ZFS_EXIT(zfsvfs);
1964 		return (error);
1965 	}
1966 
1967 	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
1968 		zfs_acl_ids_free(&acl_ids);
1969 		zfs_dirent_unlock(dl);
1970 		ZFS_EXIT(zfsvfs);
1971 		return (error);
1972 	}
1973 
1974 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1975 		zfs_acl_ids_free(&acl_ids);
1976 		zfs_dirent_unlock(dl);
1977 		ZFS_EXIT(zfsvfs);
1978 		return (SET_ERROR(EDQUOT));
1979 	}
1980 
1981 	/*
1982 	 * Add a new entry to the directory.
1983 	 */
1984 	tx = dmu_tx_create(zfsvfs->z_os);
1985 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1986 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1987 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1988 	if (fuid_dirtied)
1989 		zfs_fuid_txhold(zfsvfs, tx);
1990 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1991 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1992 		    acl_ids.z_aclp->z_acl_bytes);
1993 	}
1994 
1995 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1996 	    ZFS_SA_BASE_ATTR_SIZE);
1997 
1998 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1999 	if (error) {
2000 		zfs_dirent_unlock(dl);
2001 		if (error == ERESTART) {
2002 			waited = B_TRUE;
2003 			dmu_tx_wait(tx);
2004 			dmu_tx_abort(tx);
2005 			goto top;
2006 		}
2007 		zfs_acl_ids_free(&acl_ids);
2008 		dmu_tx_abort(tx);
2009 		ZFS_EXIT(zfsvfs);
2010 		return (error);
2011 	}
2012 
2013 	/*
2014 	 * Create new node.
2015 	 */
2016 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
2017 
2018 	if (fuid_dirtied)
2019 		zfs_fuid_sync(zfsvfs, tx);
2020 
2021 	/*
2022 	 * Now put new name in parent dir.
2023 	 */
2024 	(void) zfs_link_create(dl, zp, tx, ZNEW);
2025 
2026 	*vpp = ZTOV(zp);
2027 
2028 	txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
2029 	if (flags & FIGNORECASE)
2030 		txtype |= TX_CI;
2031 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
2032 	    acl_ids.z_fuidp, vap);
2033 
2034 	zfs_acl_ids_free(&acl_ids);
2035 
2036 	dmu_tx_commit(tx);
2037 
2038 	zfs_dirent_unlock(dl);
2039 
2040 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2041 		zil_commit(zilog, 0);
2042 
2043 	ZFS_EXIT(zfsvfs);
2044 	return (0);
2045 }
2046 
2047 /*
2048  * Remove a directory subdir entry.  If the current working
2049  * directory is the same as the subdir to be removed, the
2050  * remove will fail.
2051  *
2052  *	IN:	dvp	- vnode of directory to remove from.
2053  *		name	- name of directory to be removed.
2054  *		cwd	- vnode of current working directory.
2055  *		cr	- credentials of caller.
2056  *		ct	- caller context
2057  *		flags	- case flags
2058  *
2059  *	RETURN:	0 on success, error code on failure.
2060  *
2061  * Timestamps:
2062  *	dvp - ctime|mtime updated
2063  */
2064 /*ARGSUSED*/
2065 static int
2066 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2067     caller_context_t *ct, int flags)
2068 {
2069 	znode_t		*dzp = VTOZ(dvp);
2070 	znode_t		*zp;
2071 	vnode_t		*vp;
2072 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2073 	zilog_t		*zilog;
2074 	zfs_dirlock_t	*dl;
2075 	dmu_tx_t	*tx;
2076 	int		error;
2077 	int		zflg = ZEXISTS;
2078 	boolean_t	waited = B_FALSE;
2079 
2080 	ZFS_ENTER(zfsvfs);
2081 	ZFS_VERIFY_ZP(dzp);
2082 	zilog = zfsvfs->z_log;
2083 
2084 	if (flags & FIGNORECASE)
2085 		zflg |= ZCILOOK;
2086 top:
2087 	zp = NULL;
2088 
2089 	/*
2090 	 * Attempt to lock directory; fail if entry doesn't exist.
2091 	 */
2092 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2093 	    NULL, NULL)) {
2094 		ZFS_EXIT(zfsvfs);
2095 		return (error);
2096 	}
2097 
2098 	vp = ZTOV(zp);
2099 
2100 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2101 		goto out;
2102 	}
2103 
2104 	if (vp->v_type != VDIR) {
2105 		error = SET_ERROR(ENOTDIR);
2106 		goto out;
2107 	}
2108 
2109 	if (vp == cwd) {
2110 		error = SET_ERROR(EINVAL);
2111 		goto out;
2112 	}
2113 
2114 	vnevent_rmdir(vp, dvp, name, ct);
2115 
2116 	/*
2117 	 * Grab a lock on the directory to make sure that noone is
2118 	 * trying to add (or lookup) entries while we are removing it.
2119 	 */
2120 	rw_enter(&zp->z_name_lock, RW_WRITER);
2121 
2122 	/*
2123 	 * Grab a lock on the parent pointer to make sure we play well
2124 	 * with the treewalk and directory rename code.
2125 	 */
2126 	rw_enter(&zp->z_parent_lock, RW_WRITER);
2127 
2128 	tx = dmu_tx_create(zfsvfs->z_os);
2129 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2130 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2131 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2132 	zfs_sa_upgrade_txholds(tx, zp);
2133 	zfs_sa_upgrade_txholds(tx, dzp);
2134 	dmu_tx_mark_netfree(tx);
2135 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
2136 	if (error) {
2137 		rw_exit(&zp->z_parent_lock);
2138 		rw_exit(&zp->z_name_lock);
2139 		zfs_dirent_unlock(dl);
2140 		VN_RELE(vp);
2141 		if (error == ERESTART) {
2142 			waited = B_TRUE;
2143 			dmu_tx_wait(tx);
2144 			dmu_tx_abort(tx);
2145 			goto top;
2146 		}
2147 		dmu_tx_abort(tx);
2148 		ZFS_EXIT(zfsvfs);
2149 		return (error);
2150 	}
2151 
2152 	error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2153 
2154 	if (error == 0) {
2155 		uint64_t txtype = TX_RMDIR;
2156 		if (flags & FIGNORECASE)
2157 			txtype |= TX_CI;
2158 		zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT);
2159 	}
2160 
2161 	dmu_tx_commit(tx);
2162 
2163 	rw_exit(&zp->z_parent_lock);
2164 	rw_exit(&zp->z_name_lock);
2165 out:
2166 	zfs_dirent_unlock(dl);
2167 
2168 	VN_RELE(vp);
2169 
2170 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2171 		zil_commit(zilog, 0);
2172 
2173 	ZFS_EXIT(zfsvfs);
2174 	return (error);
2175 }
2176 
2177 /*
2178  * Read as many directory entries as will fit into the provided
2179  * buffer from the given directory cursor position (specified in
2180  * the uio structure).
2181  *
2182  *	IN:	vp	- vnode of directory to read.
2183  *		uio	- structure supplying read location, range info,
2184  *			  and return buffer.
2185  *		cr	- credentials of caller.
2186  *		ct	- caller context
2187  *		flags	- case flags
2188  *
2189  *	OUT:	uio	- updated offset and range, buffer filled.
2190  *		eofp	- set to true if end-of-file detected.
2191  *
2192  *	RETURN:	0 on success, error code on failure.
2193  *
2194  * Timestamps:
2195  *	vp - atime updated
2196  *
2197  * Note that the low 4 bits of the cookie returned by zap is always zero.
2198  * This allows us to use the low range for "special" directory entries:
2199  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2200  * we use the offset 2 for the '.zfs' directory.
2201  */
2202 /* ARGSUSED */
2203 static int
2204 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp,
2205     caller_context_t *ct, int flags)
2206 {
2207 	znode_t		*zp = VTOZ(vp);
2208 	iovec_t		*iovp;
2209 	edirent_t	*eodp;
2210 	dirent64_t	*odp;
2211 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2212 	objset_t	*os;
2213 	caddr_t		outbuf;
2214 	size_t		bufsize;
2215 	zap_cursor_t	zc;
2216 	zap_attribute_t	zap;
2217 	uint_t		bytes_wanted;
2218 	uint64_t	offset; /* must be unsigned; checks for < 1 */
2219 	uint64_t	parent;
2220 	int		local_eof;
2221 	int		outcount;
2222 	int		error;
2223 	uint8_t		prefetch;
2224 	boolean_t	check_sysattrs;
2225 
2226 	ZFS_ENTER(zfsvfs);
2227 	ZFS_VERIFY_ZP(zp);
2228 
2229 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2230 	    &parent, sizeof (parent))) != 0) {
2231 		ZFS_EXIT(zfsvfs);
2232 		return (error);
2233 	}
2234 
2235 	/*
2236 	 * If we are not given an eof variable,
2237 	 * use a local one.
2238 	 */
2239 	if (eofp == NULL)
2240 		eofp = &local_eof;
2241 
2242 	/*
2243 	 * Check for valid iov_len.
2244 	 */
2245 	if (uio->uio_iov->iov_len <= 0) {
2246 		ZFS_EXIT(zfsvfs);
2247 		return (SET_ERROR(EINVAL));
2248 	}
2249 
2250 	/*
2251 	 * Quit if directory has been removed (posix)
2252 	 */
2253 	if ((*eofp = zp->z_unlinked) != 0) {
2254 		ZFS_EXIT(zfsvfs);
2255 		return (0);
2256 	}
2257 
2258 	error = 0;
2259 	os = zfsvfs->z_os;
2260 	offset = uio->uio_loffset;
2261 	prefetch = zp->z_zn_prefetch;
2262 
2263 	/*
2264 	 * Initialize the iterator cursor.
2265 	 */
2266 	if (offset <= 3) {
2267 		/*
2268 		 * Start iteration from the beginning of the directory.
2269 		 */
2270 		zap_cursor_init(&zc, os, zp->z_id);
2271 	} else {
2272 		/*
2273 		 * The offset is a serialized cursor.
2274 		 */
2275 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2276 	}
2277 
2278 	/*
2279 	 * Get space to change directory entries into fs independent format.
2280 	 */
2281 	iovp = uio->uio_iov;
2282 	bytes_wanted = iovp->iov_len;
2283 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2284 		bufsize = bytes_wanted;
2285 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
2286 		odp = (struct dirent64 *)outbuf;
2287 	} else {
2288 		bufsize = bytes_wanted;
2289 		outbuf = NULL;
2290 		odp = (struct dirent64 *)iovp->iov_base;
2291 	}
2292 	eodp = (struct edirent *)odp;
2293 
2294 	/*
2295 	 * If this VFS supports the system attribute view interface; and
2296 	 * we're looking at an extended attribute directory; and we care
2297 	 * about normalization conflicts on this vfs; then we must check
2298 	 * for normalization conflicts with the sysattr name space.
2299 	 */
2300 	check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2301 	    (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2302 	    (flags & V_RDDIR_ENTFLAGS);
2303 
2304 	/*
2305 	 * Transform to file-system independent format
2306 	 */
2307 	outcount = 0;
2308 	while (outcount < bytes_wanted) {
2309 		ino64_t objnum;
2310 		ushort_t reclen;
2311 		off64_t *next = NULL;
2312 
2313 		/*
2314 		 * Special case `.', `..', and `.zfs'.
2315 		 */
2316 		if (offset == 0) {
2317 			(void) strcpy(zap.za_name, ".");
2318 			zap.za_normalization_conflict = 0;
2319 			objnum = zp->z_id;
2320 		} else if (offset == 1) {
2321 			(void) strcpy(zap.za_name, "..");
2322 			zap.za_normalization_conflict = 0;
2323 			objnum = parent;
2324 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
2325 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2326 			zap.za_normalization_conflict = 0;
2327 			objnum = ZFSCTL_INO_ROOT;
2328 		} else {
2329 			/*
2330 			 * Grab next entry.
2331 			 */
2332 			if (error = zap_cursor_retrieve(&zc, &zap)) {
2333 				if ((*eofp = (error == ENOENT)) != 0)
2334 					break;
2335 				else
2336 					goto update;
2337 			}
2338 
2339 			if (zap.za_integer_length != 8 ||
2340 			    zap.za_num_integers != 1) {
2341 				cmn_err(CE_WARN, "zap_readdir: bad directory "
2342 				    "entry, obj = %lld, offset = %lld\n",
2343 				    (u_longlong_t)zp->z_id,
2344 				    (u_longlong_t)offset);
2345 				error = SET_ERROR(ENXIO);
2346 				goto update;
2347 			}
2348 
2349 			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2350 			/*
2351 			 * MacOS X can extract the object type here such as:
2352 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2353 			 */
2354 
2355 			if (check_sysattrs && !zap.za_normalization_conflict) {
2356 				zap.za_normalization_conflict =
2357 				    xattr_sysattr_casechk(zap.za_name);
2358 			}
2359 		}
2360 
2361 		if (flags & V_RDDIR_ACCFILTER) {
2362 			/*
2363 			 * If we have no access at all, don't include
2364 			 * this entry in the returned information
2365 			 */
2366 			znode_t	*ezp;
2367 			if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2368 				goto skip_entry;
2369 			if (!zfs_has_access(ezp, cr)) {
2370 				VN_RELE(ZTOV(ezp));
2371 				goto skip_entry;
2372 			}
2373 			VN_RELE(ZTOV(ezp));
2374 		}
2375 
2376 		if (flags & V_RDDIR_ENTFLAGS)
2377 			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2378 		else
2379 			reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2380 
2381 		/*
2382 		 * Will this entry fit in the buffer?
2383 		 */
2384 		if (outcount + reclen > bufsize) {
2385 			/*
2386 			 * Did we manage to fit anything in the buffer?
2387 			 */
2388 			if (!outcount) {
2389 				error = SET_ERROR(EINVAL);
2390 				goto update;
2391 			}
2392 			break;
2393 		}
2394 		if (flags & V_RDDIR_ENTFLAGS) {
2395 			/*
2396 			 * Add extended flag entry:
2397 			 */
2398 			eodp->ed_ino = objnum;
2399 			eodp->ed_reclen = reclen;
2400 			/* NOTE: ed_off is the offset for the *next* entry */
2401 			next = &(eodp->ed_off);
2402 			eodp->ed_eflags = zap.za_normalization_conflict ?
2403 			    ED_CASE_CONFLICT : 0;
2404 			(void) strncpy(eodp->ed_name, zap.za_name,
2405 			    EDIRENT_NAMELEN(reclen));
2406 			eodp = (edirent_t *)((intptr_t)eodp + reclen);
2407 		} else {
2408 			/*
2409 			 * Add normal entry:
2410 			 */
2411 			odp->d_ino = objnum;
2412 			odp->d_reclen = reclen;
2413 			/* NOTE: d_off is the offset for the *next* entry */
2414 			next = &(odp->d_off);
2415 			(void) strncpy(odp->d_name, zap.za_name,
2416 			    DIRENT64_NAMELEN(reclen));
2417 			odp = (dirent64_t *)((intptr_t)odp + reclen);
2418 		}
2419 		outcount += reclen;
2420 
2421 		ASSERT(outcount <= bufsize);
2422 
2423 		/* Prefetch znode */
2424 		if (prefetch)
2425 			dmu_prefetch(os, objnum, 0, 0, 0,
2426 			    ZIO_PRIORITY_SYNC_READ);
2427 
2428 	skip_entry:
2429 		/*
2430 		 * Move to the next entry, fill in the previous offset.
2431 		 */
2432 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2433 			zap_cursor_advance(&zc);
2434 			offset = zap_cursor_serialize(&zc);
2435 		} else {
2436 			offset += 1;
2437 		}
2438 		if (next)
2439 			*next = offset;
2440 	}
2441 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2442 
2443 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2444 		iovp->iov_base += outcount;
2445 		iovp->iov_len -= outcount;
2446 		uio->uio_resid -= outcount;
2447 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2448 		/*
2449 		 * Reset the pointer.
2450 		 */
2451 		offset = uio->uio_loffset;
2452 	}
2453 
2454 update:
2455 	zap_cursor_fini(&zc);
2456 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2457 		kmem_free(outbuf, bufsize);
2458 
2459 	if (error == ENOENT)
2460 		error = 0;
2461 
2462 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2463 
2464 	uio->uio_loffset = offset;
2465 	ZFS_EXIT(zfsvfs);
2466 	return (error);
2467 }
2468 
2469 ulong_t zfs_fsync_sync_cnt = 4;
2470 
2471 static int
2472 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2473 {
2474 	znode_t	*zp = VTOZ(vp);
2475 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2476 
2477 	/*
2478 	 * Regardless of whether this is required for standards conformance,
2479 	 * this is the logical behavior when fsync() is called on a file with
2480 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
2481 	 * going to be pushed out as part of the zil_commit().
2482 	 */
2483 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2484 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
2485 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr, ct);
2486 
2487 	(void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2488 
2489 	if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2490 		ZFS_ENTER(zfsvfs);
2491 		ZFS_VERIFY_ZP(zp);
2492 		zil_commit(zfsvfs->z_log, zp->z_id);
2493 		ZFS_EXIT(zfsvfs);
2494 	}
2495 	return (0);
2496 }
2497 
2498 
2499 /*
2500  * Get the requested file attributes and place them in the provided
2501  * vattr structure.
2502  *
2503  *	IN:	vp	- vnode of file.
2504  *		vap	- va_mask identifies requested attributes.
2505  *			  If AT_XVATTR set, then optional attrs are requested
2506  *		flags	- ATTR_NOACLCHECK (CIFS server context)
2507  *		cr	- credentials of caller.
2508  *		ct	- caller context
2509  *
2510  *	OUT:	vap	- attribute values.
2511  *
2512  *	RETURN:	0 (always succeeds).
2513  */
2514 /* ARGSUSED */
2515 static int
2516 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2517     caller_context_t *ct)
2518 {
2519 	znode_t *zp = VTOZ(vp);
2520 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2521 	int	error = 0;
2522 	uint64_t links;
2523 	uint64_t mtime[2], ctime[2];
2524 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2525 	xoptattr_t *xoap = NULL;
2526 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2527 	sa_bulk_attr_t bulk[2];
2528 	int count = 0;
2529 
2530 	ZFS_ENTER(zfsvfs);
2531 	ZFS_VERIFY_ZP(zp);
2532 
2533 	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2534 
2535 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2536 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2537 
2538 	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2539 		ZFS_EXIT(zfsvfs);
2540 		return (error);
2541 	}
2542 
2543 	/*
2544 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2545 	 * Also, if we are the owner don't bother, since owner should
2546 	 * always be allowed to read basic attributes of file.
2547 	 */
2548 	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2549 	    (vap->va_uid != crgetuid(cr))) {
2550 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2551 		    skipaclchk, cr)) {
2552 			ZFS_EXIT(zfsvfs);
2553 			return (error);
2554 		}
2555 	}
2556 
2557 	/*
2558 	 * Return all attributes.  It's cheaper to provide the answer
2559 	 * than to determine whether we were asked the question.
2560 	 */
2561 
2562 	mutex_enter(&zp->z_lock);
2563 	vap->va_type = vp->v_type;
2564 	vap->va_mode = zp->z_mode & MODEMASK;
2565 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2566 	vap->va_nodeid = zp->z_id;
2567 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2568 		links = zp->z_links + 1;
2569 	else
2570 		links = zp->z_links;
2571 	vap->va_nlink = MIN(links, UINT32_MAX);	/* nlink_t limit! */
2572 	vap->va_size = zp->z_size;
2573 	vap->va_rdev = vp->v_rdev;
2574 	vap->va_seq = zp->z_seq;
2575 
2576 	/*
2577 	 * Add in any requested optional attributes and the create time.
2578 	 * Also set the corresponding bits in the returned attribute bitmap.
2579 	 */
2580 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2581 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2582 			xoap->xoa_archive =
2583 			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2584 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2585 		}
2586 
2587 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2588 			xoap->xoa_readonly =
2589 			    ((zp->z_pflags & ZFS_READONLY) != 0);
2590 			XVA_SET_RTN(xvap, XAT_READONLY);
2591 		}
2592 
2593 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2594 			xoap->xoa_system =
2595 			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2596 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2597 		}
2598 
2599 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2600 			xoap->xoa_hidden =
2601 			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2602 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2603 		}
2604 
2605 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2606 			xoap->xoa_nounlink =
2607 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2608 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2609 		}
2610 
2611 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2612 			xoap->xoa_immutable =
2613 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2614 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2615 		}
2616 
2617 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2618 			xoap->xoa_appendonly =
2619 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2620 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2621 		}
2622 
2623 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2624 			xoap->xoa_nodump =
2625 			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2626 			XVA_SET_RTN(xvap, XAT_NODUMP);
2627 		}
2628 
2629 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2630 			xoap->xoa_opaque =
2631 			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2632 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2633 		}
2634 
2635 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2636 			xoap->xoa_av_quarantined =
2637 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2638 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2639 		}
2640 
2641 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2642 			xoap->xoa_av_modified =
2643 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2644 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2645 		}
2646 
2647 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2648 		    vp->v_type == VREG) {
2649 			zfs_sa_get_scanstamp(zp, xvap);
2650 		}
2651 
2652 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2653 			uint64_t times[2];
2654 
2655 			(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2656 			    times, sizeof (times));
2657 			ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2658 			XVA_SET_RTN(xvap, XAT_CREATETIME);
2659 		}
2660 
2661 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2662 			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2663 			XVA_SET_RTN(xvap, XAT_REPARSE);
2664 		}
2665 		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2666 			xoap->xoa_generation = zp->z_gen;
2667 			XVA_SET_RTN(xvap, XAT_GEN);
2668 		}
2669 
2670 		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2671 			xoap->xoa_offline =
2672 			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2673 			XVA_SET_RTN(xvap, XAT_OFFLINE);
2674 		}
2675 
2676 		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2677 			xoap->xoa_sparse =
2678 			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2679 			XVA_SET_RTN(xvap, XAT_SPARSE);
2680 		}
2681 	}
2682 
2683 	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2684 	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2685 	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2686 
2687 	mutex_exit(&zp->z_lock);
2688 
2689 	sa_object_size(zp->z_sa_hdl, &vap->va_blksize, &vap->va_nblocks);
2690 
2691 	if (zp->z_blksz == 0) {
2692 		/*
2693 		 * Block size hasn't been set; suggest maximal I/O transfers.
2694 		 */
2695 		vap->va_blksize = zfsvfs->z_max_blksz;
2696 	}
2697 
2698 	ZFS_EXIT(zfsvfs);
2699 	return (0);
2700 }
2701 
2702 /*
2703  * Set the file attributes to the values contained in the
2704  * vattr structure.
2705  *
2706  *	IN:	vp	- vnode of file to be modified.
2707  *		vap	- new attribute values.
2708  *			  If AT_XVATTR set, then optional attrs are being set
2709  *		flags	- ATTR_UTIME set if non-default time values provided.
2710  *			- ATTR_NOACLCHECK (CIFS context only).
2711  *		cr	- credentials of caller.
2712  *		ct	- caller context
2713  *
2714  *	RETURN:	0 on success, error code on failure.
2715  *
2716  * Timestamps:
2717  *	vp - ctime updated, mtime updated if size changed.
2718  */
2719 /* ARGSUSED */
2720 static int
2721 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2722     caller_context_t *ct)
2723 {
2724 	znode_t		*zp = VTOZ(vp);
2725 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2726 	zilog_t		*zilog;
2727 	dmu_tx_t	*tx;
2728 	vattr_t		oldva;
2729 	xvattr_t	tmpxvattr;
2730 	uint_t		mask = vap->va_mask;
2731 	uint_t		saved_mask = 0;
2732 	int		trim_mask = 0;
2733 	uint64_t	new_mode;
2734 	uint64_t	new_uid, new_gid;
2735 	uint64_t	xattr_obj;
2736 	uint64_t	mtime[2], ctime[2];
2737 	znode_t		*attrzp;
2738 	int		need_policy = FALSE;
2739 	int		err, err2;
2740 	zfs_fuid_info_t *fuidp = NULL;
2741 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2742 	xoptattr_t	*xoap;
2743 	zfs_acl_t	*aclp;
2744 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2745 	boolean_t	fuid_dirtied = B_FALSE;
2746 	sa_bulk_attr_t	bulk[7], xattr_bulk[7];
2747 	int		count = 0, xattr_count = 0;
2748 
2749 	if (mask == 0)
2750 		return (0);
2751 
2752 	if (mask & AT_NOSET)
2753 		return (SET_ERROR(EINVAL));
2754 
2755 	ZFS_ENTER(zfsvfs);
2756 	ZFS_VERIFY_ZP(zp);
2757 
2758 	zilog = zfsvfs->z_log;
2759 
2760 	/*
2761 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
2762 	 * that file system is at proper version level
2763 	 */
2764 
2765 	if (zfsvfs->z_use_fuids == B_FALSE &&
2766 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2767 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2768 	    (mask & AT_XVATTR))) {
2769 		ZFS_EXIT(zfsvfs);
2770 		return (SET_ERROR(EINVAL));
2771 	}
2772 
2773 	if (mask & AT_SIZE && vp->v_type == VDIR) {
2774 		ZFS_EXIT(zfsvfs);
2775 		return (SET_ERROR(EISDIR));
2776 	}
2777 
2778 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2779 		ZFS_EXIT(zfsvfs);
2780 		return (SET_ERROR(EINVAL));
2781 	}
2782 
2783 	/*
2784 	 * If this is an xvattr_t, then get a pointer to the structure of
2785 	 * optional attributes.  If this is NULL, then we have a vattr_t.
2786 	 */
2787 	xoap = xva_getxoptattr(xvap);
2788 
2789 	xva_init(&tmpxvattr);
2790 
2791 	/*
2792 	 * Immutable files can only alter immutable bit and atime
2793 	 */
2794 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2795 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2796 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2797 		ZFS_EXIT(zfsvfs);
2798 		return (SET_ERROR(EPERM));
2799 	}
2800 
2801 	/*
2802 	 * Note: ZFS_READONLY is handled in zfs_zaccess_common.
2803 	 */
2804 
2805 	/*
2806 	 * Verify timestamps doesn't overflow 32 bits.
2807 	 * ZFS can handle large timestamps, but 32bit syscalls can't
2808 	 * handle times greater than 2039.  This check should be removed
2809 	 * once large timestamps are fully supported.
2810 	 */
2811 	if (mask & (AT_ATIME | AT_MTIME)) {
2812 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2813 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2814 			ZFS_EXIT(zfsvfs);
2815 			return (SET_ERROR(EOVERFLOW));
2816 		}
2817 	}
2818 
2819 top:
2820 	attrzp = NULL;
2821 	aclp = NULL;
2822 
2823 	/* Can this be moved to before the top label? */
2824 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2825 		ZFS_EXIT(zfsvfs);
2826 		return (SET_ERROR(EROFS));
2827 	}
2828 
2829 	/*
2830 	 * First validate permissions
2831 	 */
2832 
2833 	if (mask & AT_SIZE) {
2834 		err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
2835 		if (err) {
2836 			ZFS_EXIT(zfsvfs);
2837 			return (err);
2838 		}
2839 		/*
2840 		 * XXX - Note, we are not providing any open
2841 		 * mode flags here (like FNDELAY), so we may
2842 		 * block if there are locks present... this
2843 		 * should be addressed in openat().
2844 		 */
2845 		/* XXX - would it be OK to generate a log record here? */
2846 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2847 		if (err) {
2848 			ZFS_EXIT(zfsvfs);
2849 			return (err);
2850 		}
2851 
2852 		if (vap->va_size == 0)
2853 			vnevent_truncate(ZTOV(zp), ct);
2854 	}
2855 
2856 	if (mask & (AT_ATIME|AT_MTIME) ||
2857 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2858 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2859 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2860 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2861 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2862 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2863 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2864 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2865 		    skipaclchk, cr);
2866 	}
2867 
2868 	if (mask & (AT_UID|AT_GID)) {
2869 		int	idmask = (mask & (AT_UID|AT_GID));
2870 		int	take_owner;
2871 		int	take_group;
2872 
2873 		/*
2874 		 * NOTE: even if a new mode is being set,
2875 		 * we may clear S_ISUID/S_ISGID bits.
2876 		 */
2877 
2878 		if (!(mask & AT_MODE))
2879 			vap->va_mode = zp->z_mode;
2880 
2881 		/*
2882 		 * Take ownership or chgrp to group we are a member of
2883 		 */
2884 
2885 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2886 		take_group = (mask & AT_GID) &&
2887 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
2888 
2889 		/*
2890 		 * If both AT_UID and AT_GID are set then take_owner and
2891 		 * take_group must both be set in order to allow taking
2892 		 * ownership.
2893 		 *
2894 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2895 		 *
2896 		 */
2897 
2898 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2899 		    ((idmask == AT_UID) && take_owner) ||
2900 		    ((idmask == AT_GID) && take_group)) {
2901 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2902 			    skipaclchk, cr) == 0) {
2903 				/*
2904 				 * Remove setuid/setgid for non-privileged users
2905 				 */
2906 				secpolicy_setid_clear(vap, cr);
2907 				trim_mask = (mask & (AT_UID|AT_GID));
2908 			} else {
2909 				need_policy =  TRUE;
2910 			}
2911 		} else {
2912 			need_policy =  TRUE;
2913 		}
2914 	}
2915 
2916 	mutex_enter(&zp->z_lock);
2917 	oldva.va_mode = zp->z_mode;
2918 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2919 	if (mask & AT_XVATTR) {
2920 		/*
2921 		 * Update xvattr mask to include only those attributes
2922 		 * that are actually changing.
2923 		 *
2924 		 * the bits will be restored prior to actually setting
2925 		 * the attributes so the caller thinks they were set.
2926 		 */
2927 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2928 			if (xoap->xoa_appendonly !=
2929 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2930 				need_policy = TRUE;
2931 			} else {
2932 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2933 				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2934 			}
2935 		}
2936 
2937 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2938 			if (xoap->xoa_nounlink !=
2939 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2940 				need_policy = TRUE;
2941 			} else {
2942 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2943 				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2944 			}
2945 		}
2946 
2947 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2948 			if (xoap->xoa_immutable !=
2949 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2950 				need_policy = TRUE;
2951 			} else {
2952 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2953 				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2954 			}
2955 		}
2956 
2957 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2958 			if (xoap->xoa_nodump !=
2959 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2960 				need_policy = TRUE;
2961 			} else {
2962 				XVA_CLR_REQ(xvap, XAT_NODUMP);
2963 				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
2964 			}
2965 		}
2966 
2967 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2968 			if (xoap->xoa_av_modified !=
2969 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2970 				need_policy = TRUE;
2971 			} else {
2972 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2973 				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
2974 			}
2975 		}
2976 
2977 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2978 			if ((vp->v_type != VREG &&
2979 			    xoap->xoa_av_quarantined) ||
2980 			    xoap->xoa_av_quarantined !=
2981 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2982 				need_policy = TRUE;
2983 			} else {
2984 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2985 				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
2986 			}
2987 		}
2988 
2989 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2990 			mutex_exit(&zp->z_lock);
2991 			ZFS_EXIT(zfsvfs);
2992 			return (SET_ERROR(EPERM));
2993 		}
2994 
2995 		if (need_policy == FALSE &&
2996 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2997 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2998 			need_policy = TRUE;
2999 		}
3000 	}
3001 
3002 	mutex_exit(&zp->z_lock);
3003 
3004 	if (mask & AT_MODE) {
3005 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
3006 			err = secpolicy_setid_setsticky_clear(vp, vap,
3007 			    &oldva, cr);
3008 			if (err) {
3009 				ZFS_EXIT(zfsvfs);
3010 				return (err);
3011 			}
3012 			trim_mask |= AT_MODE;
3013 		} else {
3014 			need_policy = TRUE;
3015 		}
3016 	}
3017 
3018 	if (need_policy) {
3019 		/*
3020 		 * If trim_mask is set then take ownership
3021 		 * has been granted or write_acl is present and user
3022 		 * has the ability to modify mode.  In that case remove
3023 		 * UID|GID and or MODE from mask so that
3024 		 * secpolicy_vnode_setattr() doesn't revoke it.
3025 		 */
3026 
3027 		if (trim_mask) {
3028 			saved_mask = vap->va_mask;
3029 			vap->va_mask &= ~trim_mask;
3030 		}
3031 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
3032 		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
3033 		if (err) {
3034 			ZFS_EXIT(zfsvfs);
3035 			return (err);
3036 		}
3037 
3038 		if (trim_mask)
3039 			vap->va_mask |= saved_mask;
3040 	}
3041 
3042 	/*
3043 	 * secpolicy_vnode_setattr, or take ownership may have
3044 	 * changed va_mask
3045 	 */
3046 	mask = vap->va_mask;
3047 
3048 	if ((mask & (AT_UID | AT_GID))) {
3049 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
3050 		    &xattr_obj, sizeof (xattr_obj));
3051 
3052 		if (err == 0 && xattr_obj) {
3053 			err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
3054 			if (err)
3055 				goto out2;
3056 		}
3057 		if (mask & AT_UID) {
3058 			new_uid = zfs_fuid_create(zfsvfs,
3059 			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3060 			if (new_uid != zp->z_uid &&
3061 			    zfs_fuid_overquota(zfsvfs, B_FALSE, new_uid)) {
3062 				if (attrzp)
3063 					VN_RELE(ZTOV(attrzp));
3064 				err = SET_ERROR(EDQUOT);
3065 				goto out2;
3066 			}
3067 		}
3068 
3069 		if (mask & AT_GID) {
3070 			new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3071 			    cr, ZFS_GROUP, &fuidp);
3072 			if (new_gid != zp->z_gid &&
3073 			    zfs_fuid_overquota(zfsvfs, B_TRUE, new_gid)) {
3074 				if (attrzp)
3075 					VN_RELE(ZTOV(attrzp));
3076 				err = SET_ERROR(EDQUOT);
3077 				goto out2;
3078 			}
3079 		}
3080 	}
3081 	tx = dmu_tx_create(zfsvfs->z_os);
3082 
3083 	if (mask & AT_MODE) {
3084 		uint64_t pmode = zp->z_mode;
3085 		uint64_t acl_obj;
3086 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3087 
3088 		if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
3089 		    !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
3090 			err = SET_ERROR(EPERM);
3091 			goto out;
3092 		}
3093 
3094 		if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3095 			goto out;
3096 
3097 		mutex_enter(&zp->z_lock);
3098 		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
3099 			/*
3100 			 * Are we upgrading ACL from old V0 format
3101 			 * to V1 format?
3102 			 */
3103 			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
3104 			    zfs_znode_acl_version(zp) ==
3105 			    ZFS_ACL_VERSION_INITIAL) {
3106 				dmu_tx_hold_free(tx, acl_obj, 0,
3107 				    DMU_OBJECT_END);
3108 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3109 				    0, aclp->z_acl_bytes);
3110 			} else {
3111 				dmu_tx_hold_write(tx, acl_obj, 0,
3112 				    aclp->z_acl_bytes);
3113 			}
3114 		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3115 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3116 			    0, aclp->z_acl_bytes);
3117 		}
3118 		mutex_exit(&zp->z_lock);
3119 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3120 	} else {
3121 		if ((mask & AT_XVATTR) &&
3122 		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3123 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3124 		else
3125 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3126 	}
3127 
3128 	if (attrzp) {
3129 		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
3130 	}
3131 
3132 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3133 	if (fuid_dirtied)
3134 		zfs_fuid_txhold(zfsvfs, tx);
3135 
3136 	zfs_sa_upgrade_txholds(tx, zp);
3137 
3138 	err = dmu_tx_assign(tx, TXG_WAIT);
3139 	if (err)
3140 		goto out;
3141 
3142 	count = 0;
3143 	/*
3144 	 * Set each attribute requested.
3145 	 * We group settings according to the locks they need to acquire.
3146 	 *
3147 	 * Note: you cannot set ctime directly, although it will be
3148 	 * updated as a side-effect of calling this function.
3149 	 */
3150 
3151 
3152 	if (mask & (AT_UID|AT_GID|AT_MODE))
3153 		mutex_enter(&zp->z_acl_lock);
3154 	mutex_enter(&zp->z_lock);
3155 
3156 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3157 	    &zp->z_pflags, sizeof (zp->z_pflags));
3158 
3159 	if (attrzp) {
3160 		if (mask & (AT_UID|AT_GID|AT_MODE))
3161 			mutex_enter(&attrzp->z_acl_lock);
3162 		mutex_enter(&attrzp->z_lock);
3163 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3164 		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
3165 		    sizeof (attrzp->z_pflags));
3166 	}
3167 
3168 	if (mask & (AT_UID|AT_GID)) {
3169 
3170 		if (mask & AT_UID) {
3171 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
3172 			    &new_uid, sizeof (new_uid));
3173 			zp->z_uid = new_uid;
3174 			if (attrzp) {
3175 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3176 				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
3177 				    sizeof (new_uid));
3178 				attrzp->z_uid = new_uid;
3179 			}
3180 		}
3181 
3182 		if (mask & AT_GID) {
3183 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
3184 			    NULL, &new_gid, sizeof (new_gid));
3185 			zp->z_gid = new_gid;
3186 			if (attrzp) {
3187 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3188 				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
3189 				    sizeof (new_gid));
3190 				attrzp->z_gid = new_gid;
3191 			}
3192 		}
3193 		if (!(mask & AT_MODE)) {
3194 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
3195 			    NULL, &new_mode, sizeof (new_mode));
3196 			new_mode = zp->z_mode;
3197 		}
3198 		err = zfs_acl_chown_setattr(zp);
3199 		ASSERT(err == 0);
3200 		if (attrzp) {
3201 			err = zfs_acl_chown_setattr(attrzp);
3202 			ASSERT(err == 0);
3203 		}
3204 	}
3205 
3206 	if (mask & AT_MODE) {
3207 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
3208 		    &new_mode, sizeof (new_mode));
3209 		zp->z_mode = new_mode;
3210 		ASSERT3U((uintptr_t)aclp, !=, NULL);
3211 		err = zfs_aclset_common(zp, aclp, cr, tx);
3212 		ASSERT0(err);
3213 		if (zp->z_acl_cached)
3214 			zfs_acl_free(zp->z_acl_cached);
3215 		zp->z_acl_cached = aclp;
3216 		aclp = NULL;
3217 	}
3218 
3219 
3220 	if (mask & AT_ATIME) {
3221 		ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
3222 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
3223 		    &zp->z_atime, sizeof (zp->z_atime));
3224 	}
3225 
3226 	if (mask & AT_MTIME) {
3227 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3228 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3229 		    mtime, sizeof (mtime));
3230 	}
3231 
3232 	/* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3233 	if (mask & AT_SIZE && !(mask & AT_MTIME)) {
3234 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
3235 		    NULL, mtime, sizeof (mtime));
3236 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3237 		    &ctime, sizeof (ctime));
3238 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3239 		    B_TRUE);
3240 	} else if (mask != 0) {
3241 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3242 		    &ctime, sizeof (ctime));
3243 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
3244 		    B_TRUE);
3245 		if (attrzp) {
3246 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3247 			    SA_ZPL_CTIME(zfsvfs), NULL,
3248 			    &ctime, sizeof (ctime));
3249 			zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3250 			    mtime, ctime, B_TRUE);
3251 		}
3252 	}
3253 	/*
3254 	 * Do this after setting timestamps to prevent timestamp
3255 	 * update from toggling bit
3256 	 */
3257 
3258 	if (xoap && (mask & AT_XVATTR)) {
3259 
3260 		/*
3261 		 * restore trimmed off masks
3262 		 * so that return masks can be set for caller.
3263 		 */
3264 
3265 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3266 			XVA_SET_REQ(xvap, XAT_APPENDONLY);
3267 		}
3268 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3269 			XVA_SET_REQ(xvap, XAT_NOUNLINK);
3270 		}
3271 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3272 			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3273 		}
3274 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3275 			XVA_SET_REQ(xvap, XAT_NODUMP);
3276 		}
3277 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3278 			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3279 		}
3280 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3281 			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3282 		}
3283 
3284 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3285 			ASSERT(vp->v_type == VREG);
3286 
3287 		zfs_xvattr_set(zp, xvap, tx);
3288 	}
3289 
3290 	if (fuid_dirtied)
3291 		zfs_fuid_sync(zfsvfs, tx);
3292 
3293 	if (mask != 0)
3294 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3295 
3296 	mutex_exit(&zp->z_lock);
3297 	if (mask & (AT_UID|AT_GID|AT_MODE))
3298 		mutex_exit(&zp->z_acl_lock);
3299 
3300 	if (attrzp) {
3301 		if (mask & (AT_UID|AT_GID|AT_MODE))
3302 			mutex_exit(&attrzp->z_acl_lock);
3303 		mutex_exit(&attrzp->z_lock);
3304 	}
3305 out:
3306 	if (err == 0 && attrzp) {
3307 		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3308 		    xattr_count, tx);
3309 		ASSERT(err2 == 0);
3310 	}
3311 
3312 	if (attrzp)
3313 		VN_RELE(ZTOV(attrzp));
3314 
3315 	if (aclp)
3316 		zfs_acl_free(aclp);
3317 
3318 	if (fuidp) {
3319 		zfs_fuid_info_free(fuidp);
3320 		fuidp = NULL;
3321 	}
3322 
3323 	if (err) {
3324 		dmu_tx_abort(tx);
3325 		if (err == ERESTART)
3326 			goto top;
3327 	} else {
3328 		err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3329 		dmu_tx_commit(tx);
3330 	}
3331 
3332 out2:
3333 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3334 		zil_commit(zilog, 0);
3335 
3336 	ZFS_EXIT(zfsvfs);
3337 	return (err);
3338 }
3339 
3340 typedef struct zfs_zlock {
3341 	krwlock_t	*zl_rwlock;	/* lock we acquired */
3342 	znode_t		*zl_znode;	/* znode we held */
3343 	struct zfs_zlock *zl_next;	/* next in list */
3344 } zfs_zlock_t;
3345 
3346 /*
3347  * Drop locks and release vnodes that were held by zfs_rename_lock().
3348  */
3349 static void
3350 zfs_rename_unlock(zfs_zlock_t **zlpp)
3351 {
3352 	zfs_zlock_t *zl;
3353 
3354 	while ((zl = *zlpp) != NULL) {
3355 		if (zl->zl_znode != NULL)
3356 			VN_RELE(ZTOV(zl->zl_znode));
3357 		rw_exit(zl->zl_rwlock);
3358 		*zlpp = zl->zl_next;
3359 		kmem_free(zl, sizeof (*zl));
3360 	}
3361 }
3362 
3363 /*
3364  * Search back through the directory tree, using the ".." entries.
3365  * Lock each directory in the chain to prevent concurrent renames.
3366  * Fail any attempt to move a directory into one of its own descendants.
3367  * XXX - z_parent_lock can overlap with map or grow locks
3368  */
3369 static int
3370 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3371 {
3372 	zfs_zlock_t	*zl;
3373 	znode_t		*zp = tdzp;
3374 	uint64_t	rootid = zp->z_zfsvfs->z_root;
3375 	uint64_t	oidp = zp->z_id;
3376 	krwlock_t	*rwlp = &szp->z_parent_lock;
3377 	krw_t		rw = RW_WRITER;
3378 
3379 	/*
3380 	 * First pass write-locks szp and compares to zp->z_id.
3381 	 * Later passes read-lock zp and compare to zp->z_parent.
3382 	 */
3383 	do {
3384 		if (!rw_tryenter(rwlp, rw)) {
3385 			/*
3386 			 * Another thread is renaming in this path.
3387 			 * Note that if we are a WRITER, we don't have any
3388 			 * parent_locks held yet.
3389 			 */
3390 			if (rw == RW_READER && zp->z_id > szp->z_id) {
3391 				/*
3392 				 * Drop our locks and restart
3393 				 */
3394 				zfs_rename_unlock(&zl);
3395 				*zlpp = NULL;
3396 				zp = tdzp;
3397 				oidp = zp->z_id;
3398 				rwlp = &szp->z_parent_lock;
3399 				rw = RW_WRITER;
3400 				continue;
3401 			} else {
3402 				/*
3403 				 * Wait for other thread to drop its locks
3404 				 */
3405 				rw_enter(rwlp, rw);
3406 			}
3407 		}
3408 
3409 		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3410 		zl->zl_rwlock = rwlp;
3411 		zl->zl_znode = NULL;
3412 		zl->zl_next = *zlpp;
3413 		*zlpp = zl;
3414 
3415 		if (oidp == szp->z_id)		/* We're a descendant of szp */
3416 			return (SET_ERROR(EINVAL));
3417 
3418 		if (oidp == rootid)		/* We've hit the top */
3419 			return (0);
3420 
3421 		if (rw == RW_READER) {		/* i.e. not the first pass */
3422 			int error = zfs_zget(zp->z_zfsvfs, oidp, &zp);
3423 			if (error)
3424 				return (error);
3425 			zl->zl_znode = zp;
3426 		}
3427 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zp->z_zfsvfs),
3428 		    &oidp, sizeof (oidp));
3429 		rwlp = &zp->z_parent_lock;
3430 		rw = RW_READER;
3431 
3432 	} while (zp->z_id != sdzp->z_id);
3433 
3434 	return (0);
3435 }
3436 
3437 /*
3438  * Move an entry from the provided source directory to the target
3439  * directory.  Change the entry name as indicated.
3440  *
3441  *	IN:	sdvp	- Source directory containing the "old entry".
3442  *		snm	- Old entry name.
3443  *		tdvp	- Target directory to contain the "new entry".
3444  *		tnm	- New entry name.
3445  *		cr	- credentials of caller.
3446  *		ct	- caller context
3447  *		flags	- case flags
3448  *
3449  *	RETURN:	0 on success, error code on failure.
3450  *
3451  * Timestamps:
3452  *	sdvp,tdvp - ctime|mtime updated
3453  */
3454 /*ARGSUSED*/
3455 static int
3456 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
3457     caller_context_t *ct, int flags)
3458 {
3459 	znode_t		*tdzp, *szp, *tzp;
3460 	znode_t		*sdzp = VTOZ(sdvp);
3461 	zfsvfs_t	*zfsvfs = sdzp->z_zfsvfs;
3462 	zilog_t		*zilog;
3463 	vnode_t		*realvp;
3464 	zfs_dirlock_t	*sdl, *tdl;
3465 	dmu_tx_t	*tx;
3466 	zfs_zlock_t	*zl;
3467 	int		cmp, serr, terr;
3468 	int		error = 0, rm_err = 0;
3469 	int		zflg = 0;
3470 	boolean_t	waited = B_FALSE;
3471 
3472 	ZFS_ENTER(zfsvfs);
3473 	ZFS_VERIFY_ZP(sdzp);
3474 	zilog = zfsvfs->z_log;
3475 
3476 	/*
3477 	 * Make sure we have the real vp for the target directory.
3478 	 */
3479 	if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3480 		tdvp = realvp;
3481 
3482 	tdzp = VTOZ(tdvp);
3483 	ZFS_VERIFY_ZP(tdzp);
3484 
3485 	/*
3486 	 * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
3487 	 * ctldir appear to have the same v_vfsp.
3488 	 */
3489 	if (tdzp->z_zfsvfs != zfsvfs || zfsctl_is_node(tdvp)) {
3490 		ZFS_EXIT(zfsvfs);
3491 		return (SET_ERROR(EXDEV));
3492 	}
3493 
3494 	if (zfsvfs->z_utf8 && u8_validate(tnm,
3495 	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3496 		ZFS_EXIT(zfsvfs);
3497 		return (SET_ERROR(EILSEQ));
3498 	}
3499 
3500 	if (flags & FIGNORECASE)
3501 		zflg |= ZCILOOK;
3502 
3503 top:
3504 	szp = NULL;
3505 	tzp = NULL;
3506 	zl = NULL;
3507 
3508 	/*
3509 	 * This is to prevent the creation of links into attribute space
3510 	 * by renaming a linked file into/outof an attribute directory.
3511 	 * See the comment in zfs_link() for why this is considered bad.
3512 	 */
3513 	if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3514 		ZFS_EXIT(zfsvfs);
3515 		return (SET_ERROR(EINVAL));
3516 	}
3517 
3518 	/*
3519 	 * Lock source and target directory entries.  To prevent deadlock,
3520 	 * a lock ordering must be defined.  We lock the directory with
3521 	 * the smallest object id first, or if it's a tie, the one with
3522 	 * the lexically first name.
3523 	 */
3524 	if (sdzp->z_id < tdzp->z_id) {
3525 		cmp = -1;
3526 	} else if (sdzp->z_id > tdzp->z_id) {
3527 		cmp = 1;
3528 	} else {
3529 		/*
3530 		 * First compare the two name arguments without
3531 		 * considering any case folding.
3532 		 */
3533 		int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
3534 
3535 		cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3536 		ASSERT(error == 0 || !zfsvfs->z_utf8);
3537 		if (cmp == 0) {
3538 			/*
3539 			 * POSIX: "If the old argument and the new argument
3540 			 * both refer to links to the same existing file,
3541 			 * the rename() function shall return successfully
3542 			 * and perform no other action."
3543 			 */
3544 			ZFS_EXIT(zfsvfs);
3545 			return (0);
3546 		}
3547 		/*
3548 		 * If the file system is case-folding, then we may
3549 		 * have some more checking to do.  A case-folding file
3550 		 * system is either supporting mixed case sensitivity
3551 		 * access or is completely case-insensitive.  Note
3552 		 * that the file system is always case preserving.
3553 		 *
3554 		 * In mixed sensitivity mode case sensitive behavior
3555 		 * is the default.  FIGNORECASE must be used to
3556 		 * explicitly request case insensitive behavior.
3557 		 *
3558 		 * If the source and target names provided differ only
3559 		 * by case (e.g., a request to rename 'tim' to 'Tim'),
3560 		 * we will treat this as a special case in the
3561 		 * case-insensitive mode: as long as the source name
3562 		 * is an exact match, we will allow this to proceed as
3563 		 * a name-change request.
3564 		 */
3565 		if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
3566 		    (zfsvfs->z_case == ZFS_CASE_MIXED &&
3567 		    flags & FIGNORECASE)) &&
3568 		    u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
3569 		    &error) == 0) {
3570 			/*
3571 			 * case preserving rename request, require exact
3572 			 * name matches
3573 			 */
3574 			zflg |= ZCIEXACT;
3575 			zflg &= ~ZCILOOK;
3576 		}
3577 	}
3578 
3579 	/*
3580 	 * If the source and destination directories are the same, we should
3581 	 * grab the z_name_lock of that directory only once.
3582 	 */
3583 	if (sdzp == tdzp) {
3584 		zflg |= ZHAVELOCK;
3585 		rw_enter(&sdzp->z_name_lock, RW_READER);
3586 	}
3587 
3588 	if (cmp < 0) {
3589 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3590 		    ZEXISTS | zflg, NULL, NULL);
3591 		terr = zfs_dirent_lock(&tdl,
3592 		    tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3593 	} else {
3594 		terr = zfs_dirent_lock(&tdl,
3595 		    tdzp, tnm, &tzp, zflg, NULL, NULL);
3596 		serr = zfs_dirent_lock(&sdl,
3597 		    sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3598 		    NULL, NULL);
3599 	}
3600 
3601 	if (serr) {
3602 		/*
3603 		 * Source entry invalid or not there.
3604 		 */
3605 		if (!terr) {
3606 			zfs_dirent_unlock(tdl);
3607 			if (tzp)
3608 				VN_RELE(ZTOV(tzp));
3609 		}
3610 
3611 		if (sdzp == tdzp)
3612 			rw_exit(&sdzp->z_name_lock);
3613 
3614 		if (strcmp(snm, "..") == 0)
3615 			serr = SET_ERROR(EINVAL);
3616 		ZFS_EXIT(zfsvfs);
3617 		return (serr);
3618 	}
3619 	if (terr) {
3620 		zfs_dirent_unlock(sdl);
3621 		VN_RELE(ZTOV(szp));
3622 
3623 		if (sdzp == tdzp)
3624 			rw_exit(&sdzp->z_name_lock);
3625 
3626 		if (strcmp(tnm, "..") == 0)
3627 			terr = SET_ERROR(EINVAL);
3628 		ZFS_EXIT(zfsvfs);
3629 		return (terr);
3630 	}
3631 
3632 	/*
3633 	 * Must have write access at the source to remove the old entry
3634 	 * and write access at the target to create the new entry.
3635 	 * Note that if target and source are the same, this can be
3636 	 * done in a single check.
3637 	 */
3638 
3639 	if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
3640 		goto out;
3641 
3642 	if (ZTOV(szp)->v_type == VDIR) {
3643 		/*
3644 		 * Check to make sure rename is valid.
3645 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3646 		 */
3647 		if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
3648 			goto out;
3649 	}
3650 
3651 	/*
3652 	 * Does target exist?
3653 	 */
3654 	if (tzp) {
3655 		/*
3656 		 * Source and target must be the same type.
3657 		 */
3658 		if (ZTOV(szp)->v_type == VDIR) {
3659 			if (ZTOV(tzp)->v_type != VDIR) {
3660 				error = SET_ERROR(ENOTDIR);
3661 				goto out;
3662 			}
3663 		} else {
3664 			if (ZTOV(tzp)->v_type == VDIR) {
3665 				error = SET_ERROR(EISDIR);
3666 				goto out;
3667 			}
3668 		}
3669 		/*
3670 		 * POSIX dictates that when the source and target
3671 		 * entries refer to the same file object, rename
3672 		 * must do nothing and exit without error.
3673 		 */
3674 		if (szp->z_id == tzp->z_id) {
3675 			error = 0;
3676 			goto out;
3677 		}
3678 	}
3679 
3680 	vnevent_pre_rename_src(ZTOV(szp), sdvp, snm, ct);
3681 	if (tzp)
3682 		vnevent_pre_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3683 
3684 	/*
3685 	 * notify the target directory if it is not the same
3686 	 * as source directory.
3687 	 */
3688 	if (tdvp != sdvp) {
3689 		vnevent_pre_rename_dest_dir(tdvp, ZTOV(szp), tnm, ct);
3690 	}
3691 
3692 	tx = dmu_tx_create(zfsvfs->z_os);
3693 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3694 	dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3695 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3696 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3697 	if (sdzp != tdzp) {
3698 		dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3699 		zfs_sa_upgrade_txholds(tx, tdzp);
3700 	}
3701 	if (tzp) {
3702 		dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3703 		zfs_sa_upgrade_txholds(tx, tzp);
3704 	}
3705 
3706 	zfs_sa_upgrade_txholds(tx, szp);
3707 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3708 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
3709 	if (error) {
3710 		if (zl != NULL)
3711 			zfs_rename_unlock(&zl);
3712 		zfs_dirent_unlock(sdl);
3713 		zfs_dirent_unlock(tdl);
3714 
3715 		if (sdzp == tdzp)
3716 			rw_exit(&sdzp->z_name_lock);
3717 
3718 		VN_RELE(ZTOV(szp));
3719 		if (tzp)
3720 			VN_RELE(ZTOV(tzp));
3721 		if (error == ERESTART) {
3722 			waited = B_TRUE;
3723 			dmu_tx_wait(tx);
3724 			dmu_tx_abort(tx);
3725 			goto top;
3726 		}
3727 		dmu_tx_abort(tx);
3728 		ZFS_EXIT(zfsvfs);
3729 		return (error);
3730 	}
3731 
3732 	if (tzp)	/* Attempt to remove the existing target */
3733 		error = rm_err = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3734 
3735 	if (error == 0) {
3736 		error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3737 		if (error == 0) {
3738 			szp->z_pflags |= ZFS_AV_MODIFIED;
3739 
3740 			error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3741 			    (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3742 			ASSERT0(error);
3743 
3744 			error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3745 			if (error == 0) {
3746 				zfs_log_rename(zilog, tx, TX_RENAME |
3747 				    (flags & FIGNORECASE ? TX_CI : 0), sdzp,
3748 				    sdl->dl_name, tdzp, tdl->dl_name, szp);
3749 
3750 				/*
3751 				 * Update path information for the target vnode
3752 				 */
3753 				vn_renamepath(tdvp, ZTOV(szp), tnm,
3754 				    strlen(tnm));
3755 			} else {
3756 				/*
3757 				 * At this point, we have successfully created
3758 				 * the target name, but have failed to remove
3759 				 * the source name.  Since the create was done
3760 				 * with the ZRENAMING flag, there are
3761 				 * complications; for one, the link count is
3762 				 * wrong.  The easiest way to deal with this
3763 				 * is to remove the newly created target, and
3764 				 * return the original error.  This must
3765 				 * succeed; fortunately, it is very unlikely to
3766 				 * fail, since we just created it.
3767 				 */
3768 				VERIFY3U(zfs_link_destroy(tdl, szp, tx,
3769 				    ZRENAMING, NULL), ==, 0);
3770 			}
3771 		}
3772 	}
3773 
3774 	dmu_tx_commit(tx);
3775 
3776 	if (tzp && rm_err == 0)
3777 		vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3778 
3779 	if (error == 0) {
3780 		vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
3781 		/* notify the target dir if it is not the same as source dir */
3782 		if (tdvp != sdvp)
3783 			vnevent_rename_dest_dir(tdvp, ct);
3784 	}
3785 out:
3786 	if (zl != NULL)
3787 		zfs_rename_unlock(&zl);
3788 
3789 	zfs_dirent_unlock(sdl);
3790 	zfs_dirent_unlock(tdl);
3791 
3792 	if (sdzp == tdzp)
3793 		rw_exit(&sdzp->z_name_lock);
3794 
3795 
3796 	VN_RELE(ZTOV(szp));
3797 	if (tzp)
3798 		VN_RELE(ZTOV(tzp));
3799 
3800 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3801 		zil_commit(zilog, 0);
3802 
3803 	ZFS_EXIT(zfsvfs);
3804 	return (error);
3805 }
3806 
3807 /*
3808  * Insert the indicated symbolic reference entry into the directory.
3809  *
3810  *	IN:	dvp	- Directory to contain new symbolic link.
3811  *		link	- Name for new symlink entry.
3812  *		vap	- Attributes of new entry.
3813  *		cr	- credentials of caller.
3814  *		ct	- caller context
3815  *		flags	- case flags
3816  *
3817  *	RETURN:	0 on success, error code on failure.
3818  *
3819  * Timestamps:
3820  *	dvp - ctime|mtime updated
3821  */
3822 /*ARGSUSED*/
3823 static int
3824 zfs_symlink(vnode_t *dvp, char *name, vattr_t *vap, char *link, cred_t *cr,
3825     caller_context_t *ct, int flags)
3826 {
3827 	znode_t		*zp, *dzp = VTOZ(dvp);
3828 	zfs_dirlock_t	*dl;
3829 	dmu_tx_t	*tx;
3830 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3831 	zilog_t		*zilog;
3832 	uint64_t	len = strlen(link);
3833 	int		error;
3834 	int		zflg = ZNEW;
3835 	zfs_acl_ids_t	acl_ids;
3836 	boolean_t	fuid_dirtied;
3837 	uint64_t	txtype = TX_SYMLINK;
3838 	boolean_t	waited = B_FALSE;
3839 
3840 	ASSERT(vap->va_type == VLNK);
3841 
3842 	ZFS_ENTER(zfsvfs);
3843 	ZFS_VERIFY_ZP(dzp);
3844 	zilog = zfsvfs->z_log;
3845 
3846 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3847 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3848 		ZFS_EXIT(zfsvfs);
3849 		return (SET_ERROR(EILSEQ));
3850 	}
3851 	if (flags & FIGNORECASE)
3852 		zflg |= ZCILOOK;
3853 
3854 	if (len > MAXPATHLEN) {
3855 		ZFS_EXIT(zfsvfs);
3856 		return (SET_ERROR(ENAMETOOLONG));
3857 	}
3858 
3859 	if ((error = zfs_acl_ids_create(dzp, 0,
3860 	    vap, cr, NULL, &acl_ids)) != 0) {
3861 		ZFS_EXIT(zfsvfs);
3862 		return (error);
3863 	}
3864 top:
3865 	/*
3866 	 * Attempt to lock directory; fail if entry already exists.
3867 	 */
3868 	error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3869 	if (error) {
3870 		zfs_acl_ids_free(&acl_ids);
3871 		ZFS_EXIT(zfsvfs);
3872 		return (error);
3873 	}
3874 
3875 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
3876 		zfs_acl_ids_free(&acl_ids);
3877 		zfs_dirent_unlock(dl);
3878 		ZFS_EXIT(zfsvfs);
3879 		return (error);
3880 	}
3881 
3882 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
3883 		zfs_acl_ids_free(&acl_ids);
3884 		zfs_dirent_unlock(dl);
3885 		ZFS_EXIT(zfsvfs);
3886 		return (SET_ERROR(EDQUOT));
3887 	}
3888 	tx = dmu_tx_create(zfsvfs->z_os);
3889 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3890 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3891 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3892 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3893 	    ZFS_SA_BASE_ATTR_SIZE + len);
3894 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
3895 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3896 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3897 		    acl_ids.z_aclp->z_acl_bytes);
3898 	}
3899 	if (fuid_dirtied)
3900 		zfs_fuid_txhold(zfsvfs, tx);
3901 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
3902 	if (error) {
3903 		zfs_dirent_unlock(dl);
3904 		if (error == ERESTART) {
3905 			waited = B_TRUE;
3906 			dmu_tx_wait(tx);
3907 			dmu_tx_abort(tx);
3908 			goto top;
3909 		}
3910 		zfs_acl_ids_free(&acl_ids);
3911 		dmu_tx_abort(tx);
3912 		ZFS_EXIT(zfsvfs);
3913 		return (error);
3914 	}
3915 
3916 	/*
3917 	 * Create a new object for the symlink.
3918 	 * for version 4 ZPL datsets the symlink will be an SA attribute
3919 	 */
3920 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3921 
3922 	if (fuid_dirtied)
3923 		zfs_fuid_sync(zfsvfs, tx);
3924 
3925 	mutex_enter(&zp->z_lock);
3926 	if (zp->z_is_sa)
3927 		error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
3928 		    link, len, tx);
3929 	else
3930 		zfs_sa_symlink(zp, link, len, tx);
3931 	mutex_exit(&zp->z_lock);
3932 
3933 	zp->z_size = len;
3934 	(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
3935 	    &zp->z_size, sizeof (zp->z_size), tx);
3936 	/*
3937 	 * Insert the new object into the directory.
3938 	 */
3939 	(void) zfs_link_create(dl, zp, tx, ZNEW);
3940 
3941 	if (flags & FIGNORECASE)
3942 		txtype |= TX_CI;
3943 	zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3944 
3945 	zfs_acl_ids_free(&acl_ids);
3946 
3947 	dmu_tx_commit(tx);
3948 
3949 	zfs_dirent_unlock(dl);
3950 
3951 	VN_RELE(ZTOV(zp));
3952 
3953 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3954 		zil_commit(zilog, 0);
3955 
3956 	ZFS_EXIT(zfsvfs);
3957 	return (error);
3958 }
3959 
3960 /*
3961  * Return, in the buffer contained in the provided uio structure,
3962  * the symbolic path referred to by vp.
3963  *
3964  *	IN:	vp	- vnode of symbolic link.
3965  *		uio	- structure to contain the link path.
3966  *		cr	- credentials of caller.
3967  *		ct	- caller context
3968  *
3969  *	OUT:	uio	- structure containing the link path.
3970  *
3971  *	RETURN:	0 on success, error code on failure.
3972  *
3973  * Timestamps:
3974  *	vp - atime updated
3975  */
3976 /* ARGSUSED */
3977 static int
3978 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
3979 {
3980 	znode_t		*zp = VTOZ(vp);
3981 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3982 	int		error;
3983 
3984 	ZFS_ENTER(zfsvfs);
3985 	ZFS_VERIFY_ZP(zp);
3986 
3987 	mutex_enter(&zp->z_lock);
3988 	if (zp->z_is_sa)
3989 		error = sa_lookup_uio(zp->z_sa_hdl,
3990 		    SA_ZPL_SYMLINK(zfsvfs), uio);
3991 	else
3992 		error = zfs_sa_readlink(zp, uio);
3993 	mutex_exit(&zp->z_lock);
3994 
3995 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3996 
3997 	ZFS_EXIT(zfsvfs);
3998 	return (error);
3999 }
4000 
4001 /*
4002  * Insert a new entry into directory tdvp referencing svp.
4003  *
4004  *	IN:	tdvp	- Directory to contain new entry.
4005  *		svp	- vnode of new entry.
4006  *		name	- name of new entry.
4007  *		cr	- credentials of caller.
4008  *		ct	- caller context
4009  *
4010  *	RETURN:	0 on success, error code on failure.
4011  *
4012  * Timestamps:
4013  *	tdvp - ctime|mtime updated
4014  *	 svp - ctime updated
4015  */
4016 /* ARGSUSED */
4017 static int
4018 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
4019     caller_context_t *ct, int flags)
4020 {
4021 	znode_t		*dzp = VTOZ(tdvp);
4022 	znode_t		*tzp, *szp;
4023 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
4024 	zilog_t		*zilog;
4025 	zfs_dirlock_t	*dl;
4026 	dmu_tx_t	*tx;
4027 	vnode_t		*realvp;
4028 	int		error;
4029 	int		zf = ZNEW;
4030 	uint64_t	parent;
4031 	uid_t		owner;
4032 	boolean_t	waited = B_FALSE;
4033 
4034 	ASSERT(tdvp->v_type == VDIR);
4035 
4036 	ZFS_ENTER(zfsvfs);
4037 	ZFS_VERIFY_ZP(dzp);
4038 	zilog = zfsvfs->z_log;
4039 
4040 	if (VOP_REALVP(svp, &realvp, ct) == 0)
4041 		svp = realvp;
4042 
4043 	/*
4044 	 * POSIX dictates that we return EPERM here.
4045 	 * Better choices include ENOTSUP or EISDIR.
4046 	 */
4047 	if (svp->v_type == VDIR) {
4048 		ZFS_EXIT(zfsvfs);
4049 		return (SET_ERROR(EPERM));
4050 	}
4051 
4052 	szp = VTOZ(svp);
4053 	ZFS_VERIFY_ZP(szp);
4054 
4055 	/*
4056 	 * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
4057 	 * ctldir appear to have the same v_vfsp.
4058 	 */
4059 	if (szp->z_zfsvfs != zfsvfs || zfsctl_is_node(svp)) {
4060 		ZFS_EXIT(zfsvfs);
4061 		return (SET_ERROR(EXDEV));
4062 	}
4063 
4064 	/* Prevent links to .zfs/shares files */
4065 
4066 	if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
4067 	    &parent, sizeof (uint64_t))) != 0) {
4068 		ZFS_EXIT(zfsvfs);
4069 		return (error);
4070 	}
4071 	if (parent == zfsvfs->z_shares_dir) {
4072 		ZFS_EXIT(zfsvfs);
4073 		return (SET_ERROR(EPERM));
4074 	}
4075 
4076 	if (zfsvfs->z_utf8 && u8_validate(name,
4077 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4078 		ZFS_EXIT(zfsvfs);
4079 		return (SET_ERROR(EILSEQ));
4080 	}
4081 	if (flags & FIGNORECASE)
4082 		zf |= ZCILOOK;
4083 
4084 	/*
4085 	 * We do not support links between attributes and non-attributes
4086 	 * because of the potential security risk of creating links
4087 	 * into "normal" file space in order to circumvent restrictions
4088 	 * imposed in attribute space.
4089 	 */
4090 	if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
4091 		ZFS_EXIT(zfsvfs);
4092 		return (SET_ERROR(EINVAL));
4093 	}
4094 
4095 
4096 	owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
4097 	if (owner != crgetuid(cr) && secpolicy_basic_link(cr) != 0) {
4098 		ZFS_EXIT(zfsvfs);
4099 		return (SET_ERROR(EPERM));
4100 	}
4101 
4102 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4103 		ZFS_EXIT(zfsvfs);
4104 		return (error);
4105 	}
4106 
4107 top:
4108 	/*
4109 	 * Attempt to lock directory; fail if entry already exists.
4110 	 */
4111 	error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
4112 	if (error) {
4113 		ZFS_EXIT(zfsvfs);
4114 		return (error);
4115 	}
4116 
4117 	tx = dmu_tx_create(zfsvfs->z_os);
4118 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
4119 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4120 	zfs_sa_upgrade_txholds(tx, szp);
4121 	zfs_sa_upgrade_txholds(tx, dzp);
4122 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
4123 	if (error) {
4124 		zfs_dirent_unlock(dl);
4125 		if (error == ERESTART) {
4126 			waited = B_TRUE;
4127 			dmu_tx_wait(tx);
4128 			dmu_tx_abort(tx);
4129 			goto top;
4130 		}
4131 		dmu_tx_abort(tx);
4132 		ZFS_EXIT(zfsvfs);
4133 		return (error);
4134 	}
4135 
4136 	error = zfs_link_create(dl, szp, tx, 0);
4137 
4138 	if (error == 0) {
4139 		uint64_t txtype = TX_LINK;
4140 		if (flags & FIGNORECASE)
4141 			txtype |= TX_CI;
4142 		zfs_log_link(zilog, tx, txtype, dzp, szp, name);
4143 	}
4144 
4145 	dmu_tx_commit(tx);
4146 
4147 	zfs_dirent_unlock(dl);
4148 
4149 	if (error == 0) {
4150 		vnevent_link(svp, ct);
4151 	}
4152 
4153 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4154 		zil_commit(zilog, 0);
4155 
4156 	ZFS_EXIT(zfsvfs);
4157 	return (error);
4158 }
4159 
4160 /*
4161  * zfs_null_putapage() is used when the file system has been force
4162  * unmounted. It just drops the pages.
4163  */
4164 /* ARGSUSED */
4165 static int
4166 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4167     size_t *lenp, int flags, cred_t *cr)
4168 {
4169 	pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
4170 	return (0);
4171 }
4172 
4173 /*
4174  * Push a page out to disk, klustering if possible.
4175  *
4176  *	IN:	vp	- file to push page to.
4177  *		pp	- page to push.
4178  *		flags	- additional flags.
4179  *		cr	- credentials of caller.
4180  *
4181  *	OUT:	offp	- start of range pushed.
4182  *		lenp	- len of range pushed.
4183  *
4184  *	RETURN:	0 on success, error code on failure.
4185  *
4186  * NOTE: callers must have locked the page to be pushed.  On
4187  * exit, the page (and all other pages in the kluster) must be
4188  * unlocked.
4189  */
4190 /* ARGSUSED */
4191 static int
4192 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4193     size_t *lenp, int flags, cred_t *cr)
4194 {
4195 	znode_t		*zp = VTOZ(vp);
4196 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4197 	dmu_tx_t	*tx;
4198 	u_offset_t	off, koff;
4199 	size_t		len, klen;
4200 	int		err;
4201 
4202 	off = pp->p_offset;
4203 	len = PAGESIZE;
4204 	/*
4205 	 * If our blocksize is bigger than the page size, try to kluster
4206 	 * multiple pages so that we write a full block (thus avoiding
4207 	 * a read-modify-write).
4208 	 */
4209 	if (off < zp->z_size && zp->z_blksz > PAGESIZE) {
4210 		klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
4211 		koff = ISP2(klen) ? P2ALIGN(off, (u_offset_t)klen) : 0;
4212 		ASSERT(koff <= zp->z_size);
4213 		if (koff + klen > zp->z_size)
4214 			klen = P2ROUNDUP(zp->z_size - koff, (uint64_t)PAGESIZE);
4215 		pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
4216 	}
4217 	ASSERT3U(btop(len), ==, btopr(len));
4218 
4219 	/*
4220 	 * Can't push pages past end-of-file.
4221 	 */
4222 	if (off >= zp->z_size) {
4223 		/* ignore all pages */
4224 		err = 0;
4225 		goto out;
4226 	} else if (off + len > zp->z_size) {
4227 		int npages = btopr(zp->z_size - off);
4228 		page_t *trunc;
4229 
4230 		page_list_break(&pp, &trunc, npages);
4231 		/* ignore pages past end of file */
4232 		if (trunc)
4233 			pvn_write_done(trunc, flags);
4234 		len = zp->z_size - off;
4235 	}
4236 
4237 	if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
4238 	    zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
4239 		err = SET_ERROR(EDQUOT);
4240 		goto out;
4241 	}
4242 	tx = dmu_tx_create(zfsvfs->z_os);
4243 	dmu_tx_hold_write(tx, zp->z_id, off, len);
4244 
4245 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4246 	zfs_sa_upgrade_txholds(tx, zp);
4247 	err = dmu_tx_assign(tx, TXG_WAIT);
4248 	if (err != 0) {
4249 		dmu_tx_abort(tx);
4250 		goto out;
4251 	}
4252 
4253 	if (zp->z_blksz <= PAGESIZE) {
4254 		caddr_t va = zfs_map_page(pp, S_READ);
4255 		ASSERT3U(len, <=, PAGESIZE);
4256 		dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
4257 		zfs_unmap_page(pp, va);
4258 	} else {
4259 		err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
4260 	}
4261 
4262 	if (err == 0) {
4263 		uint64_t mtime[2], ctime[2];
4264 		sa_bulk_attr_t bulk[3];
4265 		int count = 0;
4266 
4267 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4268 		    &mtime, 16);
4269 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4270 		    &ctime, 16);
4271 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4272 		    &zp->z_pflags, 8);
4273 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
4274 		    B_TRUE);
4275 		err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
4276 		ASSERT0(err);
4277 		zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len, 0);
4278 	}
4279 	dmu_tx_commit(tx);
4280 
4281 out:
4282 	pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
4283 	if (offp)
4284 		*offp = off;
4285 	if (lenp)
4286 		*lenp = len;
4287 
4288 	return (err);
4289 }
4290 
4291 /*
4292  * Copy the portion of the file indicated from pages into the file.
4293  * The pages are stored in a page list attached to the files vnode.
4294  *
4295  *	IN:	vp	- vnode of file to push page data to.
4296  *		off	- position in file to put data.
4297  *		len	- amount of data to write.
4298  *		flags	- flags to control the operation.
4299  *		cr	- credentials of caller.
4300  *		ct	- caller context.
4301  *
4302  *	RETURN:	0 on success, error code on failure.
4303  *
4304  * Timestamps:
4305  *	vp - ctime|mtime updated
4306  */
4307 /*ARGSUSED*/
4308 static int
4309 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
4310     caller_context_t *ct)
4311 {
4312 	znode_t		*zp = VTOZ(vp);
4313 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4314 	page_t		*pp;
4315 	size_t		io_len;
4316 	u_offset_t	io_off;
4317 	uint_t		blksz;
4318 	locked_range_t	*lr;
4319 	int		error = 0;
4320 
4321 	ZFS_ENTER(zfsvfs);
4322 	ZFS_VERIFY_ZP(zp);
4323 
4324 	/*
4325 	 * There's nothing to do if no data is cached.
4326 	 */
4327 	if (!vn_has_cached_data(vp)) {
4328 		ZFS_EXIT(zfsvfs);
4329 		return (0);
4330 	}
4331 
4332 	/*
4333 	 * Align this request to the file block size in case we kluster.
4334 	 * XXX - this can result in pretty aggresive locking, which can
4335 	 * impact simultanious read/write access.  One option might be
4336 	 * to break up long requests (len == 0) into block-by-block
4337 	 * operations to get narrower locking.
4338 	 */
4339 	blksz = zp->z_blksz;
4340 	if (ISP2(blksz))
4341 		io_off = P2ALIGN_TYPED(off, blksz, u_offset_t);
4342 	else
4343 		io_off = 0;
4344 	if (len > 0 && ISP2(blksz))
4345 		io_len = P2ROUNDUP_TYPED(len + (off - io_off), blksz, size_t);
4346 	else
4347 		io_len = 0;
4348 
4349 	if (io_len == 0) {
4350 		/*
4351 		 * Search the entire vp list for pages >= io_off.
4352 		 */
4353 		lr = rangelock_enter(&zp->z_rangelock,
4354 		    io_off, UINT64_MAX, RL_WRITER);
4355 		error = pvn_vplist_dirty(vp, io_off, zfs_putapage, flags, cr);
4356 		goto out;
4357 	}
4358 	lr = rangelock_enter(&zp->z_rangelock, io_off, io_len, RL_WRITER);
4359 
4360 	if (off > zp->z_size) {
4361 		/* past end of file */
4362 		rangelock_exit(lr);
4363 		ZFS_EXIT(zfsvfs);
4364 		return (0);
4365 	}
4366 
4367 	len = MIN(io_len, P2ROUNDUP(zp->z_size, PAGESIZE) - io_off);
4368 
4369 	for (off = io_off; io_off < off + len; io_off += io_len) {
4370 		if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
4371 			pp = page_lookup(vp, io_off,
4372 			    (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
4373 		} else {
4374 			pp = page_lookup_nowait(vp, io_off,
4375 			    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
4376 		}
4377 
4378 		if (pp != NULL && pvn_getdirty(pp, flags)) {
4379 			int err;
4380 
4381 			/*
4382 			 * Found a dirty page to push
4383 			 */
4384 			err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
4385 			if (err)
4386 				error = err;
4387 		} else {
4388 			io_len = PAGESIZE;
4389 		}
4390 	}
4391 out:
4392 	rangelock_exit(lr);
4393 	if ((flags & B_ASYNC) == 0 || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4394 		zil_commit(zfsvfs->z_log, zp->z_id);
4395 	ZFS_EXIT(zfsvfs);
4396 	return (error);
4397 }
4398 
4399 /*ARGSUSED*/
4400 void
4401 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4402 {
4403 	znode_t	*zp = VTOZ(vp);
4404 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4405 	int error;
4406 
4407 	rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4408 	if (zp->z_sa_hdl == NULL) {
4409 		/*
4410 		 * The fs has been unmounted, or we did a
4411 		 * suspend/resume and this file no longer exists.
4412 		 */
4413 		if (vn_has_cached_data(vp)) {
4414 			(void) pvn_vplist_dirty(vp, 0, zfs_null_putapage,
4415 			    B_INVAL, cr);
4416 		}
4417 
4418 		mutex_enter(&zp->z_lock);
4419 		mutex_enter(&vp->v_lock);
4420 		ASSERT(vp->v_count == 1);
4421 		VN_RELE_LOCKED(vp);
4422 		mutex_exit(&vp->v_lock);
4423 		mutex_exit(&zp->z_lock);
4424 		rw_exit(&zfsvfs->z_teardown_inactive_lock);
4425 		zfs_znode_free(zp);
4426 		return;
4427 	}
4428 
4429 	/*
4430 	 * Attempt to push any data in the page cache.  If this fails
4431 	 * we will get kicked out later in zfs_zinactive().
4432 	 */
4433 	if (vn_has_cached_data(vp)) {
4434 		(void) pvn_vplist_dirty(vp, 0, zfs_putapage, B_INVAL|B_ASYNC,
4435 		    cr);
4436 	}
4437 
4438 	if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4439 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4440 
4441 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4442 		zfs_sa_upgrade_txholds(tx, zp);
4443 		error = dmu_tx_assign(tx, TXG_WAIT);
4444 		if (error) {
4445 			dmu_tx_abort(tx);
4446 		} else {
4447 			mutex_enter(&zp->z_lock);
4448 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4449 			    (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4450 			zp->z_atime_dirty = 0;
4451 			mutex_exit(&zp->z_lock);
4452 			dmu_tx_commit(tx);
4453 		}
4454 	}
4455 
4456 	zfs_zinactive(zp);
4457 	rw_exit(&zfsvfs->z_teardown_inactive_lock);
4458 }
4459 
4460 /*
4461  * Bounds-check the seek operation.
4462  *
4463  *	IN:	vp	- vnode seeking within
4464  *		ooff	- old file offset
4465  *		noffp	- pointer to new file offset
4466  *		ct	- caller context
4467  *
4468  *	RETURN:	0 on success, EINVAL if new offset invalid.
4469  */
4470 /* ARGSUSED */
4471 static int
4472 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp,
4473     caller_context_t *ct)
4474 {
4475 	if (vp->v_type == VDIR)
4476 		return (0);
4477 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4478 }
4479 
4480 /*
4481  * Pre-filter the generic locking function to trap attempts to place
4482  * a mandatory lock on a memory mapped file.
4483  */
4484 static int
4485 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
4486     flk_callback_t *flk_cbp, cred_t *cr, caller_context_t *ct)
4487 {
4488 	znode_t *zp = VTOZ(vp);
4489 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4490 
4491 	ZFS_ENTER(zfsvfs);
4492 	ZFS_VERIFY_ZP(zp);
4493 
4494 	/*
4495 	 * We are following the UFS semantics with respect to mapcnt
4496 	 * here: If we see that the file is mapped already, then we will
4497 	 * return an error, but we don't worry about races between this
4498 	 * function and zfs_map().
4499 	 */
4500 	if (zp->z_mapcnt > 0 && MANDMODE(zp->z_mode)) {
4501 		ZFS_EXIT(zfsvfs);
4502 		return (SET_ERROR(EAGAIN));
4503 	}
4504 	ZFS_EXIT(zfsvfs);
4505 	return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4506 }
4507 
4508 /*
4509  * If we can't find a page in the cache, we will create a new page
4510  * and fill it with file data.  For efficiency, we may try to fill
4511  * multiple pages at once (klustering) to fill up the supplied page
4512  * list.  Note that the pages to be filled are held with an exclusive
4513  * lock to prevent access by other threads while they are being filled.
4514  */
4515 static int
4516 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
4517     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
4518 {
4519 	znode_t *zp = VTOZ(vp);
4520 	page_t *pp, *cur_pp;
4521 	objset_t *os = zp->z_zfsvfs->z_os;
4522 	u_offset_t io_off, total;
4523 	size_t io_len;
4524 	int err;
4525 
4526 	if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
4527 		/*
4528 		 * We only have a single page, don't bother klustering
4529 		 */
4530 		io_off = off;
4531 		io_len = PAGESIZE;
4532 		pp = page_create_va(vp, io_off, io_len,
4533 		    PG_EXCL | PG_WAIT, seg, addr);
4534 	} else {
4535 		/*
4536 		 * Try to find enough pages to fill the page list
4537 		 */
4538 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4539 		    &io_len, off, plsz, 0);
4540 	}
4541 	if (pp == NULL) {
4542 		/*
4543 		 * The page already exists, nothing to do here.
4544 		 */
4545 		*pl = NULL;
4546 		return (0);
4547 	}
4548 
4549 	/*
4550 	 * Fill the pages in the kluster.
4551 	 */
4552 	cur_pp = pp;
4553 	for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4554 		caddr_t va;
4555 
4556 		ASSERT3U(io_off, ==, cur_pp->p_offset);
4557 		va = zfs_map_page(cur_pp, S_WRITE);
4558 		err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4559 		    DMU_READ_PREFETCH);
4560 		zfs_unmap_page(cur_pp, va);
4561 		if (err) {
4562 			/* On error, toss the entire kluster */
4563 			pvn_read_done(pp, B_ERROR);
4564 			/* convert checksum errors into IO errors */
4565 			if (err == ECKSUM)
4566 				err = SET_ERROR(EIO);
4567 			return (err);
4568 		}
4569 		cur_pp = cur_pp->p_next;
4570 	}
4571 
4572 	/*
4573 	 * Fill in the page list array from the kluster starting
4574 	 * from the desired offset `off'.
4575 	 * NOTE: the page list will always be null terminated.
4576 	 */
4577 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4578 	ASSERT(pl == NULL || (*pl)->p_offset == off);
4579 
4580 	return (0);
4581 }
4582 
4583 /*
4584  * Return pointers to the pages for the file region [off, off + len]
4585  * in the pl array.  If plsz is greater than len, this function may
4586  * also return page pointers from after the specified region
4587  * (i.e. the region [off, off + plsz]).  These additional pages are
4588  * only returned if they are already in the cache, or were created as
4589  * part of a klustered read.
4590  *
4591  *	IN:	vp	- vnode of file to get data from.
4592  *		off	- position in file to get data from.
4593  *		len	- amount of data to retrieve.
4594  *		plsz	- length of provided page list.
4595  *		seg	- segment to obtain pages for.
4596  *		addr	- virtual address of fault.
4597  *		rw	- mode of created pages.
4598  *		cr	- credentials of caller.
4599  *		ct	- caller context.
4600  *
4601  *	OUT:	protp	- protection mode of created pages.
4602  *		pl	- list of pages created.
4603  *
4604  *	RETURN:	0 on success, error code on failure.
4605  *
4606  * Timestamps:
4607  *	vp - atime updated
4608  */
4609 /* ARGSUSED */
4610 static int
4611 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
4612     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
4613     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
4614 {
4615 	znode_t		*zp = VTOZ(vp);
4616 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4617 	page_t		**pl0 = pl;
4618 	int		err = 0;
4619 
4620 	/* we do our own caching, faultahead is unnecessary */
4621 	if (pl == NULL)
4622 		return (0);
4623 	else if (len > plsz)
4624 		len = plsz;
4625 	else
4626 		len = P2ROUNDUP(len, PAGESIZE);
4627 	ASSERT(plsz >= len);
4628 
4629 	ZFS_ENTER(zfsvfs);
4630 	ZFS_VERIFY_ZP(zp);
4631 
4632 	if (protp)
4633 		*protp = PROT_ALL;
4634 
4635 	/*
4636 	 * Loop through the requested range [off, off + len) looking
4637 	 * for pages.  If we don't find a page, we will need to create
4638 	 * a new page and fill it with data from the file.
4639 	 */
4640 	while (len > 0) {
4641 		if (*pl = page_lookup(vp, off, SE_SHARED))
4642 			*(pl+1) = NULL;
4643 		else if (err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw))
4644 			goto out;
4645 		while (*pl) {
4646 			ASSERT3U((*pl)->p_offset, ==, off);
4647 			off += PAGESIZE;
4648 			addr += PAGESIZE;
4649 			if (len > 0) {
4650 				ASSERT3U(len, >=, PAGESIZE);
4651 				len -= PAGESIZE;
4652 			}
4653 			ASSERT3U(plsz, >=, PAGESIZE);
4654 			plsz -= PAGESIZE;
4655 			pl++;
4656 		}
4657 	}
4658 
4659 	/*
4660 	 * Fill out the page array with any pages already in the cache.
4661 	 */
4662 	while (plsz > 0 &&
4663 	    (*pl++ = page_lookup_nowait(vp, off, SE_SHARED))) {
4664 			off += PAGESIZE;
4665 			plsz -= PAGESIZE;
4666 	}
4667 out:
4668 	if (err) {
4669 		/*
4670 		 * Release any pages we have previously locked.
4671 		 */
4672 		while (pl > pl0)
4673 			page_unlock(*--pl);
4674 	} else {
4675 		ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4676 	}
4677 
4678 	*pl = NULL;
4679 
4680 	ZFS_EXIT(zfsvfs);
4681 	return (err);
4682 }
4683 
4684 /*
4685  * Request a memory map for a section of a file.  This code interacts
4686  * with common code and the VM system as follows:
4687  *
4688  * - common code calls mmap(), which ends up in smmap_common()
4689  * - this calls VOP_MAP(), which takes you into (say) zfs
4690  * - zfs_map() calls as_map(), passing segvn_create() as the callback
4691  * - segvn_create() creates the new segment and calls VOP_ADDMAP()
4692  * - zfs_addmap() updates z_mapcnt
4693  */
4694 /*ARGSUSED*/
4695 static int
4696 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
4697     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4698     caller_context_t *ct)
4699 {
4700 	znode_t *zp = VTOZ(vp);
4701 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4702 	segvn_crargs_t	vn_a;
4703 	int		error;
4704 
4705 	ZFS_ENTER(zfsvfs);
4706 	ZFS_VERIFY_ZP(zp);
4707 
4708 	/*
4709 	 * Note: ZFS_READONLY is handled in zfs_zaccess_common.
4710 	 */
4711 
4712 	if ((prot & PROT_WRITE) && (zp->z_pflags &
4713 	    (ZFS_IMMUTABLE | ZFS_APPENDONLY))) {
4714 		ZFS_EXIT(zfsvfs);
4715 		return (SET_ERROR(EPERM));
4716 	}
4717 
4718 	if ((prot & (PROT_READ | PROT_EXEC)) &&
4719 	    (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4720 		ZFS_EXIT(zfsvfs);
4721 		return (SET_ERROR(EACCES));
4722 	}
4723 
4724 	if (vp->v_flag & VNOMAP) {
4725 		ZFS_EXIT(zfsvfs);
4726 		return (SET_ERROR(ENOSYS));
4727 	}
4728 
4729 	if (off < 0 || len > MAXOFFSET_T - off) {
4730 		ZFS_EXIT(zfsvfs);
4731 		return (SET_ERROR(ENXIO));
4732 	}
4733 
4734 	if (vp->v_type != VREG) {
4735 		ZFS_EXIT(zfsvfs);
4736 		return (SET_ERROR(ENODEV));
4737 	}
4738 
4739 	/*
4740 	 * If file is locked, disallow mapping.
4741 	 */
4742 	if (MANDMODE(zp->z_mode) && vn_has_flocks(vp)) {
4743 		ZFS_EXIT(zfsvfs);
4744 		return (SET_ERROR(EAGAIN));
4745 	}
4746 
4747 	as_rangelock(as);
4748 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
4749 	if (error != 0) {
4750 		as_rangeunlock(as);
4751 		ZFS_EXIT(zfsvfs);
4752 		return (error);
4753 	}
4754 
4755 	vn_a.vp = vp;
4756 	vn_a.offset = (u_offset_t)off;
4757 	vn_a.type = flags & MAP_TYPE;
4758 	vn_a.prot = prot;
4759 	vn_a.maxprot = maxprot;
4760 	vn_a.cred = cr;
4761 	vn_a.amp = NULL;
4762 	vn_a.flags = flags & ~MAP_TYPE;
4763 	vn_a.szc = 0;
4764 	vn_a.lgrp_mem_policy_flags = 0;
4765 
4766 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
4767 
4768 	as_rangeunlock(as);
4769 	ZFS_EXIT(zfsvfs);
4770 	return (error);
4771 }
4772 
4773 /* ARGSUSED */
4774 static int
4775 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4776     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4777     caller_context_t *ct)
4778 {
4779 	uint64_t pages = btopr(len);
4780 
4781 	atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
4782 	return (0);
4783 }
4784 
4785 /*
4786  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
4787  * more accurate mtime for the associated file.  Since we don't have a way of
4788  * detecting when the data was actually modified, we have to resort to
4789  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
4790  * last page is pushed.  The problem occurs when the msync() call is omitted,
4791  * which by far the most common case:
4792  *
4793  *	open()
4794  *	mmap()
4795  *	<modify memory>
4796  *	munmap()
4797  *	close()
4798  *	<time lapse>
4799  *	putpage() via fsflush
4800  *
4801  * If we wait until fsflush to come along, we can have a modification time that
4802  * is some arbitrary point in the future.  In order to prevent this in the
4803  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
4804  * torn down.
4805  */
4806 /* ARGSUSED */
4807 static int
4808 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4809     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
4810     caller_context_t *ct)
4811 {
4812 	uint64_t pages = btopr(len);
4813 
4814 	ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
4815 	atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
4816 
4817 	if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
4818 	    vn_has_cached_data(vp))
4819 		(void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
4820 
4821 	return (0);
4822 }
4823 
4824 /*
4825  * Free or allocate space in a file.  Currently, this function only
4826  * supports the `F_FREESP' command.  However, this command is somewhat
4827  * misnamed, as its functionality includes the ability to allocate as
4828  * well as free space.
4829  *
4830  *	IN:	vp	- vnode of file to free data in.
4831  *		cmd	- action to take (only F_FREESP supported).
4832  *		bfp	- section of file to free/alloc.
4833  *		flag	- current file open mode flags.
4834  *		offset	- current file offset.
4835  *		cr	- credentials of caller [UNUSED].
4836  *		ct	- caller context.
4837  *
4838  *	RETURN:	0 on success, error code on failure.
4839  *
4840  * Timestamps:
4841  *	vp - ctime|mtime updated
4842  */
4843 /* ARGSUSED */
4844 static int
4845 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
4846     offset_t offset, cred_t *cr, caller_context_t *ct)
4847 {
4848 	znode_t		*zp = VTOZ(vp);
4849 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4850 	uint64_t	off, len;
4851 	int		error;
4852 
4853 	ZFS_ENTER(zfsvfs);
4854 	ZFS_VERIFY_ZP(zp);
4855 
4856 	if (cmd != F_FREESP) {
4857 		ZFS_EXIT(zfsvfs);
4858 		return (SET_ERROR(EINVAL));
4859 	}
4860 
4861 	/*
4862 	 * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
4863 	 * callers might not be able to detect properly that we are read-only,
4864 	 * so check it explicitly here.
4865 	 */
4866 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
4867 		ZFS_EXIT(zfsvfs);
4868 		return (SET_ERROR(EROFS));
4869 	}
4870 
4871 	if (error = convoff(vp, bfp, 0, offset)) {
4872 		ZFS_EXIT(zfsvfs);
4873 		return (error);
4874 	}
4875 
4876 	if (bfp->l_len < 0) {
4877 		ZFS_EXIT(zfsvfs);
4878 		return (SET_ERROR(EINVAL));
4879 	}
4880 
4881 	off = bfp->l_start;
4882 	len = bfp->l_len; /* 0 means from off to end of file */
4883 
4884 	error = zfs_freesp(zp, off, len, flag, TRUE);
4885 
4886 	if (error == 0 && off == 0 && len == 0)
4887 		vnevent_truncate(ZTOV(zp), ct);
4888 
4889 	ZFS_EXIT(zfsvfs);
4890 	return (error);
4891 }
4892 
4893 /*ARGSUSED*/
4894 static int
4895 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
4896 {
4897 	znode_t		*zp = VTOZ(vp);
4898 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4899 	uint32_t	gen;
4900 	uint64_t	gen64;
4901 	uint64_t	object = zp->z_id;
4902 	zfid_short_t	*zfid;
4903 	int		size, i, error;
4904 
4905 	ZFS_ENTER(zfsvfs);
4906 	ZFS_VERIFY_ZP(zp);
4907 
4908 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
4909 	    &gen64, sizeof (uint64_t))) != 0) {
4910 		ZFS_EXIT(zfsvfs);
4911 		return (error);
4912 	}
4913 
4914 	gen = (uint32_t)gen64;
4915 
4916 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
4917 	if (fidp->fid_len < size) {
4918 		fidp->fid_len = size;
4919 		ZFS_EXIT(zfsvfs);
4920 		return (SET_ERROR(ENOSPC));
4921 	}
4922 
4923 	zfid = (zfid_short_t *)fidp;
4924 
4925 	zfid->zf_len = size;
4926 
4927 	for (i = 0; i < sizeof (zfid->zf_object); i++)
4928 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4929 
4930 	/* Must have a non-zero generation number to distinguish from .zfs */
4931 	if (gen == 0)
4932 		gen = 1;
4933 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
4934 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4935 
4936 	if (size == LONG_FID_LEN) {
4937 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
4938 		zfid_long_t	*zlfid;
4939 
4940 		zlfid = (zfid_long_t *)fidp;
4941 
4942 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4943 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4944 
4945 		/* XXX - this should be the generation number for the objset */
4946 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4947 			zlfid->zf_setgen[i] = 0;
4948 	}
4949 
4950 	ZFS_EXIT(zfsvfs);
4951 	return (0);
4952 }
4953 
4954 static int
4955 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
4956     caller_context_t *ct)
4957 {
4958 	znode_t		*zp, *xzp;
4959 	zfsvfs_t	*zfsvfs;
4960 	zfs_dirlock_t	*dl;
4961 	int		error;
4962 
4963 	switch (cmd) {
4964 	case _PC_LINK_MAX:
4965 		*valp = ULONG_MAX;
4966 		return (0);
4967 
4968 	case _PC_FILESIZEBITS:
4969 		*valp = 64;
4970 		return (0);
4971 
4972 	case _PC_XATTR_EXISTS:
4973 		zp = VTOZ(vp);
4974 		zfsvfs = zp->z_zfsvfs;
4975 		ZFS_ENTER(zfsvfs);
4976 		ZFS_VERIFY_ZP(zp);
4977 		*valp = 0;
4978 		error = zfs_dirent_lock(&dl, zp, "", &xzp,
4979 		    ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
4980 		if (error == 0) {
4981 			zfs_dirent_unlock(dl);
4982 			if (!zfs_dirempty(xzp))
4983 				*valp = 1;
4984 			VN_RELE(ZTOV(xzp));
4985 		} else if (error == ENOENT) {
4986 			/*
4987 			 * If there aren't extended attributes, it's the
4988 			 * same as having zero of them.
4989 			 */
4990 			error = 0;
4991 		}
4992 		ZFS_EXIT(zfsvfs);
4993 		return (error);
4994 
4995 	case _PC_SATTR_ENABLED:
4996 	case _PC_SATTR_EXISTS:
4997 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
4998 		    (vp->v_type == VREG || vp->v_type == VDIR);
4999 		return (0);
5000 
5001 	case _PC_ACCESS_FILTERING:
5002 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_ACCESS_FILTER) &&
5003 		    vp->v_type == VDIR;
5004 		return (0);
5005 
5006 	case _PC_ACL_ENABLED:
5007 		*valp = _ACL_ACE_ENABLED;
5008 		return (0);
5009 
5010 	case _PC_MIN_HOLE_SIZE:
5011 		*valp = (ulong_t)SPA_MINBLOCKSIZE;
5012 		return (0);
5013 
5014 	case _PC_TIMESTAMP_RESOLUTION:
5015 		/* nanosecond timestamp resolution */
5016 		*valp = 1L;
5017 		return (0);
5018 
5019 	default:
5020 		return (fs_pathconf(vp, cmd, valp, cr, ct));
5021 	}
5022 }
5023 
5024 /*ARGSUSED*/
5025 static int
5026 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5027     caller_context_t *ct)
5028 {
5029 	znode_t *zp = VTOZ(vp);
5030 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5031 	int error;
5032 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5033 
5034 	ZFS_ENTER(zfsvfs);
5035 	ZFS_VERIFY_ZP(zp);
5036 	error = zfs_getacl(zp, vsecp, skipaclchk, cr);
5037 	ZFS_EXIT(zfsvfs);
5038 
5039 	return (error);
5040 }
5041 
5042 /*ARGSUSED*/
5043 static int
5044 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5045     caller_context_t *ct)
5046 {
5047 	znode_t *zp = VTOZ(vp);
5048 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5049 	int error;
5050 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5051 	zilog_t	*zilog = zfsvfs->z_log;
5052 
5053 	ZFS_ENTER(zfsvfs);
5054 	ZFS_VERIFY_ZP(zp);
5055 
5056 	error = zfs_setacl(zp, vsecp, skipaclchk, cr);
5057 
5058 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
5059 		zil_commit(zilog, 0);
5060 
5061 	ZFS_EXIT(zfsvfs);
5062 	return (error);
5063 }
5064 
5065 /*
5066  * The smallest read we may consider to loan out an arcbuf.
5067  * This must be a power of 2.
5068  */
5069 int zcr_blksz_min = (1 << 10);	/* 1K */
5070 /*
5071  * If set to less than the file block size, allow loaning out of an
5072  * arcbuf for a partial block read.  This must be a power of 2.
5073  */
5074 int zcr_blksz_max = (1 << 17);	/* 128K */
5075 
5076 /*ARGSUSED*/
5077 static int
5078 zfs_reqzcbuf(vnode_t *vp, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr,
5079     caller_context_t *ct)
5080 {
5081 	znode_t	*zp = VTOZ(vp);
5082 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5083 	int max_blksz = zfsvfs->z_max_blksz;
5084 	uio_t *uio = &xuio->xu_uio;
5085 	ssize_t size = uio->uio_resid;
5086 	offset_t offset = uio->uio_loffset;
5087 	int blksz;
5088 	int fullblk, i;
5089 	arc_buf_t *abuf;
5090 	ssize_t maxsize;
5091 	int preamble, postamble;
5092 
5093 	if (xuio->xu_type != UIOTYPE_ZEROCOPY)
5094 		return (SET_ERROR(EINVAL));
5095 
5096 	ZFS_ENTER(zfsvfs);
5097 	ZFS_VERIFY_ZP(zp);
5098 	switch (ioflag) {
5099 	case UIO_WRITE:
5100 		/*
5101 		 * Loan out an arc_buf for write if write size is bigger than
5102 		 * max_blksz, and the file's block size is also max_blksz.
5103 		 */
5104 		blksz = max_blksz;
5105 		if (size < blksz || zp->z_blksz != blksz) {
5106 			ZFS_EXIT(zfsvfs);
5107 			return (SET_ERROR(EINVAL));
5108 		}
5109 		/*
5110 		 * Caller requests buffers for write before knowing where the
5111 		 * write offset might be (e.g. NFS TCP write).
5112 		 */
5113 		if (offset == -1) {
5114 			preamble = 0;
5115 		} else {
5116 			preamble = P2PHASE(offset, blksz);
5117 			if (preamble) {
5118 				preamble = blksz - preamble;
5119 				size -= preamble;
5120 			}
5121 		}
5122 
5123 		postamble = P2PHASE(size, blksz);
5124 		size -= postamble;
5125 
5126 		fullblk = size / blksz;
5127 		(void) dmu_xuio_init(xuio,
5128 		    (preamble != 0) + fullblk + (postamble != 0));
5129 		DTRACE_PROBE3(zfs_reqzcbuf_align, int, preamble,
5130 		    int, postamble, int,
5131 		    (preamble != 0) + fullblk + (postamble != 0));
5132 
5133 		/*
5134 		 * Have to fix iov base/len for partial buffers.  They
5135 		 * currently represent full arc_buf's.
5136 		 */
5137 		if (preamble) {
5138 			/* data begins in the middle of the arc_buf */
5139 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5140 			    blksz);
5141 			ASSERT(abuf);
5142 			(void) dmu_xuio_add(xuio, abuf,
5143 			    blksz - preamble, preamble);
5144 		}
5145 
5146 		for (i = 0; i < fullblk; i++) {
5147 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5148 			    blksz);
5149 			ASSERT(abuf);
5150 			(void) dmu_xuio_add(xuio, abuf, 0, blksz);
5151 		}
5152 
5153 		if (postamble) {
5154 			/* data ends in the middle of the arc_buf */
5155 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5156 			    blksz);
5157 			ASSERT(abuf);
5158 			(void) dmu_xuio_add(xuio, abuf, 0, postamble);
5159 		}
5160 		break;
5161 	case UIO_READ:
5162 		/*
5163 		 * Loan out an arc_buf for read if the read size is larger than
5164 		 * the current file block size.  Block alignment is not
5165 		 * considered.  Partial arc_buf will be loaned out for read.
5166 		 */
5167 		blksz = zp->z_blksz;
5168 		if (blksz < zcr_blksz_min)
5169 			blksz = zcr_blksz_min;
5170 		if (blksz > zcr_blksz_max)
5171 			blksz = zcr_blksz_max;
5172 		/* avoid potential complexity of dealing with it */
5173 		if (blksz > max_blksz) {
5174 			ZFS_EXIT(zfsvfs);
5175 			return (SET_ERROR(EINVAL));
5176 		}
5177 
5178 		maxsize = zp->z_size - uio->uio_loffset;
5179 		if (size > maxsize)
5180 			size = maxsize;
5181 
5182 		if (size < blksz || vn_has_cached_data(vp)) {
5183 			ZFS_EXIT(zfsvfs);
5184 			return (SET_ERROR(EINVAL));
5185 		}
5186 		break;
5187 	default:
5188 		ZFS_EXIT(zfsvfs);
5189 		return (SET_ERROR(EINVAL));
5190 	}
5191 
5192 	uio->uio_extflg = UIO_XUIO;
5193 	XUIO_XUZC_RW(xuio) = ioflag;
5194 	ZFS_EXIT(zfsvfs);
5195 	return (0);
5196 }
5197 
5198 /*ARGSUSED*/
5199 static int
5200 zfs_retzcbuf(vnode_t *vp, xuio_t *xuio, cred_t *cr, caller_context_t *ct)
5201 {
5202 	int i;
5203 	arc_buf_t *abuf;
5204 	int ioflag = XUIO_XUZC_RW(xuio);
5205 
5206 	ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
5207 
5208 	i = dmu_xuio_cnt(xuio);
5209 	while (i-- > 0) {
5210 		abuf = dmu_xuio_arcbuf(xuio, i);
5211 		/*
5212 		 * if abuf == NULL, it must be a write buffer
5213 		 * that has been returned in zfs_write().
5214 		 */
5215 		if (abuf)
5216 			dmu_return_arcbuf(abuf);
5217 		ASSERT(abuf || ioflag == UIO_WRITE);
5218 	}
5219 
5220 	dmu_xuio_fini(xuio);
5221 	return (0);
5222 }
5223 
5224 /*
5225  * Predeclare these here so that the compiler assumes that
5226  * this is an "old style" function declaration that does
5227  * not include arguments => we won't get type mismatch errors
5228  * in the initializations that follow.
5229  */
5230 static int zfs_inval();
5231 static int zfs_isdir();
5232 
5233 static int
5234 zfs_inval()
5235 {
5236 	return (SET_ERROR(EINVAL));
5237 }
5238 
5239 static int
5240 zfs_isdir()
5241 {
5242 	return (SET_ERROR(EISDIR));
5243 }
5244 /*
5245  * Directory vnode operations template
5246  */
5247 vnodeops_t *zfs_dvnodeops;
5248 const fs_operation_def_t zfs_dvnodeops_template[] = {
5249 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5250 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5251 	VOPNAME_READ,		{ .error = zfs_isdir },
5252 	VOPNAME_WRITE,		{ .error = zfs_isdir },
5253 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5254 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5255 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5256 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5257 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5258 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5259 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5260 	VOPNAME_LINK,		{ .vop_link = zfs_link },
5261 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5262 	VOPNAME_MKDIR,		{ .vop_mkdir = zfs_mkdir },
5263 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5264 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5265 	VOPNAME_SYMLINK,	{ .vop_symlink = zfs_symlink },
5266 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5267 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5268 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5269 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5270 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5271 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5272 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5273 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5274 	NULL,			NULL
5275 };
5276 
5277 /*
5278  * Regular file vnode operations template
5279  */
5280 vnodeops_t *zfs_fvnodeops;
5281 const fs_operation_def_t zfs_fvnodeops_template[] = {
5282 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5283 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5284 	VOPNAME_READ,		{ .vop_read = zfs_read },
5285 	VOPNAME_WRITE,		{ .vop_write = zfs_write },
5286 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5287 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5288 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5289 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5290 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5291 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5292 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5293 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5294 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5295 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5296 	VOPNAME_FRLOCK,		{ .vop_frlock = zfs_frlock },
5297 	VOPNAME_SPACE,		{ .vop_space = zfs_space },
5298 	VOPNAME_GETPAGE,	{ .vop_getpage = zfs_getpage },
5299 	VOPNAME_PUTPAGE,	{ .vop_putpage = zfs_putpage },
5300 	VOPNAME_MAP,		{ .vop_map = zfs_map },
5301 	VOPNAME_ADDMAP,		{ .vop_addmap = zfs_addmap },
5302 	VOPNAME_DELMAP,		{ .vop_delmap = zfs_delmap },
5303 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5304 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5305 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5306 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5307 	VOPNAME_REQZCBUF,	{ .vop_reqzcbuf = zfs_reqzcbuf },
5308 	VOPNAME_RETZCBUF,	{ .vop_retzcbuf = zfs_retzcbuf },
5309 	NULL,			NULL
5310 };
5311 
5312 /*
5313  * Symbolic link vnode operations template
5314  */
5315 vnodeops_t *zfs_symvnodeops;
5316 const fs_operation_def_t zfs_symvnodeops_template[] = {
5317 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5318 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5319 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5320 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5321 	VOPNAME_READLINK,	{ .vop_readlink = zfs_readlink },
5322 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5323 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5324 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5325 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5326 	NULL,			NULL
5327 };
5328 
5329 /*
5330  * special share hidden files vnode operations template
5331  */
5332 vnodeops_t *zfs_sharevnodeops;
5333 const fs_operation_def_t zfs_sharevnodeops_template[] = {
5334 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5335 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5336 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5337 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5338 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5339 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5340 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5341 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5342 	NULL,			NULL
5343 };
5344 
5345 /*
5346  * Extended attribute directory vnode operations template
5347  *
5348  * This template is identical to the directory vnodes
5349  * operation template except for restricted operations:
5350  *	VOP_MKDIR()
5351  *	VOP_SYMLINK()
5352  *
5353  * Note that there are other restrictions embedded in:
5354  *	zfs_create()	- restrict type to VREG
5355  *	zfs_link()	- no links into/out of attribute space
5356  *	zfs_rename()	- no moves into/out of attribute space
5357  */
5358 vnodeops_t *zfs_xdvnodeops;
5359 const fs_operation_def_t zfs_xdvnodeops_template[] = {
5360 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5361 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5362 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5363 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5364 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5365 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5366 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5367 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5368 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5369 	VOPNAME_LINK,		{ .vop_link = zfs_link },
5370 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5371 	VOPNAME_MKDIR,		{ .error = zfs_inval },
5372 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5373 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5374 	VOPNAME_SYMLINK,	{ .error = zfs_inval },
5375 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5376 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5377 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5378 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5379 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5380 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5381 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5382 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5383 	NULL,			NULL
5384 };
5385 
5386 /*
5387  * Error vnode operations template
5388  */
5389 vnodeops_t *zfs_evnodeops;
5390 const fs_operation_def_t zfs_evnodeops_template[] = {
5391 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5392 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5393 	NULL,			NULL
5394 };
5395