xref: /illumos-gate/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision c3d26abc)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
24  * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  */
27 
28 /* Portions Copyright 2007 Jeremy Teo */
29 /* Portions Copyright 2010 Robert Milkowski */
30 
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <sys/time.h>
34 #include <sys/systm.h>
35 #include <sys/sysmacros.h>
36 #include <sys/resource.h>
37 #include <sys/vfs.h>
38 #include <sys/vfs_opreg.h>
39 #include <sys/vnode.h>
40 #include <sys/file.h>
41 #include <sys/stat.h>
42 #include <sys/kmem.h>
43 #include <sys/taskq.h>
44 #include <sys/uio.h>
45 #include <sys/vmsystm.h>
46 #include <sys/atomic.h>
47 #include <sys/vm.h>
48 #include <vm/seg_vn.h>
49 #include <vm/pvn.h>
50 #include <vm/as.h>
51 #include <vm/kpm.h>
52 #include <vm/seg_kpm.h>
53 #include <sys/mman.h>
54 #include <sys/pathname.h>
55 #include <sys/cmn_err.h>
56 #include <sys/errno.h>
57 #include <sys/unistd.h>
58 #include <sys/zfs_dir.h>
59 #include <sys/zfs_acl.h>
60 #include <sys/zfs_ioctl.h>
61 #include <sys/fs/zfs.h>
62 #include <sys/dmu.h>
63 #include <sys/dmu_objset.h>
64 #include <sys/spa.h>
65 #include <sys/txg.h>
66 #include <sys/dbuf.h>
67 #include <sys/zap.h>
68 #include <sys/sa.h>
69 #include <sys/dirent.h>
70 #include <sys/policy.h>
71 #include <sys/sunddi.h>
72 #include <sys/filio.h>
73 #include <sys/sid.h>
74 #include "fs/fs_subr.h"
75 #include <sys/zfs_ctldir.h>
76 #include <sys/zfs_fuid.h>
77 #include <sys/zfs_sa.h>
78 #include <sys/dnlc.h>
79 #include <sys/zfs_rlock.h>
80 #include <sys/extdirent.h>
81 #include <sys/kidmap.h>
82 #include <sys/cred.h>
83 #include <sys/attr.h>
84 
85 /*
86  * Programming rules.
87  *
88  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
89  * properly lock its in-core state, create a DMU transaction, do the work,
90  * record this work in the intent log (ZIL), commit the DMU transaction,
91  * and wait for the intent log to commit if it is a synchronous operation.
92  * Moreover, the vnode ops must work in both normal and log replay context.
93  * The ordering of events is important to avoid deadlocks and references
94  * to freed memory.  The example below illustrates the following Big Rules:
95  *
96  *  (1)	A check must be made in each zfs thread for a mounted file system.
97  *	This is done avoiding races using ZFS_ENTER(zfsvfs).
98  *	A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
99  *	must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
100  *	can return EIO from the calling function.
101  *
102  *  (2)	VN_RELE() should always be the last thing except for zil_commit()
103  *	(if necessary) and ZFS_EXIT(). This is for 3 reasons:
104  *	First, if it's the last reference, the vnode/znode
105  *	can be freed, so the zp may point to freed memory.  Second, the last
106  *	reference will call zfs_zinactive(), which may induce a lot of work --
107  *	pushing cached pages (which acquires range locks) and syncing out
108  *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
109  *	which could deadlock the system if you were already holding one.
110  *	If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
111  *
112  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
113  *	as they can span dmu_tx_assign() calls.
114  *
115  *  (4) If ZPL locks are held, pass TXG_NOWAIT as the second argument to
116  *      dmu_tx_assign().  This is critical because we don't want to block
117  *      while holding locks.
118  *
119  *	If no ZPL locks are held (aside from ZFS_ENTER()), use TXG_WAIT.  This
120  *	reduces lock contention and CPU usage when we must wait (note that if
121  *	throughput is constrained by the storage, nearly every transaction
122  *	must wait).
123  *
124  *      Note, in particular, that if a lock is sometimes acquired before
125  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
126  *      to use a non-blocking assign can deadlock the system.  The scenario:
127  *
128  *	Thread A has grabbed a lock before calling dmu_tx_assign().
129  *	Thread B is in an already-assigned tx, and blocks for this lock.
130  *	Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
131  *	forever, because the previous txg can't quiesce until B's tx commits.
132  *
133  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
134  *	then drop all locks, call dmu_tx_wait(), and try again.  On subsequent
135  *	calls to dmu_tx_assign(), pass TXG_WAITED rather than TXG_NOWAIT,
136  *	to indicate that this operation has already called dmu_tx_wait().
137  *	This will ensure that we don't retry forever, waiting a short bit
138  *	each time.
139  *
140  *  (5)	If the operation succeeded, generate the intent log entry for it
141  *	before dropping locks.  This ensures that the ordering of events
142  *	in the intent log matches the order in which they actually occurred.
143  *	During ZIL replay the zfs_log_* functions will update the sequence
144  *	number to indicate the zil transaction has replayed.
145  *
146  *  (6)	At the end of each vnode op, the DMU tx must always commit,
147  *	regardless of whether there were any errors.
148  *
149  *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
150  *	to ensure that synchronous semantics are provided when necessary.
151  *
152  * In general, this is how things should be ordered in each vnode op:
153  *
154  *	ZFS_ENTER(zfsvfs);		// exit if unmounted
155  * top:
156  *	zfs_dirent_lock(&dl, ...)	// lock directory entry (may VN_HOLD())
157  *	rw_enter(...);			// grab any other locks you need
158  *	tx = dmu_tx_create(...);	// get DMU tx
159  *	dmu_tx_hold_*();		// hold each object you might modify
160  *	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
161  *	if (error) {
162  *		rw_exit(...);		// drop locks
163  *		zfs_dirent_unlock(dl);	// unlock directory entry
164  *		VN_RELE(...);		// release held vnodes
165  *		if (error == ERESTART) {
166  *			waited = B_TRUE;
167  *			dmu_tx_wait(tx);
168  *			dmu_tx_abort(tx);
169  *			goto top;
170  *		}
171  *		dmu_tx_abort(tx);	// abort DMU tx
172  *		ZFS_EXIT(zfsvfs);	// finished in zfs
173  *		return (error);		// really out of space
174  *	}
175  *	error = do_real_work();		// do whatever this VOP does
176  *	if (error == 0)
177  *		zfs_log_*(...);		// on success, make ZIL entry
178  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
179  *	rw_exit(...);			// drop locks
180  *	zfs_dirent_unlock(dl);		// unlock directory entry
181  *	VN_RELE(...);			// release held vnodes
182  *	zil_commit(zilog, foid);	// synchronous when necessary
183  *	ZFS_EXIT(zfsvfs);		// finished in zfs
184  *	return (error);			// done, report error
185  */
186 
187 /* ARGSUSED */
188 static int
189 zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
190 {
191 	znode_t	*zp = VTOZ(*vpp);
192 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
193 
194 	ZFS_ENTER(zfsvfs);
195 	ZFS_VERIFY_ZP(zp);
196 
197 	if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
198 	    ((flag & FAPPEND) == 0)) {
199 		ZFS_EXIT(zfsvfs);
200 		return (SET_ERROR(EPERM));
201 	}
202 
203 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
204 	    ZTOV(zp)->v_type == VREG &&
205 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
206 		if (fs_vscan(*vpp, cr, 0) != 0) {
207 			ZFS_EXIT(zfsvfs);
208 			return (SET_ERROR(EACCES));
209 		}
210 	}
211 
212 	/* Keep a count of the synchronous opens in the znode */
213 	if (flag & (FSYNC | FDSYNC))
214 		atomic_inc_32(&zp->z_sync_cnt);
215 
216 	ZFS_EXIT(zfsvfs);
217 	return (0);
218 }
219 
220 /* ARGSUSED */
221 static int
222 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
223     caller_context_t *ct)
224 {
225 	znode_t	*zp = VTOZ(vp);
226 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
227 
228 	/*
229 	 * Clean up any locks held by this process on the vp.
230 	 */
231 	cleanlocks(vp, ddi_get_pid(), 0);
232 	cleanshares(vp, ddi_get_pid());
233 
234 	ZFS_ENTER(zfsvfs);
235 	ZFS_VERIFY_ZP(zp);
236 
237 	/* Decrement the synchronous opens in the znode */
238 	if ((flag & (FSYNC | FDSYNC)) && (count == 1))
239 		atomic_dec_32(&zp->z_sync_cnt);
240 
241 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
242 	    ZTOV(zp)->v_type == VREG &&
243 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
244 		VERIFY(fs_vscan(vp, cr, 1) == 0);
245 
246 	ZFS_EXIT(zfsvfs);
247 	return (0);
248 }
249 
250 /*
251  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
252  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
253  */
254 static int
255 zfs_holey(vnode_t *vp, int cmd, offset_t *off)
256 {
257 	znode_t	*zp = VTOZ(vp);
258 	uint64_t noff = (uint64_t)*off; /* new offset */
259 	uint64_t file_sz;
260 	int error;
261 	boolean_t hole;
262 
263 	file_sz = zp->z_size;
264 	if (noff >= file_sz)  {
265 		return (SET_ERROR(ENXIO));
266 	}
267 
268 	if (cmd == _FIO_SEEK_HOLE)
269 		hole = B_TRUE;
270 	else
271 		hole = B_FALSE;
272 
273 	error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
274 
275 	if (error == ESRCH)
276 		return (SET_ERROR(ENXIO));
277 
278 	/*
279 	 * We could find a hole that begins after the logical end-of-file,
280 	 * because dmu_offset_next() only works on whole blocks.  If the
281 	 * EOF falls mid-block, then indicate that the "virtual hole"
282 	 * at the end of the file begins at the logical EOF, rather than
283 	 * at the end of the last block.
284 	 */
285 	if (noff > file_sz) {
286 		ASSERT(hole);
287 		noff = file_sz;
288 	}
289 
290 	if (noff < *off)
291 		return (error);
292 	*off = noff;
293 	return (error);
294 }
295 
296 /* ARGSUSED */
297 static int
298 zfs_ioctl(vnode_t *vp, int com, intptr_t data, int flag, cred_t *cred,
299     int *rvalp, caller_context_t *ct)
300 {
301 	offset_t off;
302 	offset_t ndata;
303 	dmu_object_info_t doi;
304 	int error;
305 	zfsvfs_t *zfsvfs;
306 	znode_t *zp;
307 
308 	switch (com) {
309 	case _FIOFFS:
310 	{
311 		return (zfs_sync(vp->v_vfsp, 0, cred));
312 
313 		/*
314 		 * The following two ioctls are used by bfu.  Faking out,
315 		 * necessary to avoid bfu errors.
316 		 */
317 	}
318 	case _FIOGDIO:
319 	case _FIOSDIO:
320 	{
321 		return (0);
322 	}
323 
324 	case _FIO_SEEK_DATA:
325 	case _FIO_SEEK_HOLE:
326 	{
327 		if (ddi_copyin((void *)data, &off, sizeof (off), flag))
328 			return (SET_ERROR(EFAULT));
329 
330 		zp = VTOZ(vp);
331 		zfsvfs = zp->z_zfsvfs;
332 		ZFS_ENTER(zfsvfs);
333 		ZFS_VERIFY_ZP(zp);
334 
335 		/* offset parameter is in/out */
336 		error = zfs_holey(vp, com, &off);
337 		ZFS_EXIT(zfsvfs);
338 		if (error)
339 			return (error);
340 		if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
341 			return (SET_ERROR(EFAULT));
342 		return (0);
343 	}
344 	case _FIO_COUNT_FILLED:
345 	{
346 		/*
347 		 * _FIO_COUNT_FILLED adds a new ioctl command which
348 		 * exposes the number of filled blocks in a
349 		 * ZFS object.
350 		 */
351 		zp = VTOZ(vp);
352 		zfsvfs = zp->z_zfsvfs;
353 		ZFS_ENTER(zfsvfs);
354 		ZFS_VERIFY_ZP(zp);
355 
356 		/*
357 		 * Wait for all dirty blocks for this object
358 		 * to get synced out to disk, and the DMU info
359 		 * updated.
360 		 */
361 		error = dmu_object_wait_synced(zfsvfs->z_os, zp->z_id);
362 		if (error) {
363 			ZFS_EXIT(zfsvfs);
364 			return (error);
365 		}
366 
367 		/*
368 		 * Retrieve fill count from DMU object.
369 		 */
370 		error = dmu_object_info(zfsvfs->z_os, zp->z_id, &doi);
371 		if (error) {
372 			ZFS_EXIT(zfsvfs);
373 			return (error);
374 		}
375 
376 		ndata = doi.doi_fill_count;
377 
378 		ZFS_EXIT(zfsvfs);
379 		if (ddi_copyout(&ndata, (void *)data, sizeof (ndata), flag))
380 			return (SET_ERROR(EFAULT));
381 		return (0);
382 	}
383 	}
384 	return (SET_ERROR(ENOTTY));
385 }
386 
387 /*
388  * Utility functions to map and unmap a single physical page.  These
389  * are used to manage the mappable copies of ZFS file data, and therefore
390  * do not update ref/mod bits.
391  */
392 caddr_t
393 zfs_map_page(page_t *pp, enum seg_rw rw)
394 {
395 	if (kpm_enable)
396 		return (hat_kpm_mapin(pp, 0));
397 	ASSERT(rw == S_READ || rw == S_WRITE);
398 	return (ppmapin(pp, PROT_READ | ((rw == S_WRITE) ? PROT_WRITE : 0),
399 	    (caddr_t)-1));
400 }
401 
402 void
403 zfs_unmap_page(page_t *pp, caddr_t addr)
404 {
405 	if (kpm_enable) {
406 		hat_kpm_mapout(pp, 0, addr);
407 	} else {
408 		ppmapout(addr);
409 	}
410 }
411 
412 /*
413  * When a file is memory mapped, we must keep the IO data synchronized
414  * between the DMU cache and the memory mapped pages.  What this means:
415  *
416  * On Write:	If we find a memory mapped page, we write to *both*
417  *		the page and the dmu buffer.
418  */
419 static void
420 update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid)
421 {
422 	int64_t	off;
423 
424 	off = start & PAGEOFFSET;
425 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
426 		page_t *pp;
427 		uint64_t nbytes = MIN(PAGESIZE - off, len);
428 
429 		if (pp = page_lookup(vp, start, SE_SHARED)) {
430 			caddr_t va;
431 
432 			va = zfs_map_page(pp, S_WRITE);
433 			(void) dmu_read(os, oid, start+off, nbytes, va+off,
434 			    DMU_READ_PREFETCH);
435 			zfs_unmap_page(pp, va);
436 			page_unlock(pp);
437 		}
438 		len -= nbytes;
439 		off = 0;
440 	}
441 }
442 
443 /*
444  * When a file is memory mapped, we must keep the IO data synchronized
445  * between the DMU cache and the memory mapped pages.  What this means:
446  *
447  * On Read:	We "read" preferentially from memory mapped pages,
448  *		else we default from the dmu buffer.
449  *
450  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
451  *	 the file is memory mapped.
452  */
453 static int
454 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
455 {
456 	znode_t *zp = VTOZ(vp);
457 	int64_t	start, off;
458 	int len = nbytes;
459 	int error = 0;
460 
461 	start = uio->uio_loffset;
462 	off = start & PAGEOFFSET;
463 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
464 		page_t *pp;
465 		uint64_t bytes = MIN(PAGESIZE - off, len);
466 
467 		if (pp = page_lookup(vp, start, SE_SHARED)) {
468 			caddr_t va;
469 
470 			va = zfs_map_page(pp, S_READ);
471 			error = uiomove(va + off, bytes, UIO_READ, uio);
472 			zfs_unmap_page(pp, va);
473 			page_unlock(pp);
474 		} else {
475 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
476 			    uio, bytes);
477 		}
478 		len -= bytes;
479 		off = 0;
480 		if (error)
481 			break;
482 	}
483 	return (error);
484 }
485 
486 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
487 
488 /*
489  * Read bytes from specified file into supplied buffer.
490  *
491  *	IN:	vp	- vnode of file to be read from.
492  *		uio	- structure supplying read location, range info,
493  *			  and return buffer.
494  *		ioflag	- SYNC flags; used to provide FRSYNC semantics.
495  *		cr	- credentials of caller.
496  *		ct	- caller context
497  *
498  *	OUT:	uio	- updated offset and range, buffer filled.
499  *
500  *	RETURN:	0 on success, error code on failure.
501  *
502  * Side Effects:
503  *	vp - atime updated if byte count > 0
504  */
505 /* ARGSUSED */
506 static int
507 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
508 {
509 	znode_t		*zp = VTOZ(vp);
510 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
511 	ssize_t		n, nbytes;
512 	int		error = 0;
513 	rl_t		*rl;
514 	xuio_t		*xuio = NULL;
515 
516 	ZFS_ENTER(zfsvfs);
517 	ZFS_VERIFY_ZP(zp);
518 
519 	if (zp->z_pflags & ZFS_AV_QUARANTINED) {
520 		ZFS_EXIT(zfsvfs);
521 		return (SET_ERROR(EACCES));
522 	}
523 
524 	/*
525 	 * Validate file offset
526 	 */
527 	if (uio->uio_loffset < (offset_t)0) {
528 		ZFS_EXIT(zfsvfs);
529 		return (SET_ERROR(EINVAL));
530 	}
531 
532 	/*
533 	 * Fasttrack empty reads
534 	 */
535 	if (uio->uio_resid == 0) {
536 		ZFS_EXIT(zfsvfs);
537 		return (0);
538 	}
539 
540 	/*
541 	 * Check for mandatory locks
542 	 */
543 	if (MANDMODE(zp->z_mode)) {
544 		if (error = chklock(vp, FREAD,
545 		    uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
546 			ZFS_EXIT(zfsvfs);
547 			return (error);
548 		}
549 	}
550 
551 	/*
552 	 * If we're in FRSYNC mode, sync out this znode before reading it.
553 	 */
554 	if (ioflag & FRSYNC || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
555 		zil_commit(zfsvfs->z_log, zp->z_id);
556 
557 	/*
558 	 * Lock the range against changes.
559 	 */
560 	rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
561 
562 	/*
563 	 * If we are reading past end-of-file we can skip
564 	 * to the end; but we might still need to set atime.
565 	 */
566 	if (uio->uio_loffset >= zp->z_size) {
567 		error = 0;
568 		goto out;
569 	}
570 
571 	ASSERT(uio->uio_loffset < zp->z_size);
572 	n = MIN(uio->uio_resid, zp->z_size - uio->uio_loffset);
573 
574 	if ((uio->uio_extflg == UIO_XUIO) &&
575 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY)) {
576 		int nblk;
577 		int blksz = zp->z_blksz;
578 		uint64_t offset = uio->uio_loffset;
579 
580 		xuio = (xuio_t *)uio;
581 		if ((ISP2(blksz))) {
582 			nblk = (P2ROUNDUP(offset + n, blksz) - P2ALIGN(offset,
583 			    blksz)) / blksz;
584 		} else {
585 			ASSERT(offset + n <= blksz);
586 			nblk = 1;
587 		}
588 		(void) dmu_xuio_init(xuio, nblk);
589 
590 		if (vn_has_cached_data(vp)) {
591 			/*
592 			 * For simplicity, we always allocate a full buffer
593 			 * even if we only expect to read a portion of a block.
594 			 */
595 			while (--nblk >= 0) {
596 				(void) dmu_xuio_add(xuio,
597 				    dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
598 				    blksz), 0, blksz);
599 			}
600 		}
601 	}
602 
603 	while (n > 0) {
604 		nbytes = MIN(n, zfs_read_chunk_size -
605 		    P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
606 
607 		if (vn_has_cached_data(vp)) {
608 			error = mappedread(vp, nbytes, uio);
609 		} else {
610 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
611 			    uio, nbytes);
612 		}
613 		if (error) {
614 			/* convert checksum errors into IO errors */
615 			if (error == ECKSUM)
616 				error = SET_ERROR(EIO);
617 			break;
618 		}
619 
620 		n -= nbytes;
621 	}
622 out:
623 	zfs_range_unlock(rl);
624 
625 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
626 	ZFS_EXIT(zfsvfs);
627 	return (error);
628 }
629 
630 /*
631  * Write the bytes to a file.
632  *
633  *	IN:	vp	- vnode of file to be written to.
634  *		uio	- structure supplying write location, range info,
635  *			  and data buffer.
636  *		ioflag	- FAPPEND, FSYNC, and/or FDSYNC.  FAPPEND is
637  *			  set if in append mode.
638  *		cr	- credentials of caller.
639  *		ct	- caller context (NFS/CIFS fem monitor only)
640  *
641  *	OUT:	uio	- updated offset and range.
642  *
643  *	RETURN:	0 on success, error code on failure.
644  *
645  * Timestamps:
646  *	vp - ctime|mtime updated if byte count > 0
647  */
648 
649 /* ARGSUSED */
650 static int
651 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
652 {
653 	znode_t		*zp = VTOZ(vp);
654 	rlim64_t	limit = uio->uio_llimit;
655 	ssize_t		start_resid = uio->uio_resid;
656 	ssize_t		tx_bytes;
657 	uint64_t	end_size;
658 	dmu_tx_t	*tx;
659 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
660 	zilog_t		*zilog;
661 	offset_t	woff;
662 	ssize_t		n, nbytes;
663 	rl_t		*rl;
664 	int		max_blksz = zfsvfs->z_max_blksz;
665 	int		error = 0;
666 	arc_buf_t	*abuf;
667 	iovec_t		*aiov = NULL;
668 	xuio_t		*xuio = NULL;
669 	int		i_iov = 0;
670 	int		iovcnt = uio->uio_iovcnt;
671 	iovec_t		*iovp = uio->uio_iov;
672 	int		write_eof;
673 	int		count = 0;
674 	sa_bulk_attr_t	bulk[4];
675 	uint64_t	mtime[2], ctime[2];
676 
677 	/*
678 	 * Fasttrack empty write
679 	 */
680 	n = start_resid;
681 	if (n == 0)
682 		return (0);
683 
684 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
685 		limit = MAXOFFSET_T;
686 
687 	ZFS_ENTER(zfsvfs);
688 	ZFS_VERIFY_ZP(zp);
689 
690 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
691 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
692 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
693 	    &zp->z_size, 8);
694 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
695 	    &zp->z_pflags, 8);
696 
697 	/*
698 	 * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
699 	 * callers might not be able to detect properly that we are read-only,
700 	 * so check it explicitly here.
701 	 */
702 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
703 		ZFS_EXIT(zfsvfs);
704 		return (SET_ERROR(EROFS));
705 	}
706 
707 	/*
708 	 * If immutable or not appending then return EPERM
709 	 */
710 	if ((zp->z_pflags & (ZFS_IMMUTABLE | ZFS_READONLY)) ||
711 	    ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
712 	    (uio->uio_loffset < zp->z_size))) {
713 		ZFS_EXIT(zfsvfs);
714 		return (SET_ERROR(EPERM));
715 	}
716 
717 	zilog = zfsvfs->z_log;
718 
719 	/*
720 	 * Validate file offset
721 	 */
722 	woff = ioflag & FAPPEND ? zp->z_size : uio->uio_loffset;
723 	if (woff < 0) {
724 		ZFS_EXIT(zfsvfs);
725 		return (SET_ERROR(EINVAL));
726 	}
727 
728 	/*
729 	 * Check for mandatory locks before calling zfs_range_lock()
730 	 * in order to prevent a deadlock with locks set via fcntl().
731 	 */
732 	if (MANDMODE((mode_t)zp->z_mode) &&
733 	    (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
734 		ZFS_EXIT(zfsvfs);
735 		return (error);
736 	}
737 
738 	/*
739 	 * Pre-fault the pages to ensure slow (eg NFS) pages
740 	 * don't hold up txg.
741 	 * Skip this if uio contains loaned arc_buf.
742 	 */
743 	if ((uio->uio_extflg == UIO_XUIO) &&
744 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY))
745 		xuio = (xuio_t *)uio;
746 	else
747 		uio_prefaultpages(MIN(n, max_blksz), uio);
748 
749 	/*
750 	 * If in append mode, set the io offset pointer to eof.
751 	 */
752 	if (ioflag & FAPPEND) {
753 		/*
754 		 * Obtain an appending range lock to guarantee file append
755 		 * semantics.  We reset the write offset once we have the lock.
756 		 */
757 		rl = zfs_range_lock(zp, 0, n, RL_APPEND);
758 		woff = rl->r_off;
759 		if (rl->r_len == UINT64_MAX) {
760 			/*
761 			 * We overlocked the file because this write will cause
762 			 * the file block size to increase.
763 			 * Note that zp_size cannot change with this lock held.
764 			 */
765 			woff = zp->z_size;
766 		}
767 		uio->uio_loffset = woff;
768 	} else {
769 		/*
770 		 * Note that if the file block size will change as a result of
771 		 * this write, then this range lock will lock the entire file
772 		 * so that we can re-write the block safely.
773 		 */
774 		rl = zfs_range_lock(zp, woff, n, RL_WRITER);
775 	}
776 
777 	if (woff >= limit) {
778 		zfs_range_unlock(rl);
779 		ZFS_EXIT(zfsvfs);
780 		return (SET_ERROR(EFBIG));
781 	}
782 
783 	if ((woff + n) > limit || woff > (limit - n))
784 		n = limit - woff;
785 
786 	/* Will this write extend the file length? */
787 	write_eof = (woff + n > zp->z_size);
788 
789 	end_size = MAX(zp->z_size, woff + n);
790 
791 	/*
792 	 * Write the file in reasonable size chunks.  Each chunk is written
793 	 * in a separate transaction; this keeps the intent log records small
794 	 * and allows us to do more fine-grained space accounting.
795 	 */
796 	while (n > 0) {
797 		abuf = NULL;
798 		woff = uio->uio_loffset;
799 		if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
800 		    zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
801 			if (abuf != NULL)
802 				dmu_return_arcbuf(abuf);
803 			error = SET_ERROR(EDQUOT);
804 			break;
805 		}
806 
807 		if (xuio && abuf == NULL) {
808 			ASSERT(i_iov < iovcnt);
809 			aiov = &iovp[i_iov];
810 			abuf = dmu_xuio_arcbuf(xuio, i_iov);
811 			dmu_xuio_clear(xuio, i_iov);
812 			DTRACE_PROBE3(zfs_cp_write, int, i_iov,
813 			    iovec_t *, aiov, arc_buf_t *, abuf);
814 			ASSERT((aiov->iov_base == abuf->b_data) ||
815 			    ((char *)aiov->iov_base - (char *)abuf->b_data +
816 			    aiov->iov_len == arc_buf_size(abuf)));
817 			i_iov++;
818 		} else if (abuf == NULL && n >= max_blksz &&
819 		    woff >= zp->z_size &&
820 		    P2PHASE(woff, max_blksz) == 0 &&
821 		    zp->z_blksz == max_blksz) {
822 			/*
823 			 * This write covers a full block.  "Borrow" a buffer
824 			 * from the dmu so that we can fill it before we enter
825 			 * a transaction.  This avoids the possibility of
826 			 * holding up the transaction if the data copy hangs
827 			 * up on a pagefault (e.g., from an NFS server mapping).
828 			 */
829 			size_t cbytes;
830 
831 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
832 			    max_blksz);
833 			ASSERT(abuf != NULL);
834 			ASSERT(arc_buf_size(abuf) == max_blksz);
835 			if (error = uiocopy(abuf->b_data, max_blksz,
836 			    UIO_WRITE, uio, &cbytes)) {
837 				dmu_return_arcbuf(abuf);
838 				break;
839 			}
840 			ASSERT(cbytes == max_blksz);
841 		}
842 
843 		/*
844 		 * Start a transaction.
845 		 */
846 		tx = dmu_tx_create(zfsvfs->z_os);
847 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
848 		dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
849 		zfs_sa_upgrade_txholds(tx, zp);
850 		error = dmu_tx_assign(tx, TXG_WAIT);
851 		if (error) {
852 			dmu_tx_abort(tx);
853 			if (abuf != NULL)
854 				dmu_return_arcbuf(abuf);
855 			break;
856 		}
857 
858 		/*
859 		 * If zfs_range_lock() over-locked we grow the blocksize
860 		 * and then reduce the lock range.  This will only happen
861 		 * on the first iteration since zfs_range_reduce() will
862 		 * shrink down r_len to the appropriate size.
863 		 */
864 		if (rl->r_len == UINT64_MAX) {
865 			uint64_t new_blksz;
866 
867 			if (zp->z_blksz > max_blksz) {
868 				/*
869 				 * File's blocksize is already larger than the
870 				 * "recordsize" property.  Only let it grow to
871 				 * the next power of 2.
872 				 */
873 				ASSERT(!ISP2(zp->z_blksz));
874 				new_blksz = MIN(end_size,
875 				    1 << highbit64(zp->z_blksz));
876 			} else {
877 				new_blksz = MIN(end_size, max_blksz);
878 			}
879 			zfs_grow_blocksize(zp, new_blksz, tx);
880 			zfs_range_reduce(rl, woff, n);
881 		}
882 
883 		/*
884 		 * XXX - should we really limit each write to z_max_blksz?
885 		 * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
886 		 */
887 		nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
888 
889 		if (abuf == NULL) {
890 			tx_bytes = uio->uio_resid;
891 			error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
892 			    uio, nbytes, tx);
893 			tx_bytes -= uio->uio_resid;
894 		} else {
895 			tx_bytes = nbytes;
896 			ASSERT(xuio == NULL || tx_bytes == aiov->iov_len);
897 			/*
898 			 * If this is not a full block write, but we are
899 			 * extending the file past EOF and this data starts
900 			 * block-aligned, use assign_arcbuf().  Otherwise,
901 			 * write via dmu_write().
902 			 */
903 			if (tx_bytes < max_blksz && (!write_eof ||
904 			    aiov->iov_base != abuf->b_data)) {
905 				ASSERT(xuio);
906 				dmu_write(zfsvfs->z_os, zp->z_id, woff,
907 				    aiov->iov_len, aiov->iov_base, tx);
908 				dmu_return_arcbuf(abuf);
909 				xuio_stat_wbuf_copied();
910 			} else {
911 				ASSERT(xuio || tx_bytes == max_blksz);
912 				dmu_assign_arcbuf(sa_get_db(zp->z_sa_hdl),
913 				    woff, abuf, tx);
914 			}
915 			ASSERT(tx_bytes <= uio->uio_resid);
916 			uioskip(uio, tx_bytes);
917 		}
918 		if (tx_bytes && vn_has_cached_data(vp)) {
919 			update_pages(vp, woff,
920 			    tx_bytes, zfsvfs->z_os, zp->z_id);
921 		}
922 
923 		/*
924 		 * If we made no progress, we're done.  If we made even
925 		 * partial progress, update the znode and ZIL accordingly.
926 		 */
927 		if (tx_bytes == 0) {
928 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
929 			    (void *)&zp->z_size, sizeof (uint64_t), tx);
930 			dmu_tx_commit(tx);
931 			ASSERT(error != 0);
932 			break;
933 		}
934 
935 		/*
936 		 * Clear Set-UID/Set-GID bits on successful write if not
937 		 * privileged and at least one of the excute bits is set.
938 		 *
939 		 * It would be nice to to this after all writes have
940 		 * been done, but that would still expose the ISUID/ISGID
941 		 * to another app after the partial write is committed.
942 		 *
943 		 * Note: we don't call zfs_fuid_map_id() here because
944 		 * user 0 is not an ephemeral uid.
945 		 */
946 		mutex_enter(&zp->z_acl_lock);
947 		if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) |
948 		    (S_IXUSR >> 6))) != 0 &&
949 		    (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
950 		    secpolicy_vnode_setid_retain(cr,
951 		    (zp->z_mode & S_ISUID) != 0 && zp->z_uid == 0) != 0) {
952 			uint64_t newmode;
953 			zp->z_mode &= ~(S_ISUID | S_ISGID);
954 			newmode = zp->z_mode;
955 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
956 			    (void *)&newmode, sizeof (uint64_t), tx);
957 		}
958 		mutex_exit(&zp->z_acl_lock);
959 
960 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
961 		    B_TRUE);
962 
963 		/*
964 		 * Update the file size (zp_size) if it has changed;
965 		 * account for possible concurrent updates.
966 		 */
967 		while ((end_size = zp->z_size) < uio->uio_loffset) {
968 			(void) atomic_cas_64(&zp->z_size, end_size,
969 			    uio->uio_loffset);
970 			ASSERT(error == 0);
971 		}
972 		/*
973 		 * If we are replaying and eof is non zero then force
974 		 * the file size to the specified eof. Note, there's no
975 		 * concurrency during replay.
976 		 */
977 		if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
978 			zp->z_size = zfsvfs->z_replay_eof;
979 
980 		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
981 
982 		zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
983 		dmu_tx_commit(tx);
984 
985 		if (error != 0)
986 			break;
987 		ASSERT(tx_bytes == nbytes);
988 		n -= nbytes;
989 
990 		if (!xuio && n > 0)
991 			uio_prefaultpages(MIN(n, max_blksz), uio);
992 	}
993 
994 	zfs_range_unlock(rl);
995 
996 	/*
997 	 * If we're in replay mode, or we made no progress, return error.
998 	 * Otherwise, it's at least a partial write, so it's successful.
999 	 */
1000 	if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
1001 		ZFS_EXIT(zfsvfs);
1002 		return (error);
1003 	}
1004 
1005 	if (ioflag & (FSYNC | FDSYNC) ||
1006 	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1007 		zil_commit(zilog, zp->z_id);
1008 
1009 	ZFS_EXIT(zfsvfs);
1010 	return (0);
1011 }
1012 
1013 void
1014 zfs_get_done(zgd_t *zgd, int error)
1015 {
1016 	znode_t *zp = zgd->zgd_private;
1017 	objset_t *os = zp->z_zfsvfs->z_os;
1018 
1019 	if (zgd->zgd_db)
1020 		dmu_buf_rele(zgd->zgd_db, zgd);
1021 
1022 	zfs_range_unlock(zgd->zgd_rl);
1023 
1024 	/*
1025 	 * Release the vnode asynchronously as we currently have the
1026 	 * txg stopped from syncing.
1027 	 */
1028 	VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1029 
1030 	if (error == 0 && zgd->zgd_bp)
1031 		zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1032 
1033 	kmem_free(zgd, sizeof (zgd_t));
1034 }
1035 
1036 #ifdef DEBUG
1037 static int zil_fault_io = 0;
1038 #endif
1039 
1040 /*
1041  * Get data to generate a TX_WRITE intent log record.
1042  */
1043 int
1044 zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1045 {
1046 	zfsvfs_t *zfsvfs = arg;
1047 	objset_t *os = zfsvfs->z_os;
1048 	znode_t *zp;
1049 	uint64_t object = lr->lr_foid;
1050 	uint64_t offset = lr->lr_offset;
1051 	uint64_t size = lr->lr_length;
1052 	blkptr_t *bp = &lr->lr_blkptr;
1053 	dmu_buf_t *db;
1054 	zgd_t *zgd;
1055 	int error = 0;
1056 
1057 	ASSERT(zio != NULL);
1058 	ASSERT(size != 0);
1059 
1060 	/*
1061 	 * Nothing to do if the file has been removed
1062 	 */
1063 	if (zfs_zget(zfsvfs, object, &zp) != 0)
1064 		return (SET_ERROR(ENOENT));
1065 	if (zp->z_unlinked) {
1066 		/*
1067 		 * Release the vnode asynchronously as we currently have the
1068 		 * txg stopped from syncing.
1069 		 */
1070 		VN_RELE_ASYNC(ZTOV(zp),
1071 		    dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1072 		return (SET_ERROR(ENOENT));
1073 	}
1074 
1075 	zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1076 	zgd->zgd_zilog = zfsvfs->z_log;
1077 	zgd->zgd_private = zp;
1078 
1079 	/*
1080 	 * Write records come in two flavors: immediate and indirect.
1081 	 * For small writes it's cheaper to store the data with the
1082 	 * log record (immediate); for large writes it's cheaper to
1083 	 * sync the data and get a pointer to it (indirect) so that
1084 	 * we don't have to write the data twice.
1085 	 */
1086 	if (buf != NULL) { /* immediate write */
1087 		zgd->zgd_rl = zfs_range_lock(zp, offset, size, RL_READER);
1088 		/* test for truncation needs to be done while range locked */
1089 		if (offset >= zp->z_size) {
1090 			error = SET_ERROR(ENOENT);
1091 		} else {
1092 			error = dmu_read(os, object, offset, size, buf,
1093 			    DMU_READ_NO_PREFETCH);
1094 		}
1095 		ASSERT(error == 0 || error == ENOENT);
1096 	} else { /* indirect write */
1097 		/*
1098 		 * Have to lock the whole block to ensure when it's
1099 		 * written out and it's checksum is being calculated
1100 		 * that no one can change the data. We need to re-check
1101 		 * blocksize after we get the lock in case it's changed!
1102 		 */
1103 		for (;;) {
1104 			uint64_t blkoff;
1105 			size = zp->z_blksz;
1106 			blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1107 			offset -= blkoff;
1108 			zgd->zgd_rl = zfs_range_lock(zp, offset, size,
1109 			    RL_READER);
1110 			if (zp->z_blksz == size)
1111 				break;
1112 			offset += blkoff;
1113 			zfs_range_unlock(zgd->zgd_rl);
1114 		}
1115 		/* test for truncation needs to be done while range locked */
1116 		if (lr->lr_offset >= zp->z_size)
1117 			error = SET_ERROR(ENOENT);
1118 #ifdef DEBUG
1119 		if (zil_fault_io) {
1120 			error = SET_ERROR(EIO);
1121 			zil_fault_io = 0;
1122 		}
1123 #endif
1124 		if (error == 0)
1125 			error = dmu_buf_hold(os, object, offset, zgd, &db,
1126 			    DMU_READ_NO_PREFETCH);
1127 
1128 		if (error == 0) {
1129 			blkptr_t *obp = dmu_buf_get_blkptr(db);
1130 			if (obp) {
1131 				ASSERT(BP_IS_HOLE(bp));
1132 				*bp = *obp;
1133 			}
1134 
1135 			zgd->zgd_db = db;
1136 			zgd->zgd_bp = bp;
1137 
1138 			ASSERT(db->db_offset == offset);
1139 			ASSERT(db->db_size == size);
1140 
1141 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1142 			    zfs_get_done, zgd);
1143 			ASSERT(error || lr->lr_length <= zp->z_blksz);
1144 
1145 			/*
1146 			 * On success, we need to wait for the write I/O
1147 			 * initiated by dmu_sync() to complete before we can
1148 			 * release this dbuf.  We will finish everything up
1149 			 * in the zfs_get_done() callback.
1150 			 */
1151 			if (error == 0)
1152 				return (0);
1153 
1154 			if (error == EALREADY) {
1155 				lr->lr_common.lrc_txtype = TX_WRITE2;
1156 				error = 0;
1157 			}
1158 		}
1159 	}
1160 
1161 	zfs_get_done(zgd, error);
1162 
1163 	return (error);
1164 }
1165 
1166 /*ARGSUSED*/
1167 static int
1168 zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1169     caller_context_t *ct)
1170 {
1171 	znode_t *zp = VTOZ(vp);
1172 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1173 	int error;
1174 
1175 	ZFS_ENTER(zfsvfs);
1176 	ZFS_VERIFY_ZP(zp);
1177 
1178 	if (flag & V_ACE_MASK)
1179 		error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1180 	else
1181 		error = zfs_zaccess_rwx(zp, mode, flag, cr);
1182 
1183 	ZFS_EXIT(zfsvfs);
1184 	return (error);
1185 }
1186 
1187 /*
1188  * If vnode is for a device return a specfs vnode instead.
1189  */
1190 static int
1191 specvp_check(vnode_t **vpp, cred_t *cr)
1192 {
1193 	int error = 0;
1194 
1195 	if (IS_DEVVP(*vpp)) {
1196 		struct vnode *svp;
1197 
1198 		svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1199 		VN_RELE(*vpp);
1200 		if (svp == NULL)
1201 			error = SET_ERROR(ENOSYS);
1202 		*vpp = svp;
1203 	}
1204 	return (error);
1205 }
1206 
1207 
1208 /*
1209  * Lookup an entry in a directory, or an extended attribute directory.
1210  * If it exists, return a held vnode reference for it.
1211  *
1212  *	IN:	dvp	- vnode of directory to search.
1213  *		nm	- name of entry to lookup.
1214  *		pnp	- full pathname to lookup [UNUSED].
1215  *		flags	- LOOKUP_XATTR set if looking for an attribute.
1216  *		rdir	- root directory vnode [UNUSED].
1217  *		cr	- credentials of caller.
1218  *		ct	- caller context
1219  *		direntflags - directory lookup flags
1220  *		realpnp - returned pathname.
1221  *
1222  *	OUT:	vpp	- vnode of located entry, NULL if not found.
1223  *
1224  *	RETURN:	0 on success, error code on failure.
1225  *
1226  * Timestamps:
1227  *	NA
1228  */
1229 /* ARGSUSED */
1230 static int
1231 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
1232     int flags, vnode_t *rdir, cred_t *cr,  caller_context_t *ct,
1233     int *direntflags, pathname_t *realpnp)
1234 {
1235 	znode_t *zdp = VTOZ(dvp);
1236 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1237 	int	error = 0;
1238 
1239 	/* fast path */
1240 	if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1241 
1242 		if (dvp->v_type != VDIR) {
1243 			return (SET_ERROR(ENOTDIR));
1244 		} else if (zdp->z_sa_hdl == NULL) {
1245 			return (SET_ERROR(EIO));
1246 		}
1247 
1248 		if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1249 			error = zfs_fastaccesschk_execute(zdp, cr);
1250 			if (!error) {
1251 				*vpp = dvp;
1252 				VN_HOLD(*vpp);
1253 				return (0);
1254 			}
1255 			return (error);
1256 		} else {
1257 			vnode_t *tvp = dnlc_lookup(dvp, nm);
1258 
1259 			if (tvp) {
1260 				error = zfs_fastaccesschk_execute(zdp, cr);
1261 				if (error) {
1262 					VN_RELE(tvp);
1263 					return (error);
1264 				}
1265 				if (tvp == DNLC_NO_VNODE) {
1266 					VN_RELE(tvp);
1267 					return (SET_ERROR(ENOENT));
1268 				} else {
1269 					*vpp = tvp;
1270 					return (specvp_check(vpp, cr));
1271 				}
1272 			}
1273 		}
1274 	}
1275 
1276 	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1277 
1278 	ZFS_ENTER(zfsvfs);
1279 	ZFS_VERIFY_ZP(zdp);
1280 
1281 	*vpp = NULL;
1282 
1283 	if (flags & LOOKUP_XATTR) {
1284 		/*
1285 		 * If the xattr property is off, refuse the lookup request.
1286 		 */
1287 		if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1288 			ZFS_EXIT(zfsvfs);
1289 			return (SET_ERROR(EINVAL));
1290 		}
1291 
1292 		/*
1293 		 * We don't allow recursive attributes..
1294 		 * Maybe someday we will.
1295 		 */
1296 		if (zdp->z_pflags & ZFS_XATTR) {
1297 			ZFS_EXIT(zfsvfs);
1298 			return (SET_ERROR(EINVAL));
1299 		}
1300 
1301 		if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1302 			ZFS_EXIT(zfsvfs);
1303 			return (error);
1304 		}
1305 
1306 		/*
1307 		 * Do we have permission to get into attribute directory?
1308 		 */
1309 
1310 		if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1311 		    B_FALSE, cr)) {
1312 			VN_RELE(*vpp);
1313 			*vpp = NULL;
1314 		}
1315 
1316 		ZFS_EXIT(zfsvfs);
1317 		return (error);
1318 	}
1319 
1320 	if (dvp->v_type != VDIR) {
1321 		ZFS_EXIT(zfsvfs);
1322 		return (SET_ERROR(ENOTDIR));
1323 	}
1324 
1325 	/*
1326 	 * Check accessibility of directory.
1327 	 */
1328 
1329 	if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr)) {
1330 		ZFS_EXIT(zfsvfs);
1331 		return (error);
1332 	}
1333 
1334 	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1335 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1336 		ZFS_EXIT(zfsvfs);
1337 		return (SET_ERROR(EILSEQ));
1338 	}
1339 
1340 	error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1341 	if (error == 0)
1342 		error = specvp_check(vpp, cr);
1343 
1344 	ZFS_EXIT(zfsvfs);
1345 	return (error);
1346 }
1347 
1348 /*
1349  * Attempt to create a new entry in a directory.  If the entry
1350  * already exists, truncate the file if permissible, else return
1351  * an error.  Return the vp of the created or trunc'd file.
1352  *
1353  *	IN:	dvp	- vnode of directory to put new file entry in.
1354  *		name	- name of new file entry.
1355  *		vap	- attributes of new file.
1356  *		excl	- flag indicating exclusive or non-exclusive mode.
1357  *		mode	- mode to open file with.
1358  *		cr	- credentials of caller.
1359  *		flag	- large file flag [UNUSED].
1360  *		ct	- caller context
1361  *		vsecp	- ACL to be set
1362  *
1363  *	OUT:	vpp	- vnode of created or trunc'd entry.
1364  *
1365  *	RETURN:	0 on success, error code on failure.
1366  *
1367  * Timestamps:
1368  *	dvp - ctime|mtime updated if new entry created
1369  *	 vp - ctime|mtime always, atime if new
1370  */
1371 
1372 /* ARGSUSED */
1373 static int
1374 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, vcexcl_t excl,
1375     int mode, vnode_t **vpp, cred_t *cr, int flag, caller_context_t *ct,
1376     vsecattr_t *vsecp)
1377 {
1378 	znode_t		*zp, *dzp = VTOZ(dvp);
1379 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1380 	zilog_t		*zilog;
1381 	objset_t	*os;
1382 	zfs_dirlock_t	*dl;
1383 	dmu_tx_t	*tx;
1384 	int		error;
1385 	ksid_t		*ksid;
1386 	uid_t		uid;
1387 	gid_t		gid = crgetgid(cr);
1388 	zfs_acl_ids_t   acl_ids;
1389 	boolean_t	fuid_dirtied;
1390 	boolean_t	have_acl = B_FALSE;
1391 	boolean_t	waited = B_FALSE;
1392 
1393 	/*
1394 	 * If we have an ephemeral id, ACL, or XVATTR then
1395 	 * make sure file system is at proper version
1396 	 */
1397 
1398 	ksid = crgetsid(cr, KSID_OWNER);
1399 	if (ksid)
1400 		uid = ksid_getid(ksid);
1401 	else
1402 		uid = crgetuid(cr);
1403 
1404 	if (zfsvfs->z_use_fuids == B_FALSE &&
1405 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1406 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1407 		return (SET_ERROR(EINVAL));
1408 
1409 	ZFS_ENTER(zfsvfs);
1410 	ZFS_VERIFY_ZP(dzp);
1411 	os = zfsvfs->z_os;
1412 	zilog = zfsvfs->z_log;
1413 
1414 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1415 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1416 		ZFS_EXIT(zfsvfs);
1417 		return (SET_ERROR(EILSEQ));
1418 	}
1419 
1420 	if (vap->va_mask & AT_XVATTR) {
1421 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1422 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1423 			ZFS_EXIT(zfsvfs);
1424 			return (error);
1425 		}
1426 	}
1427 top:
1428 	*vpp = NULL;
1429 
1430 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1431 		vap->va_mode &= ~VSVTX;
1432 
1433 	if (*name == '\0') {
1434 		/*
1435 		 * Null component name refers to the directory itself.
1436 		 */
1437 		VN_HOLD(dvp);
1438 		zp = dzp;
1439 		dl = NULL;
1440 		error = 0;
1441 	} else {
1442 		/* possible VN_HOLD(zp) */
1443 		int zflg = 0;
1444 
1445 		if (flag & FIGNORECASE)
1446 			zflg |= ZCILOOK;
1447 
1448 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1449 		    NULL, NULL);
1450 		if (error) {
1451 			if (have_acl)
1452 				zfs_acl_ids_free(&acl_ids);
1453 			if (strcmp(name, "..") == 0)
1454 				error = SET_ERROR(EISDIR);
1455 			ZFS_EXIT(zfsvfs);
1456 			return (error);
1457 		}
1458 	}
1459 
1460 	if (zp == NULL) {
1461 		uint64_t txtype;
1462 
1463 		/*
1464 		 * Create a new file object and update the directory
1465 		 * to reference it.
1466 		 */
1467 		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1468 			if (have_acl)
1469 				zfs_acl_ids_free(&acl_ids);
1470 			goto out;
1471 		}
1472 
1473 		/*
1474 		 * We only support the creation of regular files in
1475 		 * extended attribute directories.
1476 		 */
1477 
1478 		if ((dzp->z_pflags & ZFS_XATTR) &&
1479 		    (vap->va_type != VREG)) {
1480 			if (have_acl)
1481 				zfs_acl_ids_free(&acl_ids);
1482 			error = SET_ERROR(EINVAL);
1483 			goto out;
1484 		}
1485 
1486 		if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
1487 		    cr, vsecp, &acl_ids)) != 0)
1488 			goto out;
1489 		have_acl = B_TRUE;
1490 
1491 		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1492 			zfs_acl_ids_free(&acl_ids);
1493 			error = SET_ERROR(EDQUOT);
1494 			goto out;
1495 		}
1496 
1497 		tx = dmu_tx_create(os);
1498 
1499 		dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1500 		    ZFS_SA_BASE_ATTR_SIZE);
1501 
1502 		fuid_dirtied = zfsvfs->z_fuid_dirty;
1503 		if (fuid_dirtied)
1504 			zfs_fuid_txhold(zfsvfs, tx);
1505 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1506 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1507 		if (!zfsvfs->z_use_sa &&
1508 		    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1509 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1510 			    0, acl_ids.z_aclp->z_acl_bytes);
1511 		}
1512 		error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1513 		if (error) {
1514 			zfs_dirent_unlock(dl);
1515 			if (error == ERESTART) {
1516 				waited = B_TRUE;
1517 				dmu_tx_wait(tx);
1518 				dmu_tx_abort(tx);
1519 				goto top;
1520 			}
1521 			zfs_acl_ids_free(&acl_ids);
1522 			dmu_tx_abort(tx);
1523 			ZFS_EXIT(zfsvfs);
1524 			return (error);
1525 		}
1526 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1527 
1528 		if (fuid_dirtied)
1529 			zfs_fuid_sync(zfsvfs, tx);
1530 
1531 		(void) zfs_link_create(dl, zp, tx, ZNEW);
1532 		txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1533 		if (flag & FIGNORECASE)
1534 			txtype |= TX_CI;
1535 		zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1536 		    vsecp, acl_ids.z_fuidp, vap);
1537 		zfs_acl_ids_free(&acl_ids);
1538 		dmu_tx_commit(tx);
1539 	} else {
1540 		int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1541 
1542 		if (have_acl)
1543 			zfs_acl_ids_free(&acl_ids);
1544 		have_acl = B_FALSE;
1545 
1546 		/*
1547 		 * A directory entry already exists for this name.
1548 		 */
1549 		/*
1550 		 * Can't truncate an existing file if in exclusive mode.
1551 		 */
1552 		if (excl == EXCL) {
1553 			error = SET_ERROR(EEXIST);
1554 			goto out;
1555 		}
1556 		/*
1557 		 * Can't open a directory for writing.
1558 		 */
1559 		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1560 			error = SET_ERROR(EISDIR);
1561 			goto out;
1562 		}
1563 		/*
1564 		 * Verify requested access to file.
1565 		 */
1566 		if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1567 			goto out;
1568 		}
1569 
1570 		mutex_enter(&dzp->z_lock);
1571 		dzp->z_seq++;
1572 		mutex_exit(&dzp->z_lock);
1573 
1574 		/*
1575 		 * Truncate regular files if requested.
1576 		 */
1577 		if ((ZTOV(zp)->v_type == VREG) &&
1578 		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1579 			/* we can't hold any locks when calling zfs_freesp() */
1580 			zfs_dirent_unlock(dl);
1581 			dl = NULL;
1582 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1583 			if (error == 0) {
1584 				vnevent_create(ZTOV(zp), ct);
1585 			}
1586 		}
1587 	}
1588 out:
1589 
1590 	if (dl)
1591 		zfs_dirent_unlock(dl);
1592 
1593 	if (error) {
1594 		if (zp)
1595 			VN_RELE(ZTOV(zp));
1596 	} else {
1597 		*vpp = ZTOV(zp);
1598 		error = specvp_check(vpp, cr);
1599 	}
1600 
1601 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1602 		zil_commit(zilog, 0);
1603 
1604 	ZFS_EXIT(zfsvfs);
1605 	return (error);
1606 }
1607 
1608 /*
1609  * Remove an entry from a directory.
1610  *
1611  *	IN:	dvp	- vnode of directory to remove entry from.
1612  *		name	- name of entry to remove.
1613  *		cr	- credentials of caller.
1614  *		ct	- caller context
1615  *		flags	- case flags
1616  *
1617  *	RETURN:	0 on success, error code on failure.
1618  *
1619  * Timestamps:
1620  *	dvp - ctime|mtime
1621  *	 vp - ctime (if nlink > 0)
1622  */
1623 
1624 uint64_t null_xattr = 0;
1625 
1626 /*ARGSUSED*/
1627 static int
1628 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1629     int flags)
1630 {
1631 	znode_t		*zp, *dzp = VTOZ(dvp);
1632 	znode_t		*xzp;
1633 	vnode_t		*vp;
1634 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1635 	zilog_t		*zilog;
1636 	uint64_t	acl_obj, xattr_obj;
1637 	uint64_t	xattr_obj_unlinked = 0;
1638 	uint64_t	obj = 0;
1639 	zfs_dirlock_t	*dl;
1640 	dmu_tx_t	*tx;
1641 	boolean_t	may_delete_now, delete_now = FALSE;
1642 	boolean_t	unlinked, toobig = FALSE;
1643 	uint64_t	txtype;
1644 	pathname_t	*realnmp = NULL;
1645 	pathname_t	realnm;
1646 	int		error;
1647 	int		zflg = ZEXISTS;
1648 	boolean_t	waited = B_FALSE;
1649 
1650 	ZFS_ENTER(zfsvfs);
1651 	ZFS_VERIFY_ZP(dzp);
1652 	zilog = zfsvfs->z_log;
1653 
1654 	if (flags & FIGNORECASE) {
1655 		zflg |= ZCILOOK;
1656 		pn_alloc(&realnm);
1657 		realnmp = &realnm;
1658 	}
1659 
1660 top:
1661 	xattr_obj = 0;
1662 	xzp = NULL;
1663 	/*
1664 	 * Attempt to lock directory; fail if entry doesn't exist.
1665 	 */
1666 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1667 	    NULL, realnmp)) {
1668 		if (realnmp)
1669 			pn_free(realnmp);
1670 		ZFS_EXIT(zfsvfs);
1671 		return (error);
1672 	}
1673 
1674 	vp = ZTOV(zp);
1675 
1676 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1677 		goto out;
1678 	}
1679 
1680 	/*
1681 	 * Need to use rmdir for removing directories.
1682 	 */
1683 	if (vp->v_type == VDIR) {
1684 		error = SET_ERROR(EPERM);
1685 		goto out;
1686 	}
1687 
1688 	vnevent_remove(vp, dvp, name, ct);
1689 
1690 	if (realnmp)
1691 		dnlc_remove(dvp, realnmp->pn_buf);
1692 	else
1693 		dnlc_remove(dvp, name);
1694 
1695 	mutex_enter(&vp->v_lock);
1696 	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1697 	mutex_exit(&vp->v_lock);
1698 
1699 	/*
1700 	 * We may delete the znode now, or we may put it in the unlinked set;
1701 	 * it depends on whether we're the last link, and on whether there are
1702 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1703 	 * allow for either case.
1704 	 */
1705 	obj = zp->z_id;
1706 	tx = dmu_tx_create(zfsvfs->z_os);
1707 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1708 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1709 	zfs_sa_upgrade_txholds(tx, zp);
1710 	zfs_sa_upgrade_txholds(tx, dzp);
1711 	if (may_delete_now) {
1712 		toobig =
1713 		    zp->z_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1714 		/* if the file is too big, only hold_free a token amount */
1715 		dmu_tx_hold_free(tx, zp->z_id, 0,
1716 		    (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1717 	}
1718 
1719 	/* are there any extended attributes? */
1720 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1721 	    &xattr_obj, sizeof (xattr_obj));
1722 	if (error == 0 && xattr_obj) {
1723 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1724 		ASSERT0(error);
1725 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1726 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1727 	}
1728 
1729 	mutex_enter(&zp->z_lock);
1730 	if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1731 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1732 	mutex_exit(&zp->z_lock);
1733 
1734 	/* charge as an update -- would be nice not to charge at all */
1735 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1736 
1737 	/*
1738 	 * Mark this transaction as typically resulting in a net free of space
1739 	 */
1740 	dmu_tx_mark_netfree(tx);
1741 
1742 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1743 	if (error) {
1744 		zfs_dirent_unlock(dl);
1745 		VN_RELE(vp);
1746 		if (xzp)
1747 			VN_RELE(ZTOV(xzp));
1748 		if (error == ERESTART) {
1749 			waited = B_TRUE;
1750 			dmu_tx_wait(tx);
1751 			dmu_tx_abort(tx);
1752 			goto top;
1753 		}
1754 		if (realnmp)
1755 			pn_free(realnmp);
1756 		dmu_tx_abort(tx);
1757 		ZFS_EXIT(zfsvfs);
1758 		return (error);
1759 	}
1760 
1761 	/*
1762 	 * Remove the directory entry.
1763 	 */
1764 	error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1765 
1766 	if (error) {
1767 		dmu_tx_commit(tx);
1768 		goto out;
1769 	}
1770 
1771 	if (unlinked) {
1772 		/*
1773 		 * Hold z_lock so that we can make sure that the ACL obj
1774 		 * hasn't changed.  Could have been deleted due to
1775 		 * zfs_sa_upgrade().
1776 		 */
1777 		mutex_enter(&zp->z_lock);
1778 		mutex_enter(&vp->v_lock);
1779 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1780 		    &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1781 		delete_now = may_delete_now && !toobig &&
1782 		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1783 		    xattr_obj == xattr_obj_unlinked && zfs_external_acl(zp) ==
1784 		    acl_obj;
1785 		mutex_exit(&vp->v_lock);
1786 	}
1787 
1788 	if (delete_now) {
1789 		if (xattr_obj_unlinked) {
1790 			ASSERT3U(xzp->z_links, ==, 2);
1791 			mutex_enter(&xzp->z_lock);
1792 			xzp->z_unlinked = 1;
1793 			xzp->z_links = 0;
1794 			error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1795 			    &xzp->z_links, sizeof (xzp->z_links), tx);
1796 			ASSERT3U(error,  ==,  0);
1797 			mutex_exit(&xzp->z_lock);
1798 			zfs_unlinked_add(xzp, tx);
1799 
1800 			if (zp->z_is_sa)
1801 				error = sa_remove(zp->z_sa_hdl,
1802 				    SA_ZPL_XATTR(zfsvfs), tx);
1803 			else
1804 				error = sa_update(zp->z_sa_hdl,
1805 				    SA_ZPL_XATTR(zfsvfs), &null_xattr,
1806 				    sizeof (uint64_t), tx);
1807 			ASSERT0(error);
1808 		}
1809 		mutex_enter(&vp->v_lock);
1810 		vp->v_count--;
1811 		ASSERT0(vp->v_count);
1812 		mutex_exit(&vp->v_lock);
1813 		mutex_exit(&zp->z_lock);
1814 		zfs_znode_delete(zp, tx);
1815 	} else if (unlinked) {
1816 		mutex_exit(&zp->z_lock);
1817 		zfs_unlinked_add(zp, tx);
1818 	}
1819 
1820 	txtype = TX_REMOVE;
1821 	if (flags & FIGNORECASE)
1822 		txtype |= TX_CI;
1823 	zfs_log_remove(zilog, tx, txtype, dzp, name, obj);
1824 
1825 	dmu_tx_commit(tx);
1826 out:
1827 	if (realnmp)
1828 		pn_free(realnmp);
1829 
1830 	zfs_dirent_unlock(dl);
1831 
1832 	if (!delete_now)
1833 		VN_RELE(vp);
1834 	if (xzp)
1835 		VN_RELE(ZTOV(xzp));
1836 
1837 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1838 		zil_commit(zilog, 0);
1839 
1840 	ZFS_EXIT(zfsvfs);
1841 	return (error);
1842 }
1843 
1844 /*
1845  * Create a new directory and insert it into dvp using the name
1846  * provided.  Return a pointer to the inserted directory.
1847  *
1848  *	IN:	dvp	- vnode of directory to add subdir to.
1849  *		dirname	- name of new directory.
1850  *		vap	- attributes of new directory.
1851  *		cr	- credentials of caller.
1852  *		ct	- caller context
1853  *		flags	- case flags
1854  *		vsecp	- ACL to be set
1855  *
1856  *	OUT:	vpp	- vnode of created directory.
1857  *
1858  *	RETURN:	0 on success, error code on failure.
1859  *
1860  * Timestamps:
1861  *	dvp - ctime|mtime updated
1862  *	 vp - ctime|mtime|atime updated
1863  */
1864 /*ARGSUSED*/
1865 static int
1866 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1867     caller_context_t *ct, int flags, vsecattr_t *vsecp)
1868 {
1869 	znode_t		*zp, *dzp = VTOZ(dvp);
1870 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1871 	zilog_t		*zilog;
1872 	zfs_dirlock_t	*dl;
1873 	uint64_t	txtype;
1874 	dmu_tx_t	*tx;
1875 	int		error;
1876 	int		zf = ZNEW;
1877 	ksid_t		*ksid;
1878 	uid_t		uid;
1879 	gid_t		gid = crgetgid(cr);
1880 	zfs_acl_ids_t   acl_ids;
1881 	boolean_t	fuid_dirtied;
1882 	boolean_t	waited = B_FALSE;
1883 
1884 	ASSERT(vap->va_type == VDIR);
1885 
1886 	/*
1887 	 * If we have an ephemeral id, ACL, or XVATTR then
1888 	 * make sure file system is at proper version
1889 	 */
1890 
1891 	ksid = crgetsid(cr, KSID_OWNER);
1892 	if (ksid)
1893 		uid = ksid_getid(ksid);
1894 	else
1895 		uid = crgetuid(cr);
1896 	if (zfsvfs->z_use_fuids == B_FALSE &&
1897 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1898 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1899 		return (SET_ERROR(EINVAL));
1900 
1901 	ZFS_ENTER(zfsvfs);
1902 	ZFS_VERIFY_ZP(dzp);
1903 	zilog = zfsvfs->z_log;
1904 
1905 	if (dzp->z_pflags & ZFS_XATTR) {
1906 		ZFS_EXIT(zfsvfs);
1907 		return (SET_ERROR(EINVAL));
1908 	}
1909 
1910 	if (zfsvfs->z_utf8 && u8_validate(dirname,
1911 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1912 		ZFS_EXIT(zfsvfs);
1913 		return (SET_ERROR(EILSEQ));
1914 	}
1915 	if (flags & FIGNORECASE)
1916 		zf |= ZCILOOK;
1917 
1918 	if (vap->va_mask & AT_XVATTR) {
1919 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1920 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1921 			ZFS_EXIT(zfsvfs);
1922 			return (error);
1923 		}
1924 	}
1925 
1926 	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1927 	    vsecp, &acl_ids)) != 0) {
1928 		ZFS_EXIT(zfsvfs);
1929 		return (error);
1930 	}
1931 	/*
1932 	 * First make sure the new directory doesn't exist.
1933 	 *
1934 	 * Existence is checked first to make sure we don't return
1935 	 * EACCES instead of EEXIST which can cause some applications
1936 	 * to fail.
1937 	 */
1938 top:
1939 	*vpp = NULL;
1940 
1941 	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
1942 	    NULL, NULL)) {
1943 		zfs_acl_ids_free(&acl_ids);
1944 		ZFS_EXIT(zfsvfs);
1945 		return (error);
1946 	}
1947 
1948 	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
1949 		zfs_acl_ids_free(&acl_ids);
1950 		zfs_dirent_unlock(dl);
1951 		ZFS_EXIT(zfsvfs);
1952 		return (error);
1953 	}
1954 
1955 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1956 		zfs_acl_ids_free(&acl_ids);
1957 		zfs_dirent_unlock(dl);
1958 		ZFS_EXIT(zfsvfs);
1959 		return (SET_ERROR(EDQUOT));
1960 	}
1961 
1962 	/*
1963 	 * Add a new entry to the directory.
1964 	 */
1965 	tx = dmu_tx_create(zfsvfs->z_os);
1966 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1967 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1968 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1969 	if (fuid_dirtied)
1970 		zfs_fuid_txhold(zfsvfs, tx);
1971 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1972 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1973 		    acl_ids.z_aclp->z_acl_bytes);
1974 	}
1975 
1976 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1977 	    ZFS_SA_BASE_ATTR_SIZE);
1978 
1979 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1980 	if (error) {
1981 		zfs_dirent_unlock(dl);
1982 		if (error == ERESTART) {
1983 			waited = B_TRUE;
1984 			dmu_tx_wait(tx);
1985 			dmu_tx_abort(tx);
1986 			goto top;
1987 		}
1988 		zfs_acl_ids_free(&acl_ids);
1989 		dmu_tx_abort(tx);
1990 		ZFS_EXIT(zfsvfs);
1991 		return (error);
1992 	}
1993 
1994 	/*
1995 	 * Create new node.
1996 	 */
1997 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1998 
1999 	if (fuid_dirtied)
2000 		zfs_fuid_sync(zfsvfs, tx);
2001 
2002 	/*
2003 	 * Now put new name in parent dir.
2004 	 */
2005 	(void) zfs_link_create(dl, zp, tx, ZNEW);
2006 
2007 	*vpp = ZTOV(zp);
2008 
2009 	txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
2010 	if (flags & FIGNORECASE)
2011 		txtype |= TX_CI;
2012 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
2013 	    acl_ids.z_fuidp, vap);
2014 
2015 	zfs_acl_ids_free(&acl_ids);
2016 
2017 	dmu_tx_commit(tx);
2018 
2019 	zfs_dirent_unlock(dl);
2020 
2021 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2022 		zil_commit(zilog, 0);
2023 
2024 	ZFS_EXIT(zfsvfs);
2025 	return (0);
2026 }
2027 
2028 /*
2029  * Remove a directory subdir entry.  If the current working
2030  * directory is the same as the subdir to be removed, the
2031  * remove will fail.
2032  *
2033  *	IN:	dvp	- vnode of directory to remove from.
2034  *		name	- name of directory to be removed.
2035  *		cwd	- vnode of current working directory.
2036  *		cr	- credentials of caller.
2037  *		ct	- caller context
2038  *		flags	- case flags
2039  *
2040  *	RETURN:	0 on success, error code on failure.
2041  *
2042  * Timestamps:
2043  *	dvp - ctime|mtime updated
2044  */
2045 /*ARGSUSED*/
2046 static int
2047 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2048     caller_context_t *ct, int flags)
2049 {
2050 	znode_t		*dzp = VTOZ(dvp);
2051 	znode_t		*zp;
2052 	vnode_t		*vp;
2053 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2054 	zilog_t		*zilog;
2055 	zfs_dirlock_t	*dl;
2056 	dmu_tx_t	*tx;
2057 	int		error;
2058 	int		zflg = ZEXISTS;
2059 	boolean_t	waited = B_FALSE;
2060 
2061 	ZFS_ENTER(zfsvfs);
2062 	ZFS_VERIFY_ZP(dzp);
2063 	zilog = zfsvfs->z_log;
2064 
2065 	if (flags & FIGNORECASE)
2066 		zflg |= ZCILOOK;
2067 top:
2068 	zp = NULL;
2069 
2070 	/*
2071 	 * Attempt to lock directory; fail if entry doesn't exist.
2072 	 */
2073 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2074 	    NULL, NULL)) {
2075 		ZFS_EXIT(zfsvfs);
2076 		return (error);
2077 	}
2078 
2079 	vp = ZTOV(zp);
2080 
2081 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2082 		goto out;
2083 	}
2084 
2085 	if (vp->v_type != VDIR) {
2086 		error = SET_ERROR(ENOTDIR);
2087 		goto out;
2088 	}
2089 
2090 	if (vp == cwd) {
2091 		error = SET_ERROR(EINVAL);
2092 		goto out;
2093 	}
2094 
2095 	vnevent_rmdir(vp, dvp, name, ct);
2096 
2097 	/*
2098 	 * Grab a lock on the directory to make sure that noone is
2099 	 * trying to add (or lookup) entries while we are removing it.
2100 	 */
2101 	rw_enter(&zp->z_name_lock, RW_WRITER);
2102 
2103 	/*
2104 	 * Grab a lock on the parent pointer to make sure we play well
2105 	 * with the treewalk and directory rename code.
2106 	 */
2107 	rw_enter(&zp->z_parent_lock, RW_WRITER);
2108 
2109 	tx = dmu_tx_create(zfsvfs->z_os);
2110 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2111 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2112 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2113 	zfs_sa_upgrade_txholds(tx, zp);
2114 	zfs_sa_upgrade_txholds(tx, dzp);
2115 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
2116 	if (error) {
2117 		rw_exit(&zp->z_parent_lock);
2118 		rw_exit(&zp->z_name_lock);
2119 		zfs_dirent_unlock(dl);
2120 		VN_RELE(vp);
2121 		if (error == ERESTART) {
2122 			waited = B_TRUE;
2123 			dmu_tx_wait(tx);
2124 			dmu_tx_abort(tx);
2125 			goto top;
2126 		}
2127 		dmu_tx_abort(tx);
2128 		ZFS_EXIT(zfsvfs);
2129 		return (error);
2130 	}
2131 
2132 	error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2133 
2134 	if (error == 0) {
2135 		uint64_t txtype = TX_RMDIR;
2136 		if (flags & FIGNORECASE)
2137 			txtype |= TX_CI;
2138 		zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT);
2139 	}
2140 
2141 	dmu_tx_commit(tx);
2142 
2143 	rw_exit(&zp->z_parent_lock);
2144 	rw_exit(&zp->z_name_lock);
2145 out:
2146 	zfs_dirent_unlock(dl);
2147 
2148 	VN_RELE(vp);
2149 
2150 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2151 		zil_commit(zilog, 0);
2152 
2153 	ZFS_EXIT(zfsvfs);
2154 	return (error);
2155 }
2156 
2157 /*
2158  * Read as many directory entries as will fit into the provided
2159  * buffer from the given directory cursor position (specified in
2160  * the uio structure).
2161  *
2162  *	IN:	vp	- vnode of directory to read.
2163  *		uio	- structure supplying read location, range info,
2164  *			  and return buffer.
2165  *		cr	- credentials of caller.
2166  *		ct	- caller context
2167  *		flags	- case flags
2168  *
2169  *	OUT:	uio	- updated offset and range, buffer filled.
2170  *		eofp	- set to true if end-of-file detected.
2171  *
2172  *	RETURN:	0 on success, error code on failure.
2173  *
2174  * Timestamps:
2175  *	vp - atime updated
2176  *
2177  * Note that the low 4 bits of the cookie returned by zap is always zero.
2178  * This allows us to use the low range for "special" directory entries:
2179  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2180  * we use the offset 2 for the '.zfs' directory.
2181  */
2182 /* ARGSUSED */
2183 static int
2184 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp,
2185     caller_context_t *ct, int flags)
2186 {
2187 	znode_t		*zp = VTOZ(vp);
2188 	iovec_t		*iovp;
2189 	edirent_t	*eodp;
2190 	dirent64_t	*odp;
2191 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2192 	objset_t	*os;
2193 	caddr_t		outbuf;
2194 	size_t		bufsize;
2195 	zap_cursor_t	zc;
2196 	zap_attribute_t	zap;
2197 	uint_t		bytes_wanted;
2198 	uint64_t	offset; /* must be unsigned; checks for < 1 */
2199 	uint64_t	parent;
2200 	int		local_eof;
2201 	int		outcount;
2202 	int		error;
2203 	uint8_t		prefetch;
2204 	boolean_t	check_sysattrs;
2205 
2206 	ZFS_ENTER(zfsvfs);
2207 	ZFS_VERIFY_ZP(zp);
2208 
2209 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2210 	    &parent, sizeof (parent))) != 0) {
2211 		ZFS_EXIT(zfsvfs);
2212 		return (error);
2213 	}
2214 
2215 	/*
2216 	 * If we are not given an eof variable,
2217 	 * use a local one.
2218 	 */
2219 	if (eofp == NULL)
2220 		eofp = &local_eof;
2221 
2222 	/*
2223 	 * Check for valid iov_len.
2224 	 */
2225 	if (uio->uio_iov->iov_len <= 0) {
2226 		ZFS_EXIT(zfsvfs);
2227 		return (SET_ERROR(EINVAL));
2228 	}
2229 
2230 	/*
2231 	 * Quit if directory has been removed (posix)
2232 	 */
2233 	if ((*eofp = zp->z_unlinked) != 0) {
2234 		ZFS_EXIT(zfsvfs);
2235 		return (0);
2236 	}
2237 
2238 	error = 0;
2239 	os = zfsvfs->z_os;
2240 	offset = uio->uio_loffset;
2241 	prefetch = zp->z_zn_prefetch;
2242 
2243 	/*
2244 	 * Initialize the iterator cursor.
2245 	 */
2246 	if (offset <= 3) {
2247 		/*
2248 		 * Start iteration from the beginning of the directory.
2249 		 */
2250 		zap_cursor_init(&zc, os, zp->z_id);
2251 	} else {
2252 		/*
2253 		 * The offset is a serialized cursor.
2254 		 */
2255 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2256 	}
2257 
2258 	/*
2259 	 * Get space to change directory entries into fs independent format.
2260 	 */
2261 	iovp = uio->uio_iov;
2262 	bytes_wanted = iovp->iov_len;
2263 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2264 		bufsize = bytes_wanted;
2265 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
2266 		odp = (struct dirent64 *)outbuf;
2267 	} else {
2268 		bufsize = bytes_wanted;
2269 		outbuf = NULL;
2270 		odp = (struct dirent64 *)iovp->iov_base;
2271 	}
2272 	eodp = (struct edirent *)odp;
2273 
2274 	/*
2275 	 * If this VFS supports the system attribute view interface; and
2276 	 * we're looking at an extended attribute directory; and we care
2277 	 * about normalization conflicts on this vfs; then we must check
2278 	 * for normalization conflicts with the sysattr name space.
2279 	 */
2280 	check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2281 	    (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2282 	    (flags & V_RDDIR_ENTFLAGS);
2283 
2284 	/*
2285 	 * Transform to file-system independent format
2286 	 */
2287 	outcount = 0;
2288 	while (outcount < bytes_wanted) {
2289 		ino64_t objnum;
2290 		ushort_t reclen;
2291 		off64_t *next = NULL;
2292 
2293 		/*
2294 		 * Special case `.', `..', and `.zfs'.
2295 		 */
2296 		if (offset == 0) {
2297 			(void) strcpy(zap.za_name, ".");
2298 			zap.za_normalization_conflict = 0;
2299 			objnum = zp->z_id;
2300 		} else if (offset == 1) {
2301 			(void) strcpy(zap.za_name, "..");
2302 			zap.za_normalization_conflict = 0;
2303 			objnum = parent;
2304 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
2305 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2306 			zap.za_normalization_conflict = 0;
2307 			objnum = ZFSCTL_INO_ROOT;
2308 		} else {
2309 			/*
2310 			 * Grab next entry.
2311 			 */
2312 			if (error = zap_cursor_retrieve(&zc, &zap)) {
2313 				if ((*eofp = (error == ENOENT)) != 0)
2314 					break;
2315 				else
2316 					goto update;
2317 			}
2318 
2319 			if (zap.za_integer_length != 8 ||
2320 			    zap.za_num_integers != 1) {
2321 				cmn_err(CE_WARN, "zap_readdir: bad directory "
2322 				    "entry, obj = %lld, offset = %lld\n",
2323 				    (u_longlong_t)zp->z_id,
2324 				    (u_longlong_t)offset);
2325 				error = SET_ERROR(ENXIO);
2326 				goto update;
2327 			}
2328 
2329 			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2330 			/*
2331 			 * MacOS X can extract the object type here such as:
2332 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2333 			 */
2334 
2335 			if (check_sysattrs && !zap.za_normalization_conflict) {
2336 				zap.za_normalization_conflict =
2337 				    xattr_sysattr_casechk(zap.za_name);
2338 			}
2339 		}
2340 
2341 		if (flags & V_RDDIR_ACCFILTER) {
2342 			/*
2343 			 * If we have no access at all, don't include
2344 			 * this entry in the returned information
2345 			 */
2346 			znode_t	*ezp;
2347 			if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2348 				goto skip_entry;
2349 			if (!zfs_has_access(ezp, cr)) {
2350 				VN_RELE(ZTOV(ezp));
2351 				goto skip_entry;
2352 			}
2353 			VN_RELE(ZTOV(ezp));
2354 		}
2355 
2356 		if (flags & V_RDDIR_ENTFLAGS)
2357 			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2358 		else
2359 			reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2360 
2361 		/*
2362 		 * Will this entry fit in the buffer?
2363 		 */
2364 		if (outcount + reclen > bufsize) {
2365 			/*
2366 			 * Did we manage to fit anything in the buffer?
2367 			 */
2368 			if (!outcount) {
2369 				error = SET_ERROR(EINVAL);
2370 				goto update;
2371 			}
2372 			break;
2373 		}
2374 		if (flags & V_RDDIR_ENTFLAGS) {
2375 			/*
2376 			 * Add extended flag entry:
2377 			 */
2378 			eodp->ed_ino = objnum;
2379 			eodp->ed_reclen = reclen;
2380 			/* NOTE: ed_off is the offset for the *next* entry */
2381 			next = &(eodp->ed_off);
2382 			eodp->ed_eflags = zap.za_normalization_conflict ?
2383 			    ED_CASE_CONFLICT : 0;
2384 			(void) strncpy(eodp->ed_name, zap.za_name,
2385 			    EDIRENT_NAMELEN(reclen));
2386 			eodp = (edirent_t *)((intptr_t)eodp + reclen);
2387 		} else {
2388 			/*
2389 			 * Add normal entry:
2390 			 */
2391 			odp->d_ino = objnum;
2392 			odp->d_reclen = reclen;
2393 			/* NOTE: d_off is the offset for the *next* entry */
2394 			next = &(odp->d_off);
2395 			(void) strncpy(odp->d_name, zap.za_name,
2396 			    DIRENT64_NAMELEN(reclen));
2397 			odp = (dirent64_t *)((intptr_t)odp + reclen);
2398 		}
2399 		outcount += reclen;
2400 
2401 		ASSERT(outcount <= bufsize);
2402 
2403 		/* Prefetch znode */
2404 		if (prefetch)
2405 			dmu_prefetch(os, objnum, 0, 0, 0,
2406 			    ZIO_PRIORITY_SYNC_READ);
2407 
2408 	skip_entry:
2409 		/*
2410 		 * Move to the next entry, fill in the previous offset.
2411 		 */
2412 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2413 			zap_cursor_advance(&zc);
2414 			offset = zap_cursor_serialize(&zc);
2415 		} else {
2416 			offset += 1;
2417 		}
2418 		if (next)
2419 			*next = offset;
2420 	}
2421 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2422 
2423 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2424 		iovp->iov_base += outcount;
2425 		iovp->iov_len -= outcount;
2426 		uio->uio_resid -= outcount;
2427 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2428 		/*
2429 		 * Reset the pointer.
2430 		 */
2431 		offset = uio->uio_loffset;
2432 	}
2433 
2434 update:
2435 	zap_cursor_fini(&zc);
2436 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2437 		kmem_free(outbuf, bufsize);
2438 
2439 	if (error == ENOENT)
2440 		error = 0;
2441 
2442 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2443 
2444 	uio->uio_loffset = offset;
2445 	ZFS_EXIT(zfsvfs);
2446 	return (error);
2447 }
2448 
2449 ulong_t zfs_fsync_sync_cnt = 4;
2450 
2451 static int
2452 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2453 {
2454 	znode_t	*zp = VTOZ(vp);
2455 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2456 
2457 	/*
2458 	 * Regardless of whether this is required for standards conformance,
2459 	 * this is the logical behavior when fsync() is called on a file with
2460 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
2461 	 * going to be pushed out as part of the zil_commit().
2462 	 */
2463 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2464 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
2465 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr, ct);
2466 
2467 	(void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2468 
2469 	if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2470 		ZFS_ENTER(zfsvfs);
2471 		ZFS_VERIFY_ZP(zp);
2472 		zil_commit(zfsvfs->z_log, zp->z_id);
2473 		ZFS_EXIT(zfsvfs);
2474 	}
2475 	return (0);
2476 }
2477 
2478 
2479 /*
2480  * Get the requested file attributes and place them in the provided
2481  * vattr structure.
2482  *
2483  *	IN:	vp	- vnode of file.
2484  *		vap	- va_mask identifies requested attributes.
2485  *			  If AT_XVATTR set, then optional attrs are requested
2486  *		flags	- ATTR_NOACLCHECK (CIFS server context)
2487  *		cr	- credentials of caller.
2488  *		ct	- caller context
2489  *
2490  *	OUT:	vap	- attribute values.
2491  *
2492  *	RETURN:	0 (always succeeds).
2493  */
2494 /* ARGSUSED */
2495 static int
2496 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2497     caller_context_t *ct)
2498 {
2499 	znode_t *zp = VTOZ(vp);
2500 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2501 	int	error = 0;
2502 	uint64_t links;
2503 	uint64_t mtime[2], ctime[2];
2504 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2505 	xoptattr_t *xoap = NULL;
2506 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2507 	sa_bulk_attr_t bulk[2];
2508 	int count = 0;
2509 
2510 	ZFS_ENTER(zfsvfs);
2511 	ZFS_VERIFY_ZP(zp);
2512 
2513 	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2514 
2515 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2516 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2517 
2518 	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2519 		ZFS_EXIT(zfsvfs);
2520 		return (error);
2521 	}
2522 
2523 	/*
2524 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2525 	 * Also, if we are the owner don't bother, since owner should
2526 	 * always be allowed to read basic attributes of file.
2527 	 */
2528 	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2529 	    (vap->va_uid != crgetuid(cr))) {
2530 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2531 		    skipaclchk, cr)) {
2532 			ZFS_EXIT(zfsvfs);
2533 			return (error);
2534 		}
2535 	}
2536 
2537 	/*
2538 	 * Return all attributes.  It's cheaper to provide the answer
2539 	 * than to determine whether we were asked the question.
2540 	 */
2541 
2542 	mutex_enter(&zp->z_lock);
2543 	vap->va_type = vp->v_type;
2544 	vap->va_mode = zp->z_mode & MODEMASK;
2545 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2546 	vap->va_nodeid = zp->z_id;
2547 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2548 		links = zp->z_links + 1;
2549 	else
2550 		links = zp->z_links;
2551 	vap->va_nlink = MIN(links, UINT32_MAX);	/* nlink_t limit! */
2552 	vap->va_size = zp->z_size;
2553 	vap->va_rdev = vp->v_rdev;
2554 	vap->va_seq = zp->z_seq;
2555 
2556 	/*
2557 	 * Add in any requested optional attributes and the create time.
2558 	 * Also set the corresponding bits in the returned attribute bitmap.
2559 	 */
2560 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2561 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2562 			xoap->xoa_archive =
2563 			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2564 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2565 		}
2566 
2567 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2568 			xoap->xoa_readonly =
2569 			    ((zp->z_pflags & ZFS_READONLY) != 0);
2570 			XVA_SET_RTN(xvap, XAT_READONLY);
2571 		}
2572 
2573 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2574 			xoap->xoa_system =
2575 			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2576 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2577 		}
2578 
2579 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2580 			xoap->xoa_hidden =
2581 			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2582 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2583 		}
2584 
2585 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2586 			xoap->xoa_nounlink =
2587 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2588 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2589 		}
2590 
2591 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2592 			xoap->xoa_immutable =
2593 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2594 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2595 		}
2596 
2597 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2598 			xoap->xoa_appendonly =
2599 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2600 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2601 		}
2602 
2603 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2604 			xoap->xoa_nodump =
2605 			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2606 			XVA_SET_RTN(xvap, XAT_NODUMP);
2607 		}
2608 
2609 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2610 			xoap->xoa_opaque =
2611 			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2612 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2613 		}
2614 
2615 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2616 			xoap->xoa_av_quarantined =
2617 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2618 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2619 		}
2620 
2621 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2622 			xoap->xoa_av_modified =
2623 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2624 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2625 		}
2626 
2627 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2628 		    vp->v_type == VREG) {
2629 			zfs_sa_get_scanstamp(zp, xvap);
2630 		}
2631 
2632 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2633 			uint64_t times[2];
2634 
2635 			(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2636 			    times, sizeof (times));
2637 			ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2638 			XVA_SET_RTN(xvap, XAT_CREATETIME);
2639 		}
2640 
2641 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2642 			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2643 			XVA_SET_RTN(xvap, XAT_REPARSE);
2644 		}
2645 		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2646 			xoap->xoa_generation = zp->z_gen;
2647 			XVA_SET_RTN(xvap, XAT_GEN);
2648 		}
2649 
2650 		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2651 			xoap->xoa_offline =
2652 			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2653 			XVA_SET_RTN(xvap, XAT_OFFLINE);
2654 		}
2655 
2656 		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2657 			xoap->xoa_sparse =
2658 			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2659 			XVA_SET_RTN(xvap, XAT_SPARSE);
2660 		}
2661 	}
2662 
2663 	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2664 	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2665 	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2666 
2667 	mutex_exit(&zp->z_lock);
2668 
2669 	sa_object_size(zp->z_sa_hdl, &vap->va_blksize, &vap->va_nblocks);
2670 
2671 	if (zp->z_blksz == 0) {
2672 		/*
2673 		 * Block size hasn't been set; suggest maximal I/O transfers.
2674 		 */
2675 		vap->va_blksize = zfsvfs->z_max_blksz;
2676 	}
2677 
2678 	ZFS_EXIT(zfsvfs);
2679 	return (0);
2680 }
2681 
2682 /*
2683  * Set the file attributes to the values contained in the
2684  * vattr structure.
2685  *
2686  *	IN:	vp	- vnode of file to be modified.
2687  *		vap	- new attribute values.
2688  *			  If AT_XVATTR set, then optional attrs are being set
2689  *		flags	- ATTR_UTIME set if non-default time values provided.
2690  *			- ATTR_NOACLCHECK (CIFS context only).
2691  *		cr	- credentials of caller.
2692  *		ct	- caller context
2693  *
2694  *	RETURN:	0 on success, error code on failure.
2695  *
2696  * Timestamps:
2697  *	vp - ctime updated, mtime updated if size changed.
2698  */
2699 /* ARGSUSED */
2700 static int
2701 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2702     caller_context_t *ct)
2703 {
2704 	znode_t		*zp = VTOZ(vp);
2705 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2706 	zilog_t		*zilog;
2707 	dmu_tx_t	*tx;
2708 	vattr_t		oldva;
2709 	xvattr_t	tmpxvattr;
2710 	uint_t		mask = vap->va_mask;
2711 	uint_t		saved_mask = 0;
2712 	int		trim_mask = 0;
2713 	uint64_t	new_mode;
2714 	uint64_t	new_uid, new_gid;
2715 	uint64_t	xattr_obj;
2716 	uint64_t	mtime[2], ctime[2];
2717 	znode_t		*attrzp;
2718 	int		need_policy = FALSE;
2719 	int		err, err2;
2720 	zfs_fuid_info_t *fuidp = NULL;
2721 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2722 	xoptattr_t	*xoap;
2723 	zfs_acl_t	*aclp;
2724 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2725 	boolean_t	fuid_dirtied = B_FALSE;
2726 	sa_bulk_attr_t	bulk[7], xattr_bulk[7];
2727 	int		count = 0, xattr_count = 0;
2728 
2729 	if (mask == 0)
2730 		return (0);
2731 
2732 	if (mask & AT_NOSET)
2733 		return (SET_ERROR(EINVAL));
2734 
2735 	ZFS_ENTER(zfsvfs);
2736 	ZFS_VERIFY_ZP(zp);
2737 
2738 	zilog = zfsvfs->z_log;
2739 
2740 	/*
2741 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
2742 	 * that file system is at proper version level
2743 	 */
2744 
2745 	if (zfsvfs->z_use_fuids == B_FALSE &&
2746 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2747 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2748 	    (mask & AT_XVATTR))) {
2749 		ZFS_EXIT(zfsvfs);
2750 		return (SET_ERROR(EINVAL));
2751 	}
2752 
2753 	if (mask & AT_SIZE && vp->v_type == VDIR) {
2754 		ZFS_EXIT(zfsvfs);
2755 		return (SET_ERROR(EISDIR));
2756 	}
2757 
2758 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2759 		ZFS_EXIT(zfsvfs);
2760 		return (SET_ERROR(EINVAL));
2761 	}
2762 
2763 	/*
2764 	 * If this is an xvattr_t, then get a pointer to the structure of
2765 	 * optional attributes.  If this is NULL, then we have a vattr_t.
2766 	 */
2767 	xoap = xva_getxoptattr(xvap);
2768 
2769 	xva_init(&tmpxvattr);
2770 
2771 	/*
2772 	 * Immutable files can only alter immutable bit and atime
2773 	 */
2774 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2775 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2776 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2777 		ZFS_EXIT(zfsvfs);
2778 		return (SET_ERROR(EPERM));
2779 	}
2780 
2781 	if ((mask & AT_SIZE) && (zp->z_pflags & ZFS_READONLY)) {
2782 		ZFS_EXIT(zfsvfs);
2783 		return (SET_ERROR(EPERM));
2784 	}
2785 
2786 	/*
2787 	 * Verify timestamps doesn't overflow 32 bits.
2788 	 * ZFS can handle large timestamps, but 32bit syscalls can't
2789 	 * handle times greater than 2039.  This check should be removed
2790 	 * once large timestamps are fully supported.
2791 	 */
2792 	if (mask & (AT_ATIME | AT_MTIME)) {
2793 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2794 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2795 			ZFS_EXIT(zfsvfs);
2796 			return (SET_ERROR(EOVERFLOW));
2797 		}
2798 	}
2799 
2800 top:
2801 	attrzp = NULL;
2802 	aclp = NULL;
2803 
2804 	/* Can this be moved to before the top label? */
2805 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2806 		ZFS_EXIT(zfsvfs);
2807 		return (SET_ERROR(EROFS));
2808 	}
2809 
2810 	/*
2811 	 * First validate permissions
2812 	 */
2813 
2814 	if (mask & AT_SIZE) {
2815 		err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
2816 		if (err) {
2817 			ZFS_EXIT(zfsvfs);
2818 			return (err);
2819 		}
2820 		/*
2821 		 * XXX - Note, we are not providing any open
2822 		 * mode flags here (like FNDELAY), so we may
2823 		 * block if there are locks present... this
2824 		 * should be addressed in openat().
2825 		 */
2826 		/* XXX - would it be OK to generate a log record here? */
2827 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2828 		if (err) {
2829 			ZFS_EXIT(zfsvfs);
2830 			return (err);
2831 		}
2832 
2833 		if (vap->va_size == 0)
2834 			vnevent_truncate(ZTOV(zp), ct);
2835 	}
2836 
2837 	if (mask & (AT_ATIME|AT_MTIME) ||
2838 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2839 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2840 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2841 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2842 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2843 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2844 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2845 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2846 		    skipaclchk, cr);
2847 	}
2848 
2849 	if (mask & (AT_UID|AT_GID)) {
2850 		int	idmask = (mask & (AT_UID|AT_GID));
2851 		int	take_owner;
2852 		int	take_group;
2853 
2854 		/*
2855 		 * NOTE: even if a new mode is being set,
2856 		 * we may clear S_ISUID/S_ISGID bits.
2857 		 */
2858 
2859 		if (!(mask & AT_MODE))
2860 			vap->va_mode = zp->z_mode;
2861 
2862 		/*
2863 		 * Take ownership or chgrp to group we are a member of
2864 		 */
2865 
2866 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2867 		take_group = (mask & AT_GID) &&
2868 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
2869 
2870 		/*
2871 		 * If both AT_UID and AT_GID are set then take_owner and
2872 		 * take_group must both be set in order to allow taking
2873 		 * ownership.
2874 		 *
2875 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2876 		 *
2877 		 */
2878 
2879 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2880 		    ((idmask == AT_UID) && take_owner) ||
2881 		    ((idmask == AT_GID) && take_group)) {
2882 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2883 			    skipaclchk, cr) == 0) {
2884 				/*
2885 				 * Remove setuid/setgid for non-privileged users
2886 				 */
2887 				secpolicy_setid_clear(vap, cr);
2888 				trim_mask = (mask & (AT_UID|AT_GID));
2889 			} else {
2890 				need_policy =  TRUE;
2891 			}
2892 		} else {
2893 			need_policy =  TRUE;
2894 		}
2895 	}
2896 
2897 	mutex_enter(&zp->z_lock);
2898 	oldva.va_mode = zp->z_mode;
2899 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2900 	if (mask & AT_XVATTR) {
2901 		/*
2902 		 * Update xvattr mask to include only those attributes
2903 		 * that are actually changing.
2904 		 *
2905 		 * the bits will be restored prior to actually setting
2906 		 * the attributes so the caller thinks they were set.
2907 		 */
2908 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2909 			if (xoap->xoa_appendonly !=
2910 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2911 				need_policy = TRUE;
2912 			} else {
2913 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2914 				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2915 			}
2916 		}
2917 
2918 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2919 			if (xoap->xoa_nounlink !=
2920 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2921 				need_policy = TRUE;
2922 			} else {
2923 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2924 				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2925 			}
2926 		}
2927 
2928 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2929 			if (xoap->xoa_immutable !=
2930 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2931 				need_policy = TRUE;
2932 			} else {
2933 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2934 				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2935 			}
2936 		}
2937 
2938 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2939 			if (xoap->xoa_nodump !=
2940 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2941 				need_policy = TRUE;
2942 			} else {
2943 				XVA_CLR_REQ(xvap, XAT_NODUMP);
2944 				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
2945 			}
2946 		}
2947 
2948 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2949 			if (xoap->xoa_av_modified !=
2950 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2951 				need_policy = TRUE;
2952 			} else {
2953 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2954 				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
2955 			}
2956 		}
2957 
2958 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2959 			if ((vp->v_type != VREG &&
2960 			    xoap->xoa_av_quarantined) ||
2961 			    xoap->xoa_av_quarantined !=
2962 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2963 				need_policy = TRUE;
2964 			} else {
2965 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2966 				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
2967 			}
2968 		}
2969 
2970 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2971 			mutex_exit(&zp->z_lock);
2972 			ZFS_EXIT(zfsvfs);
2973 			return (SET_ERROR(EPERM));
2974 		}
2975 
2976 		if (need_policy == FALSE &&
2977 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2978 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2979 			need_policy = TRUE;
2980 		}
2981 	}
2982 
2983 	mutex_exit(&zp->z_lock);
2984 
2985 	if (mask & AT_MODE) {
2986 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
2987 			err = secpolicy_setid_setsticky_clear(vp, vap,
2988 			    &oldva, cr);
2989 			if (err) {
2990 				ZFS_EXIT(zfsvfs);
2991 				return (err);
2992 			}
2993 			trim_mask |= AT_MODE;
2994 		} else {
2995 			need_policy = TRUE;
2996 		}
2997 	}
2998 
2999 	if (need_policy) {
3000 		/*
3001 		 * If trim_mask is set then take ownership
3002 		 * has been granted or write_acl is present and user
3003 		 * has the ability to modify mode.  In that case remove
3004 		 * UID|GID and or MODE from mask so that
3005 		 * secpolicy_vnode_setattr() doesn't revoke it.
3006 		 */
3007 
3008 		if (trim_mask) {
3009 			saved_mask = vap->va_mask;
3010 			vap->va_mask &= ~trim_mask;
3011 		}
3012 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
3013 		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
3014 		if (err) {
3015 			ZFS_EXIT(zfsvfs);
3016 			return (err);
3017 		}
3018 
3019 		if (trim_mask)
3020 			vap->va_mask |= saved_mask;
3021 	}
3022 
3023 	/*
3024 	 * secpolicy_vnode_setattr, or take ownership may have
3025 	 * changed va_mask
3026 	 */
3027 	mask = vap->va_mask;
3028 
3029 	if ((mask & (AT_UID | AT_GID))) {
3030 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
3031 		    &xattr_obj, sizeof (xattr_obj));
3032 
3033 		if (err == 0 && xattr_obj) {
3034 			err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
3035 			if (err)
3036 				goto out2;
3037 		}
3038 		if (mask & AT_UID) {
3039 			new_uid = zfs_fuid_create(zfsvfs,
3040 			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3041 			if (new_uid != zp->z_uid &&
3042 			    zfs_fuid_overquota(zfsvfs, B_FALSE, new_uid)) {
3043 				if (attrzp)
3044 					VN_RELE(ZTOV(attrzp));
3045 				err = SET_ERROR(EDQUOT);
3046 				goto out2;
3047 			}
3048 		}
3049 
3050 		if (mask & AT_GID) {
3051 			new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3052 			    cr, ZFS_GROUP, &fuidp);
3053 			if (new_gid != zp->z_gid &&
3054 			    zfs_fuid_overquota(zfsvfs, B_TRUE, new_gid)) {
3055 				if (attrzp)
3056 					VN_RELE(ZTOV(attrzp));
3057 				err = SET_ERROR(EDQUOT);
3058 				goto out2;
3059 			}
3060 		}
3061 	}
3062 	tx = dmu_tx_create(zfsvfs->z_os);
3063 
3064 	if (mask & AT_MODE) {
3065 		uint64_t pmode = zp->z_mode;
3066 		uint64_t acl_obj;
3067 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3068 
3069 		if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
3070 		    !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
3071 			err = SET_ERROR(EPERM);
3072 			goto out;
3073 		}
3074 
3075 		if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3076 			goto out;
3077 
3078 		mutex_enter(&zp->z_lock);
3079 		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
3080 			/*
3081 			 * Are we upgrading ACL from old V0 format
3082 			 * to V1 format?
3083 			 */
3084 			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
3085 			    zfs_znode_acl_version(zp) ==
3086 			    ZFS_ACL_VERSION_INITIAL) {
3087 				dmu_tx_hold_free(tx, acl_obj, 0,
3088 				    DMU_OBJECT_END);
3089 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3090 				    0, aclp->z_acl_bytes);
3091 			} else {
3092 				dmu_tx_hold_write(tx, acl_obj, 0,
3093 				    aclp->z_acl_bytes);
3094 			}
3095 		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3096 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3097 			    0, aclp->z_acl_bytes);
3098 		}
3099 		mutex_exit(&zp->z_lock);
3100 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3101 	} else {
3102 		if ((mask & AT_XVATTR) &&
3103 		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3104 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3105 		else
3106 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3107 	}
3108 
3109 	if (attrzp) {
3110 		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
3111 	}
3112 
3113 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3114 	if (fuid_dirtied)
3115 		zfs_fuid_txhold(zfsvfs, tx);
3116 
3117 	zfs_sa_upgrade_txholds(tx, zp);
3118 
3119 	err = dmu_tx_assign(tx, TXG_WAIT);
3120 	if (err)
3121 		goto out;
3122 
3123 	count = 0;
3124 	/*
3125 	 * Set each attribute requested.
3126 	 * We group settings according to the locks they need to acquire.
3127 	 *
3128 	 * Note: you cannot set ctime directly, although it will be
3129 	 * updated as a side-effect of calling this function.
3130 	 */
3131 
3132 
3133 	if (mask & (AT_UID|AT_GID|AT_MODE))
3134 		mutex_enter(&zp->z_acl_lock);
3135 	mutex_enter(&zp->z_lock);
3136 
3137 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3138 	    &zp->z_pflags, sizeof (zp->z_pflags));
3139 
3140 	if (attrzp) {
3141 		if (mask & (AT_UID|AT_GID|AT_MODE))
3142 			mutex_enter(&attrzp->z_acl_lock);
3143 		mutex_enter(&attrzp->z_lock);
3144 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3145 		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
3146 		    sizeof (attrzp->z_pflags));
3147 	}
3148 
3149 	if (mask & (AT_UID|AT_GID)) {
3150 
3151 		if (mask & AT_UID) {
3152 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
3153 			    &new_uid, sizeof (new_uid));
3154 			zp->z_uid = new_uid;
3155 			if (attrzp) {
3156 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3157 				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
3158 				    sizeof (new_uid));
3159 				attrzp->z_uid = new_uid;
3160 			}
3161 		}
3162 
3163 		if (mask & AT_GID) {
3164 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
3165 			    NULL, &new_gid, sizeof (new_gid));
3166 			zp->z_gid = new_gid;
3167 			if (attrzp) {
3168 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3169 				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
3170 				    sizeof (new_gid));
3171 				attrzp->z_gid = new_gid;
3172 			}
3173 		}
3174 		if (!(mask & AT_MODE)) {
3175 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
3176 			    NULL, &new_mode, sizeof (new_mode));
3177 			new_mode = zp->z_mode;
3178 		}
3179 		err = zfs_acl_chown_setattr(zp);
3180 		ASSERT(err == 0);
3181 		if (attrzp) {
3182 			err = zfs_acl_chown_setattr(attrzp);
3183 			ASSERT(err == 0);
3184 		}
3185 	}
3186 
3187 	if (mask & AT_MODE) {
3188 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
3189 		    &new_mode, sizeof (new_mode));
3190 		zp->z_mode = new_mode;
3191 		ASSERT3U((uintptr_t)aclp, !=, NULL);
3192 		err = zfs_aclset_common(zp, aclp, cr, tx);
3193 		ASSERT0(err);
3194 		if (zp->z_acl_cached)
3195 			zfs_acl_free(zp->z_acl_cached);
3196 		zp->z_acl_cached = aclp;
3197 		aclp = NULL;
3198 	}
3199 
3200 
3201 	if (mask & AT_ATIME) {
3202 		ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
3203 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
3204 		    &zp->z_atime, sizeof (zp->z_atime));
3205 	}
3206 
3207 	if (mask & AT_MTIME) {
3208 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3209 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3210 		    mtime, sizeof (mtime));
3211 	}
3212 
3213 	/* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3214 	if (mask & AT_SIZE && !(mask & AT_MTIME)) {
3215 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
3216 		    NULL, mtime, sizeof (mtime));
3217 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3218 		    &ctime, sizeof (ctime));
3219 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3220 		    B_TRUE);
3221 	} else if (mask != 0) {
3222 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3223 		    &ctime, sizeof (ctime));
3224 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
3225 		    B_TRUE);
3226 		if (attrzp) {
3227 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3228 			    SA_ZPL_CTIME(zfsvfs), NULL,
3229 			    &ctime, sizeof (ctime));
3230 			zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3231 			    mtime, ctime, B_TRUE);
3232 		}
3233 	}
3234 	/*
3235 	 * Do this after setting timestamps to prevent timestamp
3236 	 * update from toggling bit
3237 	 */
3238 
3239 	if (xoap && (mask & AT_XVATTR)) {
3240 
3241 		/*
3242 		 * restore trimmed off masks
3243 		 * so that return masks can be set for caller.
3244 		 */
3245 
3246 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3247 			XVA_SET_REQ(xvap, XAT_APPENDONLY);
3248 		}
3249 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3250 			XVA_SET_REQ(xvap, XAT_NOUNLINK);
3251 		}
3252 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3253 			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3254 		}
3255 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3256 			XVA_SET_REQ(xvap, XAT_NODUMP);
3257 		}
3258 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3259 			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3260 		}
3261 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3262 			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3263 		}
3264 
3265 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3266 			ASSERT(vp->v_type == VREG);
3267 
3268 		zfs_xvattr_set(zp, xvap, tx);
3269 	}
3270 
3271 	if (fuid_dirtied)
3272 		zfs_fuid_sync(zfsvfs, tx);
3273 
3274 	if (mask != 0)
3275 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3276 
3277 	mutex_exit(&zp->z_lock);
3278 	if (mask & (AT_UID|AT_GID|AT_MODE))
3279 		mutex_exit(&zp->z_acl_lock);
3280 
3281 	if (attrzp) {
3282 		if (mask & (AT_UID|AT_GID|AT_MODE))
3283 			mutex_exit(&attrzp->z_acl_lock);
3284 		mutex_exit(&attrzp->z_lock);
3285 	}
3286 out:
3287 	if (err == 0 && attrzp) {
3288 		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3289 		    xattr_count, tx);
3290 		ASSERT(err2 == 0);
3291 	}
3292 
3293 	if (attrzp)
3294 		VN_RELE(ZTOV(attrzp));
3295 
3296 	if (aclp)
3297 		zfs_acl_free(aclp);
3298 
3299 	if (fuidp) {
3300 		zfs_fuid_info_free(fuidp);
3301 		fuidp = NULL;
3302 	}
3303 
3304 	if (err) {
3305 		dmu_tx_abort(tx);
3306 		if (err == ERESTART)
3307 			goto top;
3308 	} else {
3309 		err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3310 		dmu_tx_commit(tx);
3311 	}
3312 
3313 out2:
3314 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3315 		zil_commit(zilog, 0);
3316 
3317 	ZFS_EXIT(zfsvfs);
3318 	return (err);
3319 }
3320 
3321 typedef struct zfs_zlock {
3322 	krwlock_t	*zl_rwlock;	/* lock we acquired */
3323 	znode_t		*zl_znode;	/* znode we held */
3324 	struct zfs_zlock *zl_next;	/* next in list */
3325 } zfs_zlock_t;
3326 
3327 /*
3328  * Drop locks and release vnodes that were held by zfs_rename_lock().
3329  */
3330 static void
3331 zfs_rename_unlock(zfs_zlock_t **zlpp)
3332 {
3333 	zfs_zlock_t *zl;
3334 
3335 	while ((zl = *zlpp) != NULL) {
3336 		if (zl->zl_znode != NULL)
3337 			VN_RELE(ZTOV(zl->zl_znode));
3338 		rw_exit(zl->zl_rwlock);
3339 		*