zfs_vnops.c revision 224251
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 */
24
25/* Portions Copyright 2007 Jeremy Teo */
26/* Portions Copyright 2010 Robert Milkowski */
27
28#include <sys/types.h>
29#include <sys/param.h>
30#include <sys/time.h>
31#include <sys/systm.h>
32#include <sys/sysmacros.h>
33#include <sys/resource.h>
34#include <sys/vfs.h>
35#include <sys/vnode.h>
36#include <sys/file.h>
37#include <sys/stat.h>
38#include <sys/kmem.h>
39#include <sys/taskq.h>
40#include <sys/uio.h>
41#include <sys/atomic.h>
42#include <sys/namei.h>
43#include <sys/mman.h>
44#include <sys/cmn_err.h>
45#include <sys/errno.h>
46#include <sys/unistd.h>
47#include <sys/zfs_dir.h>
48#include <sys/zfs_ioctl.h>
49#include <sys/fs/zfs.h>
50#include <sys/dmu.h>
51#include <sys/dmu_objset.h>
52#include <sys/spa.h>
53#include <sys/txg.h>
54#include <sys/dbuf.h>
55#include <sys/zap.h>
56#include <sys/sa.h>
57#include <sys/dirent.h>
58#include <sys/policy.h>
59#include <sys/sunddi.h>
60#include <sys/filio.h>
61#include <sys/sid.h>
62#include <sys/zfs_ctldir.h>
63#include <sys/zfs_fuid.h>
64#include <sys/zfs_sa.h>
65#include <sys/dnlc.h>
66#include <sys/zfs_rlock.h>
67#include <sys/extdirent.h>
68#include <sys/kidmap.h>
69#include <sys/bio.h>
70#include <sys/buf.h>
71#include <sys/sf_buf.h>
72#include <sys/sched.h>
73#include <sys/acl.h>
74#include <vm/vm_pageout.h>
75
76/*
77 * Programming rules.
78 *
79 * Each vnode op performs some logical unit of work.  To do this, the ZPL must
80 * properly lock its in-core state, create a DMU transaction, do the work,
81 * record this work in the intent log (ZIL), commit the DMU transaction,
82 * and wait for the intent log to commit if it is a synchronous operation.
83 * Moreover, the vnode ops must work in both normal and log replay context.
84 * The ordering of events is important to avoid deadlocks and references
85 * to freed memory.  The example below illustrates the following Big Rules:
86 *
87 *  (1) A check must be made in each zfs thread for a mounted file system.
88 *	This is done avoiding races using ZFS_ENTER(zfsvfs).
89 *      A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
90 *      must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
91 *      can return EIO from the calling function.
92 *
93 *  (2)	VN_RELE() should always be the last thing except for zil_commit()
94 *	(if necessary) and ZFS_EXIT(). This is for 3 reasons:
95 *	First, if it's the last reference, the vnode/znode
96 *	can be freed, so the zp may point to freed memory.  Second, the last
97 *	reference will call zfs_zinactive(), which may induce a lot of work --
98 *	pushing cached pages (which acquires range locks) and syncing out
99 *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
100 *	which could deadlock the system if you were already holding one.
101 *	If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
102 *
103 *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
104 *	as they can span dmu_tx_assign() calls.
105 *
106 *  (4)	Always pass TXG_NOWAIT as the second argument to dmu_tx_assign().
107 *	This is critical because we don't want to block while holding locks.
108 *	Note, in particular, that if a lock is sometimes acquired before
109 *	the tx assigns, and sometimes after (e.g. z_lock), then failing to
110 *	use a non-blocking assign can deadlock the system.  The scenario:
111 *
112 *	Thread A has grabbed a lock before calling dmu_tx_assign().
113 *	Thread B is in an already-assigned tx, and blocks for this lock.
114 *	Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
115 *	forever, because the previous txg can't quiesce until B's tx commits.
116 *
117 *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
118 *	then drop all locks, call dmu_tx_wait(), and try again.
119 *
120 *  (5)	If the operation succeeded, generate the intent log entry for it
121 *	before dropping locks.  This ensures that the ordering of events
122 *	in the intent log matches the order in which they actually occurred.
123 *      During ZIL replay the zfs_log_* functions will update the sequence
124 *	number to indicate the zil transaction has replayed.
125 *
126 *  (6)	At the end of each vnode op, the DMU tx must always commit,
127 *	regardless of whether there were any errors.
128 *
129 *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
130 *	to ensure that synchronous semantics are provided when necessary.
131 *
132 * In general, this is how things should be ordered in each vnode op:
133 *
134 *	ZFS_ENTER(zfsvfs);		// exit if unmounted
135 * top:
136 *	zfs_dirent_lock(&dl, ...)	// lock directory entry (may VN_HOLD())
137 *	rw_enter(...);			// grab any other locks you need
138 *	tx = dmu_tx_create(...);	// get DMU tx
139 *	dmu_tx_hold_*();		// hold each object you might modify
140 *	error = dmu_tx_assign(tx, TXG_NOWAIT);	// try to assign
141 *	if (error) {
142 *		rw_exit(...);		// drop locks
143 *		zfs_dirent_unlock(dl);	// unlock directory entry
144 *		VN_RELE(...);		// release held vnodes
145 *		if (error == ERESTART) {
146 *			dmu_tx_wait(tx);
147 *			dmu_tx_abort(tx);
148 *			goto top;
149 *		}
150 *		dmu_tx_abort(tx);	// abort DMU tx
151 *		ZFS_EXIT(zfsvfs);	// finished in zfs
152 *		return (error);		// really out of space
153 *	}
154 *	error = do_real_work();		// do whatever this VOP does
155 *	if (error == 0)
156 *		zfs_log_*(...);		// on success, make ZIL entry
157 *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
158 *	rw_exit(...);			// drop locks
159 *	zfs_dirent_unlock(dl);		// unlock directory entry
160 *	VN_RELE(...);			// release held vnodes
161 *	zil_commit(zilog, foid);	// synchronous when necessary
162 *	ZFS_EXIT(zfsvfs);		// finished in zfs
163 *	return (error);			// done, report error
164 */
165
166/* ARGSUSED */
167static int
168zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
169{
170	znode_t	*zp = VTOZ(*vpp);
171	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
172
173	ZFS_ENTER(zfsvfs);
174	ZFS_VERIFY_ZP(zp);
175
176	if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
177	    ((flag & FAPPEND) == 0)) {
178		ZFS_EXIT(zfsvfs);
179		return (EPERM);
180	}
181
182	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
183	    ZTOV(zp)->v_type == VREG &&
184	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
185		if (fs_vscan(*vpp, cr, 0) != 0) {
186			ZFS_EXIT(zfsvfs);
187			return (EACCES);
188		}
189	}
190
191	/* Keep a count of the synchronous opens in the znode */
192	if (flag & (FSYNC | FDSYNC))
193		atomic_inc_32(&zp->z_sync_cnt);
194
195	ZFS_EXIT(zfsvfs);
196	return (0);
197}
198
199/* ARGSUSED */
200static int
201zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
202    caller_context_t *ct)
203{
204	znode_t	*zp = VTOZ(vp);
205	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
206
207	/*
208	 * Clean up any locks held by this process on the vp.
209	 */
210	cleanlocks(vp, ddi_get_pid(), 0);
211	cleanshares(vp, ddi_get_pid());
212
213	ZFS_ENTER(zfsvfs);
214	ZFS_VERIFY_ZP(zp);
215
216	/* Decrement the synchronous opens in the znode */
217	if ((flag & (FSYNC | FDSYNC)) && (count == 1))
218		atomic_dec_32(&zp->z_sync_cnt);
219
220	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
221	    ZTOV(zp)->v_type == VREG &&
222	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
223		VERIFY(fs_vscan(vp, cr, 1) == 0);
224
225	ZFS_EXIT(zfsvfs);
226	return (0);
227}
228
229/*
230 * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
231 * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
232 */
233static int
234zfs_holey(vnode_t *vp, u_long cmd, offset_t *off)
235{
236	znode_t	*zp = VTOZ(vp);
237	uint64_t noff = (uint64_t)*off; /* new offset */
238	uint64_t file_sz;
239	int error;
240	boolean_t hole;
241
242	file_sz = zp->z_size;
243	if (noff >= file_sz)  {
244		return (ENXIO);
245	}
246
247	if (cmd == _FIO_SEEK_HOLE)
248		hole = B_TRUE;
249	else
250		hole = B_FALSE;
251
252	error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
253
254	/* end of file? */
255	if ((error == ESRCH) || (noff > file_sz)) {
256		/*
257		 * Handle the virtual hole at the end of file.
258		 */
259		if (hole) {
260			*off = file_sz;
261			return (0);
262		}
263		return (ENXIO);
264	}
265
266	if (noff < *off)
267		return (error);
268	*off = noff;
269	return (error);
270}
271
272/* ARGSUSED */
273static int
274zfs_ioctl(vnode_t *vp, u_long com, intptr_t data, int flag, cred_t *cred,
275    int *rvalp, caller_context_t *ct)
276{
277	offset_t off;
278	int error;
279	zfsvfs_t *zfsvfs;
280	znode_t *zp;
281
282	switch (com) {
283	case _FIOFFS:
284		return (0);
285
286		/*
287		 * The following two ioctls are used by bfu.  Faking out,
288		 * necessary to avoid bfu errors.
289		 */
290	case _FIOGDIO:
291	case _FIOSDIO:
292		return (0);
293
294	case _FIO_SEEK_DATA:
295	case _FIO_SEEK_HOLE:
296		if (ddi_copyin((void *)data, &off, sizeof (off), flag))
297			return (EFAULT);
298
299		zp = VTOZ(vp);
300		zfsvfs = zp->z_zfsvfs;
301		ZFS_ENTER(zfsvfs);
302		ZFS_VERIFY_ZP(zp);
303
304		/* offset parameter is in/out */
305		error = zfs_holey(vp, com, &off);
306		ZFS_EXIT(zfsvfs);
307		if (error)
308			return (error);
309		if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
310			return (EFAULT);
311		return (0);
312	}
313	return (ENOTTY);
314}
315
316static vm_page_t
317page_lookup(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
318{
319	vm_object_t obj;
320	vm_page_t pp;
321
322	obj = vp->v_object;
323	VM_OBJECT_LOCK_ASSERT(obj, MA_OWNED);
324
325	for (;;) {
326		if ((pp = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
327		    vm_page_is_valid(pp, (vm_offset_t)off, nbytes)) {
328			if ((pp->oflags & VPO_BUSY) != 0) {
329				/*
330				 * Reference the page before unlocking and
331				 * sleeping so that the page daemon is less
332				 * likely to reclaim it.
333				 */
334				vm_page_lock_queues();
335				vm_page_flag_set(pp, PG_REFERENCED);
336				vm_page_sleep(pp, "zfsmwb");
337				continue;
338			}
339			vm_page_busy(pp);
340			vm_page_undirty(pp);
341		} else {
342			if (__predict_false(obj->cache != NULL)) {
343				vm_page_cache_free(obj, OFF_TO_IDX(start),
344				    OFF_TO_IDX(start) + 1);
345			}
346			pp = NULL;
347		}
348		break;
349	}
350	return (pp);
351}
352
353static void
354page_unlock(vm_page_t pp)
355{
356
357	vm_page_wakeup(pp);
358}
359
360static caddr_t
361zfs_map_page(vm_page_t pp, struct sf_buf **sfp)
362{
363
364	*sfp = sf_buf_alloc(pp, 0);
365	return ((caddr_t)sf_buf_kva(*sfp));
366}
367
368static void
369zfs_unmap_page(struct sf_buf *sf)
370{
371
372	sf_buf_free(sf);
373}
374
375/*
376 * When a file is memory mapped, we must keep the IO data synchronized
377 * between the DMU cache and the memory mapped pages.  What this means:
378 *
379 * On Write:	If we find a memory mapped page, we write to *both*
380 *		the page and the dmu buffer.
381 */
382static void
383update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid,
384    int segflg, dmu_tx_t *tx)
385{
386	vm_object_t obj;
387	struct sf_buf *sf;
388	int off;
389
390	ASSERT(vp->v_mount != NULL);
391	obj = vp->v_object;
392	ASSERT(obj != NULL);
393
394	off = start & PAGEOFFSET;
395	VM_OBJECT_LOCK(obj);
396	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
397		vm_page_t pp;
398		int nbytes = MIN(PAGESIZE - off, len);
399
400		if ((pp = page_lookup(vp, start, off, nbytes)) != NULL) {
401			caddr_t va;
402
403			VM_OBJECT_UNLOCK(obj);
404			va = zfs_map_page(pp, &sf);
405			if (segflg == UIO_NOCOPY) {
406				(void) dmu_write(os, oid, start+off, nbytes,
407				    va+off, tx);
408			} else {
409				(void) dmu_read(os, oid, start+off, nbytes,
410				    va+off, DMU_READ_PREFETCH);
411			}
412			zfs_unmap_page(sf);
413			VM_OBJECT_LOCK(obj);
414			page_unlock(pp);
415		}
416		len -= nbytes;
417		off = 0;
418	}
419	VM_OBJECT_UNLOCK(obj);
420}
421
422/*
423 * Read with UIO_NOCOPY flag means that sendfile(2) requests
424 * ZFS to populate a range of page cache pages with data.
425 *
426 * NOTE: this function could be optimized to pre-allocate
427 * all pages in advance, drain VPO_BUSY on all of them,
428 * map them into contiguous KVA region and populate them
429 * in one single dmu_read() call.
430 */
431static int
432mappedread_sf(vnode_t *vp, int nbytes, uio_t *uio)
433{
434	znode_t *zp = VTOZ(vp);
435	objset_t *os = zp->z_zfsvfs->z_os;
436	struct sf_buf *sf;
437	vm_object_t obj;
438	vm_page_t pp;
439	int64_t start;
440	caddr_t va;
441	int len = nbytes;
442	int off;
443	int error = 0;
444
445	ASSERT(uio->uio_segflg == UIO_NOCOPY);
446	ASSERT(vp->v_mount != NULL);
447	obj = vp->v_object;
448	ASSERT(obj != NULL);
449	ASSERT((uio->uio_loffset & PAGEOFFSET) == 0);
450
451	VM_OBJECT_LOCK(obj);
452	for (start = uio->uio_loffset; len > 0; start += PAGESIZE) {
453		int bytes = MIN(PAGESIZE, len);
454
455		pp = vm_page_grab(obj, OFF_TO_IDX(start), VM_ALLOC_NOBUSY |
456		    VM_ALLOC_NORMAL | VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY);
457		if (pp->valid == 0) {
458			vm_page_io_start(pp);
459			VM_OBJECT_UNLOCK(obj);
460			va = zfs_map_page(pp, &sf);
461			error = dmu_read(os, zp->z_id, start, bytes, va,
462			    DMU_READ_PREFETCH);
463			if (bytes != PAGESIZE && error == 0)
464				bzero(va + bytes, PAGESIZE - bytes);
465			zfs_unmap_page(sf);
466			VM_OBJECT_LOCK(obj);
467			vm_page_io_finish(pp);
468			vm_page_lock(pp);
469			if (error) {
470				vm_page_free(pp);
471			} else {
472				pp->valid = VM_PAGE_BITS_ALL;
473				vm_page_activate(pp);
474			}
475			vm_page_unlock(pp);
476		}
477		if (error)
478			break;
479		uio->uio_resid -= bytes;
480		uio->uio_offset += bytes;
481		len -= bytes;
482	}
483	VM_OBJECT_UNLOCK(obj);
484	return (error);
485}
486
487/*
488 * When a file is memory mapped, we must keep the IO data synchronized
489 * between the DMU cache and the memory mapped pages.  What this means:
490 *
491 * On Read:	We "read" preferentially from memory mapped pages,
492 *		else we default from the dmu buffer.
493 *
494 * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
495 *	the file is memory mapped.
496 */
497static int
498mappedread(vnode_t *vp, int nbytes, uio_t *uio)
499{
500	znode_t *zp = VTOZ(vp);
501	objset_t *os = zp->z_zfsvfs->z_os;
502	vm_object_t obj;
503	int64_t start;
504	caddr_t va;
505	int len = nbytes;
506	int off;
507	int error = 0;
508
509	ASSERT(vp->v_mount != NULL);
510	obj = vp->v_object;
511	ASSERT(obj != NULL);
512
513	start = uio->uio_loffset;
514	off = start & PAGEOFFSET;
515	VM_OBJECT_LOCK(obj);
516	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
517		vm_page_t pp;
518		uint64_t bytes = MIN(PAGESIZE - off, len);
519
520		if (pp = page_lookup(vp, start, off, bytes)) {
521			struct sf_buf *sf;
522			caddr_t va;
523
524			VM_OBJECT_UNLOCK(obj);
525			va = zfs_map_page(pp, &sf);
526			error = uiomove(va + off, bytes, UIO_READ, uio);
527			zfs_unmap_page(sf);
528			VM_OBJECT_LOCK(obj);
529			page_unlock(pp);
530		} else {
531			VM_OBJECT_UNLOCK(obj);
532			error = dmu_read_uio(os, zp->z_id, uio, bytes);
533			VM_OBJECT_LOCK(obj);
534		}
535		len -= bytes;
536		off = 0;
537		if (error)
538			break;
539	}
540	VM_OBJECT_UNLOCK(obj);
541	return (error);
542}
543
544offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
545
546/*
547 * Read bytes from specified file into supplied buffer.
548 *
549 *	IN:	vp	- vnode of file to be read from.
550 *		uio	- structure supplying read location, range info,
551 *			  and return buffer.
552 *		ioflag	- SYNC flags; used to provide FRSYNC semantics.
553 *		cr	- credentials of caller.
554 *		ct	- caller context
555 *
556 *	OUT:	uio	- updated offset and range, buffer filled.
557 *
558 *	RETURN:	0 if success
559 *		error code if failure
560 *
561 * Side Effects:
562 *	vp - atime updated if byte count > 0
563 */
564/* ARGSUSED */
565static int
566zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
567{
568	znode_t		*zp = VTOZ(vp);
569	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
570	objset_t	*os;
571	ssize_t		n, nbytes;
572	int		error;
573	rl_t		*rl;
574	xuio_t		*xuio = NULL;
575
576	ZFS_ENTER(zfsvfs);
577	ZFS_VERIFY_ZP(zp);
578	os = zfsvfs->z_os;
579
580	if (zp->z_pflags & ZFS_AV_QUARANTINED) {
581		ZFS_EXIT(zfsvfs);
582		return (EACCES);
583	}
584
585	/*
586	 * Validate file offset
587	 */
588	if (uio->uio_loffset < (offset_t)0) {
589		ZFS_EXIT(zfsvfs);
590		return (EINVAL);
591	}
592
593	/*
594	 * Fasttrack empty reads
595	 */
596	if (uio->uio_resid == 0) {
597		ZFS_EXIT(zfsvfs);
598		return (0);
599	}
600
601	/*
602	 * Check for mandatory locks
603	 */
604	if (MANDMODE(zp->z_mode)) {
605		if (error = chklock(vp, FREAD,
606		    uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
607			ZFS_EXIT(zfsvfs);
608			return (error);
609		}
610	}
611
612	/*
613	 * If we're in FRSYNC mode, sync out this znode before reading it.
614	 */
615	if (ioflag & FRSYNC || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
616		zil_commit(zfsvfs->z_log, zp->z_id);
617
618	/*
619	 * Lock the range against changes.
620	 */
621	rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
622
623	/*
624	 * If we are reading past end-of-file we can skip
625	 * to the end; but we might still need to set atime.
626	 */
627	if (uio->uio_loffset >= zp->z_size) {
628		error = 0;
629		goto out;
630	}
631
632	ASSERT(uio->uio_loffset < zp->z_size);
633	n = MIN(uio->uio_resid, zp->z_size - uio->uio_loffset);
634
635#ifdef sun
636	if ((uio->uio_extflg == UIO_XUIO) &&
637	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY)) {
638		int nblk;
639		int blksz = zp->z_blksz;
640		uint64_t offset = uio->uio_loffset;
641
642		xuio = (xuio_t *)uio;
643		if ((ISP2(blksz))) {
644			nblk = (P2ROUNDUP(offset + n, blksz) - P2ALIGN(offset,
645			    blksz)) / blksz;
646		} else {
647			ASSERT(offset + n <= blksz);
648			nblk = 1;
649		}
650		(void) dmu_xuio_init(xuio, nblk);
651
652		if (vn_has_cached_data(vp)) {
653			/*
654			 * For simplicity, we always allocate a full buffer
655			 * even if we only expect to read a portion of a block.
656			 */
657			while (--nblk >= 0) {
658				(void) dmu_xuio_add(xuio,
659				    dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
660				    blksz), 0, blksz);
661			}
662		}
663	}
664#endif	/* sun */
665
666	while (n > 0) {
667		nbytes = MIN(n, zfs_read_chunk_size -
668		    P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
669
670#ifdef __FreeBSD__
671		if (uio->uio_segflg == UIO_NOCOPY)
672			error = mappedread_sf(vp, nbytes, uio);
673		else
674#endif /* __FreeBSD__ */
675		if (vn_has_cached_data(vp))
676			error = mappedread(vp, nbytes, uio);
677		else
678			error = dmu_read_uio(os, zp->z_id, uio, nbytes);
679		if (error) {
680			/* convert checksum errors into IO errors */
681			if (error == ECKSUM)
682				error = EIO;
683			break;
684		}
685
686		n -= nbytes;
687	}
688out:
689	zfs_range_unlock(rl);
690
691	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
692	ZFS_EXIT(zfsvfs);
693	return (error);
694}
695
696/*
697 * Write the bytes to a file.
698 *
699 *	IN:	vp	- vnode of file to be written to.
700 *		uio	- structure supplying write location, range info,
701 *			  and data buffer.
702 *		ioflag	- FAPPEND flag set if in append mode.
703 *		cr	- credentials of caller.
704 *		ct	- caller context (NFS/CIFS fem monitor only)
705 *
706 *	OUT:	uio	- updated offset and range.
707 *
708 *	RETURN:	0 if success
709 *		error code if failure
710 *
711 * Timestamps:
712 *	vp - ctime|mtime updated if byte count > 0
713 */
714
715/* ARGSUSED */
716static int
717zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
718{
719	znode_t		*zp = VTOZ(vp);
720	rlim64_t	limit = MAXOFFSET_T;
721	ssize_t		start_resid = uio->uio_resid;
722	ssize_t		tx_bytes;
723	uint64_t	end_size;
724	dmu_tx_t	*tx;
725	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
726	zilog_t		*zilog;
727	offset_t	woff;
728	ssize_t		n, nbytes;
729	rl_t		*rl;
730	int		max_blksz = zfsvfs->z_max_blksz;
731	int		error;
732	arc_buf_t	*abuf;
733	iovec_t		*aiov;
734	xuio_t		*xuio = NULL;
735	int		i_iov = 0;
736	int		iovcnt = uio->uio_iovcnt;
737	iovec_t		*iovp = uio->uio_iov;
738	int		write_eof;
739	int		count = 0;
740	sa_bulk_attr_t	bulk[4];
741	uint64_t	mtime[2], ctime[2];
742
743	/*
744	 * Fasttrack empty write
745	 */
746	n = start_resid;
747	if (n == 0)
748		return (0);
749
750	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
751		limit = MAXOFFSET_T;
752
753	ZFS_ENTER(zfsvfs);
754	ZFS_VERIFY_ZP(zp);
755
756	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
757	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
758	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
759	    &zp->z_size, 8);
760	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
761	    &zp->z_pflags, 8);
762
763	/*
764	 * If immutable or not appending then return EPERM
765	 */
766	if ((zp->z_pflags & (ZFS_IMMUTABLE | ZFS_READONLY)) ||
767	    ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
768	    (uio->uio_loffset < zp->z_size))) {
769		ZFS_EXIT(zfsvfs);
770		return (EPERM);
771	}
772
773	zilog = zfsvfs->z_log;
774
775	/*
776	 * Validate file offset
777	 */
778	woff = ioflag & FAPPEND ? zp->z_size : uio->uio_loffset;
779	if (woff < 0) {
780		ZFS_EXIT(zfsvfs);
781		return (EINVAL);
782	}
783
784	/*
785	 * Check for mandatory locks before calling zfs_range_lock()
786	 * in order to prevent a deadlock with locks set via fcntl().
787	 */
788	if (MANDMODE((mode_t)zp->z_mode) &&
789	    (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
790		ZFS_EXIT(zfsvfs);
791		return (error);
792	}
793
794#ifdef sun
795	/*
796	 * Pre-fault the pages to ensure slow (eg NFS) pages
797	 * don't hold up txg.
798	 * Skip this if uio contains loaned arc_buf.
799	 */
800	if ((uio->uio_extflg == UIO_XUIO) &&
801	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY))
802		xuio = (xuio_t *)uio;
803	else
804		uio_prefaultpages(MIN(n, max_blksz), uio);
805#endif	/* sun */
806
807	/*
808	 * If in append mode, set the io offset pointer to eof.
809	 */
810	if (ioflag & FAPPEND) {
811		/*
812		 * Obtain an appending range lock to guarantee file append
813		 * semantics.  We reset the write offset once we have the lock.
814		 */
815		rl = zfs_range_lock(zp, 0, n, RL_APPEND);
816		woff = rl->r_off;
817		if (rl->r_len == UINT64_MAX) {
818			/*
819			 * We overlocked the file because this write will cause
820			 * the file block size to increase.
821			 * Note that zp_size cannot change with this lock held.
822			 */
823			woff = zp->z_size;
824		}
825		uio->uio_loffset = woff;
826	} else {
827		/*
828		 * Note that if the file block size will change as a result of
829		 * this write, then this range lock will lock the entire file
830		 * so that we can re-write the block safely.
831		 */
832		rl = zfs_range_lock(zp, woff, n, RL_WRITER);
833	}
834
835	if (woff >= limit) {
836		zfs_range_unlock(rl);
837		ZFS_EXIT(zfsvfs);
838		return (EFBIG);
839	}
840
841	if ((woff + n) > limit || woff > (limit - n))
842		n = limit - woff;
843
844	/* Will this write extend the file length? */
845	write_eof = (woff + n > zp->z_size);
846
847	end_size = MAX(zp->z_size, woff + n);
848
849	/*
850	 * Write the file in reasonable size chunks.  Each chunk is written
851	 * in a separate transaction; this keeps the intent log records small
852	 * and allows us to do more fine-grained space accounting.
853	 */
854	while (n > 0) {
855		abuf = NULL;
856		woff = uio->uio_loffset;
857again:
858		if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
859		    zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
860			if (abuf != NULL)
861				dmu_return_arcbuf(abuf);
862			error = EDQUOT;
863			break;
864		}
865
866		if (xuio && abuf == NULL) {
867			ASSERT(i_iov < iovcnt);
868			aiov = &iovp[i_iov];
869			abuf = dmu_xuio_arcbuf(xuio, i_iov);
870			dmu_xuio_clear(xuio, i_iov);
871			DTRACE_PROBE3(zfs_cp_write, int, i_iov,
872			    iovec_t *, aiov, arc_buf_t *, abuf);
873			ASSERT((aiov->iov_base == abuf->b_data) ||
874			    ((char *)aiov->iov_base - (char *)abuf->b_data +
875			    aiov->iov_len == arc_buf_size(abuf)));
876			i_iov++;
877		} else if (abuf == NULL && n >= max_blksz &&
878		    woff >= zp->z_size &&
879		    P2PHASE(woff, max_blksz) == 0 &&
880		    zp->z_blksz == max_blksz) {
881			/*
882			 * This write covers a full block.  "Borrow" a buffer
883			 * from the dmu so that we can fill it before we enter
884			 * a transaction.  This avoids the possibility of
885			 * holding up the transaction if the data copy hangs
886			 * up on a pagefault (e.g., from an NFS server mapping).
887			 */
888			size_t cbytes;
889
890			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
891			    max_blksz);
892			ASSERT(abuf != NULL);
893			ASSERT(arc_buf_size(abuf) == max_blksz);
894			if (error = uiocopy(abuf->b_data, max_blksz,
895			    UIO_WRITE, uio, &cbytes)) {
896				dmu_return_arcbuf(abuf);
897				break;
898			}
899			ASSERT(cbytes == max_blksz);
900		}
901
902		/*
903		 * Start a transaction.
904		 */
905		tx = dmu_tx_create(zfsvfs->z_os);
906		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
907		dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
908		zfs_sa_upgrade_txholds(tx, zp);
909		error = dmu_tx_assign(tx, TXG_NOWAIT);
910		if (error) {
911			if (error == ERESTART) {
912				dmu_tx_wait(tx);
913				dmu_tx_abort(tx);
914				goto again;
915			}
916			dmu_tx_abort(tx);
917			if (abuf != NULL)
918				dmu_return_arcbuf(abuf);
919			break;
920		}
921
922		/*
923		 * If zfs_range_lock() over-locked we grow the blocksize
924		 * and then reduce the lock range.  This will only happen
925		 * on the first iteration since zfs_range_reduce() will
926		 * shrink down r_len to the appropriate size.
927		 */
928		if (rl->r_len == UINT64_MAX) {
929			uint64_t new_blksz;
930
931			if (zp->z_blksz > max_blksz) {
932				ASSERT(!ISP2(zp->z_blksz));
933				new_blksz = MIN(end_size, SPA_MAXBLOCKSIZE);
934			} else {
935				new_blksz = MIN(end_size, max_blksz);
936			}
937			zfs_grow_blocksize(zp, new_blksz, tx);
938			zfs_range_reduce(rl, woff, n);
939		}
940
941		/*
942		 * XXX - should we really limit each write to z_max_blksz?
943		 * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
944		 */
945		nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
946
947		if (woff + nbytes > zp->z_size)
948			vnode_pager_setsize(vp, woff + nbytes);
949
950		if (abuf == NULL) {
951			tx_bytes = uio->uio_resid;
952			error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
953			    uio, nbytes, tx);
954			tx_bytes -= uio->uio_resid;
955		} else {
956			tx_bytes = nbytes;
957			ASSERT(xuio == NULL || tx_bytes == aiov->iov_len);
958			/*
959			 * If this is not a full block write, but we are
960			 * extending the file past EOF and this data starts
961			 * block-aligned, use assign_arcbuf().  Otherwise,
962			 * write via dmu_write().
963			 */
964			if (tx_bytes < max_blksz && (!write_eof ||
965			    aiov->iov_base != abuf->b_data)) {
966				ASSERT(xuio);
967				dmu_write(zfsvfs->z_os, zp->z_id, woff,
968				    aiov->iov_len, aiov->iov_base, tx);
969				dmu_return_arcbuf(abuf);
970				xuio_stat_wbuf_copied();
971			} else {
972				ASSERT(xuio || tx_bytes == max_blksz);
973				dmu_assign_arcbuf(sa_get_db(zp->z_sa_hdl),
974				    woff, abuf, tx);
975			}
976			ASSERT(tx_bytes <= uio->uio_resid);
977			uioskip(uio, tx_bytes);
978		}
979		if (tx_bytes && vn_has_cached_data(vp)) {
980			update_pages(vp, woff, tx_bytes, zfsvfs->z_os,
981			    zp->z_id, uio->uio_segflg, tx);
982		}
983
984		/*
985		 * If we made no progress, we're done.  If we made even
986		 * partial progress, update the znode and ZIL accordingly.
987		 */
988		if (tx_bytes == 0) {
989			(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
990			    (void *)&zp->z_size, sizeof (uint64_t), tx);
991			dmu_tx_commit(tx);
992			ASSERT(error != 0);
993			break;
994		}
995
996		/*
997		 * Clear Set-UID/Set-GID bits on successful write if not
998		 * privileged and at least one of the excute bits is set.
999		 *
1000		 * It would be nice to to this after all writes have
1001		 * been done, but that would still expose the ISUID/ISGID
1002		 * to another app after the partial write is committed.
1003		 *
1004		 * Note: we don't call zfs_fuid_map_id() here because
1005		 * user 0 is not an ephemeral uid.
1006		 */
1007		mutex_enter(&zp->z_acl_lock);
1008		if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) |
1009		    (S_IXUSR >> 6))) != 0 &&
1010		    (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
1011		    secpolicy_vnode_setid_retain(vp, cr,
1012		    (zp->z_mode & S_ISUID) != 0 && zp->z_uid == 0) != 0) {
1013			uint64_t newmode;
1014			zp->z_mode &= ~(S_ISUID | S_ISGID);
1015			newmode = zp->z_mode;
1016			(void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
1017			    (void *)&newmode, sizeof (uint64_t), tx);
1018		}
1019		mutex_exit(&zp->z_acl_lock);
1020
1021		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
1022		    B_TRUE);
1023
1024		/*
1025		 * Update the file size (zp_size) if it has changed;
1026		 * account for possible concurrent updates.
1027		 */
1028		while ((end_size = zp->z_size) < uio->uio_loffset) {
1029			(void) atomic_cas_64(&zp->z_size, end_size,
1030			    uio->uio_loffset);
1031			ASSERT(error == 0);
1032		}
1033		/*
1034		 * If we are replaying and eof is non zero then force
1035		 * the file size to the specified eof. Note, there's no
1036		 * concurrency during replay.
1037		 */
1038		if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
1039			zp->z_size = zfsvfs->z_replay_eof;
1040
1041		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1042
1043		zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
1044		dmu_tx_commit(tx);
1045
1046		if (error != 0)
1047			break;
1048		ASSERT(tx_bytes == nbytes);
1049		n -= nbytes;
1050
1051#ifdef sun
1052		if (!xuio && n > 0)
1053			uio_prefaultpages(MIN(n, max_blksz), uio);
1054#endif	/* sun */
1055	}
1056
1057	zfs_range_unlock(rl);
1058
1059	/*
1060	 * If we're in replay mode, or we made no progress, return error.
1061	 * Otherwise, it's at least a partial write, so it's successful.
1062	 */
1063	if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
1064		ZFS_EXIT(zfsvfs);
1065		return (error);
1066	}
1067
1068	if (ioflag & (FSYNC | FDSYNC) ||
1069	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1070		zil_commit(zilog, zp->z_id);
1071
1072	ZFS_EXIT(zfsvfs);
1073	return (0);
1074}
1075
1076void
1077zfs_get_done(zgd_t *zgd, int error)
1078{
1079	znode_t *zp = zgd->zgd_private;
1080	objset_t *os = zp->z_zfsvfs->z_os;
1081	int vfslocked;
1082
1083	if (zgd->zgd_db)
1084		dmu_buf_rele(zgd->zgd_db, zgd);
1085
1086	zfs_range_unlock(zgd->zgd_rl);
1087
1088	vfslocked = VFS_LOCK_GIANT(zp->z_zfsvfs->z_vfs);
1089	/*
1090	 * Release the vnode asynchronously as we currently have the
1091	 * txg stopped from syncing.
1092	 */
1093	VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1094
1095	if (error == 0 && zgd->zgd_bp)
1096		zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1097
1098	kmem_free(zgd, sizeof (zgd_t));
1099	VFS_UNLOCK_GIANT(vfslocked);
1100}
1101
1102#ifdef DEBUG
1103static int zil_fault_io = 0;
1104#endif
1105
1106/*
1107 * Get data to generate a TX_WRITE intent log record.
1108 */
1109int
1110zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1111{
1112	zfsvfs_t *zfsvfs = arg;
1113	objset_t *os = zfsvfs->z_os;
1114	znode_t *zp;
1115	uint64_t object = lr->lr_foid;
1116	uint64_t offset = lr->lr_offset;
1117	uint64_t size = lr->lr_length;
1118	blkptr_t *bp = &lr->lr_blkptr;
1119	dmu_buf_t *db;
1120	zgd_t *zgd;
1121	int error = 0;
1122
1123	ASSERT(zio != NULL);
1124	ASSERT(size != 0);
1125
1126	/*
1127	 * Nothing to do if the file has been removed
1128	 */
1129	if (zfs_zget(zfsvfs, object, &zp) != 0)
1130		return (ENOENT);
1131	if (zp->z_unlinked) {
1132		/*
1133		 * Release the vnode asynchronously as we currently have the
1134		 * txg stopped from syncing.
1135		 */
1136		VN_RELE_ASYNC(ZTOV(zp),
1137		    dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1138		return (ENOENT);
1139	}
1140
1141	zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1142	zgd->zgd_zilog = zfsvfs->z_log;
1143	zgd->zgd_private = zp;
1144
1145	/*
1146	 * Write records come in two flavors: immediate and indirect.
1147	 * For small writes it's cheaper to store the data with the
1148	 * log record (immediate); for large writes it's cheaper to
1149	 * sync the data and get a pointer to it (indirect) so that
1150	 * we don't have to write the data twice.
1151	 */
1152	if (buf != NULL) { /* immediate write */
1153		zgd->zgd_rl = zfs_range_lock(zp, offset, size, RL_READER);
1154		/* test for truncation needs to be done while range locked */
1155		if (offset >= zp->z_size) {
1156			error = ENOENT;
1157		} else {
1158			error = dmu_read(os, object, offset, size, buf,
1159			    DMU_READ_NO_PREFETCH);
1160		}
1161		ASSERT(error == 0 || error == ENOENT);
1162	} else { /* indirect write */
1163		/*
1164		 * Have to lock the whole block to ensure when it's
1165		 * written out and it's checksum is being calculated
1166		 * that no one can change the data. We need to re-check
1167		 * blocksize after we get the lock in case it's changed!
1168		 */
1169		for (;;) {
1170			uint64_t blkoff;
1171			size = zp->z_blksz;
1172			blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1173			offset -= blkoff;
1174			zgd->zgd_rl = zfs_range_lock(zp, offset, size,
1175			    RL_READER);
1176			if (zp->z_blksz == size)
1177				break;
1178			offset += blkoff;
1179			zfs_range_unlock(zgd->zgd_rl);
1180		}
1181		/* test for truncation needs to be done while range locked */
1182		if (lr->lr_offset >= zp->z_size)
1183			error = ENOENT;
1184#ifdef DEBUG
1185		if (zil_fault_io) {
1186			error = EIO;
1187			zil_fault_io = 0;
1188		}
1189#endif
1190		if (error == 0)
1191			error = dmu_buf_hold(os, object, offset, zgd, &db,
1192			    DMU_READ_NO_PREFETCH);
1193
1194		if (error == 0) {
1195			zgd->zgd_db = db;
1196			zgd->zgd_bp = bp;
1197
1198			ASSERT(db->db_offset == offset);
1199			ASSERT(db->db_size == size);
1200
1201			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1202			    zfs_get_done, zgd);
1203			ASSERT(error || lr->lr_length <= zp->z_blksz);
1204
1205			/*
1206			 * On success, we need to wait for the write I/O
1207			 * initiated by dmu_sync() to complete before we can
1208			 * release this dbuf.  We will finish everything up
1209			 * in the zfs_get_done() callback.
1210			 */
1211			if (error == 0)
1212				return (0);
1213
1214			if (error == EALREADY) {
1215				lr->lr_common.lrc_txtype = TX_WRITE2;
1216				error = 0;
1217			}
1218		}
1219	}
1220
1221	zfs_get_done(zgd, error);
1222
1223	return (error);
1224}
1225
1226/*ARGSUSED*/
1227static int
1228zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1229    caller_context_t *ct)
1230{
1231	znode_t *zp = VTOZ(vp);
1232	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1233	int error;
1234
1235	ZFS_ENTER(zfsvfs);
1236	ZFS_VERIFY_ZP(zp);
1237
1238	if (flag & V_ACE_MASK)
1239		error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1240	else
1241		error = zfs_zaccess_rwx(zp, mode, flag, cr);
1242
1243	ZFS_EXIT(zfsvfs);
1244	return (error);
1245}
1246
1247/*
1248 * If vnode is for a device return a specfs vnode instead.
1249 */
1250static int
1251specvp_check(vnode_t **vpp, cred_t *cr)
1252{
1253	int error = 0;
1254
1255	if (IS_DEVVP(*vpp)) {
1256		struct vnode *svp;
1257
1258		svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1259		VN_RELE(*vpp);
1260		if (svp == NULL)
1261			error = ENOSYS;
1262		*vpp = svp;
1263	}
1264	return (error);
1265}
1266
1267
1268/*
1269 * Lookup an entry in a directory, or an extended attribute directory.
1270 * If it exists, return a held vnode reference for it.
1271 *
1272 *	IN:	dvp	- vnode of directory to search.
1273 *		nm	- name of entry to lookup.
1274 *		pnp	- full pathname to lookup [UNUSED].
1275 *		flags	- LOOKUP_XATTR set if looking for an attribute.
1276 *		rdir	- root directory vnode [UNUSED].
1277 *		cr	- credentials of caller.
1278 *		ct	- caller context
1279 *		direntflags - directory lookup flags
1280 *		realpnp - returned pathname.
1281 *
1282 *	OUT:	vpp	- vnode of located entry, NULL if not found.
1283 *
1284 *	RETURN:	0 if success
1285 *		error code if failure
1286 *
1287 * Timestamps:
1288 *	NA
1289 */
1290/* ARGSUSED */
1291static int
1292zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct componentname *cnp,
1293    int nameiop, cred_t *cr, kthread_t *td, int flags)
1294{
1295	znode_t *zdp = VTOZ(dvp);
1296	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1297	int	error = 0;
1298	int *direntflags = NULL;
1299	void *realpnp = NULL;
1300
1301	/* fast path */
1302	if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1303
1304		if (dvp->v_type != VDIR) {
1305			return (ENOTDIR);
1306		} else if (zdp->z_sa_hdl == NULL) {
1307			return (EIO);
1308		}
1309
1310		if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1311			error = zfs_fastaccesschk_execute(zdp, cr);
1312			if (!error) {
1313				*vpp = dvp;
1314				VN_HOLD(*vpp);
1315				return (0);
1316			}
1317			return (error);
1318		} else {
1319			vnode_t *tvp = dnlc_lookup(dvp, nm);
1320
1321			if (tvp) {
1322				error = zfs_fastaccesschk_execute(zdp, cr);
1323				if (error) {
1324					VN_RELE(tvp);
1325					return (error);
1326				}
1327				if (tvp == DNLC_NO_VNODE) {
1328					VN_RELE(tvp);
1329					return (ENOENT);
1330				} else {
1331					*vpp = tvp;
1332					return (specvp_check(vpp, cr));
1333				}
1334			}
1335		}
1336	}
1337
1338	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1339
1340	ZFS_ENTER(zfsvfs);
1341	ZFS_VERIFY_ZP(zdp);
1342
1343	*vpp = NULL;
1344
1345	if (flags & LOOKUP_XATTR) {
1346#ifdef TODO
1347		/*
1348		 * If the xattr property is off, refuse the lookup request.
1349		 */
1350		if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1351			ZFS_EXIT(zfsvfs);
1352			return (EINVAL);
1353		}
1354#endif
1355
1356		/*
1357		 * We don't allow recursive attributes..
1358		 * Maybe someday we will.
1359		 */
1360		if (zdp->z_pflags & ZFS_XATTR) {
1361			ZFS_EXIT(zfsvfs);
1362			return (EINVAL);
1363		}
1364
1365		if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1366			ZFS_EXIT(zfsvfs);
1367			return (error);
1368		}
1369
1370		/*
1371		 * Do we have permission to get into attribute directory?
1372		 */
1373
1374		if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1375		    B_FALSE, cr)) {
1376			VN_RELE(*vpp);
1377			*vpp = NULL;
1378		}
1379
1380		ZFS_EXIT(zfsvfs);
1381		return (error);
1382	}
1383
1384	if (dvp->v_type != VDIR) {
1385		ZFS_EXIT(zfsvfs);
1386		return (ENOTDIR);
1387	}
1388
1389	/*
1390	 * Check accessibility of directory.
1391	 */
1392
1393	if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr)) {
1394		ZFS_EXIT(zfsvfs);
1395		return (error);
1396	}
1397
1398	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1399	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1400		ZFS_EXIT(zfsvfs);
1401		return (EILSEQ);
1402	}
1403
1404	error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1405	if (error == 0)
1406		error = specvp_check(vpp, cr);
1407
1408	/* Translate errors and add SAVENAME when needed. */
1409	if (cnp->cn_flags & ISLASTCN) {
1410		switch (nameiop) {
1411		case CREATE:
1412		case RENAME:
1413			if (error == ENOENT) {
1414				error = EJUSTRETURN;
1415				cnp->cn_flags |= SAVENAME;
1416				break;
1417			}
1418			/* FALLTHROUGH */
1419		case DELETE:
1420			if (error == 0)
1421				cnp->cn_flags |= SAVENAME;
1422			break;
1423		}
1424	}
1425	if (error == 0 && (nm[0] != '.' || nm[1] != '\0')) {
1426		int ltype = 0;
1427
1428		if (cnp->cn_flags & ISDOTDOT) {
1429			ltype = VOP_ISLOCKED(dvp);
1430			VOP_UNLOCK(dvp, 0);
1431		}
1432		ZFS_EXIT(zfsvfs);
1433		error = zfs_vnode_lock(*vpp, cnp->cn_lkflags);
1434		if (cnp->cn_flags & ISDOTDOT)
1435			vn_lock(dvp, ltype | LK_RETRY);
1436		if (error != 0) {
1437			VN_RELE(*vpp);
1438			*vpp = NULL;
1439			return (error);
1440		}
1441	} else {
1442		ZFS_EXIT(zfsvfs);
1443	}
1444
1445#ifdef FREEBSD_NAMECACHE
1446	/*
1447	 * Insert name into cache (as non-existent) if appropriate.
1448	 */
1449	if (error == ENOENT && (cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
1450		cache_enter(dvp, *vpp, cnp);
1451	/*
1452	 * Insert name into cache if appropriate.
1453	 */
1454	if (error == 0 && (cnp->cn_flags & MAKEENTRY)) {
1455		if (!(cnp->cn_flags & ISLASTCN) ||
1456		    (nameiop != DELETE && nameiop != RENAME)) {
1457			cache_enter(dvp, *vpp, cnp);
1458		}
1459	}
1460#endif
1461
1462	return (error);
1463}
1464
1465/*
1466 * Attempt to create a new entry in a directory.  If the entry
1467 * already exists, truncate the file if permissible, else return
1468 * an error.  Return the vp of the created or trunc'd file.
1469 *
1470 *	IN:	dvp	- vnode of directory to put new file entry in.
1471 *		name	- name of new file entry.
1472 *		vap	- attributes of new file.
1473 *		excl	- flag indicating exclusive or non-exclusive mode.
1474 *		mode	- mode to open file with.
1475 *		cr	- credentials of caller.
1476 *		flag	- large file flag [UNUSED].
1477 *		ct	- caller context
1478 *		vsecp 	- ACL to be set
1479 *
1480 *	OUT:	vpp	- vnode of created or trunc'd entry.
1481 *
1482 *	RETURN:	0 if success
1483 *		error code if failure
1484 *
1485 * Timestamps:
1486 *	dvp - ctime|mtime updated if new entry created
1487 *	 vp - ctime|mtime always, atime if new
1488 */
1489
1490/* ARGSUSED */
1491static int
1492zfs_create(vnode_t *dvp, char *name, vattr_t *vap, int excl, int mode,
1493    vnode_t **vpp, cred_t *cr, kthread_t *td)
1494{
1495	znode_t		*zp, *dzp = VTOZ(dvp);
1496	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1497	zilog_t		*zilog;
1498	objset_t	*os;
1499	zfs_dirlock_t	*dl;
1500	dmu_tx_t	*tx;
1501	int		error;
1502	ksid_t		*ksid;
1503	uid_t		uid;
1504	gid_t		gid = crgetgid(cr);
1505	zfs_acl_ids_t   acl_ids;
1506	boolean_t	fuid_dirtied;
1507	boolean_t	have_acl = B_FALSE;
1508	void		*vsecp = NULL;
1509	int		flag = 0;
1510
1511	/*
1512	 * If we have an ephemeral id, ACL, or XVATTR then
1513	 * make sure file system is at proper version
1514	 */
1515
1516	ksid = crgetsid(cr, KSID_OWNER);
1517	if (ksid)
1518		uid = ksid_getid(ksid);
1519	else
1520		uid = crgetuid(cr);
1521
1522	if (zfsvfs->z_use_fuids == B_FALSE &&
1523	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1524	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1525		return (EINVAL);
1526
1527	ZFS_ENTER(zfsvfs);
1528	ZFS_VERIFY_ZP(dzp);
1529	os = zfsvfs->z_os;
1530	zilog = zfsvfs->z_log;
1531
1532	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1533	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1534		ZFS_EXIT(zfsvfs);
1535		return (EILSEQ);
1536	}
1537
1538	if (vap->va_mask & AT_XVATTR) {
1539		if ((error = secpolicy_xvattr(dvp, (xvattr_t *)vap,
1540		    crgetuid(cr), cr, vap->va_type)) != 0) {
1541			ZFS_EXIT(zfsvfs);
1542			return (error);
1543		}
1544	}
1545top:
1546	*vpp = NULL;
1547
1548	if ((vap->va_mode & S_ISVTX) && secpolicy_vnode_stky_modify(cr))
1549		vap->va_mode &= ~S_ISVTX;
1550
1551	if (*name == '\0') {
1552		/*
1553		 * Null component name refers to the directory itself.
1554		 */
1555		VN_HOLD(dvp);
1556		zp = dzp;
1557		dl = NULL;
1558		error = 0;
1559	} else {
1560		/* possible VN_HOLD(zp) */
1561		int zflg = 0;
1562
1563		if (flag & FIGNORECASE)
1564			zflg |= ZCILOOK;
1565
1566		error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1567		    NULL, NULL);
1568		if (error) {
1569			if (have_acl)
1570				zfs_acl_ids_free(&acl_ids);
1571			if (strcmp(name, "..") == 0)
1572				error = EISDIR;
1573			ZFS_EXIT(zfsvfs);
1574			return (error);
1575		}
1576	}
1577
1578	if (zp == NULL) {
1579		uint64_t txtype;
1580
1581		/*
1582		 * Create a new file object and update the directory
1583		 * to reference it.
1584		 */
1585		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1586			if (have_acl)
1587				zfs_acl_ids_free(&acl_ids);
1588			goto out;
1589		}
1590
1591		/*
1592		 * We only support the creation of regular files in
1593		 * extended attribute directories.
1594		 */
1595
1596		if ((dzp->z_pflags & ZFS_XATTR) &&
1597		    (vap->va_type != VREG)) {
1598			if (have_acl)
1599				zfs_acl_ids_free(&acl_ids);
1600			error = EINVAL;
1601			goto out;
1602		}
1603
1604		if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
1605		    cr, vsecp, &acl_ids)) != 0)
1606			goto out;
1607		have_acl = B_TRUE;
1608
1609		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1610			zfs_acl_ids_free(&acl_ids);
1611			error = EDQUOT;
1612			goto out;
1613		}
1614
1615		tx = dmu_tx_create(os);
1616
1617		dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1618		    ZFS_SA_BASE_ATTR_SIZE);
1619
1620		fuid_dirtied = zfsvfs->z_fuid_dirty;
1621		if (fuid_dirtied)
1622			zfs_fuid_txhold(zfsvfs, tx);
1623		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1624		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1625		if (!zfsvfs->z_use_sa &&
1626		    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1627			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1628			    0, acl_ids.z_aclp->z_acl_bytes);
1629		}
1630		error = dmu_tx_assign(tx, TXG_NOWAIT);
1631		if (error) {
1632			zfs_dirent_unlock(dl);
1633			if (error == ERESTART) {
1634				dmu_tx_wait(tx);
1635				dmu_tx_abort(tx);
1636				goto top;
1637			}
1638			zfs_acl_ids_free(&acl_ids);
1639			dmu_tx_abort(tx);
1640			ZFS_EXIT(zfsvfs);
1641			return (error);
1642		}
1643		zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1644
1645		if (fuid_dirtied)
1646			zfs_fuid_sync(zfsvfs, tx);
1647
1648		(void) zfs_link_create(dl, zp, tx, ZNEW);
1649		txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1650		if (flag & FIGNORECASE)
1651			txtype |= TX_CI;
1652		zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1653		    vsecp, acl_ids.z_fuidp, vap);
1654		zfs_acl_ids_free(&acl_ids);
1655		dmu_tx_commit(tx);
1656	} else {
1657		int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1658
1659		if (have_acl)
1660			zfs_acl_ids_free(&acl_ids);
1661		have_acl = B_FALSE;
1662
1663		/*
1664		 * A directory entry already exists for this name.
1665		 */
1666		/*
1667		 * Can't truncate an existing file if in exclusive mode.
1668		 */
1669		if (excl == EXCL) {
1670			error = EEXIST;
1671			goto out;
1672		}
1673		/*
1674		 * Can't open a directory for writing.
1675		 */
1676		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1677			error = EISDIR;
1678			goto out;
1679		}
1680		/*
1681		 * Verify requested access to file.
1682		 */
1683		if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1684			goto out;
1685		}
1686
1687		mutex_enter(&dzp->z_lock);
1688		dzp->z_seq++;
1689		mutex_exit(&dzp->z_lock);
1690
1691		/*
1692		 * Truncate regular files if requested.
1693		 */
1694		if ((ZTOV(zp)->v_type == VREG) &&
1695		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1696			/* we can't hold any locks when calling zfs_freesp() */
1697			zfs_dirent_unlock(dl);
1698			dl = NULL;
1699			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1700			if (error == 0) {
1701				vnevent_create(ZTOV(zp), ct);
1702			}
1703		}
1704	}
1705out:
1706	if (dl)
1707		zfs_dirent_unlock(dl);
1708
1709	if (error) {
1710		if (zp)
1711			VN_RELE(ZTOV(zp));
1712	} else {
1713		*vpp = ZTOV(zp);
1714		error = specvp_check(vpp, cr);
1715	}
1716
1717	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1718		zil_commit(zilog, 0);
1719
1720	ZFS_EXIT(zfsvfs);
1721	return (error);
1722}
1723
1724/*
1725 * Remove an entry from a directory.
1726 *
1727 *	IN:	dvp	- vnode of directory to remove entry from.
1728 *		name	- name of entry to remove.
1729 *		cr	- credentials of caller.
1730 *		ct	- caller context
1731 *		flags	- case flags
1732 *
1733 *	RETURN:	0 if success
1734 *		error code if failure
1735 *
1736 * Timestamps:
1737 *	dvp - ctime|mtime
1738 *	 vp - ctime (if nlink > 0)
1739 */
1740
1741uint64_t null_xattr = 0;
1742
1743/*ARGSUSED*/
1744static int
1745zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1746    int flags)
1747{
1748	znode_t		*zp, *dzp = VTOZ(dvp);
1749	znode_t		*xzp;
1750	vnode_t		*vp;
1751	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1752	zilog_t		*zilog;
1753	uint64_t	acl_obj, xattr_obj;
1754	uint64_t 	xattr_obj_unlinked = 0;
1755	uint64_t	obj = 0;
1756	zfs_dirlock_t	*dl;
1757	dmu_tx_t	*tx;
1758	boolean_t	may_delete_now, delete_now = FALSE;
1759	boolean_t	unlinked, toobig = FALSE;
1760	uint64_t	txtype;
1761	pathname_t	*realnmp = NULL;
1762	pathname_t	realnm;
1763	int		error;
1764	int		zflg = ZEXISTS;
1765
1766	ZFS_ENTER(zfsvfs);
1767	ZFS_VERIFY_ZP(dzp);
1768	zilog = zfsvfs->z_log;
1769
1770	if (flags & FIGNORECASE) {
1771		zflg |= ZCILOOK;
1772		pn_alloc(&realnm);
1773		realnmp = &realnm;
1774	}
1775
1776top:
1777	xattr_obj = 0;
1778	xzp = NULL;
1779	/*
1780	 * Attempt to lock directory; fail if entry doesn't exist.
1781	 */
1782	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1783	    NULL, realnmp)) {
1784		if (realnmp)
1785			pn_free(realnmp);
1786		ZFS_EXIT(zfsvfs);
1787		return (error);
1788	}
1789
1790	vp = ZTOV(zp);
1791
1792	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1793		goto out;
1794	}
1795
1796	/*
1797	 * Need to use rmdir for removing directories.
1798	 */
1799	if (vp->v_type == VDIR) {
1800		error = EPERM;
1801		goto out;
1802	}
1803
1804	vnevent_remove(vp, dvp, name, ct);
1805
1806	if (realnmp)
1807		dnlc_remove(dvp, realnmp->pn_buf);
1808	else
1809		dnlc_remove(dvp, name);
1810
1811	VI_LOCK(vp);
1812	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1813	VI_UNLOCK(vp);
1814
1815	/*
1816	 * We may delete the znode now, or we may put it in the unlinked set;
1817	 * it depends on whether we're the last link, and on whether there are
1818	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1819	 * allow for either case.
1820	 */
1821	obj = zp->z_id;
1822	tx = dmu_tx_create(zfsvfs->z_os);
1823	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1824	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1825	zfs_sa_upgrade_txholds(tx, zp);
1826	zfs_sa_upgrade_txholds(tx, dzp);
1827	if (may_delete_now) {
1828		toobig =
1829		    zp->z_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1830		/* if the file is too big, only hold_free a token amount */
1831		dmu_tx_hold_free(tx, zp->z_id, 0,
1832		    (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1833	}
1834
1835	/* are there any extended attributes? */
1836	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1837	    &xattr_obj, sizeof (xattr_obj));
1838	if (error == 0 && xattr_obj) {
1839		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1840		ASSERT3U(error, ==, 0);
1841		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1842		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1843	}
1844
1845	mutex_enter(&zp->z_lock);
1846	if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1847		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1848	mutex_exit(&zp->z_lock);
1849
1850	/* charge as an update -- would be nice not to charge at all */
1851	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1852
1853	error = dmu_tx_assign(tx, TXG_NOWAIT);
1854	if (error) {
1855		zfs_dirent_unlock(dl);
1856		VN_RELE(vp);
1857		if (xzp)
1858			VN_RELE(ZTOV(xzp));
1859		if (error == ERESTART) {
1860			dmu_tx_wait(tx);
1861			dmu_tx_abort(tx);
1862			goto top;
1863		}
1864		if (realnmp)
1865			pn_free(realnmp);
1866		dmu_tx_abort(tx);
1867		ZFS_EXIT(zfsvfs);
1868		return (error);
1869	}
1870
1871	/*
1872	 * Remove the directory entry.
1873	 */
1874	error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1875
1876	if (error) {
1877		dmu_tx_commit(tx);
1878		goto out;
1879	}
1880
1881	if (unlinked) {
1882
1883		/*
1884		 * Hold z_lock so that we can make sure that the ACL obj
1885		 * hasn't changed.  Could have been deleted due to
1886		 * zfs_sa_upgrade().
1887		 */
1888		mutex_enter(&zp->z_lock);
1889		VI_LOCK(vp);
1890		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1891		    &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1892		delete_now = may_delete_now && !toobig &&
1893		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1894		    xattr_obj == xattr_obj_unlinked && zfs_external_acl(zp) ==
1895		    acl_obj;
1896		VI_UNLOCK(vp);
1897	}
1898
1899	if (delete_now) {
1900		if (xattr_obj_unlinked) {
1901			ASSERT3U(xzp->z_links, ==, 2);
1902			mutex_enter(&xzp->z_lock);
1903			xzp->z_unlinked = 1;
1904			xzp->z_links = 0;
1905			error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1906			    &xzp->z_links, sizeof (xzp->z_links), tx);
1907			ASSERT3U(error,  ==,  0);
1908			mutex_exit(&xzp->z_lock);
1909			zfs_unlinked_add(xzp, tx);
1910
1911			if (zp->z_is_sa)
1912				error = sa_remove(zp->z_sa_hdl,
1913				    SA_ZPL_XATTR(zfsvfs), tx);
1914			else
1915				error = sa_update(zp->z_sa_hdl,
1916				    SA_ZPL_XATTR(zfsvfs), &null_xattr,
1917				    sizeof (uint64_t), tx);
1918			ASSERT3U(error, ==, 0);
1919		}
1920		VI_LOCK(vp);
1921		vp->v_count--;
1922		ASSERT3U(vp->v_count, ==, 0);
1923		VI_UNLOCK(vp);
1924		mutex_exit(&zp->z_lock);
1925		zfs_znode_delete(zp, tx);
1926	} else if (unlinked) {
1927		mutex_exit(&zp->z_lock);
1928		zfs_unlinked_add(zp, tx);
1929	}
1930
1931	txtype = TX_REMOVE;
1932	if (flags & FIGNORECASE)
1933		txtype |= TX_CI;
1934	zfs_log_remove(zilog, tx, txtype, dzp, name, obj);
1935
1936	dmu_tx_commit(tx);
1937out:
1938	if (realnmp)
1939		pn_free(realnmp);
1940
1941	zfs_dirent_unlock(dl);
1942
1943	if (!delete_now)
1944		VN_RELE(vp);
1945	if (xzp)
1946		VN_RELE(ZTOV(xzp));
1947
1948	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1949		zil_commit(zilog, 0);
1950
1951	ZFS_EXIT(zfsvfs);
1952	return (error);
1953}
1954
1955/*
1956 * Create a new directory and insert it into dvp using the name
1957 * provided.  Return a pointer to the inserted directory.
1958 *
1959 *	IN:	dvp	- vnode of directory to add subdir to.
1960 *		dirname	- name of new directory.
1961 *		vap	- attributes of new directory.
1962 *		cr	- credentials of caller.
1963 *		ct	- caller context
1964 *		vsecp	- ACL to be set
1965 *
1966 *	OUT:	vpp	- vnode of created directory.
1967 *
1968 *	RETURN:	0 if success
1969 *		error code if failure
1970 *
1971 * Timestamps:
1972 *	dvp - ctime|mtime updated
1973 *	 vp - ctime|mtime|atime updated
1974 */
1975/*ARGSUSED*/
1976static int
1977zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1978    caller_context_t *ct, int flags, vsecattr_t *vsecp)
1979{
1980	znode_t		*zp, *dzp = VTOZ(dvp);
1981	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1982	zilog_t		*zilog;
1983	zfs_dirlock_t	*dl;
1984	uint64_t	txtype;
1985	dmu_tx_t	*tx;
1986	int		error;
1987	int		zf = ZNEW;
1988	ksid_t		*ksid;
1989	uid_t		uid;
1990	gid_t		gid = crgetgid(cr);
1991	zfs_acl_ids_t   acl_ids;
1992	boolean_t	fuid_dirtied;
1993
1994	ASSERT(vap->va_type == VDIR);
1995
1996	/*
1997	 * If we have an ephemeral id, ACL, or XVATTR then
1998	 * make sure file system is at proper version
1999	 */
2000
2001	ksid = crgetsid(cr, KSID_OWNER);
2002	if (ksid)
2003		uid = ksid_getid(ksid);
2004	else
2005		uid = crgetuid(cr);
2006	if (zfsvfs->z_use_fuids == B_FALSE &&
2007	    (vsecp || (vap->va_mask & AT_XVATTR) ||
2008	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
2009		return (EINVAL);
2010
2011	ZFS_ENTER(zfsvfs);
2012	ZFS_VERIFY_ZP(dzp);
2013	zilog = zfsvfs->z_log;
2014
2015	if (dzp->z_pflags & ZFS_XATTR) {
2016		ZFS_EXIT(zfsvfs);
2017		return (EINVAL);
2018	}
2019
2020	if (zfsvfs->z_utf8 && u8_validate(dirname,
2021	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
2022		ZFS_EXIT(zfsvfs);
2023		return (EILSEQ);
2024	}
2025	if (flags & FIGNORECASE)
2026		zf |= ZCILOOK;
2027
2028	if (vap->va_mask & AT_XVATTR) {
2029		if ((error = secpolicy_xvattr(dvp, (xvattr_t *)vap,
2030		    crgetuid(cr), cr, vap->va_type)) != 0) {
2031			ZFS_EXIT(zfsvfs);
2032			return (error);
2033		}
2034	}
2035
2036	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
2037	    vsecp, &acl_ids)) != 0) {
2038		ZFS_EXIT(zfsvfs);
2039		return (error);
2040	}
2041	/*
2042	 * First make sure the new directory doesn't exist.
2043	 *
2044	 * Existence is checked first to make sure we don't return
2045	 * EACCES instead of EEXIST which can cause some applications
2046	 * to fail.
2047	 */
2048top:
2049	*vpp = NULL;
2050
2051	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
2052	    NULL, NULL)) {
2053		zfs_acl_ids_free(&acl_ids);
2054		ZFS_EXIT(zfsvfs);
2055		return (error);
2056	}
2057
2058	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
2059		zfs_acl_ids_free(&acl_ids);
2060		zfs_dirent_unlock(dl);
2061		ZFS_EXIT(zfsvfs);
2062		return (error);
2063	}
2064
2065	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
2066		zfs_acl_ids_free(&acl_ids);
2067		zfs_dirent_unlock(dl);
2068		ZFS_EXIT(zfsvfs);
2069		return (EDQUOT);
2070	}
2071
2072	/*
2073	 * Add a new entry to the directory.
2074	 */
2075	tx = dmu_tx_create(zfsvfs->z_os);
2076	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
2077	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
2078	fuid_dirtied = zfsvfs->z_fuid_dirty;
2079	if (fuid_dirtied)
2080		zfs_fuid_txhold(zfsvfs, tx);
2081	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2082		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
2083		    acl_ids.z_aclp->z_acl_bytes);
2084	}
2085
2086	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
2087	    ZFS_SA_BASE_ATTR_SIZE);
2088
2089	error = dmu_tx_assign(tx, TXG_NOWAIT);
2090	if (error) {
2091		zfs_dirent_unlock(dl);
2092		if (error == ERESTART) {
2093			dmu_tx_wait(tx);
2094			dmu_tx_abort(tx);
2095			goto top;
2096		}
2097		zfs_acl_ids_free(&acl_ids);
2098		dmu_tx_abort(tx);
2099		ZFS_EXIT(zfsvfs);
2100		return (error);
2101	}
2102
2103	/*
2104	 * Create new node.
2105	 */
2106	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
2107
2108	if (fuid_dirtied)
2109		zfs_fuid_sync(zfsvfs, tx);
2110
2111	/*
2112	 * Now put new name in parent dir.
2113	 */
2114	(void) zfs_link_create(dl, zp, tx, ZNEW);
2115
2116	*vpp = ZTOV(zp);
2117
2118	txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
2119	if (flags & FIGNORECASE)
2120		txtype |= TX_CI;
2121	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
2122	    acl_ids.z_fuidp, vap);
2123
2124	zfs_acl_ids_free(&acl_ids);
2125
2126	dmu_tx_commit(tx);
2127
2128	zfs_dirent_unlock(dl);
2129
2130	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2131		zil_commit(zilog, 0);
2132
2133	ZFS_EXIT(zfsvfs);
2134	return (0);
2135}
2136
2137/*
2138 * Remove a directory subdir entry.  If the current working
2139 * directory is the same as the subdir to be removed, the
2140 * remove will fail.
2141 *
2142 *	IN:	dvp	- vnode of directory to remove from.
2143 *		name	- name of directory to be removed.
2144 *		cwd	- vnode of current working directory.
2145 *		cr	- credentials of caller.
2146 *		ct	- caller context
2147 *		flags	- case flags
2148 *
2149 *	RETURN:	0 if success
2150 *		error code if failure
2151 *
2152 * Timestamps:
2153 *	dvp - ctime|mtime updated
2154 */
2155/*ARGSUSED*/
2156static int
2157zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2158    caller_context_t *ct, int flags)
2159{
2160	znode_t		*dzp = VTOZ(dvp);
2161	znode_t		*zp;
2162	vnode_t		*vp;
2163	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2164	zilog_t		*zilog;
2165	zfs_dirlock_t	*dl;
2166	dmu_tx_t	*tx;
2167	int		error;
2168	int		zflg = ZEXISTS;
2169
2170	ZFS_ENTER(zfsvfs);
2171	ZFS_VERIFY_ZP(dzp);
2172	zilog = zfsvfs->z_log;
2173
2174	if (flags & FIGNORECASE)
2175		zflg |= ZCILOOK;
2176top:
2177	zp = NULL;
2178
2179	/*
2180	 * Attempt to lock directory; fail if entry doesn't exist.
2181	 */
2182	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2183	    NULL, NULL)) {
2184		ZFS_EXIT(zfsvfs);
2185		return (error);
2186	}
2187
2188	vp = ZTOV(zp);
2189
2190	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2191		goto out;
2192	}
2193
2194	if (vp->v_type != VDIR) {
2195		error = ENOTDIR;
2196		goto out;
2197	}
2198
2199	if (vp == cwd) {
2200		error = EINVAL;
2201		goto out;
2202	}
2203
2204	vnevent_rmdir(vp, dvp, name, ct);
2205
2206	/*
2207	 * Grab a lock on the directory to make sure that noone is
2208	 * trying to add (or lookup) entries while we are removing it.
2209	 */
2210	rw_enter(&zp->z_name_lock, RW_WRITER);
2211
2212	/*
2213	 * Grab a lock on the parent pointer to make sure we play well
2214	 * with the treewalk and directory rename code.
2215	 */
2216	rw_enter(&zp->z_parent_lock, RW_WRITER);
2217
2218	tx = dmu_tx_create(zfsvfs->z_os);
2219	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2220	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2221	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2222	zfs_sa_upgrade_txholds(tx, zp);
2223	zfs_sa_upgrade_txholds(tx, dzp);
2224	error = dmu_tx_assign(tx, TXG_NOWAIT);
2225	if (error) {
2226		rw_exit(&zp->z_parent_lock);
2227		rw_exit(&zp->z_name_lock);
2228		zfs_dirent_unlock(dl);
2229		VN_RELE(vp);
2230		if (error == ERESTART) {
2231			dmu_tx_wait(tx);
2232			dmu_tx_abort(tx);
2233			goto top;
2234		}
2235		dmu_tx_abort(tx);
2236		ZFS_EXIT(zfsvfs);
2237		return (error);
2238	}
2239
2240#ifdef FREEBSD_NAMECACHE
2241	cache_purge(dvp);
2242#endif
2243
2244	error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2245
2246	if (error == 0) {
2247		uint64_t txtype = TX_RMDIR;
2248		if (flags & FIGNORECASE)
2249			txtype |= TX_CI;
2250		zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT);
2251	}
2252
2253	dmu_tx_commit(tx);
2254
2255	rw_exit(&zp->z_parent_lock);
2256	rw_exit(&zp->z_name_lock);
2257#ifdef FREEBSD_NAMECACHE
2258	cache_purge(vp);
2259#endif
2260out:
2261	zfs_dirent_unlock(dl);
2262
2263	VN_RELE(vp);
2264
2265	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2266		zil_commit(zilog, 0);
2267
2268	ZFS_EXIT(zfsvfs);
2269	return (error);
2270}
2271
2272/*
2273 * Read as many directory entries as will fit into the provided
2274 * buffer from the given directory cursor position (specified in
2275 * the uio structure.
2276 *
2277 *	IN:	vp	- vnode of directory to read.
2278 *		uio	- structure supplying read location, range info,
2279 *			  and return buffer.
2280 *		cr	- credentials of caller.
2281 *		ct	- caller context
2282 *		flags	- case flags
2283 *
2284 *	OUT:	uio	- updated offset and range, buffer filled.
2285 *		eofp	- set to true if end-of-file detected.
2286 *
2287 *	RETURN:	0 if success
2288 *		error code if failure
2289 *
2290 * Timestamps:
2291 *	vp - atime updated
2292 *
2293 * Note that the low 4 bits of the cookie returned by zap is always zero.
2294 * This allows us to use the low range for "special" directory entries:
2295 * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2296 * we use the offset 2 for the '.zfs' directory.
2297 */
2298/* ARGSUSED */
2299static int
2300zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp, int *ncookies, u_long **cookies)
2301{
2302	znode_t		*zp = VTOZ(vp);
2303	iovec_t		*iovp;
2304	edirent_t	*eodp;
2305	dirent64_t	*odp;
2306	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2307	objset_t	*os;
2308	caddr_t		outbuf;
2309	size_t		bufsize;
2310	zap_cursor_t	zc;
2311	zap_attribute_t	zap;
2312	uint_t		bytes_wanted;
2313	uint64_t	offset; /* must be unsigned; checks for < 1 */
2314	uint64_t	parent;
2315	int		local_eof;
2316	int		outcount;
2317	int		error;
2318	uint8_t		prefetch;
2319	boolean_t	check_sysattrs;
2320	uint8_t		type;
2321	int		ncooks;
2322	u_long		*cooks = NULL;
2323	int		flags = 0;
2324
2325	ZFS_ENTER(zfsvfs);
2326	ZFS_VERIFY_ZP(zp);
2327
2328	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2329	    &parent, sizeof (parent))) != 0) {
2330		ZFS_EXIT(zfsvfs);
2331		return (error);
2332	}
2333
2334	/*
2335	 * If we are not given an eof variable,
2336	 * use a local one.
2337	 */
2338	if (eofp == NULL)
2339		eofp = &local_eof;
2340
2341	/*
2342	 * Check for valid iov_len.
2343	 */
2344	if (uio->uio_iov->iov_len <= 0) {
2345		ZFS_EXIT(zfsvfs);
2346		return (EINVAL);
2347	}
2348
2349	/*
2350	 * Quit if directory has been removed (posix)
2351	 */
2352	if ((*eofp = zp->z_unlinked) != 0) {
2353		ZFS_EXIT(zfsvfs);
2354		return (0);
2355	}
2356
2357	error = 0;
2358	os = zfsvfs->z_os;
2359	offset = uio->uio_loffset;
2360	prefetch = zp->z_zn_prefetch;
2361
2362	/*
2363	 * Initialize the iterator cursor.
2364	 */
2365	if (offset <= 3) {
2366		/*
2367		 * Start iteration from the beginning of the directory.
2368		 */
2369		zap_cursor_init(&zc, os, zp->z_id);
2370	} else {
2371		/*
2372		 * The offset is a serialized cursor.
2373		 */
2374		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2375	}
2376
2377	/*
2378	 * Get space to change directory entries into fs independent format.
2379	 */
2380	iovp = uio->uio_iov;
2381	bytes_wanted = iovp->iov_len;
2382	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2383		bufsize = bytes_wanted;
2384		outbuf = kmem_alloc(bufsize, KM_SLEEP);
2385		odp = (struct dirent64 *)outbuf;
2386	} else {
2387		bufsize = bytes_wanted;
2388		odp = (struct dirent64 *)iovp->iov_base;
2389	}
2390	eodp = (struct edirent *)odp;
2391
2392	if (ncookies != NULL) {
2393		/*
2394		 * Minimum entry size is dirent size and 1 byte for a file name.
2395		 */
2396		ncooks = uio->uio_resid / (sizeof(struct dirent) - sizeof(((struct dirent *)NULL)->d_name) + 1);
2397		cooks = malloc(ncooks * sizeof(u_long), M_TEMP, M_WAITOK);
2398		*cookies = cooks;
2399		*ncookies = ncooks;
2400	}
2401	/*
2402	 * If this VFS supports the system attribute view interface; and
2403	 * we're looking at an extended attribute directory; and we care
2404	 * about normalization conflicts on this vfs; then we must check
2405	 * for normalization conflicts with the sysattr name space.
2406	 */
2407#ifdef TODO
2408	check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2409	    (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2410	    (flags & V_RDDIR_ENTFLAGS);
2411#else
2412	check_sysattrs = 0;
2413#endif
2414
2415	/*
2416	 * Transform to file-system independent format
2417	 */
2418	outcount = 0;
2419	while (outcount < bytes_wanted) {
2420		ino64_t objnum;
2421		ushort_t reclen;
2422		off64_t *next = NULL;
2423
2424		/*
2425		 * Special case `.', `..', and `.zfs'.
2426		 */
2427		if (offset == 0) {
2428			(void) strcpy(zap.za_name, ".");
2429			zap.za_normalization_conflict = 0;
2430			objnum = zp->z_id;
2431			type = DT_DIR;
2432		} else if (offset == 1) {
2433			(void) strcpy(zap.za_name, "..");
2434			zap.za_normalization_conflict = 0;
2435			objnum = parent;
2436			type = DT_DIR;
2437		} else if (offset == 2 && zfs_show_ctldir(zp)) {
2438			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2439			zap.za_normalization_conflict = 0;
2440			objnum = ZFSCTL_INO_ROOT;
2441			type = DT_DIR;
2442		} else {
2443			/*
2444			 * Grab next entry.
2445			 */
2446			if (error = zap_cursor_retrieve(&zc, &zap)) {
2447				if ((*eofp = (error == ENOENT)) != 0)
2448					break;
2449				else
2450					goto update;
2451			}
2452
2453			if (zap.za_integer_length != 8 ||
2454			    zap.za_num_integers != 1) {
2455				cmn_err(CE_WARN, "zap_readdir: bad directory "
2456				    "entry, obj = %lld, offset = %lld\n",
2457				    (u_longlong_t)zp->z_id,
2458				    (u_longlong_t)offset);
2459				error = ENXIO;
2460				goto update;
2461			}
2462
2463			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2464			/*
2465			 * MacOS X can extract the object type here such as:
2466			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2467			 */
2468			type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2469
2470			if (check_sysattrs && !zap.za_normalization_conflict) {
2471#ifdef TODO
2472				zap.za_normalization_conflict =
2473				    xattr_sysattr_casechk(zap.za_name);
2474#else
2475				panic("%s:%u: TODO", __func__, __LINE__);
2476#endif
2477			}
2478		}
2479
2480		if (flags & V_RDDIR_ACCFILTER) {
2481			/*
2482			 * If we have no access at all, don't include
2483			 * this entry in the returned information
2484			 */
2485			znode_t	*ezp;
2486			if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2487				goto skip_entry;
2488			if (!zfs_has_access(ezp, cr)) {
2489				VN_RELE(ZTOV(ezp));
2490				goto skip_entry;
2491			}
2492			VN_RELE(ZTOV(ezp));
2493		}
2494
2495		if (flags & V_RDDIR_ENTFLAGS)
2496			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2497		else
2498			reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2499
2500		/*
2501		 * Will this entry fit in the buffer?
2502		 */
2503		if (outcount + reclen > bufsize) {
2504			/*
2505			 * Did we manage to fit anything in the buffer?
2506			 */
2507			if (!outcount) {
2508				error = EINVAL;
2509				goto update;
2510			}
2511			break;
2512		}
2513		if (flags & V_RDDIR_ENTFLAGS) {
2514			/*
2515			 * Add extended flag entry:
2516			 */
2517			eodp->ed_ino = objnum;
2518			eodp->ed_reclen = reclen;
2519			/* NOTE: ed_off is the offset for the *next* entry */
2520			next = &(eodp->ed_off);
2521			eodp->ed_eflags = zap.za_normalization_conflict ?
2522			    ED_CASE_CONFLICT : 0;
2523			(void) strncpy(eodp->ed_name, zap.za_name,
2524			    EDIRENT_NAMELEN(reclen));
2525			eodp = (edirent_t *)((intptr_t)eodp + reclen);
2526		} else {
2527			/*
2528			 * Add normal entry:
2529			 */
2530			odp->d_ino = objnum;
2531			odp->d_reclen = reclen;
2532			odp->d_namlen = strlen(zap.za_name);
2533			(void) strlcpy(odp->d_name, zap.za_name, odp->d_namlen + 1);
2534			odp->d_type = type;
2535			odp = (dirent64_t *)((intptr_t)odp + reclen);
2536		}
2537		outcount += reclen;
2538
2539		ASSERT(outcount <= bufsize);
2540
2541		/* Prefetch znode */
2542		if (prefetch)
2543			dmu_prefetch(os, objnum, 0, 0);
2544
2545	skip_entry:
2546		/*
2547		 * Move to the next entry, fill in the previous offset.
2548		 */
2549		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2550			zap_cursor_advance(&zc);
2551			offset = zap_cursor_serialize(&zc);
2552		} else {
2553			offset += 1;
2554		}
2555
2556		if (cooks != NULL) {
2557			*cooks++ = offset;
2558			ncooks--;
2559			KASSERT(ncooks >= 0, ("ncookies=%d", ncooks));
2560		}
2561	}
2562	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2563
2564	/* Subtract unused cookies */
2565	if (ncookies != NULL)
2566		*ncookies -= ncooks;
2567
2568	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2569		iovp->iov_base += outcount;
2570		iovp->iov_len -= outcount;
2571		uio->uio_resid -= outcount;
2572	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2573		/*
2574		 * Reset the pointer.
2575		 */
2576		offset = uio->uio_loffset;
2577	}
2578
2579update:
2580	zap_cursor_fini(&zc);
2581	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2582		kmem_free(outbuf, bufsize);
2583
2584	if (error == ENOENT)
2585		error = 0;
2586
2587	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2588
2589	uio->uio_loffset = offset;
2590	ZFS_EXIT(zfsvfs);
2591	if (error != 0 && cookies != NULL) {
2592		free(*cookies, M_TEMP);
2593		*cookies = NULL;
2594		*ncookies = 0;
2595	}
2596	return (error);
2597}
2598
2599ulong_t zfs_fsync_sync_cnt = 4;
2600
2601static int
2602zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2603{
2604	znode_t	*zp = VTOZ(vp);
2605	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2606
2607	(void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2608
2609	if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2610		ZFS_ENTER(zfsvfs);
2611		ZFS_VERIFY_ZP(zp);
2612		zil_commit(zfsvfs->z_log, zp->z_id);
2613		ZFS_EXIT(zfsvfs);
2614	}
2615	return (0);
2616}
2617
2618
2619/*
2620 * Get the requested file attributes and place them in the provided
2621 * vattr structure.
2622 *
2623 *	IN:	vp	- vnode of file.
2624 *		vap	- va_mask identifies requested attributes.
2625 *			  If AT_XVATTR set, then optional attrs are requested
2626 *		flags	- ATTR_NOACLCHECK (CIFS server context)
2627 *		cr	- credentials of caller.
2628 *		ct	- caller context
2629 *
2630 *	OUT:	vap	- attribute values.
2631 *
2632 *	RETURN:	0 (always succeeds)
2633 */
2634/* ARGSUSED */
2635static int
2636zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2637    caller_context_t *ct)
2638{
2639	znode_t *zp = VTOZ(vp);
2640	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2641	int	error = 0;
2642	uint32_t blksize;
2643	u_longlong_t nblocks;
2644	uint64_t links;
2645	uint64_t mtime[2], ctime[2], crtime[2], rdev;
2646	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2647	xoptattr_t *xoap = NULL;
2648	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2649	sa_bulk_attr_t bulk[4];
2650	int count = 0;
2651
2652	ZFS_ENTER(zfsvfs);
2653	ZFS_VERIFY_ZP(zp);
2654
2655	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2656
2657	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2658	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2659	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &crtime, 16);
2660	if (vp->v_type == VBLK || vp->v_type == VCHR)
2661		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_RDEV(zfsvfs), NULL,
2662		    &rdev, 8);
2663
2664	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2665		ZFS_EXIT(zfsvfs);
2666		return (error);
2667	}
2668
2669	/*
2670	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2671	 * Also, if we are the owner don't bother, since owner should
2672	 * always be allowed to read basic attributes of file.
2673	 */
2674	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2675	    (vap->va_uid != crgetuid(cr))) {
2676		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2677		    skipaclchk, cr)) {
2678			ZFS_EXIT(zfsvfs);
2679			return (error);
2680		}
2681	}
2682
2683	/*
2684	 * Return all attributes.  It's cheaper to provide the answer
2685	 * than to determine whether we were asked the question.
2686	 */
2687
2688	mutex_enter(&zp->z_lock);
2689	vap->va_type = IFTOVT(zp->z_mode);
2690	vap->va_mode = zp->z_mode & ~S_IFMT;
2691//	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2692	vap->va_nodeid = zp->z_id;
2693	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2694		links = zp->z_links + 1;
2695	else
2696		links = zp->z_links;
2697	vap->va_nlink = MIN(links, UINT32_MAX);	/* nlink_t limit! */
2698	vap->va_size = zp->z_size;
2699	vap->va_fsid = vp->v_mount->mnt_stat.f_fsid.val[0];
2700	if (vp->v_type == VBLK || vp->v_type == VCHR)
2701		vap->va_rdev = zfs_cmpldev(rdev);
2702	vap->va_seq = zp->z_seq;
2703	vap->va_flags = 0;	/* FreeBSD: Reset chflags(2) flags. */
2704
2705	/*
2706	 * Add in any requested optional attributes and the create time.
2707	 * Also set the corresponding bits in the returned attribute bitmap.
2708	 */
2709	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2710		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2711			xoap->xoa_archive =
2712			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2713			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2714		}
2715
2716		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2717			xoap->xoa_readonly =
2718			    ((zp->z_pflags & ZFS_READONLY) != 0);
2719			XVA_SET_RTN(xvap, XAT_READONLY);
2720		}
2721
2722		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2723			xoap->xoa_system =
2724			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2725			XVA_SET_RTN(xvap, XAT_SYSTEM);
2726		}
2727
2728		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2729			xoap->xoa_hidden =
2730			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2731			XVA_SET_RTN(xvap, XAT_HIDDEN);
2732		}
2733
2734		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2735			xoap->xoa_nounlink =
2736			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2737			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2738		}
2739
2740		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2741			xoap->xoa_immutable =
2742			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2743			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2744		}
2745
2746		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2747			xoap->xoa_appendonly =
2748			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2749			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2750		}
2751
2752		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2753			xoap->xoa_nodump =
2754			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2755			XVA_SET_RTN(xvap, XAT_NODUMP);
2756		}
2757
2758		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2759			xoap->xoa_opaque =
2760			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2761			XVA_SET_RTN(xvap, XAT_OPAQUE);
2762		}
2763
2764		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2765			xoap->xoa_av_quarantined =
2766			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2767			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2768		}
2769
2770		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2771			xoap->xoa_av_modified =
2772			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2773			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2774		}
2775
2776		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2777		    vp->v_type == VREG) {
2778			zfs_sa_get_scanstamp(zp, xvap);
2779		}
2780
2781		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2782			uint64_t times[2];
2783
2784			(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2785			    times, sizeof (times));
2786			ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2787			XVA_SET_RTN(xvap, XAT_CREATETIME);
2788		}
2789
2790		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2791			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2792			XVA_SET_RTN(xvap, XAT_REPARSE);
2793		}
2794		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2795			xoap->xoa_generation = zp->z_gen;
2796			XVA_SET_RTN(xvap, XAT_GEN);
2797		}
2798
2799		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2800			xoap->xoa_offline =
2801			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2802			XVA_SET_RTN(xvap, XAT_OFFLINE);
2803		}
2804
2805		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2806			xoap->xoa_sparse =
2807			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2808			XVA_SET_RTN(xvap, XAT_SPARSE);
2809		}
2810	}
2811
2812	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2813	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2814	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2815	ZFS_TIME_DECODE(&vap->va_birthtime, crtime);
2816
2817	mutex_exit(&zp->z_lock);
2818
2819	sa_object_size(zp->z_sa_hdl, &blksize, &nblocks);
2820	vap->va_blksize = blksize;
2821	vap->va_bytes = nblocks << 9;	/* nblocks * 512 */
2822
2823	if (zp->z_blksz == 0) {
2824		/*
2825		 * Block size hasn't been set; suggest maximal I/O transfers.
2826		 */
2827		vap->va_blksize = zfsvfs->z_max_blksz;
2828	}
2829
2830	ZFS_EXIT(zfsvfs);
2831	return (0);
2832}
2833
2834/*
2835 * Set the file attributes to the values contained in the
2836 * vattr structure.
2837 *
2838 *	IN:	vp	- vnode of file to be modified.
2839 *		vap	- new attribute values.
2840 *			  If AT_XVATTR set, then optional attrs are being set
2841 *		flags	- ATTR_UTIME set if non-default time values provided.
2842 *			- ATTR_NOACLCHECK (CIFS context only).
2843 *		cr	- credentials of caller.
2844 *		ct	- caller context
2845 *
2846 *	RETURN:	0 if success
2847 *		error code if failure
2848 *
2849 * Timestamps:
2850 *	vp - ctime updated, mtime updated if size changed.
2851 */
2852/* ARGSUSED */
2853static int
2854zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2855	caller_context_t *ct)
2856{
2857	znode_t		*zp = VTOZ(vp);
2858	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2859	zilog_t		*zilog;
2860	dmu_tx_t	*tx;
2861	vattr_t		oldva;
2862	xvattr_t	tmpxvattr;
2863	uint_t		mask = vap->va_mask;
2864	uint_t		saved_mask;
2865	uint64_t	saved_mode;
2866	int		trim_mask = 0;
2867	uint64_t	new_mode;
2868	uint64_t	new_uid, new_gid;
2869	uint64_t	xattr_obj;
2870	uint64_t	mtime[2], ctime[2];
2871	znode_t		*attrzp;
2872	int		need_policy = FALSE;
2873	int		err, err2;
2874	zfs_fuid_info_t *fuidp = NULL;
2875	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2876	xoptattr_t	*xoap;
2877	zfs_acl_t	*aclp;
2878	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2879	boolean_t	fuid_dirtied = B_FALSE;
2880	sa_bulk_attr_t	bulk[7], xattr_bulk[7];
2881	int		count = 0, xattr_count = 0;
2882
2883	if (mask == 0)
2884		return (0);
2885
2886	if (mask & AT_NOSET)
2887		return (EINVAL);
2888
2889	ZFS_ENTER(zfsvfs);
2890	ZFS_VERIFY_ZP(zp);
2891
2892	zilog = zfsvfs->z_log;
2893
2894	/*
2895	 * Make sure that if we have ephemeral uid/gid or xvattr specified
2896	 * that file system is at proper version level
2897	 */
2898
2899	if (zfsvfs->z_use_fuids == B_FALSE &&
2900	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2901	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2902	    (mask & AT_XVATTR))) {
2903		ZFS_EXIT(zfsvfs);
2904		return (EINVAL);
2905	}
2906
2907	if (mask & AT_SIZE && vp->v_type == VDIR) {
2908		ZFS_EXIT(zfsvfs);
2909		return (EISDIR);
2910	}
2911
2912	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2913		ZFS_EXIT(zfsvfs);
2914		return (EINVAL);
2915	}
2916
2917	/*
2918	 * If this is an xvattr_t, then get a pointer to the structure of
2919	 * optional attributes.  If this is NULL, then we have a vattr_t.
2920	 */
2921	xoap = xva_getxoptattr(xvap);
2922
2923	xva_init(&tmpxvattr);
2924
2925	/*
2926	 * Immutable files can only alter immutable bit and atime
2927	 */
2928	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2929	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2930	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2931		ZFS_EXIT(zfsvfs);
2932		return (EPERM);
2933	}
2934
2935	if ((mask & AT_SIZE) && (zp->z_pflags & ZFS_READONLY)) {
2936		ZFS_EXIT(zfsvfs);
2937		return (EPERM);
2938	}
2939
2940	/*
2941	 * Verify timestamps doesn't overflow 32 bits.
2942	 * ZFS can handle large timestamps, but 32bit syscalls can't
2943	 * handle times greater than 2039.  This check should be removed
2944	 * once large timestamps are fully supported.
2945	 */
2946	if (mask & (AT_ATIME | AT_MTIME)) {
2947		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2948		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2949			ZFS_EXIT(zfsvfs);
2950			return (EOVERFLOW);
2951		}
2952	}
2953
2954top:
2955	attrzp = NULL;
2956	aclp = NULL;
2957
2958	/* Can this be moved to before the top label? */
2959	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2960		ZFS_EXIT(zfsvfs);
2961		return (EROFS);
2962	}
2963
2964	/*
2965	 * First validate permissions
2966	 */
2967
2968	if (mask & AT_SIZE) {
2969		/*
2970		 * XXX - Note, we are not providing any open
2971		 * mode flags here (like FNDELAY), so we may
2972		 * block if there are locks present... this
2973		 * should be addressed in openat().
2974		 */
2975		/* XXX - would it be OK to generate a log record here? */
2976		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2977		if (err) {
2978			ZFS_EXIT(zfsvfs);
2979			return (err);
2980		}
2981	}
2982
2983	if (mask & (AT_ATIME|AT_MTIME) ||
2984	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2985	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2986	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2987	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2988	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2989	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2990	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2991		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2992		    skipaclchk, cr);
2993	}
2994
2995	if (mask & (AT_UID|AT_GID)) {
2996		int	idmask = (mask & (AT_UID|AT_GID));
2997		int	take_owner;
2998		int	take_group;
2999
3000		/*
3001		 * NOTE: even if a new mode is being set,
3002		 * we may clear S_ISUID/S_ISGID bits.
3003		 */
3004
3005		if (!(mask & AT_MODE))
3006			vap->va_mode = zp->z_mode;
3007
3008		/*
3009		 * Take ownership or chgrp to group we are a member of
3010		 */
3011
3012		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
3013		take_group = (mask & AT_GID) &&
3014		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
3015
3016		/*
3017		 * If both AT_UID and AT_GID are set then take_owner and
3018		 * take_group must both be set in order to allow taking
3019		 * ownership.
3020		 *
3021		 * Otherwise, send the check through secpolicy_vnode_setattr()
3022		 *
3023		 */
3024
3025		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
3026		    ((idmask == AT_UID) && take_owner) ||
3027		    ((idmask == AT_GID) && take_group)) {
3028			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
3029			    skipaclchk, cr) == 0) {
3030				/*
3031				 * Remove setuid/setgid for non-privileged users
3032				 */
3033				secpolicy_setid_clear(vap, vp, cr);
3034				trim_mask = (mask & (AT_UID|AT_GID));
3035			} else {
3036				need_policy =  TRUE;
3037			}
3038		} else {
3039			need_policy =  TRUE;
3040		}
3041	}
3042
3043	mutex_enter(&zp->z_lock);
3044	oldva.va_mode = zp->z_mode;
3045	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
3046	if (mask & AT_XVATTR) {
3047		/*
3048		 * Update xvattr mask to include only those attributes
3049		 * that are actually changing.
3050		 *
3051		 * the bits will be restored prior to actually setting
3052		 * the attributes so the caller thinks they were set.
3053		 */
3054		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
3055			if (xoap->xoa_appendonly !=
3056			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
3057				need_policy = TRUE;
3058			} else {
3059				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
3060				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
3061			}
3062		}
3063
3064		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
3065			if (xoap->xoa_nounlink !=
3066			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
3067				need_policy = TRUE;
3068			} else {
3069				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
3070				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
3071			}
3072		}
3073
3074		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
3075			if (xoap->xoa_immutable !=
3076			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
3077				need_policy = TRUE;
3078			} else {
3079				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
3080				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
3081			}
3082		}
3083
3084		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
3085			if (xoap->xoa_nodump !=
3086			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
3087				need_policy = TRUE;
3088			} else {
3089				XVA_CLR_REQ(xvap, XAT_NODUMP);
3090				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
3091			}
3092		}
3093
3094		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
3095			if (xoap->xoa_av_modified !=
3096			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
3097				need_policy = TRUE;
3098			} else {
3099				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
3100				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
3101			}
3102		}
3103
3104		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
3105			if ((vp->v_type != VREG &&
3106			    xoap->xoa_av_quarantined) ||
3107			    xoap->xoa_av_quarantined !=
3108			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
3109				need_policy = TRUE;
3110			} else {
3111				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
3112				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
3113			}
3114		}
3115
3116		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
3117			mutex_exit(&zp->z_lock);
3118			ZFS_EXIT(zfsvfs);
3119			return (EPERM);
3120		}
3121
3122		if (need_policy == FALSE &&
3123		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
3124		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
3125			need_policy = TRUE;
3126		}
3127	}
3128
3129	mutex_exit(&zp->z_lock);
3130
3131	if (mask & AT_MODE) {
3132		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
3133			err = secpolicy_setid_setsticky_clear(vp, vap,
3134			    &oldva, cr);
3135			if (err) {
3136				ZFS_EXIT(zfsvfs);
3137				return (err);
3138			}
3139			trim_mask |= AT_MODE;
3140		} else {
3141			need_policy = TRUE;
3142		}
3143	}
3144
3145	if (need_policy) {
3146		/*
3147		 * If trim_mask is set then take ownership
3148		 * has been granted or write_acl is present and user
3149		 * has the ability to modify mode.  In that case remove
3150		 * UID|GID and or MODE from mask so that
3151		 * secpolicy_vnode_setattr() doesn't revoke it.
3152		 */
3153
3154		if (trim_mask) {
3155			saved_mask = vap->va_mask;
3156			vap->va_mask &= ~trim_mask;
3157			if (trim_mask & AT_MODE) {
3158				/*
3159				 * Save the mode, as secpolicy_vnode_setattr()
3160				 * will overwrite it with ova.va_mode.
3161				 */
3162				saved_mode = vap->va_mode;
3163			}
3164		}
3165		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
3166		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
3167		if (err) {
3168			ZFS_EXIT(zfsvfs);
3169			return (err);
3170		}
3171
3172		if (trim_mask) {
3173			vap->va_mask |= saved_mask;
3174			if (trim_mask & AT_MODE) {
3175				/*
3176				 * Recover the mode after
3177				 * secpolicy_vnode_setattr().
3178				 */
3179				vap->va_mode = saved_mode;
3180			}
3181		}
3182	}
3183
3184	/*
3185	 * secpolicy_vnode_setattr, or take ownership may have
3186	 * changed va_mask
3187	 */
3188	mask = vap->va_mask;
3189
3190	if ((mask & (AT_UID | AT_GID))) {
3191		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
3192		    &xattr_obj, sizeof (xattr_obj));
3193
3194		if (err == 0 && xattr_obj) {
3195			err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
3196			if (err)
3197				goto out2;
3198		}
3199		if (mask & AT_UID) {
3200			new_uid = zfs_fuid_create(zfsvfs,
3201			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3202			if (new_uid != zp->z_uid &&
3203			    zfs_fuid_overquota(zfsvfs, B_FALSE, new_uid)) {
3204				if (attrzp)
3205					VN_RELE(ZTOV(attrzp));
3206				err = EDQUOT;
3207				goto out2;
3208			}
3209		}
3210
3211		if (mask & AT_GID) {
3212			new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3213			    cr, ZFS_GROUP, &fuidp);
3214			if (new_gid != zp->z_gid &&
3215			    zfs_fuid_overquota(zfsvfs, B_TRUE, new_gid)) {
3216				if (attrzp)
3217					VN_RELE(ZTOV(attrzp));
3218				err = EDQUOT;
3219				goto out2;
3220			}
3221		}
3222	}
3223	tx = dmu_tx_create(zfsvfs->z_os);
3224
3225	if (mask & AT_MODE) {
3226		uint64_t pmode = zp->z_mode;
3227		uint64_t acl_obj;
3228		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3229
3230		if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3231			goto out;
3232
3233		mutex_enter(&zp->z_lock);
3234		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
3235			/*
3236			 * Are we upgrading ACL from old V0 format
3237			 * to V1 format?
3238			 */
3239			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
3240			    zfs_znode_acl_version(zp) ==
3241			    ZFS_ACL_VERSION_INITIAL) {
3242				dmu_tx_hold_free(tx, acl_obj, 0,
3243				    DMU_OBJECT_END);
3244				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3245				    0, aclp->z_acl_bytes);
3246			} else {
3247				dmu_tx_hold_write(tx, acl_obj, 0,
3248				    aclp->z_acl_bytes);
3249			}
3250		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3251			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3252			    0, aclp->z_acl_bytes);
3253		}
3254		mutex_exit(&zp->z_lock);
3255		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3256	} else {
3257		if ((mask & AT_XVATTR) &&
3258		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3259			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3260		else
3261			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3262	}
3263
3264	if (attrzp) {
3265		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
3266	}
3267
3268	fuid_dirtied = zfsvfs->z_fuid_dirty;
3269	if (fuid_dirtied)
3270		zfs_fuid_txhold(zfsvfs, tx);
3271
3272	zfs_sa_upgrade_txholds(tx, zp);
3273
3274	err = dmu_tx_assign(tx, TXG_NOWAIT);
3275	if (err) {
3276		if (err == ERESTART)
3277			dmu_tx_wait(tx);
3278		goto out;
3279	}
3280
3281	count = 0;
3282	/*
3283	 * Set each attribute requested.
3284	 * We group settings according to the locks they need to acquire.
3285	 *
3286	 * Note: you cannot set ctime directly, although it will be
3287	 * updated as a side-effect of calling this function.
3288	 */
3289
3290
3291	if (mask & (AT_UID|AT_GID|AT_MODE))
3292		mutex_enter(&zp->z_acl_lock);
3293	mutex_enter(&zp->z_lock);
3294
3295	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3296	    &zp->z_pflags, sizeof (zp->z_pflags));
3297
3298	if (attrzp) {
3299		if (mask & (AT_UID|AT_GID|AT_MODE))
3300			mutex_enter(&attrzp->z_acl_lock);
3301		mutex_enter(&attrzp->z_lock);
3302		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3303		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
3304		    sizeof (attrzp->z_pflags));
3305	}
3306
3307	if (mask & (AT_UID|AT_GID)) {
3308
3309		if (mask & AT_UID) {
3310			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
3311			    &new_uid, sizeof (new_uid));
3312			zp->z_uid = new_uid;
3313			if (attrzp) {
3314				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3315				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
3316				    sizeof (new_uid));
3317				attrzp->z_uid = new_uid;
3318			}
3319		}
3320
3321		if (mask & AT_GID) {
3322			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
3323			    NULL, &new_gid, sizeof (new_gid));
3324			zp->z_gid = new_gid;
3325			if (attrzp) {
3326				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3327				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
3328				    sizeof (new_gid));
3329				attrzp->z_gid = new_gid;
3330			}
3331		}
3332		if (!(mask & AT_MODE)) {
3333			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
3334			    NULL, &new_mode, sizeof (new_mode));
3335			new_mode = zp->z_mode;
3336		}
3337		err = zfs_acl_chown_setattr(zp);
3338		ASSERT(err == 0);
3339		if (attrzp) {
3340			err = zfs_acl_chown_setattr(attrzp);
3341			ASSERT(err == 0);
3342		}
3343	}
3344
3345	if (mask & AT_MODE) {
3346		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
3347		    &new_mode, sizeof (new_mode));
3348		zp->z_mode = new_mode;
3349		ASSERT3U((uintptr_t)aclp, !=, 0);
3350		err = zfs_aclset_common(zp, aclp, cr, tx);
3351		ASSERT3U(err, ==, 0);
3352		if (zp->z_acl_cached)
3353			zfs_acl_free(zp->z_acl_cached);
3354		zp->z_acl_cached = aclp;
3355		aclp = NULL;
3356	}
3357
3358
3359	if (mask & AT_ATIME) {
3360		ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
3361		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
3362		    &zp->z_atime, sizeof (zp->z_atime));
3363	}
3364
3365	if (mask & AT_MTIME) {
3366		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3367		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3368		    mtime, sizeof (mtime));
3369	}
3370
3371	/* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3372	if (mask & AT_SIZE && !(mask & AT_MTIME)) {
3373		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
3374		    NULL, mtime, sizeof (mtime));
3375		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3376		    &ctime, sizeof (ctime));
3377		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3378		    B_TRUE);
3379	} else if (mask != 0) {
3380		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3381		    &ctime, sizeof (ctime));
3382		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
3383		    B_TRUE);
3384		if (attrzp) {
3385			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3386			    SA_ZPL_CTIME(zfsvfs), NULL,
3387			    &ctime, sizeof (ctime));
3388			zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3389			    mtime, ctime, B_TRUE);
3390		}
3391	}
3392	/*
3393	 * Do this after setting timestamps to prevent timestamp
3394	 * update from toggling bit
3395	 */
3396
3397	if (xoap && (mask & AT_XVATTR)) {
3398
3399		/*
3400		 * restore trimmed off masks
3401		 * so that return masks can be set for caller.
3402		 */
3403
3404		if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3405			XVA_SET_REQ(xvap, XAT_APPENDONLY);
3406		}
3407		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3408			XVA_SET_REQ(xvap, XAT_NOUNLINK);
3409		}
3410		if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3411			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3412		}
3413		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3414			XVA_SET_REQ(xvap, XAT_NODUMP);
3415		}
3416		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3417			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3418		}
3419		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3420			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3421		}
3422
3423		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3424			ASSERT(vp->v_type == VREG);
3425
3426		zfs_xvattr_set(zp, xvap, tx);
3427	}
3428
3429	if (fuid_dirtied)
3430		zfs_fuid_sync(zfsvfs, tx);
3431
3432	if (mask != 0)
3433		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3434
3435	mutex_exit(&zp->z_lock);
3436	if (mask & (AT_UID|AT_GID|AT_MODE))
3437		mutex_exit(&zp->z_acl_lock);
3438
3439	if (attrzp) {
3440		if (mask & (AT_UID|AT_GID|AT_MODE))
3441			mutex_exit(&attrzp->z_acl_lock);
3442		mutex_exit(&attrzp->z_lock);
3443	}
3444out:
3445	if (err == 0 && attrzp) {
3446		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3447		    xattr_count, tx);
3448		ASSERT(err2 == 0);
3449	}
3450
3451	if (attrzp)
3452		VN_RELE(ZTOV(attrzp));
3453	if (aclp)
3454		zfs_acl_free(aclp);
3455
3456	if (fuidp) {
3457		zfs_fuid_info_free(fuidp);
3458		fuidp = NULL;
3459	}
3460
3461	if (err) {
3462		dmu_tx_abort(tx);
3463		if (err == ERESTART)
3464			goto top;
3465	} else {
3466		err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3467		dmu_tx_commit(tx);
3468	}
3469
3470out2:
3471	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3472		zil_commit(zilog, 0);
3473
3474	ZFS_EXIT(zfsvfs);
3475	return (err);
3476}
3477
3478typedef struct zfs_zlock {
3479	krwlock_t	*zl_rwlock;	/* lock we acquired */
3480	znode_t		*zl_znode;	/* znode we held */
3481	struct zfs_zlock *zl_next;	/* next in list */
3482} zfs_zlock_t;
3483
3484/*
3485 * Drop locks and release vnodes that were held by zfs_rename_lock().
3486 */
3487static void
3488zfs_rename_unlock(zfs_zlock_t **zlpp)
3489{
3490	zfs_zlock_t *zl;
3491
3492	while ((zl = *zlpp) != NULL) {
3493		if (zl->zl_znode != NULL)
3494			VN_RELE(ZTOV(zl->zl_znode));
3495		rw_exit(zl->zl_rwlock);
3496		*zlpp = zl->zl_next;
3497		kmem_free(zl, sizeof (*zl));
3498	}
3499}
3500
3501/*
3502 * Search back through the directory tree, using the ".." entries.
3503 * Lock each directory in the chain to prevent concurrent renames.
3504 * Fail any attempt to move a directory into one of its own descendants.
3505 * XXX - z_parent_lock can overlap with map or grow locks
3506 */
3507static int
3508zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3509{
3510	zfs_zlock_t	*zl;
3511	znode_t		*zp = tdzp;
3512	uint64_t	rootid = zp->z_zfsvfs->z_root;
3513	uint64_t	oidp = zp->z_id;
3514	krwlock_t	*rwlp = &szp->z_parent_lock;
3515	krw_t		rw = RW_WRITER;
3516
3517	/*
3518	 * First pass write-locks szp and compares to zp->z_id.
3519	 * Later passes read-lock zp and compare to zp->z_parent.
3520	 */
3521	do {
3522		if (!rw_tryenter(rwlp, rw)) {
3523			/*
3524			 * Another thread is renaming in this path.
3525			 * Note that if we are a WRITER, we don't have any
3526			 * parent_locks held yet.
3527			 */
3528			if (rw == RW_READER && zp->z_id > szp->z_id) {
3529				/*
3530				 * Drop our locks and restart
3531				 */
3532				zfs_rename_unlock(&zl);
3533				*zlpp = NULL;
3534				zp = tdzp;
3535				oidp = zp->z_id;
3536				rwlp = &szp->z_parent_lock;
3537				rw = RW_WRITER;
3538				continue;
3539			} else {
3540				/*
3541				 * Wait for other thread to drop its locks
3542				 */
3543				rw_enter(rwlp, rw);
3544			}
3545		}
3546
3547		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3548		zl->zl_rwlock = rwlp;
3549		zl->zl_znode = NULL;
3550		zl->zl_next = *zlpp;
3551		*zlpp = zl;
3552
3553		if (oidp == szp->z_id)		/* We're a descendant of szp */
3554			return (EINVAL);
3555
3556		if (oidp == rootid)		/* We've hit the top */
3557			return (0);
3558
3559		if (rw == RW_READER) {		/* i.e. not the first pass */
3560			int error = zfs_zget(zp->z_zfsvfs, oidp, &zp);
3561			if (error)
3562				return (error);
3563			zl->zl_znode = zp;
3564		}
3565		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zp->z_zfsvfs),
3566		    &oidp, sizeof (oidp));
3567		rwlp = &zp->z_parent_lock;
3568		rw = RW_READER;
3569
3570	} while (zp->z_id != sdzp->z_id);
3571
3572	return (0);
3573}
3574
3575/*
3576 * Move an entry from the provided source directory to the target
3577 * directory.  Change the entry name as indicated.
3578 *
3579 *	IN:	sdvp	- Source directory containing the "old entry".
3580 *		snm	- Old entry name.
3581 *		tdvp	- Target directory to contain the "new entry".
3582 *		tnm	- New entry name.
3583 *		cr	- credentials of caller.
3584 *		ct	- caller context
3585 *		flags	- case flags
3586 *
3587 *	RETURN:	0 if success
3588 *		error code if failure
3589 *
3590 * Timestamps:
3591 *	sdvp,tdvp - ctime|mtime updated
3592 */
3593/*ARGSUSED*/
3594static int
3595zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
3596    caller_context_t *ct, int flags)
3597{
3598	znode_t		*tdzp, *szp, *tzp;
3599	znode_t		*sdzp = VTOZ(sdvp);
3600	zfsvfs_t	*zfsvfs = sdzp->z_zfsvfs;
3601	zilog_t		*zilog;
3602	vnode_t		*realvp;
3603	zfs_dirlock_t	*sdl, *tdl;
3604	dmu_tx_t	*tx;
3605	zfs_zlock_t	*zl;
3606	int		cmp, serr, terr;
3607	int		error = 0;
3608	int		zflg = 0;
3609
3610	ZFS_ENTER(zfsvfs);
3611	ZFS_VERIFY_ZP(sdzp);
3612	zilog = zfsvfs->z_log;
3613
3614	/*
3615	 * Make sure we have the real vp for the target directory.
3616	 */
3617	if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3618		tdvp = realvp;
3619
3620	if (tdvp->v_vfsp != sdvp->v_vfsp || zfsctl_is_node(tdvp)) {
3621		ZFS_EXIT(zfsvfs);
3622		return (EXDEV);
3623	}
3624
3625	tdzp = VTOZ(tdvp);
3626	ZFS_VERIFY_ZP(tdzp);
3627	if (zfsvfs->z_utf8 && u8_validate(tnm,
3628	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3629		ZFS_EXIT(zfsvfs);
3630		return (EILSEQ);
3631	}
3632
3633	if (flags & FIGNORECASE)
3634		zflg |= ZCILOOK;
3635
3636top:
3637	szp = NULL;
3638	tzp = NULL;
3639	zl = NULL;
3640
3641	/*
3642	 * This is to prevent the creation of links into attribute space
3643	 * by renaming a linked file into/outof an attribute directory.
3644	 * See the comment in zfs_link() for why this is considered bad.
3645	 */
3646	if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3647		ZFS_EXIT(zfsvfs);
3648		return (EINVAL);
3649	}
3650
3651	/*
3652	 * Lock source and target directory entries.  To prevent deadlock,
3653	 * a lock ordering must be defined.  We lock the directory with
3654	 * the smallest object id first, or if it's a tie, the one with
3655	 * the lexically first name.
3656	 */
3657	if (sdzp->z_id < tdzp->z_id) {
3658		cmp = -1;
3659	} else if (sdzp->z_id > tdzp->z_id) {
3660		cmp = 1;
3661	} else {
3662		/*
3663		 * First compare the two name arguments without
3664		 * considering any case folding.
3665		 */
3666		int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
3667
3668		cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3669		ASSERT(error == 0 || !zfsvfs->z_utf8);
3670		if (cmp == 0) {
3671			/*
3672			 * POSIX: "If the old argument and the new argument
3673			 * both refer to links to the same existing file,
3674			 * the rename() function shall return successfully
3675			 * and perform no other action."
3676			 */
3677			ZFS_EXIT(zfsvfs);
3678			return (0);
3679		}
3680		/*
3681		 * If the file system is case-folding, then we may
3682		 * have some more checking to do.  A case-folding file
3683		 * system is either supporting mixed case sensitivity
3684		 * access or is completely case-insensitive.  Note
3685		 * that the file system is always case preserving.
3686		 *
3687		 * In mixed sensitivity mode case sensitive behavior
3688		 * is the default.  FIGNORECASE must be used to
3689		 * explicitly request case insensitive behavior.
3690		 *
3691		 * If the source and target names provided differ only
3692		 * by case (e.g., a request to rename 'tim' to 'Tim'),
3693		 * we will treat this as a special case in the
3694		 * case-insensitive mode: as long as the source name
3695		 * is an exact match, we will allow this to proceed as
3696		 * a name-change request.
3697		 */
3698		if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
3699		    (zfsvfs->z_case == ZFS_CASE_MIXED &&
3700		    flags & FIGNORECASE)) &&
3701		    u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
3702		    &error) == 0) {
3703			/*
3704			 * case preserving rename request, require exact
3705			 * name matches
3706			 */
3707			zflg |= ZCIEXACT;
3708			zflg &= ~ZCILOOK;
3709		}
3710	}
3711
3712	/*
3713	 * If the source and destination directories are the same, we should
3714	 * grab the z_name_lock of that directory only once.
3715	 */
3716	if (sdzp == tdzp) {
3717		zflg |= ZHAVELOCK;
3718		rw_enter(&sdzp->z_name_lock, RW_READER);
3719	}
3720
3721	if (cmp < 0) {
3722		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3723		    ZEXISTS | zflg, NULL, NULL);
3724		terr = zfs_dirent_lock(&tdl,
3725		    tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3726	} else {
3727		terr = zfs_dirent_lock(&tdl,
3728		    tdzp, tnm, &tzp, zflg, NULL, NULL);
3729		serr = zfs_dirent_lock(&sdl,
3730		    sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3731		    NULL, NULL);
3732	}
3733
3734	if (serr) {
3735		/*
3736		 * Source entry invalid or not there.
3737		 */
3738		if (!terr) {
3739			zfs_dirent_unlock(tdl);
3740			if (tzp)
3741				VN_RELE(ZTOV(tzp));
3742		}
3743
3744		if (sdzp == tdzp)
3745			rw_exit(&sdzp->z_name_lock);
3746
3747		/*
3748		 * FreeBSD: In OpenSolaris they only check if rename source is
3749		 * ".." here, because "." is handled in their lookup. This is
3750		 * not the case for FreeBSD, so we check for "." explicitly.
3751		 */
3752		if (strcmp(snm, ".") == 0 || strcmp(snm, "..") == 0)
3753			serr = EINVAL;
3754		ZFS_EXIT(zfsvfs);
3755		return (serr);
3756	}
3757	if (terr) {
3758		zfs_dirent_unlock(sdl);
3759		VN_RELE(ZTOV(szp));
3760
3761		if (sdzp == tdzp)
3762			rw_exit(&sdzp->z_name_lock);
3763
3764		if (strcmp(tnm, "..") == 0)
3765			terr = EINVAL;
3766		ZFS_EXIT(zfsvfs);
3767		return (terr);
3768	}
3769
3770	/*
3771	 * Must have write access at the source to remove the old entry
3772	 * and write access at the target to create the new entry.
3773	 * Note that if target and source are the same, this can be
3774	 * done in a single check.
3775	 */
3776
3777	if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
3778		goto out;
3779
3780	if (ZTOV(szp)->v_type == VDIR) {
3781		/*
3782		 * Check to make sure rename is valid.
3783		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3784		 */
3785		if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
3786			goto out;
3787	}
3788
3789	/*
3790	 * Does target exist?
3791	 */
3792	if (tzp) {
3793		/*
3794		 * Source and target must be the same type.
3795		 */
3796		if (ZTOV(szp)->v_type == VDIR) {
3797			if (ZTOV(tzp)->v_type != VDIR) {
3798				error = ENOTDIR;
3799				goto out;
3800			}
3801		} else {
3802			if (ZTOV(tzp)->v_type == VDIR) {
3803				error = EISDIR;
3804				goto out;
3805			}
3806		}
3807		/*
3808		 * POSIX dictates that when the source and target
3809		 * entries refer to the same file object, rename
3810		 * must do nothing and exit without error.
3811		 */
3812		if (szp->z_id == tzp->z_id) {
3813			error = 0;
3814			goto out;
3815		}
3816	}
3817
3818	vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
3819	if (tzp)
3820		vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3821
3822	/*
3823	 * notify the target directory if it is not the same
3824	 * as source directory.
3825	 */
3826	if (tdvp != sdvp) {
3827		vnevent_rename_dest_dir(tdvp, ct);
3828	}
3829
3830	tx = dmu_tx_create(zfsvfs->z_os);
3831	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3832	dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3833	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3834	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3835	if (sdzp != tdzp) {
3836		dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3837		zfs_sa_upgrade_txholds(tx, tdzp);
3838	}
3839	if (tzp) {
3840		dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3841		zfs_sa_upgrade_txholds(tx, tzp);
3842	}
3843
3844	zfs_sa_upgrade_txholds(tx, szp);
3845	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3846	error = dmu_tx_assign(tx, TXG_NOWAIT);
3847	if (error) {
3848		if (zl != NULL)
3849			zfs_rename_unlock(&zl);
3850		zfs_dirent_unlock(sdl);
3851		zfs_dirent_unlock(tdl);
3852
3853		if (sdzp == tdzp)
3854			rw_exit(&sdzp->z_name_lock);
3855
3856		VN_RELE(ZTOV(szp));
3857		if (tzp)
3858			VN_RELE(ZTOV(tzp));
3859		if (error == ERESTART) {
3860			dmu_tx_wait(tx);
3861			dmu_tx_abort(tx);
3862			goto top;
3863		}
3864		dmu_tx_abort(tx);
3865		ZFS_EXIT(zfsvfs);
3866		return (error);
3867	}
3868
3869	if (tzp)	/* Attempt to remove the existing target */
3870		error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3871
3872	if (error == 0) {
3873		error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3874		if (error == 0) {
3875			szp->z_pflags |= ZFS_AV_MODIFIED;
3876
3877			error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3878			    (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3879			ASSERT3U(error, ==, 0);
3880
3881			error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3882			if (error == 0) {
3883				zfs_log_rename(zilog, tx, TX_RENAME |
3884				    (flags & FIGNORECASE ? TX_CI : 0), sdzp,
3885				    sdl->dl_name, tdzp, tdl->dl_name, szp);
3886
3887				/*
3888				 * Update path information for the target vnode
3889				 */
3890				vn_renamepath(tdvp, ZTOV(szp), tnm,
3891				    strlen(tnm));
3892			} else {
3893				/*
3894				 * At this point, we have successfully created
3895				 * the target name, but have failed to remove
3896				 * the source name.  Since the create was done
3897				 * with the ZRENAMING flag, there are
3898				 * complications; for one, the link count is
3899				 * wrong.  The easiest way to deal with this
3900				 * is to remove the newly created target, and
3901				 * return the original error.  This must
3902				 * succeed; fortunately, it is very unlikely to
3903				 * fail, since we just created it.
3904				 */
3905				VERIFY3U(zfs_link_destroy(tdl, szp, tx,
3906				    ZRENAMING, NULL), ==, 0);
3907			}
3908		}
3909#ifdef FREEBSD_NAMECACHE
3910		if (error == 0) {
3911			cache_purge(sdvp);
3912			cache_purge(tdvp);
3913		}
3914#endif
3915	}
3916
3917	dmu_tx_commit(tx);
3918out:
3919	if (zl != NULL)
3920		zfs_rename_unlock(&zl);
3921
3922	zfs_dirent_unlock(sdl);
3923	zfs_dirent_unlock(tdl);
3924
3925	if (sdzp == tdzp)
3926		rw_exit(&sdzp->z_name_lock);
3927
3928
3929	VN_RELE(ZTOV(szp));
3930	if (tzp)
3931		VN_RELE(ZTOV(tzp));
3932
3933	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3934		zil_commit(zilog, 0);
3935
3936	ZFS_EXIT(zfsvfs);
3937
3938	return (error);
3939}
3940
3941/*
3942 * Insert the indicated symbolic reference entry into the directory.
3943 *
3944 *	IN:	dvp	- Directory to contain new symbolic link.
3945 *		link	- Name for new symlink entry.
3946 *		vap	- Attributes of new entry.
3947 *		target	- Target path of new symlink.
3948 *		cr	- credentials of caller.
3949 *		ct	- caller context
3950 *		flags	- case flags
3951 *
3952 *	RETURN:	0 if success
3953 *		error code if failure
3954 *
3955 * Timestamps:
3956 *	dvp - ctime|mtime updated
3957 */
3958/*ARGSUSED*/
3959static int
3960zfs_symlink(vnode_t *dvp, vnode_t **vpp, char *name, vattr_t *vap, char *link,
3961    cred_t *cr, kthread_t *td)
3962{
3963	znode_t		*zp, *dzp = VTOZ(dvp);
3964	zfs_dirlock_t	*dl;
3965	dmu_tx_t	*tx;
3966	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3967	zilog_t		*zilog;
3968	uint64_t	len = strlen(link);
3969	int		error;
3970	int		zflg = ZNEW;
3971	zfs_acl_ids_t	acl_ids;
3972	boolean_t	fuid_dirtied;
3973	uint64_t	txtype = TX_SYMLINK;
3974	int		flags = 0;
3975
3976	ASSERT(vap->va_type == VLNK);
3977
3978	ZFS_ENTER(zfsvfs);
3979	ZFS_VERIFY_ZP(dzp);
3980	zilog = zfsvfs->z_log;
3981
3982	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3983	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3984		ZFS_EXIT(zfsvfs);
3985		return (EILSEQ);
3986	}
3987	if (flags & FIGNORECASE)
3988		zflg |= ZCILOOK;
3989
3990	if (len > MAXPATHLEN) {
3991		ZFS_EXIT(zfsvfs);
3992		return (ENAMETOOLONG);
3993	}
3994
3995	if ((error = zfs_acl_ids_create(dzp, 0,
3996	    vap, cr, NULL, &acl_ids)) != 0) {
3997		ZFS_EXIT(zfsvfs);
3998		return (error);
3999	}
4000top:
4001	/*
4002	 * Attempt to lock directory; fail if entry already exists.
4003	 */
4004	error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
4005	if (error) {
4006		zfs_acl_ids_free(&acl_ids);
4007		ZFS_EXIT(zfsvfs);
4008		return (error);
4009	}
4010
4011	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4012		zfs_acl_ids_free(&acl_ids);
4013		zfs_dirent_unlock(dl);
4014		ZFS_EXIT(zfsvfs);
4015		return (error);
4016	}
4017
4018	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
4019		zfs_acl_ids_free(&acl_ids);
4020		zfs_dirent_unlock(dl);
4021		ZFS_EXIT(zfsvfs);
4022		return (EDQUOT);
4023	}
4024	tx = dmu_tx_create(zfsvfs->z_os);
4025	fuid_dirtied = zfsvfs->z_fuid_dirty;
4026	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
4027	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4028	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
4029	    ZFS_SA_BASE_ATTR_SIZE + len);
4030	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
4031	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
4032		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
4033		    acl_ids.z_aclp->z_acl_bytes);
4034	}
4035	if (fuid_dirtied)
4036		zfs_fuid_txhold(zfsvfs, tx);
4037	error = dmu_tx_assign(tx, TXG_NOWAIT);
4038	if (error) {
4039		zfs_dirent_unlock(dl);
4040		if (error == ERESTART) {
4041			dmu_tx_wait(tx);
4042			dmu_tx_abort(tx);
4043			goto top;
4044		}
4045		zfs_acl_ids_free(&acl_ids);
4046		dmu_tx_abort(tx);
4047		ZFS_EXIT(zfsvfs);
4048		return (error);
4049	}
4050
4051	/*
4052	 * Create a new object for the symlink.
4053	 * for version 4 ZPL datsets the symlink will be an SA attribute
4054	 */
4055	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
4056
4057	if (fuid_dirtied)
4058		zfs_fuid_sync(zfsvfs, tx);
4059
4060	mutex_enter(&zp->z_lock);
4061	if (zp->z_is_sa)
4062		error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
4063		    link, len, tx);
4064	else
4065		zfs_sa_symlink(zp, link, len, tx);
4066	mutex_exit(&zp->z_lock);
4067
4068	zp->z_size = len;
4069	(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
4070	    &zp->z_size, sizeof (zp->z_size), tx);
4071	/*
4072	 * Insert the new object into the directory.
4073	 */
4074	(void) zfs_link_create(dl, zp, tx, ZNEW);
4075
4076	if (flags & FIGNORECASE)
4077		txtype |= TX_CI;
4078	zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
4079	*vpp = ZTOV(zp);
4080
4081	zfs_acl_ids_free(&acl_ids);
4082
4083	dmu_tx_commit(tx);
4084
4085	zfs_dirent_unlock(dl);
4086
4087	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4088		zil_commit(zilog, 0);
4089
4090	ZFS_EXIT(zfsvfs);
4091	return (error);
4092}
4093
4094/*
4095 * Return, in the buffer contained in the provided uio structure,
4096 * the symbolic path referred to by vp.
4097 *
4098 *	IN:	vp	- vnode of symbolic link.
4099 *		uoip	- structure to contain the link path.
4100 *		cr	- credentials of caller.
4101 *		ct	- caller context
4102 *
4103 *	OUT:	uio	- structure to contain the link path.
4104 *
4105 *	RETURN:	0 if success
4106 *		error code if failure
4107 *
4108 * Timestamps:
4109 *	vp - atime updated
4110 */
4111/* ARGSUSED */
4112static int
4113zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
4114{
4115	znode_t		*zp = VTOZ(vp);
4116	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4117	int		error;
4118
4119	ZFS_ENTER(zfsvfs);
4120	ZFS_VERIFY_ZP(zp);
4121
4122	mutex_enter(&zp->z_lock);
4123	if (zp->z_is_sa)
4124		error = sa_lookup_uio(zp->z_sa_hdl,
4125		    SA_ZPL_SYMLINK(zfsvfs), uio);
4126	else
4127		error = zfs_sa_readlink(zp, uio);
4128	mutex_exit(&zp->z_lock);
4129
4130	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4131
4132	ZFS_EXIT(zfsvfs);
4133	return (error);
4134}
4135
4136/*
4137 * Insert a new entry into directory tdvp referencing svp.
4138 *
4139 *	IN:	tdvp	- Directory to contain new entry.
4140 *		svp	- vnode of new entry.
4141 *		name	- name of new entry.
4142 *		cr	- credentials of caller.
4143 *		ct	- caller context
4144 *
4145 *	RETURN:	0 if success
4146 *		error code if failure
4147 *
4148 * Timestamps:
4149 *	tdvp - ctime|mtime updated
4150 *	 svp - ctime updated
4151 */
4152/* ARGSUSED */
4153static int
4154zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
4155    caller_context_t *ct, int flags)
4156{
4157	znode_t		*dzp = VTOZ(tdvp);
4158	znode_t		*tzp, *szp;
4159	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
4160	zilog_t		*zilog;
4161	zfs_dirlock_t	*dl;
4162	dmu_tx_t	*tx;
4163	vnode_t		*realvp;
4164	int		error;
4165	int		zf = ZNEW;
4166	uint64_t	parent;
4167	uid_t		owner;
4168
4169	ASSERT(tdvp->v_type == VDIR);
4170
4171	ZFS_ENTER(zfsvfs);
4172	ZFS_VERIFY_ZP(dzp);
4173	zilog = zfsvfs->z_log;
4174
4175	if (VOP_REALVP(svp, &realvp, ct) == 0)
4176		svp = realvp;
4177
4178	/*
4179	 * POSIX dictates that we return EPERM here.
4180	 * Better choices include ENOTSUP or EISDIR.
4181	 */
4182	if (svp->v_type == VDIR) {
4183		ZFS_EXIT(zfsvfs);
4184		return (EPERM);
4185	}
4186
4187	if (svp->v_vfsp != tdvp->v_vfsp || zfsctl_is_node(svp)) {
4188		ZFS_EXIT(zfsvfs);
4189		return (EXDEV);
4190	}
4191
4192	szp = VTOZ(svp);
4193	ZFS_VERIFY_ZP(szp);
4194
4195	/* Prevent links to .zfs/shares files */
4196
4197	if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
4198	    &parent, sizeof (uint64_t))) != 0) {
4199		ZFS_EXIT(zfsvfs);
4200		return (error);
4201	}
4202	if (parent == zfsvfs->z_shares_dir) {
4203		ZFS_EXIT(zfsvfs);
4204		return (EPERM);
4205	}
4206
4207	if (zfsvfs->z_utf8 && u8_validate(name,
4208	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4209		ZFS_EXIT(zfsvfs);
4210		return (EILSEQ);
4211	}
4212	if (flags & FIGNORECASE)
4213		zf |= ZCILOOK;
4214
4215	/*
4216	 * We do not support links between attributes and non-attributes
4217	 * because of the potential security risk of creating links
4218	 * into "normal" file space in order to circumvent restrictions
4219	 * imposed in attribute space.
4220	 */
4221	if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
4222		ZFS_EXIT(zfsvfs);
4223		return (EINVAL);
4224	}
4225
4226
4227	owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
4228	if (owner != crgetuid(cr) && secpolicy_basic_link(svp, cr) != 0) {
4229		ZFS_EXIT(zfsvfs);
4230		return (EPERM);
4231	}
4232
4233	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4234		ZFS_EXIT(zfsvfs);
4235		return (error);
4236	}
4237
4238top:
4239	/*
4240	 * Attempt to lock directory; fail if entry already exists.
4241	 */
4242	error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
4243	if (error) {
4244		ZFS_EXIT(zfsvfs);
4245		return (error);
4246	}
4247
4248	tx = dmu_tx_create(zfsvfs->z_os);
4249	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
4250	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4251	zfs_sa_upgrade_txholds(tx, szp);
4252	zfs_sa_upgrade_txholds(tx, dzp);
4253	error = dmu_tx_assign(tx, TXG_NOWAIT);
4254	if (error) {
4255		zfs_dirent_unlock(dl);
4256		if (error == ERESTART) {
4257			dmu_tx_wait(tx);
4258			dmu_tx_abort(tx);
4259			goto top;
4260		}
4261		dmu_tx_abort(tx);
4262		ZFS_EXIT(zfsvfs);
4263		return (error);
4264	}
4265
4266	error = zfs_link_create(dl, szp, tx, 0);
4267
4268	if (error == 0) {
4269		uint64_t txtype = TX_LINK;
4270		if (flags & FIGNORECASE)
4271			txtype |= TX_CI;
4272		zfs_log_link(zilog, tx, txtype, dzp, szp, name);
4273	}
4274
4275	dmu_tx_commit(tx);
4276
4277	zfs_dirent_unlock(dl);
4278
4279	if (error == 0) {
4280		vnevent_link(svp, ct);
4281	}
4282
4283	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4284		zil_commit(zilog, 0);
4285
4286	ZFS_EXIT(zfsvfs);
4287	return (error);
4288}
4289
4290#ifdef sun
4291/*
4292 * zfs_null_putapage() is used when the file system has been force
4293 * unmounted. It just drops the pages.
4294 */
4295/* ARGSUSED */
4296static int
4297zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4298		size_t *lenp, int flags, cred_t *cr)
4299{
4300	pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
4301	return (0);
4302}
4303
4304/*
4305 * Push a page out to disk, klustering if possible.
4306 *
4307 *	IN:	vp	- file to push page to.
4308 *		pp	- page to push.
4309 *		flags	- additional flags.
4310 *		cr	- credentials of caller.
4311 *
4312 *	OUT:	offp	- start of range pushed.
4313 *		lenp	- len of range pushed.
4314 *
4315 *	RETURN:	0 if success
4316 *		error code if failure
4317 *
4318 * NOTE: callers must have locked the page to be pushed.  On
4319 * exit, the page (and all other pages in the kluster) must be
4320 * unlocked.
4321 */
4322/* ARGSUSED */
4323static int
4324zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4325		size_t *lenp, int flags, cred_t *cr)
4326{
4327	znode_t		*zp = VTOZ(vp);
4328	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4329	dmu_tx_t	*tx;
4330	u_offset_t	off, koff;
4331	size_t		len, klen;
4332	int		err;
4333
4334	off = pp->p_offset;
4335	len = PAGESIZE;
4336	/*
4337	 * If our blocksize is bigger than the page size, try to kluster
4338	 * multiple pages so that we write a full block (thus avoiding
4339	 * a read-modify-write).
4340	 */
4341	if (off < zp->z_size && zp->z_blksz > PAGESIZE) {
4342		klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
4343		koff = ISP2(klen) ? P2ALIGN(off, (u_offset_t)klen) : 0;
4344		ASSERT(koff <= zp->z_size);
4345		if (koff + klen > zp->z_size)
4346			klen = P2ROUNDUP(zp->z_size - koff, (uint64_t)PAGESIZE);
4347		pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
4348	}
4349	ASSERT3U(btop(len), ==, btopr(len));
4350
4351	/*
4352	 * Can't push pages past end-of-file.
4353	 */
4354	if (off >= zp->z_size) {
4355		/* ignore all pages */
4356		err = 0;
4357		goto out;
4358	} else if (off + len > zp->z_size) {
4359		int npages = btopr(zp->z_size - off);
4360		page_t *trunc;
4361
4362		page_list_break(&pp, &trunc, npages);
4363		/* ignore pages past end of file */
4364		if (trunc)
4365			pvn_write_done(trunc, flags);
4366		len = zp->z_size - off;
4367	}
4368
4369	if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
4370	    zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
4371		err = EDQUOT;
4372		goto out;
4373	}
4374top:
4375	tx = dmu_tx_create(zfsvfs->z_os);
4376	dmu_tx_hold_write(tx, zp->z_id, off, len);
4377
4378	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4379	zfs_sa_upgrade_txholds(tx, zp);
4380	err = dmu_tx_assign(tx, TXG_NOWAIT);
4381	if (err != 0) {
4382		if (err == ERESTART) {
4383			dmu_tx_wait(tx);
4384			dmu_tx_abort(tx);
4385			goto top;
4386		}
4387		dmu_tx_abort(tx);
4388		goto out;
4389	}
4390
4391	if (zp->z_blksz <= PAGESIZE) {
4392		caddr_t va = zfs_map_page(pp, S_READ);
4393		ASSERT3U(len, <=, PAGESIZE);
4394		dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
4395		zfs_unmap_page(pp, va);
4396	} else {
4397		err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
4398	}
4399
4400	if (err == 0) {
4401		uint64_t mtime[2], ctime[2];
4402		sa_bulk_attr_t bulk[3];
4403		int count = 0;
4404
4405		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4406		    &mtime, 16);
4407		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4408		    &ctime, 16);
4409		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4410		    &zp->z_pflags, 8);
4411		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
4412		    B_TRUE);
4413		zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len, 0);
4414	}
4415	dmu_tx_commit(tx);
4416
4417out:
4418	pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
4419	if (offp)
4420		*offp = off;
4421	if (lenp)
4422		*lenp = len;
4423
4424	return (err);
4425}
4426
4427/*
4428 * Copy the portion of the file indicated from pages into the file.
4429 * The pages are stored in a page list attached to the files vnode.
4430 *
4431 *	IN:	vp	- vnode of file to push page data to.
4432 *		off	- position in file to put data.
4433 *		len	- amount of data to write.
4434 *		flags	- flags to control the operation.
4435 *		cr	- credentials of caller.
4436 *		ct	- caller context.
4437 *
4438 *	RETURN:	0 if success
4439 *		error code if failure
4440 *
4441 * Timestamps:
4442 *	vp - ctime|mtime updated
4443 */
4444/*ARGSUSED*/
4445static int
4446zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
4447    caller_context_t *ct)
4448{
4449	znode_t		*zp = VTOZ(vp);
4450	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4451	page_t		*pp;
4452	size_t		io_len;
4453	u_offset_t	io_off;
4454	uint_t		blksz;
4455	rl_t		*rl;
4456	int		error = 0;
4457
4458	ZFS_ENTER(zfsvfs);
4459	ZFS_VERIFY_ZP(zp);
4460
4461	/*
4462	 * Align this request to the file block size in case we kluster.
4463	 * XXX - this can result in pretty aggresive locking, which can
4464	 * impact simultanious read/write access.  One option might be
4465	 * to break up long requests (len == 0) into block-by-block
4466	 * operations to get narrower locking.
4467	 */
4468	blksz = zp->z_blksz;
4469	if (ISP2(blksz))
4470		io_off = P2ALIGN_TYPED(off, blksz, u_offset_t);
4471	else
4472		io_off = 0;
4473	if (len > 0 && ISP2(blksz))
4474		io_len = P2ROUNDUP_TYPED(len + (off - io_off), blksz, size_t);
4475	else
4476		io_len = 0;
4477
4478	if (io_len == 0) {
4479		/*
4480		 * Search the entire vp list for pages >= io_off.
4481		 */
4482		rl = zfs_range_lock(zp, io_off, UINT64_MAX, RL_WRITER);
4483		error = pvn_vplist_dirty(vp, io_off, zfs_putapage, flags, cr);
4484		goto out;
4485	}
4486	rl = zfs_range_lock(zp, io_off, io_len, RL_WRITER);
4487
4488	if (off > zp->z_size) {
4489		/* past end of file */
4490		zfs_range_unlock(rl);
4491		ZFS_EXIT(zfsvfs);
4492		return (0);
4493	}
4494
4495	len = MIN(io_len, P2ROUNDUP(zp->z_size, PAGESIZE) - io_off);
4496
4497	for (off = io_off; io_off < off + len; io_off += io_len) {
4498		if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
4499			pp = page_lookup(vp, io_off,
4500			    (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
4501		} else {
4502			pp = page_lookup_nowait(vp, io_off,
4503			    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
4504		}
4505
4506		if (pp != NULL && pvn_getdirty(pp, flags)) {
4507			int err;
4508
4509			/*
4510			 * Found a dirty page to push
4511			 */
4512			err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
4513			if (err)
4514				error = err;
4515		} else {
4516			io_len = PAGESIZE;
4517		}
4518	}
4519out:
4520	zfs_range_unlock(rl);
4521	if ((flags & B_ASYNC) == 0 || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4522		zil_commit(zfsvfs->z_log, zp->z_id);
4523	ZFS_EXIT(zfsvfs);
4524	return (error);
4525}
4526#endif	/* sun */
4527
4528/*ARGSUSED*/
4529void
4530zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4531{
4532	znode_t	*zp = VTOZ(vp);
4533	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4534	int error;
4535
4536	rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4537	if (zp->z_sa_hdl == NULL) {
4538		/*
4539		 * The fs has been unmounted, or we did a
4540		 * suspend/resume and this file no longer exists.
4541		 */
4542		VI_LOCK(vp);
4543		ASSERT(vp->v_count <= 1);
4544		vp->v_count = 0;
4545		VI_UNLOCK(vp);
4546		vrecycle(vp, curthread);
4547		rw_exit(&zfsvfs->z_teardown_inactive_lock);
4548		return;
4549	}
4550
4551	if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4552		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4553
4554		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4555		zfs_sa_upgrade_txholds(tx, zp);
4556		error = dmu_tx_assign(tx, TXG_WAIT);
4557		if (error) {
4558			dmu_tx_abort(tx);
4559		} else {
4560			mutex_enter(&zp->z_lock);
4561			(void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4562			    (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4563			zp->z_atime_dirty = 0;
4564			mutex_exit(&zp->z_lock);
4565			dmu_tx_commit(tx);
4566		}
4567	}
4568
4569	zfs_zinactive(zp);
4570	rw_exit(&zfsvfs->z_teardown_inactive_lock);
4571}
4572
4573#ifdef sun
4574/*
4575 * Bounds-check the seek operation.
4576 *
4577 *	IN:	vp	- vnode seeking within
4578 *		ooff	- old file offset
4579 *		noffp	- pointer to new file offset
4580 *		ct	- caller context
4581 *
4582 *	RETURN:	0 if success
4583 *		EINVAL if new offset invalid
4584 */
4585/* ARGSUSED */
4586static int
4587zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp,
4588    caller_context_t *ct)
4589{
4590	if (vp->v_type == VDIR)
4591		return (0);
4592	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4593}
4594
4595/*
4596 * Pre-filter the generic locking function to trap attempts to place
4597 * a mandatory lock on a memory mapped file.
4598 */
4599static int
4600zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
4601    flk_callback_t *flk_cbp, cred_t *cr, caller_context_t *ct)
4602{
4603	znode_t *zp = VTOZ(vp);
4604	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4605
4606	ZFS_ENTER(zfsvfs);
4607	ZFS_VERIFY_ZP(zp);
4608
4609	/*
4610	 * We are following the UFS semantics with respect to mapcnt
4611	 * here: If we see that the file is mapped already, then we will
4612	 * return an error, but we don't worry about races between this
4613	 * function and zfs_map().
4614	 */
4615	if (zp->z_mapcnt > 0 && MANDMODE(zp->z_mode)) {
4616		ZFS_EXIT(zfsvfs);
4617		return (EAGAIN);
4618	}
4619	ZFS_EXIT(zfsvfs);
4620	return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4621}
4622
4623/*
4624 * If we can't find a page in the cache, we will create a new page
4625 * and fill it with file data.  For efficiency, we may try to fill
4626 * multiple pages at once (klustering) to fill up the supplied page
4627 * list.  Note that the pages to be filled are held with an exclusive
4628 * lock to prevent access by other threads while they are being filled.
4629 */
4630static int
4631zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
4632    caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
4633{
4634	znode_t *zp = VTOZ(vp);
4635	page_t *pp, *cur_pp;
4636	objset_t *os = zp->z_zfsvfs->z_os;
4637	u_offset_t io_off, total;
4638	size_t io_len;
4639	int err;
4640
4641	if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
4642		/*
4643		 * We only have a single page, don't bother klustering
4644		 */
4645		io_off = off;
4646		io_len = PAGESIZE;
4647		pp = page_create_va(vp, io_off, io_len,
4648		    PG_EXCL | PG_WAIT, seg, addr);
4649	} else {
4650		/*
4651		 * Try to find enough pages to fill the page list
4652		 */
4653		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4654		    &io_len, off, plsz, 0);
4655	}
4656	if (pp == NULL) {
4657		/*
4658		 * The page already exists, nothing to do here.
4659		 */
4660		*pl = NULL;
4661		return (0);
4662	}
4663
4664	/*
4665	 * Fill the pages in the kluster.
4666	 */
4667	cur_pp = pp;
4668	for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4669		caddr_t va;
4670
4671		ASSERT3U(io_off, ==, cur_pp->p_offset);
4672		va = zfs_map_page(cur_pp, S_WRITE);
4673		err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4674		    DMU_READ_PREFETCH);
4675		zfs_unmap_page(cur_pp, va);
4676		if (err) {
4677			/* On error, toss the entire kluster */
4678			pvn_read_done(pp, B_ERROR);
4679			/* convert checksum errors into IO errors */
4680			if (err == ECKSUM)
4681				err = EIO;
4682			return (err);
4683		}
4684		cur_pp = cur_pp->p_next;
4685	}
4686
4687	/*
4688	 * Fill in the page list array from the kluster starting
4689	 * from the desired offset `off'.
4690	 * NOTE: the page list will always be null terminated.
4691	 */
4692	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4693	ASSERT(pl == NULL || (*pl)->p_offset == off);
4694
4695	return (0);
4696}
4697
4698/*
4699 * Return pointers to the pages for the file region [off, off + len]
4700 * in the pl array.  If plsz is greater than len, this function may
4701 * also return page pointers from after the specified region
4702 * (i.e. the region [off, off + plsz]).  These additional pages are
4703 * only returned if they are already in the cache, or were created as
4704 * part of a klustered read.
4705 *
4706 *	IN:	vp	- vnode of file to get data from.
4707 *		off	- position in file to get data from.
4708 *		len	- amount of data to retrieve.
4709 *		plsz	- length of provided page list.
4710 *		seg	- segment to obtain pages for.
4711 *		addr	- virtual address of fault.
4712 *		rw	- mode of created pages.
4713 *		cr	- credentials of caller.
4714 *		ct	- caller context.
4715 *
4716 *	OUT:	protp	- protection mode of created pages.
4717 *		pl	- list of pages created.
4718 *
4719 *	RETURN:	0 if success
4720 *		error code if failure
4721 *
4722 * Timestamps:
4723 *	vp - atime updated
4724 */
4725/* ARGSUSED */
4726static int
4727zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
4728	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
4729	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
4730{
4731	znode_t		*zp = VTOZ(vp);
4732	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4733	page_t		**pl0 = pl;
4734	int		err = 0;
4735
4736	/* we do our own caching, faultahead is unnecessary */
4737	if (pl == NULL)
4738		return (0);
4739	else if (len > plsz)
4740		len = plsz;
4741	else
4742		len = P2ROUNDUP(len, PAGESIZE);
4743	ASSERT(plsz >= len);
4744
4745	ZFS_ENTER(zfsvfs);
4746	ZFS_VERIFY_ZP(zp);
4747
4748	if (protp)
4749		*protp = PROT_ALL;
4750
4751	/*
4752	 * Loop through the requested range [off, off + len) looking
4753	 * for pages.  If we don't find a page, we will need to create
4754	 * a new page and fill it with data from the file.
4755	 */
4756	while (len > 0) {
4757		if (*pl = page_lookup(vp, off, SE_SHARED))
4758			*(pl+1) = NULL;
4759		else if (err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw))
4760			goto out;
4761		while (*pl) {
4762			ASSERT3U((*pl)->p_offset, ==, off);
4763			off += PAGESIZE;
4764			addr += PAGESIZE;
4765			if (len > 0) {
4766				ASSERT3U(len, >=, PAGESIZE);
4767				len -= PAGESIZE;
4768			}
4769			ASSERT3U(plsz, >=, PAGESIZE);
4770			plsz -= PAGESIZE;
4771			pl++;
4772		}
4773	}
4774
4775	/*
4776	 * Fill out the page array with any pages already in the cache.
4777	 */
4778	while (plsz > 0 &&
4779	    (*pl++ = page_lookup_nowait(vp, off, SE_SHARED))) {
4780			off += PAGESIZE;
4781			plsz -= PAGESIZE;
4782	}
4783out:
4784	if (err) {
4785		/*
4786		 * Release any pages we have previously locked.
4787		 */
4788		while (pl > pl0)
4789			page_unlock(*--pl);
4790	} else {
4791		ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4792	}
4793
4794	*pl = NULL;
4795
4796	ZFS_EXIT(zfsvfs);
4797	return (err);
4798}
4799
4800/*
4801 * Request a memory map for a section of a file.  This code interacts
4802 * with common code and the VM system as follows:
4803 *
4804 *	common code calls mmap(), which ends up in smmap_common()
4805 *
4806 *	this calls VOP_MAP(), which takes you into (say) zfs
4807 *
4808 *	zfs_map() calls as_map(), passing segvn_create() as the callback
4809 *
4810 *	segvn_create() creates the new segment and calls VOP_ADDMAP()
4811 *
4812 *	zfs_addmap() updates z_mapcnt
4813 */
4814/*ARGSUSED*/
4815static int
4816zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
4817    size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4818    caller_context_t *ct)
4819{
4820	znode_t *zp = VTOZ(vp);
4821	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4822	segvn_crargs_t	vn_a;
4823	int		error;
4824
4825	ZFS_ENTER(zfsvfs);
4826	ZFS_VERIFY_ZP(zp);
4827
4828	if ((prot & PROT_WRITE) && (zp->z_pflags &
4829	    (ZFS_IMMUTABLE | ZFS_READONLY | ZFS_APPENDONLY))) {
4830		ZFS_EXIT(zfsvfs);
4831		return (EPERM);
4832	}
4833
4834	if ((prot & (PROT_READ | PROT_EXEC)) &&
4835	    (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4836		ZFS_EXIT(zfsvfs);
4837		return (EACCES);
4838	}
4839
4840	if (vp->v_flag & VNOMAP) {
4841		ZFS_EXIT(zfsvfs);
4842		return (ENOSYS);
4843	}
4844
4845	if (off < 0 || len > MAXOFFSET_T - off) {
4846		ZFS_EXIT(zfsvfs);
4847		return (ENXIO);
4848	}
4849
4850	if (vp->v_type != VREG) {
4851		ZFS_EXIT(zfsvfs);
4852		return (ENODEV);
4853	}
4854
4855	/*
4856	 * If file is locked, disallow mapping.
4857	 */
4858	if (MANDMODE(zp->z_mode) && vn_has_flocks(vp)) {
4859		ZFS_EXIT(zfsvfs);
4860		return (EAGAIN);
4861	}
4862
4863	as_rangelock(as);
4864	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
4865	if (error != 0) {
4866		as_rangeunlock(as);
4867		ZFS_EXIT(zfsvfs);
4868		return (error);
4869	}
4870
4871	vn_a.vp = vp;
4872	vn_a.offset = (u_offset_t)off;
4873	vn_a.type = flags & MAP_TYPE;
4874	vn_a.prot = prot;
4875	vn_a.maxprot = maxprot;
4876	vn_a.cred = cr;
4877	vn_a.amp = NULL;
4878	vn_a.flags = flags & ~MAP_TYPE;
4879	vn_a.szc = 0;
4880	vn_a.lgrp_mem_policy_flags = 0;
4881
4882	error = as_map(as, *addrp, len, segvn_create, &vn_a);
4883
4884	as_rangeunlock(as);
4885	ZFS_EXIT(zfsvfs);
4886	return (error);
4887}
4888
4889/* ARGSUSED */
4890static int
4891zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4892    size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4893    caller_context_t *ct)
4894{
4895	uint64_t pages = btopr(len);
4896
4897	atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
4898	return (0);
4899}
4900
4901/*
4902 * The reason we push dirty pages as part of zfs_delmap() is so that we get a
4903 * more accurate mtime for the associated file.  Since we don't have a way of
4904 * detecting when the data was actually modified, we have to resort to
4905 * heuristics.  If an explicit msync() is done, then we mark the mtime when the
4906 * last page is pushed.  The problem occurs when the msync() call is omitted,
4907 * which by far the most common case:
4908 *
4909 * 	open()
4910 * 	mmap()
4911 * 	<modify memory>
4912 * 	munmap()
4913 * 	close()
4914 * 	<time lapse>
4915 * 	putpage() via fsflush
4916 *
4917 * If we wait until fsflush to come along, we can have a modification time that
4918 * is some arbitrary point in the future.  In order to prevent this in the
4919 * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
4920 * torn down.
4921 */
4922/* ARGSUSED */
4923static int
4924zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4925    size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
4926    caller_context_t *ct)
4927{
4928	uint64_t pages = btopr(len);
4929
4930	ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
4931	atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
4932
4933	if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
4934	    vn_has_cached_data(vp))
4935		(void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
4936
4937	return (0);
4938}
4939
4940/*
4941 * Free or allocate space in a file.  Currently, this function only
4942 * supports the `F_FREESP' command.  However, this command is somewhat
4943 * misnamed, as its functionality includes the ability to allocate as
4944 * well as free space.
4945 *
4946 *	IN:	vp	- vnode of file to free data in.
4947 *		cmd	- action to take (only F_FREESP supported).
4948 *		bfp	- section of file to free/alloc.
4949 *		flag	- current file open mode flags.
4950 *		offset	- current file offset.
4951 *		cr	- credentials of caller [UNUSED].
4952 *		ct	- caller context.
4953 *
4954 *	RETURN:	0 if success
4955 *		error code if failure
4956 *
4957 * Timestamps:
4958 *	vp - ctime|mtime updated
4959 */
4960/* ARGSUSED */
4961static int
4962zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
4963    offset_t offset, cred_t *cr, caller_context_t *ct)
4964{
4965	znode_t		*zp = VTOZ(vp);
4966	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4967	uint64_t	off, len;
4968	int		error;
4969
4970	ZFS_ENTER(zfsvfs);
4971	ZFS_VERIFY_ZP(zp);
4972
4973	if (cmd != F_FREESP) {
4974		ZFS_EXIT(zfsvfs);
4975		return (EINVAL);
4976	}
4977
4978	if (error = convoff(vp, bfp, 0, offset)) {
4979		ZFS_EXIT(zfsvfs);
4980		return (error);
4981	}
4982
4983	if (bfp->l_len < 0) {
4984		ZFS_EXIT(zfsvfs);
4985		return (EINVAL);
4986	}
4987
4988	off = bfp->l_start;
4989	len = bfp->l_len; /* 0 means from off to end of file */
4990
4991	error = zfs_freesp(zp, off, len, flag, TRUE);
4992
4993	ZFS_EXIT(zfsvfs);
4994	return (error);
4995}
4996#endif	/* sun */
4997
4998CTASSERT(sizeof(struct zfid_short) <= sizeof(struct fid));
4999CTASSERT(sizeof(struct zfid_long) <= sizeof(struct fid));
5000
5001/*ARGSUSED*/
5002static int
5003zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
5004{
5005	znode_t		*zp = VTOZ(vp);
5006	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
5007	uint32_t	gen;
5008	uint64_t	gen64;
5009	uint64_t	object = zp->z_id;
5010	zfid_short_t	*zfid;
5011	int		size, i, error;
5012
5013	ZFS_ENTER(zfsvfs);
5014	ZFS_VERIFY_ZP(zp);
5015
5016	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
5017	    &gen64, sizeof (uint64_t))) != 0) {
5018		ZFS_EXIT(zfsvfs);
5019		return (error);
5020	}
5021
5022	gen = (uint32_t)gen64;
5023
5024	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
5025	fidp->fid_len = size;
5026
5027	zfid = (zfid_short_t *)fidp;
5028
5029	zfid->zf_len = size;
5030
5031	for (i = 0; i < sizeof (zfid->zf_object); i++)
5032		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
5033
5034	/* Must have a non-zero generation number to distinguish from .zfs */
5035	if (gen == 0)
5036		gen = 1;
5037	for (i = 0; i < sizeof (zfid->zf_gen); i++)
5038		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
5039
5040	if (size == LONG_FID_LEN) {
5041		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
5042		zfid_long_t	*zlfid;
5043
5044		zlfid = (zfid_long_t *)fidp;
5045
5046		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
5047			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
5048
5049		/* XXX - this should be the generation number for the objset */
5050		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
5051			zlfid->zf_setgen[i] = 0;
5052	}
5053
5054	ZFS_EXIT(zfsvfs);
5055	return (0);
5056}
5057
5058static int
5059zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
5060    caller_context_t *ct)
5061{
5062	znode_t		*zp, *xzp;
5063	zfsvfs_t	*zfsvfs;
5064	zfs_dirlock_t	*dl;
5065	int		error;
5066
5067	switch (cmd) {
5068	case _PC_LINK_MAX:
5069		*valp = INT_MAX;
5070		return (0);
5071
5072	case _PC_FILESIZEBITS:
5073		*valp = 64;
5074		return (0);
5075#ifdef sun
5076	case _PC_XATTR_EXISTS:
5077		zp = VTOZ(vp);
5078		zfsvfs = zp->z_zfsvfs;
5079		ZFS_ENTER(zfsvfs);
5080		ZFS_VERIFY_ZP(zp);
5081		*valp = 0;
5082		error = zfs_dirent_lock(&dl, zp, "", &xzp,
5083		    ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
5084		if (error == 0) {
5085			zfs_dirent_unlock(dl);
5086			if (!zfs_dirempty(xzp))
5087				*valp = 1;
5088			VN_RELE(ZTOV(xzp));
5089		} else if (error == ENOENT) {
5090			/*
5091			 * If there aren't extended attributes, it's the
5092			 * same as having zero of them.
5093			 */
5094			error = 0;
5095		}
5096		ZFS_EXIT(zfsvfs);
5097		return (error);
5098
5099	case _PC_SATTR_ENABLED:
5100	case _PC_SATTR_EXISTS:
5101		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
5102		    (vp->v_type == VREG || vp->v_type == VDIR);
5103		return (0);
5104
5105	case _PC_ACCESS_FILTERING:
5106		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_ACCESS_FILTER) &&
5107		    vp->v_type == VDIR;
5108		return (0);
5109
5110	case _PC_ACL_ENABLED:
5111		*valp = _ACL_ACE_ENABLED;
5112		return (0);
5113#endif	/* sun */
5114	case _PC_MIN_HOLE_SIZE:
5115		*valp = (int)SPA_MINBLOCKSIZE;
5116		return (0);
5117#ifdef sun
5118	case _PC_TIMESTAMP_RESOLUTION:
5119		/* nanosecond timestamp resolution */
5120		*valp = 1L;
5121		return (0);
5122#endif	/* sun */
5123	case _PC_ACL_EXTENDED:
5124		*valp = 0;
5125		return (0);
5126
5127	case _PC_ACL_NFS4:
5128		*valp = 1;
5129		return (0);
5130
5131	case _PC_ACL_PATH_MAX:
5132		*valp = ACL_MAX_ENTRIES;
5133		return (0);
5134
5135	default:
5136		return (EOPNOTSUPP);
5137	}
5138}
5139
5140/*ARGSUSED*/
5141static int
5142zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5143    caller_context_t *ct)
5144{
5145	znode_t *zp = VTOZ(vp);
5146	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5147	int error;
5148	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5149
5150	ZFS_ENTER(zfsvfs);
5151	ZFS_VERIFY_ZP(zp);
5152	error = zfs_getacl(zp, vsecp, skipaclchk, cr);
5153	ZFS_EXIT(zfsvfs);
5154
5155	return (error);
5156}
5157
5158/*ARGSUSED*/
5159static int
5160zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5161    caller_context_t *ct)
5162{
5163	znode_t *zp = VTOZ(vp);
5164	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5165	int error;
5166	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5167	zilog_t	*zilog = zfsvfs->z_log;
5168
5169	ZFS_ENTER(zfsvfs);
5170	ZFS_VERIFY_ZP(zp);
5171
5172	error = zfs_setacl(zp, vsecp, skipaclchk, cr);
5173
5174	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
5175		zil_commit(zilog, 0);
5176
5177	ZFS_EXIT(zfsvfs);
5178	return (error);
5179}
5180
5181#ifdef sun
5182/*
5183 * Tunable, both must be a power of 2.
5184 *
5185 * zcr_blksz_min: the smallest read we may consider to loan out an arcbuf
5186 * zcr_blksz_max: if set to less than the file block size, allow loaning out of
5187 *                an arcbuf for a partial block read
5188 */
5189int zcr_blksz_min = (1 << 10);	/* 1K */
5190int zcr_blksz_max = (1 << 17);	/* 128K */
5191
5192/*ARGSUSED*/
5193static int
5194zfs_reqzcbuf(vnode_t *vp, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr,
5195    caller_context_t *ct)
5196{
5197	znode_t	*zp = VTOZ(vp);
5198	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5199	int max_blksz = zfsvfs->z_max_blksz;
5200	uio_t *uio = &xuio->xu_uio;
5201	ssize_t size = uio->uio_resid;
5202	offset_t offset = uio->uio_loffset;
5203	int blksz;
5204	int fullblk, i;
5205	arc_buf_t *abuf;
5206	ssize_t maxsize;
5207	int preamble, postamble;
5208
5209	if (xuio->xu_type != UIOTYPE_ZEROCOPY)
5210		return (EINVAL);
5211
5212	ZFS_ENTER(zfsvfs);
5213	ZFS_VERIFY_ZP(zp);
5214	switch (ioflag) {
5215	case UIO_WRITE:
5216		/*
5217		 * Loan out an arc_buf for write if write size is bigger than
5218		 * max_blksz, and the file's block size is also max_blksz.
5219		 */
5220		blksz = max_blksz;
5221		if (size < blksz || zp->z_blksz != blksz) {
5222			ZFS_EXIT(zfsvfs);
5223			return (EINVAL);
5224		}
5225		/*
5226		 * Caller requests buffers for write before knowing where the
5227		 * write offset might be (e.g. NFS TCP write).
5228		 */
5229		if (offset == -1) {
5230			preamble = 0;
5231		} else {
5232			preamble = P2PHASE(offset, blksz);
5233			if (preamble) {
5234				preamble = blksz - preamble;
5235				size -= preamble;
5236			}
5237		}
5238
5239		postamble = P2PHASE(size, blksz);
5240		size -= postamble;
5241
5242		fullblk = size / blksz;
5243		(void) dmu_xuio_init(xuio,
5244		    (preamble != 0) + fullblk + (postamble != 0));
5245		DTRACE_PROBE3(zfs_reqzcbuf_align, int, preamble,
5246		    int, postamble, int,
5247		    (preamble != 0) + fullblk + (postamble != 0));
5248
5249		/*
5250		 * Have to fix iov base/len for partial buffers.  They
5251		 * currently represent full arc_buf's.
5252		 */
5253		if (preamble) {
5254			/* data begins in the middle of the arc_buf */
5255			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5256			    blksz);
5257			ASSERT(abuf);
5258			(void) dmu_xuio_add(xuio, abuf,
5259			    blksz - preamble, preamble);
5260		}
5261
5262		for (i = 0; i < fullblk; i++) {
5263			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5264			    blksz);
5265			ASSERT(abuf);
5266			(void) dmu_xuio_add(xuio, abuf, 0, blksz);
5267		}
5268
5269		if (postamble) {
5270			/* data ends in the middle of the arc_buf */
5271			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5272			    blksz);
5273			ASSERT(abuf);
5274			(void) dmu_xuio_add(xuio, abuf, 0, postamble);
5275		}
5276		break;
5277	case UIO_READ:
5278		/*
5279		 * Loan out an arc_buf for read if the read size is larger than
5280		 * the current file block size.  Block alignment is not
5281		 * considered.  Partial arc_buf will be loaned out for read.
5282		 */
5283		blksz = zp->z_blksz;
5284		if (blksz < zcr_blksz_min)
5285			blksz = zcr_blksz_min;
5286		if (blksz > zcr_blksz_max)
5287			blksz = zcr_blksz_max;
5288		/* avoid potential complexity of dealing with it */
5289		if (blksz > max_blksz) {
5290			ZFS_EXIT(zfsvfs);
5291			return (EINVAL);
5292		}
5293
5294		maxsize = zp->z_size - uio->uio_loffset;
5295		if (size > maxsize)
5296			size = maxsize;
5297
5298		if (size < blksz || vn_has_cached_data(vp)) {
5299			ZFS_EXIT(zfsvfs);
5300			return (EINVAL);
5301		}
5302		break;
5303	default:
5304		ZFS_EXIT(zfsvfs);
5305		return (EINVAL);
5306	}
5307
5308	uio->uio_extflg = UIO_XUIO;
5309	XUIO_XUZC_RW(xuio) = ioflag;
5310	ZFS_EXIT(zfsvfs);
5311	return (0);
5312}
5313
5314/*ARGSUSED*/
5315static int
5316zfs_retzcbuf(vnode_t *vp, xuio_t *xuio, cred_t *cr, caller_context_t *ct)
5317{
5318	int i;
5319	arc_buf_t *abuf;
5320	int ioflag = XUIO_XUZC_RW(xuio);
5321
5322	ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
5323
5324	i = dmu_xuio_cnt(xuio);
5325	while (i-- > 0) {
5326		abuf = dmu_xuio_arcbuf(xuio, i);
5327		/*
5328		 * if abuf == NULL, it must be a write buffer
5329		 * that has been returned in zfs_write().
5330		 */
5331		if (abuf)
5332			dmu_return_arcbuf(abuf);
5333		ASSERT(abuf || ioflag == UIO_WRITE);
5334	}
5335
5336	dmu_xuio_fini(xuio);
5337	return (0);
5338}
5339
5340/*
5341 * Predeclare these here so that the compiler assumes that
5342 * this is an "old style" function declaration that does
5343 * not include arguments => we won't get type mismatch errors
5344 * in the initializations that follow.
5345 */
5346static int zfs_inval();
5347static int zfs_isdir();
5348
5349static int
5350zfs_inval()
5351{
5352	return (EINVAL);
5353}
5354
5355static int
5356zfs_isdir()
5357{
5358	return (EISDIR);
5359}
5360/*
5361 * Directory vnode operations template
5362 */
5363vnodeops_t *zfs_dvnodeops;
5364const fs_operation_def_t zfs_dvnodeops_template[] = {
5365	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5366	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5367	VOPNAME_READ,		{ .error = zfs_isdir },
5368	VOPNAME_WRITE,		{ .error = zfs_isdir },
5369	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5370	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5371	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5372	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5373	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5374	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5375	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5376	VOPNAME_LINK,		{ .vop_link = zfs_link },
5377	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5378	VOPNAME_MKDIR,		{ .vop_mkdir = zfs_mkdir },
5379	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5380	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5381	VOPNAME_SYMLINK,	{ .vop_symlink = zfs_symlink },
5382	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5383	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5384	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5385	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5386	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5387	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5388	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5389	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
5390	NULL,			NULL
5391};
5392
5393/*
5394 * Regular file vnode operations template
5395 */
5396vnodeops_t *zfs_fvnodeops;
5397const fs_operation_def_t zfs_fvnodeops_template[] = {
5398	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5399	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5400	VOPNAME_READ,		{ .vop_read = zfs_read },
5401	VOPNAME_WRITE,		{ .vop_write = zfs_write },
5402	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5403	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5404	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5405	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5406	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5407	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5408	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5409	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5410	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5411	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5412	VOPNAME_FRLOCK,		{ .vop_frlock = zfs_frlock },
5413	VOPNAME_SPACE,		{ .vop_space = zfs_space },
5414	VOPNAME_GETPAGE,	{ .vop_getpage = zfs_getpage },
5415	VOPNAME_PUTPAGE,	{ .vop_putpage = zfs_putpage },
5416	VOPNAME_MAP,		{ .vop_map = zfs_map },
5417	VOPNAME_ADDMAP,		{ .vop_addmap = zfs_addmap },
5418	VOPNAME_DELMAP,		{ .vop_delmap = zfs_delmap },
5419	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5420	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5421	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5422	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5423	VOPNAME_REQZCBUF, 	{ .vop_reqzcbuf = zfs_reqzcbuf },
5424	VOPNAME_RETZCBUF, 	{ .vop_retzcbuf = zfs_retzcbuf },
5425	NULL,			NULL
5426};
5427
5428/*
5429 * Symbolic link vnode operations template
5430 */
5431vnodeops_t *zfs_symvnodeops;
5432const fs_operation_def_t zfs_symvnodeops_template[] = {
5433	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5434	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5435	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5436	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5437	VOPNAME_READLINK,	{ .vop_readlink = zfs_readlink },
5438	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5439	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5440	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5441	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5442	NULL,			NULL
5443};
5444
5445/*
5446 * special share hidden files vnode operations template
5447 */
5448vnodeops_t *zfs_sharevnodeops;
5449const fs_operation_def_t zfs_sharevnodeops_template[] = {
5450	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5451	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5452	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5453	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5454	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5455	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5456	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5457	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5458	NULL,			NULL
5459};
5460
5461/*
5462 * Extended attribute directory vnode operations template
5463 *	This template is identical to the directory vnodes
5464 *	operation template except for restricted operations:
5465 *		VOP_MKDIR()
5466 *		VOP_SYMLINK()
5467 * Note that there are other restrictions embedded in:
5468 *	zfs_create()	- restrict type to VREG
5469 *	zfs_link()	- no links into/out of attribute space
5470 *	zfs_rename()	- no moves into/out of attribute space
5471 */
5472vnodeops_t *zfs_xdvnodeops;
5473const fs_operation_def_t zfs_xdvnodeops_template[] = {
5474	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5475	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5476	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5477	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5478	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5479	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5480	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5481	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5482	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5483	VOPNAME_LINK,		{ .vop_link = zfs_link },
5484	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5485	VOPNAME_MKDIR,		{ .error = zfs_inval },
5486	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5487	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5488	VOPNAME_SYMLINK,	{ .error = zfs_inval },
5489	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5490	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5491	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5492	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5493	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5494	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5495	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5496	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5497	NULL,			NULL
5498};
5499
5500/*
5501 * Error vnode operations template
5502 */
5503vnodeops_t *zfs_evnodeops;
5504const fs_operation_def_t zfs_evnodeops_template[] = {
5505	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5506	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5507	NULL,			NULL
5508};
5509#endif	/* sun */
5510
5511static int
5512ioflags(int ioflags)
5513{
5514	int flags = 0;
5515
5516	if (ioflags & IO_APPEND)
5517		flags |= FAPPEND;
5518	if (ioflags & IO_NDELAY)
5519        	flags |= FNONBLOCK;
5520	if (ioflags & IO_SYNC)
5521		flags |= (FSYNC | FDSYNC | FRSYNC);
5522
5523	return (flags);
5524}
5525
5526static int
5527zfs_getpages(struct vnode *vp, vm_page_t *m, int count, int reqpage)
5528{
5529	znode_t *zp = VTOZ(vp);
5530	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5531	objset_t *os = zp->z_zfsvfs->z_os;
5532	vm_page_t mreq;
5533	vm_object_t object;
5534	caddr_t va;
5535	struct sf_buf *sf;
5536	int i, error;
5537	int pcount, size;
5538
5539	ZFS_ENTER(zfsvfs);
5540	ZFS_VERIFY_ZP(zp);
5541
5542	pcount = round_page(count) / PAGE_SIZE;
5543	mreq = m[reqpage];
5544	object = mreq->object;
5545	error = 0;
5546
5547	KASSERT(vp->v_object == object, ("mismatching object"));
5548
5549	VM_OBJECT_LOCK(object);
5550
5551	for (i = 0; i < pcount; i++) {
5552		if (i != reqpage) {
5553			vm_page_lock(m[i]);
5554			vm_page_free(m[i]);
5555			vm_page_unlock(m[i]);
5556		}
5557	}
5558
5559	if (mreq->valid) {
5560		if (mreq->valid != VM_PAGE_BITS_ALL)
5561			vm_page_zero_invalid(mreq, TRUE);
5562		VM_OBJECT_UNLOCK(object);
5563		ZFS_EXIT(zfsvfs);
5564		return (VM_PAGER_OK);
5565	}
5566
5567	PCPU_INC(cnt.v_vnodein);
5568	PCPU_INC(cnt.v_vnodepgsin);
5569
5570	if (IDX_TO_OFF(mreq->pindex) >= object->un_pager.vnp.vnp_size) {
5571		VM_OBJECT_UNLOCK(object);
5572		ZFS_EXIT(zfsvfs);
5573		return (VM_PAGER_BAD);
5574	}
5575
5576	size = PAGE_SIZE;
5577	if (IDX_TO_OFF(mreq->pindex) + size > object->un_pager.vnp.vnp_size)
5578		size = object->un_pager.vnp.vnp_size - IDX_TO_OFF(mreq->pindex);
5579
5580	VM_OBJECT_UNLOCK(object);
5581	va = zfs_map_page(mreq, &sf);
5582	error = dmu_read(os, zp->z_id, IDX_TO_OFF(mreq->pindex),
5583	    size, va, DMU_READ_PREFETCH);
5584	if (size != PAGE_SIZE)
5585		bzero(va + size, PAGE_SIZE - size);
5586	zfs_unmap_page(sf);
5587	VM_OBJECT_LOCK(object);
5588
5589	if (!error)
5590		mreq->valid = VM_PAGE_BITS_ALL;
5591	KASSERT(mreq->dirty == 0, ("zfs_getpages: page %p is dirty", mreq));
5592
5593	VM_OBJECT_UNLOCK(object);
5594
5595	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
5596	ZFS_EXIT(zfsvfs);
5597	return (error ? VM_PAGER_ERROR : VM_PAGER_OK);
5598}
5599
5600static int
5601zfs_freebsd_getpages(ap)
5602	struct vop_getpages_args /* {
5603		struct vnode *a_vp;
5604		vm_page_t *a_m;
5605		int a_count;
5606		int a_reqpage;
5607		vm_ooffset_t a_offset;
5608	} */ *ap;
5609{
5610
5611	return (zfs_getpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_reqpage));
5612}
5613
5614static int
5615zfs_freebsd_open(ap)
5616	struct vop_open_args /* {
5617		struct vnode *a_vp;
5618		int a_mode;
5619		struct ucred *a_cred;
5620		struct thread *a_td;
5621	} */ *ap;
5622{
5623	vnode_t	*vp = ap->a_vp;
5624	znode_t *zp = VTOZ(vp);
5625	int error;
5626
5627	error = zfs_open(&vp, ap->a_mode, ap->a_cred, NULL);
5628	if (error == 0)
5629		vnode_create_vobject(vp, zp->z_size, ap->a_td);
5630	return (error);
5631}
5632
5633static int
5634zfs_freebsd_close(ap)
5635	struct vop_close_args /* {
5636		struct vnode *a_vp;
5637		int  a_fflag;
5638		struct ucred *a_cred;
5639		struct thread *a_td;
5640	} */ *ap;
5641{
5642
5643	return (zfs_close(ap->a_vp, ap->a_fflag, 0, 0, ap->a_cred, NULL));
5644}
5645
5646static int
5647zfs_freebsd_ioctl(ap)
5648	struct vop_ioctl_args /* {
5649		struct vnode *a_vp;
5650		u_long a_command;
5651		caddr_t a_data;
5652		int a_fflag;
5653		struct ucred *cred;
5654		struct thread *td;
5655	} */ *ap;
5656{
5657
5658	return (zfs_ioctl(ap->a_vp, ap->a_command, (intptr_t)ap->a_data,
5659	    ap->a_fflag, ap->a_cred, NULL, NULL));
5660}
5661
5662static int
5663zfs_freebsd_read(ap)
5664	struct vop_read_args /* {
5665		struct vnode *a_vp;
5666		struct uio *a_uio;
5667		int a_ioflag;
5668		struct ucred *a_cred;
5669	} */ *ap;
5670{
5671
5672	return (zfs_read(ap->a_vp, ap->a_uio, ioflags(ap->a_ioflag),
5673	    ap->a_cred, NULL));
5674}
5675
5676static int
5677zfs_freebsd_write(ap)
5678	struct vop_write_args /* {
5679		struct vnode *a_vp;
5680		struct uio *a_uio;
5681		int a_ioflag;
5682		struct ucred *a_cred;
5683	} */ *ap;
5684{
5685
5686	if (vn_rlimit_fsize(ap->a_vp, ap->a_uio, ap->a_uio->uio_td))
5687		return (EFBIG);
5688
5689	return (zfs_write(ap->a_vp, ap->a_uio, ioflags(ap->a_ioflag),
5690	    ap->a_cred, NULL));
5691}
5692
5693static int
5694zfs_freebsd_access(ap)
5695	struct vop_access_args /* {
5696		struct vnode *a_vp;
5697		accmode_t a_accmode;
5698		struct ucred *a_cred;
5699		struct thread *a_td;
5700	} */ *ap;
5701{
5702	vnode_t *vp = ap->a_vp;
5703	znode_t *zp = VTOZ(vp);
5704	accmode_t accmode;
5705	int error = 0;
5706
5707	/*
5708	 * ZFS itself only knowns about VREAD, VWRITE, VEXEC and VAPPEND,
5709	 */
5710	accmode = ap->a_accmode & (VREAD|VWRITE|VEXEC|VAPPEND);
5711	if (accmode != 0)
5712		error = zfs_access(ap->a_vp, accmode, 0, ap->a_cred, NULL);
5713
5714	/*
5715	 * VADMIN has to be handled by vaccess().
5716	 */
5717	if (error == 0) {
5718		accmode = ap->a_accmode & ~(VREAD|VWRITE|VEXEC|VAPPEND);
5719		if (accmode != 0) {
5720			error = vaccess(vp->v_type, zp->z_mode, zp->z_uid,
5721			    zp->z_gid, accmode, ap->a_cred, NULL);
5722		}
5723	}
5724
5725	/*
5726	 * For VEXEC, ensure that at least one execute bit is set for
5727	 * non-directories.
5728	 */
5729	if (error == 0 && (ap->a_accmode & VEXEC) != 0 && vp->v_type != VDIR &&
5730	    (zp->z_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
5731		error = EACCES;
5732	}
5733
5734	return (error);
5735}
5736
5737static int
5738zfs_freebsd_lookup(ap)
5739	struct vop_lookup_args /* {
5740		struct vnode *a_dvp;
5741		struct vnode **a_vpp;
5742		struct componentname *a_cnp;
5743	} */ *ap;
5744{
5745	struct componentname *cnp = ap->a_cnp;
5746	char nm[NAME_MAX + 1];
5747
5748	ASSERT(cnp->cn_namelen < sizeof(nm));
5749	strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1, sizeof(nm)));
5750
5751	return (zfs_lookup(ap->a_dvp, nm, ap->a_vpp, cnp, cnp->cn_nameiop,
5752	    cnp->cn_cred, cnp->cn_thread, 0));
5753}
5754
5755static int
5756zfs_freebsd_create(ap)
5757	struct vop_create_args /* {
5758		struct vnode *a_dvp;
5759		struct vnode **a_vpp;
5760		struct componentname *a_cnp;
5761		struct vattr *a_vap;
5762	} */ *ap;
5763{
5764	struct componentname *cnp = ap->a_cnp;
5765	vattr_t *vap = ap->a_vap;
5766	int mode;
5767
5768	ASSERT(cnp->cn_flags & SAVENAME);
5769
5770	vattr_init_mask(vap);
5771	mode = vap->va_mode & ALLPERMS;
5772
5773	return (zfs_create(ap->a_dvp, cnp->cn_nameptr, vap, !EXCL, mode,
5774	    ap->a_vpp, cnp->cn_cred, cnp->cn_thread));
5775}
5776
5777static int
5778zfs_freebsd_remove(ap)
5779	struct vop_remove_args /* {
5780		struct vnode *a_dvp;
5781		struct vnode *a_vp;
5782		struct componentname *a_cnp;
5783	} */ *ap;
5784{
5785
5786	ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5787
5788	return (zfs_remove(ap->a_dvp, ap->a_cnp->cn_nameptr,
5789	    ap->a_cnp->cn_cred, NULL, 0));
5790}
5791
5792static int
5793zfs_freebsd_mkdir(ap)
5794	struct vop_mkdir_args /* {
5795		struct vnode *a_dvp;
5796		struct vnode **a_vpp;
5797		struct componentname *a_cnp;
5798		struct vattr *a_vap;
5799	} */ *ap;
5800{
5801	vattr_t *vap = ap->a_vap;
5802
5803	ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5804
5805	vattr_init_mask(vap);
5806
5807	return (zfs_mkdir(ap->a_dvp, ap->a_cnp->cn_nameptr, vap, ap->a_vpp,
5808	    ap->a_cnp->cn_cred, NULL, 0, NULL));
5809}
5810
5811static int
5812zfs_freebsd_rmdir(ap)
5813	struct vop_rmdir_args /* {
5814		struct vnode *a_dvp;
5815		struct vnode *a_vp;
5816		struct componentname *a_cnp;
5817	} */ *ap;
5818{
5819	struct componentname *cnp = ap->a_cnp;
5820
5821	ASSERT(cnp->cn_flags & SAVENAME);
5822
5823	return (zfs_rmdir(ap->a_dvp, cnp->cn_nameptr, NULL, cnp->cn_cred, NULL, 0));
5824}
5825
5826static int
5827zfs_freebsd_readdir(ap)
5828	struct vop_readdir_args /* {
5829		struct vnode *a_vp;
5830		struct uio *a_uio;
5831		struct ucred *a_cred;
5832		int *a_eofflag;
5833		int *a_ncookies;
5834		u_long **a_cookies;
5835	} */ *ap;
5836{
5837
5838	return (zfs_readdir(ap->a_vp, ap->a_uio, ap->a_cred, ap->a_eofflag,
5839	    ap->a_ncookies, ap->a_cookies));
5840}
5841
5842static int
5843zfs_freebsd_fsync(ap)
5844	struct vop_fsync_args /* {
5845		struct vnode *a_vp;
5846		int a_waitfor;
5847		struct thread *a_td;
5848	} */ *ap;
5849{
5850
5851	vop_stdfsync(ap);
5852	return (zfs_fsync(ap->a_vp, 0, ap->a_td->td_ucred, NULL));
5853}
5854
5855static int
5856zfs_freebsd_getattr(ap)
5857	struct vop_getattr_args /* {
5858		struct vnode *a_vp;
5859		struct vattr *a_vap;
5860		struct ucred *a_cred;
5861	} */ *ap;
5862{
5863	vattr_t *vap = ap->a_vap;
5864	xvattr_t xvap;
5865	u_long fflags = 0;
5866	int error;
5867
5868	xva_init(&xvap);
5869	xvap.xva_vattr = *vap;
5870	xvap.xva_vattr.va_mask |= AT_XVATTR;
5871
5872	/* Convert chflags into ZFS-type flags. */
5873	/* XXX: what about SF_SETTABLE?. */
5874	XVA_SET_REQ(&xvap, XAT_IMMUTABLE);
5875	XVA_SET_REQ(&xvap, XAT_APPENDONLY);
5876	XVA_SET_REQ(&xvap, XAT_NOUNLINK);
5877	XVA_SET_REQ(&xvap, XAT_NODUMP);
5878	error = zfs_getattr(ap->a_vp, (vattr_t *)&xvap, 0, ap->a_cred, NULL);
5879	if (error != 0)
5880		return (error);
5881
5882	/* Convert ZFS xattr into chflags. */
5883#define	FLAG_CHECK(fflag, xflag, xfield)	do {			\
5884	if (XVA_ISSET_RTN(&xvap, (xflag)) && (xfield) != 0)		\
5885		fflags |= (fflag);					\
5886} while (0)
5887	FLAG_CHECK(SF_IMMUTABLE, XAT_IMMUTABLE,
5888	    xvap.xva_xoptattrs.xoa_immutable);
5889	FLAG_CHECK(SF_APPEND, XAT_APPENDONLY,
5890	    xvap.xva_xoptattrs.xoa_appendonly);
5891	FLAG_CHECK(SF_NOUNLINK, XAT_NOUNLINK,
5892	    xvap.xva_xoptattrs.xoa_nounlink);
5893	FLAG_CHECK(UF_NODUMP, XAT_NODUMP,
5894	    xvap.xva_xoptattrs.xoa_nodump);
5895#undef	FLAG_CHECK
5896	*vap = xvap.xva_vattr;
5897	vap->va_flags = fflags;
5898	return (0);
5899}
5900
5901static int
5902zfs_freebsd_setattr(ap)
5903	struct vop_setattr_args /* {
5904		struct vnode *a_vp;
5905		struct vattr *a_vap;
5906		struct ucred *a_cred;
5907	} */ *ap;
5908{
5909	vnode_t *vp = ap->a_vp;
5910	vattr_t *vap = ap->a_vap;
5911	cred_t *cred = ap->a_cred;
5912	xvattr_t xvap;
5913	u_long fflags;
5914	uint64_t zflags;
5915
5916	vattr_init_mask(vap);
5917	vap->va_mask &= ~AT_NOSET;
5918
5919	xva_init(&xvap);
5920	xvap.xva_vattr = *vap;
5921
5922	zflags = VTOZ(vp)->z_pflags;
5923
5924	if (vap->va_flags != VNOVAL) {
5925		zfsvfs_t *zfsvfs = VTOZ(vp)->z_zfsvfs;
5926		int error;
5927
5928		if (zfsvfs->z_use_fuids == B_FALSE)
5929			return (EOPNOTSUPP);
5930
5931		fflags = vap->va_flags;
5932		if ((fflags & ~(SF_IMMUTABLE|SF_APPEND|SF_NOUNLINK|UF_NODUMP)) != 0)
5933			return (EOPNOTSUPP);
5934		/*
5935		 * Unprivileged processes are not permitted to unset system
5936		 * flags, or modify flags if any system flags are set.
5937		 * Privileged non-jail processes may not modify system flags
5938		 * if securelevel > 0 and any existing system flags are set.
5939		 * Privileged jail processes behave like privileged non-jail
5940		 * processes if the security.jail.chflags_allowed sysctl is
5941		 * is non-zero; otherwise, they behave like unprivileged
5942		 * processes.
5943		 */
5944		if (secpolicy_fs_owner(vp->v_mount, cred) == 0 ||
5945		    priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0) == 0) {
5946			if (zflags &
5947			    (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
5948				error = securelevel_gt(cred, 0);
5949				if (error != 0)
5950					return (error);
5951			}
5952		} else {
5953			/*
5954			 * Callers may only modify the file flags on objects they
5955			 * have VADMIN rights for.
5956			 */
5957			if ((error = VOP_ACCESS(vp, VADMIN, cred, curthread)) != 0)
5958				return (error);
5959			if (zflags &
5960			    (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
5961				return (EPERM);
5962			}
5963			if (fflags &
5964			    (SF_IMMUTABLE | SF_APPEND | SF_NOUNLINK)) {
5965				return (EPERM);
5966			}
5967		}
5968
5969#define	FLAG_CHANGE(fflag, zflag, xflag, xfield)	do {		\
5970	if (((fflags & (fflag)) && !(zflags & (zflag))) ||		\
5971	    ((zflags & (zflag)) && !(fflags & (fflag)))) {		\
5972		XVA_SET_REQ(&xvap, (xflag));				\
5973		(xfield) = ((fflags & (fflag)) != 0);			\
5974	}								\
5975} while (0)
5976		/* Convert chflags into ZFS-type flags. */
5977		/* XXX: what about SF_SETTABLE?. */
5978		FLAG_CHANGE(SF_IMMUTABLE, ZFS_IMMUTABLE, XAT_IMMUTABLE,
5979		    xvap.xva_xoptattrs.xoa_immutable);
5980		FLAG_CHANGE(SF_APPEND, ZFS_APPENDONLY, XAT_APPENDONLY,
5981		    xvap.xva_xoptattrs.xoa_appendonly);
5982		FLAG_CHANGE(SF_NOUNLINK, ZFS_NOUNLINK, XAT_NOUNLINK,
5983		    xvap.xva_xoptattrs.xoa_nounlink);
5984		FLAG_CHANGE(UF_NODUMP, ZFS_NODUMP, XAT_NODUMP,
5985		    xvap.xva_xoptattrs.xoa_nodump);
5986#undef	FLAG_CHANGE
5987	}
5988	return (zfs_setattr(vp, (vattr_t *)&xvap, 0, cred, NULL));
5989}
5990
5991static int
5992zfs_freebsd_rename(ap)
5993	struct vop_rename_args  /* {
5994		struct vnode *a_fdvp;
5995		struct vnode *a_fvp;
5996		struct componentname *a_fcnp;
5997		struct vnode *a_tdvp;
5998		struct vnode *a_tvp;
5999		struct componentname *a_tcnp;
6000	} */ *ap;
6001{
6002	vnode_t *fdvp = ap->a_fdvp;
6003	vnode_t *fvp = ap->a_fvp;
6004	vnode_t *tdvp = ap->a_tdvp;
6005	vnode_t *tvp = ap->a_tvp;
6006	int error;
6007
6008	ASSERT(ap->a_fcnp->cn_flags & (SAVENAME|SAVESTART));
6009	ASSERT(ap->a_tcnp->cn_flags & (SAVENAME|SAVESTART));
6010
6011	error = zfs_rename(fdvp, ap->a_fcnp->cn_nameptr, tdvp,
6012	    ap->a_tcnp->cn_nameptr, ap->a_fcnp->cn_cred, NULL, 0);
6013
6014	if (tdvp == tvp)
6015		VN_RELE(tdvp);
6016	else
6017		VN_URELE(tdvp);
6018	if (tvp)
6019		VN_URELE(tvp);
6020	VN_RELE(fdvp);
6021	VN_RELE(fvp);
6022
6023	return (error);
6024}
6025
6026static int
6027zfs_freebsd_symlink(ap)
6028	struct vop_symlink_args /* {
6029		struct vnode *a_dvp;
6030		struct vnode **a_vpp;
6031		struct componentname *a_cnp;
6032		struct vattr *a_vap;
6033		char *a_target;
6034	} */ *ap;
6035{
6036	struct componentname *cnp = ap->a_cnp;
6037	vattr_t *vap = ap->a_vap;
6038
6039	ASSERT(cnp->cn_flags & SAVENAME);
6040
6041	vap->va_type = VLNK;	/* FreeBSD: Syscall only sets va_mode. */
6042	vattr_init_mask(vap);
6043
6044	return (zfs_symlink(ap->a_dvp, ap->a_vpp, cnp->cn_nameptr, vap,
6045	    ap->a_target, cnp->cn_cred, cnp->cn_thread));
6046}
6047
6048static int
6049zfs_freebsd_readlink(ap)
6050	struct vop_readlink_args /* {
6051		struct vnode *a_vp;
6052		struct uio *a_uio;
6053		struct ucred *a_cred;
6054	} */ *ap;
6055{
6056
6057	return (zfs_readlink(ap->a_vp, ap->a_uio, ap->a_cred, NULL));
6058}
6059
6060static int
6061zfs_freebsd_link(ap)
6062	struct vop_link_args /* {
6063		struct vnode *a_tdvp;
6064		struct vnode *a_vp;
6065		struct componentname *a_cnp;
6066	} */ *ap;
6067{
6068	struct componentname *cnp = ap->a_cnp;
6069
6070	ASSERT(cnp->cn_flags & SAVENAME);
6071
6072	return (zfs_link(ap->a_tdvp, ap->a_vp, cnp->cn_nameptr, cnp->cn_cred, NULL, 0));
6073}
6074
6075static int
6076zfs_freebsd_inactive(ap)
6077	struct vop_inactive_args /* {
6078		struct vnode *a_vp;
6079		struct thread *a_td;
6080	} */ *ap;
6081{
6082	vnode_t *vp = ap->a_vp;
6083
6084	zfs_inactive(vp, ap->a_td->td_ucred, NULL);
6085	return (0);
6086}
6087
6088static void
6089zfs_reclaim_complete(void *arg, int pending)
6090{
6091	znode_t	*zp = arg;
6092	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
6093
6094	rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
6095	if (zp->z_sa_hdl != NULL) {
6096		ZFS_OBJ_HOLD_ENTER(zfsvfs, zp->z_id);
6097		zfs_znode_dmu_fini(zp);
6098		ZFS_OBJ_HOLD_EXIT(zfsvfs, zp->z_id);
6099	}
6100	zfs_znode_free(zp);
6101	rw_exit(&zfsvfs->z_teardown_inactive_lock);
6102	/*
6103	 * If the file system is being unmounted, there is a process waiting
6104	 * for us, wake it up.
6105	 */
6106	if (zfsvfs->z_unmounted)
6107		wakeup_one(zfsvfs);
6108}
6109
6110static int
6111zfs_freebsd_reclaim(ap)
6112	struct vop_reclaim_args /* {
6113		struct vnode *a_vp;
6114		struct thread *a_td;
6115	} */ *ap;
6116{
6117	vnode_t	*vp = ap->a_vp;
6118	znode_t	*zp = VTOZ(vp);
6119	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
6120	boolean_t rlocked;
6121
6122	rlocked = rw_tryenter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
6123
6124	ASSERT(zp != NULL);
6125
6126	/*
6127	 * Destroy the vm object and flush associated pages.
6128	 */
6129	vnode_destroy_vobject(vp);
6130
6131	mutex_enter(&zp->z_lock);
6132	zp->z_vnode = NULL;
6133	mutex_exit(&zp->z_lock);
6134
6135	if (zp->z_unlinked) {
6136		;	/* Do nothing. */
6137	} else if (!rlocked) {
6138		TASK_INIT(&zp->z_task, 0, zfs_reclaim_complete, zp);
6139		taskqueue_enqueue(taskqueue_thread, &zp->z_task);
6140	} else if (zp->z_sa_hdl == NULL) {
6141		zfs_znode_free(zp);
6142	} else /* if (!zp->z_unlinked && zp->z_dbuf != NULL) */ {
6143		int locked;
6144
6145		locked = MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)) ? 2 :
6146		    ZFS_OBJ_HOLD_TRYENTER(zfsvfs, zp->z_id);
6147		if (locked == 0) {
6148			/*
6149			 * Lock can't be obtained due to deadlock possibility,
6150			 * so defer znode destruction.
6151			 */
6152			TASK_INIT(&zp->z_task, 0, zfs_reclaim_complete, zp);
6153			taskqueue_enqueue(taskqueue_thread, &zp->z_task);
6154		} else {
6155			zfs_znode_dmu_fini(zp);
6156			if (locked == 1)
6157				ZFS_OBJ_HOLD_EXIT(zfsvfs, zp->z_id);
6158			zfs_znode_free(zp);
6159		}
6160	}
6161	VI_LOCK(vp);
6162	vp->v_data = NULL;
6163	ASSERT(vp->v_holdcnt >= 1);
6164	VI_UNLOCK(vp);
6165	if (rlocked)
6166		rw_exit(&zfsvfs->z_teardown_inactive_lock);
6167	return (0);
6168}
6169
6170static int
6171zfs_freebsd_fid(ap)
6172	struct vop_fid_args /* {
6173		struct vnode *a_vp;
6174		struct fid *a_fid;
6175	} */ *ap;
6176{
6177
6178	return (zfs_fid(ap->a_vp, (void *)ap->a_fid, NULL));
6179}
6180
6181static int
6182zfs_freebsd_pathconf(ap)
6183	struct vop_pathconf_args /* {
6184		struct vnode *a_vp;
6185		int a_name;
6186		register_t *a_retval;
6187	} */ *ap;
6188{
6189	ulong_t val;
6190	int error;
6191
6192	error = zfs_pathconf(ap->a_vp, ap->a_name, &val, curthread->td_ucred, NULL);
6193	if (error == 0)
6194		*ap->a_retval = val;
6195	else if (error == EOPNOTSUPP)
6196		error = vop_stdpathconf(ap);
6197	return (error);
6198}
6199
6200static int
6201zfs_freebsd_fifo_pathconf(ap)
6202	struct vop_pathconf_args /* {
6203		struct vnode *a_vp;
6204		int a_name;
6205		register_t *a_retval;
6206	} */ *ap;
6207{
6208
6209	switch (ap->a_name) {
6210	case _PC_ACL_EXTENDED:
6211	case _PC_ACL_NFS4:
6212	case _PC_ACL_PATH_MAX:
6213	case _PC_MAC_PRESENT:
6214		return (zfs_freebsd_pathconf(ap));
6215	default:
6216		return (fifo_specops.vop_pathconf(ap));
6217	}
6218}
6219
6220/*
6221 * FreeBSD's extended attributes namespace defines file name prefix for ZFS'
6222 * extended attribute name:
6223 *
6224 *	NAMESPACE	PREFIX
6225 *	system		freebsd:system:
6226 *	user		(none, can be used to access ZFS fsattr(5) attributes
6227 *			created on Solaris)
6228 */
6229static int
6230zfs_create_attrname(int attrnamespace, const char *name, char *attrname,
6231    size_t size)
6232{
6233	const char *namespace, *prefix, *suffix;
6234
6235	/* We don't allow '/' character in attribute name. */
6236	if (strchr(name, '/') != NULL)
6237		return (EINVAL);
6238	/* We don't allow attribute names that start with "freebsd:" string. */
6239	if (strncmp(name, "freebsd:", 8) == 0)
6240		return (EINVAL);
6241
6242	bzero(attrname, size);
6243
6244	switch (attrnamespace) {
6245	case EXTATTR_NAMESPACE_USER:
6246#if 0
6247		prefix = "freebsd:";
6248		namespace = EXTATTR_NAMESPACE_USER_STRING;
6249		suffix = ":";
6250#else
6251		/*
6252		 * This is the default namespace by which we can access all
6253		 * attributes created on Solaris.
6254		 */
6255		prefix = namespace = suffix = "";
6256#endif
6257		break;
6258	case EXTATTR_NAMESPACE_SYSTEM:
6259		prefix = "freebsd:";
6260		namespace = EXTATTR_NAMESPACE_SYSTEM_STRING;
6261		suffix = ":";
6262		break;
6263	case EXTATTR_NAMESPACE_EMPTY:
6264	default:
6265		return (EINVAL);
6266	}
6267	if (snprintf(attrname, size, "%s%s%s%s", prefix, namespace, suffix,
6268	    name) >= size) {
6269		return (ENAMETOOLONG);
6270	}
6271	return (0);
6272}
6273
6274/*
6275 * Vnode operating to retrieve a named extended attribute.
6276 */
6277static int
6278zfs_getextattr(struct vop_getextattr_args *ap)
6279/*
6280vop_getextattr {
6281	IN struct vnode *a_vp;
6282	IN int a_attrnamespace;
6283	IN const char *a_name;
6284	INOUT struct uio *a_uio;
6285	OUT size_t *a_size;
6286	IN struct ucred *a_cred;
6287	IN struct thread *a_td;
6288};
6289*/
6290{
6291	zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6292	struct thread *td = ap->a_td;
6293	struct nameidata nd;
6294	char attrname[255];
6295	struct vattr va;
6296	vnode_t *xvp = NULL, *vp;
6297	int error, flags;
6298
6299	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6300	    ap->a_cred, ap->a_td, VREAD);
6301	if (error != 0)
6302		return (error);
6303
6304	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6305	    sizeof(attrname));
6306	if (error != 0)
6307		return (error);
6308
6309	ZFS_ENTER(zfsvfs);
6310
6311	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6312	    LOOKUP_XATTR);
6313	if (error != 0) {
6314		ZFS_EXIT(zfsvfs);
6315		return (error);
6316	}
6317
6318	flags = FREAD;
6319	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, attrname,
6320	    xvp, td);
6321	error = vn_open_cred(&nd, &flags, 0, 0, ap->a_cred, NULL);
6322	vp = nd.ni_vp;
6323	NDFREE(&nd, NDF_ONLY_PNBUF);
6324	if (error != 0) {
6325		ZFS_EXIT(zfsvfs);
6326		if (error == ENOENT)
6327			error = ENOATTR;
6328		return (error);
6329	}
6330
6331	if (ap->a_size != NULL) {
6332		error = VOP_GETATTR(vp, &va, ap->a_cred);
6333		if (error == 0)
6334			*ap->a_size = (size_t)va.va_size;
6335	} else if (ap->a_uio != NULL)
6336		error = VOP_READ(vp, ap->a_uio, IO_UNIT | IO_SYNC, ap->a_cred);
6337
6338	VOP_UNLOCK(vp, 0);
6339	vn_close(vp, flags, ap->a_cred, td);
6340	ZFS_EXIT(zfsvfs);
6341
6342	return (error);
6343}
6344
6345/*
6346 * Vnode operation to remove a named attribute.
6347 */
6348int
6349zfs_deleteextattr(struct vop_deleteextattr_args *ap)
6350/*
6351vop_deleteextattr {
6352	IN struct vnode *a_vp;
6353	IN int a_attrnamespace;
6354	IN const char *a_name;
6355	IN struct ucred *a_cred;
6356	IN struct thread *a_td;
6357};
6358*/
6359{
6360	zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6361	struct thread *td = ap->a_td;
6362	struct nameidata nd;
6363	char attrname[255];
6364	struct vattr va;
6365	vnode_t *xvp = NULL, *vp;
6366	int error, flags;
6367
6368	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6369	    ap->a_cred, ap->a_td, VWRITE);
6370	if (error != 0)
6371		return (error);
6372
6373	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6374	    sizeof(attrname));
6375	if (error != 0)
6376		return (error);
6377
6378	ZFS_ENTER(zfsvfs);
6379
6380	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6381	    LOOKUP_XATTR);
6382	if (error != 0) {
6383		ZFS_EXIT(zfsvfs);
6384		return (error);
6385	}
6386
6387	NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF | MPSAFE,
6388	    UIO_SYSSPACE, attrname, xvp, td);
6389	error = namei(&nd);
6390	vp = nd.ni_vp;
6391	NDFREE(&nd, NDF_ONLY_PNBUF);
6392	if (error != 0) {
6393		ZFS_EXIT(zfsvfs);
6394		if (error == ENOENT)
6395			error = ENOATTR;
6396		return (error);
6397	}
6398	error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
6399
6400	vput(nd.ni_dvp);
6401	if (vp == nd.ni_dvp)
6402		vrele(vp);
6403	else
6404		vput(vp);
6405	ZFS_EXIT(zfsvfs);
6406
6407	return (error);
6408}
6409
6410/*
6411 * Vnode operation to set a named attribute.
6412 */
6413static int
6414zfs_setextattr(struct vop_setextattr_args *ap)
6415/*
6416vop_setextattr {
6417	IN struct vnode *a_vp;
6418	IN int a_attrnamespace;
6419	IN const char *a_name;
6420	INOUT struct uio *a_uio;
6421	IN struct ucred *a_cred;
6422	IN struct thread *a_td;
6423};
6424*/
6425{
6426	zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6427	struct thread *td = ap->a_td;
6428	struct nameidata nd;
6429	char attrname[255];
6430	struct vattr va;
6431	vnode_t *xvp = NULL, *vp;
6432	int error, flags;
6433
6434	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6435	    ap->a_cred, ap->a_td, VWRITE);
6436	if (error != 0)
6437		return (error);
6438
6439	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6440	    sizeof(attrname));
6441	if (error != 0)
6442		return (error);
6443
6444	ZFS_ENTER(zfsvfs);
6445
6446	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6447	    LOOKUP_XATTR | CREATE_XATTR_DIR);
6448	if (error != 0) {
6449		ZFS_EXIT(zfsvfs);
6450		return (error);
6451	}
6452
6453	flags = FFLAGS(O_WRONLY | O_CREAT);
6454	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, attrname,
6455	    xvp, td);
6456	error = vn_open_cred(&nd, &flags, 0600, 0, ap->a_cred, NULL);
6457	vp = nd.ni_vp;
6458	NDFREE(&nd, NDF_ONLY_PNBUF);
6459	if (error != 0) {
6460		ZFS_EXIT(zfsvfs);
6461		return (error);
6462	}
6463
6464	VATTR_NULL(&va);
6465	va.va_size = 0;
6466	error = VOP_SETATTR(vp, &va, ap->a_cred);
6467	if (error == 0)
6468		VOP_WRITE(vp, ap->a_uio, IO_UNIT | IO_SYNC, ap->a_cred);
6469
6470	VOP_UNLOCK(vp, 0);
6471	vn_close(vp, flags, ap->a_cred, td);
6472	ZFS_EXIT(zfsvfs);
6473
6474	return (error);
6475}
6476
6477/*
6478 * Vnode operation to retrieve extended attributes on a vnode.
6479 */
6480static int
6481zfs_listextattr(struct vop_listextattr_args *ap)
6482/*
6483vop_listextattr {
6484	IN struct vnode *a_vp;
6485	IN int a_attrnamespace;
6486	INOUT struct uio *a_uio;
6487	OUT size_t *a_size;
6488	IN struct ucred *a_cred;
6489	IN struct thread *a_td;
6490};
6491*/
6492{
6493	zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6494	struct thread *td = ap->a_td;
6495	struct nameidata nd;
6496	char attrprefix[16];
6497	u_char dirbuf[sizeof(struct dirent)];
6498	struct dirent *dp;
6499	struct iovec aiov;
6500	struct uio auio, *uio = ap->a_uio;
6501	size_t *sizep = ap->a_size;
6502	size_t plen;
6503	vnode_t *xvp = NULL, *vp;
6504	int done, error, eof, pos;
6505
6506	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6507	    ap->a_cred, ap->a_td, VREAD);
6508	if (error != 0)
6509		return (error);
6510
6511	error = zfs_create_attrname(ap->a_attrnamespace, "", attrprefix,
6512	    sizeof(attrprefix));
6513	if (error != 0)
6514		return (error);
6515	plen = strlen(attrprefix);
6516
6517	ZFS_ENTER(zfsvfs);
6518
6519	if (sizep != NULL)
6520		*sizep = 0;
6521
6522	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6523	    LOOKUP_XATTR);
6524	if (error != 0) {
6525		ZFS_EXIT(zfsvfs);
6526		/*
6527		 * ENOATTR means that the EA directory does not yet exist,
6528		 * i.e. there are no extended attributes there.
6529		 */
6530		if (error == ENOATTR)
6531			error = 0;
6532		return (error);
6533	}
6534
6535	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED | MPSAFE,
6536	    UIO_SYSSPACE, ".", xvp, td);
6537	error = namei(&nd);
6538	vp = nd.ni_vp;
6539	NDFREE(&nd, NDF_ONLY_PNBUF);
6540	if (error != 0) {
6541		ZFS_EXIT(zfsvfs);
6542		return (error);
6543	}
6544
6545	auio.uio_iov = &aiov;
6546	auio.uio_iovcnt = 1;
6547	auio.uio_segflg = UIO_SYSSPACE;
6548	auio.uio_td = td;
6549	auio.uio_rw = UIO_READ;
6550	auio.uio_offset = 0;
6551
6552	do {
6553		u_char nlen;
6554
6555		aiov.iov_base = (void *)dirbuf;
6556		aiov.iov_len = sizeof(dirbuf);
6557		auio.uio_resid = sizeof(dirbuf);
6558		error = VOP_READDIR(vp, &auio, ap->a_cred, &eof, NULL, NULL);
6559		done = sizeof(dirbuf) - auio.uio_resid;
6560		if (error != 0)
6561			break;
6562		for (pos = 0; pos < done;) {
6563			dp = (struct dirent *)(dirbuf + pos);
6564			pos += dp->d_reclen;
6565			/*
6566			 * XXX: Temporarily we also accept DT_UNKNOWN, as this
6567			 * is what we get when attribute was created on Solaris.
6568			 */
6569			if (dp->d_type != DT_REG && dp->d_type != DT_UNKNOWN)
6570				continue;
6571			if (plen == 0 && strncmp(dp->d_name, "freebsd:", 8) == 0)
6572				continue;
6573			else if (strncmp(dp->d_name, attrprefix, plen) != 0)
6574				continue;
6575			nlen = dp->d_namlen - plen;
6576			if (sizep != NULL)
6577				*sizep += 1 + nlen;
6578			else if (uio != NULL) {
6579				/*
6580				 * Format of extattr name entry is one byte for
6581				 * length and the rest for name.
6582				 */
6583				error = uiomove(&nlen, 1, uio->uio_rw, uio);
6584				if (error == 0) {
6585					error = uiomove(dp->d_name + plen, nlen,
6586					    uio->uio_rw, uio);
6587				}
6588				if (error != 0)
6589					break;
6590			}
6591		}
6592	} while (!eof && error == 0);
6593
6594	vput(vp);
6595	ZFS_EXIT(zfsvfs);
6596
6597	return (error);
6598}
6599
6600int
6601zfs_freebsd_getacl(ap)
6602	struct vop_getacl_args /* {
6603		struct vnode *vp;
6604		acl_type_t type;
6605		struct acl *aclp;
6606		struct ucred *cred;
6607		struct thread *td;
6608	} */ *ap;
6609{
6610	int		error;
6611	vsecattr_t      vsecattr;
6612
6613	if (ap->a_type != ACL_TYPE_NFS4)
6614		return (EINVAL);
6615
6616	vsecattr.vsa_mask = VSA_ACE | VSA_ACECNT;
6617	if (error = zfs_getsecattr(ap->a_vp, &vsecattr, 0, ap->a_cred, NULL))
6618		return (error);
6619
6620	error = acl_from_aces(ap->a_aclp, vsecattr.vsa_aclentp, vsecattr.vsa_aclcnt);
6621	if (vsecattr.vsa_aclentp != NULL)
6622		kmem_free(vsecattr.vsa_aclentp, vsecattr.vsa_aclentsz);
6623
6624	return (error);
6625}
6626
6627int
6628zfs_freebsd_setacl(ap)
6629	struct vop_setacl_args /* {
6630		struct vnode *vp;
6631		acl_type_t type;
6632		struct acl *aclp;
6633		struct ucred *cred;
6634		struct thread *td;
6635	} */ *ap;
6636{
6637	int		error;
6638	vsecattr_t      vsecattr;
6639	int		aclbsize;	/* size of acl list in bytes */
6640	aclent_t	*aaclp;
6641
6642	if (ap->a_type != ACL_TYPE_NFS4)
6643		return (EINVAL);
6644
6645	if (ap->a_aclp->acl_cnt < 1 || ap->a_aclp->acl_cnt > MAX_ACL_ENTRIES)
6646		return (EINVAL);
6647
6648	/*
6649	 * With NFSv4 ACLs, chmod(2) may need to add additional entries,
6650	 * splitting every entry into two and appending "canonical six"
6651	 * entries at the end.  Don't allow for setting an ACL that would
6652	 * cause chmod(2) to run out of ACL entries.
6653	 */
6654	if (ap->a_aclp->acl_cnt * 2 + 6 > ACL_MAX_ENTRIES)
6655		return (ENOSPC);
6656
6657	error = acl_nfs4_check(ap->a_aclp, ap->a_vp->v_type == VDIR);
6658	if (error != 0)
6659		return (error);
6660
6661	vsecattr.vsa_mask = VSA_ACE;
6662	aclbsize = ap->a_aclp->acl_cnt * sizeof(ace_t);
6663	vsecattr.vsa_aclentp = kmem_alloc(aclbsize, KM_SLEEP);
6664	aaclp = vsecattr.vsa_aclentp;
6665	vsecattr.vsa_aclentsz = aclbsize;
6666
6667	aces_from_acl(vsecattr.vsa_aclentp, &vsecattr.vsa_aclcnt, ap->a_aclp);
6668	error = zfs_setsecattr(ap->a_vp, &vsecattr, 0, ap->a_cred, NULL);
6669	kmem_free(aaclp, aclbsize);
6670
6671	return (error);
6672}
6673
6674int
6675zfs_freebsd_aclcheck(ap)
6676	struct vop_aclcheck_args /* {
6677		struct vnode *vp;
6678		acl_type_t type;
6679		struct acl *aclp;
6680		struct ucred *cred;
6681		struct thread *td;
6682	} */ *ap;
6683{
6684
6685	return (EOPNOTSUPP);
6686}
6687
6688struct vop_vector zfs_vnodeops;
6689struct vop_vector zfs_fifoops;
6690struct vop_vector zfs_shareops;
6691
6692struct vop_vector zfs_vnodeops = {
6693	.vop_default =		&default_vnodeops,
6694	.vop_inactive =		zfs_freebsd_inactive,
6695	.vop_reclaim =		zfs_freebsd_reclaim,
6696	.vop_access =		zfs_freebsd_access,
6697#ifdef FREEBSD_NAMECACHE
6698	.vop_lookup =		vfs_cache_lookup,
6699	.vop_cachedlookup =	zfs_freebsd_lookup,
6700#else
6701	.vop_lookup =		zfs_freebsd_lookup,
6702#endif
6703	.vop_getattr =		zfs_freebsd_getattr,
6704	.vop_setattr =		zfs_freebsd_setattr,
6705	.vop_create =		zfs_freebsd_create,
6706	.vop_mknod =		zfs_freebsd_create,
6707	.vop_mkdir =		zfs_freebsd_mkdir,
6708	.vop_readdir =		zfs_freebsd_readdir,
6709	.vop_fsync =		zfs_freebsd_fsync,
6710	.vop_open =		zfs_freebsd_open,
6711	.vop_close =		zfs_freebsd_close,
6712	.vop_rmdir =		zfs_freebsd_rmdir,
6713	.vop_ioctl =		zfs_freebsd_ioctl,
6714	.vop_link =		zfs_freebsd_link,
6715	.vop_symlink =		zfs_freebsd_symlink,
6716	.vop_readlink =		zfs_freebsd_readlink,
6717	.vop_read =		zfs_freebsd_read,
6718	.vop_write =		zfs_freebsd_write,
6719	.vop_remove =		zfs_freebsd_remove,
6720	.vop_rename =		zfs_freebsd_rename,
6721	.vop_pathconf =		zfs_freebsd_pathconf,
6722	.vop_bmap =		VOP_EOPNOTSUPP,
6723	.vop_fid =		zfs_freebsd_fid,
6724	.vop_getextattr =	zfs_getextattr,
6725	.vop_deleteextattr =	zfs_deleteextattr,
6726	.vop_setextattr =	zfs_setextattr,
6727	.vop_listextattr =	zfs_listextattr,
6728	.vop_getacl =		zfs_freebsd_getacl,
6729	.vop_setacl =		zfs_freebsd_setacl,
6730	.vop_aclcheck =		zfs_freebsd_aclcheck,
6731	.vop_getpages =		zfs_freebsd_getpages,
6732};
6733
6734struct vop_vector zfs_fifoops = {
6735	.vop_default =		&fifo_specops,
6736	.vop_fsync =		zfs_freebsd_fsync,
6737	.vop_access =		zfs_freebsd_access,
6738	.vop_getattr =		zfs_freebsd_getattr,
6739	.vop_inactive =		zfs_freebsd_inactive,
6740	.vop_read =		VOP_PANIC,
6741	.vop_reclaim =		zfs_freebsd_reclaim,
6742	.vop_setattr =		zfs_freebsd_setattr,
6743	.vop_write =		VOP_PANIC,
6744	.vop_pathconf = 	zfs_freebsd_fifo_pathconf,
6745	.vop_fid =		zfs_freebsd_fid,
6746	.vop_getacl =		zfs_freebsd_getacl,
6747	.vop_setacl =		zfs_freebsd_setacl,
6748	.vop_aclcheck =		zfs_freebsd_aclcheck,
6749};
6750
6751/*
6752 * special share hidden files vnode operations template
6753 */
6754struct vop_vector zfs_shareops = {
6755	.vop_default =		&default_vnodeops,
6756	.vop_access =		zfs_freebsd_access,
6757	.vop_inactive =		zfs_freebsd_inactive,
6758	.vop_reclaim =		zfs_freebsd_reclaim,
6759	.vop_fid =		zfs_freebsd_fid,
6760	.vop_pathconf =		zfs_freebsd_pathconf,
6761};
6762