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