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