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