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