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