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