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