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