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