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