xref: /titanic_51/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision 38e9bdff89ac3db1d2adb25900776c2cbb6a3438)
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 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
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/vnode.h>
36 #include <sys/file.h>
37 #include <sys/stat.h>
38 #include <sys/kmem.h>
39 #include <sys/taskq.h>
40 #include <sys/uio.h>
41 #include <sys/vmsystm.h>
42 #include <sys/atomic.h>
43 #include <vm/seg_vn.h>
44 #include <vm/pvn.h>
45 #include <vm/as.h>
46 #include <sys/mman.h>
47 #include <sys/pathname.h>
48 #include <sys/cmn_err.h>
49 #include <sys/errno.h>
50 #include <sys/unistd.h>
51 #include <sys/zfs_vfsops.h>
52 #include <sys/zfs_dir.h>
53 #include <sys/zfs_acl.h>
54 #include <sys/zfs_ioctl.h>
55 #include <sys/fs/zfs.h>
56 #include <sys/dmu.h>
57 #include <sys/spa.h>
58 #include <sys/txg.h>
59 #include <sys/dbuf.h>
60 #include <sys/zap.h>
61 #include <sys/dirent.h>
62 #include <sys/policy.h>
63 #include <sys/sunddi.h>
64 #include <sys/filio.h>
65 #include "fs/fs_subr.h"
66 #include <sys/zfs_ctldir.h>
67 #include <sys/dnlc.h>
68 #include <sys/zfs_rlock.h>
69 
70 /*
71  * Programming rules.
72  *
73  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
74  * properly lock its in-core state, create a DMU transaction, do the work,
75  * record this work in the intent log (ZIL), commit the DMU transaction,
76  * and wait the the intent log to commit if it's is a synchronous operation.
77  * Morover, the vnode ops must work in both normal and log replay context.
78  * The ordering of events is important to avoid deadlocks and references
79  * to freed memory.  The example below illustrates the following Big Rules:
80  *
81  *  (1) A check must be made in each zfs thread for a mounted file system.
82  *	This is done avoiding races using ZFS_ENTER(zfsvfs).
83  *	A ZFS_EXIT(zfsvfs) is needed before all returns.
84  *
85  *  (2)	VN_RELE() should always be the last thing except for zil_commit()
86  *	and ZFS_EXIT(). This is for 3 reasons:
87  *	First, if it's the last reference, the vnode/znode
88  *	can be freed, so the zp may point to freed memory.  Second, the last
89  *	reference will call zfs_zinactive(), which may induce a lot of work --
90  *	pushing cached pages (which acquires range locks) and syncing out
91  *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
92  *	which could deadlock the system if you were already holding one.
93  *
94  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
95  *	as they can span dmu_tx_assign() calls.
96  *
97  *  (4)	Always pass zfsvfs->z_assign as the second argument to dmu_tx_assign().
98  *	In normal operation, this will be TXG_NOWAIT.  During ZIL replay,
99  *	it will be a specific txg.  Either way, dmu_tx_assign() never blocks.
100  *	This is critical because we don't want to block while holding locks.
101  *	Note, in particular, that if a lock is sometimes acquired before
102  *	the tx assigns, and sometimes after (e.g. z_lock), then failing to
103  *	use a non-blocking assign can deadlock the system.  The scenario:
104  *
105  *	Thread A has grabbed a lock before calling dmu_tx_assign().
106  *	Thread B is in an already-assigned tx, and blocks for this lock.
107  *	Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
108  *	forever, because the previous txg can't quiesce until B's tx commits.
109  *
110  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
111  *	then drop all locks, call dmu_tx_wait(), and try again.
112  *
113  *  (5)	If the operation succeeded, generate the intent log entry for it
114  *	before dropping locks.  This ensures that the ordering of events
115  *	in the intent log matches the order in which they actually occurred.
116  *
117  *  (6)	At the end of each vnode op, the DMU tx must always commit,
118  *	regardless of whether there were any errors.
119  *
120  *  (7)	After dropping all locks, invoke zil_commit(zilog, seq, ioflag)
121  *	to ensure that synchronous semantics are provided when necessary.
122  *
123  * In general, this is how things should be ordered in each vnode op:
124  *
125  *	ZFS_ENTER(zfsvfs);		// exit if unmounted
126  * top:
127  *	zfs_dirent_lock(&dl, ...)	// lock directory entry (may VN_HOLD())
128  *	rw_enter(...);			// grab any other locks you need
129  *	tx = dmu_tx_create(...);	// get DMU tx
130  *	dmu_tx_hold_*();		// hold each object you might modify
131  *	error = dmu_tx_assign(tx, zfsvfs->z_assign);	// try to assign
132  *	if (error) {
133  *		rw_exit(...);		// drop locks
134  *		zfs_dirent_unlock(dl);	// unlock directory entry
135  *		VN_RELE(...);		// release held vnodes
136  *		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
137  *			dmu_tx_wait(tx);
138  *			dmu_tx_abort(tx);
139  *			goto top;
140  *		}
141  *		dmu_tx_abort(tx);	// abort DMU tx
142  *		ZFS_EXIT(zfsvfs);	// finished in zfs
143  *		return (error);		// really out of space
144  *	}
145  *	error = do_real_work();		// do whatever this VOP does
146  *	if (error == 0)
147  *		seq = zfs_log_*(...);	// on success, make ZIL entry
148  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
149  *	rw_exit(...);			// drop locks
150  *	zfs_dirent_unlock(dl);		// unlock directory entry
151  *	VN_RELE(...);			// release held vnodes
152  *	zil_commit(zilog, seq, ioflag);	// synchronous when necessary
153  *	ZFS_EXIT(zfsvfs);		// finished in zfs
154  *	return (error);			// done, report error
155  */
156 
157 /* ARGSUSED */
158 static int
159 zfs_open(vnode_t **vpp, int flag, cred_t *cr)
160 {
161 	return (0);
162 }
163 
164 /* ARGSUSED */
165 static int
166 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
167 {
168 	/*
169 	 * Clean up any locks held by this process on the vp.
170 	 */
171 	cleanlocks(vp, ddi_get_pid(), 0);
172 	cleanshares(vp, ddi_get_pid());
173 
174 	return (0);
175 }
176 
177 /*
178  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
179  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
180  */
181 static int
182 zfs_holey(vnode_t *vp, int cmd, offset_t *off)
183 {
184 	znode_t	*zp = VTOZ(vp);
185 	uint64_t noff = (uint64_t)*off; /* new offset */
186 	uint64_t file_sz;
187 	int error;
188 	boolean_t hole;
189 
190 	file_sz = zp->z_phys->zp_size;
191 	if (noff >= file_sz)  {
192 		return (ENXIO);
193 	}
194 
195 	if (cmd == _FIO_SEEK_HOLE)
196 		hole = B_TRUE;
197 	else
198 		hole = B_FALSE;
199 
200 	error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
201 
202 	/* end of file? */
203 	if ((error == ESRCH) || (noff > file_sz)) {
204 		/*
205 		 * Handle the virtual hole at the end of file.
206 		 */
207 		if (hole) {
208 			*off = file_sz;
209 			return (0);
210 		}
211 		return (ENXIO);
212 	}
213 
214 	if (noff < *off)
215 		return (error);
216 	*off = noff;
217 	return (error);
218 }
219 
220 /* ARGSUSED */
221 static int
222 zfs_ioctl(vnode_t *vp, int com, intptr_t data, int flag, cred_t *cred,
223     int *rvalp)
224 {
225 	offset_t off;
226 	int error;
227 	zfsvfs_t *zfsvfs;
228 
229 	switch (com) {
230 	    case _FIOFFS:
231 		return (zfs_sync(vp->v_vfsp, 0, cred));
232 
233 		/*
234 		 * The following two ioctls are used by bfu.  Faking out,
235 		 * necessary to avoid bfu errors.
236 		 */
237 	    case _FIOGDIO:
238 	    case _FIOSDIO:
239 		return (0);
240 
241 	    case _FIO_SEEK_DATA:
242 	    case _FIO_SEEK_HOLE:
243 		if (ddi_copyin((void *)data, &off, sizeof (off), flag))
244 			return (EFAULT);
245 
246 		zfsvfs = VTOZ(vp)->z_zfsvfs;
247 		ZFS_ENTER(zfsvfs);
248 
249 		/* offset parameter is in/out */
250 		error = zfs_holey(vp, com, &off);
251 		ZFS_EXIT(zfsvfs);
252 		if (error)
253 			return (error);
254 		if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
255 			return (EFAULT);
256 		return (0);
257 	}
258 	return (ENOTTY);
259 }
260 
261 /*
262  * When a file is memory mapped, we must keep the IO data synchronized
263  * between the DMU cache and the memory mapped pages.  What this means:
264  *
265  * On Write:	If we find a memory mapped page, we write to *both*
266  *		the page and the dmu buffer.
267  *
268  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
269  *	the file is memory mapped.
270  */
271 static int
272 mappedwrite(vnode_t *vp, uint64_t woff, int nbytes, uio_t *uio, dmu_tx_t *tx)
273 {
274 	znode_t	*zp = VTOZ(vp);
275 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
276 	int64_t	start, off;
277 	int len = nbytes;
278 	int error = 0;
279 
280 	start = uio->uio_loffset;
281 	off = start & PAGEOFFSET;
282 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
283 		page_t *pp;
284 		uint64_t bytes = MIN(PAGESIZE - off, len);
285 
286 		/*
287 		 * We don't want a new page to "appear" in the middle of
288 		 * the file update (because it may not get the write
289 		 * update data), so we grab a lock to block
290 		 * zfs_getpage().
291 		 */
292 		rw_enter(&zp->z_map_lock, RW_WRITER);
293 		if (pp = page_lookup(vp, start, SE_SHARED)) {
294 			caddr_t va;
295 
296 			rw_exit(&zp->z_map_lock);
297 			va = ppmapin(pp, PROT_READ | PROT_WRITE, (caddr_t)-1L);
298 			error = uiomove(va+off, bytes, UIO_WRITE, uio);
299 			if (error == 0) {
300 				dmu_write(zfsvfs->z_os, zp->z_id,
301 				    woff, bytes, va+off, tx);
302 			}
303 			ppmapout(va);
304 			page_unlock(pp);
305 		} else {
306 			error = dmu_write_uio(zfsvfs->z_os, zp->z_id,
307 			    woff, bytes, uio, tx);
308 			rw_exit(&zp->z_map_lock);
309 		}
310 		len -= bytes;
311 		woff += bytes;
312 		off = 0;
313 		if (error)
314 			break;
315 	}
316 	return (error);
317 }
318 
319 /*
320  * When a file is memory mapped, we must keep the IO data synchronized
321  * between the DMU cache and the memory mapped pages.  What this means:
322  *
323  * On Read:	We "read" preferentially from memory mapped pages,
324  *		else we default from the dmu buffer.
325  *
326  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
327  *	the file is memory mapped.
328  */
329 static int
330 mappedread(vnode_t *vp, char *addr, int nbytes, uio_t *uio)
331 {
332 	int64_t	start, off, bytes;
333 	int len = nbytes;
334 	int error = 0;
335 
336 	start = uio->uio_loffset;
337 	off = start & PAGEOFFSET;
338 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
339 		page_t *pp;
340 
341 		bytes = MIN(PAGESIZE - off, len);
342 		if (pp = page_lookup(vp, start, SE_SHARED)) {
343 			caddr_t va;
344 
345 			va = ppmapin(pp, PROT_READ | PROT_WRITE, (caddr_t)-1L);
346 			error = uiomove(va + off, bytes, UIO_READ, uio);
347 			ppmapout(va);
348 			page_unlock(pp);
349 		} else {
350 			/* XXX use dmu_read here? */
351 			error = uiomove(addr, bytes, UIO_READ, uio);
352 		}
353 		len -= bytes;
354 		addr += bytes;
355 		off = 0;
356 		if (error)
357 			break;
358 	}
359 	return (error);
360 }
361 
362 uint_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
363 
364 /*
365  * Read bytes from specified file into supplied buffer.
366  *
367  *	IN:	vp	- vnode of file to be read from.
368  *		uio	- structure supplying read location, range info,
369  *			  and return buffer.
370  *		ioflag	- SYNC flags; used to provide FRSYNC semantics.
371  *		cr	- credentials of caller.
372  *
373  *	OUT:	uio	- updated offset and range, buffer filled.
374  *
375  *	RETURN:	0 if success
376  *		error code if failure
377  *
378  * Side Effects:
379  *	vp - atime updated if byte count > 0
380  */
381 /* ARGSUSED */
382 static int
383 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
384 {
385 	znode_t		*zp = VTOZ(vp);
386 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
387 	uint64_t	delta;
388 	ssize_t		n, size, cnt, ndone;
389 	int		error, i, numbufs;
390 	dmu_buf_t	*dbp, **dbpp;
391 	rl_t		*rl;
392 
393 	ZFS_ENTER(zfsvfs);
394 
395 	/*
396 	 * Validate file offset
397 	 */
398 	if (uio->uio_loffset < (offset_t)0) {
399 		ZFS_EXIT(zfsvfs);
400 		return (EINVAL);
401 	}
402 
403 	/*
404 	 * Fasttrack empty reads
405 	 */
406 	if (uio->uio_resid == 0) {
407 		ZFS_EXIT(zfsvfs);
408 		return (0);
409 	}
410 
411 	/*
412 	 * Check for mandatory locks
413 	 */
414 	if (MANDMODE((mode_t)zp->z_phys->zp_mode)) {
415 		if (error = chklock(vp, FREAD,
416 		    uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
417 			ZFS_EXIT(zfsvfs);
418 			return (error);
419 		}
420 	}
421 
422 	/*
423 	 * If we're in FRSYNC mode, sync out this znode before reading it.
424 	 */
425 	zil_commit(zfsvfs->z_log, zp->z_last_itx, ioflag & FRSYNC);
426 
427 	/*
428 	 * Lock the range against changes.
429 	 */
430 	rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
431 
432 	/*
433 	 * If we are reading past end-of-file we can skip
434 	 * to the end; but we might still need to set atime.
435 	 */
436 	if (uio->uio_loffset >= zp->z_phys->zp_size) {
437 		cnt = 0;
438 		error = 0;
439 		goto out;
440 	}
441 
442 	cnt = MIN(uio->uio_resid, zp->z_phys->zp_size - uio->uio_loffset);
443 
444 	for (ndone = 0; ndone < cnt; ndone += zfs_read_chunk_size) {
445 		ASSERT(uio->uio_loffset < zp->z_phys->zp_size);
446 		n = MIN(zfs_read_chunk_size,
447 		    zp->z_phys->zp_size - uio->uio_loffset);
448 		n = MIN(n, cnt);
449 		error = dmu_buf_hold_array(zfsvfs->z_os, zp->z_id,
450 		    uio->uio_loffset, n, TRUE, FTAG, &numbufs, &dbpp);
451 		if (error)
452 			goto out;
453 		/*
454 		 * Compute the adjustment to align the dmu buffers
455 		 * with the uio buffer.
456 		 */
457 		delta = uio->uio_loffset - dbpp[0]->db_offset;
458 
459 		for (i = 0; i < numbufs; i++) {
460 			if (n < 0)
461 				break;
462 			dbp = dbpp[i];
463 			size = dbp->db_size - delta;
464 			/*
465 			 * XXX -- this is correct, but may be suboptimal.
466 			 * If the pages are all clean, we don't need to
467 			 * go through mappedread().  Maybe the VMODSORT
468 			 * stuff can help us here.
469 			 */
470 			if (vn_has_cached_data(vp)) {
471 				error = mappedread(vp, (caddr_t)dbp->db_data +
472 				    delta, (n < size ? n : size), uio);
473 			} else {
474 				error = uiomove((caddr_t)dbp->db_data + delta,
475 					(n < size ? n : size), UIO_READ, uio);
476 			}
477 			if (error) {
478 				dmu_buf_rele_array(dbpp, numbufs, FTAG);
479 				goto out;
480 			}
481 			n -= dbp->db_size;
482 			if (delta) {
483 				n += delta;
484 				delta = 0;
485 			}
486 		}
487 		dmu_buf_rele_array(dbpp, numbufs, FTAG);
488 	}
489 out:
490 	zfs_range_unlock(rl);
491 
492 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
493 	ZFS_EXIT(zfsvfs);
494 	return (error);
495 }
496 
497 /*
498  * Fault in the pages of the first n bytes specified by the uio structure.
499  * 1 byte in each page is touched and the uio struct is unmodified.
500  * Any error will exit this routine as this is only a best
501  * attempt to get the pages resident. This is a copy of ufs_trans_touch().
502  */
503 static void
504 zfs_prefault_write(ssize_t n, struct uio *uio)
505 {
506 	struct iovec *iov;
507 	ulong_t cnt, incr;
508 	caddr_t p;
509 	uint8_t tmp;
510 
511 	iov = uio->uio_iov;
512 
513 	while (n) {
514 		cnt = MIN(iov->iov_len, n);
515 		if (cnt == 0) {
516 			/* empty iov entry */
517 			iov++;
518 			continue;
519 		}
520 		n -= cnt;
521 		/*
522 		 * touch each page in this segment.
523 		 */
524 		p = iov->iov_base;
525 		while (cnt) {
526 			switch (uio->uio_segflg) {
527 			case UIO_USERSPACE:
528 			case UIO_USERISPACE:
529 				if (fuword8(p, &tmp))
530 					return;
531 				break;
532 			case UIO_SYSSPACE:
533 				if (kcopy(p, &tmp, 1))
534 					return;
535 				break;
536 			}
537 			incr = MIN(cnt, PAGESIZE);
538 			p += incr;
539 			cnt -= incr;
540 		}
541 		/*
542 		 * touch the last byte in case it straddles a page.
543 		 */
544 		p--;
545 		switch (uio->uio_segflg) {
546 		case UIO_USERSPACE:
547 		case UIO_USERISPACE:
548 			if (fuword8(p, &tmp))
549 				return;
550 			break;
551 		case UIO_SYSSPACE:
552 			if (kcopy(p, &tmp, 1))
553 				return;
554 			break;
555 		}
556 		iov++;
557 	}
558 }
559 
560 /*
561  * Write the bytes to a file.
562  *
563  *	IN:	vp	- vnode of file to be written to.
564  *		uio	- structure supplying write location, range info,
565  *			  and data buffer.
566  *		ioflag	- FAPPEND flag set if in append mode.
567  *		cr	- credentials of caller.
568  *
569  *	OUT:	uio	- updated offset and range.
570  *
571  *	RETURN:	0 if success
572  *		error code if failure
573  *
574  * Timestamps:
575  *	vp - ctime|mtime updated if byte count > 0
576  */
577 /* ARGSUSED */
578 static int
579 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
580 {
581 	znode_t		*zp = VTOZ(vp);
582 	rlim64_t	limit = uio->uio_llimit;
583 	ssize_t		start_resid = uio->uio_resid;
584 	ssize_t		tx_bytes;
585 	uint64_t	end_size;
586 	dmu_tx_t	*tx;
587 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
588 	zilog_t		*zilog = zfsvfs->z_log;
589 	uint64_t	seq = 0;
590 	offset_t	woff;
591 	ssize_t		n, nbytes;
592 	rl_t		*rl;
593 	int		max_blksz = zfsvfs->z_max_blksz;
594 	int		error;
595 
596 	/*
597 	 * Fasttrack empty write
598 	 */
599 	n = start_resid;
600 	if (n == 0)
601 		return (0);
602 
603 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
604 		limit = MAXOFFSET_T;
605 
606 	ZFS_ENTER(zfsvfs);
607 
608 	/*
609 	 * Pre-fault the pages to ensure slow (eg NFS) pages
610 	 * don't hold up txg.
611 	 */
612 	zfs_prefault_write(n, uio);
613 
614 	/*
615 	 * If in append mode, set the io offset pointer to eof.
616 	 */
617 	if (ioflag & FAPPEND) {
618 		/*
619 		 * Range lock for a file append:
620 		 * The value for the start of range will be determined by
621 		 * zfs_range_lock() (to guarantee append semantics).
622 		 * If this write will cause the block size to increase,
623 		 * zfs_range_lock() will lock the entire file, so we must
624 		 * later reduce the range after we grow the block size.
625 		 */
626 		rl = zfs_range_lock(zp, 0, n, RL_APPEND);
627 		if (rl->r_len == UINT64_MAX) {
628 			/* overlocked, zp_size can't change */
629 			woff = uio->uio_loffset = zp->z_phys->zp_size;
630 		} else {
631 			woff = uio->uio_loffset = rl->r_off;
632 		}
633 	} else {
634 		woff = uio->uio_loffset;
635 		/*
636 		 * Validate file offset
637 		 */
638 		if (woff < 0) {
639 			ZFS_EXIT(zfsvfs);
640 			return (EINVAL);
641 		}
642 
643 		/*
644 		 * If we need to grow the block size then zfs_range_lock()
645 		 * will lock a wider range than we request here.
646 		 * Later after growing the block size we reduce the range.
647 		 */
648 		rl = zfs_range_lock(zp, woff, n, RL_WRITER);
649 	}
650 
651 	if (woff >= limit) {
652 		error = EFBIG;
653 		goto no_tx_done;
654 	}
655 
656 	if ((woff + n) > limit || woff > (limit - n))
657 		n = limit - woff;
658 
659 	/*
660 	 * Check for mandatory locks
661 	 */
662 	if (MANDMODE((mode_t)zp->z_phys->zp_mode) &&
663 	    (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0)
664 		goto no_tx_done;
665 	end_size = MAX(zp->z_phys->zp_size, woff + n);
666 top:
667 	tx = dmu_tx_create(zfsvfs->z_os);
668 	dmu_tx_hold_bonus(tx, zp->z_id);
669 	dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
670 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
671 	if (error) {
672 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
673 			dmu_tx_wait(tx);
674 			dmu_tx_abort(tx);
675 			goto top;
676 		}
677 		dmu_tx_abort(tx);
678 		goto no_tx_done;
679 	}
680 
681 	/*
682 	 * If zfs_range_lock() over-locked we grow the blocksize
683 	 * and then reduce the lock range.
684 	 */
685 	if (rl->r_len == UINT64_MAX) {
686 		uint64_t new_blksz;
687 
688 		if (zp->z_blksz > max_blksz) {
689 			ASSERT(!ISP2(zp->z_blksz));
690 			new_blksz = MIN(end_size, SPA_MAXBLOCKSIZE);
691 		} else {
692 			new_blksz = MIN(end_size, max_blksz);
693 		}
694 		zfs_grow_blocksize(zp, new_blksz, tx);
695 		zfs_range_reduce(rl, woff, n);
696 	}
697 
698 	/*
699 	 * The file data does not fit in the znode "cache", so we
700 	 * will be writing to the file block data buffers.
701 	 * Each buffer will be written in a separate transaction;
702 	 * this keeps the intent log records small and allows us
703 	 * to do more fine-grained space accounting.
704 	 */
705 	while (n > 0) {
706 		/*
707 		 * XXX - should we really limit each write to z_max_blksz?
708 		 * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
709 		 */
710 		nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
711 		rw_enter(&zp->z_map_lock, RW_READER);
712 
713 		tx_bytes = uio->uio_resid;
714 		if (vn_has_cached_data(vp)) {
715 			rw_exit(&zp->z_map_lock);
716 			error = mappedwrite(vp, woff, nbytes, uio, tx);
717 		} else {
718 			error = dmu_write_uio(zfsvfs->z_os, zp->z_id,
719 			    woff, nbytes, uio, tx);
720 			rw_exit(&zp->z_map_lock);
721 		}
722 		tx_bytes -= uio->uio_resid;
723 
724 		if (error) {
725 			/* XXX - do we need to "clean up" the dmu buffer? */
726 			break;
727 		}
728 
729 		ASSERT(tx_bytes == nbytes);
730 
731 		/*
732 		 * Clear Set-UID/Set-GID bits on successful write if not
733 		 * privileged and at least one of the excute bits is set.
734 		 *
735 		 * It would be nice to to this after all writes have
736 		 * been done, but that would still expose the ISUID/ISGID
737 		 * to another app after the partial write is committed.
738 		 */
739 
740 		mutex_enter(&zp->z_acl_lock);
741 		if ((zp->z_phys->zp_mode & (S_IXUSR | (S_IXUSR >> 3) |
742 		    (S_IXUSR >> 6))) != 0 &&
743 		    (zp->z_phys->zp_mode & (S_ISUID | S_ISGID)) != 0 &&
744 		    secpolicy_vnode_setid_retain(cr,
745 		    (zp->z_phys->zp_mode & S_ISUID) != 0 &&
746 		    zp->z_phys->zp_uid == 0) != 0) {
747 			    zp->z_phys->zp_mode &= ~(S_ISUID | S_ISGID);
748 		}
749 		mutex_exit(&zp->z_acl_lock);
750 
751 		n -= nbytes;
752 		if (n <= 0)
753 			break;
754 
755 		/*
756 		 * We have more work ahead of us, so wrap up this transaction
757 		 * and start another.  Exact same logic as tx_done below.
758 		 */
759 		while ((end_size = zp->z_phys->zp_size) < uio->uio_loffset) {
760 			dmu_buf_will_dirty(zp->z_dbuf, tx);
761 			(void) atomic_cas_64(&zp->z_phys->zp_size, end_size,
762 			    uio->uio_loffset);
763 		}
764 		zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
765 		seq = zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes,
766 		    ioflag, uio);
767 		dmu_tx_commit(tx);
768 
769 		/*
770 		 * Start another transaction.
771 		 */
772 		woff = uio->uio_loffset;
773 		tx = dmu_tx_create(zfsvfs->z_os);
774 		dmu_tx_hold_bonus(tx, zp->z_id);
775 		dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
776 		error = dmu_tx_assign(tx, zfsvfs->z_assign);
777 		if (error) {
778 			if (error == ERESTART &&
779 			    zfsvfs->z_assign == TXG_NOWAIT) {
780 				dmu_tx_wait(tx);
781 				dmu_tx_abort(tx);
782 				goto top;
783 			}
784 			dmu_tx_abort(tx);
785 			goto no_tx_done;
786 		}
787 	}
788 
789 tx_done:
790 
791 	if (tx_bytes != 0) {
792 		/*
793 		 * Update the file size if it has changed; account
794 		 * for possible concurrent updates.
795 		 */
796 		while ((end_size = zp->z_phys->zp_size) < uio->uio_loffset) {
797 			dmu_buf_will_dirty(zp->z_dbuf, tx);
798 			(void) atomic_cas_64(&zp->z_phys->zp_size, end_size,
799 			    uio->uio_loffset);
800 		}
801 		zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
802 		seq = zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes,
803 		    ioflag, uio);
804 	}
805 	dmu_tx_commit(tx);
806 
807 
808 no_tx_done:
809 
810 	zfs_range_unlock(rl);
811 
812 	/*
813 	 * If we're in replay mode, or we made no progress, return error.
814 	 * Otherwise, it's at least a partial write, so it's successful.
815 	 */
816 	if (zfsvfs->z_assign >= TXG_INITIAL || uio->uio_resid == start_resid) {
817 		ZFS_EXIT(zfsvfs);
818 		return (error);
819 	}
820 
821 	zil_commit(zilog, seq, ioflag & (FSYNC | FDSYNC));
822 
823 	ZFS_EXIT(zfsvfs);
824 	return (0);
825 }
826 
827 void
828 zfs_get_done(dmu_buf_t *db, void *vrl)
829 {
830 	rl_t *rl = (rl_t *)vrl;
831 	vnode_t *vp = ZTOV(rl->r_zp);
832 
833 	dmu_buf_rele(db, rl);
834 	zfs_range_unlock(rl);
835 	VN_RELE(vp);
836 }
837 
838 /*
839  * Get data to generate a TX_WRITE intent log record.
840  */
841 int
842 zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
843 {
844 	zfsvfs_t *zfsvfs = arg;
845 	objset_t *os = zfsvfs->z_os;
846 	znode_t *zp;
847 	uint64_t off = lr->lr_offset;
848 	dmu_buf_t *db;
849 	rl_t *rl;
850 	int dlen = lr->lr_length;  		/* length of user data */
851 	int error = 0;
852 
853 	ASSERT(dlen != 0);
854 
855 	/*
856 	 * Nothing to do if the file has been removed
857 	 */
858 	if (zfs_zget(zfsvfs, lr->lr_foid, &zp) != 0)
859 		return (ENOENT);
860 	if (zp->z_reap) {
861 		VN_RELE(ZTOV(zp));
862 		return (ENOENT);
863 	}
864 
865 	/*
866 	 * Write records come in two flavors: immediate and indirect.
867 	 * For small writes it's cheaper to store the data with the
868 	 * log record (immediate); for large writes it's cheaper to
869 	 * sync the data and get a pointer to it (indirect) so that
870 	 * we don't have to write the data twice.
871 	 */
872 	if (buf != NULL) { /* immediate write */
873 		rl = zfs_range_lock(zp, off, dlen, RL_READER);
874 		/* test for truncation needs to be done while range locked */
875 		if (off >= zp->z_phys->zp_size) {
876 			error = ENOENT;
877 			goto out;
878 		}
879 		VERIFY(0 == dmu_buf_hold(os, lr->lr_foid, off, FTAG, &db));
880 		bcopy((char *)db->db_data + off - db->db_offset, buf, dlen);
881 		dmu_buf_rele(db, FTAG);
882 	} else { /* indirect write */
883 		uint64_t boff; /* block starting offset */
884 
885 		/*
886 		 * Have to lock the whole block to ensure when it's
887 		 * written out and it's checksum is being calculated
888 		 * that no one can change the data. We need to re-check
889 		 * blocksize after we get the lock in case it's changed!
890 		 */
891 		for (;;) {
892 			if (ISP2(zp->z_blksz)) {
893 				boff = P2ALIGN_TYPED(off, zp->z_blksz,
894 				    uint64_t);
895 			} else {
896 				boff = 0;
897 			}
898 			dlen = zp->z_blksz;
899 			rl = zfs_range_lock(zp, boff, dlen, RL_READER);
900 			if (zp->z_blksz == dlen)
901 				break;
902 			zfs_range_unlock(rl);
903 		}
904 		/* test for truncation needs to be done while range locked */
905 		if (off >= zp->z_phys->zp_size) {
906 			error = ENOENT;
907 			goto out;
908 		}
909 		VERIFY(0 == dmu_buf_hold(os, lr->lr_foid, boff, rl, &db));
910 		ASSERT(boff == db->db_offset);
911 		lr->lr_blkoff = off - boff;
912 		error = dmu_sync(zio, db, &lr->lr_blkptr,
913 		    lr->lr_common.lrc_txg, zio ? zfs_get_done : NULL, rl);
914 		/*
915 		 * If we get EINPROGRESS, then we need to wait for a
916 		 * write IO initiated by dmu_sync() to complete before
917 		 * we can release this dbuf.  We will finish everthing
918 		 * up in the zfs_get_done() callback.
919 		 */
920 		if (error == EINPROGRESS)
921 			return (0);
922 		dmu_buf_rele(db, rl);
923 	}
924 out:
925 	zfs_range_unlock(rl);
926 	VN_RELE(ZTOV(zp));
927 	return (error);
928 }
929 
930 /*ARGSUSED*/
931 static int
932 zfs_access(vnode_t *vp, int mode, int flags, cred_t *cr)
933 {
934 	znode_t *zp = VTOZ(vp);
935 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
936 	int error;
937 
938 	ZFS_ENTER(zfsvfs);
939 	error = zfs_zaccess_rwx(zp, mode, cr);
940 	ZFS_EXIT(zfsvfs);
941 	return (error);
942 }
943 
944 /*
945  * Lookup an entry in a directory, or an extended attribute directory.
946  * If it exists, return a held vnode reference for it.
947  *
948  *	IN:	dvp	- vnode of directory to search.
949  *		nm	- name of entry to lookup.
950  *		pnp	- full pathname to lookup [UNUSED].
951  *		flags	- LOOKUP_XATTR set if looking for an attribute.
952  *		rdir	- root directory vnode [UNUSED].
953  *		cr	- credentials of caller.
954  *
955  *	OUT:	vpp	- vnode of located entry, NULL if not found.
956  *
957  *	RETURN:	0 if success
958  *		error code if failure
959  *
960  * Timestamps:
961  *	NA
962  */
963 /* ARGSUSED */
964 static int
965 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
966     int flags, vnode_t *rdir, cred_t *cr)
967 {
968 
969 	znode_t *zdp = VTOZ(dvp);
970 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
971 	int	error;
972 
973 	ZFS_ENTER(zfsvfs);
974 
975 	*vpp = NULL;
976 
977 	if (flags & LOOKUP_XATTR) {
978 		/*
979 		 * We don't allow recursive attributes..
980 		 * Maybe someday we will.
981 		 */
982 		if (zdp->z_phys->zp_flags & ZFS_XATTR) {
983 			ZFS_EXIT(zfsvfs);
984 			return (EINVAL);
985 		}
986 
987 		if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr)) {
988 			ZFS_EXIT(zfsvfs);
989 			return (error);
990 		}
991 
992 		/*
993 		 * Do we have permission to get into attribute directory?
994 		 */
995 
996 		if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, cr)) {
997 			VN_RELE(*vpp);
998 		}
999 
1000 		ZFS_EXIT(zfsvfs);
1001 		return (error);
1002 	}
1003 
1004 	if (dvp->v_type != VDIR) {
1005 		ZFS_EXIT(zfsvfs);
1006 		return (ENOTDIR);
1007 	}
1008 
1009 	/*
1010 	 * Check accessibility of directory.
1011 	 */
1012 
1013 	if (error = zfs_zaccess(zdp, ACE_EXECUTE, cr)) {
1014 		ZFS_EXIT(zfsvfs);
1015 		return (error);
1016 	}
1017 
1018 	if ((error = zfs_dirlook(zdp, nm, vpp)) == 0) {
1019 
1020 		/*
1021 		 * Convert device special files
1022 		 */
1023 		if (IS_DEVVP(*vpp)) {
1024 			vnode_t	*svp;
1025 
1026 			svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1027 			VN_RELE(*vpp);
1028 			if (svp == NULL)
1029 				error = ENOSYS;
1030 			else
1031 				*vpp = svp;
1032 		}
1033 	}
1034 
1035 	ZFS_EXIT(zfsvfs);
1036 	return (error);
1037 }
1038 
1039 /*
1040  * Attempt to create a new entry in a directory.  If the entry
1041  * already exists, truncate the file if permissible, else return
1042  * an error.  Return the vp of the created or trunc'd file.
1043  *
1044  *	IN:	dvp	- vnode of directory to put new file entry in.
1045  *		name	- name of new file entry.
1046  *		vap	- attributes of new file.
1047  *		excl	- flag indicating exclusive or non-exclusive mode.
1048  *		mode	- mode to open file with.
1049  *		cr	- credentials of caller.
1050  *		flag	- large file flag [UNUSED].
1051  *
1052  *	OUT:	vpp	- vnode of created or trunc'd entry.
1053  *
1054  *	RETURN:	0 if success
1055  *		error code if failure
1056  *
1057  * Timestamps:
1058  *	dvp - ctime|mtime updated if new entry created
1059  *	 vp - ctime|mtime always, atime if new
1060  */
1061 /* ARGSUSED */
1062 static int
1063 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, vcexcl_t excl,
1064     int mode, vnode_t **vpp, cred_t *cr, int flag)
1065 {
1066 	znode_t		*zp, *dzp = VTOZ(dvp);
1067 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1068 	zilog_t		*zilog = zfsvfs->z_log;
1069 	uint64_t	seq = 0;
1070 	objset_t	*os = zfsvfs->z_os;
1071 	zfs_dirlock_t	*dl;
1072 	dmu_tx_t	*tx;
1073 	int		error;
1074 	uint64_t	zoid;
1075 
1076 	ZFS_ENTER(zfsvfs);
1077 
1078 top:
1079 	*vpp = NULL;
1080 
1081 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1082 		vap->va_mode &= ~VSVTX;
1083 
1084 	if (*name == '\0') {
1085 		/*
1086 		 * Null component name refers to the directory itself.
1087 		 */
1088 		VN_HOLD(dvp);
1089 		zp = dzp;
1090 		dl = NULL;
1091 		error = 0;
1092 	} else {
1093 		/* possible VN_HOLD(zp) */
1094 		if (error = zfs_dirent_lock(&dl, dzp, name, &zp, 0)) {
1095 			if (strcmp(name, "..") == 0)
1096 				error = EISDIR;
1097 			ZFS_EXIT(zfsvfs);
1098 			return (error);
1099 		}
1100 	}
1101 
1102 	zoid = zp ? zp->z_id : -1ULL;
1103 
1104 	if (zp == NULL) {
1105 		/*
1106 		 * Create a new file object and update the directory
1107 		 * to reference it.
1108 		 */
1109 		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
1110 			goto out;
1111 		}
1112 
1113 		/*
1114 		 * We only support the creation of regular files in
1115 		 * extended attribute directories.
1116 		 */
1117 		if ((dzp->z_phys->zp_flags & ZFS_XATTR) &&
1118 		    (vap->va_type != VREG)) {
1119 			error = EINVAL;
1120 			goto out;
1121 		}
1122 
1123 		tx = dmu_tx_create(os);
1124 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1125 		dmu_tx_hold_bonus(tx, dzp->z_id);
1126 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1127 		if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
1128 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1129 			    0, SPA_MAXBLOCKSIZE);
1130 		error = dmu_tx_assign(tx, zfsvfs->z_assign);
1131 		if (error) {
1132 			zfs_dirent_unlock(dl);
1133 			if (error == ERESTART &&
1134 			    zfsvfs->z_assign == TXG_NOWAIT) {
1135 				dmu_tx_wait(tx);
1136 				dmu_tx_abort(tx);
1137 				goto top;
1138 			}
1139 			dmu_tx_abort(tx);
1140 			ZFS_EXIT(zfsvfs);
1141 			return (error);
1142 		}
1143 		zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
1144 		ASSERT(zp->z_id == zoid);
1145 		(void) zfs_link_create(dl, zp, tx, ZNEW);
1146 		seq = zfs_log_create(zilog, tx, TX_CREATE, dzp, zp, name);
1147 		dmu_tx_commit(tx);
1148 	} else {
1149 		/*
1150 		 * A directory entry already exists for this name.
1151 		 */
1152 		/*
1153 		 * Can't truncate an existing file if in exclusive mode.
1154 		 */
1155 		if (excl == EXCL) {
1156 			error = EEXIST;
1157 			goto out;
1158 		}
1159 		/*
1160 		 * Can't open a directory for writing.
1161 		 */
1162 		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1163 			error = EISDIR;
1164 			goto out;
1165 		}
1166 		/*
1167 		 * Verify requested access to file.
1168 		 */
1169 		if (mode && (error = zfs_zaccess_rwx(zp, mode, cr))) {
1170 			goto out;
1171 		}
1172 
1173 		mutex_enter(&dzp->z_lock);
1174 		dzp->z_seq++;
1175 		mutex_exit(&dzp->z_lock);
1176 
1177 		/*
1178 		 * Truncate regular files if requested.
1179 		 */
1180 		if ((ZTOV(zp)->v_type == VREG) &&
1181 		    (zp->z_phys->zp_size != 0) &&
1182 		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1183 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1184 			if (error == ERESTART &&
1185 			    zfsvfs->z_assign == TXG_NOWAIT) {
1186 				/* NB: we already did dmu_tx_wait() */
1187 				zfs_dirent_unlock(dl);
1188 				VN_RELE(ZTOV(zp));
1189 				goto top;
1190 			}
1191 		}
1192 	}
1193 out:
1194 
1195 	if (dl)
1196 		zfs_dirent_unlock(dl);
1197 
1198 	if (error) {
1199 		if (zp)
1200 			VN_RELE(ZTOV(zp));
1201 	} else {
1202 		*vpp = ZTOV(zp);
1203 		/*
1204 		 * If vnode is for a device return a specfs vnode instead.
1205 		 */
1206 		if (IS_DEVVP(*vpp)) {
1207 			struct vnode *svp;
1208 
1209 			svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1210 			VN_RELE(*vpp);
1211 			if (svp == NULL) {
1212 				error = ENOSYS;
1213 			}
1214 			*vpp = svp;
1215 		}
1216 	}
1217 
1218 	zil_commit(zilog, seq, 0);
1219 
1220 	ZFS_EXIT(zfsvfs);
1221 	return (error);
1222 }
1223 
1224 /*
1225  * Remove an entry from a directory.
1226  *
1227  *	IN:	dvp	- vnode of directory to remove entry from.
1228  *		name	- name of entry to remove.
1229  *		cr	- credentials of caller.
1230  *
1231  *	RETURN:	0 if success
1232  *		error code if failure
1233  *
1234  * Timestamps:
1235  *	dvp - ctime|mtime
1236  *	 vp - ctime (if nlink > 0)
1237  */
1238 static int
1239 zfs_remove(vnode_t *dvp, char *name, cred_t *cr)
1240 {
1241 	znode_t		*zp, *dzp = VTOZ(dvp);
1242 	znode_t		*xzp = NULL;
1243 	vnode_t		*vp;
1244 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1245 	zilog_t		*zilog = zfsvfs->z_log;
1246 	uint64_t	seq = 0;
1247 	uint64_t	acl_obj, xattr_obj;
1248 	zfs_dirlock_t	*dl;
1249 	dmu_tx_t	*tx;
1250 	int		may_delete_now, delete_now = FALSE;
1251 	int		reaped;
1252 	int		error;
1253 
1254 	ZFS_ENTER(zfsvfs);
1255 
1256 top:
1257 	/*
1258 	 * Attempt to lock directory; fail if entry doesn't exist.
1259 	 */
1260 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZEXISTS)) {
1261 		ZFS_EXIT(zfsvfs);
1262 		return (error);
1263 	}
1264 
1265 	vp = ZTOV(zp);
1266 
1267 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1268 		goto out;
1269 	}
1270 
1271 	/*
1272 	 * Need to use rmdir for removing directories.
1273 	 */
1274 	if (vp->v_type == VDIR) {
1275 		error = EPERM;
1276 		goto out;
1277 	}
1278 
1279 	vnevent_remove(vp);
1280 
1281 	dnlc_remove(dvp, name);
1282 
1283 	mutex_enter(&vp->v_lock);
1284 	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1285 	mutex_exit(&vp->v_lock);
1286 
1287 	/*
1288 	 * We may delete the znode now, or we may put it on the delete queue;
1289 	 * it depends on whether we're the last link, and on whether there are
1290 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1291 	 * allow for either case.
1292 	 */
1293 	tx = dmu_tx_create(zfsvfs->z_os);
1294 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1295 	dmu_tx_hold_bonus(tx, zp->z_id);
1296 	if (may_delete_now)
1297 		dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
1298 
1299 	/* are there any extended attributes? */
1300 	if ((xattr_obj = zp->z_phys->zp_xattr) != 0) {
1301 		/*
1302 		 * XXX - There is a possibility that the delete
1303 		 * of the parent file could succeed, but then we get
1304 		 * an ENOSPC when we try to delete the xattrs...
1305 		 * so we would need to re-try the deletes periodically
1306 		 */
1307 		/* XXX - do we need this if we are deleting? */
1308 		dmu_tx_hold_bonus(tx, xattr_obj);
1309 	}
1310 
1311 	/* are there any additional acls */
1312 	if ((acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj) != 0 &&
1313 	    may_delete_now)
1314 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1315 
1316 	/* charge as an update -- would be nice not to charge at all */
1317 	dmu_tx_hold_zap(tx, zfsvfs->z_dqueue, FALSE, NULL);
1318 
1319 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1320 	if (error) {
1321 		zfs_dirent_unlock(dl);
1322 		VN_RELE(vp);
1323 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1324 			dmu_tx_wait(tx);
1325 			dmu_tx_abort(tx);
1326 			goto top;
1327 		}
1328 		dmu_tx_abort(tx);
1329 		ZFS_EXIT(zfsvfs);
1330 		return (error);
1331 	}
1332 
1333 	/*
1334 	 * Remove the directory entry.
1335 	 */
1336 	error = zfs_link_destroy(dl, zp, tx, 0, &reaped);
1337 
1338 	if (error) {
1339 		dmu_tx_commit(tx);
1340 		goto out;
1341 	}
1342 
1343 	if (reaped) {
1344 		mutex_enter(&vp->v_lock);
1345 		delete_now = may_delete_now &&
1346 		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1347 		    zp->z_phys->zp_xattr == xattr_obj &&
1348 		    zp->z_phys->zp_acl.z_acl_extern_obj == acl_obj;
1349 		mutex_exit(&vp->v_lock);
1350 	}
1351 
1352 	if (delete_now) {
1353 		if (zp->z_phys->zp_xattr) {
1354 			error = zfs_zget(zfsvfs, zp->z_phys->zp_xattr, &xzp);
1355 			ASSERT3U(error, ==, 0);
1356 			ASSERT3U(xzp->z_phys->zp_links, ==, 2);
1357 			dmu_buf_will_dirty(xzp->z_dbuf, tx);
1358 			mutex_enter(&xzp->z_lock);
1359 			xzp->z_reap = 1;
1360 			xzp->z_phys->zp_links = 0;
1361 			mutex_exit(&xzp->z_lock);
1362 			zfs_dq_add(xzp, tx);
1363 			zp->z_phys->zp_xattr = 0; /* probably unnecessary */
1364 		}
1365 		mutex_enter(&zp->z_lock);
1366 		mutex_enter(&vp->v_lock);
1367 		vp->v_count--;
1368 		ASSERT3U(vp->v_count, ==, 0);
1369 		mutex_exit(&vp->v_lock);
1370 		zp->z_active = 0;
1371 		mutex_exit(&zp->z_lock);
1372 		zfs_znode_delete(zp, tx);
1373 		VFS_RELE(zfsvfs->z_vfs);
1374 	} else if (reaped) {
1375 		zfs_dq_add(zp, tx);
1376 	}
1377 
1378 	seq = zfs_log_remove(zilog, tx, TX_REMOVE, dzp, name);
1379 
1380 	dmu_tx_commit(tx);
1381 out:
1382 	zfs_dirent_unlock(dl);
1383 
1384 	if (!delete_now) {
1385 		VN_RELE(vp);
1386 	} else if (xzp) {
1387 		/* this rele delayed to prevent nesting transactions */
1388 		VN_RELE(ZTOV(xzp));
1389 	}
1390 
1391 	zil_commit(zilog, seq, 0);
1392 
1393 	ZFS_EXIT(zfsvfs);
1394 	return (error);
1395 }
1396 
1397 /*
1398  * Create a new directory and insert it into dvp using the name
1399  * provided.  Return a pointer to the inserted directory.
1400  *
1401  *	IN:	dvp	- vnode of directory to add subdir to.
1402  *		dirname	- name of new directory.
1403  *		vap	- attributes of new directory.
1404  *		cr	- credentials of caller.
1405  *
1406  *	OUT:	vpp	- vnode of created directory.
1407  *
1408  *	RETURN:	0 if success
1409  *		error code if failure
1410  *
1411  * Timestamps:
1412  *	dvp - ctime|mtime updated
1413  *	 vp - ctime|mtime|atime updated
1414  */
1415 static int
1416 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr)
1417 {
1418 	znode_t		*zp, *dzp = VTOZ(dvp);
1419 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1420 	zilog_t		*zilog = zfsvfs->z_log;
1421 	uint64_t	seq = 0;
1422 	zfs_dirlock_t	*dl;
1423 	uint64_t	zoid = 0;
1424 	dmu_tx_t	*tx;
1425 	int		error;
1426 
1427 	ASSERT(vap->va_type == VDIR);
1428 
1429 	ZFS_ENTER(zfsvfs);
1430 
1431 	if (dzp->z_phys->zp_flags & ZFS_XATTR) {
1432 		ZFS_EXIT(zfsvfs);
1433 		return (EINVAL);
1434 	}
1435 top:
1436 	*vpp = NULL;
1437 
1438 	/*
1439 	 * First make sure the new directory doesn't exist.
1440 	 */
1441 	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, ZNEW)) {
1442 		ZFS_EXIT(zfsvfs);
1443 		return (error);
1444 	}
1445 
1446 	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, cr)) {
1447 		zfs_dirent_unlock(dl);
1448 		ZFS_EXIT(zfsvfs);
1449 		return (error);
1450 	}
1451 
1452 	/*
1453 	 * Add a new entry to the directory.
1454 	 */
1455 	tx = dmu_tx_create(zfsvfs->z_os);
1456 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1457 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1458 	if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
1459 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1460 		    0, SPA_MAXBLOCKSIZE);
1461 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1462 	if (error) {
1463 		zfs_dirent_unlock(dl);
1464 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1465 			dmu_tx_wait(tx);
1466 			dmu_tx_abort(tx);
1467 			goto top;
1468 		}
1469 		dmu_tx_abort(tx);
1470 		ZFS_EXIT(zfsvfs);
1471 		return (error);
1472 	}
1473 
1474 	/*
1475 	 * Create new node.
1476 	 */
1477 	zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
1478 
1479 	/*
1480 	 * Now put new name in parent dir.
1481 	 */
1482 	(void) zfs_link_create(dl, zp, tx, ZNEW);
1483 
1484 	*vpp = ZTOV(zp);
1485 
1486 	seq = zfs_log_create(zilog, tx, TX_MKDIR, dzp, zp, dirname);
1487 	dmu_tx_commit(tx);
1488 
1489 	zfs_dirent_unlock(dl);
1490 
1491 	zil_commit(zilog, seq, 0);
1492 
1493 	ZFS_EXIT(zfsvfs);
1494 	return (0);
1495 }
1496 
1497 /*
1498  * Remove a directory subdir entry.  If the current working
1499  * directory is the same as the subdir to be removed, the
1500  * remove will fail.
1501  *
1502  *	IN:	dvp	- vnode of directory to remove from.
1503  *		name	- name of directory to be removed.
1504  *		cwd	- vnode of current working directory.
1505  *		cr	- credentials of caller.
1506  *
1507  *	RETURN:	0 if success
1508  *		error code if failure
1509  *
1510  * Timestamps:
1511  *	dvp - ctime|mtime updated
1512  */
1513 static int
1514 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr)
1515 {
1516 	znode_t		*dzp = VTOZ(dvp);
1517 	znode_t		*zp;
1518 	vnode_t		*vp;
1519 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1520 	zilog_t		*zilog = zfsvfs->z_log;
1521 	uint64_t	seq = 0;
1522 	zfs_dirlock_t	*dl;
1523 	dmu_tx_t	*tx;
1524 	int		error;
1525 
1526 	ZFS_ENTER(zfsvfs);
1527 
1528 top:
1529 	zp = NULL;
1530 
1531 	/*
1532 	 * Attempt to lock directory; fail if entry doesn't exist.
1533 	 */
1534 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZEXISTS)) {
1535 		ZFS_EXIT(zfsvfs);
1536 		return (error);
1537 	}
1538 
1539 	vp = ZTOV(zp);
1540 
1541 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1542 		goto out;
1543 	}
1544 
1545 	if (vp->v_type != VDIR) {
1546 		error = ENOTDIR;
1547 		goto out;
1548 	}
1549 
1550 	if (vp == cwd) {
1551 		error = EINVAL;
1552 		goto out;
1553 	}
1554 
1555 	vnevent_rmdir(vp);
1556 
1557 	/*
1558 	 * Grab a lock on the parent pointer make sure we play well
1559 	 * with the treewalk and directory rename code.
1560 	 */
1561 	rw_enter(&zp->z_parent_lock, RW_WRITER);
1562 
1563 	tx = dmu_tx_create(zfsvfs->z_os);
1564 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1565 	dmu_tx_hold_bonus(tx, zp->z_id);
1566 	dmu_tx_hold_zap(tx, zfsvfs->z_dqueue, FALSE, NULL);
1567 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1568 	if (error) {
1569 		rw_exit(&zp->z_parent_lock);
1570 		zfs_dirent_unlock(dl);
1571 		VN_RELE(vp);
1572 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1573 			dmu_tx_wait(tx);
1574 			dmu_tx_abort(tx);
1575 			goto top;
1576 		}
1577 		dmu_tx_abort(tx);
1578 		ZFS_EXIT(zfsvfs);
1579 		return (error);
1580 	}
1581 
1582 	error = zfs_link_destroy(dl, zp, tx, 0, NULL);
1583 
1584 	if (error == 0)
1585 		seq = zfs_log_remove(zilog, tx, TX_RMDIR, dzp, name);
1586 
1587 	dmu_tx_commit(tx);
1588 
1589 	rw_exit(&zp->z_parent_lock);
1590 out:
1591 	zfs_dirent_unlock(dl);
1592 
1593 	VN_RELE(vp);
1594 
1595 	zil_commit(zilog, seq, 0);
1596 
1597 	ZFS_EXIT(zfsvfs);
1598 	return (error);
1599 }
1600 
1601 /*
1602  * Read as many directory entries as will fit into the provided
1603  * buffer from the given directory cursor position (specified in
1604  * the uio structure.
1605  *
1606  *	IN:	vp	- vnode of directory to read.
1607  *		uio	- structure supplying read location, range info,
1608  *			  and return buffer.
1609  *		cr	- credentials of caller.
1610  *
1611  *	OUT:	uio	- updated offset and range, buffer filled.
1612  *		eofp	- set to true if end-of-file detected.
1613  *
1614  *	RETURN:	0 if success
1615  *		error code if failure
1616  *
1617  * Timestamps:
1618  *	vp - atime updated
1619  *
1620  * Note that the low 4 bits of the cookie returned by zap is always zero.
1621  * This allows us to use the low range for "special" directory entries:
1622  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1623  * we use the offset 2 for the '.zfs' directory.
1624  */
1625 /* ARGSUSED */
1626 static int
1627 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp)
1628 {
1629 	znode_t		*zp = VTOZ(vp);
1630 	iovec_t		*iovp;
1631 	dirent64_t	*odp;
1632 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1633 	objset_t	*os;
1634 	caddr_t		outbuf;
1635 	size_t		bufsize;
1636 	zap_cursor_t	zc;
1637 	zap_attribute_t	zap;
1638 	uint_t		bytes_wanted;
1639 	ushort_t	this_reclen;
1640 	uint64_t	offset; /* must be unsigned; checks for < 1 */
1641 	off64_t		*next;
1642 	int		local_eof;
1643 	int		outcount;
1644 	int		error;
1645 	uint8_t		prefetch;
1646 
1647 	ZFS_ENTER(zfsvfs);
1648 
1649 	/*
1650 	 * If we are not given an eof variable,
1651 	 * use a local one.
1652 	 */
1653 	if (eofp == NULL)
1654 		eofp = &local_eof;
1655 
1656 	/*
1657 	 * Check for valid iov_len.
1658 	 */
1659 	if (uio->uio_iov->iov_len <= 0) {
1660 		ZFS_EXIT(zfsvfs);
1661 		return (EINVAL);
1662 	}
1663 
1664 	/*
1665 	 * Quit if directory has been removed (posix)
1666 	 */
1667 	if ((*eofp = zp->z_reap) != 0) {
1668 		ZFS_EXIT(zfsvfs);
1669 		return (0);
1670 	}
1671 
1672 	error = 0;
1673 	os = zfsvfs->z_os;
1674 	offset = uio->uio_loffset;
1675 	prefetch = zp->z_zn_prefetch;
1676 
1677 	/*
1678 	 * Initialize the iterator cursor.
1679 	 */
1680 	if (offset <= 3) {
1681 		/*
1682 		 * Start iteration from the beginning of the directory.
1683 		 */
1684 		zap_cursor_init(&zc, os, zp->z_id);
1685 	} else {
1686 		/*
1687 		 * The offset is a serialized cursor.
1688 		 */
1689 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1690 	}
1691 
1692 	/*
1693 	 * Get space to change directory entries into fs independent format.
1694 	 */
1695 	iovp = uio->uio_iov;
1696 	bytes_wanted = iovp->iov_len;
1697 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
1698 		bufsize = bytes_wanted;
1699 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
1700 		odp = (struct dirent64 *)outbuf;
1701 	} else {
1702 		bufsize = bytes_wanted;
1703 		odp = (struct dirent64 *)iovp->iov_base;
1704 	}
1705 
1706 	/*
1707 	 * Transform to file-system independent format
1708 	 */
1709 	outcount = 0;
1710 	while (outcount < bytes_wanted) {
1711 		/*
1712 		 * Special case `.', `..', and `.zfs'.
1713 		 */
1714 		if (offset == 0) {
1715 			(void) strcpy(zap.za_name, ".");
1716 			zap.za_first_integer = zp->z_id;
1717 			this_reclen = DIRENT64_RECLEN(1);
1718 		} else if (offset == 1) {
1719 			(void) strcpy(zap.za_name, "..");
1720 			zap.za_first_integer = zp->z_phys->zp_parent;
1721 			this_reclen = DIRENT64_RECLEN(2);
1722 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
1723 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
1724 			zap.za_first_integer = ZFSCTL_INO_ROOT;
1725 			this_reclen =
1726 			    DIRENT64_RECLEN(sizeof (ZFS_CTLDIR_NAME) - 1);
1727 		} else {
1728 			/*
1729 			 * Grab next entry.
1730 			 */
1731 			if (error = zap_cursor_retrieve(&zc, &zap)) {
1732 				if ((*eofp = (error == ENOENT)) != 0)
1733 					break;
1734 				else
1735 					goto update;
1736 			}
1737 
1738 			if (zap.za_integer_length != 8 ||
1739 			    zap.za_num_integers != 1) {
1740 				cmn_err(CE_WARN, "zap_readdir: bad directory "
1741 				    "entry, obj = %lld, offset = %lld\n",
1742 				    (u_longlong_t)zp->z_id,
1743 				    (u_longlong_t)offset);
1744 				error = ENXIO;
1745 				goto update;
1746 			}
1747 			this_reclen = DIRENT64_RECLEN(strlen(zap.za_name));
1748 		}
1749 
1750 		/*
1751 		 * Will this entry fit in the buffer?
1752 		 */
1753 		if (outcount + this_reclen > bufsize) {
1754 			/*
1755 			 * Did we manage to fit anything in the buffer?
1756 			 */
1757 			if (!outcount) {
1758 				error = EINVAL;
1759 				goto update;
1760 			}
1761 			break;
1762 		}
1763 		/*
1764 		 * Add this entry:
1765 		 */
1766 		odp->d_ino = (ino64_t)zap.za_first_integer;
1767 		odp->d_reclen = (ushort_t)this_reclen;
1768 		/* NOTE: d_off is the offset for the *next* entry */
1769 		next = &(odp->d_off);
1770 		(void) strncpy(odp->d_name, zap.za_name,
1771 		    DIRENT64_NAMELEN(this_reclen));
1772 		outcount += this_reclen;
1773 		odp = (dirent64_t *)((intptr_t)odp + this_reclen);
1774 
1775 		ASSERT(outcount <= bufsize);
1776 
1777 		/* Prefetch znode */
1778 		if (prefetch)
1779 			dmu_prefetch(os, zap.za_first_integer, 0, 0);
1780 
1781 		/*
1782 		 * Move to the next entry, fill in the previous offset.
1783 		 */
1784 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
1785 			zap_cursor_advance(&zc);
1786 			offset = zap_cursor_serialize(&zc);
1787 		} else {
1788 			offset += 1;
1789 		}
1790 		*next = offset;
1791 	}
1792 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
1793 
1794 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
1795 		iovp->iov_base += outcount;
1796 		iovp->iov_len -= outcount;
1797 		uio->uio_resid -= outcount;
1798 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
1799 		/*
1800 		 * Reset the pointer.
1801 		 */
1802 		offset = uio->uio_loffset;
1803 	}
1804 
1805 update:
1806 	zap_cursor_fini(&zc);
1807 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
1808 		kmem_free(outbuf, bufsize);
1809 
1810 	if (error == ENOENT)
1811 		error = 0;
1812 
1813 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
1814 
1815 	uio->uio_loffset = offset;
1816 	ZFS_EXIT(zfsvfs);
1817 	return (error);
1818 }
1819 
1820 static int
1821 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr)
1822 {
1823 	znode_t	*zp = VTOZ(vp);
1824 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1825 
1826 	/*
1827 	 * Regardless of whether this is required for standards conformance,
1828 	 * this is the logical behavior when fsync() is called on a file with
1829 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
1830 	 * going to be pushed out as part of the zil_commit().
1831 	 */
1832 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
1833 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
1834 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr);
1835 
1836 	ZFS_ENTER(zfsvfs);
1837 	zil_commit(zfsvfs->z_log, zp->z_last_itx, FSYNC);
1838 	ZFS_EXIT(zfsvfs);
1839 	return (0);
1840 }
1841 
1842 /*
1843  * Get the requested file attributes and place them in the provided
1844  * vattr structure.
1845  *
1846  *	IN:	vp	- vnode of file.
1847  *		vap	- va_mask identifies requested attributes.
1848  *		flags	- [UNUSED]
1849  *		cr	- credentials of caller.
1850  *
1851  *	OUT:	vap	- attribute values.
1852  *
1853  *	RETURN:	0 (always succeeds)
1854  */
1855 /* ARGSUSED */
1856 static int
1857 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr)
1858 {
1859 	znode_t *zp = VTOZ(vp);
1860 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1861 	znode_phys_t *pzp = zp->z_phys;
1862 	int	error;
1863 
1864 	ZFS_ENTER(zfsvfs);
1865 
1866 	/*
1867 	 * Return all attributes.  It's cheaper to provide the answer
1868 	 * than to determine whether we were asked the question.
1869 	 */
1870 	mutex_enter(&zp->z_lock);
1871 
1872 	vap->va_type = vp->v_type;
1873 	vap->va_mode = pzp->zp_mode & MODEMASK;
1874 	vap->va_uid = zp->z_phys->zp_uid;
1875 	vap->va_gid = zp->z_phys->zp_gid;
1876 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
1877 	vap->va_nodeid = zp->z_id;
1878 	vap->va_nlink = MIN(pzp->zp_links, UINT32_MAX);	/* nlink_t limit! */
1879 	vap->va_size = pzp->zp_size;
1880 	vap->va_rdev = vp->v_rdev;
1881 	vap->va_seq = zp->z_seq;
1882 
1883 	ZFS_TIME_DECODE(&vap->va_atime, pzp->zp_atime);
1884 	ZFS_TIME_DECODE(&vap->va_mtime, pzp->zp_mtime);
1885 	ZFS_TIME_DECODE(&vap->va_ctime, pzp->zp_ctime);
1886 
1887 	/*
1888 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
1889 	 * Also, if we are the owner don't bother, since owner should
1890 	 * always be allowed to read basic attributes of file.
1891 	 */
1892 	if (!(zp->z_phys->zp_flags & ZFS_ACL_TRIVIAL) &&
1893 	    (zp->z_phys->zp_uid != crgetuid(cr))) {
1894 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, cr)) {
1895 			mutex_exit(&zp->z_lock);
1896 			ZFS_EXIT(zfsvfs);
1897 			return (error);
1898 		}
1899 	}
1900 
1901 	mutex_exit(&zp->z_lock);
1902 
1903 	dmu_object_size_from_db(zp->z_dbuf, &vap->va_blksize, &vap->va_nblocks);
1904 
1905 	if (zp->z_blksz == 0) {
1906 		/*
1907 		 * Block size hasn't been set; suggest maximal I/O transfers.
1908 		 */
1909 		vap->va_blksize = zfsvfs->z_max_blksz;
1910 	}
1911 
1912 	ZFS_EXIT(zfsvfs);
1913 	return (0);
1914 }
1915 
1916 /*
1917  * Set the file attributes to the values contained in the
1918  * vattr structure.
1919  *
1920  *	IN:	vp	- vnode of file to be modified.
1921  *		vap	- new attribute values.
1922  *		flags	- ATTR_UTIME set if non-default time values provided.
1923  *		cr	- credentials of caller.
1924  *
1925  *	RETURN:	0 if success
1926  *		error code if failure
1927  *
1928  * Timestamps:
1929  *	vp - ctime updated, mtime updated if size changed.
1930  */
1931 /* ARGSUSED */
1932 static int
1933 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
1934 	caller_context_t *ct)
1935 {
1936 	struct znode	*zp = VTOZ(vp);
1937 	znode_phys_t	*pzp = zp->z_phys;
1938 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1939 	zilog_t		*zilog = zfsvfs->z_log;
1940 	uint64_t	seq = 0;
1941 	dmu_tx_t	*tx;
1942 	vattr_t		oldva;
1943 	uint_t		mask = vap->va_mask;
1944 	uint_t		saved_mask;
1945 	int		trim_mask = FALSE;
1946 	uint64_t	new_mode;
1947 	znode_t		*attrzp;
1948 	int		need_policy = FALSE;
1949 	int		err;
1950 
1951 	if (mask == 0)
1952 		return (0);
1953 
1954 	if (mask & AT_NOSET)
1955 		return (EINVAL);
1956 
1957 	if (mask & AT_SIZE && vp->v_type == VDIR)
1958 		return (EISDIR);
1959 
1960 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO)
1961 		return (EINVAL);
1962 
1963 	ZFS_ENTER(zfsvfs);
1964 
1965 top:
1966 	attrzp = NULL;
1967 
1968 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
1969 		ZFS_EXIT(zfsvfs);
1970 		return (EROFS);
1971 	}
1972 
1973 	/*
1974 	 * First validate permissions
1975 	 */
1976 
1977 	if (mask & AT_SIZE) {
1978 		err = zfs_zaccess(zp, ACE_WRITE_DATA, cr);
1979 		if (err) {
1980 			ZFS_EXIT(zfsvfs);
1981 			return (err);
1982 		}
1983 		/*
1984 		 * XXX - Note, we are not providing any open
1985 		 * mode flags here (like FNDELAY), so we may
1986 		 * block if there are locks present... this
1987 		 * should be addressed in openat().
1988 		 */
1989 		do {
1990 			err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
1991 			/* NB: we already did dmu_tx_wait() if necessary */
1992 		} while (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT);
1993 		if (err) {
1994 			ZFS_EXIT(zfsvfs);
1995 			return (err);
1996 		}
1997 	}
1998 
1999 	if (mask & (AT_ATIME|AT_MTIME))
2000 		need_policy = zfs_zaccess_v4_perm(zp, ACE_WRITE_ATTRIBUTES, cr);
2001 
2002 	if (mask & (AT_UID|AT_GID)) {
2003 		int	idmask = (mask & (AT_UID|AT_GID));
2004 		int	take_owner;
2005 		int	take_group;
2006 
2007 		/*
2008 		 * NOTE: even if a new mode is being set,
2009 		 * we may clear S_ISUID/S_ISGID bits.
2010 		 */
2011 
2012 		if (!(mask & AT_MODE))
2013 			vap->va_mode = pzp->zp_mode;
2014 
2015 		/*
2016 		 * Take ownership or chgrp to group we are a member of
2017 		 */
2018 
2019 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2020 		take_group = (mask & AT_GID) && groupmember(vap->va_gid, cr);
2021 
2022 		/*
2023 		 * If both AT_UID and AT_GID are set then take_owner and
2024 		 * take_group must both be set in order to allow taking
2025 		 * ownership.
2026 		 *
2027 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2028 		 *
2029 		 */
2030 
2031 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2032 		    ((idmask == AT_UID) && take_owner) ||
2033 		    ((idmask == AT_GID) && take_group)) {
2034 			if (zfs_zaccess_v4_perm(zp, ACE_WRITE_OWNER, cr) == 0) {
2035 				/*
2036 				 * Remove setuid/setgid for non-privileged users
2037 				 */
2038 				secpolicy_setid_clear(vap, cr);
2039 				trim_mask = TRUE;
2040 				saved_mask = vap->va_mask;
2041 			} else {
2042 				need_policy =  TRUE;
2043 			}
2044 		} else {
2045 			need_policy =  TRUE;
2046 		}
2047 	}
2048 
2049 	if (mask & AT_MODE)
2050 		need_policy = TRUE;
2051 
2052 	if (need_policy) {
2053 		mutex_enter(&zp->z_lock);
2054 		oldva.va_mode = pzp->zp_mode;
2055 		oldva.va_uid = zp->z_phys->zp_uid;
2056 		oldva.va_gid = zp->z_phys->zp_gid;
2057 		mutex_exit(&zp->z_lock);
2058 
2059 		/*
2060 		 * If trim_mask is set then take ownership
2061 		 * has been granted.  In that case remove
2062 		 * UID|GID from mask so that
2063 		 * secpolicy_vnode_setattr() doesn't revoke it.
2064 		 */
2065 		if (trim_mask)
2066 			vap->va_mask &= ~(AT_UID|AT_GID);
2067 
2068 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2069 		    (int (*)(void *, int, cred_t *))zfs_zaccess_rwx, zp);
2070 		if (err) {
2071 			ZFS_EXIT(zfsvfs);
2072 			return (err);
2073 		}
2074 
2075 		if (trim_mask)
2076 			vap->va_mask |= (saved_mask & (AT_UID|AT_GID));
2077 	}
2078 
2079 	/*
2080 	 * secpolicy_vnode_setattr, or take ownership may have
2081 	 * changed va_mask
2082 	 */
2083 	mask = vap->va_mask;
2084 
2085 	tx = dmu_tx_create(zfsvfs->z_os);
2086 	dmu_tx_hold_bonus(tx, zp->z_id);
2087 
2088 	if (mask & AT_MODE) {
2089 		uint64_t pmode = pzp->zp_mode;
2090 
2091 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2092 
2093 		if (zp->z_phys->zp_acl.z_acl_extern_obj)
2094 			dmu_tx_hold_write(tx,
2095 			    pzp->zp_acl.z_acl_extern_obj, 0, SPA_MAXBLOCKSIZE);
2096 		else
2097 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2098 			    0, ZFS_ACL_SIZE(MAX_ACL_SIZE));
2099 	}
2100 
2101 	if ((mask & (AT_UID | AT_GID)) && zp->z_phys->zp_xattr != 0) {
2102 		err = zfs_zget(zp->z_zfsvfs, zp->z_phys->zp_xattr, &attrzp);
2103 		if (err) {
2104 			dmu_tx_abort(tx);
2105 			ZFS_EXIT(zfsvfs);
2106 			return (err);
2107 		}
2108 		dmu_tx_hold_bonus(tx, attrzp->z_id);
2109 	}
2110 
2111 	err = dmu_tx_assign(tx, zfsvfs->z_assign);
2112 	if (err) {
2113 		if (attrzp)
2114 			VN_RELE(ZTOV(attrzp));
2115 		if (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2116 			dmu_tx_wait(tx);
2117 			dmu_tx_abort(tx);
2118 			goto top;
2119 		}
2120 		dmu_tx_abort(tx);
2121 		ZFS_EXIT(zfsvfs);
2122 		return (err);
2123 	}
2124 
2125 	dmu_buf_will_dirty(zp->z_dbuf, tx);
2126 
2127 	/*
2128 	 * Set each attribute requested.
2129 	 * We group settings according to the locks they need to acquire.
2130 	 *
2131 	 * Note: you cannot set ctime directly, although it will be
2132 	 * updated as a side-effect of calling this function.
2133 	 */
2134 
2135 	mutex_enter(&zp->z_lock);
2136 
2137 	if (mask & AT_MODE) {
2138 		err = zfs_acl_chmod_setattr(zp, new_mode, tx);
2139 		ASSERT3U(err, ==, 0);
2140 	}
2141 
2142 	if (attrzp)
2143 		mutex_enter(&attrzp->z_lock);
2144 
2145 	if (mask & AT_UID) {
2146 		zp->z_phys->zp_uid = (uint64_t)vap->va_uid;
2147 		if (attrzp) {
2148 			attrzp->z_phys->zp_uid = (uint64_t)vap->va_uid;
2149 		}
2150 	}
2151 
2152 	if (mask & AT_GID) {
2153 		zp->z_phys->zp_gid = (uint64_t)vap->va_gid;
2154 		if (attrzp)
2155 			attrzp->z_phys->zp_gid = (uint64_t)vap->va_gid;
2156 	}
2157 
2158 	if (attrzp)
2159 		mutex_exit(&attrzp->z_lock);
2160 
2161 	if (mask & AT_ATIME)
2162 		ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
2163 
2164 	if (mask & AT_MTIME)
2165 		ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
2166 
2167 	if (mask & AT_SIZE)
2168 		zfs_time_stamper_locked(zp, CONTENT_MODIFIED, tx);
2169 	else if (mask != 0)
2170 		zfs_time_stamper_locked(zp, STATE_CHANGED, tx);
2171 
2172 	if (mask != 0)
2173 		seq = zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask);
2174 
2175 	mutex_exit(&zp->z_lock);
2176 
2177 	if (attrzp)
2178 		VN_RELE(ZTOV(attrzp));
2179 
2180 	dmu_tx_commit(tx);
2181 
2182 	zil_commit(zilog, seq, 0);
2183 
2184 	ZFS_EXIT(zfsvfs);
2185 	return (err);
2186 }
2187 
2188 /*
2189  * Search back through the directory tree, using the ".." entries.
2190  * Lock each directory in the chain to prevent concurrent renames.
2191  * Fail any attempt to move a directory into one of its own descendants.
2192  * XXX - z_parent_lock can overlap with map or grow locks
2193  */
2194 typedef struct zfs_zlock {
2195 	krwlock_t	*zl_rwlock;	/* lock we acquired */
2196 	znode_t		*zl_znode;	/* znode we held */
2197 	struct zfs_zlock *zl_next;	/* next in list */
2198 } zfs_zlock_t;
2199 
2200 static int
2201 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
2202 {
2203 	zfs_zlock_t	*zl;
2204 	znode_t 	*zp = tdzp;
2205 	uint64_t	rootid = zp->z_zfsvfs->z_root;
2206 	uint64_t	*oidp = &zp->z_id;
2207 	krwlock_t	*rwlp = &szp->z_parent_lock;
2208 	krw_t		rw = RW_WRITER;
2209 
2210 	/*
2211 	 * First pass write-locks szp and compares to zp->z_id.
2212 	 * Later passes read-lock zp and compare to zp->z_parent.
2213 	 */
2214 	do {
2215 		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
2216 		zl->zl_rwlock = rwlp;
2217 		zl->zl_znode = NULL;
2218 		zl->zl_next = *zlpp;
2219 		*zlpp = zl;
2220 
2221 		rw_enter(rwlp, rw);
2222 
2223 		if (*oidp == szp->z_id)		/* We're a descendant of szp */
2224 			return (EINVAL);
2225 
2226 		if (*oidp == rootid)		/* We've hit the top */
2227 			return (0);
2228 
2229 		if (rw == RW_READER) {		/* i.e. not the first pass */
2230 			int error = zfs_zget(zp->z_zfsvfs, *oidp, &zp);
2231 			if (error)
2232 				return (error);
2233 			zl->zl_znode = zp;
2234 		}
2235 		oidp = &zp->z_phys->zp_parent;
2236 		rwlp = &zp->z_parent_lock;
2237 		rw = RW_READER;
2238 
2239 	} while (zp->z_id != sdzp->z_id);
2240 
2241 	return (0);
2242 }
2243 
2244 /*
2245  * Drop locks and release vnodes that were held by zfs_rename_lock().
2246  */
2247 static void
2248 zfs_rename_unlock(zfs_zlock_t **zlpp)
2249 {
2250 	zfs_zlock_t *zl;
2251 
2252 	while ((zl = *zlpp) != NULL) {
2253 		if (zl->zl_znode != NULL)
2254 			VN_RELE(ZTOV(zl->zl_znode));
2255 		rw_exit(zl->zl_rwlock);
2256 		*zlpp = zl->zl_next;
2257 		kmem_free(zl, sizeof (*zl));
2258 	}
2259 }
2260 
2261 /*
2262  * Move an entry from the provided source directory to the target
2263  * directory.  Change the entry name as indicated.
2264  *
2265  *	IN:	sdvp	- Source directory containing the "old entry".
2266  *		snm	- Old entry name.
2267  *		tdvp	- Target directory to contain the "new entry".
2268  *		tnm	- New entry name.
2269  *		cr	- credentials of caller.
2270  *
2271  *	RETURN:	0 if success
2272  *		error code if failure
2273  *
2274  * Timestamps:
2275  *	sdvp,tdvp - ctime|mtime updated
2276  */
2277 static int
2278 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr)
2279 {
2280 	znode_t		*tdzp, *szp, *tzp;
2281 	znode_t		*sdzp = VTOZ(sdvp);
2282 	zfsvfs_t	*zfsvfs = sdzp->z_zfsvfs;
2283 	zilog_t		*zilog = zfsvfs->z_log;
2284 	uint64_t	seq = 0;
2285 	vnode_t		*realvp;
2286 	zfs_dirlock_t	*sdl, *tdl;
2287 	dmu_tx_t	*tx;
2288 	zfs_zlock_t	*zl;
2289 	int		cmp, serr, terr, error;
2290 
2291 	ZFS_ENTER(zfsvfs);
2292 
2293 	/*
2294 	 * Make sure we have the real vp for the target directory.
2295 	 */
2296 	if (VOP_REALVP(tdvp, &realvp) == 0)
2297 		tdvp = realvp;
2298 
2299 	if (tdvp->v_vfsp != sdvp->v_vfsp) {
2300 		ZFS_EXIT(zfsvfs);
2301 		return (EXDEV);
2302 	}
2303 
2304 	tdzp = VTOZ(tdvp);
2305 top:
2306 	szp = NULL;
2307 	tzp = NULL;
2308 	zl = NULL;
2309 
2310 	/*
2311 	 * This is to prevent the creation of links into attribute space
2312 	 * by renaming a linked file into/outof an attribute directory.
2313 	 * See the comment in zfs_link() for why this is considered bad.
2314 	 */
2315 	if ((tdzp->z_phys->zp_flags & ZFS_XATTR) !=
2316 	    (sdzp->z_phys->zp_flags & ZFS_XATTR)) {
2317 		ZFS_EXIT(zfsvfs);
2318 		return (EINVAL);
2319 	}
2320 
2321 	/*
2322 	 * Lock source and target directory entries.  To prevent deadlock,
2323 	 * a lock ordering must be defined.  We lock the directory with
2324 	 * the smallest object id first, or if it's a tie, the one with
2325 	 * the lexically first name.
2326 	 */
2327 	if (sdzp->z_id < tdzp->z_id) {
2328 		cmp = -1;
2329 	} else if (sdzp->z_id > tdzp->z_id) {
2330 		cmp = 1;
2331 	} else {
2332 		cmp = strcmp(snm, tnm);
2333 		if (cmp == 0) {
2334 			/*
2335 			 * POSIX: "If the old argument and the new argument
2336 			 * both refer to links to the same existing file,
2337 			 * the rename() function shall return successfully
2338 			 * and perform no other action."
2339 			 */
2340 			ZFS_EXIT(zfsvfs);
2341 			return (0);
2342 		}
2343 	}
2344 	if (cmp < 0) {
2345 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp, ZEXISTS);
2346 		terr = zfs_dirent_lock(&tdl, tdzp, tnm, &tzp, 0);
2347 	} else {
2348 		terr = zfs_dirent_lock(&tdl, tdzp, tnm, &tzp, 0);
2349 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp, ZEXISTS);
2350 	}
2351 
2352 	if (serr) {
2353 		/*
2354 		 * Source entry invalid or not there.
2355 		 */
2356 		if (!terr) {
2357 			zfs_dirent_unlock(tdl);
2358 			if (tzp)
2359 				VN_RELE(ZTOV(tzp));
2360 		}
2361 		if (strcmp(snm, "..") == 0)
2362 			serr = EINVAL;
2363 		ZFS_EXIT(zfsvfs);
2364 		return (serr);
2365 	}
2366 	if (terr) {
2367 		zfs_dirent_unlock(sdl);
2368 		VN_RELE(ZTOV(szp));
2369 		if (strcmp(tnm, "..") == 0)
2370 			terr = EINVAL;
2371 		ZFS_EXIT(zfsvfs);
2372 		return (terr);
2373 	}
2374 
2375 	/*
2376 	 * Must have write access at the source to remove the old entry
2377 	 * and write access at the target to create the new entry.
2378 	 * Note that if target and source are the same, this can be
2379 	 * done in a single check.
2380 	 */
2381 
2382 	if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
2383 		goto out;
2384 
2385 	if (ZTOV(szp)->v_type == VDIR) {
2386 		/*
2387 		 * Check to make sure rename is valid.
2388 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
2389 		 */
2390 		if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
2391 			goto out;
2392 	}
2393 
2394 	/*
2395 	 * Does target exist?
2396 	 */
2397 	if (tzp) {
2398 		/*
2399 		 * Source and target must be the same type.
2400 		 */
2401 		if (ZTOV(szp)->v_type == VDIR) {
2402 			if (ZTOV(tzp)->v_type != VDIR) {
2403 				error = ENOTDIR;
2404 				goto out;
2405 			}
2406 		} else {
2407 			if (ZTOV(tzp)->v_type == VDIR) {
2408 				error = EISDIR;
2409 				goto out;
2410 			}
2411 		}
2412 		/*
2413 		 * POSIX dictates that when the source and target
2414 		 * entries refer to the same file object, rename
2415 		 * must do nothing and exit without error.
2416 		 */
2417 		if (szp->z_id == tzp->z_id) {
2418 			error = 0;
2419 			goto out;
2420 		}
2421 	}
2422 
2423 	vnevent_rename_src(ZTOV(szp));
2424 	if (tzp)
2425 		vnevent_rename_dest(ZTOV(tzp));
2426 
2427 	tx = dmu_tx_create(zfsvfs->z_os);
2428 	dmu_tx_hold_bonus(tx, szp->z_id);	/* nlink changes */
2429 	dmu_tx_hold_bonus(tx, sdzp->z_id);	/* nlink changes */
2430 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
2431 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
2432 	if (sdzp != tdzp)
2433 		dmu_tx_hold_bonus(tx, tdzp->z_id);	/* nlink changes */
2434 	if (tzp)
2435 		dmu_tx_hold_bonus(tx, tzp->z_id);	/* parent changes */
2436 	dmu_tx_hold_zap(tx, zfsvfs->z_dqueue, FALSE, NULL);
2437 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
2438 	if (error) {
2439 		if (zl != NULL)
2440 			zfs_rename_unlock(&zl);
2441 		zfs_dirent_unlock(sdl);
2442 		zfs_dirent_unlock(tdl);
2443 		VN_RELE(ZTOV(szp));
2444 		if (tzp)
2445 			VN_RELE(ZTOV(tzp));
2446 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2447 			dmu_tx_wait(tx);
2448 			dmu_tx_abort(tx);
2449 			goto top;
2450 		}
2451 		dmu_tx_abort(tx);
2452 		ZFS_EXIT(zfsvfs);
2453 		return (error);
2454 	}
2455 
2456 	if (tzp)	/* Attempt to remove the existing target */
2457 		error = zfs_link_destroy(tdl, tzp, tx, 0, NULL);
2458 
2459 	if (error == 0) {
2460 		error = zfs_link_create(tdl, szp, tx, ZRENAMING);
2461 		if (error == 0) {
2462 			error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
2463 			ASSERT(error == 0);
2464 			seq = zfs_log_rename(zilog, tx, TX_RENAME,
2465 			    sdzp, sdl->dl_name, tdzp, tdl->dl_name, szp);
2466 		}
2467 	}
2468 
2469 	dmu_tx_commit(tx);
2470 out:
2471 	if (zl != NULL)
2472 		zfs_rename_unlock(&zl);
2473 
2474 	zfs_dirent_unlock(sdl);
2475 	zfs_dirent_unlock(tdl);
2476 
2477 	VN_RELE(ZTOV(szp));
2478 	if (tzp)
2479 		VN_RELE(ZTOV(tzp));
2480 
2481 	zil_commit(zilog, seq, 0);
2482 
2483 	ZFS_EXIT(zfsvfs);
2484 	return (error);
2485 }
2486 
2487 /*
2488  * Insert the indicated symbolic reference entry into the directory.
2489  *
2490  *	IN:	dvp	- Directory to contain new symbolic link.
2491  *		link	- Name for new symlink entry.
2492  *		vap	- Attributes of new entry.
2493  *		target	- Target path of new symlink.
2494  *		cr	- credentials of caller.
2495  *
2496  *	RETURN:	0 if success
2497  *		error code if failure
2498  *
2499  * Timestamps:
2500  *	dvp - ctime|mtime updated
2501  */
2502 static int
2503 zfs_symlink(vnode_t *dvp, char *name, vattr_t *vap, char *link, cred_t *cr)
2504 {
2505 	znode_t		*zp, *dzp = VTOZ(dvp);
2506 	zfs_dirlock_t	*dl;
2507 	dmu_tx_t	*tx;
2508 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2509 	zilog_t		*zilog = zfsvfs->z_log;
2510 	uint64_t	seq = 0;
2511 	uint64_t	zoid;
2512 	int		len = strlen(link);
2513 	int		error;
2514 
2515 	ASSERT(vap->va_type == VLNK);
2516 
2517 	ZFS_ENTER(zfsvfs);
2518 top:
2519 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
2520 		ZFS_EXIT(zfsvfs);
2521 		return (error);
2522 	}
2523 
2524 	if (len > MAXPATHLEN) {
2525 		ZFS_EXIT(zfsvfs);
2526 		return (ENAMETOOLONG);
2527 	}
2528 
2529 	/*
2530 	 * Attempt to lock directory; fail if entry already exists.
2531 	 */
2532 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZNEW)) {
2533 		ZFS_EXIT(zfsvfs);
2534 		return (error);
2535 	}
2536 
2537 	tx = dmu_tx_create(zfsvfs->z_os);
2538 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
2539 	dmu_tx_hold_bonus(tx, dzp->z_id);
2540 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
2541 	if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
2542 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, SPA_MAXBLOCKSIZE);
2543 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
2544 	if (error) {
2545 		zfs_dirent_unlock(dl);
2546 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2547 			dmu_tx_wait(tx);
2548 			dmu_tx_abort(tx);
2549 			goto top;
2550 		}
2551 		dmu_tx_abort(tx);
2552 		ZFS_EXIT(zfsvfs);
2553 		return (error);
2554 	}
2555 
2556 	dmu_buf_will_dirty(dzp->z_dbuf, tx);
2557 
2558 	/*
2559 	 * Create a new object for the symlink.
2560 	 * Put the link content into bonus buffer if it will fit;
2561 	 * otherwise, store it just like any other file data.
2562 	 */
2563 	zoid = 0;
2564 	if (sizeof (znode_phys_t) + len <= dmu_bonus_max()) {
2565 		zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, len);
2566 		if (len != 0)
2567 			bcopy(link, zp->z_phys + 1, len);
2568 	} else {
2569 		dmu_buf_t *dbp;
2570 
2571 		zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
2572 
2573 		/*
2574 		 * Nothing can access the znode yet so no locking needed
2575 		 * for growing the znode's blocksize.
2576 		 */
2577 		zfs_grow_blocksize(zp, len, tx);
2578 
2579 		VERIFY(0 == dmu_buf_hold(zfsvfs->z_os, zoid, 0, FTAG, &dbp));
2580 		dmu_buf_will_dirty(dbp, tx);
2581 
2582 		ASSERT3U(len, <=, dbp->db_size);
2583 		bcopy(link, dbp->db_data, len);
2584 		dmu_buf_rele(dbp, FTAG);
2585 	}
2586 	zp->z_phys->zp_size = len;
2587 
2588 	/*
2589 	 * Insert the new object into the directory.
2590 	 */
2591 	(void) zfs_link_create(dl, zp, tx, ZNEW);
2592 out:
2593 	if (error == 0)
2594 		seq = zfs_log_symlink(zilog, tx, TX_SYMLINK,
2595 		    dzp, zp, name, link);
2596 
2597 	dmu_tx_commit(tx);
2598 
2599 	zfs_dirent_unlock(dl);
2600 
2601 	VN_RELE(ZTOV(zp));
2602 
2603 	zil_commit(zilog, seq, 0);
2604 
2605 	ZFS_EXIT(zfsvfs);
2606 	return (error);
2607 }
2608 
2609 /*
2610  * Return, in the buffer contained in the provided uio structure,
2611  * the symbolic path referred to by vp.
2612  *
2613  *	IN:	vp	- vnode of symbolic link.
2614  *		uoip	- structure to contain the link path.
2615  *		cr	- credentials of caller.
2616  *
2617  *	OUT:	uio	- structure to contain the link path.
2618  *
2619  *	RETURN:	0 if success
2620  *		error code if failure
2621  *
2622  * Timestamps:
2623  *	vp - atime updated
2624  */
2625 /* ARGSUSED */
2626 static int
2627 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr)
2628 {
2629 	znode_t		*zp = VTOZ(vp);
2630 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2631 	size_t		bufsz;
2632 	int		error;
2633 
2634 	ZFS_ENTER(zfsvfs);
2635 
2636 	bufsz = (size_t)zp->z_phys->zp_size;
2637 	if (bufsz + sizeof (znode_phys_t) <= zp->z_dbuf->db_size) {
2638 		error = uiomove(zp->z_phys + 1,
2639 		    MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
2640 	} else {
2641 		dmu_buf_t *dbp;
2642 		error = dmu_buf_hold(zfsvfs->z_os, zp->z_id, 0, FTAG, &dbp);
2643 		if (error) {
2644 			ZFS_EXIT(zfsvfs);
2645 			return (error);
2646 		}
2647 		error = uiomove(dbp->db_data,
2648 		    MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
2649 		dmu_buf_rele(dbp, FTAG);
2650 	}
2651 
2652 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2653 	ZFS_EXIT(zfsvfs);
2654 	return (error);
2655 }
2656 
2657 /*
2658  * Insert a new entry into directory tdvp referencing svp.
2659  *
2660  *	IN:	tdvp	- Directory to contain new entry.
2661  *		svp	- vnode of new entry.
2662  *		name	- name of new entry.
2663  *		cr	- credentials of caller.
2664  *
2665  *	RETURN:	0 if success
2666  *		error code if failure
2667  *
2668  * Timestamps:
2669  *	tdvp - ctime|mtime updated
2670  *	 svp - ctime updated
2671  */
2672 /* ARGSUSED */
2673 static int
2674 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr)
2675 {
2676 	znode_t		*dzp = VTOZ(tdvp);
2677 	znode_t		*tzp, *szp;
2678 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2679 	zilog_t		*zilog = zfsvfs->z_log;
2680 	uint64_t	seq = 0;
2681 	zfs_dirlock_t	*dl;
2682 	dmu_tx_t	*tx;
2683 	vnode_t		*realvp;
2684 	int		error;
2685 
2686 	ASSERT(tdvp->v_type == VDIR);
2687 
2688 	ZFS_ENTER(zfsvfs);
2689 
2690 	if (VOP_REALVP(svp, &realvp) == 0)
2691 		svp = realvp;
2692 
2693 	if (svp->v_vfsp != tdvp->v_vfsp) {
2694 		ZFS_EXIT(zfsvfs);
2695 		return (EXDEV);
2696 	}
2697 
2698 	szp = VTOZ(svp);
2699 top:
2700 	/*
2701 	 * We do not support links between attributes and non-attributes
2702 	 * because of the potential security risk of creating links
2703 	 * into "normal" file space in order to circumvent restrictions
2704 	 * imposed in attribute space.
2705 	 */
2706 	if ((szp->z_phys->zp_flags & ZFS_XATTR) !=
2707 	    (dzp->z_phys->zp_flags & ZFS_XATTR)) {
2708 		ZFS_EXIT(zfsvfs);
2709 		return (EINVAL);
2710 	}
2711 
2712 	/*
2713 	 * POSIX dictates that we return EPERM here.
2714 	 * Better choices include ENOTSUP or EISDIR.
2715 	 */
2716 	if (svp->v_type == VDIR) {
2717 		ZFS_EXIT(zfsvfs);
2718 		return (EPERM);
2719 	}
2720 
2721 	if ((uid_t)szp->z_phys->zp_uid != crgetuid(cr) &&
2722 	    secpolicy_basic_link(cr) != 0) {
2723 		ZFS_EXIT(zfsvfs);
2724 		return (EPERM);
2725 	}
2726 
2727 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
2728 		ZFS_EXIT(zfsvfs);
2729 		return (error);
2730 	}
2731 
2732 	/*
2733 	 * Attempt to lock directory; fail if entry already exists.
2734 	 */
2735 	if (error = zfs_dirent_lock(&dl, dzp, name, &tzp, ZNEW)) {
2736 		ZFS_EXIT(zfsvfs);
2737 		return (error);
2738 	}
2739 
2740 	tx = dmu_tx_create(zfsvfs->z_os);
2741 	dmu_tx_hold_bonus(tx, szp->z_id);
2742 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
2743 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
2744 	if (error) {
2745 		zfs_dirent_unlock(dl);
2746 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2747 			dmu_tx_wait(tx);
2748 			dmu_tx_abort(tx);
2749 			goto top;
2750 		}
2751 		dmu_tx_abort(tx);
2752 		ZFS_EXIT(zfsvfs);
2753 		return (error);
2754 	}
2755 
2756 	error = zfs_link_create(dl, szp, tx, 0);
2757 
2758 	if (error == 0)
2759 		seq = zfs_log_link(zilog, tx, TX_LINK, dzp, szp, name);
2760 
2761 	dmu_tx_commit(tx);
2762 
2763 	zfs_dirent_unlock(dl);
2764 
2765 	zil_commit(zilog, seq, 0);
2766 
2767 	ZFS_EXIT(zfsvfs);
2768 	return (error);
2769 }
2770 
2771 /*
2772  * zfs_null_putapage() is used when the file system has been force
2773  * unmounted. It just drops the pages.
2774  */
2775 /* ARGSUSED */
2776 static int
2777 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
2778 		size_t *lenp, int flags, cred_t *cr)
2779 {
2780 	pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
2781 	return (0);
2782 }
2783 
2784 /* ARGSUSED */
2785 static int
2786 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
2787 		size_t *lenp, int flags, cred_t *cr)
2788 {
2789 	znode_t		*zp = VTOZ(vp);
2790 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2791 	zilog_t		*zilog = zfsvfs->z_log;
2792 	dmu_tx_t	*tx;
2793 	rl_t		*rl;
2794 	u_offset_t	off;
2795 	ssize_t		len;
2796 	caddr_t		va;
2797 	int		err;
2798 
2799 top:
2800 	off = pp->p_offset;
2801 	rl = zfs_range_lock(zp, off, PAGESIZE, RL_WRITER);
2802 	/*
2803 	 * Can't push pages past end-of-file.
2804 	 */
2805 	if (off >= zp->z_phys->zp_size) {
2806 		zfs_range_unlock(rl);
2807 		return (EIO);
2808 	}
2809 	len = MIN(PAGESIZE, zp->z_phys->zp_size - off);
2810 
2811 	tx = dmu_tx_create(zfsvfs->z_os);
2812 	dmu_tx_hold_write(tx, zp->z_id, off, len);
2813 	dmu_tx_hold_bonus(tx, zp->z_id);
2814 	err = dmu_tx_assign(tx, zfsvfs->z_assign);
2815 	if (err != 0) {
2816 		zfs_range_unlock(rl);
2817 		if (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2818 			dmu_tx_wait(tx);
2819 			dmu_tx_abort(tx);
2820 			goto top;
2821 		}
2822 		dmu_tx_abort(tx);
2823 		goto out;
2824 	}
2825 
2826 	va = ppmapin(pp, PROT_READ | PROT_WRITE, (caddr_t)-1);
2827 
2828 	dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
2829 
2830 	ppmapout(va);
2831 
2832 	zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
2833 	(void) zfs_log_write(zilog, tx, TX_WRITE, zp, off, len, 0, NULL);
2834 	dmu_tx_commit(tx);
2835 
2836 	zfs_range_unlock(rl);
2837 
2838 	pvn_write_done(pp, B_WRITE | flags);
2839 	if (offp)
2840 		*offp = off;
2841 	if (lenp)
2842 		*lenp = len;
2843 
2844 out:
2845 	return (err);
2846 }
2847 
2848 /*
2849  * Copy the portion of the file indicated from pages into the file.
2850  * The pages are stored in a page list attached to the files vnode.
2851  *
2852  *	IN:	vp	- vnode of file to push page data to.
2853  *		off	- position in file to put data.
2854  *		len	- amount of data to write.
2855  *		flags	- flags to control the operation.
2856  *		cr	- credentials of caller.
2857  *
2858  *	RETURN:	0 if success
2859  *		error code if failure
2860  *
2861  * Timestamps:
2862  *	vp - ctime|mtime updated
2863  */
2864 static int
2865 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr)
2866 {
2867 	znode_t		*zp = VTOZ(vp);
2868 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2869 	page_t		*pp;
2870 	size_t		io_len;
2871 	u_offset_t	io_off;
2872 	uint64_t	filesz;
2873 	int		error = 0;
2874 
2875 	ZFS_ENTER(zfsvfs);
2876 
2877 	ASSERT(zp->z_dbuf_held && zp->z_phys);
2878 
2879 	if (len == 0) {
2880 		/*
2881 		 * Search the entire vp list for pages >= off.
2882 		 */
2883 		error = pvn_vplist_dirty(vp, (u_offset_t)off, zfs_putapage,
2884 		    flags, cr);
2885 		goto out;
2886 	}
2887 
2888 	filesz = zp->z_phys->zp_size; /* get consistent copy of zp_size */
2889 	if (off > filesz) {
2890 		/* past end of file */
2891 		ZFS_EXIT(zfsvfs);
2892 		return (0);
2893 	}
2894 
2895 	len = MIN(len, filesz - off);
2896 
2897 	for (io_off = off; io_off < off + len; io_off += io_len) {
2898 		if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
2899 			pp = page_lookup(vp, io_off,
2900 				(flags & (B_INVAL | B_FREE)) ?
2901 					SE_EXCL : SE_SHARED);
2902 		} else {
2903 			pp = page_lookup_nowait(vp, io_off,
2904 				(flags & B_FREE) ? SE_EXCL : SE_SHARED);
2905 		}
2906 
2907 		if (pp != NULL && pvn_getdirty(pp, flags)) {
2908 			int err;
2909 
2910 			/*
2911 			 * Found a dirty page to push
2912 			 */
2913 			err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
2914 			if (err)
2915 				error = err;
2916 		} else {
2917 			io_len = PAGESIZE;
2918 		}
2919 	}
2920 out:
2921 	zil_commit(zfsvfs->z_log, UINT64_MAX, (flags & B_ASYNC) ? 0 : FDSYNC);
2922 	ZFS_EXIT(zfsvfs);
2923 	return (error);
2924 }
2925 
2926 void
2927 zfs_inactive(vnode_t *vp, cred_t *cr)
2928 {
2929 	znode_t	*zp = VTOZ(vp);
2930 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2931 	int error;
2932 
2933 	rw_enter(&zfsvfs->z_um_lock, RW_READER);
2934 	if (zfsvfs->z_unmounted2) {
2935 		ASSERT(zp->z_dbuf_held == 0);
2936 
2937 		if (vn_has_cached_data(vp)) {
2938 			(void) pvn_vplist_dirty(vp, 0, zfs_null_putapage,
2939 			    B_INVAL, cr);
2940 		}
2941 
2942 		mutex_enter(&zp->z_lock);
2943 		vp->v_count = 0; /* count arrives as 1 */
2944 		if (zp->z_dbuf == NULL) {
2945 			mutex_exit(&zp->z_lock);
2946 			zfs_znode_free(zp);
2947 		} else {
2948 			mutex_exit(&zp->z_lock);
2949 		}
2950 		rw_exit(&zfsvfs->z_um_lock);
2951 		VFS_RELE(zfsvfs->z_vfs);
2952 		return;
2953 	}
2954 
2955 	/*
2956 	 * Attempt to push any data in the page cache.  If this fails
2957 	 * we will get kicked out later in zfs_zinactive().
2958 	 */
2959 	if (vn_has_cached_data(vp)) {
2960 		(void) pvn_vplist_dirty(vp, 0, zfs_putapage, B_INVAL|B_ASYNC,
2961 		    cr);
2962 	}
2963 
2964 	if (zp->z_atime_dirty && zp->z_reap == 0) {
2965 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
2966 
2967 		dmu_tx_hold_bonus(tx, zp->z_id);
2968 		error = dmu_tx_assign(tx, TXG_WAIT);
2969 		if (error) {
2970 			dmu_tx_abort(tx);
2971 		} else {
2972 			dmu_buf_will_dirty(zp->z_dbuf, tx);
2973 			mutex_enter(&zp->z_lock);
2974 			zp->z_atime_dirty = 0;
2975 			mutex_exit(&zp->z_lock);
2976 			dmu_tx_commit(tx);
2977 		}
2978 	}
2979 
2980 	zfs_zinactive(zp);
2981 	rw_exit(&zfsvfs->z_um_lock);
2982 }
2983 
2984 /*
2985  * Bounds-check the seek operation.
2986  *
2987  *	IN:	vp	- vnode seeking within
2988  *		ooff	- old file offset
2989  *		noffp	- pointer to new file offset
2990  *
2991  *	RETURN:	0 if success
2992  *		EINVAL if new offset invalid
2993  */
2994 /* ARGSUSED */
2995 static int
2996 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp)
2997 {
2998 	if (vp->v_type == VDIR)
2999 		return (0);
3000 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
3001 }
3002 
3003 /*
3004  * Pre-filter the generic locking function to trap attempts to place
3005  * a mandatory lock on a memory mapped file.
3006  */
3007 static int
3008 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
3009     flk_callback_t *flk_cbp, cred_t *cr)
3010 {
3011 	znode_t *zp = VTOZ(vp);
3012 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3013 	int error;
3014 
3015 	ZFS_ENTER(zfsvfs);
3016 
3017 	/*
3018 	 * We are following the UFS semantics with respect to mapcnt
3019 	 * here: If we see that the file is mapped already, then we will
3020 	 * return an error, but we don't worry about races between this
3021 	 * function and zfs_map().
3022 	 */
3023 	if (zp->z_mapcnt > 0 && MANDMODE((mode_t)zp->z_phys->zp_mode)) {
3024 		ZFS_EXIT(zfsvfs);
3025 		return (EAGAIN);
3026 	}
3027 	error = fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr);
3028 	ZFS_EXIT(zfsvfs);
3029 	return (error);
3030 }
3031 
3032 /*
3033  * If we can't find a page in the cache, we will create a new page
3034  * and fill it with file data.  For efficiency, we may try to fill
3035  * multiple pages at once (klustering).
3036  */
3037 static int
3038 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
3039     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
3040 {
3041 	znode_t *zp = VTOZ(vp);
3042 	page_t *pp, *cur_pp;
3043 	objset_t *os = zp->z_zfsvfs->z_os;
3044 	caddr_t va;
3045 	u_offset_t io_off, total;
3046 	uint64_t oid = zp->z_id;
3047 	size_t io_len;
3048 	uint64_t filesz;
3049 	int err;
3050 
3051 	/*
3052 	 * If we are only asking for a single page don't bother klustering.
3053 	 */
3054 	filesz = zp->z_phys->zp_size; /* get consistent copy of zp_size */
3055 	if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE || off > filesz) {
3056 		io_off = off;
3057 		io_len = PAGESIZE;
3058 		pp = page_create_va(vp, io_off, io_len, PG_WAIT, seg, addr);
3059 	} else {
3060 		/*
3061 		 * Try to fill a kluster of pages (a blocks worth).
3062 		 */
3063 		size_t klen;
3064 		u_offset_t koff;
3065 
3066 		if (!ISP2(zp->z_blksz)) {
3067 			/* Only one block in the file. */
3068 			klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
3069 			koff = 0;
3070 		} else {
3071 			klen = plsz;
3072 			koff = P2ALIGN(off, (u_offset_t)klen);
3073 		}
3074 		ASSERT(koff <= filesz);
3075 		if (koff + klen > filesz)
3076 			klen = P2ROUNDUP(filesz, (uint64_t)PAGESIZE) - koff;
3077 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
3078 			    &io_len, koff, klen, 0);
3079 	}
3080 	if (pp == NULL) {
3081 		/*
3082 		 * Some other thread entered the page before us.
3083 		 * Return to zfs_getpage to retry the lookup.
3084 		 */
3085 		*pl = NULL;
3086 		return (0);
3087 	}
3088 
3089 	/*
3090 	 * Fill the pages in the kluster.
3091 	 */
3092 	cur_pp = pp;
3093 	for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
3094 		ASSERT(io_off == cur_pp->p_offset);
3095 		va = ppmapin(cur_pp, PROT_READ | PROT_WRITE, (caddr_t)-1);
3096 		err = dmu_read(os, oid, io_off, PAGESIZE, va);
3097 		ppmapout(va);
3098 		if (err) {
3099 			/* On error, toss the entire kluster */
3100 			pvn_read_done(pp, B_ERROR);
3101 			return (err);
3102 		}
3103 		cur_pp = cur_pp->p_next;
3104 	}
3105 out:
3106 	/*
3107 	 * Fill in the page list array from the kluster.  If
3108 	 * there are too many pages in the kluster, return
3109 	 * as many pages as possible starting from the desired
3110 	 * offset `off'.
3111 	 * NOTE: the page list will always be null terminated.
3112 	 */
3113 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
3114 
3115 	return (0);
3116 }
3117 
3118 /*
3119  * Return pointers to the pages for the file region [off, off + len]
3120  * in the pl array.  If plsz is greater than len, this function may
3121  * also return page pointers from before or after the specified
3122  * region (i.e. some region [off', off' + plsz]).  These additional
3123  * pages are only returned if they are already in the cache, or were
3124  * created as part of a klustered read.
3125  *
3126  *	IN:	vp	- vnode of file to get data from.
3127  *		off	- position in file to get data from.
3128  *		len	- amount of data to retrieve.
3129  *		plsz	- length of provided page list.
3130  *		seg	- segment to obtain pages for.
3131  *		addr	- virtual address of fault.
3132  *		rw	- mode of created pages.
3133  *		cr	- credentials of caller.
3134  *
3135  *	OUT:	protp	- protection mode of created pages.
3136  *		pl	- list of pages created.
3137  *
3138  *	RETURN:	0 if success
3139  *		error code if failure
3140  *
3141  * Timestamps:
3142  *	vp - atime updated
3143  */
3144 /* ARGSUSED */
3145 static int
3146 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
3147 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
3148 	enum seg_rw rw, cred_t *cr)
3149 {
3150 	znode_t		*zp = VTOZ(vp);
3151 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3152 	page_t		*pp, **pl0 = pl;
3153 	rl_t		*rl;
3154 	int		cnt = 0, need_unlock = 0, err = 0;
3155 
3156 	ZFS_ENTER(zfsvfs);
3157 
3158 	if (protp)
3159 		*protp = PROT_ALL;
3160 
3161 	ASSERT(zp->z_dbuf_held && zp->z_phys);
3162 
3163 	/* no faultahead (for now) */
3164 	if (pl == NULL) {
3165 		ZFS_EXIT(zfsvfs);
3166 		return (0);
3167 	}
3168 
3169 	/*
3170 	 * Make sure nobody restructures the file in the middle of the getpage.
3171 	 */
3172 	rl = zfs_range_lock(zp, off, len, RL_READER);
3173 
3174 	/* can't fault past EOF */
3175 	if (off >= zp->z_phys->zp_size) {
3176 		zfs_range_unlock(rl);
3177 		ZFS_EXIT(zfsvfs);
3178 		return (EFAULT);
3179 	}
3180 
3181 	/*
3182 	 * If we already own the lock, then we must be page faulting
3183 	 * in the middle of a write to this file (i.e., we are writing
3184 	 * to this file using data from a mapped region of the file).
3185 	 */
3186 	if (!rw_owner(&zp->z_map_lock)) {
3187 		rw_enter(&zp->z_map_lock, RW_WRITER);
3188 		need_unlock = TRUE;
3189 	}
3190 
3191 	/*
3192 	 * Loop through the requested range [off, off + len] looking
3193 	 * for pages.  If we don't find a page, we will need to create
3194 	 * a new page and fill it with data from the file.
3195 	 */
3196 	while (len > 0) {
3197 		if (plsz < PAGESIZE)
3198 			break;
3199 		if (pp = page_lookup(vp, off, SE_SHARED)) {
3200 			*pl++ = pp;
3201 			off += PAGESIZE;
3202 			addr += PAGESIZE;
3203 			len -= PAGESIZE;
3204 			plsz -= PAGESIZE;
3205 		} else {
3206 			err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw);
3207 			/*
3208 			 * klustering may have changed our region
3209 			 * to be block aligned.
3210 			 */
3211 			if (((pp = *pl) != 0) && (off != pp->p_offset)) {
3212 				int delta = off - pp->p_offset;
3213 				len += delta;
3214 				off -= delta;
3215 				addr -= delta;
3216 			}
3217 			while (*pl) {
3218 				pl++;
3219 				cnt++;
3220 				off += PAGESIZE;
3221 				addr += PAGESIZE;
3222 				plsz -= PAGESIZE;
3223 				if (len > PAGESIZE)
3224 					len -= PAGESIZE;
3225 				else
3226 					len = 0;
3227 			}
3228 			if (err) {
3229 				/*
3230 				 * Release any pages we have locked.
3231 				 */
3232 				while (pl > pl0)
3233 					page_unlock(*--pl);
3234 				goto out;
3235 			}
3236 		}
3237 	}
3238 
3239 	/*
3240 	 * Fill out the page array with any pages already in the cache.
3241 	 */
3242 	while (plsz > 0) {
3243 		pp = page_lookup_nowait(vp, off, SE_SHARED);
3244 		if (pp == NULL)
3245 			break;
3246 		*pl++ = pp;
3247 		off += PAGESIZE;
3248 		plsz -= PAGESIZE;
3249 	}
3250 
3251 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3252 out:
3253 	*pl = NULL;
3254 
3255 	if (need_unlock)
3256 		rw_exit(&zp->z_map_lock);
3257 	zfs_range_unlock(rl);
3258 
3259 	ZFS_EXIT(zfsvfs);
3260 	return (err);
3261 }
3262 
3263 /*
3264  * Request a memory map for a section of a file.  This code interacts
3265  * with common code and the VM system as follows:
3266  *
3267  *	common code calls mmap(), which ends up in smmap_common()
3268  *
3269  *	this calls VOP_MAP(), which takes you into (say) zfs
3270  *
3271  *	zfs_map() calls as_map(), passing segvn_create() as the callback
3272  *
3273  *	segvn_create() creates the new segment and calls VOP_ADDMAP()
3274  *
3275  *	zfs_addmap() updates z_mapcnt
3276  */
3277 static int
3278 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
3279     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
3280 {
3281 	znode_t *zp = VTOZ(vp);
3282 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3283 	segvn_crargs_t	vn_a;
3284 	int		error;
3285 
3286 	ZFS_ENTER(zfsvfs);
3287 
3288 	if (vp->v_flag & VNOMAP) {
3289 		ZFS_EXIT(zfsvfs);
3290 		return (ENOSYS);
3291 	}
3292 
3293 	if (off < 0 || len > MAXOFFSET_T - off) {
3294 		ZFS_EXIT(zfsvfs);
3295 		return (ENXIO);
3296 	}
3297 
3298 	if (vp->v_type != VREG) {
3299 		ZFS_EXIT(zfsvfs);
3300 		return (ENODEV);
3301 	}
3302 
3303 	/*
3304 	 * If file is locked, disallow mapping.
3305 	 */
3306 	if (MANDMODE((mode_t)zp->z_phys->zp_mode) && vn_has_flocks(vp)) {
3307 		ZFS_EXIT(zfsvfs);
3308 		return (EAGAIN);
3309 	}
3310 
3311 	as_rangelock(as);
3312 	if ((flags & MAP_FIXED) == 0) {
3313 		map_addr(addrp, len, off, 1, flags);
3314 		if (*addrp == NULL) {
3315 			as_rangeunlock(as);
3316 			ZFS_EXIT(zfsvfs);
3317 			return (ENOMEM);
3318 		}
3319 	} else {
3320 		/*
3321 		 * User specified address - blow away any previous mappings
3322 		 */
3323 		(void) as_unmap(as, *addrp, len);
3324 	}
3325 
3326 	vn_a.vp = vp;
3327 	vn_a.offset = (u_offset_t)off;
3328 	vn_a.type = flags & MAP_TYPE;
3329 	vn_a.prot = prot;
3330 	vn_a.maxprot = maxprot;
3331 	vn_a.cred = cr;
3332 	vn_a.amp = NULL;
3333 	vn_a.flags = flags & ~MAP_TYPE;
3334 	vn_a.szc = 0;
3335 	vn_a.lgrp_mem_policy_flags = 0;
3336 
3337 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
3338 
3339 	as_rangeunlock(as);
3340 	ZFS_EXIT(zfsvfs);
3341 	return (error);
3342 }
3343 
3344 /* ARGSUSED */
3345 static int
3346 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
3347     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
3348 {
3349 	uint64_t pages = btopr(len);
3350 
3351 	atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
3352 	return (0);
3353 }
3354 
3355 /*
3356  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
3357  * more accurate mtime for the associated file.  Since we don't have a way of
3358  * detecting when the data was actually modified, we have to resort to
3359  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
3360  * last page is pushed.  The problem occurs when the msync() call is omitted,
3361  * which by far the most common case:
3362  *
3363  * 	open()
3364  * 	mmap()
3365  * 	<modify memory>
3366  * 	munmap()
3367  * 	close()
3368  * 	<time lapse>
3369  * 	putpage() via fsflush
3370  *
3371  * If we wait until fsflush to come along, we can have a modification time that
3372  * is some arbitrary point in the future.  In order to prevent this in the
3373  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
3374  * torn down.
3375  */
3376 /* ARGSUSED */
3377 static int
3378 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
3379     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr)
3380 {
3381 	uint64_t pages = btopr(len);
3382 
3383 	ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
3384 	atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
3385 
3386 	if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
3387 	    vn_has_cached_data(vp))
3388 		(void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr);
3389 
3390 	return (0);
3391 }
3392 
3393 /*
3394  * Free or allocate space in a file.  Currently, this function only
3395  * supports the `F_FREESP' command.  However, this command is somewhat
3396  * misnamed, as its functionality includes the ability to allocate as
3397  * well as free space.
3398  *
3399  *	IN:	vp	- vnode of file to free data in.
3400  *		cmd	- action to take (only F_FREESP supported).
3401  *		bfp	- section of file to free/alloc.
3402  *		flag	- current file open mode flags.
3403  *		offset	- current file offset.
3404  *		cr	- credentials of caller [UNUSED].
3405  *
3406  *	RETURN:	0 if success
3407  *		error code if failure
3408  *
3409  * Timestamps:
3410  *	vp - ctime|mtime updated
3411  */
3412 /* ARGSUSED */
3413 static int
3414 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
3415     offset_t offset, cred_t *cr, caller_context_t *ct)
3416 {
3417 	znode_t		*zp = VTOZ(vp);
3418 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3419 	uint64_t	off, len;
3420 	int		error;
3421 
3422 	ZFS_ENTER(zfsvfs);
3423 
3424 top:
3425 	if (cmd != F_FREESP) {
3426 		ZFS_EXIT(zfsvfs);
3427 		return (EINVAL);
3428 	}
3429 
3430 	if (error = convoff(vp, bfp, 0, offset)) {
3431 		ZFS_EXIT(zfsvfs);
3432 		return (error);
3433 	}
3434 
3435 	if (bfp->l_len < 0) {
3436 		ZFS_EXIT(zfsvfs);
3437 		return (EINVAL);
3438 	}
3439 
3440 	off = bfp->l_start;
3441 	len = bfp->l_len; /* 0 means from off to end of file */
3442 
3443 	do {
3444 		error = zfs_freesp(zp, off, len, flag, TRUE);
3445 		/* NB: we already did dmu_tx_wait() if necessary */
3446 	} while (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT);
3447 
3448 	ZFS_EXIT(zfsvfs);
3449 	return (error);
3450 }
3451 
3452 static int
3453 zfs_fid(vnode_t *vp, fid_t *fidp)
3454 {
3455 	znode_t		*zp = VTOZ(vp);
3456 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3457 	uint32_t	gen = (uint32_t)zp->z_phys->zp_gen;
3458 	uint64_t	object = zp->z_id;
3459 	zfid_short_t	*zfid;
3460 	int		size, i;
3461 
3462 	ZFS_ENTER(zfsvfs);
3463 
3464 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
3465 	if (fidp->fid_len < size) {
3466 		fidp->fid_len = size;
3467 		ZFS_EXIT(zfsvfs);
3468 		return (ENOSPC);
3469 	}
3470 
3471 	zfid = (zfid_short_t *)fidp;
3472 
3473 	zfid->zf_len = size;
3474 
3475 	for (i = 0; i < sizeof (zfid->zf_object); i++)
3476 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
3477 
3478 	/* Must have a non-zero generation number to distinguish from .zfs */
3479 	if (gen == 0)
3480 		gen = 1;
3481 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
3482 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
3483 
3484 	if (size == LONG_FID_LEN) {
3485 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
3486 		zfid_long_t	*zlfid;
3487 
3488 		zlfid = (zfid_long_t *)fidp;
3489 
3490 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
3491 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
3492 
3493 		/* XXX - this should be the generation number for the objset */
3494 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
3495 			zlfid->zf_setgen[i] = 0;
3496 	}
3497 
3498 	ZFS_EXIT(zfsvfs);
3499 	return (0);
3500 }
3501 
3502 static int
3503 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr)
3504 {
3505 	znode_t		*zp, *xzp;
3506 	zfsvfs_t	*zfsvfs;
3507 	zfs_dirlock_t	*dl;
3508 	int		error;
3509 
3510 	switch (cmd) {
3511 	case _PC_LINK_MAX:
3512 		*valp = ULONG_MAX;
3513 		return (0);
3514 
3515 	case _PC_FILESIZEBITS:
3516 		*valp = 64;
3517 		return (0);
3518 
3519 	case _PC_XATTR_EXISTS:
3520 		zp = VTOZ(vp);
3521 		zfsvfs = zp->z_zfsvfs;
3522 		ZFS_ENTER(zfsvfs);
3523 		*valp = 0;
3524 		error = zfs_dirent_lock(&dl, zp, "", &xzp,
3525 		    ZXATTR | ZEXISTS | ZSHARED);
3526 		if (error == 0) {
3527 			zfs_dirent_unlock(dl);
3528 			if (!zfs_dirempty(xzp))
3529 				*valp = 1;
3530 			VN_RELE(ZTOV(xzp));
3531 		} else if (error == ENOENT) {
3532 			/*
3533 			 * If there aren't extended attributes, it's the
3534 			 * same as having zero of them.
3535 			 */
3536 			error = 0;
3537 		}
3538 		ZFS_EXIT(zfsvfs);
3539 		return (error);
3540 
3541 	case _PC_ACL_ENABLED:
3542 		*valp = _ACL_ACE_ENABLED;
3543 		return (0);
3544 
3545 	case _PC_MIN_HOLE_SIZE:
3546 		*valp = (ulong_t)SPA_MINBLOCKSIZE;
3547 		return (0);
3548 
3549 	default:
3550 		return (fs_pathconf(vp, cmd, valp, cr));
3551 	}
3552 }
3553 
3554 /*ARGSUSED*/
3555 static int
3556 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr)
3557 {
3558 	znode_t *zp = VTOZ(vp);
3559 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3560 	int error;
3561 
3562 	ZFS_ENTER(zfsvfs);
3563 	error = zfs_getacl(zp, vsecp, cr);
3564 	ZFS_EXIT(zfsvfs);
3565 
3566 	return (error);
3567 }
3568 
3569 /*ARGSUSED*/
3570 static int
3571 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr)
3572 {
3573 	znode_t *zp = VTOZ(vp);
3574 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3575 	int error;
3576 
3577 	ZFS_ENTER(zfsvfs);
3578 	error = zfs_setacl(zp, vsecp, cr);
3579 	ZFS_EXIT(zfsvfs);
3580 	return (error);
3581 }
3582 
3583 /*
3584  * Predeclare these here so that the compiler assumes that
3585  * this is an "old style" function declaration that does
3586  * not include arguments => we won't get type mismatch errors
3587  * in the initializations that follow.
3588  */
3589 static int zfs_inval();
3590 static int zfs_isdir();
3591 
3592 static int
3593 zfs_inval()
3594 {
3595 	return (EINVAL);
3596 }
3597 
3598 static int
3599 zfs_isdir()
3600 {
3601 	return (EISDIR);
3602 }
3603 /*
3604  * Directory vnode operations template
3605  */
3606 vnodeops_t *zfs_dvnodeops;
3607 const fs_operation_def_t zfs_dvnodeops_template[] = {
3608 	VOPNAME_OPEN, zfs_open,
3609 	VOPNAME_CLOSE, zfs_close,
3610 	VOPNAME_READ, zfs_isdir,
3611 	VOPNAME_WRITE, zfs_isdir,
3612 	VOPNAME_IOCTL, zfs_ioctl,
3613 	VOPNAME_GETATTR, zfs_getattr,
3614 	VOPNAME_SETATTR, zfs_setattr,
3615 	VOPNAME_ACCESS, zfs_access,
3616 	VOPNAME_LOOKUP, zfs_lookup,
3617 	VOPNAME_CREATE, zfs_create,
3618 	VOPNAME_REMOVE, zfs_remove,
3619 	VOPNAME_LINK, zfs_link,
3620 	VOPNAME_RENAME, zfs_rename,
3621 	VOPNAME_MKDIR, zfs_mkdir,
3622 	VOPNAME_RMDIR, zfs_rmdir,
3623 	VOPNAME_READDIR, zfs_readdir,
3624 	VOPNAME_SYMLINK, zfs_symlink,
3625 	VOPNAME_FSYNC, zfs_fsync,
3626 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3627 	VOPNAME_FID, zfs_fid,
3628 	VOPNAME_SEEK, zfs_seek,
3629 	VOPNAME_PATHCONF, zfs_pathconf,
3630 	VOPNAME_GETSECATTR, zfs_getsecattr,
3631 	VOPNAME_SETSECATTR, zfs_setsecattr,
3632 	NULL, NULL
3633 };
3634 
3635 /*
3636  * Regular file vnode operations template
3637  */
3638 vnodeops_t *zfs_fvnodeops;
3639 const fs_operation_def_t zfs_fvnodeops_template[] = {
3640 	VOPNAME_OPEN, zfs_open,
3641 	VOPNAME_CLOSE, zfs_close,
3642 	VOPNAME_READ, zfs_read,
3643 	VOPNAME_WRITE, zfs_write,
3644 	VOPNAME_IOCTL, zfs_ioctl,
3645 	VOPNAME_GETATTR, zfs_getattr,
3646 	VOPNAME_SETATTR, zfs_setattr,
3647 	VOPNAME_ACCESS, zfs_access,
3648 	VOPNAME_LOOKUP, zfs_lookup,
3649 	VOPNAME_RENAME, zfs_rename,
3650 	VOPNAME_FSYNC, zfs_fsync,
3651 	VOPNAME_INACTIVE, (fs_generic_func_p)zfs_inactive,
3652 	VOPNAME_FID, zfs_fid,
3653 	VOPNAME_SEEK, zfs_seek,
3654 	VOPNAME_FRLOCK, zfs_frlock,
3655 	VOPNAME_SPACE, zfs_space,
3656 	VOPNAME_GETPAGE, zfs_getpage,
3657 	VOPNAME_PUTPAGE, zfs_putpage,
3658 	VOPNAME_MAP, (fs_generic_func_p) zfs_map,
3659 	VOPNAME_ADDMAP, (fs_generic_func_p) zfs_addmap,
3660 	VOPNAME_DELMAP, zfs_delmap,
3661 	VOPNAME_PATHCONF, zfs_pathconf,
3662 	VOPNAME_GETSECATTR, zfs_getsecattr,
3663 	VOPNAME_SETSECATTR, zfs_setsecattr,
3664 	VOPNAME_VNEVENT, fs_vnevent_support,
3665 	NULL, NULL
3666 };
3667 
3668 /*
3669  * Symbolic link vnode operations template
3670  */
3671 vnodeops_t *zfs_symvnodeops;
3672 const fs_operation_def_t zfs_symvnodeops_template[] = {
3673 	VOPNAME_GETATTR, zfs_getattr,
3674 	VOPNAME_SETATTR, zfs_setattr,
3675 	VOPNAME_ACCESS, zfs_access,
3676 	VOPNAME_RENAME, zfs_rename,
3677 	VOPNAME_READLINK, zfs_readlink,
3678 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3679 	VOPNAME_FID, zfs_fid,
3680 	VOPNAME_PATHCONF, zfs_pathconf,
3681 	VOPNAME_VNEVENT, fs_vnevent_support,
3682 	NULL, NULL
3683 };
3684 
3685 /*
3686  * Extended attribute directory vnode operations template
3687  *	This template is identical to the directory vnodes
3688  *	operation template except for restricted operations:
3689  *		VOP_MKDIR()
3690  *		VOP_SYMLINK()
3691  * Note that there are other restrictions embedded in:
3692  *	zfs_create()	- restrict type to VREG
3693  *	zfs_link()	- no links into/out of attribute space
3694  *	zfs_rename()	- no moves into/out of attribute space
3695  */
3696 vnodeops_t *zfs_xdvnodeops;
3697 const fs_operation_def_t zfs_xdvnodeops_template[] = {
3698 	VOPNAME_OPEN, zfs_open,
3699 	VOPNAME_CLOSE, zfs_close,
3700 	VOPNAME_IOCTL, zfs_ioctl,
3701 	VOPNAME_GETATTR, zfs_getattr,
3702 	VOPNAME_SETATTR, zfs_setattr,
3703 	VOPNAME_ACCESS, zfs_access,
3704 	VOPNAME_LOOKUP, zfs_lookup,
3705 	VOPNAME_CREATE, zfs_create,
3706 	VOPNAME_REMOVE, zfs_remove,
3707 	VOPNAME_LINK, zfs_link,
3708 	VOPNAME_RENAME, zfs_rename,
3709 	VOPNAME_MKDIR, zfs_inval,
3710 	VOPNAME_RMDIR, zfs_rmdir,
3711 	VOPNAME_READDIR, zfs_readdir,
3712 	VOPNAME_SYMLINK, zfs_inval,
3713 	VOPNAME_FSYNC, zfs_fsync,
3714 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3715 	VOPNAME_FID, zfs_fid,
3716 	VOPNAME_SEEK, zfs_seek,
3717 	VOPNAME_PATHCONF, zfs_pathconf,
3718 	VOPNAME_GETSECATTR, zfs_getsecattr,
3719 	VOPNAME_SETSECATTR, zfs_setsecattr,
3720 	VOPNAME_VNEVENT, fs_vnevent_support,
3721 	NULL, NULL
3722 };
3723 
3724 /*
3725  * Error vnode operations template
3726  */
3727 vnodeops_t *zfs_evnodeops;
3728 const fs_operation_def_t zfs_evnodeops_template[] = {
3729 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3730 	VOPNAME_PATHCONF, zfs_pathconf,
3731 	NULL, NULL
3732 };
3733