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