xref: /titanic_44/usr/src/uts/common/fs/nfs/nfs4_client.c (revision 77979b9b6355335c7ed83048268aa1e05e10855a)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  *  	Copyright (c) 1983,1984,1985,1986,1987,1988,1989  AT&T.
28  *	All Rights Reserved
29  */
30 
31 #include <sys/param.h>
32 #include <sys/types.h>
33 #include <sys/systm.h>
34 #include <sys/thread.h>
35 #include <sys/t_lock.h>
36 #include <sys/time.h>
37 #include <sys/vnode.h>
38 #include <sys/vfs.h>
39 #include <sys/errno.h>
40 #include <sys/buf.h>
41 #include <sys/stat.h>
42 #include <sys/cred.h>
43 #include <sys/kmem.h>
44 #include <sys/debug.h>
45 #include <sys/dnlc.h>
46 #include <sys/vmsystm.h>
47 #include <sys/flock.h>
48 #include <sys/share.h>
49 #include <sys/cmn_err.h>
50 #include <sys/tiuser.h>
51 #include <sys/sysmacros.h>
52 #include <sys/callb.h>
53 #include <sys/acl.h>
54 #include <sys/kstat.h>
55 #include <sys/signal.h>
56 #include <sys/disp.h>
57 #include <sys/atomic.h>
58 #include <sys/list.h>
59 #include <sys/sdt.h>
60 
61 #include <rpc/types.h>
62 #include <rpc/xdr.h>
63 #include <rpc/auth.h>
64 #include <rpc/clnt.h>
65 
66 #include <nfs/nfs.h>
67 #include <nfs/nfs_clnt.h>
68 #include <nfs/nfs_acl.h>
69 
70 #include <nfs/nfs4.h>
71 #include <nfs/rnode4.h>
72 #include <nfs/nfs4_clnt.h>
73 
74 #include <vm/hat.h>
75 #include <vm/as.h>
76 #include <vm/page.h>
77 #include <vm/pvn.h>
78 #include <vm/seg.h>
79 #include <vm/seg_map.h>
80 #include <vm/seg_vn.h>
81 
82 #include <sys/ddi.h>
83 
84 /*
85  * Arguments to page-flush thread.
86  */
87 typedef struct {
88 	vnode_t *vp;
89 	cred_t *cr;
90 } pgflush_t;
91 
92 #ifdef DEBUG
93 int nfs4_client_lease_debug;
94 int nfs4_sharedfh_debug;
95 int nfs4_fname_debug;
96 
97 /* temporary: panic if v_type is inconsistent with r_attr va_type */
98 int nfs4_vtype_debug;
99 
100 uint_t nfs4_tsd_key;
101 #endif
102 
103 static time_t	nfs4_client_resumed = 0;
104 static	callb_id_t cid = 0;
105 
106 static int	nfs4renew(nfs4_server_t *);
107 static void	nfs4_attrcache_va(vnode_t *, nfs4_ga_res_t *, int);
108 static void	nfs4_pgflush_thread(pgflush_t *);
109 
110 static boolean_t nfs4_client_cpr_callb(void *, int);
111 
112 struct mi4_globals {
113 	kmutex_t	mig_lock;  /* lock protecting mig_list */
114 	list_t		mig_list;  /* list of NFS v4 mounts in zone */
115 	boolean_t	mig_destructor_called;
116 };
117 
118 static zone_key_t mi4_list_key;
119 
120 /*
121  * Attributes caching:
122  *
123  * Attributes are cached in the rnode in struct vattr form.
124  * There is a time associated with the cached attributes (r_time_attr_inval)
125  * which tells whether the attributes are valid. The time is initialized
126  * to the difference between current time and the modify time of the vnode
127  * when new attributes are cached. This allows the attributes for
128  * files that have changed recently to be timed out sooner than for files
129  * that have not changed for a long time. There are minimum and maximum
130  * timeout values that can be set per mount point.
131  */
132 
133 /*
134  * If a cache purge is in progress, wait for it to finish.
135  *
136  * The current thread must not be in the middle of an
137  * nfs4_start_op/nfs4_end_op region.  Otherwise, there could be a deadlock
138  * between this thread, a recovery thread, and the page flush thread.
139  */
140 int
141 nfs4_waitfor_purge_complete(vnode_t *vp)
142 {
143 	rnode4_t *rp;
144 	k_sigset_t smask;
145 
146 	rp = VTOR4(vp);
147 	if ((rp->r_serial != NULL && rp->r_serial != curthread) ||
148 	    ((rp->r_flags & R4PGFLUSH) && rp->r_pgflush != curthread)) {
149 		mutex_enter(&rp->r_statelock);
150 		sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
151 		while ((rp->r_serial != NULL && rp->r_serial != curthread) ||
152 		    ((rp->r_flags & R4PGFLUSH) &&
153 		    rp->r_pgflush != curthread)) {
154 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
155 				sigunintr(&smask);
156 				mutex_exit(&rp->r_statelock);
157 				return (EINTR);
158 			}
159 		}
160 		sigunintr(&smask);
161 		mutex_exit(&rp->r_statelock);
162 	}
163 	return (0);
164 }
165 
166 /*
167  * Validate caches by checking cached attributes. If they have timed out,
168  * then get new attributes from the server.  As a side effect, cache
169  * invalidation is done if the attributes have changed.
170  *
171  * If the attributes have not timed out and if there is a cache
172  * invalidation being done by some other thread, then wait until that
173  * thread has completed the cache invalidation.
174  */
175 int
176 nfs4_validate_caches(vnode_t *vp, cred_t *cr)
177 {
178 	int error;
179 	nfs4_ga_res_t gar;
180 
181 	if (ATTRCACHE4_VALID(vp)) {
182 		error = nfs4_waitfor_purge_complete(vp);
183 		if (error)
184 			return (error);
185 		return (0);
186 	}
187 
188 	gar.n4g_va.va_mask = AT_ALL;
189 	return (nfs4_getattr_otw(vp, &gar, cr, 0));
190 }
191 
192 /*
193  * Fill in attribute from the cache.
194  * If valid, then return 0 to indicate that no error occurred,
195  * otherwise return 1 to indicate that an error occurred.
196  */
197 static int
198 nfs4_getattr_cache(vnode_t *vp, struct vattr *vap)
199 {
200 	rnode4_t *rp;
201 
202 	rp = VTOR4(vp);
203 	mutex_enter(&rp->r_statelock);
204 	mutex_enter(&rp->r_statev4_lock);
205 	if (ATTRCACHE4_VALID(vp)) {
206 		mutex_exit(&rp->r_statev4_lock);
207 		/*
208 		 * Cached attributes are valid
209 		 */
210 		*vap = rp->r_attr;
211 		mutex_exit(&rp->r_statelock);
212 		return (0);
213 	}
214 	mutex_exit(&rp->r_statev4_lock);
215 	mutex_exit(&rp->r_statelock);
216 	return (1);
217 }
218 
219 
220 /*
221  * If returned error is ESTALE flush all caches.  The nfs4_purge_caches()
222  * call is synchronous because all the pages were invalidated by the
223  * nfs4_invalidate_pages() call.
224  */
225 void
226 nfs4_purge_stale_fh(int errno, vnode_t *vp, cred_t *cr)
227 {
228 	struct rnode4 *rp = VTOR4(vp);
229 
230 	/* Ensure that the ..._end_op() call has been done */
231 	ASSERT(tsd_get(nfs4_tsd_key) == NULL);
232 
233 	if (errno != ESTALE)
234 		return;
235 
236 	mutex_enter(&rp->r_statelock);
237 	rp->r_flags |= R4STALE;
238 	if (!rp->r_error)
239 		rp->r_error = errno;
240 	mutex_exit(&rp->r_statelock);
241 	if (nfs4_has_pages(vp))
242 		nfs4_invalidate_pages(vp, (u_offset_t)0, cr);
243 	nfs4_purge_caches(vp, NFS4_PURGE_DNLC, cr, FALSE);
244 }
245 
246 /*
247  * Purge all of the various NFS `data' caches.  If "asyncpg" is TRUE, the
248  * page purge is done asynchronously.
249  */
250 void
251 nfs4_purge_caches(vnode_t *vp, int purge_dnlc, cred_t *cr, int asyncpg)
252 {
253 	rnode4_t *rp;
254 	char *contents;
255 	vnode_t *xattr;
256 	int size;
257 	int pgflush;			/* are we the page flush thread? */
258 
259 	/*
260 	 * Purge the DNLC for any entries which refer to this file.
261 	 */
262 	if (vp->v_count > 1 &&
263 	    (vp->v_type == VDIR || purge_dnlc == NFS4_PURGE_DNLC))
264 		dnlc_purge_vp(vp);
265 
266 	/*
267 	 * Clear any readdir state bits and purge the readlink response cache.
268 	 */
269 	rp = VTOR4(vp);
270 	mutex_enter(&rp->r_statelock);
271 	rp->r_flags &= ~R4LOOKUP;
272 	contents = rp->r_symlink.contents;
273 	size = rp->r_symlink.size;
274 	rp->r_symlink.contents = NULL;
275 
276 	xattr = rp->r_xattr_dir;
277 	rp->r_xattr_dir = NULL;
278 
279 	/*
280 	 * Purge pathconf cache too.
281 	 */
282 	rp->r_pathconf.pc4_xattr_valid = 0;
283 	rp->r_pathconf.pc4_cache_valid = 0;
284 
285 	pgflush = (curthread == rp->r_pgflush);
286 	mutex_exit(&rp->r_statelock);
287 
288 	if (contents != NULL) {
289 
290 		kmem_free((void *)contents, size);
291 	}
292 
293 	if (xattr != NULL)
294 		VN_RELE(xattr);
295 
296 	/*
297 	 * Flush the page cache.  If the current thread is the page flush
298 	 * thread, don't initiate a new page flush.  There's no need for
299 	 * it, and doing it correctly is hard.
300 	 */
301 	if (nfs4_has_pages(vp) && !pgflush) {
302 		if (!asyncpg) {
303 			(void) nfs4_waitfor_purge_complete(vp);
304 			nfs4_flush_pages(vp, cr);
305 		} else {
306 			pgflush_t *args;
307 
308 			/*
309 			 * We don't hold r_statelock while creating the
310 			 * thread, in case the call blocks.  So we use a
311 			 * flag to indicate that a page flush thread is
312 			 * active.
313 			 */
314 			mutex_enter(&rp->r_statelock);
315 			if (rp->r_flags & R4PGFLUSH) {
316 				mutex_exit(&rp->r_statelock);
317 			} else {
318 				rp->r_flags |= R4PGFLUSH;
319 				mutex_exit(&rp->r_statelock);
320 
321 				args = kmem_alloc(sizeof (pgflush_t),
322 				    KM_SLEEP);
323 				args->vp = vp;
324 				VN_HOLD(args->vp);
325 				args->cr = cr;
326 				crhold(args->cr);
327 				(void) zthread_create(NULL, 0,
328 				    nfs4_pgflush_thread, args, 0,
329 				    minclsyspri);
330 			}
331 		}
332 	}
333 
334 	/*
335 	 * Flush the readdir response cache.
336 	 */
337 	nfs4_purge_rddir_cache(vp);
338 }
339 
340 /*
341  * Invalidate all pages for the given file, after writing back the dirty
342  * ones.
343  */
344 
345 void
346 nfs4_flush_pages(vnode_t *vp, cred_t *cr)
347 {
348 	int error;
349 	rnode4_t *rp = VTOR4(vp);
350 
351 	error = VOP_PUTPAGE(vp, (u_offset_t)0, 0, B_INVAL, cr, NULL);
352 	if (error == ENOSPC || error == EDQUOT) {
353 		mutex_enter(&rp->r_statelock);
354 		if (!rp->r_error)
355 			rp->r_error = error;
356 		mutex_exit(&rp->r_statelock);
357 	}
358 }
359 
360 /*
361  * Page flush thread.
362  */
363 
364 static void
365 nfs4_pgflush_thread(pgflush_t *args)
366 {
367 	rnode4_t *rp = VTOR4(args->vp);
368 
369 	/* remember which thread we are, so we don't deadlock ourselves */
370 	mutex_enter(&rp->r_statelock);
371 	ASSERT(rp->r_pgflush == NULL);
372 	rp->r_pgflush = curthread;
373 	mutex_exit(&rp->r_statelock);
374 
375 	nfs4_flush_pages(args->vp, args->cr);
376 
377 	mutex_enter(&rp->r_statelock);
378 	rp->r_pgflush = NULL;
379 	rp->r_flags &= ~R4PGFLUSH;
380 	cv_broadcast(&rp->r_cv);
381 	mutex_exit(&rp->r_statelock);
382 
383 	VN_RELE(args->vp);
384 	crfree(args->cr);
385 	kmem_free(args, sizeof (pgflush_t));
386 	zthread_exit();
387 }
388 
389 /*
390  * Purge the readdir cache of all entries which are not currently
391  * being filled.
392  */
393 void
394 nfs4_purge_rddir_cache(vnode_t *vp)
395 {
396 	rnode4_t *rp;
397 
398 	rp = VTOR4(vp);
399 
400 	mutex_enter(&rp->r_statelock);
401 	rp->r_direof = NULL;
402 	rp->r_flags &= ~R4LOOKUP;
403 	rp->r_flags |= R4READDIRWATTR;
404 	rddir4_cache_purge(rp);
405 	mutex_exit(&rp->r_statelock);
406 }
407 
408 /*
409  * Set attributes cache for given vnode using virtual attributes.  There is
410  * no cache validation, but if the attributes are deemed to be stale, they
411  * are ignored.  This corresponds to nfs3_attrcache().
412  *
413  * Set the timeout value on the attribute cache and fill it
414  * with the passed in attributes.
415  */
416 void
417 nfs4_attrcache_noinval(vnode_t *vp, nfs4_ga_res_t *garp, hrtime_t t)
418 {
419 	rnode4_t *rp = VTOR4(vp);
420 
421 	mutex_enter(&rp->r_statelock);
422 	if (rp->r_time_attr_saved <= t)
423 		nfs4_attrcache_va(vp, garp, FALSE);
424 	mutex_exit(&rp->r_statelock);
425 }
426 
427 /*
428  * Use the passed in virtual attributes to check to see whether the
429  * data and metadata caches are valid, cache the new attributes, and
430  * then do the cache invalidation if required.
431  *
432  * The cache validation and caching of the new attributes is done
433  * atomically via the use of the mutex, r_statelock.  If required,
434  * the cache invalidation is done atomically w.r.t. the cache
435  * validation and caching of the attributes via the pseudo lock,
436  * r_serial.
437  *
438  * This routine is used to do cache validation and attributes caching
439  * for operations with a single set of post operation attributes.
440  */
441 
442 void
443 nfs4_attr_cache(vnode_t *vp, nfs4_ga_res_t *garp,
444     hrtime_t t, cred_t *cr, int async,
445     change_info4 *cinfo)
446 {
447 	rnode4_t *rp;
448 	int mtime_changed = 0;
449 	int ctime_changed = 0;
450 	vsecattr_t *vsp;
451 	int was_serial, set_time_cache_inval, recov;
452 	vattr_t *vap = &garp->n4g_va;
453 	mntinfo4_t *mi = VTOMI4(vp);
454 	len_t preattr_rsize;
455 	boolean_t writemodify_set = B_FALSE;
456 	boolean_t cachepurge_set = B_FALSE;
457 
458 	ASSERT(mi->mi_vfsp->vfs_dev == garp->n4g_va.va_fsid);
459 
460 	/* Is curthread the recovery thread? */
461 	mutex_enter(&mi->mi_lock);
462 	recov = (VTOMI4(vp)->mi_recovthread == curthread);
463 	mutex_exit(&mi->mi_lock);
464 
465 	rp = VTOR4(vp);
466 	mutex_enter(&rp->r_statelock);
467 	was_serial = (rp->r_serial == curthread);
468 	if (rp->r_serial && !was_serial) {
469 		klwp_t *lwp = ttolwp(curthread);
470 
471 		/*
472 		 * If we're the recovery thread, then purge current attrs
473 		 * and bail out to avoid potential deadlock between another
474 		 * thread caching attrs (r_serial thread), recov thread,
475 		 * and an async writer thread.
476 		 */
477 		if (recov) {
478 			PURGE_ATTRCACHE4_LOCKED(rp);
479 			mutex_exit(&rp->r_statelock);
480 			return;
481 		}
482 
483 		if (lwp != NULL)
484 			lwp->lwp_nostop++;
485 		while (rp->r_serial != NULL) {
486 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
487 				mutex_exit(&rp->r_statelock);
488 				if (lwp != NULL)
489 					lwp->lwp_nostop--;
490 				return;
491 			}
492 		}
493 		if (lwp != NULL)
494 			lwp->lwp_nostop--;
495 	}
496 
497 	/*
498 	 * If there is a page flush thread, the current thread needs to
499 	 * bail out, to prevent a possible deadlock between the current
500 	 * thread (which might be in a start_op/end_op region), the
501 	 * recovery thread, and the page flush thread.  Expire the
502 	 * attribute cache, so that any attributes the current thread was
503 	 * going to set are not lost.
504 	 */
505 	if ((rp->r_flags & R4PGFLUSH) && rp->r_pgflush != curthread) {
506 		PURGE_ATTRCACHE4_LOCKED(rp);
507 		mutex_exit(&rp->r_statelock);
508 		return;
509 	}
510 
511 	if (rp->r_time_attr_saved > t) {
512 		/*
513 		 * Attributes have been cached since these attributes were
514 		 * probably made. If there is an inconsistency in what is
515 		 * cached, mark them invalid. If not, don't act on them.
516 		 */
517 		if (!CACHE4_VALID(rp, vap->va_mtime, vap->va_size))
518 			PURGE_ATTRCACHE4_LOCKED(rp);
519 		mutex_exit(&rp->r_statelock);
520 		return;
521 	}
522 	set_time_cache_inval = 0;
523 	if (cinfo) {
524 		/*
525 		 * Only directory modifying callers pass non-NULL cinfo.
526 		 */
527 		ASSERT(vp->v_type == VDIR);
528 		/*
529 		 * If the cache timeout either doesn't exist or hasn't expired,
530 		 * and dir didn't changed on server before dirmod op
531 		 * and dir didn't change after dirmod op but before getattr
532 		 * then there's a chance that the client's cached data for
533 		 * this object is current (not stale).  No immediate cache
534 		 * flush is required.
535 		 *
536 		 */
537 		if ((! rp->r_time_cache_inval || t < rp->r_time_cache_inval) &&
538 		    cinfo->before == rp->r_change &&
539 		    (garp->n4g_change_valid &&
540 		    cinfo->after == garp->n4g_change)) {
541 
542 			/*
543 			 * If atomic isn't set, then the before/after info
544 			 * cannot be blindly trusted.  For this case, we tell
545 			 * nfs4_attrcache_va to cache the attrs but also
546 			 * establish an absolute maximum cache timeout.  When
547 			 * the timeout is reached, caches will be flushed.
548 			 */
549 			if (! cinfo->atomic)
550 				set_time_cache_inval = 1;
551 		} else {
552 
553 			/*
554 			 * We're not sure exactly what changed, but we know
555 			 * what to do.  flush all caches for dir.  remove the
556 			 * attr timeout.
557 			 *
558 			 * a) timeout expired.  flush all caches.
559 			 * b) r_change != cinfo.before.  flush all caches.
560 			 * c) r_change == cinfo.before, but cinfo.after !=
561 			 *    post-op getattr(change).  flush all caches.
562 			 * d) post-op getattr(change) not provided by server.
563 			 *    flush all caches.
564 			 */
565 			mtime_changed = 1;
566 			ctime_changed = 1;
567 			rp->r_time_cache_inval = 0;
568 		}
569 	} else {
570 		/*
571 		 * Write thread after writing data to file on remote server,
572 		 * will always set R4WRITEMODIFIED to indicate that file on
573 		 * remote server was modified with a WRITE operation and would
574 		 * have marked attribute cache as timed out. If R4WRITEMODIFIED
575 		 * is set, then do not check for mtime and ctime change.
576 		 */
577 		if (!(rp->r_flags & R4WRITEMODIFIED)) {
578 			if (!CACHE4_VALID(rp, vap->va_mtime, vap->va_size))
579 				mtime_changed = 1;
580 
581 			if (rp->r_attr.va_ctime.tv_sec !=
582 			    vap->va_ctime.tv_sec ||
583 			    rp->r_attr.va_ctime.tv_nsec !=
584 			    vap->va_ctime.tv_nsec)
585 				ctime_changed = 1;
586 		} else {
587 			writemodify_set = B_TRUE;
588 		}
589 	}
590 
591 	preattr_rsize = rp->r_size;
592 
593 	nfs4_attrcache_va(vp, garp, set_time_cache_inval);
594 
595 	/*
596 	 * If we have updated filesize in nfs4_attrcache_va, as soon as we
597 	 * drop statelock we will be in transition of purging all
598 	 * our caches and updating them. It is possible for another
599 	 * thread to pick this new file size and read in zeroed data.
600 	 * stall other threads till cache purge is complete.
601 	 */
602 	if ((!cinfo) && (rp->r_size != preattr_rsize)) {
603 		/*
604 		 * If R4WRITEMODIFIED was set and we have updated the file
605 		 * size, Server's returned file size need not necessarily
606 		 * be because of this Client's WRITE. We need to purge
607 		 * all caches.
608 		 */
609 		if (writemodify_set)
610 			mtime_changed = 1;
611 
612 		if (mtime_changed && !(rp->r_flags & R4INCACHEPURGE)) {
613 			rp->r_flags |= R4INCACHEPURGE;
614 			cachepurge_set = B_TRUE;
615 		}
616 	}
617 
618 	if (!mtime_changed && !ctime_changed) {
619 		mutex_exit(&rp->r_statelock);
620 		return;
621 	}
622 
623 	rp->r_serial = curthread;
624 
625 	mutex_exit(&rp->r_statelock);
626 
627 	/*
628 	 * If we're the recov thread, then force async nfs4_purge_caches
629 	 * to avoid potential deadlock.
630 	 */
631 	if (mtime_changed)
632 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, recov ? 1 : async);
633 
634 	if ((rp->r_flags & R4INCACHEPURGE) && cachepurge_set) {
635 		mutex_enter(&rp->r_statelock);
636 		rp->r_flags &= ~R4INCACHEPURGE;
637 		cv_broadcast(&rp->r_cv);
638 		mutex_exit(&rp->r_statelock);
639 		cachepurge_set = B_FALSE;
640 	}
641 
642 	if (ctime_changed) {
643 		(void) nfs4_access_purge_rp(rp);
644 		if (rp->r_secattr != NULL) {
645 			mutex_enter(&rp->r_statelock);
646 			vsp = rp->r_secattr;
647 			rp->r_secattr = NULL;
648 			mutex_exit(&rp->r_statelock);
649 			if (vsp != NULL)
650 				nfs4_acl_free_cache(vsp);
651 		}
652 	}
653 
654 	if (!was_serial) {
655 		mutex_enter(&rp->r_statelock);
656 		rp->r_serial = NULL;
657 		cv_broadcast(&rp->r_cv);
658 		mutex_exit(&rp->r_statelock);
659 	}
660 }
661 
662 /*
663  * Set attributes cache for given vnode using virtual attributes.
664  *
665  * Set the timeout value on the attribute cache and fill it
666  * with the passed in attributes.
667  *
668  * The caller must be holding r_statelock.
669  */
670 static void
671 nfs4_attrcache_va(vnode_t *vp, nfs4_ga_res_t *garp, int set_cache_timeout)
672 {
673 	rnode4_t *rp;
674 	mntinfo4_t *mi;
675 	hrtime_t delta;
676 	hrtime_t now;
677 	vattr_t *vap = &garp->n4g_va;
678 
679 	rp = VTOR4(vp);
680 
681 	ASSERT(MUTEX_HELD(&rp->r_statelock));
682 	ASSERT(vap->va_mask == AT_ALL);
683 
684 	/* Switch to master before checking v_flag */
685 	if (IS_SHADOW(vp, rp))
686 		vp = RTOV4(rp);
687 
688 	now = gethrtime();
689 
690 	mi = VTOMI4(vp);
691 
692 	/*
693 	 * Only establish a new cache timeout (if requested).  Never
694 	 * extend a timeout.  Never clear a timeout.  Clearing a timeout
695 	 * is done by nfs4_update_dircaches (ancestor in our call chain)
696 	 */
697 	if (set_cache_timeout && ! rp->r_time_cache_inval)
698 		rp->r_time_cache_inval = now + mi->mi_acdirmax;
699 
700 	/*
701 	 * Delta is the number of nanoseconds that we will
702 	 * cache the attributes of the file.  It is based on
703 	 * the number of nanoseconds since the last time that
704 	 * we detected a change.  The assumption is that files
705 	 * that changed recently are likely to change again.
706 	 * There is a minimum and a maximum for regular files
707 	 * and for directories which is enforced though.
708 	 *
709 	 * Using the time since last change was detected
710 	 * eliminates direct comparison or calculation
711 	 * using mixed client and server times.  NFS does
712 	 * not make any assumptions regarding the client
713 	 * and server clocks being synchronized.
714 	 */
715 	if (vap->va_mtime.tv_sec != rp->r_attr.va_mtime.tv_sec ||
716 	    vap->va_mtime.tv_nsec != rp->r_attr.va_mtime.tv_nsec ||
717 	    vap->va_size != rp->r_attr.va_size) {
718 		rp->r_time_attr_saved = now;
719 	}
720 
721 	if ((mi->mi_flags & MI4_NOAC) || (vp->v_flag & VNOCACHE))
722 		delta = 0;
723 	else {
724 		delta = now - rp->r_time_attr_saved;
725 		if (vp->v_type == VDIR) {
726 			if (delta < mi->mi_acdirmin)
727 				delta = mi->mi_acdirmin;
728 			else if (delta > mi->mi_acdirmax)
729 				delta = mi->mi_acdirmax;
730 		} else {
731 			if (delta < mi->mi_acregmin)
732 				delta = mi->mi_acregmin;
733 			else if (delta > mi->mi_acregmax)
734 				delta = mi->mi_acregmax;
735 		}
736 	}
737 	rp->r_time_attr_inval = now + delta;
738 
739 	rp->r_attr = *vap;
740 	if (garp->n4g_change_valid)
741 		rp->r_change = garp->n4g_change;
742 
743 	/*
744 	 * The attributes that were returned may be valid and can
745 	 * be used, but they may not be allowed to be cached.
746 	 * Reset the timers to cause immediate invalidation and
747 	 * clear r_change so no VERIFY operations will suceed
748 	 */
749 	if (garp->n4g_attrwhy == NFS4_GETATTR_NOCACHE_OK) {
750 		rp->r_time_attr_inval = now;
751 		rp->r_time_attr_saved = now;
752 		rp->r_change = 0;
753 	}
754 
755 	/*
756 	 * If mounted_on_fileid returned AND the object is a stub,
757 	 * then set object's va_nodeid to the mounted over fid
758 	 * returned by server.
759 	 *
760 	 * If mounted_on_fileid not provided/supported, then
761 	 * just set it to 0 for now.  Eventually it would be
762 	 * better to set it to a hashed version of FH.  This
763 	 * would probably be good enough to provide a unique
764 	 * fid/d_ino within a dir.
765 	 *
766 	 * We don't need to carry mounted_on_fileid in the
767 	 * rnode as long as the client never requests fileid
768 	 * without also requesting mounted_on_fileid.  For
769 	 * now, it stays.
770 	 */
771 	if (garp->n4g_mon_fid_valid) {
772 		rp->r_mntd_fid = garp->n4g_mon_fid;
773 
774 		if (RP_ISSTUB(rp))
775 			rp->r_attr.va_nodeid = rp->r_mntd_fid;
776 	}
777 
778 	/*
779 	 * Check to see if there are valid pathconf bits to
780 	 * cache in the rnode.
781 	 */
782 	if (garp->n4g_ext_res) {
783 		if (garp->n4g_ext_res->n4g_pc4.pc4_cache_valid) {
784 			rp->r_pathconf = garp->n4g_ext_res->n4g_pc4;
785 		} else {
786 			if (garp->n4g_ext_res->n4g_pc4.pc4_xattr_valid) {
787 				rp->r_pathconf.pc4_xattr_valid = TRUE;
788 				rp->r_pathconf.pc4_xattr_exists =
789 				    garp->n4g_ext_res->n4g_pc4.pc4_xattr_exists;
790 			}
791 		}
792 	}
793 	/*
794 	 * Update the size of the file if there is no cached data or if
795 	 * the cached data is clean and there is no data being written
796 	 * out.
797 	 */
798 	if (rp->r_size != vap->va_size &&
799 	    (!vn_has_cached_data(vp) ||
800 	    (!(rp->r_flags & R4DIRTY) && rp->r_count == 0))) {
801 		rp->r_size = vap->va_size;
802 	}
803 	nfs_setswaplike(vp, vap);
804 	rp->r_flags &= ~R4WRITEMODIFIED;
805 }
806 
807 /*
808  * Get attributes over-the-wire and update attributes cache
809  * if no error occurred in the over-the-wire operation.
810  * Return 0 if successful, otherwise error.
811  */
812 int
813 nfs4_getattr_otw(vnode_t *vp, nfs4_ga_res_t *garp, cred_t *cr, int get_acl)
814 {
815 	mntinfo4_t *mi = VTOMI4(vp);
816 	hrtime_t t;
817 	nfs4_recov_state_t recov_state;
818 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
819 
820 	recov_state.rs_flags = 0;
821 	recov_state.rs_num_retry_despite_err = 0;
822 
823 	/* Save the original mount point security flavor */
824 	(void) save_mnt_secinfo(mi->mi_curr_serv);
825 
826 recov_retry:
827 
828 	if ((e.error = nfs4_start_fop(mi, vp, NULL, OH_GETATTR,
829 	    &recov_state, NULL))) {
830 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
831 		return (e.error);
832 	}
833 
834 	t = gethrtime();
835 
836 	nfs4_getattr_otw_norecovery(vp, garp, &e, cr, get_acl);
837 
838 	if (nfs4_needs_recovery(&e, FALSE, vp->v_vfsp)) {
839 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
840 		    NULL, OP_GETATTR, NULL) == FALSE)  {
841 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_GETATTR,
842 			    &recov_state, 1);
843 			goto recov_retry;
844 		}
845 	}
846 
847 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_GETATTR, &recov_state, 0);
848 
849 	if (!e.error) {
850 		if (e.stat == NFS4_OK) {
851 			nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
852 		} else {
853 			e.error = geterrno4(e.stat);
854 
855 			nfs4_purge_stale_fh(e.error, vp, cr);
856 		}
857 	}
858 
859 	/*
860 	 * If getattr a node that is a stub for a crossed
861 	 * mount point, keep the original secinfo flavor for
862 	 * the current file system, not the crossed one.
863 	 */
864 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
865 
866 	return (e.error);
867 }
868 
869 /*
870  * Generate a compound to get attributes over-the-wire.
871  */
872 void
873 nfs4_getattr_otw_norecovery(vnode_t *vp, nfs4_ga_res_t *garp,
874     nfs4_error_t *ep, cred_t *cr, int get_acl)
875 {
876 	COMPOUND4args_clnt args;
877 	COMPOUND4res_clnt res;
878 	int doqueue;
879 	rnode4_t *rp = VTOR4(vp);
880 	nfs_argop4 argop[2];
881 
882 	args.ctag = TAG_GETATTR;
883 
884 	args.array_len = 2;
885 	args.array = argop;
886 
887 	/* putfh */
888 	argop[0].argop = OP_CPUTFH;
889 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
890 
891 	/* getattr */
892 	/*
893 	 * Unlike nfs version 2 and 3, where getattr returns all the
894 	 * attributes, nfs version 4 returns only the ones explicitly
895 	 * asked for. This creates problems, as some system functions
896 	 * (e.g. cache check) require certain attributes and if the
897 	 * cached node lacks some attributes such as uid/gid, it can
898 	 * affect system utilities (e.g. "ls") that rely on the information
899 	 * to be there. This can lead to anything from system crashes to
900 	 * corrupted information processed by user apps.
901 	 * So to ensure that all bases are covered, request at least
902 	 * the AT_ALL attribute mask.
903 	 */
904 	argop[1].argop = OP_GETATTR;
905 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
906 	if (get_acl)
907 		argop[1].nfs_argop4_u.opgetattr.attr_request |= FATTR4_ACL_MASK;
908 	argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
909 
910 	doqueue = 1;
911 
912 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, ep);
913 
914 	if (ep->error)
915 		return;
916 
917 	if (res.status != NFS4_OK) {
918 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
919 		return;
920 	}
921 
922 	*garp = res.array[1].nfs_resop4_u.opgetattr.ga_res;
923 
924 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
925 }
926 
927 /*
928  * Return either cached or remote attributes. If get remote attr
929  * use them to check and invalidate caches, then cache the new attributes.
930  */
931 int
932 nfs4getattr(vnode_t *vp, vattr_t *vap, cred_t *cr)
933 {
934 	int error;
935 	rnode4_t *rp;
936 	nfs4_ga_res_t gar;
937 
938 	ASSERT(nfs4_consistent_type(vp));
939 
940 	/*
941 	 * If we've got cached attributes, we're done, otherwise go
942 	 * to the server to get attributes, which will update the cache
943 	 * in the process. Either way, use the cached attributes for
944 	 * the caller's vattr_t.
945 	 *
946 	 * Note that we ignore the gar set by the OTW call: the attr caching
947 	 * code may make adjustments when storing to the rnode, and we want
948 	 * to see those changes here.
949 	 */
950 	rp = VTOR4(vp);
951 	error = 0;
952 	mutex_enter(&rp->r_statelock);
953 	if (!ATTRCACHE4_VALID(vp)) {
954 		mutex_exit(&rp->r_statelock);
955 		error = nfs4_getattr_otw(vp, &gar, cr, 0);
956 		mutex_enter(&rp->r_statelock);
957 	}
958 
959 	if (!error)
960 		*vap = rp->r_attr;
961 
962 	/* Return the client's view of file size */
963 	vap->va_size = rp->r_size;
964 
965 	mutex_exit(&rp->r_statelock);
966 
967 	ASSERT(nfs4_consistent_type(vp));
968 
969 	return (error);
970 }
971 
972 int
973 nfs4_attr_otw(vnode_t *vp, nfs4_tag_type_t tag_type,
974     nfs4_ga_res_t *garp, bitmap4 reqbitmap, cred_t *cr)
975 {
976 	COMPOUND4args_clnt args;
977 	COMPOUND4res_clnt res;
978 	int doqueue;
979 	nfs_argop4 argop[2];
980 	mntinfo4_t *mi = VTOMI4(vp);
981 	bool_t needrecov = FALSE;
982 	nfs4_recov_state_t recov_state;
983 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
984 	nfs4_ga_ext_res_t *gerp;
985 
986 	recov_state.rs_flags = 0;
987 	recov_state.rs_num_retry_despite_err = 0;
988 
989 recov_retry:
990 	args.ctag = tag_type;
991 
992 	args.array_len = 2;
993 	args.array = argop;
994 
995 	e.error = nfs4_start_fop(mi, vp, NULL, OH_GETATTR, &recov_state, NULL);
996 	if (e.error)
997 		return (e.error);
998 
999 	/* putfh */
1000 	argop[0].argop = OP_CPUTFH;
1001 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
1002 
1003 	/* getattr */
1004 	argop[1].argop = OP_GETATTR;
1005 	argop[1].nfs_argop4_u.opgetattr.attr_request = reqbitmap;
1006 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
1007 
1008 	doqueue = 1;
1009 
1010 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1011 	    "nfs4_attr_otw: %s call, rp %s", needrecov ? "recov" : "first",
1012 	    rnode4info(VTOR4(vp))));
1013 
1014 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
1015 
1016 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
1017 	if (!needrecov && e.error) {
1018 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_GETATTR, &recov_state,
1019 		    needrecov);
1020 		return (e.error);
1021 	}
1022 
1023 	if (needrecov) {
1024 		bool_t abort;
1025 
1026 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1027 		    "nfs4_attr_otw: initiating recovery\n"));
1028 
1029 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
1030 		    NULL, OP_GETATTR, NULL);
1031 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_GETATTR, &recov_state,
1032 		    needrecov);
1033 		if (!e.error) {
1034 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1035 			e.error = geterrno4(res.status);
1036 		}
1037 		if (abort == FALSE)
1038 			goto recov_retry;
1039 		return (e.error);
1040 	}
1041 
1042 	if (res.status) {
1043 		e.error = geterrno4(res.status);
1044 	} else {
1045 		gerp = garp->n4g_ext_res;
1046 		bcopy(&res.array[1].nfs_resop4_u.opgetattr.ga_res,
1047 		    garp, sizeof (nfs4_ga_res_t));
1048 		garp->n4g_ext_res = gerp;
1049 		if (garp->n4g_ext_res &&
1050 		    res.array[1].nfs_resop4_u.opgetattr.ga_res.n4g_ext_res)
1051 			bcopy(res.array[1].nfs_resop4_u.opgetattr.
1052 			    ga_res.n4g_ext_res,
1053 			    garp->n4g_ext_res, sizeof (nfs4_ga_ext_res_t));
1054 	}
1055 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1056 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_GETATTR, &recov_state,
1057 	    needrecov);
1058 	return (e.error);
1059 }
1060 
1061 /*
1062  * Asynchronous I/O parameters.  nfs_async_threads is the high-water mark
1063  * for the demand-based allocation of async threads per-mount.  The
1064  * nfs_async_timeout is the amount of time a thread will live after it
1065  * becomes idle, unless new I/O requests are received before the thread
1066  * dies.  See nfs4_async_putpage and nfs4_async_start.
1067  */
1068 
1069 static void	nfs4_async_start(struct vfs *);
1070 
1071 static void
1072 free_async_args4(struct nfs4_async_reqs *args)
1073 {
1074 	rnode4_t *rp;
1075 
1076 	if (args->a_io != NFS4_INACTIVE) {
1077 		rp = VTOR4(args->a_vp);
1078 		mutex_enter(&rp->r_statelock);
1079 		rp->r_count--;
1080 		if (args->a_io == NFS4_PUTAPAGE ||
1081 		    args->a_io == NFS4_PAGEIO)
1082 			rp->r_awcount--;
1083 		cv_broadcast(&rp->r_cv);
1084 		mutex_exit(&rp->r_statelock);
1085 		VN_RELE(args->a_vp);
1086 	}
1087 	crfree(args->a_cred);
1088 	kmem_free(args, sizeof (*args));
1089 }
1090 
1091 /*
1092  * Cross-zone thread creation and NFS access is disallowed, yet fsflush() and
1093  * pageout(), running in the global zone, have legitimate reasons to do
1094  * VOP_PUTPAGE(B_ASYNC) on other zones' NFS mounts.  We avoid the problem by
1095  * use of a a per-mount "asynchronous requests manager thread" which is
1096  * signaled by the various asynchronous work routines when there is
1097  * asynchronous work to be done.  It is responsible for creating new
1098  * worker threads if necessary, and notifying existing worker threads
1099  * that there is work to be done.
1100  *
1101  * In other words, it will "take the specifications from the customers and
1102  * give them to the engineers."
1103  *
1104  * Worker threads die off of their own accord if they are no longer
1105  * needed.
1106  *
1107  * This thread is killed when the zone is going away or the filesystem
1108  * is being unmounted.
1109  */
1110 void
1111 nfs4_async_manager(vfs_t *vfsp)
1112 {
1113 	callb_cpr_t cprinfo;
1114 	mntinfo4_t *mi;
1115 	uint_t max_threads;
1116 
1117 	mi = VFTOMI4(vfsp);
1118 
1119 	CALLB_CPR_INIT(&cprinfo, &mi->mi_async_lock, callb_generic_cpr,
1120 	    "nfs4_async_manager");
1121 
1122 	mutex_enter(&mi->mi_async_lock);
1123 	/*
1124 	 * We want to stash the max number of threads that this mount was
1125 	 * allowed so we can use it later when the variable is set to zero as
1126 	 * part of the zone/mount going away.
1127 	 *
1128 	 * We want to be able to create at least one thread to handle
1129 	 * asyncrhonous inactive calls.
1130 	 */
1131 	max_threads = MAX(mi->mi_max_threads, 1);
1132 	mutex_enter(&mi->mi_lock);
1133 	/*
1134 	 * We don't want to wait for mi_max_threads to go to zero, since that
1135 	 * happens as part of a failed unmount, but this thread should only
1136 	 * exit when the mount is really going away.
1137 	 *
1138 	 * Once MI4_ASYNC_MGR_STOP is set, no more async operations will be
1139 	 * attempted: the various _async_*() functions know to do things
1140 	 * inline if mi_max_threads == 0.  Henceforth we just drain out the
1141 	 * outstanding requests.
1142 	 *
1143 	 * Note that we still create zthreads even if we notice the zone is
1144 	 * shutting down (MI4_ASYNC_MGR_STOP is set); this may cause the zone
1145 	 * shutdown sequence to take slightly longer in some cases, but
1146 	 * doesn't violate the protocol, as all threads will exit as soon as
1147 	 * they're done processing the remaining requests.
1148 	 */
1149 	while (!(mi->mi_flags & MI4_ASYNC_MGR_STOP) ||
1150 	    mi->mi_async_req_count > 0) {
1151 		mutex_exit(&mi->mi_lock);
1152 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
1153 		cv_wait(&mi->mi_async_reqs_cv, &mi->mi_async_lock);
1154 		CALLB_CPR_SAFE_END(&cprinfo, &mi->mi_async_lock);
1155 		while (mi->mi_async_req_count > 0) {
1156 			/*
1157 			 * Paranoia: If the mount started out having
1158 			 * (mi->mi_max_threads == 0), and the value was
1159 			 * later changed (via a debugger or somesuch),
1160 			 * we could be confused since we will think we
1161 			 * can't create any threads, and the calling
1162 			 * code (which looks at the current value of
1163 			 * mi->mi_max_threads, now non-zero) thinks we
1164 			 * can.
1165 			 *
1166 			 * So, because we're paranoid, we create threads
1167 			 * up to the maximum of the original and the
1168 			 * current value. This means that future
1169 			 * (debugger-induced) alterations of
1170 			 * mi->mi_max_threads are ignored for our
1171 			 * purposes, but who told them they could change
1172 			 * random values on a live kernel anyhow?
1173 			 */
1174 			if (mi->mi_threads <
1175 			    MAX(mi->mi_max_threads, max_threads)) {
1176 				mi->mi_threads++;
1177 				mutex_exit(&mi->mi_async_lock);
1178 				MI4_HOLD(mi);
1179 				VFS_HOLD(vfsp);	/* hold for new thread */
1180 				(void) zthread_create(NULL, 0, nfs4_async_start,
1181 				    vfsp, 0, minclsyspri);
1182 				mutex_enter(&mi->mi_async_lock);
1183 			}
1184 			cv_signal(&mi->mi_async_work_cv);
1185 			ASSERT(mi->mi_async_req_count != 0);
1186 			mi->mi_async_req_count--;
1187 		}
1188 		mutex_enter(&mi->mi_lock);
1189 	}
1190 	mutex_exit(&mi->mi_lock);
1191 
1192 	NFS4_DEBUG(nfs4_client_zone_debug, (CE_NOTE,
1193 	    "nfs4_async_manager exiting for vfs %p\n", (void *)mi->mi_vfsp));
1194 	/*
1195 	 * Let everyone know we're done.
1196 	 */
1197 	mi->mi_manager_thread = NULL;
1198 	/*
1199 	 * Wake up the inactive thread.
1200 	 */
1201 	cv_broadcast(&mi->mi_inact_req_cv);
1202 	/*
1203 	 * Wake up anyone sitting in nfs4_async_manager_stop()
1204 	 */
1205 	cv_broadcast(&mi->mi_async_cv);
1206 	/*
1207 	 * There is no explicit call to mutex_exit(&mi->mi_async_lock)
1208 	 * since CALLB_CPR_EXIT is actually responsible for releasing
1209 	 * 'mi_async_lock'.
1210 	 */
1211 	CALLB_CPR_EXIT(&cprinfo);
1212 	VFS_RELE(vfsp);	/* release thread's hold */
1213 	MI4_RELE(mi);
1214 	zthread_exit();
1215 }
1216 
1217 /*
1218  * Signal (and wait for) the async manager thread to clean up and go away.
1219  */
1220 void
1221 nfs4_async_manager_stop(vfs_t *vfsp)
1222 {
1223 	mntinfo4_t *mi = VFTOMI4(vfsp);
1224 
1225 	mutex_enter(&mi->mi_async_lock);
1226 	mutex_enter(&mi->mi_lock);
1227 	mi->mi_flags |= MI4_ASYNC_MGR_STOP;
1228 	mutex_exit(&mi->mi_lock);
1229 	cv_broadcast(&mi->mi_async_reqs_cv);
1230 	/*
1231 	 * Wait for the async manager thread to die.
1232 	 */
1233 	while (mi->mi_manager_thread != NULL)
1234 		cv_wait(&mi->mi_async_cv, &mi->mi_async_lock);
1235 	mutex_exit(&mi->mi_async_lock);
1236 }
1237 
1238 int
1239 nfs4_async_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr,
1240     struct seg *seg, cred_t *cr, void (*readahead)(vnode_t *,
1241     u_offset_t, caddr_t, struct seg *, cred_t *))
1242 {
1243 	rnode4_t *rp;
1244 	mntinfo4_t *mi;
1245 	struct nfs4_async_reqs *args;
1246 
1247 	rp = VTOR4(vp);
1248 	ASSERT(rp->r_freef == NULL);
1249 
1250 	mi = VTOMI4(vp);
1251 
1252 	/*
1253 	 * If addr falls in a different segment, don't bother doing readahead.
1254 	 */
1255 	if (addr >= seg->s_base + seg->s_size)
1256 		return (-1);
1257 
1258 	/*
1259 	 * If we can't allocate a request structure, punt on the readahead.
1260 	 */
1261 	if ((args = kmem_alloc(sizeof (*args), KM_NOSLEEP)) == NULL)
1262 		return (-1);
1263 
1264 	/*
1265 	 * If a lock operation is pending, don't initiate any new
1266 	 * readaheads.  Otherwise, bump r_count to indicate the new
1267 	 * asynchronous I/O.
1268 	 */
1269 	if (!nfs_rw_tryenter(&rp->r_lkserlock, RW_READER)) {
1270 		kmem_free(args, sizeof (*args));
1271 		return (-1);
1272 	}
1273 	mutex_enter(&rp->r_statelock);
1274 	rp->r_count++;
1275 	mutex_exit(&rp->r_statelock);
1276 	nfs_rw_exit(&rp->r_lkserlock);
1277 
1278 	args->a_next = NULL;
1279 #ifdef DEBUG
1280 	args->a_queuer = curthread;
1281 #endif
1282 	VN_HOLD(vp);
1283 	args->a_vp = vp;
1284 	ASSERT(cr != NULL);
1285 	crhold(cr);
1286 	args->a_cred = cr;
1287 	args->a_io = NFS4_READ_AHEAD;
1288 	args->a_nfs4_readahead = readahead;
1289 	args->a_nfs4_blkoff = blkoff;
1290 	args->a_nfs4_seg = seg;
1291 	args->a_nfs4_addr = addr;
1292 
1293 	mutex_enter(&mi->mi_async_lock);
1294 
1295 	/*
1296 	 * If asyncio has been disabled, don't bother readahead.
1297 	 */
1298 	if (mi->mi_max_threads == 0) {
1299 		mutex_exit(&mi->mi_async_lock);
1300 		goto noasync;
1301 	}
1302 
1303 	/*
1304 	 * Link request structure into the async list and
1305 	 * wakeup async thread to do the i/o.
1306 	 */
1307 	if (mi->mi_async_reqs[NFS4_READ_AHEAD] == NULL) {
1308 		mi->mi_async_reqs[NFS4_READ_AHEAD] = args;
1309 		mi->mi_async_tail[NFS4_READ_AHEAD] = args;
1310 	} else {
1311 		mi->mi_async_tail[NFS4_READ_AHEAD]->a_next = args;
1312 		mi->mi_async_tail[NFS4_READ_AHEAD] = args;
1313 	}
1314 
1315 	if (mi->mi_io_kstats) {
1316 		mutex_enter(&mi->mi_lock);
1317 		kstat_waitq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
1318 		mutex_exit(&mi->mi_lock);
1319 	}
1320 
1321 	mi->mi_async_req_count++;
1322 	ASSERT(mi->mi_async_req_count != 0);
1323 	cv_signal(&mi->mi_async_reqs_cv);
1324 	mutex_exit(&mi->mi_async_lock);
1325 	return (0);
1326 
1327 noasync:
1328 	mutex_enter(&rp->r_statelock);
1329 	rp->r_count--;
1330 	cv_broadcast(&rp->r_cv);
1331 	mutex_exit(&rp->r_statelock);
1332 	VN_RELE(vp);
1333 	crfree(cr);
1334 	kmem_free(args, sizeof (*args));
1335 	return (-1);
1336 }
1337 
1338 /*
1339  * The async queues for each mounted file system are arranged as a
1340  * set of queues, one for each async i/o type.  Requests are taken
1341  * from the queues in a round-robin fashion.  A number of consecutive
1342  * requests are taken from each queue before moving on to the next
1343  * queue.  This functionality may allow the NFS Version 2 server to do
1344  * write clustering, even if the client is mixing writes and reads
1345  * because it will take multiple write requests from the queue
1346  * before processing any of the other async i/o types.
1347  *
1348  * XXX The nfs4_async_start thread is unsafe in the light of the present
1349  * model defined by cpr to suspend the system. Specifically over the
1350  * wire calls are cpr-unsafe. The thread should be reevaluated in
1351  * case of future updates to the cpr model.
1352  */
1353 static void
1354 nfs4_async_start(struct vfs *vfsp)
1355 {
1356 	struct nfs4_async_reqs *args;
1357 	mntinfo4_t *mi = VFTOMI4(vfsp);
1358 	clock_t time_left = 1;
1359 	callb_cpr_t cprinfo;
1360 	int i;
1361 	extern int nfs_async_timeout;
1362 
1363 	/*
1364 	 * Dynamic initialization of nfs_async_timeout to allow nfs to be
1365 	 * built in an implementation independent manner.
1366 	 */
1367 	if (nfs_async_timeout == -1)
1368 		nfs_async_timeout = NFS_ASYNC_TIMEOUT;
1369 
1370 	CALLB_CPR_INIT(&cprinfo, &mi->mi_async_lock, callb_generic_cpr, "nas");
1371 
1372 	mutex_enter(&mi->mi_async_lock);
1373 	for (;;) {
1374 		/*
1375 		 * Find the next queue containing an entry.  We start
1376 		 * at the current queue pointer and then round robin
1377 		 * through all of them until we either find a non-empty
1378 		 * queue or have looked through all of them.
1379 		 */
1380 		for (i = 0; i < NFS4_ASYNC_TYPES; i++) {
1381 			args = *mi->mi_async_curr;
1382 			if (args != NULL)
1383 				break;
1384 			mi->mi_async_curr++;
1385 			if (mi->mi_async_curr ==
1386 			    &mi->mi_async_reqs[NFS4_ASYNC_TYPES])
1387 				mi->mi_async_curr = &mi->mi_async_reqs[0];
1388 		}
1389 		/*
1390 		 * If we didn't find a entry, then block until woken up
1391 		 * again and then look through the queues again.
1392 		 */
1393 		if (args == NULL) {
1394 			/*
1395 			 * Exiting is considered to be safe for CPR as well
1396 			 */
1397 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
1398 
1399 			/*
1400 			 * Wakeup thread waiting to unmount the file
1401 			 * system only if all async threads are inactive.
1402 			 *
1403 			 * If we've timed-out and there's nothing to do,
1404 			 * then get rid of this thread.
1405 			 */
1406 			if (mi->mi_max_threads == 0 || time_left <= 0) {
1407 				if (--mi->mi_threads == 0)
1408 					cv_signal(&mi->mi_async_cv);
1409 				CALLB_CPR_EXIT(&cprinfo);
1410 				VFS_RELE(vfsp);	/* release thread's hold */
1411 				MI4_RELE(mi);
1412 				zthread_exit();
1413 				/* NOTREACHED */
1414 			}
1415 			time_left = cv_timedwait(&mi->mi_async_work_cv,
1416 			    &mi->mi_async_lock, nfs_async_timeout + lbolt);
1417 
1418 			CALLB_CPR_SAFE_END(&cprinfo, &mi->mi_async_lock);
1419 
1420 			continue;
1421 		} else {
1422 			time_left = 1;
1423 		}
1424 
1425 		/*
1426 		 * Remove the request from the async queue and then
1427 		 * update the current async request queue pointer.  If
1428 		 * the current queue is empty or we have removed enough
1429 		 * consecutive entries from it, then reset the counter
1430 		 * for this queue and then move the current pointer to
1431 		 * the next queue.
1432 		 */
1433 		*mi->mi_async_curr = args->a_next;
1434 		if (*mi->mi_async_curr == NULL ||
1435 		    --mi->mi_async_clusters[args->a_io] == 0) {
1436 			mi->mi_async_clusters[args->a_io] =
1437 			    mi->mi_async_init_clusters;
1438 			mi->mi_async_curr++;
1439 			if (mi->mi_async_curr ==
1440 			    &mi->mi_async_reqs[NFS4_ASYNC_TYPES])
1441 				mi->mi_async_curr = &mi->mi_async_reqs[0];
1442 		}
1443 
1444 		if (args->a_io != NFS4_INACTIVE && mi->mi_io_kstats) {
1445 			mutex_enter(&mi->mi_lock);
1446 			kstat_waitq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
1447 			mutex_exit(&mi->mi_lock);
1448 		}
1449 
1450 		mutex_exit(&mi->mi_async_lock);
1451 
1452 		/*
1453 		 * Obtain arguments from the async request structure.
1454 		 */
1455 		if (args->a_io == NFS4_READ_AHEAD && mi->mi_max_threads > 0) {
1456 			(*args->a_nfs4_readahead)(args->a_vp,
1457 			    args->a_nfs4_blkoff, args->a_nfs4_addr,
1458 			    args->a_nfs4_seg, args->a_cred);
1459 		} else if (args->a_io == NFS4_PUTAPAGE) {
1460 			(void) (*args->a_nfs4_putapage)(args->a_vp,
1461 			    args->a_nfs4_pp, args->a_nfs4_off,
1462 			    args->a_nfs4_len, args->a_nfs4_flags,
1463 			    args->a_cred);
1464 		} else if (args->a_io == NFS4_PAGEIO) {
1465 			(void) (*args->a_nfs4_pageio)(args->a_vp,
1466 			    args->a_nfs4_pp, args->a_nfs4_off,
1467 			    args->a_nfs4_len, args->a_nfs4_flags,
1468 			    args->a_cred);
1469 		} else if (args->a_io == NFS4_READDIR) {
1470 			(void) ((*args->a_nfs4_readdir)(args->a_vp,
1471 			    args->a_nfs4_rdc, args->a_cred));
1472 		} else if (args->a_io == NFS4_COMMIT) {
1473 			(*args->a_nfs4_commit)(args->a_vp, args->a_nfs4_plist,
1474 			    args->a_nfs4_offset, args->a_nfs4_count,
1475 			    args->a_cred);
1476 		} else if (args->a_io == NFS4_INACTIVE) {
1477 			nfs4_inactive_otw(args->a_vp, args->a_cred);
1478 		}
1479 
1480 		/*
1481 		 * Now, release the vnode and free the credentials
1482 		 * structure.
1483 		 */
1484 		free_async_args4(args);
1485 		/*
1486 		 * Reacquire the mutex because it will be needed above.
1487 		 */
1488 		mutex_enter(&mi->mi_async_lock);
1489 	}
1490 }
1491 
1492 /*
1493  * nfs4_inactive_thread - look for vnodes that need over-the-wire calls as
1494  * part of VOP_INACTIVE.
1495  */
1496 
1497 void
1498 nfs4_inactive_thread(mntinfo4_t *mi)
1499 {
1500 	struct nfs4_async_reqs *args;
1501 	callb_cpr_t cprinfo;
1502 	vfs_t *vfsp = mi->mi_vfsp;
1503 
1504 	CALLB_CPR_INIT(&cprinfo, &mi->mi_async_lock, callb_generic_cpr,
1505 	    "nfs4_inactive_thread");
1506 
1507 	for (;;) {
1508 		mutex_enter(&mi->mi_async_lock);
1509 		args = mi->mi_async_reqs[NFS4_INACTIVE];
1510 		if (args == NULL) {
1511 			mutex_enter(&mi->mi_lock);
1512 			/*
1513 			 * We don't want to exit until the async manager is done
1514 			 * with its work; hence the check for mi_manager_thread
1515 			 * being NULL.
1516 			 *
1517 			 * The async manager thread will cv_broadcast() on
1518 			 * mi_inact_req_cv when it's done, at which point we'll
1519 			 * wake up and exit.
1520 			 */
1521 			if (mi->mi_manager_thread == NULL)
1522 				goto die;
1523 			mi->mi_flags |= MI4_INACTIVE_IDLE;
1524 			mutex_exit(&mi->mi_lock);
1525 			cv_signal(&mi->mi_async_cv);
1526 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
1527 			cv_wait(&mi->mi_inact_req_cv, &mi->mi_async_lock);
1528 			CALLB_CPR_SAFE_END(&cprinfo, &mi->mi_async_lock);
1529 			mutex_exit(&mi->mi_async_lock);
1530 		} else {
1531 			mutex_enter(&mi->mi_lock);
1532 			mi->mi_flags &= ~MI4_INACTIVE_IDLE;
1533 			mutex_exit(&mi->mi_lock);
1534 			mi->mi_async_reqs[NFS4_INACTIVE] = args->a_next;
1535 			mutex_exit(&mi->mi_async_lock);
1536 			nfs4_inactive_otw(args->a_vp, args->a_cred);
1537 			crfree(args->a_cred);
1538 			kmem_free(args, sizeof (*args));
1539 		}
1540 	}
1541 die:
1542 	mutex_exit(&mi->mi_lock);
1543 	mi->mi_inactive_thread = NULL;
1544 	cv_signal(&mi->mi_async_cv);
1545 
1546 	/*
1547 	 * There is no explicit call to mutex_exit(&mi->mi_async_lock) since
1548 	 * CALLB_CPR_EXIT is actually responsible for releasing 'mi_async_lock'.
1549 	 */
1550 	CALLB_CPR_EXIT(&cprinfo);
1551 
1552 	NFS4_DEBUG(nfs4_client_zone_debug, (CE_NOTE,
1553 	    "nfs4_inactive_thread exiting for vfs %p\n", (void *)vfsp));
1554 
1555 	MI4_RELE(mi);
1556 	zthread_exit();
1557 	/* NOTREACHED */
1558 }
1559 
1560 /*
1561  * nfs_async_stop:
1562  * Wait for all outstanding putpage operations and the inactive thread to
1563  * complete; nfs4_async_stop_sig() without interruptibility.
1564  */
1565 void
1566 nfs4_async_stop(struct vfs *vfsp)
1567 {
1568 	mntinfo4_t *mi = VFTOMI4(vfsp);
1569 
1570 	/*
1571 	 * Wait for all outstanding async operations to complete and for
1572 	 * worker threads to exit.
1573 	 */
1574 	mutex_enter(&mi->mi_async_lock);
1575 	mi->mi_max_threads = 0;
1576 	cv_broadcast(&mi->mi_async_work_cv);
1577 	while (mi->mi_threads != 0)
1578 		cv_wait(&mi->mi_async_cv, &mi->mi_async_lock);
1579 
1580 	/*
1581 	 * Wait for the inactive thread to finish doing what it's doing.  It
1582 	 * won't exit until the last reference to the vfs_t goes away.
1583 	 */
1584 	if (mi->mi_inactive_thread != NULL) {
1585 		mutex_enter(&mi->mi_lock);
1586 		while (!(mi->mi_flags & MI4_INACTIVE_IDLE) ||
1587 		    (mi->mi_async_reqs[NFS4_INACTIVE] != NULL)) {
1588 			mutex_exit(&mi->mi_lock);
1589 			cv_wait(&mi->mi_async_cv, &mi->mi_async_lock);
1590 			mutex_enter(&mi->mi_lock);
1591 		}
1592 		mutex_exit(&mi->mi_lock);
1593 	}
1594 	mutex_exit(&mi->mi_async_lock);
1595 }
1596 
1597 /*
1598  * nfs_async_stop_sig:
1599  * Wait for all outstanding putpage operations and the inactive thread to
1600  * complete. If a signal is delivered we will abort and return non-zero;
1601  * otherwise return 0. Since this routine is called from nfs4_unmount, we
1602  * need to make it interruptible.
1603  */
1604 int
1605 nfs4_async_stop_sig(struct vfs *vfsp)
1606 {
1607 	mntinfo4_t *mi = VFTOMI4(vfsp);
1608 	ushort_t omax;
1609 	bool_t intr = FALSE;
1610 
1611 	/*
1612 	 * Wait for all outstanding putpage operations to complete and for
1613 	 * worker threads to exit.
1614 	 */
1615 	mutex_enter(&mi->mi_async_lock);
1616 	omax = mi->mi_max_threads;
1617 	mi->mi_max_threads = 0;
1618 	cv_broadcast(&mi->mi_async_work_cv);
1619 	while (mi->mi_threads != 0) {
1620 		if (!cv_wait_sig(&mi->mi_async_cv, &mi->mi_async_lock)) {
1621 			intr = TRUE;
1622 			goto interrupted;
1623 		}
1624 	}
1625 
1626 	/*
1627 	 * Wait for the inactive thread to finish doing what it's doing.  It
1628 	 * won't exit until the a last reference to the vfs_t goes away.
1629 	 */
1630 	if (mi->mi_inactive_thread != NULL) {
1631 		mutex_enter(&mi->mi_lock);
1632 		while (!(mi->mi_flags & MI4_INACTIVE_IDLE) ||
1633 		    (mi->mi_async_reqs[NFS4_INACTIVE] != NULL)) {
1634 			mutex_exit(&mi->mi_lock);
1635 			if (!cv_wait_sig(&mi->mi_async_cv,
1636 			    &mi->mi_async_lock)) {
1637 				intr = TRUE;
1638 				goto interrupted;
1639 			}
1640 			mutex_enter(&mi->mi_lock);
1641 		}
1642 		mutex_exit(&mi->mi_lock);
1643 	}
1644 interrupted:
1645 	if (intr)
1646 		mi->mi_max_threads = omax;
1647 	mutex_exit(&mi->mi_async_lock);
1648 
1649 	return (intr);
1650 }
1651 
1652 int
1653 nfs4_async_putapage(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
1654     int flags, cred_t *cr, int (*putapage)(vnode_t *, page_t *,
1655     u_offset_t, size_t, int, cred_t *))
1656 {
1657 	rnode4_t *rp;
1658 	mntinfo4_t *mi;
1659 	struct nfs4_async_reqs *args;
1660 
1661 	ASSERT(flags & B_ASYNC);
1662 	ASSERT(vp->v_vfsp != NULL);
1663 
1664 	rp = VTOR4(vp);
1665 	ASSERT(rp->r_count > 0);
1666 
1667 	mi = VTOMI4(vp);
1668 
1669 	/*
1670 	 * If we can't allocate a request structure, do the putpage
1671 	 * operation synchronously in this thread's context.
1672 	 */
1673 	if ((args = kmem_alloc(sizeof (*args), KM_NOSLEEP)) == NULL)
1674 		goto noasync;
1675 
1676 	args->a_next = NULL;
1677 #ifdef DEBUG
1678 	args->a_queuer = curthread;
1679 #endif
1680 	VN_HOLD(vp);
1681 	args->a_vp = vp;
1682 	ASSERT(cr != NULL);
1683 	crhold(cr);
1684 	args->a_cred = cr;
1685 	args->a_io = NFS4_PUTAPAGE;
1686 	args->a_nfs4_putapage = putapage;
1687 	args->a_nfs4_pp = pp;
1688 	args->a_nfs4_off = off;
1689 	args->a_nfs4_len = (uint_t)len;
1690 	args->a_nfs4_flags = flags;
1691 
1692 	mutex_enter(&mi->mi_async_lock);
1693 
1694 	/*
1695 	 * If asyncio has been disabled, then make a synchronous request.
1696 	 * This check is done a second time in case async io was diabled
1697 	 * while this thread was blocked waiting for memory pressure to
1698 	 * reduce or for the queue to drain.
1699 	 */
1700 	if (mi->mi_max_threads == 0) {
1701 		mutex_exit(&mi->mi_async_lock);
1702 
1703 		VN_RELE(vp);
1704 		crfree(cr);
1705 		kmem_free(args, sizeof (*args));
1706 		goto noasync;
1707 	}
1708 
1709 	/*
1710 	 * Link request structure into the async list and
1711 	 * wakeup async thread to do the i/o.
1712 	 */
1713 	if (mi->mi_async_reqs[NFS4_PUTAPAGE] == NULL) {
1714 		mi->mi_async_reqs[NFS4_PUTAPAGE] = args;
1715 		mi->mi_async_tail[NFS4_PUTAPAGE] = args;
1716 	} else {
1717 		mi->mi_async_tail[NFS4_PUTAPAGE]->a_next = args;
1718 		mi->mi_async_tail[NFS4_PUTAPAGE] = args;
1719 	}
1720 
1721 	mutex_enter(&rp->r_statelock);
1722 	rp->r_count++;
1723 	rp->r_awcount++;
1724 	mutex_exit(&rp->r_statelock);
1725 
1726 	if (mi->mi_io_kstats) {
1727 		mutex_enter(&mi->mi_lock);
1728 		kstat_waitq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
1729 		mutex_exit(&mi->mi_lock);
1730 	}
1731 
1732 	mi->mi_async_req_count++;
1733 	ASSERT(mi->mi_async_req_count != 0);
1734 	cv_signal(&mi->mi_async_reqs_cv);
1735 	mutex_exit(&mi->mi_async_lock);
1736 	return (0);
1737 
1738 noasync:
1739 
1740 	if (curproc == proc_pageout || curproc == proc_fsflush ||
1741 	    nfs_zone() == mi->mi_zone) {
1742 		/*
1743 		 * If we get here in the context of the pageout/fsflush,
1744 		 * or we have run out of memory or we're attempting to
1745 		 * unmount we refuse to do a sync write, because this may
1746 		 * hang pageout/fsflush and the machine. In this case,
1747 		 * we just re-mark the page as dirty and punt on the page.
1748 		 *
1749 		 * Make sure B_FORCE isn't set.  We can re-mark the
1750 		 * pages as dirty and unlock the pages in one swoop by
1751 		 * passing in B_ERROR to pvn_write_done().  However,
1752 		 * we should make sure B_FORCE isn't set - we don't
1753 		 * want the page tossed before it gets written out.
1754 		 */
1755 		if (flags & B_FORCE)
1756 			flags &= ~(B_INVAL | B_FORCE);
1757 		pvn_write_done(pp, flags | B_ERROR);
1758 		return (0);
1759 	}
1760 
1761 	/*
1762 	 * We'll get here only if (nfs_zone() != mi->mi_zone)
1763 	 * which means that this was a cross-zone sync putpage.
1764 	 *
1765 	 * We pass in B_ERROR to pvn_write_done() to re-mark the pages
1766 	 * as dirty and unlock them.
1767 	 *
1768 	 * We don't want to clear B_FORCE here as the caller presumably
1769 	 * knows what they're doing if they set it.
1770 	 */
1771 	pvn_write_done(pp, flags | B_ERROR);
1772 	return (EPERM);
1773 }
1774 
1775 int
1776 nfs4_async_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
1777     int flags, cred_t *cr, int (*pageio)(vnode_t *, page_t *, u_offset_t,
1778     size_t, int, cred_t *))
1779 {
1780 	rnode4_t *rp;
1781 	mntinfo4_t *mi;
1782 	struct nfs4_async_reqs *args;
1783 
1784 	ASSERT(flags & B_ASYNC);
1785 	ASSERT(vp->v_vfsp != NULL);
1786 
1787 	rp = VTOR4(vp);
1788 	ASSERT(rp->r_count > 0);
1789 
1790 	mi = VTOMI4(vp);
1791 
1792 	/*
1793 	 * If we can't allocate a request structure, do the pageio
1794 	 * request synchronously in this thread's context.
1795 	 */
1796 	if ((args = kmem_alloc(sizeof (*args), KM_NOSLEEP)) == NULL)
1797 		goto noasync;
1798 
1799 	args->a_next = NULL;
1800 #ifdef DEBUG
1801 	args->a_queuer = curthread;
1802 #endif
1803 	VN_HOLD(vp);
1804 	args->a_vp = vp;
1805 	ASSERT(cr != NULL);
1806 	crhold(cr);
1807 	args->a_cred = cr;
1808 	args->a_io = NFS4_PAGEIO;
1809 	args->a_nfs4_pageio = pageio;
1810 	args->a_nfs4_pp = pp;
1811 	args->a_nfs4_off = io_off;
1812 	args->a_nfs4_len = (uint_t)io_len;
1813 	args->a_nfs4_flags = flags;
1814 
1815 	mutex_enter(&mi->mi_async_lock);
1816 
1817 	/*
1818 	 * If asyncio has been disabled, then make a synchronous request.
1819 	 * This check is done a second time in case async io was diabled
1820 	 * while this thread was blocked waiting for memory pressure to
1821 	 * reduce or for the queue to drain.
1822 	 */
1823 	if (mi->mi_max_threads == 0) {
1824 		mutex_exit(&mi->mi_async_lock);
1825 
1826 		VN_RELE(vp);
1827 		crfree(cr);
1828 		kmem_free(args, sizeof (*args));
1829 		goto noasync;
1830 	}
1831 
1832 	/*
1833 	 * Link request structure into the async list and
1834 	 * wakeup async thread to do the i/o.
1835 	 */
1836 	if (mi->mi_async_reqs[NFS4_PAGEIO] == NULL) {
1837 		mi->mi_async_reqs[NFS4_PAGEIO] = args;
1838 		mi->mi_async_tail[NFS4_PAGEIO] = args;
1839 	} else {
1840 		mi->mi_async_tail[NFS4_PAGEIO]->a_next = args;
1841 		mi->mi_async_tail[NFS4_PAGEIO] = args;
1842 	}
1843 
1844 	mutex_enter(&rp->r_statelock);
1845 	rp->r_count++;
1846 	rp->r_awcount++;
1847 	mutex_exit(&rp->r_statelock);
1848 
1849 	if (mi->mi_io_kstats) {
1850 		mutex_enter(&mi->mi_lock);
1851 		kstat_waitq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
1852 		mutex_exit(&mi->mi_lock);
1853 	}
1854 
1855 	mi->mi_async_req_count++;
1856 	ASSERT(mi->mi_async_req_count != 0);
1857 	cv_signal(&mi->mi_async_reqs_cv);
1858 	mutex_exit(&mi->mi_async_lock);
1859 	return (0);
1860 
1861 noasync:
1862 	/*
1863 	 * If we can't do it ASYNC, for reads we do nothing (but cleanup
1864 	 * the page list), for writes we do it synchronously, except for
1865 	 * proc_pageout/proc_fsflush as described below.
1866 	 */
1867 	if (flags & B_READ) {
1868 		pvn_read_done(pp, flags | B_ERROR);
1869 		return (0);
1870 	}
1871 
1872 	if (curproc == proc_pageout || curproc == proc_fsflush) {
1873 		/*
1874 		 * If we get here in the context of the pageout/fsflush,
1875 		 * we refuse to do a sync write, because this may hang
1876 		 * pageout/fsflush (and the machine). In this case, we just
1877 		 * re-mark the page as dirty and punt on the page.
1878 		 *
1879 		 * Make sure B_FORCE isn't set.  We can re-mark the
1880 		 * pages as dirty and unlock the pages in one swoop by
1881 		 * passing in B_ERROR to pvn_write_done().  However,
1882 		 * we should make sure B_FORCE isn't set - we don't
1883 		 * want the page tossed before it gets written out.
1884 		 */
1885 		if (flags & B_FORCE)
1886 			flags &= ~(B_INVAL | B_FORCE);
1887 		pvn_write_done(pp, flags | B_ERROR);
1888 		return (0);
1889 	}
1890 
1891 	if (nfs_zone() != mi->mi_zone) {
1892 		/*
1893 		 * So this was a cross-zone sync pageio.  We pass in B_ERROR
1894 		 * to pvn_write_done() to re-mark the pages as dirty and unlock
1895 		 * them.
1896 		 *
1897 		 * We don't want to clear B_FORCE here as the caller presumably
1898 		 * knows what they're doing if they set it.
1899 		 */
1900 		pvn_write_done(pp, flags | B_ERROR);
1901 		return (EPERM);
1902 	}
1903 	return ((*pageio)(vp, pp, io_off, io_len, flags, cr));
1904 }
1905 
1906 void
1907 nfs4_async_readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr,
1908     int (*readdir)(vnode_t *, rddir4_cache *, cred_t *))
1909 {
1910 	rnode4_t *rp;
1911 	mntinfo4_t *mi;
1912 	struct nfs4_async_reqs *args;
1913 
1914 	rp = VTOR4(vp);
1915 	ASSERT(rp->r_freef == NULL);
1916 
1917 	mi = VTOMI4(vp);
1918 
1919 	/*
1920 	 * If we can't allocate a request structure, skip the readdir.
1921 	 */
1922 	if ((args = kmem_alloc(sizeof (*args), KM_NOSLEEP)) == NULL)
1923 		goto noasync;
1924 
1925 	args->a_next = NULL;
1926 #ifdef DEBUG
1927 	args->a_queuer = curthread;
1928 #endif
1929 	VN_HOLD(vp);
1930 	args->a_vp = vp;
1931 	ASSERT(cr != NULL);
1932 	crhold(cr);
1933 	args->a_cred = cr;
1934 	args->a_io = NFS4_READDIR;
1935 	args->a_nfs4_readdir = readdir;
1936 	args->a_nfs4_rdc = rdc;
1937 
1938 	mutex_enter(&mi->mi_async_lock);
1939 
1940 	/*
1941 	 * If asyncio has been disabled, then skip this request
1942 	 */
1943 	if (mi->mi_max_threads == 0) {
1944 		mutex_exit(&mi->mi_async_lock);
1945 
1946 		VN_RELE(vp);
1947 		crfree(cr);
1948 		kmem_free(args, sizeof (*args));
1949 		goto noasync;
1950 	}
1951 
1952 	/*
1953 	 * Link request structure into the async list and
1954 	 * wakeup async thread to do the i/o.
1955 	 */
1956 	if (mi->mi_async_reqs[NFS4_READDIR] == NULL) {
1957 		mi->mi_async_reqs[NFS4_READDIR] = args;
1958 		mi->mi_async_tail[NFS4_READDIR] = args;
1959 	} else {
1960 		mi->mi_async_tail[NFS4_READDIR]->a_next = args;
1961 		mi->mi_async_tail[NFS4_READDIR] = args;
1962 	}
1963 
1964 	mutex_enter(&rp->r_statelock);
1965 	rp->r_count++;
1966 	mutex_exit(&rp->r_statelock);
1967 
1968 	if (mi->mi_io_kstats) {
1969 		mutex_enter(&mi->mi_lock);
1970 		kstat_waitq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
1971 		mutex_exit(&mi->mi_lock);
1972 	}
1973 
1974 	mi->mi_async_req_count++;
1975 	ASSERT(mi->mi_async_req_count != 0);
1976 	cv_signal(&mi->mi_async_reqs_cv);
1977 	mutex_exit(&mi->mi_async_lock);
1978 	return;
1979 
1980 noasync:
1981 	mutex_enter(&rp->r_statelock);
1982 	rdc->entries = NULL;
1983 	/*
1984 	 * Indicate that no one is trying to fill this entry and
1985 	 * it still needs to be filled.
1986 	 */
1987 	rdc->flags &= ~RDDIR;
1988 	rdc->flags |= RDDIRREQ;
1989 	rddir4_cache_rele(rp, rdc);
1990 	mutex_exit(&rp->r_statelock);
1991 }
1992 
1993 void
1994 nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
1995     cred_t *cr, void (*commit)(vnode_t *, page_t *, offset3, count3,
1996     cred_t *))
1997 {
1998 	rnode4_t *rp;
1999 	mntinfo4_t *mi;
2000 	struct nfs4_async_reqs *args;
2001 	page_t *pp;
2002 
2003 	rp = VTOR4(vp);
2004 	mi = VTOMI4(vp);
2005 
2006 	/*
2007 	 * If we can't allocate a request structure, do the commit
2008 	 * operation synchronously in this thread's context.
2009 	 */
2010 	if ((args = kmem_alloc(sizeof (*args), KM_NOSLEEP)) == NULL)
2011 		goto noasync;
2012 
2013 	args->a_next = NULL;
2014 #ifdef DEBUG
2015 	args->a_queuer = curthread;
2016 #endif
2017 	VN_HOLD(vp);
2018 	args->a_vp = vp;
2019 	ASSERT(cr != NULL);
2020 	crhold(cr);
2021 	args->a_cred = cr;
2022 	args->a_io = NFS4_COMMIT;
2023 	args->a_nfs4_commit = commit;
2024 	args->a_nfs4_plist = plist;
2025 	args->a_nfs4_offset = offset;
2026 	args->a_nfs4_count = count;
2027 
2028 	mutex_enter(&mi->mi_async_lock);
2029 
2030 	/*
2031 	 * If asyncio has been disabled, then make a synchronous request.
2032 	 * This check is done a second time in case async io was diabled
2033 	 * while this thread was blocked waiting for memory pressure to
2034 	 * reduce or for the queue to drain.
2035 	 */
2036 	if (mi->mi_max_threads == 0) {
2037 		mutex_exit(&mi->mi_async_lock);
2038 
2039 		VN_RELE(vp);
2040 		crfree(cr);
2041 		kmem_free(args, sizeof (*args));
2042 		goto noasync;
2043 	}
2044 
2045 	/*
2046 	 * Link request structure into the async list and
2047 	 * wakeup async thread to do the i/o.
2048 	 */
2049 	if (mi->mi_async_reqs[NFS4_COMMIT] == NULL) {
2050 		mi->mi_async_reqs[NFS4_COMMIT] = args;
2051 		mi->mi_async_tail[NFS4_COMMIT] = args;
2052 	} else {
2053 		mi->mi_async_tail[NFS4_COMMIT]->a_next = args;
2054 		mi->mi_async_tail[NFS4_COMMIT] = args;
2055 	}
2056 
2057 	mutex_enter(&rp->r_statelock);
2058 	rp->r_count++;
2059 	mutex_exit(&rp->r_statelock);
2060 
2061 	if (mi->mi_io_kstats) {
2062 		mutex_enter(&mi->mi_lock);
2063 		kstat_waitq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
2064 		mutex_exit(&mi->mi_lock);
2065 	}
2066 
2067 	mi->mi_async_req_count++;
2068 	ASSERT(mi->mi_async_req_count != 0);
2069 	cv_signal(&mi->mi_async_reqs_cv);
2070 	mutex_exit(&mi->mi_async_lock);
2071 	return;
2072 
2073 noasync:
2074 	if (curproc == proc_pageout || curproc == proc_fsflush ||
2075 	    nfs_zone() != mi->mi_zone) {
2076 		while (plist != NULL) {
2077 			pp = plist;
2078 			page_sub(&plist, pp);
2079 			pp->p_fsdata = C_COMMIT;
2080 			page_unlock(pp);
2081 		}
2082 		return;
2083 	}
2084 	(*commit)(vp, plist, offset, count, cr);
2085 }
2086 
2087 /*
2088  * nfs4_async_inactive - hand off a VOP_INACTIVE call to a thread.  The
2089  * reference to the vnode is handed over to the thread; the caller should
2090  * no longer refer to the vnode.
2091  *
2092  * Unlike most of the async routines, this handoff is needed for
2093  * correctness reasons, not just performance.  So doing operations in the
2094  * context of the current thread is not an option.
2095  */
2096 void
2097 nfs4_async_inactive(vnode_t *vp, cred_t *cr)
2098 {
2099 	mntinfo4_t *mi;
2100 	struct nfs4_async_reqs *args;
2101 	boolean_t signal_inactive_thread = B_FALSE;
2102 
2103 	mi = VTOMI4(vp);
2104 
2105 	args = kmem_alloc(sizeof (*args), KM_SLEEP);
2106 	args->a_next = NULL;
2107 #ifdef DEBUG
2108 	args->a_queuer = curthread;
2109 #endif
2110 	args->a_vp = vp;
2111 	ASSERT(cr != NULL);
2112 	crhold(cr);
2113 	args->a_cred = cr;
2114 	args->a_io = NFS4_INACTIVE;
2115 
2116 	/*
2117 	 * Note that we don't check mi->mi_max_threads here, since we
2118 	 * *need* to get rid of this vnode regardless of whether someone
2119 	 * set nfs4_max_threads to zero in /etc/system.
2120 	 *
2121 	 * The manager thread knows about this and is willing to create
2122 	 * at least one thread to accommodate us.
2123 	 */
2124 	mutex_enter(&mi->mi_async_lock);
2125 	if (mi->mi_inactive_thread == NULL) {
2126 		rnode4_t *rp;
2127 		vnode_t *unldvp = NULL;
2128 		char *unlname;
2129 		cred_t *unlcred;
2130 
2131 		mutex_exit(&mi->mi_async_lock);
2132 		/*
2133 		 * We just need to free up the memory associated with the
2134 		 * vnode, which can be safely done from within the current
2135 		 * context.
2136 		 */
2137 		crfree(cr);	/* drop our reference */
2138 		kmem_free(args, sizeof (*args));
2139 		rp = VTOR4(vp);
2140 		mutex_enter(&rp->r_statelock);
2141 		if (rp->r_unldvp != NULL) {
2142 			unldvp = rp->r_unldvp;
2143 			rp->r_unldvp = NULL;
2144 			unlname = rp->r_unlname;
2145 			rp->r_unlname = NULL;
2146 			unlcred = rp->r_unlcred;
2147 			rp->r_unlcred = NULL;
2148 		}
2149 		mutex_exit(&rp->r_statelock);
2150 		/*
2151 		 * No need to explicitly throw away any cached pages.  The
2152 		 * eventual r4inactive() will attempt a synchronous
2153 		 * VOP_PUTPAGE() which will immediately fail since the request
2154 		 * is coming from the wrong zone, and then will proceed to call
2155 		 * nfs4_invalidate_pages() which will clean things up for us.
2156 		 *
2157 		 * Throw away the delegation here so rp4_addfree()'s attempt to
2158 		 * return any existing delegations becomes a no-op.
2159 		 */
2160 		if (rp->r_deleg_type != OPEN_DELEGATE_NONE) {
2161 			(void) nfs_rw_enter_sig(&mi->mi_recovlock, RW_READER,
2162 			    FALSE);
2163 			(void) nfs4delegreturn(rp, NFS4_DR_DISCARD);
2164 			nfs_rw_exit(&mi->mi_recovlock);
2165 		}
2166 		nfs4_clear_open_streams(rp);
2167 
2168 		rp4_addfree(rp, cr);
2169 		if (unldvp != NULL) {
2170 			kmem_free(unlname, MAXNAMELEN);
2171 			VN_RELE(unldvp);
2172 			crfree(unlcred);
2173 		}
2174 		return;
2175 	}
2176 
2177 	if (mi->mi_manager_thread == NULL) {
2178 		/*
2179 		 * We want to talk to the inactive thread.
2180 		 */
2181 		signal_inactive_thread = B_TRUE;
2182 	}
2183 
2184 	/*
2185 	 * Enqueue the vnode and wake up either the special thread (empty
2186 	 * list) or an async thread.
2187 	 */
2188 	if (mi->mi_async_reqs[NFS4_INACTIVE] == NULL) {
2189 		mi->mi_async_reqs[NFS4_INACTIVE] = args;
2190 		mi->mi_async_tail[NFS4_INACTIVE] = args;
2191 		signal_inactive_thread = B_TRUE;
2192 	} else {
2193 		mi->mi_async_tail[NFS4_INACTIVE]->a_next = args;
2194 		mi->mi_async_tail[NFS4_INACTIVE] = args;
2195 	}
2196 	if (signal_inactive_thread) {
2197 		cv_signal(&mi->mi_inact_req_cv);
2198 	} else  {
2199 		mi->mi_async_req_count++;
2200 		ASSERT(mi->mi_async_req_count != 0);
2201 		cv_signal(&mi->mi_async_reqs_cv);
2202 	}
2203 
2204 	mutex_exit(&mi->mi_async_lock);
2205 }
2206 
2207 int
2208 writerp4(rnode4_t *rp, caddr_t base, int tcount, struct uio *uio, int pgcreated)
2209 {
2210 	int pagecreate;
2211 	int n;
2212 	int saved_n;
2213 	caddr_t saved_base;
2214 	u_offset_t offset;
2215 	int error;
2216 	int sm_error;
2217 	vnode_t *vp = RTOV(rp);
2218 
2219 	ASSERT(tcount <= MAXBSIZE && tcount <= uio->uio_resid);
2220 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_WRITER));
2221 	if (!vpm_enable) {
2222 		ASSERT(((uintptr_t)base & MAXBOFFSET) + tcount <= MAXBSIZE);
2223 	}
2224 
2225 	/*
2226 	 * Move bytes in at most PAGESIZE chunks. We must avoid
2227 	 * spanning pages in uiomove() because page faults may cause
2228 	 * the cache to be invalidated out from under us. The r_size is not
2229 	 * updated until after the uiomove. If we push the last page of a
2230 	 * file before r_size is correct, we will lose the data written past
2231 	 * the current (and invalid) r_size.
2232 	 */
2233 	do {
2234 		offset = uio->uio_loffset;
2235 		pagecreate = 0;
2236 
2237 		/*
2238 		 * n is the number of bytes required to satisfy the request
2239 		 *   or the number of bytes to fill out the page.
2240 		 */
2241 		n = (int)MIN((PAGESIZE - (offset & PAGEOFFSET)), tcount);
2242 
2243 		/*
2244 		 * Check to see if we can skip reading in the page
2245 		 * and just allocate the memory.  We can do this
2246 		 * if we are going to rewrite the entire mapping
2247 		 * or if we are going to write to or beyond the current
2248 		 * end of file from the beginning of the mapping.
2249 		 *
2250 		 * The read of r_size is now protected by r_statelock.
2251 		 */
2252 		mutex_enter(&rp->r_statelock);
2253 		/*
2254 		 * When pgcreated is nonzero the caller has already done
2255 		 * a segmap_getmapflt with forcefault 0 and S_WRITE. With
2256 		 * segkpm this means we already have at least one page
2257 		 * created and mapped at base.
2258 		 */
2259 		pagecreate = pgcreated ||
2260 		    ((offset & PAGEOFFSET) == 0 &&
2261 		    (n == PAGESIZE || ((offset + n) >= rp->r_size)));
2262 
2263 		mutex_exit(&rp->r_statelock);
2264 
2265 		if (!vpm_enable && pagecreate) {
2266 			/*
2267 			 * The last argument tells segmap_pagecreate() to
2268 			 * always lock the page, as opposed to sometimes
2269 			 * returning with the page locked. This way we avoid a
2270 			 * fault on the ensuing uiomove(), but also
2271 			 * more importantly (to fix bug 1094402) we can
2272 			 * call segmap_fault() to unlock the page in all
2273 			 * cases. An alternative would be to modify
2274 			 * segmap_pagecreate() to tell us when it is
2275 			 * locking a page, but that's a fairly major
2276 			 * interface change.
2277 			 */
2278 			if (pgcreated == 0)
2279 				(void) segmap_pagecreate(segkmap, base,
2280 				    (uint_t)n, 1);
2281 			saved_base = base;
2282 			saved_n = n;
2283 		}
2284 
2285 		/*
2286 		 * The number of bytes of data in the last page can not
2287 		 * be accurately be determined while page is being
2288 		 * uiomove'd to and the size of the file being updated.
2289 		 * Thus, inform threads which need to know accurately
2290 		 * how much data is in the last page of the file.  They
2291 		 * will not do the i/o immediately, but will arrange for
2292 		 * the i/o to happen later when this modify operation
2293 		 * will have finished.
2294 		 */
2295 		ASSERT(!(rp->r_flags & R4MODINPROGRESS));
2296 		mutex_enter(&rp->r_statelock);
2297 		rp->r_flags |= R4MODINPROGRESS;
2298 		rp->r_modaddr = (offset & MAXBMASK);
2299 		mutex_exit(&rp->r_statelock);
2300 
2301 		if (vpm_enable) {
2302 			/*
2303 			 * Copy data. If new pages are created, part of
2304 			 * the page that is not written will be initizliazed
2305 			 * with zeros.
2306 			 */
2307 			error = vpm_data_copy(vp, offset, n, uio,
2308 			    !pagecreate, NULL, 0, S_WRITE);
2309 		} else {
2310 			error = uiomove(base, n, UIO_WRITE, uio);
2311 		}
2312 
2313 		/*
2314 		 * r_size is the maximum number of
2315 		 * bytes known to be in the file.
2316 		 * Make sure it is at least as high as the
2317 		 * first unwritten byte pointed to by uio_loffset.
2318 		 */
2319 		mutex_enter(&rp->r_statelock);
2320 		if (rp->r_size < uio->uio_loffset)
2321 			rp->r_size = uio->uio_loffset;
2322 		rp->r_flags &= ~R4MODINPROGRESS;
2323 		rp->r_flags |= R4DIRTY;
2324 		mutex_exit(&rp->r_statelock);
2325 
2326 		/* n = # of bytes written */
2327 		n = (int)(uio->uio_loffset - offset);
2328 
2329 		if (!vpm_enable) {
2330 			base += n;
2331 		}
2332 
2333 		tcount -= n;
2334 		/*
2335 		 * If we created pages w/o initializing them completely,
2336 		 * we need to zero the part that wasn't set up.
2337 		 * This happens on a most EOF write cases and if
2338 		 * we had some sort of error during the uiomove.
2339 		 */
2340 		if (!vpm_enable && pagecreate) {
2341 			if ((uio->uio_loffset & PAGEOFFSET) || n == 0)
2342 				(void) kzero(base, PAGESIZE - n);
2343 
2344 			if (pgcreated) {
2345 				/*
2346 				 * Caller is responsible for this page,
2347 				 * it was not created in this loop.
2348 				 */
2349 				pgcreated = 0;
2350 			} else {
2351 				/*
2352 				 * For bug 1094402: segmap_pagecreate locks
2353 				 * page. Unlock it. This also unlocks the
2354 				 * pages allocated by page_create_va() in
2355 				 * segmap_pagecreate().
2356 				 */
2357 				sm_error = segmap_fault(kas.a_hat, segkmap,
2358 				    saved_base, saved_n,
2359 				    F_SOFTUNLOCK, S_WRITE);
2360 				if (error == 0)
2361 					error = sm_error;
2362 			}
2363 		}
2364 	} while (tcount > 0 && error == 0);
2365 
2366 	return (error);
2367 }
2368 
2369 int
2370 nfs4_putpages(vnode_t *vp, u_offset_t off, size_t len, int flags, cred_t *cr)
2371 {
2372 	rnode4_t *rp;
2373 	page_t *pp;
2374 	u_offset_t eoff;
2375 	u_offset_t io_off;
2376 	size_t io_len;
2377 	int error;
2378 	int rdirty;
2379 	int err;
2380 
2381 	rp = VTOR4(vp);
2382 	ASSERT(rp->r_count > 0);
2383 
2384 	if (!nfs4_has_pages(vp))
2385 		return (0);
2386 
2387 	ASSERT(vp->v_type != VCHR);
2388 
2389 	/*
2390 	 * If R4OUTOFSPACE is set, then all writes turn into B_INVAL
2391 	 * writes.  B_FORCE is set to force the VM system to actually
2392 	 * invalidate the pages, even if the i/o failed.  The pages
2393 	 * need to get invalidated because they can't be written out
2394 	 * because there isn't any space left on either the server's
2395 	 * file system or in the user's disk quota.  The B_FREE bit
2396 	 * is cleared to avoid confusion as to whether this is a
2397 	 * request to place the page on the freelist or to destroy
2398 	 * it.
2399 	 */
2400 	if ((rp->r_flags & R4OUTOFSPACE) ||
2401 	    (vp->v_vfsp->vfs_flag & VFS_UNMOUNTED))
2402 		flags = (flags & ~B_FREE) | B_INVAL | B_FORCE;
2403 
2404 	if (len == 0) {
2405 		/*
2406 		 * If doing a full file synchronous operation, then clear
2407 		 * the R4DIRTY bit.  If a page gets dirtied while the flush
2408 		 * is happening, then R4DIRTY will get set again.  The
2409 		 * R4DIRTY bit must get cleared before the flush so that
2410 		 * we don't lose this information.
2411 		 *
2412 		 * If there are no full file async write operations
2413 		 * pending and RDIRTY bit is set, clear it.
2414 		 */
2415 		if (off == (u_offset_t)0 &&
2416 		    !(flags & B_ASYNC) &&
2417 		    (rp->r_flags & R4DIRTY)) {
2418 			mutex_enter(&rp->r_statelock);
2419 			rdirty = (rp->r_flags & R4DIRTY);
2420 			rp->r_flags &= ~R4DIRTY;
2421 			mutex_exit(&rp->r_statelock);
2422 		} else if (flags & B_ASYNC && off == (u_offset_t)0) {
2423 			mutex_enter(&rp->r_statelock);
2424 			if (rp->r_flags & R4DIRTY && rp->r_awcount == 0) {
2425 				rdirty = (rp->r_flags & R4DIRTY);
2426 				rp->r_flags &= ~R4DIRTY;
2427 			}
2428 			mutex_exit(&rp->r_statelock);
2429 		} else
2430 			rdirty = 0;
2431 
2432 		/*
2433 		 * Search the entire vp list for pages >= off, and flush
2434 		 * the dirty pages.
2435 		 */
2436 		error = pvn_vplist_dirty(vp, off, rp->r_putapage,
2437 		    flags, cr);
2438 
2439 		/*
2440 		 * If an error occurred and the file was marked as dirty
2441 		 * before and we aren't forcibly invalidating pages, then
2442 		 * reset the R4DIRTY flag.
2443 		 */
2444 		if (error && rdirty &&
2445 		    (flags & (B_INVAL | B_FORCE)) != (B_INVAL | B_FORCE)) {
2446 			mutex_enter(&rp->r_statelock);
2447 			rp->r_flags |= R4DIRTY;
2448 			mutex_exit(&rp->r_statelock);
2449 		}
2450 	} else {
2451 		/*
2452 		 * Do a range from [off...off + len) looking for pages
2453 		 * to deal with.
2454 		 */
2455 		error = 0;
2456 		io_len = 0;
2457 		eoff = off + len;
2458 		mutex_enter(&rp->r_statelock);
2459 		for (io_off = off; io_off < eoff && io_off < rp->r_size;
2460 		    io_off += io_len) {
2461 			mutex_exit(&rp->r_statelock);
2462 			/*
2463 			 * If we are not invalidating, synchronously
2464 			 * freeing or writing pages use the routine
2465 			 * page_lookup_nowait() to prevent reclaiming
2466 			 * them from the free list.
2467 			 */
2468 			if ((flags & B_INVAL) || !(flags & B_ASYNC)) {
2469 				pp = page_lookup(vp, io_off,
2470 				    (flags & (B_INVAL | B_FREE)) ?
2471 				    SE_EXCL : SE_SHARED);
2472 			} else {
2473 				pp = page_lookup_nowait(vp, io_off,
2474 				    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
2475 			}
2476 
2477 			if (pp == NULL || !pvn_getdirty(pp, flags))
2478 				io_len = PAGESIZE;
2479 			else {
2480 				err = (*rp->r_putapage)(vp, pp, &io_off,
2481 				    &io_len, flags, cr);
2482 				if (!error)
2483 					error = err;
2484 				/*
2485 				 * "io_off" and "io_len" are returned as
2486 				 * the range of pages we actually wrote.
2487 				 * This allows us to skip ahead more quickly
2488 				 * since several pages may've been dealt
2489 				 * with by this iteration of the loop.
2490 				 */
2491 			}
2492 			mutex_enter(&rp->r_statelock);
2493 		}
2494 		mutex_exit(&rp->r_statelock);
2495 	}
2496 
2497 	return (error);
2498 }
2499 
2500 void
2501 nfs4_invalidate_pages(vnode_t *vp, u_offset_t off, cred_t *cr)
2502 {
2503 	rnode4_t *rp;
2504 
2505 	rp = VTOR4(vp);
2506 	if (IS_SHADOW(vp, rp))
2507 		vp = RTOV4(rp);
2508 	mutex_enter(&rp->r_statelock);
2509 	while (rp->r_flags & R4TRUNCATE)
2510 		cv_wait(&rp->r_cv, &rp->r_statelock);
2511 	rp->r_flags |= R4TRUNCATE;
2512 	if (off == (u_offset_t)0) {
2513 		rp->r_flags &= ~R4DIRTY;
2514 		if (!(rp->r_flags & R4STALE))
2515 			rp->r_error = 0;
2516 	}
2517 	rp->r_truncaddr = off;
2518 	mutex_exit(&rp->r_statelock);
2519 	(void) pvn_vplist_dirty(vp, off, rp->r_putapage,
2520 	    B_INVAL | B_TRUNC, cr);
2521 	mutex_enter(&rp->r_statelock);
2522 	rp->r_flags &= ~R4TRUNCATE;
2523 	cv_broadcast(&rp->r_cv);
2524 	mutex_exit(&rp->r_statelock);
2525 }
2526 
2527 static int
2528 nfs4_mnt_kstat_update(kstat_t *ksp, int rw)
2529 {
2530 	mntinfo4_t *mi;
2531 	struct mntinfo_kstat *mik;
2532 	vfs_t *vfsp;
2533 
2534 	/* this is a read-only kstat. Bail out on a write */
2535 	if (rw == KSTAT_WRITE)
2536 		return (EACCES);
2537 
2538 
2539 	/*
2540 	 * We don't want to wait here as kstat_chain_lock could be held by
2541 	 * dounmount(). dounmount() takes vfs_reflock before the chain lock
2542 	 * and thus could lead to a deadlock.
2543 	 */
2544 	vfsp = (struct vfs *)ksp->ks_private;
2545 
2546 	mi = VFTOMI4(vfsp);
2547 	mik = (struct mntinfo_kstat *)ksp->ks_data;
2548 
2549 	(void) strcpy(mik->mik_proto, mi->mi_curr_serv->sv_knconf->knc_proto);
2550 
2551 	mik->mik_vers = (uint32_t)mi->mi_vers;
2552 	mik->mik_flags = mi->mi_flags;
2553 	/*
2554 	 * The sv_secdata holds the flavor the client specifies.
2555 	 * If the client uses default and a security negotiation
2556 	 * occurs, sv_currsec will point to the current flavor
2557 	 * selected from the server flavor list.
2558 	 * sv_currsec is NULL if no security negotiation takes place.
2559 	 */
2560 	mik->mik_secmod = mi->mi_curr_serv->sv_currsec ?
2561 	    mi->mi_curr_serv->sv_currsec->secmod :
2562 	    mi->mi_curr_serv->sv_secdata->secmod;
2563 	mik->mik_curread = (uint32_t)mi->mi_curread;
2564 	mik->mik_curwrite = (uint32_t)mi->mi_curwrite;
2565 	mik->mik_retrans = mi->mi_retrans;
2566 	mik->mik_timeo = mi->mi_timeo;
2567 	mik->mik_acregmin = HR2SEC(mi->mi_acregmin);
2568 	mik->mik_acregmax = HR2SEC(mi->mi_acregmax);
2569 	mik->mik_acdirmin = HR2SEC(mi->mi_acdirmin);
2570 	mik->mik_acdirmax = HR2SEC(mi->mi_acdirmax);
2571 	mik->mik_noresponse = (uint32_t)mi->mi_noresponse;
2572 	mik->mik_failover = (uint32_t)mi->mi_failover;
2573 	mik->mik_remap = (uint32_t)mi->mi_remap;
2574 
2575 	(void) strcpy(mik->mik_curserver, mi->mi_curr_serv->sv_hostname);
2576 
2577 	return (0);
2578 }
2579 
2580 void
2581 nfs4_mnt_kstat_init(struct vfs *vfsp)
2582 {
2583 	mntinfo4_t *mi = VFTOMI4(vfsp);
2584 
2585 	/*
2586 	 * PSARC 2001/697 Contract Private Interface
2587 	 * All nfs kstats are under SunMC contract
2588 	 * Please refer to the PSARC listed above and contact
2589 	 * SunMC before making any changes!
2590 	 *
2591 	 * Changes must be reviewed by Solaris File Sharing
2592 	 * Changes must be communicated to contract-2001-697@sun.com
2593 	 *
2594 	 */
2595 
2596 	mi->mi_io_kstats = kstat_create_zone("nfs", getminor(vfsp->vfs_dev),
2597 	    NULL, "nfs", KSTAT_TYPE_IO, 1, 0, mi->mi_zone->zone_id);
2598 	if (mi->mi_io_kstats) {
2599 		if (mi->mi_zone->zone_id != GLOBAL_ZONEID)
2600 			kstat_zone_add(mi->mi_io_kstats, GLOBAL_ZONEID);
2601 		mi->mi_io_kstats->ks_lock = &mi->mi_lock;
2602 		kstat_install(mi->mi_io_kstats);
2603 	}
2604 
2605 	if ((mi->mi_ro_kstats = kstat_create_zone("nfs",
2606 	    getminor(vfsp->vfs_dev), "mntinfo", "misc", KSTAT_TYPE_RAW,
2607 	    sizeof (struct mntinfo_kstat), 0, mi->mi_zone->zone_id)) != NULL) {
2608 		if (mi->mi_zone->zone_id != GLOBAL_ZONEID)
2609 			kstat_zone_add(mi->mi_ro_kstats, GLOBAL_ZONEID);
2610 		mi->mi_ro_kstats->ks_update = nfs4_mnt_kstat_update;
2611 		mi->mi_ro_kstats->ks_private = (void *)vfsp;
2612 		kstat_install(mi->mi_ro_kstats);
2613 	}
2614 
2615 	nfs4_mnt_recov_kstat_init(vfsp);
2616 }
2617 
2618 void
2619 nfs4_write_error(vnode_t *vp, int error, cred_t *cr)
2620 {
2621 	mntinfo4_t *mi;
2622 
2623 	mi = VTOMI4(vp);
2624 	/*
2625 	 * In case of forced unmount, do not print any messages
2626 	 * since it can flood the console with error messages.
2627 	 */
2628 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED)
2629 		return;
2630 
2631 	/*
2632 	 * If the mount point is dead, not recoverable, do not
2633 	 * print error messages that can flood the console.
2634 	 */
2635 	if (mi->mi_flags & MI4_RECOV_FAIL)
2636 		return;
2637 
2638 	/*
2639 	 * No use in flooding the console with ENOSPC
2640 	 * messages from the same file system.
2641 	 */
2642 	if ((error != ENOSPC && error != EDQUOT) ||
2643 	    lbolt - mi->mi_printftime > 0) {
2644 		zoneid_t zoneid = mi->mi_zone->zone_id;
2645 
2646 #ifdef DEBUG
2647 		nfs_perror(error, "NFS%ld write error on host %s: %m.\n",
2648 		    mi->mi_vers, VTOR4(vp)->r_server->sv_hostname, NULL);
2649 #else
2650 		nfs_perror(error, "NFS write error on host %s: %m.\n",
2651 		    VTOR4(vp)->r_server->sv_hostname, NULL);
2652 #endif
2653 		if (error == ENOSPC || error == EDQUOT) {
2654 			zcmn_err(zoneid, CE_CONT,
2655 			    "^File: userid=%d, groupid=%d\n",
2656 			    crgetuid(cr), crgetgid(cr));
2657 			if (crgetuid(curthread->t_cred) != crgetuid(cr) ||
2658 			    crgetgid(curthread->t_cred) != crgetgid(cr)) {
2659 				zcmn_err(zoneid, CE_CONT,
2660 				    "^User: userid=%d, groupid=%d\n",
2661 				    crgetuid(curthread->t_cred),
2662 				    crgetgid(curthread->t_cred));
2663 			}
2664 			mi->mi_printftime = lbolt +
2665 			    nfs_write_error_interval * hz;
2666 		}
2667 		sfh4_printfhandle(VTOR4(vp)->r_fh);
2668 #ifdef DEBUG
2669 		if (error == EACCES) {
2670 			zcmn_err(zoneid, CE_CONT,
2671 			    "nfs_bio: cred is%s kcred\n",
2672 			    cr == kcred ? "" : " not");
2673 		}
2674 #endif
2675 	}
2676 }
2677 
2678 /*
2679  * Return non-zero if the given file can be safely memory mapped.  Locks
2680  * are safe if whole-file (length and offset are both zero).
2681  */
2682 
2683 #define	SAFE_LOCK(flk)	((flk).l_start == 0 && (flk).l_len == 0)
2684 
2685 static int
2686 nfs4_safemap(const vnode_t *vp)
2687 {
2688 	locklist_t	*llp, *next_llp;
2689 	int		safe = 1;
2690 	rnode4_t	*rp = VTOR4(vp);
2691 
2692 	ASSERT(nfs_rw_lock_held(&rp->r_lkserlock, RW_WRITER));
2693 
2694 	NFS4_DEBUG(nfs4_client_map_debug, (CE_NOTE, "nfs4_safemap: "
2695 	    "vp = %p", (void *)vp));
2696 
2697 	/*
2698 	 * Review all the locks for the vnode, both ones that have been
2699 	 * acquired and ones that are pending.  We assume that
2700 	 * flk_active_locks_for_vp() has merged any locks that can be
2701 	 * merged (so that if a process has the entire file locked, it is
2702 	 * represented as a single lock).
2703 	 *
2704 	 * Note that we can't bail out of the loop if we find a non-safe
2705 	 * lock, because we have to free all the elements in the llp list.
2706 	 * We might be able to speed up this code slightly by not looking
2707 	 * at each lock's l_start and l_len fields once we've found a
2708 	 * non-safe lock.
2709 	 */
2710 
2711 	llp = flk_active_locks_for_vp(vp);
2712 	while (llp) {
2713 		NFS4_DEBUG(nfs4_client_map_debug, (CE_NOTE,
2714 		    "nfs4_safemap: active lock (%" PRId64 ", %" PRId64 ")",
2715 		    llp->ll_flock.l_start, llp->ll_flock.l_len));
2716 		if (!SAFE_LOCK(llp->ll_flock)) {
2717 			safe = 0;
2718 			NFS4_DEBUG(nfs4_client_map_debug, (CE_NOTE,
2719 			    "nfs4_safemap: unsafe active lock (%" PRId64
2720 			    ", %" PRId64 ")", llp->ll_flock.l_start,
2721 			    llp->ll_flock.l_len));
2722 		}
2723 		next_llp = llp->ll_next;
2724 		VN_RELE(llp->ll_vp);
2725 		kmem_free(llp, sizeof (*llp));
2726 		llp = next_llp;
2727 	}
2728 
2729 	NFS4_DEBUG(nfs4_client_map_debug, (CE_NOTE, "nfs4_safemap: %s",
2730 	    safe ? "safe" : "unsafe"));
2731 	return (safe);
2732 }
2733 
2734 /*
2735  * Return whether there is a lost LOCK or LOCKU queued up for the given
2736  * file that would make an mmap request unsafe.  cf. nfs4_safemap().
2737  */
2738 
2739 bool_t
2740 nfs4_map_lost_lock_conflict(vnode_t *vp)
2741 {
2742 	bool_t conflict = FALSE;
2743 	nfs4_lost_rqst_t *lrp;
2744 	mntinfo4_t *mi = VTOMI4(vp);
2745 
2746 	mutex_enter(&mi->mi_lock);
2747 	for (lrp = list_head(&mi->mi_lost_state); lrp != NULL;
2748 	    lrp = list_next(&mi->mi_lost_state, lrp)) {
2749 		if (lrp->lr_op != OP_LOCK && lrp->lr_op != OP_LOCKU)
2750 			continue;
2751 		ASSERT(lrp->lr_vp != NULL);
2752 		if (!VOP_CMP(lrp->lr_vp, vp, NULL))
2753 			continue;	/* different file */
2754 		if (!SAFE_LOCK(*lrp->lr_flk)) {
2755 			conflict = TRUE;
2756 			break;
2757 		}
2758 	}
2759 
2760 	mutex_exit(&mi->mi_lock);
2761 	return (conflict);
2762 }
2763 
2764 /*
2765  * nfs_lockcompletion:
2766  *
2767  * If the vnode has a lock that makes it unsafe to cache the file, mark it
2768  * as non cachable (set VNOCACHE bit).
2769  */
2770 
2771 void
2772 nfs4_lockcompletion(vnode_t *vp, int cmd)
2773 {
2774 	rnode4_t *rp = VTOR4(vp);
2775 
2776 	ASSERT(nfs_rw_lock_held(&rp->r_lkserlock, RW_WRITER));
2777 	ASSERT(!IS_SHADOW(vp, rp));
2778 
2779 	if (cmd == F_SETLK || cmd == F_SETLKW) {
2780 
2781 		if (!nfs4_safemap(vp)) {
2782 			mutex_enter(&vp->v_lock);
2783 			vp->v_flag |= VNOCACHE;
2784 			mutex_exit(&vp->v_lock);
2785 		} else {
2786 			mutex_enter(&vp->v_lock);
2787 			vp->v_flag &= ~VNOCACHE;
2788 			mutex_exit(&vp->v_lock);
2789 		}
2790 	}
2791 	/*
2792 	 * The cached attributes of the file are stale after acquiring
2793 	 * the lock on the file. They were updated when the file was
2794 	 * opened, but not updated when the lock was acquired. Therefore the
2795 	 * cached attributes are invalidated after the lock is obtained.
2796 	 */
2797 	PURGE_ATTRCACHE4(vp);
2798 }
2799 
2800 /* ARGSUSED */
2801 static void *
2802 nfs4_mi_init(zoneid_t zoneid)
2803 {
2804 	struct mi4_globals *mig;
2805 
2806 	mig = kmem_alloc(sizeof (*mig), KM_SLEEP);
2807 	mutex_init(&mig->mig_lock, NULL, MUTEX_DEFAULT, NULL);
2808 	list_create(&mig->mig_list, sizeof (mntinfo4_t),
2809 	    offsetof(mntinfo4_t, mi_zone_node));
2810 	mig->mig_destructor_called = B_FALSE;
2811 	return (mig);
2812 }
2813 
2814 /*
2815  * Callback routine to tell all NFSv4 mounts in the zone to start tearing down
2816  * state and killing off threads.
2817  */
2818 /* ARGSUSED */
2819 static void
2820 nfs4_mi_shutdown(zoneid_t zoneid, void *data)
2821 {
2822 	struct mi4_globals *mig = data;
2823 	mntinfo4_t *mi;
2824 	nfs4_server_t *np;
2825 
2826 	NFS4_DEBUG(nfs4_client_zone_debug, (CE_NOTE,
2827 	    "nfs4_mi_shutdown zone %d\n", zoneid));
2828 	ASSERT(mig != NULL);
2829 	for (;;) {
2830 		mutex_enter(&mig->mig_lock);
2831 		mi = list_head(&mig->mig_list);
2832 		if (mi == NULL) {
2833 			mutex_exit(&mig->mig_lock);
2834 			break;
2835 		}
2836 
2837 		NFS4_DEBUG(nfs4_client_zone_debug, (CE_NOTE,
2838 		    "nfs4_mi_shutdown stopping vfs %p\n", (void *)mi->mi_vfsp));
2839 		/*
2840 		 * purge the DNLC for this filesystem
2841 		 */
2842 		(void) dnlc_purge_vfsp(mi->mi_vfsp, 0);
2843 		/*
2844 		 * Tell existing async worker threads to exit.
2845 		 */
2846 		mutex_enter(&mi->mi_async_lock);
2847 		mi->mi_max_threads = 0;
2848 		cv_broadcast(&mi->mi_async_work_cv);
2849 		/*
2850 		 * Set the appropriate flags, signal and wait for both the
2851 		 * async manager and the inactive thread to exit when they're
2852 		 * done with their current work.
2853 		 */
2854 		mutex_enter(&mi->mi_lock);
2855 		mi->mi_flags |= (MI4_ASYNC_MGR_STOP|MI4_DEAD);
2856 		mutex_exit(&mi->mi_lock);
2857 		mutex_exit(&mi->mi_async_lock);
2858 		if (mi->mi_manager_thread) {
2859 			nfs4_async_manager_stop(mi->mi_vfsp);
2860 		}
2861 		if (mi->mi_inactive_thread) {
2862 			mutex_enter(&mi->mi_async_lock);
2863 			cv_signal(&mi->mi_inact_req_cv);
2864 			/*
2865 			 * Wait for the inactive thread to exit.
2866 			 */
2867 			while (mi->mi_inactive_thread != NULL) {
2868 				cv_wait(&mi->mi_async_cv, &mi->mi_async_lock);
2869 			}
2870 			mutex_exit(&mi->mi_async_lock);
2871 		}
2872 		/*
2873 		 * Wait for the recovery thread to complete, that is, it will
2874 		 * signal when it is done using the "mi" structure and about
2875 		 * to exit
2876 		 */
2877 		mutex_enter(&mi->mi_lock);
2878 		while (mi->mi_in_recovery > 0)
2879 			cv_wait(&mi->mi_cv_in_recov, &mi->mi_lock);
2880 		mutex_exit(&mi->mi_lock);
2881 		/*
2882 		 * We're done when every mi has been done or the list is empty.
2883 		 * This one is done, remove it from the list.
2884 		 */
2885 		list_remove(&mig->mig_list, mi);
2886 		mutex_exit(&mig->mig_lock);
2887 		zone_rele(mi->mi_zone);
2888 		/*
2889 		 * Release hold on vfs and mi done to prevent race with zone
2890 		 * shutdown. This releases the hold in nfs4_mi_zonelist_add.
2891 		 */
2892 		VFS_RELE(mi->mi_vfsp);
2893 		MI4_RELE(mi);
2894 	}
2895 	/*
2896 	 * Tell each renew thread in the zone to exit
2897 	 */
2898 	mutex_enter(&nfs4_server_lst_lock);
2899 	for (np = nfs4_server_lst.forw; np != &nfs4_server_lst; np = np->forw) {
2900 		mutex_enter(&np->s_lock);
2901 		if (np->zoneid == zoneid) {
2902 			/*
2903 			 * We add another hold onto the nfs4_server_t
2904 			 * because this will make sure tha the nfs4_server_t
2905 			 * stays around until nfs4_callback_fini_zone destroys
2906 			 * the zone. This way, the renew thread can
2907 			 * unconditionally release its holds on the
2908 			 * nfs4_server_t.
2909 			 */
2910 			np->s_refcnt++;
2911 			nfs4_mark_srv_dead(np);
2912 		}
2913 		mutex_exit(&np->s_lock);
2914 	}
2915 	mutex_exit(&nfs4_server_lst_lock);
2916 }
2917 
2918 static void
2919 nfs4_mi_free_globals(struct mi4_globals *mig)
2920 {
2921 	list_destroy(&mig->mig_list);	/* makes sure the list is empty */
2922 	mutex_destroy(&mig->mig_lock);
2923 	kmem_free(mig, sizeof (*mig));
2924 }
2925 
2926 /* ARGSUSED */
2927 static void
2928 nfs4_mi_destroy(zoneid_t zoneid, void *data)
2929 {
2930 	struct mi4_globals *mig = data;
2931 
2932 	NFS4_DEBUG(nfs4_client_zone_debug, (CE_NOTE,
2933 	    "nfs4_mi_destroy zone %d\n", zoneid));
2934 	ASSERT(mig != NULL);
2935 	mutex_enter(&mig->mig_lock);
2936 	if (list_head(&mig->mig_list) != NULL) {
2937 		/* Still waiting for VFS_FREEVFS() */
2938 		mig->mig_destructor_called = B_TRUE;
2939 		mutex_exit(&mig->mig_lock);
2940 		return;
2941 	}
2942 	nfs4_mi_free_globals(mig);
2943 }
2944 
2945 /*
2946  * Add an NFS mount to the per-zone list of NFS mounts.
2947  */
2948 void
2949 nfs4_mi_zonelist_add(mntinfo4_t *mi)
2950 {
2951 	struct mi4_globals *mig;
2952 
2953 	mig = zone_getspecific(mi4_list_key, mi->mi_zone);
2954 	mutex_enter(&mig->mig_lock);
2955 	list_insert_head(&mig->mig_list, mi);
2956 	/*
2957 	 * hold added to eliminate race with zone shutdown -this will be
2958 	 * released in mi_shutdown
2959 	 */
2960 	MI4_HOLD(mi);
2961 	VFS_HOLD(mi->mi_vfsp);
2962 	mutex_exit(&mig->mig_lock);
2963 }
2964 
2965 /*
2966  * Remove an NFS mount from the per-zone list of NFS mounts.
2967  */
2968 int
2969 nfs4_mi_zonelist_remove(mntinfo4_t *mi)
2970 {
2971 	struct mi4_globals *mig;
2972 	int ret = 0;
2973 
2974 	mig = zone_getspecific(mi4_list_key, mi->mi_zone);
2975 	mutex_enter(&mig->mig_lock);
2976 	mutex_enter(&mi->mi_lock);
2977 	/* if this mi is marked dead, then the zone already released it */
2978 	if (!(mi->mi_flags & MI4_DEAD)) {
2979 		list_remove(&mig->mig_list, mi);
2980 		mutex_exit(&mi->mi_lock);
2981 
2982 		/* release the holds put on in zonelist_add(). */
2983 		VFS_RELE(mi->mi_vfsp);
2984 		MI4_RELE(mi);
2985 		ret = 1;
2986 	} else {
2987 		mutex_exit(&mi->mi_lock);
2988 	}
2989 
2990 	/*
2991 	 * We can be called asynchronously by VFS_FREEVFS() after the zone
2992 	 * shutdown/destroy callbacks have executed; if so, clean up the zone's
2993 	 * mi globals.
2994 	 */
2995 	if (list_head(&mig->mig_list) == NULL &&
2996 	    mig->mig_destructor_called == B_TRUE) {
2997 		nfs4_mi_free_globals(mig);
2998 		return (ret);
2999 	}
3000 	mutex_exit(&mig->mig_lock);
3001 	return (ret);
3002 }
3003 
3004 void
3005 nfs_free_mi4(mntinfo4_t *mi)
3006 {
3007 	nfs4_open_owner_t	*foop;
3008 	nfs4_oo_hash_bucket_t   *bucketp;
3009 	nfs4_debug_msg_t	*msgp;
3010 	int i;
3011 	servinfo4_t 		*svp;
3012 
3013 	mutex_enter(&mi->mi_lock);
3014 	ASSERT(mi->mi_recovthread == NULL);
3015 	ASSERT(mi->mi_flags & MI4_ASYNC_MGR_STOP);
3016 	mutex_exit(&mi->mi_lock);
3017 	mutex_enter(&mi->mi_async_lock);
3018 	ASSERT(mi->mi_threads == 0);
3019 	ASSERT(mi->mi_manager_thread == NULL);
3020 	mutex_exit(&mi->mi_async_lock);
3021 	svp = mi->mi_servers;
3022 	sv4_free(svp);
3023 	if (mi->mi_io_kstats) {
3024 		kstat_delete(mi->mi_io_kstats);
3025 		mi->mi_io_kstats = NULL;
3026 	}
3027 	if (mi->mi_ro_kstats) {
3028 		kstat_delete(mi->mi_ro_kstats);
3029 		mi->mi_ro_kstats = NULL;
3030 	}
3031 	if (mi->mi_recov_ksp) {
3032 		kstat_delete(mi->mi_recov_ksp);
3033 		mi->mi_recov_ksp = NULL;
3034 	}
3035 	mutex_enter(&mi->mi_msg_list_lock);
3036 	while (msgp = list_head(&mi->mi_msg_list)) {
3037 		list_remove(&mi->mi_msg_list, msgp);
3038 		nfs4_free_msg(msgp);
3039 	}
3040 	mutex_exit(&mi->mi_msg_list_lock);
3041 	list_destroy(&mi->mi_msg_list);
3042 	if (mi->mi_fname != NULL)
3043 		fn_rele(&mi->mi_fname);
3044 	if (mi->mi_rootfh != NULL)
3045 		sfh4_rele(&mi->mi_rootfh);
3046 	if (mi->mi_srvparentfh != NULL)
3047 		sfh4_rele(&mi->mi_srvparentfh);
3048 	mutex_destroy(&mi->mi_lock);
3049 	mutex_destroy(&mi->mi_async_lock);
3050 	mutex_destroy(&mi->mi_msg_list_lock);
3051 	nfs_rw_destroy(&mi->mi_recovlock);
3052 	nfs_rw_destroy(&mi->mi_rename_lock);
3053 	nfs_rw_destroy(&mi->mi_fh_lock);
3054 	cv_destroy(&mi->mi_failover_cv);
3055 	cv_destroy(&mi->mi_async_reqs_cv);
3056 	cv_destroy(&mi->mi_async_work_cv);
3057 	cv_destroy(&mi->mi_async_cv);
3058 	cv_destroy(&mi->mi_inact_req_cv);
3059 	/*
3060 	 * Destroy the oo hash lists and mutexes for the cred hash table.
3061 	 */
3062 	for (i = 0; i < NFS4_NUM_OO_BUCKETS; i++) {
3063 		bucketp = &(mi->mi_oo_list[i]);
3064 		/* Destroy any remaining open owners on the list */
3065 		foop = list_head(&bucketp->b_oo_hash_list);
3066 		while (foop != NULL) {
3067 			list_remove(&bucketp->b_oo_hash_list, foop);
3068 			nfs4_destroy_open_owner(foop);
3069 			foop = list_head(&bucketp->b_oo_hash_list);
3070 		}
3071 		list_destroy(&bucketp->b_oo_hash_list);
3072 		mutex_destroy(&bucketp->b_lock);
3073 	}
3074 	/*
3075 	 * Empty and destroy the freed open owner list.
3076 	 */
3077 	foop = list_head(&mi->mi_foo_list);
3078 	while (foop != NULL) {
3079 		list_remove(&mi->mi_foo_list, foop);
3080 		nfs4_destroy_open_owner(foop);
3081 		foop = list_head(&mi->mi_foo_list);
3082 	}
3083 	list_destroy(&mi->mi_foo_list);
3084 	list_destroy(&mi->mi_bseqid_list);
3085 	list_destroy(&mi->mi_lost_state);
3086 	avl_destroy(&mi->mi_filehandles);
3087 	kmem_free(mi, sizeof (*mi));
3088 }
3089 void
3090 mi_hold(mntinfo4_t *mi)
3091 {
3092 	atomic_add_32(&mi->mi_count, 1);
3093 	ASSERT(mi->mi_count != 0);
3094 }
3095 
3096 void
3097 mi_rele(mntinfo4_t *mi)
3098 {
3099 	ASSERT(mi->mi_count != 0);
3100 	if (atomic_add_32_nv(&mi->mi_count, -1) == 0) {
3101 		nfs_free_mi4(mi);
3102 	}
3103 }
3104 
3105 vnode_t    nfs4_xattr_notsupp_vnode;
3106 
3107 void
3108 nfs4_clnt_init(void)
3109 {
3110 	nfs4_vnops_init();
3111 	(void) nfs4_rnode_init();
3112 	(void) nfs4_shadow_init();
3113 	(void) nfs4_acache_init();
3114 	(void) nfs4_subr_init();
3115 	nfs4_acl_init();
3116 	nfs_idmap_init();
3117 	nfs4_callback_init();
3118 	nfs4_secinfo_init();
3119 #ifdef	DEBUG
3120 	tsd_create(&nfs4_tsd_key, NULL);
3121 #endif
3122 
3123 	/*
3124 	 * Add a CPR callback so that we can update client
3125 	 * lease after a suspend and resume.
3126 	 */
3127 	cid = callb_add(nfs4_client_cpr_callb, 0, CB_CL_CPR_RPC, "nfs4");
3128 
3129 	zone_key_create(&mi4_list_key, nfs4_mi_init, nfs4_mi_shutdown,
3130 	    nfs4_mi_destroy);
3131 
3132 	/*
3133 	 * Initialise the reference count of the notsupp xattr cache vnode to 1
3134 	 * so that it never goes away (VOP_INACTIVE isn't called on it).
3135 	 */
3136 	nfs4_xattr_notsupp_vnode.v_count = 1;
3137 }
3138 
3139 void
3140 nfs4_clnt_fini(void)
3141 {
3142 	(void) zone_key_delete(mi4_list_key);
3143 	nfs4_vnops_fini();
3144 	(void) nfs4_rnode_fini();
3145 	(void) nfs4_shadow_fini();
3146 	(void) nfs4_acache_fini();
3147 	(void) nfs4_subr_fini();
3148 	nfs_idmap_fini();
3149 	nfs4_callback_fini();
3150 	nfs4_secinfo_fini();
3151 #ifdef	DEBUG
3152 	tsd_destroy(&nfs4_tsd_key);
3153 #endif
3154 	if (cid)
3155 		(void) callb_delete(cid);
3156 }
3157 
3158 /*ARGSUSED*/
3159 static boolean_t
3160 nfs4_client_cpr_callb(void *arg, int code)
3161 {
3162 	/*
3163 	 * We get called for Suspend and Resume events.
3164 	 * For the suspend case we simply don't care!
3165 	 */
3166 	if (code == CB_CODE_CPR_CHKPT) {
3167 		return (B_TRUE);
3168 	}
3169 
3170 	/*
3171 	 * When we get to here we are in the process of
3172 	 * resuming the system from a previous suspend.
3173 	 */
3174 	nfs4_client_resumed = gethrestime_sec();
3175 	return (B_TRUE);
3176 }
3177 
3178 void
3179 nfs4_renew_lease_thread(nfs4_server_t *sp)
3180 {
3181 	int	error = 0;
3182 	time_t	tmp_last_renewal_time, tmp_time, tmp_now_time, kip_secs;
3183 	clock_t	tick_delay = 0;
3184 	clock_t time_left = 0;
3185 	callb_cpr_t cpr_info;
3186 	kmutex_t cpr_lock;
3187 
3188 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3189 	    "nfs4_renew_lease_thread: acting on sp 0x%p", (void*)sp));
3190 	mutex_init(&cpr_lock, NULL, MUTEX_DEFAULT, NULL);
3191 	CALLB_CPR_INIT(&cpr_info, &cpr_lock, callb_generic_cpr, "nfsv4Lease");
3192 
3193 	mutex_enter(&sp->s_lock);
3194 	/* sp->s_lease_time is set via a GETATTR */
3195 	sp->last_renewal_time = gethrestime_sec();
3196 	sp->lease_valid = NFS4_LEASE_UNINITIALIZED;
3197 	ASSERT(sp->s_refcnt >= 1);
3198 
3199 	for (;;) {
3200 		if (!sp->state_ref_count ||
3201 		    sp->lease_valid != NFS4_LEASE_VALID) {
3202 
3203 			kip_secs = MAX((sp->s_lease_time >> 1) -
3204 			    (3 * sp->propagation_delay.tv_sec), 1);
3205 
3206 			tick_delay = SEC_TO_TICK(kip_secs);
3207 
3208 			NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3209 			    "nfs4_renew_lease_thread: no renew : thread "
3210 			    "wait %ld secs", kip_secs));
3211 
3212 			NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3213 			    "nfs4_renew_lease_thread: no renew : "
3214 			    "state_ref_count %d, lease_valid %d",
3215 			    sp->state_ref_count, sp->lease_valid));
3216 
3217 			mutex_enter(&cpr_lock);
3218 			CALLB_CPR_SAFE_BEGIN(&cpr_info);
3219 			mutex_exit(&cpr_lock);
3220 			time_left = cv_timedwait(&sp->cv_thread_exit,
3221 			    &sp->s_lock, tick_delay + lbolt);
3222 			mutex_enter(&cpr_lock);
3223 			CALLB_CPR_SAFE_END(&cpr_info, &cpr_lock);
3224 			mutex_exit(&cpr_lock);
3225 
3226 			NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3227 			    "nfs4_renew_lease_thread: no renew: "
3228 			    "time left %ld", time_left));
3229 
3230 			if (sp->s_thread_exit == NFS4_THREAD_EXIT)
3231 				goto die;
3232 			continue;
3233 		}
3234 
3235 		tmp_last_renewal_time = sp->last_renewal_time;
3236 
3237 		tmp_time = gethrestime_sec() - sp->last_renewal_time +
3238 		    (3 * sp->propagation_delay.tv_sec);
3239 
3240 		NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3241 		    "nfs4_renew_lease_thread: tmp_time %ld, "
3242 		    "sp->last_renewal_time %ld", tmp_time,
3243 		    sp->last_renewal_time));
3244 
3245 		kip_secs = MAX((sp->s_lease_time >> 1) - tmp_time, 1);
3246 
3247 		tick_delay = SEC_TO_TICK(kip_secs);
3248 
3249 		NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3250 		    "nfs4_renew_lease_thread: valid lease: sleep for %ld "
3251 		    "secs", kip_secs));
3252 
3253 		mutex_enter(&cpr_lock);
3254 		CALLB_CPR_SAFE_BEGIN(&cpr_info);
3255 		mutex_exit(&cpr_lock);
3256 		time_left = cv_timedwait(&sp->cv_thread_exit, &sp->s_lock,
3257 		    tick_delay + lbolt);
3258 		mutex_enter(&cpr_lock);
3259 		CALLB_CPR_SAFE_END(&cpr_info, &cpr_lock);
3260 		mutex_exit(&cpr_lock);
3261 
3262 		NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3263 		    "nfs4_renew_lease_thread: valid lease: time left %ld :"
3264 		    "sp last_renewal_time %ld, nfs4_client_resumed %ld, "
3265 		    "tmp_last_renewal_time %ld", time_left,
3266 		    sp->last_renewal_time, nfs4_client_resumed,
3267 		    tmp_last_renewal_time));
3268 
3269 		if (sp->s_thread_exit == NFS4_THREAD_EXIT)
3270 			goto die;
3271 
3272 		if (tmp_last_renewal_time == sp->last_renewal_time ||
3273 		    (nfs4_client_resumed != 0 &&
3274 		    nfs4_client_resumed > sp->last_renewal_time)) {
3275 			/*
3276 			 * Issue RENEW op since we haven't renewed the lease
3277 			 * since we slept.
3278 			 */
3279 			tmp_now_time = gethrestime_sec();
3280 			error = nfs4renew(sp);
3281 			/*
3282 			 * Need to re-acquire sp's lock, nfs4renew()
3283 			 * relinqueshes it.
3284 			 */
3285 			mutex_enter(&sp->s_lock);
3286 
3287 			/*
3288 			 * See if someone changed s_thread_exit while we gave
3289 			 * up s_lock.
3290 			 */
3291 			if (sp->s_thread_exit == NFS4_THREAD_EXIT)
3292 				goto die;
3293 
3294 			if (!error) {
3295 				/*
3296 				 * check to see if we implicitly renewed while
3297 				 * we waited for a reply for our RENEW call.
3298 				 */
3299 				if (tmp_last_renewal_time ==
3300 				    sp->last_renewal_time) {
3301 					/* no implicit renew came */
3302 					sp->last_renewal_time = tmp_now_time;
3303 				} else {
3304 					NFS4_DEBUG(nfs4_client_lease_debug,
3305 					    (CE_NOTE, "renew_thread: did "
3306 					    "implicit renewal before reply "
3307 					    "from server for RENEW"));
3308 				}
3309 			} else {
3310 				/* figure out error */
3311 				NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3312 				    "renew_thread: nfs4renew returned error"
3313 				    " %d", error));
3314 			}
3315 
3316 		}
3317 	}
3318 
3319 die:
3320 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3321 	    "nfs4_renew_lease_thread: thread exiting"));
3322 
3323 	while (sp->s_otw_call_count != 0) {
3324 		NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3325 		    "nfs4_renew_lease_thread: waiting for outstanding "
3326 		    "otw calls to finish for sp 0x%p, current "
3327 		    "s_otw_call_count %d", (void *)sp,
3328 		    sp->s_otw_call_count));
3329 		mutex_enter(&cpr_lock);
3330 		CALLB_CPR_SAFE_BEGIN(&cpr_info);
3331 		mutex_exit(&cpr_lock);
3332 		cv_wait(&sp->s_cv_otw_count, &sp->s_lock);
3333 		mutex_enter(&cpr_lock);
3334 		CALLB_CPR_SAFE_END(&cpr_info, &cpr_lock);
3335 		mutex_exit(&cpr_lock);
3336 	}
3337 	mutex_exit(&sp->s_lock);
3338 
3339 	nfs4_server_rele(sp);		/* free the thread's reference */
3340 	nfs4_server_rele(sp);		/* free the list's reference */
3341 	sp = NULL;
3342 
3343 done:
3344 	mutex_enter(&cpr_lock);
3345 	CALLB_CPR_EXIT(&cpr_info);	/* drops cpr_lock */
3346 	mutex_destroy(&cpr_lock);
3347 
3348 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3349 	    "nfs4_renew_lease_thread: renew thread exit officially"));
3350 
3351 	zthread_exit();
3352 	/* NOT REACHED */
3353 }
3354 
3355 /*
3356  * Send out a RENEW op to the server.
3357  * Assumes sp is locked down.
3358  */
3359 static int
3360 nfs4renew(nfs4_server_t *sp)
3361 {
3362 	COMPOUND4args_clnt args;
3363 	COMPOUND4res_clnt res;
3364 	nfs_argop4 argop[1];
3365 	int doqueue = 1;
3366 	int rpc_error;
3367 	cred_t *cr;
3368 	mntinfo4_t *mi;
3369 	timespec_t prop_time, after_time;
3370 	int needrecov = FALSE;
3371 	nfs4_recov_state_t recov_state;
3372 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3373 
3374 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE, "nfs4renew"));
3375 
3376 	recov_state.rs_flags = 0;
3377 	recov_state.rs_num_retry_despite_err = 0;
3378 
3379 recov_retry:
3380 	mi = sp->mntinfo4_list;
3381 	VFS_HOLD(mi->mi_vfsp);
3382 	mutex_exit(&sp->s_lock);
3383 	ASSERT(mi != NULL);
3384 
3385 	e.error = nfs4_start_op(mi, NULL, NULL, &recov_state);
3386 	if (e.error) {
3387 		VFS_RELE(mi->mi_vfsp);
3388 		return (e.error);
3389 	}
3390 
3391 	/* Check to see if we're dealing with a marked-dead sp */
3392 	mutex_enter(&sp->s_lock);
3393 	if (sp->s_thread_exit == NFS4_THREAD_EXIT) {
3394 		mutex_exit(&sp->s_lock);
3395 		nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
3396 		VFS_RELE(mi->mi_vfsp);
3397 		return (0);
3398 	}
3399 
3400 	/* Make sure mi hasn't changed on us */
3401 	if (mi != sp->mntinfo4_list) {
3402 		/* Must drop sp's lock to avoid a recursive mutex enter */
3403 		mutex_exit(&sp->s_lock);
3404 		nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
3405 		VFS_RELE(mi->mi_vfsp);
3406 		mutex_enter(&sp->s_lock);
3407 		goto recov_retry;
3408 	}
3409 	mutex_exit(&sp->s_lock);
3410 
3411 	args.ctag = TAG_RENEW;
3412 
3413 	args.array_len = 1;
3414 	args.array = argop;
3415 
3416 	argop[0].argop = OP_RENEW;
3417 
3418 	mutex_enter(&sp->s_lock);
3419 	argop[0].nfs_argop4_u.oprenew.clientid = sp->clientid;
3420 	cr = sp->s_cred;
3421 	crhold(cr);
3422 	mutex_exit(&sp->s_lock);
3423 
3424 	ASSERT(cr != NULL);
3425 
3426 	/* used to figure out RTT for sp */
3427 	gethrestime(&prop_time);
3428 
3429 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3430 	    "nfs4renew: %s call, sp 0x%p", needrecov ? "recov" : "first",
3431 	    (void*)sp));
3432 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE, "before: %ld s %ld ns ",
3433 	    prop_time.tv_sec, prop_time.tv_nsec));
3434 
3435 	DTRACE_PROBE2(nfs4__renew__start, nfs4_server_t *, sp,
3436 	    mntinfo4_t *, mi);
3437 
3438 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3439 	crfree(cr);
3440 
3441 	DTRACE_PROBE2(nfs4__renew__end, nfs4_server_t *, sp,
3442 	    mntinfo4_t *, mi);
3443 
3444 	gethrestime(&after_time);
3445 
3446 	mutex_enter(&sp->s_lock);
3447 	sp->propagation_delay.tv_sec =
3448 	    MAX(1, after_time.tv_sec - prop_time.tv_sec);
3449 	mutex_exit(&sp->s_lock);
3450 
3451 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE, "after : %ld s %ld ns ",
3452 	    after_time.tv_sec, after_time.tv_nsec));
3453 
3454 	if (e.error == 0 && res.status == NFS4ERR_CB_PATH_DOWN) {
3455 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3456 		nfs4_delegreturn_all(sp);
3457 		nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
3458 		VFS_RELE(mi->mi_vfsp);
3459 		/*
3460 		 * If the server returns CB_PATH_DOWN, it has renewed
3461 		 * the lease and informed us that the callback path is
3462 		 * down.  Since the lease is renewed, just return 0 and
3463 		 * let the renew thread proceed as normal.
3464 		 */
3465 		return (0);
3466 	}
3467 
3468 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3469 	if (!needrecov && e.error) {
3470 		nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
3471 		VFS_RELE(mi->mi_vfsp);
3472 		return (e.error);
3473 	}
3474 
3475 	rpc_error = e.error;
3476 
3477 	if (needrecov) {
3478 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3479 		    "nfs4renew: initiating recovery\n"));
3480 
3481 		if (nfs4_start_recovery(&e, mi, NULL, NULL, NULL, NULL,
3482 		    OP_RENEW, NULL) == FALSE) {
3483 			nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
3484 			VFS_RELE(mi->mi_vfsp);
3485 			if (!e.error)
3486 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3487 				    (caddr_t)&res);
3488 			mutex_enter(&sp->s_lock);
3489 			goto recov_retry;
3490 		}
3491 		/* fall through for res.status case */
3492 	}
3493 
3494 	if (res.status) {
3495 		if (res.status == NFS4ERR_LEASE_MOVED) {
3496 			/*EMPTY*/
3497 			/*
3498 			 * XXX need to try every mntinfo4 in sp->mntinfo4_list
3499 			 * to renew the lease on that server
3500 			 */
3501 		}
3502 		e.error = geterrno4(res.status);
3503 	}
3504 
3505 	if (!rpc_error)
3506 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3507 
3508 	nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
3509 
3510 	VFS_RELE(mi->mi_vfsp);
3511 
3512 	return (e.error);
3513 }
3514 
3515 void
3516 nfs4_inc_state_ref_count(mntinfo4_t *mi)
3517 {
3518 	nfs4_server_t	*sp;
3519 
3520 	/* this locks down sp if it is found */
3521 	sp = find_nfs4_server(mi);
3522 
3523 	if (sp != NULL) {
3524 		nfs4_inc_state_ref_count_nolock(sp, mi);
3525 		mutex_exit(&sp->s_lock);
3526 		nfs4_server_rele(sp);
3527 	}
3528 }
3529 
3530 /*
3531  * Bump the number of OPEN files (ie: those with state) so we know if this
3532  * nfs4_server has any state to maintain a lease for or not.
3533  *
3534  * Also, marks the nfs4_server's lease valid if it hasn't been done so already.
3535  */
3536 void
3537 nfs4_inc_state_ref_count_nolock(nfs4_server_t *sp, mntinfo4_t *mi)
3538 {
3539 	ASSERT(mutex_owned(&sp->s_lock));
3540 
3541 	sp->state_ref_count++;
3542 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3543 	    "nfs4_inc_state_ref_count: state_ref_count now %d",
3544 	    sp->state_ref_count));
3545 
3546 	if (sp->lease_valid == NFS4_LEASE_UNINITIALIZED)
3547 		sp->lease_valid = NFS4_LEASE_VALID;
3548 
3549 	/*
3550 	 * If this call caused the lease to be marked valid and/or
3551 	 * took the state_ref_count from 0 to 1, then start the time
3552 	 * on lease renewal.
3553 	 */
3554 	if (sp->lease_valid == NFS4_LEASE_VALID && sp->state_ref_count == 1)
3555 		sp->last_renewal_time = gethrestime_sec();
3556 
3557 	/* update the number of open files for mi */
3558 	mi->mi_open_files++;
3559 }
3560 
3561 void
3562 nfs4_dec_state_ref_count(mntinfo4_t *mi)
3563 {
3564 	nfs4_server_t	*sp;
3565 
3566 	/* this locks down sp if it is found */
3567 	sp = find_nfs4_server_all(mi, 1);
3568 
3569 	if (sp != NULL) {
3570 		nfs4_dec_state_ref_count_nolock(sp, mi);
3571 		mutex_exit(&sp->s_lock);
3572 		nfs4_server_rele(sp);
3573 	}
3574 }
3575 
3576 /*
3577  * Decrement the number of OPEN files (ie: those with state) so we know if
3578  * this nfs4_server has any state to maintain a lease for or not.
3579  */
3580 void
3581 nfs4_dec_state_ref_count_nolock(nfs4_server_t *sp, mntinfo4_t *mi)
3582 {
3583 	ASSERT(mutex_owned(&sp->s_lock));
3584 	ASSERT(sp->state_ref_count != 0);
3585 	sp->state_ref_count--;
3586 
3587 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3588 	    "nfs4_dec_state_ref_count: state ref count now %d",
3589 	    sp->state_ref_count));
3590 
3591 	mi->mi_open_files--;
3592 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3593 	    "nfs4_dec_state_ref_count: mi open files %d, v4 flags 0x%x",
3594 	    mi->mi_open_files, mi->mi_flags));
3595 
3596 	/* We don't have to hold the mi_lock to test mi_flags */
3597 	if (mi->mi_open_files == 0 &&
3598 	    (mi->mi_flags & MI4_REMOVE_ON_LAST_CLOSE)) {
3599 		NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3600 		    "nfs4_dec_state_ref_count: remove mntinfo4 %p since "
3601 		    "we have closed the last open file", (void*)mi));
3602 		nfs4_remove_mi_from_server(mi, sp);
3603 	}
3604 }
3605 
3606 bool_t
3607 inlease(nfs4_server_t *sp)
3608 {
3609 	bool_t result;
3610 
3611 	ASSERT(mutex_owned(&sp->s_lock));
3612 
3613 	if (sp->lease_valid == NFS4_LEASE_VALID &&
3614 	    gethrestime_sec() < sp->last_renewal_time + sp->s_lease_time)
3615 		result = TRUE;
3616 	else
3617 		result = FALSE;
3618 
3619 	return (result);
3620 }
3621 
3622 
3623 /*
3624  * Return non-zero if the given nfs4_server_t is going through recovery.
3625  */
3626 
3627 int
3628 nfs4_server_in_recovery(nfs4_server_t *sp)
3629 {
3630 	return (nfs_rw_lock_held(&sp->s_recovlock, RW_WRITER));
3631 }
3632 
3633 /*
3634  * Compare two shared filehandle objects.  Returns -1, 0, or +1, if the
3635  * first is less than, equal to, or greater than the second.
3636  */
3637 
3638 int
3639 sfh4cmp(const void *p1, const void *p2)
3640 {
3641 	const nfs4_sharedfh_t *sfh1 = (const nfs4_sharedfh_t *)p1;
3642 	const nfs4_sharedfh_t *sfh2 = (const nfs4_sharedfh_t *)p2;
3643 
3644 	return (nfs4cmpfh(&sfh1->sfh_fh, &sfh2->sfh_fh));
3645 }
3646 
3647 /*
3648  * Create a table for shared filehandle objects.
3649  */
3650 
3651 void
3652 sfh4_createtab(avl_tree_t *tab)
3653 {
3654 	avl_create(tab, sfh4cmp, sizeof (nfs4_sharedfh_t),
3655 	    offsetof(nfs4_sharedfh_t, sfh_tree));
3656 }
3657 
3658 /*
3659  * Return a shared filehandle object for the given filehandle.  The caller
3660  * is responsible for eventually calling sfh4_rele().
3661  */
3662 
3663 nfs4_sharedfh_t *
3664 sfh4_put(const nfs_fh4 *fh, mntinfo4_t *mi, nfs4_sharedfh_t *key)
3665 {
3666 	nfs4_sharedfh_t *sfh, *nsfh;
3667 	avl_index_t where;
3668 	nfs4_sharedfh_t skey;
3669 
3670 	if (!key) {
3671 		skey.sfh_fh = *fh;
3672 		key = &skey;
3673 	}
3674 
3675 	nsfh = kmem_alloc(sizeof (nfs4_sharedfh_t), KM_SLEEP);
3676 	nsfh->sfh_fh.nfs_fh4_len = fh->nfs_fh4_len;
3677 	/*
3678 	 * We allocate the largest possible filehandle size because it's
3679 	 * not that big, and it saves us from possibly having to resize the
3680 	 * buffer later.
3681 	 */
3682 	nsfh->sfh_fh.nfs_fh4_val = kmem_alloc(NFS4_FHSIZE, KM_SLEEP);
3683 	bcopy(fh->nfs_fh4_val, nsfh->sfh_fh.nfs_fh4_val, fh->nfs_fh4_len);
3684 	mutex_init(&nsfh->sfh_lock, NULL, MUTEX_DEFAULT, NULL);
3685 	nsfh->sfh_refcnt = 1;
3686 	nsfh->sfh_flags = SFH4_IN_TREE;
3687 	nsfh->sfh_mi = mi;
3688 	NFS4_DEBUG(nfs4_sharedfh_debug, (CE_NOTE, "sfh4_get: new object (%p)",
3689 	    (void *)nsfh));
3690 
3691 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_WRITER, 0);
3692 	sfh = avl_find(&mi->mi_filehandles, key, &where);
3693 	if (sfh != NULL) {
3694 		mutex_enter(&sfh->sfh_lock);
3695 		sfh->sfh_refcnt++;
3696 		mutex_exit(&sfh->sfh_lock);
3697 		nfs_rw_exit(&mi->mi_fh_lock);
3698 		/* free our speculative allocs */
3699 		kmem_free(nsfh->sfh_fh.nfs_fh4_val, NFS4_FHSIZE);
3700 		kmem_free(nsfh, sizeof (nfs4_sharedfh_t));
3701 		return (sfh);
3702 	}
3703 
3704 	avl_insert(&mi->mi_filehandles, nsfh, where);
3705 	nfs_rw_exit(&mi->mi_fh_lock);
3706 
3707 	return (nsfh);
3708 }
3709 
3710 /*
3711  * Return a shared filehandle object for the given filehandle.  The caller
3712  * is responsible for eventually calling sfh4_rele().
3713  */
3714 
3715 nfs4_sharedfh_t *
3716 sfh4_get(const nfs_fh4 *fh, mntinfo4_t *mi)
3717 {
3718 	nfs4_sharedfh_t *sfh;
3719 	nfs4_sharedfh_t key;
3720 
3721 	ASSERT(fh->nfs_fh4_len <= NFS4_FHSIZE);
3722 
3723 #ifdef DEBUG
3724 	if (nfs4_sharedfh_debug) {
3725 		nfs4_fhandle_t fhandle;
3726 
3727 		fhandle.fh_len = fh->nfs_fh4_len;
3728 		bcopy(fh->nfs_fh4_val, fhandle.fh_buf, fhandle.fh_len);
3729 		zcmn_err(mi->mi_zone->zone_id, CE_NOTE, "sfh4_get:");
3730 		nfs4_printfhandle(&fhandle);
3731 	}
3732 #endif
3733 
3734 	/*
3735 	 * If there's already an object for the given filehandle, bump the
3736 	 * reference count and return it.  Otherwise, create a new object
3737 	 * and add it to the AVL tree.
3738 	 */
3739 
3740 	key.sfh_fh = *fh;
3741 
3742 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
3743 	sfh = avl_find(&mi->mi_filehandles, &key, NULL);
3744 	if (sfh != NULL) {
3745 		mutex_enter(&sfh->sfh_lock);
3746 		sfh->sfh_refcnt++;
3747 		NFS4_DEBUG(nfs4_sharedfh_debug, (CE_NOTE,
3748 		    "sfh4_get: found existing %p, new refcnt=%d",
3749 		    (void *)sfh, sfh->sfh_refcnt));
3750 		mutex_exit(&sfh->sfh_lock);
3751 		nfs_rw_exit(&mi->mi_fh_lock);
3752 		return (sfh);
3753 	}
3754 	nfs_rw_exit(&mi->mi_fh_lock);
3755 
3756 	return (sfh4_put(fh, mi, &key));
3757 }
3758 
3759 /*
3760  * Get a reference to the given shared filehandle object.
3761  */
3762 
3763 void
3764 sfh4_hold(nfs4_sharedfh_t *sfh)
3765 {
3766 	ASSERT(sfh->sfh_refcnt > 0);
3767 
3768 	mutex_enter(&sfh->sfh_lock);
3769 	sfh->sfh_refcnt++;
3770 	NFS4_DEBUG(nfs4_sharedfh_debug,
3771 	    (CE_NOTE, "sfh4_hold %p, new refcnt=%d",
3772 	    (void *)sfh, sfh->sfh_refcnt));
3773 	mutex_exit(&sfh->sfh_lock);
3774 }
3775 
3776 /*
3777  * Release a reference to the given shared filehandle object and null out
3778  * the given pointer.
3779  */
3780 
3781 void
3782 sfh4_rele(nfs4_sharedfh_t **sfhpp)
3783 {
3784 	mntinfo4_t *mi;
3785 	nfs4_sharedfh_t *sfh = *sfhpp;
3786 
3787 	ASSERT(sfh->sfh_refcnt > 0);
3788 
3789 	mutex_enter(&sfh->sfh_lock);
3790 	if (sfh->sfh_refcnt > 1) {
3791 		sfh->sfh_refcnt--;
3792 		NFS4_DEBUG(nfs4_sharedfh_debug, (CE_NOTE,
3793 		    "sfh4_rele %p, new refcnt=%d",
3794 		    (void *)sfh, sfh->sfh_refcnt));
3795 		mutex_exit(&sfh->sfh_lock);
3796 		goto finish;
3797 	}
3798 	mutex_exit(&sfh->sfh_lock);
3799 
3800 	/*
3801 	 * Possibly the last reference, so get the lock for the table in
3802 	 * case it's time to remove the object from the table.
3803 	 */
3804 	mi = sfh->sfh_mi;
3805 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_WRITER, 0);
3806 	mutex_enter(&sfh->sfh_lock);
3807 	sfh->sfh_refcnt--;
3808 	if (sfh->sfh_refcnt > 0) {
3809 		NFS4_DEBUG(nfs4_sharedfh_debug, (CE_NOTE,
3810 		    "sfh4_rele %p, new refcnt=%d",
3811 		    (void *)sfh, sfh->sfh_refcnt));
3812 		mutex_exit(&sfh->sfh_lock);
3813 		nfs_rw_exit(&mi->mi_fh_lock);
3814 		goto finish;
3815 	}
3816 
3817 	NFS4_DEBUG(nfs4_sharedfh_debug, (CE_NOTE,
3818 	    "sfh4_rele %p, last ref", (void *)sfh));
3819 	if (sfh->sfh_flags & SFH4_IN_TREE) {
3820 		avl_remove(&mi->mi_filehandles, sfh);
3821 		sfh->sfh_flags &= ~SFH4_IN_TREE;
3822 	}
3823 	mutex_exit(&sfh->sfh_lock);
3824 	nfs_rw_exit(&mi->mi_fh_lock);
3825 	mutex_destroy(&sfh->sfh_lock);
3826 	kmem_free(sfh->sfh_fh.nfs_fh4_val, NFS4_FHSIZE);
3827 	kmem_free(sfh, sizeof (nfs4_sharedfh_t));
3828 
3829 finish:
3830 	*sfhpp = NULL;
3831 }
3832 
3833 /*
3834  * Update the filehandle for the given shared filehandle object.
3835  */
3836 
3837 int nfs4_warn_dupfh = 0;	/* if set, always warn about dup fhs below */
3838 
3839 void
3840 sfh4_update(nfs4_sharedfh_t *sfh, const nfs_fh4 *newfh)
3841 {
3842 	mntinfo4_t *mi = sfh->sfh_mi;
3843 	nfs4_sharedfh_t *dupsfh;
3844 	avl_index_t where;
3845 	nfs4_sharedfh_t key;
3846 
3847 #ifdef DEBUG
3848 	mutex_enter(&sfh->sfh_lock);
3849 	ASSERT(sfh->sfh_refcnt > 0);
3850 	mutex_exit(&sfh->sfh_lock);
3851 #endif
3852 	ASSERT(newfh->nfs_fh4_len <= NFS4_FHSIZE);
3853 
3854 	/*
3855 	 * The basic plan is to remove the shared filehandle object from
3856 	 * the table, update it to have the new filehandle, then reinsert
3857 	 * it.
3858 	 */
3859 
3860 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_WRITER, 0);
3861 	mutex_enter(&sfh->sfh_lock);
3862 	if (sfh->sfh_flags & SFH4_IN_TREE) {
3863 		avl_remove(&mi->mi_filehandles, sfh);
3864 		sfh->sfh_flags &= ~SFH4_IN_TREE;
3865 	}
3866 	mutex_exit(&sfh->sfh_lock);
3867 	sfh->sfh_fh.nfs_fh4_len = newfh->nfs_fh4_len;
3868 	bcopy(newfh->nfs_fh4_val, sfh->sfh_fh.nfs_fh4_val,
3869 	    sfh->sfh_fh.nfs_fh4_len);
3870 
3871 	/*
3872 	 * XXX If there is already a shared filehandle object with the new
3873 	 * filehandle, we're in trouble, because the rnode code assumes
3874 	 * that there is only one shared filehandle object for a given
3875 	 * filehandle.  So issue a warning (for read-write mounts only)
3876 	 * and don't try to re-insert the given object into the table.
3877 	 * Hopefully the given object will quickly go away and everyone
3878 	 * will use the new object.
3879 	 */
3880 	key.sfh_fh = *newfh;
3881 	dupsfh = avl_find(&mi->mi_filehandles, &key, &where);
3882 	if (dupsfh != NULL) {
3883 		if (!(mi->mi_vfsp->vfs_flag & VFS_RDONLY) || nfs4_warn_dupfh) {
3884 			zcmn_err(mi->mi_zone->zone_id, CE_WARN, "sfh4_update: "
3885 			    "duplicate filehandle detected");
3886 			sfh4_printfhandle(dupsfh);
3887 		}
3888 	} else {
3889 		avl_insert(&mi->mi_filehandles, sfh, where);
3890 		mutex_enter(&sfh->sfh_lock);
3891 		sfh->sfh_flags |= SFH4_IN_TREE;
3892 		mutex_exit(&sfh->sfh_lock);
3893 	}
3894 	nfs_rw_exit(&mi->mi_fh_lock);
3895 }
3896 
3897 /*
3898  * Copy out the current filehandle for the given shared filehandle object.
3899  */
3900 
3901 void
3902 sfh4_copyval(const nfs4_sharedfh_t *sfh, nfs4_fhandle_t *fhp)
3903 {
3904 	mntinfo4_t *mi = sfh->sfh_mi;
3905 
3906 	ASSERT(sfh->sfh_refcnt > 0);
3907 
3908 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
3909 	fhp->fh_len = sfh->sfh_fh.nfs_fh4_len;
3910 	ASSERT(fhp->fh_len <= NFS4_FHSIZE);
3911 	bcopy(sfh->sfh_fh.nfs_fh4_val, fhp->fh_buf, fhp->fh_len);
3912 	nfs_rw_exit(&mi->mi_fh_lock);
3913 }
3914 
3915 /*
3916  * Print out the filehandle for the given shared filehandle object.
3917  */
3918 
3919 void
3920 sfh4_printfhandle(const nfs4_sharedfh_t *sfh)
3921 {
3922 	nfs4_fhandle_t fhandle;
3923 
3924 	sfh4_copyval(sfh, &fhandle);
3925 	nfs4_printfhandle(&fhandle);
3926 }
3927 
3928 /*
3929  * Compare 2 fnames.  Returns -1 if the first is "less" than the second, 0
3930  * if they're the same, +1 if the first is "greater" than the second.  The
3931  * caller (or whoever's calling the AVL package) is responsible for
3932  * handling locking issues.
3933  */
3934 
3935 static int
3936 fncmp(const void *p1, const void *p2)
3937 {
3938 	const nfs4_fname_t *f1 = p1;
3939 	const nfs4_fname_t *f2 = p2;
3940 	int res;
3941 
3942 	res = strcmp(f1->fn_name, f2->fn_name);
3943 	/*
3944 	 * The AVL package wants +/-1, not arbitrary positive or negative
3945 	 * integers.
3946 	 */
3947 	if (res > 0)
3948 		res = 1;
3949 	else if (res < 0)
3950 		res = -1;
3951 	return (res);
3952 }
3953 
3954 /*
3955  * Get or create an fname with the given name, as a child of the given
3956  * fname.  The caller is responsible for eventually releasing the reference
3957  * (fn_rele()).  parent may be NULL.
3958  */
3959 
3960 nfs4_fname_t *
3961 fn_get(nfs4_fname_t *parent, char *name, nfs4_sharedfh_t *sfh)
3962 {
3963 	nfs4_fname_t key;
3964 	nfs4_fname_t *fnp;
3965 	avl_index_t where;
3966 
3967 	key.fn_name = name;
3968 
3969 	/*
3970 	 * If there's already an fname registered with the given name, bump
3971 	 * its reference count and return it.  Otherwise, create a new one
3972 	 * and add it to the parent's AVL tree.
3973 	 *
3974 	 * fname entries we are looking for should match both name
3975 	 * and sfh stored in the fname.
3976 	 */
3977 again:
3978 	if (parent != NULL) {
3979 		mutex_enter(&parent->fn_lock);
3980 		fnp = avl_find(&parent->fn_children, &key, &where);
3981 		if (fnp != NULL) {
3982 			/*
3983 			 * This hold on fnp is released below later,
3984 			 * in case this is not the fnp we want.
3985 			 */
3986 			fn_hold(fnp);
3987 
3988 			if (fnp->fn_sfh == sfh) {
3989 				/*
3990 				 * We have found our entry.
3991 				 * put an hold and return it.
3992 				 */
3993 				mutex_exit(&parent->fn_lock);
3994 				return (fnp);
3995 			}
3996 
3997 			/*
3998 			 * We have found an entry that has a mismatching
3999 			 * fn_sfh. This could be a stale entry due to
4000 			 * server side rename. We will remove this entry
4001 			 * and make sure no such entries exist.
4002 			 */
4003 			mutex_exit(&parent->fn_lock);
4004 			mutex_enter(&fnp->fn_lock);
4005 			if (fnp->fn_parent == parent) {
4006 				/*
4007 				 * Remove ourselves from parent's
4008 				 * fn_children tree.
4009 				 */
4010 				mutex_enter(&parent->fn_lock);
4011 				avl_remove(&parent->fn_children, fnp);
4012 				mutex_exit(&parent->fn_lock);
4013 				fn_rele(&fnp->fn_parent);
4014 			}
4015 			mutex_exit(&fnp->fn_lock);
4016 			fn_rele(&fnp);
4017 			goto again;
4018 		}
4019 	}
4020 
4021 	fnp = kmem_alloc(sizeof (nfs4_fname_t), KM_SLEEP);
4022 	mutex_init(&fnp->fn_lock, NULL, MUTEX_DEFAULT, NULL);
4023 	fnp->fn_parent = parent;
4024 	if (parent != NULL)
4025 		fn_hold(parent);
4026 	fnp->fn_len = strlen(name);
4027 	ASSERT(fnp->fn_len < MAXNAMELEN);
4028 	fnp->fn_name = kmem_alloc(fnp->fn_len + 1, KM_SLEEP);
4029 	(void) strcpy(fnp->fn_name, name);
4030 	fnp->fn_refcnt = 1;
4031 
4032 	/*
4033 	 * This hold on sfh is later released
4034 	 * when we do the final fn_rele() on this fname.
4035 	 */
4036 	sfh4_hold(sfh);
4037 	fnp->fn_sfh = sfh;
4038 
4039 	avl_create(&fnp->fn_children, fncmp, sizeof (nfs4_fname_t),
4040 	    offsetof(nfs4_fname_t, fn_tree));
4041 	NFS4_DEBUG(nfs4_fname_debug, (CE_NOTE,
4042 	    "fn_get %p:%s, a new nfs4_fname_t!",
4043 	    (void *)fnp, fnp->fn_name));
4044 	if (parent != NULL) {
4045 		avl_insert(&parent->fn_children, fnp, where);
4046 		mutex_exit(&parent->fn_lock);
4047 	}
4048 
4049 	return (fnp);
4050 }
4051 
4052 void
4053 fn_hold(nfs4_fname_t *fnp)
4054 {
4055 	atomic_add_32(&fnp->fn_refcnt, 1);
4056 	NFS4_DEBUG(nfs4_fname_debug, (CE_NOTE,
4057 	    "fn_hold %p:%s, new refcnt=%d",
4058 	    (void *)fnp, fnp->fn_name, fnp->fn_refcnt));
4059 }
4060 
4061 /*
4062  * Decrement the reference count of the given fname, and destroy it if its
4063  * reference count goes to zero.  Nulls out the given pointer.
4064  */
4065 
4066 void
4067 fn_rele(nfs4_fname_t **fnpp)
4068 {
4069 	nfs4_fname_t *parent;
4070 	uint32_t newref;
4071 	nfs4_fname_t *fnp;
4072 
4073 recur:
4074 	fnp = *fnpp;
4075 	*fnpp = NULL;
4076 
4077 	mutex_enter(&fnp->fn_lock);
4078 	parent = fnp->fn_parent;
4079 	if (parent != NULL)
4080 		mutex_enter(&parent->fn_lock);	/* prevent new references */
4081 	newref = atomic_add_32_nv(&fnp->fn_refcnt, -1);
4082 	if (newref > 0) {
4083 		NFS4_DEBUG(nfs4_fname_debug, (CE_NOTE,
4084 		    "fn_rele %p:%s, new refcnt=%d",
4085 		    (void *)fnp, fnp->fn_name, fnp->fn_refcnt));
4086 		if (parent != NULL)
4087 			mutex_exit(&parent->fn_lock);
4088 		mutex_exit(&fnp->fn_lock);
4089 		return;
4090 	}
4091 
4092 	NFS4_DEBUG(nfs4_fname_debug, (CE_NOTE,
4093 	    "fn_rele %p:%s, last reference, deleting...",
4094 	    (void *)fnp, fnp->fn_name));
4095 	if (parent != NULL) {
4096 		avl_remove(&parent->fn_children, fnp);
4097 		mutex_exit(&parent->fn_lock);
4098 	}
4099 	kmem_free(fnp->fn_name, fnp->fn_len + 1);
4100 	sfh4_rele(&fnp->fn_sfh);
4101 	mutex_destroy(&fnp->fn_lock);
4102 	avl_destroy(&fnp->fn_children);
4103 	kmem_free(fnp, sizeof (nfs4_fname_t));
4104 	/*
4105 	 * Recursivly fn_rele the parent.
4106 	 * Use goto instead of a recursive call to avoid stack overflow.
4107 	 */
4108 	if (parent != NULL) {
4109 		fnpp = &parent;
4110 		goto recur;
4111 	}
4112 }
4113 
4114 /*
4115  * Returns the single component name of the given fname, in a MAXNAMELEN
4116  * string buffer, which the caller is responsible for freeing.  Note that
4117  * the name may become invalid as a result of fn_move().
4118  */
4119 
4120 char *
4121 fn_name(nfs4_fname_t *fnp)
4122 {
4123 	char *name;
4124 
4125 	ASSERT(fnp->fn_len < MAXNAMELEN);
4126 	name = kmem_alloc(MAXNAMELEN, KM_SLEEP);
4127 	mutex_enter(&fnp->fn_lock);
4128 	(void) strcpy(name, fnp->fn_name);
4129 	mutex_exit(&fnp->fn_lock);
4130 
4131 	return (name);
4132 }
4133 
4134 
4135 /*
4136  * fn_path_realloc
4137  *
4138  * This function, used only by fn_path, constructs
4139  * a new string which looks like "prepend" + "/" + "current".
4140  * by allocating a new string and freeing the old one.
4141  */
4142 static void
4143 fn_path_realloc(char **curses, char *prepend)
4144 {
4145 	int len, curlen = 0;
4146 	char *news;
4147 
4148 	if (*curses == NULL) {
4149 		/*
4150 		 * Prime the pump, allocate just the
4151 		 * space for prepend and return that.
4152 		 */
4153 		len = strlen(prepend) + 1;
4154 		news = kmem_alloc(len, KM_SLEEP);
4155 		(void) strncpy(news, prepend, len);
4156 	} else {
4157 		/*
4158 		 * Allocate the space  for a new string
4159 		 * +1 +1 is for the "/" and the NULL
4160 		 * byte at the end of it all.
4161 		 */
4162 		curlen = strlen(*curses);
4163 		len = curlen + strlen(prepend) + 1 + 1;
4164 		news = kmem_alloc(len, KM_SLEEP);
4165 		(void) strncpy(news, prepend, len);
4166 		(void) strcat(news, "/");
4167 		(void) strcat(news, *curses);
4168 		kmem_free(*curses, curlen + 1);
4169 	}
4170 	*curses = news;
4171 }
4172 
4173 /*
4174  * Returns the path name (starting from the fs root) for the given fname.
4175  * The caller is responsible for freeing.  Note that the path may be or
4176  * become invalid as a result of fn_move().
4177  */
4178 
4179 char *
4180 fn_path(nfs4_fname_t *fnp)
4181 {
4182 	char *path;
4183 	nfs4_fname_t *nextfnp;
4184 
4185 	if (fnp == NULL)
4186 		return (NULL);
4187 
4188 	path = NULL;
4189 
4190 	/* walk up the tree constructing the pathname.  */
4191 
4192 	fn_hold(fnp);			/* adjust for later rele */
4193 	do {
4194 		mutex_enter(&fnp->fn_lock);
4195 		/*
4196 		 * Add fn_name in front of the current path
4197 		 */
4198 		fn_path_realloc(&path, fnp->fn_name);
4199 		nextfnp = fnp->fn_parent;
4200 		if (nextfnp != NULL)
4201 			fn_hold(nextfnp);
4202 		mutex_exit(&fnp->fn_lock);
4203 		fn_rele(&fnp);
4204 		fnp = nextfnp;
4205 	} while (fnp != NULL);
4206 
4207 	return (path);
4208 }
4209 
4210 /*
4211  * Return a reference to the parent of the given fname, which the caller is
4212  * responsible for eventually releasing.
4213  */
4214 
4215 nfs4_fname_t *
4216 fn_parent(nfs4_fname_t *fnp)
4217 {
4218 	nfs4_fname_t *parent;
4219 
4220 	mutex_enter(&fnp->fn_lock);
4221 	parent = fnp->fn_parent;
4222 	if (parent != NULL)
4223 		fn_hold(parent);
4224 	mutex_exit(&fnp->fn_lock);
4225 
4226 	return (parent);
4227 }
4228 
4229 /*
4230  * Update fnp so that its parent is newparent and its name is newname.
4231  */
4232 
4233 void
4234 fn_move(nfs4_fname_t *fnp, nfs4_fname_t *newparent, char *newname)
4235 {
4236 	nfs4_fname_t *parent, *tmpfnp;
4237 	ssize_t newlen;
4238 	nfs4_fname_t key;
4239 	avl_index_t where;
4240 
4241 	/*
4242 	 * This assert exists to catch the client trying to rename
4243 	 * a dir to be a child of itself.  This happened at a recent
4244 	 * bakeoff against a 3rd party (broken) server which allowed
4245 	 * the rename to succeed.  If it trips it means that:
4246 	 *	a) the code in nfs4rename that detects this case is broken
4247 	 *	b) the server is broken (since it allowed the bogus rename)
4248 	 *
4249 	 * For non-DEBUG kernels, prepare for a recursive mutex_enter
4250 	 * panic below from:  mutex_enter(&newparent->fn_lock);
4251 	 */
4252 	ASSERT(fnp != newparent);
4253 
4254 	/*
4255 	 * Remove fnp from its current parent, change its name, then add it
4256 	 * to newparent. It might happen that fnp was replaced by another
4257 	 * nfs4_fname_t with the same fn_name in parent->fn_children.
4258 	 * In such case, fnp->fn_parent is NULL and we skip the removal
4259 	 * of fnp from its current parent.
4260 	 */
4261 	mutex_enter(&fnp->fn_lock);
4262 	parent = fnp->fn_parent;
4263 	if (parent != NULL) {
4264 		mutex_enter(&parent->fn_lock);
4265 		avl_remove(&parent->fn_children, fnp);
4266 		mutex_exit(&parent->fn_lock);
4267 		fn_rele(&fnp->fn_parent);
4268 	}
4269 
4270 	newlen = strlen(newname);
4271 	if (newlen != fnp->fn_len) {
4272 		ASSERT(newlen < MAXNAMELEN);
4273 		kmem_free(fnp->fn_name, fnp->fn_len + 1);
4274 		fnp->fn_name = kmem_alloc(newlen + 1, KM_SLEEP);
4275 		fnp->fn_len = newlen;
4276 	}
4277 	(void) strcpy(fnp->fn_name, newname);
4278 
4279 again:
4280 	mutex_enter(&newparent->fn_lock);
4281 	key.fn_name = fnp->fn_name;
4282 	tmpfnp = avl_find(&newparent->fn_children, &key, &where);
4283 	if (tmpfnp != NULL) {
4284 		/*
4285 		 * This could be due to a file that was unlinked while
4286 		 * open, or perhaps the rnode is in the free list.  Remove
4287 		 * it from newparent and let it go away on its own.  The
4288 		 * contorted code is to deal with lock order issues and
4289 		 * race conditions.
4290 		 */
4291 		fn_hold(tmpfnp);
4292 		mutex_exit(&newparent->fn_lock);
4293 		mutex_enter(&tmpfnp->fn_lock);
4294 		if (tmpfnp->fn_parent == newparent) {
4295 			mutex_enter(&newparent->fn_lock);
4296 			avl_remove(&newparent->fn_children, tmpfnp);
4297 			mutex_exit(&newparent->fn_lock);
4298 			fn_rele(&tmpfnp->fn_parent);
4299 		}
4300 		mutex_exit(&tmpfnp->fn_lock);
4301 		fn_rele(&tmpfnp);
4302 		goto again;
4303 	}
4304 	fnp->fn_parent = newparent;
4305 	fn_hold(newparent);
4306 	avl_insert(&newparent->fn_children, fnp, where);
4307 	mutex_exit(&newparent->fn_lock);
4308 	mutex_exit(&fnp->fn_lock);
4309 }
4310 
4311 #ifdef DEBUG
4312 /*
4313  * Return non-zero if the type information makes sense for the given vnode.
4314  * Otherwise panic.
4315  */
4316 int
4317 nfs4_consistent_type(vnode_t *vp)
4318 {
4319 	rnode4_t *rp = VTOR4(vp);
4320 
4321 	if (nfs4_vtype_debug && vp->v_type != VNON &&
4322 	    rp->r_attr.va_type != VNON && vp->v_type != rp->r_attr.va_type) {
4323 		cmn_err(CE_PANIC, "vnode %p type mismatch; v_type=%d, "
4324 		    "rnode attr type=%d", (void *)vp, vp->v_type,
4325 		    rp->r_attr.va_type);
4326 	}
4327 
4328 	return (1);
4329 }
4330 #endif /* DEBUG */
4331