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