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