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