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