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