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