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