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