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