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