xref: /titanic_44/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision 12054bfce7d1b03f143c8287d83cc15b25ff43cf)
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_by_bonus(zp->z_dbuf,
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_read(os, lr->lr_foid, off, dlen, buf));
880 	} else { /* indirect write */
881 		uint64_t boff; /* block starting offset */
882 
883 		ASSERT3U(dlen, <=, zp->z_blksz);
884 		/*
885 		 * Have to lock the whole block to ensure when it's
886 		 * written out and it's checksum is being calculated
887 		 * that no one can change the data. We need to re-check
888 		 * blocksize after we get the lock in case it's changed!
889 		 */
890 		for (;;) {
891 			if (ISP2(zp->z_blksz)) {
892 				boff = P2ALIGN_TYPED(off, zp->z_blksz,
893 				    uint64_t);
894 			} else {
895 				boff = 0;
896 			}
897 			dlen = zp->z_blksz;
898 			rl = zfs_range_lock(zp, boff, dlen, RL_READER);
899 			if (zp->z_blksz == dlen)
900 				break;
901 			zfs_range_unlock(rl);
902 		}
903 		/* test for truncation needs to be done while range locked */
904 		if (off >= zp->z_phys->zp_size) {
905 			error = ENOENT;
906 			goto out;
907 		}
908 		VERIFY(0 == dmu_buf_hold(os, lr->lr_foid, boff, rl, &db));
909 		ASSERT(boff == db->db_offset);
910 		lr->lr_blkoff = off - boff;
911 		error = dmu_sync(zio, db, &lr->lr_blkptr,
912 		    lr->lr_common.lrc_txg, zio ? zfs_get_done : NULL, rl);
913 		/*
914 		 * If we get EINPROGRESS, then we need to wait for a
915 		 * write IO initiated by dmu_sync() to complete before
916 		 * we can release this dbuf.  We will finish everthing
917 		 * up in the zfs_get_done() callback.
918 		 */
919 		if (error == EINPROGRESS)
920 			return (0);
921 		dmu_buf_rele(db, rl);
922 	}
923 out:
924 	zfs_range_unlock(rl);
925 	VN_RELE(ZTOV(zp));
926 	return (error);
927 }
928 
929 /*ARGSUSED*/
930 static int
931 zfs_access(vnode_t *vp, int mode, int flags, cred_t *cr)
932 {
933 	znode_t *zp = VTOZ(vp);
934 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
935 	int error;
936 
937 	ZFS_ENTER(zfsvfs);
938 	error = zfs_zaccess_rwx(zp, mode, cr);
939 	ZFS_EXIT(zfsvfs);
940 	return (error);
941 }
942 
943 /*
944  * Lookup an entry in a directory, or an extended attribute directory.
945  * If it exists, return a held vnode reference for it.
946  *
947  *	IN:	dvp	- vnode of directory to search.
948  *		nm	- name of entry to lookup.
949  *		pnp	- full pathname to lookup [UNUSED].
950  *		flags	- LOOKUP_XATTR set if looking for an attribute.
951  *		rdir	- root directory vnode [UNUSED].
952  *		cr	- credentials of caller.
953  *
954  *	OUT:	vpp	- vnode of located entry, NULL if not found.
955  *
956  *	RETURN:	0 if success
957  *		error code if failure
958  *
959  * Timestamps:
960  *	NA
961  */
962 /* ARGSUSED */
963 static int
964 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
965     int flags, vnode_t *rdir, cred_t *cr)
966 {
967 
968 	znode_t *zdp = VTOZ(dvp);
969 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
970 	int	error;
971 
972 	ZFS_ENTER(zfsvfs);
973 
974 	*vpp = NULL;
975 
976 	if (flags & LOOKUP_XATTR) {
977 		/*
978 		 * We don't allow recursive attributes..
979 		 * Maybe someday we will.
980 		 */
981 		if (zdp->z_phys->zp_flags & ZFS_XATTR) {
982 			ZFS_EXIT(zfsvfs);
983 			return (EINVAL);
984 		}
985 
986 		if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr)) {
987 			ZFS_EXIT(zfsvfs);
988 			return (error);
989 		}
990 
991 		/*
992 		 * Do we have permission to get into attribute directory?
993 		 */
994 
995 		if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, cr)) {
996 			VN_RELE(*vpp);
997 		}
998 
999 		ZFS_EXIT(zfsvfs);
1000 		return (error);
1001 	}
1002 
1003 	if (dvp->v_type != VDIR) {
1004 		ZFS_EXIT(zfsvfs);
1005 		return (ENOTDIR);
1006 	}
1007 
1008 	/*
1009 	 * Check accessibility of directory.
1010 	 */
1011 
1012 	if (error = zfs_zaccess(zdp, ACE_EXECUTE, cr)) {
1013 		ZFS_EXIT(zfsvfs);
1014 		return (error);
1015 	}
1016 
1017 	if ((error = zfs_dirlook(zdp, nm, vpp)) == 0) {
1018 
1019 		/*
1020 		 * Convert device special files
1021 		 */
1022 		if (IS_DEVVP(*vpp)) {
1023 			vnode_t	*svp;
1024 
1025 			svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1026 			VN_RELE(*vpp);
1027 			if (svp == NULL)
1028 				error = ENOSYS;
1029 			else
1030 				*vpp = svp;
1031 		}
1032 	}
1033 
1034 	ZFS_EXIT(zfsvfs);
1035 	return (error);
1036 }
1037 
1038 /*
1039  * Attempt to create a new entry in a directory.  If the entry
1040  * already exists, truncate the file if permissible, else return
1041  * an error.  Return the vp of the created or trunc'd file.
1042  *
1043  *	IN:	dvp	- vnode of directory to put new file entry in.
1044  *		name	- name of new file entry.
1045  *		vap	- attributes of new file.
1046  *		excl	- flag indicating exclusive or non-exclusive mode.
1047  *		mode	- mode to open file with.
1048  *		cr	- credentials of caller.
1049  *		flag	- large file flag [UNUSED].
1050  *
1051  *	OUT:	vpp	- vnode of created or trunc'd entry.
1052  *
1053  *	RETURN:	0 if success
1054  *		error code if failure
1055  *
1056  * Timestamps:
1057  *	dvp - ctime|mtime updated if new entry created
1058  *	 vp - ctime|mtime always, atime if new
1059  */
1060 /* ARGSUSED */
1061 static int
1062 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, vcexcl_t excl,
1063     int mode, vnode_t **vpp, cred_t *cr, int flag)
1064 {
1065 	znode_t		*zp, *dzp = VTOZ(dvp);
1066 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1067 	zilog_t		*zilog = zfsvfs->z_log;
1068 	uint64_t	seq = 0;
1069 	objset_t	*os = zfsvfs->z_os;
1070 	zfs_dirlock_t	*dl;
1071 	dmu_tx_t	*tx;
1072 	int		error;
1073 	uint64_t	zoid;
1074 
1075 	ZFS_ENTER(zfsvfs);
1076 
1077 top:
1078 	*vpp = NULL;
1079 
1080 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1081 		vap->va_mode &= ~VSVTX;
1082 
1083 	if (*name == '\0') {
1084 		/*
1085 		 * Null component name refers to the directory itself.
1086 		 */
1087 		VN_HOLD(dvp);
1088 		zp = dzp;
1089 		dl = NULL;
1090 		error = 0;
1091 	} else {
1092 		/* possible VN_HOLD(zp) */
1093 		if (error = zfs_dirent_lock(&dl, dzp, name, &zp, 0)) {
1094 			if (strcmp(name, "..") == 0)
1095 				error = EISDIR;
1096 			ZFS_EXIT(zfsvfs);
1097 			return (error);
1098 		}
1099 	}
1100 
1101 	zoid = zp ? zp->z_id : -1ULL;
1102 
1103 	if (zp == NULL) {
1104 		/*
1105 		 * Create a new file object and update the directory
1106 		 * to reference it.
1107 		 */
1108 		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
1109 			goto out;
1110 		}
1111 
1112 		/*
1113 		 * We only support the creation of regular files in
1114 		 * extended attribute directories.
1115 		 */
1116 		if ((dzp->z_phys->zp_flags & ZFS_XATTR) &&
1117 		    (vap->va_type != VREG)) {
1118 			error = EINVAL;
1119 			goto out;
1120 		}
1121 
1122 		tx = dmu_tx_create(os);
1123 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1124 		dmu_tx_hold_bonus(tx, dzp->z_id);
1125 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1126 		if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
1127 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1128 			    0, SPA_MAXBLOCKSIZE);
1129 		error = dmu_tx_assign(tx, zfsvfs->z_assign);
1130 		if (error) {
1131 			zfs_dirent_unlock(dl);
1132 			if (error == ERESTART &&
1133 			    zfsvfs->z_assign == TXG_NOWAIT) {
1134 				dmu_tx_wait(tx);
1135 				dmu_tx_abort(tx);
1136 				goto top;
1137 			}
1138 			dmu_tx_abort(tx);
1139 			ZFS_EXIT(zfsvfs);
1140 			return (error);
1141 		}
1142 		zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
1143 		ASSERT(zp->z_id == zoid);
1144 		(void) zfs_link_create(dl, zp, tx, ZNEW);
1145 		seq = zfs_log_create(zilog, tx, TX_CREATE, dzp, zp, name);
1146 		dmu_tx_commit(tx);
1147 	} else {
1148 		/*
1149 		 * A directory entry already exists for this name.
1150 		 */
1151 		/*
1152 		 * Can't truncate an existing file if in exclusive mode.
1153 		 */
1154 		if (excl == EXCL) {
1155 			error = EEXIST;
1156 			goto out;
1157 		}
1158 		/*
1159 		 * Can't open a directory for writing.
1160 		 */
1161 		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1162 			error = EISDIR;
1163 			goto out;
1164 		}
1165 		/*
1166 		 * Verify requested access to file.
1167 		 */
1168 		if (mode && (error = zfs_zaccess_rwx(zp, mode, cr))) {
1169 			goto out;
1170 		}
1171 
1172 		mutex_enter(&dzp->z_lock);
1173 		dzp->z_seq++;
1174 		mutex_exit(&dzp->z_lock);
1175 
1176 		/*
1177 		 * Truncate regular files if requested.
1178 		 */
1179 		if ((ZTOV(zp)->v_type == VREG) &&
1180 		    (zp->z_phys->zp_size != 0) &&
1181 		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1182 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1183 			if (error == ERESTART &&
1184 			    zfsvfs->z_assign == TXG_NOWAIT) {
1185 				/* NB: we already did dmu_tx_wait() */
1186 				zfs_dirent_unlock(dl);
1187 				VN_RELE(ZTOV(zp));
1188 				goto top;
1189 			}
1190 		}
1191 	}
1192 out:
1193 
1194 	if (dl)
1195 		zfs_dirent_unlock(dl);
1196 
1197 	if (error) {
1198 		if (zp)
1199 			VN_RELE(ZTOV(zp));
1200 	} else {
1201 		*vpp = ZTOV(zp);
1202 		/*
1203 		 * If vnode is for a device return a specfs vnode instead.
1204 		 */
1205 		if (IS_DEVVP(*vpp)) {
1206 			struct vnode *svp;
1207 
1208 			svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1209 			VN_RELE(*vpp);
1210 			if (svp == NULL) {
1211 				error = ENOSYS;
1212 			}
1213 			*vpp = svp;
1214 		}
1215 	}
1216 
1217 	zil_commit(zilog, seq, 0);
1218 
1219 	ZFS_EXIT(zfsvfs);
1220 	return (error);
1221 }
1222 
1223 /*
1224  * Remove an entry from a directory.
1225  *
1226  *	IN:	dvp	- vnode of directory to remove entry from.
1227  *		name	- name of entry to remove.
1228  *		cr	- credentials of caller.
1229  *
1230  *	RETURN:	0 if success
1231  *		error code if failure
1232  *
1233  * Timestamps:
1234  *	dvp - ctime|mtime
1235  *	 vp - ctime (if nlink > 0)
1236  */
1237 static int
1238 zfs_remove(vnode_t *dvp, char *name, cred_t *cr)
1239 {
1240 	znode_t		*zp, *dzp = VTOZ(dvp);
1241 	znode_t		*xzp = NULL;
1242 	vnode_t		*vp;
1243 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1244 	zilog_t		*zilog = zfsvfs->z_log;
1245 	uint64_t	seq = 0;
1246 	uint64_t	acl_obj, xattr_obj;
1247 	zfs_dirlock_t	*dl;
1248 	dmu_tx_t	*tx;
1249 	int		may_delete_now, delete_now = FALSE;
1250 	int		reaped;
1251 	int		error;
1252 
1253 	ZFS_ENTER(zfsvfs);
1254 
1255 top:
1256 	/*
1257 	 * Attempt to lock directory; fail if entry doesn't exist.
1258 	 */
1259 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZEXISTS)) {
1260 		ZFS_EXIT(zfsvfs);
1261 		return (error);
1262 	}
1263 
1264 	vp = ZTOV(zp);
1265 
1266 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1267 		goto out;
1268 	}
1269 
1270 	/*
1271 	 * Need to use rmdir for removing directories.
1272 	 */
1273 	if (vp->v_type == VDIR) {
1274 		error = EPERM;
1275 		goto out;
1276 	}
1277 
1278 	vnevent_remove(vp);
1279 
1280 	dnlc_remove(dvp, name);
1281 
1282 	mutex_enter(&vp->v_lock);
1283 	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1284 	mutex_exit(&vp->v_lock);
1285 
1286 	/*
1287 	 * We may delete the znode now, or we may put it on the delete queue;
1288 	 * it depends on whether we're the last link, and on whether there are
1289 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1290 	 * allow for either case.
1291 	 */
1292 	tx = dmu_tx_create(zfsvfs->z_os);
1293 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1294 	dmu_tx_hold_bonus(tx, zp->z_id);
1295 	if (may_delete_now)
1296 		dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
1297 
1298 	/* are there any extended attributes? */
1299 	if ((xattr_obj = zp->z_phys->zp_xattr) != 0) {
1300 		/*
1301 		 * XXX - There is a possibility that the delete
1302 		 * of the parent file could succeed, but then we get
1303 		 * an ENOSPC when we try to delete the xattrs...
1304 		 * so we would need to re-try the deletes periodically
1305 		 */
1306 		/* XXX - do we need this if we are deleting? */
1307 		dmu_tx_hold_bonus(tx, xattr_obj);
1308 	}
1309 
1310 	/* are there any additional acls */
1311 	if ((acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj) != 0 &&
1312 	    may_delete_now)
1313 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1314 
1315 	/* charge as an update -- would be nice not to charge at all */
1316 	dmu_tx_hold_zap(tx, zfsvfs->z_dqueue, FALSE, NULL);
1317 
1318 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1319 	if (error) {
1320 		zfs_dirent_unlock(dl);
1321 		VN_RELE(vp);
1322 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1323 			dmu_tx_wait(tx);
1324 			dmu_tx_abort(tx);
1325 			goto top;
1326 		}
1327 		dmu_tx_abort(tx);
1328 		ZFS_EXIT(zfsvfs);
1329 		return (error);
1330 	}
1331 
1332 	/*
1333 	 * Remove the directory entry.
1334 	 */
1335 	error = zfs_link_destroy(dl, zp, tx, 0, &reaped);
1336 
1337 	if (error) {
1338 		dmu_tx_commit(tx);
1339 		goto out;
1340 	}
1341 
1342 	if (reaped) {
1343 		mutex_enter(&vp->v_lock);
1344 		delete_now = may_delete_now &&
1345 		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1346 		    zp->z_phys->zp_xattr == xattr_obj &&
1347 		    zp->z_phys->zp_acl.z_acl_extern_obj == acl_obj;
1348 		mutex_exit(&vp->v_lock);
1349 	}
1350 
1351 	if (delete_now) {
1352 		if (zp->z_phys->zp_xattr) {
1353 			error = zfs_zget(zfsvfs, zp->z_phys->zp_xattr, &xzp);
1354 			ASSERT3U(error, ==, 0);
1355 			ASSERT3U(xzp->z_phys->zp_links, ==, 2);
1356 			dmu_buf_will_dirty(xzp->z_dbuf, tx);
1357 			mutex_enter(&xzp->z_lock);
1358 			xzp->z_reap = 1;
1359 			xzp->z_phys->zp_links = 0;
1360 			mutex_exit(&xzp->z_lock);
1361 			zfs_dq_add(xzp, tx);
1362 			zp->z_phys->zp_xattr = 0; /* probably unnecessary */
1363 		}
1364 		mutex_enter(&zp->z_lock);
1365 		mutex_enter(&vp->v_lock);
1366 		vp->v_count--;
1367 		ASSERT3U(vp->v_count, ==, 0);
1368 		mutex_exit(&vp->v_lock);
1369 		mutex_exit(&zp->z_lock);
1370 		zfs_znode_delete(zp, tx);
1371 		VFS_RELE(zfsvfs->z_vfs);
1372 	} else if (reaped) {
1373 		zfs_dq_add(zp, tx);
1374 	}
1375 
1376 	seq = zfs_log_remove(zilog, tx, TX_REMOVE, dzp, name);
1377 
1378 	dmu_tx_commit(tx);
1379 out:
1380 	zfs_dirent_unlock(dl);
1381 
1382 	if (!delete_now) {
1383 		VN_RELE(vp);
1384 	} else if (xzp) {
1385 		/* this rele delayed to prevent nesting transactions */
1386 		VN_RELE(ZTOV(xzp));
1387 	}
1388 
1389 	zil_commit(zilog, seq, 0);
1390 
1391 	ZFS_EXIT(zfsvfs);
1392 	return (error);
1393 }
1394 
1395 /*
1396  * Create a new directory and insert it into dvp using the name
1397  * provided.  Return a pointer to the inserted directory.
1398  *
1399  *	IN:	dvp	- vnode of directory to add subdir to.
1400  *		dirname	- name of new directory.
1401  *		vap	- attributes of new directory.
1402  *		cr	- credentials of caller.
1403  *
1404  *	OUT:	vpp	- vnode of created directory.
1405  *
1406  *	RETURN:	0 if success
1407  *		error code if failure
1408  *
1409  * Timestamps:
1410  *	dvp - ctime|mtime updated
1411  *	 vp - ctime|mtime|atime updated
1412  */
1413 static int
1414 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr)
1415 {
1416 	znode_t		*zp, *dzp = VTOZ(dvp);
1417 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1418 	zilog_t		*zilog = zfsvfs->z_log;
1419 	uint64_t	seq = 0;
1420 	zfs_dirlock_t	*dl;
1421 	uint64_t	zoid = 0;
1422 	dmu_tx_t	*tx;
1423 	int		error;
1424 
1425 	ASSERT(vap->va_type == VDIR);
1426 
1427 	ZFS_ENTER(zfsvfs);
1428 
1429 	if (dzp->z_phys->zp_flags & ZFS_XATTR) {
1430 		ZFS_EXIT(zfsvfs);
1431 		return (EINVAL);
1432 	}
1433 top:
1434 	*vpp = NULL;
1435 
1436 	/*
1437 	 * First make sure the new directory doesn't exist.
1438 	 */
1439 	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, ZNEW)) {
1440 		ZFS_EXIT(zfsvfs);
1441 		return (error);
1442 	}
1443 
1444 	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, cr)) {
1445 		zfs_dirent_unlock(dl);
1446 		ZFS_EXIT(zfsvfs);
1447 		return (error);
1448 	}
1449 
1450 	/*
1451 	 * Add a new entry to the directory.
1452 	 */
1453 	tx = dmu_tx_create(zfsvfs->z_os);
1454 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1455 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1456 	if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
1457 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1458 		    0, SPA_MAXBLOCKSIZE);
1459 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1460 	if (error) {
1461 		zfs_dirent_unlock(dl);
1462 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1463 			dmu_tx_wait(tx);
1464 			dmu_tx_abort(tx);
1465 			goto top;
1466 		}
1467 		dmu_tx_abort(tx);
1468 		ZFS_EXIT(zfsvfs);
1469 		return (error);
1470 	}
1471 
1472 	/*
1473 	 * Create new node.
1474 	 */
1475 	zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
1476 
1477 	/*
1478 	 * Now put new name in parent dir.
1479 	 */
1480 	(void) zfs_link_create(dl, zp, tx, ZNEW);
1481 
1482 	*vpp = ZTOV(zp);
1483 
1484 	seq = zfs_log_create(zilog, tx, TX_MKDIR, dzp, zp, dirname);
1485 	dmu_tx_commit(tx);
1486 
1487 	zfs_dirent_unlock(dl);
1488 
1489 	zil_commit(zilog, seq, 0);
1490 
1491 	ZFS_EXIT(zfsvfs);
1492 	return (0);
1493 }
1494 
1495 /*
1496  * Remove a directory subdir entry.  If the current working
1497  * directory is the same as the subdir to be removed, the
1498  * remove will fail.
1499  *
1500  *	IN:	dvp	- vnode of directory to remove from.
1501  *		name	- name of directory to be removed.
1502  *		cwd	- vnode of current working directory.
1503  *		cr	- credentials of caller.
1504  *
1505  *	RETURN:	0 if success
1506  *		error code if failure
1507  *
1508  * Timestamps:
1509  *	dvp - ctime|mtime updated
1510  */
1511 static int
1512 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr)
1513 {
1514 	znode_t		*dzp = VTOZ(dvp);
1515 	znode_t		*zp;
1516 	vnode_t		*vp;
1517 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1518 	zilog_t		*zilog = zfsvfs->z_log;
1519 	uint64_t	seq = 0;
1520 	zfs_dirlock_t	*dl;
1521 	dmu_tx_t	*tx;
1522 	int		error;
1523 
1524 	ZFS_ENTER(zfsvfs);
1525 
1526 top:
1527 	zp = NULL;
1528 
1529 	/*
1530 	 * Attempt to lock directory; fail if entry doesn't exist.
1531 	 */
1532 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZEXISTS)) {
1533 		ZFS_EXIT(zfsvfs);
1534 		return (error);
1535 	}
1536 
1537 	vp = ZTOV(zp);
1538 
1539 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1540 		goto out;
1541 	}
1542 
1543 	if (vp->v_type != VDIR) {
1544 		error = ENOTDIR;
1545 		goto out;
1546 	}
1547 
1548 	if (vp == cwd) {
1549 		error = EINVAL;
1550 		goto out;
1551 	}
1552 
1553 	vnevent_rmdir(vp);
1554 
1555 	/*
1556 	 * Grab a lock on the parent pointer make sure we play well
1557 	 * with the treewalk and directory rename code.
1558 	 */
1559 	rw_enter(&zp->z_parent_lock, RW_WRITER);
1560 
1561 	tx = dmu_tx_create(zfsvfs->z_os);
1562 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1563 	dmu_tx_hold_bonus(tx, zp->z_id);
1564 	dmu_tx_hold_zap(tx, zfsvfs->z_dqueue, FALSE, NULL);
1565 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
1566 	if (error) {
1567 		rw_exit(&zp->z_parent_lock);
1568 		zfs_dirent_unlock(dl);
1569 		VN_RELE(vp);
1570 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1571 			dmu_tx_wait(tx);
1572 			dmu_tx_abort(tx);
1573 			goto top;
1574 		}
1575 		dmu_tx_abort(tx);
1576 		ZFS_EXIT(zfsvfs);
1577 		return (error);
1578 	}
1579 
1580 	error = zfs_link_destroy(dl, zp, tx, 0, NULL);
1581 
1582 	if (error == 0)
1583 		seq = zfs_log_remove(zilog, tx, TX_RMDIR, dzp, name);
1584 
1585 	dmu_tx_commit(tx);
1586 
1587 	rw_exit(&zp->z_parent_lock);
1588 out:
1589 	zfs_dirent_unlock(dl);
1590 
1591 	VN_RELE(vp);
1592 
1593 	zil_commit(zilog, seq, 0);
1594 
1595 	ZFS_EXIT(zfsvfs);
1596 	return (error);
1597 }
1598 
1599 /*
1600  * Read as many directory entries as will fit into the provided
1601  * buffer from the given directory cursor position (specified in
1602  * the uio structure.
1603  *
1604  *	IN:	vp	- vnode of directory to read.
1605  *		uio	- structure supplying read location, range info,
1606  *			  and return buffer.
1607  *		cr	- credentials of caller.
1608  *
1609  *	OUT:	uio	- updated offset and range, buffer filled.
1610  *		eofp	- set to true if end-of-file detected.
1611  *
1612  *	RETURN:	0 if success
1613  *		error code if failure
1614  *
1615  * Timestamps:
1616  *	vp - atime updated
1617  *
1618  * Note that the low 4 bits of the cookie returned by zap is always zero.
1619  * This allows us to use the low range for "special" directory entries:
1620  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1621  * we use the offset 2 for the '.zfs' directory.
1622  */
1623 /* ARGSUSED */
1624 static int
1625 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp)
1626 {
1627 	znode_t		*zp = VTOZ(vp);
1628 	iovec_t		*iovp;
1629 	dirent64_t	*odp;
1630 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1631 	objset_t	*os;
1632 	caddr_t		outbuf;
1633 	size_t		bufsize;
1634 	zap_cursor_t	zc;
1635 	zap_attribute_t	zap;
1636 	uint_t		bytes_wanted;
1637 	ushort_t	this_reclen;
1638 	uint64_t	offset; /* must be unsigned; checks for < 1 */
1639 	off64_t		*next;
1640 	int		local_eof;
1641 	int		outcount;
1642 	int		error;
1643 	uint8_t		prefetch;
1644 
1645 	ZFS_ENTER(zfsvfs);
1646 
1647 	/*
1648 	 * If we are not given an eof variable,
1649 	 * use a local one.
1650 	 */
1651 	if (eofp == NULL)
1652 		eofp = &local_eof;
1653 
1654 	/*
1655 	 * Check for valid iov_len.
1656 	 */
1657 	if (uio->uio_iov->iov_len <= 0) {
1658 		ZFS_EXIT(zfsvfs);
1659 		return (EINVAL);
1660 	}
1661 
1662 	/*
1663 	 * Quit if directory has been removed (posix)
1664 	 */
1665 	if ((*eofp = zp->z_reap) != 0) {
1666 		ZFS_EXIT(zfsvfs);
1667 		return (0);
1668 	}
1669 
1670 	error = 0;
1671 	os = zfsvfs->z_os;
1672 	offset = uio->uio_loffset;
1673 	prefetch = zp->z_zn_prefetch;
1674 
1675 	/*
1676 	 * Initialize the iterator cursor.
1677 	 */
1678 	if (offset <= 3) {
1679 		/*
1680 		 * Start iteration from the beginning of the directory.
1681 		 */
1682 		zap_cursor_init(&zc, os, zp->z_id);
1683 	} else {
1684 		/*
1685 		 * The offset is a serialized cursor.
1686 		 */
1687 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1688 	}
1689 
1690 	/*
1691 	 * Get space to change directory entries into fs independent format.
1692 	 */
1693 	iovp = uio->uio_iov;
1694 	bytes_wanted = iovp->iov_len;
1695 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
1696 		bufsize = bytes_wanted;
1697 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
1698 		odp = (struct dirent64 *)outbuf;
1699 	} else {
1700 		bufsize = bytes_wanted;
1701 		odp = (struct dirent64 *)iovp->iov_base;
1702 	}
1703 
1704 	/*
1705 	 * Transform to file-system independent format
1706 	 */
1707 	outcount = 0;
1708 	while (outcount < bytes_wanted) {
1709 		/*
1710 		 * Special case `.', `..', and `.zfs'.
1711 		 */
1712 		if (offset == 0) {
1713 			(void) strcpy(zap.za_name, ".");
1714 			zap.za_first_integer = zp->z_id;
1715 			this_reclen = DIRENT64_RECLEN(1);
1716 		} else if (offset == 1) {
1717 			(void) strcpy(zap.za_name, "..");
1718 			zap.za_first_integer = zp->z_phys->zp_parent;
1719 			this_reclen = DIRENT64_RECLEN(2);
1720 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
1721 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
1722 			zap.za_first_integer = ZFSCTL_INO_ROOT;
1723 			this_reclen =
1724 			    DIRENT64_RECLEN(sizeof (ZFS_CTLDIR_NAME) - 1);
1725 		} else {
1726 			/*
1727 			 * Grab next entry.
1728 			 */
1729 			if (error = zap_cursor_retrieve(&zc, &zap)) {
1730 				if ((*eofp = (error == ENOENT)) != 0)
1731 					break;
1732 				else
1733 					goto update;
1734 			}
1735 
1736 			if (zap.za_integer_length != 8 ||
1737 			    zap.za_num_integers != 1) {
1738 				cmn_err(CE_WARN, "zap_readdir: bad directory "
1739 				    "entry, obj = %lld, offset = %lld\n",
1740 				    (u_longlong_t)zp->z_id,
1741 				    (u_longlong_t)offset);
1742 				error = ENXIO;
1743 				goto update;
1744 			}
1745 			this_reclen = DIRENT64_RECLEN(strlen(zap.za_name));
1746 		}
1747 
1748 		/*
1749 		 * Will this entry fit in the buffer?
1750 		 */
1751 		if (outcount + this_reclen > bufsize) {
1752 			/*
1753 			 * Did we manage to fit anything in the buffer?
1754 			 */
1755 			if (!outcount) {
1756 				error = EINVAL;
1757 				goto update;
1758 			}
1759 			break;
1760 		}
1761 		/*
1762 		 * Add this entry:
1763 		 */
1764 		odp->d_ino = (ino64_t)zap.za_first_integer;
1765 		odp->d_reclen = (ushort_t)this_reclen;
1766 		/* NOTE: d_off is the offset for the *next* entry */
1767 		next = &(odp->d_off);
1768 		(void) strncpy(odp->d_name, zap.za_name,
1769 		    DIRENT64_NAMELEN(this_reclen));
1770 		outcount += this_reclen;
1771 		odp = (dirent64_t *)((intptr_t)odp + this_reclen);
1772 
1773 		ASSERT(outcount <= bufsize);
1774 
1775 		/* Prefetch znode */
1776 		if (prefetch)
1777 			dmu_prefetch(os, zap.za_first_integer, 0, 0);
1778 
1779 		/*
1780 		 * Move to the next entry, fill in the previous offset.
1781 		 */
1782 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
1783 			zap_cursor_advance(&zc);
1784 			offset = zap_cursor_serialize(&zc);
1785 		} else {
1786 			offset += 1;
1787 		}
1788 		*next = offset;
1789 	}
1790 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
1791 
1792 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
1793 		iovp->iov_base += outcount;
1794 		iovp->iov_len -= outcount;
1795 		uio->uio_resid -= outcount;
1796 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
1797 		/*
1798 		 * Reset the pointer.
1799 		 */
1800 		offset = uio->uio_loffset;
1801 	}
1802 
1803 update:
1804 	zap_cursor_fini(&zc);
1805 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
1806 		kmem_free(outbuf, bufsize);
1807 
1808 	if (error == ENOENT)
1809 		error = 0;
1810 
1811 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
1812 
1813 	uio->uio_loffset = offset;
1814 	ZFS_EXIT(zfsvfs);
1815 	return (error);
1816 }
1817 
1818 static int
1819 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr)
1820 {
1821 	znode_t	*zp = VTOZ(vp);
1822 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1823 
1824 	/*
1825 	 * Regardless of whether this is required for standards conformance,
1826 	 * this is the logical behavior when fsync() is called on a file with
1827 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
1828 	 * going to be pushed out as part of the zil_commit().
1829 	 */
1830 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
1831 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
1832 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr);
1833 
1834 	ZFS_ENTER(zfsvfs);
1835 	zil_commit(zfsvfs->z_log, zp->z_last_itx, FSYNC);
1836 	ZFS_EXIT(zfsvfs);
1837 	return (0);
1838 }
1839 
1840 /*
1841  * Get the requested file attributes and place them in the provided
1842  * vattr structure.
1843  *
1844  *	IN:	vp	- vnode of file.
1845  *		vap	- va_mask identifies requested attributes.
1846  *		flags	- [UNUSED]
1847  *		cr	- credentials of caller.
1848  *
1849  *	OUT:	vap	- attribute values.
1850  *
1851  *	RETURN:	0 (always succeeds)
1852  */
1853 /* ARGSUSED */
1854 static int
1855 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr)
1856 {
1857 	znode_t *zp = VTOZ(vp);
1858 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1859 	znode_phys_t *pzp = zp->z_phys;
1860 	int	error;
1861 
1862 	ZFS_ENTER(zfsvfs);
1863 
1864 	/*
1865 	 * Return all attributes.  It's cheaper to provide the answer
1866 	 * than to determine whether we were asked the question.
1867 	 */
1868 	mutex_enter(&zp->z_lock);
1869 
1870 	vap->va_type = vp->v_type;
1871 	vap->va_mode = pzp->zp_mode & MODEMASK;
1872 	vap->va_uid = zp->z_phys->zp_uid;
1873 	vap->va_gid = zp->z_phys->zp_gid;
1874 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
1875 	vap->va_nodeid = zp->z_id;
1876 	vap->va_nlink = MIN(pzp->zp_links, UINT32_MAX);	/* nlink_t limit! */
1877 	vap->va_size = pzp->zp_size;
1878 	vap->va_rdev = vp->v_rdev;
1879 	vap->va_seq = zp->z_seq;
1880 
1881 	ZFS_TIME_DECODE(&vap->va_atime, pzp->zp_atime);
1882 	ZFS_TIME_DECODE(&vap->va_mtime, pzp->zp_mtime);
1883 	ZFS_TIME_DECODE(&vap->va_ctime, pzp->zp_ctime);
1884 
1885 	/*
1886 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
1887 	 * Also, if we are the owner don't bother, since owner should
1888 	 * always be allowed to read basic attributes of file.
1889 	 */
1890 	if (!(zp->z_phys->zp_flags & ZFS_ACL_TRIVIAL) &&
1891 	    (zp->z_phys->zp_uid != crgetuid(cr))) {
1892 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, cr)) {
1893 			mutex_exit(&zp->z_lock);
1894 			ZFS_EXIT(zfsvfs);
1895 			return (error);
1896 		}
1897 	}
1898 
1899 	mutex_exit(&zp->z_lock);
1900 
1901 	dmu_object_size_from_db(zp->z_dbuf, &vap->va_blksize, &vap->va_nblocks);
1902 
1903 	if (zp->z_blksz == 0) {
1904 		/*
1905 		 * Block size hasn't been set; suggest maximal I/O transfers.
1906 		 */
1907 		vap->va_blksize = zfsvfs->z_max_blksz;
1908 	}
1909 
1910 	ZFS_EXIT(zfsvfs);
1911 	return (0);
1912 }
1913 
1914 /*
1915  * Set the file attributes to the values contained in the
1916  * vattr structure.
1917  *
1918  *	IN:	vp	- vnode of file to be modified.
1919  *		vap	- new attribute values.
1920  *		flags	- ATTR_UTIME set if non-default time values provided.
1921  *		cr	- credentials of caller.
1922  *
1923  *	RETURN:	0 if success
1924  *		error code if failure
1925  *
1926  * Timestamps:
1927  *	vp - ctime updated, mtime updated if size changed.
1928  */
1929 /* ARGSUSED */
1930 static int
1931 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
1932 	caller_context_t *ct)
1933 {
1934 	struct znode	*zp = VTOZ(vp);
1935 	znode_phys_t	*pzp = zp->z_phys;
1936 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1937 	zilog_t		*zilog = zfsvfs->z_log;
1938 	uint64_t	seq = 0;
1939 	dmu_tx_t	*tx;
1940 	vattr_t		oldva;
1941 	uint_t		mask = vap->va_mask;
1942 	uint_t		saved_mask;
1943 	int		trim_mask = FALSE;
1944 	uint64_t	new_mode;
1945 	znode_t		*attrzp;
1946 	int		need_policy = FALSE;
1947 	int		err;
1948 
1949 	if (mask == 0)
1950 		return (0);
1951 
1952 	if (mask & AT_NOSET)
1953 		return (EINVAL);
1954 
1955 	if (mask & AT_SIZE && vp->v_type == VDIR)
1956 		return (EISDIR);
1957 
1958 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO)
1959 		return (EINVAL);
1960 
1961 	ZFS_ENTER(zfsvfs);
1962 
1963 top:
1964 	attrzp = NULL;
1965 
1966 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
1967 		ZFS_EXIT(zfsvfs);
1968 		return (EROFS);
1969 	}
1970 
1971 	/*
1972 	 * First validate permissions
1973 	 */
1974 
1975 	if (mask & AT_SIZE) {
1976 		err = zfs_zaccess(zp, ACE_WRITE_DATA, cr);
1977 		if (err) {
1978 			ZFS_EXIT(zfsvfs);
1979 			return (err);
1980 		}
1981 		/*
1982 		 * XXX - Note, we are not providing any open
1983 		 * mode flags here (like FNDELAY), so we may
1984 		 * block if there are locks present... this
1985 		 * should be addressed in openat().
1986 		 */
1987 		do {
1988 			err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
1989 			/* NB: we already did dmu_tx_wait() if necessary */
1990 		} while (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT);
1991 		if (err) {
1992 			ZFS_EXIT(zfsvfs);
1993 			return (err);
1994 		}
1995 	}
1996 
1997 	if (mask & (AT_ATIME|AT_MTIME))
1998 		need_policy = zfs_zaccess_v4_perm(zp, ACE_WRITE_ATTRIBUTES, cr);
1999 
2000 	if (mask & (AT_UID|AT_GID)) {
2001 		int	idmask = (mask & (AT_UID|AT_GID));
2002 		int	take_owner;
2003 		int	take_group;
2004 
2005 		/*
2006 		 * NOTE: even if a new mode is being set,
2007 		 * we may clear S_ISUID/S_ISGID bits.
2008 		 */
2009 
2010 		if (!(mask & AT_MODE))
2011 			vap->va_mode = pzp->zp_mode;
2012 
2013 		/*
2014 		 * Take ownership or chgrp to group we are a member of
2015 		 */
2016 
2017 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2018 		take_group = (mask & AT_GID) && groupmember(vap->va_gid, cr);
2019 
2020 		/*
2021 		 * If both AT_UID and AT_GID are set then take_owner and
2022 		 * take_group must both be set in order to allow taking
2023 		 * ownership.
2024 		 *
2025 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2026 		 *
2027 		 */
2028 
2029 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2030 		    ((idmask == AT_UID) && take_owner) ||
2031 		    ((idmask == AT_GID) && take_group)) {
2032 			if (zfs_zaccess_v4_perm(zp, ACE_WRITE_OWNER, cr) == 0) {
2033 				/*
2034 				 * Remove setuid/setgid for non-privileged users
2035 				 */
2036 				secpolicy_setid_clear(vap, cr);
2037 				trim_mask = TRUE;
2038 				saved_mask = vap->va_mask;
2039 			} else {
2040 				need_policy =  TRUE;
2041 			}
2042 		} else {
2043 			need_policy =  TRUE;
2044 		}
2045 	}
2046 
2047 	if (mask & AT_MODE)
2048 		need_policy = TRUE;
2049 
2050 	if (need_policy) {
2051 		mutex_enter(&zp->z_lock);
2052 		oldva.va_mode = pzp->zp_mode;
2053 		oldva.va_uid = zp->z_phys->zp_uid;
2054 		oldva.va_gid = zp->z_phys->zp_gid;
2055 		mutex_exit(&zp->z_lock);
2056 
2057 		/*
2058 		 * If trim_mask is set then take ownership
2059 		 * has been granted.  In that case remove
2060 		 * UID|GID from mask so that
2061 		 * secpolicy_vnode_setattr() doesn't revoke it.
2062 		 */
2063 		if (trim_mask)
2064 			vap->va_mask &= ~(AT_UID|AT_GID);
2065 
2066 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2067 		    (int (*)(void *, int, cred_t *))zfs_zaccess_rwx, zp);
2068 		if (err) {
2069 			ZFS_EXIT(zfsvfs);
2070 			return (err);
2071 		}
2072 
2073 		if (trim_mask)
2074 			vap->va_mask |= (saved_mask & (AT_UID|AT_GID));
2075 	}
2076 
2077 	/*
2078 	 * secpolicy_vnode_setattr, or take ownership may have
2079 	 * changed va_mask
2080 	 */
2081 	mask = vap->va_mask;
2082 
2083 	tx = dmu_tx_create(zfsvfs->z_os);
2084 	dmu_tx_hold_bonus(tx, zp->z_id);
2085 
2086 	if (mask & AT_MODE) {
2087 		uint64_t pmode = pzp->zp_mode;
2088 
2089 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2090 
2091 		if (zp->z_phys->zp_acl.z_acl_extern_obj)
2092 			dmu_tx_hold_write(tx,
2093 			    pzp->zp_acl.z_acl_extern_obj, 0, SPA_MAXBLOCKSIZE);
2094 		else
2095 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2096 			    0, ZFS_ACL_SIZE(MAX_ACL_SIZE));
2097 	}
2098 
2099 	if ((mask & (AT_UID | AT_GID)) && zp->z_phys->zp_xattr != 0) {
2100 		err = zfs_zget(zp->z_zfsvfs, zp->z_phys->zp_xattr, &attrzp);
2101 		if (err) {
2102 			dmu_tx_abort(tx);
2103 			ZFS_EXIT(zfsvfs);
2104 			return (err);
2105 		}
2106 		dmu_tx_hold_bonus(tx, attrzp->z_id);
2107 	}
2108 
2109 	err = dmu_tx_assign(tx, zfsvfs->z_assign);
2110 	if (err) {
2111 		if (attrzp)
2112 			VN_RELE(ZTOV(attrzp));
2113 		if (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2114 			dmu_tx_wait(tx);
2115 			dmu_tx_abort(tx);
2116 			goto top;
2117 		}
2118 		dmu_tx_abort(tx);
2119 		ZFS_EXIT(zfsvfs);
2120 		return (err);
2121 	}
2122 
2123 	dmu_buf_will_dirty(zp->z_dbuf, tx);
2124 
2125 	/*
2126 	 * Set each attribute requested.
2127 	 * We group settings according to the locks they need to acquire.
2128 	 *
2129 	 * Note: you cannot set ctime directly, although it will be
2130 	 * updated as a side-effect of calling this function.
2131 	 */
2132 
2133 	mutex_enter(&zp->z_lock);
2134 
2135 	if (mask & AT_MODE) {
2136 		err = zfs_acl_chmod_setattr(zp, new_mode, tx);
2137 		ASSERT3U(err, ==, 0);
2138 	}
2139 
2140 	if (attrzp)
2141 		mutex_enter(&attrzp->z_lock);
2142 
2143 	if (mask & AT_UID) {
2144 		zp->z_phys->zp_uid = (uint64_t)vap->va_uid;
2145 		if (attrzp) {
2146 			attrzp->z_phys->zp_uid = (uint64_t)vap->va_uid;
2147 		}
2148 	}
2149 
2150 	if (mask & AT_GID) {
2151 		zp->z_phys->zp_gid = (uint64_t)vap->va_gid;
2152 		if (attrzp)
2153 			attrzp->z_phys->zp_gid = (uint64_t)vap->va_gid;
2154 	}
2155 
2156 	if (attrzp)
2157 		mutex_exit(&attrzp->z_lock);
2158 
2159 	if (mask & AT_ATIME)
2160 		ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
2161 
2162 	if (mask & AT_MTIME)
2163 		ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
2164 
2165 	if (mask & AT_SIZE)
2166 		zfs_time_stamper_locked(zp, CONTENT_MODIFIED, tx);
2167 	else if (mask != 0)
2168 		zfs_time_stamper_locked(zp, STATE_CHANGED, tx);
2169 
2170 	if (mask != 0)
2171 		seq = zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask);
2172 
2173 	mutex_exit(&zp->z_lock);
2174 
2175 	if (attrzp)
2176 		VN_RELE(ZTOV(attrzp));
2177 
2178 	dmu_tx_commit(tx);
2179 
2180 	zil_commit(zilog, seq, 0);
2181 
2182 	ZFS_EXIT(zfsvfs);
2183 	return (err);
2184 }
2185 
2186 /*
2187  * Search back through the directory tree, using the ".." entries.
2188  * Lock each directory in the chain to prevent concurrent renames.
2189  * Fail any attempt to move a directory into one of its own descendants.
2190  * XXX - z_parent_lock can overlap with map or grow locks
2191  */
2192 typedef struct zfs_zlock {
2193 	krwlock_t	*zl_rwlock;	/* lock we acquired */
2194 	znode_t		*zl_znode;	/* znode we held */
2195 	struct zfs_zlock *zl_next;	/* next in list */
2196 } zfs_zlock_t;
2197 
2198 static int
2199 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
2200 {
2201 	zfs_zlock_t	*zl;
2202 	znode_t 	*zp = tdzp;
2203 	uint64_t	rootid = zp->z_zfsvfs->z_root;
2204 	uint64_t	*oidp = &zp->z_id;
2205 	krwlock_t	*rwlp = &szp->z_parent_lock;
2206 	krw_t		rw = RW_WRITER;
2207 
2208 	/*
2209 	 * First pass write-locks szp and compares to zp->z_id.
2210 	 * Later passes read-lock zp and compare to zp->z_parent.
2211 	 */
2212 	do {
2213 		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
2214 		zl->zl_rwlock = rwlp;
2215 		zl->zl_znode = NULL;
2216 		zl->zl_next = *zlpp;
2217 		*zlpp = zl;
2218 
2219 		rw_enter(rwlp, rw);
2220 
2221 		if (*oidp == szp->z_id)		/* We're a descendant of szp */
2222 			return (EINVAL);
2223 
2224 		if (*oidp == rootid)		/* We've hit the top */
2225 			return (0);
2226 
2227 		if (rw == RW_READER) {		/* i.e. not the first pass */
2228 			int error = zfs_zget(zp->z_zfsvfs, *oidp, &zp);
2229 			if (error)
2230 				return (error);
2231 			zl->zl_znode = zp;
2232 		}
2233 		oidp = &zp->z_phys->zp_parent;
2234 		rwlp = &zp->z_parent_lock;
2235 		rw = RW_READER;
2236 
2237 	} while (zp->z_id != sdzp->z_id);
2238 
2239 	return (0);
2240 }
2241 
2242 /*
2243  * Drop locks and release vnodes that were held by zfs_rename_lock().
2244  */
2245 static void
2246 zfs_rename_unlock(zfs_zlock_t **zlpp)
2247 {
2248 	zfs_zlock_t *zl;
2249 
2250 	while ((zl = *zlpp) != NULL) {
2251 		if (zl->zl_znode != NULL)
2252 			VN_RELE(ZTOV(zl->zl_znode));
2253 		rw_exit(zl->zl_rwlock);
2254 		*zlpp = zl->zl_next;
2255 		kmem_free(zl, sizeof (*zl));
2256 	}
2257 }
2258 
2259 /*
2260  * Move an entry from the provided source directory to the target
2261  * directory.  Change the entry name as indicated.
2262  *
2263  *	IN:	sdvp	- Source directory containing the "old entry".
2264  *		snm	- Old entry name.
2265  *		tdvp	- Target directory to contain the "new entry".
2266  *		tnm	- New entry name.
2267  *		cr	- credentials of caller.
2268  *
2269  *	RETURN:	0 if success
2270  *		error code if failure
2271  *
2272  * Timestamps:
2273  *	sdvp,tdvp - ctime|mtime updated
2274  */
2275 static int
2276 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr)
2277 {
2278 	znode_t		*tdzp, *szp, *tzp;
2279 	znode_t		*sdzp = VTOZ(sdvp);
2280 	zfsvfs_t	*zfsvfs = sdzp->z_zfsvfs;
2281 	zilog_t		*zilog = zfsvfs->z_log;
2282 	uint64_t	seq = 0;
2283 	vnode_t		*realvp;
2284 	zfs_dirlock_t	*sdl, *tdl;
2285 	dmu_tx_t	*tx;
2286 	zfs_zlock_t	*zl;
2287 	int		cmp, serr, terr, error;
2288 
2289 	ZFS_ENTER(zfsvfs);
2290 
2291 	/*
2292 	 * Make sure we have the real vp for the target directory.
2293 	 */
2294 	if (VOP_REALVP(tdvp, &realvp) == 0)
2295 		tdvp = realvp;
2296 
2297 	if (tdvp->v_vfsp != sdvp->v_vfsp) {
2298 		ZFS_EXIT(zfsvfs);
2299 		return (EXDEV);
2300 	}
2301 
2302 	tdzp = VTOZ(tdvp);
2303 top:
2304 	szp = NULL;
2305 	tzp = NULL;
2306 	zl = NULL;
2307 
2308 	/*
2309 	 * This is to prevent the creation of links into attribute space
2310 	 * by renaming a linked file into/outof an attribute directory.
2311 	 * See the comment in zfs_link() for why this is considered bad.
2312 	 */
2313 	if ((tdzp->z_phys->zp_flags & ZFS_XATTR) !=
2314 	    (sdzp->z_phys->zp_flags & ZFS_XATTR)) {
2315 		ZFS_EXIT(zfsvfs);
2316 		return (EINVAL);
2317 	}
2318 
2319 	/*
2320 	 * Lock source and target directory entries.  To prevent deadlock,
2321 	 * a lock ordering must be defined.  We lock the directory with
2322 	 * the smallest object id first, or if it's a tie, the one with
2323 	 * the lexically first name.
2324 	 */
2325 	if (sdzp->z_id < tdzp->z_id) {
2326 		cmp = -1;
2327 	} else if (sdzp->z_id > tdzp->z_id) {
2328 		cmp = 1;
2329 	} else {
2330 		cmp = strcmp(snm, tnm);
2331 		if (cmp == 0) {
2332 			/*
2333 			 * POSIX: "If the old argument and the new argument
2334 			 * both refer to links to the same existing file,
2335 			 * the rename() function shall return successfully
2336 			 * and perform no other action."
2337 			 */
2338 			ZFS_EXIT(zfsvfs);
2339 			return (0);
2340 		}
2341 	}
2342 	if (cmp < 0) {
2343 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp, ZEXISTS);
2344 		terr = zfs_dirent_lock(&tdl, tdzp, tnm, &tzp, 0);
2345 	} else {
2346 		terr = zfs_dirent_lock(&tdl, tdzp, tnm, &tzp, 0);
2347 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp, ZEXISTS);
2348 	}
2349 
2350 	if (serr) {
2351 		/*
2352 		 * Source entry invalid or not there.
2353 		 */
2354 		if (!terr) {
2355 			zfs_dirent_unlock(tdl);
2356 			if (tzp)
2357 				VN_RELE(ZTOV(tzp));
2358 		}
2359 		if (strcmp(snm, "..") == 0)
2360 			serr = EINVAL;
2361 		ZFS_EXIT(zfsvfs);
2362 		return (serr);
2363 	}
2364 	if (terr) {
2365 		zfs_dirent_unlock(sdl);
2366 		VN_RELE(ZTOV(szp));
2367 		if (strcmp(tnm, "..") == 0)
2368 			terr = EINVAL;
2369 		ZFS_EXIT(zfsvfs);
2370 		return (terr);
2371 	}
2372 
2373 	/*
2374 	 * Must have write access at the source to remove the old entry
2375 	 * and write access at the target to create the new entry.
2376 	 * Note that if target and source are the same, this can be
2377 	 * done in a single check.
2378 	 */
2379 
2380 	if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
2381 		goto out;
2382 
2383 	if (ZTOV(szp)->v_type == VDIR) {
2384 		/*
2385 		 * Check to make sure rename is valid.
2386 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
2387 		 */
2388 		if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
2389 			goto out;
2390 	}
2391 
2392 	/*
2393 	 * Does target exist?
2394 	 */
2395 	if (tzp) {
2396 		/*
2397 		 * Source and target must be the same type.
2398 		 */
2399 		if (ZTOV(szp)->v_type == VDIR) {
2400 			if (ZTOV(tzp)->v_type != VDIR) {
2401 				error = ENOTDIR;
2402 				goto out;
2403 			}
2404 		} else {
2405 			if (ZTOV(tzp)->v_type == VDIR) {
2406 				error = EISDIR;
2407 				goto out;
2408 			}
2409 		}
2410 		/*
2411 		 * POSIX dictates that when the source and target
2412 		 * entries refer to the same file object, rename
2413 		 * must do nothing and exit without error.
2414 		 */
2415 		if (szp->z_id == tzp->z_id) {
2416 			error = 0;
2417 			goto out;
2418 		}
2419 	}
2420 
2421 	vnevent_rename_src(ZTOV(szp));
2422 	if (tzp)
2423 		vnevent_rename_dest(ZTOV(tzp));
2424 
2425 	tx = dmu_tx_create(zfsvfs->z_os);
2426 	dmu_tx_hold_bonus(tx, szp->z_id);	/* nlink changes */
2427 	dmu_tx_hold_bonus(tx, sdzp->z_id);	/* nlink changes */
2428 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
2429 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
2430 	if (sdzp != tdzp)
2431 		dmu_tx_hold_bonus(tx, tdzp->z_id);	/* nlink changes */
2432 	if (tzp)
2433 		dmu_tx_hold_bonus(tx, tzp->z_id);	/* parent changes */
2434 	dmu_tx_hold_zap(tx, zfsvfs->z_dqueue, FALSE, NULL);
2435 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
2436 	if (error) {
2437 		if (zl != NULL)
2438 			zfs_rename_unlock(&zl);
2439 		zfs_dirent_unlock(sdl);
2440 		zfs_dirent_unlock(tdl);
2441 		VN_RELE(ZTOV(szp));
2442 		if (tzp)
2443 			VN_RELE(ZTOV(tzp));
2444 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2445 			dmu_tx_wait(tx);
2446 			dmu_tx_abort(tx);
2447 			goto top;
2448 		}
2449 		dmu_tx_abort(tx);
2450 		ZFS_EXIT(zfsvfs);
2451 		return (error);
2452 	}
2453 
2454 	if (tzp)	/* Attempt to remove the existing target */
2455 		error = zfs_link_destroy(tdl, tzp, tx, 0, NULL);
2456 
2457 	if (error == 0) {
2458 		error = zfs_link_create(tdl, szp, tx, ZRENAMING);
2459 		if (error == 0) {
2460 			error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
2461 			ASSERT(error == 0);
2462 			seq = zfs_log_rename(zilog, tx, TX_RENAME,
2463 			    sdzp, sdl->dl_name, tdzp, tdl->dl_name, szp);
2464 		}
2465 	}
2466 
2467 	dmu_tx_commit(tx);
2468 out:
2469 	if (zl != NULL)
2470 		zfs_rename_unlock(&zl);
2471 
2472 	zfs_dirent_unlock(sdl);
2473 	zfs_dirent_unlock(tdl);
2474 
2475 	VN_RELE(ZTOV(szp));
2476 	if (tzp)
2477 		VN_RELE(ZTOV(tzp));
2478 
2479 	zil_commit(zilog, seq, 0);
2480 
2481 	ZFS_EXIT(zfsvfs);
2482 	return (error);
2483 }
2484 
2485 /*
2486  * Insert the indicated symbolic reference entry into the directory.
2487  *
2488  *	IN:	dvp	- Directory to contain new symbolic link.
2489  *		link	- Name for new symlink entry.
2490  *		vap	- Attributes of new entry.
2491  *		target	- Target path of new symlink.
2492  *		cr	- credentials of caller.
2493  *
2494  *	RETURN:	0 if success
2495  *		error code if failure
2496  *
2497  * Timestamps:
2498  *	dvp - ctime|mtime updated
2499  */
2500 static int
2501 zfs_symlink(vnode_t *dvp, char *name, vattr_t *vap, char *link, cred_t *cr)
2502 {
2503 	znode_t		*zp, *dzp = VTOZ(dvp);
2504 	zfs_dirlock_t	*dl;
2505 	dmu_tx_t	*tx;
2506 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2507 	zilog_t		*zilog = zfsvfs->z_log;
2508 	uint64_t	seq = 0;
2509 	uint64_t	zoid;
2510 	int		len = strlen(link);
2511 	int		error;
2512 
2513 	ASSERT(vap->va_type == VLNK);
2514 
2515 	ZFS_ENTER(zfsvfs);
2516 top:
2517 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
2518 		ZFS_EXIT(zfsvfs);
2519 		return (error);
2520 	}
2521 
2522 	if (len > MAXPATHLEN) {
2523 		ZFS_EXIT(zfsvfs);
2524 		return (ENAMETOOLONG);
2525 	}
2526 
2527 	/*
2528 	 * Attempt to lock directory; fail if entry already exists.
2529 	 */
2530 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZNEW)) {
2531 		ZFS_EXIT(zfsvfs);
2532 		return (error);
2533 	}
2534 
2535 	tx = dmu_tx_create(zfsvfs->z_os);
2536 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
2537 	dmu_tx_hold_bonus(tx, dzp->z_id);
2538 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
2539 	if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
2540 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, SPA_MAXBLOCKSIZE);
2541 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
2542 	if (error) {
2543 		zfs_dirent_unlock(dl);
2544 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2545 			dmu_tx_wait(tx);
2546 			dmu_tx_abort(tx);
2547 			goto top;
2548 		}
2549 		dmu_tx_abort(tx);
2550 		ZFS_EXIT(zfsvfs);
2551 		return (error);
2552 	}
2553 
2554 	dmu_buf_will_dirty(dzp->z_dbuf, tx);
2555 
2556 	/*
2557 	 * Create a new object for the symlink.
2558 	 * Put the link content into bonus buffer if it will fit;
2559 	 * otherwise, store it just like any other file data.
2560 	 */
2561 	zoid = 0;
2562 	if (sizeof (znode_phys_t) + len <= dmu_bonus_max()) {
2563 		zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, len);
2564 		if (len != 0)
2565 			bcopy(link, zp->z_phys + 1, len);
2566 	} else {
2567 		dmu_buf_t *dbp;
2568 
2569 		zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
2570 
2571 		/*
2572 		 * Nothing can access the znode yet so no locking needed
2573 		 * for growing the znode's blocksize.
2574 		 */
2575 		zfs_grow_blocksize(zp, len, tx);
2576 
2577 		VERIFY(0 == dmu_buf_hold(zfsvfs->z_os, zoid, 0, FTAG, &dbp));
2578 		dmu_buf_will_dirty(dbp, tx);
2579 
2580 		ASSERT3U(len, <=, dbp->db_size);
2581 		bcopy(link, dbp->db_data, len);
2582 		dmu_buf_rele(dbp, FTAG);
2583 	}
2584 	zp->z_phys->zp_size = len;
2585 
2586 	/*
2587 	 * Insert the new object into the directory.
2588 	 */
2589 	(void) zfs_link_create(dl, zp, tx, ZNEW);
2590 out:
2591 	if (error == 0)
2592 		seq = zfs_log_symlink(zilog, tx, TX_SYMLINK,
2593 		    dzp, zp, name, link);
2594 
2595 	dmu_tx_commit(tx);
2596 
2597 	zfs_dirent_unlock(dl);
2598 
2599 	VN_RELE(ZTOV(zp));
2600 
2601 	zil_commit(zilog, seq, 0);
2602 
2603 	ZFS_EXIT(zfsvfs);
2604 	return (error);
2605 }
2606 
2607 /*
2608  * Return, in the buffer contained in the provided uio structure,
2609  * the symbolic path referred to by vp.
2610  *
2611  *	IN:	vp	- vnode of symbolic link.
2612  *		uoip	- structure to contain the link path.
2613  *		cr	- credentials of caller.
2614  *
2615  *	OUT:	uio	- structure to contain the link path.
2616  *
2617  *	RETURN:	0 if success
2618  *		error code if failure
2619  *
2620  * Timestamps:
2621  *	vp - atime updated
2622  */
2623 /* ARGSUSED */
2624 static int
2625 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr)
2626 {
2627 	znode_t		*zp = VTOZ(vp);
2628 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2629 	size_t		bufsz;
2630 	int		error;
2631 
2632 	ZFS_ENTER(zfsvfs);
2633 
2634 	bufsz = (size_t)zp->z_phys->zp_size;
2635 	if (bufsz + sizeof (znode_phys_t) <= zp->z_dbuf->db_size) {
2636 		error = uiomove(zp->z_phys + 1,
2637 		    MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
2638 	} else {
2639 		dmu_buf_t *dbp;
2640 		error = dmu_buf_hold(zfsvfs->z_os, zp->z_id, 0, FTAG, &dbp);
2641 		if (error) {
2642 			ZFS_EXIT(zfsvfs);
2643 			return (error);
2644 		}
2645 		error = uiomove(dbp->db_data,
2646 		    MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
2647 		dmu_buf_rele(dbp, FTAG);
2648 	}
2649 
2650 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2651 	ZFS_EXIT(zfsvfs);
2652 	return (error);
2653 }
2654 
2655 /*
2656  * Insert a new entry into directory tdvp referencing svp.
2657  *
2658  *	IN:	tdvp	- Directory to contain new entry.
2659  *		svp	- vnode of new entry.
2660  *		name	- name of new entry.
2661  *		cr	- credentials of caller.
2662  *
2663  *	RETURN:	0 if success
2664  *		error code if failure
2665  *
2666  * Timestamps:
2667  *	tdvp - ctime|mtime updated
2668  *	 svp - ctime updated
2669  */
2670 /* ARGSUSED */
2671 static int
2672 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr)
2673 {
2674 	znode_t		*dzp = VTOZ(tdvp);
2675 	znode_t		*tzp, *szp;
2676 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2677 	zilog_t		*zilog = zfsvfs->z_log;
2678 	uint64_t	seq = 0;
2679 	zfs_dirlock_t	*dl;
2680 	dmu_tx_t	*tx;
2681 	vnode_t		*realvp;
2682 	int		error;
2683 
2684 	ASSERT(tdvp->v_type == VDIR);
2685 
2686 	ZFS_ENTER(zfsvfs);
2687 
2688 	if (VOP_REALVP(svp, &realvp) == 0)
2689 		svp = realvp;
2690 
2691 	if (svp->v_vfsp != tdvp->v_vfsp) {
2692 		ZFS_EXIT(zfsvfs);
2693 		return (EXDEV);
2694 	}
2695 
2696 	szp = VTOZ(svp);
2697 top:
2698 	/*
2699 	 * We do not support links between attributes and non-attributes
2700 	 * because of the potential security risk of creating links
2701 	 * into "normal" file space in order to circumvent restrictions
2702 	 * imposed in attribute space.
2703 	 */
2704 	if ((szp->z_phys->zp_flags & ZFS_XATTR) !=
2705 	    (dzp->z_phys->zp_flags & ZFS_XATTR)) {
2706 		ZFS_EXIT(zfsvfs);
2707 		return (EINVAL);
2708 	}
2709 
2710 	/*
2711 	 * POSIX dictates that we return EPERM here.
2712 	 * Better choices include ENOTSUP or EISDIR.
2713 	 */
2714 	if (svp->v_type == VDIR) {
2715 		ZFS_EXIT(zfsvfs);
2716 		return (EPERM);
2717 	}
2718 
2719 	if ((uid_t)szp->z_phys->zp_uid != crgetuid(cr) &&
2720 	    secpolicy_basic_link(cr) != 0) {
2721 		ZFS_EXIT(zfsvfs);
2722 		return (EPERM);
2723 	}
2724 
2725 	if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
2726 		ZFS_EXIT(zfsvfs);
2727 		return (error);
2728 	}
2729 
2730 	/*
2731 	 * Attempt to lock directory; fail if entry already exists.
2732 	 */
2733 	if (error = zfs_dirent_lock(&dl, dzp, name, &tzp, ZNEW)) {
2734 		ZFS_EXIT(zfsvfs);
2735 		return (error);
2736 	}
2737 
2738 	tx = dmu_tx_create(zfsvfs->z_os);
2739 	dmu_tx_hold_bonus(tx, szp->z_id);
2740 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
2741 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
2742 	if (error) {
2743 		zfs_dirent_unlock(dl);
2744 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2745 			dmu_tx_wait(tx);
2746 			dmu_tx_abort(tx);
2747 			goto top;
2748 		}
2749 		dmu_tx_abort(tx);
2750 		ZFS_EXIT(zfsvfs);
2751 		return (error);
2752 	}
2753 
2754 	error = zfs_link_create(dl, szp, tx, 0);
2755 
2756 	if (error == 0)
2757 		seq = zfs_log_link(zilog, tx, TX_LINK, dzp, szp, name);
2758 
2759 	dmu_tx_commit(tx);
2760 
2761 	zfs_dirent_unlock(dl);
2762 
2763 	zil_commit(zilog, seq, 0);
2764 
2765 	ZFS_EXIT(zfsvfs);
2766 	return (error);
2767 }
2768 
2769 /*
2770  * zfs_null_putapage() is used when the file system has been force
2771  * unmounted. It just drops the pages.
2772  */
2773 /* ARGSUSED */
2774 static int
2775 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
2776 		size_t *lenp, int flags, cred_t *cr)
2777 {
2778 	pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
2779 	return (0);
2780 }
2781 
2782 /* ARGSUSED */
2783 static int
2784 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
2785 		size_t *lenp, int flags, cred_t *cr)
2786 {
2787 	znode_t		*zp = VTOZ(vp);
2788 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2789 	zilog_t		*zilog = zfsvfs->z_log;
2790 	dmu_tx_t	*tx;
2791 	rl_t		*rl;
2792 	u_offset_t	off;
2793 	ssize_t		len;
2794 	caddr_t		va;
2795 	int		err;
2796 
2797 top:
2798 	off = pp->p_offset;
2799 	rl = zfs_range_lock(zp, off, PAGESIZE, RL_WRITER);
2800 	/*
2801 	 * Can't push pages past end-of-file.
2802 	 */
2803 	if (off >= zp->z_phys->zp_size) {
2804 		zfs_range_unlock(rl);
2805 		return (EIO);
2806 	}
2807 	len = MIN(PAGESIZE, zp->z_phys->zp_size - off);
2808 
2809 	tx = dmu_tx_create(zfsvfs->z_os);
2810 	dmu_tx_hold_write(tx, zp->z_id, off, len);
2811 	dmu_tx_hold_bonus(tx, zp->z_id);
2812 	err = dmu_tx_assign(tx, zfsvfs->z_assign);
2813 	if (err != 0) {
2814 		zfs_range_unlock(rl);
2815 		if (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2816 			dmu_tx_wait(tx);
2817 			dmu_tx_abort(tx);
2818 			goto top;
2819 		}
2820 		dmu_tx_abort(tx);
2821 		goto out;
2822 	}
2823 
2824 	va = ppmapin(pp, PROT_READ | PROT_WRITE, (caddr_t)-1);
2825 
2826 	dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
2827 
2828 	ppmapout(va);
2829 
2830 	zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
2831 	(void) zfs_log_write(zilog, tx, TX_WRITE, zp, off, len, 0, NULL);
2832 	dmu_tx_commit(tx);
2833 
2834 	zfs_range_unlock(rl);
2835 
2836 	pvn_write_done(pp, B_WRITE | flags);
2837 	if (offp)
2838 		*offp = off;
2839 	if (lenp)
2840 		*lenp = len;
2841 
2842 out:
2843 	return (err);
2844 }
2845 
2846 /*
2847  * Copy the portion of the file indicated from pages into the file.
2848  * The pages are stored in a page list attached to the files vnode.
2849  *
2850  *	IN:	vp	- vnode of file to push page data to.
2851  *		off	- position in file to put data.
2852  *		len	- amount of data to write.
2853  *		flags	- flags to control the operation.
2854  *		cr	- credentials of caller.
2855  *
2856  *	RETURN:	0 if success
2857  *		error code if failure
2858  *
2859  * Timestamps:
2860  *	vp - ctime|mtime updated
2861  */
2862 static int
2863 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr)
2864 {
2865 	znode_t		*zp = VTOZ(vp);
2866 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2867 	page_t		*pp;
2868 	size_t		io_len;
2869 	u_offset_t	io_off;
2870 	uint64_t	filesz;
2871 	int		error = 0;
2872 
2873 	ZFS_ENTER(zfsvfs);
2874 
2875 	ASSERT(zp->z_dbuf_held && zp->z_phys);
2876 
2877 	if (len == 0) {
2878 		/*
2879 		 * Search the entire vp list for pages >= off.
2880 		 */
2881 		error = pvn_vplist_dirty(vp, (u_offset_t)off, zfs_putapage,
2882 		    flags, cr);
2883 		goto out;
2884 	}
2885 
2886 	filesz = zp->z_phys->zp_size; /* get consistent copy of zp_size */
2887 	if (off > filesz) {
2888 		/* past end of file */
2889 		ZFS_EXIT(zfsvfs);
2890 		return (0);
2891 	}
2892 
2893 	len = MIN(len, filesz - off);
2894 
2895 	for (io_off = off; io_off < off + len; io_off += io_len) {
2896 		if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
2897 			pp = page_lookup(vp, io_off,
2898 				(flags & (B_INVAL | B_FREE)) ?
2899 					SE_EXCL : SE_SHARED);
2900 		} else {
2901 			pp = page_lookup_nowait(vp, io_off,
2902 				(flags & B_FREE) ? SE_EXCL : SE_SHARED);
2903 		}
2904 
2905 		if (pp != NULL && pvn_getdirty(pp, flags)) {
2906 			int err;
2907 
2908 			/*
2909 			 * Found a dirty page to push
2910 			 */
2911 			err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
2912 			if (err)
2913 				error = err;
2914 		} else {
2915 			io_len = PAGESIZE;
2916 		}
2917 	}
2918 out:
2919 	zil_commit(zfsvfs->z_log, UINT64_MAX, (flags & B_ASYNC) ? 0 : FDSYNC);
2920 	ZFS_EXIT(zfsvfs);
2921 	return (error);
2922 }
2923 
2924 void
2925 zfs_inactive(vnode_t *vp, cred_t *cr)
2926 {
2927 	znode_t	*zp = VTOZ(vp);
2928 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2929 	int error;
2930 
2931 	rw_enter(&zfsvfs->z_um_lock, RW_READER);
2932 	if (zfsvfs->z_unmounted2) {
2933 		ASSERT(zp->z_dbuf_held == 0);
2934 
2935 		if (vn_has_cached_data(vp)) {
2936 			(void) pvn_vplist_dirty(vp, 0, zfs_null_putapage,
2937 			    B_INVAL, cr);
2938 		}
2939 
2940 		mutex_enter(&zp->z_lock);
2941 		vp->v_count = 0; /* count arrives as 1 */
2942 		if (zp->z_dbuf == NULL) {
2943 			mutex_exit(&zp->z_lock);
2944 			zfs_znode_free(zp);
2945 		} else {
2946 			mutex_exit(&zp->z_lock);
2947 		}
2948 		rw_exit(&zfsvfs->z_um_lock);
2949 		VFS_RELE(zfsvfs->z_vfs);
2950 		return;
2951 	}
2952 
2953 	/*
2954 	 * Attempt to push any data in the page cache.  If this fails
2955 	 * we will get kicked out later in zfs_zinactive().
2956 	 */
2957 	if (vn_has_cached_data(vp)) {
2958 		(void) pvn_vplist_dirty(vp, 0, zfs_putapage, B_INVAL|B_ASYNC,
2959 		    cr);
2960 	}
2961 
2962 	if (zp->z_atime_dirty && zp->z_reap == 0) {
2963 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
2964 
2965 		dmu_tx_hold_bonus(tx, zp->z_id);
2966 		error = dmu_tx_assign(tx, TXG_WAIT);
2967 		if (error) {
2968 			dmu_tx_abort(tx);
2969 		} else {
2970 			dmu_buf_will_dirty(zp->z_dbuf, tx);
2971 			mutex_enter(&zp->z_lock);
2972 			zp->z_atime_dirty = 0;
2973 			mutex_exit(&zp->z_lock);
2974 			dmu_tx_commit(tx);
2975 		}
2976 	}
2977 
2978 	zfs_zinactive(zp);
2979 	rw_exit(&zfsvfs->z_um_lock);
2980 }
2981 
2982 /*
2983  * Bounds-check the seek operation.
2984  *
2985  *	IN:	vp	- vnode seeking within
2986  *		ooff	- old file offset
2987  *		noffp	- pointer to new file offset
2988  *
2989  *	RETURN:	0 if success
2990  *		EINVAL if new offset invalid
2991  */
2992 /* ARGSUSED */
2993 static int
2994 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp)
2995 {
2996 	if (vp->v_type == VDIR)
2997 		return (0);
2998 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
2999 }
3000 
3001 /*
3002  * Pre-filter the generic locking function to trap attempts to place
3003  * a mandatory lock on a memory mapped file.
3004  */
3005 static int
3006 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
3007     flk_callback_t *flk_cbp, cred_t *cr)
3008 {
3009 	znode_t *zp = VTOZ(vp);
3010 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3011 	int error;
3012 
3013 	ZFS_ENTER(zfsvfs);
3014 
3015 	/*
3016 	 * We are following the UFS semantics with respect to mapcnt
3017 	 * here: If we see that the file is mapped already, then we will
3018 	 * return an error, but we don't worry about races between this
3019 	 * function and zfs_map().
3020 	 */
3021 	if (zp->z_mapcnt > 0 && MANDMODE((mode_t)zp->z_phys->zp_mode)) {
3022 		ZFS_EXIT(zfsvfs);
3023 		return (EAGAIN);
3024 	}
3025 	error = fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr);
3026 	ZFS_EXIT(zfsvfs);
3027 	return (error);
3028 }
3029 
3030 /*
3031  * If we can't find a page in the cache, we will create a new page
3032  * and fill it with file data.  For efficiency, we may try to fill
3033  * multiple pages at once (klustering).
3034  */
3035 static int
3036 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
3037     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
3038 {
3039 	znode_t *zp = VTOZ(vp);
3040 	page_t *pp, *cur_pp;
3041 	objset_t *os = zp->z_zfsvfs->z_os;
3042 	caddr_t va;
3043 	u_offset_t io_off, total;
3044 	uint64_t oid = zp->z_id;
3045 	size_t io_len;
3046 	uint64_t filesz;
3047 	int err;
3048 
3049 	/*
3050 	 * If we are only asking for a single page don't bother klustering.
3051 	 */
3052 	filesz = zp->z_phys->zp_size; /* get consistent copy of zp_size */
3053 	if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE || off > filesz) {
3054 		io_off = off;
3055 		io_len = PAGESIZE;
3056 		pp = page_create_va(vp, io_off, io_len, PG_WAIT, seg, addr);
3057 	} else {
3058 		/*
3059 		 * Try to fill a kluster of pages (a blocks worth).
3060 		 */
3061 		size_t klen;
3062 		u_offset_t koff;
3063 
3064 		if (!ISP2(zp->z_blksz)) {
3065 			/* Only one block in the file. */
3066 			klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
3067 			koff = 0;
3068 		} else {
3069 			klen = plsz;
3070 			koff = P2ALIGN(off, (u_offset_t)klen);
3071 		}
3072 		ASSERT(koff <= filesz);
3073 		if (koff + klen > filesz)
3074 			klen = P2ROUNDUP(filesz, (uint64_t)PAGESIZE) - koff;
3075 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
3076 			    &io_len, koff, klen, 0);
3077 	}
3078 	if (pp == NULL) {
3079 		/*
3080 		 * Some other thread entered the page before us.
3081 		 * Return to zfs_getpage to retry the lookup.
3082 		 */
3083 		*pl = NULL;
3084 		return (0);
3085 	}
3086 
3087 	/*
3088 	 * Fill the pages in the kluster.
3089 	 */
3090 	cur_pp = pp;
3091 	for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
3092 		ASSERT(io_off == cur_pp->p_offset);
3093 		va = ppmapin(cur_pp, PROT_READ | PROT_WRITE, (caddr_t)-1);
3094 		err = dmu_read(os, oid, io_off, PAGESIZE, va);
3095 		ppmapout(va);
3096 		if (err) {
3097 			/* On error, toss the entire kluster */
3098 			pvn_read_done(pp, B_ERROR);
3099 			return (err);
3100 		}
3101 		cur_pp = cur_pp->p_next;
3102 	}
3103 out:
3104 	/*
3105 	 * Fill in the page list array from the kluster.  If
3106 	 * there are too many pages in the kluster, return
3107 	 * as many pages as possible starting from the desired
3108 	 * offset `off'.
3109 	 * NOTE: the page list will always be null terminated.
3110 	 */
3111 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
3112 
3113 	return (0);
3114 }
3115 
3116 /*
3117  * Return pointers to the pages for the file region [off, off + len]
3118  * in the pl array.  If plsz is greater than len, this function may
3119  * also return page pointers from before or after the specified
3120  * region (i.e. some region [off', off' + plsz]).  These additional
3121  * pages are only returned if they are already in the cache, or were
3122  * created as part of a klustered read.
3123  *
3124  *	IN:	vp	- vnode of file to get data from.
3125  *		off	- position in file to get data from.
3126  *		len	- amount of data to retrieve.
3127  *		plsz	- length of provided page list.
3128  *		seg	- segment to obtain pages for.
3129  *		addr	- virtual address of fault.
3130  *		rw	- mode of created pages.
3131  *		cr	- credentials of caller.
3132  *
3133  *	OUT:	protp	- protection mode of created pages.
3134  *		pl	- list of pages created.
3135  *
3136  *	RETURN:	0 if success
3137  *		error code if failure
3138  *
3139  * Timestamps:
3140  *	vp - atime updated
3141  */
3142 /* ARGSUSED */
3143 static int
3144 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
3145 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
3146 	enum seg_rw rw, cred_t *cr)
3147 {
3148 	znode_t		*zp = VTOZ(vp);
3149 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3150 	page_t		*pp, **pl0 = pl;
3151 	rl_t		*rl;
3152 	int		cnt = 0, need_unlock = 0, err = 0;
3153 
3154 	ZFS_ENTER(zfsvfs);
3155 
3156 	if (protp)
3157 		*protp = PROT_ALL;
3158 
3159 	ASSERT(zp->z_dbuf_held && zp->z_phys);
3160 
3161 	/* no faultahead (for now) */
3162 	if (pl == NULL) {
3163 		ZFS_EXIT(zfsvfs);
3164 		return (0);
3165 	}
3166 
3167 	/*
3168 	 * Make sure nobody restructures the file in the middle of the getpage.
3169 	 */
3170 	rl = zfs_range_lock(zp, off, len, RL_READER);
3171 
3172 	/* can't fault past EOF */
3173 	if (off >= zp->z_phys->zp_size) {
3174 		zfs_range_unlock(rl);
3175 		ZFS_EXIT(zfsvfs);
3176 		return (EFAULT);
3177 	}
3178 
3179 	/*
3180 	 * If we already own the lock, then we must be page faulting
3181 	 * in the middle of a write to this file (i.e., we are writing
3182 	 * to this file using data from a mapped region of the file).
3183 	 */
3184 	if (!rw_owner(&zp->z_map_lock)) {
3185 		rw_enter(&zp->z_map_lock, RW_WRITER);
3186 		need_unlock = TRUE;
3187 	}
3188 
3189 	/*
3190 	 * Loop through the requested range [off, off + len] looking
3191 	 * for pages.  If we don't find a page, we will need to create
3192 	 * a new page and fill it with data from the file.
3193 	 */
3194 	while (len > 0) {
3195 		if (plsz < PAGESIZE)
3196 			break;
3197 		if (pp = page_lookup(vp, off, SE_SHARED)) {
3198 			*pl++ = pp;
3199 			off += PAGESIZE;
3200 			addr += PAGESIZE;
3201 			len -= PAGESIZE;
3202 			plsz -= PAGESIZE;
3203 		} else {
3204 			err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw);
3205 			/*
3206 			 * klustering may have changed our region
3207 			 * to be block aligned.
3208 			 */
3209 			if (((pp = *pl) != 0) && (off != pp->p_offset)) {
3210 				int delta = off - pp->p_offset;
3211 				len += delta;
3212 				off -= delta;
3213 				addr -= delta;
3214 			}
3215 			while (*pl) {
3216 				pl++;
3217 				cnt++;
3218 				off += PAGESIZE;
3219 				addr += PAGESIZE;
3220 				plsz -= PAGESIZE;
3221 				if (len > PAGESIZE)
3222 					len -= PAGESIZE;
3223 				else
3224 					len = 0;
3225 			}
3226 			if (err) {
3227 				/*
3228 				 * Release any pages we have locked.
3229 				 */
3230 				while (pl > pl0)
3231 					page_unlock(*--pl);
3232 				goto out;
3233 			}
3234 		}
3235 	}
3236 
3237 	/*
3238 	 * Fill out the page array with any pages already in the cache.
3239 	 */
3240 	while (plsz > 0) {
3241 		pp = page_lookup_nowait(vp, off, SE_SHARED);
3242 		if (pp == NULL)
3243 			break;
3244 		*pl++ = pp;
3245 		off += PAGESIZE;
3246 		plsz -= PAGESIZE;
3247 	}
3248 
3249 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3250 out:
3251 	*pl = NULL;
3252 
3253 	if (need_unlock)
3254 		rw_exit(&zp->z_map_lock);
3255 	zfs_range_unlock(rl);
3256 
3257 	ZFS_EXIT(zfsvfs);
3258 	return (err);
3259 }
3260 
3261 /*
3262  * Request a memory map for a section of a file.  This code interacts
3263  * with common code and the VM system as follows:
3264  *
3265  *	common code calls mmap(), which ends up in smmap_common()
3266  *
3267  *	this calls VOP_MAP(), which takes you into (say) zfs
3268  *
3269  *	zfs_map() calls as_map(), passing segvn_create() as the callback
3270  *
3271  *	segvn_create() creates the new segment and calls VOP_ADDMAP()
3272  *
3273  *	zfs_addmap() updates z_mapcnt
3274  */
3275 static int
3276 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
3277     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
3278 {
3279 	znode_t *zp = VTOZ(vp);
3280 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3281 	segvn_crargs_t	vn_a;
3282 	int		error;
3283 
3284 	ZFS_ENTER(zfsvfs);
3285 
3286 	if (vp->v_flag & VNOMAP) {
3287 		ZFS_EXIT(zfsvfs);
3288 		return (ENOSYS);
3289 	}
3290 
3291 	if (off < 0 || len > MAXOFFSET_T - off) {
3292 		ZFS_EXIT(zfsvfs);
3293 		return (ENXIO);
3294 	}
3295 
3296 	if (vp->v_type != VREG) {
3297 		ZFS_EXIT(zfsvfs);
3298 		return (ENODEV);
3299 	}
3300 
3301 	/*
3302 	 * If file is locked, disallow mapping.
3303 	 */
3304 	if (MANDMODE((mode_t)zp->z_phys->zp_mode) && vn_has_flocks(vp)) {
3305 		ZFS_EXIT(zfsvfs);
3306 		return (EAGAIN);
3307 	}
3308 
3309 	as_rangelock(as);
3310 	if ((flags & MAP_FIXED) == 0) {
3311 		map_addr(addrp, len, off, 1, flags);
3312 		if (*addrp == NULL) {
3313 			as_rangeunlock(as);
3314 			ZFS_EXIT(zfsvfs);
3315 			return (ENOMEM);
3316 		}
3317 	} else {
3318 		/*
3319 		 * User specified address - blow away any previous mappings
3320 		 */
3321 		(void) as_unmap(as, *addrp, len);
3322 	}
3323 
3324 	vn_a.vp = vp;
3325 	vn_a.offset = (u_offset_t)off;
3326 	vn_a.type = flags & MAP_TYPE;
3327 	vn_a.prot = prot;
3328 	vn_a.maxprot = maxprot;
3329 	vn_a.cred = cr;
3330 	vn_a.amp = NULL;
3331 	vn_a.flags = flags & ~MAP_TYPE;
3332 	vn_a.szc = 0;
3333 	vn_a.lgrp_mem_policy_flags = 0;
3334 
3335 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
3336 
3337 	as_rangeunlock(as);
3338 	ZFS_EXIT(zfsvfs);
3339 	return (error);
3340 }
3341 
3342 /* ARGSUSED */
3343 static int
3344 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
3345     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
3346 {
3347 	uint64_t pages = btopr(len);
3348 
3349 	atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
3350 	return (0);
3351 }
3352 
3353 /*
3354  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
3355  * more accurate mtime for the associated file.  Since we don't have a way of
3356  * detecting when the data was actually modified, we have to resort to
3357  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
3358  * last page is pushed.  The problem occurs when the msync() call is omitted,
3359  * which by far the most common case:
3360  *
3361  * 	open()
3362  * 	mmap()
3363  * 	<modify memory>
3364  * 	munmap()
3365  * 	close()
3366  * 	<time lapse>
3367  * 	putpage() via fsflush
3368  *
3369  * If we wait until fsflush to come along, we can have a modification time that
3370  * is some arbitrary point in the future.  In order to prevent this in the
3371  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
3372  * torn down.
3373  */
3374 /* ARGSUSED */
3375 static int
3376 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
3377     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr)
3378 {
3379 	uint64_t pages = btopr(len);
3380 
3381 	ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
3382 	atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
3383 
3384 	if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
3385 	    vn_has_cached_data(vp))
3386 		(void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr);
3387 
3388 	return (0);
3389 }
3390 
3391 /*
3392  * Free or allocate space in a file.  Currently, this function only
3393  * supports the `F_FREESP' command.  However, this command is somewhat
3394  * misnamed, as its functionality includes the ability to allocate as
3395  * well as free space.
3396  *
3397  *	IN:	vp	- vnode of file to free data in.
3398  *		cmd	- action to take (only F_FREESP supported).
3399  *		bfp	- section of file to free/alloc.
3400  *		flag	- current file open mode flags.
3401  *		offset	- current file offset.
3402  *		cr	- credentials of caller [UNUSED].
3403  *
3404  *	RETURN:	0 if success
3405  *		error code if failure
3406  *
3407  * Timestamps:
3408  *	vp - ctime|mtime updated
3409  */
3410 /* ARGSUSED */
3411 static int
3412 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
3413     offset_t offset, cred_t *cr, caller_context_t *ct)
3414 {
3415 	znode_t		*zp = VTOZ(vp);
3416 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3417 	uint64_t	off, len;
3418 	int		error;
3419 
3420 	ZFS_ENTER(zfsvfs);
3421 
3422 top:
3423 	if (cmd != F_FREESP) {
3424 		ZFS_EXIT(zfsvfs);
3425 		return (EINVAL);
3426 	}
3427 
3428 	if (error = convoff(vp, bfp, 0, offset)) {
3429 		ZFS_EXIT(zfsvfs);
3430 		return (error);
3431 	}
3432 
3433 	if (bfp->l_len < 0) {
3434 		ZFS_EXIT(zfsvfs);
3435 		return (EINVAL);
3436 	}
3437 
3438 	off = bfp->l_start;
3439 	len = bfp->l_len; /* 0 means from off to end of file */
3440 
3441 	do {
3442 		error = zfs_freesp(zp, off, len, flag, TRUE);
3443 		/* NB: we already did dmu_tx_wait() if necessary */
3444 	} while (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT);
3445 
3446 	ZFS_EXIT(zfsvfs);
3447 	return (error);
3448 }
3449 
3450 static int
3451 zfs_fid(vnode_t *vp, fid_t *fidp)
3452 {
3453 	znode_t		*zp = VTOZ(vp);
3454 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3455 	uint32_t	gen = (uint32_t)zp->z_phys->zp_gen;
3456 	uint64_t	object = zp->z_id;
3457 	zfid_short_t	*zfid;
3458 	int		size, i;
3459 
3460 	ZFS_ENTER(zfsvfs);
3461 
3462 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
3463 	if (fidp->fid_len < size) {
3464 		fidp->fid_len = size;
3465 		ZFS_EXIT(zfsvfs);
3466 		return (ENOSPC);
3467 	}
3468 
3469 	zfid = (zfid_short_t *)fidp;
3470 
3471 	zfid->zf_len = size;
3472 
3473 	for (i = 0; i < sizeof (zfid->zf_object); i++)
3474 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
3475 
3476 	/* Must have a non-zero generation number to distinguish from .zfs */
3477 	if (gen == 0)
3478 		gen = 1;
3479 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
3480 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
3481 
3482 	if (size == LONG_FID_LEN) {
3483 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
3484 		zfid_long_t	*zlfid;
3485 
3486 		zlfid = (zfid_long_t *)fidp;
3487 
3488 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
3489 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
3490 
3491 		/* XXX - this should be the generation number for the objset */
3492 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
3493 			zlfid->zf_setgen[i] = 0;
3494 	}
3495 
3496 	ZFS_EXIT(zfsvfs);
3497 	return (0);
3498 }
3499 
3500 static int
3501 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr)
3502 {
3503 	znode_t		*zp, *xzp;
3504 	zfsvfs_t	*zfsvfs;
3505 	zfs_dirlock_t	*dl;
3506 	int		error;
3507 
3508 	switch (cmd) {
3509 	case _PC_LINK_MAX:
3510 		*valp = ULONG_MAX;
3511 		return (0);
3512 
3513 	case _PC_FILESIZEBITS:
3514 		*valp = 64;
3515 		return (0);
3516 
3517 	case _PC_XATTR_EXISTS:
3518 		zp = VTOZ(vp);
3519 		zfsvfs = zp->z_zfsvfs;
3520 		ZFS_ENTER(zfsvfs);
3521 		*valp = 0;
3522 		error = zfs_dirent_lock(&dl, zp, "", &xzp,
3523 		    ZXATTR | ZEXISTS | ZSHARED);
3524 		if (error == 0) {
3525 			zfs_dirent_unlock(dl);
3526 			if (!zfs_dirempty(xzp))
3527 				*valp = 1;
3528 			VN_RELE(ZTOV(xzp));
3529 		} else if (error == ENOENT) {
3530 			/*
3531 			 * If there aren't extended attributes, it's the
3532 			 * same as having zero of them.
3533 			 */
3534 			error = 0;
3535 		}
3536 		ZFS_EXIT(zfsvfs);
3537 		return (error);
3538 
3539 	case _PC_ACL_ENABLED:
3540 		*valp = _ACL_ACE_ENABLED;
3541 		return (0);
3542 
3543 	case _PC_MIN_HOLE_SIZE:
3544 		*valp = (ulong_t)SPA_MINBLOCKSIZE;
3545 		return (0);
3546 
3547 	default:
3548 		return (fs_pathconf(vp, cmd, valp, cr));
3549 	}
3550 }
3551 
3552 /*ARGSUSED*/
3553 static int
3554 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr)
3555 {
3556 	znode_t *zp = VTOZ(vp);
3557 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3558 	int error;
3559 
3560 	ZFS_ENTER(zfsvfs);
3561 	error = zfs_getacl(zp, vsecp, cr);
3562 	ZFS_EXIT(zfsvfs);
3563 
3564 	return (error);
3565 }
3566 
3567 /*ARGSUSED*/
3568 static int
3569 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr)
3570 {
3571 	znode_t *zp = VTOZ(vp);
3572 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3573 	int error;
3574 
3575 	ZFS_ENTER(zfsvfs);
3576 	error = zfs_setacl(zp, vsecp, cr);
3577 	ZFS_EXIT(zfsvfs);
3578 	return (error);
3579 }
3580 
3581 /*
3582  * Predeclare these here so that the compiler assumes that
3583  * this is an "old style" function declaration that does
3584  * not include arguments => we won't get type mismatch errors
3585  * in the initializations that follow.
3586  */
3587 static int zfs_inval();
3588 static int zfs_isdir();
3589 
3590 static int
3591 zfs_inval()
3592 {
3593 	return (EINVAL);
3594 }
3595 
3596 static int
3597 zfs_isdir()
3598 {
3599 	return (EISDIR);
3600 }
3601 /*
3602  * Directory vnode operations template
3603  */
3604 vnodeops_t *zfs_dvnodeops;
3605 const fs_operation_def_t zfs_dvnodeops_template[] = {
3606 	VOPNAME_OPEN, zfs_open,
3607 	VOPNAME_CLOSE, zfs_close,
3608 	VOPNAME_READ, zfs_isdir,
3609 	VOPNAME_WRITE, zfs_isdir,
3610 	VOPNAME_IOCTL, zfs_ioctl,
3611 	VOPNAME_GETATTR, zfs_getattr,
3612 	VOPNAME_SETATTR, zfs_setattr,
3613 	VOPNAME_ACCESS, zfs_access,
3614 	VOPNAME_LOOKUP, zfs_lookup,
3615 	VOPNAME_CREATE, zfs_create,
3616 	VOPNAME_REMOVE, zfs_remove,
3617 	VOPNAME_LINK, zfs_link,
3618 	VOPNAME_RENAME, zfs_rename,
3619 	VOPNAME_MKDIR, zfs_mkdir,
3620 	VOPNAME_RMDIR, zfs_rmdir,
3621 	VOPNAME_READDIR, zfs_readdir,
3622 	VOPNAME_SYMLINK, zfs_symlink,
3623 	VOPNAME_FSYNC, zfs_fsync,
3624 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3625 	VOPNAME_FID, zfs_fid,
3626 	VOPNAME_SEEK, zfs_seek,
3627 	VOPNAME_PATHCONF, zfs_pathconf,
3628 	VOPNAME_GETSECATTR, zfs_getsecattr,
3629 	VOPNAME_SETSECATTR, zfs_setsecattr,
3630 	NULL, NULL
3631 };
3632 
3633 /*
3634  * Regular file vnode operations template
3635  */
3636 vnodeops_t *zfs_fvnodeops;
3637 const fs_operation_def_t zfs_fvnodeops_template[] = {
3638 	VOPNAME_OPEN, zfs_open,
3639 	VOPNAME_CLOSE, zfs_close,
3640 	VOPNAME_READ, zfs_read,
3641 	VOPNAME_WRITE, zfs_write,
3642 	VOPNAME_IOCTL, zfs_ioctl,
3643 	VOPNAME_GETATTR, zfs_getattr,
3644 	VOPNAME_SETATTR, zfs_setattr,
3645 	VOPNAME_ACCESS, zfs_access,
3646 	VOPNAME_LOOKUP, zfs_lookup,
3647 	VOPNAME_RENAME, zfs_rename,
3648 	VOPNAME_FSYNC, zfs_fsync,
3649 	VOPNAME_INACTIVE, (fs_generic_func_p)zfs_inactive,
3650 	VOPNAME_FID, zfs_fid,
3651 	VOPNAME_SEEK, zfs_seek,
3652 	VOPNAME_FRLOCK, zfs_frlock,
3653 	VOPNAME_SPACE, zfs_space,
3654 	VOPNAME_GETPAGE, zfs_getpage,
3655 	VOPNAME_PUTPAGE, zfs_putpage,
3656 	VOPNAME_MAP, (fs_generic_func_p) zfs_map,
3657 	VOPNAME_ADDMAP, (fs_generic_func_p) zfs_addmap,
3658 	VOPNAME_DELMAP, zfs_delmap,
3659 	VOPNAME_PATHCONF, zfs_pathconf,
3660 	VOPNAME_GETSECATTR, zfs_getsecattr,
3661 	VOPNAME_SETSECATTR, zfs_setsecattr,
3662 	VOPNAME_VNEVENT, fs_vnevent_support,
3663 	NULL, NULL
3664 };
3665 
3666 /*
3667  * Symbolic link vnode operations template
3668  */
3669 vnodeops_t *zfs_symvnodeops;
3670 const fs_operation_def_t zfs_symvnodeops_template[] = {
3671 	VOPNAME_GETATTR, zfs_getattr,
3672 	VOPNAME_SETATTR, zfs_setattr,
3673 	VOPNAME_ACCESS, zfs_access,
3674 	VOPNAME_RENAME, zfs_rename,
3675 	VOPNAME_READLINK, zfs_readlink,
3676 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3677 	VOPNAME_FID, zfs_fid,
3678 	VOPNAME_PATHCONF, zfs_pathconf,
3679 	VOPNAME_VNEVENT, fs_vnevent_support,
3680 	NULL, NULL
3681 };
3682 
3683 /*
3684  * Extended attribute directory vnode operations template
3685  *	This template is identical to the directory vnodes
3686  *	operation template except for restricted operations:
3687  *		VOP_MKDIR()
3688  *		VOP_SYMLINK()
3689  * Note that there are other restrictions embedded in:
3690  *	zfs_create()	- restrict type to VREG
3691  *	zfs_link()	- no links into/out of attribute space
3692  *	zfs_rename()	- no moves into/out of attribute space
3693  */
3694 vnodeops_t *zfs_xdvnodeops;
3695 const fs_operation_def_t zfs_xdvnodeops_template[] = {
3696 	VOPNAME_OPEN, zfs_open,
3697 	VOPNAME_CLOSE, zfs_close,
3698 	VOPNAME_IOCTL, zfs_ioctl,
3699 	VOPNAME_GETATTR, zfs_getattr,
3700 	VOPNAME_SETATTR, zfs_setattr,
3701 	VOPNAME_ACCESS, zfs_access,
3702 	VOPNAME_LOOKUP, zfs_lookup,
3703 	VOPNAME_CREATE, zfs_create,
3704 	VOPNAME_REMOVE, zfs_remove,
3705 	VOPNAME_LINK, zfs_link,
3706 	VOPNAME_RENAME, zfs_rename,
3707 	VOPNAME_MKDIR, zfs_inval,
3708 	VOPNAME_RMDIR, zfs_rmdir,
3709 	VOPNAME_READDIR, zfs_readdir,
3710 	VOPNAME_SYMLINK, zfs_inval,
3711 	VOPNAME_FSYNC, zfs_fsync,
3712 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3713 	VOPNAME_FID, zfs_fid,
3714 	VOPNAME_SEEK, zfs_seek,
3715 	VOPNAME_PATHCONF, zfs_pathconf,
3716 	VOPNAME_GETSECATTR, zfs_getsecattr,
3717 	VOPNAME_SETSECATTR, zfs_setsecattr,
3718 	VOPNAME_VNEVENT, fs_vnevent_support,
3719 	NULL, NULL
3720 };
3721 
3722 /*
3723  * Error vnode operations template
3724  */
3725 vnodeops_t *zfs_evnodeops;
3726 const fs_operation_def_t zfs_evnodeops_template[] = {
3727 	VOPNAME_INACTIVE, (fs_generic_func_p) zfs_inactive,
3728 	VOPNAME_PATHCONF, zfs_pathconf,
3729 	NULL, NULL
3730 };
3731