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