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