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