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