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