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