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