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