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