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