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