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