xref: /titanic_44/usr/src/uts/common/rpc/clnt_cots.c (revision 448b8615fe9e8af757530284920a235430ead7e8)
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 /*
32  * Portions of this source code were derived from Berkeley 4.3 BSD
33  * under license from the Regents of the University of California.
34  */
35 
36 #pragma ident	"%Z%%M%	%I%	%E% SMI"
37 
38 /*
39  * Implements a kernel based, client side RPC over Connection Oriented
40  * Transports (COTS).
41  */
42 
43 /*
44  * Much of this file has been re-written to let NFS work better over slow
45  * transports. A description follows.
46  *
47  * One of the annoying things about kRPC/COTS is that it will temporarily
48  * create more than one connection between a client and server. This
49  * happens because when a connection is made, the end-points entry in the
50  * linked list of connections (headed by cm_hd), is removed so that other
51  * threads don't mess with it. Went ahead and bit the bullet by keeping
52  * the endpoint on the connection list and introducing state bits,
53  * condition variables etc. to the connection entry data structure (struct
54  * cm_xprt).
55  *
56  * Here is a summary of the changes to cm-xprt:
57  *
58  *	x_ctime is the timestamp of when the endpoint was last
59  *	connected or disconnected. If an end-point is ever disconnected
60  *	or re-connected, then any outstanding RPC request is presumed
61  *	lost, telling clnt_cots_kcallit that it needs to re-send the
62  *	request, not just wait for the original request's reply to
63  *	arrive.
64  *
65  *	x_thread flag which tells us if a thread is doing a connection attempt.
66  *
67  *	x_waitdis flag which tells us we are waiting a disconnect ACK.
68  *
69  *	x_needdis flag which tells us we need to send a T_DISCONN_REQ
70  *	to kill the connection.
71  *
72  *	x_needrel flag which tells us we need to send a T_ORDREL_REQ to
73  *	gracefully close the connection.
74  *
75  *	#defined bitmasks for the all the b_* bits so that more
76  *	efficient (and at times less clumsy) masks can be used to
77  *	manipulated state in cases where multiple bits have to
78  *	set/cleared/checked in the same critical section.
79  *
80  *	x_conn_cv and x_dis-_cv are new condition variables to let
81  *	threads knows when the connection attempt is done, and to let
82  *	the connecting thread know when the disconnect handshake is
83  *	done.
84  *
85  * Added the CONN_HOLD() macro so that all reference holds have the same
86  * look and feel.
87  *
88  * In the private (cku_private) portion of the client handle,
89  *
90  *	cku_flags replaces the cku_sent a boolean. cku_flags keeps
91  *	track of whether a request as been sent, and whether the
92  *	client's handles call record is on the dispatch list (so that
93  *	the reply can be matched by XID to the right client handle).
94  *	The idea of CKU_ONQUEUE is that we can exit clnt_cots_kcallit()
95  *	and still have the response find the right client handle so
96  *	that the retry of CLNT_CALL() gets the result. Testing, found
97  *	situations where if the timeout was increased, performance
98  *	degraded. This was due to us hitting a window where the thread
99  *	was back in rfscall() (probably printing server not responding)
100  *	while the response came back but no place to put it.
101  *
102  *	cku_ctime is just a cache of x_ctime. If they match,
103  *	clnt_cots_kcallit() won't to send a retry (unless the maximum
104  *	receive count limit as been reached). If the don't match, then
105  *	we assume the request has been lost, and a retry of the request
106  *	is needed.
107  *
108  *	cku_recv_attempts counts the number of receive count attempts
109  *	after one try is sent on the wire.
110  *
111  * Added the clnt_delay() routine so that interruptible and
112  * noninterruptible delays are possible.
113  *
114  * CLNT_MIN_TIMEOUT has been bumped to 10 seconds from 3. This is used to
115  * control how long the client delays before returned after getting
116  * ECONNREFUSED. At 3 seconds, 8 client threads per mount really does bash
117  * a server that may be booting and not yet started nfsd.
118  *
119  * CLNT_MAXRECV_WITHOUT_RETRY is a new macro (value of 3) (with a tunable)
120  * Why don't we just wait forever (receive an infinite # of times)?
121  * Because the server may have rebooted. More insidious is that some
122  * servers (ours) will drop NFS/TCP requests in some cases. This is bad,
123  * but it is a reality.
124  *
125  * The case of a server doing orderly release really messes up the
126  * client's recovery, especially if the server's TCP implementation is
127  * buggy.  It was found was that the kRPC/COTS client was breaking some
128  * TPI rules, such as not waiting for the acknowledgement of a
129  * T_DISCON_REQ (hence the added case statements T_ERROR_ACK, T_OK_ACK and
130  * T_DISCON_REQ in clnt_dispatch_notifyall()).
131  *
132  * One of things that we've seen is that a kRPC TCP endpoint goes into
133  * TIMEWAIT and a thus a reconnect takes a long time to satisfy because
134  * that the TIMEWAIT state takes a while to finish.  If a server sends a
135  * T_ORDREL_IND, there is little point in an RPC client doing a
136  * T_ORDREL_REQ, because the RPC request isn't going to make it (the
137  * server is saying that it won't accept any more data). So kRPC was
138  * changed to send a T_DISCON_REQ when we get a T_ORDREL_IND. So now the
139  * connection skips the TIMEWAIT state and goes straight to a bound state
140  * that kRPC can quickly switch to connected.
141  *
142  * Code that issues TPI request must use waitforack() to wait for the
143  * corresponding ack (assuming there is one) in any future modifications.
144  * This works around problems that may be introduced by breaking TPI rules
145  * (by submitting new calls before earlier requests have been acked) in the
146  * case of a signal or other early return.  waitforack() depends on
147  * clnt_dispatch_notifyconn() to issue the wakeup when the ack
148  * arrives, so adding new TPI calls may require corresponding changes
149  * to clnt_dispatch_notifyconn(). Presently, the timeout period is based on
150  * CLNT_MIN_TIMEOUT which is 10 seconds. If you modify this value, be sure
151  * not to set it too low or TPI ACKS will be lost.
152  */
153 
154 #include <sys/param.h>
155 #include <sys/types.h>
156 #include <sys/user.h>
157 #include <sys/systm.h>
158 #include <sys/sysmacros.h>
159 #include <sys/proc.h>
160 #include <sys/socket.h>
161 #include <sys/file.h>
162 #include <sys/stream.h>
163 #include <sys/strsubr.h>
164 #include <sys/stropts.h>
165 #include <sys/strsun.h>
166 #include <sys/timod.h>
167 #include <sys/tiuser.h>
168 #include <sys/tihdr.h>
169 #include <sys/t_kuser.h>
170 #include <sys/fcntl.h>
171 #include <sys/errno.h>
172 #include <sys/kmem.h>
173 #include <sys/debug.h>
174 #include <sys/systm.h>
175 #include <sys/kstat.h>
176 #include <sys/t_lock.h>
177 #include <sys/ddi.h>
178 #include <sys/cmn_err.h>
179 #include <sys/time.h>
180 #include <sys/isa_defs.h>
181 #include <sys/callb.h>
182 #include <sys/sunddi.h>
183 #include <sys/atomic.h>
184 
185 #include <netinet/in.h>
186 #include <netinet/tcp.h>
187 
188 #include <rpc/types.h>
189 #include <rpc/xdr.h>
190 #include <rpc/auth.h>
191 #include <rpc/clnt.h>
192 #include <rpc/rpc_msg.h>
193 
194 #define	COTS_DEFAULT_ALLOCSIZE	2048
195 
196 #define	WIRE_HDR_SIZE	20	/* serialized call header, sans proc number */
197 #define	MSG_OFFSET	128	/* offset of call into the mblk */
198 
199 const char *kinet_ntop6(uchar_t *, char *, size_t);
200 
201 static int	clnt_cots_ksettimers(CLIENT *, struct rpc_timers *,
202     struct rpc_timers *, int, void(*)(int, int, caddr_t), caddr_t, uint32_t);
203 static enum clnt_stat	clnt_cots_kcallit(CLIENT *, rpcproc_t, xdrproc_t,
204     caddr_t, xdrproc_t, caddr_t, struct timeval);
205 static void	clnt_cots_kabort(CLIENT *);
206 static void	clnt_cots_kerror(CLIENT *, struct rpc_err *);
207 static bool_t	clnt_cots_kfreeres(CLIENT *, xdrproc_t, caddr_t);
208 static void	clnt_cots_kdestroy(CLIENT *);
209 static bool_t	clnt_cots_kcontrol(CLIENT *, int, char *);
210 
211 
212 /* List of transports managed by the connection manager. */
213 struct cm_xprt {
214 	TIUSER		*x_tiptr;	/* transport handle */
215 	queue_t		*x_wq;		/* send queue */
216 	clock_t		x_time;		/* last time we handed this xprt out */
217 	clock_t		x_ctime;	/* time we went to CONNECTED */
218 	int		x_tidu_size;    /* TIDU size of this transport */
219 	union {
220 	    struct {
221 		unsigned int
222 #ifdef	_BIT_FIELDS_HTOL
223 		b_closing:	1,	/* we've sent a ord rel on this conn */
224 		b_dead:		1,	/* transport is closed or disconn */
225 		b_doomed:	1,	/* too many conns, let this go idle */
226 		b_connected:	1,	/* this connection is connected */
227 
228 		b_ordrel:	1,	/* do an orderly release? */
229 		b_thread:	1,	/* thread doing connect */
230 		b_waitdis:	1,	/* waiting for disconnect ACK */
231 		b_needdis:	1,	/* need T_DISCON_REQ */
232 
233 		b_needrel:	1,	/* need T_ORDREL_REQ */
234 		b_early_disc:	1,	/* got a T_ORDREL_IND or T_DISCON_IND */
235 					/* disconnect during connect */
236 
237 		b_pad:		22;
238 
239 #endif
240 
241 #ifdef	_BIT_FIELDS_LTOH
242 		b_pad:		22,
243 
244 		b_early_disc:	1,	/* got a T_ORDREL_IND or T_DISCON_IND */
245 					/* disconnect during connect */
246 		b_needrel:	1,	/* need T_ORDREL_REQ */
247 
248 		b_needdis:	1,	/* need T_DISCON_REQ */
249 		b_waitdis:	1,	/* waiting for disconnect ACK */
250 		b_thread:	1,	/* thread doing connect */
251 		b_ordrel:	1,	/* do an orderly release? */
252 
253 		b_connected:	1,	/* this connection is connected */
254 		b_doomed:	1,	/* too many conns, let this go idle */
255 		b_dead:		1,	/* transport is closed or disconn */
256 		b_closing:	1;	/* we've sent a ord rel on this conn */
257 #endif
258 	    } bit;	    unsigned int word;
259 
260 #define	x_closing	x_state.bit.b_closing
261 #define	x_dead		x_state.bit.b_dead
262 #define	x_doomed	x_state.bit.b_doomed
263 #define	x_connected	x_state.bit.b_connected
264 
265 #define	x_ordrel	x_state.bit.b_ordrel
266 #define	x_thread	x_state.bit.b_thread
267 #define	x_waitdis	x_state.bit.b_waitdis
268 #define	x_needdis	x_state.bit.b_needdis
269 
270 #define	x_needrel	x_state.bit.b_needrel
271 #define	x_early_disc    x_state.bit.b_early_disc
272 
273 #define	x_state_flags	x_state.word
274 
275 #define	X_CLOSING	0x80000000
276 #define	X_DEAD		0x40000000
277 #define	X_DOOMED	0x20000000
278 #define	X_CONNECTED	0x10000000
279 
280 #define	X_ORDREL	0x08000000
281 #define	X_THREAD	0x04000000
282 #define	X_WAITDIS	0x02000000
283 #define	X_NEEDDIS	0x01000000
284 
285 #define	X_NEEDREL	0x00800000
286 #define	X_EARLYDISC	0x00400000
287 
288 #define	X_BADSTATES	(X_CLOSING | X_DEAD | X_DOOMED)
289 
290 	}		x_state;
291 	int		x_ref;		/* number of users of this xprt */
292 	int		x_family;	/* address family of transport */
293 	dev_t		x_rdev;		/* device number of transport */
294 	struct cm_xprt	*x_next;
295 
296 	struct netbuf	x_server;	/* destination address */
297 	struct netbuf	x_src;		/* src address (for retries) */
298 	kmutex_t	x_lock;		/* lock on this entry */
299 	kcondvar_t	x_cv;		/* to signal when can be closed */
300 	kcondvar_t	x_conn_cv;	/* to signal when connection attempt */
301 					/* is complete */
302 	kstat_t		*x_ksp;
303 
304 	kcondvar_t	x_dis_cv;	/* to signal when disconnect attempt */
305 					/* is complete */
306 	zoneid_t	x_zoneid;	/* zone this xprt belongs to */
307 };
308 
309 typedef struct cm_kstat_xprt {
310 	kstat_named_t	x_wq;
311 	kstat_named_t	x_server;
312 	kstat_named_t	x_family;
313 	kstat_named_t	x_rdev;
314 	kstat_named_t	x_time;
315 	kstat_named_t	x_state;
316 	kstat_named_t	x_ref;
317 	kstat_named_t	x_port;
318 } cm_kstat_xprt_t;
319 
320 static cm_kstat_xprt_t cm_kstat_template = {
321 	{ "write_queue", KSTAT_DATA_UINT32 },
322 	{ "server",	KSTAT_DATA_STRING },
323 	{ "addr_family", KSTAT_DATA_UINT32 },
324 	{ "device",	KSTAT_DATA_UINT32 },
325 	{ "time_stamp",	KSTAT_DATA_UINT32 },
326 	{ "status",	KSTAT_DATA_UINT32 },
327 	{ "ref_count",	KSTAT_DATA_INT32 },
328 	{ "port",	KSTAT_DATA_UINT32 },
329 };
330 
331 /*
332  * The inverse of this is connmgr_release().
333  */
334 #define	CONN_HOLD(Cm_entry)	{\
335 	mutex_enter(&(Cm_entry)->x_lock);	\
336 	(Cm_entry)->x_ref++;	\
337 	mutex_exit(&(Cm_entry)->x_lock);	\
338 }
339 
340 
341 /*
342  * Private data per rpc handle.  This structure is allocated by
343  * clnt_cots_kcreate, and freed by clnt_cots_kdestroy.
344  */
345 typedef struct cku_private_s {
346 	CLIENT			cku_client;	/* client handle */
347 	calllist_t		cku_call;	/* for dispatching calls */
348 	struct rpc_err		cku_err;	/* error status */
349 
350 	struct netbuf		cku_srcaddr;	/* source address for retries */
351 	int			cku_addrfmly;  /* for binding port */
352 	struct netbuf		cku_addr;	/* remote address */
353 	dev_t			cku_device;	/* device to use */
354 	uint_t			cku_flags;
355 #define	CKU_ONQUEUE		0x1
356 #define	CKU_SENT		0x2
357 
358 	bool_t			cku_progress;	/* for CLSET_PROGRESS */
359 	uint32_t		cku_xid;	/* current XID */
360 	clock_t			cku_ctime;	/* time stamp of when */
361 						/* connection was created */
362 	uint_t			cku_recv_attempts;
363 	XDR			cku_outxdr;	/* xdr routine for output */
364 	XDR			cku_inxdr;	/* xdr routine for input */
365 	char			cku_rpchdr[WIRE_HDR_SIZE + 4];
366 						/* pre-serialized rpc header */
367 
368 	uint_t			cku_outbuflen;	/* default output mblk length */
369 	struct cred		*cku_cred;	/* credentials */
370 	bool_t			cku_nodelayonerr;
371 						/* for CLSET_NODELAYONERR */
372 	int			cku_useresvport; /* Use reserved port */
373 	struct rpc_cots_client	*cku_stats;	/* stats for zone */
374 } cku_private_t;
375 
376 static struct cm_xprt *connmgr_wrapconnect(struct cm_xprt *,
377 	const struct timeval *, struct netbuf *, int, struct netbuf *,
378 	struct rpc_err *, bool_t, bool_t);
379 
380 static bool_t	connmgr_connect(struct cm_xprt *, queue_t *, struct netbuf *,
381 				int, calllist_t *, int *, bool_t reconnect,
382 				const struct timeval *, bool_t);
383 
384 static bool_t	connmgr_setopt(queue_t *, int, int, calllist_t *);
385 static void	connmgr_sndrel(struct cm_xprt *);
386 static void	connmgr_snddis(struct cm_xprt *);
387 static void	connmgr_close(struct cm_xprt *);
388 static void	connmgr_release(struct cm_xprt *);
389 static struct cm_xprt *connmgr_wrapget(struct netbuf *, const struct timeval *,
390 	cku_private_t *);
391 
392 static struct cm_xprt *connmgr_get(struct netbuf *, const struct timeval *,
393 	struct netbuf *, int, struct netbuf *, struct rpc_err *, dev_t,
394 	bool_t, int);
395 
396 static void connmgr_cancelconn(struct cm_xprt *);
397 static enum clnt_stat connmgr_cwait(struct cm_xprt *, const struct timeval *,
398 	bool_t);
399 static void connmgr_dis_and_wait(struct cm_xprt *);
400 
401 static void	clnt_dispatch_send(queue_t *, mblk_t *, calllist_t *, uint_t,
402 					uint_t);
403 
404 static int clnt_delay(clock_t, bool_t);
405 
406 static int waitforack(calllist_t *, t_scalar_t, const struct timeval *, bool_t);
407 
408 /*
409  * Operations vector for TCP/IP based RPC
410  */
411 static struct clnt_ops tcp_ops = {
412 	clnt_cots_kcallit,	/* do rpc call */
413 	clnt_cots_kabort,	/* abort call */
414 	clnt_cots_kerror,	/* return error status */
415 	clnt_cots_kfreeres,	/* free results */
416 	clnt_cots_kdestroy,	/* destroy rpc handle */
417 	clnt_cots_kcontrol,	/* the ioctl() of rpc */
418 	clnt_cots_ksettimers,	/* set retry timers */
419 };
420 
421 static int rpc_kstat_instance = 0;  /* keeps the current instance */
422 				/* number for the next kstat_create */
423 
424 static struct cm_xprt *cm_hd = NULL;
425 static kmutex_t connmgr_lock;	/* for connection mngr's list of transports */
426 
427 extern kmutex_t clnt_max_msg_lock;
428 
429 static calllist_t *clnt_pending = NULL;
430 extern kmutex_t clnt_pending_lock;
431 
432 static int clnt_cots_hash_size = DEFAULT_HASH_SIZE;
433 
434 static call_table_t *cots_call_ht;
435 
436 static const struct rpc_cots_client {
437 	kstat_named_t	rccalls;
438 	kstat_named_t	rcbadcalls;
439 	kstat_named_t	rcbadxids;
440 	kstat_named_t	rctimeouts;
441 	kstat_named_t	rcnewcreds;
442 	kstat_named_t	rcbadverfs;
443 	kstat_named_t	rctimers;
444 	kstat_named_t	rccantconn;
445 	kstat_named_t	rcnomem;
446 	kstat_named_t	rcintrs;
447 } cots_rcstat_tmpl = {
448 	{ "calls",	KSTAT_DATA_UINT64 },
449 	{ "badcalls",	KSTAT_DATA_UINT64 },
450 	{ "badxids",	KSTAT_DATA_UINT64 },
451 	{ "timeouts",	KSTAT_DATA_UINT64 },
452 	{ "newcreds",	KSTAT_DATA_UINT64 },
453 	{ "badverfs",	KSTAT_DATA_UINT64 },
454 	{ "timers",	KSTAT_DATA_UINT64 },
455 	{ "cantconn",	KSTAT_DATA_UINT64 },
456 	{ "nomem",	KSTAT_DATA_UINT64 },
457 	{ "interrupts", KSTAT_DATA_UINT64 }
458 };
459 
460 #define	COTSRCSTAT_INCR(p, x)	\
461 	atomic_add_64(&(p)->x.value.ui64, 1)
462 
463 #define	CLNT_MAX_CONNS	1	/* concurrent connections between clnt/srvr */
464 static int clnt_max_conns = CLNT_MAX_CONNS;
465 
466 #define	CLNT_MIN_TIMEOUT	10	/* seconds to wait after we get a */
467 					/* connection reset */
468 #define	CLNT_MIN_CONNTIMEOUT	5	/* seconds to wait for a connection */
469 
470 
471 static int clnt_cots_min_tout = CLNT_MIN_TIMEOUT;
472 static int clnt_cots_min_conntout = CLNT_MIN_CONNTIMEOUT;
473 
474 /*
475  * Limit the number of times we will attempt to receive a reply without
476  * re-sending a response.
477  */
478 #define	CLNT_MAXRECV_WITHOUT_RETRY	3
479 static uint_t clnt_cots_maxrecv	= CLNT_MAXRECV_WITHOUT_RETRY;
480 
481 uint_t *clnt_max_msg_sizep;
482 void (*clnt_stop_idle)(queue_t *wq);
483 
484 #define	ptoh(p)		(&((p)->cku_client))
485 #define	htop(h)		((cku_private_t *)((h)->cl_private))
486 
487 /*
488  * Times to retry
489  */
490 #define	REFRESHES	2	/* authentication refreshes */
491 
492 /*
493  * The following is used to determine the global default behavior for
494  * COTS when binding to a local port.
495  *
496  * If the value is set to 1 the default will be to select a reserved
497  * (aka privileged) port, if the value is zero the default will be to
498  * use non-reserved ports.  Users of kRPC may override this by using
499  * CLNT_CONTROL() and CLSET_BINDRESVPORT.
500  */
501 static int clnt_cots_do_bindresvport = 1;
502 
503 static zone_key_t zone_cots_key;
504 
505 /*
506  * We need to do this after all kernel threads in the zone have exited.
507  */
508 /* ARGSUSED */
509 static void
510 clnt_zone_destroy(zoneid_t zoneid, void *unused)
511 {
512 	struct cm_xprt **cmp;
513 	struct cm_xprt *cm_entry;
514 	struct cm_xprt *freelist = NULL;
515 
516 	mutex_enter(&connmgr_lock);
517 	cmp = &cm_hd;
518 	while ((cm_entry = *cmp) != NULL) {
519 		if (cm_entry->x_zoneid == zoneid) {
520 			*cmp = cm_entry->x_next;
521 			cm_entry->x_next = freelist;
522 			freelist = cm_entry;
523 		} else {
524 			cmp = &cm_entry->x_next;
525 		}
526 	}
527 	mutex_exit(&connmgr_lock);
528 	while ((cm_entry = freelist) != NULL) {
529 		freelist = cm_entry->x_next;
530 		connmgr_close(cm_entry);
531 	}
532 }
533 
534 int
535 clnt_cots_kcreate(dev_t dev, struct netbuf *addr, int family, rpcprog_t prog,
536 	rpcvers_t vers, uint_t max_msgsize, cred_t *cred, CLIENT **ncl)
537 {
538 	CLIENT *h;
539 	cku_private_t *p;
540 	struct rpc_msg call_msg;
541 	struct rpcstat *rpcstat;
542 
543 	RPCLOG(8, "clnt_cots_kcreate: prog %u\n", prog);
544 
545 	rpcstat = zone_getspecific(rpcstat_zone_key, rpc_zone());
546 	ASSERT(rpcstat != NULL);
547 
548 	/* Allocate and intialize the client handle. */
549 	p = kmem_zalloc(sizeof (*p), KM_SLEEP);
550 
551 	h = ptoh(p);
552 
553 	h->cl_private = (caddr_t)p;
554 	h->cl_auth = authkern_create();
555 	h->cl_ops = &tcp_ops;
556 
557 	cv_init(&p->cku_call.call_cv, NULL, CV_DEFAULT, NULL);
558 	mutex_init(&p->cku_call.call_lock, NULL, MUTEX_DEFAULT, NULL);
559 
560 	/*
561 	 * If the current sanity check size in rpcmod is smaller
562 	 * than the size needed, then increase the sanity check.
563 	 */
564 	if (max_msgsize != 0 && clnt_max_msg_sizep != NULL &&
565 	    max_msgsize > *clnt_max_msg_sizep) {
566 		mutex_enter(&clnt_max_msg_lock);
567 		if (max_msgsize > *clnt_max_msg_sizep)
568 			*clnt_max_msg_sizep = max_msgsize;
569 		mutex_exit(&clnt_max_msg_lock);
570 	}
571 
572 	p->cku_outbuflen = COTS_DEFAULT_ALLOCSIZE;
573 
574 	/* Preserialize the call message header */
575 
576 	call_msg.rm_xid = 0;
577 	call_msg.rm_direction = CALL;
578 	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
579 	call_msg.rm_call.cb_prog = prog;
580 	call_msg.rm_call.cb_vers = vers;
581 
582 	xdrmem_create(&p->cku_outxdr, p->cku_rpchdr, WIRE_HDR_SIZE, XDR_ENCODE);
583 
584 	if (!xdr_callhdr(&p->cku_outxdr, &call_msg)) {
585 		RPCLOG0(1, "clnt_cots_kcreate - Fatal header serialization "
586 		    "error\n");
587 		auth_destroy(h->cl_auth);
588 		kmem_free(p, sizeof (cku_private_t));
589 		RPCLOG0(1, "clnt_cots_kcreate: create failed error EINVAL\n");
590 		return (EINVAL);		/* XXX */
591 	}
592 
593 	/*
594 	 * The zalloc initialized the fields below.
595 	 * p->cku_xid = 0;
596 	 * p->cku_flags = 0;
597 	 * p->cku_srcaddr.len = 0;
598 	 * p->cku_srcaddr.maxlen = 0;
599 	 */
600 
601 	p->cku_cred = cred;
602 	p->cku_device = dev;
603 	p->cku_addrfmly = family;
604 	p->cku_addr.buf = kmem_zalloc(addr->maxlen, KM_SLEEP);
605 	p->cku_addr.maxlen = addr->maxlen;
606 	p->cku_addr.len = addr->len;
607 	bcopy(addr->buf, p->cku_addr.buf, addr->len);
608 	p->cku_stats = rpcstat->rpc_cots_client;
609 	p->cku_useresvport = -1; /* value is has not been set */
610 
611 	*ncl = h;
612 	return (0);
613 }
614 
615 /*ARGSUSED*/
616 static void
617 clnt_cots_kabort(CLIENT *h)
618 {
619 }
620 
621 /*
622  * Return error info on this handle.
623  */
624 static void
625 clnt_cots_kerror(CLIENT *h, struct rpc_err *err)
626 {
627 	/* LINTED pointer alignment */
628 	cku_private_t *p = htop(h);
629 
630 	*err = p->cku_err;
631 }
632 
633 static bool_t
634 clnt_cots_kfreeres(CLIENT *h, xdrproc_t xdr_res, caddr_t res_ptr)
635 {
636 	/* LINTED pointer alignment */
637 	cku_private_t *p = htop(h);
638 	XDR *xdrs;
639 
640 	xdrs = &(p->cku_outxdr);
641 	xdrs->x_op = XDR_FREE;
642 	return ((*xdr_res)(xdrs, res_ptr));
643 }
644 
645 static bool_t
646 clnt_cots_kcontrol(CLIENT *h, int cmd, char *arg)
647 {
648 	cku_private_t *p = htop(h);
649 
650 	switch (cmd) {
651 	case CLSET_PROGRESS:
652 		p->cku_progress = TRUE;
653 		return (TRUE);
654 
655 	case CLSET_XID:
656 		if (arg == NULL)
657 			return (FALSE);
658 
659 		p->cku_xid = *((uint32_t *)arg);
660 		return (TRUE);
661 
662 	case CLGET_XID:
663 		if (arg == NULL)
664 			return (FALSE);
665 
666 		*((uint32_t *)arg) = p->cku_xid;
667 		return (TRUE);
668 
669 	case CLSET_NODELAYONERR:
670 		if (arg == NULL)
671 			return (FALSE);
672 
673 		if (*((bool_t *)arg) == TRUE) {
674 			p->cku_nodelayonerr = TRUE;
675 			return (TRUE);
676 		}
677 		if (*((bool_t *)arg) == FALSE) {
678 			p->cku_nodelayonerr = FALSE;
679 			return (TRUE);
680 		}
681 		return (FALSE);
682 
683 	case CLGET_NODELAYONERR:
684 		if (arg == NULL)
685 			return (FALSE);
686 
687 		*((bool_t *)arg) = p->cku_nodelayonerr;
688 		return (TRUE);
689 
690 	case CLSET_BINDRESVPORT:
691 		if (arg == NULL)
692 			return (FALSE);
693 
694 		if (*(int *)arg != 1 && *(int *)arg != 0)
695 			return (FALSE);
696 
697 		p->cku_useresvport = *(int *)arg;
698 
699 		return (TRUE);
700 
701 	case CLGET_BINDRESVPORT:
702 		if (arg == NULL)
703 			return (FALSE);
704 
705 		*(int *)arg = p->cku_useresvport;
706 
707 		return (TRUE);
708 
709 	default:
710 		return (FALSE);
711 	}
712 }
713 
714 /*
715  * Destroy rpc handle.  Frees the space used for output buffer,
716  * private data, and handle structure.
717  */
718 static void
719 clnt_cots_kdestroy(CLIENT *h)
720 {
721 	/* LINTED pointer alignment */
722 	cku_private_t *p = htop(h);
723 	calllist_t *call = &p->cku_call;
724 
725 	RPCLOG(8, "clnt_cots_kdestroy h: %p\n", (void *)h);
726 	RPCLOG(8, "clnt_cots_kdestroy h: xid=0x%x\n", p->cku_xid);
727 
728 	if (p->cku_flags & CKU_ONQUEUE) {
729 		RPCLOG(64, "clnt_cots_kdestroy h: removing call for xid 0x%x "
730 		    "from dispatch list\n", p->cku_xid);
731 		call_table_remove(call);
732 	}
733 
734 	if (call->call_reply)
735 		freemsg(call->call_reply);
736 	cv_destroy(&call->call_cv);
737 	mutex_destroy(&call->call_lock);
738 
739 	kmem_free(p->cku_srcaddr.buf, p->cku_srcaddr.maxlen);
740 	kmem_free(p->cku_addr.buf, p->cku_addr.maxlen);
741 	kmem_free(p, sizeof (*p));
742 }
743 
744 static int clnt_cots_pulls;
745 #define	RM_HDR_SIZE	4	/* record mark header size */
746 
747 /*
748  * Call remote procedure.
749  */
750 static enum clnt_stat
751 clnt_cots_kcallit(CLIENT *h, rpcproc_t procnum, xdrproc_t xdr_args,
752     caddr_t argsp, xdrproc_t xdr_results, caddr_t resultsp, struct timeval wait)
753 {
754 	/* LINTED pointer alignment */
755 	cku_private_t *p = htop(h);
756 	calllist_t *call = &p->cku_call;
757 	XDR *xdrs;
758 	struct rpc_msg reply_msg;
759 	mblk_t *mp;
760 #ifdef	RPCDEBUG
761 	clock_t time_sent;
762 #endif
763 	struct netbuf *retryaddr;
764 	struct cm_xprt *cm_entry = NULL;
765 	queue_t *wq;
766 	int len;
767 	int mpsize;
768 	int refreshes = REFRESHES;
769 	int interrupted;
770 	int tidu_size;
771 	enum clnt_stat status;
772 	struct timeval cwait;
773 	bool_t delay_first = FALSE;
774 	clock_t ticks;
775 
776 	RPCLOG(2, "clnt_cots_kcallit, procnum %u\n", procnum);
777 	COTSRCSTAT_INCR(p->cku_stats, rccalls);
778 
779 	RPCLOG(2, "clnt_cots_kcallit: wait.tv_sec: %ld\n", wait.tv_sec);
780 	RPCLOG(2, "clnt_cots_kcallit: wait.tv_usec: %ld\n", wait.tv_usec);
781 
782 	/*
783 	 * Bug ID 1240234:
784 	 * Look out for zero length timeouts. We don't want to
785 	 * wait zero seconds for a connection to be established.
786 	 */
787 	if (wait.tv_sec < clnt_cots_min_conntout) {
788 		cwait.tv_sec = clnt_cots_min_conntout;
789 		cwait.tv_usec = 0;
790 		RPCLOG(8, "clnt_cots_kcallit: wait.tv_sec (%ld) too low,",
791 		    wait.tv_sec);
792 		RPCLOG(8, " setting to: %d\n", clnt_cots_min_conntout);
793 	} else {
794 		cwait = wait;
795 	}
796 
797 call_again:
798 	if (cm_entry) {
799 		connmgr_release(cm_entry);
800 		cm_entry = NULL;
801 	}
802 
803 	mp = NULL;
804 
805 	/*
806 	 * If the call is not a retry, allocate a new xid and cache it
807 	 * for future retries.
808 	 * Bug ID 1246045:
809 	 * Treat call as a retry for purposes of binding the source
810 	 * port only if we actually attempted to send anything on
811 	 * the previous call.
812 	 */
813 	if (p->cku_xid == 0) {
814 		p->cku_xid = alloc_xid();
815 		call->call_zoneid = rpc_zoneid();
816 
817 		/*
818 		 * We need to ASSERT here that our xid != 0 because this
819 		 * determines whether or not our call record gets placed on
820 		 * the hash table or the linked list.  By design, we mandate
821 		 * that RPC calls over cots must have xid's != 0, so we can
822 		 * ensure proper management of the hash table.
823 		 */
824 		ASSERT(p->cku_xid != 0);
825 
826 		retryaddr = NULL;
827 		p->cku_flags &= ~CKU_SENT;
828 
829 		if (p->cku_flags & CKU_ONQUEUE) {
830 			RPCLOG(8, "clnt_cots_kcallit: new call, dequeuing old"
831 			    " one (%p)\n", (void *)call);
832 			call_table_remove(call);
833 			p->cku_flags &= ~CKU_ONQUEUE;
834 			RPCLOG(64, "clnt_cots_kcallit: removing call from "
835 			    "dispatch list because xid was zero (now 0x%x)\n",
836 			    p->cku_xid);
837 		}
838 
839 		if (call->call_reply != NULL) {
840 			freemsg(call->call_reply);
841 			call->call_reply = NULL;
842 		}
843 	} else if (p->cku_srcaddr.buf == NULL || p->cku_srcaddr.len == 0) {
844 		retryaddr = NULL;
845 
846 	} else if (p->cku_flags & CKU_SENT) {
847 		retryaddr = &p->cku_srcaddr;
848 
849 	} else {
850 		/*
851 		 * Bug ID 1246045: Nothing was sent, so set retryaddr to
852 		 * NULL and let connmgr_get() bind to any source port it
853 		 * can get.
854 		 */
855 		retryaddr = NULL;
856 	}
857 
858 	RPCLOG(64, "clnt_cots_kcallit: xid = 0x%x", p->cku_xid);
859 	RPCLOG(64, " flags = 0x%x\n", p->cku_flags);
860 
861 	p->cku_err.re_status = RPC_TIMEDOUT;
862 	p->cku_err.re_errno = p->cku_err.re_terrno = 0;
863 
864 	cm_entry = connmgr_wrapget(retryaddr, &cwait, p);
865 
866 	if (cm_entry == NULL) {
867 		RPCLOG(1, "clnt_cots_kcallit: can't connect status %s\n",
868 		    clnt_sperrno(p->cku_err.re_status));
869 
870 		/*
871 		 * The reasons why we fail to create a connection are
872 		 * varied. In most cases we don't want the caller to
873 		 * immediately retry. This could have one or more
874 		 * bad effects. This includes flooding the net with
875 		 * connect requests to ports with no listener; a hard
876 		 * kernel loop due to all the "reserved" TCP ports being
877 		 * in use.
878 		 */
879 		delay_first = TRUE;
880 
881 		/*
882 		 * Even if we end up returning EINTR, we still count a
883 		 * a "can't connect", because the connection manager
884 		 * might have been committed to waiting for or timing out on
885 		 * a connection.
886 		 */
887 		COTSRCSTAT_INCR(p->cku_stats, rccantconn);
888 		switch (p->cku_err.re_status) {
889 		case RPC_INTR:
890 			p->cku_err.re_errno = EINTR;
891 
892 			/*
893 			 * No need to delay because a UNIX signal(2)
894 			 * interrupted us. The caller likely won't
895 			 * retry the CLNT_CALL() and even if it does,
896 			 * we assume the caller knows what it is doing.
897 			 */
898 			delay_first = FALSE;
899 			break;
900 
901 		case RPC_TIMEDOUT:
902 			p->cku_err.re_errno = ETIMEDOUT;
903 
904 			/*
905 			 * No need to delay because timed out already
906 			 * on the connection request and assume that the
907 			 * transport time out is longer than our minimum
908 			 * timeout, or least not too much smaller.
909 			 */
910 			delay_first = FALSE;
911 			break;
912 
913 		case RPC_SYSTEMERROR:
914 		case RPC_TLIERROR:
915 			/*
916 			 * We want to delay here because a transient
917 			 * system error has a better chance of going away
918 			 * if we delay a bit. If it's not transient, then
919 			 * we don't want end up in a hard kernel loop
920 			 * due to retries.
921 			 */
922 			ASSERT(p->cku_err.re_errno != 0);
923 			break;
924 
925 
926 		case RPC_CANTCONNECT:
927 			/*
928 			 * RPC_CANTCONNECT is set on T_ERROR_ACK which
929 			 * implies some error down in the TCP layer or
930 			 * below. If cku_nodelayonerror is set then we
931 			 * assume the caller knows not to try too hard.
932 			 */
933 			RPCLOG0(8, "clnt_cots_kcallit: connection failed,");
934 			RPCLOG0(8, " re_status=RPC_CANTCONNECT,");
935 			RPCLOG(8, " re_errno=%d,", p->cku_err.re_errno);
936 			RPCLOG(8, " cku_nodelayonerr=%d", p->cku_nodelayonerr);
937 			if (p->cku_nodelayonerr == TRUE)
938 				delay_first = FALSE;
939 
940 			p->cku_err.re_errno = EIO;
941 
942 			break;
943 
944 		case RPC_XPRTFAILED:
945 			/*
946 			 * We want to delay here because we likely
947 			 * got a refused connection.
948 			 */
949 			if (p->cku_err.re_errno == 0)
950 				p->cku_err.re_errno = EIO;
951 
952 			RPCLOG(1, "clnt_cots_kcallit: transport failed: %d\n",
953 			    p->cku_err.re_errno);
954 
955 			break;
956 
957 		default:
958 			/*
959 			 * We delay here because it is better to err
960 			 * on the side of caution. If we got here then
961 			 * status could have been RPC_SUCCESS, but we
962 			 * know that we did not get a connection, so
963 			 * force the rpc status to RPC_CANTCONNECT.
964 			 */
965 			p->cku_err.re_status = RPC_CANTCONNECT;
966 			p->cku_err.re_errno = EIO;
967 			break;
968 		}
969 		if (delay_first == TRUE)
970 			ticks = clnt_cots_min_tout * drv_usectohz(1000000);
971 		goto cots_done;
972 	}
973 
974 	/*
975 	 * If we've never sent any request on this connection (send count
976 	 * is zero, or the connection has been reset), cache the
977 	 * the connection's create time and send a request (possibly a retry)
978 	 */
979 	if ((p->cku_flags & CKU_SENT) == 0 ||
980 	    p->cku_ctime != cm_entry->x_ctime) {
981 		p->cku_ctime = cm_entry->x_ctime;
982 
983 	} else if ((p->cku_flags & CKU_SENT) && (p->cku_flags & CKU_ONQUEUE) &&
984 	    (call->call_reply != NULL ||
985 	    p->cku_recv_attempts < clnt_cots_maxrecv)) {
986 
987 		/*
988 		 * If we've sent a request and our call is on the dispatch
989 		 * queue and we haven't made too many receive attempts, then
990 		 * don't re-send, just receive.
991 		 */
992 		p->cku_recv_attempts++;
993 		goto read_again;
994 	}
995 
996 	/*
997 	 * Now we create the RPC request in a STREAMS message.  We have to do
998 	 * this after the call to connmgr_get so that we have the correct
999 	 * TIDU size for the transport.
1000 	 */
1001 	tidu_size = cm_entry->x_tidu_size;
1002 	len = MSG_OFFSET + MAX(tidu_size, RM_HDR_SIZE + WIRE_HDR_SIZE);
1003 
1004 	while ((mp = allocb(len, BPRI_MED)) == NULL) {
1005 		if (strwaitbuf(len, BPRI_MED)) {
1006 			p->cku_err.re_status = RPC_SYSTEMERROR;
1007 			p->cku_err.re_errno = ENOSR;
1008 			COTSRCSTAT_INCR(p->cku_stats, rcnomem);
1009 			goto cots_done;
1010 		}
1011 	}
1012 	xdrs = &p->cku_outxdr;
1013 	xdrmblk_init(xdrs, mp, XDR_ENCODE, tidu_size);
1014 	mpsize = MBLKSIZE(mp);
1015 	ASSERT(mpsize >= len);
1016 	ASSERT(mp->b_rptr == mp->b_datap->db_base);
1017 
1018 	/*
1019 	 * If the size of mblk is not appreciably larger than what we
1020 	 * asked, then resize the mblk to exactly len bytes. The reason for
1021 	 * this: suppose len is 1600 bytes, the tidu is 1460 bytes
1022 	 * (from TCP over ethernet), and the arguments to the RPC require
1023 	 * 2800 bytes. Ideally we want the protocol to render two
1024 	 * ~1400 byte segments over the wire. However if allocb() gives us a 2k
1025 	 * mblk, and we allocate a second mblk for the remainder, the protocol
1026 	 * module may generate 3 segments over the wire:
1027 	 * 1460 bytes for the first, 448 (2048 - 1600) for the second, and
1028 	 * 892 for the third. If we "waste" 448 bytes in the first mblk,
1029 	 * the XDR encoding will generate two ~1400 byte mblks, and the
1030 	 * protocol module is more likely to produce properly sized segments.
1031 	 */
1032 	if ((mpsize >> 1) <= len)
1033 		mp->b_rptr += (mpsize - len);
1034 
1035 	/*
1036 	 * Adjust b_rptr to reserve space for the non-data protocol headers
1037 	 * any downstream modules might like to add, and for the
1038 	 * record marking header.
1039 	 */
1040 	mp->b_rptr += (MSG_OFFSET + RM_HDR_SIZE);
1041 
1042 	if (h->cl_auth->ah_cred.oa_flavor != RPCSEC_GSS) {
1043 		/* Copy in the preserialized RPC header information. */
1044 		bcopy(p->cku_rpchdr, mp->b_rptr, WIRE_HDR_SIZE);
1045 
1046 		/* Use XDR_SETPOS() to set the b_wptr to past the RPC header. */
1047 		XDR_SETPOS(xdrs, (uint_t)(mp->b_rptr - mp->b_datap->db_base +
1048 		    WIRE_HDR_SIZE));
1049 
1050 		ASSERT((mp->b_wptr - mp->b_rptr) == WIRE_HDR_SIZE);
1051 
1052 		/* Serialize the procedure number and the arguments. */
1053 		if ((!XDR_PUTINT32(xdrs, (int32_t *)&procnum)) ||
1054 		    (!AUTH_MARSHALL(h->cl_auth, xdrs, p->cku_cred)) ||
1055 		    (!(*xdr_args)(xdrs, argsp))) {
1056 			p->cku_err.re_status = RPC_CANTENCODEARGS;
1057 			p->cku_err.re_errno = EIO;
1058 			goto cots_done;
1059 		}
1060 
1061 		(*(uint32_t *)(mp->b_rptr)) = p->cku_xid;
1062 	} else {
1063 		uint32_t *uproc = (uint32_t *)&p->cku_rpchdr[WIRE_HDR_SIZE];
1064 		IXDR_PUT_U_INT32(uproc, procnum);
1065 
1066 		(*(uint32_t *)(&p->cku_rpchdr[0])) = p->cku_xid;
1067 
1068 		/* Use XDR_SETPOS() to set the b_wptr. */
1069 		XDR_SETPOS(xdrs, (uint_t)(mp->b_rptr - mp->b_datap->db_base));
1070 
1071 		/* Serialize the procedure number and the arguments. */
1072 		if (!AUTH_WRAP(h->cl_auth, p->cku_rpchdr, WIRE_HDR_SIZE+4,
1073 		    xdrs, xdr_args, argsp)) {
1074 			p->cku_err.re_status = RPC_CANTENCODEARGS;
1075 			p->cku_err.re_errno = EIO;
1076 			goto cots_done;
1077 		}
1078 	}
1079 
1080 	RPCLOG(2, "clnt_cots_kcallit: connected, sending call, tidu_size %d\n",
1081 	    tidu_size);
1082 
1083 	wq = cm_entry->x_wq;
1084 	clnt_dispatch_send(wq, mp, call, p->cku_xid,
1085 	    (p->cku_flags & CKU_ONQUEUE));
1086 
1087 	RPCLOG(64, "clnt_cots_kcallit: sent call for xid 0x%x\n",
1088 	    (uint_t)p->cku_xid);
1089 	p->cku_flags = (CKU_ONQUEUE|CKU_SENT);
1090 	p->cku_recv_attempts = 1;
1091 
1092 #ifdef	RPCDEBUG
1093 	time_sent = lbolt;
1094 #endif
1095 
1096 	/*
1097 	 * Wait for a reply or a timeout.  If there is no error or timeout,
1098 	 * (both indicated by call_status), call->call_reply will contain
1099 	 * the RPC reply message.
1100 	 */
1101 read_again:
1102 	mutex_enter(&call->call_lock);
1103 	interrupted = 0;
1104 	if (call->call_status == RPC_TIMEDOUT) {
1105 		/*
1106 		 * Indicate that the lwp is not to be stopped while waiting
1107 		 * for this network traffic.  This is to avoid deadlock while
1108 		 * debugging a process via /proc and also to avoid recursive
1109 		 * mutex_enter()s due to NFS page faults while stopping
1110 		 * (NFS holds locks when it calls here).
1111 		 */
1112 		clock_t cv_wait_ret;
1113 		clock_t timout;
1114 		clock_t oldlbolt;
1115 
1116 		klwp_t *lwp = ttolwp(curthread);
1117 
1118 		if (lwp != NULL)
1119 			lwp->lwp_nostop++;
1120 
1121 		oldlbolt = lbolt;
1122 		timout = wait.tv_sec * drv_usectohz(1000000) +
1123 		    drv_usectohz(wait.tv_usec) + oldlbolt;
1124 		/*
1125 		 * Iterate until the call_status is changed to something
1126 		 * other that RPC_TIMEDOUT, or if cv_timedwait_sig() returns
1127 		 * something <=0 zero. The latter means that we timed
1128 		 * out.
1129 		 */
1130 		if (h->cl_nosignal)
1131 			while ((cv_wait_ret = cv_timedwait(&call->call_cv,
1132 			    &call->call_lock, timout)) > 0 &&
1133 			    call->call_status == RPC_TIMEDOUT)
1134 				;
1135 		else
1136 			while ((cv_wait_ret = cv_timedwait_sig(
1137 			    &call->call_cv,
1138 			    &call->call_lock, timout)) > 0 &&
1139 			    call->call_status == RPC_TIMEDOUT)
1140 				;
1141 
1142 		switch (cv_wait_ret) {
1143 		case 0:
1144 			/*
1145 			 * If we got out of the above loop with
1146 			 * cv_timedwait_sig() returning 0, then we were
1147 			 * interrupted regardless what call_status is.
1148 			 */
1149 			interrupted = 1;
1150 			break;
1151 		case -1:
1152 			/* cv_timedwait_sig() timed out */
1153 			break;
1154 		default:
1155 
1156 			/*
1157 			 * We were cv_signaled(). If we didn't
1158 			 * get a successful call_status and returned
1159 			 * before time expired, delay up to clnt_cots_min_tout
1160 			 * seconds so that the caller doesn't immediately
1161 			 * try to call us again and thus force the
1162 			 * same condition that got us here (such
1163 			 * as a RPC_XPRTFAILED due to the server not
1164 			 * listening on the end-point.
1165 			 */
1166 			if (call->call_status != RPC_SUCCESS) {
1167 				clock_t curlbolt;
1168 				clock_t diff;
1169 
1170 				curlbolt = ddi_get_lbolt();
1171 				ticks = clnt_cots_min_tout *
1172 				    drv_usectohz(1000000);
1173 				diff = curlbolt - oldlbolt;
1174 				if (diff < ticks) {
1175 					delay_first = TRUE;
1176 					if (diff > 0)
1177 						ticks -= diff;
1178 				}
1179 			}
1180 			break;
1181 		}
1182 
1183 		if (lwp != NULL)
1184 			lwp->lwp_nostop--;
1185 	}
1186 	/*
1187 	 * Get the reply message, if any.  This will be freed at the end
1188 	 * whether or not an error occurred.
1189 	 */
1190 	mp = call->call_reply;
1191 	call->call_reply = NULL;
1192 
1193 	/*
1194 	 * call_err is the error info when the call is on dispatch queue.
1195 	 * cku_err is the error info returned to the caller.
1196 	 * Sync cku_err with call_err for local message processing.
1197 	 */
1198 
1199 	status = call->call_status;
1200 	p->cku_err = call->call_err;
1201 	mutex_exit(&call->call_lock);
1202 
1203 	if (status != RPC_SUCCESS) {
1204 		switch (status) {
1205 		case RPC_TIMEDOUT:
1206 			if (interrupted) {
1207 				COTSRCSTAT_INCR(p->cku_stats, rcintrs);
1208 				p->cku_err.re_status = RPC_INTR;
1209 				p->cku_err.re_errno = EINTR;
1210 				RPCLOG(1, "clnt_cots_kcallit: xid 0x%x",
1211 				    p->cku_xid);
1212 				RPCLOG(1, "signal interrupted at %ld", lbolt);
1213 				RPCLOG(1, ", was sent at %ld\n", time_sent);
1214 			} else {
1215 				COTSRCSTAT_INCR(p->cku_stats, rctimeouts);
1216 				p->cku_err.re_errno = ETIMEDOUT;
1217 				RPCLOG(1, "clnt_cots_kcallit: timed out at %ld",
1218 				    lbolt);
1219 				RPCLOG(1, ", was sent at %ld\n", time_sent);
1220 			}
1221 			break;
1222 
1223 		case RPC_XPRTFAILED:
1224 			if (p->cku_err.re_errno == 0)
1225 				p->cku_err.re_errno = EIO;
1226 
1227 			RPCLOG(1, "clnt_cots_kcallit: transport failed: %d\n",
1228 			    p->cku_err.re_errno);
1229 			break;
1230 
1231 		case RPC_SYSTEMERROR:
1232 			ASSERT(p->cku_err.re_errno);
1233 			RPCLOG(1, "clnt_cots_kcallit: system error: %d\n",
1234 			    p->cku_err.re_errno);
1235 			break;
1236 
1237 		default:
1238 			p->cku_err.re_status = RPC_SYSTEMERROR;
1239 			p->cku_err.re_errno = EIO;
1240 			RPCLOG(1, "clnt_cots_kcallit: error: %s\n",
1241 			    clnt_sperrno(status));
1242 			break;
1243 		}
1244 		if (p->cku_err.re_status != RPC_TIMEDOUT) {
1245 
1246 			if (p->cku_flags & CKU_ONQUEUE) {
1247 				call_table_remove(call);
1248 				p->cku_flags &= ~CKU_ONQUEUE;
1249 			}
1250 
1251 			RPCLOG(64, "clnt_cots_kcallit: non TIMEOUT so xid 0x%x "
1252 			    "taken off dispatch list\n", p->cku_xid);
1253 			if (call->call_reply) {
1254 				freemsg(call->call_reply);
1255 				call->call_reply = NULL;
1256 			}
1257 		} else if (wait.tv_sec != 0) {
1258 			/*
1259 			 * We've sent the request over TCP and so we have
1260 			 * every reason to believe it will get
1261 			 * delivered. In which case returning a timeout is not
1262 			 * appropriate.
1263 			 */
1264 			if (p->cku_progress == TRUE &&
1265 			    p->cku_recv_attempts < clnt_cots_maxrecv) {
1266 				p->cku_err.re_status = RPC_INPROGRESS;
1267 			}
1268 		}
1269 		goto cots_done;
1270 	}
1271 
1272 	xdrs = &p->cku_inxdr;
1273 	xdrmblk_init(xdrs, mp, XDR_DECODE, 0);
1274 
1275 	reply_msg.rm_direction = REPLY;
1276 	reply_msg.rm_reply.rp_stat = MSG_ACCEPTED;
1277 	reply_msg.acpted_rply.ar_stat = SUCCESS;
1278 
1279 	reply_msg.acpted_rply.ar_verf = _null_auth;
1280 	/*
1281 	 *  xdr_results will be done in AUTH_UNWRAP.
1282 	 */
1283 	reply_msg.acpted_rply.ar_results.where = NULL;
1284 	reply_msg.acpted_rply.ar_results.proc = xdr_void;
1285 
1286 	if (xdr_replymsg(xdrs, &reply_msg)) {
1287 		enum clnt_stat re_status;
1288 
1289 		_seterr_reply(&reply_msg, &p->cku_err);
1290 
1291 		re_status = p->cku_err.re_status;
1292 		if (re_status == RPC_SUCCESS) {
1293 			/*
1294 			 * Reply is good, check auth.
1295 			 */
1296 			if (!AUTH_VALIDATE(h->cl_auth,
1297 			    &reply_msg.acpted_rply.ar_verf)) {
1298 				COTSRCSTAT_INCR(p->cku_stats, rcbadverfs);
1299 				RPCLOG0(1, "clnt_cots_kcallit: validation "
1300 				    "failure\n");
1301 				freemsg(mp);
1302 				(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
1303 				mutex_enter(&call->call_lock);
1304 				if (call->call_reply == NULL)
1305 					call->call_status = RPC_TIMEDOUT;
1306 				mutex_exit(&call->call_lock);
1307 				goto read_again;
1308 			} else if (!AUTH_UNWRAP(h->cl_auth, xdrs,
1309 			    xdr_results, resultsp)) {
1310 				RPCLOG0(1, "clnt_cots_kcallit: validation "
1311 				    "failure (unwrap)\n");
1312 				p->cku_err.re_status = RPC_CANTDECODERES;
1313 				p->cku_err.re_errno = EIO;
1314 			}
1315 		} else {
1316 			/* set errno in case we can't recover */
1317 			if (re_status != RPC_VERSMISMATCH &&
1318 			    re_status != RPC_AUTHERROR &&
1319 			    re_status != RPC_PROGVERSMISMATCH)
1320 				p->cku_err.re_errno = EIO;
1321 
1322 			if (re_status == RPC_AUTHERROR) {
1323 				/*
1324 				 * Maybe our credential need to be refreshed
1325 				 */
1326 				if (cm_entry) {
1327 					/*
1328 					 * There is the potential that the
1329 					 * cm_entry has/will be marked dead,
1330 					 * so drop the connection altogether,
1331 					 * force REFRESH to establish new
1332 					 * connection.
1333 					 */
1334 					connmgr_cancelconn(cm_entry);
1335 					cm_entry = NULL;
1336 				}
1337 
1338 				if ((refreshes > 0) &&
1339 				    AUTH_REFRESH(h->cl_auth, &reply_msg,
1340 				    p->cku_cred)) {
1341 					refreshes--;
1342 					(void) xdr_rpc_free_verifier(xdrs,
1343 					    &reply_msg);
1344 					freemsg(mp);
1345 					mp = NULL;
1346 
1347 					if (p->cku_flags & CKU_ONQUEUE) {
1348 						call_table_remove(call);
1349 						p->cku_flags &= ~CKU_ONQUEUE;
1350 					}
1351 
1352 					RPCLOG(64,
1353 					    "clnt_cots_kcallit: AUTH_ERROR, xid"
1354 					    " 0x%x removed off dispatch list\n",
1355 					    p->cku_xid);
1356 					if (call->call_reply) {
1357 						freemsg(call->call_reply);
1358 						call->call_reply = NULL;
1359 					}
1360 
1361 					COTSRCSTAT_INCR(p->cku_stats,
1362 					    rcbadcalls);
1363 					COTSRCSTAT_INCR(p->cku_stats,
1364 					    rcnewcreds);
1365 					goto call_again;
1366 				}
1367 
1368 				/*
1369 				 * We have used the client handle to
1370 				 * do an AUTH_REFRESH and the RPC status may
1371 				 * be set to RPC_SUCCESS; Let's make sure to
1372 				 * set it to RPC_AUTHERROR.
1373 				 */
1374 				p->cku_err.re_status = RPC_AUTHERROR;
1375 
1376 				/*
1377 				 * Map recoverable and unrecoverable
1378 				 * authentication errors to appropriate errno
1379 				 */
1380 				switch (p->cku_err.re_why) {
1381 				case AUTH_TOOWEAK:
1382 					/*
1383 					 * This could be a failure where the
1384 					 * server requires use of a reserved
1385 					 * port,  check and optionally set the
1386 					 * client handle useresvport trying
1387 					 * one more time. Next go round we
1388 					 * fall out with the tooweak error.
1389 					 */
1390 					if (p->cku_useresvport != 1) {
1391 						p->cku_useresvport = 1;
1392 						p->cku_xid = 0;
1393 						(void) xdr_rpc_free_verifier
1394 						    (xdrs, &reply_msg);
1395 						freemsg(mp);
1396 						goto call_again;
1397 					}
1398 					/* FALLTHRU */
1399 				case AUTH_BADCRED:
1400 				case AUTH_BADVERF:
1401 				case AUTH_INVALIDRESP:
1402 				case AUTH_FAILED:
1403 				case RPCSEC_GSS_NOCRED:
1404 				case RPCSEC_GSS_FAILED:
1405 						p->cku_err.re_errno = EACCES;
1406 						break;
1407 				case AUTH_REJECTEDCRED:
1408 				case AUTH_REJECTEDVERF:
1409 				default:	p->cku_err.re_errno = EIO;
1410 						break;
1411 				}
1412 				RPCLOG(1, "clnt_cots_kcallit : authentication"
1413 				    " failed with RPC_AUTHERROR of type %d\n",
1414 				    (int)p->cku_err.re_why);
1415 			}
1416 		}
1417 	} else {
1418 		/* reply didn't decode properly. */
1419 		p->cku_err.re_status = RPC_CANTDECODERES;
1420 		p->cku_err.re_errno = EIO;
1421 		RPCLOG0(1, "clnt_cots_kcallit: decode failure\n");
1422 	}
1423 
1424 	(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
1425 
1426 	if (p->cku_flags & CKU_ONQUEUE) {
1427 		call_table_remove(call);
1428 		p->cku_flags &= ~CKU_ONQUEUE;
1429 	}
1430 
1431 	RPCLOG(64, "clnt_cots_kcallit: xid 0x%x taken off dispatch list",
1432 	    p->cku_xid);
1433 	RPCLOG(64, " status is %s\n", clnt_sperrno(p->cku_err.re_status));
1434 cots_done:
1435 	if (cm_entry)
1436 		connmgr_release(cm_entry);
1437 
1438 	if (mp != NULL)
1439 		freemsg(mp);
1440 	if ((p->cku_flags & CKU_ONQUEUE) == 0 && call->call_reply) {
1441 		freemsg(call->call_reply);
1442 		call->call_reply = NULL;
1443 	}
1444 	if (p->cku_err.re_status != RPC_SUCCESS) {
1445 		RPCLOG0(1, "clnt_cots_kcallit: tail-end failure\n");
1446 		COTSRCSTAT_INCR(p->cku_stats, rcbadcalls);
1447 	}
1448 
1449 	/*
1450 	 * No point in delaying if the zone is going away.
1451 	 */
1452 	if (delay_first == TRUE &&
1453 	    !(zone_status_get(curproc->p_zone) >= ZONE_IS_SHUTTING_DOWN)) {
1454 		if (clnt_delay(ticks, h->cl_nosignal) == EINTR) {
1455 			p->cku_err.re_errno = EINTR;
1456 			p->cku_err.re_status = RPC_INTR;
1457 		}
1458 	}
1459 	return (p->cku_err.re_status);
1460 }
1461 
1462 /*
1463  * Kinit routine for cots.  This sets up the correct operations in
1464  * the client handle, as the handle may have previously been a clts
1465  * handle, and clears the xid field so there is no way a new call
1466  * could be mistaken for a retry.  It also sets in the handle the
1467  * information that is passed at create/kinit time but needed at
1468  * call time, as cots creates the transport at call time - device,
1469  * address of the server, protocol family.
1470  */
1471 void
1472 clnt_cots_kinit(CLIENT *h, dev_t dev, int family, struct netbuf *addr,
1473 	int max_msgsize, cred_t *cred)
1474 {
1475 	/* LINTED pointer alignment */
1476 	cku_private_t *p = htop(h);
1477 	calllist_t *call = &p->cku_call;
1478 
1479 	h->cl_ops = &tcp_ops;
1480 	if (p->cku_flags & CKU_ONQUEUE) {
1481 		call_table_remove(call);
1482 		p->cku_flags &= ~CKU_ONQUEUE;
1483 		RPCLOG(64, "clnt_cots_kinit: removing call for xid 0x%x from"
1484 		    " dispatch list\n", p->cku_xid);
1485 	}
1486 
1487 	if (call->call_reply != NULL) {
1488 		freemsg(call->call_reply);
1489 		call->call_reply = NULL;
1490 	}
1491 
1492 	call->call_bucket = NULL;
1493 	call->call_hash = 0;
1494 
1495 	/*
1496 	 * We don't clear cku_flags here, because clnt_cots_kcallit()
1497 	 * takes care of handling the cku_flags reset.
1498 	 */
1499 	p->cku_xid = 0;
1500 	p->cku_device = dev;
1501 	p->cku_addrfmly = family;
1502 	p->cku_cred = cred;
1503 
1504 	if (p->cku_addr.maxlen < addr->len) {
1505 		if (p->cku_addr.maxlen != 0 && p->cku_addr.buf != NULL)
1506 			kmem_free(p->cku_addr.buf, p->cku_addr.maxlen);
1507 		p->cku_addr.buf = kmem_zalloc(addr->maxlen, KM_SLEEP);
1508 		p->cku_addr.maxlen = addr->maxlen;
1509 	}
1510 
1511 	p->cku_addr.len = addr->len;
1512 	bcopy(addr->buf, p->cku_addr.buf, addr->len);
1513 
1514 	/*
1515 	 * If the current sanity check size in rpcmod is smaller
1516 	 * than the size needed, then increase the sanity check.
1517 	 */
1518 	if (max_msgsize != 0 && clnt_max_msg_sizep != NULL &&
1519 	    max_msgsize > *clnt_max_msg_sizep) {
1520 		mutex_enter(&clnt_max_msg_lock);
1521 		if (max_msgsize > *clnt_max_msg_sizep)
1522 			*clnt_max_msg_sizep = max_msgsize;
1523 		mutex_exit(&clnt_max_msg_lock);
1524 	}
1525 }
1526 
1527 /*
1528  * ksettimers is a no-op for cots, with the exception of setting the xid.
1529  */
1530 /* ARGSUSED */
1531 static int
1532 clnt_cots_ksettimers(CLIENT *h, struct rpc_timers *t, struct rpc_timers *all,
1533 	int minimum, void (*feedback)(int, int, caddr_t), caddr_t arg,
1534 	uint32_t xid)
1535 {
1536 	/* LINTED pointer alignment */
1537 	cku_private_t *p = htop(h);
1538 
1539 	if (xid)
1540 		p->cku_xid = xid;
1541 	COTSRCSTAT_INCR(p->cku_stats, rctimers);
1542 	return (0);
1543 }
1544 
1545 extern void rpc_poptimod(struct vnode *);
1546 extern int kstr_push(struct vnode *, char *);
1547 
1548 int
1549 conn_kstat_update(kstat_t *ksp, int rw)
1550 {
1551 	struct cm_xprt *cm_entry;
1552 	struct cm_kstat_xprt *cm_ksp_data;
1553 	uchar_t *b;
1554 	char *fbuf;
1555 
1556 	if (rw == KSTAT_WRITE)
1557 		return (EACCES);
1558 	if (ksp == NULL || ksp->ks_private == NULL)
1559 		return (EIO);
1560 	cm_entry  = (struct cm_xprt *)ksp->ks_private;
1561 	cm_ksp_data = (struct cm_kstat_xprt *)ksp->ks_data;
1562 
1563 	cm_ksp_data->x_wq.value.ui32 = (uint32_t)(uintptr_t)cm_entry->x_wq;
1564 	cm_ksp_data->x_family.value.ui32 = cm_entry->x_family;
1565 	cm_ksp_data->x_rdev.value.ui32 = (uint32_t)cm_entry->x_rdev;
1566 	cm_ksp_data->x_time.value.ui32 = cm_entry->x_time;
1567 	cm_ksp_data->x_ref.value.ui32 = cm_entry->x_ref;
1568 	cm_ksp_data->x_state.value.ui32 = cm_entry->x_state_flags;
1569 
1570 	if (cm_entry->x_server.buf) {
1571 		fbuf = cm_ksp_data->x_server.value.str.addr.ptr;
1572 		if (cm_entry->x_family == AF_INET &&
1573 		    cm_entry->x_server.len ==
1574 		    sizeof (struct sockaddr_in)) {
1575 			struct sockaddr_in  *sa;
1576 			sa = (struct sockaddr_in *)
1577 				cm_entry->x_server.buf;
1578 			b = (uchar_t *)&sa->sin_addr;
1579 			(void) sprintf(fbuf,
1580 			    "%03d.%03d.%03d.%03d", b[0] & 0xFF, b[1] & 0xFF,
1581 			    b[2] & 0xFF, b[3] & 0xFF);
1582 			cm_ksp_data->x_port.value.ui32 =
1583 				(uint32_t)sa->sin_port;
1584 		} else if (cm_entry->x_family == AF_INET6 &&
1585 				cm_entry->x_server.len >=
1586 				sizeof (struct sockaddr_in6)) {
1587 			/* extract server IP address & port */
1588 			struct sockaddr_in6 *sin6;
1589 			sin6 = (struct sockaddr_in6 *)cm_entry->x_server.buf;
1590 			(void) kinet_ntop6((uchar_t *)&sin6->sin6_addr, fbuf,
1591 				INET6_ADDRSTRLEN);
1592 			cm_ksp_data->x_port.value.ui32 = sin6->sin6_port;
1593 		} else {
1594 			struct sockaddr_in  *sa;
1595 
1596 			sa = (struct sockaddr_in *)cm_entry->x_server.buf;
1597 			b = (uchar_t *)&sa->sin_addr;
1598 			(void) sprintf(fbuf,
1599 			    "%03d.%03d.%03d.%03d", b[0] & 0xFF, b[1] & 0xFF,
1600 			    b[2] & 0xFF, b[3] & 0xFF);
1601 		}
1602 		KSTAT_NAMED_STR_BUFLEN(&cm_ksp_data->x_server) =
1603 		    strlen(fbuf) + 1;
1604 	}
1605 
1606 	return (0);
1607 }
1608 
1609 
1610 /*
1611  * We want a version of delay which is interruptible by a UNIX signal
1612  * Return EINTR if an interrupt occured.
1613  */
1614 static int
1615 clnt_delay(clock_t ticks, bool_t nosignal)
1616 {
1617 	if (nosignal == TRUE) {
1618 		delay(ticks);
1619 		return (0);
1620 	}
1621 	return (delay_sig(ticks));
1622 }
1623 
1624 /*
1625  * Wait for a connection until a timeout, or until we are
1626  * signalled that there has been a connection state change.
1627  */
1628 static enum clnt_stat
1629 connmgr_cwait(struct cm_xprt *cm_entry, const struct timeval *waitp,
1630 	bool_t nosignal)
1631 {
1632 	bool_t interrupted;
1633 	clock_t timout, cv_stat;
1634 	enum clnt_stat clstat;
1635 	unsigned int old_state;
1636 
1637 	ASSERT(MUTEX_HELD(&connmgr_lock));
1638 	/*
1639 	 * We wait for the transport connection to be made, or an
1640 	 * indication that it could not be made.
1641 	 */
1642 	clstat = RPC_TIMEDOUT;
1643 	interrupted = FALSE;
1644 
1645 	old_state = cm_entry->x_state_flags;
1646 	/*
1647 	 * Now loop until cv_timedwait{_sig} returns because of
1648 	 * a signal(0) or timeout(-1) or cv_signal(>0). But it may be
1649 	 * cv_signalled for various other reasons too. So loop
1650 	 * until there is a state change on the connection.
1651 	 */
1652 
1653 	timout = waitp->tv_sec * drv_usectohz(1000000) +
1654 	    drv_usectohz(waitp->tv_usec) + lbolt;
1655 
1656 	if (nosignal) {
1657 		while ((cv_stat = cv_timedwait(&cm_entry->x_conn_cv,
1658 		    &connmgr_lock, timout)) > 0 &&
1659 		    cm_entry->x_state_flags == old_state)
1660 			;
1661 	} else {
1662 		while ((cv_stat = cv_timedwait_sig(&cm_entry->x_conn_cv,
1663 		    &connmgr_lock, timout)) > 0 &&
1664 		    cm_entry->x_state_flags == old_state)
1665 			;
1666 
1667 		if (cv_stat == 0) /* got intr signal? */
1668 			interrupted = TRUE;
1669 	}
1670 
1671 	if ((cm_entry->x_state_flags & (X_BADSTATES|X_CONNECTED)) ==
1672 	    X_CONNECTED) {
1673 		clstat = RPC_SUCCESS;
1674 	} else {
1675 		if (interrupted == TRUE)
1676 			clstat = RPC_INTR;
1677 		RPCLOG(1, "connmgr_cwait: can't connect, error: %s\n",
1678 		    clnt_sperrno(clstat));
1679 	}
1680 
1681 	return (clstat);
1682 }
1683 
1684 /*
1685  * Primary interface for how RPC grabs a connection.
1686  */
1687 static struct cm_xprt *
1688 connmgr_wrapget(
1689 	struct netbuf *retryaddr,
1690 	const struct timeval *waitp,
1691 	cku_private_t *p)
1692 {
1693 	struct cm_xprt *cm_entry;
1694 
1695 	cm_entry = connmgr_get(retryaddr, waitp, &p->cku_addr, p->cku_addrfmly,
1696 	    &p->cku_srcaddr, &p->cku_err, p->cku_device,
1697 	    p->cku_client.cl_nosignal, p->cku_useresvport);
1698 
1699 	if (cm_entry == NULL) {
1700 		/*
1701 		 * Re-map the call status to RPC_INTR if the err code is
1702 		 * EINTR. This can happen if calls status is RPC_TLIERROR.
1703 		 * However, don't re-map if signalling has been turned off.
1704 		 * XXX Really need to create a separate thread whenever
1705 		 * there isn't an existing connection.
1706 		 */
1707 		if (p->cku_err.re_errno == EINTR) {
1708 			if (p->cku_client.cl_nosignal == TRUE)
1709 				p->cku_err.re_errno = EIO;
1710 			else
1711 				p->cku_err.re_status = RPC_INTR;
1712 		}
1713 	}
1714 
1715 	return (cm_entry);
1716 }
1717 
1718 /*
1719  * Obtains a transport to the server specified in addr.  If a suitable transport
1720  * does not already exist in the list of cached transports, a new connection
1721  * is created, connected, and added to the list. The connection is for sending
1722  * only - the reply message may come back on another transport connection.
1723  */
1724 static struct cm_xprt *
1725 connmgr_get(
1726 	struct netbuf	*retryaddr,
1727 	const struct timeval	*waitp,	/* changed to a ptr to converse stack */
1728 	struct netbuf	*destaddr,
1729 	int		addrfmly,
1730 	struct netbuf	*srcaddr,
1731 	struct rpc_err	*rpcerr,
1732 	dev_t		device,
1733 	bool_t		nosignal,
1734 	int		useresvport)
1735 {
1736 	struct cm_xprt *cm_entry;
1737 	struct cm_xprt *lru_entry;
1738 	struct cm_xprt **cmp;
1739 	queue_t *wq;
1740 	TIUSER *tiptr;
1741 	int i;
1742 	int retval;
1743 	clock_t prev_time;
1744 	int tidu_size;
1745 	bool_t	connected;
1746 	zoneid_t zoneid = rpc_zoneid();
1747 
1748 	/*
1749 	 * If the call is not a retry, look for a transport entry that
1750 	 * goes to the server of interest.
1751 	 */
1752 	mutex_enter(&connmgr_lock);
1753 
1754 	if (retryaddr == NULL) {
1755 use_new_conn:
1756 		i = 0;
1757 		cm_entry = lru_entry = NULL;
1758 		prev_time = lbolt;
1759 
1760 		cmp = &cm_hd;
1761 		while ((cm_entry = *cmp) != NULL) {
1762 			ASSERT(cm_entry != cm_entry->x_next);
1763 			/*
1764 			 * Garbage collect conections that are marked
1765 			 * for needs disconnect.
1766 			 */
1767 			if (cm_entry->x_needdis) {
1768 				CONN_HOLD(cm_entry);
1769 				connmgr_dis_and_wait(cm_entry);
1770 				connmgr_release(cm_entry);
1771 				/*
1772 				 * connmgr_lock could have been
1773 				 * dropped for the disconnect
1774 				 * processing so start over.
1775 				 */
1776 				goto use_new_conn;
1777 			}
1778 
1779 			/*
1780 			 * Garbage collect the dead connections that have
1781 			 * no threads working on them.
1782 			 */
1783 			if ((cm_entry->x_state_flags & (X_DEAD|X_THREAD)) ==
1784 			    X_DEAD) {
1785 				mutex_enter(&cm_entry->x_lock);
1786 				if (cm_entry->x_ref != 0) {
1787 					/*
1788 					 * Currently in use.
1789 					 * Cleanup later.
1790 					 */
1791 					cmp = &cm_entry->x_next;
1792 					mutex_exit(&cm_entry->x_lock);
1793 					continue;
1794 				}
1795 				mutex_exit(&cm_entry->x_lock);
1796 				*cmp = cm_entry->x_next;
1797 				mutex_exit(&connmgr_lock);
1798 				connmgr_close(cm_entry);
1799 				mutex_enter(&connmgr_lock);
1800 				goto use_new_conn;
1801 			}
1802 
1803 
1804 			if ((cm_entry->x_state_flags & X_BADSTATES) == 0 &&
1805 			    cm_entry->x_zoneid == zoneid &&
1806 			    cm_entry->x_rdev == device &&
1807 			    destaddr->len == cm_entry->x_server.len &&
1808 			    bcmp(destaddr->buf, cm_entry->x_server.buf,
1809 			    destaddr->len) == 0) {
1810 				/*
1811 				 * If the matching entry isn't connected,
1812 				 * attempt to reconnect it.
1813 				 */
1814 				if (cm_entry->x_connected == FALSE) {
1815 					/*
1816 					 * We don't go through trying
1817 					 * to find the least recently
1818 					 * used connected because
1819 					 * connmgr_reconnect() briefly
1820 					 * dropped the connmgr_lock,
1821 					 * allowing a window for our
1822 					 * accounting to be messed up.
1823 					 * In any case, a re-connected
1824 					 * connection is as good as
1825 					 * a LRU connection.
1826 					 */
1827 					return (connmgr_wrapconnect(cm_entry,
1828 					    waitp, destaddr, addrfmly, srcaddr,
1829 					    rpcerr, TRUE, nosignal));
1830 				}
1831 				i++;
1832 				if (cm_entry->x_time - prev_time <= 0 ||
1833 				    lru_entry == NULL) {
1834 					prev_time = cm_entry->x_time;
1835 					lru_entry = cm_entry;
1836 				}
1837 			}
1838 			cmp = &cm_entry->x_next;
1839 		}
1840 
1841 		if (i > clnt_max_conns) {
1842 			RPCLOG(8, "connmgr_get: too many conns, dooming entry"
1843 			    " %p\n", (void *)lru_entry->x_tiptr);
1844 			lru_entry->x_doomed = TRUE;
1845 			goto use_new_conn;
1846 		}
1847 
1848 		/*
1849 		 * If we are at the maximum number of connections to
1850 		 * the server, hand back the least recently used one.
1851 		 */
1852 		if (i == clnt_max_conns) {
1853 			/*
1854 			 * Copy into the handle the source address of
1855 			 * the connection, which we will use in case of
1856 			 * a later retry.
1857 			 */
1858 			if (srcaddr->len != lru_entry->x_src.len) {
1859 				if (srcaddr->len > 0)
1860 					kmem_free(srcaddr->buf,
1861 					    srcaddr->maxlen);
1862 				srcaddr->buf = kmem_zalloc(
1863 				    lru_entry->x_src.len, KM_SLEEP);
1864 				srcaddr->maxlen = srcaddr->len =
1865 				    lru_entry->x_src.len;
1866 			}
1867 			bcopy(lru_entry->x_src.buf, srcaddr->buf, srcaddr->len);
1868 			RPCLOG(2, "connmgr_get: call going out on %p\n",
1869 			    (void *)lru_entry);
1870 			lru_entry->x_time = lbolt;
1871 			CONN_HOLD(lru_entry);
1872 			mutex_exit(&connmgr_lock);
1873 			return (lru_entry);
1874 		}
1875 
1876 	} else {
1877 		/*
1878 		 * This is the retry case (retryaddr != NULL).  Retries must
1879 		 * be sent on the same source port as the original call.
1880 		 */
1881 
1882 		/*
1883 		 * Walk the list looking for a connection with a source address
1884 		 * that matches the retry address.
1885 		 */
1886 		cmp = &cm_hd;
1887 		while ((cm_entry = *cmp) != NULL) {
1888 			ASSERT(cm_entry != cm_entry->x_next);
1889 			if (zoneid != cm_entry->x_zoneid ||
1890 			    device != cm_entry->x_rdev ||
1891 			    retryaddr->len != cm_entry->x_src.len ||
1892 			    bcmp(retryaddr->buf, cm_entry->x_src.buf,
1893 			    retryaddr->len) != 0) {
1894 				cmp = &cm_entry->x_next;
1895 				continue;
1896 			}
1897 
1898 			/*
1899 			 * Sanity check: if the connection with our source
1900 			 * port is going to some other server, something went
1901 			 * wrong, as we never delete connections (i.e. release
1902 			 * ports) unless they have been idle.  In this case,
1903 			 * it is probably better to send the call out using
1904 			 * a new source address than to fail it altogether,
1905 			 * since that port may never be released.
1906 			 */
1907 			if (destaddr->len != cm_entry->x_server.len ||
1908 			    bcmp(destaddr->buf, cm_entry->x_server.buf,
1909 			    destaddr->len) != 0) {
1910 				RPCLOG(1, "connmgr_get: tiptr %p"
1911 				    " is going to a different server"
1912 				    " with the port that belongs"
1913 				    " to us!\n", (void *)cm_entry->x_tiptr);
1914 				retryaddr = NULL;
1915 				goto use_new_conn;
1916 			}
1917 
1918 			/*
1919 			 * If the connection of interest is not connected and we
1920 			 * can't reconnect it, then the server is probably
1921 			 * still down.  Return NULL to the caller and let it
1922 			 * retry later if it wants to.  We have a delay so the
1923 			 * machine doesn't go into a tight retry loop.  If the
1924 			 * entry was already connected, or the reconnected was
1925 			 * successful, return this entry.
1926 			 */
1927 			if (cm_entry->x_connected == FALSE) {
1928 				return (connmgr_wrapconnect(cm_entry,
1929 				    waitp, destaddr, addrfmly, NULL,
1930 				    rpcerr, TRUE, nosignal));
1931 			} else {
1932 				CONN_HOLD(cm_entry);
1933 
1934 				cm_entry->x_time = lbolt;
1935 				mutex_exit(&connmgr_lock);
1936 				RPCLOG(2, "connmgr_get: found old "
1937 				    "transport %p for retry\n",
1938 				    (void *)cm_entry);
1939 				return (cm_entry);
1940 			}
1941 		}
1942 
1943 		/*
1944 		 * We cannot find an entry in the list for this retry.
1945 		 * Either the entry has been removed temporarily to be
1946 		 * reconnected by another thread, or the original call
1947 		 * got a port but never got connected,
1948 		 * and hence the transport never got put in the
1949 		 * list.  Fall through to the "create new connection" code -
1950 		 * the former case will fail there trying to rebind the port,
1951 		 * and the later case (and any other pathological cases) will
1952 		 * rebind and reconnect and not hang the client machine.
1953 		 */
1954 		RPCLOG0(8, "connmgr_get: no entry in list for retry\n");
1955 	}
1956 	/*
1957 	 * Set up a transport entry in the connection manager's list.
1958 	 */
1959 	cm_entry = (struct cm_xprt *)
1960 	    kmem_zalloc(sizeof (struct cm_xprt), KM_SLEEP);
1961 
1962 	cm_entry->x_server.buf = kmem_zalloc(destaddr->len, KM_SLEEP);
1963 	bcopy(destaddr->buf, cm_entry->x_server.buf, destaddr->len);
1964 	cm_entry->x_server.len = cm_entry->x_server.maxlen = destaddr->len;
1965 
1966 	cm_entry->x_state_flags = X_THREAD;
1967 	cm_entry->x_ref = 1;
1968 	cm_entry->x_family = addrfmly;
1969 	cm_entry->x_rdev = device;
1970 	cm_entry->x_zoneid = zoneid;
1971 	mutex_init(&cm_entry->x_lock, NULL, MUTEX_DEFAULT, NULL);
1972 	cv_init(&cm_entry->x_cv, NULL, CV_DEFAULT, NULL);
1973 	cv_init(&cm_entry->x_conn_cv, NULL, CV_DEFAULT, NULL);
1974 	cv_init(&cm_entry->x_dis_cv, NULL, CV_DEFAULT, NULL);
1975 
1976 	/*
1977 	 * Note that we add this partially initialized entry to the
1978 	 * connection list. This is so that we don't have connections to
1979 	 * the same server.
1980 	 *
1981 	 * Note that x_src is not initialized at this point. This is because
1982 	 * retryaddr might be NULL in which case x_src is whatever
1983 	 * t_kbind/bindresvport gives us. If another thread wants a
1984 	 * connection to the same server, seemingly we have an issue, but we
1985 	 * don't. If the other thread comes in with retryaddr == NULL, then it
1986 	 * will never look at x_src, and it will end up waiting in
1987 	 * connmgr_cwait() for the first thread to finish the connection
1988 	 * attempt. If the other thread comes in with retryaddr != NULL, then
1989 	 * that means there was a request sent on a connection, in which case
1990 	 * the the connection should already exist. Thus the first thread
1991 	 * never gets here ... it finds the connection it its server in the
1992 	 * connection list.
1993 	 *
1994 	 * But even if theory is wrong, in the retryaddr != NULL case, the 2nd
1995 	 * thread will skip us because x_src.len == 0.
1996 	 */
1997 	cm_entry->x_next = cm_hd;
1998 	cm_hd = cm_entry;
1999 	mutex_exit(&connmgr_lock);
2000 
2001 	/*
2002 	 * Either we didn't find an entry to the server of interest, or we
2003 	 * don't have the maximum number of connections to that server -
2004 	 * create a new connection.
2005 	 */
2006 	RPCLOG0(8, "connmgr_get: creating new connection\n");
2007 	rpcerr->re_status = RPC_TLIERROR;
2008 
2009 	i = t_kopen(NULL, device, FREAD|FWRITE|FNDELAY, &tiptr, zone_kcred());
2010 	if (i) {
2011 		RPCLOG(1, "connmgr_get: can't open cots device, error %d\n", i);
2012 		rpcerr->re_errno = i;
2013 		connmgr_cancelconn(cm_entry);
2014 		return (NULL);
2015 	}
2016 	rpc_poptimod(tiptr->fp->f_vnode);
2017 
2018 	if (i = strioctl(tiptr->fp->f_vnode, I_PUSH, (intptr_t)"rpcmod", 0,
2019 	    K_TO_K, kcred, &retval)) {
2020 		RPCLOG(1, "connmgr_get: can't push cots module, %d\n", i);
2021 		(void) t_kclose(tiptr, 1);
2022 		rpcerr->re_errno = i;
2023 		connmgr_cancelconn(cm_entry);
2024 		return (NULL);
2025 	}
2026 
2027 	if (i = strioctl(tiptr->fp->f_vnode, RPC_CLIENT, 0, 0, K_TO_K,
2028 	    kcred, &retval)) {
2029 		RPCLOG(1, "connmgr_get: can't set client status with cots "
2030 		    "module, %d\n", i);
2031 		(void) t_kclose(tiptr, 1);
2032 		rpcerr->re_errno = i;
2033 		connmgr_cancelconn(cm_entry);
2034 		return (NULL);
2035 	}
2036 
2037 	mutex_enter(&connmgr_lock);
2038 
2039 	wq = tiptr->fp->f_vnode->v_stream->sd_wrq->q_next;
2040 	cm_entry->x_wq = wq;
2041 
2042 	mutex_exit(&connmgr_lock);
2043 
2044 	if (i = strioctl(tiptr->fp->f_vnode, I_PUSH, (intptr_t)"timod", 0,
2045 	    K_TO_K, kcred, &retval)) {
2046 		RPCLOG(1, "connmgr_get: can't push timod, %d\n", i);
2047 		(void) t_kclose(tiptr, 1);
2048 		rpcerr->re_errno = i;
2049 		connmgr_cancelconn(cm_entry);
2050 		return (NULL);
2051 	}
2052 
2053 	/*
2054 	 * If the caller has not specified reserved port usage then
2055 	 * take the system default.
2056 	 */
2057 	if (useresvport == -1)
2058 		useresvport = clnt_cots_do_bindresvport;
2059 
2060 	if ((useresvport || retryaddr != NULL) &&
2061 	    (addrfmly == AF_INET || addrfmly == AF_INET6)) {
2062 		bool_t alloc_src = FALSE;
2063 
2064 		if (srcaddr->len != destaddr->len) {
2065 			kmem_free(srcaddr->buf, srcaddr->maxlen);
2066 			srcaddr->buf = kmem_zalloc(destaddr->len, KM_SLEEP);
2067 			srcaddr->maxlen = destaddr->len;
2068 			srcaddr->len = destaddr->len;
2069 			alloc_src = TRUE;
2070 		}
2071 
2072 		if ((i = bindresvport(tiptr, retryaddr, srcaddr, TRUE)) != 0) {
2073 			(void) t_kclose(tiptr, 1);
2074 			RPCLOG(1, "connmgr_get: couldn't bind, retryaddr: "
2075 			    "%p\n", (void *)retryaddr);
2076 
2077 			/*
2078 			 * 1225408: If we allocated a source address, then it
2079 			 * is either garbage or all zeroes. In that case
2080 			 * we need to clear srcaddr.
2081 			 */
2082 			if (alloc_src == TRUE) {
2083 				kmem_free(srcaddr->buf, srcaddr->maxlen);
2084 				srcaddr->maxlen = srcaddr->len = 0;
2085 				srcaddr->buf = NULL;
2086 			}
2087 			rpcerr->re_errno = i;
2088 			connmgr_cancelconn(cm_entry);
2089 			return (NULL);
2090 		}
2091 	} else {
2092 		if ((i = t_kbind(tiptr, NULL, NULL)) != 0) {
2093 			RPCLOG(1, "clnt_cots_kcreate: t_kbind: %d\n", i);
2094 			(void) t_kclose(tiptr, 1);
2095 			rpcerr->re_errno = i;
2096 			connmgr_cancelconn(cm_entry);
2097 			return (NULL);
2098 		}
2099 	}
2100 
2101 	{
2102 		/*
2103 		 * Keep the kernel stack lean. Don't move this call
2104 		 * declaration to the top of this function because a
2105 		 * call is declared in connmgr_wrapconnect()
2106 		 */
2107 		calllist_t call;
2108 
2109 		bzero(&call, sizeof (call));
2110 		cv_init(&call.call_cv, NULL, CV_DEFAULT, NULL);
2111 
2112 		/*
2113 		 * This is a bound end-point so don't close it's stream.
2114 		 */
2115 		connected = connmgr_connect(cm_entry, wq, destaddr, addrfmly,
2116 		    &call, &tidu_size, FALSE, waitp, nosignal);
2117 		*rpcerr = call.call_err;
2118 		cv_destroy(&call.call_cv);
2119 
2120 	}
2121 
2122 	mutex_enter(&connmgr_lock);
2123 
2124 	/*
2125 	 * Set up a transport entry in the connection manager's list.
2126 	 */
2127 	cm_entry->x_src.buf = kmem_zalloc(srcaddr->len, KM_SLEEP);
2128 	bcopy(srcaddr->buf, cm_entry->x_src.buf, srcaddr->len);
2129 	cm_entry->x_src.len = cm_entry->x_src.maxlen = srcaddr->len;
2130 
2131 	cm_entry->x_tiptr = tiptr;
2132 	cm_entry->x_time = lbolt;
2133 
2134 	if (tiptr->tp_info.servtype == T_COTS_ORD)
2135 		cm_entry->x_ordrel = TRUE;
2136 	else
2137 		cm_entry->x_ordrel = FALSE;
2138 
2139 	cm_entry->x_tidu_size = tidu_size;
2140 
2141 	if (cm_entry->x_early_disc) {
2142 		/*
2143 		 * We need to check if a disconnect request has come
2144 		 * while we are connected, if so, then we need to
2145 		 * set rpcerr->re_status appropriately before returning
2146 		 * NULL to caller.
2147 		 */
2148 		if (rpcerr->re_status == RPC_SUCCESS)
2149 			rpcerr->re_status = RPC_XPRTFAILED;
2150 		cm_entry->x_connected = FALSE;
2151 	} else
2152 		cm_entry->x_connected = connected;
2153 
2154 	/*
2155 	 * There could be a discrepancy here such that
2156 	 * x_early_disc is TRUE yet connected is TRUE as well
2157 	 * and the connection is actually connected. In that case
2158 	 * lets be conservative and declare the connection as not
2159 	 * connected.
2160 	 */
2161 	cm_entry->x_early_disc = FALSE;
2162 	cm_entry->x_needdis = (cm_entry->x_connected == FALSE);
2163 	cm_entry->x_ctime = lbolt;
2164 
2165 	/*
2166 	 * Notify any threads waiting that the connection attempt is done.
2167 	 */
2168 	cm_entry->x_thread = FALSE;
2169 	cv_broadcast(&cm_entry->x_conn_cv);
2170 
2171 	if (cm_entry->x_connected == FALSE) {
2172 		mutex_exit(&connmgr_lock);
2173 		connmgr_release(cm_entry);
2174 		return (NULL);
2175 	}
2176 
2177 	mutex_exit(&connmgr_lock);
2178 
2179 	return (cm_entry);
2180 }
2181 
2182 /*
2183  * Keep the cm_xprt entry on the connecton list when making a connection. This
2184  * is to prevent multiple connections to a slow server from appearing.
2185  * We use the bit field x_thread to tell if a thread is doing a connection
2186  * which keeps other interested threads from messing with connection.
2187  * Those other threads just wait if x_thread is set.
2188  *
2189  * If x_thread is not set, then we do the actual work of connecting via
2190  * connmgr_connect().
2191  *
2192  * mutex convention: called with connmgr_lock held, returns with it released.
2193  */
2194 static struct cm_xprt *
2195 connmgr_wrapconnect(
2196 	struct cm_xprt	*cm_entry,
2197 	const struct timeval	*waitp,
2198 	struct netbuf	*destaddr,
2199 	int		addrfmly,
2200 	struct netbuf	*srcaddr,
2201 	struct rpc_err	*rpcerr,
2202 	bool_t		reconnect,
2203 	bool_t		nosignal)
2204 {
2205 	ASSERT(MUTEX_HELD(&connmgr_lock));
2206 	/*
2207 	 * Hold this entry as we are about to drop connmgr_lock.
2208 	 */
2209 	CONN_HOLD(cm_entry);
2210 
2211 	/*
2212 	 * If there is a thread already making a connection for us, then
2213 	 * wait for it to complete the connection.
2214 	 */
2215 	if (cm_entry->x_thread == TRUE) {
2216 		rpcerr->re_status = connmgr_cwait(cm_entry, waitp, nosignal);
2217 
2218 		if (rpcerr->re_status != RPC_SUCCESS) {
2219 			mutex_exit(&connmgr_lock);
2220 			connmgr_release(cm_entry);
2221 			return (NULL);
2222 		}
2223 	} else {
2224 		bool_t connected;
2225 		calllist_t call;
2226 
2227 		cm_entry->x_thread = TRUE;
2228 
2229 		while (cm_entry->x_needrel == TRUE) {
2230 			cm_entry->x_needrel = FALSE;
2231 
2232 			connmgr_sndrel(cm_entry);
2233 			delay(drv_usectohz(1000000));
2234 
2235 			mutex_enter(&connmgr_lock);
2236 		}
2237 
2238 		/*
2239 		 * If we need to send a T_DISCON_REQ, send one.
2240 		 */
2241 		connmgr_dis_and_wait(cm_entry);
2242 
2243 		mutex_exit(&connmgr_lock);
2244 
2245 		bzero(&call, sizeof (call));
2246 		cv_init(&call.call_cv, NULL, CV_DEFAULT, NULL);
2247 
2248 		connected = connmgr_connect(cm_entry, cm_entry->x_wq,
2249 		    destaddr, addrfmly, &call, &cm_entry->x_tidu_size,
2250 		    reconnect, waitp, nosignal);
2251 
2252 		*rpcerr = call.call_err;
2253 		cv_destroy(&call.call_cv);
2254 
2255 		mutex_enter(&connmgr_lock);
2256 
2257 
2258 		if (cm_entry->x_early_disc) {
2259 			/*
2260 			 * We need to check if a disconnect request has come
2261 			 * while we are connected, if so, then we need to
2262 			 * set rpcerr->re_status appropriately before returning
2263 			 * NULL to caller.
2264 			 */
2265 			if (rpcerr->re_status == RPC_SUCCESS)
2266 				rpcerr->re_status = RPC_XPRTFAILED;
2267 			cm_entry->x_connected = FALSE;
2268 		} else
2269 			cm_entry->x_connected = connected;
2270 
2271 		/*
2272 		 * There could be a discrepancy here such that
2273 		 * x_early_disc is TRUE yet connected is TRUE as well
2274 		 * and the connection is actually connected. In that case
2275 		 * lets be conservative and declare the connection as not
2276 		 * connected.
2277 		 */
2278 
2279 		cm_entry->x_early_disc = FALSE;
2280 		cm_entry->x_needdis = (cm_entry->x_connected == FALSE);
2281 
2282 
2283 		/*
2284 		 * connmgr_connect() may have given up before the connection
2285 		 * actually timed out. So ensure that before the next
2286 		 * connection attempt we do a disconnect.
2287 		 */
2288 		cm_entry->x_ctime = lbolt;
2289 		cm_entry->x_thread = FALSE;
2290 
2291 		cv_broadcast(&cm_entry->x_conn_cv);
2292 
2293 		if (cm_entry->x_connected == FALSE) {
2294 			mutex_exit(&connmgr_lock);
2295 			connmgr_release(cm_entry);
2296 			return (NULL);
2297 		}
2298 	}
2299 
2300 	if (srcaddr != NULL) {
2301 		/*
2302 		 * Copy into the handle the
2303 		 * source address of the
2304 		 * connection, which we will use
2305 		 * in case of a later retry.
2306 		 */
2307 		if (srcaddr->len != cm_entry->x_src.len) {
2308 			if (srcaddr->maxlen > 0)
2309 				kmem_free(srcaddr->buf, srcaddr->maxlen);
2310 			srcaddr->buf = kmem_zalloc(cm_entry->x_src.len,
2311 			    KM_SLEEP);
2312 			srcaddr->maxlen = srcaddr->len =
2313 			    cm_entry->x_src.len;
2314 		}
2315 		bcopy(cm_entry->x_src.buf, srcaddr->buf, srcaddr->len);
2316 	}
2317 	cm_entry->x_time = lbolt;
2318 	mutex_exit(&connmgr_lock);
2319 	return (cm_entry);
2320 }
2321 
2322 /*
2323  * If we need to send a T_DISCON_REQ, send one.
2324  */
2325 static void
2326 connmgr_dis_and_wait(struct cm_xprt *cm_entry)
2327 {
2328 	ASSERT(MUTEX_HELD(&connmgr_lock));
2329 	for (;;) {
2330 		while (cm_entry->x_needdis == TRUE) {
2331 			RPCLOG(8, "connmgr_dis_and_wait: need "
2332 			    "T_DISCON_REQ for connection 0x%p\n",
2333 			    (void *)cm_entry);
2334 			cm_entry->x_needdis = FALSE;
2335 			cm_entry->x_waitdis = TRUE;
2336 
2337 			connmgr_snddis(cm_entry);
2338 
2339 			mutex_enter(&connmgr_lock);
2340 		}
2341 
2342 		if (cm_entry->x_waitdis == TRUE) {
2343 			clock_t curlbolt;
2344 			clock_t timout;
2345 
2346 			RPCLOG(8, "connmgr_dis_and_wait waiting for "
2347 			    "T_DISCON_REQ's ACK for connection %p\n",
2348 			    (void *)cm_entry);
2349 			curlbolt = ddi_get_lbolt();
2350 
2351 			timout = clnt_cots_min_conntout *
2352 			    drv_usectohz(1000000) + curlbolt;
2353 
2354 			/*
2355 			 * The TPI spec says that the T_DISCON_REQ
2356 			 * will get acknowledged, but in practice
2357 			 * the ACK may never get sent. So don't
2358 			 * block forever.
2359 			 */
2360 			(void) cv_timedwait(&cm_entry->x_dis_cv,
2361 			    &connmgr_lock, timout);
2362 		}
2363 		/*
2364 		 * If we got the ACK, break. If we didn't,
2365 		 * then send another T_DISCON_REQ.
2366 		 */
2367 		if (cm_entry->x_waitdis == FALSE) {
2368 			break;
2369 		} else {
2370 			RPCLOG(8, "connmgr_dis_and_wait: did"
2371 			    "not get T_DISCON_REQ's ACK for "
2372 			    "connection  %p\n", (void *)cm_entry);
2373 			cm_entry->x_needdis = TRUE;
2374 		}
2375 	}
2376 }
2377 
2378 static void
2379 connmgr_cancelconn(struct cm_xprt *cm_entry)
2380 {
2381 	/*
2382 	 * Mark the connection table entry as dead; the next thread that
2383 	 * goes through connmgr_release() will notice this and deal with it.
2384 	 */
2385 	mutex_enter(&connmgr_lock);
2386 	cm_entry->x_dead = TRUE;
2387 
2388 	/*
2389 	 * Notify any threads waiting for the connection that it isn't
2390 	 * going to happen.
2391 	 */
2392 	cm_entry->x_thread = FALSE;
2393 	cv_broadcast(&cm_entry->x_conn_cv);
2394 	mutex_exit(&connmgr_lock);
2395 
2396 	connmgr_release(cm_entry);
2397 }
2398 
2399 static void
2400 connmgr_close(struct cm_xprt *cm_entry)
2401 {
2402 	mutex_enter(&cm_entry->x_lock);
2403 	while (cm_entry->x_ref != 0) {
2404 		/*
2405 		 * Must be a noninterruptible wait.
2406 		 */
2407 		cv_wait(&cm_entry->x_cv, &cm_entry->x_lock);
2408 	}
2409 
2410 	if (cm_entry->x_tiptr != NULL)
2411 		(void) t_kclose(cm_entry->x_tiptr, 1);
2412 
2413 	mutex_exit(&cm_entry->x_lock);
2414 	if (cm_entry->x_ksp != NULL) {
2415 		mutex_enter(&connmgr_lock);
2416 		cm_entry->x_ksp->ks_private = NULL;
2417 		mutex_exit(&connmgr_lock);
2418 
2419 		/*
2420 		 * Must free the buffer we allocated for the
2421 		 * server address in the update function
2422 		 */
2423 		if (((struct cm_kstat_xprt *)(cm_entry->x_ksp->ks_data))->
2424 		    x_server.value.str.addr.ptr != NULL)
2425 			kmem_free(((struct cm_kstat_xprt *)(cm_entry->x_ksp->
2426 			    ks_data))->x_server.value.str.addr.ptr,
2427 			    INET6_ADDRSTRLEN);
2428 		kmem_free(cm_entry->x_ksp->ks_data,
2429 		    cm_entry->x_ksp->ks_data_size);
2430 		kstat_delete(cm_entry->x_ksp);
2431 	}
2432 
2433 	mutex_destroy(&cm_entry->x_lock);
2434 	cv_destroy(&cm_entry->x_cv);
2435 	cv_destroy(&cm_entry->x_conn_cv);
2436 	cv_destroy(&cm_entry->x_dis_cv);
2437 
2438 	if (cm_entry->x_server.buf != NULL)
2439 		kmem_free(cm_entry->x_server.buf, cm_entry->x_server.maxlen);
2440 	if (cm_entry->x_src.buf != NULL)
2441 		kmem_free(cm_entry->x_src.buf, cm_entry->x_src.maxlen);
2442 	kmem_free(cm_entry, sizeof (struct cm_xprt));
2443 }
2444 
2445 /*
2446  * Called by KRPC after sending the call message to release the connection
2447  * it was using.
2448  */
2449 static void
2450 connmgr_release(struct cm_xprt *cm_entry)
2451 {
2452 	mutex_enter(&cm_entry->x_lock);
2453 	cm_entry->x_ref--;
2454 	if (cm_entry->x_ref == 0)
2455 		cv_signal(&cm_entry->x_cv);
2456 	mutex_exit(&cm_entry->x_lock);
2457 }
2458 
2459 /*
2460  * Given an open stream, connect to the remote.  Returns true if connected,
2461  * false otherwise.
2462  */
2463 static bool_t
2464 connmgr_connect(
2465 	struct cm_xprt		*cm_entry,
2466 	queue_t			*wq,
2467 	struct netbuf		*addr,
2468 	int			addrfmly,
2469 	calllist_t 		*e,
2470 	int 			*tidu_ptr,
2471 	bool_t 			reconnect,
2472 	const struct timeval 	*waitp,
2473 	bool_t 			nosignal)
2474 {
2475 	mblk_t *mp;
2476 	struct T_conn_req *tcr;
2477 	struct T_info_ack *tinfo;
2478 	int interrupted, error;
2479 	int tidu_size, kstat_instance;
2480 
2481 	/* if it's a reconnect, flush any lingering data messages */
2482 	if (reconnect)
2483 		(void) putctl1(wq, M_FLUSH, FLUSHRW);
2484 
2485 	mp = allocb(sizeof (*tcr) + addr->len, BPRI_LO);
2486 	if (mp == NULL) {
2487 		/*
2488 		 * This is unfortunate, but we need to look up the stats for
2489 		 * this zone to increment the "memory allocation failed"
2490 		 * counter.  curproc->p_zone is safe since we're initiating a
2491 		 * connection and not in some strange streams context.
2492 		 */
2493 		struct rpcstat *rpcstat;
2494 
2495 		rpcstat = zone_getspecific(rpcstat_zone_key, rpc_zone());
2496 		ASSERT(rpcstat != NULL);
2497 
2498 		RPCLOG0(1, "connmgr_connect: cannot alloc mp for "
2499 		    "sending conn request\n");
2500 		COTSRCSTAT_INCR(rpcstat->rpc_cots_client, rcnomem);
2501 		e->call_status = RPC_SYSTEMERROR;
2502 		e->call_reason = ENOSR;
2503 		return (FALSE);
2504 	}
2505 
2506 	mp->b_datap->db_type = M_PROTO;
2507 	tcr = (struct T_conn_req *)mp->b_rptr;
2508 	bzero(tcr, sizeof (*tcr));
2509 	tcr->PRIM_type = T_CONN_REQ;
2510 	tcr->DEST_length = addr->len;
2511 	tcr->DEST_offset = sizeof (struct T_conn_req);
2512 	mp->b_wptr = mp->b_rptr + sizeof (*tcr);
2513 
2514 	bcopy(addr->buf, mp->b_wptr, tcr->DEST_length);
2515 	mp->b_wptr += tcr->DEST_length;
2516 
2517 	RPCLOG(8, "connmgr_connect: sending conn request on queue "
2518 	    "%p", (void *)wq);
2519 	RPCLOG(8, " call %p\n", (void *)wq);
2520 	/*
2521 	 * We use the entry in the handle that is normally used for
2522 	 * waiting for RPC replies to wait for the connection accept.
2523 	 */
2524 	clnt_dispatch_send(wq, mp, e, 0, 0);
2525 
2526 	mutex_enter(&clnt_pending_lock);
2527 
2528 	/*
2529 	 * We wait for the transport connection to be made, or an
2530 	 * indication that it could not be made.
2531 	 */
2532 	interrupted = 0;
2533 
2534 	/*
2535 	 * waitforack should have been called with T_OK_ACK, but the
2536 	 * present implementation needs to be passed T_INFO_ACK to
2537 	 * work correctly.
2538 	 */
2539 	error = waitforack(e, T_INFO_ACK, waitp, nosignal);
2540 	if (error == EINTR)
2541 		interrupted = 1;
2542 	if (zone_status_get(curproc->p_zone) >= ZONE_IS_EMPTY) {
2543 		/*
2544 		 * No time to lose; we essentially have been signaled to
2545 		 * quit.
2546 		 */
2547 		interrupted = 1;
2548 	}
2549 #ifdef RPCDEBUG
2550 	if (error == ETIME)
2551 		RPCLOG0(8, "connmgr_connect: giving up "
2552 		    "on connection attempt; "
2553 		    "clnt_dispatch notifyconn "
2554 		    "diagnostic 'no one waiting for "
2555 		    "connection' should not be "
2556 		    "unexpected\n");
2557 #endif
2558 	if (e->call_prev)
2559 		e->call_prev->call_next = e->call_next;
2560 	else
2561 		clnt_pending = e->call_next;
2562 	if (e->call_next)
2563 		e->call_next->call_prev = e->call_prev;
2564 	mutex_exit(&clnt_pending_lock);
2565 
2566 	if (e->call_status != RPC_SUCCESS || error != 0) {
2567 		if (interrupted)
2568 			e->call_status = RPC_INTR;
2569 		else if (error == ETIME)
2570 			e->call_status = RPC_TIMEDOUT;
2571 		else if (error == EPROTO)
2572 			e->call_status = RPC_SYSTEMERROR;
2573 
2574 		RPCLOG(8, "connmgr_connect: can't connect, status: "
2575 		    "%s\n", clnt_sperrno(e->call_status));
2576 
2577 		if (e->call_reply) {
2578 			freemsg(e->call_reply);
2579 			e->call_reply = NULL;
2580 		}
2581 
2582 		return (FALSE);
2583 	}
2584 	/*
2585 	 * The result of the "connection accept" is a T_info_ack
2586 	 * in the call_reply field.
2587 	 */
2588 	ASSERT(e->call_reply != NULL);
2589 	mp = e->call_reply;
2590 	e->call_reply = NULL;
2591 	tinfo = (struct T_info_ack *)mp->b_rptr;
2592 
2593 	tidu_size = tinfo->TIDU_size;
2594 	tidu_size -= (tidu_size % BYTES_PER_XDR_UNIT);
2595 	if (tidu_size > COTS_DEFAULT_ALLOCSIZE || (tidu_size <= 0))
2596 		tidu_size = COTS_DEFAULT_ALLOCSIZE;
2597 	*tidu_ptr = tidu_size;
2598 
2599 	freemsg(mp);
2600 
2601 	/*
2602 	 * Set up the pertinent options.  NODELAY is so the transport doesn't
2603 	 * buffer up RPC messages on either end.  This may not be valid for
2604 	 * all transports.  Failure to set this option is not cause to
2605 	 * bail out so we return success anyway.  Note that lack of NODELAY
2606 	 * or some other way to flush the message on both ends will cause
2607 	 * lots of retries and terrible performance.
2608 	 */
2609 	if (addrfmly == AF_INET || addrfmly == AF_INET6) {
2610 		(void) connmgr_setopt(wq, IPPROTO_TCP, TCP_NODELAY, e);
2611 		if (e->call_status == RPC_XPRTFAILED)
2612 			return (FALSE);
2613 	}
2614 
2615 	/*
2616 	 * Since we have a connection, we now need to figure out if
2617 	 * we need to create a kstat. If x_ksp is not NULL then we
2618 	 * are reusing a connection and so we do not need to create
2619 	 * another kstat -- lets just return.
2620 	 */
2621 	if (cm_entry->x_ksp != NULL)
2622 		return (TRUE);
2623 
2624 	/*
2625 	 * We need to increment rpc_kstat_instance atomically to prevent
2626 	 * two kstats being created with the same instance.
2627 	 */
2628 	kstat_instance = atomic_add_32_nv((uint32_t *)&rpc_kstat_instance, 1);
2629 
2630 	if ((cm_entry->x_ksp = kstat_create_zone("unix", kstat_instance,
2631 	    "rpc_cots_connections", "rpc", KSTAT_TYPE_NAMED,
2632 	    (uint_t)(sizeof (cm_kstat_xprt_t) / sizeof (kstat_named_t)),
2633 	    KSTAT_FLAG_VIRTUAL, cm_entry->x_zoneid)) == NULL) {
2634 		return (TRUE);
2635 	}
2636 
2637 	cm_entry->x_ksp->ks_lock = &connmgr_lock;
2638 	cm_entry->x_ksp->ks_private = cm_entry;
2639 	cm_entry->x_ksp->ks_data_size = ((INET6_ADDRSTRLEN * sizeof (char))
2640 	    + sizeof (cm_kstat_template));
2641 	cm_entry->x_ksp->ks_data = kmem_alloc(cm_entry->x_ksp->ks_data_size,
2642 	    KM_SLEEP);
2643 	bcopy(&cm_kstat_template, cm_entry->x_ksp->ks_data,
2644 	    cm_entry->x_ksp->ks_data_size);
2645 	((struct cm_kstat_xprt *)(cm_entry->x_ksp->ks_data))->
2646 	    x_server.value.str.addr.ptr =
2647 	    kmem_alloc(INET6_ADDRSTRLEN, KM_SLEEP);
2648 
2649 	cm_entry->x_ksp->ks_update = conn_kstat_update;
2650 	kstat_install(cm_entry->x_ksp);
2651 	return (TRUE);
2652 }
2653 
2654 /*
2655  * Called by connmgr_connect to set an option on the new stream.
2656  */
2657 static bool_t
2658 connmgr_setopt(queue_t *wq, int level, int name, calllist_t *e)
2659 {
2660 	mblk_t *mp;
2661 	struct opthdr *opt;
2662 	struct T_optmgmt_req *tor;
2663 	struct timeval waitp;
2664 	int error;
2665 
2666 	mp = allocb(sizeof (struct T_optmgmt_req) + sizeof (struct opthdr) +
2667 	    sizeof (int), BPRI_LO);
2668 	if (mp == NULL) {
2669 		RPCLOG0(1, "connmgr_setopt: cannot alloc mp for option "
2670 		    "request\n");
2671 		return (FALSE);
2672 	}
2673 
2674 	mp->b_datap->db_type = M_PROTO;
2675 	tor = (struct T_optmgmt_req *)(mp->b_rptr);
2676 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
2677 	tor->MGMT_flags = T_NEGOTIATE;
2678 	tor->OPT_length = sizeof (struct opthdr) + sizeof (int);
2679 	tor->OPT_offset = sizeof (struct T_optmgmt_req);
2680 
2681 	opt = (struct opthdr *)(mp->b_rptr + sizeof (struct T_optmgmt_req));
2682 	opt->level = level;
2683 	opt->name = name;
2684 	opt->len = sizeof (int);
2685 	*(int *)((char *)opt + sizeof (*opt)) = 1;
2686 	mp->b_wptr += sizeof (struct T_optmgmt_req) + sizeof (struct opthdr) +
2687 	    sizeof (int);
2688 
2689 	/*
2690 	 * We will use this connection regardless
2691 	 * of whether or not the option is settable.
2692 	 */
2693 	clnt_dispatch_send(wq, mp, e, 0, 0);
2694 	mutex_enter(&clnt_pending_lock);
2695 
2696 	waitp.tv_sec = clnt_cots_min_conntout;
2697 	waitp.tv_usec = 0;
2698 	error = waitforack(e, T_OPTMGMT_ACK, &waitp, 1);
2699 
2700 	if (e->call_prev)
2701 		e->call_prev->call_next = e->call_next;
2702 	else
2703 		clnt_pending = e->call_next;
2704 	if (e->call_next)
2705 		e->call_next->call_prev = e->call_prev;
2706 	mutex_exit(&clnt_pending_lock);
2707 
2708 	if (e->call_reply != NULL) {
2709 		freemsg(e->call_reply);
2710 		e->call_reply = NULL;
2711 	}
2712 
2713 	if (e->call_status != RPC_SUCCESS || error != 0) {
2714 		RPCLOG(1, "connmgr_setopt: can't set option: %d\n", name);
2715 		return (FALSE);
2716 	}
2717 	RPCLOG(8, "connmgr_setopt: successfully set option: %d\n", name);
2718 	return (TRUE);
2719 }
2720 
2721 #ifdef	DEBUG
2722 
2723 /*
2724  * This is a knob to let us force code coverage in allocation failure
2725  * case.
2726  */
2727 static int	connmgr_failsnd;
2728 #define	CONN_SND_ALLOC(Size, Pri)	\
2729 	((connmgr_failsnd-- > 0) ? NULL : allocb(Size, Pri))
2730 
2731 #else
2732 
2733 #define	CONN_SND_ALLOC(Size, Pri)	allocb(Size, Pri)
2734 
2735 #endif
2736 
2737 /*
2738  * Sends an orderly release on the specified queue.
2739  * Entered with connmgr_lock. Exited without connmgr_lock
2740  */
2741 static void
2742 connmgr_sndrel(struct cm_xprt *cm_entry)
2743 {
2744 	struct T_ordrel_req *torr;
2745 	mblk_t *mp;
2746 	queue_t *q = cm_entry->x_wq;
2747 	ASSERT(MUTEX_HELD(&connmgr_lock));
2748 	mp = CONN_SND_ALLOC(sizeof (struct T_ordrel_req), BPRI_LO);
2749 	if (mp == NULL) {
2750 		cm_entry->x_needrel = TRUE;
2751 		mutex_exit(&connmgr_lock);
2752 		RPCLOG(1, "connmgr_sndrel: cannot alloc mp for sending ordrel "
2753 		    "to queue %p\n", (void *)q);
2754 		return;
2755 	}
2756 	mutex_exit(&connmgr_lock);
2757 
2758 	mp->b_datap->db_type = M_PROTO;
2759 	torr = (struct T_ordrel_req *)(mp->b_rptr);
2760 	torr->PRIM_type = T_ORDREL_REQ;
2761 	mp->b_wptr = mp->b_rptr + sizeof (struct T_ordrel_req);
2762 
2763 	RPCLOG(8, "connmgr_sndrel: sending ordrel to queue %p\n", (void *)q);
2764 	put(q, mp);
2765 }
2766 
2767 /*
2768  * Sends an disconnect on the specified queue.
2769  * Entered with connmgr_lock. Exited without connmgr_lock
2770  */
2771 static void
2772 connmgr_snddis(struct cm_xprt *cm_entry)
2773 {
2774 	struct T_discon_req *tdis;
2775 	mblk_t *mp;
2776 	queue_t *q = cm_entry->x_wq;
2777 
2778 	ASSERT(MUTEX_HELD(&connmgr_lock));
2779 	mp = CONN_SND_ALLOC(sizeof (*tdis), BPRI_LO);
2780 	if (mp == NULL) {
2781 		cm_entry->x_needdis = TRUE;
2782 		mutex_exit(&connmgr_lock);
2783 		RPCLOG(1, "connmgr_snddis: cannot alloc mp for sending discon "
2784 		    "to queue %p\n", (void *)q);
2785 		return;
2786 	}
2787 	mutex_exit(&connmgr_lock);
2788 
2789 	mp->b_datap->db_type = M_PROTO;
2790 	tdis = (struct T_discon_req *)mp->b_rptr;
2791 	tdis->PRIM_type = T_DISCON_REQ;
2792 	mp->b_wptr = mp->b_rptr + sizeof (*tdis);
2793 
2794 	RPCLOG(8, "connmgr_snddis: sending discon to queue %p\n", (void *)q);
2795 	put(q, mp);
2796 }
2797 
2798 /*
2799  * Sets up the entry for receiving replies, and calls rpcmod's write put proc
2800  * (through put) to send the call.
2801  */
2802 static void
2803 clnt_dispatch_send(queue_t *q, mblk_t *mp, calllist_t *e, uint_t xid,
2804 			uint_t queue_flag)
2805 {
2806 	ASSERT(e != NULL);
2807 
2808 	e->call_status = RPC_TIMEDOUT;	/* optimistic, eh? */
2809 	e->call_reason = 0;
2810 	e->call_wq = q;
2811 	e->call_xid = xid;
2812 	e->call_notified = FALSE;
2813 
2814 	/*
2815 	 * If queue_flag is set then the calllist_t is already on the hash
2816 	 * queue.  In this case just send the message and return.
2817 	 */
2818 	if (queue_flag) {
2819 		put(q, mp);
2820 		return;
2821 	}
2822 
2823 	/*
2824 	 * Set up calls for RPC requests (with XID != 0) on the hash
2825 	 * queue for fast lookups and place other calls (i.e.
2826 	 * connection management) on the linked list.
2827 	 */
2828 	if (xid != 0) {
2829 		RPCLOG(64, "clnt_dispatch_send: putting xid 0x%x on "
2830 		    "dispatch list\n", xid);
2831 		e->call_hash = call_hash(xid, clnt_cots_hash_size);
2832 		e->call_bucket = &cots_call_ht[e->call_hash];
2833 		call_table_enter(e);
2834 	} else {
2835 		mutex_enter(&clnt_pending_lock);
2836 		if (clnt_pending)
2837 			clnt_pending->call_prev = e;
2838 		e->call_next = clnt_pending;
2839 		e->call_prev = NULL;
2840 		clnt_pending = e;
2841 		mutex_exit(&clnt_pending_lock);
2842 	}
2843 
2844 	put(q, mp);
2845 }
2846 
2847 /*
2848  * Called by rpcmod to notify a client with a clnt_pending call that its reply
2849  * has arrived.  If we can't find a client waiting for this reply, we log
2850  * the error and return.
2851  */
2852 bool_t
2853 clnt_dispatch_notify(mblk_t *mp, zoneid_t zoneid)
2854 {
2855 	calllist_t *e = NULL;
2856 	call_table_t *chtp;
2857 	uint32_t xid;
2858 	uint_t hash;
2859 
2860 	if ((IS_P2ALIGNED(mp->b_rptr, sizeof (uint32_t))) &&
2861 	    (mp->b_wptr - mp->b_rptr) >= sizeof (xid))
2862 		xid = *((uint32_t *)mp->b_rptr);
2863 	else {
2864 		int i = 0;
2865 		unsigned char *p = (unsigned char *)&xid;
2866 		unsigned char *rptr;
2867 		mblk_t *tmp = mp;
2868 
2869 		/*
2870 		 * Copy the xid, byte-by-byte into xid.
2871 		 */
2872 		while (tmp) {
2873 			rptr = tmp->b_rptr;
2874 			while (rptr < tmp->b_wptr) {
2875 				*p++ = *rptr++;
2876 				if (++i >= sizeof (xid))
2877 					goto done_xid_copy;
2878 			}
2879 			tmp = tmp->b_cont;
2880 		}
2881 
2882 		/*
2883 		 * If we got here, we ran out of mblk space before the
2884 		 * xid could be copied.
2885 		 */
2886 		ASSERT(tmp == NULL && i < sizeof (xid));
2887 
2888 		RPCLOG0(1,
2889 		    "clnt_dispatch_notify: message less than size of xid\n");
2890 		return (FALSE);
2891 
2892 	}
2893 done_xid_copy:
2894 
2895 	hash = call_hash(xid, clnt_cots_hash_size);
2896 	chtp = &cots_call_ht[hash];
2897 	/* call_table_find returns with the hash bucket locked */
2898 	call_table_find(chtp, xid, e);
2899 
2900 	if (e != NULL) {
2901 		/*
2902 		 * Found thread waiting for this reply
2903 		 */
2904 		mutex_enter(&e->call_lock);
2905 
2906 		/*
2907 		 * verify that the reply is coming in on
2908 		 * the same zone that it was sent from.
2909 		 */
2910 		if (e->call_zoneid != zoneid) {
2911 			mutex_exit(&e->call_lock);
2912 			mutex_exit(&chtp->ct_lock);
2913 			return (FALSE);
2914 		}
2915 
2916 		if (e->call_reply)
2917 			/*
2918 			 * This can happen under the following scenario:
2919 			 * clnt_cots_kcallit() times out on the response,
2920 			 * rfscall() repeats the CLNT_CALL() with
2921 			 * the same xid, clnt_cots_kcallit() sends the retry,
2922 			 * thereby putting the clnt handle on the pending list,
2923 			 * the first response arrives, signalling the thread
2924 			 * in clnt_cots_kcallit(). Before that thread is
2925 			 * dispatched, the second response arrives as well,
2926 			 * and clnt_dispatch_notify still finds the handle on
2927 			 * the pending list, with call_reply set. So free the
2928 			 * old reply now.
2929 			 *
2930 			 * It is also possible for a response intended for
2931 			 * an RPC call with a different xid to reside here.
2932 			 * This can happen if the thread that owned this
2933 			 * client handle prior to the current owner bailed
2934 			 * out and left its call record on the dispatch
2935 			 * queue.  A window exists where the response can
2936 			 * arrive before the current owner dispatches its
2937 			 * RPC call.
2938 			 *
2939 			 * In any case, this is the very last point where we
2940 			 * can safely check the call_reply field before
2941 			 * placing the new response there.
2942 			 */
2943 			freemsg(e->call_reply);
2944 		e->call_reply = mp;
2945 		e->call_status = RPC_SUCCESS;
2946 		e->call_notified = TRUE;
2947 		cv_signal(&e->call_cv);
2948 		mutex_exit(&e->call_lock);
2949 		mutex_exit(&chtp->ct_lock);
2950 		return (TRUE);
2951 	} else {
2952 		zone_t *zone;
2953 		struct rpcstat *rpcstat;
2954 
2955 		mutex_exit(&chtp->ct_lock);
2956 		RPCLOG(65, "clnt_dispatch_notify: no caller for reply 0x%x\n",
2957 		    xid);
2958 		/*
2959 		 * This is unfortunate, but we need to lookup the zone so we
2960 		 * can increment its "rcbadxids" counter.
2961 		 */
2962 		zone = zone_find_by_id(zoneid);
2963 		if (zone == NULL) {
2964 			/*
2965 			 * The zone went away...
2966 			 */
2967 			return (FALSE);
2968 		}
2969 		rpcstat = zone_getspecific(rpcstat_zone_key, zone);
2970 		if (zone_status_get(zone) >= ZONE_IS_SHUTTING_DOWN) {
2971 			/*
2972 			 * Not interested
2973 			 */
2974 			zone_rele(zone);
2975 			return (FALSE);
2976 		}
2977 		COTSRCSTAT_INCR(rpcstat->rpc_cots_client, rcbadxids);
2978 		zone_rele(zone);
2979 	}
2980 	return (FALSE);
2981 }
2982 
2983 /*
2984  * Called by rpcmod when a non-data indication arrives.  The ones in which we
2985  * are interested are connection indications and options acks.  We dispatch
2986  * based on the queue the indication came in on.  If we are not interested in
2987  * what came in, we return false to rpcmod, who will then pass it upstream.
2988  */
2989 bool_t
2990 clnt_dispatch_notifyconn(queue_t *q, mblk_t *mp)
2991 {
2992 	calllist_t *e;
2993 	int type;
2994 
2995 	ASSERT((q->q_flag & QREADR) == 0);
2996 
2997 	type = ((union T_primitives *)mp->b_rptr)->type;
2998 	RPCLOG(8, "clnt_dispatch_notifyconn: prim type: [%s]\n",
2999 	    rpc_tpiprim2name(type));
3000 	mutex_enter(&clnt_pending_lock);
3001 	for (e = clnt_pending; /* NO CONDITION */; e = e->call_next) {
3002 		if (e == NULL) {
3003 			mutex_exit(&clnt_pending_lock);
3004 			RPCLOG(1, "clnt_dispatch_notifyconn: no one waiting "
3005 			    "for connection on queue 0x%p\n", (void *)q);
3006 			return (FALSE);
3007 		}
3008 		if (e->call_wq == q)
3009 			break;
3010 	}
3011 
3012 	switch (type) {
3013 	case T_CONN_CON:
3014 		/*
3015 		 * The transport is now connected, send a T_INFO_REQ to get
3016 		 * the tidu size.
3017 		 */
3018 		mutex_exit(&clnt_pending_lock);
3019 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
3020 		    sizeof (struct T_info_req));
3021 		mp->b_rptr = mp->b_datap->db_base;
3022 		((union T_primitives *)mp->b_rptr)->type = T_INFO_REQ;
3023 		mp->b_wptr = mp->b_rptr + sizeof (struct T_info_req);
3024 		mp->b_datap->db_type = M_PCPROTO;
3025 		put(q, mp);
3026 		return (TRUE);
3027 	case T_INFO_ACK:
3028 	case T_OPTMGMT_ACK:
3029 		e->call_status = RPC_SUCCESS;
3030 		e->call_reply = mp;
3031 		e->call_notified = TRUE;
3032 		cv_signal(&e->call_cv);
3033 		break;
3034 	case T_ERROR_ACK:
3035 		e->call_status = RPC_CANTCONNECT;
3036 		e->call_reply = mp;
3037 		e->call_notified = TRUE;
3038 		cv_signal(&e->call_cv);
3039 		break;
3040 	case T_OK_ACK:
3041 		/*
3042 		 * Great, but we are really waiting for a T_CONN_CON
3043 		 */
3044 		freemsg(mp);
3045 		break;
3046 	default:
3047 		mutex_exit(&clnt_pending_lock);
3048 		RPCLOG(1, "clnt_dispatch_notifyconn: bad type %d\n", type);
3049 		return (FALSE);
3050 	}
3051 
3052 	mutex_exit(&clnt_pending_lock);
3053 	return (TRUE);
3054 }
3055 
3056 /*
3057  * Called by rpcmod when the transport is (or should be) going away.  Informs
3058  * all callers waiting for replies and marks the entry in the connection
3059  * manager's list as unconnected, and either closing (close handshake in
3060  * progress) or dead.
3061  */
3062 void
3063 clnt_dispatch_notifyall(queue_t *q, int32_t msg_type, int32_t reason)
3064 {
3065 	calllist_t *e;
3066 	call_table_t *ctp;
3067 	struct cm_xprt *cm_entry;
3068 	int have_connmgr_lock;
3069 	int i;
3070 
3071 	ASSERT((q->q_flag & QREADR) == 0);
3072 
3073 	RPCLOG(1, "clnt_dispatch_notifyall on queue %p", (void *)q);
3074 	RPCLOG(1, " received a notifcation prim type [%s]",
3075 	    rpc_tpiprim2name(msg_type));
3076 	RPCLOG(1, " and reason %d\n", reason);
3077 
3078 	/*
3079 	 * Find the transport entry in the connection manager's list, close
3080 	 * the transport and delete the entry.  In the case where rpcmod's
3081 	 * idle timer goes off, it sends us a T_ORDREL_REQ, indicating we
3082 	 * should gracefully close the connection.
3083 	 */
3084 	have_connmgr_lock = 1;
3085 	mutex_enter(&connmgr_lock);
3086 	for (cm_entry = cm_hd; cm_entry; cm_entry = cm_entry->x_next) {
3087 		ASSERT(cm_entry != cm_entry->x_next);
3088 		if (cm_entry->x_wq == q) {
3089 			ASSERT(MUTEX_HELD(&connmgr_lock));
3090 			ASSERT(have_connmgr_lock == 1);
3091 			switch (msg_type) {
3092 			case T_ORDREL_REQ:
3093 
3094 				if (cm_entry->x_dead) {
3095 					RPCLOG(1, "idle timeout on dead "
3096 					    "connection: %p\n",
3097 					    (void *)cm_entry);
3098 					if (clnt_stop_idle != NULL)
3099 						(*clnt_stop_idle)(q);
3100 					break;
3101 				}
3102 
3103 				/*
3104 				 * Only mark the connection as dead if it is
3105 				 * connected and idle.
3106 				 * An unconnected connection has probably
3107 				 * gone idle because the server is down,
3108 				 * and when it comes back up there will be
3109 				 * retries that need to use that connection.
3110 				 */
3111 				if (cm_entry->x_connected ||
3112 				    cm_entry->x_doomed) {
3113 					if (cm_entry->x_ordrel) {
3114 						if (cm_entry->x_closing ==
3115 						    TRUE) {
3116 							/*
3117 							 * The connection is
3118 							 * obviously wedged due
3119 							 * to a bug or problem
3120 							 * with the transport.
3121 							 * Mark it as dead.
3122 							 * Otherwise we can
3123 							 * leak connections.
3124 							 */
3125 							cm_entry->x_dead = TRUE;
3126 							mutex_exit(
3127 							    &connmgr_lock);
3128 							have_connmgr_lock = 0;
3129 							if (clnt_stop_idle !=
3130 							    NULL)
3131 							(*clnt_stop_idle)(q);
3132 							break;
3133 						}
3134 						cm_entry->x_closing = TRUE;
3135 						connmgr_sndrel(cm_entry);
3136 						have_connmgr_lock = 0;
3137 					} else {
3138 						cm_entry->x_dead = TRUE;
3139 						mutex_exit(&connmgr_lock);
3140 						have_connmgr_lock = 0;
3141 						if (clnt_stop_idle != NULL)
3142 							(*clnt_stop_idle)(q);
3143 					}
3144 				} else {
3145 					/*
3146 					 * We don't mark the connection
3147 					 * as dead, but we turn off the
3148 					 * idle timer.
3149 					 */
3150 					mutex_exit(&connmgr_lock);
3151 					have_connmgr_lock = 0;
3152 					if (clnt_stop_idle != NULL)
3153 						(*clnt_stop_idle)(q);
3154 					RPCLOG(1, "clnt_dispatch_notifyall:"
3155 					    " ignoring timeout from rpcmod"
3156 					    " (q %p) because we are not "
3157 					    " connected\n", (void *)q);
3158 				}
3159 				break;
3160 			case T_ORDREL_IND:
3161 				/*
3162 				 * If this entry is marked closing, then we are
3163 				 * completing a close handshake, and the
3164 				 * connection is dead.  Otherwise, the server is
3165 				 * trying to close. Since the server will not
3166 				 * be sending any more RPC replies, we abort
3167 				 * the connection, including flushing
3168 				 * any RPC requests that are in-transit.
3169 				 */
3170 				if (cm_entry->x_closing) {
3171 					cm_entry->x_dead = TRUE;
3172 					mutex_exit(&connmgr_lock);
3173 					have_connmgr_lock = 0;
3174 					if (clnt_stop_idle != NULL)
3175 						(*clnt_stop_idle)(q);
3176 				} else {
3177 					/*
3178 					 * if we're getting a disconnect
3179 					 * before we've finished our
3180 					 * connect attempt, mark it for
3181 					 * later processing
3182 					 */
3183 					if (cm_entry->x_thread)
3184 						cm_entry->x_early_disc = TRUE;
3185 					else
3186 						cm_entry->x_connected = FALSE;
3187 					cm_entry->x_waitdis = TRUE;
3188 					connmgr_snddis(cm_entry);
3189 					have_connmgr_lock = 0;
3190 				}
3191 				break;
3192 
3193 			case T_ERROR_ACK:
3194 			case T_OK_ACK:
3195 				cm_entry->x_waitdis = FALSE;
3196 				cv_signal(&cm_entry->x_dis_cv);
3197 				mutex_exit(&connmgr_lock);
3198 				return;
3199 
3200 			case T_DISCON_REQ:
3201 				if (cm_entry->x_thread)
3202 					cm_entry->x_early_disc = TRUE;
3203 				else
3204 					cm_entry->x_connected = FALSE;
3205 				cm_entry->x_waitdis = TRUE;
3206 
3207 				connmgr_snddis(cm_entry);
3208 				have_connmgr_lock = 0;
3209 				break;
3210 
3211 			case T_DISCON_IND:
3212 			default:
3213 				/*
3214 				 * if we're getting a disconnect before
3215 				 * we've finished our connect attempt,
3216 				 * mark it for later processing
3217 				 */
3218 				if (cm_entry->x_closing) {
3219 					cm_entry->x_dead = TRUE;
3220 					mutex_exit(&connmgr_lock);
3221 					have_connmgr_lock = 0;
3222 					if (clnt_stop_idle != NULL)
3223 						(*clnt_stop_idle)(q);
3224 				} else {
3225 					if (cm_entry->x_thread) {
3226 						cm_entry->x_early_disc = TRUE;
3227 					} else {
3228 						cm_entry->x_dead = TRUE;
3229 						cm_entry->x_connected = FALSE;
3230 					}
3231 				}
3232 				break;
3233 			}
3234 			break;
3235 		}
3236 	}
3237 
3238 	if (have_connmgr_lock)
3239 		mutex_exit(&connmgr_lock);
3240 
3241 	if (msg_type == T_ERROR_ACK || msg_type == T_OK_ACK) {
3242 		RPCLOG(1, "clnt_dispatch_notifyall: (wq %p) could not find "
3243 		    "connmgr entry for discon ack\n", (void *)q);
3244 		return;
3245 	}
3246 
3247 	/*
3248 	 * Then kick all the clnt_pending calls out of their wait.  There
3249 	 * should be no clnt_pending calls in the case of rpcmod's idle
3250 	 * timer firing.
3251 	 */
3252 	for (i = 0; i < clnt_cots_hash_size; i++) {
3253 		ctp = &cots_call_ht[i];
3254 		mutex_enter(&ctp->ct_lock);
3255 		for (e = ctp->ct_call_next;
3256 		    e != (calllist_t *)ctp;
3257 		    e = e->call_next) {
3258 			if (e->call_wq == q && e->call_notified == FALSE) {
3259 				RPCLOG(1,
3260 				    "clnt_dispatch_notifyall for queue %p ",
3261 				    (void *)q);
3262 				RPCLOG(1, "aborting clnt_pending call %p\n",
3263 				    (void *)e);
3264 
3265 				if (msg_type == T_DISCON_IND)
3266 					e->call_reason = reason;
3267 				e->call_notified = TRUE;
3268 				e->call_status = RPC_XPRTFAILED;
3269 				cv_signal(&e->call_cv);
3270 			}
3271 		}
3272 		mutex_exit(&ctp->ct_lock);
3273 	}
3274 
3275 	mutex_enter(&clnt_pending_lock);
3276 	for (e = clnt_pending; e; e = e->call_next) {
3277 		/*
3278 		 * Only signal those RPC handles that haven't been
3279 		 * signalled yet. Otherwise we can get a bogus call_reason.
3280 		 * This can happen if thread A is making a call over a
3281 		 * connection. If the server is killed, it will cause
3282 		 * reset, and reason will default to EIO as a result of
3283 		 * a T_ORDREL_IND. Thread B then attempts to recreate
3284 		 * the connection but gets a T_DISCON_IND. If we set the
3285 		 * call_reason code for all threads, then if thread A
3286 		 * hasn't been dispatched yet, it will get the wrong
3287 		 * reason. The bogus call_reason can make it harder to
3288 		 * discriminate between calls that fail because the
3289 		 * connection attempt failed versus those where the call
3290 		 * may have been executed on the server.
3291 		 */
3292 		if (e->call_wq == q && e->call_notified == FALSE) {
3293 			RPCLOG(1, "clnt_dispatch_notifyall for queue %p ",
3294 			    (void *)q);
3295 			RPCLOG(1, " aborting clnt_pending call %p\n",
3296 			    (void *)e);
3297 
3298 			if (msg_type == T_DISCON_IND)
3299 				e->call_reason = reason;
3300 			e->call_notified = TRUE;
3301 			/*
3302 			 * Let the caller timeout, else he will retry
3303 			 * immediately.
3304 			 */
3305 			e->call_status = RPC_XPRTFAILED;
3306 
3307 			/*
3308 			 * We used to just signal those threads
3309 			 * waiting for a connection, (call_xid = 0).
3310 			 * That meant that threads waiting for a response
3311 			 * waited till their timeout expired. This
3312 			 * could be a long time if they've specified a
3313 			 * maximum timeout. (2^31 - 1). So we
3314 			 * Signal all threads now.
3315 			 */
3316 			cv_signal(&e->call_cv);
3317 		}
3318 	}
3319 	mutex_exit(&clnt_pending_lock);
3320 }
3321 
3322 
3323 /*ARGSUSED*/
3324 /*
3325  * after resuming a system that's been suspended for longer than the
3326  * NFS server's idle timeout (svc_idle_timeout for Solaris 2), rfscall()
3327  * generates "NFS server X not responding" and "NFS server X ok" messages;
3328  * here we reset inet connections to cause a re-connect and avoid those
3329  * NFS messages.  see 4045054
3330  */
3331 boolean_t
3332 connmgr_cpr_reset(void *arg, int code)
3333 {
3334 	struct cm_xprt *cxp;
3335 
3336 	if (code == CB_CODE_CPR_CHKPT)
3337 		return (B_TRUE);
3338 
3339 	if (mutex_tryenter(&connmgr_lock) == 0)
3340 		return (B_FALSE);
3341 	for (cxp = cm_hd; cxp; cxp = cxp->x_next) {
3342 		if ((cxp->x_family == AF_INET || cxp->x_family == AF_INET6) &&
3343 		    cxp->x_connected == TRUE) {
3344 			if (cxp->x_thread)
3345 				cxp->x_early_disc = TRUE;
3346 			else
3347 				cxp->x_connected = FALSE;
3348 			cxp->x_needdis = TRUE;
3349 		}
3350 	}
3351 	mutex_exit(&connmgr_lock);
3352 	return (B_TRUE);
3353 }
3354 
3355 void
3356 clnt_cots_stats_init(zoneid_t zoneid, struct rpc_cots_client **statsp)
3357 {
3358 
3359 	*statsp = (struct rpc_cots_client *)rpcstat_zone_init_common(zoneid,
3360 	    "unix", "rpc_cots_client", (const kstat_named_t *)&cots_rcstat_tmpl,
3361 	    sizeof (cots_rcstat_tmpl));
3362 }
3363 
3364 void
3365 clnt_cots_stats_fini(zoneid_t zoneid, struct rpc_cots_client **statsp)
3366 {
3367 	rpcstat_zone_fini_common(zoneid, "unix", "rpc_cots_client");
3368 	kmem_free(*statsp, sizeof (cots_rcstat_tmpl));
3369 }
3370 
3371 void
3372 clnt_cots_init(void)
3373 {
3374 	mutex_init(&connmgr_lock, NULL, MUTEX_DEFAULT, NULL);
3375 	mutex_init(&clnt_pending_lock, NULL, MUTEX_DEFAULT, NULL);
3376 
3377 	if (clnt_cots_hash_size < DEFAULT_MIN_HASH_SIZE)
3378 		clnt_cots_hash_size = DEFAULT_MIN_HASH_SIZE;
3379 
3380 	cots_call_ht = call_table_init(clnt_cots_hash_size);
3381 	zone_key_create(&zone_cots_key, NULL, NULL, clnt_zone_destroy);
3382 }
3383 
3384 void
3385 clnt_cots_fini(void)
3386 {
3387 	(void) zone_key_delete(zone_cots_key);
3388 }
3389 
3390 /*
3391  * Wait for TPI ack, returns success only if expected ack is received
3392  * within timeout period.
3393  */
3394 
3395 static int
3396 waitforack(calllist_t *e, t_scalar_t ack_prim, const struct timeval *waitp,
3397     bool_t nosignal)
3398 {
3399 	union T_primitives *tpr;
3400 	clock_t timout;
3401 	int cv_stat = 1;
3402 
3403 	ASSERT(MUTEX_HELD(&clnt_pending_lock));
3404 	while (e->call_reply == NULL) {
3405 		if (waitp != NULL) {
3406 			timout = waitp->tv_sec * drv_usectohz(MICROSEC) +
3407 			    drv_usectohz(waitp->tv_usec) + lbolt;
3408 			if (nosignal)
3409 				cv_stat = cv_timedwait(&e->call_cv,
3410 				    &clnt_pending_lock, timout);
3411 			else
3412 				cv_stat = cv_timedwait_sig(&e->call_cv,
3413 				    &clnt_pending_lock, timout);
3414 		} else {
3415 			if (nosignal)
3416 				cv_wait(&e->call_cv, &clnt_pending_lock);
3417 			else
3418 				cv_stat = cv_wait_sig(&e->call_cv,
3419 				    &clnt_pending_lock);
3420 		}
3421 		if (cv_stat == -1)
3422 			return (ETIME);
3423 		if (cv_stat == 0)
3424 			return (EINTR);
3425 		/*
3426 		 * if we received an error from the server and we know a reply
3427 		 * is not going to be sent, do not wait for the full timeout,
3428 		 * return now.
3429 		 */
3430 		if (e->call_status == RPC_XPRTFAILED)
3431 			return (e->call_reason);
3432 	}
3433 	tpr = (union T_primitives *)e->call_reply->b_rptr;
3434 	if (tpr->type == ack_prim)
3435 		return (0); /* Success */
3436 
3437 	if (tpr->type == T_ERROR_ACK) {
3438 		if (tpr->error_ack.TLI_error == TSYSERR)
3439 			return (tpr->error_ack.UNIX_error);
3440 		else
3441 			return (t_tlitosyserr(tpr->error_ack.TLI_error));
3442 	}
3443 
3444 	return (EPROTO); /* unknown or unexpected primitive */
3445 }
3446