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