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