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