xref: /illumos-gate/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision 13b136d3061155363c62c9f6568d25b8b27da8f6)
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, unlinked);
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 		    B_FALSE);
2239 	}
2240 
2241 	dmu_tx_commit(tx);
2242 
2243 	rw_exit(&zp->z_parent_lock);
2244 	rw_exit(&zp->z_name_lock);
2245 out:
2246 	zfs_dirent_unlock(dl);
2247 
2248 	VN_RELE(vp);
2249 
2250 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2251 		zil_commit(zilog, 0);
2252 
2253 	ZFS_EXIT(zfsvfs);
2254 	return (error);
2255 }
2256 
2257 /*
2258  * Read as many directory entries as will fit into the provided
2259  * buffer from the given directory cursor position (specified in
2260  * the uio structure).
2261  *
2262  *	IN:	vp	- vnode of directory to read.
2263  *		uio	- structure supplying read location, range info,
2264  *			  and return buffer.
2265  *		cr	- credentials of caller.
2266  *		ct	- caller context
2267  *		flags	- case flags
2268  *
2269  *	OUT:	uio	- updated offset and range, buffer filled.
2270  *		eofp	- set to true if end-of-file detected.
2271  *
2272  *	RETURN:	0 on success, error code on failure.
2273  *
2274  * Timestamps:
2275  *	vp - atime updated
2276  *
2277  * Note that the low 4 bits of the cookie returned by zap is always zero.
2278  * This allows us to use the low range for "special" directory entries:
2279  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2280  * we use the offset 2 for the '.zfs' directory.
2281  */
2282 /* ARGSUSED */
2283 static int
2284 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp,
2285     caller_context_t *ct, int flags)
2286 {
2287 	znode_t		*zp = VTOZ(vp);
2288 	iovec_t		*iovp;
2289 	edirent_t	*eodp;
2290 	dirent64_t	*odp;
2291 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2292 	objset_t	*os;
2293 	caddr_t		outbuf;
2294 	size_t		bufsize;
2295 	zap_cursor_t	zc;
2296 	zap_attribute_t	zap;
2297 	uint_t		bytes_wanted;
2298 	uint64_t	offset; /* must be unsigned; checks for < 1 */
2299 	uint64_t	parent;
2300 	int		local_eof;
2301 	int		outcount;
2302 	int		error;
2303 	uint8_t		prefetch;
2304 	boolean_t	check_sysattrs;
2305 
2306 	ZFS_ENTER(zfsvfs);
2307 	ZFS_VERIFY_ZP(zp);
2308 
2309 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2310 	    &parent, sizeof (parent))) != 0) {
2311 		ZFS_EXIT(zfsvfs);
2312 		return (error);
2313 	}
2314 
2315 	/*
2316 	 * If we are not given an eof variable,
2317 	 * use a local one.
2318 	 */
2319 	if (eofp == NULL)
2320 		eofp = &local_eof;
2321 
2322 	/*
2323 	 * Check for valid iov_len.
2324 	 */
2325 	if (uio->uio_iov->iov_len <= 0) {
2326 		ZFS_EXIT(zfsvfs);
2327 		return (SET_ERROR(EINVAL));
2328 	}
2329 
2330 	/*
2331 	 * Quit if directory has been removed (posix)
2332 	 */
2333 	if ((*eofp = zp->z_unlinked) != 0) {
2334 		ZFS_EXIT(zfsvfs);
2335 		return (0);
2336 	}
2337 
2338 	error = 0;
2339 	os = zfsvfs->z_os;
2340 	offset = uio->uio_loffset;
2341 	prefetch = zp->z_zn_prefetch;
2342 
2343 	/*
2344 	 * Initialize the iterator cursor.
2345 	 */
2346 	if (offset <= 3) {
2347 		/*
2348 		 * Start iteration from the beginning of the directory.
2349 		 */
2350 		zap_cursor_init(&zc, os, zp->z_id);
2351 	} else {
2352 		/*
2353 		 * The offset is a serialized cursor.
2354 		 */
2355 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2356 	}
2357 
2358 	/*
2359 	 * Get space to change directory entries into fs independent format.
2360 	 */
2361 	iovp = uio->uio_iov;
2362 	bytes_wanted = iovp->iov_len;
2363 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2364 		bufsize = bytes_wanted;
2365 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
2366 		odp = (struct dirent64 *)outbuf;
2367 	} else {
2368 		bufsize = bytes_wanted;
2369 		outbuf = NULL;
2370 		odp = (struct dirent64 *)iovp->iov_base;
2371 	}
2372 	eodp = (struct edirent *)odp;
2373 
2374 	/*
2375 	 * If this VFS supports the system attribute view interface; and
2376 	 * we're looking at an extended attribute directory; and we care
2377 	 * about normalization conflicts on this vfs; then we must check
2378 	 * for normalization conflicts with the sysattr name space.
2379 	 */
2380 	check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2381 	    (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2382 	    (flags & V_RDDIR_ENTFLAGS);
2383 
2384 	/*
2385 	 * Transform to file-system independent format
2386 	 */
2387 	outcount = 0;
2388 	while (outcount < bytes_wanted) {
2389 		ino64_t objnum;
2390 		ushort_t reclen;
2391 		off64_t *next = NULL;
2392 
2393 		/*
2394 		 * Special case `.', `..', and `.zfs'.
2395 		 */
2396 		if (offset == 0) {
2397 			(void) strcpy(zap.za_name, ".");
2398 			zap.za_normalization_conflict = 0;
2399 			objnum = zp->z_id;
2400 		} else if (offset == 1) {
2401 			(void) strcpy(zap.za_name, "..");
2402 			zap.za_normalization_conflict = 0;
2403 			objnum = parent;
2404 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
2405 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2406 			zap.za_normalization_conflict = 0;
2407 			objnum = ZFSCTL_INO_ROOT;
2408 		} else {
2409 			/*
2410 			 * Grab next entry.
2411 			 */
2412 			if (error = zap_cursor_retrieve(&zc, &zap)) {
2413 				if ((*eofp = (error == ENOENT)) != 0)
2414 					break;
2415 				else
2416 					goto update;
2417 			}
2418 
2419 			if (zap.za_integer_length != 8 ||
2420 			    zap.za_num_integers != 1) {
2421 				cmn_err(CE_WARN, "zap_readdir: bad directory "
2422 				    "entry, obj = %lld, offset = %lld\n",
2423 				    (u_longlong_t)zp->z_id,
2424 				    (u_longlong_t)offset);
2425 				error = SET_ERROR(ENXIO);
2426 				goto update;
2427 			}
2428 
2429 			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2430 			/*
2431 			 * MacOS X can extract the object type here such as:
2432 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2433 			 */
2434 
2435 			if (check_sysattrs && !zap.za_normalization_conflict) {
2436 				zap.za_normalization_conflict =
2437 				    xattr_sysattr_casechk(zap.za_name);
2438 			}
2439 		}
2440 
2441 		if (flags & V_RDDIR_ACCFILTER) {
2442 			/*
2443 			 * If we have no access at all, don't include
2444 			 * this entry in the returned information
2445 			 */
2446 			znode_t	*ezp;
2447 			if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2448 				goto skip_entry;
2449 			if (!zfs_has_access(ezp, cr)) {
2450 				VN_RELE(ZTOV(ezp));
2451 				goto skip_entry;
2452 			}
2453 			VN_RELE(ZTOV(ezp));
2454 		}
2455 
2456 		if (flags & V_RDDIR_ENTFLAGS)
2457 			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2458 		else
2459 			reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2460 
2461 		/*
2462 		 * Will this entry fit in the buffer?
2463 		 */
2464 		if (outcount + reclen > bufsize) {
2465 			/*
2466 			 * Did we manage to fit anything in the buffer?
2467 			 */
2468 			if (!outcount) {
2469 				error = SET_ERROR(EINVAL);
2470 				goto update;
2471 			}
2472 			break;
2473 		}
2474 		if (flags & V_RDDIR_ENTFLAGS) {
2475 			/*
2476 			 * Add extended flag entry:
2477 			 */
2478 			eodp->ed_ino = objnum;
2479 			eodp->ed_reclen = reclen;
2480 			/* NOTE: ed_off is the offset for the *next* entry */
2481 			next = &(eodp->ed_off);
2482 			eodp->ed_eflags = zap.za_normalization_conflict ?
2483 			    ED_CASE_CONFLICT : 0;
2484 			(void) strncpy(eodp->ed_name, zap.za_name,
2485 			    EDIRENT_NAMELEN(reclen));
2486 			eodp = (edirent_t *)((intptr_t)eodp + reclen);
2487 		} else {
2488 			/*
2489 			 * Add normal entry:
2490 			 */
2491 			odp->d_ino = objnum;
2492 			odp->d_reclen = reclen;
2493 			/* NOTE: d_off is the offset for the *next* entry */
2494 			next = &(odp->d_off);
2495 			(void) strncpy(odp->d_name, zap.za_name,
2496 			    DIRENT64_NAMELEN(reclen));
2497 			odp = (dirent64_t *)((intptr_t)odp + reclen);
2498 		}
2499 		outcount += reclen;
2500 
2501 		ASSERT(outcount <= bufsize);
2502 
2503 		/* Prefetch znode */
2504 		if (prefetch)
2505 			dmu_prefetch(os, objnum, 0, 0, 0,
2506 			    ZIO_PRIORITY_SYNC_READ);
2507 
2508 	skip_entry:
2509 		/*
2510 		 * Move to the next entry, fill in the previous offset.
2511 		 */
2512 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2513 			zap_cursor_advance(&zc);
2514 			offset = zap_cursor_serialize(&zc);
2515 		} else {
2516 			offset += 1;
2517 		}
2518 		if (next)
2519 			*next = offset;
2520 	}
2521 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2522 
2523 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2524 		iovp->iov_base += outcount;
2525 		iovp->iov_len -= outcount;
2526 		uio->uio_resid -= outcount;
2527 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2528 		/*
2529 		 * Reset the pointer.
2530 		 */
2531 		offset = uio->uio_loffset;
2532 	}
2533 
2534 update:
2535 	zap_cursor_fini(&zc);
2536 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2537 		kmem_free(outbuf, bufsize);
2538 
2539 	if (error == ENOENT)
2540 		error = 0;
2541 
2542 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2543 
2544 	uio->uio_loffset = offset;
2545 	ZFS_EXIT(zfsvfs);
2546 	return (error);
2547 }
2548 
2549 ulong_t zfs_fsync_sync_cnt = 4;
2550 
2551 static int
2552 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2553 {
2554 	znode_t	*zp = VTOZ(vp);
2555 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2556 
2557 	/*
2558 	 * Regardless of whether this is required for standards conformance,
2559 	 * this is the logical behavior when fsync() is called on a file with
2560 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
2561 	 * going to be pushed out as part of the zil_commit().
2562 	 */
2563 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2564 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
2565 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr, ct);
2566 
2567 	(void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2568 
2569 	if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2570 		ZFS_ENTER(zfsvfs);
2571 		ZFS_VERIFY_ZP(zp);
2572 		zil_commit(zfsvfs->z_log, zp->z_id);
2573 		ZFS_EXIT(zfsvfs);
2574 	}
2575 	return (0);
2576 }
2577 
2578 
2579 /*
2580  * Get the requested file attributes and place them in the provided
2581  * vattr structure.
2582  *
2583  *	IN:	vp	- vnode of file.
2584  *		vap	- va_mask identifies requested attributes.
2585  *			  If AT_XVATTR set, then optional attrs are requested
2586  *		flags	- ATTR_NOACLCHECK (CIFS server context)
2587  *		cr	- credentials of caller.
2588  *		ct	- caller context
2589  *
2590  *	OUT:	vap	- attribute values.
2591  *
2592  *	RETURN:	0 (always succeeds).
2593  */
2594 /* ARGSUSED */
2595 static int
2596 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2597     caller_context_t *ct)
2598 {
2599 	znode_t *zp = VTOZ(vp);
2600 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2601 	int	error = 0;
2602 	uint64_t links;
2603 	uint64_t mtime[2], ctime[2];
2604 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2605 	xoptattr_t *xoap = NULL;
2606 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2607 	sa_bulk_attr_t bulk[2];
2608 	int count = 0;
2609 
2610 	ZFS_ENTER(zfsvfs);
2611 	ZFS_VERIFY_ZP(zp);
2612 
2613 	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2614 
2615 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2616 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2617 
2618 	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2619 		ZFS_EXIT(zfsvfs);
2620 		return (error);
2621 	}
2622 
2623 	/*
2624 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2625 	 * Also, if we are the owner don't bother, since owner should
2626 	 * always be allowed to read basic attributes of file.
2627 	 */
2628 	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2629 	    (vap->va_uid != crgetuid(cr))) {
2630 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2631 		    skipaclchk, cr)) {
2632 			ZFS_EXIT(zfsvfs);
2633 			return (error);
2634 		}
2635 	}
2636 
2637 	/*
2638 	 * Return all attributes.  It's cheaper to provide the answer
2639 	 * than to determine whether we were asked the question.
2640 	 */
2641 
2642 	mutex_enter(&zp->z_lock);
2643 	vap->va_type = vp->v_type;
2644 	vap->va_mode = zp->z_mode & MODEMASK;
2645 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2646 	vap->va_nodeid = zp->z_id;
2647 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2648 		links = zp->z_links + 1;
2649 	else
2650 		links = zp->z_links;
2651 	vap->va_nlink = MIN(links, UINT32_MAX);	/* nlink_t limit! */
2652 	vap->va_size = zp->z_size;
2653 	vap->va_rdev = vp->v_rdev;
2654 	vap->va_seq = zp->z_seq;
2655 
2656 	/*
2657 	 * Add in any requested optional attributes and the create time.
2658 	 * Also set the corresponding bits in the returned attribute bitmap.
2659 	 */
2660 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2661 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2662 			xoap->xoa_archive =
2663 			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2664 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2665 		}
2666 
2667 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2668 			xoap->xoa_readonly =
2669 			    ((zp->z_pflags & ZFS_READONLY) != 0);
2670 			XVA_SET_RTN(xvap, XAT_READONLY);
2671 		}
2672 
2673 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2674 			xoap->xoa_system =
2675 			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2676 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2677 		}
2678 
2679 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2680 			xoap->xoa_hidden =
2681 			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2682 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2683 		}
2684 
2685 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2686 			xoap->xoa_nounlink =
2687 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2688 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2689 		}
2690 
2691 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2692 			xoap->xoa_immutable =
2693 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2694 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2695 		}
2696 
2697 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2698 			xoap->xoa_appendonly =
2699 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2700 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2701 		}
2702 
2703 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2704 			xoap->xoa_nodump =
2705 			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2706 			XVA_SET_RTN(xvap, XAT_NODUMP);
2707 		}
2708 
2709 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2710 			xoap->xoa_opaque =
2711 			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2712 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2713 		}
2714 
2715 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2716 			xoap->xoa_av_quarantined =
2717 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2718 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2719 		}
2720 
2721 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2722 			xoap->xoa_av_modified =
2723 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2724 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2725 		}
2726 
2727 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2728 		    vp->v_type == VREG) {
2729 			zfs_sa_get_scanstamp(zp, xvap);
2730 		}
2731 
2732 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2733 			uint64_t times[2];
2734 
2735 			(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2736 			    times, sizeof (times));
2737 			ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2738 			XVA_SET_RTN(xvap, XAT_CREATETIME);
2739 		}
2740 
2741 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2742 			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2743 			XVA_SET_RTN(xvap, XAT_REPARSE);
2744 		}
2745 		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2746 			xoap->xoa_generation = zp->z_gen;
2747 			XVA_SET_RTN(xvap, XAT_GEN);
2748 		}
2749 
2750 		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2751 			xoap->xoa_offline =
2752 			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2753 			XVA_SET_RTN(xvap, XAT_OFFLINE);
2754 		}
2755 
2756 		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2757 			xoap->xoa_sparse =
2758 			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2759 			XVA_SET_RTN(xvap, XAT_SPARSE);
2760 		}
2761 
2762 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2763 			xoap->xoa_projinherit =
2764 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0);
2765 			XVA_SET_RTN(xvap, XAT_PROJINHERIT);
2766 		}
2767 
2768 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2769 			xoap->xoa_projid = zp->z_projid;
2770 			XVA_SET_RTN(xvap, XAT_PROJID);
2771 		}
2772 	}
2773 
2774 	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2775 	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2776 	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2777 
2778 	mutex_exit(&zp->z_lock);
2779 
2780 	sa_object_size(zp->z_sa_hdl, &vap->va_blksize, &vap->va_nblocks);
2781 
2782 	if (zp->z_blksz == 0) {
2783 		/*
2784 		 * Block size hasn't been set; suggest maximal I/O transfers.
2785 		 */
2786 		vap->va_blksize = zfsvfs->z_max_blksz;
2787 	}
2788 
2789 	ZFS_EXIT(zfsvfs);
2790 	return (0);
2791 }
2792 
2793 /*
2794  * For the operation of changing file's user/group/project, we need to
2795  * handle not only the main object that is assigned to the file directly,
2796  * but also the ones that are used by the file via hidden xattr directory.
2797  *
2798  * Because the xattr directory may contain many EA entries, it may be
2799  * impossible to change all of them in the same transaction as changing the
2800  * main object's user/group/project attributes. If so, we have to change them
2801  * via other multiple independent transactions one by one. It may be not a good
2802  * solution, but we have no better idea yet.
2803  */
2804 static int
2805 zfs_setattr_dir(znode_t *dzp)
2806 {
2807 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2808 	objset_t	*os = zfsvfs->z_os;
2809 	zap_cursor_t	zc;
2810 	zap_attribute_t	zap;
2811 	zfs_dirlock_t	*dl;
2812 	znode_t		*zp = NULL;
2813 	dmu_tx_t	*tx = NULL;
2814 	sa_bulk_attr_t	bulk[4];
2815 	int		count;
2816 	int		err;
2817 
2818 	zap_cursor_init(&zc, os, dzp->z_id);
2819 	while ((err = zap_cursor_retrieve(&zc, &zap)) == 0) {
2820 		count = 0;
2821 		if (zap.za_integer_length != 8 || zap.za_num_integers != 1) {
2822 			err = ENXIO;
2823 			break;
2824 		}
2825 
2826 		err = zfs_dirent_lock(&dl, dzp, (char *)zap.za_name, &zp,
2827 		    ZEXISTS, NULL, NULL);
2828 		if (err == ENOENT)
2829 			goto next;
2830 		if (err)
2831 			break;
2832 
2833 		if (zp->z_uid == dzp->z_uid &&
2834 		    zp->z_gid == dzp->z_gid &&
2835 		    zp->z_projid == dzp->z_projid)
2836 			goto next;
2837 
2838 		tx = dmu_tx_create(os);
2839 		if (!(zp->z_pflags & ZFS_PROJID))
2840 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2841 		else
2842 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2843 
2844 		err = dmu_tx_assign(tx, TXG_WAIT);
2845 		if (err)
2846 			break;
2847 
2848 		mutex_enter(&dzp->z_lock);
2849 
2850 		if (zp->z_uid != dzp->z_uid) {
2851 			zp->z_uid = dzp->z_uid;
2852 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2853 			    &dzp->z_uid, sizeof (dzp->z_uid));
2854 		}
2855 
2856 		if (zp->z_gid != dzp->z_gid) {
2857 			zp->z_gid = dzp->z_gid;
2858 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
2859 			    &dzp->z_gid, sizeof (dzp->z_gid));
2860 		}
2861 
2862 		if (zp->z_projid != dzp->z_projid) {
2863 			if (!(zp->z_pflags & ZFS_PROJID)) {
2864 				zp->z_pflags |= ZFS_PROJID;
2865 				SA_ADD_BULK_ATTR(bulk, count,
2866 				    SA_ZPL_FLAGS(zfsvfs), NULL, &zp->z_pflags,
2867 				    sizeof (zp->z_pflags));
2868 			}
2869 
2870 			zp->z_projid = dzp->z_projid;
2871 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PROJID(zfsvfs),
2872 			    NULL, &zp->z_projid, sizeof (zp->z_projid));
2873 		}
2874 
2875 		mutex_exit(&dzp->z_lock);
2876 
2877 		if (likely(count > 0)) {
2878 			err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2879 			dmu_tx_commit(tx);
2880 		} else {
2881 			dmu_tx_abort(tx);
2882 		}
2883 		tx = NULL;
2884 		if (err != 0 && err != ENOENT)
2885 			break;
2886 
2887 next:
2888 		if (zp) {
2889 			VN_RELE(ZTOV(zp));
2890 			zp = NULL;
2891 			zfs_dirent_unlock(dl);
2892 		}
2893 		zap_cursor_advance(&zc);
2894 	}
2895 
2896 	if (tx)
2897 		dmu_tx_abort(tx);
2898 	if (zp) {
2899 		VN_RELE(ZTOV(zp));
2900 		zfs_dirent_unlock(dl);
2901 	}
2902 	zap_cursor_fini(&zc);
2903 
2904 	return (err == ENOENT ? 0 : err);
2905 }
2906 
2907 /*
2908  * Set the file attributes to the values contained in the
2909  * vattr structure.
2910  *
2911  *	IN:	vp	- vnode of file to be modified.
2912  *		vap	- new attribute values.
2913  *			  If AT_XVATTR set, then optional attrs are being set
2914  *		flags	- ATTR_UTIME set if non-default time values provided.
2915  *			- ATTR_NOACLCHECK (CIFS context only).
2916  *		cr	- credentials of caller.
2917  *		ct	- caller context
2918  *
2919  *	RETURN:	0 on success, error code on failure.
2920  *
2921  * Timestamps:
2922  *	vp - ctime updated, mtime updated if size changed.
2923  */
2924 /* ARGSUSED */
2925 static int
2926 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2927     caller_context_t *ct)
2928 {
2929 	znode_t		*zp = VTOZ(vp);
2930 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2931 	objset_t	*os = zfsvfs->z_os;
2932 	zilog_t		*zilog;
2933 	dmu_tx_t	*tx;
2934 	vattr_t		oldva;
2935 	xvattr_t	tmpxvattr;
2936 	uint_t		mask = vap->va_mask;
2937 	uint_t		saved_mask = 0;
2938 	int		trim_mask = 0;
2939 	uint64_t	new_mode;
2940 	uint64_t	new_uid, new_gid;
2941 	uint64_t	xattr_obj;
2942 	uint64_t	mtime[2], ctime[2];
2943 	uint64_t	projid = ZFS_INVALID_PROJID;
2944 	znode_t		*attrzp;
2945 	int		need_policy = FALSE;
2946 	int		err, err2 = 0;
2947 	zfs_fuid_info_t *fuidp = NULL;
2948 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2949 	xoptattr_t	*xoap;
2950 	zfs_acl_t	*aclp;
2951 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2952 	boolean_t	fuid_dirtied = B_FALSE;
2953 	boolean_t	handle_eadir = B_FALSE;
2954 	sa_bulk_attr_t	bulk[8], xattr_bulk[8];
2955 	int		count = 0, xattr_count = 0;
2956 
2957 	if (mask == 0)
2958 		return (0);
2959 
2960 	if (mask & AT_NOSET)
2961 		return (SET_ERROR(EINVAL));
2962 
2963 	ZFS_ENTER(zfsvfs);
2964 	ZFS_VERIFY_ZP(zp);
2965 
2966 	/*
2967 	 * If this is a xvattr_t, then get a pointer to the structure of
2968 	 * optional attributes.  If this is NULL, then we have a vattr_t.
2969 	 */
2970 	xoap = xva_getxoptattr(xvap);
2971 	if (xoap != NULL && (mask & AT_XVATTR)) {
2972 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2973 			if (!dmu_objset_projectquota_enabled(os) ||
2974 			    (vp->v_type != VREG && vp->v_type != VDIR)) {
2975 				ZFS_EXIT(zfsvfs);
2976 				return (SET_ERROR(ENOTSUP));
2977 			}
2978 
2979 			projid = xoap->xoa_projid;
2980 			if (unlikely(projid == ZFS_INVALID_PROJID)) {
2981 				ZFS_EXIT(zfsvfs);
2982 				return (SET_ERROR(EINVAL));
2983 			}
2984 
2985 			if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID)
2986 				projid = ZFS_INVALID_PROJID;
2987 			else
2988 				need_policy = TRUE;
2989 		}
2990 
2991 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) &&
2992 		    (!dmu_objset_projectquota_enabled(os) ||
2993 		    (vp->v_type != VREG && vp->v_type != VDIR))) {
2994 				ZFS_EXIT(zfsvfs);
2995 				return (SET_ERROR(ENOTSUP));
2996 		}
2997 	}
2998 
2999 	zilog = zfsvfs->z_log;
3000 
3001 	/*
3002 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
3003 	 * that file system is at proper version level
3004 	 */
3005 
3006 	if (zfsvfs->z_use_fuids == B_FALSE &&
3007 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
3008 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
3009 	    (mask & AT_XVATTR))) {
3010 		ZFS_EXIT(zfsvfs);
3011 		return (SET_ERROR(EINVAL));
3012 	}
3013 
3014 	if (mask & AT_SIZE && vp->v_type == VDIR) {
3015 		ZFS_EXIT(zfsvfs);
3016 		return (SET_ERROR(EISDIR));
3017 	}
3018 
3019 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
3020 		ZFS_EXIT(zfsvfs);
3021 		return (SET_ERROR(EINVAL));
3022 	}
3023 
3024 	xva_init(&tmpxvattr);
3025 
3026 	/*
3027 	 * Immutable files can only alter immutable bit and atime
3028 	 */
3029 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
3030 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
3031 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
3032 		ZFS_EXIT(zfsvfs);
3033 		return (SET_ERROR(EPERM));
3034 	}
3035 
3036 	/*
3037 	 * Note: ZFS_READONLY is handled in zfs_zaccess_common.
3038 	 */
3039 
3040 	/*
3041 	 * Verify timestamps doesn't overflow 32 bits.
3042 	 * ZFS can handle large timestamps, but 32bit syscalls can't
3043 	 * handle times greater than 2039.  This check should be removed
3044 	 * once large timestamps are fully supported.
3045 	 */
3046 	if (mask & (AT_ATIME | AT_MTIME)) {
3047 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
3048 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
3049 			ZFS_EXIT(zfsvfs);
3050 			return (SET_ERROR(EOVERFLOW));
3051 		}
3052 	}
3053 
3054 top:
3055 	attrzp = NULL;
3056 	aclp = NULL;
3057 
3058 	/* Can this be moved to before the top label? */
3059 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
3060 		ZFS_EXIT(zfsvfs);
3061 		return (SET_ERROR(EROFS));
3062 	}
3063 
3064 	/*
3065 	 * First validate permissions
3066 	 */
3067 
3068 	if (mask & AT_SIZE) {
3069 		err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
3070 		if (err) {
3071 			ZFS_EXIT(zfsvfs);
3072 			return (err);
3073 		}
3074 		/*
3075 		 * XXX - Note, we are not providing any open
3076 		 * mode flags here (like FNDELAY), so we may
3077 		 * block if there are locks present... this
3078 		 * should be addressed in openat().
3079 		 */
3080 		/* XXX - would it be OK to generate a log record here? */
3081 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
3082 		if (err) {
3083 			ZFS_EXIT(zfsvfs);
3084 			return (err);
3085 		}
3086 
3087 		if (vap->va_size == 0)
3088 			vnevent_truncate(ZTOV(zp), ct);
3089 	}
3090 
3091 	if (mask & (AT_ATIME|AT_MTIME) ||
3092 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
3093 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
3094 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
3095 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
3096 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
3097 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
3098 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
3099 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
3100 		    skipaclchk, cr);
3101 	}
3102 
3103 	if (mask & (AT_UID|AT_GID)) {
3104 		int	idmask = (mask & (AT_UID|AT_GID));
3105 		int	take_owner;
3106 		int	take_group;
3107 
3108 		/*
3109 		 * NOTE: even if a new mode is being set,
3110 		 * we may clear S_ISUID/S_ISGID bits.
3111 		 */
3112 
3113 		if (!(mask & AT_MODE))
3114 			vap->va_mode = zp->z_mode;
3115 
3116 		/*
3117 		 * Take ownership or chgrp to group we are a member of
3118 		 */
3119 
3120 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
3121 		take_group = (mask & AT_GID) &&
3122 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
3123 
3124 		/*
3125 		 * If both AT_UID and AT_GID are set then take_owner and
3126 		 * take_group must both be set in order to allow taking
3127 		 * ownership.
3128 		 *
3129 		 * Otherwise, send the check through secpolicy_vnode_setattr()
3130 		 *
3131 		 */
3132 
3133 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
3134 		    ((idmask == AT_UID) && take_owner) ||
3135 		    ((idmask == AT_GID) && take_group)) {
3136 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
3137 			    skipaclchk, cr) == 0) {
3138 				/*
3139 				 * Remove setuid/setgid for non-privileged users
3140 				 */
3141 				secpolicy_setid_clear(vap, cr);
3142 				trim_mask = (mask & (AT_UID|AT_GID));
3143 			} else {
3144 				need_policy =  TRUE;
3145 			}
3146 		} else {
3147 			need_policy =  TRUE;
3148 		}
3149 	}
3150 
3151 	mutex_enter(&zp->z_lock);
3152 	oldva.va_mode = zp->z_mode;
3153 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
3154 	if (mask & AT_XVATTR) {
3155 		/*
3156 		 * Update xvattr mask to include only those attributes
3157 		 * that are actually changing.
3158 		 *
3159 		 * the bits will be restored prior to actually setting
3160 		 * the attributes so the caller thinks they were set.
3161 		 */
3162 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
3163 			if (xoap->xoa_appendonly !=
3164 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
3165 				need_policy = TRUE;
3166 			} else {
3167 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
3168 				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
3169 			}
3170 		}
3171 
3172 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
3173 			if (xoap->xoa_projinherit !=
3174 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) {
3175 				need_policy = TRUE;
3176 			} else {
3177 				XVA_CLR_REQ(xvap, XAT_PROJINHERIT);
3178 				XVA_SET_REQ(&tmpxvattr, XAT_PROJINHERIT);
3179 			}
3180 		}
3181 
3182 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
3183 			if (xoap->xoa_nounlink !=
3184 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
3185 				need_policy = TRUE;
3186 			} else {
3187 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
3188 				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
3189 			}
3190 		}
3191 
3192 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
3193 			if (xoap->xoa_immutable !=
3194 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
3195 				need_policy = TRUE;
3196 			} else {
3197 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
3198 				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
3199 			}
3200 		}
3201 
3202 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
3203 			if (xoap->xoa_nodump !=
3204 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
3205 				need_policy = TRUE;
3206 			} else {
3207 				XVA_CLR_REQ(xvap, XAT_NODUMP);
3208 				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
3209 			}
3210 		}
3211 
3212 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
3213 			if (xoap->xoa_av_modified !=
3214 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
3215 				need_policy = TRUE;
3216 			} else {
3217 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
3218 				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
3219 			}
3220 		}
3221 
3222 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
3223 			if ((vp->v_type != VREG &&
3224 			    xoap->xoa_av_quarantined) ||
3225 			    xoap->xoa_av_quarantined !=
3226 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
3227 				need_policy = TRUE;
3228 			} else {
3229 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
3230 				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
3231 			}
3232 		}
3233 
3234 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
3235 			mutex_exit(&zp->z_lock);
3236 			ZFS_EXIT(zfsvfs);
3237 			return (SET_ERROR(EPERM));
3238 		}
3239 
3240 		if (need_policy == FALSE &&
3241 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
3242 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
3243 			need_policy = TRUE;
3244 		}
3245 	}
3246 
3247 	mutex_exit(&zp->z_lock);
3248 
3249 	if (mask & AT_MODE) {
3250 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
3251 			err = secpolicy_setid_setsticky_clear(vp, vap,
3252 			    &oldva, cr);
3253 			if (err) {
3254 				ZFS_EXIT(zfsvfs);
3255 				return (err);
3256 			}
3257 			trim_mask |= AT_MODE;
3258 		} else {
3259 			need_policy = TRUE;
3260 		}
3261 	}
3262 
3263 	if (need_policy) {
3264 		/*
3265 		 * If trim_mask is set then take ownership
3266 		 * has been granted or write_acl is present and user
3267 		 * has the ability to modify mode.  In that case remove
3268 		 * UID|GID and or MODE from mask so that
3269 		 * secpolicy_vnode_setattr() doesn't revoke it.
3270 		 */
3271 
3272 		if (trim_mask) {
3273 			saved_mask = vap->va_mask;
3274 			vap->va_mask &= ~trim_mask;
3275 		}
3276 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
3277 		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
3278 		if (err) {
3279 			ZFS_EXIT(zfsvfs);
3280 			return (err);
3281 		}
3282 
3283 		if (trim_mask)
3284 			vap->va_mask |= saved_mask;
3285 	}
3286 
3287 	/*
3288 	 * secpolicy_vnode_setattr, or take ownership may have
3289 	 * changed va_mask
3290 	 */
3291 	mask = vap->va_mask;
3292 
3293 	if ((mask & (AT_UID | AT_GID)) || projid != ZFS_INVALID_PROJID) {
3294 		handle_eadir = B_TRUE;
3295 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
3296 		    &xattr_obj, sizeof (xattr_obj));
3297 
3298 		if (err == 0 && xattr_obj) {
3299 			err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
3300 			if (err)
3301 				goto out2;
3302 		}
3303 		if (mask & AT_UID) {
3304 			new_uid = zfs_fuid_create(zfsvfs,
3305 			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3306 			if (new_uid != zp->z_uid &&
3307 			    zfs_id_overquota(zfsvfs, DMU_USERUSED_OBJECT,
3308 			    new_uid)) {
3309 				if (attrzp)
3310 					VN_RELE(ZTOV(attrzp));
3311 				err = SET_ERROR(EDQUOT);
3312 				goto out2;
3313 			}
3314 		}
3315 
3316 		if (mask & AT_GID) {
3317 			new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3318 			    cr, ZFS_GROUP, &fuidp);
3319 			if (new_gid != zp->z_gid &&
3320 			    zfs_id_overquota(zfsvfs, DMU_GROUPUSED_OBJECT,
3321 			    new_gid)) {
3322 				if (attrzp)
3323 					VN_RELE(ZTOV(attrzp));
3324 				err = SET_ERROR(EDQUOT);
3325 				goto out2;
3326 			}
3327 		}
3328 
3329 		if (projid != ZFS_INVALID_PROJID &&
3330 		    zfs_id_overquota(zfsvfs, DMU_PROJECTUSED_OBJECT, projid)) {
3331 			if (attrzp)
3332 				VN_RELE(ZTOV(attrzp));
3333 			err = EDQUOT;
3334 			goto out2;
3335 		}
3336 	}
3337 	tx = dmu_tx_create(os);
3338 
3339 	if (mask & AT_MODE) {
3340 		uint64_t pmode = zp->z_mode;
3341 		uint64_t acl_obj;
3342 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3343 
3344 		if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
3345 		    !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
3346 			err = SET_ERROR(EPERM);
3347 			goto out;
3348 		}
3349 
3350 		if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3351 			goto out;
3352 
3353 		mutex_enter(&zp->z_lock);
3354 		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
3355 			/*
3356 			 * Are we upgrading ACL from old V0 format
3357 			 * to V1 format?
3358 			 */
3359 			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
3360 			    zfs_znode_acl_version(zp) ==
3361 			    ZFS_ACL_VERSION_INITIAL) {
3362 				dmu_tx_hold_free(tx, acl_obj, 0,
3363 				    DMU_OBJECT_END);
3364 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3365 				    0, aclp->z_acl_bytes);
3366 			} else {
3367 				dmu_tx_hold_write(tx, acl_obj, 0,
3368 				    aclp->z_acl_bytes);
3369 			}
3370 		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3371 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3372 			    0, aclp->z_acl_bytes);
3373 		}
3374 		mutex_exit(&zp->z_lock);
3375 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3376 	} else {
3377 		if (((mask & AT_XVATTR) &&
3378 		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) ||
3379 		    (projid != ZFS_INVALID_PROJID &&
3380 		    !(zp->z_pflags & ZFS_PROJID)))
3381 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3382 		else
3383 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3384 	}
3385 
3386 	if (attrzp) {
3387 		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
3388 	}
3389 
3390 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3391 	if (fuid_dirtied)
3392 		zfs_fuid_txhold(zfsvfs, tx);
3393 
3394 	zfs_sa_upgrade_txholds(tx, zp);
3395 
3396 	err = dmu_tx_assign(tx, TXG_WAIT);
3397 	if (err)
3398 		goto out;
3399 
3400 	count = 0;
3401 	/*
3402 	 * Set each attribute requested.
3403 	 * We group settings according to the locks they need to acquire.
3404 	 *
3405 	 * Note: you cannot set ctime directly, although it will be
3406 	 * updated as a side-effect of calling this function.
3407 	 */
3408 
3409 	if (projid != ZFS_INVALID_PROJID && !(zp->z_pflags & ZFS_PROJID)) {
3410 		/*
3411 		 * For the existing object that is upgraded from old system,
3412 		 * its on-disk layout has no slot for the project ID attribute.
3413 		 * But quota accounting logic needs to access related slots by
3414 		 * offset directly. So we need to adjust old objects' layout
3415 		 * to make the project ID to some unified and fixed offset.
3416 		 */
3417 		if (attrzp)
3418 			err = sa_add_projid(attrzp->z_sa_hdl, tx, projid);
3419 		if (err == 0)
3420 			err = sa_add_projid(zp->z_sa_hdl, tx, projid);
3421 
3422 		if (unlikely(err == EEXIST))
3423 			err = 0;
3424 		else if (err != 0)
3425 			goto out;
3426 		else
3427 			projid = ZFS_INVALID_PROJID;
3428 	}
3429 
3430 	if (mask & (AT_UID|AT_GID|AT_MODE))
3431 		mutex_enter(&zp->z_acl_lock);
3432 	mutex_enter(&zp->z_lock);
3433 
3434 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3435 	    &zp->z_pflags, sizeof (zp->z_pflags));
3436 
3437 	if (attrzp) {
3438 		if (mask & (AT_UID|AT_GID|AT_MODE))
3439 			mutex_enter(&attrzp->z_acl_lock);
3440 		mutex_enter(&attrzp->z_lock);
3441 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3442 		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
3443 		    sizeof (attrzp->z_pflags));
3444 		if (projid != ZFS_INVALID_PROJID) {
3445 			attrzp->z_projid = projid;
3446 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3447 			    SA_ZPL_PROJID(zfsvfs), NULL, &attrzp->z_projid,
3448 			    sizeof (attrzp->z_projid));
3449 		}
3450 	}
3451 
3452 	if (mask & (AT_UID|AT_GID)) {
3453 
3454 		if (mask & AT_UID) {
3455 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
3456 			    &new_uid, sizeof (new_uid));
3457 			zp->z_uid = new_uid;
3458 			if (attrzp) {
3459 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3460 				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
3461 				    sizeof (new_uid));
3462 				attrzp->z_uid = new_uid;
3463 			}
3464 		}
3465 
3466 		if (mask & AT_GID) {
3467 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
3468 			    NULL, &new_gid, sizeof (new_gid));
3469 			zp->z_gid = new_gid;
3470 			if (attrzp) {
3471 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3472 				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
3473 				    sizeof (new_gid));
3474 				attrzp->z_gid = new_gid;
3475 			}
3476 		}
3477 		if (!(mask & AT_MODE)) {
3478 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
3479 			    NULL, &new_mode, sizeof (new_mode));
3480 			new_mode = zp->z_mode;
3481 		}
3482 		err = zfs_acl_chown_setattr(zp);
3483 		ASSERT(err == 0);
3484 		if (attrzp) {
3485 			err = zfs_acl_chown_setattr(attrzp);
3486 			ASSERT(err == 0);
3487 		}
3488 	}
3489 
3490 	if (mask & AT_MODE) {
3491 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
3492 		    &new_mode, sizeof (new_mode));
3493 		zp->z_mode = new_mode;
3494 		ASSERT3U((uintptr_t)aclp, !=, NULL);
3495 		err = zfs_aclset_common(zp, aclp, cr, tx);
3496 		ASSERT0(err);
3497 		if (zp->z_acl_cached)
3498 			zfs_acl_free(zp->z_acl_cached);
3499 		zp->z_acl_cached = aclp;
3500 		aclp = NULL;
3501 	}
3502 
3503 
3504 	if (mask & AT_ATIME) {
3505 		ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
3506 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
3507 		    &zp->z_atime, sizeof (zp->z_atime));
3508 	}
3509 
3510 	if (mask & AT_MTIME) {
3511 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3512 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3513 		    mtime, sizeof (mtime));
3514 	}
3515 
3516 	/* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3517 	if (mask & AT_SIZE && !(mask & AT_MTIME)) {
3518 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
3519 		    NULL, mtime, sizeof (mtime));
3520 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3521 		    &ctime, sizeof (ctime));
3522 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3523 		    B_TRUE);
3524 	} else if (mask != 0) {
3525 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3526 		    &ctime, sizeof (ctime));
3527 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
3528 		    B_TRUE);
3529 		if (attrzp) {
3530 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3531 			    SA_ZPL_CTIME(zfsvfs), NULL,
3532 			    &ctime, sizeof (ctime));
3533 			zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3534 			    mtime, ctime, B_TRUE);
3535 		}
3536 	}
3537 
3538 	if (projid != ZFS_INVALID_PROJID) {
3539 		zp->z_projid = projid;
3540 		SA_ADD_BULK_ATTR(bulk, count,
3541 		    SA_ZPL_PROJID(zfsvfs), NULL, &zp->z_projid,
3542 		    sizeof (zp->z_projid));
3543 	}
3544 
3545 	/*
3546 	 * Do this after setting timestamps to prevent timestamp
3547 	 * update from toggling bit
3548 	 */
3549 
3550 	if (xoap && (mask & AT_XVATTR)) {
3551 
3552 		/*
3553 		 * restore trimmed off masks
3554 		 * so that return masks can be set for caller.
3555 		 */
3556 
3557 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3558 			XVA_SET_REQ(xvap, XAT_APPENDONLY);
3559 		}
3560 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3561 			XVA_SET_REQ(xvap, XAT_NOUNLINK);
3562 		}
3563 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3564 			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3565 		}
3566 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3567 			XVA_SET_REQ(xvap, XAT_NODUMP);
3568 		}
3569 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3570 			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3571 		}
3572 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3573 			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3574 		}
3575 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_PROJINHERIT)) {
3576 			XVA_SET_REQ(xvap, XAT_PROJINHERIT);
3577 		}
3578 
3579 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3580 			ASSERT(vp->v_type == VREG);
3581 
3582 		zfs_xvattr_set(zp, xvap, tx);
3583 	}
3584 
3585 	if (fuid_dirtied)
3586 		zfs_fuid_sync(zfsvfs, tx);
3587 
3588 	if (mask != 0)
3589 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3590 
3591 	mutex_exit(&zp->z_lock);
3592 	if (mask & (AT_UID|AT_GID|AT_MODE))
3593 		mutex_exit(&zp->z_acl_lock);
3594 
3595 	if (attrzp) {
3596 		if (mask & (AT_UID|AT_GID|AT_MODE))
3597 			mutex_exit(&attrzp->z_acl_lock);
3598 		mutex_exit(&attrzp->z_lock);
3599 	}
3600 out:
3601 	if (err == 0 && xattr_count > 0) {
3602 		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3603 		    xattr_count, tx);
3604 		ASSERT(err2 == 0);
3605 	}
3606 
3607 	if (aclp)
3608 		zfs_acl_free(aclp);
3609 
3610 	if (fuidp) {
3611 		zfs_fuid_info_free(fuidp);
3612 		fuidp = NULL;
3613 	}
3614 
3615 	if (err) {
3616 		dmu_tx_abort(tx);
3617 		if (attrzp)
3618 			VN_RELE(ZTOV(attrzp));
3619 		if (err == ERESTART)
3620 			goto top;
3621 	} else {
3622 		if (count > 0)
3623 			err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3624 		dmu_tx_commit(tx);
3625 		if (attrzp) {
3626 			if (err2 == 0 && handle_eadir)
3627 				err2 = zfs_setattr_dir(attrzp);
3628 			VN_RELE(ZTOV(attrzp));
3629 		}
3630 	}
3631 
3632 out2:
3633 	if (os->os_sync == ZFS_SYNC_ALWAYS)
3634 		zil_commit(zilog, 0);
3635 
3636 	ZFS_EXIT(zfsvfs);
3637 	return (err);
3638 }
3639 
3640 typedef struct zfs_zlock {
3641 	krwlock_t	*zl_rwlock;	/* lock we acquired */
3642 	znode_t		*zl_znode;	/* znode we held */
3643 	struct zfs_zlock *zl_next;	/* next in list */
3644 } zfs_zlock_t;
3645 
3646 /*
3647  * Drop locks and release vnodes that were held by zfs_rename_lock().
3648  */
3649 static void
3650 zfs_rename_unlock(zfs_zlock_t **zlpp)
3651 {
3652 	zfs_zlock_t *zl;
3653 
3654 	while ((zl = *zlpp) != NULL) {
3655 		if (zl->zl_znode != NULL)
3656 			VN_RELE(ZTOV(zl->zl_znode));
3657 		rw_exit(zl->zl_rwlock);
3658 		*zlpp = zl->zl_next;
3659 		kmem_free(zl, sizeof (*zl));
3660 	}
3661 }
3662 
3663 /*
3664  * Search back through the directory tree, using the ".." entries.
3665  * Lock each directory in the chain to prevent concurrent renames.
3666  * Fail any attempt to move a directory into one of its own descendants.
3667  * XXX - z_parent_lock can overlap with map or grow locks
3668  */
3669 static int
3670 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3671 {
3672 	zfs_zlock_t	*zl;
3673 	znode_t		*zp = tdzp;
3674 	uint64_t	rootid = zp->z_zfsvfs->z_root;
3675 	uint64_t	oidp = zp->z_id;
3676 	krwlock_t	*rwlp = &szp->z_parent_lock;
3677 	krw_t		rw = RW_WRITER;
3678 
3679 	/*
3680 	 * First pass write-locks szp and compares to zp->z_id.
3681 	 * Later passes read-lock zp and compare to zp->z_parent.
3682 	 */
3683 	do {
3684 		if (!rw_tryenter(rwlp, rw)) {
3685 			/*
3686 			 * Another thread is renaming in this path.
3687 			 * Note that if we are a WRITER, we don't have any
3688 			 * parent_locks held yet.
3689 			 */
3690 			if (rw == RW_READER && zp->z_id > szp->z_id) {
3691 				/*
3692 				 * Drop our locks and restart
3693 				 */
3694 				zfs_rename_unlock(&zl);
3695 				*zlpp = NULL;
3696 				zp = tdzp;
3697 				oidp = zp->z_id;
3698 				rwlp = &szp->z_parent_lock;
3699 				rw = RW_WRITER;
3700 				continue;
3701 			} else {
3702 				/*
3703 				 * Wait for other thread to drop its locks
3704 				 */
3705 				rw_enter(rwlp, rw);
3706 			}
3707 		}
3708 
3709 		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3710 		zl->zl_rwlock = rwlp;
3711 		zl->zl_znode = NULL;
3712 		zl->zl_next = *zlpp;
3713 		*zlpp = zl;
3714 
3715 		if (oidp == szp->z_id)		/* We're a descendant of szp */
3716 			return (SET_ERROR(EINVAL));
3717 
3718 		if (oidp == rootid)		/* We've hit the top */
3719 			return (0);
3720 
3721 		if (rw == RW_READER) {		/* i.e. not the first pass */
3722 			int error = zfs_zget(zp->z_zfsvfs, oidp, &zp);
3723 			if (error)
3724 				return (error);
3725 			zl->zl_znode = zp;
3726 		}
3727 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zp->z_zfsvfs),
3728 		    &oidp, sizeof (oidp));
3729 		rwlp = &zp->z_parent_lock;
3730 		rw = RW_READER;
3731 
3732 	} while (zp->z_id != sdzp->z_id);
3733 
3734 	return (0);
3735 }
3736 
3737 /*
3738  * Move an entry from the provided source directory to the target
3739  * directory.  Change the entry name as indicated.
3740  *
3741  *	IN:	sdvp	- Source directory containing the "old entry".
3742  *		snm	- Old entry name.
3743  *		tdvp	- Target directory to contain the "new entry".
3744  *		tnm	- New entry name.
3745  *		cr	- credentials of caller.
3746  *		ct	- caller context
3747  *		flags	- case flags
3748  *
3749  *	RETURN:	0 on success, error code on failure.
3750  *
3751  * Timestamps:
3752  *	sdvp,tdvp - ctime|mtime updated
3753  */
3754 /*ARGSUSED*/
3755 static int
3756 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
3757     caller_context_t *ct, int flags)
3758 {
3759 	znode_t		*tdzp, *szp, *tzp;
3760 	znode_t		*sdzp = VTOZ(sdvp);
3761 	zfsvfs_t	*zfsvfs = sdzp->z_zfsvfs;
3762 	zilog_t		*zilog;
3763 	vnode_t		*realvp;
3764 	zfs_dirlock_t	*sdl, *tdl;
3765 	dmu_tx_t	*tx;
3766 	zfs_zlock_t	*zl;
3767 	int		cmp, serr, terr;
3768 	int		error = 0, rm_err = 0;
3769 	int		zflg = 0;
3770 	boolean_t	waited = B_FALSE;
3771 
3772 	ZFS_ENTER(zfsvfs);
3773 	ZFS_VERIFY_ZP(sdzp);
3774 	zilog = zfsvfs->z_log;
3775 
3776 	/*
3777 	 * Make sure we have the real vp for the target directory.
3778 	 */
3779 	if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3780 		tdvp = realvp;
3781 
3782 	tdzp = VTOZ(tdvp);
3783 	ZFS_VERIFY_ZP(tdzp);
3784 
3785 	/*
3786 	 * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
3787 	 * ctldir appear to have the same v_vfsp.
3788 	 */
3789 	if (tdzp->z_zfsvfs != zfsvfs || zfsctl_is_node(tdvp)) {
3790 		ZFS_EXIT(zfsvfs);
3791 		return (SET_ERROR(EXDEV));
3792 	}
3793 
3794 	if (zfsvfs->z_utf8 && u8_validate(tnm,
3795 	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3796 		ZFS_EXIT(zfsvfs);
3797 		return (SET_ERROR(EILSEQ));
3798 	}
3799 
3800 	if (flags & FIGNORECASE)
3801 		zflg |= ZCILOOK;
3802 
3803 top:
3804 	szp = NULL;
3805 	tzp = NULL;
3806 	zl = NULL;
3807 
3808 	/*
3809 	 * This is to prevent the creation of links into attribute space
3810 	 * by renaming a linked file into/outof an attribute directory.
3811 	 * See the comment in zfs_link() for why this is considered bad.
3812 	 */
3813 	if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3814 		ZFS_EXIT(zfsvfs);
3815 		return (SET_ERROR(EINVAL));
3816 	}
3817 
3818 	/*
3819 	 * Lock source and target directory entries.  To prevent deadlock,
3820 	 * a lock ordering must be defined.  We lock the directory with
3821 	 * the smallest object id first, or if it's a tie, the one with
3822 	 * the lexically first name.
3823 	 */
3824 	if (sdzp->z_id < tdzp->z_id) {
3825 		cmp = -1;
3826 	} else if (sdzp->z_id > tdzp->z_id) {
3827 		cmp = 1;
3828 	} else {
3829 		/*
3830 		 * First compare the two name arguments without
3831 		 * considering any case folding.
3832 		 */
3833 		int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
3834 
3835 		cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3836 		ASSERT(error == 0 || !zfsvfs->z_utf8);
3837 		if (cmp == 0) {
3838 			/*
3839 			 * POSIX: "If the old argument and the new argument
3840 			 * both refer to links to the same existing file,
3841 			 * the rename() function shall return successfully
3842 			 * and perform no other action."
3843 			 */
3844 			ZFS_EXIT(zfsvfs);
3845 			return (0);
3846 		}
3847 		/*
3848 		 * If the file system is case-folding, then we may
3849 		 * have some more checking to do.  A case-folding file
3850 		 * system is either supporting mixed case sensitivity
3851 		 * access or is completely case-insensitive.  Note
3852 		 * that the file system is always case preserving.
3853 		 *
3854 		 * In mixed sensitivity mode case sensitive behavior
3855 		 * is the default.  FIGNORECASE must be used to
3856 		 * explicitly request case insensitive behavior.
3857 		 *
3858 		 * If the source and target names provided differ only
3859 		 * by case (e.g., a request to rename 'tim' to 'Tim'),
3860 		 * we will treat this as a special case in the
3861 		 * case-insensitive mode: as long as the source name
3862 		 * is an exact match, we will allow this to proceed as
3863 		 * a name-change request.
3864 		 */
3865 		if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
3866 		    (zfsvfs->z_case == ZFS_CASE_MIXED &&
3867 		    flags & FIGNORECASE)) &&
3868 		    u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
3869 		    &error) == 0) {
3870 			/*
3871 			 * case preserving rename request, require exact
3872 			 * name matches
3873 			 */
3874 			zflg |= ZCIEXACT;
3875 			zflg &= ~ZCILOOK;
3876 		}
3877 	}
3878 
3879 	/*
3880 	 * If the source and destination directories are the same, we should
3881 	 * grab the z_name_lock of that directory only once.
3882 	 */
3883 	if (sdzp == tdzp) {
3884 		zflg |= ZHAVELOCK;
3885 		rw_enter(&sdzp->z_name_lock, RW_READER);
3886 	}
3887 
3888 	if (cmp < 0) {
3889 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3890 		    ZEXISTS | zflg, NULL, NULL);
3891 		terr = zfs_dirent_lock(&tdl,
3892 		    tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3893 	} else {
3894 		terr = zfs_dirent_lock(&tdl,
3895 		    tdzp, tnm, &tzp, zflg, NULL, NULL);
3896 		serr = zfs_dirent_lock(&sdl,
3897 		    sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3898 		    NULL, NULL);
3899 	}
3900 
3901 	if (serr) {
3902 		/*
3903 		 * Source entry invalid or not there.
3904 		 */
3905 		if (!terr) {
3906 			zfs_dirent_unlock(tdl);
3907 			if (tzp)
3908 				VN_RELE(ZTOV(tzp));
3909 		}
3910 
3911 		if (sdzp == tdzp)
3912 			rw_exit(&sdzp->z_name_lock);
3913 
3914 		if (strcmp(snm, "..") == 0)
3915 			serr = SET_ERROR(EINVAL);
3916 		ZFS_EXIT(zfsvfs);
3917 		return (serr);
3918 	}
3919 	if (terr) {
3920 		zfs_dirent_unlock(sdl);
3921 		VN_RELE(ZTOV(szp));
3922 
3923 		if (sdzp == tdzp)
3924 			rw_exit(&sdzp->z_name_lock);
3925 
3926 		if (strcmp(tnm, "..") == 0)
3927 			terr = SET_ERROR(EINVAL);
3928 		ZFS_EXIT(zfsvfs);
3929 		return (terr);
3930 	}
3931 
3932 	/*
3933 	 * If we are using project inheritance, it means if the directory has
3934 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
3935 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3936 	 * such case, we only allow renames into our tree when the project
3937 	 * IDs are the same.
3938 	 */
3939 	if (tdzp->z_pflags & ZFS_PROJINHERIT &&
3940 	    tdzp->z_projid != szp->z_projid) {
3941 		error = SET_ERROR(EXDEV);
3942 		goto out;
3943 	}
3944 
3945 	/*
3946 	 * Must have write access at the source to remove the old entry
3947 	 * and write access at the target to create the new entry.
3948 	 * Note that if target and source are the same, this can be
3949 	 * done in a single check.
3950 	 */
3951 
3952 	if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
3953 		goto out;
3954 
3955 	if (ZTOV(szp)->v_type == VDIR) {
3956 		/*
3957 		 * Check to make sure rename is valid.
3958 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3959 		 */
3960 		if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
3961 			goto out;
3962 	}
3963 
3964 	/*
3965 	 * Does target exist?
3966 	 */
3967 	if (tzp) {
3968 		/*
3969 		 * Source and target must be the same type.
3970 		 */
3971 		if (ZTOV(szp)->v_type == VDIR) {
3972 			if (ZTOV(tzp)->v_type != VDIR) {
3973 				error = SET_ERROR(ENOTDIR);
3974 				goto out;
3975 			}
3976 		} else {
3977 			if (ZTOV(tzp)->v_type == VDIR) {
3978 				error = SET_ERROR(EISDIR);
3979 				goto out;
3980 			}
3981 		}
3982 		/*
3983 		 * POSIX dictates that when the source and target
3984 		 * entries refer to the same file object, rename
3985 		 * must do nothing and exit without error.
3986 		 */
3987 		if (szp->z_id == tzp->z_id) {
3988 			error = 0;
3989 			goto out;
3990 		}
3991 	}
3992 
3993 	vnevent_pre_rename_src(ZTOV(szp), sdvp, snm, ct);
3994 	if (tzp)
3995 		vnevent_pre_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3996 
3997 	/*
3998 	 * notify the target directory if it is not the same
3999 	 * as source directory.
4000 	 */
4001 	if (tdvp != sdvp) {
4002 		vnevent_pre_rename_dest_dir(tdvp, ZTOV(szp), tnm, ct);
4003 	}
4004 
4005 	tx = dmu_tx_create(zfsvfs->z_os);
4006 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
4007 	dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
4008 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
4009 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
4010 	if (sdzp != tdzp) {
4011 		dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
4012 		zfs_sa_upgrade_txholds(tx, tdzp);
4013 	}
4014 	if (tzp) {
4015 		dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
4016 		zfs_sa_upgrade_txholds(tx, tzp);
4017 	}
4018 
4019 	zfs_sa_upgrade_txholds(tx, szp);
4020 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
4021 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
4022 	if (error) {
4023 		if (zl != NULL)
4024 			zfs_rename_unlock(&zl);
4025 		zfs_dirent_unlock(sdl);
4026 		zfs_dirent_unlock(tdl);
4027 
4028 		if (sdzp == tdzp)
4029 			rw_exit(&sdzp->z_name_lock);
4030 
4031 		VN_RELE(ZTOV(szp));
4032 		if (tzp)
4033 			VN_RELE(ZTOV(tzp));
4034 		if (error == ERESTART) {
4035 			waited = B_TRUE;
4036 			dmu_tx_wait(tx);
4037 			dmu_tx_abort(tx);
4038 			goto top;
4039 		}
4040 		dmu_tx_abort(tx);
4041 		ZFS_EXIT(zfsvfs);
4042 		return (error);
4043 	}
4044 
4045 	if (tzp)	/* Attempt to remove the existing target */
4046 		error = rm_err = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
4047 
4048 	if (error == 0) {
4049 		error = zfs_link_create(tdl, szp, tx, ZRENAMING);
4050 		if (error == 0) {
4051 			szp->z_pflags |= ZFS_AV_MODIFIED;
4052 			if (tdzp->z_pflags & ZFS_PROJINHERIT)
4053 				szp->z_pflags |= ZFS_PROJINHERIT;
4054 
4055 			error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
4056 			    (void *)&szp->z_pflags, sizeof (uint64_t), tx);
4057 			ASSERT0(error);
4058 
4059 			error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
4060 			if (error == 0) {
4061 				zfs_log_rename(zilog, tx, TX_RENAME |
4062 				    (flags & FIGNORECASE ? TX_CI : 0), sdzp,
4063 				    sdl->dl_name, tdzp, tdl->dl_name, szp);
4064 
4065 				/*
4066 				 * Update path information for the target vnode
4067 				 */
4068 				vn_renamepath(tdvp, ZTOV(szp), tnm,
4069 				    strlen(tnm));
4070 			} else {
4071 				/*
4072 				 * At this point, we have successfully created
4073 				 * the target name, but have failed to remove
4074 				 * the source name.  Since the create was done
4075 				 * with the ZRENAMING flag, there are
4076 				 * complications; for one, the link count is
4077 				 * wrong.  The easiest way to deal with this
4078 				 * is to remove the newly created target, and
4079 				 * return the original error.  This must
4080 				 * succeed; fortunately, it is very unlikely to
4081 				 * fail, since we just created it.
4082 				 */
4083 				VERIFY3U(zfs_link_destroy(tdl, szp, tx,
4084 				    ZRENAMING, NULL), ==, 0);
4085 			}
4086 		}
4087 	}
4088 
4089 	dmu_tx_commit(tx);
4090 
4091 	if (tzp && rm_err == 0)
4092 		vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
4093 
4094 	if (error == 0) {
4095 		vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
4096 		/* notify the target dir if it is not the same as source dir */
4097 		if (tdvp != sdvp)
4098 			vnevent_rename_dest_dir(tdvp, ct);
4099 	}
4100 out:
4101 	if (zl != NULL)
4102 		zfs_rename_unlock(&zl);
4103 
4104 	zfs_dirent_unlock(sdl);
4105 	zfs_dirent_unlock(tdl);
4106 
4107 	if (sdzp == tdzp)
4108 		rw_exit(&sdzp->z_name_lock);
4109 
4110 
4111 	VN_RELE(ZTOV(szp));
4112 	if (tzp)
4113 		VN_RELE(ZTOV(tzp));
4114 
4115 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4116 		zil_commit(zilog, 0);
4117 
4118 	ZFS_EXIT(zfsvfs);
4119 	return (error);
4120 }
4121 
4122 /*
4123  * Insert the indicated symbolic reference entry into the directory.
4124  *
4125  *	IN:	dvp	- Directory to contain new symbolic link.
4126  *		link	- Name for new symlink entry.
4127  *		vap	- Attributes of new entry.
4128  *		cr	- credentials of caller.
4129  *		ct	- caller context
4130  *		flags	- case flags
4131  *
4132  *	RETURN:	0 on success, error code on failure.
4133  *
4134  * Timestamps:
4135  *	dvp - ctime|mtime updated
4136  */
4137 /*ARGSUSED*/
4138 static int
4139 zfs_symlink(vnode_t *dvp, char *name, vattr_t *vap, char *link, cred_t *cr,
4140     caller_context_t *ct, int flags)
4141 {
4142 	znode_t		*zp, *dzp = VTOZ(dvp);
4143 	zfs_dirlock_t	*dl;
4144 	dmu_tx_t	*tx;
4145 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
4146 	zilog_t		*zilog;
4147 	uint64_t	len = strlen(link);
4148 	int		error;
4149 	int		zflg = ZNEW;
4150 	zfs_acl_ids_t	acl_ids;
4151 	boolean_t	fuid_dirtied;
4152 	uint64_t	txtype = TX_SYMLINK;
4153 	boolean_t	waited = B_FALSE;
4154 
4155 	ASSERT(vap->va_type == VLNK);
4156 
4157 	ZFS_ENTER(zfsvfs);
4158 	ZFS_VERIFY_ZP(dzp);
4159 	zilog = zfsvfs->z_log;
4160 
4161 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
4162 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4163 		ZFS_EXIT(zfsvfs);
4164 		return (SET_ERROR(EILSEQ));
4165 	}
4166 	if (flags & FIGNORECASE)
4167 		zflg |= ZCILOOK;
4168 
4169 	if (len > MAXPATHLEN) {
4170 		ZFS_EXIT(zfsvfs);
4171 		return (SET_ERROR(ENAMETOOLONG));
4172 	}
4173 
4174 	if ((error = zfs_acl_ids_create(dzp, 0,
4175 	    vap, cr, NULL, &acl_ids)) != 0) {
4176 		ZFS_EXIT(zfsvfs);
4177 		return (error);
4178 	}
4179 top:
4180 	/*
4181 	 * Attempt to lock directory; fail if entry already exists.
4182 	 */
4183 	error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
4184 	if (error) {
4185 		zfs_acl_ids_free(&acl_ids);
4186 		ZFS_EXIT(zfsvfs);
4187 		return (error);
4188 	}
4189 
4190 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4191 		zfs_acl_ids_free(&acl_ids);
4192 		zfs_dirent_unlock(dl);
4193 		ZFS_EXIT(zfsvfs);
4194 		return (error);
4195 	}
4196 
4197 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, ZFS_DEFAULT_PROJID)) {
4198 		zfs_acl_ids_free(&acl_ids);
4199 		zfs_dirent_unlock(dl);
4200 		ZFS_EXIT(zfsvfs);
4201 		return (SET_ERROR(EDQUOT));
4202 	}
4203 	tx = dmu_tx_create(zfsvfs->z_os);
4204 	fuid_dirtied = zfsvfs->z_fuid_dirty;
4205 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
4206 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4207 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
4208 	    ZFS_SA_BASE_ATTR_SIZE + len);
4209 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
4210 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
4211 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
4212 		    acl_ids.z_aclp->z_acl_bytes);
4213 	}
4214 	if (fuid_dirtied)
4215 		zfs_fuid_txhold(zfsvfs, tx);
4216 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
4217 	if (error) {
4218 		zfs_dirent_unlock(dl);
4219 		if (error == ERESTART) {
4220 			waited = B_TRUE;
4221 			dmu_tx_wait(tx);
4222 			dmu_tx_abort(tx);
4223 			goto top;
4224 		}
4225 		zfs_acl_ids_free(&acl_ids);
4226 		dmu_tx_abort(tx);
4227 		ZFS_EXIT(zfsvfs);
4228 		return (error);
4229 	}
4230 
4231 	/*
4232 	 * Create a new object for the symlink.
4233 	 * for version 4 ZPL datsets the symlink will be an SA attribute
4234 	 */
4235 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
4236 
4237 	if (fuid_dirtied)
4238 		zfs_fuid_sync(zfsvfs, tx);
4239 
4240 	mutex_enter(&zp->z_lock);
4241 	if (zp->z_is_sa)
4242 		error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
4243 		    link, len, tx);
4244 	else
4245 		zfs_sa_symlink(zp, link, len, tx);
4246 	mutex_exit(&zp->z_lock);
4247 
4248 	zp->z_size = len;
4249 	(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
4250 	    &zp->z_size, sizeof (zp->z_size), tx);
4251 	/*
4252 	 * Insert the new object into the directory.
4253 	 */
4254 	(void) zfs_link_create(dl, zp, tx, ZNEW);
4255 
4256 	if (flags & FIGNORECASE)
4257 		txtype |= TX_CI;
4258 	zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
4259 
4260 	zfs_acl_ids_free(&acl_ids);
4261 
4262 	dmu_tx_commit(tx);
4263 
4264 	zfs_dirent_unlock(dl);
4265 
4266 	VN_RELE(ZTOV(zp));
4267 
4268 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4269 		zil_commit(zilog, 0);
4270 
4271 	ZFS_EXIT(zfsvfs);
4272 	return (error);
4273 }
4274 
4275 /*
4276  * Return, in the buffer contained in the provided uio structure,
4277  * the symbolic path referred to by vp.
4278  *
4279  *	IN:	vp	- vnode of symbolic link.
4280  *		uio	- structure to contain the link path.
4281  *		cr	- credentials of caller.
4282  *		ct	- caller context
4283  *
4284  *	OUT:	uio	- structure containing the link path.
4285  *
4286  *	RETURN:	0 on success, error code on failure.
4287  *
4288  * Timestamps:
4289  *	vp - atime updated
4290  */
4291 /* ARGSUSED */
4292 static int
4293 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
4294 {
4295 	znode_t		*zp = VTOZ(vp);
4296 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4297 	int		error;
4298 
4299 	ZFS_ENTER(zfsvfs);
4300 	ZFS_VERIFY_ZP(zp);
4301 
4302 	mutex_enter(&zp->z_lock);
4303 	if (zp->z_is_sa)
4304 		error = sa_lookup_uio(zp->z_sa_hdl,
4305 		    SA_ZPL_SYMLINK(zfsvfs), uio);
4306 	else
4307 		error = zfs_sa_readlink(zp, uio);
4308 	mutex_exit(&zp->z_lock);
4309 
4310 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4311 
4312 	ZFS_EXIT(zfsvfs);
4313 	return (error);
4314 }
4315 
4316 /*
4317  * Insert a new entry into directory tdvp referencing svp.
4318  *
4319  *	IN:	tdvp	- Directory to contain new entry.
4320  *		svp	- vnode of new entry.
4321  *		name	- name of new entry.
4322  *		cr	- credentials of caller.
4323  *		ct	- caller context
4324  *
4325  *	RETURN:	0 on success, error code on failure.
4326  *
4327  * Timestamps:
4328  *	tdvp - ctime|mtime updated
4329  *	 svp - ctime updated
4330  */
4331 /* ARGSUSED */
4332 static int
4333 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
4334     caller_context_t *ct, int flags)
4335 {
4336 	znode_t		*dzp = VTOZ(tdvp);
4337 	znode_t		*tzp, *szp;
4338 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
4339 	zilog_t		*zilog;
4340 	zfs_dirlock_t	*dl;
4341 	dmu_tx_t	*tx;
4342 	vnode_t		*realvp;
4343 	int		error;
4344 	int		zf = ZNEW;
4345 	uint64_t	parent;
4346 	uid_t		owner;
4347 	boolean_t	waited = B_FALSE;
4348 
4349 	ASSERT(tdvp->v_type == VDIR);
4350 
4351 	ZFS_ENTER(zfsvfs);
4352 	ZFS_VERIFY_ZP(dzp);
4353 	zilog = zfsvfs->z_log;
4354 
4355 	if (VOP_REALVP(svp, &realvp, ct) == 0)
4356 		svp = realvp;
4357 
4358 	/*
4359 	 * POSIX dictates that we return EPERM here.
4360 	 * Better choices include ENOTSUP or EISDIR.
4361 	 */
4362 	if (svp->v_type == VDIR) {
4363 		ZFS_EXIT(zfsvfs);
4364 		return (SET_ERROR(EPERM));
4365 	}
4366 
4367 	szp = VTOZ(svp);
4368 	ZFS_VERIFY_ZP(szp);
4369 
4370 	/*
4371 	 * If we are using project inheritance, it means if the directory has
4372 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
4373 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
4374 	 * such case, we only allow hard link creation in our tree when the
4375 	 * project IDs are the same.
4376 	 */
4377 	if (dzp->z_pflags & ZFS_PROJINHERIT && dzp->z_projid != szp->z_projid) {
4378 		ZFS_EXIT(zfsvfs);
4379 		return (SET_ERROR(EXDEV));
4380 	}
4381 
4382 	/*
4383 	 * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
4384 	 * ctldir appear to have the same v_vfsp.
4385 	 */
4386 	if (szp->z_zfsvfs != zfsvfs || zfsctl_is_node(svp)) {
4387 		ZFS_EXIT(zfsvfs);
4388 		return (SET_ERROR(EXDEV));
4389 	}
4390 
4391 	/* Prevent links to .zfs/shares files */
4392 
4393 	if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
4394 	    &parent, sizeof (uint64_t))) != 0) {
4395 		ZFS_EXIT(zfsvfs);
4396 		return (error);
4397 	}
4398 	if (parent == zfsvfs->z_shares_dir) {
4399 		ZFS_EXIT(zfsvfs);
4400 		return (SET_ERROR(EPERM));
4401 	}
4402 
4403 	if (zfsvfs->z_utf8 && u8_validate(name,
4404 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4405 		ZFS_EXIT(zfsvfs);
4406 		return (SET_ERROR(EILSEQ));
4407 	}
4408 	if (flags & FIGNORECASE)
4409 		zf |= ZCILOOK;
4410 
4411 	/*
4412 	 * We do not support links between attributes and non-attributes
4413 	 * because of the potential security risk of creating links
4414 	 * into "normal" file space in order to circumvent restrictions
4415 	 * imposed in attribute space.
4416 	 */
4417 	if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
4418 		ZFS_EXIT(zfsvfs);
4419 		return (SET_ERROR(EINVAL));
4420 	}
4421 
4422 
4423 	owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
4424 	if (owner != crgetuid(cr) && secpolicy_basic_link(cr) != 0) {
4425 		ZFS_EXIT(zfsvfs);
4426 		return (SET_ERROR(EPERM));
4427 	}
4428 
4429 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4430 		ZFS_EXIT(zfsvfs);
4431 		return (error);
4432 	}
4433 
4434 top:
4435 	/*
4436 	 * Attempt to lock directory; fail if entry already exists.
4437 	 */
4438 	error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
4439 	if (error) {
4440 		ZFS_EXIT(zfsvfs);
4441 		return (error);
4442 	}
4443 
4444 	tx = dmu_tx_create(zfsvfs->z_os);
4445 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
4446 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4447 	zfs_sa_upgrade_txholds(tx, szp);
4448 	zfs_sa_upgrade_txholds(tx, dzp);
4449 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
4450 	if (error) {
4451 		zfs_dirent_unlock(dl);
4452 		if (error == ERESTART) {
4453 			waited = B_TRUE;
4454 			dmu_tx_wait(tx);
4455 			dmu_tx_abort(tx);
4456 			goto top;
4457 		}
4458 		dmu_tx_abort(tx);
4459 		ZFS_EXIT(zfsvfs);
4460 		return (error);
4461 	}
4462 
4463 	error = zfs_link_create(dl, szp, tx, 0);
4464 
4465 	if (error == 0) {
4466 		uint64_t txtype = TX_LINK;
4467 		if (flags & FIGNORECASE)
4468 			txtype |= TX_CI;
4469 		zfs_log_link(zilog, tx, txtype, dzp, szp, name);
4470 	}
4471 
4472 	dmu_tx_commit(tx);
4473 
4474 	zfs_dirent_unlock(dl);
4475 
4476 	if (error == 0) {
4477 		vnevent_link(svp, ct);
4478 	}
4479 
4480 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4481 		zil_commit(zilog, 0);
4482 
4483 	ZFS_EXIT(zfsvfs);
4484 	return (error);
4485 }
4486 
4487 /*
4488  * zfs_null_putapage() is used when the file system has been force
4489  * unmounted. It just drops the pages.
4490  */
4491 /* ARGSUSED */
4492 static int
4493 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4494     size_t *lenp, int flags, cred_t *cr)
4495 {
4496 	pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
4497 	return (0);
4498 }
4499 
4500 /*
4501  * Push a page out to disk, klustering if possible.
4502  *
4503  *	IN:	vp	- file to push page to.
4504  *		pp	- page to push.
4505  *		flags	- additional flags.
4506  *		cr	- credentials of caller.
4507  *
4508  *	OUT:	offp	- start of range pushed.
4509  *		lenp	- len of range pushed.
4510  *
4511  *	RETURN:	0 on success, error code on failure.
4512  *
4513  * NOTE: callers must have locked the page to be pushed.  On
4514  * exit, the page (and all other pages in the kluster) must be
4515  * unlocked.
4516  */
4517 /* ARGSUSED */
4518 static int
4519 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4520     size_t *lenp, int flags, cred_t *cr)
4521 {
4522 	znode_t		*zp = VTOZ(vp);
4523 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4524 	dmu_tx_t	*tx;
4525 	u_offset_t	off, koff;
4526 	size_t		len, klen;
4527 	int		err;
4528 
4529 	off = pp->p_offset;
4530 	len = PAGESIZE;
4531 	/*
4532 	 * If our blocksize is bigger than the page size, try to kluster
4533 	 * multiple pages so that we write a full block (thus avoiding
4534 	 * a read-modify-write).
4535 	 */
4536 	if (off < zp->z_size && zp->z_blksz > PAGESIZE) {
4537 		klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
4538 		koff = ISP2(klen) ? P2ALIGN(off, (u_offset_t)klen) : 0;
4539 		ASSERT(koff <= zp->z_size);
4540 		if (koff + klen > zp->z_size)
4541 			klen = P2ROUNDUP(zp->z_size - koff, (uint64_t)PAGESIZE);
4542 		pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
4543 	}
4544 	ASSERT3U(btop(len), ==, btopr(len));
4545 
4546 	/*
4547 	 * Can't push pages past end-of-file.
4548 	 */
4549 	if (off >= zp->z_size) {
4550 		/* ignore all pages */
4551 		err = 0;
4552 		goto out;
4553 	} else if (off + len > zp->z_size) {
4554 		int npages = btopr(zp->z_size - off);
4555 		page_t *trunc;
4556 
4557 		page_list_break(&pp, &trunc, npages);
4558 		/* ignore pages past end of file */
4559 		if (trunc)
4560 			pvn_write_done(trunc, flags);
4561 		len = zp->z_size - off;
4562 	}
4563 
4564 	if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, zp->z_uid) ||
4565 	    zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, zp->z_gid)) {
4566 		err = SET_ERROR(EDQUOT);
4567 		goto out;
4568 	}
4569 	tx = dmu_tx_create(zfsvfs->z_os);
4570 	dmu_tx_hold_write(tx, zp->z_id, off, len);
4571 
4572 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4573 	zfs_sa_upgrade_txholds(tx, zp);
4574 	err = dmu_tx_assign(tx, TXG_WAIT);
4575 	if (err != 0) {
4576 		dmu_tx_abort(tx);
4577 		goto out;
4578 	}
4579 
4580 	if (zp->z_blksz <= PAGESIZE) {
4581 		caddr_t va = zfs_map_page(pp, S_READ);
4582 		ASSERT3U(len, <=, PAGESIZE);
4583 		dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
4584 		zfs_unmap_page(pp, va);
4585 	} else {
4586 		err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
4587 	}
4588 
4589 	if (err == 0) {
4590 		uint64_t mtime[2], ctime[2];
4591 		sa_bulk_attr_t bulk[3];
4592 		int count = 0;
4593 
4594 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4595 		    &mtime, 16);
4596 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4597 		    &ctime, 16);
4598 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4599 		    &zp->z_pflags, 8);
4600 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
4601 		    B_TRUE);
4602 		err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
4603 		ASSERT0(err);
4604 		zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len, 0);
4605 	}
4606 	dmu_tx_commit(tx);
4607 
4608 out:
4609 	pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
4610 	if (offp)
4611 		*offp = off;
4612 	if (lenp)
4613 		*lenp = len;
4614 
4615 	return (err);
4616 }
4617 
4618 /*
4619  * Copy the portion of the file indicated from pages into the file.
4620  * The pages are stored in a page list attached to the files vnode.
4621  *
4622  *	IN:	vp	- vnode of file to push page data to.
4623  *		off	- position in file to put data.
4624  *		len	- amount of data to write.
4625  *		flags	- flags to control the operation.
4626  *		cr	- credentials of caller.
4627  *		ct	- caller context.
4628  *
4629  *	RETURN:	0 on success, error code on failure.
4630  *
4631  * Timestamps:
4632  *	vp - ctime|mtime updated
4633  */
4634 /*ARGSUSED*/
4635 static int
4636 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
4637     caller_context_t *ct)
4638 {
4639 	znode_t		*zp = VTOZ(vp);
4640 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4641 	page_t		*pp;
4642 	size_t		io_len;
4643 	u_offset_t	io_off;
4644 	uint_t		blksz;
4645 	locked_range_t	*lr;
4646 	int		error = 0;
4647 
4648 	ZFS_ENTER(zfsvfs);
4649 	ZFS_VERIFY_ZP(zp);
4650 
4651 	/*
4652 	 * There's nothing to do if no data is cached.
4653 	 */
4654 	if (!vn_has_cached_data(vp)) {
4655 		ZFS_EXIT(zfsvfs);
4656 		return (0);
4657 	}
4658 
4659 	/*
4660 	 * Align this request to the file block size in case we kluster.
4661 	 * XXX - this can result in pretty aggresive locking, which can
4662 	 * impact simultanious read/write access.  One option might be
4663 	 * to break up long requests (len == 0) into block-by-block
4664 	 * operations to get narrower locking.
4665 	 */
4666 	blksz = zp->z_blksz;
4667 	if (ISP2(blksz))
4668 		io_off = P2ALIGN_TYPED(off, blksz, u_offset_t);
4669 	else
4670 		io_off = 0;
4671 	if (len > 0 && ISP2(blksz))
4672 		io_len = P2ROUNDUP_TYPED(len + (off - io_off), blksz, size_t);
4673 	else
4674 		io_len = 0;
4675 
4676 	if (io_len == 0) {
4677 		/*
4678 		 * Search the entire vp list for pages >= io_off.
4679 		 */
4680 		lr = rangelock_enter(&zp->z_rangelock,
4681 		    io_off, UINT64_MAX, RL_WRITER);
4682 		error = pvn_vplist_dirty(vp, io_off, zfs_putapage, flags, cr);
4683 		goto out;
4684 	}
4685 	lr = rangelock_enter(&zp->z_rangelock, io_off, io_len, RL_WRITER);
4686 
4687 	if (off > zp->z_size) {
4688 		/* past end of file */
4689 		rangelock_exit(lr);
4690 		ZFS_EXIT(zfsvfs);
4691 		return (0);
4692 	}
4693 
4694 	len = MIN(io_len, P2ROUNDUP(zp->z_size, PAGESIZE) - io_off);
4695 
4696 	for (off = io_off; io_off < off + len; io_off += io_len) {
4697 		if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
4698 			pp = page_lookup(vp, io_off,
4699 			    (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
4700 		} else {
4701 			pp = page_lookup_nowait(vp, io_off,
4702 			    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
4703 		}
4704 
4705 		if (pp != NULL && pvn_getdirty(pp, flags)) {
4706 			int err;
4707 
4708 			/*
4709 			 * Found a dirty page to push
4710 			 */
4711 			err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
4712 			if (err)
4713 				error = err;
4714 		} else {
4715 			io_len = PAGESIZE;
4716 		}
4717 	}
4718 out:
4719 	rangelock_exit(lr);
4720 	if ((flags & B_ASYNC) == 0 || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4721 		zil_commit(zfsvfs->z_log, zp->z_id);
4722 	ZFS_EXIT(zfsvfs);
4723 	return (error);
4724 }
4725 
4726 /*ARGSUSED*/
4727 void
4728 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4729 {
4730 	znode_t	*zp = VTOZ(vp);
4731 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4732 	int error;
4733 
4734 	rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4735 	if (zp->z_sa_hdl == NULL) {
4736 		/*
4737 		 * The fs has been unmounted, or we did a
4738 		 * suspend/resume and this file no longer exists.
4739 		 */
4740 		if (vn_has_cached_data(vp)) {
4741 			(void) pvn_vplist_dirty(vp, 0, zfs_null_putapage,
4742 			    B_INVAL, cr);
4743 		}
4744 
4745 		mutex_enter(&zp->z_lock);
4746 		mutex_enter(&vp->v_lock);
4747 		ASSERT(vp->v_count == 1);
4748 		VN_RELE_LOCKED(vp);
4749 		mutex_exit(&vp->v_lock);
4750 		mutex_exit(&zp->z_lock);
4751 		rw_exit(&zfsvfs->z_teardown_inactive_lock);
4752 		zfs_znode_free(zp);
4753 		return;
4754 	}
4755 
4756 	/*
4757 	 * Attempt to push any data in the page cache.  If this fails
4758 	 * we will get kicked out later in zfs_zinactive().
4759 	 */
4760 	if (vn_has_cached_data(vp)) {
4761 		(void) pvn_vplist_dirty(vp, 0, zfs_putapage, B_INVAL|B_ASYNC,
4762 		    cr);
4763 	}
4764 
4765 	if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4766 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4767 
4768 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4769 		zfs_sa_upgrade_txholds(tx, zp);
4770 		error = dmu_tx_assign(tx, TXG_WAIT);
4771 		if (error) {
4772 			dmu_tx_abort(tx);
4773 		} else {
4774 			mutex_enter(&zp->z_lock);
4775 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4776 			    (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4777 			zp->z_atime_dirty = 0;
4778 			mutex_exit(&zp->z_lock);
4779 			dmu_tx_commit(tx);
4780 		}
4781 	}
4782 
4783 	zfs_zinactive(zp);
4784 	rw_exit(&zfsvfs->z_teardown_inactive_lock);
4785 }
4786 
4787 /*
4788  * Bounds-check the seek operation.
4789  *
4790  *	IN:	vp	- vnode seeking within
4791  *		ooff	- old file offset
4792  *		noffp	- pointer to new file offset
4793  *		ct	- caller context
4794  *
4795  *	RETURN:	0 on success, EINVAL if new offset invalid.
4796  */
4797 /* ARGSUSED */
4798 static int
4799 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp,
4800     caller_context_t *ct)
4801 {
4802 	if (vp->v_type == VDIR)
4803 		return (0);
4804 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4805 }
4806 
4807 /*
4808  * Pre-filter the generic locking function to trap attempts to place
4809  * a mandatory lock on a memory mapped file.
4810  */
4811 static int
4812 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
4813     flk_callback_t *flk_cbp, cred_t *cr, caller_context_t *ct)
4814 {
4815 	znode_t *zp = VTOZ(vp);
4816 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4817 
4818 	ZFS_ENTER(zfsvfs);
4819 	ZFS_VERIFY_ZP(zp);
4820 
4821 	/*
4822 	 * We are following the UFS semantics with respect to mapcnt
4823 	 * here: If we see that the file is mapped already, then we will
4824 	 * return an error, but we don't worry about races between this
4825 	 * function and zfs_map().
4826 	 */
4827 	if (zp->z_mapcnt > 0 && MANDMODE(zp->z_mode)) {
4828 		ZFS_EXIT(zfsvfs);
4829 		return (SET_ERROR(EAGAIN));
4830 	}
4831 	ZFS_EXIT(zfsvfs);
4832 	return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4833 }
4834 
4835 /*
4836  * If we can't find a page in the cache, we will create a new page
4837  * and fill it with file data.  For efficiency, we may try to fill
4838  * multiple pages at once (klustering) to fill up the supplied page
4839  * list.  Note that the pages to be filled are held with an exclusive
4840  * lock to prevent access by other threads while they are being filled.
4841  */
4842 static int
4843 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
4844     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
4845 {
4846 	znode_t *zp = VTOZ(vp);
4847 	page_t *pp, *cur_pp;
4848 	objset_t *os = zp->z_zfsvfs->z_os;
4849 	u_offset_t io_off, total;
4850 	size_t io_len;
4851 	int err;
4852 
4853 	if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
4854 		/*
4855 		 * We only have a single page, don't bother klustering
4856 		 */
4857 		io_off = off;
4858 		io_len = PAGESIZE;
4859 		pp = page_create_va(vp, io_off, io_len,
4860 		    PG_EXCL | PG_WAIT, seg, addr);
4861 	} else {
4862 		/*
4863 		 * Try to find enough pages to fill the page list
4864 		 */
4865 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4866 		    &io_len, off, plsz, 0);
4867 	}
4868 	if (pp == NULL) {
4869 		/*
4870 		 * The page already exists, nothing to do here.
4871 		 */
4872 		*pl = NULL;
4873 		return (0);
4874 	}
4875 
4876 	/*
4877 	 * Fill the pages in the kluster.
4878 	 */
4879 	cur_pp = pp;
4880 	for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4881 		caddr_t va;
4882 
4883 		ASSERT3U(io_off, ==, cur_pp->p_offset);
4884 		va = zfs_map_page(cur_pp, S_WRITE);
4885 		err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4886 		    DMU_READ_PREFETCH);
4887 		zfs_unmap_page(cur_pp, va);
4888 		if (err) {
4889 			/* On error, toss the entire kluster */
4890 			pvn_read_done(pp, B_ERROR);
4891 			/* convert checksum errors into IO errors */
4892 			if (err == ECKSUM)
4893 				err = SET_ERROR(EIO);
4894 			return (err);
4895 		}
4896 		cur_pp = cur_pp->p_next;
4897 	}
4898 
4899 	/*
4900 	 * Fill in the page list array from the kluster starting
4901 	 * from the desired offset `off'.
4902 	 * NOTE: the page list will always be null terminated.
4903 	 */
4904 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4905 	ASSERT(pl == NULL || (*pl)->p_offset == off);
4906 
4907 	return (0);
4908 }
4909 
4910 /*
4911  * Return pointers to the pages for the file region [off, off + len]
4912  * in the pl array.  If plsz is greater than len, this function may
4913  * also return page pointers from after the specified region
4914  * (i.e. the region [off, off + plsz]).  These additional pages are
4915  * only returned if they are already in the cache, or were created as
4916  * part of a klustered read.
4917  *
4918  *	IN:	vp	- vnode of file to get data from.
4919  *		off	- position in file to get data from.
4920  *		len	- amount of data to retrieve.
4921  *		plsz	- length of provided page list.
4922  *		seg	- segment to obtain pages for.
4923  *		addr	- virtual address of fault.
4924  *		rw	- mode of created pages.
4925  *		cr	- credentials of caller.
4926  *		ct	- caller context.
4927  *
4928  *	OUT:	protp	- protection mode of created pages.
4929  *		pl	- list of pages created.
4930  *
4931  *	RETURN:	0 on success, error code on failure.
4932  *
4933  * Timestamps:
4934  *	vp - atime updated
4935  */
4936 /* ARGSUSED */
4937 static int
4938 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
4939     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
4940     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
4941 {
4942 	znode_t		*zp = VTOZ(vp);
4943 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4944 	page_t		**pl0 = pl;
4945 	int		err = 0;
4946 
4947 	/* we do our own caching, faultahead is unnecessary */
4948 	if (pl == NULL)
4949 		return (0);
4950 	else if (len > plsz)
4951 		len = plsz;
4952 	else
4953 		len = P2ROUNDUP(len, PAGESIZE);
4954 	ASSERT(plsz >= len);
4955 
4956 	ZFS_ENTER(zfsvfs);
4957 	ZFS_VERIFY_ZP(zp);
4958 
4959 	if (protp)
4960 		*protp = PROT_ALL;
4961 
4962 	/*
4963 	 * Loop through the requested range [off, off + len) looking
4964 	 * for pages.  If we don't find a page, we will need to create
4965 	 * a new page and fill it with data from the file.
4966 	 */
4967 	while (len > 0) {
4968 		if (*pl = page_lookup(vp, off, SE_SHARED))
4969 			*(pl+1) = NULL;
4970 		else if (err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw))
4971 			goto out;
4972 		while (*pl) {
4973 			ASSERT3U((*pl)->p_offset, ==, off);
4974 			off += PAGESIZE;
4975 			addr += PAGESIZE;
4976 			if (len > 0) {
4977 				ASSERT3U(len, >=, PAGESIZE);
4978 				len -= PAGESIZE;
4979 			}
4980 			ASSERT3U(plsz, >=, PAGESIZE);
4981 			plsz -= PAGESIZE;
4982 			pl++;
4983 		}
4984 	}
4985 
4986 	/*
4987 	 * Fill out the page array with any pages already in the cache.
4988 	 */
4989 	while (plsz > 0 &&
4990 	    (*pl++ = page_lookup_nowait(vp, off, SE_SHARED))) {
4991 			off += PAGESIZE;
4992 			plsz -= PAGESIZE;
4993 	}
4994 out:
4995 	if (err) {
4996 		/*
4997 		 * Release any pages we have previously locked.
4998 		 */
4999 		while (pl > pl0)
5000 			page_unlock(*--pl);
5001 	} else {
5002 		ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
5003 	}
5004 
5005 	*pl = NULL;
5006 
5007 	ZFS_EXIT(zfsvfs);
5008 	return (err);
5009 }
5010 
5011 /*
5012  * Request a memory map for a section of a file.  This code interacts
5013  * with common code and the VM system as follows:
5014  *
5015  * - common code calls mmap(), which ends up in smmap_common()
5016  * - this calls VOP_MAP(), which takes you into (say) zfs
5017  * - zfs_map() calls as_map(), passing segvn_create() as the callback
5018  * - segvn_create() creates the new segment and calls VOP_ADDMAP()
5019  * - zfs_addmap() updates z_mapcnt
5020  */
5021 /*ARGSUSED*/
5022 static int
5023 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
5024     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
5025     caller_context_t *ct)
5026 {
5027 	znode_t *zp = VTOZ(vp);
5028 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5029 	segvn_crargs_t	vn_a;
5030 	int		error;
5031 
5032 	ZFS_ENTER(zfsvfs);
5033 	ZFS_VERIFY_ZP(zp);
5034 
5035 	/*
5036 	 * Note: ZFS_READONLY is handled in zfs_zaccess_common.
5037 	 */
5038 
5039 	if ((prot & PROT_WRITE) && (zp->z_pflags &
5040 	    (ZFS_IMMUTABLE | ZFS_APPENDONLY))) {
5041 		ZFS_EXIT(zfsvfs);
5042 		return (SET_ERROR(EPERM));
5043 	}
5044 
5045 	if ((prot & (PROT_READ | PROT_EXEC)) &&
5046 	    (zp->z_pflags & ZFS_AV_QUARANTINED)) {
5047 		ZFS_EXIT(zfsvfs);
5048 		return (SET_ERROR(EACCES));
5049 	}
5050 
5051 	if (vp->v_flag & VNOMAP) {
5052 		ZFS_EXIT(zfsvfs);
5053 		return (SET_ERROR(ENOSYS));
5054 	}
5055 
5056 	if (off < 0 || len > MAXOFFSET_T - off) {
5057 		ZFS_EXIT(zfsvfs);
5058 		return (SET_ERROR(ENXIO));
5059 	}
5060 
5061 	if (vp->v_type != VREG) {
5062 		ZFS_EXIT(zfsvfs);
5063 		return (SET_ERROR(ENODEV));
5064 	}
5065 
5066 	/*
5067 	 * If file is locked, disallow mapping.
5068 	 */
5069 	if (MANDMODE(zp->z_mode) && vn_has_flocks(vp)) {
5070 		ZFS_EXIT(zfsvfs);
5071 		return (SET_ERROR(EAGAIN));
5072 	}
5073 
5074 	as_rangelock(as);
5075 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
5076 	if (error != 0) {
5077 		as_rangeunlock(as);
5078 		ZFS_EXIT(zfsvfs);
5079 		return (error);
5080 	}
5081 
5082 	vn_a.vp = vp;
5083 	vn_a.offset = (u_offset_t)off;
5084 	vn_a.type = flags & MAP_TYPE;
5085 	vn_a.prot = prot;
5086 	vn_a.maxprot = maxprot;
5087 	vn_a.cred = cr;
5088 	vn_a.amp = NULL;
5089 	vn_a.flags = flags & ~MAP_TYPE;
5090 	vn_a.szc = 0;
5091 	vn_a.lgrp_mem_policy_flags = 0;
5092 
5093 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
5094 
5095 	as_rangeunlock(as);
5096 	ZFS_EXIT(zfsvfs);
5097 	return (error);
5098 }
5099 
5100 /* ARGSUSED */
5101 static int
5102 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
5103     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
5104     caller_context_t *ct)
5105 {
5106 	uint64_t pages = btopr(len);
5107 
5108 	atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
5109 	return (0);
5110 }
5111 
5112 /*
5113  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
5114  * more accurate mtime for the associated file.  Since we don't have a way of
5115  * detecting when the data was actually modified, we have to resort to
5116  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
5117  * last page is pushed.  The problem occurs when the msync() call is omitted,
5118  * which by far the most common case:
5119  *
5120  *	open()
5121  *	mmap()
5122  *	<modify memory>
5123  *	munmap()
5124  *	close()
5125  *	<time lapse>
5126  *	putpage() via fsflush
5127  *
5128  * If we wait until fsflush to come along, we can have a modification time that
5129  * is some arbitrary point in the future.  In order to prevent this in the
5130  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
5131  * torn down.
5132  */
5133 /* ARGSUSED */
5134 static int
5135 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
5136     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
5137     caller_context_t *ct)
5138 {
5139 	uint64_t pages = btopr(len);
5140 
5141 	ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
5142 	atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
5143 
5144 	if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
5145 	    vn_has_cached_data(vp))
5146 		(void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
5147 
5148 	return (0);
5149 }
5150 
5151 /*
5152  * Free or allocate space in a file.  Currently, this function only
5153  * supports the `F_FREESP' command.  However, this command is somewhat
5154  * misnamed, as its functionality includes the ability to allocate as
5155  * well as free space.
5156  *
5157  *	IN:	vp	- vnode of file to free data in.
5158  *		cmd	- action to take (only F_FREESP supported).
5159  *		bfp	- section of file to free/alloc.
5160  *		flag	- current file open mode flags.
5161  *		offset	- current file offset.
5162  *		cr	- credentials of caller [UNUSED].
5163  *		ct	- caller context.
5164  *
5165  *	RETURN:	0 on success, error code on failure.
5166  *
5167  * Timestamps:
5168  *	vp - ctime|mtime updated
5169  */
5170 /* ARGSUSED */
5171 static int
5172 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
5173     offset_t offset, cred_t *cr, caller_context_t *ct)
5174 {
5175 	znode_t		*zp = VTOZ(vp);
5176 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
5177 	uint64_t	off, len;
5178 	int		error;
5179 
5180 	ZFS_ENTER(zfsvfs);
5181 	ZFS_VERIFY_ZP(zp);
5182 
5183 	if (cmd != F_FREESP) {
5184 		ZFS_EXIT(zfsvfs);
5185 		return (SET_ERROR(EINVAL));
5186 	}
5187 
5188 	/*
5189 	 * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
5190 	 * callers might not be able to detect properly that we are read-only,
5191 	 * so check it explicitly here.
5192 	 */
5193 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
5194 		ZFS_EXIT(zfsvfs);
5195 		return (SET_ERROR(EROFS));
5196 	}
5197 
5198 	if (error = convoff(vp, bfp, 0, offset)) {
5199 		ZFS_EXIT(zfsvfs);
5200 		return (error);
5201 	}
5202 
5203 	if (bfp->l_len < 0) {
5204 		ZFS_EXIT(zfsvfs);
5205 		return (SET_ERROR(EINVAL));
5206 	}
5207 
5208 	off = bfp->l_start;
5209 	len = bfp->l_len; /* 0 means from off to end of file */
5210 
5211 	error = zfs_freesp(zp, off, len, flag, TRUE);
5212 
5213 	if (error == 0 && off == 0 && len == 0)
5214 		vnevent_truncate(ZTOV(zp), ct);
5215 
5216 	ZFS_EXIT(zfsvfs);
5217 	return (error);
5218 }
5219 
5220 /*ARGSUSED*/
5221 static int
5222 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
5223 {
5224 	znode_t		*zp = VTOZ(vp);
5225 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
5226 	uint32_t	gen;
5227 	uint64_t	gen64;
5228 	uint64_t	object = zp->z_id;
5229 	zfid_short_t	*zfid;
5230 	int		size, i, error;
5231 
5232 	ZFS_ENTER(zfsvfs);
5233 	ZFS_VERIFY_ZP(zp);
5234 
5235 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
5236 	    &gen64, sizeof (uint64_t))) != 0) {
5237 		ZFS_EXIT(zfsvfs);
5238 		return (error);
5239 	}
5240 
5241 	gen = (uint32_t)gen64;
5242 
5243 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
5244 	if (fidp->fid_len < size) {
5245 		fidp->fid_len = size;
5246 		ZFS_EXIT(zfsvfs);
5247 		return (SET_ERROR(ENOSPC));
5248 	}
5249 
5250 	zfid = (zfid_short_t *)fidp;
5251 
5252 	zfid->zf_len = size;
5253 
5254 	for (i = 0; i < sizeof (zfid->zf_object); i++)
5255 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
5256 
5257 	/* Must have a non-zero generation number to distinguish from .zfs */
5258 	if (gen == 0)
5259 		gen = 1;
5260 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
5261 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
5262 
5263 	if (size == LONG_FID_LEN) {
5264 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
5265 		zfid_long_t	*zlfid;
5266 
5267 		zlfid = (zfid_long_t *)fidp;
5268 
5269 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
5270 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
5271 
5272 		/* XXX - this should be the generation number for the objset */
5273 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
5274 			zlfid->zf_setgen[i] = 0;
5275 	}
5276 
5277 	ZFS_EXIT(zfsvfs);
5278 	return (0);
5279 }
5280 
5281 static int
5282 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
5283     caller_context_t *ct)
5284 {
5285 	znode_t		*zp, *xzp;
5286 	zfsvfs_t	*zfsvfs;
5287 	zfs_dirlock_t	*dl;
5288 	int		error;
5289 
5290 	switch (cmd) {
5291 	case _PC_LINK_MAX:
5292 		*valp = ULONG_MAX;
5293 		return (0);
5294 
5295 	case _PC_FILESIZEBITS:
5296 		*valp = 64;
5297 		return (0);
5298 
5299 	case _PC_XATTR_EXISTS:
5300 		zp = VTOZ(vp);
5301 		zfsvfs = zp->z_zfsvfs;
5302 		ZFS_ENTER(zfsvfs);
5303 		ZFS_VERIFY_ZP(zp);
5304 		*valp = 0;
5305 		error = zfs_dirent_lock(&dl, zp, "", &xzp,
5306 		    ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
5307 		if (error == 0) {
5308 			zfs_dirent_unlock(dl);
5309 			if (!zfs_dirempty(xzp))
5310 				*valp = 1;
5311 			VN_RELE(ZTOV(xzp));
5312 		} else if (error == ENOENT) {
5313 			/*
5314 			 * If there aren't extended attributes, it's the
5315 			 * same as having zero of them.
5316 			 */
5317 			error = 0;
5318 		}
5319 		ZFS_EXIT(zfsvfs);
5320 		return (error);
5321 
5322 	case _PC_SATTR_ENABLED:
5323 	case _PC_SATTR_EXISTS:
5324 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
5325 		    (vp->v_type == VREG || vp->v_type == VDIR);
5326 		return (0);
5327 
5328 	case _PC_ACCESS_FILTERING:
5329 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_ACCESS_FILTER) &&
5330 		    vp->v_type == VDIR;
5331 		return (0);
5332 
5333 	case _PC_ACL_ENABLED:
5334 		*valp = _ACL_ACE_ENABLED;
5335 		return (0);
5336 
5337 	case _PC_MIN_HOLE_SIZE:
5338 		*valp = (ulong_t)SPA_MINBLOCKSIZE;
5339 		return (0);
5340 
5341 	case _PC_TIMESTAMP_RESOLUTION:
5342 		/* nanosecond timestamp resolution */
5343 		*valp = 1L;
5344 		return (0);
5345 
5346 	default:
5347 		return (fs_pathconf(vp, cmd, valp, cr, ct));
5348 	}
5349 }
5350 
5351 /*ARGSUSED*/
5352 static int
5353 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5354     caller_context_t *ct)
5355 {
5356 	znode_t *zp = VTOZ(vp);
5357 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5358 	int error;
5359 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5360 
5361 	ZFS_ENTER(zfsvfs);
5362 	ZFS_VERIFY_ZP(zp);
5363 	error = zfs_getacl(zp, vsecp, skipaclchk, cr);
5364 	ZFS_EXIT(zfsvfs);
5365 
5366 	return (error);
5367 }
5368 
5369 /*ARGSUSED*/
5370 static int
5371 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5372     caller_context_t *ct)
5373 {
5374 	znode_t *zp = VTOZ(vp);
5375 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5376 	int error;
5377 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5378 	zilog_t	*zilog = zfsvfs->z_log;
5379 
5380 	ZFS_ENTER(zfsvfs);
5381 	ZFS_VERIFY_ZP(zp);
5382 
5383 	error = zfs_setacl(zp, vsecp, skipaclchk, cr);
5384 
5385 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
5386 		zil_commit(zilog, 0);
5387 
5388 	ZFS_EXIT(zfsvfs);
5389 	return (error);
5390 }
5391 
5392 /*
5393  * The smallest read we may consider to loan out an arcbuf.
5394  * This must be a power of 2.
5395  */
5396 int zcr_blksz_min = (1 << 10);	/* 1K */
5397 /*
5398  * If set to less than the file block size, allow loaning out of an
5399  * arcbuf for a partial block read.  This must be a power of 2.
5400  */
5401 int zcr_blksz_max = (1 << 17);	/* 128K */
5402 
5403 /*ARGSUSED*/
5404 static int
5405 zfs_reqzcbuf(vnode_t *vp, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr,
5406     caller_context_t *ct)
5407 {
5408 	znode_t	*zp = VTOZ(vp);
5409 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5410 	int max_blksz = zfsvfs->z_max_blksz;
5411 	uio_t *uio = &xuio->xu_uio;
5412 	ssize_t size = uio->uio_resid;
5413 	offset_t offset = uio->uio_loffset;
5414 	int blksz;
5415 	int fullblk, i;
5416 	arc_buf_t *abuf;
5417 	ssize_t maxsize;
5418 	int preamble, postamble;
5419 
5420 	if (xuio->xu_type != UIOTYPE_ZEROCOPY)
5421 		return (SET_ERROR(EINVAL));
5422 
5423 	ZFS_ENTER(zfsvfs);
5424 	ZFS_VERIFY_ZP(zp);
5425 	switch (ioflag) {
5426 	case UIO_WRITE:
5427 		/*
5428 		 * Loan out an arc_buf for write if write size is bigger than
5429 		 * max_blksz, and the file's block size is also max_blksz.
5430 		 */
5431 		blksz = max_blksz;
5432 		if (size < blksz || zp->z_blksz != blksz) {
5433 			ZFS_EXIT(zfsvfs);
5434 			return (SET_ERROR(EINVAL));
5435 		}
5436 		/*
5437 		 * Caller requests buffers for write before knowing where the
5438 		 * write offset might be (e.g. NFS TCP write).
5439 		 */
5440 		if (offset == -1) {
5441 			preamble = 0;
5442 		} else {
5443 			preamble = P2PHASE(offset, blksz);
5444 			if (preamble) {
5445 				preamble = blksz - preamble;
5446 				size -= preamble;
5447 			}
5448 		}
5449 
5450 		postamble = P2PHASE(size, blksz);
5451 		size -= postamble;
5452 
5453 		fullblk = size / blksz;
5454 		(void) dmu_xuio_init(xuio,
5455 		    (preamble != 0) + fullblk + (postamble != 0));
5456 		DTRACE_PROBE3(zfs_reqzcbuf_align, int, preamble,
5457 		    int, postamble, int,
5458 		    (preamble != 0) + fullblk + (postamble != 0));
5459 
5460 		/*
5461 		 * Have to fix iov base/len for partial buffers.  They
5462 		 * currently represent full arc_buf's.
5463 		 */
5464 		if (preamble) {
5465 			/* data begins in the middle of the arc_buf */
5466 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5467 			    blksz);
5468 			ASSERT(abuf);
5469 			(void) dmu_xuio_add(xuio, abuf,
5470 			    blksz - preamble, preamble);
5471 		}
5472 
5473 		for (i = 0; i < fullblk; i++) {
5474 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5475 			    blksz);
5476 			ASSERT(abuf);
5477 			(void) dmu_xuio_add(xuio, abuf, 0, blksz);
5478 		}
5479 
5480 		if (postamble) {
5481 			/* data ends in the middle of the arc_buf */
5482 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5483 			    blksz);
5484 			ASSERT(abuf);
5485 			(void) dmu_xuio_add(xuio, abuf, 0, postamble);
5486 		}
5487 		break;
5488 	case UIO_READ:
5489 		/*
5490 		 * Loan out an arc_buf for read if the read size is larger than
5491 		 * the current file block size.  Block alignment is not
5492 		 * considered.  Partial arc_buf will be loaned out for read.
5493 		 */
5494 		blksz = zp->z_blksz;
5495 		if (blksz < zcr_blksz_min)
5496 			blksz = zcr_blksz_min;
5497 		if (blksz > zcr_blksz_max)
5498 			blksz = zcr_blksz_max;
5499 		/* avoid potential complexity of dealing with it */
5500 		if (blksz > max_blksz) {
5501 			ZFS_EXIT(zfsvfs);
5502 			return (SET_ERROR(EINVAL));
5503 		}
5504 
5505 		maxsize = zp->z_size - uio->uio_loffset;
5506 		if (size > maxsize)
5507 			size = maxsize;
5508 
5509 		if (size < blksz || vn_has_cached_data(vp)) {
5510 			ZFS_EXIT(zfsvfs);
5511 			return (SET_ERROR(EINVAL));
5512 		}
5513 		break;
5514 	default:
5515 		ZFS_EXIT(zfsvfs);
5516 		return (SET_ERROR(EINVAL));
5517 	}
5518 
5519 	uio->uio_extflg = UIO_XUIO;
5520 	XUIO_XUZC_RW(xuio) = ioflag;
5521 	ZFS_EXIT(zfsvfs);
5522 	return (0);
5523 }
5524 
5525 /*ARGSUSED*/
5526 static int
5527 zfs_retzcbuf(vnode_t *vp, xuio_t *xuio, cred_t *cr, caller_context_t *ct)
5528 {
5529 	int i;
5530 	arc_buf_t *abuf;
5531 	int ioflag = XUIO_XUZC_RW(xuio);
5532 
5533 	ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
5534 
5535 	i = dmu_xuio_cnt(xuio);
5536 	while (i-- > 0) {
5537 		abuf = dmu_xuio_arcbuf(xuio, i);
5538 		/*
5539 		 * if abuf == NULL, it must be a write buffer
5540 		 * that has been returned in zfs_write().
5541 		 */
5542 		if (abuf)
5543 			dmu_return_arcbuf(abuf);
5544 		ASSERT(abuf || ioflag == UIO_WRITE);
5545 	}
5546 
5547 	dmu_xuio_fini(xuio);
5548 	return (0);
5549 }
5550 
5551 /*
5552  * Predeclare these here so that the compiler assumes that
5553  * this is an "old style" function declaration that does
5554  * not include arguments => we won't get type mismatch errors
5555  * in the initializations that follow.
5556  */
5557 static int zfs_inval();
5558 static int zfs_isdir();
5559 
5560 static int
5561 zfs_inval()
5562 {
5563 	return (SET_ERROR(EINVAL));
5564 }
5565 
5566 static int
5567 zfs_isdir()
5568 {
5569 	return (SET_ERROR(EISDIR));
5570 }
5571 /*
5572  * Directory vnode operations template
5573  */
5574 vnodeops_t *zfs_dvnodeops;
5575 const fs_operation_def_t zfs_dvnodeops_template[] = {
5576 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5577 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5578 	VOPNAME_READ,		{ .error = zfs_isdir },
5579 	VOPNAME_WRITE,		{ .error = zfs_isdir },
5580 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5581 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5582 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5583 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5584 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5585 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5586 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5587 	VOPNAME_LINK,		{ .vop_link = zfs_link },
5588 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5589 	VOPNAME_MKDIR,		{ .vop_mkdir = zfs_mkdir },
5590 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5591 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5592 	VOPNAME_SYMLINK,	{ .vop_symlink = zfs_symlink },
5593 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5594 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5595 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5596 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5597 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5598 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5599 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5600 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5601 	NULL,			NULL
5602 };
5603 
5604 /*
5605  * Regular file vnode operations template
5606  */
5607 vnodeops_t *zfs_fvnodeops;
5608 const fs_operation_def_t zfs_fvnodeops_template[] = {
5609 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5610 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5611 	VOPNAME_READ,		{ .vop_read = zfs_read },
5612 	VOPNAME_WRITE,		{ .vop_write = zfs_write },
5613 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5614 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5615 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5616 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5617 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5618 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5619 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5620 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5621 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5622 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5623 	VOPNAME_FRLOCK,		{ .vop_frlock = zfs_frlock },
5624 	VOPNAME_SPACE,		{ .vop_space = zfs_space },
5625 	VOPNAME_GETPAGE,	{ .vop_getpage = zfs_getpage },
5626 	VOPNAME_PUTPAGE,	{ .vop_putpage = zfs_putpage },
5627 	VOPNAME_MAP,		{ .vop_map = zfs_map },
5628 	VOPNAME_ADDMAP,		{ .vop_addmap = zfs_addmap },
5629 	VOPNAME_DELMAP,		{ .vop_delmap = zfs_delmap },
5630 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5631 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5632 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5633 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5634 	VOPNAME_REQZCBUF,	{ .vop_reqzcbuf = zfs_reqzcbuf },
5635 	VOPNAME_RETZCBUF,	{ .vop_retzcbuf = zfs_retzcbuf },
5636 	NULL,			NULL
5637 };
5638 
5639 /*
5640  * Symbolic link vnode operations template
5641  */
5642 vnodeops_t *zfs_symvnodeops;
5643 const fs_operation_def_t zfs_symvnodeops_template[] = {
5644 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5645 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5646 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5647 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5648 	VOPNAME_READLINK,	{ .vop_readlink = zfs_readlink },
5649 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5650 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5651 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5652 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5653 	NULL,			NULL
5654 };
5655 
5656 /*
5657  * special share hidden files vnode operations template
5658  */
5659 vnodeops_t *zfs_sharevnodeops;
5660 const fs_operation_def_t zfs_sharevnodeops_template[] = {
5661 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5662 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5663 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5664 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5665 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5666 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5667 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5668 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5669 	NULL,			NULL
5670 };
5671 
5672 /*
5673  * Extended attribute directory vnode operations template
5674  *
5675  * This template is identical to the directory vnodes
5676  * operation template except for restricted operations:
5677  *	VOP_MKDIR()
5678  *	VOP_SYMLINK()
5679  *
5680  * Note that there are other restrictions embedded in:
5681  *	zfs_create()	- restrict type to VREG
5682  *	zfs_link()	- no links into/out of attribute space
5683  *	zfs_rename()	- no moves into/out of attribute space
5684  */
5685 vnodeops_t *zfs_xdvnodeops;
5686 const fs_operation_def_t zfs_xdvnodeops_template[] = {
5687 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5688 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5689 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5690 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5691 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5692 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5693 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5694 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5695 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5696 	VOPNAME_LINK,		{ .vop_link = zfs_link },
5697 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5698 	VOPNAME_MKDIR,		{ .error = zfs_inval },
5699 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5700 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5701 	VOPNAME_SYMLINK,	{ .error = zfs_inval },
5702 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5703 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5704 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5705 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5706 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5707 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5708 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5709 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5710 	NULL,			NULL
5711 };
5712 
5713 /*
5714  * Error vnode operations template
5715  */
5716 vnodeops_t *zfs_evnodeops;
5717 const fs_operation_def_t zfs_evnodeops_template[] = {
5718 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5719 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5720 	NULL,			NULL
5721 };
5722