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