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