xref: /titanic_41/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision 0cfdb6036e046270988a17ac442e4d717d426a44)
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 	zfs_acl_t	*aclp = NULL;
1125 	zfs_fuid_info_t *fuidp = NULL;
1126 
1127 	/*
1128 	 * If we have an ephemeral id, ACL, or XVATTR then
1129 	 * make sure file system is at proper version
1130 	 */
1131 
1132 	if (zfsvfs->z_use_fuids == B_FALSE &&
1133 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1134 	    IS_EPHEMERAL(crgetuid(cr)) || IS_EPHEMERAL(crgetgid(cr))))
1135 		return (EINVAL);
1136 
1137 	ZFS_ENTER(zfsvfs);
1138 	ZFS_VERIFY_ZP(dzp);
1139 	os = zfsvfs->z_os;
1140 	zilog = zfsvfs->z_log;
1141 
1142 	if (zfsvfs->z_case & ZFS_UTF8_ONLY && u8_validate(name, strlen(name),
1143 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1144 		ZFS_EXIT(zfsvfs);
1145 		return (EILSEQ);
1146 	}
1147 
1148 	if (vap->va_mask & AT_XVATTR) {
1149 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1150 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1151 			ZFS_EXIT(zfsvfs);
1152 			return (error);
1153 		}
1154 	}
1155 top:
1156 	*vpp = NULL;
1157 
1158 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1159 		vap->va_mode &= ~VSVTX;
1160 
1161 	if (*name == '\0') {
1162 		/*
1163 		 * Null component name refers to the directory itself.
1164 		 */
1165 		VN_HOLD(dvp);
1166 		zp = dzp;
1167 		dl = NULL;
1168 		error = 0;
1169 	} else {
1170 		/* possible VN_HOLD(zp) */
1171 		int zflg = 0;
1172 
1173 		if (flag & FIGNORECASE)
1174 			zflg |= ZCILOOK;
1175 
1176 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1177 		    NULL, NULL);
1178 		if (error) {
1179 			if (strcmp(name, "..") == 0)
1180 				error = EISDIR;
1181 			ZFS_EXIT(zfsvfs);
1182 			if (aclp)
1183 				zfs_acl_free(aclp);
1184 			return (error);
1185 		}
1186 	}
1187 	if (vsecp && aclp == NULL) {
1188 		error = zfs_vsec_2_aclp(zfsvfs, vap->va_type, vsecp, &aclp);
1189 		if (error) {
1190 			ZFS_EXIT(zfsvfs);
1191 			if (dl)
1192 				zfs_dirent_unlock(dl);
1193 			return (error);
1194 		}
1195 	}
1196 
1197 	if (zp == NULL) {
1198 		uint64_t txtype;
1199 
1200 		/*
1201 		 * Create a new file object and update the directory
1202 		 * to reference it.
1203 		 */
1204 		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1205 			goto out;
1206 		}
1207 
1208 		/*
1209 		 * We only support the creation of regular files in
1210 		 * extended attribute directories.
1211 		 */
1212 		if ((dzp->z_phys->zp_flags & ZFS_XATTR) &&
1213 		    (vap->va_type != VREG)) {
1214 			error = EINVAL;
1215 			goto out;
1216 		}
1217 
1218 		tx = dmu_tx_create(os);
1219 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1220 		if (zfsvfs->z_fuid_obj == 0) {
1221 			dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1222 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1223 			    SPA_MAXBLOCKSIZE);
1224 			dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, FALSE, NULL);
1225 		} else {
1226 			dmu_tx_hold_bonus(tx, zfsvfs->z_fuid_obj);
1227 			dmu_tx_hold_write(tx, zfsvfs->z_fuid_obj, 0,
1228 			    SPA_MAXBLOCKSIZE);
1229 		}
1230 		dmu_tx_hold_bonus(tx, dzp->z_id);
1231 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1232 		if ((dzp->z_phys->zp_flags & ZFS_INHERIT_ACE) || aclp) {
1233 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1234 			    0, SPA_MAXBLOCKSIZE);
1235 		}
1236 		error = dmu_tx_assign(tx, zfsvfs->z_assign);
1237 		if (error) {
1238 			zfs_dirent_unlock(dl);
1239 			if (error == ERESTART &&
1240 			    zfsvfs->z_assign == TXG_NOWAIT) {
1241 				dmu_tx_wait(tx);
1242 				dmu_tx_abort(tx);
1243 				goto top;
1244 			}
1245 			dmu_tx_abort(tx);
1246 			ZFS_EXIT(zfsvfs);
1247 			if (aclp)
1248 				zfs_acl_free(aclp);
1249 			return (error);
1250 		}
1251 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, 0, aclp, &fuidp);
1252 		(void) zfs_link_create(dl, zp, tx, ZNEW);
1253 		txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1254 		if (flag & FIGNORECASE)
1255 			txtype |= TX_CI;
1256 		zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1257 		    vsecp, fuidp, vap);
1258 		if (fuidp)
1259 			zfs_fuid_info_free(fuidp);
1260 		dmu_tx_commit(tx);
1261 	} else {
1262 		int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1263 
1264 		/*
1265 		 * A directory entry already exists for this name.
1266 		 */
1267 		/*
1268 		 * Can't truncate an existing file if in exclusive mode.
1269 		 */
1270 		if (excl == EXCL) {
1271 			error = EEXIST;
1272 			goto out;
1273 		}
1274 		/*
1275 		 * Can't open a directory for writing.
1276 		 */
1277 		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1278 			error = EISDIR;
1279 			goto out;
1280 		}
1281 		/*
1282 		 * Verify requested access to file.
1283 		 */
1284 		if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1285 			goto out;
1286 		}
1287 
1288 		mutex_enter(&dzp->z_lock);
1289 		dzp->z_seq++;
1290 		mutex_exit(&dzp->z_lock);
1291 
1292 		/*
1293 		 * Truncate regular files if requested.
1294 		 */
1295 		if ((ZTOV(zp)->v_type == VREG) &&
1296 		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1297 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1298 			if (error == ERESTART &&
1299 			    zfsvfs->z_assign == TXG_NOWAIT) {
1300 				/* NB: we already did dmu_tx_wait() */
1301 				zfs_dirent_unlock(dl);
1302 				VN_RELE(ZTOV(zp));
1303 				goto top;
1304 			}
1305 
1306 			if (error == 0) {
1307 				vnevent_create(ZTOV(zp), ct);
1308 			}
1309 		}
1310 	}
1311 out:
1312 
1313 	if (dl)
1314 		zfs_dirent_unlock(dl);
1315 
1316 	if (error) {
1317 		if (zp)
1318 			VN_RELE(ZTOV(zp));
1319 	} else {
1320 		*vpp = ZTOV(zp);
1321 		/*
1322 		 * If vnode is for a device return a specfs vnode instead.
1323 		 */
1324 		if (IS_DEVVP(*vpp)) {
1325 			struct vnode *svp;
1326 
1327 			svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1328 			VN_RELE(*vpp);
1329 			if (svp == NULL) {
1330 				error = ENOSYS;
1331 			}
1332 			*vpp = svp;
1333 		}
1334 	}
1335 	if (aclp)
1336 		zfs_acl_free(aclp);
1337 
1338 	ZFS_EXIT(zfsvfs);
1339 	return (error);
1340 }
1341 
1342 /*
1343  * Remove an entry from a directory.
1344  *
1345  *	IN:	dvp	- vnode of directory to remove entry from.
1346  *		name	- name of entry to remove.
1347  *		cr	- credentials of caller.
1348  *		ct	- caller context
1349  *		flags	- case flags
1350  *
1351  *	RETURN:	0 if success
1352  *		error code if failure
1353  *
1354  * Timestamps:
1355  *	dvp - ctime|mtime
1356  *	 vp - ctime (if nlink > 0)
1357  */
1358 /*ARGSUSED*/
1359 static int
1360 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1361     int flags)
1362 {
1363 	znode_t		*zp, *dzp = VTOZ(dvp);
1364 	znode_t		*xzp = NULL;
1365 	vnode_t		*vp;
1366 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1367 	zilog_t		*zilog;
1368 	uint64_t	acl_obj, xattr_obj;
1369 	zfs_dirlock_t	*dl;
1370 	dmu_tx_t	*tx;
1371 	boolean_t	may_delete_now, delete_now = FALSE;
1372 	boolean_t	unlinked;
1373 	uint64_t	txtype;
1374 	pathname_t	*realnmp = NULL;
1375 	pathname_t	realnm;
1376 	int		error;
1377 	int		zflg = ZEXISTS;
1378 
1379 	ZFS_ENTER(zfsvfs);
1380 	ZFS_VERIFY_ZP(dzp);
1381 	zilog = zfsvfs->z_log;
1382 
1383 	if (flags & FIGNORECASE) {
1384 		zflg |= ZCILOOK;
1385 		pn_alloc(&realnm);
1386 		realnmp = &realnm;
1387 	}
1388 
1389 top:
1390 	/*
1391 	 * Attempt to lock directory; fail if entry doesn't exist.
1392 	 */
1393 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1394 	    NULL, realnmp)) {
1395 		if (realnmp)
1396 			pn_free(realnmp);
1397 		ZFS_EXIT(zfsvfs);
1398 		return (error);
1399 	}
1400 
1401 	vp = ZTOV(zp);
1402 
1403 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1404 		goto out;
1405 	}
1406 
1407 	/*
1408 	 * Need to use rmdir for removing directories.
1409 	 */
1410 	if (vp->v_type == VDIR) {
1411 		error = EPERM;
1412 		goto out;
1413 	}
1414 
1415 	vnevent_remove(vp, dvp, name, ct);
1416 
1417 	if (realnmp)
1418 		dnlc_remove(dvp, realnmp->pn_path);
1419 	else
1420 		dnlc_remove(dvp, name);
1421 
1422 	mutex_enter(&vp->v_lock);
1423 	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1424 	mutex_exit(&vp->v_lock);
1425 
1426 	/*
1427 	 * We may delete the znode now, or we may put it in the unlinked set;
1428 	 * it depends on whether we're the last link, and on whether there are
1429 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1430 	 * allow for either case.
1431 	 */
1432 	tx = dmu_tx_create(zfsvfs->z_os);
1433 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1434 	dmu_tx_hold_bonus(tx, zp->z_id);
1435 	if (may_delete_now)
1436 		dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
1437 
1438 	/* are there any extended attributes? */
1439 	if ((xattr_obj = zp->z_phys->zp_xattr) != 0) {
1440 		/* XXX - do we need this if we are deleting? */
1441 		dmu_tx_hold_bonus(tx, xattr_obj);
1442 	}
1443 
1444 	/* are there any additional acls */
1445 	if ((acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj) != 0 &&
1446 	    may_delete_now)
1447 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1448 
1449 	/* charge as an update -- would be nice not to charge at all */
1450 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1451 
1452 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1453 	if (error) {
1454 		zfs_dirent_unlock(dl);
1455 		VN_RELE(vp);
1456 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1457 			dmu_tx_wait(tx);
1458 			dmu_tx_abort(tx);
1459 			goto top;
1460 		}
1461 		if (realnmp)
1462 			pn_free(realnmp);
1463 		dmu_tx_abort(tx);
1464 		ZFS_EXIT(zfsvfs);
1465 		return (error);
1466 	}
1467 
1468 	/*
1469 	 * Remove the directory entry.
1470 	 */
1471 	error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1472 
1473 	if (error) {
1474 		dmu_tx_commit(tx);
1475 		goto out;
1476 	}
1477 
1478 	if (unlinked) {
1479 		mutex_enter(&vp->v_lock);
1480 		delete_now = may_delete_now &&
1481 		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1482 		    zp->z_phys->zp_xattr == xattr_obj &&
1483 		    zp->z_phys->zp_acl.z_acl_extern_obj == acl_obj;
1484 		mutex_exit(&vp->v_lock);
1485 	}
1486 
1487 	if (delete_now) {
1488 		if (zp->z_phys->zp_xattr) {
1489 			error = zfs_zget(zfsvfs, zp->z_phys->zp_xattr, &xzp);
1490 			ASSERT3U(error, ==, 0);
1491 			ASSERT3U(xzp->z_phys->zp_links, ==, 2);
1492 			dmu_buf_will_dirty(xzp->z_dbuf, tx);
1493 			mutex_enter(&xzp->z_lock);
1494 			xzp->z_unlinked = 1;
1495 			xzp->z_phys->zp_links = 0;
1496 			mutex_exit(&xzp->z_lock);
1497 			zfs_unlinked_add(xzp, tx);
1498 			zp->z_phys->zp_xattr = 0; /* probably unnecessary */
1499 		}
1500 		mutex_enter(&zp->z_lock);
1501 		mutex_enter(&vp->v_lock);
1502 		vp->v_count--;
1503 		ASSERT3U(vp->v_count, ==, 0);
1504 		mutex_exit(&vp->v_lock);
1505 		mutex_exit(&zp->z_lock);
1506 		zfs_znode_delete(zp, tx);
1507 		VFS_RELE(zfsvfs->z_vfs);
1508 	} else if (unlinked) {
1509 		zfs_unlinked_add(zp, tx);
1510 	}
1511 
1512 	txtype = TX_REMOVE;
1513 	if (flags & FIGNORECASE)
1514 		txtype |= TX_CI;
1515 	zfs_log_remove(zilog, tx, txtype, dzp, name);
1516 
1517 	dmu_tx_commit(tx);
1518 out:
1519 	if (realnmp)
1520 		pn_free(realnmp);
1521 
1522 	zfs_dirent_unlock(dl);
1523 
1524 	if (!delete_now) {
1525 		VN_RELE(vp);
1526 	} else if (xzp) {
1527 		/* this rele delayed to prevent nesting transactions */
1528 		VN_RELE(ZTOV(xzp));
1529 	}
1530 
1531 	ZFS_EXIT(zfsvfs);
1532 	return (error);
1533 }
1534 
1535 /*
1536  * Create a new directory and insert it into dvp using the name
1537  * provided.  Return a pointer to the inserted directory.
1538  *
1539  *	IN:	dvp	- vnode of directory to add subdir to.
1540  *		dirname	- name of new directory.
1541  *		vap	- attributes of new directory.
1542  *		cr	- credentials of caller.
1543  *		ct	- caller context
1544  *		vsecp	- ACL to be set
1545  *
1546  *	OUT:	vpp	- vnode of created directory.
1547  *
1548  *	RETURN:	0 if success
1549  *		error code if failure
1550  *
1551  * Timestamps:
1552  *	dvp - ctime|mtime updated
1553  *	 vp - ctime|mtime|atime updated
1554  */
1555 /*ARGSUSED*/
1556 static int
1557 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1558     caller_context_t *ct, int flags, vsecattr_t *vsecp)
1559 {
1560 	znode_t		*zp, *dzp = VTOZ(dvp);
1561 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1562 	zilog_t		*zilog;
1563 	zfs_dirlock_t	*dl;
1564 	uint64_t	txtype;
1565 	dmu_tx_t	*tx;
1566 	int		error;
1567 	zfs_acl_t	*aclp = NULL;
1568 	zfs_fuid_info_t	*fuidp = NULL;
1569 	int		zf = ZNEW;
1570 
1571 	ASSERT(vap->va_type == VDIR);
1572 
1573 	/*
1574 	 * If we have an ephemeral id, ACL, or XVATTR then
1575 	 * make sure file system is at proper version
1576 	 */
1577 
1578 	if (zfsvfs->z_use_fuids == B_FALSE &&
1579 	    (vsecp || (vap->va_mask & AT_XVATTR) || IS_EPHEMERAL(crgetuid(cr))||
1580 	    IS_EPHEMERAL(crgetgid(cr))))
1581 		return (EINVAL);
1582 
1583 	ZFS_ENTER(zfsvfs);
1584 	ZFS_VERIFY_ZP(dzp);
1585 	zilog = zfsvfs->z_log;
1586 
1587 	if (dzp->z_phys->zp_flags & ZFS_XATTR) {
1588 		ZFS_EXIT(zfsvfs);
1589 		return (EINVAL);
1590 	}
1591 
1592 	if (zfsvfs->z_case & ZFS_UTF8_ONLY && u8_validate(dirname,
1593 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1594 		ZFS_EXIT(zfsvfs);
1595 		return (EILSEQ);
1596 	}
1597 	if (flags & FIGNORECASE)
1598 		zf |= ZCILOOK;
1599 
1600 	if (vap->va_mask & AT_XVATTR)
1601 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1602 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1603 			ZFS_EXIT(zfsvfs);
1604 			return (error);
1605 		}
1606 
1607 	/*
1608 	 * First make sure the new directory doesn't exist.
1609 	 */
1610 top:
1611 	*vpp = NULL;
1612 
1613 	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
1614 	    NULL, NULL)) {
1615 		ZFS_EXIT(zfsvfs);
1616 		return (error);
1617 	}
1618 
1619 	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
1620 		zfs_dirent_unlock(dl);
1621 		ZFS_EXIT(zfsvfs);
1622 		return (error);
1623 	}
1624 
1625 	if (vsecp && aclp == NULL) {
1626 		error = zfs_vsec_2_aclp(zfsvfs, vap->va_type, vsecp, &aclp);
1627 		if (error) {
1628 			zfs_dirent_unlock(dl);
1629 			ZFS_EXIT(zfsvfs);
1630 			return (error);
1631 		}
1632 	}
1633 	/*
1634 	 * Add a new entry to the directory.
1635 	 */
1636 	tx = dmu_tx_create(zfsvfs->z_os);
1637 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1638 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1639 	if (zfsvfs->z_fuid_obj == 0) {
1640 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1641 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1642 		    SPA_MAXBLOCKSIZE);
1643 		dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, FALSE, NULL);
1644 	} else {
1645 		dmu_tx_hold_bonus(tx, zfsvfs->z_fuid_obj);
1646 		dmu_tx_hold_write(tx, zfsvfs->z_fuid_obj, 0,
1647 		    SPA_MAXBLOCKSIZE);
1648 	}
1649 	if ((dzp->z_phys->zp_flags & ZFS_INHERIT_ACE) || aclp)
1650 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1651 		    0, SPA_MAXBLOCKSIZE);
1652 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1653 	if (error) {
1654 		zfs_dirent_unlock(dl);
1655 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1656 			dmu_tx_wait(tx);
1657 			dmu_tx_abort(tx);
1658 			goto top;
1659 		}
1660 		dmu_tx_abort(tx);
1661 		ZFS_EXIT(zfsvfs);
1662 		if (aclp)
1663 			zfs_acl_free(aclp);
1664 		return (error);
1665 	}
1666 
1667 	/*
1668 	 * Create new node.
1669 	 */
1670 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, 0, aclp, &fuidp);
1671 
1672 	if (aclp)
1673 		zfs_acl_free(aclp);
1674 
1675 	/*
1676 	 * Now put new name in parent dir.
1677 	 */
1678 	(void) zfs_link_create(dl, zp, tx, ZNEW);
1679 
1680 	*vpp = ZTOV(zp);
1681 
1682 	txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
1683 	if (flags & FIGNORECASE)
1684 		txtype |= TX_CI;
1685 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp, fuidp, vap);
1686 
1687 	if (fuidp)
1688 		zfs_fuid_info_free(fuidp);
1689 	dmu_tx_commit(tx);
1690 
1691 	zfs_dirent_unlock(dl);
1692 
1693 	ZFS_EXIT(zfsvfs);
1694 	return (0);
1695 }
1696 
1697 /*
1698  * Remove a directory subdir entry.  If the current working
1699  * directory is the same as the subdir to be removed, the
1700  * remove will fail.
1701  *
1702  *	IN:	dvp	- vnode of directory to remove from.
1703  *		name	- name of directory to be removed.
1704  *		cwd	- vnode of current working directory.
1705  *		cr	- credentials of caller.
1706  *		ct	- caller context
1707  *		flags	- case flags
1708  *
1709  *	RETURN:	0 if success
1710  *		error code if failure
1711  *
1712  * Timestamps:
1713  *	dvp - ctime|mtime updated
1714  */
1715 /*ARGSUSED*/
1716 static int
1717 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
1718     caller_context_t *ct, int flags)
1719 {
1720 	znode_t		*dzp = VTOZ(dvp);
1721 	znode_t		*zp;
1722 	vnode_t		*vp;
1723 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1724 	zilog_t		*zilog;
1725 	zfs_dirlock_t	*dl;
1726 	dmu_tx_t	*tx;
1727 	int		error;
1728 	int		zflg = ZEXISTS;
1729 
1730 	ZFS_ENTER(zfsvfs);
1731 	ZFS_VERIFY_ZP(dzp);
1732 	zilog = zfsvfs->z_log;
1733 
1734 	if (flags & FIGNORECASE)
1735 		zflg |= ZCILOOK;
1736 top:
1737 	zp = NULL;
1738 
1739 	/*
1740 	 * Attempt to lock directory; fail if entry doesn't exist.
1741 	 */
1742 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1743 	    NULL, NULL)) {
1744 		ZFS_EXIT(zfsvfs);
1745 		return (error);
1746 	}
1747 
1748 	vp = ZTOV(zp);
1749 
1750 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1751 		goto out;
1752 	}
1753 
1754 	if (vp->v_type != VDIR) {
1755 		error = ENOTDIR;
1756 		goto out;
1757 	}
1758 
1759 	if (vp == cwd) {
1760 		error = EINVAL;
1761 		goto out;
1762 	}
1763 
1764 	vnevent_rmdir(vp, dvp, name, ct);
1765 
1766 	/*
1767 	 * Grab a lock on the directory to make sure that noone is
1768 	 * trying to add (or lookup) entries while we are removing it.
1769 	 */
1770 	rw_enter(&zp->z_name_lock, RW_WRITER);
1771 
1772 	/*
1773 	 * Grab a lock on the parent pointer to make sure we play well
1774 	 * with the treewalk and directory rename code.
1775 	 */
1776 	rw_enter(&zp->z_parent_lock, RW_WRITER);
1777 
1778 	tx = dmu_tx_create(zfsvfs->z_os);
1779 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1780 	dmu_tx_hold_bonus(tx, zp->z_id);
1781 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1782 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1783 	if (error) {
1784 		rw_exit(&zp->z_parent_lock);
1785 		rw_exit(&zp->z_name_lock);
1786 		zfs_dirent_unlock(dl);
1787 		VN_RELE(vp);
1788 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1789 			dmu_tx_wait(tx);
1790 			dmu_tx_abort(tx);
1791 			goto top;
1792 		}
1793 		dmu_tx_abort(tx);
1794 		ZFS_EXIT(zfsvfs);
1795 		return (error);
1796 	}
1797 
1798 	error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
1799 
1800 	if (error == 0) {
1801 		uint64_t txtype = TX_RMDIR;
1802 		if (flags & FIGNORECASE)
1803 			txtype |= TX_CI;
1804 		zfs_log_remove(zilog, tx, txtype, dzp, name);
1805 	}
1806 
1807 	dmu_tx_commit(tx);
1808 
1809 	rw_exit(&zp->z_parent_lock);
1810 	rw_exit(&zp->z_name_lock);
1811 out:
1812 	zfs_dirent_unlock(dl);
1813 
1814 	VN_RELE(vp);
1815 
1816 	ZFS_EXIT(zfsvfs);
1817 	return (error);
1818 }
1819 
1820 /*
1821  * Read as many directory entries as will fit into the provided
1822  * buffer from the given directory cursor position (specified in
1823  * the uio structure.
1824  *
1825  *	IN:	vp	- vnode of directory to read.
1826  *		uio	- structure supplying read location, range info,
1827  *			  and return buffer.
1828  *		cr	- credentials of caller.
1829  *		ct	- caller context
1830  *		flags	- case flags
1831  *
1832  *	OUT:	uio	- updated offset and range, buffer filled.
1833  *		eofp	- set to true if end-of-file detected.
1834  *
1835  *	RETURN:	0 if success
1836  *		error code if failure
1837  *
1838  * Timestamps:
1839  *	vp - atime updated
1840  *
1841  * Note that the low 4 bits of the cookie returned by zap is always zero.
1842  * This allows us to use the low range for "special" directory entries:
1843  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1844  * we use the offset 2 for the '.zfs' directory.
1845  */
1846 /* ARGSUSED */
1847 static int
1848 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp,
1849     caller_context_t *ct, int flags)
1850 {
1851 	znode_t		*zp = VTOZ(vp);
1852 	iovec_t		*iovp;
1853 	edirent_t	*eodp;
1854 	dirent64_t	*odp;
1855 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1856 	objset_t	*os;
1857 	caddr_t		outbuf;
1858 	size_t		bufsize;
1859 	zap_cursor_t	zc;
1860 	zap_attribute_t	zap;
1861 	uint_t		bytes_wanted;
1862 	uint64_t	offset; /* must be unsigned; checks for < 1 */
1863 	int		local_eof;
1864 	int		outcount;
1865 	int		error;
1866 	uint8_t		prefetch;
1867 
1868 	ZFS_ENTER(zfsvfs);
1869 	ZFS_VERIFY_ZP(zp);
1870 
1871 	/*
1872 	 * If we are not given an eof variable,
1873 	 * use a local one.
1874 	 */
1875 	if (eofp == NULL)
1876 		eofp = &local_eof;
1877 
1878 	/*
1879 	 * Check for valid iov_len.
1880 	 */
1881 	if (uio->uio_iov->iov_len <= 0) {
1882 		ZFS_EXIT(zfsvfs);
1883 		return (EINVAL);
1884 	}
1885 
1886 	/*
1887 	 * Quit if directory has been removed (posix)
1888 	 */
1889 	if ((*eofp = zp->z_unlinked) != 0) {
1890 		ZFS_EXIT(zfsvfs);
1891 		return (0);
1892 	}
1893 
1894 	error = 0;
1895 	os = zfsvfs->z_os;
1896 	offset = uio->uio_loffset;
1897 	prefetch = zp->z_zn_prefetch;
1898 
1899 	/*
1900 	 * Initialize the iterator cursor.
1901 	 */
1902 	if (offset <= 3) {
1903 		/*
1904 		 * Start iteration from the beginning of the directory.
1905 		 */
1906 		zap_cursor_init(&zc, os, zp->z_id);
1907 	} else {
1908 		/*
1909 		 * The offset is a serialized cursor.
1910 		 */
1911 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1912 	}
1913 
1914 	/*
1915 	 * Get space to change directory entries into fs independent format.
1916 	 */
1917 	iovp = uio->uio_iov;
1918 	bytes_wanted = iovp->iov_len;
1919 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
1920 		bufsize = bytes_wanted;
1921 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
1922 		odp = (struct dirent64 *)outbuf;
1923 	} else {
1924 		bufsize = bytes_wanted;
1925 		odp = (struct dirent64 *)iovp->iov_base;
1926 	}
1927 	eodp = (struct edirent *)odp;
1928 
1929 	/*
1930 	 * Transform to file-system independent format
1931 	 */
1932 	outcount = 0;
1933 	while (outcount < bytes_wanted) {
1934 		ino64_t objnum;
1935 		ushort_t reclen;
1936 		off64_t *next;
1937 
1938 		/*
1939 		 * Special case `.', `..', and `.zfs'.
1940 		 */
1941 		if (offset == 0) {
1942 			(void) strcpy(zap.za_name, ".");
1943 			zap.za_normalization_conflict = 0;
1944 			objnum = zp->z_id;
1945 		} else if (offset == 1) {
1946 			(void) strcpy(zap.za_name, "..");
1947 			zap.za_normalization_conflict = 0;
1948 			objnum = zp->z_phys->zp_parent;
1949 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
1950 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
1951 			zap.za_normalization_conflict = 0;
1952 			objnum = ZFSCTL_INO_ROOT;
1953 		} else {
1954 			/*
1955 			 * Grab next entry.
1956 			 */
1957 			if (error = zap_cursor_retrieve(&zc, &zap)) {
1958 				if ((*eofp = (error == ENOENT)) != 0)
1959 					break;
1960 				else
1961 					goto update;
1962 			}
1963 
1964 			if (zap.za_integer_length != 8 ||
1965 			    zap.za_num_integers != 1) {
1966 				cmn_err(CE_WARN, "zap_readdir: bad directory "
1967 				    "entry, obj = %lld, offset = %lld\n",
1968 				    (u_longlong_t)zp->z_id,
1969 				    (u_longlong_t)offset);
1970 				error = ENXIO;
1971 				goto update;
1972 			}
1973 
1974 			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
1975 			/*
1976 			 * MacOS X can extract the object type here such as:
1977 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1978 			 */
1979 		}
1980 
1981 		if (flags & V_RDDIR_ENTFLAGS)
1982 			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
1983 		else
1984 			reclen = DIRENT64_RECLEN(strlen(zap.za_name));
1985 
1986 		/*
1987 		 * Will this entry fit in the buffer?
1988 		 */
1989 		if (outcount + reclen > bufsize) {
1990 			/*
1991 			 * Did we manage to fit anything in the buffer?
1992 			 */
1993 			if (!outcount) {
1994 				error = EINVAL;
1995 				goto update;
1996 			}
1997 			break;
1998 		}
1999 		if (flags & V_RDDIR_ENTFLAGS) {
2000 			/*
2001 			 * Add extended flag entry:
2002 			 */
2003 			eodp->ed_ino = objnum;
2004 			eodp->ed_reclen = reclen;
2005 			/* NOTE: ed_off is the offset for the *next* entry */
2006 			next = &(eodp->ed_off);
2007 			eodp->ed_eflags = zap.za_normalization_conflict ?
2008 			    ED_CASE_CONFLICT : 0;
2009 			(void) strncpy(eodp->ed_name, zap.za_name,
2010 			    EDIRENT_NAMELEN(reclen));
2011 			eodp = (edirent_t *)((intptr_t)eodp + reclen);
2012 		} else {
2013 			/*
2014 			 * Add normal entry:
2015 			 */
2016 			odp->d_ino = objnum;
2017 			odp->d_reclen = reclen;
2018 			/* NOTE: d_off is the offset for the *next* entry */
2019 			next = &(odp->d_off);
2020 			(void) strncpy(odp->d_name, zap.za_name,
2021 			    DIRENT64_NAMELEN(reclen));
2022 			odp = (dirent64_t *)((intptr_t)odp + reclen);
2023 		}
2024 		outcount += reclen;
2025 
2026 		ASSERT(outcount <= bufsize);
2027 
2028 		/* Prefetch znode */
2029 		if (prefetch)
2030 			dmu_prefetch(os, objnum, 0, 0);
2031 
2032 		/*
2033 		 * Move to the next entry, fill in the previous offset.
2034 		 */
2035 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2036 			zap_cursor_advance(&zc);
2037 			offset = zap_cursor_serialize(&zc);
2038 		} else {
2039 			offset += 1;
2040 		}
2041 		*next = offset;
2042 	}
2043 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2044 
2045 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2046 		iovp->iov_base += outcount;
2047 		iovp->iov_len -= outcount;
2048 		uio->uio_resid -= outcount;
2049 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2050 		/*
2051 		 * Reset the pointer.
2052 		 */
2053 		offset = uio->uio_loffset;
2054 	}
2055 
2056 update:
2057 	zap_cursor_fini(&zc);
2058 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2059 		kmem_free(outbuf, bufsize);
2060 
2061 	if (error == ENOENT)
2062 		error = 0;
2063 
2064 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2065 
2066 	uio->uio_loffset = offset;
2067 	ZFS_EXIT(zfsvfs);
2068 	return (error);
2069 }
2070 
2071 ulong_t zfs_fsync_sync_cnt = 4;
2072 
2073 static int
2074 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2075 {
2076 	znode_t	*zp = VTOZ(vp);
2077 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2078 
2079 	/*
2080 	 * Regardless of whether this is required for standards conformance,
2081 	 * this is the logical behavior when fsync() is called on a file with
2082 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
2083 	 * going to be pushed out as part of the zil_commit().
2084 	 */
2085 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2086 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
2087 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr, ct);
2088 
2089 	(void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2090 
2091 	ZFS_ENTER(zfsvfs);
2092 	ZFS_VERIFY_ZP(zp);
2093 	zil_commit(zfsvfs->z_log, zp->z_last_itx, zp->z_id);
2094 	ZFS_EXIT(zfsvfs);
2095 	return (0);
2096 }
2097 
2098 
2099 /*
2100  * Get the requested file attributes and place them in the provided
2101  * vattr structure.
2102  *
2103  *	IN:	vp	- vnode of file.
2104  *		vap	- va_mask identifies requested attributes.
2105  *			  If AT_XVATTR set, then optional attrs are requested
2106  *		flags	- ATTR_NOACLCHECK (CIFS server context)
2107  *		cr	- credentials of caller.
2108  *		ct	- caller context
2109  *
2110  *	OUT:	vap	- attribute values.
2111  *
2112  *	RETURN:	0 (always succeeds)
2113  */
2114 /* ARGSUSED */
2115 static int
2116 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2117     caller_context_t *ct)
2118 {
2119 	znode_t *zp = VTOZ(vp);
2120 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2121 	znode_phys_t *pzp;
2122 	int	error = 0;
2123 	uint64_t links;
2124 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2125 	xoptattr_t *xoap = NULL;
2126 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2127 
2128 	ZFS_ENTER(zfsvfs);
2129 	ZFS_VERIFY_ZP(zp);
2130 	pzp = zp->z_phys;
2131 
2132 	mutex_enter(&zp->z_lock);
2133 
2134 	/*
2135 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2136 	 * Also, if we are the owner don't bother, since owner should
2137 	 * always be allowed to read basic attributes of file.
2138 	 */
2139 	if (!(pzp->zp_flags & ZFS_ACL_TRIVIAL) &&
2140 	    (pzp->zp_uid != crgetuid(cr))) {
2141 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2142 		    skipaclchk, cr)) {
2143 			mutex_exit(&zp->z_lock);
2144 			ZFS_EXIT(zfsvfs);
2145 			return (error);
2146 		}
2147 	}
2148 
2149 	/*
2150 	 * Return all attributes.  It's cheaper to provide the answer
2151 	 * than to determine whether we were asked the question.
2152 	 */
2153 
2154 	vap->va_type = vp->v_type;
2155 	vap->va_mode = pzp->zp_mode & MODEMASK;
2156 	zfs_fuid_map_ids(zp, &vap->va_uid, &vap->va_gid);
2157 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2158 	vap->va_nodeid = zp->z_id;
2159 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2160 		links = pzp->zp_links + 1;
2161 	else
2162 		links = pzp->zp_links;
2163 	vap->va_nlink = MIN(links, UINT32_MAX);	/* nlink_t limit! */
2164 	vap->va_size = pzp->zp_size;
2165 	vap->va_rdev = vp->v_rdev;
2166 	vap->va_seq = zp->z_seq;
2167 
2168 	/*
2169 	 * Add in any requested optional attributes and the create time.
2170 	 * Also set the corresponding bits in the returned attribute bitmap.
2171 	 */
2172 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2173 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2174 			xoap->xoa_archive =
2175 			    ((pzp->zp_flags & ZFS_ARCHIVE) != 0);
2176 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2177 		}
2178 
2179 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2180 			xoap->xoa_readonly =
2181 			    ((pzp->zp_flags & ZFS_READONLY) != 0);
2182 			XVA_SET_RTN(xvap, XAT_READONLY);
2183 		}
2184 
2185 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2186 			xoap->xoa_system =
2187 			    ((pzp->zp_flags & ZFS_SYSTEM) != 0);
2188 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2189 		}
2190 
2191 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2192 			xoap->xoa_hidden =
2193 			    ((pzp->zp_flags & ZFS_HIDDEN) != 0);
2194 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2195 		}
2196 
2197 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2198 			xoap->xoa_nounlink =
2199 			    ((pzp->zp_flags & ZFS_NOUNLINK) != 0);
2200 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2201 		}
2202 
2203 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2204 			xoap->xoa_immutable =
2205 			    ((pzp->zp_flags & ZFS_IMMUTABLE) != 0);
2206 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2207 		}
2208 
2209 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2210 			xoap->xoa_appendonly =
2211 			    ((pzp->zp_flags & ZFS_APPENDONLY) != 0);
2212 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2213 		}
2214 
2215 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2216 			xoap->xoa_nodump =
2217 			    ((pzp->zp_flags & ZFS_NODUMP) != 0);
2218 			XVA_SET_RTN(xvap, XAT_NODUMP);
2219 		}
2220 
2221 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2222 			xoap->xoa_opaque =
2223 			    ((pzp->zp_flags & ZFS_OPAQUE) != 0);
2224 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2225 		}
2226 
2227 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2228 			xoap->xoa_av_quarantined =
2229 			    ((pzp->zp_flags & ZFS_AV_QUARANTINED) != 0);
2230 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2231 		}
2232 
2233 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2234 			xoap->xoa_av_modified =
2235 			    ((pzp->zp_flags & ZFS_AV_MODIFIED) != 0);
2236 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2237 		}
2238 
2239 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2240 		    vp->v_type == VREG &&
2241 		    (pzp->zp_flags & ZFS_BONUS_SCANSTAMP)) {
2242 			size_t len;
2243 			dmu_object_info_t doi;
2244 
2245 			/*
2246 			 * Only VREG files have anti-virus scanstamps, so we
2247 			 * won't conflict with symlinks in the bonus buffer.
2248 			 */
2249 			dmu_object_info_from_db(zp->z_dbuf, &doi);
2250 			len = sizeof (xoap->xoa_av_scanstamp) +
2251 			    sizeof (znode_phys_t);
2252 			if (len <= doi.doi_bonus_size) {
2253 				/*
2254 				 * pzp points to the start of the
2255 				 * znode_phys_t. pzp + 1 points to the
2256 				 * first byte after the znode_phys_t.
2257 				 */
2258 				(void) memcpy(xoap->xoa_av_scanstamp,
2259 				    pzp + 1,
2260 				    sizeof (xoap->xoa_av_scanstamp));
2261 				XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
2262 			}
2263 		}
2264 
2265 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2266 			ZFS_TIME_DECODE(&xoap->xoa_createtime, pzp->zp_crtime);
2267 			XVA_SET_RTN(xvap, XAT_CREATETIME);
2268 		}
2269 	}
2270 
2271 	ZFS_TIME_DECODE(&vap->va_atime, pzp->zp_atime);
2272 	ZFS_TIME_DECODE(&vap->va_mtime, pzp->zp_mtime);
2273 	ZFS_TIME_DECODE(&vap->va_ctime, pzp->zp_ctime);
2274 
2275 	mutex_exit(&zp->z_lock);
2276 
2277 	dmu_object_size_from_db(zp->z_dbuf, &vap->va_blksize, &vap->va_nblocks);
2278 
2279 	if (zp->z_blksz == 0) {
2280 		/*
2281 		 * Block size hasn't been set; suggest maximal I/O transfers.
2282 		 */
2283 		vap->va_blksize = zfsvfs->z_max_blksz;
2284 	}
2285 
2286 	ZFS_EXIT(zfsvfs);
2287 	return (0);
2288 }
2289 
2290 /*
2291  * Set the file attributes to the values contained in the
2292  * vattr structure.
2293  *
2294  *	IN:	vp	- vnode of file to be modified.
2295  *		vap	- new attribute values.
2296  *			  If AT_XVATTR set, then optional attrs are being set
2297  *		flags	- ATTR_UTIME set if non-default time values provided.
2298  *			- ATTR_NOACLCHECK (CIFS context only).
2299  *		cr	- credentials of caller.
2300  *		ct	- caller context
2301  *
2302  *	RETURN:	0 if success
2303  *		error code if failure
2304  *
2305  * Timestamps:
2306  *	vp - ctime updated, mtime updated if size changed.
2307  */
2308 /* ARGSUSED */
2309 static int
2310 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2311 	caller_context_t *ct)
2312 {
2313 	znode_t		*zp = VTOZ(vp);
2314 	znode_phys_t	*pzp;
2315 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2316 	zilog_t		*zilog;
2317 	dmu_tx_t	*tx;
2318 	vattr_t		oldva;
2319 	uint_t		mask = vap->va_mask;
2320 	uint_t		saved_mask;
2321 	int		trim_mask = 0;
2322 	uint64_t	new_mode;
2323 	znode_t		*attrzp;
2324 	int		need_policy = FALSE;
2325 	int		err;
2326 	zfs_fuid_info_t *fuidp = NULL;
2327 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2328 	xoptattr_t	*xoap;
2329 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2330 
2331 	if (mask == 0)
2332 		return (0);
2333 
2334 	if (mask & AT_NOSET)
2335 		return (EINVAL);
2336 
2337 	ZFS_ENTER(zfsvfs);
2338 	ZFS_VERIFY_ZP(zp);
2339 
2340 	pzp = zp->z_phys;
2341 	zilog = zfsvfs->z_log;
2342 
2343 	/*
2344 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
2345 	 * that file system is at proper version level
2346 	 */
2347 
2348 	if (zfsvfs->z_use_fuids == B_FALSE &&
2349 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2350 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2351 	    (mask & AT_XVATTR))) {
2352 		ZFS_EXIT(zfsvfs);
2353 		return (EINVAL);
2354 	}
2355 
2356 	if (mask & AT_SIZE && vp->v_type == VDIR) {
2357 		ZFS_EXIT(zfsvfs);
2358 		return (EISDIR);
2359 	}
2360 
2361 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2362 		ZFS_EXIT(zfsvfs);
2363 		return (EINVAL);
2364 	}
2365 
2366 	/*
2367 	 * If this is an xvattr_t, then get a pointer to the structure of
2368 	 * optional attributes.  If this is NULL, then we have a vattr_t.
2369 	 */
2370 	xoap = xva_getxoptattr(xvap);
2371 
2372 	/*
2373 	 * Immutable files can only alter immutable bit and atime
2374 	 */
2375 	if ((pzp->zp_flags & ZFS_IMMUTABLE) &&
2376 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2377 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2378 		ZFS_EXIT(zfsvfs);
2379 		return (EPERM);
2380 	}
2381 
2382 	if ((mask & AT_SIZE) && (pzp->zp_flags & ZFS_READONLY)) {
2383 		ZFS_EXIT(zfsvfs);
2384 		return (EPERM);
2385 	}
2386 
2387 top:
2388 	attrzp = NULL;
2389 
2390 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2391 		ZFS_EXIT(zfsvfs);
2392 		return (EROFS);
2393 	}
2394 
2395 	/*
2396 	 * First validate permissions
2397 	 */
2398 
2399 	if (mask & AT_SIZE) {
2400 		err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
2401 		if (err) {
2402 			ZFS_EXIT(zfsvfs);
2403 			return (err);
2404 		}
2405 		/*
2406 		 * XXX - Note, we are not providing any open
2407 		 * mode flags here (like FNDELAY), so we may
2408 		 * block if there are locks present... this
2409 		 * should be addressed in openat().
2410 		 */
2411 		do {
2412 			err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2413 			/* NB: we already did dmu_tx_wait() if necessary */
2414 		} while (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT);
2415 		if (err) {
2416 			ZFS_EXIT(zfsvfs);
2417 			return (err);
2418 		}
2419 	}
2420 
2421 	if (mask & (AT_ATIME|AT_MTIME) ||
2422 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2423 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2424 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2425 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2426 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM))))
2427 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2428 		    skipaclchk, cr);
2429 
2430 	if (mask & (AT_UID|AT_GID)) {
2431 		int	idmask = (mask & (AT_UID|AT_GID));
2432 		int	take_owner;
2433 		int	take_group;
2434 
2435 		/*
2436 		 * NOTE: even if a new mode is being set,
2437 		 * we may clear S_ISUID/S_ISGID bits.
2438 		 */
2439 
2440 		if (!(mask & AT_MODE))
2441 			vap->va_mode = pzp->zp_mode;
2442 
2443 		/*
2444 		 * Take ownership or chgrp to group we are a member of
2445 		 */
2446 
2447 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2448 		take_group = (mask & AT_GID) &&
2449 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
2450 
2451 		/*
2452 		 * If both AT_UID and AT_GID are set then take_owner and
2453 		 * take_group must both be set in order to allow taking
2454 		 * ownership.
2455 		 *
2456 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2457 		 *
2458 		 */
2459 
2460 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2461 		    ((idmask == AT_UID) && take_owner) ||
2462 		    ((idmask == AT_GID) && take_group)) {
2463 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2464 			    skipaclchk, cr) == 0) {
2465 				/*
2466 				 * Remove setuid/setgid for non-privileged users
2467 				 */
2468 				secpolicy_setid_clear(vap, cr);
2469 				trim_mask = (mask & (AT_UID|AT_GID));
2470 			} else {
2471 				need_policy =  TRUE;
2472 			}
2473 		} else {
2474 			need_policy =  TRUE;
2475 		}
2476 	}
2477 
2478 	mutex_enter(&zp->z_lock);
2479 	oldva.va_mode = pzp->zp_mode;
2480 	zfs_fuid_map_ids(zp, &oldva.va_uid, &oldva.va_gid);
2481 	if (mask & AT_XVATTR) {
2482 		if ((need_policy == FALSE) &&
2483 		    (XVA_ISSET_REQ(xvap, XAT_APPENDONLY) &&
2484 		    xoap->xoa_appendonly !=
2485 		    ((pzp->zp_flags & ZFS_APPENDONLY) != 0)) ||
2486 		    (XVA_ISSET_REQ(xvap, XAT_NOUNLINK) &&
2487 		    xoap->xoa_nounlink !=
2488 		    ((pzp->zp_flags & ZFS_NOUNLINK) != 0)) ||
2489 		    (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE) &&
2490 		    xoap->xoa_immutable !=
2491 		    ((pzp->zp_flags & ZFS_IMMUTABLE) != 0)) ||
2492 		    (XVA_ISSET_REQ(xvap, XAT_NODUMP) &&
2493 		    xoap->xoa_nodump !=
2494 		    ((pzp->zp_flags & ZFS_NODUMP) != 0)) ||
2495 		    (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED) &&
2496 		    xoap->xoa_av_modified !=
2497 		    ((pzp->zp_flags & ZFS_AV_MODIFIED) != 0)) ||
2498 		    (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED) &&
2499 		    xoap->xoa_av_quarantined !=
2500 		    ((pzp->zp_flags & ZFS_AV_QUARANTINED) != 0)) ||
2501 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) ||
2502 		    (XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2503 			need_policy = TRUE;
2504 		}
2505 	}
2506 
2507 	mutex_exit(&zp->z_lock);
2508 
2509 	if (mask & AT_MODE) {
2510 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
2511 			err = secpolicy_setid_setsticky_clear(vp, vap,
2512 			    &oldva, cr);
2513 			if (err) {
2514 				ZFS_EXIT(zfsvfs);
2515 				return (err);
2516 			}
2517 			trim_mask |= AT_MODE;
2518 		} else {
2519 			need_policy = TRUE;
2520 		}
2521 	}
2522 
2523 	if (need_policy) {
2524 		/*
2525 		 * If trim_mask is set then take ownership
2526 		 * has been granted or write_acl is present and user
2527 		 * has the ability to modify mode.  In that case remove
2528 		 * UID|GID and or MODE from mask so that
2529 		 * secpolicy_vnode_setattr() doesn't revoke it.
2530 		 */
2531 
2532 		if (trim_mask) {
2533 			saved_mask = vap->va_mask;
2534 			vap->va_mask &= ~trim_mask;
2535 		}
2536 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2537 		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
2538 		if (err) {
2539 			ZFS_EXIT(zfsvfs);
2540 			return (err);
2541 		}
2542 
2543 		if (trim_mask)
2544 			vap->va_mask |= saved_mask;
2545 	}
2546 
2547 	/*
2548 	 * secpolicy_vnode_setattr, or take ownership may have
2549 	 * changed va_mask
2550 	 */
2551 	mask = vap->va_mask;
2552 
2553 	tx = dmu_tx_create(zfsvfs->z_os);
2554 	dmu_tx_hold_bonus(tx, zp->z_id);
2555 	if (zfsvfs->z_fuid_obj == 0) {
2556 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
2557 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
2558 		    SPA_MAXBLOCKSIZE);
2559 		dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, FALSE, NULL);
2560 	} else {
2561 		dmu_tx_hold_bonus(tx, zfsvfs->z_fuid_obj);
2562 		dmu_tx_hold_write(tx, zfsvfs->z_fuid_obj, 0,
2563 		    SPA_MAXBLOCKSIZE);
2564 	}
2565 
2566 	if (mask & AT_MODE) {
2567 		uint64_t pmode = pzp->zp_mode;
2568 
2569 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2570 
2571 		if (pzp->zp_acl.z_acl_extern_obj) {
2572 			/* Are we upgrading ACL from old V0 format to new V1 */
2573 			if (zfsvfs->z_version <= ZPL_VERSION_FUID &&
2574 			    pzp->zp_acl.z_acl_version ==
2575 			    ZFS_ACL_VERSION_INITIAL) {
2576 				dmu_tx_hold_free(tx,
2577 				    pzp->zp_acl.z_acl_extern_obj, 0,
2578 				    DMU_OBJECT_END);
2579 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2580 				    0, sizeof (zfs_object_ace_t) * 2048 + 6);
2581 			} else {
2582 				dmu_tx_hold_write(tx,
2583 				    pzp->zp_acl.z_acl_extern_obj, 0,
2584 				    SPA_MAXBLOCKSIZE);
2585 			}
2586 		} else {
2587 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2588 			    0, sizeof (zfs_object_ace_t) * 2048 + 6);
2589 		}
2590 	}
2591 
2592 	if ((mask & (AT_UID | AT_GID)) && pzp->zp_xattr != 0) {
2593 		err = zfs_zget(zp->z_zfsvfs, pzp->zp_xattr, &attrzp);
2594 		if (err) {
2595 			dmu_tx_abort(tx);
2596 			ZFS_EXIT(zfsvfs);
2597 			return (err);
2598 		}
2599 		dmu_tx_hold_bonus(tx, attrzp->z_id);
2600 	}
2601 
2602 	err = dmu_tx_assign(tx, zfsvfs->z_assign);
2603 	if (err) {
2604 		if (attrzp)
2605 			VN_RELE(ZTOV(attrzp));
2606 		if (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2607 			dmu_tx_wait(tx);
2608 			dmu_tx_abort(tx);
2609 			goto top;
2610 		}
2611 		dmu_tx_abort(tx);
2612 		ZFS_EXIT(zfsvfs);
2613 		return (err);
2614 	}
2615 
2616 	dmu_buf_will_dirty(zp->z_dbuf, tx);
2617 
2618 	/*
2619 	 * Set each attribute requested.
2620 	 * We group settings according to the locks they need to acquire.
2621 	 *
2622 	 * Note: you cannot set ctime directly, although it will be
2623 	 * updated as a side-effect of calling this function.
2624 	 */
2625 
2626 	mutex_enter(&zp->z_lock);
2627 
2628 	if (mask & AT_MODE) {
2629 		err = zfs_acl_chmod_setattr(zp, new_mode, tx);
2630 		ASSERT3U(err, ==, 0);
2631 	}
2632 
2633 	if (attrzp)
2634 		mutex_enter(&attrzp->z_lock);
2635 
2636 	if (mask & AT_UID) {
2637 		pzp->zp_uid = zfs_fuid_create(zfsvfs,
2638 		    vap->va_uid, ZFS_OWNER, tx, &fuidp);
2639 		if (attrzp) {
2640 			attrzp->z_phys->zp_uid = zfs_fuid_create(zfsvfs,
2641 			    vap->va_uid,  ZFS_OWNER, tx, &fuidp);
2642 		}
2643 	}
2644 
2645 	if (mask & AT_GID) {
2646 		pzp->zp_gid = zfs_fuid_create(zfsvfs, vap->va_gid,
2647 		    ZFS_GROUP, tx, &fuidp);
2648 		if (attrzp)
2649 			attrzp->z_phys->zp_gid = zfs_fuid_create(zfsvfs,
2650 			    vap->va_gid, ZFS_GROUP, tx, &fuidp);
2651 	}
2652 
2653 	if (attrzp)
2654 		mutex_exit(&attrzp->z_lock);
2655 
2656 	if (mask & AT_ATIME)
2657 		ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
2658 
2659 	if (mask & AT_MTIME)
2660 		ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
2661 
2662 	if (mask & AT_SIZE)
2663 		zfs_time_stamper_locked(zp, CONTENT_MODIFIED, tx);
2664 	else if (mask != 0)
2665 		zfs_time_stamper_locked(zp, STATE_CHANGED, tx);
2666 	/*
2667 	 * Do this after setting timestamps to prevent timestamp
2668 	 * update from toggling bit
2669 	 */
2670 
2671 	if (xoap && (mask & AT_XVATTR)) {
2672 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
2673 			size_t len;
2674 			dmu_object_info_t doi;
2675 
2676 			ASSERT(vp->v_type == VREG);
2677 
2678 			/* Grow the bonus buffer if necessary. */
2679 			dmu_object_info_from_db(zp->z_dbuf, &doi);
2680 			len = sizeof (xoap->xoa_av_scanstamp) +
2681 			    sizeof (znode_phys_t);
2682 			if (len > doi.doi_bonus_size)
2683 				VERIFY(dmu_set_bonus(zp->z_dbuf, len, tx) == 0);
2684 		}
2685 		zfs_xvattr_set(zp, xvap);
2686 	}
2687 
2688 	if (mask != 0)
2689 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
2690 
2691 	if (fuidp)
2692 		zfs_fuid_info_free(fuidp);
2693 	mutex_exit(&zp->z_lock);
2694 
2695 	if (attrzp)
2696 		VN_RELE(ZTOV(attrzp));
2697 
2698 	dmu_tx_commit(tx);
2699 
2700 	ZFS_EXIT(zfsvfs);
2701 	return (err);
2702 }
2703 
2704 typedef struct zfs_zlock {
2705 	krwlock_t	*zl_rwlock;	/* lock we acquired */
2706 	znode_t		*zl_znode;	/* znode we held */
2707 	struct zfs_zlock *zl_next;	/* next in list */
2708 } zfs_zlock_t;
2709 
2710 /*
2711  * Drop locks and release vnodes that were held by zfs_rename_lock().
2712  */
2713 static void
2714 zfs_rename_unlock(zfs_zlock_t **zlpp)
2715 {
2716 	zfs_zlock_t *zl;
2717 
2718 	while ((zl = *zlpp) != NULL) {
2719 		if (zl->zl_znode != NULL)
2720 			VN_RELE(ZTOV(zl->zl_znode));
2721 		rw_exit(zl->zl_rwlock);
2722 		*zlpp = zl->zl_next;
2723 		kmem_free(zl, sizeof (*zl));
2724 	}
2725 }
2726 
2727 /*
2728  * Search back through the directory tree, using the ".." entries.
2729  * Lock each directory in the chain to prevent concurrent renames.
2730  * Fail any attempt to move a directory into one of its own descendants.
2731  * XXX - z_parent_lock can overlap with map or grow locks
2732  */
2733 static int
2734 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
2735 {
2736 	zfs_zlock_t	*zl;
2737 	znode_t		*zp = tdzp;
2738 	uint64_t	rootid = zp->z_zfsvfs->z_root;
2739 	uint64_t	*oidp = &zp->z_id;
2740 	krwlock_t	*rwlp = &szp->z_parent_lock;
2741 	krw_t		rw = RW_WRITER;
2742 
2743 	/*
2744 	 * First pass write-locks szp and compares to zp->z_id.
2745 	 * Later passes read-lock zp and compare to zp->z_parent.
2746 	 */
2747 	do {
2748 		if (!rw_tryenter(rwlp, rw)) {
2749 			/*
2750 			 * Another thread is renaming in this path.
2751 			 * Note that if we are a WRITER, we don't have any
2752 			 * parent_locks held yet.
2753 			 */
2754 			if (rw == RW_READER && zp->z_id > szp->z_id) {
2755 				/*
2756 				 * Drop our locks and restart
2757 				 */
2758 				zfs_rename_unlock(&zl);
2759 				*zlpp = NULL;
2760 				zp = tdzp;
2761 				oidp = &zp->z_id;
2762 				rwlp = &szp->z_parent_lock;
2763 				rw = RW_WRITER;
2764 				continue;
2765 			} else {
2766 				/*
2767 				 * Wait for other thread to drop its locks
2768 				 */
2769 				rw_enter(rwlp, rw);
2770 			}
2771 		}
2772 
2773 		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
2774 		zl->zl_rwlock = rwlp;
2775 		zl->zl_znode = NULL;
2776 		zl->zl_next = *zlpp;
2777 		*zlpp = zl;
2778 
2779 		if (*oidp == szp->z_id)		/* We're a descendant of szp */
2780 			return (EINVAL);
2781 
2782 		if (*oidp == rootid)		/* We've hit the top */
2783 			return (0);
2784 
2785 		if (rw == RW_READER) {		/* i.e. not the first pass */
2786 			int error = zfs_zget(zp->z_zfsvfs, *oidp, &zp);
2787 			if (error)
2788 				return (error);
2789 			zl->zl_znode = zp;
2790 		}
2791 		oidp = &zp->z_phys->zp_parent;
2792 		rwlp = &zp->z_parent_lock;
2793 		rw = RW_READER;
2794 
2795 	} while (zp->z_id != sdzp->z_id);
2796 
2797 	return (0);
2798 }
2799 
2800 /*
2801  * Move an entry from the provided source directory to the target
2802  * directory.  Change the entry name as indicated.
2803  *
2804  *	IN:	sdvp	- Source directory containing the "old entry".
2805  *		snm	- Old entry name.
2806  *		tdvp	- Target directory to contain the "new entry".
2807  *		tnm	- New entry name.
2808  *		cr	- credentials of caller.
2809  *		ct	- caller context
2810  *		flags	- case flags
2811  *
2812  *	RETURN:	0 if success
2813  *		error code if failure
2814  *
2815  * Timestamps:
2816  *	sdvp,tdvp - ctime|mtime updated
2817  */
2818 /*ARGSUSED*/
2819 static int
2820 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
2821     caller_context_t *ct, int flags)
2822 {
2823 	znode_t		*tdzp, *szp, *tzp;
2824 	znode_t		*sdzp = VTOZ(sdvp);
2825 	zfsvfs_t	*zfsvfs = sdzp->z_zfsvfs;
2826 	zilog_t		*zilog;
2827 	vnode_t		*realvp;
2828 	zfs_dirlock_t	*sdl, *tdl;
2829 	dmu_tx_t	*tx;
2830 	zfs_zlock_t	*zl;
2831 	int		cmp, serr, terr;
2832 	int		error = 0;
2833 	int		zflg = 0;
2834 
2835 	ZFS_ENTER(zfsvfs);
2836 	ZFS_VERIFY_ZP(sdzp);
2837 	zilog = zfsvfs->z_log;
2838 
2839 	/*
2840 	 * Make sure we have the real vp for the target directory.
2841 	 */
2842 	if (VOP_REALVP(tdvp, &realvp, ct) == 0)
2843 		tdvp = realvp;
2844 
2845 	if (tdvp->v_vfsp != sdvp->v_vfsp) {
2846 		ZFS_EXIT(zfsvfs);
2847 		return (EXDEV);
2848 	}
2849 
2850 	tdzp = VTOZ(tdvp);
2851 	ZFS_VERIFY_ZP(tdzp);
2852 	if (zfsvfs->z_case & ZFS_UTF8_ONLY && u8_validate(tnm,
2853 	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
2854 		ZFS_EXIT(zfsvfs);
2855 		return (EILSEQ);
2856 	}
2857 
2858 	if (flags & FIGNORECASE)
2859 		zflg |= ZCILOOK;
2860 
2861 top:
2862 	szp = NULL;
2863 	tzp = NULL;
2864 	zl = NULL;
2865 
2866 	/*
2867 	 * This is to prevent the creation of links into attribute space
2868 	 * by renaming a linked file into/outof an attribute directory.
2869 	 * See the comment in zfs_link() for why this is considered bad.
2870 	 */
2871 	if ((tdzp->z_phys->zp_flags & ZFS_XATTR) !=
2872 	    (sdzp->z_phys->zp_flags & ZFS_XATTR)) {
2873 		ZFS_EXIT(zfsvfs);
2874 		return (EINVAL);
2875 	}
2876 
2877 	/*
2878 	 * Lock source and target directory entries.  To prevent deadlock,
2879 	 * a lock ordering must be defined.  We lock the directory with
2880 	 * the smallest object id first, or if it's a tie, the one with
2881 	 * the lexically first name.
2882 	 */
2883 	if (sdzp->z_id < tdzp->z_id) {
2884 		cmp = -1;
2885 	} else if (sdzp->z_id > tdzp->z_id) {
2886 		cmp = 1;
2887 	} else {
2888 		/*
2889 		 * First compare the two name arguments without
2890 		 * considering any case folding.
2891 		 */
2892 		int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
2893 
2894 		cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
2895 		ASSERT(error == 0 || !(zfsvfs->z_case & ZFS_UTF8_ONLY));
2896 		if (cmp == 0) {
2897 			/*
2898 			 * POSIX: "If the old argument and the new argument
2899 			 * both refer to links to the same existing file,
2900 			 * the rename() function shall return successfully
2901 			 * and perform no other action."
2902 			 */
2903 			ZFS_EXIT(zfsvfs);
2904 			return (0);
2905 		}
2906 		/*
2907 		 * If the file system is case-folding, then we may
2908 		 * have some more checking to do.  A case-folding file
2909 		 * system is either supporting mixed case sensitivity
2910 		 * access or is completely case-insensitive.  Note
2911 		 * that the file system is always case preserving.
2912 		 *
2913 		 * In mixed sensitivity mode case sensitive behavior
2914 		 * is the default.  FIGNORECASE must be used to
2915 		 * explicitly request case insensitive behavior.
2916 		 *
2917 		 * If the source and target names provided differ only
2918 		 * by case (e.g., a request to rename 'tim' to 'Tim'),
2919 		 * we will treat this as a special case in the
2920 		 * case-insensitive mode: as long as the source name
2921 		 * is an exact match, we will allow this to proceed as
2922 		 * a name-change request.
2923 		 */
2924 		if ((zfsvfs->z_case & ZFS_CI_ONLY ||
2925 		    (zfsvfs->z_case & ZFS_CI_MIXD && flags & FIGNORECASE)) &&
2926 		    u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
2927 		    &error) == 0) {
2928 			/*
2929 			 * case preserving rename request, require exact
2930 			 * name matches
2931 			 */
2932 			zflg |= ZCIEXACT;
2933 			zflg &= ~ZCILOOK;
2934 		}
2935 	}
2936 
2937 	if (cmp < 0) {
2938 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
2939 		    ZEXISTS | zflg, NULL, NULL);
2940 		terr = zfs_dirent_lock(&tdl,
2941 		    tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
2942 	} else {
2943 		terr = zfs_dirent_lock(&tdl,
2944 		    tdzp, tnm, &tzp, zflg, NULL, NULL);
2945 		serr = zfs_dirent_lock(&sdl,
2946 		    sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
2947 		    NULL, NULL);
2948 	}
2949 
2950 	if (serr) {
2951 		/*
2952 		 * Source entry invalid or not there.
2953 		 */
2954 		if (!terr) {
2955 			zfs_dirent_unlock(tdl);
2956 			if (tzp)
2957 				VN_RELE(ZTOV(tzp));
2958 		}
2959 		if (strcmp(snm, "..") == 0)
2960 			serr = EINVAL;
2961 		ZFS_EXIT(zfsvfs);
2962 		return (serr);
2963 	}
2964 	if (terr) {
2965 		zfs_dirent_unlock(sdl);
2966 		VN_RELE(ZTOV(szp));
2967 		if (strcmp(tnm, "..") == 0)
2968 			terr = EINVAL;
2969 		ZFS_EXIT(zfsvfs);
2970 		return (terr);
2971 	}
2972 
2973 	/*
2974 	 * Must have write access at the source to remove the old entry
2975 	 * and write access at the target to create the new entry.
2976 	 * Note that if target and source are the same, this can be
2977 	 * done in a single check.
2978 	 */
2979 
2980 	if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
2981 		goto out;
2982 
2983 	if (ZTOV(szp)->v_type == VDIR) {
2984 		/*
2985 		 * Check to make sure rename is valid.
2986 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
2987 		 */
2988 		if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
2989 			goto out;
2990 	}
2991 
2992 	/*
2993 	 * Does target exist?
2994 	 */
2995 	if (tzp) {
2996 		/*
2997 		 * Source and target must be the same type.
2998 		 */
2999 		if (ZTOV(szp)->v_type == VDIR) {
3000 			if (ZTOV(tzp)->v_type != VDIR) {
3001 				error = ENOTDIR;
3002 				goto out;
3003 			}
3004 		} else {
3005 			if (ZTOV(tzp)->v_type == VDIR) {
3006 				error = EISDIR;
3007 				goto out;
3008 			}
3009 		}
3010 		/*
3011 		 * POSIX dictates that when the source and target
3012 		 * entries refer to the same file object, rename
3013 		 * must do nothing and exit without error.
3014 		 */
3015 		if (szp->z_id == tzp->z_id) {
3016 			error = 0;
3017 			goto out;
3018 		}
3019 	}
3020 
3021 	vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
3022 	if (tzp)
3023 		vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3024 
3025 	/*
3026 	 * notify the target directory if it is not the same
3027 	 * as source directory.
3028 	 */
3029 	if (tdvp != sdvp) {
3030 		vnevent_rename_dest_dir(tdvp, ct);
3031 	}
3032 
3033 	tx = dmu_tx_create(zfsvfs->z_os);
3034 	dmu_tx_hold_bonus(tx, szp->z_id);	/* nlink changes */
3035 	dmu_tx_hold_bonus(tx, sdzp->z_id);	/* nlink changes */
3036 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3037 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3038 	if (sdzp != tdzp)
3039 		dmu_tx_hold_bonus(tx, tdzp->z_id);	/* nlink changes */
3040 	if (tzp)
3041 		dmu_tx_hold_bonus(tx, tzp->z_id);	/* parent changes */
3042 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3043 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
3044 	if (error) {
3045 		if (zl != NULL)
3046 			zfs_rename_unlock(&zl);
3047 		zfs_dirent_unlock(sdl);
3048 		zfs_dirent_unlock(tdl);
3049 		VN_RELE(ZTOV(szp));
3050 		if (tzp)
3051 			VN_RELE(ZTOV(tzp));
3052 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
3053 			dmu_tx_wait(tx);
3054 			dmu_tx_abort(tx);
3055 			goto top;
3056 		}
3057 		dmu_tx_abort(tx);
3058 		ZFS_EXIT(zfsvfs);
3059 		return (error);
3060 	}
3061 
3062 	if (tzp)	/* Attempt to remove the existing target */
3063 		error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3064 
3065 	if (error == 0) {
3066 		error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3067 		if (error == 0) {
3068 			szp->z_phys->zp_flags |= ZFS_AV_MODIFIED;
3069 
3070 			error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3071 			ASSERT(error == 0);
3072 
3073 			zfs_log_rename(zilog, tx,
3074 			    TX_RENAME | (flags & FIGNORECASE ? TX_CI : 0),
3075 			    sdzp, sdl->dl_name, tdzp, tdl->dl_name, szp);
3076 		}
3077 	}
3078 
3079 	dmu_tx_commit(tx);
3080 out:
3081 	if (zl != NULL)
3082 		zfs_rename_unlock(&zl);
3083 
3084 	zfs_dirent_unlock(sdl);
3085 	zfs_dirent_unlock(tdl);
3086 
3087 	VN_RELE(ZTOV(szp));
3088 	if (tzp)
3089 		VN_RELE(ZTOV(tzp));
3090 
3091 	ZFS_EXIT(zfsvfs);
3092 	return (error);
3093 }
3094 
3095 /*
3096  * Insert the indicated symbolic reference entry into the directory.
3097  *
3098  *	IN:	dvp	- Directory to contain new symbolic link.
3099  *		link	- Name for new symlink entry.
3100  *		vap	- Attributes of new entry.
3101  *		target	- Target path of new symlink.
3102  *		cr	- credentials of caller.
3103  *		ct	- caller context
3104  *		flags	- case flags
3105  *
3106  *	RETURN:	0 if success
3107  *		error code if failure
3108  *
3109  * Timestamps:
3110  *	dvp - ctime|mtime updated
3111  */
3112 /*ARGSUSED*/
3113 static int
3114 zfs_symlink(vnode_t *dvp, char *name, vattr_t *vap, char *link, cred_t *cr,
3115     caller_context_t *ct, int flags)
3116 {
3117 	znode_t		*zp, *dzp = VTOZ(dvp);
3118 	zfs_dirlock_t	*dl;
3119 	dmu_tx_t	*tx;
3120 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3121 	zilog_t		*zilog;
3122 	int		len = strlen(link);
3123 	int		error;
3124 	int		zflg = ZNEW;
3125 	zfs_fuid_info_t *fuidp = NULL;
3126 
3127 	ASSERT(vap->va_type == VLNK);
3128 
3129 	ZFS_ENTER(zfsvfs);
3130 	ZFS_VERIFY_ZP(dzp);
3131 	zilog = zfsvfs->z_log;
3132 
3133 	if (zfsvfs->z_case & ZFS_UTF8_ONLY && u8_validate(name, strlen(name),
3134 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3135 		ZFS_EXIT(zfsvfs);
3136 		return (EILSEQ);
3137 	}
3138 	if (flags & FIGNORECASE)
3139 		zflg |= ZCILOOK;
3140 top:
3141 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
3142 		ZFS_EXIT(zfsvfs);
3143 		return (error);
3144 	}
3145 
3146 	if (len > MAXPATHLEN) {
3147 		ZFS_EXIT(zfsvfs);
3148 		return (ENAMETOOLONG);
3149 	}
3150 
3151 	/*
3152 	 * Attempt to lock directory; fail if entry already exists.
3153 	 */
3154 	error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3155 	if (error) {
3156 		ZFS_EXIT(zfsvfs);
3157 		return (error);
3158 	}
3159 
3160 	tx = dmu_tx_create(zfsvfs->z_os);
3161 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3162 	dmu_tx_hold_bonus(tx, dzp->z_id);
3163 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3164 	if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
3165 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, SPA_MAXBLOCKSIZE);
3166 	if (zfsvfs->z_fuid_obj == 0) {
3167 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
3168 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3169 		    SPA_MAXBLOCKSIZE);
3170 		dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, FALSE, NULL);
3171 	} else {
3172 		dmu_tx_hold_bonus(tx, zfsvfs->z_fuid_obj);
3173 		dmu_tx_hold_write(tx, zfsvfs->z_fuid_obj, 0,
3174 		    SPA_MAXBLOCKSIZE);
3175 	}
3176 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
3177 	if (error) {
3178 		zfs_dirent_unlock(dl);
3179 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
3180 			dmu_tx_wait(tx);
3181 			dmu_tx_abort(tx);
3182 			goto top;
3183 		}
3184 		dmu_tx_abort(tx);
3185 		ZFS_EXIT(zfsvfs);
3186 		return (error);
3187 	}
3188 
3189 	dmu_buf_will_dirty(dzp->z_dbuf, tx);
3190 
3191 	/*
3192 	 * Create a new object for the symlink.
3193 	 * Put the link content into bonus buffer if it will fit;
3194 	 * otherwise, store it just like any other file data.
3195 	 */
3196 	if (sizeof (znode_phys_t) + len <= dmu_bonus_max()) {
3197 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, len, NULL, &fuidp);
3198 		if (len != 0)
3199 			bcopy(link, zp->z_phys + 1, len);
3200 	} else {
3201 		dmu_buf_t *dbp;
3202 
3203 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, 0, NULL, &fuidp);
3204 		/*
3205 		 * Nothing can access the znode yet so no locking needed
3206 		 * for growing the znode's blocksize.
3207 		 */
3208 		zfs_grow_blocksize(zp, len, tx);
3209 
3210 		VERIFY(0 == dmu_buf_hold(zfsvfs->z_os,
3211 		    zp->z_id, 0, FTAG, &dbp));
3212 		dmu_buf_will_dirty(dbp, tx);
3213 
3214 		ASSERT3U(len, <=, dbp->db_size);
3215 		bcopy(link, dbp->db_data, len);
3216 		dmu_buf_rele(dbp, FTAG);
3217 	}
3218 	zp->z_phys->zp_size = len;
3219 
3220 	/*
3221 	 * Insert the new object into the directory.
3222 	 */
3223 	(void) zfs_link_create(dl, zp, tx, ZNEW);
3224 out:
3225 	if (error == 0) {
3226 		uint64_t txtype = TX_SYMLINK;
3227 		if (flags & FIGNORECASE)
3228 			txtype |= TX_CI;
3229 		zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3230 	}
3231 	if (fuidp)
3232 		zfs_fuid_info_free(fuidp);
3233 
3234 	dmu_tx_commit(tx);
3235 
3236 	zfs_dirent_unlock(dl);
3237 
3238 	VN_RELE(ZTOV(zp));
3239 
3240 	ZFS_EXIT(zfsvfs);
3241 	return (error);
3242 }
3243 
3244 /*
3245  * Return, in the buffer contained in the provided uio structure,
3246  * the symbolic path referred to by vp.
3247  *
3248  *	IN:	vp	- vnode of symbolic link.
3249  *		uoip	- structure to contain the link path.
3250  *		cr	- credentials of caller.
3251  *		ct	- caller context
3252  *
3253  *	OUT:	uio	- structure to contain the link path.
3254  *
3255  *	RETURN:	0 if success
3256  *		error code if failure
3257  *
3258  * Timestamps:
3259  *	vp - atime updated
3260  */
3261 /* ARGSUSED */
3262 static int
3263 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
3264 {
3265 	znode_t		*zp = VTOZ(vp);
3266 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3267 	size_t		bufsz;
3268 	int		error;
3269 
3270 	ZFS_ENTER(zfsvfs);
3271 	ZFS_VERIFY_ZP(zp);
3272 
3273 	bufsz = (size_t)zp->z_phys->zp_size;
3274 	if (bufsz + sizeof (znode_phys_t) <= zp->z_dbuf->db_size) {
3275 		error = uiomove(zp->z_phys + 1,
3276 		    MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
3277 	} else {
3278 		dmu_buf_t *dbp;
3279 		error = dmu_buf_hold(zfsvfs->z_os, zp->z_id, 0, FTAG, &dbp);
3280 		if (error) {
3281 			ZFS_EXIT(zfsvfs);
3282 			return (error);
3283 		}
3284 		error = uiomove(dbp->db_data,
3285 		    MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
3286 		dmu_buf_rele(dbp, FTAG);
3287 	}
3288 
3289 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3290 	ZFS_EXIT(zfsvfs);
3291 	return (error);
3292 }
3293 
3294 /*
3295  * Insert a new entry into directory tdvp referencing svp.
3296  *
3297  *	IN:	tdvp	- Directory to contain new entry.
3298  *		svp	- vnode of new entry.
3299  *		name	- name of new entry.
3300  *		cr	- credentials of caller.
3301  *		ct	- caller context
3302  *
3303  *	RETURN:	0 if success
3304  *		error code if failure
3305  *
3306  * Timestamps:
3307  *	tdvp - ctime|mtime updated
3308  *	 svp - ctime updated
3309  */
3310 /* ARGSUSED */
3311 static int
3312 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
3313     caller_context_t *ct, int flags)
3314 {
3315 	znode_t		*dzp = VTOZ(tdvp);
3316 	znode_t		*tzp, *szp;
3317 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3318 	zilog_t		*zilog;
3319 	zfs_dirlock_t	*dl;
3320 	dmu_tx_t	*tx;
3321 	vnode_t		*realvp;
3322 	int		error;
3323 	int		zf = ZNEW;
3324 	uid_t		owner;
3325 
3326 	ASSERT(tdvp->v_type == VDIR);
3327 
3328 	ZFS_ENTER(zfsvfs);
3329 	ZFS_VERIFY_ZP(dzp);
3330 	zilog = zfsvfs->z_log;
3331 
3332 	if (VOP_REALVP(svp, &realvp, ct) == 0)
3333 		svp = realvp;
3334 
3335 	if (svp->v_vfsp != tdvp->v_vfsp) {
3336 		ZFS_EXIT(zfsvfs);
3337 		return (EXDEV);
3338 	}
3339 	szp = VTOZ(svp);
3340 	ZFS_VERIFY_ZP(szp);
3341 
3342 	if (zfsvfs->z_case & ZFS_UTF8_ONLY && u8_validate(name,
3343 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3344 		ZFS_EXIT(zfsvfs);
3345 		return (EILSEQ);
3346 	}
3347 	if (flags & FIGNORECASE)
3348 		zf |= ZCILOOK;
3349 
3350 top:
3351 	/*
3352 	 * We do not support links between attributes and non-attributes
3353 	 * because of the potential security risk of creating links
3354 	 * into "normal" file space in order to circumvent restrictions
3355 	 * imposed in attribute space.
3356 	 */
3357 	if ((szp->z_phys->zp_flags & ZFS_XATTR) !=
3358 	    (dzp->z_phys->zp_flags & ZFS_XATTR)) {
3359 		ZFS_EXIT(zfsvfs);
3360 		return (EINVAL);
3361 	}
3362 
3363 	/*
3364 	 * POSIX dictates that we return EPERM here.
3365 	 * Better choices include ENOTSUP or EISDIR.
3366 	 */
3367 	if (svp->v_type == VDIR) {
3368 		ZFS_EXIT(zfsvfs);
3369 		return (EPERM);
3370 	}
3371 
3372 	zfs_fuid_map_id(zfsvfs, szp->z_phys->zp_uid, ZFS_OWNER, &owner);
3373 	if (owner != crgetuid(cr) &&
3374 	    secpolicy_basic_link(cr) != 0) {
3375 		ZFS_EXIT(zfsvfs);
3376 		return (EPERM);
3377 	}
3378 
3379 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
3380 		ZFS_EXIT(zfsvfs);
3381 		return (error);
3382 	}
3383 
3384 	/*
3385 	 * Attempt to lock directory; fail if entry already exists.
3386 	 */
3387 	error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
3388 	if (error) {
3389 		ZFS_EXIT(zfsvfs);
3390 		return (error);
3391 	}
3392 
3393 	tx = dmu_tx_create(zfsvfs->z_os);
3394 	dmu_tx_hold_bonus(tx, szp->z_id);
3395 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3396 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
3397 	if (error) {
3398 		zfs_dirent_unlock(dl);
3399 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
3400 			dmu_tx_wait(tx);
3401 			dmu_tx_abort(tx);
3402 			goto top;
3403 		}
3404 		dmu_tx_abort(tx);
3405 		ZFS_EXIT(zfsvfs);
3406 		return (error);
3407 	}
3408 
3409 	error = zfs_link_create(dl, szp, tx, 0);
3410 
3411 	if (error == 0) {
3412 		uint64_t txtype = TX_LINK;
3413 		if (flags & FIGNORECASE)
3414 			txtype |= TX_CI;
3415 		zfs_log_link(zilog, tx, txtype, dzp, szp, name);
3416 	}
3417 
3418 	dmu_tx_commit(tx);
3419 
3420 	zfs_dirent_unlock(dl);
3421 
3422 	if (error == 0) {
3423 		vnevent_link(svp, ct);
3424 	}
3425 
3426 	ZFS_EXIT(zfsvfs);
3427 	return (error);
3428 }
3429 
3430 /*
3431  * zfs_null_putapage() is used when the file system has been force
3432  * unmounted. It just drops the pages.
3433  */
3434 /* ARGSUSED */
3435 static int
3436 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
3437 		size_t *lenp, int flags, cred_t *cr)
3438 {
3439 	pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
3440 	return (0);
3441 }
3442 
3443 /*
3444  * Push a page out to disk, klustering if possible.
3445  *
3446  *	IN:	vp	- file to push page to.
3447  *		pp	- page to push.
3448  *		flags	- additional flags.
3449  *		cr	- credentials of caller.
3450  *
3451  *	OUT:	offp	- start of range pushed.
3452  *		lenp	- len of range pushed.
3453  *
3454  *	RETURN:	0 if success
3455  *		error code if failure
3456  *
3457  * NOTE: callers must have locked the page to be pushed.  On
3458  * exit, the page (and all other pages in the kluster) must be
3459  * unlocked.
3460  */
3461 /* ARGSUSED */
3462 static int
3463 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
3464 		size_t *lenp, int flags, cred_t *cr)
3465 {
3466 	znode_t		*zp = VTOZ(vp);
3467 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3468 	zilog_t		*zilog = zfsvfs->z_log;
3469 	dmu_tx_t	*tx;
3470 	rl_t		*rl;
3471 	u_offset_t	off, koff;
3472 	size_t		len, klen;
3473 	uint64_t	filesz;
3474 	int		err;
3475 
3476 	filesz = zp->z_phys->zp_size;
3477 	off = pp->p_offset;
3478 	len = PAGESIZE;
3479 	/*
3480 	 * If our blocksize is bigger than the page size, try to kluster
3481 	 * muiltiple pages so that we write a full block (thus avoiding
3482 	 * a read-modify-write).
3483 	 */
3484 	if (off < filesz && zp->z_blksz > PAGESIZE) {
3485 		if (!ISP2(zp->z_blksz)) {
3486 			/* Only one block in the file. */
3487 			klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
3488 			koff = 0;
3489 		} else {
3490 			klen = zp->z_blksz;
3491 			koff = P2ALIGN(off, (u_offset_t)klen);
3492 		}
3493 		ASSERT(koff <= filesz);
3494 		if (koff + klen > filesz)
3495 			klen = P2ROUNDUP(filesz - koff, (uint64_t)PAGESIZE);
3496 		pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
3497 	}
3498 	ASSERT3U(btop(len), ==, btopr(len));
3499 top:
3500 	rl = zfs_range_lock(zp, off, len, RL_WRITER);
3501 	/*
3502 	 * Can't push pages past end-of-file.
3503 	 */
3504 	filesz = zp->z_phys->zp_size;
3505 	if (off >= filesz) {
3506 		/* ignore all pages */
3507 		err = 0;
3508 		goto out;
3509 	} else if (off + len > filesz) {
3510 		int npages = btopr(filesz - off);
3511 		page_t *trunc;
3512 
3513 		page_list_break(&pp, &trunc, npages);
3514 		/* ignore pages past end of file */
3515 		if (trunc)
3516 			pvn_write_done(trunc, flags);
3517 		len = filesz - off;
3518 	}
3519 
3520 	tx = dmu_tx_create(zfsvfs->z_os);
3521 	dmu_tx_hold_write(tx, zp->z_id, off, len);
3522 	dmu_tx_hold_bonus(tx, zp->z_id);
3523 	err = dmu_tx_assign(tx, zfsvfs->z_assign);
3524 	if (err != 0) {
3525 		if (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
3526 			zfs_range_unlock(rl);
3527 			dmu_tx_wait(tx);
3528 			dmu_tx_abort(tx);
3529 			err = 0;
3530 			goto top;
3531 		}
3532 		dmu_tx_abort(tx);
3533 		goto out;
3534 	}
3535 
3536 	if (zp->z_blksz <= PAGESIZE) {
3537 		caddr_t va = ppmapin(pp, PROT_READ, (caddr_t)-1);
3538 		ASSERT3U(len, <=, PAGESIZE);
3539 		dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
3540 		ppmapout(va);
3541 	} else {
3542 		err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
3543 	}
3544 
3545 	if (err == 0) {
3546 		zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
3547 		zfs_log_write(zilog, tx, TX_WRITE, zp, off, len, 0);
3548 		dmu_tx_commit(tx);
3549 	}
3550 
3551 out:
3552 	zfs_range_unlock(rl);
3553 	pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
3554 	if (offp)
3555 		*offp = off;
3556 	if (lenp)
3557 		*lenp = len;
3558 
3559 	return (err);
3560 }
3561 
3562 /*
3563  * Copy the portion of the file indicated from pages into the file.
3564  * The pages are stored in a page list attached to the files vnode.
3565  *
3566  *	IN:	vp	- vnode of file to push page data to.
3567  *		off	- position in file to put data.
3568  *		len	- amount of data to write.
3569  *		flags	- flags to control the operation.
3570  *		cr	- credentials of caller.
3571  *		ct	- caller context.
3572  *
3573  *	RETURN:	0 if success
3574  *		error code if failure
3575  *
3576  * Timestamps:
3577  *	vp - ctime|mtime updated
3578  */
3579 /*ARGSUSED*/
3580 static int
3581 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
3582     caller_context_t *ct)
3583 {
3584 	znode_t		*zp = VTOZ(vp);
3585 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3586 	page_t		*pp;
3587 	size_t		io_len;
3588 	u_offset_t	io_off;
3589 	uint64_t	filesz;
3590 	int		error = 0;
3591 
3592 	ZFS_ENTER(zfsvfs);
3593 	ZFS_VERIFY_ZP(zp);
3594 
3595 	if (len == 0) {
3596 		/*
3597 		 * Search the entire vp list for pages >= off.
3598 		 */
3599 		error = pvn_vplist_dirty(vp, (u_offset_t)off, zfs_putapage,
3600 		    flags, cr);
3601 		goto out;
3602 	}
3603 
3604 	filesz = zp->z_phys->zp_size; /* get consistent copy of zp_size */
3605 	if (off > filesz) {
3606 		/* past end of file */
3607 		ZFS_EXIT(zfsvfs);
3608 		return (0);
3609 	}
3610 
3611 	len = MIN(len, filesz - off);
3612 
3613 	for (io_off = off; io_off < off + len; io_off += io_len) {
3614 		if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
3615 			pp = page_lookup(vp, io_off,
3616 			    (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
3617 		} else {
3618 			pp = page_lookup_nowait(vp, io_off,
3619 			    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
3620 		}
3621 
3622 		if (pp != NULL && pvn_getdirty(pp, flags)) {
3623 			int err;
3624 
3625 			/*
3626 			 * Found a dirty page to push
3627 			 */
3628 			err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
3629 			if (err)
3630 				error = err;
3631 		} else {
3632 			io_len = PAGESIZE;
3633 		}
3634 	}
3635 out:
3636 	if ((flags & B_ASYNC) == 0)
3637 		zil_commit(zfsvfs->z_log, UINT64_MAX, zp->z_id);
3638 	ZFS_EXIT(zfsvfs);
3639 	return (error);
3640 }
3641 
3642 /*ARGSUSED*/
3643 void
3644 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
3645 {
3646 	znode_t	*zp = VTOZ(vp);
3647 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3648 	int error;
3649 
3650 	rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
3651 	if (zp->z_dbuf == NULL) {
3652 		/*
3653 		 * This fs has been unmounted, or we did
3654 		 * zfs_suspend/resume and it no longer exists.
3655 		 */
3656 		if (vn_has_cached_data(vp)) {
3657 			(void) pvn_vplist_dirty(vp, 0, zfs_null_putapage,
3658 			    B_INVAL, cr);
3659 		}
3660 
3661 		mutex_enter(&zp->z_lock);
3662 		vp->v_count = 0; /* count arrives as 1 */
3663 		mutex_exit(&zp->z_lock);
3664 		zfs_znode_free(zp);
3665 		rw_exit(&zfsvfs->z_teardown_inactive_lock);
3666 		VFS_RELE(zfsvfs->z_vfs);
3667 		return;
3668 	}
3669 
3670 	/*
3671 	 * Attempt to push any data in the page cache.  If this fails
3672 	 * we will get kicked out later in zfs_zinactive().
3673 	 */
3674 	if (vn_has_cached_data(vp)) {
3675 		(void) pvn_vplist_dirty(vp, 0, zfs_putapage, B_INVAL|B_ASYNC,
3676 		    cr);
3677 	}
3678 
3679 	if (zp->z_atime_dirty && zp->z_unlinked == 0) {
3680 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
3681 
3682 		dmu_tx_hold_bonus(tx, zp->z_id);
3683 		error = dmu_tx_assign(tx, TXG_WAIT);
3684 		if (error) {
3685 			dmu_tx_abort(tx);
3686 		} else {
3687 			dmu_buf_will_dirty(zp->z_dbuf, tx);
3688 			mutex_enter(&zp->z_lock);
3689 			zp->z_atime_dirty = 0;
3690 			mutex_exit(&zp->z_lock);
3691 			dmu_tx_commit(tx);
3692 		}
3693 	}
3694 
3695 	zfs_zinactive(zp);
3696 	rw_exit(&zfsvfs->z_teardown_inactive_lock);
3697 }
3698 
3699 /*
3700  * Bounds-check the seek operation.
3701  *
3702  *	IN:	vp	- vnode seeking within
3703  *		ooff	- old file offset
3704  *		noffp	- pointer to new file offset
3705  *		ct	- caller context
3706  *
3707  *	RETURN:	0 if success
3708  *		EINVAL if new offset invalid
3709  */
3710 /* ARGSUSED */
3711 static int
3712 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp,
3713     caller_context_t *ct)
3714 {
3715 	if (vp->v_type == VDIR)
3716 		return (0);
3717 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
3718 }
3719 
3720 /*
3721  * Pre-filter the generic locking function to trap attempts to place
3722  * a mandatory lock on a memory mapped file.
3723  */
3724 static int
3725 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
3726     flk_callback_t *flk_cbp, cred_t *cr, caller_context_t *ct)
3727 {
3728 	znode_t *zp = VTOZ(vp);
3729 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3730 	int error;
3731 
3732 	ZFS_ENTER(zfsvfs);
3733 	ZFS_VERIFY_ZP(zp);
3734 
3735 	/*
3736 	 * We are following the UFS semantics with respect to mapcnt
3737 	 * here: If we see that the file is mapped already, then we will
3738 	 * return an error, but we don't worry about races between this
3739 	 * function and zfs_map().
3740 	 */
3741 	if (zp->z_mapcnt > 0 && MANDMODE((mode_t)zp->z_phys->zp_mode)) {
3742 		ZFS_EXIT(zfsvfs);
3743 		return (EAGAIN);
3744 	}
3745 	error = fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct);
3746 	ZFS_EXIT(zfsvfs);
3747 	return (error);
3748 }
3749 
3750 /*
3751  * If we can't find a page in the cache, we will create a new page
3752  * and fill it with file data.  For efficiency, we may try to fill
3753  * multiple pages at once (klustering).
3754  */
3755 static int
3756 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
3757     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
3758 {
3759 	znode_t *zp = VTOZ(vp);
3760 	page_t *pp, *cur_pp;
3761 	objset_t *os = zp->z_zfsvfs->z_os;
3762 	caddr_t va;
3763 	u_offset_t io_off, total;
3764 	uint64_t oid = zp->z_id;
3765 	size_t io_len;
3766 	uint64_t filesz;
3767 	int err;
3768 
3769 	/*
3770 	 * If we are only asking for a single page don't bother klustering.
3771 	 */
3772 	filesz = zp->z_phys->zp_size; /* get consistent copy of zp_size */
3773 	if (off >= filesz)
3774 		return (EFAULT);
3775 	if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
3776 		io_off = off;
3777 		io_len = PAGESIZE;
3778 		pp = page_create_va(vp, io_off, io_len, PG_WAIT, seg, addr);
3779 	} else {
3780 		/*
3781 		 * Try to fill a kluster of pages (a blocks worth).
3782 		 */
3783 		size_t klen;
3784 		u_offset_t koff;
3785 
3786 		if (!ISP2(zp->z_blksz)) {
3787 			/* Only one block in the file. */
3788 			klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
3789 			koff = 0;
3790 		} else {
3791 			/*
3792 			 * It would be ideal to align our offset to the
3793 			 * blocksize but doing so has resulted in some
3794 			 * strange application crashes. For now, we
3795 			 * leave the offset as is and only adjust the
3796 			 * length if we are off the end of the file.
3797 			 */
3798 			koff = off;
3799 			klen = plsz;
3800 		}
3801 		ASSERT(koff <= filesz);
3802 		if (koff + klen > filesz)
3803 			klen = P2ROUNDUP(filesz, (uint64_t)PAGESIZE) - koff;
3804 		ASSERT3U(off, >=, koff);
3805 		ASSERT3U(off, <, koff + klen);
3806 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
3807 		    &io_len, koff, klen, 0);
3808 	}
3809 	if (pp == NULL) {
3810 		/*
3811 		 * Some other thread entered the page before us.
3812 		 * Return to zfs_getpage to retry the lookup.
3813 		 */
3814 		*pl = NULL;
3815 		return (0);
3816 	}
3817 
3818 	/*
3819 	 * Fill the pages in the kluster.
3820 	 */
3821 	cur_pp = pp;
3822 	for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
3823 		ASSERT3U(io_off, ==, cur_pp->p_offset);
3824 		va = ppmapin(cur_pp, PROT_READ | PROT_WRITE, (caddr_t)-1);
3825 		err = dmu_read(os, oid, io_off, PAGESIZE, va);
3826 		ppmapout(va);
3827 		if (err) {
3828 			/* On error, toss the entire kluster */
3829 			pvn_read_done(pp, B_ERROR);
3830 			return (err);
3831 		}
3832 		cur_pp = cur_pp->p_next;
3833 	}
3834 out:
3835 	/*
3836 	 * Fill in the page list array from the kluster.  If
3837 	 * there are too many pages in the kluster, return
3838 	 * as many pages as possible starting from the desired
3839 	 * offset `off'.
3840 	 * NOTE: the page list will always be null terminated.
3841 	 */
3842 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
3843 
3844 	return (0);
3845 }
3846 
3847 /*
3848  * Return pointers to the pages for the file region [off, off + len]
3849  * in the pl array.  If plsz is greater than len, this function may
3850  * also return page pointers from before or after the specified
3851  * region (i.e. some region [off', off' + plsz]).  These additional
3852  * pages are only returned if they are already in the cache, or were
3853  * created as part of a klustered read.
3854  *
3855  *	IN:	vp	- vnode of file to get data from.
3856  *		off	- position in file to get data from.
3857  *		len	- amount of data to retrieve.
3858  *		plsz	- length of provided page list.
3859  *		seg	- segment to obtain pages for.
3860  *		addr	- virtual address of fault.
3861  *		rw	- mode of created pages.
3862  *		cr	- credentials of caller.
3863  *		ct	- caller context.
3864  *
3865  *	OUT:	protp	- protection mode of created pages.
3866  *		pl	- list of pages created.
3867  *
3868  *	RETURN:	0 if success
3869  *		error code if failure
3870  *
3871  * Timestamps:
3872  *	vp - atime updated
3873  */
3874 /* ARGSUSED */
3875 static int
3876 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
3877 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
3878 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
3879 {
3880 	znode_t		*zp = VTOZ(vp);
3881 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3882 	page_t		*pp, **pl0 = pl;
3883 	int		need_unlock = 0, err = 0;
3884 	offset_t	orig_off;
3885 
3886 	ZFS_ENTER(zfsvfs);
3887 	ZFS_VERIFY_ZP(zp);
3888 
3889 	if (protp)
3890 		*protp = PROT_ALL;
3891 
3892 	/* no faultahead (for now) */
3893 	if (pl == NULL) {
3894 		ZFS_EXIT(zfsvfs);
3895 		return (0);
3896 	}
3897 
3898 	/* can't fault past EOF */
3899 	if (off >= zp->z_phys->zp_size) {
3900 		ZFS_EXIT(zfsvfs);
3901 		return (EFAULT);
3902 	}
3903 	orig_off = off;
3904 
3905 	/*
3906 	 * If we already own the lock, then we must be page faulting
3907 	 * in the middle of a write to this file (i.e., we are writing
3908 	 * to this file using data from a mapped region of the file).
3909 	 */
3910 	if (rw_owner(&zp->z_map_lock) != curthread) {
3911 		rw_enter(&zp->z_map_lock, RW_WRITER);
3912 		need_unlock = TRUE;
3913 	}
3914 
3915 	/*
3916 	 * Loop through the requested range [off, off + len] looking
3917 	 * for pages.  If we don't find a page, we will need to create
3918 	 * a new page and fill it with data from the file.
3919 	 */
3920 	while (len > 0) {
3921 		if (plsz < PAGESIZE)
3922 			break;
3923 		if (pp = page_lookup(vp, off, SE_SHARED)) {
3924 			*pl++ = pp;
3925 			off += PAGESIZE;
3926 			addr += PAGESIZE;
3927 			len -= PAGESIZE;
3928 			plsz -= PAGESIZE;
3929 		} else {
3930 			err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw);
3931 			if (err)
3932 				goto out;
3933 			/*
3934 			 * klustering may have changed our region
3935 			 * to be block aligned.
3936 			 */
3937 			if (((pp = *pl) != 0) && (off != pp->p_offset)) {
3938 				int delta = off - pp->p_offset;
3939 				len += delta;
3940 				off -= delta;
3941 				addr -= delta;
3942 			}
3943 			while (*pl) {
3944 				pl++;
3945 				off += PAGESIZE;
3946 				addr += PAGESIZE;
3947 				plsz -= PAGESIZE;
3948 				if (len > PAGESIZE)
3949 					len -= PAGESIZE;
3950 				else
3951 					len = 0;
3952 			}
3953 		}
3954 	}
3955 
3956 	/*
3957 	 * Fill out the page array with any pages already in the cache.
3958 	 */
3959 	while (plsz > 0) {
3960 		pp = page_lookup_nowait(vp, off, SE_SHARED);
3961 		if (pp == NULL)
3962 			break;
3963 		*pl++ = pp;
3964 		off += PAGESIZE;
3965 		plsz -= PAGESIZE;
3966 	}
3967 
3968 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3969 out:
3970 	/*
3971 	 * We can't grab the range lock for the page as reader which would
3972 	 * stop truncation as this leads to deadlock. So we need to recheck
3973 	 * the file size.
3974 	 */
3975 	if (orig_off >= zp->z_phys->zp_size)
3976 		err = EFAULT;
3977 	if (err) {
3978 		/*
3979 		 * Release any pages we have previously locked.
3980 		 */
3981 		while (pl > pl0)
3982 			page_unlock(*--pl);
3983 	}
3984 
3985 	*pl = NULL;
3986 
3987 	if (need_unlock)
3988 		rw_exit(&zp->z_map_lock);
3989 
3990 	ZFS_EXIT(zfsvfs);
3991 	return (err);
3992 }
3993 
3994 /*
3995  * Request a memory map for a section of a file.  This code interacts
3996  * with common code and the VM system as follows:
3997  *
3998  *	common code calls mmap(), which ends up in smmap_common()
3999  *
4000  *	this calls VOP_MAP(), which takes you into (say) zfs
4001  *
4002  *	zfs_map() calls as_map(), passing segvn_create() as the callback
4003  *
4004  *	segvn_create() creates the new segment and calls VOP_ADDMAP()
4005  *
4006  *	zfs_addmap() updates z_mapcnt
4007  */
4008 /*ARGSUSED*/
4009 static int
4010 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
4011     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4012     caller_context_t *ct)
4013 {
4014 	znode_t *zp = VTOZ(vp);
4015 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4016 	segvn_crargs_t	vn_a;
4017 	int		error;
4018 
4019 	if ((prot & PROT_WRITE) &&
4020 	    (zp->z_phys->zp_flags & (ZFS_IMMUTABLE | ZFS_READONLY |
4021 	    ZFS_APPENDONLY)))
4022 		return (EPERM);
4023 
4024 	ZFS_ENTER(zfsvfs);
4025 	ZFS_VERIFY_ZP(zp);
4026 
4027 	if (vp->v_flag & VNOMAP) {
4028 		ZFS_EXIT(zfsvfs);
4029 		return (ENOSYS);
4030 	}
4031 
4032 	if (off < 0 || len > MAXOFFSET_T - off) {
4033 		ZFS_EXIT(zfsvfs);
4034 		return (ENXIO);
4035 	}
4036 
4037 	if (vp->v_type != VREG) {
4038 		ZFS_EXIT(zfsvfs);
4039 		return (ENODEV);
4040 	}
4041 
4042 	/*
4043 	 * If file is locked, disallow mapping.
4044 	 */
4045 	if (MANDMODE((mode_t)zp->z_phys->zp_mode) && vn_has_flocks(vp)) {
4046 		ZFS_EXIT(zfsvfs);
4047 		return (EAGAIN);
4048 	}
4049 
4050 	as_rangelock(as);
4051 	if ((flags & MAP_FIXED) == 0) {
4052 		map_addr(addrp, len, off, 1, flags);
4053 		if (*addrp == NULL) {
4054 			as_rangeunlock(as);
4055 			ZFS_EXIT(zfsvfs);
4056 			return (ENOMEM);
4057 		}
4058 	} else {
4059 		/*
4060 		 * User specified address - blow away any previous mappings
4061 		 */
4062 		(void) as_unmap(as, *addrp, len);
4063 	}
4064 
4065 	vn_a.vp = vp;
4066 	vn_a.offset = (u_offset_t)off;
4067 	vn_a.type = flags & MAP_TYPE;
4068 	vn_a.prot = prot;
4069 	vn_a.maxprot = maxprot;
4070 	vn_a.cred = cr;
4071 	vn_a.amp = NULL;
4072 	vn_a.flags = flags & ~MAP_TYPE;
4073 	vn_a.szc = 0;
4074 	vn_a.lgrp_mem_policy_flags = 0;
4075 
4076 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
4077 
4078 	as_rangeunlock(as);
4079 	ZFS_EXIT(zfsvfs);
4080 	return (error);
4081 }
4082 
4083 /* ARGSUSED */
4084 static int
4085 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4086     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4087     caller_context_t *ct)
4088 {
4089 	uint64_t pages = btopr(len);
4090 
4091 	atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
4092 	return (0);
4093 }
4094 
4095 /*
4096  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
4097  * more accurate mtime for the associated file.  Since we don't have a way of
4098  * detecting when the data was actually modified, we have to resort to
4099  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
4100  * last page is pushed.  The problem occurs when the msync() call is omitted,
4101  * which by far the most common case:
4102  *
4103  * 	open()
4104  * 	mmap()
4105  * 	<modify memory>
4106  * 	munmap()
4107  * 	close()
4108  * 	<time lapse>
4109  * 	putpage() via fsflush
4110  *
4111  * If we wait until fsflush to come along, we can have a modification time that
4112  * is some arbitrary point in the future.  In order to prevent this in the
4113  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
4114  * torn down.
4115  */
4116 /* ARGSUSED */
4117 static int
4118 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4119     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
4120     caller_context_t *ct)
4121 {
4122 	uint64_t pages = btopr(len);
4123 
4124 	ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
4125 	atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
4126 
4127 	if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
4128 	    vn_has_cached_data(vp))
4129 		(void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
4130 
4131 	return (0);
4132 }
4133 
4134 /*
4135  * Free or allocate space in a file.  Currently, this function only
4136  * supports the `F_FREESP' command.  However, this command is somewhat
4137  * misnamed, as its functionality includes the ability to allocate as
4138  * well as free space.
4139  *
4140  *	IN:	vp	- vnode of file to free data in.
4141  *		cmd	- action to take (only F_FREESP supported).
4142  *		bfp	- section of file to free/alloc.
4143  *		flag	- current file open mode flags.
4144  *		offset	- current file offset.
4145  *		cr	- credentials of caller [UNUSED].
4146  *		ct	- caller context.
4147  *
4148  *	RETURN:	0 if success
4149  *		error code if failure
4150  *
4151  * Timestamps:
4152  *	vp - ctime|mtime updated
4153  */
4154 /* ARGSUSED */
4155 static int
4156 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
4157     offset_t offset, cred_t *cr, caller_context_t *ct)
4158 {
4159 	znode_t		*zp = VTOZ(vp);
4160 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4161 	uint64_t	off, len;
4162 	int		error;
4163 
4164 	ZFS_ENTER(zfsvfs);
4165 	ZFS_VERIFY_ZP(zp);
4166 
4167 top:
4168 	if (cmd != F_FREESP) {
4169 		ZFS_EXIT(zfsvfs);
4170 		return (EINVAL);
4171 	}
4172 
4173 	if (error = convoff(vp, bfp, 0, offset)) {
4174 		ZFS_EXIT(zfsvfs);
4175 		return (error);
4176 	}
4177 
4178 	if (bfp->l_len < 0) {
4179 		ZFS_EXIT(zfsvfs);
4180 		return (EINVAL);
4181 	}
4182 
4183 	off = bfp->l_start;
4184 	len = bfp->l_len; /* 0 means from off to end of file */
4185 
4186 	do {
4187 		error = zfs_freesp(zp, off, len, flag, TRUE);
4188 		/* NB: we already did dmu_tx_wait() if necessary */
4189 	} while (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT);
4190 
4191 	ZFS_EXIT(zfsvfs);
4192 	return (error);
4193 }
4194 
4195 /*ARGSUSED*/
4196 static int
4197 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
4198 {
4199 	znode_t		*zp = VTOZ(vp);
4200 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4201 	uint32_t	gen;
4202 	uint64_t	object = zp->z_id;
4203 	zfid_short_t	*zfid;
4204 	int		size, i;
4205 
4206 	ZFS_ENTER(zfsvfs);
4207 	ZFS_VERIFY_ZP(zp);
4208 	gen = (uint32_t)zp->z_gen;
4209 
4210 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
4211 	if (fidp->fid_len < size) {
4212 		fidp->fid_len = size;
4213 		ZFS_EXIT(zfsvfs);
4214 		return (ENOSPC);
4215 	}
4216 
4217 	zfid = (zfid_short_t *)fidp;
4218 
4219 	zfid->zf_len = size;
4220 
4221 	for (i = 0; i < sizeof (zfid->zf_object); i++)
4222 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4223 
4224 	/* Must have a non-zero generation number to distinguish from .zfs */
4225 	if (gen == 0)
4226 		gen = 1;
4227 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
4228 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4229 
4230 	if (size == LONG_FID_LEN) {
4231 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
4232 		zfid_long_t	*zlfid;
4233 
4234 		zlfid = (zfid_long_t *)fidp;
4235 
4236 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4237 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4238 
4239 		/* XXX - this should be the generation number for the objset */
4240 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4241 			zlfid->zf_setgen[i] = 0;
4242 	}
4243 
4244 	ZFS_EXIT(zfsvfs);
4245 	return (0);
4246 }
4247 
4248 static int
4249 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
4250     caller_context_t *ct)
4251 {
4252 	znode_t		*zp, *xzp;
4253 	zfsvfs_t	*zfsvfs;
4254 	zfs_dirlock_t	*dl;
4255 	int		error;
4256 
4257 	switch (cmd) {
4258 	case _PC_LINK_MAX:
4259 		*valp = ULONG_MAX;
4260 		return (0);
4261 
4262 	case _PC_FILESIZEBITS:
4263 		*valp = 64;
4264 		return (0);
4265 
4266 	case _PC_XATTR_EXISTS:
4267 		zp = VTOZ(vp);
4268 		zfsvfs = zp->z_zfsvfs;
4269 		ZFS_ENTER(zfsvfs);
4270 		ZFS_VERIFY_ZP(zp);
4271 		*valp = 0;
4272 		error = zfs_dirent_lock(&dl, zp, "", &xzp,
4273 		    ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
4274 		if (error == 0) {
4275 			zfs_dirent_unlock(dl);
4276 			if (!zfs_dirempty(xzp))
4277 				*valp = 1;
4278 			VN_RELE(ZTOV(xzp));
4279 		} else if (error == ENOENT) {
4280 			/*
4281 			 * If there aren't extended attributes, it's the
4282 			 * same as having zero of them.
4283 			 */
4284 			error = 0;
4285 		}
4286 		ZFS_EXIT(zfsvfs);
4287 		return (error);
4288 
4289 	case _PC_SATTR_ENABLED:
4290 	case _PC_SATTR_EXISTS:
4291 		zp = VTOZ(vp);
4292 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_XVATTR) &&
4293 		    (vp->v_type == VREG || vp->v_type == VDIR);
4294 		return (0);
4295 
4296 	case _PC_ACL_ENABLED:
4297 		*valp = _ACL_ACE_ENABLED;
4298 		return (0);
4299 
4300 	case _PC_MIN_HOLE_SIZE:
4301 		*valp = (ulong_t)SPA_MINBLOCKSIZE;
4302 		return (0);
4303 
4304 	default:
4305 		return (fs_pathconf(vp, cmd, valp, cr, ct));
4306 	}
4307 }
4308 
4309 /*ARGSUSED*/
4310 static int
4311 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
4312     caller_context_t *ct)
4313 {
4314 	znode_t *zp = VTOZ(vp);
4315 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4316 	int error;
4317 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4318 
4319 	ZFS_ENTER(zfsvfs);
4320 	ZFS_VERIFY_ZP(zp);
4321 	error = zfs_getacl(zp, vsecp, skipaclchk, cr);
4322 	ZFS_EXIT(zfsvfs);
4323 
4324 	return (error);
4325 }
4326 
4327 /*ARGSUSED*/
4328 static int
4329 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
4330     caller_context_t *ct)
4331 {
4332 	znode_t *zp = VTOZ(vp);
4333 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4334 	int error;
4335 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4336 
4337 	ZFS_ENTER(zfsvfs);
4338 	ZFS_VERIFY_ZP(zp);
4339 	error = zfs_setacl(zp, vsecp, skipaclchk, cr);
4340 	ZFS_EXIT(zfsvfs);
4341 	return (error);
4342 }
4343 
4344 /*
4345  * Predeclare these here so that the compiler assumes that
4346  * this is an "old style" function declaration that does
4347  * not include arguments => we won't get type mismatch errors
4348  * in the initializations that follow.
4349  */
4350 static int zfs_inval();
4351 static int zfs_isdir();
4352 
4353 static int
4354 zfs_inval()
4355 {
4356 	return (EINVAL);
4357 }
4358 
4359 static int
4360 zfs_isdir()
4361 {
4362 	return (EISDIR);
4363 }
4364 /*
4365  * Directory vnode operations template
4366  */
4367 vnodeops_t *zfs_dvnodeops;
4368 const fs_operation_def_t zfs_dvnodeops_template[] = {
4369 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
4370 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
4371 	VOPNAME_READ,		{ .error = zfs_isdir },
4372 	VOPNAME_WRITE,		{ .error = zfs_isdir },
4373 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
4374 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
4375 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
4376 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
4377 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
4378 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
4379 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
4380 	VOPNAME_LINK,		{ .vop_link = zfs_link },
4381 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
4382 	VOPNAME_MKDIR,		{ .vop_mkdir = zfs_mkdir },
4383 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
4384 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
4385 	VOPNAME_SYMLINK,	{ .vop_symlink = zfs_symlink },
4386 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
4387 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
4388 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
4389 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
4390 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
4391 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
4392 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
4393 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
4394 	NULL,			NULL
4395 };
4396 
4397 /*
4398  * Regular file vnode operations template
4399  */
4400 vnodeops_t *zfs_fvnodeops;
4401 const fs_operation_def_t zfs_fvnodeops_template[] = {
4402 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
4403 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
4404 	VOPNAME_READ,		{ .vop_read = zfs_read },
4405 	VOPNAME_WRITE,		{ .vop_write = zfs_write },
4406 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
4407 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
4408 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
4409 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
4410 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
4411 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
4412 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
4413 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
4414 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
4415 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
4416 	VOPNAME_FRLOCK,		{ .vop_frlock = zfs_frlock },
4417 	VOPNAME_SPACE,		{ .vop_space = zfs_space },
4418 	VOPNAME_GETPAGE,	{ .vop_getpage = zfs_getpage },
4419 	VOPNAME_PUTPAGE,	{ .vop_putpage = zfs_putpage },
4420 	VOPNAME_MAP,		{ .vop_map = zfs_map },
4421 	VOPNAME_ADDMAP,		{ .vop_addmap = zfs_addmap },
4422 	VOPNAME_DELMAP,		{ .vop_delmap = zfs_delmap },
4423 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
4424 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
4425 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
4426 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
4427 	NULL,			NULL
4428 };
4429 
4430 /*
4431  * Symbolic link vnode operations template
4432  */
4433 vnodeops_t *zfs_symvnodeops;
4434 const fs_operation_def_t zfs_symvnodeops_template[] = {
4435 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
4436 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
4437 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
4438 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
4439 	VOPNAME_READLINK,	{ .vop_readlink = zfs_readlink },
4440 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
4441 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
4442 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
4443 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
4444 	NULL,			NULL
4445 };
4446 
4447 /*
4448  * Extended attribute directory vnode operations template
4449  *	This template is identical to the directory vnodes
4450  *	operation template except for restricted operations:
4451  *		VOP_MKDIR()
4452  *		VOP_SYMLINK()
4453  * Note that there are other restrictions embedded in:
4454  *	zfs_create()	- restrict type to VREG
4455  *	zfs_link()	- no links into/out of attribute space
4456  *	zfs_rename()	- no moves into/out of attribute space
4457  */
4458 vnodeops_t *zfs_xdvnodeops;
4459 const fs_operation_def_t zfs_xdvnodeops_template[] = {
4460 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
4461 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
4462 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
4463 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
4464 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
4465 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
4466 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
4467 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
4468 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
4469 	VOPNAME_LINK,		{ .vop_link = zfs_link },
4470 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
4471 	VOPNAME_MKDIR,		{ .error = zfs_inval },
4472 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
4473 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
4474 	VOPNAME_SYMLINK,	{ .error = zfs_inval },
4475 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
4476 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
4477 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
4478 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
4479 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
4480 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
4481 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
4482 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
4483 	NULL,			NULL
4484 };
4485 
4486 /*
4487  * Error vnode operations template
4488  */
4489 vnodeops_t *zfs_evnodeops;
4490 const fs_operation_def_t zfs_evnodeops_template[] = {
4491 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
4492 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
4493 	NULL,			NULL
4494 };
4495