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