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