xref: /titanic_41/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision 9de0276978bc95c4f522fcb65f3f22e89f153b40)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2013, 2014 by Delphix. All rights reserved.
24  * Copyright 2014 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/vfs_opreg.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/vmsystm.h>
45 #include <sys/atomic.h>
46 #include <sys/vm.h>
47 #include <vm/seg_vn.h>
48 #include <vm/pvn.h>
49 #include <vm/as.h>
50 #include <vm/kpm.h>
51 #include <vm/seg_kpm.h>
52 #include <sys/mman.h>
53 #include <sys/pathname.h>
54 #include <sys/cmn_err.h>
55 #include <sys/errno.h>
56 #include <sys/unistd.h>
57 #include <sys/zfs_dir.h>
58 #include <sys/zfs_acl.h>
59 #include <sys/zfs_ioctl.h>
60 #include <sys/fs/zfs.h>
61 #include <sys/dmu.h>
62 #include <sys/dmu_objset.h>
63 #include <sys/spa.h>
64 #include <sys/txg.h>
65 #include <sys/dbuf.h>
66 #include <sys/zap.h>
67 #include <sys/sa.h>
68 #include <sys/dirent.h>
69 #include <sys/policy.h>
70 #include <sys/sunddi.h>
71 #include <sys/filio.h>
72 #include <sys/sid.h>
73 #include "fs/fs_subr.h"
74 #include <sys/zfs_ctldir.h>
75 #include <sys/zfs_fuid.h>
76 #include <sys/zfs_sa.h>
77 #include <sys/dnlc.h>
78 #include <sys/zfs_rlock.h>
79 #include <sys/extdirent.h>
80 #include <sys/kidmap.h>
81 #include <sys/cred.h>
82 #include <sys/attr.h>
83 #include <sys/zfs_events.h>
84 #include <sys/fs/zev.h>
85 
86 /*
87  * Programming rules.
88  *
89  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
90  * properly lock its in-core state, create a DMU transaction, do the work,
91  * record this work in the intent log (ZIL), commit the DMU transaction,
92  * and wait for the intent log to commit if it is a synchronous operation.
93  * Moreover, the vnode ops must work in both normal and log replay context.
94  * The ordering of events is important to avoid deadlocks and references
95  * to freed memory.  The example below illustrates the following Big Rules:
96  *
97  *  (1)	A check must be made in each zfs thread for a mounted file system.
98  *	This is done avoiding races using ZFS_ENTER(zfsvfs).
99  *	A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
100  *	must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
101  *	can return EIO from the calling function.
102  *
103  *  (2)	VN_RELE() should always be the last thing except for zil_commit()
104  *	(if necessary) and ZFS_EXIT(). This is for 3 reasons:
105  *	First, if it's the last reference, the vnode/znode
106  *	can be freed, so the zp may point to freed memory.  Second, the last
107  *	reference will call zfs_zinactive(), which may induce a lot of work --
108  *	pushing cached pages (which acquires range locks) and syncing out
109  *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
110  *	which could deadlock the system if you were already holding one.
111  *	If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
112  *
113  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
114  *	as they can span dmu_tx_assign() calls.
115  *
116  *  (4) If ZPL locks are held, pass TXG_NOWAIT as the second argument to
117  *      dmu_tx_assign().  This is critical because we don't want to block
118  *      while holding locks.
119  *
120  *	If no ZPL locks are held (aside from ZFS_ENTER()), use TXG_WAIT.  This
121  *	reduces lock contention and CPU usage when we must wait (note that if
122  *	throughput is constrained by the storage, nearly every transaction
123  *	must wait).
124  *
125  *      Note, in particular, that if a lock is sometimes acquired before
126  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
127  *      to use a non-blocking assign can deadlock the system.  The scenario:
128  *
129  *	Thread A has grabbed a lock before calling dmu_tx_assign().
130  *	Thread B is in an already-assigned tx, and blocks for this lock.
131  *	Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
132  *	forever, because the previous txg can't quiesce until B's tx commits.
133  *
134  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
135  *	then drop all locks, call dmu_tx_wait(), and try again.  On subsequent
136  *	calls to dmu_tx_assign(), pass TXG_WAITED rather than TXG_NOWAIT,
137  *	to indicate that this operation has already called dmu_tx_wait().
138  *	This will ensure that we don't retry forever, waiting a short bit
139  *	each time.
140  *
141  *  (5)	If the operation succeeded, generate the intent log entry for it
142  *	before dropping locks.  This ensures that the ordering of events
143  *	in the intent log matches the order in which they actually occurred.
144  *	During ZIL replay the zfs_log_* functions will update the sequence
145  *	number to indicate the zil transaction has replayed.
146  *
147  *  (6)	At the end of each vnode op, the DMU tx must always commit,
148  *	regardless of whether there were any errors.
149  *
150  *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
151  *	to ensure that synchronous semantics are provided when necessary.
152  *
153  * In general, this is how things should be ordered in each vnode op:
154  *
155  *	ZFS_ENTER(zfsvfs);		// exit if unmounted
156  * top:
157  *	zfs_dirent_lock(&dl, ...)	// lock directory entry (may VN_HOLD())
158  *	rw_enter(...);			// grab any other locks you need
159  *	tx = dmu_tx_create(...);	// get DMU tx
160  *	dmu_tx_hold_*();		// hold each object you might modify
161  *	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
162  *	if (error) {
163  *		rw_exit(...);		// drop locks
164  *		zfs_dirent_unlock(dl);	// unlock directory entry
165  *		VN_RELE(...);		// release held vnodes
166  *		if (error == ERESTART) {
167  *			waited = B_TRUE;
168  *			dmu_tx_wait(tx);
169  *			dmu_tx_abort(tx);
170  *			goto top;
171  *		}
172  *		dmu_tx_abort(tx);	// abort DMU tx
173  *		ZFS_EXIT(zfsvfs);	// finished in zfs
174  *		return (error);		// really out of space
175  *	}
176  *	error = do_real_work();		// do whatever this VOP does
177  *	if (error == 0)
178  *		zfs_log_*(...);		// on success, make ZIL entry
179  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
180  *	rw_exit(...);			// drop locks
181  *	zfs_dirent_unlock(dl);		// unlock directory entry
182  *	VN_RELE(...);			// release held vnodes
183  *	zil_commit(zilog, foid);	// synchronous when necessary
184  *	ZFS_EXIT(zfsvfs);		// finished in zfs
185  *	return (error);			// done, report error
186  */
187 
188 /* ARGSUSED */
189 static int
190 zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
191 {
192 	znode_t	*zp = VTOZ(*vpp);
193 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
194 
195 	ZFS_ENTER(zfsvfs);
196 	ZFS_VERIFY_ZP(zp);
197 
198 	if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
199 	    ((flag & FAPPEND) == 0)) {
200 		ZFS_EXIT(zfsvfs);
201 		return (SET_ERROR(EPERM));
202 	}
203 
204 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
205 	    ZTOV(zp)->v_type == VREG &&
206 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
207 		if (fs_vscan(*vpp, cr, 0) != 0) {
208 			ZFS_EXIT(zfsvfs);
209 			return (SET_ERROR(EACCES));
210 		}
211 	}
212 
213 	/* Keep a count of the synchronous opens in the znode */
214 	if (flag & (FSYNC | FDSYNC))
215 		atomic_inc_32(&zp->z_sync_cnt);
216 
217 	ZFS_EXIT(zfsvfs);
218 	return (0);
219 }
220 
221 /* ARGSUSED */
222 static int
223 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
224     caller_context_t *ct)
225 {
226 	znode_t	*zp = VTOZ(vp);
227 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
228 
229 	/*
230 	 * Clean up any locks held by this process on the vp.
231 	 */
232 	cleanlocks(vp, ddi_get_pid(), 0);
233 	cleanshares(vp, ddi_get_pid());
234 
235 	ZFS_ENTER(zfsvfs);
236 	ZFS_VERIFY_ZP(zp);
237 
238 	/* Decrement the synchronous opens in the znode */
239 	if ((flag & (FSYNC | FDSYNC)) && (count == 1))
240 		atomic_dec_32(&zp->z_sync_cnt);
241 
242 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
243 	    ZTOV(zp)->v_type == VREG &&
244 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
245 		VERIFY(fs_vscan(vp, cr, 1) == 0);
246 
247 	if (ZTOV(zp)->v_type == VREG && zp->z_new_content) {
248 		zp->z_new_content = 0;
249 		rw_enter(&rz_zev_rwlock, RW_READER);
250 		if (rz_zev_callbacks &&
251 		    rz_zev_callbacks->rz_zev_znode_close_after_update)
252 			rz_zev_callbacks->rz_zev_znode_close_after_update(zp);
253 		rw_exit(&rz_zev_rwlock);
254 	}
255 
256 	ZFS_EXIT(zfsvfs);
257 	return (0);
258 }
259 
260 /*
261  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
262  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
263  */
264 static int
265 zfs_holey(vnode_t *vp, int cmd, offset_t *off)
266 {
267 	znode_t	*zp = VTOZ(vp);
268 	uint64_t noff = (uint64_t)*off; /* new offset */
269 	uint64_t file_sz;
270 	int error;
271 	boolean_t hole;
272 
273 	file_sz = zp->z_size;
274 	if (noff >= file_sz)  {
275 		return (SET_ERROR(ENXIO));
276 	}
277 
278 	if (cmd == _FIO_SEEK_HOLE)
279 		hole = B_TRUE;
280 	else
281 		hole = B_FALSE;
282 
283 	error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
284 
285 	/* end of file? */
286 	if ((error == ESRCH) || (noff > file_sz)) {
287 		/*
288 		 * Handle the virtual hole at the end of file.
289 		 */
290 		if (hole) {
291 			*off = file_sz;
292 			return (0);
293 		}
294 		return (SET_ERROR(ENXIO));
295 	}
296 
297 	if (noff < *off)
298 		return (error);
299 	*off = noff;
300 	return (error);
301 }
302 
303 /* ARGSUSED */
304 static int
305 zfs_ioctl(vnode_t *vp, int com, intptr_t data, int flag, cred_t *cred,
306     int *rvalp, caller_context_t *ct)
307 {
308 	offset_t off;
309 	int error;
310 	zfsvfs_t *zfsvfs;
311 	znode_t *zp;
312 
313 	switch (com) {
314 	case _FIOFFS:
315 		return (zfs_sync(vp->v_vfsp, 0, cred));
316 
317 		/*
318 		 * The following two ioctls are used by bfu.  Faking out,
319 		 * necessary to avoid bfu errors.
320 		 */
321 	case _FIOGDIO:
322 	case _FIOSDIO:
323 		return (0);
324 
325 	case _FIO_SEEK_DATA:
326 	case _FIO_SEEK_HOLE:
327 		if (ddi_copyin((void *)data, &off, sizeof (off), flag))
328 			return (SET_ERROR(EFAULT));
329 
330 		zp = VTOZ(vp);
331 		zfsvfs = zp->z_zfsvfs;
332 		ZFS_ENTER(zfsvfs);
333 		ZFS_VERIFY_ZP(zp);
334 
335 		/* offset parameter is in/out */
336 		error = zfs_holey(vp, com, &off);
337 		ZFS_EXIT(zfsvfs);
338 		if (error)
339 			return (error);
340 		if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
341 			return (SET_ERROR(EFAULT));
342 		return (0);
343 	}
344 	return (SET_ERROR(ENOTTY));
345 }
346 
347 /*
348  * Utility functions to map and unmap a single physical page.  These
349  * are used to manage the mappable copies of ZFS file data, and therefore
350  * do not update ref/mod bits.
351  */
352 caddr_t
353 zfs_map_page(page_t *pp, enum seg_rw rw)
354 {
355 	if (kpm_enable)
356 		return (hat_kpm_mapin(pp, 0));
357 	ASSERT(rw == S_READ || rw == S_WRITE);
358 	return (ppmapin(pp, PROT_READ | ((rw == S_WRITE) ? PROT_WRITE : 0),
359 	    (caddr_t)-1));
360 }
361 
362 void
363 zfs_unmap_page(page_t *pp, caddr_t addr)
364 {
365 	if (kpm_enable) {
366 		hat_kpm_mapout(pp, 0, addr);
367 	} else {
368 		ppmapout(addr);
369 	}
370 }
371 
372 /*
373  * When a file is memory mapped, we must keep the IO data synchronized
374  * between the DMU cache and the memory mapped pages.  What this means:
375  *
376  * On Write:	If we find a memory mapped page, we write to *both*
377  *		the page and the dmu buffer.
378  */
379 static void
380 update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid)
381 {
382 	int64_t	off;
383 
384 	off = start & PAGEOFFSET;
385 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
386 		page_t *pp;
387 		uint64_t nbytes = MIN(PAGESIZE - off, len);
388 
389 		if (pp = page_lookup(vp, start, SE_SHARED)) {
390 			caddr_t va;
391 
392 			va = zfs_map_page(pp, S_WRITE);
393 			(void) dmu_read(os, oid, start+off, nbytes, va+off,
394 			    DMU_READ_PREFETCH);
395 			zfs_unmap_page(pp, va);
396 			page_unlock(pp);
397 		}
398 		len -= nbytes;
399 		off = 0;
400 	}
401 }
402 
403 /*
404  * When a file is memory mapped, we must keep the IO data synchronized
405  * between the DMU cache and the memory mapped pages.  What this means:
406  *
407  * On Read:	We "read" preferentially from memory mapped pages,
408  *		else we default from the dmu buffer.
409  *
410  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
411  *	 the file is memory mapped.
412  */
413 static int
414 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
415 {
416 	znode_t *zp = VTOZ(vp);
417 	objset_t *os = zp->z_zfsvfs->z_os;
418 	int64_t	start, off;
419 	int len = nbytes;
420 	int error = 0;
421 
422 	start = uio->uio_loffset;
423 	off = start & PAGEOFFSET;
424 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
425 		page_t *pp;
426 		uint64_t bytes = MIN(PAGESIZE - off, len);
427 
428 		if (pp = page_lookup(vp, start, SE_SHARED)) {
429 			caddr_t va;
430 
431 			va = zfs_map_page(pp, S_READ);
432 			error = uiomove(va + off, bytes, UIO_READ, uio);
433 			zfs_unmap_page(pp, va);
434 			page_unlock(pp);
435 		} else {
436 			error = dmu_read_uio(os, zp->z_id, uio, bytes);
437 		}
438 		len -= bytes;
439 		off = 0;
440 		if (error)
441 			break;
442 	}
443 	return (error);
444 }
445 
446 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
447 
448 /*
449  * Read bytes from specified file into supplied buffer.
450  *
451  *	IN:	vp	- vnode of file to be read from.
452  *		uio	- structure supplying read location, range info,
453  *			  and return buffer.
454  *		ioflag	- SYNC flags; used to provide FRSYNC semantics.
455  *		cr	- credentials of caller.
456  *		ct	- caller context
457  *
458  *	OUT:	uio	- updated offset and range, buffer filled.
459  *
460  *	RETURN:	0 on success, error code on failure.
461  *
462  * Side Effects:
463  *	vp - atime updated if byte count > 0
464  */
465 /* ARGSUSED */
466 static int
467 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
468 {
469 	znode_t		*zp = VTOZ(vp);
470 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
471 	objset_t	*os;
472 	ssize_t		n, nbytes;
473 	int		error = 0;
474 	rl_t		*rl;
475 	xuio_t		*xuio = NULL;
476 
477 	ZFS_ENTER(zfsvfs);
478 	ZFS_VERIFY_ZP(zp);
479 	os = zfsvfs->z_os;
480 
481 	if (zp->z_pflags & ZFS_AV_QUARANTINED) {
482 		ZFS_EXIT(zfsvfs);
483 		return (SET_ERROR(EACCES));
484 	}
485 
486 	/*
487 	 * Validate file offset
488 	 */
489 	if (uio->uio_loffset < (offset_t)0) {
490 		ZFS_EXIT(zfsvfs);
491 		return (SET_ERROR(EINVAL));
492 	}
493 
494 	/*
495 	 * Fasttrack empty reads
496 	 */
497 	if (uio->uio_resid == 0) {
498 		ZFS_EXIT(zfsvfs);
499 		return (0);
500 	}
501 
502 	/*
503 	 * Check for mandatory locks
504 	 */
505 	if (MANDMODE(zp->z_mode)) {
506 		if (error = chklock(vp, FREAD,
507 		    uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
508 			ZFS_EXIT(zfsvfs);
509 			return (error);
510 		}
511 	}
512 
513 	/*
514 	 * If we're in FRSYNC mode, sync out this znode before reading it.
515 	 */
516 	if (ioflag & FRSYNC || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
517 		zil_commit(zfsvfs->z_log, zp->z_id);
518 
519 	/*
520 	 * Lock the range against changes.
521 	 */
522 	rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
523 
524 	/*
525 	 * If we are reading past end-of-file we can skip
526 	 * to the end; but we might still need to set atime.
527 	 */
528 	if (uio->uio_loffset >= zp->z_size) {
529 		error = 0;
530 		goto out;
531 	}
532 
533 	ASSERT(uio->uio_loffset < zp->z_size);
534 	n = MIN(uio->uio_resid, zp->z_size - uio->uio_loffset);
535 
536 	if ((uio->uio_extflg == UIO_XUIO) &&
537 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY)) {
538 		int nblk;
539 		int blksz = zp->z_blksz;
540 		uint64_t offset = uio->uio_loffset;
541 
542 		xuio = (xuio_t *)uio;
543 		if ((ISP2(blksz))) {
544 			nblk = (P2ROUNDUP(offset + n, blksz) - P2ALIGN(offset,
545 			    blksz)) / blksz;
546 		} else {
547 			ASSERT(offset + n <= blksz);
548 			nblk = 1;
549 		}
550 		(void) dmu_xuio_init(xuio, nblk);
551 
552 		if (vn_has_cached_data(vp)) {
553 			/*
554 			 * For simplicity, we always allocate a full buffer
555 			 * even if we only expect to read a portion of a block.
556 			 */
557 			while (--nblk >= 0) {
558 				(void) dmu_xuio_add(xuio,
559 				    dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
560 				    blksz), 0, blksz);
561 			}
562 		}
563 	}
564 
565 	while (n > 0) {
566 		nbytes = MIN(n, zfs_read_chunk_size -
567 		    P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
568 
569 		if (vn_has_cached_data(vp))
570 			error = mappedread(vp, nbytes, uio);
571 		else
572 			error = dmu_read_uio(os, zp->z_id, uio, nbytes);
573 		if (error) {
574 			/* convert checksum errors into IO errors */
575 			if (error == ECKSUM)
576 				error = SET_ERROR(EIO);
577 			break;
578 		}
579 
580 		n -= nbytes;
581 	}
582 out:
583 	zfs_range_unlock(rl);
584 
585 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
586 	ZFS_EXIT(zfsvfs);
587 	return (error);
588 }
589 
590 /*
591  * Write the bytes to a file.
592  *
593  *	IN:	vp	- vnode of file to be written to.
594  *		uio	- structure supplying write location, range info,
595  *			  and data buffer.
596  *		ioflag	- FAPPEND, FSYNC, and/or FDSYNC.  FAPPEND is
597  *			  set if in append mode.
598  *		cr	- credentials of caller.
599  *		ct	- caller context (NFS/CIFS fem monitor only)
600  *
601  *	OUT:	uio	- updated offset and range.
602  *
603  *	RETURN:	0 on success, error code on failure.
604  *
605  * Timestamps:
606  *	vp - ctime|mtime updated if byte count > 0
607  */
608 
609 /* ARGSUSED */
610 static int
611 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
612 {
613 	znode_t		*zp = VTOZ(vp);
614 	rlim64_t	limit = uio->uio_llimit;
615 	ssize_t		start_resid = uio->uio_resid;
616 	ssize_t		tx_bytes;
617 	uint64_t	end_size;
618 	dmu_tx_t	*tx;
619 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
620 	zilog_t		*zilog;
621 	offset_t	woff;
622 	ssize_t		n, nbytes;
623 	rl_t		*rl;
624 	int		max_blksz = zfsvfs->z_max_blksz;
625 	int		error = 0;
626 	arc_buf_t	*abuf;
627 	iovec_t		*aiov = NULL;
628 	xuio_t		*xuio = NULL;
629 	int		i_iov = 0;
630 	int		iovcnt = uio->uio_iovcnt;
631 	iovec_t		*iovp = uio->uio_iov;
632 	int		write_eof;
633 	int		count = 0;
634 	sa_bulk_attr_t	bulk[4];
635 	uint64_t	mtime[2], ctime[2];
636 	ssize_t		lock_off, lock_len;
637 
638 	/*
639 	 * Fasttrack empty write
640 	 */
641 	n = start_resid;
642 	if (n == 0)
643 		return (0);
644 
645 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
646 		limit = MAXOFFSET_T;
647 
648 	ZFS_ENTER(zfsvfs);
649 	ZFS_VERIFY_ZP(zp);
650 
651 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
652 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
653 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
654 	    &zp->z_size, 8);
655 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
656 	    &zp->z_pflags, 8);
657 
658 	/*
659 	 * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
660 	 * callers might not be able to detect properly that we are read-only,
661 	 * so check it explicitly here.
662 	 */
663 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
664 		ZFS_EXIT(zfsvfs);
665 		return (SET_ERROR(EROFS));
666 	}
667 
668 	/*
669 	 * If immutable or not appending then return EPERM
670 	 */
671 	if ((zp->z_pflags & (ZFS_IMMUTABLE | ZFS_READONLY)) ||
672 	    ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
673 	    (uio->uio_loffset < zp->z_size))) {
674 		ZFS_EXIT(zfsvfs);
675 		return (SET_ERROR(EPERM));
676 	}
677 
678 	zilog = zfsvfs->z_log;
679 
680 	/*
681 	 * Validate file offset
682 	 */
683 	woff = ioflag & FAPPEND ? zp->z_size : uio->uio_loffset;
684 	if (woff < 0) {
685 		ZFS_EXIT(zfsvfs);
686 		return (SET_ERROR(EINVAL));
687 	}
688 
689 	/*
690 	 * Check for mandatory locks before calling zfs_range_lock()
691 	 * in order to prevent a deadlock with locks set via fcntl().
692 	 */
693 	if (MANDMODE((mode_t)zp->z_mode) &&
694 	    (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
695 		ZFS_EXIT(zfsvfs);
696 		return (error);
697 	}
698 
699 	/*
700 	 * Pre-fault the pages to ensure slow (eg NFS) pages
701 	 * don't hold up txg.
702 	 * Skip this if uio contains loaned arc_buf.
703 	 */
704 	if ((uio->uio_extflg == UIO_XUIO) &&
705 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY))
706 		xuio = (xuio_t *)uio;
707 	else
708 		uio_prefaultpages(MIN(n, max_blksz), uio);
709 
710 	/*
711 	 * If in append mode, set the io offset pointer to eof.
712 	 */
713 	if (ioflag & FAPPEND) {
714 		/*
715 		 * Obtain an appending range lock to guarantee file append
716 		 * semantics.  We reset the write offset once we have the lock.
717 		 */
718 		rl = zfs_range_lock(zp, 0, n, RL_APPEND);
719 		woff = rl->r_off;
720 		if (rl->r_len == UINT64_MAX) {
721 			/*
722 			 * We overlocked the file because this write will cause
723 			 * the file block size to increase.
724 			 * Note that zp_size cannot change with this lock held.
725 			 */
726 			woff = zp->z_size;
727 		}
728 		uio->uio_loffset = woff;
729 	} else {
730 		/*
731 		 * Note that if the file block size will change as a result of
732 		 * this write, then this range lock will lock the entire file
733 		 * so that we can re-write the block safely.
734 		 */
735 
736 		/*
737 		 * If in zev mode, lock offsets are quantized to 1MB chunks
738 		 * so that we can calculate level 1 checksums later on.
739 		 */
740 		if (rz_zev_active()) {
741 			/* start of this megabyte */
742 			lock_off = P2ALIGN(woff, ZEV_L1_SIZE);
743 			/* full megabytes */
744 			lock_len = n + (woff - lock_off);
745 			lock_len = P2ROUNDUP(lock_len, ZEV_L1_SIZE);
746 		} else {
747 			lock_off = woff;
748 			lock_len = n;
749 		}
750 
751 		rl = zfs_range_lock(zp, lock_off, lock_len, RL_WRITER);
752 	}
753 
754 	if (woff >= limit) {
755 		zfs_range_unlock(rl);
756 		ZFS_EXIT(zfsvfs);
757 		return (SET_ERROR(EFBIG));
758 	}
759 
760 	if ((woff + n) > limit || woff > (limit - n))
761 		n = limit - woff;
762 
763 	/* Will this write extend the file length? */
764 	write_eof = (woff + n > zp->z_size);
765 
766 	end_size = MAX(zp->z_size, woff + n);
767 
768 	/*
769 	 * Write the file in reasonable size chunks.  Each chunk is written
770 	 * in a separate transaction; this keeps the intent log records small
771 	 * and allows us to do more fine-grained space accounting.
772 	 */
773 	while (n > 0) {
774 		abuf = NULL;
775 		woff = uio->uio_loffset;
776 		if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
777 		    zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
778 			if (abuf != NULL)
779 				dmu_return_arcbuf(abuf);
780 			error = SET_ERROR(EDQUOT);
781 			break;
782 		}
783 
784 		if (xuio && abuf == NULL) {
785 			ASSERT(i_iov < iovcnt);
786 			aiov = &iovp[i_iov];
787 			abuf = dmu_xuio_arcbuf(xuio, i_iov);
788 			dmu_xuio_clear(xuio, i_iov);
789 			DTRACE_PROBE3(zfs_cp_write, int, i_iov,
790 			    iovec_t *, aiov, arc_buf_t *, abuf);
791 			ASSERT((aiov->iov_base == abuf->b_data) ||
792 			    ((char *)aiov->iov_base - (char *)abuf->b_data +
793 			    aiov->iov_len == arc_buf_size(abuf)));
794 			i_iov++;
795 		} else if (abuf == NULL && n >= max_blksz &&
796 		    woff >= zp->z_size &&
797 		    P2PHASE(woff, max_blksz) == 0 &&
798 		    zp->z_blksz == max_blksz) {
799 			/*
800 			 * This write covers a full block.  "Borrow" a buffer
801 			 * from the dmu so that we can fill it before we enter
802 			 * a transaction.  This avoids the possibility of
803 			 * holding up the transaction if the data copy hangs
804 			 * up on a pagefault (e.g., from an NFS server mapping).
805 			 */
806 			size_t cbytes;
807 
808 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
809 			    max_blksz);
810 			ASSERT(abuf != NULL);
811 			ASSERT(arc_buf_size(abuf) == max_blksz);
812 			if (error = uiocopy(abuf->b_data, max_blksz,
813 			    UIO_WRITE, uio, &cbytes)) {
814 				dmu_return_arcbuf(abuf);
815 				break;
816 			}
817 			ASSERT(cbytes == max_blksz);
818 		}
819 
820 		/*
821 		 * Start a transaction.
822 		 */
823 		tx = dmu_tx_create(zfsvfs->z_os);
824 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
825 		dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
826 		zfs_sa_upgrade_txholds(tx, zp);
827 		error = dmu_tx_assign(tx, TXG_WAIT);
828 		if (error) {
829 			dmu_tx_abort(tx);
830 			if (abuf != NULL)
831 				dmu_return_arcbuf(abuf);
832 			break;
833 		}
834 
835 		/*
836 		 * If zfs_range_lock() over-locked we grow the blocksize
837 		 * and then reduce the lock range.  This will only happen
838 		 * on the first iteration since zfs_range_reduce() will
839 		 * shrink down r_len to the appropriate size.
840 		 */
841 		if (rl->r_len == UINT64_MAX) {
842 			uint64_t new_blksz;
843 
844 			if (zp->z_blksz > max_blksz) {
845 				ASSERT(!ISP2(zp->z_blksz));
846 				new_blksz = MIN(end_size, SPA_MAXBLOCKSIZE);
847 			} else {
848 				new_blksz = MIN(end_size, max_blksz);
849 			}
850 			zfs_grow_blocksize(zp, new_blksz, tx);
851 			zfs_range_reduce(rl, woff, n);
852 		}
853 
854 		/*
855 		 * XXX - should we really limit each write to z_max_blksz?
856 		 * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
857 		 */
858 		nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
859 
860 		if (abuf == NULL) {
861 			tx_bytes = uio->uio_resid;
862 			error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
863 			    uio, nbytes, tx);
864 			tx_bytes -= uio->uio_resid;
865 		} else {
866 			tx_bytes = nbytes;
867 			ASSERT(xuio == NULL || tx_bytes == aiov->iov_len);
868 			/*
869 			 * If this is not a full block write, but we are
870 			 * extending the file past EOF and this data starts
871 			 * block-aligned, use assign_arcbuf().  Otherwise,
872 			 * write via dmu_write().
873 			 */
874 			if (tx_bytes < max_blksz && (!write_eof ||
875 			    aiov->iov_base != abuf->b_data)) {
876 				ASSERT(xuio);
877 				dmu_write(zfsvfs->z_os, zp->z_id, woff,
878 				    aiov->iov_len, aiov->iov_base, tx);
879 				dmu_return_arcbuf(abuf);
880 				xuio_stat_wbuf_copied();
881 			} else {
882 				ASSERT(xuio || tx_bytes == max_blksz);
883 				dmu_assign_arcbuf(sa_get_db(zp->z_sa_hdl),
884 				    woff, abuf, tx);
885 			}
886 			ASSERT(tx_bytes <= uio->uio_resid);
887 			uioskip(uio, tx_bytes);
888 		}
889 		if (tx_bytes && vn_has_cached_data(vp)) {
890 			update_pages(vp, woff,
891 			    tx_bytes, zfsvfs->z_os, zp->z_id);
892 		}
893 
894 		/*
895 		 * If we made no progress, we're done.  If we made even
896 		 * partial progress, update the znode and ZIL accordingly.
897 		 */
898 		if (tx_bytes == 0) {
899 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
900 			    (void *)&zp->z_size, sizeof (uint64_t), tx);
901 			dmu_tx_commit(tx);
902 			ASSERT(error != 0);
903 			break;
904 		}
905 
906 		/*
907 		 * Clear Set-UID/Set-GID bits on successful write if not
908 		 * privileged and at least one of the excute bits is set.
909 		 *
910 		 * It would be nice to to this after all writes have
911 		 * been done, but that would still expose the ISUID/ISGID
912 		 * to another app after the partial write is committed.
913 		 *
914 		 * Note: we don't call zfs_fuid_map_id() here because
915 		 * user 0 is not an ephemeral uid.
916 		 */
917 		mutex_enter(&zp->z_acl_lock);
918 		if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) |
919 		    (S_IXUSR >> 6))) != 0 &&
920 		    (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
921 		    secpolicy_vnode_setid_retain(cr,
922 		    (zp->z_mode & S_ISUID) != 0 && zp->z_uid == 0) != 0) {
923 			uint64_t newmode;
924 			zp->z_mode &= ~(S_ISUID | S_ISGID);
925 			newmode = zp->z_mode;
926 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
927 			    (void *)&newmode, sizeof (uint64_t), tx);
928 		}
929 		mutex_exit(&zp->z_acl_lock);
930 
931 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
932 		    B_TRUE);
933 
934 		/*
935 		 * Update the file size (zp_size) if it has changed;
936 		 * account for possible concurrent updates.
937 		 */
938 		while ((end_size = zp->z_size) < uio->uio_loffset) {
939 			(void) atomic_cas_64(&zp->z_size, end_size,
940 			    uio->uio_loffset);
941 			ASSERT(error == 0);
942 		}
943 		/*
944 		 * If we are replaying and eof is non zero then force
945 		 * the file size to the specified eof. Note, there's no
946 		 * concurrency during replay.
947 		 */
948 		if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
949 			zp->z_size = zfsvfs->z_replay_eof;
950 
951 		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
952 
953 		zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
954 		dmu_tx_commit(tx);
955 
956 		if (error != 0)
957 			break;
958 		ASSERT(tx_bytes == nbytes);
959 		n -= nbytes;
960 
961 		if (!xuio && n > 0)
962 			uio_prefaultpages(MIN(n, max_blksz), uio);
963 	}
964 
965 	zfs_range_unlock(rl);
966 
967 	/*
968 	 * If we're in replay mode, or we made no progress, return error.
969 	 * Otherwise, it's at least a partial write, so it's successful.
970 	 */
971 	if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
972 		ZFS_EXIT(zfsvfs);
973 		return (error);
974 	}
975 
976 	if (ioflag & (FSYNC | FDSYNC) ||
977 	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
978 		zil_commit(zilog, zp->z_id);
979 
980 	ZFS_EXIT(zfsvfs);
981 	return (0);
982 }
983 
984 void
985 zfs_get_done(zgd_t *zgd, int error)
986 {
987 	znode_t *zp = zgd->zgd_private;
988 	objset_t *os = zp->z_zfsvfs->z_os;
989 
990 	if (zgd->zgd_db)
991 		dmu_buf_rele(zgd->zgd_db, zgd);
992 
993 	zfs_range_unlock(zgd->zgd_rl);
994 
995 	/*
996 	 * Release the vnode asynchronously as we currently have the
997 	 * txg stopped from syncing.
998 	 */
999 	VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1000 
1001 	if (error == 0 && zgd->zgd_bp)
1002 		zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1003 
1004 	kmem_free(zgd, sizeof (zgd_t));
1005 }
1006 
1007 #ifdef DEBUG
1008 static int zil_fault_io = 0;
1009 #endif
1010 
1011 /*
1012  * Get data to generate a TX_WRITE intent log record.
1013  */
1014 int
1015 zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1016 {
1017 	zfsvfs_t *zfsvfs = arg;
1018 	objset_t *os = zfsvfs->z_os;
1019 	znode_t *zp;
1020 	uint64_t object = lr->lr_foid;
1021 	uint64_t offset = lr->lr_offset;
1022 	uint64_t size = lr->lr_length;
1023 	blkptr_t *bp = &lr->lr_blkptr;
1024 	dmu_buf_t *db;
1025 	zgd_t *zgd;
1026 	int error = 0;
1027 
1028 	ASSERT(zio != NULL);
1029 	ASSERT(size != 0);
1030 
1031 	/*
1032 	 * Nothing to do if the file has been removed
1033 	 */
1034 	if (zfs_zget(zfsvfs, object, &zp) != 0)
1035 		return (SET_ERROR(ENOENT));
1036 	if (zp->z_unlinked) {
1037 		/*
1038 		 * Release the vnode asynchronously as we currently have the
1039 		 * txg stopped from syncing.
1040 		 */
1041 		VN_RELE_ASYNC(ZTOV(zp),
1042 		    dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1043 		return (SET_ERROR(ENOENT));
1044 	}
1045 
1046 	zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1047 	zgd->zgd_zilog = zfsvfs->z_log;
1048 	zgd->zgd_private = zp;
1049 
1050 	/*
1051 	 * Write records come in two flavors: immediate and indirect.
1052 	 * For small writes it's cheaper to store the data with the
1053 	 * log record (immediate); for large writes it's cheaper to
1054 	 * sync the data and get a pointer to it (indirect) so that
1055 	 * we don't have to write the data twice.
1056 	 */
1057 	if (buf != NULL) { /* immediate write */
1058 		zgd->zgd_rl = zfs_range_lock(zp, offset, size, RL_READER);
1059 		/* test for truncation needs to be done while range locked */
1060 		if (offset >= zp->z_size) {
1061 			error = SET_ERROR(ENOENT);
1062 		} else {
1063 			error = dmu_read(os, object, offset, size, buf,
1064 			    DMU_READ_NO_PREFETCH);
1065 		}
1066 		ASSERT(error == 0 || error == ENOENT);
1067 	} else { /* indirect write */
1068 		/*
1069 		 * Have to lock the whole block to ensure when it's
1070 		 * written out and it's checksum is being calculated
1071 		 * that no one can change the data. We need to re-check
1072 		 * blocksize after we get the lock in case it's changed!
1073 		 */
1074 		for (;;) {
1075 			uint64_t blkoff;
1076 			size = zp->z_blksz;
1077 			blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1078 			offset -= blkoff;
1079 			zgd->zgd_rl = zfs_range_lock(zp, offset, size,
1080 			    RL_READER);
1081 			if (zp->z_blksz == size)
1082 				break;
1083 			offset += blkoff;
1084 			zfs_range_unlock(zgd->zgd_rl);
1085 		}
1086 		/* test for truncation needs to be done while range locked */
1087 		if (lr->lr_offset >= zp->z_size)
1088 			error = SET_ERROR(ENOENT);
1089 #ifdef DEBUG
1090 		if (zil_fault_io) {
1091 			error = SET_ERROR(EIO);
1092 			zil_fault_io = 0;
1093 		}
1094 #endif
1095 		if (error == 0)
1096 			error = dmu_buf_hold(os, object, offset, zgd, &db,
1097 			    DMU_READ_NO_PREFETCH);
1098 
1099 		if (error == 0) {
1100 			blkptr_t *obp = dmu_buf_get_blkptr(db);
1101 			if (obp) {
1102 				ASSERT(BP_IS_HOLE(bp));
1103 				*bp = *obp;
1104 			}
1105 
1106 			zgd->zgd_db = db;
1107 			zgd->zgd_bp = bp;
1108 
1109 			ASSERT(db->db_offset == offset);
1110 			ASSERT(db->db_size == size);
1111 
1112 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1113 			    zfs_get_done, zgd);
1114 			ASSERT(error || lr->lr_length <= zp->z_blksz);
1115 
1116 			/*
1117 			 * On success, we need to wait for the write I/O
1118 			 * initiated by dmu_sync() to complete before we can
1119 			 * release this dbuf.  We will finish everything up
1120 			 * in the zfs_get_done() callback.
1121 			 */
1122 			if (error == 0)
1123 				return (0);
1124 
1125 			if (error == EALREADY) {
1126 				lr->lr_common.lrc_txtype = TX_WRITE2;
1127 				error = 0;
1128 			}
1129 		}
1130 	}
1131 
1132 	zfs_get_done(zgd, error);
1133 
1134 	return (error);
1135 }
1136 
1137 /*ARGSUSED*/
1138 static int
1139 zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1140     caller_context_t *ct)
1141 {
1142 	znode_t *zp = VTOZ(vp);
1143 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1144 	int error;
1145 
1146 	ZFS_ENTER(zfsvfs);
1147 	ZFS_VERIFY_ZP(zp);
1148 
1149 	if (flag & V_ACE_MASK)
1150 		error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1151 	else
1152 		error = zfs_zaccess_rwx(zp, mode, flag, cr);
1153 
1154 	ZFS_EXIT(zfsvfs);
1155 	return (error);
1156 }
1157 
1158 /*
1159  * If vnode is for a device return a specfs vnode instead.
1160  */
1161 static int
1162 specvp_check(vnode_t **vpp, cred_t *cr)
1163 {
1164 	int error = 0;
1165 
1166 	if (IS_DEVVP(*vpp)) {
1167 		struct vnode *svp;
1168 
1169 		svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1170 		VN_RELE(*vpp);
1171 		if (svp == NULL)
1172 			error = SET_ERROR(ENOSYS);
1173 		*vpp = svp;
1174 	}
1175 	return (error);
1176 }
1177 
1178 
1179 /*
1180  * Lookup an entry in a directory, or an extended attribute directory.
1181  * If it exists, return a held vnode reference for it.
1182  *
1183  *	IN:	dvp	- vnode of directory to search.
1184  *		nm	- name of entry to lookup.
1185  *		pnp	- full pathname to lookup [UNUSED].
1186  *		flags	- LOOKUP_XATTR set if looking for an attribute.
1187  *		rdir	- root directory vnode [UNUSED].
1188  *		cr	- credentials of caller.
1189  *		ct	- caller context
1190  *		direntflags - directory lookup flags
1191  *		realpnp - returned pathname.
1192  *
1193  *	OUT:	vpp	- vnode of located entry, NULL if not found.
1194  *
1195  *	RETURN:	0 on success, error code on failure.
1196  *
1197  * Timestamps:
1198  *	NA
1199  */
1200 /* ARGSUSED */
1201 static int
1202 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
1203     int flags, vnode_t *rdir, cred_t *cr,  caller_context_t *ct,
1204     int *direntflags, pathname_t *realpnp)
1205 {
1206 	znode_t *zdp = VTOZ(dvp);
1207 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1208 	int	error = 0;
1209 
1210 	/* fast path */
1211 	if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1212 
1213 		if (dvp->v_type != VDIR) {
1214 			return (SET_ERROR(ENOTDIR));
1215 		} else if (zdp->z_sa_hdl == NULL) {
1216 			return (SET_ERROR(EIO));
1217 		}
1218 
1219 		if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1220 			error = zfs_fastaccesschk_execute(zdp, cr);
1221 			if (!error) {
1222 				*vpp = dvp;
1223 				VN_HOLD(*vpp);
1224 				return (0);
1225 			}
1226 			return (error);
1227 		} else {
1228 			vnode_t *tvp = dnlc_lookup(dvp, nm);
1229 
1230 			if (tvp) {
1231 				error = zfs_fastaccesschk_execute(zdp, cr);
1232 				if (error) {
1233 					VN_RELE(tvp);
1234 					return (error);
1235 				}
1236 				if (tvp == DNLC_NO_VNODE) {
1237 					VN_RELE(tvp);
1238 					return (SET_ERROR(ENOENT));
1239 				} else {
1240 					*vpp = tvp;
1241 					return (specvp_check(vpp, cr));
1242 				}
1243 			}
1244 		}
1245 	}
1246 
1247 	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1248 
1249 	ZFS_ENTER(zfsvfs);
1250 	ZFS_VERIFY_ZP(zdp);
1251 
1252 	*vpp = NULL;
1253 
1254 	if (flags & LOOKUP_XATTR) {
1255 		/*
1256 		 * If the xattr property is off, refuse the lookup request.
1257 		 */
1258 		if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1259 			ZFS_EXIT(zfsvfs);
1260 			return (SET_ERROR(EINVAL));
1261 		}
1262 
1263 		/*
1264 		 * We don't allow recursive attributes..
1265 		 * Maybe someday we will.
1266 		 */
1267 		if (zdp->z_pflags & ZFS_XATTR) {
1268 			ZFS_EXIT(zfsvfs);
1269 			return (SET_ERROR(EINVAL));
1270 		}
1271 
1272 		if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1273 			ZFS_EXIT(zfsvfs);
1274 			return (error);
1275 		}
1276 
1277 		/*
1278 		 * Do we have permission to get into attribute directory?
1279 		 */
1280 
1281 		if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1282 		    B_FALSE, cr)) {
1283 			VN_RELE(*vpp);
1284 			*vpp = NULL;
1285 		}
1286 
1287 		ZFS_EXIT(zfsvfs);
1288 		return (error);
1289 	}
1290 
1291 	if (dvp->v_type != VDIR) {
1292 		ZFS_EXIT(zfsvfs);
1293 		return (SET_ERROR(ENOTDIR));
1294 	}
1295 
1296 	/*
1297 	 * Check accessibility of directory.
1298 	 */
1299 
1300 	if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr)) {
1301 		ZFS_EXIT(zfsvfs);
1302 		return (error);
1303 	}
1304 
1305 	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1306 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1307 		ZFS_EXIT(zfsvfs);
1308 		return (SET_ERROR(EILSEQ));
1309 	}
1310 
1311 	error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1312 	if (error == 0)
1313 		error = specvp_check(vpp, cr);
1314 
1315 	ZFS_EXIT(zfsvfs);
1316 	return (error);
1317 }
1318 
1319 /*
1320  * Attempt to create a new entry in a directory.  If the entry
1321  * already exists, truncate the file if permissible, else return
1322  * an error.  Return the vp of the created or trunc'd file.
1323  *
1324  *	IN:	dvp	- vnode of directory to put new file entry in.
1325  *		name	- name of new file entry.
1326  *		vap	- attributes of new file.
1327  *		excl	- flag indicating exclusive or non-exclusive mode.
1328  *		mode	- mode to open file with.
1329  *		cr	- credentials of caller.
1330  *		flag	- large file flag [UNUSED].
1331  *		ct	- caller context
1332  *		vsecp	- ACL to be set
1333  *
1334  *	OUT:	vpp	- vnode of created or trunc'd entry.
1335  *
1336  *	RETURN:	0 on success, error code on failure.
1337  *
1338  * Timestamps:
1339  *	dvp - ctime|mtime updated if new entry created
1340  *	 vp - ctime|mtime always, atime if new
1341  */
1342 
1343 /* ARGSUSED */
1344 static int
1345 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, vcexcl_t excl,
1346     int mode, vnode_t **vpp, cred_t *cr, int flag, caller_context_t *ct,
1347     vsecattr_t *vsecp)
1348 {
1349 	znode_t		*zp, *dzp = VTOZ(dvp);
1350 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1351 	zilog_t		*zilog;
1352 	objset_t	*os;
1353 	zfs_dirlock_t	*dl;
1354 	dmu_tx_t	*tx;
1355 	int		error;
1356 	ksid_t		*ksid;
1357 	uid_t		uid;
1358 	gid_t		gid = crgetgid(cr);
1359 	zfs_acl_ids_t   acl_ids;
1360 	boolean_t	fuid_dirtied;
1361 	boolean_t	have_acl = B_FALSE;
1362 	boolean_t	waited = B_FALSE;
1363 
1364 	/*
1365 	 * If we have an ephemeral id, ACL, or XVATTR then
1366 	 * make sure file system is at proper version
1367 	 */
1368 
1369 	ksid = crgetsid(cr, KSID_OWNER);
1370 	if (ksid)
1371 		uid = ksid_getid(ksid);
1372 	else
1373 		uid = crgetuid(cr);
1374 
1375 	if (zfsvfs->z_use_fuids == B_FALSE &&
1376 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1377 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1378 		return (SET_ERROR(EINVAL));
1379 
1380 	ZFS_ENTER(zfsvfs);
1381 	ZFS_VERIFY_ZP(dzp);
1382 	os = zfsvfs->z_os;
1383 	zilog = zfsvfs->z_log;
1384 
1385 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1386 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1387 		ZFS_EXIT(zfsvfs);
1388 		return (SET_ERROR(EILSEQ));
1389 	}
1390 
1391 	if (vap->va_mask & AT_XVATTR) {
1392 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1393 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1394 			ZFS_EXIT(zfsvfs);
1395 			return (error);
1396 		}
1397 	}
1398 top:
1399 	*vpp = NULL;
1400 
1401 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1402 		vap->va_mode &= ~VSVTX;
1403 
1404 	if (*name == '\0') {
1405 		/*
1406 		 * Null component name refers to the directory itself.
1407 		 */
1408 		VN_HOLD(dvp);
1409 		zp = dzp;
1410 		dl = NULL;
1411 		error = 0;
1412 	} else {
1413 		/* possible VN_HOLD(zp) */
1414 		int zflg = 0;
1415 
1416 		if (flag & FIGNORECASE)
1417 			zflg |= ZCILOOK;
1418 
1419 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1420 		    NULL, NULL);
1421 		if (error) {
1422 			if (have_acl)
1423 				zfs_acl_ids_free(&acl_ids);
1424 			if (strcmp(name, "..") == 0)
1425 				error = SET_ERROR(EISDIR);
1426 			ZFS_EXIT(zfsvfs);
1427 			return (error);
1428 		}
1429 	}
1430 
1431 	if (zp == NULL) {
1432 		uint64_t txtype;
1433 
1434 		/*
1435 		 * Create a new file object and update the directory
1436 		 * to reference it.
1437 		 */
1438 		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1439 			if (have_acl)
1440 				zfs_acl_ids_free(&acl_ids);
1441 			goto out;
1442 		}
1443 
1444 		/*
1445 		 * We only support the creation of regular files in
1446 		 * extended attribute directories.
1447 		 */
1448 
1449 		if ((dzp->z_pflags & ZFS_XATTR) &&
1450 		    (vap->va_type != VREG)) {
1451 			if (have_acl)
1452 				zfs_acl_ids_free(&acl_ids);
1453 			error = SET_ERROR(EINVAL);
1454 			goto out;
1455 		}
1456 
1457 		if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
1458 		    cr, vsecp, &acl_ids)) != 0)
1459 			goto out;
1460 		have_acl = B_TRUE;
1461 
1462 		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1463 			zfs_acl_ids_free(&acl_ids);
1464 			error = SET_ERROR(EDQUOT);
1465 			goto out;
1466 		}
1467 
1468 		tx = dmu_tx_create(os);
1469 
1470 		dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1471 		    ZFS_SA_BASE_ATTR_SIZE);
1472 
1473 		fuid_dirtied = zfsvfs->z_fuid_dirty;
1474 		if (fuid_dirtied)
1475 			zfs_fuid_txhold(zfsvfs, tx);
1476 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1477 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1478 		if (!zfsvfs->z_use_sa &&
1479 		    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1480 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1481 			    0, acl_ids.z_aclp->z_acl_bytes);
1482 		}
1483 		error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1484 		if (error) {
1485 			zfs_dirent_unlock(dl);
1486 			if (error == ERESTART) {
1487 				waited = B_TRUE;
1488 				dmu_tx_wait(tx);
1489 				dmu_tx_abort(tx);
1490 				goto top;
1491 			}
1492 			zfs_acl_ids_free(&acl_ids);
1493 			dmu_tx_abort(tx);
1494 			ZFS_EXIT(zfsvfs);
1495 			return (error);
1496 		}
1497 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1498 
1499 		if (fuid_dirtied)
1500 			zfs_fuid_sync(zfsvfs, tx);
1501 
1502 		(void) zfs_link_create(dl, zp, tx, ZNEW);
1503 		txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1504 		if (flag & FIGNORECASE)
1505 			txtype |= TX_CI;
1506 		zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1507 		    vsecp, acl_ids.z_fuidp, vap);
1508 		zfs_acl_ids_free(&acl_ids);
1509 		dmu_tx_commit(tx);
1510 	} else {
1511 		int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1512 
1513 		if (have_acl)
1514 			zfs_acl_ids_free(&acl_ids);
1515 		have_acl = B_FALSE;
1516 
1517 		/*
1518 		 * A directory entry already exists for this name.
1519 		 */
1520 		/*
1521 		 * Can't truncate an existing file if in exclusive mode.
1522 		 */
1523 		if (excl == EXCL) {
1524 			error = SET_ERROR(EEXIST);
1525 			goto out;
1526 		}
1527 		/*
1528 		 * Can't open a directory for writing.
1529 		 */
1530 		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1531 			error = SET_ERROR(EISDIR);
1532 			goto out;
1533 		}
1534 		/*
1535 		 * Verify requested access to file.
1536 		 */
1537 		if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1538 			goto out;
1539 		}
1540 
1541 		mutex_enter(&dzp->z_lock);
1542 		dzp->z_seq++;
1543 		mutex_exit(&dzp->z_lock);
1544 
1545 		/*
1546 		 * Truncate regular files if requested.
1547 		 */
1548 		if ((ZTOV(zp)->v_type == VREG) &&
1549 		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1550 			/* we can't hold any locks when calling zfs_freesp() */
1551 			zfs_dirent_unlock(dl);
1552 			dl = NULL;
1553 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1554 			if (error == 0) {
1555 				vnevent_create(ZTOV(zp), ct);
1556 			}
1557 		}
1558 	}
1559 out:
1560 
1561 	if (dl)
1562 		zfs_dirent_unlock(dl);
1563 
1564 	if (error) {
1565 		if (zp)
1566 			VN_RELE(ZTOV(zp));
1567 	} else {
1568 		*vpp = ZTOV(zp);
1569 		error = specvp_check(vpp, cr);
1570 	}
1571 
1572 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1573 		zil_commit(zilog, 0);
1574 
1575 	ZFS_EXIT(zfsvfs);
1576 	return (error);
1577 }
1578 
1579 /*
1580  * Remove an entry from a directory.
1581  *
1582  *	IN:	dvp	- vnode of directory to remove entry from.
1583  *		name	- name of entry to remove.
1584  *		cr	- credentials of caller.
1585  *		ct	- caller context
1586  *		flags	- case flags
1587  *
1588  *	RETURN:	0 on success, error code on failure.
1589  *
1590  * Timestamps:
1591  *	dvp - ctime|mtime
1592  *	 vp - ctime (if nlink > 0)
1593  */
1594 
1595 uint64_t null_xattr = 0;
1596 
1597 /*ARGSUSED*/
1598 static int
1599 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1600     int flags)
1601 {
1602 	znode_t		*zp, *dzp = VTOZ(dvp);
1603 	znode_t		*xzp;
1604 	vnode_t		*vp;
1605 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1606 	zilog_t		*zilog;
1607 	uint64_t	acl_obj, xattr_obj;
1608 	uint64_t	xattr_obj_unlinked = 0;
1609 	uint64_t	obj = 0;
1610 	zfs_dirlock_t	*dl;
1611 	dmu_tx_t	*tx;
1612 	boolean_t	may_delete_now, delete_now = FALSE;
1613 	boolean_t	unlinked, toobig = FALSE;
1614 	uint64_t	txtype;
1615 	pathname_t	*realnmp = NULL;
1616 	pathname_t	realnm;
1617 	int		error;
1618 	int		zflg = ZEXISTS;
1619 	boolean_t	waited = B_FALSE;
1620 
1621 	ZFS_ENTER(zfsvfs);
1622 	ZFS_VERIFY_ZP(dzp);
1623 	zilog = zfsvfs->z_log;
1624 
1625 	if (flags & FIGNORECASE) {
1626 		zflg |= ZCILOOK;
1627 		pn_alloc(&realnm);
1628 		realnmp = &realnm;
1629 	}
1630 
1631 top:
1632 	xattr_obj = 0;
1633 	xzp = NULL;
1634 	/*
1635 	 * Attempt to lock directory; fail if entry doesn't exist.
1636 	 */
1637 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1638 	    NULL, realnmp)) {
1639 		if (realnmp)
1640 			pn_free(realnmp);
1641 		ZFS_EXIT(zfsvfs);
1642 		return (error);
1643 	}
1644 
1645 	vp = ZTOV(zp);
1646 
1647 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1648 		goto out;
1649 	}
1650 
1651 	/*
1652 	 * Need to use rmdir for removing directories.
1653 	 */
1654 	if (vp->v_type == VDIR) {
1655 		error = SET_ERROR(EPERM);
1656 		goto out;
1657 	}
1658 
1659 	vnevent_remove(vp, dvp, name, ct);
1660 
1661 	if (realnmp)
1662 		dnlc_remove(dvp, realnmp->pn_buf);
1663 	else
1664 		dnlc_remove(dvp, name);
1665 
1666 	mutex_enter(&vp->v_lock);
1667 	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1668 	mutex_exit(&vp->v_lock);
1669 
1670 	/*
1671 	 * We may delete the znode now, or we may put it in the unlinked set;
1672 	 * it depends on whether we're the last link, and on whether there are
1673 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1674 	 * allow for either case.
1675 	 */
1676 	obj = zp->z_id;
1677 	tx = dmu_tx_create(zfsvfs->z_os);
1678 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1679 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1680 	zfs_sa_upgrade_txholds(tx, zp);
1681 	zfs_sa_upgrade_txholds(tx, dzp);
1682 	if (may_delete_now) {
1683 		toobig =
1684 		    zp->z_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1685 		/* if the file is too big, only hold_free a token amount */
1686 		dmu_tx_hold_free(tx, zp->z_id, 0,
1687 		    (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1688 	}
1689 
1690 	/* are there any extended attributes? */
1691 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1692 	    &xattr_obj, sizeof (xattr_obj));
1693 	if (error == 0 && xattr_obj) {
1694 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1695 		ASSERT0(error);
1696 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1697 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1698 	}
1699 
1700 	mutex_enter(&zp->z_lock);
1701 	if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1702 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1703 	mutex_exit(&zp->z_lock);
1704 
1705 	/* charge as an update -- would be nice not to charge at all */
1706 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1707 
1708 	/*
1709 	 * Mark this transaction as typically resulting in a net free of
1710 	 * space, unless object removal will be delayed indefinitely
1711 	 * (due to active holds on the vnode due to the file being open).
1712 	 */
1713 	if (may_delete_now)
1714 		dmu_tx_mark_netfree(tx);
1715 
1716 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1717 	if (error) {
1718 		zfs_dirent_unlock(dl);
1719 		VN_RELE(vp);
1720 		if (xzp)
1721 			VN_RELE(ZTOV(xzp));
1722 		if (error == ERESTART) {
1723 			waited = B_TRUE;
1724 			dmu_tx_wait(tx);
1725 			dmu_tx_abort(tx);
1726 			goto top;
1727 		}
1728 		if (realnmp)
1729 			pn_free(realnmp);
1730 		dmu_tx_abort(tx);
1731 		ZFS_EXIT(zfsvfs);
1732 		return (error);
1733 	}
1734 
1735 	/*
1736 	 * Remove the directory entry.
1737 	 */
1738 	error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1739 
1740 	if (error) {
1741 		dmu_tx_commit(tx);
1742 		goto out;
1743 	}
1744 
1745 	if (unlinked) {
1746 		/*
1747 		 * Hold z_lock so that we can make sure that the ACL obj
1748 		 * hasn't changed.  Could have been deleted due to
1749 		 * zfs_sa_upgrade().
1750 		 */
1751 		mutex_enter(&zp->z_lock);
1752 		mutex_enter(&vp->v_lock);
1753 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1754 		    &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1755 		delete_now = may_delete_now && !toobig &&
1756 		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1757 		    xattr_obj == xattr_obj_unlinked && zfs_external_acl(zp) ==
1758 		    acl_obj;
1759 		mutex_exit(&vp->v_lock);
1760 	}
1761 
1762 	txtype = TX_REMOVE;
1763 	if (flags & FIGNORECASE)
1764 		txtype |= TX_CI;
1765 	rw_enter(&rz_zev_rwlock, RW_READER);
1766 	if (rz_zev_callbacks && rz_zev_callbacks->rz_zev_znode_remove)
1767 		rz_zev_callbacks->rz_zev_znode_remove(dzp, zp, tx,
1768 		                                      name, txtype);
1769 	rw_exit(&rz_zev_rwlock);
1770 
1771 	if (delete_now) {
1772 		if (xattr_obj_unlinked) {
1773 			ASSERT3U(xzp->z_links, ==, 2);
1774 			mutex_enter(&xzp->z_lock);
1775 			xzp->z_unlinked = 1;
1776 			xzp->z_links = 0;
1777 			error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1778 			    &xzp->z_links, sizeof (xzp->z_links), tx);
1779 			ASSERT3U(error,  ==,  0);
1780 			mutex_exit(&xzp->z_lock);
1781 			zfs_unlinked_add(xzp, tx);
1782 
1783 			if (zp->z_is_sa)
1784 				error = sa_remove(zp->z_sa_hdl,
1785 				    SA_ZPL_XATTR(zfsvfs), tx);
1786 			else
1787 				error = sa_update(zp->z_sa_hdl,
1788 				    SA_ZPL_XATTR(zfsvfs), &null_xattr,
1789 				    sizeof (uint64_t), tx);
1790 			ASSERT0(error);
1791 		}
1792 		mutex_enter(&vp->v_lock);
1793 		vp->v_count--;
1794 		ASSERT0(vp->v_count);
1795 		mutex_exit(&vp->v_lock);
1796 		mutex_exit(&zp->z_lock);
1797 		zfs_znode_delete(zp, tx);
1798 	} else if (unlinked) {
1799 		mutex_exit(&zp->z_lock);
1800 		zfs_unlinked_add(zp, tx);
1801 	}
1802 
1803 	txtype = TX_REMOVE;
1804 	if (flags & FIGNORECASE)
1805 		txtype |= TX_CI;
1806 	zfs_log_remove(zilog, tx, txtype, dzp, name, obj);
1807 
1808 	dmu_tx_commit(tx);
1809 out:
1810 	if (realnmp)
1811 		pn_free(realnmp);
1812 
1813 	zfs_dirent_unlock(dl);
1814 
1815 	if (!delete_now)
1816 		VN_RELE(vp);
1817 	if (xzp)
1818 		VN_RELE(ZTOV(xzp));
1819 
1820 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1821 		zil_commit(zilog, 0);
1822 
1823 	ZFS_EXIT(zfsvfs);
1824 	return (error);
1825 }
1826 
1827 /*
1828  * Create a new directory and insert it into dvp using the name
1829  * provided.  Return a pointer to the inserted directory.
1830  *
1831  *	IN:	dvp	- vnode of directory to add subdir to.
1832  *		dirname	- name of new directory.
1833  *		vap	- attributes of new directory.
1834  *		cr	- credentials of caller.
1835  *		ct	- caller context
1836  *		flags	- case flags
1837  *		vsecp	- ACL to be set
1838  *
1839  *	OUT:	vpp	- vnode of created directory.
1840  *
1841  *	RETURN:	0 on success, error code on failure.
1842  *
1843  * Timestamps:
1844  *	dvp - ctime|mtime updated
1845  *	 vp - ctime|mtime|atime updated
1846  */
1847 /*ARGSUSED*/
1848 static int
1849 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1850     caller_context_t *ct, int flags, vsecattr_t *vsecp)
1851 {
1852 	znode_t		*zp, *dzp = VTOZ(dvp);
1853 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1854 	zilog_t		*zilog;
1855 	zfs_dirlock_t	*dl;
1856 	uint64_t	txtype;
1857 	dmu_tx_t	*tx;
1858 	int		error;
1859 	int		zf = ZNEW;
1860 	ksid_t		*ksid;
1861 	uid_t		uid;
1862 	gid_t		gid = crgetgid(cr);
1863 	zfs_acl_ids_t   acl_ids;
1864 	boolean_t	fuid_dirtied;
1865 	boolean_t	waited = B_FALSE;
1866 
1867 	ASSERT(vap->va_type == VDIR);
1868 
1869 	/*
1870 	 * If we have an ephemeral id, ACL, or XVATTR then
1871 	 * make sure file system is at proper version
1872 	 */
1873 
1874 	ksid = crgetsid(cr, KSID_OWNER);
1875 	if (ksid)
1876 		uid = ksid_getid(ksid);
1877 	else
1878 		uid = crgetuid(cr);
1879 	if (zfsvfs->z_use_fuids == B_FALSE &&
1880 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1881 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1882 		return (SET_ERROR(EINVAL));
1883 
1884 	ZFS_ENTER(zfsvfs);
1885 	ZFS_VERIFY_ZP(dzp);
1886 	zilog = zfsvfs->z_log;
1887 
1888 	if (dzp->z_pflags & ZFS_XATTR) {
1889 		ZFS_EXIT(zfsvfs);
1890 		return (SET_ERROR(EINVAL));
1891 	}
1892 
1893 	if (zfsvfs->z_utf8 && u8_validate(dirname,
1894 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1895 		ZFS_EXIT(zfsvfs);
1896 		return (SET_ERROR(EILSEQ));
1897 	}
1898 	if (flags & FIGNORECASE)
1899 		zf |= ZCILOOK;
1900 
1901 	if (vap->va_mask & AT_XVATTR) {
1902 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1903 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1904 			ZFS_EXIT(zfsvfs);
1905 			return (error);
1906 		}
1907 	}
1908 
1909 	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1910 	    vsecp, &acl_ids)) != 0) {
1911 		ZFS_EXIT(zfsvfs);
1912 		return (error);
1913 	}
1914 	/*
1915 	 * First make sure the new directory doesn't exist.
1916 	 *
1917 	 * Existence is checked first to make sure we don't return
1918 	 * EACCES instead of EEXIST which can cause some applications
1919 	 * to fail.
1920 	 */
1921 top:
1922 	*vpp = NULL;
1923 
1924 	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
1925 	    NULL, NULL)) {
1926 		zfs_acl_ids_free(&acl_ids);
1927 		ZFS_EXIT(zfsvfs);
1928 		return (error);
1929 	}
1930 
1931 	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
1932 		zfs_acl_ids_free(&acl_ids);
1933 		zfs_dirent_unlock(dl);
1934 		ZFS_EXIT(zfsvfs);
1935 		return (error);
1936 	}
1937 
1938 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1939 		zfs_acl_ids_free(&acl_ids);
1940 		zfs_dirent_unlock(dl);
1941 		ZFS_EXIT(zfsvfs);
1942 		return (SET_ERROR(EDQUOT));
1943 	}
1944 
1945 	/*
1946 	 * Add a new entry to the directory.
1947 	 */
1948 	tx = dmu_tx_create(zfsvfs->z_os);
1949 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1950 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1951 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1952 	if (fuid_dirtied)
1953 		zfs_fuid_txhold(zfsvfs, tx);
1954 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1955 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1956 		    acl_ids.z_aclp->z_acl_bytes);
1957 	}
1958 
1959 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1960 	    ZFS_SA_BASE_ATTR_SIZE);
1961 
1962 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1963 	if (error) {
1964 		zfs_dirent_unlock(dl);
1965 		if (error == ERESTART) {
1966 			waited = B_TRUE;
1967 			dmu_tx_wait(tx);
1968 			dmu_tx_abort(tx);
1969 			goto top;
1970 		}
1971 		zfs_acl_ids_free(&acl_ids);
1972 		dmu_tx_abort(tx);
1973 		ZFS_EXIT(zfsvfs);
1974 		return (error);
1975 	}
1976 
1977 	/*
1978 	 * Create new node.
1979 	 */
1980 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1981 
1982 	if (fuid_dirtied)
1983 		zfs_fuid_sync(zfsvfs, tx);
1984 
1985 	/*
1986 	 * Now put new name in parent dir.
1987 	 */
1988 	(void) zfs_link_create(dl, zp, tx, ZNEW);
1989 
1990 	*vpp = ZTOV(zp);
1991 
1992 	txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
1993 	if (flags & FIGNORECASE)
1994 		txtype |= TX_CI;
1995 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
1996 	    acl_ids.z_fuidp, vap);
1997 
1998 	zfs_acl_ids_free(&acl_ids);
1999 
2000 	dmu_tx_commit(tx);
2001 
2002 	zfs_dirent_unlock(dl);
2003 
2004 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2005 		zil_commit(zilog, 0);
2006 
2007 	ZFS_EXIT(zfsvfs);
2008 	return (0);
2009 }
2010 
2011 /*
2012  * Remove a directory subdir entry.  If the current working
2013  * directory is the same as the subdir to be removed, the
2014  * remove will fail.
2015  *
2016  *	IN:	dvp	- vnode of directory to remove from.
2017  *		name	- name of directory to be removed.
2018  *		cwd	- vnode of current working directory.
2019  *		cr	- credentials of caller.
2020  *		ct	- caller context
2021  *		flags	- case flags
2022  *
2023  *	RETURN:	0 on success, error code on failure.
2024  *
2025  * Timestamps:
2026  *	dvp - ctime|mtime updated
2027  */
2028 /*ARGSUSED*/
2029 static int
2030 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2031     caller_context_t *ct, int flags)
2032 {
2033 	znode_t		*dzp = VTOZ(dvp);
2034 	znode_t		*zp;
2035 	vnode_t		*vp;
2036 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2037 	zilog_t		*zilog;
2038 	zfs_dirlock_t	*dl;
2039 	dmu_tx_t	*tx;
2040 	int		error;
2041 	int		zflg = ZEXISTS;
2042 	boolean_t	waited = B_FALSE;
2043 
2044 	ZFS_ENTER(zfsvfs);
2045 	ZFS_VERIFY_ZP(dzp);
2046 	zilog = zfsvfs->z_log;
2047 
2048 	if (flags & FIGNORECASE)
2049 		zflg |= ZCILOOK;
2050 top:
2051 	zp = NULL;
2052 
2053 	/*
2054 	 * Attempt to lock directory; fail if entry doesn't exist.
2055 	 */
2056 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2057 	    NULL, NULL)) {
2058 		ZFS_EXIT(zfsvfs);
2059 		return (error);
2060 	}
2061 
2062 	vp = ZTOV(zp);
2063 
2064 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2065 		goto out;
2066 	}
2067 
2068 	if (vp->v_type != VDIR) {
2069 		error = SET_ERROR(ENOTDIR);
2070 		goto out;
2071 	}
2072 
2073 	if (vp == cwd) {
2074 		error = SET_ERROR(EINVAL);
2075 		goto out;
2076 	}
2077 
2078 	vnevent_rmdir(vp, dvp, name, ct);
2079 
2080 	/*
2081 	 * Grab a lock on the directory to make sure that noone is
2082 	 * trying to add (or lookup) entries while we are removing it.
2083 	 */
2084 	rw_enter(&zp->z_name_lock, RW_WRITER);
2085 
2086 	/*
2087 	 * Grab a lock on the parent pointer to make sure we play well
2088 	 * with the treewalk and directory rename code.
2089 	 */
2090 	rw_enter(&zp->z_parent_lock, RW_WRITER);
2091 
2092 	tx = dmu_tx_create(zfsvfs->z_os);
2093 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2094 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2095 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2096 	zfs_sa_upgrade_txholds(tx, zp);
2097 	zfs_sa_upgrade_txholds(tx, dzp);
2098 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
2099 	if (error) {
2100 		rw_exit(&zp->z_parent_lock);
2101 		rw_exit(&zp->z_name_lock);
2102 		zfs_dirent_unlock(dl);
2103 		VN_RELE(vp);
2104 		if (error == ERESTART) {
2105 			waited = B_TRUE;
2106 			dmu_tx_wait(tx);
2107 			dmu_tx_abort(tx);
2108 			goto top;
2109 		}
2110 		dmu_tx_abort(tx);
2111 		ZFS_EXIT(zfsvfs);
2112 		return (error);
2113 	}
2114 
2115 	error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2116 
2117 	if (error == 0) {
2118 		uint64_t txtype = TX_RMDIR;
2119 		if (flags & FIGNORECASE)
2120 			txtype |= TX_CI;
2121 
2122 		rw_enter(&rz_zev_rwlock, RW_READER);
2123 		if (rz_zev_callbacks && rz_zev_callbacks->rz_zev_znode_remove)
2124 			rz_zev_callbacks->rz_zev_znode_remove(dzp, zp, tx,
2125 			                                      name, txtype);
2126 		rw_exit(&rz_zev_rwlock);
2127 
2128 		zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT);
2129 	}
2130 
2131 	dmu_tx_commit(tx);
2132 
2133 	rw_exit(&zp->z_parent_lock);
2134 	rw_exit(&zp->z_name_lock);
2135 out:
2136 	zfs_dirent_unlock(dl);
2137 
2138 	VN_RELE(vp);
2139 
2140 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2141 		zil_commit(zilog, 0);
2142 
2143 	ZFS_EXIT(zfsvfs);
2144 	return (error);
2145 }
2146 
2147 /*
2148  * Read as many directory entries as will fit into the provided
2149  * buffer from the given directory cursor position (specified in
2150  * the uio structure).
2151  *
2152  *	IN:	vp	- vnode of directory to read.
2153  *		uio	- structure supplying read location, range info,
2154  *			  and return buffer.
2155  *		cr	- credentials of caller.
2156  *		ct	- caller context
2157  *		flags	- case flags
2158  *
2159  *	OUT:	uio	- updated offset and range, buffer filled.
2160  *		eofp	- set to true if end-of-file detected.
2161  *
2162  *	RETURN:	0 on success, error code on failure.
2163  *
2164  * Timestamps:
2165  *	vp - atime updated
2166  *
2167  * Note that the low 4 bits of the cookie returned by zap is always zero.
2168  * This allows us to use the low range for "special" directory entries:
2169  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2170  * we use the offset 2 for the '.zfs' directory.
2171  */
2172 /* ARGSUSED */
2173 static int
2174 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp,
2175     caller_context_t *ct, int flags)
2176 {
2177 	znode_t		*zp = VTOZ(vp);
2178 	iovec_t		*iovp;
2179 	edirent_t	*eodp;
2180 	dirent64_t	*odp;
2181 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2182 	objset_t	*os;
2183 	caddr_t		outbuf;
2184 	size_t		bufsize;
2185 	zap_cursor_t	zc;
2186 	zap_attribute_t	zap;
2187 	uint_t		bytes_wanted;
2188 	uint64_t	offset; /* must be unsigned; checks for < 1 */
2189 	uint64_t	parent;
2190 	int		local_eof;
2191 	int		outcount;
2192 	int		error;
2193 	uint8_t		prefetch;
2194 	boolean_t	check_sysattrs;
2195 
2196 	ZFS_ENTER(zfsvfs);
2197 	ZFS_VERIFY_ZP(zp);
2198 
2199 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2200 	    &parent, sizeof (parent))) != 0) {
2201 		ZFS_EXIT(zfsvfs);
2202 		return (error);
2203 	}
2204 
2205 	/*
2206 	 * If we are not given an eof variable,
2207 	 * use a local one.
2208 	 */
2209 	if (eofp == NULL)
2210 		eofp = &local_eof;
2211 
2212 	/*
2213 	 * Check for valid iov_len.
2214 	 */
2215 	if (uio->uio_iov->iov_len <= 0) {
2216 		ZFS_EXIT(zfsvfs);
2217 		return (SET_ERROR(EINVAL));
2218 	}
2219 
2220 	/*
2221 	 * Quit if directory has been removed (posix)
2222 	 */
2223 	if ((*eofp = zp->z_unlinked) != 0) {
2224 		ZFS_EXIT(zfsvfs);
2225 		return (0);
2226 	}
2227 
2228 	error = 0;
2229 	os = zfsvfs->z_os;
2230 	offset = uio->uio_loffset;
2231 	prefetch = zp->z_zn_prefetch;
2232 
2233 	/*
2234 	 * Initialize the iterator cursor.
2235 	 */
2236 	if (offset <= 3) {
2237 		/*
2238 		 * Start iteration from the beginning of the directory.
2239 		 */
2240 		zap_cursor_init(&zc, os, zp->z_id);
2241 	} else {
2242 		/*
2243 		 * The offset is a serialized cursor.
2244 		 */
2245 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2246 	}
2247 
2248 	/*
2249 	 * Get space to change directory entries into fs independent format.
2250 	 */
2251 	iovp = uio->uio_iov;
2252 	bytes_wanted = iovp->iov_len;
2253 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2254 		bufsize = bytes_wanted;
2255 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
2256 		odp = (struct dirent64 *)outbuf;
2257 	} else {
2258 		bufsize = bytes_wanted;
2259 		outbuf = NULL;
2260 		odp = (struct dirent64 *)iovp->iov_base;
2261 	}
2262 	eodp = (struct edirent *)odp;
2263 
2264 	/*
2265 	 * If this VFS supports the system attribute view interface; and
2266 	 * we're looking at an extended attribute directory; and we care
2267 	 * about normalization conflicts on this vfs; then we must check
2268 	 * for normalization conflicts with the sysattr name space.
2269 	 */
2270 	check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2271 	    (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2272 	    (flags & V_RDDIR_ENTFLAGS);
2273 
2274 	/*
2275 	 * Transform to file-system independent format
2276 	 */
2277 	outcount = 0;
2278 	while (outcount < bytes_wanted) {
2279 		ino64_t objnum;
2280 		ushort_t reclen;
2281 		off64_t *next = NULL;
2282 
2283 		/*
2284 		 * Special case `.', `..', and `.zfs'.
2285 		 */
2286 		if (offset == 0) {
2287 			(void) strcpy(zap.za_name, ".");
2288 			zap.za_normalization_conflict = 0;
2289 			objnum = zp->z_id;
2290 		} else if (offset == 1) {
2291 			(void) strcpy(zap.za_name, "..");
2292 			zap.za_normalization_conflict = 0;
2293 			objnum = parent;
2294 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
2295 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2296 			zap.za_normalization_conflict = 0;
2297 			objnum = ZFSCTL_INO_ROOT;
2298 		} else {
2299 			/*
2300 			 * Grab next entry.
2301 			 */
2302 			if (error = zap_cursor_retrieve(&zc, &zap)) {
2303 				if ((*eofp = (error == ENOENT)) != 0)
2304 					break;
2305 				else
2306 					goto update;
2307 			}
2308 
2309 			if (zap.za_integer_length != 8 ||
2310 			    zap.za_num_integers != 1) {
2311 				cmn_err(CE_WARN, "zap_readdir: bad directory "
2312 				    "entry, obj = %lld, offset = %lld\n",
2313 				    (u_longlong_t)zp->z_id,
2314 				    (u_longlong_t)offset);
2315 				error = SET_ERROR(ENXIO);
2316 				goto update;
2317 			}
2318 
2319 			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2320 			/*
2321 			 * MacOS X can extract the object type here such as:
2322 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2323 			 */
2324 
2325 			if (check_sysattrs && !zap.za_normalization_conflict) {
2326 				zap.za_normalization_conflict =
2327 				    xattr_sysattr_casechk(zap.za_name);
2328 			}
2329 		}
2330 
2331 		if (flags & V_RDDIR_ACCFILTER) {
2332 			/*
2333 			 * If we have no access at all, don't include
2334 			 * this entry in the returned information
2335 			 */
2336 			znode_t	*ezp;
2337 			if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2338 				goto skip_entry;
2339 			if (!zfs_has_access(ezp, cr)) {
2340 				VN_RELE(ZTOV(ezp));
2341 				goto skip_entry;
2342 			}
2343 			VN_RELE(ZTOV(ezp));
2344 		}
2345 
2346 		if (flags & V_RDDIR_ENTFLAGS)
2347 			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2348 		else
2349 			reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2350 
2351 		/*
2352 		 * Will this entry fit in the buffer?
2353 		 */
2354 		if (outcount + reclen > bufsize) {
2355 			/*
2356 			 * Did we manage to fit anything in the buffer?
2357 			 */
2358 			if (!outcount) {
2359 				error = SET_ERROR(EINVAL);
2360 				goto update;
2361 			}
2362 			break;
2363 		}
2364 		if (flags & V_RDDIR_ENTFLAGS) {
2365 			/*
2366 			 * Add extended flag entry:
2367 			 */
2368 			eodp->ed_ino = objnum;
2369 			eodp->ed_reclen = reclen;
2370 			/* NOTE: ed_off is the offset for the *next* entry */
2371 			next = &(eodp->ed_off);
2372 			eodp->ed_eflags = zap.za_normalization_conflict ?
2373 			    ED_CASE_CONFLICT : 0;
2374 			(void) strncpy(eodp->ed_name, zap.za_name,
2375 			    EDIRENT_NAMELEN(reclen));
2376 			eodp = (edirent_t *)((intptr_t)eodp + reclen);
2377 		} else {
2378 			/*
2379 			 * Add normal entry:
2380 			 */
2381 			odp->d_ino = objnum;
2382 			odp->d_reclen = reclen;
2383 			/* NOTE: d_off is the offset for the *next* entry */
2384 			next = &(odp->d_off);
2385 			(void) strncpy(odp->d_name, zap.za_name,
2386 			    DIRENT64_NAMELEN(reclen));
2387 			odp = (dirent64_t *)((intptr_t)odp + reclen);
2388 		}
2389 		outcount += reclen;
2390 
2391 		ASSERT(outcount <= bufsize);
2392 
2393 		/* Prefetch znode */
2394 		if (prefetch)
2395 			dmu_prefetch(os, objnum, 0, 0);
2396 
2397 	skip_entry:
2398 		/*
2399 		 * Move to the next entry, fill in the previous offset.
2400 		 */
2401 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2402 			zap_cursor_advance(&zc);
2403 			offset = zap_cursor_serialize(&zc);
2404 		} else {
2405 			offset += 1;
2406 		}
2407 		if (next)
2408 			*next = offset;
2409 	}
2410 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2411 
2412 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2413 		iovp->iov_base += outcount;
2414 		iovp->iov_len -= outcount;
2415 		uio->uio_resid -= outcount;
2416 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2417 		/*
2418 		 * Reset the pointer.
2419 		 */
2420 		offset = uio->uio_loffset;
2421 	}
2422 
2423 update:
2424 	zap_cursor_fini(&zc);
2425 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2426 		kmem_free(outbuf, bufsize);
2427 
2428 	if (error == ENOENT)
2429 		error = 0;
2430 
2431 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2432 
2433 	uio->uio_loffset = offset;
2434 	ZFS_EXIT(zfsvfs);
2435 	return (error);
2436 }
2437 
2438 ulong_t zfs_fsync_sync_cnt = 4;
2439 
2440 static int
2441 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2442 {
2443 	znode_t	*zp = VTOZ(vp);
2444 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2445 
2446 	/*
2447 	 * Regardless of whether this is required for standards conformance,
2448 	 * this is the logical behavior when fsync() is called on a file with
2449 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
2450 	 * going to be pushed out as part of the zil_commit().
2451 	 */
2452 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2453 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
2454 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr, ct);
2455 
2456 	(void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2457 
2458 	if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2459 		ZFS_ENTER(zfsvfs);
2460 		ZFS_VERIFY_ZP(zp);
2461 		zil_commit(zfsvfs->z_log, zp->z_id);
2462 		ZFS_EXIT(zfsvfs);
2463 	}
2464 	return (0);
2465 }
2466 
2467 
2468 /*
2469  * Get the requested file attributes and place them in the provided
2470  * vattr structure.
2471  *
2472  *	IN:	vp	- vnode of file.
2473  *		vap	- va_mask identifies requested attributes.
2474  *			  If AT_XVATTR set, then optional attrs are requested
2475  *		flags	- ATTR_NOACLCHECK (CIFS server context)
2476  *		cr	- credentials of caller.
2477  *		ct	- caller context
2478  *
2479  *	OUT:	vap	- attribute values.
2480  *
2481  *	RETURN:	0 (always succeeds).
2482  */
2483 /* ARGSUSED */
2484 static int
2485 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2486     caller_context_t *ct)
2487 {
2488 	znode_t *zp = VTOZ(vp);
2489 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2490 	int	error = 0;
2491 	uint64_t links;
2492 	uint64_t mtime[2], ctime[2];
2493 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2494 	xoptattr_t *xoap = NULL;
2495 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2496 	sa_bulk_attr_t bulk[2];
2497 	int count = 0;
2498 
2499 	ZFS_ENTER(zfsvfs);
2500 	ZFS_VERIFY_ZP(zp);
2501 
2502 	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2503 
2504 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2505 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2506 
2507 	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2508 		ZFS_EXIT(zfsvfs);
2509 		return (error);
2510 	}
2511 
2512 	/*
2513 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2514 	 * Also, if we are the owner don't bother, since owner should
2515 	 * always be allowed to read basic attributes of file.
2516 	 */
2517 	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2518 	    (vap->va_uid != crgetuid(cr))) {
2519 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2520 		    skipaclchk, cr)) {
2521 			ZFS_EXIT(zfsvfs);
2522 			return (error);
2523 		}
2524 	}
2525 
2526 	/*
2527 	 * Return all attributes.  It's cheaper to provide the answer
2528 	 * than to determine whether we were asked the question.
2529 	 */
2530 
2531 	mutex_enter(&zp->z_lock);
2532 	vap->va_type = vp->v_type;
2533 	vap->va_mode = zp->z_mode & MODEMASK;
2534 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2535 	vap->va_nodeid = zp->z_id;
2536 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2537 		links = zp->z_links + 1;
2538 	else
2539 		links = zp->z_links;
2540 	vap->va_nlink = MIN(links, UINT32_MAX);	/* nlink_t limit! */
2541 	vap->va_size = zp->z_size;
2542 	vap->va_rdev = vp->v_rdev;
2543 	vap->va_seq = zp->z_seq;
2544 
2545 	/*
2546 	 * Add in any requested optional attributes and the create time.
2547 	 * Also set the corresponding bits in the returned attribute bitmap.
2548 	 */
2549 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2550 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2551 			xoap->xoa_archive =
2552 			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2553 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2554 		}
2555 
2556 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2557 			xoap->xoa_readonly =
2558 			    ((zp->z_pflags & ZFS_READONLY) != 0);
2559 			XVA_SET_RTN(xvap, XAT_READONLY);
2560 		}
2561 
2562 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2563 			xoap->xoa_system =
2564 			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2565 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2566 		}
2567 
2568 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2569 			xoap->xoa_hidden =
2570 			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2571 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2572 		}
2573 
2574 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2575 			xoap->xoa_nounlink =
2576 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2577 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2578 		}
2579 
2580 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2581 			xoap->xoa_immutable =
2582 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2583 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2584 		}
2585 
2586 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2587 			xoap->xoa_appendonly =
2588 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2589 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2590 		}
2591 
2592 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2593 			xoap->xoa_nodump =
2594 			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2595 			XVA_SET_RTN(xvap, XAT_NODUMP);
2596 		}
2597 
2598 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2599 			xoap->xoa_opaque =
2600 			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2601 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2602 		}
2603 
2604 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2605 			xoap->xoa_av_quarantined =
2606 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2607 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2608 		}
2609 
2610 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2611 			xoap->xoa_av_modified =
2612 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2613 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2614 		}
2615 
2616 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2617 		    vp->v_type == VREG) {
2618 			zfs_sa_get_scanstamp(zp, xvap);
2619 		}
2620 
2621 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2622 			uint64_t times[2];
2623 
2624 			(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2625 			    times, sizeof (times));
2626 			ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2627 			XVA_SET_RTN(xvap, XAT_CREATETIME);
2628 		}
2629 
2630 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2631 			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2632 			XVA_SET_RTN(xvap, XAT_REPARSE);
2633 		}
2634 		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2635 			xoap->xoa_generation = zp->z_gen;
2636 			XVA_SET_RTN(xvap, XAT_GEN);
2637 		}
2638 
2639 		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2640 			xoap->xoa_offline =
2641 			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2642 			XVA_SET_RTN(xvap, XAT_OFFLINE);
2643 		}
2644 
2645 		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2646 			xoap->xoa_sparse =
2647 			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2648 			XVA_SET_RTN(xvap, XAT_SPARSE);
2649 		}
2650 	}
2651 
2652 	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2653 	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2654 	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2655 
2656 	mutex_exit(&zp->z_lock);
2657 
2658 	sa_object_size(zp->z_sa_hdl, &vap->va_blksize, &vap->va_nblocks);
2659 
2660 	if (zp->z_blksz == 0) {
2661 		/*
2662 		 * Block size hasn't been set; suggest maximal I/O transfers.
2663 		 */
2664 		vap->va_blksize = zfsvfs->z_max_blksz;
2665 	}
2666 
2667 	ZFS_EXIT(zfsvfs);
2668 	return (0);
2669 }
2670 
2671 /*
2672  * Set the file attributes to the values contained in the
2673  * vattr structure.
2674  *
2675  *	IN:	vp	- vnode of file to be modified.
2676  *		vap	- new attribute values.
2677  *			  If AT_XVATTR set, then optional attrs are being set
2678  *		flags	- ATTR_UTIME set if non-default time values provided.
2679  *			- ATTR_NOACLCHECK (CIFS context only).
2680  *		cr	- credentials of caller.
2681  *		ct	- caller context
2682  *
2683  *	RETURN:	0 on success, error code on failure.
2684  *
2685  * Timestamps:
2686  *	vp - ctime updated, mtime updated if size changed.
2687  */
2688 /* ARGSUSED */
2689 static int
2690 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2691     caller_context_t *ct)
2692 {
2693 	znode_t		*zp = VTOZ(vp);
2694 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2695 	zilog_t		*zilog;
2696 	dmu_tx_t	*tx;
2697 	vattr_t		oldva;
2698 	xvattr_t	tmpxvattr;
2699 	uint_t		mask = vap->va_mask;
2700 	uint_t		saved_mask = 0;
2701 	int		trim_mask = 0;
2702 	uint64_t	new_mode;
2703 	uint64_t	new_uid, new_gid;
2704 	uint64_t	xattr_obj;
2705 	uint64_t	mtime[2], ctime[2];
2706 	znode_t		*attrzp;
2707 	int		need_policy = FALSE;
2708 	int		err, err2;
2709 	zfs_fuid_info_t *fuidp = NULL;
2710 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2711 	xoptattr_t	*xoap;
2712 	zfs_acl_t	*aclp;
2713 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2714 	boolean_t	fuid_dirtied = B_FALSE;
2715 	sa_bulk_attr_t	bulk[7], xattr_bulk[7];
2716 	int		count = 0, xattr_count = 0;
2717 
2718 	if (mask == 0)
2719 		return (0);
2720 
2721 	if (mask & AT_NOSET)
2722 		return (SET_ERROR(EINVAL));
2723 
2724 	ZFS_ENTER(zfsvfs);
2725 	ZFS_VERIFY_ZP(zp);
2726 
2727 	zilog = zfsvfs->z_log;
2728 
2729 	/*
2730 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
2731 	 * that file system is at proper version level
2732 	 */
2733 
2734 	if (zfsvfs->z_use_fuids == B_FALSE &&
2735 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2736 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2737 	    (mask & AT_XVATTR))) {
2738 		ZFS_EXIT(zfsvfs);
2739 		return (SET_ERROR(EINVAL));
2740 	}
2741 
2742 	if (mask & AT_SIZE && vp->v_type == VDIR) {
2743 		ZFS_EXIT(zfsvfs);
2744 		return (SET_ERROR(EISDIR));
2745 	}
2746 
2747 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2748 		ZFS_EXIT(zfsvfs);
2749 		return (SET_ERROR(EINVAL));
2750 	}
2751 
2752 	/*
2753 	 * If this is an xvattr_t, then get a pointer to the structure of
2754 	 * optional attributes.  If this is NULL, then we have a vattr_t.
2755 	 */
2756 	xoap = xva_getxoptattr(xvap);
2757 
2758 	xva_init(&tmpxvattr);
2759 
2760 	/*
2761 	 * Immutable files can only alter immutable bit and atime
2762 	 */
2763 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2764 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2765 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2766 		ZFS_EXIT(zfsvfs);
2767 		return (SET_ERROR(EPERM));
2768 	}
2769 
2770 	if ((mask & AT_SIZE) && (zp->z_pflags & ZFS_READONLY)) {
2771 		ZFS_EXIT(zfsvfs);
2772 		return (SET_ERROR(EPERM));
2773 	}
2774 
2775 	/*
2776 	 * Verify timestamps doesn't overflow 32 bits.
2777 	 * ZFS can handle large timestamps, but 32bit syscalls can't
2778 	 * handle times greater than 2039.  This check should be removed
2779 	 * once large timestamps are fully supported.
2780 	 */
2781 	if (mask & (AT_ATIME | AT_MTIME)) {
2782 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2783 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2784 			ZFS_EXIT(zfsvfs);
2785 			return (SET_ERROR(EOVERFLOW));
2786 		}
2787 	}
2788 
2789 top:
2790 	attrzp = NULL;
2791 	aclp = NULL;
2792 
2793 	/* Can this be moved to before the top label? */
2794 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2795 		ZFS_EXIT(zfsvfs);
2796 		return (SET_ERROR(EROFS));
2797 	}
2798 
2799 	/*
2800 	 * First validate permissions
2801 	 */
2802 
2803 	if (mask & AT_SIZE) {
2804 		err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
2805 		if (err) {
2806 			ZFS_EXIT(zfsvfs);
2807 			return (err);
2808 		}
2809 		/*
2810 		 * XXX - Note, we are not providing any open
2811 		 * mode flags here (like FNDELAY), so we may
2812 		 * block if there are locks present... this
2813 		 * should be addressed in openat().
2814 		 */
2815 		/* XXX - would it be OK to generate a log record here? */
2816 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2817 		if (err) {
2818 			ZFS_EXIT(zfsvfs);
2819 			return (err);
2820 		}
2821 
2822 		if (vap->va_size == 0)
2823 			vnevent_truncate(ZTOV(zp), ct);
2824 	}
2825 
2826 	if (mask & (AT_ATIME|AT_MTIME) ||
2827 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2828 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2829 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2830 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2831 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2832 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2833 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2834 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2835 		    skipaclchk, cr);
2836 	}
2837 
2838 	if (mask & (AT_UID|AT_GID)) {
2839 		int	idmask = (mask & (AT_UID|AT_GID));
2840 		int	take_owner;
2841 		int	take_group;
2842 
2843 		/*
2844 		 * NOTE: even if a new mode is being set,
2845 		 * we may clear S_ISUID/S_ISGID bits.
2846 		 */
2847 
2848 		if (!(mask & AT_MODE))
2849 			vap->va_mode = zp->z_mode;
2850 
2851 		/*
2852 		 * Take ownership or chgrp to group we are a member of
2853 		 */
2854 
2855 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2856 		take_group = (mask & AT_GID) &&
2857 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
2858 
2859 		/*
2860 		 * If both AT_UID and AT_GID are set then take_owner and
2861 		 * take_group must both be set in order to allow taking
2862 		 * ownership.
2863 		 *
2864 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2865 		 *
2866 		 */
2867 
2868 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2869 		    ((idmask == AT_UID) && take_owner) ||
2870 		    ((idmask == AT_GID) && take_group)) {
2871 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2872 			    skipaclchk, cr) == 0) {
2873 				/*
2874 				 * Remove setuid/setgid for non-privileged users
2875 				 */
2876 				secpolicy_setid_clear(vap, cr);
2877 				trim_mask = (mask & (AT_UID|AT_GID));
2878 			} else {
2879 				need_policy =  TRUE;
2880 			}
2881 		} else {
2882 			need_policy =  TRUE;
2883 		}
2884 	}
2885 
2886 	mutex_enter(&zp->z_lock);
2887 	oldva.va_mode = zp->z_mode;
2888 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2889 	if (mask & AT_XVATTR) {
2890 		/*
2891 		 * Update xvattr mask to include only those attributes
2892 		 * that are actually changing.
2893 		 *
2894 		 * the bits will be restored prior to actually setting
2895 		 * the attributes so the caller thinks they were set.
2896 		 */
2897 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2898 			if (xoap->xoa_appendonly !=
2899 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2900 				need_policy = TRUE;
2901 			} else {
2902 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2903 				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2904 			}
2905 		}
2906 
2907 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2908 			if (xoap->xoa_nounlink !=
2909 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2910 				need_policy = TRUE;
2911 			} else {
2912 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2913 				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2914 			}
2915 		}
2916 
2917 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2918 			if (xoap->xoa_immutable !=
2919 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2920 				need_policy = TRUE;
2921 			} else {
2922 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2923 				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2924 			}
2925 		}
2926 
2927 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2928 			if (xoap->xoa_nodump !=
2929 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2930 				need_policy = TRUE;
2931 			} else {
2932 				XVA_CLR_REQ(xvap, XAT_NODUMP);
2933 				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
2934 			}
2935 		}
2936 
2937 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2938 			if (xoap->xoa_av_modified !=
2939 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2940 				need_policy = TRUE;
2941 			} else {
2942 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2943 				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
2944 			}
2945 		}
2946 
2947 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2948 			if ((vp->v_type != VREG &&
2949 			    xoap->xoa_av_quarantined) ||
2950 			    xoap->xoa_av_quarantined !=
2951 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2952 				need_policy = TRUE;
2953 			} else {
2954 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2955 				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
2956 			}
2957 		}
2958 
2959 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2960 			mutex_exit(&zp->z_lock);
2961 			ZFS_EXIT(zfsvfs);
2962 			return (SET_ERROR(EPERM));
2963 		}
2964 
2965 		if (need_policy == FALSE &&
2966 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2967 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2968 			need_policy = TRUE;
2969 		}
2970 	}
2971 
2972 	mutex_exit(&zp->z_lock);
2973 
2974 	if (mask & AT_MODE) {
2975 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
2976 			err = secpolicy_setid_setsticky_clear(vp, vap,
2977 			    &oldva, cr);
2978 			if (err) {
2979 				ZFS_EXIT(zfsvfs);
2980 				return (err);
2981 			}
2982 			trim_mask |= AT_MODE;
2983 		} else {
2984 			need_policy = TRUE;
2985 		}
2986 	}
2987 
2988 	if (need_policy) {
2989 		/*
2990 		 * If trim_mask is set then take ownership
2991 		 * has been granted or write_acl is present and user
2992 		 * has the ability to modify mode.  In that case remove
2993 		 * UID|GID and or MODE from mask so that
2994 		 * secpolicy_vnode_setattr() doesn't revoke it.
2995 		 */
2996 
2997 		if (trim_mask) {
2998 			saved_mask = vap->va_mask;
2999 			vap->va_mask &= ~trim_mask;
3000 		}
3001 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
3002 		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
3003 		if (err) {
3004 			ZFS_EXIT(zfsvfs);
3005 			return (err);
3006 		}
3007 
3008 		if (trim_mask)
3009 			vap->va_mask |= saved_mask;
3010 	}
3011 
3012 	/*
3013 	 * secpolicy_vnode_setattr, or take ownership may have
3014 	 * changed va_mask
3015 	 */
3016 	mask = vap->va_mask;
3017 
3018 	if ((mask & (AT_UID | AT_GID))) {
3019 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
3020 		    &xattr_obj, sizeof (xattr_obj));
3021 
3022 		if (err == 0 && xattr_obj) {
3023 			err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
3024 			if (err)
3025 				goto out2;
3026 		}
3027 		if (mask & AT_UID) {
3028 			new_uid = zfs_fuid_create(zfsvfs,
3029 			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3030 			if (new_uid != zp->z_uid &&
3031 			    zfs_fuid_overquota(zfsvfs, B_FALSE, new_uid)) {
3032 				if (attrzp)
3033 					VN_RELE(ZTOV(attrzp));
3034 				err = SET_ERROR(EDQUOT);
3035 				goto out2;
3036 			}
3037 		}
3038 
3039 		if (mask & AT_GID) {
3040 			new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3041 			    cr, ZFS_GROUP, &fuidp);
3042 			if (new_gid != zp->z_gid &&
3043 			    zfs_fuid_overquota(zfsvfs, B_TRUE, new_gid)) {
3044 				if (attrzp)
3045 					VN_RELE(ZTOV(attrzp));
3046 				err = SET_ERROR(EDQUOT);
3047 				goto out2;
3048 			}
3049 		}
3050 	}
3051 	tx = dmu_tx_create(zfsvfs->z_os);
3052 
3053 	if (mask & AT_MODE) {
3054 		uint64_t pmode = zp->z_mode;
3055 		uint64_t acl_obj;
3056 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3057 
3058 		if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
3059 		    !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
3060 			err = SET_ERROR(EPERM);
3061 			goto out;
3062 		}
3063 
3064 		if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3065 			goto out;
3066 
3067 		mutex_enter(&zp->z_lock);
3068 		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
3069 			/*
3070 			 * Are we upgrading ACL from old V0 format
3071 			 * to V1 format?
3072 			 */
3073 			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
3074 			    zfs_znode_acl_version(zp) ==
3075 			    ZFS_ACL_VERSION_INITIAL) {
3076 				dmu_tx_hold_free(tx, acl_obj, 0,
3077 				    DMU_OBJECT_END);
3078 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3079 				    0, aclp->z_acl_bytes);
3080 			} else {
3081 				dmu_tx_hold_write(tx, acl_obj, 0,
3082 				    aclp->z_acl_bytes);
3083 			}
3084 		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3085 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3086 			    0, aclp->z_acl_bytes);
3087 		}
3088 		mutex_exit(&zp->z_lock);
3089 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3090 	} else {
3091 		if ((mask & AT_XVATTR) &&
3092 		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3093 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3094 		else
3095 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3096 	}
3097 
3098 	if (attrzp) {
3099 		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
3100 	}
3101 
3102 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3103 	if (fuid_dirtied)
3104 		zfs_fuid_txhold(zfsvfs, tx);
3105 
3106 	zfs_sa_upgrade_txholds(tx, zp);
3107 
3108 	err = dmu_tx_assign(tx, TXG_WAIT);
3109 	if (err)
3110 		goto out;
3111 
3112 	count = 0;
3113 	/*
3114 	 * Set each attribute requested.
3115 	 * We group settings according to the locks they need to acquire.
3116 	 *
3117 	 * Note: you cannot set ctime directly, although it will be
3118 	 * updated as a side-effect of calling this function.
3119 	 */
3120 
3121 
3122 	if (mask & (AT_UID|AT_GID|AT_MODE))
3123 		mutex_enter(&zp->z_acl_lock);
3124 	mutex_enter(&zp->z_lock);
3125 
3126 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3127 	    &zp->z_pflags, sizeof (zp->z_pflags));
3128 
3129 	if (attrzp) {
3130 		if (mask & (AT_UID|AT_GID|AT_MODE))
3131 			mutex_enter(&attrzp->z_acl_lock);
3132 		mutex_enter(&attrzp->z_lock);
3133 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3134 		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
3135 		    sizeof (attrzp->z_pflags));
3136 	}
3137 
3138 	if (mask & (AT_UID|AT_GID)) {
3139 
3140 		if (mask & AT_UID) {
3141 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
3142 			    &new_uid, sizeof (new_uid));
3143 			zp->z_uid = new_uid;
3144 			if (attrzp) {
3145 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3146 				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
3147 				    sizeof (new_uid));
3148 				attrzp->z_uid = new_uid;
3149 			}
3150 		}
3151 
3152 		if (mask & AT_GID) {
3153 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
3154 			    NULL, &new_gid, sizeof (new_gid));
3155 			zp->z_gid = new_gid;
3156 			if (attrzp) {
3157 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3158 				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
3159 				    sizeof (new_gid));
3160 				attrzp->z_gid = new_gid;
3161 			}
3162 		}
3163 		if (!(mask & AT_MODE)) {
3164 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
3165 			    NULL, &new_mode, sizeof (new_mode));
3166 			new_mode = zp->z_mode;
3167 		}
3168 		err = zfs_acl_chown_setattr(zp);
3169 		ASSERT(err == 0);
3170 		if (attrzp) {
3171 			err = zfs_acl_chown_setattr(attrzp);
3172 			ASSERT(err == 0);
3173 		}
3174 	}
3175 
3176 	if (mask & AT_MODE) {
3177 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
3178 		    &new_mode, sizeof (new_mode));
3179 		zp->z_mode = new_mode;
3180 		ASSERT3U((uintptr_t)aclp, !=, NULL);
3181 		err = zfs_aclset_common(zp, aclp, cr, tx);
3182 		ASSERT0(err);
3183 		if (zp->z_acl_cached)
3184 			zfs_acl_free(zp->z_acl_cached);
3185 		zp->z_acl_cached = aclp;
3186 		aclp = NULL;
3187 	}
3188 
3189 
3190 	if (mask & AT_ATIME) {
3191 		ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
3192 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
3193 		    &zp->z_atime, sizeof (zp->z_atime));
3194 	}
3195 
3196 	if (mask & AT_MTIME) {
3197 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3198 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3199 		    mtime, sizeof (mtime));
3200 	}
3201 
3202 	/* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3203 	if (mask & AT_SIZE && !(mask & AT_MTIME)) {
3204 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
3205 		    NULL, mtime, sizeof (mtime));
3206 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3207 		    &ctime, sizeof (ctime));
3208 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3209 		    B_TRUE);
3210 	} else if (mask != 0) {
3211 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3212 		    &ctime, sizeof (ctime));
3213 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
3214 		    B_TRUE);
3215 		if (attrzp) {
3216 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3217 			    SA_ZPL_CTIME(zfsvfs), NULL,
3218 			    &ctime, sizeof (ctime));
3219 			zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3220 			    mtime, ctime, B_TRUE);
3221 		}
3222 	}
3223 	/*
3224 	 * Do this after setting timestamps to prevent timestamp
3225 	 * update from toggling bit
3226 	 */
3227 
3228 	if (xoap && (mask & AT_XVATTR)) {
3229 
3230 		/*
3231 		 * restore trimmed off masks
3232 		 * so that return masks can be set for caller.
3233 		 */
3234 
3235 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3236 			XVA_SET_REQ(xvap, XAT_APPENDONLY);
3237 		}
3238 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3239 			XVA_SET_REQ(xvap, XAT_NOUNLINK);
3240 		}
3241 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3242 			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3243 		}
3244 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3245 			XVA_SET_REQ(xvap, XAT_NODUMP);
3246 		}
3247 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3248 			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3249 		}
3250 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3251 			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3252 		}
3253 
3254 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3255 			ASSERT(vp->v_type == VREG);
3256 
3257 		zfs_xvattr_set(zp, xvap, tx);
3258 	}
3259 
3260 	if (fuid_dirtied)
3261 		zfs_fuid_sync(zfsvfs, tx);
3262 
3263 	if (mask != 0)
3264 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3265 
3266 	mutex_exit(&zp->z_lock);
3267 	if (mask & (AT_UID|AT_GID|AT_MODE))
3268 		mutex_exit(&zp->z_acl_lock);
3269 
3270 	if (attrzp) {
3271 		if (mask & (AT_UID|AT_GID|AT_MODE))
3272 			mutex_exit(&attrzp->z_acl_lock);
3273 		mutex_exit(&attrzp->z_lock);
3274 	}
3275 out:
3276 	if (err == 0 && attrzp) {
3277 		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3278 		    xattr_count, tx);
3279 		ASSERT(err2 == 0);
3280 	}
3281 
3282 	if (attrzp)
3283 		VN_RELE(ZTOV(attrzp));
3284 
3285 	if (aclp)
3286 		zfs_acl_free(aclp);
3287 
3288 	if (fuidp) {
3289 		zfs_fuid_info_free(fuidp);
3290 		fuidp = NULL;
3291 	}
3292 
3293 	if (err) {
3294 		dmu_tx_abort(tx);
3295 		if (err == ERESTART)
3296 			goto top;
3297 	} else {
3298 		err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3299 		rw_enter(&rz_zev_rwlock, RW_READER);
3300 		if (rz_zev_callbacks && rz_zev_callbacks->rz_zev_znode_setattr)
3301 			rz_zev_callbacks->rz_zev_znode_setattr(zp, tx);
3302 		rw_exit(&rz_zev_rwlock);
3303 		dmu_tx_commit(tx);
3304 	}
3305 
3306 out2:
3307 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3308 		zil_commit(zilog, 0);
3309 
3310 	ZFS_EXIT(zfsvfs);
3311 	return (err);
3312 }
3313 
3314 typedef struct zfs_zlock {
3315 	krwlock_t	*zl_rwlock;	/* lock we acquired */
3316 	znode_t		*zl_znode;	/* znode we held */
3317 	struct zfs_zlock *zl_next;	/* next in list */
3318 } zfs_zlock_t;
3319 
3320 /*
3321  * Drop locks and release vnodes that were held by zfs_rename_lock().
3322  */
3323 static void
3324 zfs_rename_unlock(zfs_zlock_t **zlpp)
3325 {
3326 	zfs_zlock_t *zl;
3327 
3328 	while ((zl = *zlpp) != NULL) {
3329 		if (zl->zl_znode != NULL)
3330 			VN_RELE(ZTOV(zl->zl_znode));
3331 		rw_exit(zl->zl_rwlock);
3332 		*zlpp = zl->zl_next;
3333 		kmem_free(zl, sizeof (*zl));
3334 	}
3335 }
3336 
3337 /*
3338  * Search back through the directory tree, using the ".." entries.
3339  * Lock each directory in the chain to prevent concurrent renames.
3340  * Fail any attempt to move a directory into one of its own descendants.
3341  * XXX - z_parent_lock can overlap with map or grow locks
3342  */
3343 static int
3344 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3345 {
3346 	zfs_zlock_t	*zl;
3347 	znode_t		*zp = tdzp;
3348 	uint64_t	rootid = zp->z_zfsvfs->z_root;
3349 	uint64_t	oidp = zp->z_id;
3350 	krwlock_t	*rwlp = &szp->z_parent_lock;
3351 	krw_t		rw = RW_WRITER;
3352 
3353 	/*
3354 	 * First pass write-locks szp and compares to zp->z_id.
3355 	 * Later passes read-lock zp and compare to zp->z_parent.
3356 	 */
3357 	do {
3358 		if (!rw_tryenter(rwlp, rw)) {
3359 			/*
3360 			 * Another thread is renaming in this path.
3361 			 * Note that if we are a WRITER, we don't have any
3362 			 * parent_locks held yet.
3363 			 */
3364 			if (rw == RW_READER && zp->z_id > szp->z_id) {
3365 				/*
3366 				 * Drop our locks and restart
3367 				 */
3368 				zfs_rename_unlock(&zl);
3369 				*zlpp = NULL;
3370 				zp = tdzp;
3371 				oidp = zp->z_id;
3372 				rwlp = &szp->z_parent_lock;
3373 				rw = RW_WRITER;
3374 				continue;
3375 			} else {
3376 				/*
3377 				 * Wait for other thread to drop its locks
3378 				 */
3379 				rw_enter(rwlp, rw);
3380 			}
3381 		}
3382 
3383 		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3384 		zl->zl_rwlock = rwlp;
3385 		zl->zl_znode = NULL;
3386 		zl->zl_next = *zlpp;
3387 		*zlpp = zl;
3388 
3389 		if (oidp == szp->z_id)		/* We're a descendant of szp */
3390 			return (SET_ERROR(EINVAL));
3391 
3392 		if (oidp == rootid)		/* We've hit the top */
3393 			return (0);
3394 
3395 		if (rw == RW_READER) {		/* i.e. not the first pass */
3396 			int error = zfs_zget(zp->z_zfsvfs, oidp, &zp);
3397 			if (error)
3398 				return (error);
3399 			zl->zl_znode = zp;
3400 		}
3401 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zp->z_zfsvfs),
3402 		    &oidp, sizeof (oidp));
3403 		rwlp = &zp->z_parent_lock;
3404 		rw = RW_READER;
3405 
3406 	} while (zp->z_id != sdzp->z_id);
3407 
3408 	return (0);
3409 }
3410 
3411 /*
3412  * Move an entry from the provided source directory to the target
3413  * directory.  Change the entry name as indicated.
3414  *
3415  *	IN:	sdvp	- Source directory containing the "old entry".
3416  *		snm	- Old entry name.
3417  *		tdvp	- Target directory to contain the "new entry".
3418  *		tnm	- New entry name.
3419  *		cr	- credentials of caller.
3420  *		ct	- caller context
3421  *		flags	- case flags
3422  *
3423  *	RETURN:	0 on success, error code on failure.
3424  *
3425  * Timestamps:
3426  *	sdvp,tdvp - ctime|mtime updated
3427  */
3428 /*ARGSUSED*/
3429 static int
3430 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
3431     caller_context_t *ct, int flags)
3432 {
3433 	znode_t		*tdzp, *szp, *tzp;
3434 	znode_t		*sdzp = VTOZ(sdvp);
3435 	zfsvfs_t	*zfsvfs = sdzp->z_zfsvfs;
3436 	zilog_t		*zilog;
3437 	vnode_t		*realvp;
3438 	zfs_dirlock_t	*sdl, *tdl;
3439 	dmu_tx_t	*tx;
3440 	zfs_zlock_t	*zl;
3441 	int		cmp, serr, terr;
3442 	int		error = 0;
3443 	int		zflg = 0;
3444 	boolean_t	waited = B_FALSE;
3445 
3446 	ZFS_ENTER(zfsvfs);
3447 	ZFS_VERIFY_ZP(sdzp);
3448 	zilog = zfsvfs->z_log;
3449 
3450 	/*
3451 	 * Make sure we have the real vp for the target directory.
3452 	 */
3453 	if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3454 		tdvp = realvp;
3455 
3456 	tdzp = VTOZ(tdvp);
3457 	ZFS_VERIFY_ZP(tdzp);
3458 
3459 	/*
3460 	 * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
3461 	 * ctldir appear to have the same v_vfsp.
3462 	 */
3463 	if (tdzp->z_zfsvfs != zfsvfs || zfsctl_is_node(tdvp)) {
3464 		ZFS_EXIT(zfsvfs);
3465 		return (SET_ERROR(EXDEV));
3466 	}
3467 
3468 	if (zfsvfs->z_utf8 && u8_validate(tnm,
3469 	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3470 		ZFS_EXIT(zfsvfs);
3471 		return (SET_ERROR(EILSEQ));
3472 	}
3473 
3474 	if (flags & FIGNORECASE)
3475 		zflg |= ZCILOOK;
3476 
3477 top:
3478 	szp = NULL;
3479 	tzp = NULL;
3480 	zl = NULL;
3481 
3482 	/*
3483 	 * This is to prevent the creation of links into attribute space
3484 	 * by renaming a linked file into/outof an attribute directory.
3485 	 * See the comment in zfs_link() for why this is considered bad.
3486 	 */
3487 	if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3488 		ZFS_EXIT(zfsvfs);
3489 		return (SET_ERROR(EINVAL));
3490 	}
3491 
3492 	/*
3493 	 * Lock source and target directory entries.  To prevent deadlock,
3494 	 * a lock ordering must be defined.  We lock the directory with
3495 	 * the smallest object id first, or if it's a tie, the one with
3496 	 * the lexically first name.
3497 	 */
3498 	if (sdzp->z_id < tdzp->z_id) {
3499 		cmp = -1;
3500 	} else if (sdzp->z_id > tdzp->z_id) {
3501 		cmp = 1;
3502 	} else {
3503 		/*
3504 		 * First compare the two name arguments without
3505 		 * considering any case folding.
3506 		 */
3507 		int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
3508 
3509 		cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3510 		ASSERT(error == 0 || !zfsvfs->z_utf8);
3511 		if (cmp == 0) {
3512 			/*
3513 			 * POSIX: "If the old argument and the new argument
3514 			 * both refer to links to the same existing file,
3515 			 * the rename() function shall return successfully
3516 			 * and perform no other action."
3517 			 */
3518 			ZFS_EXIT(zfsvfs);
3519 			return (0);
3520 		}
3521 		/*
3522 		 * If the file system is case-folding, then we may
3523 		 * have some more checking to do.  A case-folding file
3524 		 * system is either supporting mixed case sensitivity
3525 		 * access or is completely case-insensitive.  Note
3526 		 * that the file system is always case preserving.
3527 		 *
3528 		 * In mixed sensitivity mode case sensitive behavior
3529 		 * is the default.  FIGNORECASE must be used to
3530 		 * explicitly request case insensitive behavior.
3531 		 *
3532 		 * If the source and target names provided differ only
3533 		 * by case (e.g., a request to rename 'tim' to 'Tim'),
3534 		 * we will treat this as a special case in the
3535 		 * case-insensitive mode: as long as the source name
3536 		 * is an exact match, we will allow this to proceed as
3537 		 * a name-change request.
3538 		 */
3539 		if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
3540 		    (zfsvfs->z_case == ZFS_CASE_MIXED &&
3541 		    flags & FIGNORECASE)) &&
3542 		    u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
3543 		    &error) == 0) {
3544 			/*
3545 			 * case preserving rename request, require exact
3546 			 * name matches
3547 			 */
3548 			zflg |= ZCIEXACT;
3549 			zflg &= ~ZCILOOK;
3550 		}
3551 	}
3552 
3553 	/*
3554 	 * If the source and destination directories are the same, we should
3555 	 * grab the z_name_lock of that directory only once.
3556 	 */
3557 	if (sdzp == tdzp) {
3558 		zflg |= ZHAVELOCK;
3559 		rw_enter(&sdzp->z_name_lock, RW_READER);
3560 	}
3561 
3562 	if (cmp < 0) {
3563 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3564 		    ZEXISTS | zflg, NULL, NULL);
3565 		terr = zfs_dirent_lock(&tdl,
3566 		    tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3567 	} else {
3568 		terr = zfs_dirent_lock(&tdl,
3569 		    tdzp, tnm, &tzp, zflg, NULL, NULL);
3570 		serr = zfs_dirent_lock(&sdl,
3571 		    sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3572 		    NULL, NULL);
3573 	}
3574 
3575 	if (serr) {
3576 		/*
3577 		 * Source entry invalid or not there.
3578 		 */
3579 		if (!terr) {
3580 			zfs_dirent_unlock(tdl);
3581 			if (tzp)
3582 				VN_RELE(ZTOV(tzp));
3583 		}
3584 
3585 		if (sdzp == tdzp)
3586 			rw_exit(&sdzp->z_name_lock);
3587 
3588 		if (strcmp(snm, "..") == 0)
3589 			serr = SET_ERROR(EINVAL);
3590 		ZFS_EXIT(zfsvfs);
3591 		return (serr);
3592 	}
3593 	if (terr) {
3594 		zfs_dirent_unlock(sdl);
3595 		VN_RELE(ZTOV(szp));
3596 
3597 		if (sdzp == tdzp)
3598 			rw_exit(&sdzp->z_name_lock);
3599 
3600 		if (strcmp(tnm, "..") == 0)
3601 			terr = SET_ERROR(EINVAL);
3602 		ZFS_EXIT(zfsvfs);
3603 		return (terr);
3604 	}
3605 
3606 	/*
3607 	 * Must have write access at the source to remove the old entry
3608 	 * and write access at the target to create the new entry.
3609 	 * Note that if target and source are the same, this can be
3610 	 * done in a single check.
3611 	 */
3612 
3613 	if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
3614 		goto out;
3615 
3616 	if (ZTOV(szp)->v_type == VDIR) {
3617 		/*
3618 		 * Check to make sure rename is valid.
3619 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3620 		 */
3621 		if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
3622 			goto out;
3623 	}
3624 
3625 	/*
3626 	 * Does target exist?
3627 	 */
3628 	if (tzp) {
3629 		/*
3630 		 * Source and target must be the same type.
3631 		 */
3632 		if (ZTOV(szp)->v_type == VDIR) {
3633 			if (ZTOV(tzp)->v_type != VDIR) {
3634 				error = SET_ERROR(ENOTDIR);
3635 				goto out;
3636 			}
3637 		} else {
3638 			if (ZTOV(tzp)->v_type == VDIR) {
3639 				error = SET_ERROR(EISDIR);
3640 				goto out;
3641 			}
3642 		}
3643 		/*
3644 		 * POSIX dictates that when the source and target
3645 		 * entries refer to the same file object, rename
3646 		 * must do nothing and exit without error.
3647 		 */
3648 		if (szp->z_id == tzp->z_id) {
3649 			error = 0;
3650 			goto out;
3651 		}
3652 	}
3653 
3654 	vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
3655 	if (tzp)
3656 		vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3657 
3658 	/*
3659 	 * notify the target directory if it is not the same
3660 	 * as source directory.
3661 	 */
3662 	if (tdvp != sdvp) {
3663 		vnevent_rename_dest_dir(tdvp, ct);
3664 	}
3665 
3666 	tx = dmu_tx_create(zfsvfs->z_os);
3667 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3668 	dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3669 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3670 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3671 	if (sdzp != tdzp) {
3672 		dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3673 		zfs_sa_upgrade_txholds(tx, tdzp);
3674 	}
3675 	if (tzp) {
3676 		dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3677 		zfs_sa_upgrade_txholds(tx, tzp);
3678 	}
3679 
3680 	zfs_sa_upgrade_txholds(tx, szp);
3681 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3682 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
3683 	if (error) {
3684 		if (zl != NULL)
3685 			zfs_rename_unlock(&zl);
3686 		zfs_dirent_unlock(sdl);
3687 		zfs_dirent_unlock(tdl);
3688 
3689 		if (sdzp == tdzp)
3690 			rw_exit(&sdzp->z_name_lock);
3691 
3692 		VN_RELE(ZTOV(szp));
3693 		if (tzp)
3694 			VN_RELE(ZTOV(tzp));
3695 		if (error == ERESTART) {
3696 			waited = B_TRUE;
3697 			dmu_tx_wait(tx);
3698 			dmu_tx_abort(tx);
3699 			goto top;
3700 		}
3701 		dmu_tx_abort(tx);
3702 		ZFS_EXIT(zfsvfs);
3703 		return (error);
3704 	}
3705 
3706 	if (tzp)	/* Attempt to remove the existing target */
3707 		error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3708 
3709 	if (error == 0) {
3710 		error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3711 		if (error == 0) {
3712 			szp->z_pflags |= ZFS_AV_MODIFIED;
3713 
3714 			error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3715 			    (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3716 			ASSERT0(error);
3717 
3718 			error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3719 			if (error == 0) {
3720 				zfs_log_rename(zilog, tx, TX_RENAME |
3721 				    (flags & FIGNORECASE ? TX_CI : 0), sdzp,
3722 				    sdl->dl_name, tdzp, tdl->dl_name, szp, tzp);
3723 
3724 				/*
3725 				 * Update path information for the target vnode
3726 				 */
3727 				vn_renamepath(tdvp, ZTOV(szp), tnm,
3728 				    strlen(tnm));
3729 			} else {
3730 				/*
3731 				 * At this point, we have successfully created
3732 				 * the target name, but have failed to remove
3733 				 * the source name.  Since the create was done
3734 				 * with the ZRENAMING flag, there are
3735 				 * complications; for one, the link count is
3736 				 * wrong.  The easiest way to deal with this
3737 				 * is to remove the newly created target, and
3738 				 * return the original error.  This must
3739 				 * succeed; fortunately, it is very unlikely to
3740 				 * fail, since we just created it.
3741 				 */
3742 				VERIFY3U(zfs_link_destroy(tdl, szp, tx,
3743 				    ZRENAMING, NULL), ==, 0);
3744 			}
3745 		}
3746 	}
3747 
3748 	dmu_tx_commit(tx);
3749 out:
3750 	if (zl != NULL)
3751 		zfs_rename_unlock(&zl);
3752 
3753 	zfs_dirent_unlock(sdl);
3754 	zfs_dirent_unlock(tdl);
3755 
3756 	if (sdzp == tdzp)
3757 		rw_exit(&sdzp->z_name_lock);
3758 
3759 
3760 	VN_RELE(ZTOV(szp));
3761 	if (tzp)
3762 		VN_RELE(ZTOV(tzp));
3763 
3764 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3765 		zil_commit(zilog, 0);
3766 
3767 	ZFS_EXIT(zfsvfs);
3768 	return (error);
3769 }
3770 
3771 /*
3772  * Insert the indicated symbolic reference entry into the directory.
3773  *
3774  *	IN:	dvp	- Directory to contain new symbolic link.
3775  *		link	- Name for new symlink entry.
3776  *		vap	- Attributes of new entry.
3777  *		cr	- credentials of caller.
3778  *		ct	- caller context
3779  *		flags	- case flags
3780  *
3781  *	RETURN:	0 on success, error code on failure.
3782  *
3783  * Timestamps:
3784  *	dvp - ctime|mtime updated
3785  */
3786 /*ARGSUSED*/
3787 static int
3788 zfs_symlink(vnode_t *dvp, char *name, vattr_t *vap, char *link, cred_t *cr,
3789     caller_context_t *ct, int flags)
3790 {
3791 	znode_t		*zp, *dzp = VTOZ(dvp);
3792 	zfs_dirlock_t	*dl;
3793 	dmu_tx_t	*tx;
3794 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3795 	zilog_t		*zilog;
3796 	uint64_t	len = strlen(link);
3797 	int		error;
3798 	int		zflg = ZNEW;
3799 	zfs_acl_ids_t	acl_ids;
3800 	boolean_t	fuid_dirtied;
3801 	uint64_t	txtype = TX_SYMLINK;
3802 	boolean_t	waited = B_FALSE;
3803 
3804 	ASSERT(vap->va_type == VLNK);
3805 
3806 	ZFS_ENTER(zfsvfs);
3807 	ZFS_VERIFY_ZP(dzp);
3808 	zilog = zfsvfs->z_log;
3809 
3810 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3811 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3812 		ZFS_EXIT(zfsvfs);
3813 		return (SET_ERROR(EILSEQ));
3814 	}
3815 	if (flags & FIGNORECASE)
3816 		zflg |= ZCILOOK;
3817 
3818 	if (len > MAXPATHLEN) {
3819 		ZFS_EXIT(zfsvfs);
3820 		return (SET_ERROR(ENAMETOOLONG));
3821 	}
3822 
3823 	if ((error = zfs_acl_ids_create(dzp, 0,
3824 	    vap, cr, NULL, &acl_ids)) != 0) {
3825 		ZFS_EXIT(zfsvfs);
3826 		return (error);
3827 	}
3828 top:
3829 	/*
3830 	 * Attempt to lock directory; fail if entry already exists.
3831 	 */
3832 	error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3833 	if (error) {
3834 		zfs_acl_ids_free(&acl_ids);
3835 		ZFS_EXIT(zfsvfs);
3836 		return (error);
3837 	}
3838 
3839 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
3840 		zfs_acl_ids_free(&acl_ids);
3841 		zfs_dirent_unlock(dl);
3842 		ZFS_EXIT(zfsvfs);
3843 		return (error);
3844 	}
3845 
3846 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
3847 		zfs_acl_ids_free(&acl_ids);
3848 		zfs_dirent_unlock(dl);
3849 		ZFS_EXIT(zfsvfs);
3850 		return (SET_ERROR(EDQUOT));
3851 	}
3852 	tx = dmu_tx_create(zfsvfs->z_os);
3853 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3854 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3855 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3856 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3857 	    ZFS_SA_BASE_ATTR_SIZE + len);
3858 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
3859 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3860 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3861 		    acl_ids.z_aclp->z_acl_bytes);
3862 	}
3863 	if (fuid_dirtied)
3864 		zfs_fuid_txhold(zfsvfs, tx);
3865 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
3866 	if (error) {
3867 		zfs_dirent_unlock(dl);
3868 		if (error == ERESTART) {
3869 			waited = B_TRUE;
3870 			dmu_tx_wait(tx);
3871 			dmu_tx_abort(tx);
3872 			goto top;
3873 		}
3874 		zfs_acl_ids_free(&acl_ids);
3875 		dmu_tx_abort(tx);
3876 		ZFS_EXIT(zfsvfs);
3877 		return (error);
3878 	}
3879 
3880 	/*
3881 	 * Create a new object for the symlink.
3882 	 * for version 4 ZPL datsets the symlink will be an SA attribute
3883 	 */
3884 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3885 
3886 	if (fuid_dirtied)
3887 		zfs_fuid_sync(zfsvfs, tx);
3888 
3889 	mutex_enter(&zp->z_lock);
3890 	if (zp->z_is_sa)
3891 		error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
3892 		    link, len, tx);
3893 	else
3894 		zfs_sa_symlink(zp, link, len, tx);
3895 	mutex_exit(&zp->z_lock);
3896 
3897 	zp->z_size = len;
3898 	(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
3899 	    &zp->z_size, sizeof (zp->z_size), tx);
3900 	/*
3901 	 * Insert the new object into the directory.
3902 	 */
3903 	(void) zfs_link_create(dl, zp, tx, ZNEW);
3904 
3905 	if (flags & FIGNORECASE)
3906 		txtype |= TX_CI;
3907 	zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3908 
3909 	zfs_acl_ids_free(&acl_ids);
3910 
3911 	dmu_tx_commit(tx);
3912 
3913 	zfs_dirent_unlock(dl);
3914 
3915 	VN_RELE(ZTOV(zp));
3916 
3917 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3918 		zil_commit(zilog, 0);
3919 
3920 	ZFS_EXIT(zfsvfs);
3921 	return (error);
3922 }
3923 
3924 /*
3925  * Return, in the buffer contained in the provided uio structure,
3926  * the symbolic path referred to by vp.
3927  *
3928  *	IN:	vp	- vnode of symbolic link.
3929  *		uio	- structure to contain the link path.
3930  *		cr	- credentials of caller.
3931  *		ct	- caller context
3932  *
3933  *	OUT:	uio	- structure containing the link path.
3934  *
3935  *	RETURN:	0 on success, error code on failure.
3936  *
3937  * Timestamps:
3938  *	vp - atime updated
3939  */
3940 /* ARGSUSED */
3941 static int
3942 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
3943 {
3944 	znode_t		*zp = VTOZ(vp);
3945 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3946 	int		error;
3947 
3948 	ZFS_ENTER(zfsvfs);
3949 	ZFS_VERIFY_ZP(zp);
3950 
3951 	mutex_enter(&zp->z_lock);
3952 	if (zp->z_is_sa)
3953 		error = sa_lookup_uio(zp->z_sa_hdl,
3954 		    SA_ZPL_SYMLINK(zfsvfs), uio);
3955 	else
3956 		error = zfs_sa_readlink(zp, uio);
3957 	mutex_exit(&zp->z_lock);
3958 
3959 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3960 
3961 	ZFS_EXIT(zfsvfs);
3962 	return (error);
3963 }
3964 
3965 /*
3966  * Insert a new entry into directory tdvp referencing svp.
3967  *
3968  *	IN:	tdvp	- Directory to contain new entry.
3969  *		svp	- vnode of new entry.
3970  *		name	- name of new entry.
3971  *		cr	- credentials of caller.
3972  *		ct	- caller context
3973  *
3974  *	RETURN:	0 on success, error code on failure.
3975  *
3976  * Timestamps:
3977  *	tdvp - ctime|mtime updated
3978  *	 svp - ctime updated
3979  */
3980 /* ARGSUSED */
3981 static int
3982 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
3983     caller_context_t *ct, int flags)
3984 {
3985 	znode_t		*dzp = VTOZ(tdvp);
3986 	znode_t		*tzp, *szp;
3987 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3988 	zilog_t		*zilog;
3989 	zfs_dirlock_t	*dl;
3990 	dmu_tx_t	*tx;
3991 	vnode_t		*realvp;
3992 	int		error;
3993 	int		zf = ZNEW;
3994 	uint64_t	parent;
3995 	uid_t		owner;
3996 	boolean_t	waited = B_FALSE;
3997 
3998 	ASSERT(tdvp->v_type == VDIR);
3999 
4000 	ZFS_ENTER(zfsvfs);
4001 	ZFS_VERIFY_ZP(dzp);
4002 	zilog = zfsvfs->z_log;
4003 
4004 	if (VOP_REALVP(svp, &realvp, ct) == 0)
4005 		svp = realvp;
4006 
4007 	/*
4008 	 * POSIX dictates that we return EPERM here.
4009 	 * Better choices include ENOTSUP or EISDIR.
4010 	 */
4011 	if (svp->v_type == VDIR) {
4012 		ZFS_EXIT(zfsvfs);
4013 		return (SET_ERROR(EPERM));
4014 	}
4015 
4016 	szp = VTOZ(svp);
4017 	ZFS_VERIFY_ZP(szp);
4018 
4019 	/*
4020 	 * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
4021 	 * ctldir appear to have the same v_vfsp.
4022 	 */
4023 	if (szp->z_zfsvfs != zfsvfs || zfsctl_is_node(svp)) {
4024 		ZFS_EXIT(zfsvfs);
4025 		return (SET_ERROR(EXDEV));
4026 	}
4027 
4028 	/* Prevent links to .zfs/shares files */
4029 
4030 	if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
4031 	    &parent, sizeof (uint64_t))) != 0) {
4032 		ZFS_EXIT(zfsvfs);
4033 		return (error);
4034 	}
4035 	if (parent == zfsvfs->z_shares_dir) {
4036 		ZFS_EXIT(zfsvfs);
4037 		return (SET_ERROR(EPERM));
4038 	}
4039 
4040 	if (zfsvfs->z_utf8 && u8_validate(name,
4041 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4042 		ZFS_EXIT(zfsvfs);
4043 		return (SET_ERROR(EILSEQ));
4044 	}
4045 	if (flags & FIGNORECASE)
4046 		zf |= ZCILOOK;
4047 
4048 	/*
4049 	 * We do not support links between attributes and non-attributes
4050 	 * because of the potential security risk of creating links
4051 	 * into "normal" file space in order to circumvent restrictions
4052 	 * imposed in attribute space.
4053 	 */
4054 	if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
4055 		ZFS_EXIT(zfsvfs);
4056 		return (SET_ERROR(EINVAL));
4057 	}
4058 
4059 
4060 	owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
4061 	if (owner != crgetuid(cr) && secpolicy_basic_link(cr) != 0) {
4062 		ZFS_EXIT(zfsvfs);
4063 		return (SET_ERROR(EPERM));
4064 	}
4065 
4066 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4067 		ZFS_EXIT(zfsvfs);
4068 		return (error);
4069 	}
4070 
4071 top:
4072 	/*
4073 	 * Attempt to lock directory; fail if entry already exists.
4074 	 */
4075 	error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
4076 	if (error) {
4077 		ZFS_EXIT(zfsvfs);
4078 		return (error);
4079 	}
4080 
4081 	tx = dmu_tx_create(zfsvfs->z_os);
4082 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
4083 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4084 	zfs_sa_upgrade_txholds(tx, szp);
4085 	zfs_sa_upgrade_txholds(tx, dzp);
4086 	error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
4087 	if (error) {
4088 		zfs_dirent_unlock(dl);
4089 		if (error == ERESTART) {
4090 			waited = B_TRUE;
4091 			dmu_tx_wait(tx);
4092 			dmu_tx_abort(tx);
4093 			goto top;
4094 		}
4095 		dmu_tx_abort(tx);
4096 		ZFS_EXIT(zfsvfs);
4097 		return (error);
4098 	}
4099 
4100 	error = zfs_link_create(dl, szp, tx, 0);
4101 
4102 	if (error == 0) {
4103 		uint64_t txtype = TX_LINK;
4104 		if (flags & FIGNORECASE)
4105 			txtype |= TX_CI;
4106 		zfs_log_link(zilog, tx, txtype, dzp, szp, name);
4107 	}
4108 
4109 	dmu_tx_commit(tx);
4110 
4111 	zfs_dirent_unlock(dl);
4112 
4113 	if (error == 0) {
4114 		vnevent_link(svp, ct);
4115 	}
4116 
4117 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4118 		zil_commit(zilog, 0);
4119 
4120 	ZFS_EXIT(zfsvfs);
4121 	return (error);
4122 }
4123 
4124 /*
4125  * zfs_null_putapage() is used when the file system has been force
4126  * unmounted. It just drops the pages.
4127  */
4128 /* ARGSUSED */
4129 static int
4130 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4131 		size_t *lenp, int flags, cred_t *cr)
4132 {
4133 	pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
4134 	return (0);
4135 }
4136 
4137 /*
4138  * Push a page out to disk, klustering if possible.
4139  *
4140  *	IN:	vp	- file to push page to.
4141  *		pp	- page to push.
4142  *		flags	- additional flags.
4143  *		cr	- credentials of caller.
4144  *
4145  *	OUT:	offp	- start of range pushed.
4146  *		lenp	- len of range pushed.
4147  *
4148  *	RETURN:	0 on success, error code on failure.
4149  *
4150  * NOTE: callers must have locked the page to be pushed.  On
4151  * exit, the page (and all other pages in the kluster) must be
4152  * unlocked.
4153  */
4154 /* ARGSUSED */
4155 static int
4156 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4157 		size_t *lenp, int flags, cred_t *cr)
4158 {
4159 	znode_t		*zp = VTOZ(vp);
4160 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4161 	dmu_tx_t	*tx;
4162 	u_offset_t	off, koff;
4163 	size_t		len, klen;
4164 	int		err;
4165 
4166 	off = pp->p_offset;
4167 	len = PAGESIZE;
4168 	/*
4169 	 * If our blocksize is bigger than the page size, try to kluster
4170 	 * multiple pages so that we write a full block (thus avoiding
4171 	 * a read-modify-write).
4172 	 */
4173 	if (off < zp->z_size && zp->z_blksz > PAGESIZE) {
4174 		klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
4175 		koff = ISP2(klen) ? P2ALIGN(off, (u_offset_t)klen) : 0;
4176 		ASSERT(koff <= zp->z_size);
4177 		if (koff + klen > zp->z_size)
4178 			klen = P2ROUNDUP(zp->z_size - koff, (uint64_t)PAGESIZE);
4179 		pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
4180 	}
4181 	ASSERT3U(btop(len), ==, btopr(len));
4182 
4183 	/*
4184 	 * Can't push pages past end-of-file.
4185 	 */
4186 	if (off >= zp->z_size) {
4187 		/* ignore all pages */
4188 		err = 0;
4189 		goto out;
4190 	} else if (off + len > zp->z_size) {
4191 		int npages = btopr(zp->z_size - off);
4192 		page_t *trunc;
4193 
4194 		page_list_break(&pp, &trunc, npages);
4195 		/* ignore pages past end of file */
4196 		if (trunc)
4197 			pvn_write_done(trunc, flags);
4198 		len = zp->z_size - off;
4199 	}
4200 
4201 	if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
4202 	    zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
4203 		err = SET_ERROR(EDQUOT);
4204 		goto out;
4205 	}
4206 	tx = dmu_tx_create(zfsvfs->z_os);
4207 	dmu_tx_hold_write(tx, zp->z_id, off, len);
4208 
4209 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4210 	zfs_sa_upgrade_txholds(tx, zp);
4211 	err = dmu_tx_assign(tx, TXG_WAIT);
4212 	if (err != 0) {
4213 		dmu_tx_abort(tx);
4214 		goto out;
4215 	}
4216 
4217 	if (zp->z_blksz <= PAGESIZE) {
4218 		caddr_t va = zfs_map_page(pp, S_READ);
4219 		ASSERT3U(len, <=, PAGESIZE);
4220 		dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
4221 		zfs_unmap_page(pp, va);
4222 	} else {
4223 		err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
4224 	}
4225 
4226 	if (err == 0) {
4227 		uint64_t mtime[2], ctime[2];
4228 		sa_bulk_attr_t bulk[3];
4229 		int count = 0;
4230 
4231 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4232 		    &mtime, 16);
4233 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4234 		    &ctime, 16);
4235 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4236 		    &zp->z_pflags, 8);
4237 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
4238 		    B_TRUE);
4239 		zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len, 0);
4240 	}
4241 	dmu_tx_commit(tx);
4242 
4243 out:
4244 	pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
4245 	if (offp)
4246 		*offp = off;
4247 	if (lenp)
4248 		*lenp = len;
4249 
4250 	return (err);
4251 }
4252 
4253 /*
4254  * Copy the portion of the file indicated from pages into the file.
4255  * The pages are stored in a page list attached to the files vnode.
4256  *
4257  *	IN:	vp	- vnode of file to push page data to.
4258  *		off	- position in file to put data.
4259  *		len	- amount of data to write.
4260  *		flags	- flags to control the operation.
4261  *		cr	- credentials of caller.
4262  *		ct	- caller context.
4263  *
4264  *	RETURN:	0 on success, error code on failure.
4265  *
4266  * Timestamps:
4267  *	vp - ctime|mtime updated
4268  */
4269 /*ARGSUSED*/
4270 static int
4271 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
4272     caller_context_t *ct)
4273 {
4274 	znode_t		*zp = VTOZ(vp);
4275 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4276 	page_t		*pp;
4277 	size_t		io_len;
4278 	u_offset_t	io_off;
4279 	uint_t		blksz;
4280 	rl_t		*rl;
4281 	int		error = 0;
4282 
4283 	ZFS_ENTER(zfsvfs);
4284 	ZFS_VERIFY_ZP(zp);
4285 
4286 	/*
4287 	 * There's nothing to do if no data is cached.
4288 	 */
4289 	if (!vn_has_cached_data(vp)) {
4290 		ZFS_EXIT(zfsvfs);
4291 		return (0);
4292 	}
4293 
4294 	/*
4295 	 * Align this request to the file block size in case we kluster.
4296 	 * XXX - this can result in pretty aggresive locking, which can
4297 	 * impact simultanious read/write access.  One option might be
4298 	 * to break up long requests (len == 0) into block-by-block
4299 	 * operations to get narrower locking.
4300 	 */
4301 	blksz = zp->z_blksz;
4302 	if (ISP2(blksz))
4303 		io_off = P2ALIGN_TYPED(off, blksz, u_offset_t);
4304 	else
4305 		io_off = 0;
4306 	if (len > 0 && ISP2(blksz))
4307 		io_len = P2ROUNDUP_TYPED(len + (off - io_off), blksz, size_t);
4308 	else
4309 		io_len = 0;
4310 
4311 	if (io_len == 0) {
4312 		/*
4313 		 * Search the entire vp list for pages >= io_off.
4314 		 */
4315 		rl = zfs_range_lock(zp, io_off, UINT64_MAX, RL_WRITER);
4316 		error = pvn_vplist_dirty(vp, io_off, zfs_putapage, flags, cr);
4317 		goto out;
4318 	}
4319 	rl = zfs_range_lock(zp, io_off, io_len, RL_WRITER);
4320 
4321 	if (off > zp->z_size) {
4322 		/* past end of file */
4323 		zfs_range_unlock(rl);
4324 		ZFS_EXIT(zfsvfs);
4325 		return (0);
4326 	}
4327 
4328 	len = MIN(io_len, P2ROUNDUP(zp->z_size, PAGESIZE) - io_off);
4329 
4330 	for (off = io_off; io_off < off + len; io_off += io_len) {
4331 		if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
4332 			pp = page_lookup(vp, io_off,
4333 			    (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
4334 		} else {
4335 			pp = page_lookup_nowait(vp, io_off,
4336 			    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
4337 		}
4338 
4339 		if (pp != NULL && pvn_getdirty(pp, flags)) {
4340 			int err;
4341 
4342 			/*
4343 			 * Found a dirty page to push
4344 			 */
4345 			err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
4346 			if (err)
4347 				error = err;
4348 		} else {
4349 			io_len = PAGESIZE;
4350 		}
4351 	}
4352 out:
4353 	zfs_range_unlock(rl);
4354 	if ((flags & B_ASYNC) == 0 || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4355 		zil_commit(zfsvfs->z_log, zp->z_id);
4356 	ZFS_EXIT(zfsvfs);
4357 	return (error);
4358 }
4359 
4360 /*ARGSUSED*/
4361 void
4362 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4363 {
4364 	znode_t	*zp = VTOZ(vp);
4365 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4366 	int error;
4367 
4368 	rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4369 	if (zp->z_sa_hdl == NULL) {
4370 		/*
4371 		 * The fs has been unmounted, or we did a
4372 		 * suspend/resume and this file no longer exists.
4373 		 */
4374 		if (vn_has_cached_data(vp)) {
4375 			(void) pvn_vplist_dirty(vp, 0, zfs_null_putapage,
4376 			    B_INVAL, cr);
4377 		}
4378 
4379 		mutex_enter(&zp->z_lock);
4380 		mutex_enter(&vp->v_lock);
4381 		ASSERT(vp->v_count == 1);
4382 		vp->v_count = 0;
4383 		mutex_exit(&vp->v_lock);
4384 		mutex_exit(&zp->z_lock);
4385 		rw_exit(&zfsvfs->z_teardown_inactive_lock);
4386 		zfs_znode_free(zp);
4387 		return;
4388 	}
4389 
4390 	/*
4391 	 * Attempt to push any data in the page cache.  If this fails
4392 	 * we will get kicked out later in zfs_zinactive().
4393 	 */
4394 	if (vn_has_cached_data(vp)) {
4395 		(void) pvn_vplist_dirty(vp, 0, zfs_putapage, B_INVAL|B_ASYNC,
4396 		    cr);
4397 	}
4398 
4399 	if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4400 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4401 
4402 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4403 		zfs_sa_upgrade_txholds(tx, zp);
4404 		error = dmu_tx_assign(tx, TXG_WAIT);
4405 		if (error) {
4406 			dmu_tx_abort(tx);
4407 		} else {
4408 			mutex_enter(&zp->z_lock);
4409 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4410 			    (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4411 			zp->z_atime_dirty = 0;
4412 			mutex_exit(&zp->z_lock);
4413 			dmu_tx_commit(tx);
4414 		}
4415 	}
4416 
4417 	zfs_zinactive(zp);
4418 	rw_exit(&zfsvfs->z_teardown_inactive_lock);
4419 }
4420 
4421 /*
4422  * Bounds-check the seek operation.
4423  *
4424  *	IN:	vp	- vnode seeking within
4425  *		ooff	- old file offset
4426  *		noffp	- pointer to new file offset
4427  *		ct	- caller context
4428  *
4429  *	RETURN:	0 on success, EINVAL if new offset invalid.
4430  */
4431 /* ARGSUSED */
4432 static int
4433 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp,
4434     caller_context_t *ct)
4435 {
4436 	if (vp->v_type == VDIR)
4437 		return (0);
4438 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4439 }
4440 
4441 /*
4442  * Pre-filter the generic locking function to trap attempts to place
4443  * a mandatory lock on a memory mapped file.
4444  */
4445 static int
4446 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
4447     flk_callback_t *flk_cbp, cred_t *cr, caller_context_t *ct)
4448 {
4449 	znode_t *zp = VTOZ(vp);
4450 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4451 
4452 	ZFS_ENTER(zfsvfs);
4453 	ZFS_VERIFY_ZP(zp);
4454 
4455 	/*
4456 	 * We are following the UFS semantics with respect to mapcnt
4457 	 * here: If we see that the file is mapped already, then we will
4458 	 * return an error, but we don't worry about races between this
4459 	 * function and zfs_map().
4460 	 */
4461 	if (zp->z_mapcnt > 0 && MANDMODE(zp->z_mode)) {
4462 		ZFS_EXIT(zfsvfs);
4463 		return (SET_ERROR(EAGAIN));
4464 	}
4465 	ZFS_EXIT(zfsvfs);
4466 	return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4467 }
4468 
4469 /*
4470  * If we can't find a page in the cache, we will create a new page
4471  * and fill it with file data.  For efficiency, we may try to fill
4472  * multiple pages at once (klustering) to fill up the supplied page
4473  * list.  Note that the pages to be filled are held with an exclusive
4474  * lock to prevent access by other threads while they are being filled.
4475  */
4476 static int
4477 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
4478     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
4479 {
4480 	znode_t *zp = VTOZ(vp);
4481 	page_t *pp, *cur_pp;
4482 	objset_t *os = zp->z_zfsvfs->z_os;
4483 	u_offset_t io_off, total;
4484 	size_t io_len;
4485 	int err;
4486 
4487 	if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
4488 		/*
4489 		 * We only have a single page, don't bother klustering
4490 		 */
4491 		io_off = off;
4492 		io_len = PAGESIZE;
4493 		pp = page_create_va(vp, io_off, io_len,
4494 		    PG_EXCL | PG_WAIT, seg, addr);
4495 	} else {
4496 		/*
4497 		 * Try to find enough pages to fill the page list
4498 		 */
4499 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4500 		    &io_len, off, plsz, 0);
4501 	}
4502 	if (pp == NULL) {
4503 		/*
4504 		 * The page already exists, nothing to do here.
4505 		 */
4506 		*pl = NULL;
4507 		return (0);
4508 	}
4509 
4510 	/*
4511 	 * Fill the pages in the kluster.
4512 	 */
4513 	cur_pp = pp;
4514 	for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4515 		caddr_t va;
4516 
4517 		ASSERT3U(io_off, ==, cur_pp->p_offset);
4518 		va = zfs_map_page(cur_pp, S_WRITE);
4519 		err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4520 		    DMU_READ_PREFETCH);
4521 		zfs_unmap_page(cur_pp, va);
4522 		if (err) {
4523 			/* On error, toss the entire kluster */
4524 			pvn_read_done(pp, B_ERROR);
4525 			/* convert checksum errors into IO errors */
4526 			if (err == ECKSUM)
4527 				err = SET_ERROR(EIO);
4528 			return (err);
4529 		}
4530 		cur_pp = cur_pp->p_next;
4531 	}
4532 
4533 	/*
4534 	 * Fill in the page list array from the kluster starting
4535 	 * from the desired offset `off'.
4536 	 * NOTE: the page list will always be null terminated.
4537 	 */
4538 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4539 	ASSERT(pl == NULL || (*pl)->p_offset == off);
4540 
4541 	return (0);
4542 }
4543 
4544 /*
4545  * Return pointers to the pages for the file region [off, off + len]
4546  * in the pl array.  If plsz is greater than len, this function may
4547  * also return page pointers from after the specified region
4548  * (i.e. the region [off, off + plsz]).  These additional pages are
4549  * only returned if they are already in the cache, or were created as
4550  * part of a klustered read.
4551  *
4552  *	IN:	vp	- vnode of file to get data from.
4553  *		off	- position in file to get data from.
4554  *		len	- amount of data to retrieve.
4555  *		plsz	- length of provided page list.
4556  *		seg	- segment to obtain pages for.
4557  *		addr	- virtual address of fault.
4558  *		rw	- mode of created pages.
4559  *		cr	- credentials of caller.
4560  *		ct	- caller context.
4561  *
4562  *	OUT:	protp	- protection mode of created pages.
4563  *		pl	- list of pages created.
4564  *
4565  *	RETURN:	0 on success, error code on failure.
4566  *
4567  * Timestamps:
4568  *	vp - atime updated
4569  */
4570 /* ARGSUSED */
4571 static int
4572 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
4573     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
4574     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
4575 {
4576 	znode_t		*zp = VTOZ(vp);
4577 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4578 	page_t		**pl0 = pl;
4579 	int		err = 0;
4580 
4581 	/* we do our own caching, faultahead is unnecessary */
4582 	if (pl == NULL)
4583 		return (0);
4584 	else if (len > plsz)
4585 		len = plsz;
4586 	else
4587 		len = P2ROUNDUP(len, PAGESIZE);
4588 	ASSERT(plsz >= len);
4589 
4590 	ZFS_ENTER(zfsvfs);
4591 	ZFS_VERIFY_ZP(zp);
4592 
4593 	if (protp)
4594 		*protp = PROT_ALL;
4595 
4596 	/*
4597 	 * Loop through the requested range [off, off + len) looking
4598 	 * for pages.  If we don't find a page, we will need to create
4599 	 * a new page and fill it with data from the file.
4600 	 */
4601 	while (len > 0) {
4602 		if (*pl = page_lookup(vp, off, SE_SHARED))
4603 			*(pl+1) = NULL;
4604 		else if (err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw))
4605 			goto out;
4606 		while (*pl) {
4607 			ASSERT3U((*pl)->p_offset, ==, off);
4608 			off += PAGESIZE;
4609 			addr += PAGESIZE;
4610 			if (len > 0) {
4611 				ASSERT3U(len, >=, PAGESIZE);
4612 				len -= PAGESIZE;
4613 			}
4614 			ASSERT3U(plsz, >=, PAGESIZE);
4615 			plsz -= PAGESIZE;
4616 			pl++;
4617 		}
4618 	}
4619 
4620 	/*
4621 	 * Fill out the page array with any pages already in the cache.
4622 	 */
4623 	while (plsz > 0 &&
4624 	    (*pl++ = page_lookup_nowait(vp, off, SE_SHARED))) {
4625 			off += PAGESIZE;
4626 			plsz -= PAGESIZE;
4627 	}
4628 out:
4629 	if (err) {
4630 		/*
4631 		 * Release any pages we have previously locked.
4632 		 */
4633 		while (pl > pl0)
4634 			page_unlock(*--pl);
4635 	} else {
4636 		ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4637 	}
4638 
4639 	*pl = NULL;
4640 
4641 	ZFS_EXIT(zfsvfs);
4642 	return (err);
4643 }
4644 
4645 /*
4646  * Request a memory map for a section of a file.  This code interacts
4647  * with common code and the VM system as follows:
4648  *
4649  * - common code calls mmap(), which ends up in smmap_common()
4650  * - this calls VOP_MAP(), which takes you into (say) zfs
4651  * - zfs_map() calls as_map(), passing segvn_create() as the callback
4652  * - segvn_create() creates the new segment and calls VOP_ADDMAP()
4653  * - zfs_addmap() updates z_mapcnt
4654  */
4655 /*ARGSUSED*/
4656 static int
4657 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
4658     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4659     caller_context_t *ct)
4660 {
4661 	znode_t *zp = VTOZ(vp);
4662 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4663 	segvn_crargs_t	vn_a;
4664 	int		error;
4665 
4666 	ZFS_ENTER(zfsvfs);
4667 	ZFS_VERIFY_ZP(zp);
4668 
4669 	if ((prot & PROT_WRITE) && (zp->z_pflags &
4670 	    (ZFS_IMMUTABLE | ZFS_READONLY | ZFS_APPENDONLY))) {
4671 		ZFS_EXIT(zfsvfs);
4672 		return (SET_ERROR(EPERM));
4673 	}
4674 
4675 	if ((prot & (PROT_READ | PROT_EXEC)) &&
4676 	    (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4677 		ZFS_EXIT(zfsvfs);
4678 		return (SET_ERROR(EACCES));
4679 	}
4680 
4681 	if (vp->v_flag & VNOMAP) {
4682 		ZFS_EXIT(zfsvfs);
4683 		return (SET_ERROR(ENOSYS));
4684 	}
4685 
4686 	if (off < 0 || len > MAXOFFSET_T - off) {
4687 		ZFS_EXIT(zfsvfs);
4688 		return (SET_ERROR(ENXIO));
4689 	}
4690 
4691 	if (vp->v_type != VREG) {
4692 		ZFS_EXIT(zfsvfs);
4693 		return (SET_ERROR(ENODEV));
4694 	}
4695 
4696 	/*
4697 	 * If file is locked, disallow mapping.
4698 	 */
4699 	if (MANDMODE(zp->z_mode) && vn_has_flocks(vp)) {
4700 		ZFS_EXIT(zfsvfs);
4701 		return (SET_ERROR(EAGAIN));
4702 	}
4703 
4704 	as_rangelock(as);
4705 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
4706 	if (error != 0) {
4707 		as_rangeunlock(as);
4708 		ZFS_EXIT(zfsvfs);
4709 		return (error);
4710 	}
4711 
4712 	vn_a.vp = vp;
4713 	vn_a.offset = (u_offset_t)off;
4714 	vn_a.type = flags & MAP_TYPE;
4715 	vn_a.prot = prot;
4716 	vn_a.maxprot = maxprot;
4717 	vn_a.cred = cr;
4718 	vn_a.amp = NULL;
4719 	vn_a.flags = flags & ~MAP_TYPE;
4720 	vn_a.szc = 0;
4721 	vn_a.lgrp_mem_policy_flags = 0;
4722 
4723 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
4724 
4725 	as_rangeunlock(as);
4726 	ZFS_EXIT(zfsvfs);
4727 	return (error);
4728 }
4729 
4730 /* ARGSUSED */
4731 static int
4732 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4733     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4734     caller_context_t *ct)
4735 {
4736 	uint64_t pages = btopr(len);
4737 
4738 	atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
4739 	return (0);
4740 }
4741 
4742 /*
4743  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
4744  * more accurate mtime for the associated file.  Since we don't have a way of
4745  * detecting when the data was actually modified, we have to resort to
4746  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
4747  * last page is pushed.  The problem occurs when the msync() call is omitted,
4748  * which by far the most common case:
4749  *
4750  *	open()
4751  *	mmap()
4752  *	<modify memory>
4753  *	munmap()
4754  *	close()
4755  *	<time lapse>
4756  *	putpage() via fsflush
4757  *
4758  * If we wait until fsflush to come along, we can have a modification time that
4759  * is some arbitrary point in the future.  In order to prevent this in the
4760  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
4761  * torn down.
4762  */
4763 /* ARGSUSED */
4764 static int
4765 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4766     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
4767     caller_context_t *ct)
4768 {
4769 	uint64_t pages = btopr(len);
4770 
4771 	ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
4772 	atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
4773 
4774 	if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
4775 	    vn_has_cached_data(vp))
4776 		(void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
4777 
4778 	return (0);
4779 }
4780 
4781 /*
4782  * Free or allocate space in a file.  Currently, this function only
4783  * supports the `F_FREESP' command.  However, this command is somewhat
4784  * misnamed, as its functionality includes the ability to allocate as
4785  * well as free space.
4786  *
4787  *	IN:	vp	- vnode of file to free data in.
4788  *		cmd	- action to take (only F_FREESP supported).
4789  *		bfp	- section of file to free/alloc.
4790  *		flag	- current file open mode flags.
4791  *		offset	- current file offset.
4792  *		cr	- credentials of caller [UNUSED].
4793  *		ct	- caller context.
4794  *
4795  *	RETURN:	0 on success, error code on failure.
4796  *
4797  * Timestamps:
4798  *	vp - ctime|mtime updated
4799  */
4800 /* ARGSUSED */
4801 static int
4802 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
4803     offset_t offset, cred_t *cr, caller_context_t *ct)
4804 {
4805 	znode_t		*zp = VTOZ(vp);
4806 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4807 	uint64_t	off, len;
4808 	int		error;
4809 
4810 	ZFS_ENTER(zfsvfs);
4811 	ZFS_VERIFY_ZP(zp);
4812 
4813 	if (cmd != F_FREESP) {
4814 		ZFS_EXIT(zfsvfs);
4815 		return (SET_ERROR(EINVAL));
4816 	}
4817 
4818 	/*
4819 	 * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
4820 	 * callers might not be able to detect properly that we are read-only,
4821 	 * so check it explicitly here.
4822 	 */
4823 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
4824 		ZFS_EXIT(zfsvfs);
4825 		return (SET_ERROR(EROFS));
4826 	}
4827 
4828 	if (error = convoff(vp, bfp, 0, offset)) {
4829 		ZFS_EXIT(zfsvfs);
4830 		return (error);
4831 	}
4832 
4833 	if (bfp->l_len < 0) {
4834 		ZFS_EXIT(zfsvfs);
4835 		return (SET_ERROR(EINVAL));
4836 	}
4837 
4838 	off = bfp->l_start;
4839 	len = bfp->l_len; /* 0 means from off to end of file */
4840 
4841 	error = zfs_freesp(zp, off, len, flag, TRUE);
4842 
4843 	if (error == 0 && off == 0 && len == 0)
4844 		vnevent_truncate(ZTOV(zp), ct);
4845 
4846 	ZFS_EXIT(zfsvfs);
4847 	return (error);
4848 }
4849 
4850 /*ARGSUSED*/
4851 static int
4852 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
4853 {
4854 	znode_t		*zp = VTOZ(vp);
4855 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4856 	uint32_t	gen;
4857 	uint64_t	gen64;
4858 	uint64_t	object = zp->z_id;
4859 	zfid_short_t	*zfid;
4860 	int		size, i, error;
4861 
4862 	ZFS_ENTER(zfsvfs);
4863 	ZFS_VERIFY_ZP(zp);
4864 
4865 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
4866 	    &gen64, sizeof (uint64_t))) != 0) {
4867 		ZFS_EXIT(zfsvfs);
4868 		return (error);
4869 	}
4870 
4871 	gen = (uint32_t)gen64;
4872 
4873 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
4874 	if (fidp->fid_len < size) {
4875 		fidp->fid_len = size;
4876 		ZFS_EXIT(zfsvfs);
4877 		return (SET_ERROR(ENOSPC));
4878 	}
4879 
4880 	zfid = (zfid_short_t *)fidp;
4881 
4882 	zfid->zf_len = size;
4883 
4884 	for (i = 0; i < sizeof (zfid->zf_object); i++)
4885 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4886 
4887 	/* Must have a non-zero generation number to distinguish from .zfs */
4888 	if (gen == 0)
4889 		gen = 1;
4890 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
4891 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4892 
4893 	if (size == LONG_FID_LEN) {
4894 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
4895 		zfid_long_t	*zlfid;
4896 
4897 		zlfid = (zfid_long_t *)fidp;
4898 
4899 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4900 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4901 
4902 		/* XXX - this should be the generation number for the objset */
4903 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4904 			zlfid->zf_setgen[i] = 0;
4905 	}
4906 
4907 	ZFS_EXIT(zfsvfs);
4908 	return (0);
4909 }
4910 
4911 static int
4912 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
4913     caller_context_t *ct)
4914 {
4915 	znode_t		*zp, *xzp;
4916 	zfsvfs_t	*zfsvfs;
4917 	zfs_dirlock_t	*dl;
4918 	int		error;
4919 
4920 	switch (cmd) {
4921 	case _PC_LINK_MAX:
4922 		*valp = ULONG_MAX;
4923 		return (0);
4924 
4925 	case _PC_FILESIZEBITS:
4926 		*valp = 64;
4927 		return (0);
4928 
4929 	case _PC_XATTR_EXISTS:
4930 		zp = VTOZ(vp);
4931 		zfsvfs = zp->z_zfsvfs;
4932 		ZFS_ENTER(zfsvfs);
4933 		ZFS_VERIFY_ZP(zp);
4934 		*valp = 0;
4935 		error = zfs_dirent_lock(&dl, zp, "", &xzp,
4936 		    ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
4937 		if (error == 0) {
4938 			zfs_dirent_unlock(dl);
4939 			if (!zfs_dirempty(xzp))
4940 				*valp = 1;
4941 			VN_RELE(ZTOV(xzp));
4942 		} else if (error == ENOENT) {
4943 			/*
4944 			 * If there aren't extended attributes, it's the
4945 			 * same as having zero of them.
4946 			 */
4947 			error = 0;
4948 		}
4949 		ZFS_EXIT(zfsvfs);
4950 		return (error);
4951 
4952 	case _PC_SATTR_ENABLED:
4953 	case _PC_SATTR_EXISTS:
4954 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
4955 		    (vp->v_type == VREG || vp->v_type == VDIR);
4956 		return (0);
4957 
4958 	case _PC_ACCESS_FILTERING:
4959 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_ACCESS_FILTER) &&
4960 		    vp->v_type == VDIR;
4961 		return (0);
4962 
4963 	case _PC_ACL_ENABLED:
4964 		*valp = _ACL_ACE_ENABLED;
4965 		return (0);
4966 
4967 	case _PC_MIN_HOLE_SIZE:
4968 		*valp = (ulong_t)SPA_MINBLOCKSIZE;
4969 		return (0);
4970 
4971 	case _PC_TIMESTAMP_RESOLUTION:
4972 		/* nanosecond timestamp resolution */
4973 		*valp = 1L;
4974 		return (0);
4975 
4976 	default:
4977 		return (fs_pathconf(vp, cmd, valp, cr, ct));
4978 	}
4979 }
4980 
4981 /*ARGSUSED*/
4982 static int
4983 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
4984     caller_context_t *ct)
4985 {
4986 	znode_t *zp = VTOZ(vp);
4987 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4988 	int error;
4989 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4990 
4991 	ZFS_ENTER(zfsvfs);
4992 	ZFS_VERIFY_ZP(zp);
4993 	error = zfs_getacl(zp, vsecp, skipaclchk, cr);
4994 	ZFS_EXIT(zfsvfs);
4995 
4996 	return (error);
4997 }
4998 
4999 /*ARGSUSED*/
5000 static int
5001 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5002     caller_context_t *ct)
5003 {
5004 	znode_t *zp = VTOZ(vp);
5005 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5006 	int error;
5007 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5008 	zilog_t	*zilog = zfsvfs->z_log;
5009 
5010 	ZFS_ENTER(zfsvfs);
5011 	ZFS_VERIFY_ZP(zp);
5012 
5013 	error = zfs_setacl(zp, vsecp, skipaclchk, cr);
5014 
5015 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
5016 		zil_commit(zilog, 0);
5017 
5018 	ZFS_EXIT(zfsvfs);
5019 	return (error);
5020 }
5021 
5022 /*
5023  * The smallest read we may consider to loan out an arcbuf.
5024  * This must be a power of 2.
5025  */
5026 int zcr_blksz_min = (1 << 10);	/* 1K */
5027 /*
5028  * If set to less than the file block size, allow loaning out of an
5029  * arcbuf for a partial block read.  This must be a power of 2.
5030  */
5031 int zcr_blksz_max = (1 << 17);	/* 128K */
5032 
5033 /*ARGSUSED*/
5034 static int
5035 zfs_reqzcbuf(vnode_t *vp, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr,
5036     caller_context_t *ct)
5037 {
5038 	znode_t	*zp = VTOZ(vp);
5039 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5040 	int max_blksz = zfsvfs->z_max_blksz;
5041 	uio_t *uio = &xuio->xu_uio;
5042 	ssize_t size = uio->uio_resid;
5043 	offset_t offset = uio->uio_loffset;
5044 	int blksz;
5045 	int fullblk, i;
5046 	arc_buf_t *abuf;
5047 	ssize_t maxsize;
5048 	int preamble, postamble;
5049 
5050 	if (xuio->xu_type != UIOTYPE_ZEROCOPY)
5051 		return (SET_ERROR(EINVAL));
5052 
5053 	ZFS_ENTER(zfsvfs);
5054 	ZFS_VERIFY_ZP(zp);
5055 	switch (ioflag) {
5056 	case UIO_WRITE:
5057 		/*
5058 		 * Loan out an arc_buf for write if write size is bigger than
5059 		 * max_blksz, and the file's block size is also max_blksz.
5060 		 */
5061 		blksz = max_blksz;
5062 		if (size < blksz || zp->z_blksz != blksz) {
5063 			ZFS_EXIT(zfsvfs);
5064 			return (SET_ERROR(EINVAL));
5065 		}
5066 		/*
5067 		 * Caller requests buffers for write before knowing where the
5068 		 * write offset might be (e.g. NFS TCP write).
5069 		 */
5070 		if (offset == -1) {
5071 			preamble = 0;
5072 		} else {
5073 			preamble = P2PHASE(offset, blksz);
5074 			if (preamble) {
5075 				preamble = blksz - preamble;
5076 				size -= preamble;
5077 			}
5078 		}
5079 
5080 		postamble = P2PHASE(size, blksz);
5081 		size -= postamble;
5082 
5083 		fullblk = size / blksz;
5084 		(void) dmu_xuio_init(xuio,
5085 		    (preamble != 0) + fullblk + (postamble != 0));
5086 		DTRACE_PROBE3(zfs_reqzcbuf_align, int, preamble,
5087 		    int, postamble, int,
5088 		    (preamble != 0) + fullblk + (postamble != 0));
5089 
5090 		/*
5091 		 * Have to fix iov base/len for partial buffers.  They
5092 		 * currently represent full arc_buf's.
5093 		 */
5094 		if (preamble) {
5095 			/* data begins in the middle of the arc_buf */
5096 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5097 			    blksz);
5098 			ASSERT(abuf);
5099 			(void) dmu_xuio_add(xuio, abuf,
5100 			    blksz - preamble, preamble);
5101 		}
5102 
5103 		for (i = 0; i < fullblk; i++) {
5104 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5105 			    blksz);
5106 			ASSERT(abuf);
5107 			(void) dmu_xuio_add(xuio, abuf, 0, blksz);
5108 		}
5109 
5110 		if (postamble) {
5111 			/* data ends in the middle of the arc_buf */
5112 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5113 			    blksz);
5114 			ASSERT(abuf);
5115 			(void) dmu_xuio_add(xuio, abuf, 0, postamble);
5116 		}
5117 		break;
5118 	case UIO_READ:
5119 		/*
5120 		 * Loan out an arc_buf for read if the read size is larger than
5121 		 * the current file block size.  Block alignment is not
5122 		 * considered.  Partial arc_buf will be loaned out for read.
5123 		 */
5124 		blksz = zp->z_blksz;
5125 		if (blksz < zcr_blksz_min)
5126 			blksz = zcr_blksz_min;
5127 		if (blksz > zcr_blksz_max)
5128 			blksz = zcr_blksz_max;
5129 		/* avoid potential complexity of dealing with it */
5130 		if (blksz > max_blksz) {
5131 			ZFS_EXIT(zfsvfs);
5132 			return (SET_ERROR(EINVAL));
5133 		}
5134 
5135 		maxsize = zp->z_size - uio->uio_loffset;
5136 		if (size > maxsize)
5137 			size = maxsize;
5138 
5139 		if (size < blksz || vn_has_cached_data(vp)) {
5140 			ZFS_EXIT(zfsvfs);
5141 			return (SET_ERROR(EINVAL));
5142 		}
5143 		break;
5144 	default:
5145 		ZFS_EXIT(zfsvfs);
5146 		return (SET_ERROR(EINVAL));
5147 	}
5148 
5149 	uio->uio_extflg = UIO_XUIO;
5150 	XUIO_XUZC_RW(xuio) = ioflag;
5151 	ZFS_EXIT(zfsvfs);
5152 	return (0);
5153 }
5154 
5155 /*ARGSUSED*/
5156 static int
5157 zfs_retzcbuf(vnode_t *vp, xuio_t *xuio, cred_t *cr, caller_context_t *ct)
5158 {
5159 	int i;
5160 	arc_buf_t *abuf;
5161 	int ioflag = XUIO_XUZC_RW(xuio);
5162 
5163 	ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
5164 
5165 	i = dmu_xuio_cnt(xuio);
5166 	while (i-- > 0) {
5167 		abuf = dmu_xuio_arcbuf(xuio, i);
5168 		/*
5169 		 * if abuf == NULL, it must be a write buffer
5170 		 * that has been returned in zfs_write().
5171 		 */
5172 		if (abuf)
5173 			dmu_return_arcbuf(abuf);
5174 		ASSERT(abuf || ioflag == UIO_WRITE);
5175 	}
5176 
5177 	dmu_xuio_fini(xuio);
5178 	return (0);
5179 }
5180 
5181 /*
5182  * Predeclare these here so that the compiler assumes that
5183  * this is an "old style" function declaration that does
5184  * not include arguments => we won't get type mismatch errors
5185  * in the initializations that follow.
5186  */
5187 static int zfs_inval();
5188 static int zfs_isdir();
5189 
5190 static int
5191 zfs_inval()
5192 {
5193 	return (SET_ERROR(EINVAL));
5194 }
5195 
5196 static int
5197 zfs_isdir()
5198 {
5199 	return (SET_ERROR(EISDIR));
5200 }
5201 /*
5202  * Directory vnode operations template
5203  */
5204 vnodeops_t *zfs_dvnodeops;
5205 const fs_operation_def_t zfs_dvnodeops_template[] = {
5206 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5207 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5208 	VOPNAME_READ,		{ .error = zfs_isdir },
5209 	VOPNAME_WRITE,		{ .error = zfs_isdir },
5210 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5211 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5212 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5213 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5214 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5215 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5216 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5217 	VOPNAME_LINK,		{ .vop_link = zfs_link },
5218 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5219 	VOPNAME_MKDIR,		{ .vop_mkdir = zfs_mkdir },
5220 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5221 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5222 	VOPNAME_SYMLINK,	{ .vop_symlink = zfs_symlink },
5223 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5224 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5225 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5226 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5227 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5228 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5229 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5230 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5231 	NULL,			NULL
5232 };
5233 
5234 /*
5235  * Regular file vnode operations template
5236  */
5237 vnodeops_t *zfs_fvnodeops;
5238 const fs_operation_def_t zfs_fvnodeops_template[] = {
5239 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5240 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5241 	VOPNAME_READ,		{ .vop_read = zfs_read },
5242 	VOPNAME_WRITE,		{ .vop_write = zfs_write },
5243 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5244 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5245 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5246 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5247 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5248 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5249 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5250 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5251 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5252 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5253 	VOPNAME_FRLOCK,		{ .vop_frlock = zfs_frlock },
5254 	VOPNAME_SPACE,		{ .vop_space = zfs_space },
5255 	VOPNAME_GETPAGE,	{ .vop_getpage = zfs_getpage },
5256 	VOPNAME_PUTPAGE,	{ .vop_putpage = zfs_putpage },
5257 	VOPNAME_MAP,		{ .vop_map = zfs_map },
5258 	VOPNAME_ADDMAP,		{ .vop_addmap = zfs_addmap },
5259 	VOPNAME_DELMAP,		{ .vop_delmap = zfs_delmap },
5260 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5261 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5262 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5263 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5264 	VOPNAME_REQZCBUF,	{ .vop_reqzcbuf = zfs_reqzcbuf },
5265 	VOPNAME_RETZCBUF,	{ .vop_retzcbuf = zfs_retzcbuf },
5266 	NULL,			NULL
5267 };
5268 
5269 /*
5270  * Symbolic link vnode operations template
5271  */
5272 vnodeops_t *zfs_symvnodeops;
5273 const fs_operation_def_t zfs_symvnodeops_template[] = {
5274 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5275 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5276 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5277 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5278 	VOPNAME_READLINK,	{ .vop_readlink = zfs_readlink },
5279 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5280 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5281 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5282 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5283 	NULL,			NULL
5284 };
5285 
5286 /*
5287  * special share hidden files vnode operations template
5288  */
5289 vnodeops_t *zfs_sharevnodeops;
5290 const fs_operation_def_t zfs_sharevnodeops_template[] = {
5291 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5292 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5293 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5294 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5295 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5296 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5297 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5298 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5299 	NULL,			NULL
5300 };
5301 
5302 /*
5303  * Extended attribute directory vnode operations template
5304  *
5305  * This template is identical to the directory vnodes
5306  * operation template except for restricted operations:
5307  *	VOP_MKDIR()
5308  *	VOP_SYMLINK()
5309  *
5310  * Note that there are other restrictions embedded in:
5311  *	zfs_create()	- restrict type to VREG
5312  *	zfs_link()	- no links into/out of attribute space
5313  *	zfs_rename()	- no moves into/out of attribute space
5314  */
5315 vnodeops_t *zfs_xdvnodeops;
5316 const fs_operation_def_t zfs_xdvnodeops_template[] = {
5317 	VOPNAME_OPEN,		{ .vop_open = zfs_open },
5318 	VOPNAME_CLOSE,		{ .vop_close = zfs_close },
5319 	VOPNAME_IOCTL,		{ .vop_ioctl = zfs_ioctl },
5320 	VOPNAME_GETATTR,	{ .vop_getattr = zfs_getattr },
5321 	VOPNAME_SETATTR,	{ .vop_setattr = zfs_setattr },
5322 	VOPNAME_ACCESS,		{ .vop_access = zfs_access },
5323 	VOPNAME_LOOKUP,		{ .vop_lookup = zfs_lookup },
5324 	VOPNAME_CREATE,		{ .vop_create = zfs_create },
5325 	VOPNAME_REMOVE,		{ .vop_remove = zfs_remove },
5326 	VOPNAME_LINK,		{ .vop_link = zfs_link },
5327 	VOPNAME_RENAME,		{ .vop_rename = zfs_rename },
5328 	VOPNAME_MKDIR,		{ .error = zfs_inval },
5329 	VOPNAME_RMDIR,		{ .vop_rmdir = zfs_rmdir },
5330 	VOPNAME_READDIR,	{ .vop_readdir = zfs_readdir },
5331 	VOPNAME_SYMLINK,	{ .error = zfs_inval },
5332 	VOPNAME_FSYNC,		{ .vop_fsync = zfs_fsync },
5333 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5334 	VOPNAME_FID,		{ .vop_fid = zfs_fid },
5335 	VOPNAME_SEEK,		{ .vop_seek = zfs_seek },
5336 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5337 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = zfs_getsecattr },
5338 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = zfs_setsecattr },
5339 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
5340 	NULL,			NULL
5341 };
5342 
5343 /*
5344  * Error vnode operations template
5345  */
5346 vnodeops_t *zfs_evnodeops;
5347 const fs_operation_def_t zfs_evnodeops_template[] = {
5348 	VOPNAME_INACTIVE,	{ .vop_inactive = zfs_inactive },
5349 	VOPNAME_PATHCONF,	{ .vop_pathconf = zfs_pathconf },
5350 	NULL,			NULL
5351 };
5352