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 2008 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/cred.h>
35 #include <sys/vfs.h>
36 #include <sys/vfs_opreg.h>
37 #include <sys/vnode.h>
38 #include <sys/pathname.h>
39 #include <sys/sysmacros.h>
40 #include <sys/kmem.h>
41 #include <sys/mkdev.h>
42 #include <sys/mount.h>
43 #include <sys/statvfs.h>
44 #include <sys/errno.h>
45 #include <sys/debug.h>
46 #include <sys/cmn_err.h>
47 #include <sys/utsname.h>
48 #include <sys/bootconf.h>
49 #include <sys/modctl.h>
50 #include <sys/acl.h>
51 #include <sys/flock.h>
52 #include <sys/time.h>
53 #include <sys/disp.h>
54 #include <sys/policy.h>
55 #include <sys/socket.h>
56 #include <sys/netconfig.h>
57 #include <sys/dnlc.h>
58 #include <sys/list.h>
59 #include <sys/mntent.h>
60 #include <sys/tsol/label.h>
61 
62 #include <rpc/types.h>
63 #include <rpc/auth.h>
64 #include <rpc/rpcsec_gss.h>
65 #include <rpc/clnt.h>
66 
67 #include <nfs/nfs.h>
68 #include <nfs/nfs_clnt.h>
69 #include <nfs/mount.h>
70 #include <nfs/nfs_acl.h>
71 
72 #include <fs/fs_subr.h>
73 
74 #include <nfs/nfs4.h>
75 #include <nfs/rnode4.h>
76 #include <nfs/nfs4_clnt.h>
77 #include <sys/fs/autofs.h>
78 
79 
80 /*
81  * Arguments passed to thread to free data structures from forced unmount.
82  */
83 
84 typedef struct {
85 	vfs_t	*fm_vfsp;
86 	int	fm_flag;
87 	cred_t	*fm_cr;
88 } freemountargs_t;
89 
90 static void	async_free_mount(vfs_t *, int, cred_t *);
91 static void	nfs4_free_mount(vfs_t *, int, cred_t *);
92 static void	nfs4_free_mount_thread(freemountargs_t *);
93 static int nfs4_chkdup_servinfo4(servinfo4_t *, servinfo4_t *);
94 
95 /*
96  * From rpcsec module (common/rpcsec).
97  */
98 extern int sec_clnt_loadinfo(struct sec_data *, struct sec_data **, model_t);
99 extern void sec_clnt_freeinfo(struct sec_data *);
100 
101 /*
102  * The order and contents of this structure must be kept in sync with that of
103  * rfsreqcnt_v4_tmpl in nfs_stats.c
104  */
105 static char *rfsnames_v4[] = {
106 	"null", "compound", "reserved",	"access", "close", "commit", "create",
107 	"delegpurge", "delegreturn", "getattr",	"getfh", "link", "lock",
108 	"lockt", "locku", "lookup", "lookupp", "nverify", "open", "openattr",
109 	"open_confirm",	"open_downgrade", "putfh", "putpubfh", "putrootfh",
110 	"read", "readdir", "readlink", "remove", "rename", "renew",
111 	"restorefh", "savefh", "secinfo", "setattr", "setclientid",
112 	"setclientid_confirm", "verify", "write"
113 };
114 
115 /*
116  * nfs4_max_mount_retry is the number of times the client will redrive
117  * a mount compound before giving up and returning failure.  The intent
118  * is to redrive mount compounds which fail NFS4ERR_STALE so that
119  * if a component of the server path being mounted goes stale, it can
120  * "recover" by redriving the mount compund (LOOKUP ops).  This recovery
121  * code is needed outside of the recovery framework because mount is a
122  * special case.  The client doesn't create vnodes/rnodes for components
123  * of the server path being mounted.  The recovery code recovers real
124  * client objects, not STALE FHs which map to components of the server
125  * path being mounted.
126  *
127  * We could just fail the mount on the first time, but that would
128  * instantly trigger failover (from nfs4_mount), and the client should
129  * try to re-lookup the STALE FH before doing failover.  The easiest
130  * way to "re-lookup" is to simply redrive the mount compound.
131  */
132 static int nfs4_max_mount_retry = 2;
133 
134 /*
135  * nfs4 vfs operations.
136  */
137 int		nfs4_mount(vfs_t *, vnode_t *, struct mounta *, cred_t *);
138 static int	nfs4_unmount(vfs_t *, int, cred_t *);
139 static int	nfs4_root(vfs_t *, vnode_t **);
140 static int	nfs4_statvfs(vfs_t *, struct statvfs64 *);
141 static int	nfs4_sync(vfs_t *, short, cred_t *);
142 static int	nfs4_vget(vfs_t *, vnode_t **, fid_t *);
143 static int	nfs4_mountroot(vfs_t *, whymountroot_t);
144 static void	nfs4_freevfs(vfs_t *);
145 
146 static int	nfs4rootvp(vnode_t **, vfs_t *, struct servinfo4 *,
147 		    int, cred_t *, zone_t *);
148 
149 vfsops_t	*nfs4_vfsops;
150 
151 int nfs4_vfsinit(void);
152 void nfs4_vfsfini(void);
153 static void nfs4setclientid_init(void);
154 static void nfs4setclientid_fini(void);
155 static void nfs4setclientid_otw(mntinfo4_t *, servinfo4_t *,  cred_t *,
156 		struct nfs4_server *, nfs4_error_t *, int *);
157 static void	destroy_nfs4_server(nfs4_server_t *);
158 static void	remove_mi(nfs4_server_t *, mntinfo4_t *);
159 
160 extern void nfs4_ephemeral_init(void);
161 extern void nfs4_ephemeral_fini(void);
162 
163 /*
164  * Initialize the vfs structure
165  */
166 
167 static int nfs4fstyp;
168 
169 
170 /*
171  * Debug variable to check for rdma based
172  * transport startup and cleanup. Controlled
173  * through /etc/system. Off by default.
174  */
175 extern int rdma_debug;
176 
177 int
178 nfs4init(int fstyp, char *name)
179 {
180 	static const fs_operation_def_t nfs4_vfsops_template[] = {
181 		VFSNAME_MOUNT,		{ .vfs_mount = nfs4_mount },
182 		VFSNAME_UNMOUNT,	{ .vfs_unmount = nfs4_unmount },
183 		VFSNAME_ROOT,		{ .vfs_root = nfs4_root },
184 		VFSNAME_STATVFS,	{ .vfs_statvfs = nfs4_statvfs },
185 		VFSNAME_SYNC,		{ .vfs_sync = nfs4_sync },
186 		VFSNAME_VGET,		{ .vfs_vget = nfs4_vget },
187 		VFSNAME_MOUNTROOT,	{ .vfs_mountroot = nfs4_mountroot },
188 		VFSNAME_FREEVFS,	{ .vfs_freevfs = nfs4_freevfs },
189 		NULL,			NULL
190 	};
191 	int error;
192 
193 	nfs4_vfsops = NULL;
194 	nfs4_vnodeops = NULL;
195 	nfs4_trigger_vnodeops = NULL;
196 
197 	error = vfs_setfsops(fstyp, nfs4_vfsops_template, &nfs4_vfsops);
198 	if (error != 0) {
199 		zcmn_err(GLOBAL_ZONEID, CE_WARN,
200 		    "nfs4init: bad vfs ops template");
201 		goto out;
202 	}
203 
204 	error = vn_make_ops(name, nfs4_vnodeops_template, &nfs4_vnodeops);
205 	if (error != 0) {
206 		zcmn_err(GLOBAL_ZONEID, CE_WARN,
207 		    "nfs4init: bad vnode ops template");
208 		goto out;
209 	}
210 
211 	error = vn_make_ops("nfs4_trigger", nfs4_trigger_vnodeops_template,
212 	    &nfs4_trigger_vnodeops);
213 	if (error != 0) {
214 		zcmn_err(GLOBAL_ZONEID, CE_WARN,
215 		    "nfs4init: bad trigger vnode ops template");
216 		goto out;
217 	}
218 
219 	nfs4fstyp = fstyp;
220 	(void) nfs4_vfsinit();
221 	(void) nfs4_init_dot_entries();
222 
223 out:
224 	if (error) {
225 		if (nfs4_trigger_vnodeops != NULL)
226 			vn_freevnodeops(nfs4_trigger_vnodeops);
227 
228 		if (nfs4_vnodeops != NULL)
229 			vn_freevnodeops(nfs4_vnodeops);
230 
231 		(void) vfs_freevfsops_by_type(fstyp);
232 	}
233 
234 	return (error);
235 }
236 
237 void
238 nfs4fini(void)
239 {
240 	(void) nfs4_destroy_dot_entries();
241 	nfs4_vfsfini();
242 }
243 
244 /*
245  * Create a new sec_data structure to store AUTH_DH related data:
246  * netname, syncaddr, knetconfig. There is no AUTH_F_RPCTIMESYNC
247  * flag set for NFS V4 since we are avoiding to contact the rpcbind
248  * daemon and is using the IP time service (IPPORT_TIMESERVER).
249  *
250  * sec_data can be freed by sec_clnt_freeinfo().
251  */
252 static struct sec_data *
253 create_authdh_data(char *netname, int nlen, struct netbuf *syncaddr,
254 		struct knetconfig *knconf) {
255 	struct sec_data *secdata;
256 	dh_k4_clntdata_t *data;
257 	char *pf, *p;
258 
259 	if (syncaddr == NULL || syncaddr->buf == NULL || nlen == 0)
260 		return (NULL);
261 
262 	secdata = kmem_alloc(sizeof (*secdata), KM_SLEEP);
263 	secdata->flags = 0;
264 
265 	data = kmem_alloc(sizeof (*data), KM_SLEEP);
266 
267 	data->syncaddr.maxlen = syncaddr->maxlen;
268 	data->syncaddr.len = syncaddr->len;
269 	data->syncaddr.buf = (char *)kmem_alloc(syncaddr->len, KM_SLEEP);
270 	bcopy(syncaddr->buf, data->syncaddr.buf, syncaddr->len);
271 
272 	/*
273 	 * duplicate the knconf information for the
274 	 * new opaque data.
275 	 */
276 	data->knconf = kmem_alloc(sizeof (*knconf), KM_SLEEP);
277 	*data->knconf = *knconf;
278 	pf = kmem_alloc(KNC_STRSIZE, KM_SLEEP);
279 	p = kmem_alloc(KNC_STRSIZE, KM_SLEEP);
280 	bcopy(knconf->knc_protofmly, pf, KNC_STRSIZE);
281 	bcopy(knconf->knc_proto, p, KNC_STRSIZE);
282 	data->knconf->knc_protofmly = pf;
283 	data->knconf->knc_proto = p;
284 
285 	/* move server netname to the sec_data structure */
286 	data->netname = kmem_alloc(nlen, KM_SLEEP);
287 	bcopy(netname, data->netname, nlen);
288 	data->netnamelen = (int)nlen;
289 
290 	secdata->secmod = AUTH_DH;
291 	secdata->rpcflavor = AUTH_DH;
292 	secdata->data = (caddr_t)data;
293 
294 	return (secdata);
295 }
296 
297 /*
298  * Returns (deep) copy of sec_data_t. Allocates all memory required; caller
299  * is responsible for freeing.
300  */
301 sec_data_t *
302 copy_sec_data(sec_data_t *fsecdata) {
303 	sec_data_t *tsecdata;
304 
305 	if (fsecdata == NULL)
306 		return (NULL);
307 
308 	if (fsecdata->rpcflavor == AUTH_DH) {
309 		dh_k4_clntdata_t *fdata = (dh_k4_clntdata_t *)fsecdata->data;
310 
311 		if (fdata == NULL)
312 			return (NULL);
313 
314 		tsecdata = (sec_data_t *)create_authdh_data(fdata->netname,
315 		    fdata->netnamelen, &fdata->syncaddr, fdata->knconf);
316 
317 		return (tsecdata);
318 	}
319 
320 	tsecdata = kmem_zalloc(sizeof (sec_data_t), KM_SLEEP);
321 
322 	tsecdata->secmod = fsecdata->secmod;
323 	tsecdata->rpcflavor = fsecdata->rpcflavor;
324 	tsecdata->flags = fsecdata->flags;
325 	tsecdata->uid = fsecdata->uid;
326 
327 	if (fsecdata->rpcflavor == RPCSEC_GSS) {
328 		gss_clntdata_t *gcd = (gss_clntdata_t *)fsecdata->data;
329 
330 		tsecdata->data = (caddr_t)copy_sec_data_gss(gcd);
331 	} else {
332 		tsecdata->data = NULL;
333 	}
334 
335 	return (tsecdata);
336 }
337 
338 gss_clntdata_t *
339 copy_sec_data_gss(gss_clntdata_t *fdata)
340 {
341 	gss_clntdata_t *tdata;
342 
343 	if (fdata == NULL)
344 		return (NULL);
345 
346 	tdata = kmem_zalloc(sizeof (gss_clntdata_t), KM_SLEEP);
347 
348 	tdata->mechanism.length = fdata->mechanism.length;
349 	tdata->mechanism.elements = kmem_zalloc(fdata->mechanism.length,
350 	    KM_SLEEP);
351 	bcopy(fdata->mechanism.elements, tdata->mechanism.elements,
352 	    fdata->mechanism.length);
353 
354 	tdata->service = fdata->service;
355 
356 	(void) strcpy(tdata->uname, fdata->uname);
357 	(void) strcpy(tdata->inst, fdata->inst);
358 	(void) strcpy(tdata->realm, fdata->realm);
359 
360 	tdata->qop = fdata->qop;
361 
362 	return (tdata);
363 }
364 
365 static int
366 nfs4_chkdup_servinfo4(servinfo4_t *svp_head, servinfo4_t *svp)
367 {
368 	servinfo4_t *si;
369 
370 	/*
371 	 * Iterate over the servinfo4 list to make sure
372 	 * we do not have a duplicate. Skip any servinfo4
373 	 * that has been marked "NOT IN USE"
374 	 */
375 	for (si = svp_head; si; si = si->sv_next) {
376 		(void) nfs_rw_enter_sig(&si->sv_lock, RW_READER, 0);
377 		if (si->sv_flags & SV4_NOTINUSE) {
378 			nfs_rw_exit(&si->sv_lock);
379 			continue;
380 		}
381 		nfs_rw_exit(&si->sv_lock);
382 		if (si == svp)
383 			continue;
384 		if (si->sv_addr.len == svp->sv_addr.len &&
385 		    strcmp(si->sv_knconf->knc_protofmly,
386 		    svp->sv_knconf->knc_protofmly) == 0 &&
387 		    bcmp(si->sv_addr.buf, svp->sv_addr.buf,
388 		    si->sv_addr.len) == 0) {
389 			/* it's a duplicate */
390 			return (1);
391 		}
392 	}
393 	/* it's not a duplicate */
394 	return (0);
395 }
396 
397 void
398 nfs4_free_args(struct nfs_args *nargs)
399 {
400 	if (nargs->knconf) {
401 		if (nargs->knconf->knc_protofmly)
402 			kmem_free(nargs->knconf->knc_protofmly,
403 			    KNC_STRSIZE);
404 		if (nargs->knconf->knc_proto)
405 			kmem_free(nargs->knconf->knc_proto, KNC_STRSIZE);
406 		kmem_free(nargs->knconf, sizeof (*nargs->knconf));
407 		nargs->knconf = NULL;
408 	}
409 
410 	if (nargs->fh) {
411 		kmem_free(nargs->fh, strlen(nargs->fh) + 1);
412 		nargs->fh = NULL;
413 	}
414 
415 	if (nargs->hostname) {
416 		kmem_free(nargs->hostname, strlen(nargs->hostname) + 1);
417 		nargs->hostname = NULL;
418 	}
419 
420 	if (nargs->addr) {
421 		if (nargs->addr->buf) {
422 			ASSERT(nargs->addr->len);
423 			kmem_free(nargs->addr->buf, nargs->addr->len);
424 		}
425 		kmem_free(nargs->addr, sizeof (struct netbuf));
426 		nargs->addr = NULL;
427 	}
428 
429 	if (nargs->syncaddr) {
430 		ASSERT(nargs->syncaddr->len);
431 		if (nargs->syncaddr->buf) {
432 			ASSERT(nargs->syncaddr->len);
433 			kmem_free(nargs->syncaddr->buf, nargs->syncaddr->len);
434 		}
435 		kmem_free(nargs->syncaddr, sizeof (struct netbuf));
436 		nargs->syncaddr = NULL;
437 	}
438 
439 	if (nargs->netname) {
440 		kmem_free(nargs->netname, strlen(nargs->netname) + 1);
441 		nargs->netname = NULL;
442 	}
443 
444 	if (nargs->nfs_ext_u.nfs_extA.secdata) {
445 		sec_clnt_freeinfo(
446 		    nargs->nfs_ext_u.nfs_extA.secdata);
447 		nargs->nfs_ext_u.nfs_extA.secdata = NULL;
448 	}
449 }
450 
451 
452 int
453 nfs4_copyin(char *data, int datalen, struct nfs_args *nargs)
454 {
455 
456 	int error;
457 	size_t hlen;			/* length of hostname */
458 	size_t nlen;			/* length of netname */
459 	char netname[MAXNETNAMELEN+1];	/* server's netname */
460 	struct netbuf addr;		/* server's address */
461 	struct netbuf syncaddr;		/* AUTH_DES time sync addr */
462 	struct knetconfig *knconf;		/* transport structure */
463 	struct sec_data *secdata = NULL;	/* security data */
464 	STRUCT_DECL(nfs_args, args);		/* nfs mount arguments */
465 	STRUCT_DECL(knetconfig, knconf_tmp);
466 	STRUCT_DECL(netbuf, addr_tmp);
467 	int flags;
468 	char *p, *pf;
469 	struct pathname pn;
470 	char *userbufptr;
471 
472 
473 	bzero(nargs, sizeof (*nargs));
474 
475 	STRUCT_INIT(args, get_udatamodel());
476 	bzero(STRUCT_BUF(args), SIZEOF_STRUCT(nfs_args, DATAMODEL_NATIVE));
477 	if (copyin(data, STRUCT_BUF(args), MIN(datalen,
478 	    STRUCT_SIZE(args))))
479 		return (EFAULT);
480 
481 	nargs->wsize = STRUCT_FGET(args, wsize);
482 	nargs->rsize = STRUCT_FGET(args, rsize);
483 	nargs->timeo = STRUCT_FGET(args, timeo);
484 	nargs->retrans = STRUCT_FGET(args, retrans);
485 	nargs->acregmin = STRUCT_FGET(args, acregmin);
486 	nargs->acregmax = STRUCT_FGET(args, acregmax);
487 	nargs->acdirmin = STRUCT_FGET(args, acdirmin);
488 	nargs->acdirmax = STRUCT_FGET(args, acdirmax);
489 
490 	flags = STRUCT_FGET(args, flags);
491 	nargs->flags = flags;
492 
493 	addr.buf = NULL;
494 	syncaddr.buf = NULL;
495 
496 
497 	/*
498 	 * Allocate space for a knetconfig structure and
499 	 * its strings and copy in from user-land.
500 	 */
501 	knconf = kmem_zalloc(sizeof (*knconf), KM_SLEEP);
502 	STRUCT_INIT(knconf_tmp, get_udatamodel());
503 	if (copyin(STRUCT_FGETP(args, knconf), STRUCT_BUF(knconf_tmp),
504 	    STRUCT_SIZE(knconf_tmp))) {
505 		kmem_free(knconf, sizeof (*knconf));
506 		return (EFAULT);
507 	}
508 
509 	knconf->knc_semantics = STRUCT_FGET(knconf_tmp, knc_semantics);
510 	knconf->knc_protofmly = STRUCT_FGETP(knconf_tmp, knc_protofmly);
511 	knconf->knc_proto = STRUCT_FGETP(knconf_tmp, knc_proto);
512 	if (get_udatamodel() != DATAMODEL_LP64) {
513 		knconf->knc_rdev = expldev(STRUCT_FGET(knconf_tmp, knc_rdev));
514 	} else {
515 		knconf->knc_rdev = STRUCT_FGET(knconf_tmp, knc_rdev);
516 	}
517 
518 	pf = kmem_alloc(KNC_STRSIZE, KM_SLEEP);
519 	p = kmem_alloc(KNC_STRSIZE, KM_SLEEP);
520 	error = copyinstr(knconf->knc_protofmly, pf, KNC_STRSIZE, NULL);
521 	if (error) {
522 		kmem_free(pf, KNC_STRSIZE);
523 		kmem_free(p, KNC_STRSIZE);
524 		kmem_free(knconf, sizeof (*knconf));
525 		return (error);
526 	}
527 
528 	error = copyinstr(knconf->knc_proto, p, KNC_STRSIZE, NULL);
529 	if (error) {
530 		kmem_free(pf, KNC_STRSIZE);
531 		kmem_free(p, KNC_STRSIZE);
532 		kmem_free(knconf, sizeof (*knconf));
533 		return (error);
534 	}
535 
536 
537 	knconf->knc_protofmly = pf;
538 	knconf->knc_proto = p;
539 
540 	nargs->knconf = knconf;
541 
542 	/*
543 	 * Get server address
544 	 */
545 	STRUCT_INIT(addr_tmp, get_udatamodel());
546 	if (copyin(STRUCT_FGETP(args, addr), STRUCT_BUF(addr_tmp),
547 	    STRUCT_SIZE(addr_tmp))) {
548 		error = EFAULT;
549 		goto errout;
550 	}
551 
552 	nargs->addr = kmem_alloc(sizeof (struct netbuf), KM_SLEEP);
553 	userbufptr = STRUCT_FGETP(addr_tmp, buf);
554 	addr.len = STRUCT_FGET(addr_tmp, len);
555 	addr.buf = kmem_alloc(addr.len, KM_SLEEP);
556 	addr.maxlen = addr.len;
557 	if (copyin(userbufptr, addr.buf, addr.len)) {
558 		kmem_free(addr.buf, addr.len);
559 		error = EFAULT;
560 		goto errout;
561 	}
562 	bcopy(&addr, nargs->addr, sizeof (struct netbuf));
563 
564 	/*
565 	 * Get the root fhandle
566 	 */
567 	error = pn_get(STRUCT_FGETP(args, fh), UIO_USERSPACE, &pn);
568 	if (error)
569 		goto errout;
570 
571 	/* Volatile fh: keep server paths, so use actual-size strings */
572 	nargs->fh = kmem_alloc(pn.pn_pathlen + 1, KM_SLEEP);
573 	bcopy(pn.pn_path, nargs->fh, pn.pn_pathlen);
574 	nargs->fh[pn.pn_pathlen] = '\0';
575 	pn_free(&pn);
576 
577 
578 	/*
579 	 * Get server's hostname
580 	 */
581 	if (flags & NFSMNT_HOSTNAME) {
582 		error = copyinstr(STRUCT_FGETP(args, hostname),
583 		    netname, sizeof (netname), &hlen);
584 		if (error)
585 			goto errout;
586 		nargs->hostname = kmem_zalloc(hlen, KM_SLEEP);
587 		(void) strcpy(nargs->hostname, netname);
588 
589 	} else {
590 		nargs->hostname = NULL;
591 	}
592 
593 
594 	/*
595 	 * If there are syncaddr and netname data, load them in. This is
596 	 * to support data needed for NFSV4 when AUTH_DH is the negotiated
597 	 * flavor via SECINFO. (instead of using MOUNT protocol in V3).
598 	 */
599 	netname[0] = '\0';
600 	if (flags & NFSMNT_SECURE) {
601 
602 		/* get syncaddr */
603 		STRUCT_INIT(addr_tmp, get_udatamodel());
604 		if (copyin(STRUCT_FGETP(args, syncaddr), STRUCT_BUF(addr_tmp),
605 		    STRUCT_SIZE(addr_tmp))) {
606 			error = EINVAL;
607 			goto errout;
608 		}
609 		userbufptr = STRUCT_FGETP(addr_tmp, buf);
610 		syncaddr.len = STRUCT_FGET(addr_tmp, len);
611 		syncaddr.buf = kmem_alloc(syncaddr.len, KM_SLEEP);
612 		syncaddr.maxlen = syncaddr.len;
613 		if (copyin(userbufptr, syncaddr.buf, syncaddr.len)) {
614 			kmem_free(syncaddr.buf, syncaddr.len);
615 			error = EFAULT;
616 			goto errout;
617 		}
618 
619 		nargs->syncaddr = kmem_alloc(sizeof (struct netbuf), KM_SLEEP);
620 		bcopy(&syncaddr, nargs->syncaddr, sizeof (struct netbuf));
621 
622 		/* get server's netname */
623 		if (copyinstr(STRUCT_FGETP(args, netname), netname,
624 		    sizeof (netname), &nlen)) {
625 			error = EFAULT;
626 			goto errout;
627 		}
628 
629 		netname[nlen] = '\0';
630 		nargs->netname = kmem_zalloc(nlen, KM_SLEEP);
631 		(void) strcpy(nargs->netname, netname);
632 	}
633 
634 	/*
635 	 * Get the extention data which has the security data structure.
636 	 * This includes data for AUTH_SYS as well.
637 	 */
638 	if (flags & NFSMNT_NEWARGS) {
639 		nargs->nfs_args_ext = STRUCT_FGET(args, nfs_args_ext);
640 		if (nargs->nfs_args_ext == NFS_ARGS_EXTA ||
641 		    nargs->nfs_args_ext == NFS_ARGS_EXTB) {
642 			/*
643 			 * Indicating the application is using the new
644 			 * sec_data structure to pass in the security
645 			 * data.
646 			 */
647 			if (STRUCT_FGETP(args,
648 			    nfs_ext_u.nfs_extA.secdata) != NULL) {
649 				error = sec_clnt_loadinfo(
650 				    (struct sec_data *)STRUCT_FGETP(args,
651 				    nfs_ext_u.nfs_extA.secdata),
652 				    &secdata, get_udatamodel());
653 			}
654 			nargs->nfs_ext_u.nfs_extA.secdata = secdata;
655 		}
656 	}
657 
658 	if (error)
659 		goto errout;
660 
661 	/*
662 	 * Failover support:
663 	 *
664 	 * We may have a linked list of nfs_args structures,
665 	 * which means the user is looking for failover.  If
666 	 * the mount is either not "read-only" or "soft",
667 	 * we want to bail out with EINVAL.
668 	 */
669 	if (nargs->nfs_args_ext == NFS_ARGS_EXTB)
670 		nargs->nfs_ext_u.nfs_extB.next =
671 		    STRUCT_FGETP(args, nfs_ext_u.nfs_extB.next);
672 
673 errout:
674 	if (error)
675 		nfs4_free_args(nargs);
676 
677 	return (error);
678 }
679 
680 
681 /*
682  * nfs mount vfsop
683  * Set up mount info record and attach it to vfs struct.
684  */
685 int
686 nfs4_mount(vfs_t *vfsp, vnode_t *mvp, struct mounta *uap, cred_t *cr)
687 {
688 	char *data = uap->dataptr;
689 	int error;
690 	vnode_t *rtvp;			/* the server's root */
691 	mntinfo4_t *mi;			/* mount info, pointed at by vfs */
692 	struct knetconfig *rdma_knconf;	/* rdma transport structure */
693 	rnode4_t *rp;
694 	struct servinfo4 *svp;		/* nfs server info */
695 	struct servinfo4 *svp_tail = NULL; /* previous nfs server info */
696 	struct servinfo4 *svp_head;	/* first nfs server info */
697 	struct servinfo4 *svp_2ndlast;	/* 2nd last in server info list */
698 	struct sec_data *secdata;	/* security data */
699 	struct nfs_args *args = NULL;
700 	int flags, addr_type, removed;
701 	zone_t *zone = nfs_zone();
702 	nfs4_error_t n4e;
703 	zone_t *mntzone = NULL;
704 
705 	if (secpolicy_fs_mount(cr, mvp, vfsp) != 0)
706 		return (EPERM);
707 	if (mvp->v_type != VDIR)
708 		return (ENOTDIR);
709 
710 	/*
711 	 * get arguments
712 	 *
713 	 * nfs_args is now versioned and is extensible, so
714 	 * uap->datalen might be different from sizeof (args)
715 	 * in a compatible situation.
716 	 */
717 more:
718 	if (!(uap->flags & MS_SYSSPACE)) {
719 		if (args == NULL)
720 			args = kmem_zalloc(sizeof (struct nfs_args), KM_SLEEP);
721 		else
722 			nfs4_free_args(args);
723 		error = nfs4_copyin(data, uap->datalen, args);
724 		if (error) {
725 			if (args) {
726 				kmem_free(args, sizeof (*args));
727 			}
728 			return (error);
729 		}
730 	} else {
731 		args = (struct nfs_args *)data;
732 	}
733 
734 	flags = args->flags;
735 
736 	/*
737 	 * If the request changes the locking type, disallow the remount,
738 	 * because it's questionable whether we can transfer the
739 	 * locking state correctly.
740 	 */
741 	if (uap->flags & MS_REMOUNT) {
742 		if (!(uap->flags & MS_SYSSPACE)) {
743 			nfs4_free_args(args);
744 			kmem_free(args, sizeof (*args));
745 		}
746 		if ((mi = VFTOMI4(vfsp)) != NULL) {
747 			uint_t new_mi_llock;
748 			uint_t old_mi_llock;
749 			new_mi_llock = (flags & NFSMNT_LLOCK) ? 1 : 0;
750 			old_mi_llock = (mi->mi_flags & MI4_LLOCK) ? 1 : 0;
751 			if (old_mi_llock != new_mi_llock)
752 				return (EBUSY);
753 		}
754 		return (0);
755 	}
756 
757 	/*
758 	 * For ephemeral mount trigger stub vnodes, we have two problems
759 	 * to solve: racing threads will likely fail the v_count check, and
760 	 * we want only one to proceed with the mount.
761 	 *
762 	 * For stubs, if the mount has already occurred (via a racing thread),
763 	 * just return success. If not, skip the v_count check and proceed.
764 	 * Note that we are already serialised at this point.
765 	 */
766 	mutex_enter(&mvp->v_lock);
767 	if (vn_matchops(mvp, nfs4_trigger_vnodeops)) {
768 		/* mntpt is a v4 stub vnode */
769 		ASSERT(RP_ISSTUB(VTOR4(mvp)));
770 		ASSERT(!(uap->flags & MS_OVERLAY));
771 		ASSERT(!(mvp->v_flag & VROOT));
772 		if (vn_mountedvfs(mvp) != NULL) {
773 			/* ephemeral mount has already occurred */
774 			ASSERT(uap->flags & MS_SYSSPACE);
775 			mutex_exit(&mvp->v_lock);
776 			return (0);
777 		}
778 	} else {
779 		/* mntpt is a non-v4 or v4 non-stub vnode */
780 		if (!(uap->flags & MS_OVERLAY) &&
781 		    (mvp->v_count != 1 || (mvp->v_flag & VROOT))) {
782 			mutex_exit(&mvp->v_lock);
783 			if (!(uap->flags & MS_SYSSPACE)) {
784 				nfs4_free_args(args);
785 				kmem_free(args, sizeof (*args));
786 			}
787 			return (EBUSY);
788 		}
789 	}
790 	mutex_exit(&mvp->v_lock);
791 
792 	/* make sure things are zeroed for errout: */
793 	rtvp = NULL;
794 	mi = NULL;
795 	secdata = NULL;
796 
797 	/*
798 	 * A valid knetconfig structure is required.
799 	 */
800 	if (!(flags & NFSMNT_KNCONF) ||
801 	    args->knconf == NULL || args->knconf->knc_protofmly == NULL ||
802 	    args->knconf->knc_proto == NULL ||
803 	    (strcmp(args->knconf->knc_proto, NC_UDP) == 0)) {
804 		if (!(uap->flags & MS_SYSSPACE)) {
805 			nfs4_free_args(args);
806 			kmem_free(args, sizeof (*args));
807 		}
808 		return (EINVAL);
809 	}
810 
811 	if ((strlen(args->knconf->knc_protofmly) >= KNC_STRSIZE) ||
812 	    (strlen(args->knconf->knc_proto) >= KNC_STRSIZE)) {
813 		if (!(uap->flags & MS_SYSSPACE)) {
814 			nfs4_free_args(args);
815 			kmem_free(args, sizeof (*args));
816 		}
817 		return (EINVAL);
818 	}
819 
820 	/*
821 	 * Allocate a servinfo4 struct.
822 	 */
823 	svp = kmem_zalloc(sizeof (*svp), KM_SLEEP);
824 	nfs_rw_init(&svp->sv_lock, NULL, RW_DEFAULT, NULL);
825 	if (svp_tail) {
826 		svp_2ndlast = svp_tail;
827 		svp_tail->sv_next = svp;
828 	} else {
829 		svp_head = svp;
830 		svp_2ndlast = svp;
831 	}
832 
833 	svp_tail = svp;
834 	svp->sv_knconf = args->knconf;
835 	args->knconf = NULL;
836 
837 	/*
838 	 * Get server address
839 	 */
840 	if (args->addr == NULL || args->addr->buf == NULL) {
841 		error = EINVAL;
842 		goto errout;
843 	}
844 
845 	svp->sv_addr.maxlen = args->addr->maxlen;
846 	svp->sv_addr.len = args->addr->len;
847 	svp->sv_addr.buf = args->addr->buf;
848 	args->addr->buf = NULL;
849 
850 	/*
851 	 * Get the root fhandle
852 	 */
853 	if (args->fh == NULL || (strlen(args->fh) >= MAXPATHLEN)) {
854 		error = EINVAL;
855 		goto errout;
856 	}
857 
858 	svp->sv_path = args->fh;
859 	svp->sv_pathlen = strlen(args->fh) + 1;
860 	args->fh = NULL;
861 
862 	/*
863 	 * Get server's hostname
864 	 */
865 	if (flags & NFSMNT_HOSTNAME) {
866 		if (args->hostname == NULL || (strlen(args->hostname) >
867 		    MAXNETNAMELEN)) {
868 			error = EINVAL;
869 			goto errout;
870 		}
871 		svp->sv_hostnamelen = strlen(args->hostname) + 1;
872 		svp->sv_hostname = args->hostname;
873 		args->hostname = NULL;
874 	} else {
875 		char *p = "unknown-host";
876 		svp->sv_hostnamelen = strlen(p) + 1;
877 		svp->sv_hostname = kmem_zalloc(svp->sv_hostnamelen, KM_SLEEP);
878 		(void) strcpy(svp->sv_hostname, p);
879 	}
880 
881 	/*
882 	 * RDMA MOUNT SUPPORT FOR NFS v4.
883 	 * Establish, is it possible to use RDMA, if so overload the
884 	 * knconf with rdma specific knconf and free the orignal knconf.
885 	 */
886 	if ((flags & NFSMNT_TRYRDMA) || (flags & NFSMNT_DORDMA)) {
887 		/*
888 		 * Determine the addr type for RDMA, IPv4 or v6.
889 		 */
890 		if (strcmp(svp->sv_knconf->knc_protofmly, NC_INET) == 0)
891 			addr_type = AF_INET;
892 		else if (strcmp(svp->sv_knconf->knc_protofmly, NC_INET6) == 0)
893 			addr_type = AF_INET6;
894 
895 		if (rdma_reachable(addr_type, &svp->sv_addr,
896 		    &rdma_knconf) == 0) {
897 			/*
898 			 * If successful, hijack the orignal knconf and
899 			 * replace with the new one, depending on the flags.
900 			 */
901 			svp->sv_origknconf = svp->sv_knconf;
902 			svp->sv_knconf = rdma_knconf;
903 		} else {
904 			if (flags & NFSMNT_TRYRDMA) {
905 #ifdef	DEBUG
906 				if (rdma_debug)
907 					zcmn_err(getzoneid(), CE_WARN,
908 					    "no RDMA onboard, revert\n");
909 #endif
910 			}
911 
912 			if (flags & NFSMNT_DORDMA) {
913 				/*
914 				 * If proto=rdma is specified and no RDMA
915 				 * path to this server is avialable then
916 				 * ditch this server.
917 				 * This is not included in the mountable
918 				 * server list or the replica list.
919 				 * Check if more servers are specified;
920 				 * Failover case, otherwise bail out of mount.
921 				 */
922 				if (args->nfs_args_ext == NFS_ARGS_EXTB &&
923 				    args->nfs_ext_u.nfs_extB.next != NULL) {
924 					data = (char *)
925 					    args->nfs_ext_u.nfs_extB.next;
926 					if (uap->flags & MS_RDONLY &&
927 					    !(flags & NFSMNT_SOFT)) {
928 						if (svp_head->sv_next == NULL) {
929 							svp_tail = NULL;
930 							svp_2ndlast = NULL;
931 							sv4_free(svp_head);
932 							goto more;
933 						} else {
934 							svp_tail = svp_2ndlast;
935 							svp_2ndlast->sv_next =
936 							    NULL;
937 							sv4_free(svp);
938 							goto more;
939 						}
940 					}
941 				} else {
942 					/*
943 					 * This is the last server specified
944 					 * in the nfs_args list passed down
945 					 * and its not rdma capable.
946 					 */
947 					if (svp_head->sv_next == NULL) {
948 						/*
949 						 * Is this the only one
950 						 */
951 						error = EINVAL;
952 #ifdef	DEBUG
953 						if (rdma_debug)
954 							zcmn_err(getzoneid(),
955 							    CE_WARN,
956 							    "No RDMA srv");
957 #endif
958 						goto errout;
959 					} else {
960 						/*
961 						 * There is list, since some
962 						 * servers specified before
963 						 * this passed all requirements
964 						 */
965 						svp_tail = svp_2ndlast;
966 						svp_2ndlast->sv_next = NULL;
967 						sv4_free(svp);
968 						goto proceed;
969 					}
970 				}
971 			}
972 		}
973 	}
974 
975 	/*
976 	 * If there are syncaddr and netname data, load them in. This is
977 	 * to support data needed for NFSV4 when AUTH_DH is the negotiated
978 	 * flavor via SECINFO. (instead of using MOUNT protocol in V3).
979 	 */
980 	if (args->flags & NFSMNT_SECURE) {
981 		svp->sv_dhsec = create_authdh_data(args->netname,
982 		    strlen(args->netname),
983 		    args->syncaddr, svp->sv_knconf);
984 	}
985 
986 	/*
987 	 * Get the extention data which has the security data structure.
988 	 * This includes data for AUTH_SYS as well.
989 	 */
990 	if (flags & NFSMNT_NEWARGS) {
991 		switch (args->nfs_args_ext) {
992 		case NFS_ARGS_EXTA:
993 		case NFS_ARGS_EXTB:
994 			/*
995 			 * Indicating the application is using the new
996 			 * sec_data structure to pass in the security
997 			 * data.
998 			 */
999 			secdata = args->nfs_ext_u.nfs_extA.secdata;
1000 			if (secdata == NULL) {
1001 				error = EINVAL;
1002 			} else if (uap->flags & MS_SYSSPACE) {
1003 				/*
1004 				 * Need to validate the flavor here if
1005 				 * sysspace, userspace was already
1006 				 * validate from the nfs_copyin function.
1007 				 */
1008 				switch (secdata->rpcflavor) {
1009 				case AUTH_NONE:
1010 				case AUTH_UNIX:
1011 				case AUTH_LOOPBACK:
1012 				case AUTH_DES:
1013 				case RPCSEC_GSS:
1014 					break;
1015 				default:
1016 					error = EINVAL;
1017 					goto errout;
1018 				}
1019 			}
1020 			args->nfs_ext_u.nfs_extA.secdata = NULL;
1021 			break;
1022 
1023 		default:
1024 			error = EINVAL;
1025 			break;
1026 		}
1027 
1028 	} else if (flags & NFSMNT_SECURE) {
1029 		/*
1030 		 * NFSMNT_SECURE is deprecated but we keep it
1031 		 * to support the rogue user-generated application
1032 		 * that may use this undocumented interface to do
1033 		 * AUTH_DH security, e.g. our own rexd.
1034 		 *
1035 		 * Also note that NFSMNT_SECURE is used for passing
1036 		 * AUTH_DH info to be used in negotiation.
1037 		 */
1038 		secdata = create_authdh_data(args->netname,
1039 		    strlen(args->netname), args->syncaddr, svp->sv_knconf);
1040 
1041 	} else {
1042 		secdata = kmem_alloc(sizeof (*secdata), KM_SLEEP);
1043 		secdata->secmod = secdata->rpcflavor = AUTH_SYS;
1044 		secdata->data = NULL;
1045 	}
1046 
1047 	svp->sv_secdata = secdata;
1048 
1049 	/*
1050 	 * User does not explictly specify a flavor, and a user
1051 	 * defined default flavor is passed down.
1052 	 */
1053 	if (flags & NFSMNT_SECDEFAULT) {
1054 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
1055 		svp->sv_flags |= SV4_TRYSECDEFAULT;
1056 		nfs_rw_exit(&svp->sv_lock);
1057 	}
1058 
1059 	/*
1060 	 * Failover support:
1061 	 *
1062 	 * We may have a linked list of nfs_args structures,
1063 	 * which means the user is looking for failover.  If
1064 	 * the mount is either not "read-only" or "soft",
1065 	 * we want to bail out with EINVAL.
1066 	 */
1067 	if (args->nfs_args_ext == NFS_ARGS_EXTB &&
1068 	    args->nfs_ext_u.nfs_extB.next != NULL) {
1069 		if (uap->flags & MS_RDONLY && !(flags & NFSMNT_SOFT)) {
1070 			data = (char *)args->nfs_ext_u.nfs_extB.next;
1071 			goto more;
1072 		}
1073 		error = EINVAL;
1074 		goto errout;
1075 	}
1076 
1077 	/*
1078 	 * Determine the zone we're being mounted into.
1079 	 */
1080 	zone_hold(mntzone = zone);		/* start with this assumption */
1081 	if (getzoneid() == GLOBAL_ZONEID) {
1082 		zone_rele(mntzone);
1083 		mntzone = zone_find_by_path(refstr_value(vfsp->vfs_mntpt));
1084 		ASSERT(mntzone != NULL);
1085 		if (mntzone != zone) {
1086 			error = EBUSY;
1087 			goto errout;
1088 		}
1089 	}
1090 
1091 	if (is_system_labeled()) {
1092 		error = nfs_mount_label_policy(vfsp, &svp->sv_addr,
1093 		    svp->sv_knconf, cr);
1094 
1095 		if (error > 0)
1096 			goto errout;
1097 
1098 		if (error == -1) {
1099 			/* change mount to read-only to prevent write-down */
1100 			vfs_setmntopt(vfsp, MNTOPT_RO, NULL, 0);
1101 		}
1102 	}
1103 
1104 	/*
1105 	 * Stop the mount from going any further if the zone is going away.
1106 	 */
1107 	if (zone_status_get(mntzone) >= ZONE_IS_SHUTTING_DOWN) {
1108 		error = EBUSY;
1109 		goto errout;
1110 	}
1111 
1112 	/*
1113 	 * Get root vnode.
1114 	 */
1115 proceed:
1116 	error = nfs4rootvp(&rtvp, vfsp, svp_head, flags, cr, mntzone);
1117 	if (error) {
1118 		/* if nfs4rootvp failed, it will free svp_head */
1119 		svp_head = NULL;
1120 		goto errout;
1121 	}
1122 
1123 	mi = VTOMI4(rtvp);
1124 
1125 	/*
1126 	 * Send client id to the server, if necessary
1127 	 */
1128 	nfs4_error_zinit(&n4e);
1129 	nfs4setclientid(mi, cr, FALSE, &n4e);
1130 
1131 	error = n4e.error;
1132 
1133 	if (error)
1134 		goto errout;
1135 
1136 	/*
1137 	 * Set option fields in the mount info record
1138 	 */
1139 
1140 	if (svp_head->sv_next) {
1141 		mutex_enter(&mi->mi_lock);
1142 		mi->mi_flags |= MI4_LLOCK;
1143 		mutex_exit(&mi->mi_lock);
1144 	}
1145 	error = nfs4_setopts(rtvp, DATAMODEL_NATIVE, args);
1146 	if (error)
1147 		goto errout;
1148 
1149 	/*
1150 	 * Time to tie in the mirror mount info at last!
1151 	 */
1152 	if (flags & NFSMNT_EPHEMERAL)
1153 		error = nfs4_record_ephemeral_mount(mi, mvp);
1154 
1155 errout:
1156 	if (error) {
1157 		if (rtvp != NULL) {
1158 			rp = VTOR4(rtvp);
1159 			if (rp->r_flags & R4HASHED)
1160 				rp4_rmhash(rp);
1161 		}
1162 		if (mi != NULL) {
1163 			nfs4_async_stop(vfsp);
1164 			nfs4_async_manager_stop(vfsp);
1165 			nfs4_remove_mi_from_server(mi, NULL);
1166 			if (rtvp != NULL)
1167 				VN_RELE(rtvp);
1168 			if (mntzone != NULL)
1169 				zone_rele(mntzone);
1170 			/* need to remove it from the zone */
1171 			removed = nfs4_mi_zonelist_remove(mi);
1172 			if (removed)
1173 				zone_rele(mi->mi_zone);
1174 			MI4_RELE(mi);
1175 			if (!(uap->flags & MS_SYSSPACE) && args) {
1176 				nfs4_free_args(args);
1177 				kmem_free(args, sizeof (*args));
1178 			}
1179 			return (error);
1180 		}
1181 		if (svp_head)
1182 			sv4_free(svp_head);
1183 	}
1184 
1185 	if (!(uap->flags & MS_SYSSPACE) && args) {
1186 		nfs4_free_args(args);
1187 		kmem_free(args, sizeof (*args));
1188 	}
1189 	if (rtvp != NULL)
1190 		VN_RELE(rtvp);
1191 
1192 	if (mntzone != NULL)
1193 		zone_rele(mntzone);
1194 
1195 	return (error);
1196 }
1197 
1198 #ifdef  DEBUG
1199 #define	VERS_MSG	"NFS4 server "
1200 #else
1201 #define	VERS_MSG	"NFS server "
1202 #endif
1203 
1204 #define	READ_MSG        \
1205 	VERS_MSG "%s returned 0 for read transfer size"
1206 #define	WRITE_MSG       \
1207 	VERS_MSG "%s returned 0 for write transfer size"
1208 #define	SIZE_MSG        \
1209 	VERS_MSG "%s returned 0 for maximum file size"
1210 
1211 /*
1212  * Get the symbolic link text from the server for a given filehandle
1213  * of that symlink.
1214  *
1215  *      (get symlink text) PUTFH READLINK
1216  */
1217 static int
1218 getlinktext_otw(mntinfo4_t *mi, nfs_fh4 *fh, char **linktextp, cred_t *cr,
1219     int flags)
1220 {
1221 	COMPOUND4args_clnt args;
1222 	COMPOUND4res_clnt res;
1223 	int doqueue;
1224 	nfs_argop4 argop[2];
1225 	nfs_resop4 *resop;
1226 	READLINK4res *lr_res;
1227 	uint_t len;
1228 	bool_t needrecov = FALSE;
1229 	nfs4_recov_state_t recov_state;
1230 	nfs4_sharedfh_t *sfh;
1231 	nfs4_error_t e;
1232 	int num_retry = nfs4_max_mount_retry;
1233 	int recovery = !(flags & NFS4_GETFH_NEEDSOP);
1234 
1235 	sfh = sfh4_get(fh, mi);
1236 	recov_state.rs_flags = 0;
1237 	recov_state.rs_num_retry_despite_err = 0;
1238 
1239 recov_retry:
1240 	nfs4_error_zinit(&e);
1241 
1242 	args.array_len = 2;
1243 	args.array = argop;
1244 	args.ctag = TAG_GET_SYMLINK;
1245 
1246 	if (! recovery) {
1247 		e.error = nfs4_start_op(mi, NULL, NULL, &recov_state);
1248 		if (e.error) {
1249 			sfh4_rele(&sfh);
1250 			return (e.error);
1251 		}
1252 	}
1253 
1254 	/* 0. putfh symlink fh */
1255 	argop[0].argop = OP_CPUTFH;
1256 	argop[0].nfs_argop4_u.opcputfh.sfh = sfh;
1257 
1258 	/* 1. readlink */
1259 	argop[1].argop = OP_READLINK;
1260 
1261 	doqueue = 1;
1262 
1263 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
1264 
1265 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
1266 
1267 	if (needrecov && !recovery && num_retry-- > 0) {
1268 
1269 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1270 		    "getlinktext_otw: initiating recovery\n"));
1271 
1272 		if (nfs4_start_recovery(&e, mi, NULL, NULL, NULL, NULL,
1273 		    OP_READLINK, NULL) == FALSE) {
1274 			nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
1275 			if (!e.error)
1276 				(void) xdr_free(xdr_COMPOUND4res_clnt,
1277 				    (caddr_t)&res);
1278 			goto recov_retry;
1279 		}
1280 	}
1281 
1282 	/*
1283 	 * If non-NFS4 pcol error and/or we weren't able to recover.
1284 	 */
1285 	if (e.error != 0) {
1286 		if (! recovery)
1287 			nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
1288 		sfh4_rele(&sfh);
1289 		return (e.error);
1290 	}
1291 
1292 	if (res.status) {
1293 		e.error = geterrno4(res.status);
1294 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1295 		if (! recovery)
1296 			nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
1297 		sfh4_rele(&sfh);
1298 		return (e.error);
1299 	}
1300 
1301 	/* res.status == NFS4_OK */
1302 	ASSERT(res.status == NFS4_OK);
1303 
1304 	resop = &res.array[1];  /* readlink res */
1305 	lr_res = &resop->nfs_resop4_u.opreadlink;
1306 
1307 	/* treat symlink name as data */
1308 	*linktextp = utf8_to_str(&lr_res->link, &len, NULL);
1309 
1310 	if (! recovery)
1311 		nfs4_end_op(mi, NULL, NULL, &recov_state, needrecov);
1312 	sfh4_rele(&sfh);
1313 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1314 	return (0);
1315 }
1316 
1317 /*
1318  * Skip over consecutive slashes and "/./" in a pathname.
1319  */
1320 void
1321 pathname_skipslashdot(struct pathname *pnp)
1322 {
1323 	char *c1, *c2;
1324 
1325 	while (pnp->pn_pathlen > 0 && *pnp->pn_path == '/') {
1326 
1327 		c1 = pnp->pn_path + 1;
1328 		c2 = pnp->pn_path + 2;
1329 
1330 		if (*c1 == '.' && (*c2 == '/' || *c2 == '\0')) {
1331 			pnp->pn_path = pnp->pn_path + 2; /* skip "/." */
1332 			pnp->pn_pathlen = pnp->pn_pathlen - 2;
1333 		} else {
1334 			pnp->pn_path++;
1335 			pnp->pn_pathlen--;
1336 		}
1337 	}
1338 }
1339 
1340 /*
1341  * Resolve a symbolic link path. The symlink is in the nth component of
1342  * svp->sv_path and has an nfs4 file handle "fh".
1343  * Upon return, the sv_path will point to the new path that has the nth
1344  * component resolved to its symlink text.
1345  */
1346 int
1347 resolve_sympath(mntinfo4_t *mi, servinfo4_t *svp, int nth, nfs_fh4 *fh,
1348     cred_t *cr, int flags)
1349 {
1350 	char *oldpath;
1351 	char *symlink, *newpath;
1352 	struct pathname oldpn, newpn;
1353 	char component[MAXNAMELEN];
1354 	int i, addlen, error = 0;
1355 	int oldpathlen;
1356 
1357 	/* Get the symbolic link text over the wire. */
1358 	error = getlinktext_otw(mi, fh, &symlink, cr, flags);
1359 
1360 	if (error || symlink == NULL || strlen(symlink) == 0)
1361 		return (error);
1362 
1363 	/*
1364 	 * Compose the new pathname.
1365 	 * Note:
1366 	 *    - only the nth component is resolved for the pathname.
1367 	 *    - pathname.pn_pathlen does not count the ending null byte.
1368 	 */
1369 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1370 	oldpath = svp->sv_path;
1371 	oldpathlen = svp->sv_pathlen;
1372 	if (error = pn_get(oldpath, UIO_SYSSPACE, &oldpn)) {
1373 		nfs_rw_exit(&svp->sv_lock);
1374 		kmem_free(symlink, strlen(symlink) + 1);
1375 		return (error);
1376 	}
1377 	nfs_rw_exit(&svp->sv_lock);
1378 	pn_alloc(&newpn);
1379 
1380 	/*
1381 	 * Skip over previous components from the oldpath so that the
1382 	 * oldpn.pn_path will point to the symlink component. Skip
1383 	 * leading slashes and "/./" (no OP_LOOKUP on ".") so that
1384 	 * pn_getcompnent can get the component.
1385 	 */
1386 	for (i = 1; i < nth; i++) {
1387 		pathname_skipslashdot(&oldpn);
1388 		error = pn_getcomponent(&oldpn, component);
1389 		if (error)
1390 			goto out;
1391 	}
1392 
1393 	/*
1394 	 * Copy the old path upto the component right before the symlink
1395 	 * if the symlink is not an absolute path.
1396 	 */
1397 	if (symlink[0] != '/') {
1398 		addlen = oldpn.pn_path - oldpn.pn_buf;
1399 		bcopy(oldpn.pn_buf, newpn.pn_path, addlen);
1400 		newpn.pn_pathlen += addlen;
1401 		newpn.pn_path += addlen;
1402 		newpn.pn_buf[newpn.pn_pathlen] = '/';
1403 		newpn.pn_pathlen++;
1404 		newpn.pn_path++;
1405 	}
1406 
1407 	/* copy the resolved symbolic link text */
1408 	addlen = strlen(symlink);
1409 	if (newpn.pn_pathlen + addlen >= newpn.pn_bufsize) {
1410 		error = ENAMETOOLONG;
1411 		goto out;
1412 	}
1413 	bcopy(symlink, newpn.pn_path, addlen);
1414 	newpn.pn_pathlen += addlen;
1415 	newpn.pn_path += addlen;
1416 
1417 	/*
1418 	 * Check if there is any remaining path after the symlink component.
1419 	 * First, skip the symlink component.
1420 	 */
1421 	pathname_skipslashdot(&oldpn);
1422 	if (error = pn_getcomponent(&oldpn, component))
1423 		goto out;
1424 
1425 	addlen = pn_pathleft(&oldpn); /* includes counting the slash */
1426 
1427 	/*
1428 	 * Copy the remaining path to the new pathname if there is any.
1429 	 */
1430 	if (addlen > 0) {
1431 		if (newpn.pn_pathlen + addlen >= newpn.pn_bufsize) {
1432 			error = ENAMETOOLONG;
1433 			goto out;
1434 		}
1435 		bcopy(oldpn.pn_path, newpn.pn_path, addlen);
1436 		newpn.pn_pathlen += addlen;
1437 	}
1438 	newpn.pn_buf[newpn.pn_pathlen] = '\0';
1439 
1440 	/* get the newpath and store it in the servinfo4_t */
1441 	newpath = kmem_alloc(newpn.pn_pathlen + 1, KM_SLEEP);
1442 	bcopy(newpn.pn_buf, newpath, newpn.pn_pathlen);
1443 	newpath[newpn.pn_pathlen] = '\0';
1444 
1445 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
1446 	svp->sv_path = newpath;
1447 	svp->sv_pathlen = strlen(newpath) + 1;
1448 	nfs_rw_exit(&svp->sv_lock);
1449 
1450 	kmem_free(oldpath, oldpathlen);
1451 out:
1452 	kmem_free(symlink, strlen(symlink) + 1);
1453 	pn_free(&newpn);
1454 	pn_free(&oldpn);
1455 
1456 	return (error);
1457 }
1458 
1459 /*
1460  * Get the root filehandle for the given filesystem and server, and update
1461  * svp.
1462  *
1463  * If NFS4_GETFH_NEEDSOP is set, then use nfs4_start_fop and nfs4_end_fop
1464  * to coordinate with recovery.  Otherwise, the caller is assumed to be
1465  * the recovery thread or have already done a start_fop.
1466  *
1467  * Errors are returned by the nfs4_error_t parameter.
1468  */
1469 
1470 static void
1471 nfs4getfh_otw(struct mntinfo4 *mi, servinfo4_t *svp, vtype_t *vtp,
1472     int flags, cred_t *cr, nfs4_error_t *ep)
1473 {
1474 	COMPOUND4args_clnt args;
1475 	COMPOUND4res_clnt res;
1476 	int doqueue = 1;
1477 	nfs_argop4 *argop;
1478 	nfs_resop4 *resop;
1479 	nfs4_ga_res_t *garp;
1480 	int num_argops;
1481 	lookup4_param_t lookuparg;
1482 	nfs_fh4 *tmpfhp;
1483 	nfs_fh4 *resfhp;
1484 	bool_t needrecov = FALSE;
1485 	nfs4_recov_state_t recov_state;
1486 	int llndx;
1487 	int nthcomp;
1488 	int recovery = !(flags & NFS4_GETFH_NEEDSOP);
1489 
1490 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1491 	ASSERT(svp->sv_path != NULL);
1492 	if (svp->sv_path[0] == '\0') {
1493 		nfs_rw_exit(&svp->sv_lock);
1494 		nfs4_error_init(ep, EINVAL);
1495 		return;
1496 	}
1497 	nfs_rw_exit(&svp->sv_lock);
1498 
1499 	recov_state.rs_flags = 0;
1500 	recov_state.rs_num_retry_despite_err = 0;
1501 recov_retry:
1502 	nfs4_error_zinit(ep);
1503 
1504 	if (!recovery) {
1505 		ep->error = nfs4_start_fop(mi, NULL, NULL, OH_MOUNT,
1506 		    &recov_state, NULL);
1507 
1508 		/*
1509 		 * If recovery has been started and this request as
1510 		 * initiated by a mount, then we must wait for recovery
1511 		 * to finish before proceeding, otherwise, the error
1512 		 * cleanup would remove data structures needed by the
1513 		 * recovery thread.
1514 		 */
1515 		if (ep->error) {
1516 			mutex_enter(&mi->mi_lock);
1517 			if (mi->mi_flags & MI4_MOUNTING) {
1518 				mi->mi_flags |= MI4_RECOV_FAIL;
1519 				mi->mi_error = EIO;
1520 
1521 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1522 				    "nfs4getfh_otw: waiting 4 recovery\n"));
1523 
1524 				while (mi->mi_flags & MI4_RECOV_ACTIV)
1525 					cv_wait(&mi->mi_failover_cv,
1526 					    &mi->mi_lock);
1527 			}
1528 			mutex_exit(&mi->mi_lock);
1529 			return;
1530 		}
1531 
1532 		/*
1533 		 * If the client does not specify a specific flavor to use
1534 		 * and has not gotten a secinfo list from the server yet,
1535 		 * retrieve the secinfo list from the server and use a
1536 		 * flavor from the list to mount.
1537 		 *
1538 		 * If fail to get the secinfo list from the server, then
1539 		 * try the default flavor.
1540 		 */
1541 		if ((svp->sv_flags & SV4_TRYSECDEFAULT) &&
1542 		    svp->sv_secinfo == NULL) {
1543 			(void) nfs4_secinfo_path(mi, cr, FALSE);
1544 		}
1545 	}
1546 
1547 	if (recovery)
1548 		args.ctag = TAG_REMAP_MOUNT;
1549 	else
1550 		args.ctag = TAG_MOUNT;
1551 
1552 	lookuparg.l4_getattrs = LKP4_ALL_ATTRIBUTES;
1553 	lookuparg.argsp = &args;
1554 	lookuparg.resp = &res;
1555 	lookuparg.header_len = 2;	/* Putrootfh, getfh */
1556 	lookuparg.trailer_len = 0;
1557 	lookuparg.ga_bits = FATTR4_FSINFO_MASK;
1558 	lookuparg.mi = mi;
1559 
1560 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1561 	ASSERT(svp->sv_path != NULL);
1562 	llndx = nfs4lookup_setup(svp->sv_path, &lookuparg, 0);
1563 	nfs_rw_exit(&svp->sv_lock);
1564 
1565 	argop = args.array;
1566 	num_argops = args.array_len;
1567 
1568 	/* choose public or root filehandle */
1569 	if (flags & NFS4_GETFH_PUBLIC)
1570 		argop[0].argop = OP_PUTPUBFH;
1571 	else
1572 		argop[0].argop = OP_PUTROOTFH;
1573 
1574 	/* get fh */
1575 	argop[1].argop = OP_GETFH;
1576 
1577 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1578 	    "nfs4getfh_otw: %s call, mi 0x%p",
1579 	    needrecov ? "recov" : "first", (void *)mi));
1580 
1581 	rfs4call(mi, &args, &res, cr, &doqueue, RFSCALL_SOFT, ep);
1582 
1583 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
1584 
1585 	if (needrecov) {
1586 		bool_t abort;
1587 
1588 		if (recovery) {
1589 			nfs4args_lookup_free(argop, num_argops);
1590 			kmem_free(argop,
1591 			    lookuparg.arglen * sizeof (nfs_argop4));
1592 			if (!ep->error)
1593 				(void) xdr_free(xdr_COMPOUND4res_clnt,
1594 				    (caddr_t)&res);
1595 			return;
1596 		}
1597 
1598 		NFS4_DEBUG(nfs4_client_recov_debug,
1599 		    (CE_NOTE, "nfs4getfh_otw: initiating recovery\n"));
1600 
1601 		abort = nfs4_start_recovery(ep, mi, NULL,
1602 		    NULL, NULL, NULL, OP_GETFH, NULL);
1603 		if (!ep->error) {
1604 			ep->error = geterrno4(res.status);
1605 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1606 		}
1607 		nfs4args_lookup_free(argop, num_argops);
1608 		kmem_free(argop, lookuparg.arglen * sizeof (nfs_argop4));
1609 		nfs4_end_fop(mi, NULL, NULL, OH_MOUNT, &recov_state, needrecov);
1610 		/* have another go? */
1611 		if (abort == FALSE)
1612 			goto recov_retry;
1613 		return;
1614 	}
1615 
1616 	/*
1617 	 * No recovery, but check if error is set.
1618 	 */
1619 	if (ep->error)  {
1620 		nfs4args_lookup_free(argop, num_argops);
1621 		kmem_free(argop, lookuparg.arglen * sizeof (nfs_argop4));
1622 		if (!recovery)
1623 			nfs4_end_fop(mi, NULL, NULL, OH_MOUNT, &recov_state,
1624 			    needrecov);
1625 		return;
1626 	}
1627 
1628 is_link_err:
1629 
1630 	/* for non-recovery errors */
1631 	if (res.status && res.status != NFS4ERR_SYMLINK) {
1632 		if (!recovery) {
1633 			nfs4_end_fop(mi, NULL, NULL, OH_MOUNT, &recov_state,
1634 			    needrecov);
1635 		}
1636 		nfs4args_lookup_free(argop, num_argops);
1637 		kmem_free(argop, lookuparg.arglen * sizeof (nfs_argop4));
1638 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1639 		return;
1640 	}
1641 
1642 	/*
1643 	 * If any intermediate component in the path is a symbolic link,
1644 	 * resolve the symlink, then try mount again using the new path.
1645 	 */
1646 	if (res.status == NFS4ERR_SYMLINK) {
1647 		int where;
1648 
1649 		/*
1650 		 * This must be from OP_LOOKUP failure. The (cfh) for this
1651 		 * OP_LOOKUP is a symlink node. Found out where the
1652 		 * OP_GETFH is for the (cfh) that is a symlink node.
1653 		 *
1654 		 * Example:
1655 		 * (mount) PUTROOTFH, GETFH, LOOKUP comp1, GETFH, GETATTR,
1656 		 * LOOKUP comp2, GETFH, GETATTR, LOOKUP comp3, GETFH, GETATTR
1657 		 *
1658 		 * LOOKUP comp3 fails with SYMLINK because comp2 is a symlink.
1659 		 * In this case, where = 7, nthcomp = 2.
1660 		 */
1661 		where = res.array_len - 2;
1662 		ASSERT(where > 0);
1663 
1664 		resop = &res.array[where - 1];
1665 		ASSERT(resop->resop == OP_GETFH);
1666 		tmpfhp = &resop->nfs_resop4_u.opgetfh.object;
1667 		nthcomp = res.array_len/3 - 1;
1668 
1669 		/*
1670 		 * Need to call nfs4_end_op before resolve_sympath to avoid
1671 		 * potential nfs4_start_op deadlock.
1672 		 */
1673 		if (!recovery)
1674 			nfs4_end_fop(mi, NULL, NULL, OH_MOUNT, &recov_state,
1675 			    needrecov);
1676 
1677 		ep->error = resolve_sympath(mi, svp, nthcomp, tmpfhp, cr,
1678 		    flags);
1679 
1680 		nfs4args_lookup_free(argop, num_argops);
1681 		kmem_free(argop, lookuparg.arglen * sizeof (nfs_argop4));
1682 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1683 
1684 		if (ep->error)
1685 			return;
1686 
1687 		goto recov_retry;
1688 	}
1689 
1690 	/* getfh */
1691 	resop = &res.array[res.array_len - 2];
1692 	ASSERT(resop->resop == OP_GETFH);
1693 	resfhp = &resop->nfs_resop4_u.opgetfh.object;
1694 
1695 	/* getattr fsinfo res */
1696 	resop++;
1697 	garp = &resop->nfs_resop4_u.opgetattr.ga_res;
1698 
1699 	*vtp = garp->n4g_va.va_type;
1700 
1701 	mi->mi_fh_expire_type = garp->n4g_ext_res->n4g_fet;
1702 
1703 	mutex_enter(&mi->mi_lock);
1704 	if (garp->n4g_ext_res->n4g_pc4.pc4_link_support)
1705 		mi->mi_flags |= MI4_LINK;
1706 	if (garp->n4g_ext_res->n4g_pc4.pc4_symlink_support)
1707 		mi->mi_flags |= MI4_SYMLINK;
1708 	if (garp->n4g_ext_res->n4g_suppattrs & FATTR4_ACL_MASK)
1709 		mi->mi_flags |= MI4_ACL;
1710 	mutex_exit(&mi->mi_lock);
1711 
1712 	if (garp->n4g_ext_res->n4g_maxread == 0)
1713 		mi->mi_tsize =
1714 		    MIN(MAXBSIZE, mi->mi_tsize);
1715 	else
1716 		mi->mi_tsize =
1717 		    MIN(garp->n4g_ext_res->n4g_maxread,
1718 		    mi->mi_tsize);
1719 
1720 	if (garp->n4g_ext_res->n4g_maxwrite == 0)
1721 		mi->mi_stsize =
1722 		    MIN(MAXBSIZE, mi->mi_stsize);
1723 	else
1724 		mi->mi_stsize =
1725 		    MIN(garp->n4g_ext_res->n4g_maxwrite,
1726 		    mi->mi_stsize);
1727 
1728 	if (garp->n4g_ext_res->n4g_maxfilesize != 0)
1729 		mi->mi_maxfilesize =
1730 		    MIN(garp->n4g_ext_res->n4g_maxfilesize,
1731 		    mi->mi_maxfilesize);
1732 
1733 	/*
1734 	 * If the final component is a a symbolic link, resolve the symlink,
1735 	 * then try mount again using the new path.
1736 	 *
1737 	 * Assume no symbolic link for root filesysm "/".
1738 	 */
1739 	if (*vtp == VLNK) {
1740 		/*
1741 		 * nthcomp is the total result length minus
1742 		 * the 1st 2 OPs (PUTROOTFH, GETFH),
1743 		 * then divided by 3 (LOOKUP,GETFH,GETATTR)
1744 		 *
1745 		 * e.g. PUTROOTFH GETFH LOOKUP 1st-comp GETFH GETATTR
1746 		 *	LOOKUP 2nd-comp GETFH GETATTR
1747 		 *
1748 		 *	(8 - 2)/3 = 2
1749 		 */
1750 		nthcomp = (res.array_len - 2)/3;
1751 
1752 		/*
1753 		 * Need to call nfs4_end_op before resolve_sympath to avoid
1754 		 * potential nfs4_start_op deadlock. See RFE 4777612.
1755 		 */
1756 		if (!recovery)
1757 			nfs4_end_fop(mi, NULL, NULL, OH_MOUNT, &recov_state,
1758 			    needrecov);
1759 
1760 		ep->error = resolve_sympath(mi, svp, nthcomp, resfhp, cr,
1761 		    flags);
1762 
1763 		nfs4args_lookup_free(argop, num_argops);
1764 		kmem_free(argop, lookuparg.arglen * sizeof (nfs_argop4));
1765 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1766 
1767 		if (ep->error)
1768 			return;
1769 
1770 		goto recov_retry;
1771 	}
1772 
1773 	/*
1774 	 * We need to figure out where in the compound the getfh
1775 	 * for the parent directory is. If the object to be mounted is
1776 	 * the root, then there is no lookup at all:
1777 	 * PUTROOTFH, GETFH.
1778 	 * If the object to be mounted is in the root, then the compound is:
1779 	 * PUTROOTFH, GETFH, LOOKUP, GETFH, GETATTR.
1780 	 * In either of these cases, the index of the GETFH is 1.
1781 	 * If it is not at the root, then it's something like:
1782 	 * PUTROOTFH, GETFH, LOOKUP, GETFH, GETATTR,
1783 	 * LOOKUP, GETFH, GETATTR
1784 	 * In this case, the index is llndx (last lookup index) - 2.
1785 	 */
1786 	if (llndx == -1 || llndx == 2)
1787 		resop = &res.array[1];
1788 	else {
1789 		ASSERT(llndx > 2);
1790 		resop = &res.array[llndx-2];
1791 	}
1792 
1793 	ASSERT(resop->resop == OP_GETFH);
1794 	tmpfhp = &resop->nfs_resop4_u.opgetfh.object;
1795 
1796 	/* save the filehandles for the replica */
1797 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
1798 	ASSERT(tmpfhp->nfs_fh4_len <= NFS4_FHSIZE);
1799 	svp->sv_pfhandle.fh_len = tmpfhp->nfs_fh4_len;
1800 	bcopy(tmpfhp->nfs_fh4_val, svp->sv_pfhandle.fh_buf,
1801 	    tmpfhp->nfs_fh4_len);
1802 	ASSERT(resfhp->nfs_fh4_len <= NFS4_FHSIZE);
1803 	svp->sv_fhandle.fh_len = resfhp->nfs_fh4_len;
1804 	bcopy(resfhp->nfs_fh4_val, svp->sv_fhandle.fh_buf, resfhp->nfs_fh4_len);
1805 
1806 	/* initialize fsid and supp_attrs for server fs */
1807 	svp->sv_fsid = garp->n4g_fsid;
1808 	svp->sv_supp_attrs =
1809 	    garp->n4g_ext_res->n4g_suppattrs | FATTR4_MANDATTR_MASK;
1810 
1811 	nfs_rw_exit(&svp->sv_lock);
1812 
1813 	nfs4args_lookup_free(argop, num_argops);
1814 	kmem_free(argop, lookuparg.arglen * sizeof (nfs_argop4));
1815 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1816 	if (!recovery)
1817 		nfs4_end_fop(mi, NULL, NULL, OH_MOUNT, &recov_state, needrecov);
1818 }
1819 
1820 static ushort_t nfs4_max_threads = 8;	/* max number of active async threads */
1821 static uint_t nfs4_bsize = 32 * 1024;	/* client `block' size */
1822 static uint_t nfs4_async_clusters = 1;	/* # of reqs from each async queue */
1823 static uint_t nfs4_cots_timeo = NFS_COTS_TIMEO;
1824 
1825 /*
1826  * Remap the root filehandle for the given filesystem.
1827  *
1828  * results returned via the nfs4_error_t parameter.
1829  */
1830 void
1831 nfs4_remap_root(mntinfo4_t *mi, nfs4_error_t *ep, int flags)
1832 {
1833 	struct servinfo4 *svp;
1834 	vtype_t vtype;
1835 	nfs_fh4 rootfh;
1836 	int getfh_flags;
1837 	char *orig_sv_path;
1838 	int orig_sv_pathlen, num_retry;
1839 
1840 	mutex_enter(&mi->mi_lock);
1841 
1842 remap_retry:
1843 	svp = mi->mi_curr_serv;
1844 	getfh_flags =
1845 	    (flags & NFS4_REMAP_NEEDSOP) ? NFS4_GETFH_NEEDSOP : 0;
1846 	getfh_flags |=
1847 	    (mi->mi_flags & MI4_PUBLIC) ? NFS4_GETFH_PUBLIC : 0;
1848 	mutex_exit(&mi->mi_lock);
1849 
1850 	/*
1851 	 * Just in case server path being mounted contains
1852 	 * symlinks and fails w/STALE, save the initial sv_path
1853 	 * so we can redrive the initial mount compound with the
1854 	 * initial sv_path -- not a symlink-expanded version.
1855 	 *
1856 	 * This could only happen if a symlink was expanded
1857 	 * and the expanded mount compound failed stale.  Because
1858 	 * it could be the case that the symlink was removed at
1859 	 * the server (and replaced with another symlink/dir,
1860 	 * we need to use the initial sv_path when attempting
1861 	 * to re-lookup everything and recover.
1862 	 */
1863 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1864 	orig_sv_pathlen = svp->sv_pathlen;
1865 	orig_sv_path = kmem_alloc(orig_sv_pathlen, KM_SLEEP);
1866 	bcopy(svp->sv_path, orig_sv_path, orig_sv_pathlen);
1867 	nfs_rw_exit(&svp->sv_lock);
1868 
1869 	num_retry = nfs4_max_mount_retry;
1870 
1871 	do {
1872 		/*
1873 		 * Get the root fh from the server.  Retry nfs4_max_mount_retry
1874 		 * (2) times if it fails with STALE since the recovery
1875 		 * infrastructure doesn't do STALE recovery for components
1876 		 * of the server path to the object being mounted.
1877 		 */
1878 		nfs4getfh_otw(mi, svp, &vtype, getfh_flags, CRED(), ep);
1879 
1880 		if (ep->error == 0 && ep->stat == NFS4_OK)
1881 			break;
1882 
1883 		/*
1884 		 * For some reason, the mount compound failed.  Before
1885 		 * retrying, we need to restore the original sv_path
1886 		 * because it might have contained symlinks that were
1887 		 * expanded by nfsgetfh_otw before the failure occurred.
1888 		 * replace current sv_path with orig sv_path -- just in case
1889 		 * it changed due to embedded symlinks.
1890 		 */
1891 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1892 		if (orig_sv_pathlen != svp->sv_pathlen) {
1893 			kmem_free(svp->sv_path, svp->sv_pathlen);
1894 			svp->sv_path = kmem_alloc(orig_sv_pathlen, KM_SLEEP);
1895 			svp->sv_pathlen = orig_sv_pathlen;
1896 		}
1897 		bcopy(orig_sv_path, svp->sv_path, orig_sv_pathlen);
1898 		nfs_rw_exit(&svp->sv_lock);
1899 
1900 	} while (num_retry-- > 0);
1901 
1902 	kmem_free(orig_sv_path, orig_sv_pathlen);
1903 
1904 	if (ep->error != 0 || ep->stat != 0) {
1905 		return;
1906 	}
1907 
1908 	if (vtype != VNON && vtype != mi->mi_type) {
1909 		/* shouldn't happen */
1910 		zcmn_err(mi->mi_zone->zone_id, CE_WARN,
1911 		    "nfs4_remap_root: server root vnode type (%d) doesn't "
1912 		    "match mount info (%d)", vtype, mi->mi_type);
1913 	}
1914 
1915 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1916 	rootfh.nfs_fh4_val = svp->sv_fhandle.fh_buf;
1917 	rootfh.nfs_fh4_len = svp->sv_fhandle.fh_len;
1918 	nfs_rw_exit(&svp->sv_lock);
1919 	sfh4_update(mi->mi_rootfh, &rootfh);
1920 
1921 	/*
1922 	 * It's possible that recovery took place on the filesystem
1923 	 * and the server has been updated between the time we did
1924 	 * the nfs4getfh_otw and now. Re-drive the otw operation
1925 	 * to make sure we have a good fh.
1926 	 */
1927 	mutex_enter(&mi->mi_lock);
1928 	if (mi->mi_curr_serv != svp)
1929 		goto remap_retry;
1930 
1931 	mutex_exit(&mi->mi_lock);
1932 }
1933 
1934 static int
1935 nfs4rootvp(vnode_t **rtvpp, vfs_t *vfsp, struct servinfo4 *svp_head,
1936     int flags, cred_t *cr, zone_t *zone)
1937 {
1938 	vnode_t *rtvp = NULL;
1939 	mntinfo4_t *mi;
1940 	dev_t nfs_dev;
1941 	int error = 0;
1942 	rnode4_t *rp;
1943 	int i;
1944 	struct vattr va;
1945 	vtype_t vtype = VNON;
1946 	vtype_t tmp_vtype = VNON;
1947 	struct servinfo4 *firstsvp = NULL, *svp = svp_head;
1948 	nfs4_oo_hash_bucket_t *bucketp;
1949 	nfs_fh4 fh;
1950 	char *droptext = "";
1951 	struct nfs_stats *nfsstatsp;
1952 	nfs4_fname_t *mfname;
1953 	nfs4_error_t e;
1954 	char *orig_sv_path;
1955 	int orig_sv_pathlen, num_retry, removed;
1956 	cred_t *lcr = NULL, *tcr = cr;
1957 
1958 	nfsstatsp = zone_getspecific(nfsstat_zone_key, nfs_zone());
1959 	ASSERT(nfsstatsp != NULL);
1960 
1961 	ASSERT(nfs_zone() == zone);
1962 	ASSERT(crgetref(cr));
1963 
1964 	/*
1965 	 * Create a mount record and link it to the vfs struct.
1966 	 */
1967 	mi = kmem_zalloc(sizeof (*mi), KM_SLEEP);
1968 	mutex_init(&mi->mi_lock, NULL, MUTEX_DEFAULT, NULL);
1969 	nfs_rw_init(&mi->mi_recovlock, NULL, RW_DEFAULT, NULL);
1970 	nfs_rw_init(&mi->mi_rename_lock, NULL, RW_DEFAULT, NULL);
1971 	nfs_rw_init(&mi->mi_fh_lock, NULL, RW_DEFAULT, NULL);
1972 
1973 	if (!(flags & NFSMNT_SOFT))
1974 		mi->mi_flags |= MI4_HARD;
1975 	if ((flags & NFSMNT_NOPRINT))
1976 		mi->mi_flags |= MI4_NOPRINT;
1977 	if (flags & NFSMNT_INT)
1978 		mi->mi_flags |= MI4_INT;
1979 	if (flags & NFSMNT_PUBLIC)
1980 		mi->mi_flags |= MI4_PUBLIC;
1981 	if (flags & NFSMNT_MIRRORMOUNT)
1982 		mi->mi_flags |= MI4_MIRRORMOUNT;
1983 	mi->mi_retrans = NFS_RETRIES;
1984 	if (svp->sv_knconf->knc_semantics == NC_TPI_COTS_ORD ||
1985 	    svp->sv_knconf->knc_semantics == NC_TPI_COTS)
1986 		mi->mi_timeo = nfs4_cots_timeo;
1987 	else
1988 		mi->mi_timeo = NFS_TIMEO;
1989 	mi->mi_prog = NFS_PROGRAM;
1990 	mi->mi_vers = NFS_V4;
1991 	mi->mi_rfsnames = rfsnames_v4;
1992 	mi->mi_reqs = nfsstatsp->nfs_stats_v4.rfsreqcnt_ptr;
1993 	cv_init(&mi->mi_failover_cv, NULL, CV_DEFAULT, NULL);
1994 	mi->mi_servers = svp;
1995 	mi->mi_curr_serv = svp;
1996 	mi->mi_acregmin = SEC2HR(ACREGMIN);
1997 	mi->mi_acregmax = SEC2HR(ACREGMAX);
1998 	mi->mi_acdirmin = SEC2HR(ACDIRMIN);
1999 	mi->mi_acdirmax = SEC2HR(ACDIRMAX);
2000 	mi->mi_fh_expire_type = FH4_PERSISTENT;
2001 	mi->mi_clientid_next = NULL;
2002 	mi->mi_clientid_prev = NULL;
2003 	mi->mi_grace_wait = 0;
2004 	mi->mi_error = 0;
2005 	mi->mi_srvsettime = 0;
2006 
2007 	mi->mi_count = 1;
2008 
2009 	mi->mi_tsize = nfs4_tsize(svp->sv_knconf);
2010 	mi->mi_stsize = mi->mi_tsize;
2011 
2012 	if (flags & NFSMNT_DIRECTIO)
2013 		mi->mi_flags |= MI4_DIRECTIO;
2014 
2015 	mi->mi_flags |= MI4_MOUNTING;
2016 
2017 	/*
2018 	 * Make a vfs struct for nfs.  We do this here instead of below
2019 	 * because rtvp needs a vfs before we can do a getattr on it.
2020 	 *
2021 	 * Assign a unique device id to the mount
2022 	 */
2023 	mutex_enter(&nfs_minor_lock);
2024 	do {
2025 		nfs_minor = (nfs_minor + 1) & MAXMIN32;
2026 		nfs_dev = makedevice(nfs_major, nfs_minor);
2027 	} while (vfs_devismounted(nfs_dev));
2028 	mutex_exit(&nfs_minor_lock);
2029 
2030 	vfsp->vfs_dev = nfs_dev;
2031 	vfs_make_fsid(&vfsp->vfs_fsid, nfs_dev, nfs4fstyp);
2032 	vfsp->vfs_data = (caddr_t)mi;
2033 	vfsp->vfs_fstype = nfsfstyp;
2034 	vfsp->vfs_bsize = nfs4_bsize;
2035 
2036 	/*
2037 	 * Initialize fields used to support async putpage operations.
2038 	 */
2039 	for (i = 0; i < NFS4_ASYNC_TYPES; i++)
2040 		mi->mi_async_clusters[i] = nfs4_async_clusters;
2041 	mi->mi_async_init_clusters = nfs4_async_clusters;
2042 	mi->mi_async_curr = &mi->mi_async_reqs[0];
2043 	mi->mi_max_threads = nfs4_max_threads;
2044 	mutex_init(&mi->mi_async_lock, NULL, MUTEX_DEFAULT, NULL);
2045 	cv_init(&mi->mi_async_reqs_cv, NULL, CV_DEFAULT, NULL);
2046 	cv_init(&mi->mi_async_work_cv, NULL, CV_DEFAULT, NULL);
2047 	cv_init(&mi->mi_async_cv, NULL, CV_DEFAULT, NULL);
2048 	cv_init(&mi->mi_inact_req_cv, NULL, CV_DEFAULT, NULL);
2049 
2050 	mi->mi_vfsp = vfsp;
2051 	zone_hold(mi->mi_zone = zone);
2052 	nfs4_mi_zonelist_add(mi);
2053 
2054 	/*
2055 	 * Initialize the <open owner/cred> hash table.
2056 	 */
2057 	for (i = 0; i < NFS4_NUM_OO_BUCKETS; i++) {
2058 		bucketp = &(mi->mi_oo_list[i]);
2059 		mutex_init(&bucketp->b_lock, NULL, MUTEX_DEFAULT, NULL);
2060 		list_create(&bucketp->b_oo_hash_list,
2061 		    sizeof (nfs4_open_owner_t),
2062 		    offsetof(nfs4_open_owner_t, oo_hash_node));
2063 	}
2064 
2065 	/*
2066 	 * Initialize the freed open owner list.
2067 	 */
2068 	mi->mi_foo_num = 0;
2069 	mi->mi_foo_max = NFS4_NUM_FREED_OPEN_OWNERS;
2070 	list_create(&mi->mi_foo_list, sizeof (nfs4_open_owner_t),
2071 	    offsetof(nfs4_open_owner_t, oo_foo_node));
2072 
2073 	list_create(&mi->mi_lost_state, sizeof (nfs4_lost_rqst_t),
2074 	    offsetof(nfs4_lost_rqst_t, lr_node));
2075 
2076 	list_create(&mi->mi_bseqid_list, sizeof (nfs4_bseqid_entry_t),
2077 	    offsetof(nfs4_bseqid_entry_t, bs_node));
2078 
2079 	/*
2080 	 * Initialize the msg buffer.
2081 	 */
2082 	list_create(&mi->mi_msg_list, sizeof (nfs4_debug_msg_t),
2083 	    offsetof(nfs4_debug_msg_t, msg_node));
2084 	mi->mi_msg_count = 0;
2085 	mutex_init(&mi->mi_msg_list_lock, NULL, MUTEX_DEFAULT, NULL);
2086 
2087 	/*
2088 	 * Initialize kstats
2089 	 */
2090 	nfs4_mnt_kstat_init(vfsp);
2091 
2092 	/*
2093 	 * Initialize the shared filehandle pool, and get the fname for
2094 	 * the filesystem root.
2095 	 */
2096 	sfh4_createtab(&mi->mi_filehandles);
2097 	mi->mi_fname = fn_get(NULL, ".");
2098 
2099 	/*
2100 	 * Save server path we're attempting to mount.
2101 	 */
2102 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
2103 	orig_sv_pathlen = svp_head->sv_pathlen;
2104 	orig_sv_path = kmem_alloc(svp_head->sv_pathlen, KM_SLEEP);
2105 	bcopy(svp_head->sv_path, orig_sv_path, svp_head->sv_pathlen);
2106 	nfs_rw_exit(&svp->sv_lock);
2107 
2108 	/*
2109 	 * Make the GETFH call to get root fh for each replica.
2110 	 */
2111 	if (svp_head->sv_next)
2112 		droptext = ", dropping replica";
2113 
2114 	/*
2115 	 * If the uid is set then set the creds for secure mounts
2116 	 * by proxy processes such as automountd.
2117 	 */
2118 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
2119 	if (svp->sv_secdata->uid != 0) {
2120 		lcr = crdup(cr);
2121 		(void) crsetugid(lcr, svp->sv_secdata->uid, crgetgid(cr));
2122 		tcr = lcr;
2123 	}
2124 	nfs_rw_exit(&svp->sv_lock);
2125 	for (svp = svp_head; svp; svp = svp->sv_next) {
2126 		if (nfs4_chkdup_servinfo4(svp_head, svp)) {
2127 			nfs_cmn_err(error, CE_WARN,
2128 			    VERS_MSG "Host %s is a duplicate%s",
2129 			    svp->sv_hostname, droptext);
2130 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
2131 			svp->sv_flags |= SV4_NOTINUSE;
2132 			nfs_rw_exit(&svp->sv_lock);
2133 			continue;
2134 		}
2135 		mi->mi_curr_serv = svp;
2136 
2137 		/*
2138 		 * Just in case server path being mounted contains
2139 		 * symlinks and fails w/STALE, save the initial sv_path
2140 		 * so we can redrive the initial mount compound with the
2141 		 * initial sv_path -- not a symlink-expanded version.
2142 		 *
2143 		 * This could only happen if a symlink was expanded
2144 		 * and the expanded mount compound failed stale.  Because
2145 		 * it could be the case that the symlink was removed at
2146 		 * the server (and replaced with another symlink/dir,
2147 		 * we need to use the initial sv_path when attempting
2148 		 * to re-lookup everything and recover.
2149 		 *
2150 		 * Other mount errors should evenutally be handled here also
2151 		 * (NFS4ERR_DELAY, NFS4ERR_RESOURCE).  For now, all mount
2152 		 * failures will result in mount being redriven a few times.
2153 		 */
2154 		num_retry = nfs4_max_mount_retry;
2155 		do {
2156 			nfs4getfh_otw(mi, svp, &tmp_vtype,
2157 			    ((flags & NFSMNT_PUBLIC) ? NFS4_GETFH_PUBLIC : 0) |
2158 			    NFS4_GETFH_NEEDSOP, tcr, &e);
2159 
2160 			if (e.error == 0 && e.stat == NFS4_OK)
2161 				break;
2162 
2163 			/*
2164 			 * replace current sv_path with orig sv_path -- just in
2165 			 * case it changed due to embedded symlinks.
2166 			 */
2167 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
2168 			if (orig_sv_pathlen != svp->sv_pathlen) {
2169 				kmem_free(svp->sv_path, svp->sv_pathlen);
2170 				svp->sv_path = kmem_alloc(orig_sv_pathlen,
2171 				    KM_SLEEP);
2172 				svp->sv_pathlen = orig_sv_pathlen;
2173 			}
2174 			bcopy(orig_sv_path, svp->sv_path, orig_sv_pathlen);
2175 			nfs_rw_exit(&svp->sv_lock);
2176 
2177 		} while (num_retry-- > 0);
2178 
2179 		error = e.error ? e.error : geterrno4(e.stat);
2180 		if (error) {
2181 			nfs_cmn_err(error, CE_WARN,
2182 			    VERS_MSG "initial call to %s failed%s: %m",
2183 			    svp->sv_hostname, droptext);
2184 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
2185 			svp->sv_flags |= SV4_NOTINUSE;
2186 			nfs_rw_exit(&svp->sv_lock);
2187 			mi->mi_flags &= ~MI4_RECOV_FAIL;
2188 			mi->mi_error = 0;
2189 			continue;
2190 		}
2191 
2192 		if (tmp_vtype == VBAD) {
2193 			zcmn_err(mi->mi_zone->zone_id, CE_WARN,
2194 			    VERS_MSG "%s returned a bad file type for "
2195 			    "root%s", svp->sv_hostname, droptext);
2196 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
2197 			svp->sv_flags |= SV4_NOTINUSE;
2198 			nfs_rw_exit(&svp->sv_lock);
2199 			continue;
2200 		}
2201 
2202 		if (vtype == VNON) {
2203 			vtype = tmp_vtype;
2204 		} else if (vtype != tmp_vtype) {
2205 			zcmn_err(mi->mi_zone->zone_id, CE_WARN,
2206 			    VERS_MSG "%s returned a different file type "
2207 			    "for root%s", svp->sv_hostname, droptext);
2208 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
2209 			svp->sv_flags |= SV4_NOTINUSE;
2210 			nfs_rw_exit(&svp->sv_lock);
2211 			continue;
2212 		}
2213 		if (firstsvp == NULL)
2214 			firstsvp = svp;
2215 	}
2216 
2217 	kmem_free(orig_sv_path, orig_sv_pathlen);
2218 
2219 	if (firstsvp == NULL) {
2220 		if (error == 0)
2221 			error = ENOENT;
2222 		goto bad;
2223 	}
2224 
2225 	mi->mi_curr_serv = svp = firstsvp;
2226 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
2227 	ASSERT((mi->mi_curr_serv->sv_flags & SV4_NOTINUSE) == 0);
2228 	fh.nfs_fh4_len = svp->sv_fhandle.fh_len;
2229 	fh.nfs_fh4_val = svp->sv_fhandle.fh_buf;
2230 	mi->mi_rootfh = sfh4_get(&fh, mi);
2231 	fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
2232 	fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
2233 	mi->mi_srvparentfh = sfh4_get(&fh, mi);
2234 	nfs_rw_exit(&svp->sv_lock);
2235 
2236 	/*
2237 	 * Make the root vnode without attributes.
2238 	 */
2239 	mfname = mi->mi_fname;
2240 	fn_hold(mfname);
2241 	rtvp = makenfs4node_by_fh(mi->mi_rootfh, NULL,
2242 	    &mfname, NULL, mi, cr, gethrtime());
2243 	rtvp->v_type = vtype;
2244 
2245 	mi->mi_curread = mi->mi_tsize;
2246 	mi->mi_curwrite = mi->mi_stsize;
2247 
2248 	/*
2249 	 * Start the manager thread responsible for handling async worker
2250 	 * threads.
2251 	 */
2252 	MI4_HOLD(mi);
2253 	VFS_HOLD(vfsp);	/* add reference for thread */
2254 	mi->mi_manager_thread = zthread_create(NULL, 0, nfs4_async_manager,
2255 	    vfsp, 0, minclsyspri);
2256 	ASSERT(mi->mi_manager_thread != NULL);
2257 
2258 	/*
2259 	 * Create the thread that handles over-the-wire calls for
2260 	 * VOP_INACTIVE.
2261 	 * This needs to happen after the manager thread is created.
2262 	 */
2263 	MI4_HOLD(mi);
2264 	mi->mi_inactive_thread = zthread_create(NULL, 0, nfs4_inactive_thread,
2265 	    mi, 0, minclsyspri);
2266 	ASSERT(mi->mi_inactive_thread != NULL);
2267 
2268 	/* If we didn't get a type, get one now */
2269 	if (rtvp->v_type == VNON) {
2270 		va.va_mask = AT_TYPE;
2271 		error = nfs4getattr(rtvp, &va, tcr);
2272 		if (error)
2273 			goto bad;
2274 		rtvp->v_type = va.va_type;
2275 	}
2276 
2277 	mi->mi_type = rtvp->v_type;
2278 
2279 	mutex_enter(&mi->mi_lock);
2280 	mi->mi_flags &= ~MI4_MOUNTING;
2281 	mutex_exit(&mi->mi_lock);
2282 
2283 	*rtvpp = rtvp;
2284 	if (lcr != NULL)
2285 		crfree(lcr);
2286 
2287 	return (0);
2288 bad:
2289 	/*
2290 	 * An error occurred somewhere, need to clean up...
2291 	 */
2292 	if (lcr != NULL)
2293 		crfree(lcr);
2294 
2295 	if (rtvp != NULL) {
2296 		/*
2297 		 * We need to release our reference to the root vnode and
2298 		 * destroy the mntinfo4 struct that we just created.
2299 		 */
2300 		rp = VTOR4(rtvp);
2301 		if (rp->r_flags & R4HASHED)
2302 			rp4_rmhash(rp);
2303 		VN_RELE(rtvp);
2304 	}
2305 	nfs4_async_stop(vfsp);
2306 	nfs4_async_manager_stop(vfsp);
2307 	removed = nfs4_mi_zonelist_remove(mi);
2308 	if (removed)
2309 		zone_rele(mi->mi_zone);
2310 
2311 	/*
2312 	 * This releases the initial "hold" of the mi since it will never
2313 	 * be referenced by the vfsp.  Also, when mount returns to vfs.c
2314 	 * with an error, the vfsp will be destroyed, not rele'd.
2315 	 */
2316 	MI4_RELE(mi);
2317 
2318 	*rtvpp = NULL;
2319 	return (error);
2320 }
2321 
2322 /*
2323  * vfs operations
2324  */
2325 static int
2326 nfs4_unmount(vfs_t *vfsp, int flag, cred_t *cr)
2327 {
2328 	mntinfo4_t		*mi;
2329 	ushort_t		omax;
2330 	int			removed;
2331 
2332 	bool_t			must_unlock;
2333 	bool_t			must_rele;
2334 
2335 	nfs4_ephemeral_tree_t	*eph_tree;
2336 
2337 	if (secpolicy_fs_unmount(cr, vfsp) != 0)
2338 		return (EPERM);
2339 
2340 	mi = VFTOMI4(vfsp);
2341 
2342 	if (flag & MS_FORCE) {
2343 		vfsp->vfs_flag |= VFS_UNMOUNTED;
2344 		if (nfs_zone() != mi->mi_zone) {
2345 			/*
2346 			 * If the request is coming from the wrong zone,
2347 			 * we don't want to create any new threads, and
2348 			 * performance is not a concern.  Do everything
2349 			 * inline.
2350 			 */
2351 			NFS4_DEBUG(nfs4_client_zone_debug, (CE_NOTE,
2352 			    "nfs4_unmount x-zone forced unmount of vfs %p\n",
2353 			    (void *)vfsp));
2354 			nfs4_free_mount(vfsp, flag, cr);
2355 		} else {
2356 			/*
2357 			 * Free data structures asynchronously, to avoid
2358 			 * blocking the current thread (for performance
2359 			 * reasons only).
2360 			 */
2361 			async_free_mount(vfsp, flag, cr);
2362 		}
2363 
2364 		return (0);
2365 	}
2366 
2367 	/*
2368 	 * Wait until all asynchronous putpage operations on
2369 	 * this file system are complete before flushing rnodes
2370 	 * from the cache.
2371 	 */
2372 	omax = mi->mi_max_threads;
2373 	if (nfs4_async_stop_sig(vfsp))
2374 		return (EINTR);
2375 
2376 	r4flush(vfsp, cr);
2377 
2378 	/*
2379 	 * About the only reason that this would fail would be
2380 	 * that the harvester is already busy tearing down this
2381 	 * node. So we fail back to the caller and let them try
2382 	 * again when needed.
2383 	 */
2384 	if (nfs4_ephemeral_umount(mi, flag, cr,
2385 	    &must_unlock, &must_rele, &eph_tree)) {
2386 		ASSERT(must_unlock == FALSE);
2387 		mutex_enter(&mi->mi_async_lock);
2388 		mi->mi_max_threads = omax;
2389 		mutex_exit(&mi->mi_async_lock);
2390 
2391 		return (EBUSY);
2392 	}
2393 
2394 	/*
2395 	 * If there are any active vnodes on this file system,
2396 	 * then the file system is busy and can't be unmounted.
2397 	 */
2398 	if (check_rtable4(vfsp)) {
2399 		nfs4_ephemeral_umount_unlock(&must_unlock, &must_rele,
2400 		    &eph_tree);
2401 
2402 		mutex_enter(&mi->mi_async_lock);
2403 		mi->mi_max_threads = omax;
2404 		mutex_exit(&mi->mi_async_lock);
2405 
2406 		return (EBUSY);
2407 	}
2408 
2409 	/*
2410 	 * The unmount can't fail from now on, so record any
2411 	 * ephemeral changes.
2412 	 */
2413 	nfs4_ephemeral_umount_activate(mi, &must_unlock,
2414 	    &must_rele, &eph_tree);
2415 
2416 	/*
2417 	 * There are no active files that could require over-the-wire
2418 	 * calls to the server, so stop the async manager and the
2419 	 * inactive thread.
2420 	 */
2421 	nfs4_async_manager_stop(vfsp);
2422 
2423 	/*
2424 	 * Destroy all rnodes belonging to this file system from the
2425 	 * rnode hash queues and purge any resources allocated to
2426 	 * them.
2427 	 */
2428 	destroy_rtable4(vfsp, cr);
2429 	vfsp->vfs_flag |= VFS_UNMOUNTED;
2430 
2431 	nfs4_remove_mi_from_server(mi, NULL);
2432 	removed = nfs4_mi_zonelist_remove(mi);
2433 	if (removed)
2434 		zone_rele(mi->mi_zone);
2435 
2436 	return (0);
2437 }
2438 
2439 /*
2440  * find root of nfs
2441  */
2442 static int
2443 nfs4_root(vfs_t *vfsp, vnode_t **vpp)
2444 {
2445 	mntinfo4_t *mi;
2446 	vnode_t *vp;
2447 	nfs4_fname_t *mfname;
2448 	servinfo4_t *svp;
2449 
2450 	mi = VFTOMI4(vfsp);
2451 
2452 	if (nfs_zone() != mi->mi_zone)
2453 		return (EPERM);
2454 
2455 	svp = mi->mi_curr_serv;
2456 	if (svp) {
2457 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
2458 		if (svp->sv_flags & SV4_ROOT_STALE) {
2459 			nfs_rw_exit(&svp->sv_lock);
2460 
2461 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
2462 			if (svp->sv_flags & SV4_ROOT_STALE) {
2463 				svp->sv_flags &= ~SV4_ROOT_STALE;
2464 				nfs_rw_exit(&svp->sv_lock);
2465 				return (ENOENT);
2466 			}
2467 			nfs_rw_exit(&svp->sv_lock);
2468 		} else
2469 			nfs_rw_exit(&svp->sv_lock);
2470 	}
2471 
2472 	mfname = mi->mi_fname;
2473 	fn_hold(mfname);
2474 	vp = makenfs4node_by_fh(mi->mi_rootfh, NULL, &mfname, NULL,
2475 	    VFTOMI4(vfsp), CRED(), gethrtime());
2476 
2477 	if (VTOR4(vp)->r_flags & R4STALE) {
2478 		VN_RELE(vp);
2479 		return (ENOENT);
2480 	}
2481 
2482 	ASSERT(vp->v_type == VNON || vp->v_type == mi->mi_type);
2483 
2484 	vp->v_type = mi->mi_type;
2485 
2486 	*vpp = vp;
2487 
2488 	return (0);
2489 }
2490 
2491 static int
2492 nfs4_statfs_otw(vnode_t *vp, struct statvfs64 *sbp, cred_t *cr)
2493 {
2494 	int error;
2495 	nfs4_ga_res_t gar;
2496 	nfs4_ga_ext_res_t ger;
2497 
2498 	gar.n4g_ext_res = &ger;
2499 
2500 	if (error = nfs4_attr_otw(vp, TAG_FSINFO, &gar,
2501 	    NFS4_STATFS_ATTR_MASK, cr))
2502 		return (error);
2503 
2504 	*sbp = gar.n4g_ext_res->n4g_sb;
2505 
2506 	return (0);
2507 }
2508 
2509 /*
2510  * Get file system statistics.
2511  */
2512 static int
2513 nfs4_statvfs(vfs_t *vfsp, struct statvfs64 *sbp)
2514 {
2515 	int error;
2516 	vnode_t *vp;
2517 	cred_t *cr;
2518 
2519 	error = nfs4_root(vfsp, &vp);
2520 	if (error)
2521 		return (error);
2522 
2523 	cr = CRED();
2524 
2525 	error = nfs4_statfs_otw(vp, sbp, cr);
2526 	if (!error) {
2527 		(void) strncpy(sbp->f_basetype,
2528 		    vfssw[vfsp->vfs_fstype].vsw_name, FSTYPSZ);
2529 		sbp->f_flag = vf_to_stf(vfsp->vfs_flag);
2530 	} else {
2531 		nfs4_purge_stale_fh(error, vp, cr);
2532 	}
2533 
2534 	VN_RELE(vp);
2535 
2536 	return (error);
2537 }
2538 
2539 static kmutex_t nfs4_syncbusy;
2540 
2541 /*
2542  * Flush dirty nfs files for file system vfsp.
2543  * If vfsp == NULL, all nfs files are flushed.
2544  *
2545  * SYNC_CLOSE in flag is passed to us to
2546  * indicate that we are shutting down and or
2547  * rebooting.
2548  */
2549 static int
2550 nfs4_sync(vfs_t *vfsp, short flag, cred_t *cr)
2551 {
2552 	/*
2553 	 * Cross-zone calls are OK here, since this translates to a
2554 	 * VOP_PUTPAGE(B_ASYNC), which gets picked up by the right zone.
2555 	 */
2556 	if (!(flag & SYNC_ATTR) && mutex_tryenter(&nfs4_syncbusy) != 0) {
2557 		r4flush(vfsp, cr);
2558 		mutex_exit(&nfs4_syncbusy);
2559 	}
2560 
2561 	/*
2562 	 * if SYNC_CLOSE is set then we know that
2563 	 * the system is rebooting, mark the mntinfo
2564 	 * for later examination.
2565 	 */
2566 	if (vfsp && (flag & SYNC_CLOSE)) {
2567 		mntinfo4_t *mi;
2568 
2569 		mi = VFTOMI4(vfsp);
2570 		if (!(mi->mi_flags & MI4_SHUTDOWN)) {
2571 			mutex_enter(&mi->mi_lock);
2572 			mi->mi_flags |= MI4_SHUTDOWN;
2573 			mutex_exit(&mi->mi_lock);
2574 		}
2575 	}
2576 	return (0);
2577 }
2578 
2579 /*
2580  * vget is difficult, if not impossible, to support in v4 because we don't
2581  * know the parent directory or name, which makes it impossible to create a
2582  * useful shadow vnode.  And we need the shadow vnode for things like
2583  * OPEN.
2584  */
2585 
2586 /* ARGSUSED */
2587 /*
2588  * XXX Check nfs4_vget_pseudo() for dependency.
2589  */
2590 static int
2591 nfs4_vget(vfs_t *vfsp, vnode_t **vpp, fid_t *fidp)
2592 {
2593 	return (EREMOTE);
2594 }
2595 
2596 /*
2597  * nfs4_mountroot get called in the case where we are diskless booting.  All
2598  * we need from here is the ability to get the server info and from there we
2599  * can simply call nfs4_rootvp.
2600  */
2601 /* ARGSUSED */
2602 static int
2603 nfs4_mountroot(vfs_t *vfsp, whymountroot_t why)
2604 {
2605 	vnode_t *rtvp;
2606 	char root_hostname[SYS_NMLN+1];
2607 	struct servinfo4 *svp;
2608 	int error;
2609 	int vfsflags;
2610 	size_t size;
2611 	char *root_path;
2612 	struct pathname pn;
2613 	char *name;
2614 	cred_t *cr;
2615 	mntinfo4_t *mi;
2616 	struct nfs_args args;		/* nfs mount arguments */
2617 	static char token[10];
2618 	nfs4_error_t n4e;
2619 
2620 	bzero(&args, sizeof (args));
2621 
2622 	/* do this BEFORE getfile which causes xid stamps to be initialized */
2623 	clkset(-1L);		/* hack for now - until we get time svc? */
2624 
2625 	if (why == ROOT_REMOUNT) {
2626 		/*
2627 		 * Shouldn't happen.
2628 		 */
2629 		panic("nfs4_mountroot: why == ROOT_REMOUNT");
2630 	}
2631 
2632 	if (why == ROOT_UNMOUNT) {
2633 		/*
2634 		 * Nothing to do for NFS.
2635 		 */
2636 		return (0);
2637 	}
2638 
2639 	/*
2640 	 * why == ROOT_INIT
2641 	 */
2642 
2643 	name = token;
2644 	*name = 0;
2645 	(void) getfsname("root", name, sizeof (token));
2646 
2647 	pn_alloc(&pn);
2648 	root_path = pn.pn_path;
2649 
2650 	svp = kmem_zalloc(sizeof (*svp), KM_SLEEP);
2651 	nfs_rw_init(&svp->sv_lock, NULL, RW_DEFAULT, NULL);
2652 	svp->sv_knconf = kmem_zalloc(sizeof (*svp->sv_knconf), KM_SLEEP);
2653 	svp->sv_knconf->knc_protofmly = kmem_alloc(KNC_STRSIZE, KM_SLEEP);
2654 	svp->sv_knconf->knc_proto = kmem_alloc(KNC_STRSIZE, KM_SLEEP);
2655 
2656 	/*
2657 	 * Get server address
2658 	 * Get the root path
2659 	 * Get server's transport
2660 	 * Get server's hostname
2661 	 * Get options
2662 	 */
2663 	args.addr = &svp->sv_addr;
2664 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
2665 	args.fh = (char *)&svp->sv_fhandle;
2666 	args.knconf = svp->sv_knconf;
2667 	args.hostname = root_hostname;
2668 	vfsflags = 0;
2669 	if (error = mount_root(*name ? name : "root", root_path, NFS_V4,
2670 	    &args, &vfsflags)) {
2671 		if (error == EPROTONOSUPPORT)
2672 			nfs_cmn_err(error, CE_WARN, "nfs4_mountroot: "
2673 			    "mount_root failed: server doesn't support NFS V4");
2674 		else
2675 			nfs_cmn_err(error, CE_WARN,
2676 			    "nfs4_mountroot: mount_root failed: %m");
2677 		nfs_rw_exit(&svp->sv_lock);
2678 		sv4_free(svp);
2679 		pn_free(&pn);
2680 		return (error);
2681 	}
2682 	nfs_rw_exit(&svp->sv_lock);
2683 	svp->sv_hostnamelen = (int)(strlen(root_hostname) + 1);
2684 	svp->sv_hostname = kmem_alloc(svp->sv_hostnamelen, KM_SLEEP);
2685 	(void) strcpy(svp->sv_hostname, root_hostname);
2686 
2687 	svp->sv_pathlen = (int)(strlen(root_path) + 1);
2688 	svp->sv_path = kmem_alloc(svp->sv_pathlen, KM_SLEEP);
2689 	(void) strcpy(svp->sv_path, root_path);
2690 
2691 	/*
2692 	 * Force root partition to always be mounted with AUTH_UNIX for now
2693 	 */
2694 	svp->sv_secdata = kmem_alloc(sizeof (*svp->sv_secdata), KM_SLEEP);
2695 	svp->sv_secdata->secmod = AUTH_UNIX;
2696 	svp->sv_secdata->rpcflavor = AUTH_UNIX;
2697 	svp->sv_secdata->data = NULL;
2698 
2699 	cr = crgetcred();
2700 	rtvp = NULL;
2701 
2702 	error = nfs4rootvp(&rtvp, vfsp, svp, args.flags, cr, global_zone);
2703 
2704 	if (error) {
2705 		crfree(cr);
2706 		pn_free(&pn);
2707 		sv4_free(svp);
2708 		return (error);
2709 	}
2710 
2711 	mi = VTOMI4(rtvp);
2712 
2713 	/*
2714 	 * Send client id to the server, if necessary
2715 	 */
2716 	nfs4_error_zinit(&n4e);
2717 	nfs4setclientid(mi, cr, FALSE, &n4e);
2718 	error = n4e.error;
2719 
2720 	crfree(cr);
2721 
2722 	if (error) {
2723 		pn_free(&pn);
2724 		goto errout;
2725 	}
2726 
2727 	error = nfs4_setopts(rtvp, DATAMODEL_NATIVE, &args);
2728 	if (error) {
2729 		nfs_cmn_err(error, CE_WARN,
2730 		    "nfs4_mountroot: invalid root mount options");
2731 		pn_free(&pn);
2732 		goto errout;
2733 	}
2734 
2735 	(void) vfs_lock_wait(vfsp);
2736 	vfs_add(NULL, vfsp, vfsflags);
2737 	vfs_unlock(vfsp);
2738 
2739 	size = strlen(svp->sv_hostname);
2740 	(void) strcpy(rootfs.bo_name, svp->sv_hostname);
2741 	rootfs.bo_name[size] = ':';
2742 	(void) strcpy(&rootfs.bo_name[size + 1], root_path);
2743 
2744 	pn_free(&pn);
2745 
2746 errout:
2747 	if (error) {
2748 		sv4_free(svp);
2749 		nfs4_async_stop(vfsp);
2750 		nfs4_async_manager_stop(vfsp);
2751 	}
2752 
2753 	if (rtvp != NULL)
2754 		VN_RELE(rtvp);
2755 
2756 	return (error);
2757 }
2758 
2759 /*
2760  * Initialization routine for VFS routines.  Should only be called once
2761  */
2762 int
2763 nfs4_vfsinit(void)
2764 {
2765 	mutex_init(&nfs4_syncbusy, NULL, MUTEX_DEFAULT, NULL);
2766 	nfs4setclientid_init();
2767 	nfs4_ephemeral_init();
2768 	return (0);
2769 }
2770 
2771 void
2772 nfs4_vfsfini(void)
2773 {
2774 	nfs4_ephemeral_fini();
2775 	nfs4setclientid_fini();
2776 	mutex_destroy(&nfs4_syncbusy);
2777 }
2778 
2779 void
2780 nfs4_freevfs(vfs_t *vfsp)
2781 {
2782 	mntinfo4_t *mi;
2783 
2784 	/* need to release the initial hold */
2785 	mi = VFTOMI4(vfsp);
2786 	MI4_RELE(mi);
2787 }
2788 
2789 /*
2790  * Client side SETCLIENTID and SETCLIENTID_CONFIRM
2791  */
2792 struct nfs4_server nfs4_server_lst =
2793 	{ &nfs4_server_lst, &nfs4_server_lst };
2794 
2795 kmutex_t nfs4_server_lst_lock;
2796 
2797 static void
2798 nfs4setclientid_init(void)
2799 {
2800 	mutex_init(&nfs4_server_lst_lock, NULL, MUTEX_DEFAULT, NULL);
2801 }
2802 
2803 static void
2804 nfs4setclientid_fini(void)
2805 {
2806 	mutex_destroy(&nfs4_server_lst_lock);
2807 }
2808 
2809 int nfs4_retry_sclid_delay = NFS4_RETRY_SCLID_DELAY;
2810 int nfs4_num_sclid_retries = NFS4_NUM_SCLID_RETRIES;
2811 
2812 /*
2813  * Set the clientid for the server for "mi".  No-op if the clientid is
2814  * already set.
2815  *
2816  * The recovery boolean should be set to TRUE if this function was called
2817  * by the recovery code, and FALSE otherwise.  This is used to determine
2818  * if we need to call nfs4_start/end_op as well as grab the mi_recovlock
2819  * for adding a mntinfo4_t to a nfs4_server_t.
2820  *
2821  * Error is returned via 'n4ep'.  If there was a 'n4ep->stat' error, then
2822  * 'n4ep->error' is set to geterrno4(n4ep->stat).
2823  */
2824 void
2825 nfs4setclientid(mntinfo4_t *mi, cred_t *cr, bool_t recovery, nfs4_error_t *n4ep)
2826 {
2827 	struct nfs4_server *np;
2828 	struct servinfo4 *svp = mi->mi_curr_serv;
2829 	nfs4_recov_state_t recov_state;
2830 	int num_retries = 0;
2831 	bool_t retry;
2832 	cred_t *lcr = NULL;
2833 	int retry_inuse = 1; /* only retry once on NFS4ERR_CLID_INUSE */
2834 	time_t lease_time = 0;
2835 
2836 	recov_state.rs_flags = 0;
2837 	recov_state.rs_num_retry_despite_err = 0;
2838 	ASSERT(n4ep != NULL);
2839 
2840 recov_retry:
2841 	retry = FALSE;
2842 	nfs4_error_zinit(n4ep);
2843 	if (!recovery)
2844 		(void) nfs_rw_enter_sig(&mi->mi_recovlock, RW_READER, 0);
2845 
2846 	mutex_enter(&nfs4_server_lst_lock);
2847 	np = servinfo4_to_nfs4_server(svp); /* This locks np if it is found */
2848 	mutex_exit(&nfs4_server_lst_lock);
2849 	if (!np) {
2850 		struct nfs4_server *tnp;
2851 		np = new_nfs4_server(svp, cr);
2852 		mutex_enter(&np->s_lock);
2853 
2854 		mutex_enter(&nfs4_server_lst_lock);
2855 		tnp = servinfo4_to_nfs4_server(svp);
2856 		if (tnp) {
2857 			/*
2858 			 * another thread snuck in and put server on list.
2859 			 * since we aren't adding it to the nfs4_server_list
2860 			 * we need to set the ref count to 0 and destroy it.
2861 			 */
2862 			np->s_refcnt = 0;
2863 			destroy_nfs4_server(np);
2864 			np = tnp;
2865 		} else {
2866 			/*
2867 			 * do not give list a reference until everything
2868 			 * succeeds
2869 			 */
2870 			insque(np, &nfs4_server_lst);
2871 		}
2872 		mutex_exit(&nfs4_server_lst_lock);
2873 	}
2874 	ASSERT(MUTEX_HELD(&np->s_lock));
2875 	/*
2876 	 * If we find the server already has N4S_CLIENTID_SET, then
2877 	 * just return, we've already done SETCLIENTID to that server
2878 	 */
2879 	if (np->s_flags & N4S_CLIENTID_SET) {
2880 		/* add mi to np's mntinfo4_list */
2881 		nfs4_add_mi_to_server(np, mi);
2882 		if (!recovery)
2883 			nfs_rw_exit(&mi->mi_recovlock);
2884 		mutex_exit(&np->s_lock);
2885 		nfs4_server_rele(np);
2886 		return;
2887 	}
2888 	mutex_exit(&np->s_lock);
2889 
2890 
2891 	/*
2892 	 * Drop the mi_recovlock since nfs4_start_op will
2893 	 * acquire it again for us.
2894 	 */
2895 	if (!recovery) {
2896 		nfs_rw_exit(&mi->mi_recovlock);
2897 
2898 		n4ep->error = nfs4_start_op(mi, NULL, NULL, &recov_state);
2899 		if (n4ep->error) {
2900 			nfs4_server_rele(np);
2901 			return;
2902 		}
2903 	}
2904 
2905 	mutex_enter(&np->s_lock);
2906 	while (np->s_flags & N4S_CLIENTID_PEND) {
2907 		if (!cv_wait_sig(&np->s_clientid_pend, &np->s_lock)) {
2908 			mutex_exit(&np->s_lock);
2909 			nfs4_server_rele(np);
2910 			if (!recovery)
2911 				nfs4_end_op(mi, NULL, NULL, &recov_state,
2912 				    recovery);
2913 			n4ep->error = EINTR;
2914 			return;
2915 		}
2916 	}
2917 
2918 	if (np->s_flags & N4S_CLIENTID_SET) {
2919 		/* XXX copied/pasted from above */
2920 		/* add mi to np's mntinfo4_list */
2921 		nfs4_add_mi_to_server(np, mi);
2922 		mutex_exit(&np->s_lock);
2923 		nfs4_server_rele(np);
2924 		if (!recovery)
2925 			nfs4_end_op(mi, NULL, NULL, &recov_state, recovery);
2926 		return;
2927 	}
2928 
2929 	/*
2930 	 * Reset the N4S_CB_PINGED flag. This is used to
2931 	 * indicate if we have received a CB_NULL from the
2932 	 * server. Also we reset the waiter flag.
2933 	 */
2934 	np->s_flags &= ~(N4S_CB_PINGED | N4S_CB_WAITER);
2935 	/* any failure must now clear this flag */
2936 	np->s_flags |= N4S_CLIENTID_PEND;
2937 	mutex_exit(&np->s_lock);
2938 	nfs4setclientid_otw(mi, svp, cr, np, n4ep, &retry_inuse);
2939 
2940 	if (n4ep->error == EACCES) {
2941 		/*
2942 		 * If the uid is set then set the creds for secure mounts
2943 		 * by proxy processes such as automountd.
2944 		 */
2945 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
2946 		if (svp->sv_secdata->uid != 0) {
2947 			lcr = crdup(cr);
2948 			(void) crsetugid(lcr, svp->sv_secdata->uid,
2949 			    crgetgid(cr));
2950 		}
2951 		nfs_rw_exit(&svp->sv_lock);
2952 
2953 		if (lcr != NULL) {
2954 			mutex_enter(&np->s_lock);
2955 			crfree(np->s_cred);
2956 			np->s_cred = lcr;
2957 			mutex_exit(&np->s_lock);
2958 			nfs4setclientid_otw(mi, svp, lcr, np, n4ep,
2959 			    &retry_inuse);
2960 		}
2961 	}
2962 	mutex_enter(&np->s_lock);
2963 	lease_time = np->s_lease_time;
2964 	np->s_flags &= ~N4S_CLIENTID_PEND;
2965 	mutex_exit(&np->s_lock);
2966 
2967 	if (n4ep->error != 0 || n4ep->stat != NFS4_OK) {
2968 		/*
2969 		 * Start recovery if failover is a possibility.  If
2970 		 * invoked by the recovery thread itself, then just
2971 		 * return and let it handle the failover first.  NB:
2972 		 * recovery is not allowed if the mount is in progress
2973 		 * since the infrastructure is not sufficiently setup
2974 		 * to allow it.  Just return the error (after suitable
2975 		 * retries).
2976 		 */
2977 		if (FAILOVER_MOUNT4(mi) && nfs4_try_failover(n4ep)) {
2978 			(void) nfs4_start_recovery(n4ep, mi, NULL,
2979 			    NULL, NULL, NULL, OP_SETCLIENTID, NULL);
2980 			/*
2981 			 * Don't retry here, just return and let
2982 			 * recovery take over.
2983 			 */
2984 			if (recovery)
2985 				retry = FALSE;
2986 		} else if (nfs4_rpc_retry_error(n4ep->error) ||
2987 		    n4ep->stat == NFS4ERR_RESOURCE ||
2988 		    n4ep->stat == NFS4ERR_STALE_CLIENTID) {
2989 
2990 			retry = TRUE;
2991 			/*
2992 			 * Always retry if in recovery or once had
2993 			 * contact with the server (but now it's
2994 			 * overloaded).
2995 			 */
2996 			if (recovery == TRUE ||
2997 			    n4ep->error == ETIMEDOUT ||
2998 			    n4ep->error == ECONNRESET)
2999 				num_retries = 0;
3000 		} else if (retry_inuse && n4ep->error == 0 &&
3001 		    n4ep->stat == NFS4ERR_CLID_INUSE) {
3002 			retry = TRUE;
3003 			num_retries = 0;
3004 		}
3005 	} else {
3006 		/*
3007 		 * Since everything succeeded give the list a reference count if
3008 		 * it hasn't been given one by add_new_nfs4_server() or if this
3009 		 * is not a recovery situation in which case it is already on
3010 		 * the list.
3011 		 */
3012 		mutex_enter(&np->s_lock);
3013 		if ((np->s_flags & N4S_INSERTED) == 0) {
3014 			np->s_refcnt++;
3015 			np->s_flags |= N4S_INSERTED;
3016 		}
3017 		mutex_exit(&np->s_lock);
3018 	}
3019 
3020 	if (!recovery)
3021 		nfs4_end_op(mi, NULL, NULL, &recov_state, recovery);
3022 
3023 
3024 	if (retry && num_retries++ < nfs4_num_sclid_retries) {
3025 		if (retry_inuse) {
3026 			delay(SEC_TO_TICK(lease_time + nfs4_retry_sclid_delay));
3027 			retry_inuse = 0;
3028 		} else
3029 			delay(SEC_TO_TICK(nfs4_retry_sclid_delay));
3030 
3031 		nfs4_server_rele(np);
3032 		goto recov_retry;
3033 	}
3034 
3035 
3036 	if (n4ep->error == 0)
3037 		n4ep->error = geterrno4(n4ep->stat);
3038 
3039 	/* broadcast before release in case no other threads are waiting */
3040 	cv_broadcast(&np->s_clientid_pend);
3041 	nfs4_server_rele(np);
3042 }
3043 
3044 int nfs4setclientid_otw_debug = 0;
3045 
3046 /*
3047  * This function handles the recovery of STALE_CLIENTID for SETCLIENTID_CONFRIM,
3048  * but nothing else; the calling function must be designed to handle those
3049  * other errors.
3050  */
3051 static void
3052 nfs4setclientid_otw(mntinfo4_t *mi, struct servinfo4 *svp,  cred_t *cr,
3053     struct nfs4_server *np, nfs4_error_t *ep, int *retry_inusep)
3054 {
3055 	COMPOUND4args_clnt args;
3056 	COMPOUND4res_clnt res;
3057 	nfs_argop4 argop[3];
3058 	SETCLIENTID4args *s_args;
3059 	SETCLIENTID4resok *s_resok;
3060 	int doqueue = 1;
3061 	nfs4_ga_res_t *garp = NULL;
3062 	timespec_t prop_time, after_time;
3063 	verifier4 verf;
3064 	clientid4 tmp_clientid;
3065 
3066 	ASSERT(!MUTEX_HELD(&np->s_lock));
3067 
3068 	args.ctag = TAG_SETCLIENTID;
3069 
3070 	args.array = argop;
3071 	args.array_len = 3;
3072 
3073 	/* PUTROOTFH */
3074 	argop[0].argop = OP_PUTROOTFH;
3075 
3076 	/* GETATTR */
3077 	argop[1].argop = OP_GETATTR;
3078 	argop[1].nfs_argop4_u.opgetattr.attr_request = FATTR4_LEASE_TIME_MASK;
3079 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
3080 
3081 	/* SETCLIENTID */
3082 	argop[2].argop = OP_SETCLIENTID;
3083 
3084 	s_args = &argop[2].nfs_argop4_u.opsetclientid;
3085 
3086 	mutex_enter(&np->s_lock);
3087 
3088 	s_args->client.verifier = np->clidtosend.verifier;
3089 	s_args->client.id_len = np->clidtosend.id_len;
3090 	ASSERT(s_args->client.id_len <= NFS4_OPAQUE_LIMIT);
3091 	s_args->client.id_val = np->clidtosend.id_val;
3092 
3093 	/*
3094 	 * Callback needs to happen on non-RDMA transport
3095 	 * Check if we have saved the original knetconfig
3096 	 * if so, use that instead.
3097 	 */
3098 	if (svp->sv_origknconf != NULL)
3099 		nfs4_cb_args(np, svp->sv_origknconf, s_args);
3100 	else
3101 		nfs4_cb_args(np, svp->sv_knconf, s_args);
3102 
3103 	mutex_exit(&np->s_lock);
3104 
3105 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
3106 
3107 	if (ep->error)
3108 		return;
3109 
3110 	/* getattr lease_time res */
3111 	if (res.array_len >= 2) {
3112 		garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
3113 
3114 #ifndef _LP64
3115 		/*
3116 		 * The 32 bit client cannot handle a lease time greater than
3117 		 * (INT32_MAX/1000000).  This is due to the use of the
3118 		 * lease_time in calls to drv_usectohz() in
3119 		 * nfs4_renew_lease_thread().  The problem is that
3120 		 * drv_usectohz() takes a time_t (which is just a long = 4
3121 		 * bytes) as its parameter.  The lease_time is multiplied by
3122 		 * 1000000 to convert seconds to usecs for the parameter.  If
3123 		 * a number bigger than (INT32_MAX/1000000) is used then we
3124 		 * overflow on the 32bit client.
3125 		 */
3126 		if (garp->n4g_ext_res->n4g_leasetime > (INT32_MAX/1000000)) {
3127 			garp->n4g_ext_res->n4g_leasetime = INT32_MAX/1000000;
3128 		}
3129 #endif
3130 
3131 		mutex_enter(&np->s_lock);
3132 		np->s_lease_time = garp->n4g_ext_res->n4g_leasetime;
3133 
3134 		/*
3135 		 * Keep track of the lease period for the mi's
3136 		 * mi_msg_list.  We need an appropiate time
3137 		 * bound to associate past facts with a current
3138 		 * event.  The lease period is perfect for this.
3139 		 */
3140 		mutex_enter(&mi->mi_msg_list_lock);
3141 		mi->mi_lease_period = np->s_lease_time;
3142 		mutex_exit(&mi->mi_msg_list_lock);
3143 		mutex_exit(&np->s_lock);
3144 	}
3145 
3146 
3147 	if (res.status == NFS4ERR_CLID_INUSE) {
3148 		clientaddr4 *clid_inuse;
3149 
3150 		if (!(*retry_inusep)) {
3151 			clid_inuse = &res.array->nfs_resop4_u.
3152 			    opsetclientid.SETCLIENTID4res_u.client_using;
3153 
3154 			zcmn_err(mi->mi_zone->zone_id, CE_NOTE,
3155 			    "NFS4 mount (SETCLIENTID failed)."
3156 			    "  nfs4_client_id.id is in"
3157 			    "use already by: r_netid<%s> r_addr<%s>",
3158 			    clid_inuse->r_netid, clid_inuse->r_addr);
3159 		}
3160 
3161 		/*
3162 		 * XXX - The client should be more robust in its
3163 		 * handling of clientid in use errors (regen another
3164 		 * clientid and try again?)
3165 		 */
3166 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3167 		return;
3168 	}
3169 
3170 	if (res.status) {
3171 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3172 		return;
3173 	}
3174 
3175 	s_resok = &res.array[2].nfs_resop4_u.
3176 	    opsetclientid.SETCLIENTID4res_u.resok4;
3177 
3178 	tmp_clientid = s_resok->clientid;
3179 
3180 	verf = s_resok->setclientid_confirm;
3181 
3182 #ifdef	DEBUG
3183 	if (nfs4setclientid_otw_debug) {
3184 		union {
3185 			clientid4	clientid;
3186 			int		foo[2];
3187 		} cid;
3188 
3189 		cid.clientid = s_resok->clientid;
3190 
3191 		zcmn_err(mi->mi_zone->zone_id, CE_NOTE,
3192 		"nfs4setclientid_otw: OK, clientid = %x,%x, "
3193 		"verifier = %" PRIx64 "\n", cid.foo[0], cid.foo[1], verf);
3194 	}
3195 #endif
3196 
3197 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3198 
3199 	/* Confirm the client id and get the lease_time attribute */
3200 
3201 	args.ctag = TAG_SETCLIENTID_CF;
3202 
3203 	args.array = argop;
3204 	args.array_len = 1;
3205 
3206 	argop[0].argop = OP_SETCLIENTID_CONFIRM;
3207 
3208 	argop[0].nfs_argop4_u.opsetclientid_confirm.clientid = tmp_clientid;
3209 	argop[0].nfs_argop4_u.opsetclientid_confirm.setclientid_confirm = verf;
3210 
3211 	/* used to figure out RTT for np */
3212 	gethrestime(&prop_time);
3213 
3214 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE, "nfs4setlientid_otw: "
3215 	    "start time: %ld sec %ld nsec", prop_time.tv_sec,
3216 	    prop_time.tv_nsec));
3217 
3218 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
3219 
3220 	gethrestime(&after_time);
3221 	mutex_enter(&np->s_lock);
3222 	np->propagation_delay.tv_sec =
3223 	    MAX(1, after_time.tv_sec - prop_time.tv_sec);
3224 	mutex_exit(&np->s_lock);
3225 
3226 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE, "nfs4setlcientid_otw: "
3227 	    "finish time: %ld sec ", after_time.tv_sec));
3228 
3229 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE, "nfs4setclientid_otw: "
3230 	    "propagation delay set to %ld sec",
3231 	    np->propagation_delay.tv_sec));
3232 
3233 	if (ep->error)
3234 		return;
3235 
3236 	if (res.status == NFS4ERR_CLID_INUSE) {
3237 		clientaddr4 *clid_inuse;
3238 
3239 		if (!(*retry_inusep)) {
3240 			clid_inuse = &res.array->nfs_resop4_u.
3241 			    opsetclientid.SETCLIENTID4res_u.client_using;
3242 
3243 			zcmn_err(mi->mi_zone->zone_id, CE_NOTE,
3244 			    "SETCLIENTID_CONFIRM failed.  "
3245 			    "nfs4_client_id.id is in use already by: "
3246 			    "r_netid<%s> r_addr<%s>",
3247 			    clid_inuse->r_netid, clid_inuse->r_addr);
3248 		}
3249 
3250 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3251 		return;
3252 	}
3253 
3254 	if (res.status) {
3255 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3256 		return;
3257 	}
3258 
3259 	mutex_enter(&np->s_lock);
3260 	np->clientid = tmp_clientid;
3261 	np->s_flags |= N4S_CLIENTID_SET;
3262 
3263 	/* Add mi to np's mntinfo4 list */
3264 	nfs4_add_mi_to_server(np, mi);
3265 
3266 	if (np->lease_valid == NFS4_LEASE_NOT_STARTED) {
3267 		/*
3268 		 * Start lease management thread.
3269 		 * Keep trying until we succeed.
3270 		 */
3271 
3272 		np->s_refcnt++;		/* pass reference to thread */
3273 		(void) zthread_create(NULL, 0, nfs4_renew_lease_thread, np, 0,
3274 		    minclsyspri);
3275 	}
3276 	mutex_exit(&np->s_lock);
3277 
3278 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3279 }
3280 
3281 /*
3282  * Add mi to sp's mntinfo4_list if it isn't already in the list.  Makes
3283  * mi's clientid the same as sp's.
3284  * Assumes sp is locked down.
3285  */
3286 void
3287 nfs4_add_mi_to_server(nfs4_server_t *sp, mntinfo4_t *mi)
3288 {
3289 	mntinfo4_t *tmi;
3290 	int in_list = 0;
3291 
3292 	ASSERT(nfs_rw_lock_held(&mi->mi_recovlock, RW_READER) ||
3293 	    nfs_rw_lock_held(&mi->mi_recovlock, RW_WRITER));
3294 	ASSERT(sp != &nfs4_server_lst);
3295 	ASSERT(MUTEX_HELD(&sp->s_lock));
3296 
3297 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3298 	    "nfs4_add_mi_to_server: add mi %p to sp %p",
3299 	    (void*)mi, (void*)sp));
3300 
3301 	for (tmi = sp->mntinfo4_list;
3302 	    tmi != NULL;
3303 	    tmi = tmi->mi_clientid_next) {
3304 		if (tmi == mi) {
3305 			NFS4_DEBUG(nfs4_client_lease_debug,
3306 			    (CE_NOTE,
3307 			    "nfs4_add_mi_to_server: mi in list"));
3308 			in_list = 1;
3309 		}
3310 	}
3311 
3312 	/*
3313 	 * First put a hold on the mntinfo4's vfsp so that references via
3314 	 * mntinfo4_list will be valid.
3315 	 */
3316 	if (!in_list)
3317 		VFS_HOLD(mi->mi_vfsp);
3318 
3319 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE, "nfs4_add_mi_to_server: "
3320 	    "hold vfs %p for mi: %p", (void*)mi->mi_vfsp, (void*)mi));
3321 
3322 	if (!in_list) {
3323 		if (sp->mntinfo4_list)
3324 			sp->mntinfo4_list->mi_clientid_prev = mi;
3325 		mi->mi_clientid_next = sp->mntinfo4_list;
3326 		sp->mntinfo4_list = mi;
3327 		mi->mi_srvsettime = gethrestime_sec();
3328 	}
3329 
3330 	/* set mi's clientid to that of sp's for later matching */
3331 	mi->mi_clientid = sp->clientid;
3332 
3333 	/*
3334 	 * Update the clientid for any other mi's belonging to sp.  This
3335 	 * must be done here while we hold sp->s_lock, so that
3336 	 * find_nfs4_server() continues to work.
3337 	 */
3338 
3339 	for (tmi = sp->mntinfo4_list;
3340 	    tmi != NULL;
3341 	    tmi = tmi->mi_clientid_next) {
3342 		if (tmi != mi) {
3343 			tmi->mi_clientid = sp->clientid;
3344 		}
3345 	}
3346 }
3347 
3348 /*
3349  * Remove the mi from sp's mntinfo4_list and release its reference.
3350  * Exception: if mi still has open files, flag it for later removal (when
3351  * all the files are closed).
3352  *
3353  * If this is the last mntinfo4 in sp's list then tell the lease renewal
3354  * thread to exit.
3355  */
3356 static void
3357 nfs4_remove_mi_from_server_nolock(mntinfo4_t *mi, nfs4_server_t *sp)
3358 {
3359 	NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3360 	    "nfs4_remove_mi_from_server_nolock: remove mi %p from sp %p",
3361 	    (void*)mi, (void*)sp));
3362 
3363 	ASSERT(sp != NULL);
3364 	ASSERT(MUTEX_HELD(&sp->s_lock));
3365 	ASSERT(mi->mi_open_files >= 0);
3366 
3367 	/*
3368 	 * First make sure this mntinfo4 can be taken off of the list,
3369 	 * ie: it doesn't have any open files remaining.
3370 	 */
3371 	if (mi->mi_open_files > 0) {
3372 		NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3373 		    "nfs4_remove_mi_from_server_nolock: don't "
3374 		    "remove mi since it still has files open"));
3375 
3376 		mutex_enter(&mi->mi_lock);
3377 		mi->mi_flags |= MI4_REMOVE_ON_LAST_CLOSE;
3378 		mutex_exit(&mi->mi_lock);
3379 		return;
3380 	}
3381 
3382 	VFS_HOLD(mi->mi_vfsp);
3383 	remove_mi(sp, mi);
3384 	VFS_RELE(mi->mi_vfsp);
3385 
3386 	if (sp->mntinfo4_list == NULL) {
3387 		/* last fs unmounted, kill the thread */
3388 		NFS4_DEBUG(nfs4_client_lease_debug, (CE_NOTE,
3389 		    "remove_mi_from_nfs4_server_nolock: kill the thread"));
3390 		nfs4_mark_srv_dead(sp);
3391 	}
3392 }
3393 
3394 /*
3395  * Remove mi from sp's mntinfo4_list and release the vfs reference.
3396  */
3397 static void
3398 remove_mi(nfs4_server_t *sp, mntinfo4_t *mi)
3399 {
3400 	ASSERT(MUTEX_HELD(&sp->s_lock));
3401 
3402 	/*
3403 	 * We release a reference, and the caller must still have a
3404 	 * reference.
3405 	 */
3406 	ASSERT(mi->mi_vfsp->vfs_count >= 2);
3407 
3408 	if (mi->mi_clientid_prev) {
3409 		mi->mi_clientid_prev->mi_clientid_next = mi->mi_clientid_next;
3410 	} else {
3411 		/* This is the first mi in sp's mntinfo4_list */
3412 		/*
3413 		 * Make sure the first mntinfo4 in the list is the actual
3414 		 * mntinfo4 passed in.
3415 		 */
3416 		ASSERT(sp->mntinfo4_list == mi);
3417 
3418 		sp->mntinfo4_list = mi->mi_clientid_next;
3419 	}
3420 	if (mi->mi_clientid_next)
3421 		mi->mi_clientid_next->mi_clientid_prev = mi->mi_clientid_prev;
3422 
3423 	/* Now mark the mntinfo4's links as being removed */
3424 	mi->mi_clientid_prev = mi->mi_clientid_next = NULL;
3425 
3426 	VFS_RELE(mi->mi_vfsp);
3427 }
3428 
3429 /*
3430  * Free all the entries in sp's mntinfo4_list.
3431  */
3432 static void
3433 remove_all_mi(nfs4_server_t *sp)
3434 {
3435 	mntinfo4_t *mi;
3436 
3437 	ASSERT(MUTEX_HELD(&sp->s_lock));
3438 
3439 	while (sp->mntinfo4_list != NULL) {
3440 		mi = sp->mntinfo4_list;
3441 		/*
3442 		 * Grab a reference in case there is only one left (which
3443 		 * remove_mi() frees).
3444 		 */
3445 		VFS_HOLD(mi->mi_vfsp);
3446 		remove_mi(sp, mi);
3447 		VFS_RELE(mi->mi_vfsp);
3448 	}
3449 }
3450 
3451 /*
3452  * Remove the mi from sp's mntinfo4_list as above, and rele the vfs.
3453  *
3454  * This version can be called with a null nfs4_server_t arg,
3455  * and will either find the right one and handle locking, or
3456  * do nothing because the mi wasn't added to an sp's mntinfo4_list.
3457  */
3458 void
3459 nfs4_remove_mi_from_server(mntinfo4_t *mi, nfs4_server_t *esp)
3460 {
3461 	nfs4_server_t	*sp;
3462 
3463 	if (esp == NULL) {
3464 		(void) nfs_rw_enter_sig(&mi->mi_recovlock, RW_READER, 0);
3465 		sp = find_nfs4_server_all(mi, 1);
3466 	} else
3467 		sp = esp;
3468 
3469 	if (sp != NULL)
3470 		nfs4_remove_mi_from_server_nolock(mi, sp);
3471 
3472 	/*
3473 	 * If we had a valid esp as input, the calling function will be
3474 	 * responsible for unlocking the esp nfs4_server.
3475 	 */
3476 	if (esp == NULL) {
3477 		if (sp != NULL)
3478 			mutex_exit(&sp->s_lock);
3479 		nfs_rw_exit(&mi->mi_recovlock);
3480 		if (sp != NULL)
3481 			nfs4_server_rele(sp);
3482 	}
3483 }
3484 
3485 /*
3486  * Return TRUE if the given server has any non-unmounted filesystems.
3487  */
3488 
3489 bool_t
3490 nfs4_fs_active(nfs4_server_t *sp)
3491 {
3492 	mntinfo4_t *mi;
3493 
3494 	ASSERT(MUTEX_HELD(&sp->s_lock));
3495 
3496 	for (mi = sp->mntinfo4_list; mi != NULL; mi = mi->mi_clientid_next) {
3497 		if (!(mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED))
3498 			return (TRUE);
3499 	}
3500 
3501 	return (FALSE);
3502 }
3503 
3504 /*
3505  * Mark sp as finished and notify any waiters.
3506  */
3507 
3508 void
3509 nfs4_mark_srv_dead(nfs4_server_t *sp)
3510 {
3511 	ASSERT(MUTEX_HELD(&sp->s_lock));
3512 
3513 	sp->s_thread_exit = NFS4_THREAD_EXIT;
3514 	cv_broadcast(&sp->cv_thread_exit);
3515 }
3516 
3517 /*
3518  * Create a new nfs4_server_t structure.
3519  * Returns new node unlocked and not in list, but with a reference count of
3520  * 1.
3521  */
3522 struct nfs4_server *
3523 new_nfs4_server(struct servinfo4 *svp, cred_t *cr)
3524 {
3525 	struct nfs4_server *np;
3526 	timespec_t tt;
3527 	union {
3528 		struct {
3529 			uint32_t sec;
3530 			uint32_t subsec;
3531 		} un_curtime;
3532 		verifier4	un_verifier;
3533 	} nfs4clientid_verifier;
3534 	char id_val[] = "Solaris: %s, NFSv4 kernel client";
3535 	int len;
3536 
3537 	np = kmem_zalloc(sizeof (struct nfs4_server), KM_SLEEP);
3538 	np->saddr.len = svp->sv_addr.len;
3539 	np->saddr.maxlen = svp->sv_addr.maxlen;
3540 	np->saddr.buf = kmem_alloc(svp->sv_addr.maxlen, KM_SLEEP);
3541 	bcopy(svp->sv_addr.buf, np->saddr.buf, svp->sv_addr.len);
3542 	np->s_refcnt = 1;
3543 
3544 	/*
3545 	 * Build the nfs_client_id4 for this server mount.  Ensure
3546 	 * the verifier is useful and that the identification is
3547 	 * somehow based on the server's address for the case of
3548 	 * multi-homed servers.
3549 	 */
3550 	nfs4clientid_verifier.un_verifier = 0;
3551 	gethrestime(&tt);
3552 	nfs4clientid_verifier.un_curtime.sec = (uint32_t)tt.tv_sec;
3553 	nfs4clientid_verifier.un_curtime.subsec = (uint32_t)tt.tv_nsec;
3554 	np->clidtosend.verifier = nfs4clientid_verifier.un_verifier;
3555 
3556 	/*
3557 	 * calculate the length of the opaque identifier.  Subtract 2
3558 	 * for the "%s" and add the traditional +1 for null
3559 	 * termination.
3560 	 */
3561 	len = strlen(id_val) - 2 + strlen(uts_nodename()) + 1;
3562 	np->clidtosend.id_len = len + np->saddr.maxlen;
3563 
3564 	np->clidtosend.id_val = kmem_alloc(np->clidtosend.id_len, KM_SLEEP);
3565 	(void) sprintf(np->clidtosend.id_val, id_val, uts_nodename());
3566 	bcopy(np->saddr.buf, &np->clidtosend.id_val[len], np->saddr.len);
3567 
3568 	np->s_flags = 0;
3569 	np->mntinfo4_list = NULL;
3570 	/* save cred for issuing rfs4calls inside the renew thread */
3571 	crhold(cr);
3572 	np->s_cred = cr;
3573 	cv_init(&np->cv_thread_exit, NULL, CV_DEFAULT, NULL);
3574 	mutex_init(&np->s_lock, NULL, MUTEX_DEFAULT, NULL);
3575 	nfs_rw_init(&np->s_recovlock, NULL, RW_DEFAULT, NULL);
3576 	list_create(&np->s_deleg_list, sizeof (rnode4_t),
3577 	    offsetof(rnode4_t, r_deleg_link));
3578 	np->s_thread_exit = 0;
3579 	np->state_ref_count = 0;
3580 	np->lease_valid = NFS4_LEASE_NOT_STARTED;
3581 	cv_init(&np->s_cv_otw_count, NULL, CV_DEFAULT, NULL);
3582 	cv_init(&np->s_clientid_pend, NULL, CV_DEFAULT, NULL);
3583 	np->s_otw_call_count = 0;
3584 	cv_init(&np->wait_cb_null, NULL, CV_DEFAULT, NULL);
3585 	np->zoneid = getzoneid();
3586 	np->zone_globals = nfs4_get_callback_globals();
3587 	ASSERT(np->zone_globals != NULL);
3588 	return (np);
3589 }
3590 
3591 /*
3592  * Create a new nfs4_server_t structure and add it to the list.
3593  * Returns new node locked; reference must eventually be freed.
3594  */
3595 static struct nfs4_server *
3596 add_new_nfs4_server(struct servinfo4 *svp, cred_t *cr)
3597 {
3598 	nfs4_server_t *sp;
3599 
3600 	ASSERT(MUTEX_HELD(&nfs4_server_lst_lock));
3601 	sp = new_nfs4_server(svp, cr);
3602 	mutex_enter(&sp->s_lock);
3603 	insque(sp, &nfs4_server_lst);
3604 	sp->s_refcnt++;			/* list gets a reference */
3605 	sp->s_flags |= N4S_INSERTED;
3606 	sp->clientid = 0;
3607 	return (sp);
3608 }
3609 
3610 int nfs4_server_t_debug = 0;
3611 
3612 #ifdef lint
3613 extern void
3614 dumpnfs4slist(char *, mntinfo4_t *, clientid4, servinfo4_t *);
3615 #endif
3616 
3617 #ifndef lint
3618 #ifdef DEBUG
3619 void
3620 dumpnfs4slist(char *txt, mntinfo4_t *mi, clientid4 clientid, servinfo4_t *srv_p)
3621 {
3622 	int hash16(void *p, int len);
3623 	nfs4_server_t *np;
3624 
3625 	NFS4_DEBUG(nfs4_server_t_debug, (CE_NOTE,
3626 	    "dumping nfs4_server_t list in %s", txt));
3627 	NFS4_DEBUG(nfs4_server_t_debug, (CE_CONT,
3628 	    "mi 0x%p, want clientid %llx, addr %d/%04X",
3629 	    mi, (longlong_t)clientid, srv_p->sv_addr.len,
3630 	    hash16((void *)srv_p->sv_addr.buf, srv_p->sv_addr.len)));
3631 	for (np = nfs4_server_lst.forw; np != &nfs4_server_lst;
3632 	    np = np->forw) {
3633 		NFS4_DEBUG(nfs4_server_t_debug, (CE_CONT,
3634 		    "node 0x%p,    clientid %llx, addr %d/%04X, cnt %d",
3635 		    np, (longlong_t)np->clientid, np->saddr.len,
3636 		    hash16((void *)np->saddr.buf, np->saddr.len),
3637 		    np->state_ref_count));
3638 		if (np->saddr.len == srv_p->sv_addr.len &&
3639 		    bcmp(np->saddr.buf, srv_p->sv_addr.buf,
3640 		    np->saddr.len) == 0)
3641 			NFS4_DEBUG(nfs4_server_t_debug, (CE_CONT,
3642 			    " - address matches"));
3643 		if (np->clientid == clientid || np->clientid == 0)
3644 			NFS4_DEBUG(nfs4_server_t_debug, (CE_CONT,
3645 			    " - clientid matches"));
3646 		if (np->s_thread_exit != NFS4_THREAD_EXIT)
3647 			NFS4_DEBUG(nfs4_server_t_debug, (CE_CONT,
3648 			    " - thread not exiting"));
3649 	}
3650 	delay(hz);
3651 }
3652 #endif
3653 #endif
3654 
3655 
3656 /*
3657  * Move a mntinfo4_t from one server list to another.
3658  * Locking of the two nfs4_server_t nodes will be done in list order.
3659  *
3660  * Returns NULL if the current nfs4_server_t for the filesystem could not
3661  * be found (e.g., due to forced unmount).  Otherwise returns a reference
3662  * to the new nfs4_server_t, which must eventually be freed.
3663  */
3664 nfs4_server_t *
3665 nfs4_move_mi(mntinfo4_t *mi, servinfo4_t *old, servinfo4_t *new)
3666 {
3667 	nfs4_server_t *p, *op = NULL, *np = NULL;
3668 	int num_open;
3669 	zoneid_t zoneid = nfs_zoneid();
3670 
3671 	ASSERT(nfs_zone() == mi->mi_zone);
3672 
3673 	mutex_enter(&nfs4_server_lst_lock);
3674 #ifdef DEBUG
3675 	if (nfs4_server_t_debug)
3676 		dumpnfs4slist("nfs4_move_mi", mi, (clientid4)0, new);
3677 #endif
3678 	for (p = nfs4_server_lst.forw; p != &nfs4_server_lst; p = p->forw) {
3679 		if (p->zoneid != zoneid)
3680 			continue;
3681 		if (p->saddr.len == old->sv_addr.len &&
3682 		    bcmp(p->saddr.buf, old->sv_addr.buf, p->saddr.len) == 0 &&
3683 		    p->s_thread_exit != NFS4_THREAD_EXIT) {
3684 			op = p;
3685 			mutex_enter(&op->s_lock);
3686 			op->s_refcnt++;
3687 		}
3688 		if (p->saddr.len == new->sv_addr.len &&
3689 		    bcmp(p->saddr.buf, new->sv_addr.buf, p->saddr.len) == 0 &&
3690 		    p->s_thread_exit != NFS4_THREAD_EXIT) {
3691 			np = p;
3692 			mutex_enter(&np->s_lock);
3693 		}
3694 		if (op != NULL && np != NULL)
3695 			break;
3696 	}
3697 	if (op == NULL) {
3698 		/*
3699 		 * Filesystem has been forcibly unmounted.  Bail out.
3700 		 */
3701 		if (np != NULL)
3702 			mutex_exit(&np->s_lock);
3703 		mutex_exit(&nfs4_server_lst_lock);
3704 		return (NULL);
3705 	}
3706 	if (np != NULL) {
3707 		np->s_refcnt++;
3708 	} else {
3709 #ifdef DEBUG
3710 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
3711 		    "nfs4_move_mi: no target nfs4_server, will create."));
3712 #endif
3713 		np = add_new_nfs4_server(new, kcred);
3714 	}
3715 	mutex_exit(&nfs4_server_lst_lock);
3716 
3717 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
3718 	    "nfs4_move_mi: for mi 0x%p, "
3719 	    "old servinfo4 0x%p, new servinfo4 0x%p, "
3720 	    "old nfs4_server 0x%p, new nfs4_server 0x%p, ",
3721 	    (void*)mi, (void*)old, (void*)new,
3722 	    (void*)op, (void*)np));
3723 	ASSERT(op != NULL && np != NULL);
3724 
3725 	/* discard any delegations */
3726 	nfs4_deleg_discard(mi, op);
3727 
3728 	num_open = mi->mi_open_files;
3729 	mi->mi_open_files = 0;
3730 	op->state_ref_count -= num_open;
3731 	ASSERT(op->state_ref_count >= 0);
3732 	np->state_ref_count += num_open;
3733 	nfs4_remove_mi_from_server_nolock(mi, op);
3734 	mi->mi_open_files = num_open;
3735 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
3736 	    "nfs4_move_mi: mi_open_files %d, op->cnt %d, np->cnt %d",
3737 	    mi->mi_open_files, op->state_ref_count, np->state_ref_count));
3738 
3739 	nfs4_add_mi_to_server(np, mi);
3740 
3741 	mutex_exit(&op->s_lock);
3742 	nfs4_server_rele(op);
3743 	mutex_exit(&np->s_lock);
3744 
3745 	return (np);
3746 }
3747 
3748 /*
3749  * Need to have the nfs4_server_lst_lock.
3750  * Search the nfs4_server list to find a match on this servinfo4
3751  * based on its address.
3752  *
3753  * Returns NULL if no match is found.  Otherwise returns a reference (which
3754  * must eventually be freed) to a locked nfs4_server.
3755  */
3756 nfs4_server_t *
3757 servinfo4_to_nfs4_server(servinfo4_t *srv_p)
3758 {
3759 	nfs4_server_t *np;
3760 	zoneid_t zoneid = nfs_zoneid();
3761 
3762 	ASSERT(MUTEX_HELD(&nfs4_server_lst_lock));
3763 	for (np = nfs4_server_lst.forw; np != &nfs4_server_lst; np = np->forw) {
3764 		if (np->zoneid == zoneid &&
3765 		    np->saddr.len == srv_p->sv_addr.len &&
3766 		    bcmp(np->saddr.buf, srv_p->sv_addr.buf,
3767 		    np->saddr.len) == 0 &&
3768 		    np->s_thread_exit != NFS4_THREAD_EXIT) {
3769 			mutex_enter(&np->s_lock);
3770 			np->s_refcnt++;
3771 			return (np);
3772 		}
3773 	}
3774 	return (NULL);
3775 }
3776 
3777 /*
3778  * Search the nfs4_server_lst to find a match based on clientid and
3779  * addr.
3780  * Locks the nfs4_server down if it is found and returns a reference that
3781  * must eventually be freed.
3782  *
3783  * Returns NULL it no match is found.  This means one of two things: either
3784  * mi is in the process of being mounted, or mi has been unmounted.
3785  *
3786  * The caller should be holding mi->mi_recovlock, and it should continue to
3787  * hold the lock until done with the returned nfs4_server_t.  Once
3788  * mi->mi_recovlock is released, there is no guarantee that the returned
3789  * mi->nfs4_server_t will continue to correspond to mi.
3790  */
3791 nfs4_server_t *
3792 find_nfs4_server(mntinfo4_t *mi)
3793 {
3794 	return (find_nfs4_server_all(mi, 0));
3795 }
3796 
3797 /*
3798  * Same as above, but takes an "all" parameter which can be
3799  * set to 1 if the caller wishes to find nfs4_server_t's which
3800  * have been marked for termination by the exit of the renew
3801  * thread.  This should only be used by operations which are
3802  * cleaning up and will not cause an OTW op.
3803  */
3804 nfs4_server_t *
3805 find_nfs4_server_all(mntinfo4_t *mi, int all)
3806 {
3807 	nfs4_server_t *np;
3808 	servinfo4_t *svp;
3809 	zoneid_t zoneid = mi->mi_zone->zone_id;
3810 
3811 	ASSERT(nfs_rw_lock_held(&mi->mi_recovlock, RW_READER) ||
3812 	    nfs_rw_lock_held(&mi->mi_recovlock, RW_WRITER));
3813 	/*
3814 	 * This can be called from nfs4_unmount() which can be called from the
3815 	 * global zone, hence it's legal for the global zone to muck with
3816 	 * another zone's server list, as long as it doesn't try to contact
3817 	 * them.
3818 	 */
3819 	ASSERT(zoneid == getzoneid() || getzoneid() == GLOBAL_ZONEID ||
3820 	    nfs_global_client_only != 0);
3821 
3822 	/*
3823 	 * The nfs4_server_lst_lock global lock is held when we get a new
3824 	 * clientid (via SETCLIENTID OTW).  Holding this global lock and
3825 	 * mi_recovlock (READER is fine) ensures that the nfs4_server
3826 	 * and this mntinfo4 can't get out of sync, so the following search is
3827 	 * always valid.
3828 	 */
3829 	mutex_enter(&nfs4_server_lst_lock);
3830 #ifdef DEBUG
3831 	if (nfs4_server_t_debug) {
3832 		/* mi->mi_clientid is unprotected, ok for debug output */
3833 		dumpnfs4slist("find_nfs4_server", mi, mi->mi_clientid,
3834 		    mi->mi_curr_serv);
3835 	}
3836 #endif
3837 	for (np = nfs4_server_lst.forw; np != &nfs4_server_lst; np = np->forw) {
3838 		mutex_enter(&np->s_lock);
3839 		svp = mi->mi_curr_serv;
3840 
3841 		if (np->zoneid == zoneid &&
3842 		    np->clientid == mi->mi_clientid &&
3843 		    np->saddr.len == svp->sv_addr.len &&
3844 		    bcmp(np->saddr.buf, svp->sv_addr.buf, np->saddr.len) == 0 &&
3845 		    (np->s_thread_exit != NFS4_THREAD_EXIT || all != 0)) {
3846 			mutex_exit(&nfs4_server_lst_lock);
3847 			np->s_refcnt++;
3848 			return (np);
3849 		}
3850 		mutex_exit(&np->s_lock);
3851 	}
3852 	mutex_exit(&nfs4_server_lst_lock);
3853 
3854 	return (NULL);
3855 }
3856 
3857 /*
3858  * Release the reference to sp and destroy it if that's the last one.
3859  */
3860 
3861 void
3862 nfs4_server_rele(nfs4_server_t *sp)
3863 {
3864 	mutex_enter(&sp->s_lock);
3865 	ASSERT(sp->s_refcnt > 0);
3866 	sp->s_refcnt--;
3867 	if (sp->s_refcnt > 0) {
3868 		mutex_exit(&sp->s_lock);
3869 		return;
3870 	}
3871 	mutex_exit(&sp->s_lock);
3872 
3873 	mutex_enter(&nfs4_server_lst_lock);
3874 	mutex_enter(&sp->s_lock);
3875 	if (sp->s_refcnt > 0) {
3876 		mutex_exit(&sp->s_lock);
3877 		mutex_exit(&nfs4_server_lst_lock);
3878 		return;
3879 	}
3880 	remque(sp);
3881 	sp->forw = sp->back = NULL;
3882 	mutex_exit(&nfs4_server_lst_lock);
3883 	destroy_nfs4_server(sp);
3884 }
3885 
3886 static void
3887 destroy_nfs4_server(nfs4_server_t *sp)
3888 {
3889 	ASSERT(MUTEX_HELD(&sp->s_lock));
3890 	ASSERT(sp->s_refcnt == 0);
3891 	ASSERT(sp->s_otw_call_count == 0);
3892 
3893 	remove_all_mi(sp);
3894 
3895 	crfree(sp->s_cred);
3896 	kmem_free(sp->saddr.buf, sp->saddr.maxlen);
3897 	kmem_free(sp->clidtosend.id_val, sp->clidtosend.id_len);
3898 	mutex_exit(&sp->s_lock);
3899 
3900 	/* destroy the nfs4_server */
3901 	nfs4callback_destroy(sp);
3902 	list_destroy(&sp->s_deleg_list);
3903 	mutex_destroy(&sp->s_lock);
3904 	cv_destroy(&sp->cv_thread_exit);
3905 	cv_destroy(&sp->s_cv_otw_count);
3906 	cv_destroy(&sp->s_clientid_pend);
3907 	cv_destroy(&sp->wait_cb_null);
3908 	nfs_rw_destroy(&sp->s_recovlock);
3909 	kmem_free(sp, sizeof (*sp));
3910 }
3911 
3912 /*
3913  * Lock sp, but only if it's still active (in the list and hasn't been
3914  * flagged as exiting) or 'all' is non-zero.
3915  * Returns TRUE if sp got locked and adds a reference to sp.
3916  */
3917 bool_t
3918 nfs4_server_vlock(nfs4_server_t *sp, int all)
3919 {
3920 	nfs4_server_t *np;
3921 
3922 	mutex_enter(&nfs4_server_lst_lock);
3923 	for (np = nfs4_server_lst.forw; np != &nfs4_server_lst; np = np->forw) {
3924 		if (sp == np && (np->s_thread_exit != NFS4_THREAD_EXIT ||
3925 		    all != 0)) {
3926 			mutex_enter(&np->s_lock);
3927 			np->s_refcnt++;
3928 			mutex_exit(&nfs4_server_lst_lock);
3929 			return (TRUE);
3930 		}
3931 	}
3932 	mutex_exit(&nfs4_server_lst_lock);
3933 	return (FALSE);
3934 }
3935 
3936 /*
3937  * Fork off a thread to free the data structures for a mount.
3938  */
3939 
3940 static void
3941 async_free_mount(vfs_t *vfsp, int flag, cred_t *cr)
3942 {
3943 	freemountargs_t *args;
3944 	args = kmem_alloc(sizeof (freemountargs_t), KM_SLEEP);
3945 	args->fm_vfsp = vfsp;
3946 	VFS_HOLD(vfsp);
3947 	MI4_HOLD(VFTOMI4(vfsp));
3948 	args->fm_flag = flag;
3949 	args->fm_cr = cr;
3950 	crhold(cr);
3951 	(void) zthread_create(NULL, 0, nfs4_free_mount_thread, args, 0,
3952 	    minclsyspri);
3953 }
3954 
3955 static void
3956 nfs4_free_mount_thread(freemountargs_t *args)
3957 {
3958 	mntinfo4_t *mi;
3959 	nfs4_free_mount(args->fm_vfsp, args->fm_flag, args->fm_cr);
3960 	mi = VFTOMI4(args->fm_vfsp);
3961 	crfree(args->fm_cr);
3962 	VFS_RELE(args->fm_vfsp);
3963 	MI4_RELE(mi);
3964 	kmem_free(args, sizeof (freemountargs_t));
3965 	zthread_exit();
3966 	/* NOTREACHED */
3967 }
3968 
3969 /*
3970  * Thread to free the data structures for a given filesystem.
3971  */
3972 static void
3973 nfs4_free_mount(vfs_t *vfsp, int flag, cred_t *cr)
3974 {
3975 	mntinfo4_t		*mi = VFTOMI4(vfsp);
3976 	nfs4_server_t		*sp;
3977 	callb_cpr_t		cpr_info;
3978 	kmutex_t		cpr_lock;
3979 	boolean_t		async_thread;
3980 	int			removed;
3981 
3982 	bool_t			must_unlock;
3983 	bool_t			must_rele;
3984 	nfs4_ephemeral_tree_t	*eph_tree;
3985 
3986 	/*
3987 	 * We need to participate in the CPR framework if this is a kernel
3988 	 * thread.
3989 	 */
3990 	async_thread = (curproc == nfs_zone()->zone_zsched);
3991 	if (async_thread) {
3992 		mutex_init(&cpr_lock, NULL, MUTEX_DEFAULT, NULL);
3993 		CALLB_CPR_INIT(&cpr_info, &cpr_lock, callb_generic_cpr,
3994 		    "nfsv4AsyncUnmount");
3995 	}
3996 
3997 	/*
3998 	 * We need to wait for all outstanding OTW calls
3999 	 * and recovery to finish before we remove the mi
4000 	 * from the nfs4_server_t, as current pending
4001 	 * calls might still need this linkage (in order
4002 	 * to find a nfs4_server_t from a mntinfo4_t).
4003 	 */
4004 	(void) nfs_rw_enter_sig(&mi->mi_recovlock, RW_READER, FALSE);
4005 	sp = find_nfs4_server(mi);
4006 	nfs_rw_exit(&mi->mi_recovlock);
4007 
4008 	if (sp) {
4009 		while (sp->s_otw_call_count != 0) {
4010 			if (async_thread) {
4011 				mutex_enter(&cpr_lock);
4012 				CALLB_CPR_SAFE_BEGIN(&cpr_info);
4013 				mutex_exit(&cpr_lock);
4014 			}
4015 			cv_wait(&sp->s_cv_otw_count, &sp->s_lock);
4016 			if (async_thread) {
4017 				mutex_enter(&cpr_lock);
4018 				CALLB_CPR_SAFE_END(&cpr_info, &cpr_lock);
4019 				mutex_exit(&cpr_lock);
4020 			}
4021 		}
4022 		mutex_exit(&sp->s_lock);
4023 		nfs4_server_rele(sp);
4024 		sp = NULL;
4025 	}
4026 
4027 	mutex_enter(&mi->mi_lock);
4028 	while (mi->mi_in_recovery != 0) {
4029 		if (async_thread) {
4030 			mutex_enter(&cpr_lock);
4031 			CALLB_CPR_SAFE_BEGIN(&cpr_info);
4032 			mutex_exit(&cpr_lock);
4033 		}
4034 		cv_wait(&mi->mi_cv_in_recov, &mi->mi_lock);
4035 		if (async_thread) {
4036 			mutex_enter(&cpr_lock);
4037 			CALLB_CPR_SAFE_END(&cpr_info, &cpr_lock);
4038 			mutex_exit(&cpr_lock);
4039 		}
4040 	}
4041 	mutex_exit(&mi->mi_lock);
4042 
4043 	/*
4044 	 * If we got an error, then do not nuke the
4045 	 * tree. Either the harvester is busy reclaiming
4046 	 * this node or we ran into some busy condition.
4047 	 *
4048 	 * The harvester will eventually come along and cleanup.
4049 	 * The only problem would be the root mount point.
4050 	 *
4051 	 * Since the busy node can occur for a variety
4052 	 * of reasons and can result in an entry staying
4053 	 * in df output but no longer accessible from the
4054 	 * directory tree, we are okay.
4055 	 */
4056 	if (!nfs4_ephemeral_umount(mi, flag, cr,
4057 	    &must_unlock, &must_rele, &eph_tree))
4058 		nfs4_ephemeral_umount_activate(mi, &must_unlock,
4059 		    &must_rele, &eph_tree);
4060 
4061 	/*
4062 	 * The original purge of the dnlc via 'dounmount'
4063 	 * doesn't guarantee that another dnlc entry was not
4064 	 * added while we waitied for all outstanding OTW
4065 	 * and recovery calls to finish.  So re-purge the
4066 	 * dnlc now.
4067 	 */
4068 	(void) dnlc_purge_vfsp(vfsp, 0);
4069 
4070 	/*
4071 	 * We need to explicitly stop the manager thread; the asyc worker
4072 	 * threads can timeout and exit on their own.
4073 	 */
4074 	mutex_enter(&mi->mi_async_lock);
4075 	mi->mi_max_threads = 0;
4076 	cv_broadcast(&mi->mi_async_work_cv);
4077 	mutex_exit(&mi->mi_async_lock);
4078 	if (mi->mi_manager_thread)
4079 		nfs4_async_manager_stop(vfsp);
4080 
4081 	destroy_rtable4(vfsp, cr);
4082 
4083 	nfs4_remove_mi_from_server(mi, NULL);
4084 
4085 	if (async_thread) {
4086 		mutex_enter(&cpr_lock);
4087 		CALLB_CPR_EXIT(&cpr_info);	/* drops cpr_lock */
4088 		mutex_destroy(&cpr_lock);
4089 	}
4090 
4091 	removed = nfs4_mi_zonelist_remove(mi);
4092 	if (removed)
4093 		zone_rele(mi->mi_zone);
4094 }
4095