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