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