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