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