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