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