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