xref: /titanic_52/usr/src/uts/common/rpc/clnt_cots.c (revision b365acd0c29cb0376af78f1f0662459a9d216641)
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 = 0; /* bind to a non-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 (cm_entry) {
1313 					/*
1314 					 * There is the potential that the
1315 					 * cm_entry has/will be marked dead,
1316 					 * so drop our ref to it, force REFRESH
1317 					 * to establish new connection.
1318 					 */
1319 					connmgr_release(cm_entry);
1320 					cm_entry = NULL;
1321 				}
1322 
1323 				if ((refreshes > 0) &&
1324 				    AUTH_REFRESH(h->cl_auth, &reply_msg,
1325 						p->cku_cred)) {
1326 					refreshes--;
1327 					(void) xdr_rpc_free_verifier(xdrs,
1328 								&reply_msg);
1329 					freemsg(mp);
1330 					mp = NULL;
1331 
1332 					if (p->cku_flags & CKU_ONQUEUE) {
1333 						call_table_remove(call);
1334 						p->cku_flags &= ~CKU_ONQUEUE;
1335 					}
1336 
1337 					RPCLOG(64,
1338 					    "clnt_cots_kcallit: AUTH_ERROR, xid"
1339 					    " 0x%x removed off dispatch list\n",
1340 					    p->cku_xid);
1341 					if (call->call_reply) {
1342 						freemsg(call->call_reply);
1343 						call->call_reply = NULL;
1344 					}
1345 
1346 					COTSRCSTAT_INCR(p->cku_stats,
1347 							rcbadcalls);
1348 					COTSRCSTAT_INCR(p->cku_stats,
1349 							rcnewcreds);
1350 					goto call_again;
1351 				} else {
1352 				/*
1353 				 * We have used the client handle to
1354 				 * do an AUTH_REFRESH and the RPC status may
1355 				 * be set to RPC_SUCCESS; Let's make sure to
1356 				 * set it to RPC_AUTHERROR.
1357 				 */
1358 				p->cku_err.re_status = RPC_AUTHERROR;
1359 				/*
1360 				 * Map recoverable and unrecoverable
1361 				 * authentication errors to appropriate errno
1362 				 */
1363 				switch (p->cku_err.re_why) {
1364 				case AUTH_TOOWEAK:
1365 					/*
1366 					 * This could be a failure where the
1367 					 * server requires use of a reserved
1368 					 * port,  check and optionally set the
1369 					 * client handle useresvport trying
1370 					 * one more time. Next go round we
1371 					 * fall out with the tooweak error.
1372 					 */
1373 					if (p->cku_useresvport != 1) {
1374 						p->cku_useresvport = 1;
1375 						p->cku_xid = 0;
1376 						(void) xdr_rpc_free_verifier
1377 							    (xdrs, &reply_msg);
1378 						freemsg(mp);
1379 						/*
1380 						 * If we got this far the
1381 						 * connection we are using is
1382 						 * connected but not valid,
1383 						 * (not a resv port) drop it
1384 						 * and force a connection.
1385 						 */
1386 						if (cm_entry) {
1387 							connmgr_cancelconn
1388 								(cm_entry);
1389 							cm_entry = NULL;
1390 						}
1391 						goto call_again;
1392 					}
1393 					/* FALLTHRU */
1394 				case AUTH_BADCRED:
1395 				case AUTH_BADVERF:
1396 				case AUTH_INVALIDRESP:
1397 				case AUTH_FAILED:
1398 				case RPCSEC_GSS_NOCRED:
1399 				case RPCSEC_GSS_FAILED:
1400 						p->cku_err.re_errno = EACCES;
1401 						break;
1402 				case AUTH_REJECTEDCRED:
1403 				case AUTH_REJECTEDVERF:
1404 				default:	p->cku_err.re_errno = EIO;
1405 						break;
1406 				}
1407 				RPCLOG(1, "clnt_cots_kcallit : authentication"
1408 				    " failed with RPC_AUTHERROR of type %d\n",
1409 				    (int)p->cku_err.re_why);
1410 			    }
1411 			}
1412 		}
1413 	} else {
1414 		/* reply didn't decode properly. */
1415 		p->cku_err.re_status = RPC_CANTDECODERES;
1416 		p->cku_err.re_errno = EIO;
1417 		RPCLOG0(1, "clnt_cots_kcallit: decode failure\n");
1418 	}
1419 
1420 	(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
1421 
1422 	if (p->cku_flags & CKU_ONQUEUE) {
1423 		call_table_remove(call);
1424 		p->cku_flags &= ~CKU_ONQUEUE;
1425 	}
1426 
1427 	RPCLOG(64, "clnt_cots_kcallit: xid 0x%x taken off dispatch list",
1428 	    p->cku_xid);
1429 	RPCLOG(64, " status is %s\n", clnt_sperrno(p->cku_err.re_status));
1430 cots_done:
1431 	if (cm_entry)
1432 		connmgr_release(cm_entry);
1433 
1434 	if (mp != NULL)
1435 		freemsg(mp);
1436 	if ((p->cku_flags & CKU_ONQUEUE) == 0 && call->call_reply) {
1437 		freemsg(call->call_reply);
1438 		call->call_reply = NULL;
1439 	}
1440 	if (p->cku_err.re_status != RPC_SUCCESS) {
1441 		RPCLOG0(1, "clnt_cots_kcallit: tail-end failure\n");
1442 		COTSRCSTAT_INCR(p->cku_stats, rcbadcalls);
1443 	}
1444 
1445 	/*
1446 	 * No point in delaying if the zone is going away.
1447 	 */
1448 	if (delay_first == TRUE &&
1449 	    !(zone_status_get(curproc->p_zone) >= ZONE_IS_SHUTTING_DOWN)) {
1450 		if (clnt_delay(ticks, h->cl_nosignal) == EINTR) {
1451 			p->cku_err.re_errno = EINTR;
1452 			p->cku_err.re_status = RPC_INTR;
1453 		}
1454 	}
1455 	return (p->cku_err.re_status);
1456 }
1457 
1458 /*
1459  * Kinit routine for cots.  This sets up the correct operations in
1460  * the client handle, as the handle may have previously been a clts
1461  * handle, and clears the xid field so there is no way a new call
1462  * could be mistaken for a retry.  It also sets in the handle the
1463  * information that is passed at create/kinit time but needed at
1464  * call time, as cots creates the transport at call time - device,
1465  * address of the server, protocol family.
1466  */
1467 void
1468 clnt_cots_kinit(CLIENT *h, dev_t dev, int family, struct netbuf *addr,
1469 	int max_msgsize, cred_t *cred)
1470 {
1471 	/* LINTED pointer alignment */
1472 	cku_private_t *p = htop(h);
1473 	calllist_t *call = &p->cku_call;
1474 
1475 	h->cl_ops = &tcp_ops;
1476 	if (p->cku_flags & CKU_ONQUEUE) {
1477 		call_table_remove(call);
1478 		p->cku_flags &= ~CKU_ONQUEUE;
1479 		RPCLOG(64, "clnt_cots_kinit: removing call for xid 0x%x from"
1480 		    " dispatch list\n", p->cku_xid);
1481 	}
1482 
1483 	if (call->call_reply != NULL) {
1484 		freemsg(call->call_reply);
1485 		call->call_reply = NULL;
1486 	}
1487 
1488 	call->call_bucket = NULL;
1489 	call->call_hash = 0;
1490 
1491 	/*
1492 	 * We don't clear cku_flags here, because clnt_cots_kcallit()
1493 	 * takes care of handling the cku_flags reset.
1494 	 */
1495 	p->cku_xid = 0;
1496 	p->cku_device = dev;
1497 	p->cku_addrfmly = family;
1498 	p->cku_cred = cred;
1499 
1500 	if (p->cku_addr.maxlen < addr->len) {
1501 		if (p->cku_addr.maxlen != 0 && p->cku_addr.buf != NULL)
1502 			kmem_free(p->cku_addr.buf, p->cku_addr.maxlen);
1503 		p->cku_addr.buf = kmem_zalloc(addr->maxlen, KM_SLEEP);
1504 		p->cku_addr.maxlen = addr->maxlen;
1505 	}
1506 
1507 	p->cku_addr.len = addr->len;
1508 	bcopy(addr->buf, p->cku_addr.buf, addr->len);
1509 
1510 	/*
1511 	 * If the current sanity check size in rpcmod is smaller
1512 	 * than the size needed, then increase the sanity check.
1513 	 */
1514 	if (max_msgsize != 0 && clnt_max_msg_sizep != NULL &&
1515 	    max_msgsize > *clnt_max_msg_sizep) {
1516 		mutex_enter(&clnt_max_msg_lock);
1517 		if (max_msgsize > *clnt_max_msg_sizep)
1518 			*clnt_max_msg_sizep = max_msgsize;
1519 		mutex_exit(&clnt_max_msg_lock);
1520 	}
1521 }
1522 
1523 /*
1524  * ksettimers is a no-op for cots, with the exception of setting the xid.
1525  */
1526 /* ARGSUSED */
1527 static int
1528 clnt_cots_ksettimers(CLIENT *h, struct rpc_timers *t, struct rpc_timers *all,
1529 	int minimum, void (*feedback)(int, int, caddr_t), caddr_t arg,
1530 	uint32_t xid)
1531 {
1532 	/* LINTED pointer alignment */
1533 	cku_private_t *p = htop(h);
1534 
1535 	if (xid)
1536 		p->cku_xid = xid;
1537 	COTSRCSTAT_INCR(p->cku_stats, rctimers);
1538 	return (0);
1539 }
1540 
1541 extern void rpc_poptimod(struct vnode *);
1542 extern int kstr_push(struct vnode *, char *);
1543 
1544 int
1545 conn_kstat_update(kstat_t *ksp, int rw)
1546 {
1547 	struct cm_xprt *cm_entry;
1548 	struct cm_kstat_xprt *cm_ksp_data;
1549 	uchar_t *b;
1550 	char *fbuf;
1551 
1552 	if (rw == KSTAT_WRITE)
1553 		return (EACCES);
1554 	if (ksp == NULL || ksp->ks_private == NULL)
1555 		return (EIO);
1556 	cm_entry  = (struct cm_xprt *)ksp->ks_private;
1557 	cm_ksp_data = (struct cm_kstat_xprt *)ksp->ks_data;
1558 
1559 	cm_ksp_data->x_wq.value.ui32 = (uint32_t)(uintptr_t)cm_entry->x_wq;
1560 	cm_ksp_data->x_family.value.ui32 = cm_entry->x_family;
1561 	cm_ksp_data->x_rdev.value.ui32 = (uint32_t)cm_entry->x_rdev;
1562 	cm_ksp_data->x_time.value.ui32 = cm_entry->x_time;
1563 	cm_ksp_data->x_ref.value.ui32 = cm_entry->x_ref;
1564 	cm_ksp_data->x_state.value.ui32 = cm_entry->x_state_flags;
1565 
1566 	if (cm_entry->x_server.buf) {
1567 		fbuf = cm_ksp_data->x_server.value.str.addr.ptr;
1568 		if (cm_entry->x_family == AF_INET &&
1569 		    cm_entry->x_server.len ==
1570 		    sizeof (struct sockaddr_in)) {
1571 			struct sockaddr_in  *sa;
1572 			sa = (struct sockaddr_in *)
1573 				cm_entry->x_server.buf;
1574 			b = (uchar_t *)&sa->sin_addr;
1575 			(void) sprintf(fbuf,
1576 			    "%03d.%03d.%03d.%03d", b[0] & 0xFF, b[1] & 0xFF,
1577 			    b[2] & 0xFF, b[3] & 0xFF);
1578 			cm_ksp_data->x_port.value.ui32 =
1579 				(uint32_t)sa->sin_port;
1580 		} else if (cm_entry->x_family == AF_INET6 &&
1581 				cm_entry->x_server.len >=
1582 				sizeof (struct sockaddr_in6)) {
1583 			/* extract server IP address & port */
1584 			struct sockaddr_in6 *sin6;
1585 			sin6 = (struct sockaddr_in6 *)cm_entry->x_server.buf;
1586 			(void) kinet_ntop6((uchar_t *)&sin6->sin6_addr, fbuf,
1587 				INET6_ADDRSTRLEN);
1588 			cm_ksp_data->x_port.value.ui32 = sin6->sin6_port;
1589 		} else {
1590 			struct sockaddr_in  *sa;
1591 
1592 			sa = (struct sockaddr_in *)cm_entry->x_server.buf;
1593 			b = (uchar_t *)&sa->sin_addr;
1594 			(void) sprintf(fbuf,
1595 			    "%03d.%03d.%03d.%03d", b[0] & 0xFF, b[1] & 0xFF,
1596 			    b[2] & 0xFF, b[3] & 0xFF);
1597 		}
1598 		KSTAT_NAMED_STR_BUFLEN(&cm_ksp_data->x_server) =
1599 			strlen(fbuf) + 1;
1600 	}
1601 
1602 	return (0);
1603 }
1604 
1605 
1606 /*
1607  * We want a version of delay which is interruptible by a UNIX signal
1608  * Return EINTR if an interrupt occured.
1609  */
1610 static int
1611 clnt_delay(clock_t ticks, bool_t nosignal)
1612 {
1613 	if (nosignal == TRUE) {
1614 		delay(ticks);
1615 		return (0);
1616 	}
1617 	return (delay_sig(ticks));
1618 }
1619 
1620 /*
1621  * Wait for a connection until a timeout, or until we are
1622  * signalled that there has been a connection state change.
1623  */
1624 static enum clnt_stat
1625 connmgr_cwait(struct cm_xprt *cm_entry, const struct timeval *waitp,
1626 	bool_t nosignal)
1627 {
1628 	bool_t interrupted;
1629 	clock_t timout, cv_stat;
1630 	enum clnt_stat clstat;
1631 	unsigned int old_state;
1632 
1633 	ASSERT(MUTEX_HELD(&connmgr_lock));
1634 	/*
1635 	 * We wait for the transport connection to be made, or an
1636 	 * indication that it could not be made.
1637 	 */
1638 	clstat = RPC_TIMEDOUT;
1639 	interrupted = FALSE;
1640 
1641 	old_state = cm_entry->x_state_flags;
1642 	/*
1643 	 * Now loop until cv_timedwait{_sig} returns because of
1644 	 * a signal(0) or timeout(-1) or cv_signal(>0). But it may be
1645 	 * cv_signalled for various other reasons too. So loop
1646 	 * until there is a state change on the connection.
1647 	 */
1648 
1649 	timout = waitp->tv_sec * drv_usectohz(1000000) +
1650 	    drv_usectohz(waitp->tv_usec) + lbolt;
1651 
1652 	if (nosignal) {
1653 		while ((cv_stat = cv_timedwait(&cm_entry->x_conn_cv,
1654 		    &connmgr_lock, timout)) > 0 &&
1655 		    cm_entry->x_state_flags == old_state)
1656 			;
1657 	} else {
1658 		while ((cv_stat = cv_timedwait_sig(&cm_entry->x_conn_cv,
1659 		    &connmgr_lock, timout)) > 0 &&
1660 		    cm_entry->x_state_flags == old_state)
1661 			;
1662 
1663 		if (cv_stat == 0) /* got intr signal? */
1664 			interrupted = TRUE;
1665 	}
1666 
1667 	if ((cm_entry->x_state_flags & (X_BADSTATES|X_CONNECTED)) ==
1668 	    X_CONNECTED) {
1669 		clstat = RPC_SUCCESS;
1670 	} else {
1671 		if (interrupted == TRUE)
1672 			clstat = RPC_INTR;
1673 		RPCLOG(1, "connmgr_cwait: can't connect, error: %s\n",
1674 		    clnt_sperrno(clstat));
1675 	}
1676 
1677 	return (clstat);
1678 }
1679 
1680 /*
1681  * Primary interface for how RPC grabs a connection.
1682  */
1683 static struct cm_xprt *
1684 connmgr_wrapget(
1685 	struct netbuf *retryaddr,
1686 	const struct timeval *waitp,
1687 	cku_private_t *p)
1688 {
1689 	struct cm_xprt *cm_entry;
1690 
1691 	cm_entry = connmgr_get(retryaddr, waitp, &p->cku_addr, p->cku_addrfmly,
1692 	    &p->cku_srcaddr, &p->cku_err, p->cku_device,
1693 	    p->cku_client.cl_nosignal, p->cku_useresvport);
1694 
1695 	if (cm_entry == NULL) {
1696 		/*
1697 		 * Re-map the call status to RPC_INTR if the err code is
1698 		 * EINTR. This can happen if calls status is RPC_TLIERROR.
1699 		 * However, don't re-map if signalling has been turned off.
1700 		 * XXX Really need to create a separate thread whenever
1701 		 * there isn't an existing connection.
1702 		 */
1703 		if (p->cku_err.re_errno == EINTR) {
1704 			if (p->cku_client.cl_nosignal == TRUE)
1705 				p->cku_err.re_errno = EIO;
1706 			else
1707 				p->cku_err.re_status = RPC_INTR;
1708 		}
1709 	}
1710 
1711 	return (cm_entry);
1712 }
1713 
1714 /*
1715  * Obtains a transport to the server specified in addr.  If a suitable transport
1716  * does not already exist in the list of cached transports, a new connection
1717  * is created, connected, and added to the list. The connection is for sending
1718  * only - the reply message may come back on another transport connection.
1719  */
1720 static struct cm_xprt *
1721 connmgr_get(
1722 	struct netbuf	*retryaddr,
1723 	const struct timeval	*waitp,	/* changed to a ptr to converse stack */
1724 	struct netbuf	*destaddr,
1725 	int		addrfmly,
1726 	struct netbuf	*srcaddr,
1727 	struct rpc_err	*rpcerr,
1728 	dev_t		device,
1729 	bool_t		nosignal,
1730 	int		useresvport)
1731 {
1732 	struct cm_xprt *cm_entry;
1733 	struct cm_xprt *lru_entry;
1734 	struct cm_xprt **cmp;
1735 	queue_t *wq;
1736 	TIUSER *tiptr;
1737 	int i;
1738 	int retval;
1739 	clock_t prev_time;
1740 	int tidu_size;
1741 	bool_t	connected;
1742 	zoneid_t zoneid = getzoneid();
1743 
1744 	/*
1745 	 * If the call is not a retry, look for a transport entry that
1746 	 * goes to the server of interest.
1747 	 */
1748 	mutex_enter(&connmgr_lock);
1749 
1750 	if (retryaddr == NULL) {
1751 use_new_conn:
1752 		i = 0;
1753 		cm_entry = lru_entry = NULL;
1754 		prev_time = lbolt;
1755 
1756 		cmp = &cm_hd;
1757 		while ((cm_entry = *cmp) != NULL) {
1758 			ASSERT(cm_entry != cm_entry->x_next);
1759 			/*
1760 			 * Garbage collect conections that are marked
1761 			 * for needs disconnect.
1762 			 */
1763 			if (cm_entry->x_needdis) {
1764 				CONN_HOLD(cm_entry);
1765 				connmgr_dis_and_wait(cm_entry);
1766 				connmgr_release(cm_entry);
1767 				/*
1768 				 * connmgr_lock could have been
1769 				 * dropped for the disconnect
1770 				 * processing so start over.
1771 				 */
1772 				goto use_new_conn;
1773 			}
1774 
1775 			/*
1776 			 * Garbage collect the dead connections that have
1777 			 * no threads working on them.
1778 			 */
1779 			if ((cm_entry->x_state_flags & (X_DEAD|X_THREAD)) ==
1780 			    X_DEAD) {
1781 				*cmp = cm_entry->x_next;
1782 				mutex_exit(&connmgr_lock);
1783 				connmgr_close(cm_entry);
1784 				mutex_enter(&connmgr_lock);
1785 				goto use_new_conn;
1786 			}
1787 
1788 
1789 			if ((cm_entry->x_state_flags & X_BADSTATES) == 0 &&
1790 			    cm_entry->x_zoneid == zoneid &&
1791 			    cm_entry->x_rdev == device &&
1792 			    destaddr->len == cm_entry->x_server.len &&
1793 			    bcmp(destaddr->buf, cm_entry->x_server.buf,
1794 			    destaddr->len) == 0) {
1795 				/*
1796 				 * If the matching entry isn't connected,
1797 				 * attempt to reconnect it.
1798 				 */
1799 				if (cm_entry->x_connected == FALSE) {
1800 					/*
1801 					 * We don't go through trying
1802 					 * to find the least recently
1803 					 * used connected because
1804 					 * connmgr_reconnect() briefly
1805 					 * dropped the connmgr_lock,
1806 					 * allowing a window for our
1807 					 * accounting to be messed up.
1808 					 * In any case, a re-connected
1809 					 * connection is as good as
1810 					 * a LRU connection.
1811 					 */
1812 					return (connmgr_wrapconnect(cm_entry,
1813 					    waitp, destaddr, addrfmly, srcaddr,
1814 					    rpcerr, TRUE, nosignal));
1815 				}
1816 				i++;
1817 				if (cm_entry->x_time - prev_time <= 0 ||
1818 				    lru_entry == NULL) {
1819 					prev_time = cm_entry->x_time;
1820 					lru_entry = cm_entry;
1821 				}
1822 			}
1823 			cmp = &cm_entry->x_next;
1824 		}
1825 
1826 		if (i > clnt_max_conns) {
1827 			RPCLOG(8, "connmgr_get: too many conns, dooming entry"
1828 			    " %p\n", (void *)lru_entry->x_tiptr);
1829 			lru_entry->x_doomed = TRUE;
1830 			goto use_new_conn;
1831 		}
1832 
1833 		/*
1834 		 * If we are at the maximum number of connections to
1835 		 * the server, hand back the least recently used one.
1836 		 */
1837 		if (i == clnt_max_conns) {
1838 			/*
1839 			 * Copy into the handle the source address of
1840 			 * the connection, which we will use in case of
1841 			 * a later retry.
1842 			 */
1843 			if (srcaddr->len != lru_entry->x_src.len) {
1844 				if (srcaddr->len > 0)
1845 					kmem_free(srcaddr->buf,
1846 					    srcaddr->maxlen);
1847 				srcaddr->buf = kmem_zalloc(
1848 				    lru_entry->x_src.len, KM_SLEEP);
1849 				srcaddr->maxlen = srcaddr->len =
1850 				    lru_entry->x_src.len;
1851 			}
1852 			bcopy(lru_entry->x_src.buf, srcaddr->buf, srcaddr->len);
1853 			RPCLOG(2, "connmgr_get: call going out on %p\n",
1854 			    (void *)lru_entry);
1855 			lru_entry->x_time = lbolt;
1856 			CONN_HOLD(lru_entry);
1857 			mutex_exit(&connmgr_lock);
1858 			return (lru_entry);
1859 		}
1860 
1861 	} else {
1862 		/*
1863 		 * This is the retry case (retryaddr != NULL).  Retries must
1864 		 * be sent on the same source port as the original call.
1865 		 */
1866 
1867 		/*
1868 		 * Walk the list looking for a connection with a source address
1869 		 * that matches the retry address.
1870 		 */
1871 		cmp = &cm_hd;
1872 		while ((cm_entry = *cmp) != NULL) {
1873 			ASSERT(cm_entry != cm_entry->x_next);
1874 			if (zoneid != cm_entry->x_zoneid ||
1875 			    device != cm_entry->x_rdev ||
1876 			    retryaddr->len != cm_entry->x_src.len ||
1877 			    bcmp(retryaddr->buf, cm_entry->x_src.buf,
1878 				    retryaddr->len) != 0) {
1879 				cmp = &cm_entry->x_next;
1880 				continue;
1881 			}
1882 
1883 			/*
1884 			 * Sanity check: if the connection with our source
1885 			 * port is going to some other server, something went
1886 			 * wrong, as we never delete connections (i.e. release
1887 			 * ports) unless they have been idle.  In this case,
1888 			 * it is probably better to send the call out using
1889 			 * a new source address than to fail it altogether,
1890 			 * since that port may never be released.
1891 			 */
1892 			if (destaddr->len != cm_entry->x_server.len ||
1893 				bcmp(destaddr->buf, cm_entry->x_server.buf,
1894 					destaddr->len) != 0) {
1895 				RPCLOG(1, "connmgr_get: tiptr %p"
1896 				    " is going to a different server"
1897 				    " with the port that belongs"
1898 				    " to us!\n", (void *)cm_entry->x_tiptr);
1899 				retryaddr = NULL;
1900 				goto use_new_conn;
1901 			}
1902 
1903 			/*
1904 			 * If the connection of interest is not connected and we
1905 			 * can't reconnect it, then the server is probably
1906 			 * still down.  Return NULL to the caller and let it
1907 			 * retry later if it wants to.  We have a delay so the
1908 			 * machine doesn't go into a tight retry loop.  If the
1909 			 * entry was already connected, or the reconnected was
1910 			 * successful, return this entry.
1911 			 */
1912 			if (cm_entry->x_connected == FALSE) {
1913 				return (connmgr_wrapconnect(cm_entry,
1914 				    waitp, destaddr, addrfmly, NULL,
1915 				    rpcerr, TRUE, nosignal));
1916 			} else {
1917 				CONN_HOLD(cm_entry);
1918 
1919 				cm_entry->x_time = lbolt;
1920 				mutex_exit(&connmgr_lock);
1921 				RPCLOG(2, "connmgr_get: found old "
1922 				    "transport %p for retry\n",
1923 				    (void *)cm_entry);
1924 				return (cm_entry);
1925 			}
1926 		}
1927 
1928 		/*
1929 		 * We cannot find an entry in the list for this retry.
1930 		 * Either the entry has been removed temporarily to be
1931 		 * reconnected by another thread, or the original call
1932 		 * got a port but never got connected,
1933 		 * and hence the transport never got put in the
1934 		 * list.  Fall through to the "create new connection" code -
1935 		 * the former case will fail there trying to rebind the port,
1936 		 * and the later case (and any other pathological cases) will
1937 		 * rebind and reconnect and not hang the client machine.
1938 		 */
1939 		RPCLOG0(8, "connmgr_get: no entry in list for retry\n");
1940 	}
1941 	/*
1942 	 * Set up a transport entry in the connection manager's list.
1943 	 */
1944 	cm_entry = (struct cm_xprt *)
1945 	    kmem_zalloc(sizeof (struct cm_xprt), KM_SLEEP);
1946 
1947 	cm_entry->x_server.buf = kmem_zalloc(destaddr->len, KM_SLEEP);
1948 	bcopy(destaddr->buf, cm_entry->x_server.buf, destaddr->len);
1949 	cm_entry->x_server.len = cm_entry->x_server.maxlen = destaddr->len;
1950 
1951 	cm_entry->x_state_flags = X_THREAD;
1952 	cm_entry->x_ref = 1;
1953 	cm_entry->x_family = addrfmly;
1954 	cm_entry->x_rdev = device;
1955 	cm_entry->x_zoneid = zoneid;
1956 	mutex_init(&cm_entry->x_lock, NULL, MUTEX_DEFAULT, NULL);
1957 	cv_init(&cm_entry->x_cv, NULL, CV_DEFAULT, NULL);
1958 	cv_init(&cm_entry->x_conn_cv, NULL, CV_DEFAULT, NULL);
1959 	cv_init(&cm_entry->x_dis_cv, NULL, CV_DEFAULT, NULL);
1960 
1961 	/*
1962 	 * Note that we add this partially initialized entry to the
1963 	 * connection list. This is so that we don't have connections to
1964 	 * the same server.
1965 	 *
1966 	 * Note that x_src is not initialized at this point. This is because
1967 	 * retryaddr might be NULL in which case x_src is whatever
1968 	 * t_kbind/bindresvport gives us. If another thread wants a
1969 	 * connection to the same server, seemingly we have an issue, but we
1970 	 * don't. If the other thread comes in with retryaddr == NULL, then it
1971 	 * will never look at x_src, and it will end up waiting in
1972 	 * connmgr_cwait() for the first thread to finish the connection
1973 	 * attempt. If the other thread comes in with retryaddr != NULL, then
1974 	 * that means there was a request sent on a connection, in which case
1975 	 * the the connection should already exist. Thus the first thread
1976 	 * never gets here ... it finds the connection it its server in the
1977 	 * connection list.
1978 	 *
1979 	 * But even if theory is wrong, in the retryaddr != NULL case, the 2nd
1980 	 * thread will skip us because x_src.len == 0.
1981 	 */
1982 	cm_entry->x_next = cm_hd;
1983 	cm_hd = cm_entry;
1984 	mutex_exit(&connmgr_lock);
1985 
1986 	/*
1987 	 * Either we didn't find an entry to the server of interest, or we
1988 	 * don't have the maximum number of connections to that server -
1989 	 * create a new connection.
1990 	 */
1991 	RPCLOG0(8, "connmgr_get: creating new connection\n");
1992 	rpcerr->re_status = RPC_TLIERROR;
1993 
1994 	i = t_kopen(NULL, device, FREAD|FWRITE|FNDELAY, &tiptr, kcred);
1995 	if (i) {
1996 		RPCLOG(1, "connmgr_get: can't open cots device, error %d\n", i);
1997 		rpcerr->re_errno = i;
1998 		connmgr_cancelconn(cm_entry);
1999 		return (NULL);
2000 	}
2001 	rpc_poptimod(tiptr->fp->f_vnode);
2002 
2003 	if (i = strioctl(tiptr->fp->f_vnode, I_PUSH, (intptr_t)"rpcmod", 0,
2004 			K_TO_K, kcred, &retval)) {
2005 		RPCLOG(1, "connmgr_get: can't push cots module, %d\n", i);
2006 		(void) t_kclose(tiptr, 1);
2007 		rpcerr->re_errno = i;
2008 		connmgr_cancelconn(cm_entry);
2009 		return (NULL);
2010 	}
2011 
2012 	if (i = strioctl(tiptr->fp->f_vnode, RPC_CLIENT, 0, 0, K_TO_K,
2013 		kcred, &retval)) {
2014 		RPCLOG(1, "connmgr_get: can't set client status with cots "
2015 		    "module, %d\n", i);
2016 		(void) t_kclose(tiptr, 1);
2017 		rpcerr->re_errno = i;
2018 		connmgr_cancelconn(cm_entry);
2019 		return (NULL);
2020 	}
2021 
2022 	mutex_enter(&connmgr_lock);
2023 
2024 	wq = tiptr->fp->f_vnode->v_stream->sd_wrq->q_next;
2025 	cm_entry->x_wq = wq;
2026 
2027 	mutex_exit(&connmgr_lock);
2028 
2029 	if (i = strioctl(tiptr->fp->f_vnode, I_PUSH, (intptr_t)"timod", 0,
2030 			K_TO_K, kcred, &retval)) {
2031 		RPCLOG(1, "connmgr_get: can't push timod, %d\n", i);
2032 		(void) t_kclose(tiptr, 1);
2033 		rpcerr->re_errno = i;
2034 		connmgr_cancelconn(cm_entry);
2035 		return (NULL);
2036 	}
2037 
2038 	/*
2039 	 * If the caller has not specified reserved port usage then
2040 	 * take the system default.
2041 	 */
2042 	if (useresvport == -1)
2043 		useresvport = clnt_cots_do_bindresvport;
2044 
2045 	if ((useresvport || retryaddr != NULL) &&
2046 	    (addrfmly == AF_INET || addrfmly == AF_INET6)) {
2047 		bool_t alloc_src = FALSE;
2048 
2049 		if (srcaddr->len != destaddr->len) {
2050 			kmem_free(srcaddr->buf, srcaddr->maxlen);
2051 			srcaddr->buf = kmem_zalloc(destaddr->len, KM_SLEEP);
2052 			srcaddr->maxlen = destaddr->len;
2053 			srcaddr->len = destaddr->len;
2054 			alloc_src = TRUE;
2055 		}
2056 
2057 		if ((i = bindresvport(tiptr, retryaddr, srcaddr, TRUE)) != 0) {
2058 			(void) t_kclose(tiptr, 1);
2059 			RPCLOG(1, "connmgr_get: couldn't bind, retryaddr: "
2060 				"%p\n", (void *)retryaddr);
2061 
2062 			/*
2063 			 * 1225408: If we allocated a source address, then it
2064 			 * is either garbage or all zeroes. In that case
2065 			 * we need to clear srcaddr.
2066 			 */
2067 			if (alloc_src == TRUE) {
2068 				kmem_free(srcaddr->buf, srcaddr->maxlen);
2069 				srcaddr->maxlen = srcaddr->len = 0;
2070 				srcaddr->buf = NULL;
2071 			}
2072 			rpcerr->re_errno = i;
2073 			connmgr_cancelconn(cm_entry);
2074 			return (NULL);
2075 		}
2076 	} else {
2077 		if ((i = t_kbind(tiptr, NULL, NULL)) != 0) {
2078 			RPCLOG(1, "clnt_cots_kcreate: t_kbind: %d\n", i);
2079 			(void) t_kclose(tiptr, 1);
2080 			rpcerr->re_errno = i;
2081 			connmgr_cancelconn(cm_entry);
2082 			return (NULL);
2083 		}
2084 	}
2085 
2086 	{
2087 		/*
2088 		 * Keep the kernel stack lean. Don't move this call
2089 		 * declaration to the top of this function because a
2090 		 * call is declared in connmgr_wrapconnect()
2091 		 */
2092 		calllist_t call;
2093 
2094 		bzero(&call, sizeof (call));
2095 		cv_init(&call.call_cv, NULL, CV_DEFAULT, NULL);
2096 
2097 		/*
2098 		 * This is a bound end-point so don't close it's stream.
2099 		 */
2100 		connected = connmgr_connect(cm_entry, wq, destaddr, addrfmly,
2101 						&call, &tidu_size, FALSE, waitp,
2102 						nosignal);
2103 		*rpcerr = call.call_err;
2104 		cv_destroy(&call.call_cv);
2105 
2106 	}
2107 
2108 	mutex_enter(&connmgr_lock);
2109 
2110 	/*
2111 	 * Set up a transport entry in the connection manager's list.
2112 	 */
2113 	cm_entry->x_src.buf = kmem_zalloc(srcaddr->len, KM_SLEEP);
2114 	bcopy(srcaddr->buf, cm_entry->x_src.buf, srcaddr->len);
2115 	cm_entry->x_src.len = cm_entry->x_src.maxlen = srcaddr->len;
2116 
2117 	cm_entry->x_tiptr = tiptr;
2118 	cm_entry->x_time = lbolt;
2119 
2120 	if (tiptr->tp_info.servtype == T_COTS_ORD)
2121 		cm_entry->x_ordrel = TRUE;
2122 	else
2123 		cm_entry->x_ordrel = FALSE;
2124 
2125 	cm_entry->x_tidu_size = tidu_size;
2126 
2127 	if (cm_entry->x_early_disc)
2128 		cm_entry->x_connected = FALSE;
2129 	else
2130 		cm_entry->x_connected = connected;
2131 
2132 	/*
2133 	 * There could be a discrepancy here such that
2134 	 * x_early_disc is TRUE yet connected is TRUE as well
2135 	 * and the connection is actually connected. In that case
2136 	 * lets be conservative and declare the connection as not
2137 	 * connected.
2138 	 */
2139 	cm_entry->x_early_disc = FALSE;
2140 	cm_entry->x_needdis = (cm_entry->x_connected == FALSE);
2141 	cm_entry->x_ctime = lbolt;
2142 
2143 	/*
2144 	 * Notify any threads waiting that the connection attempt is done.
2145 	 */
2146 	cm_entry->x_thread = FALSE;
2147 	cv_broadcast(&cm_entry->x_conn_cv);
2148 
2149 	mutex_exit(&connmgr_lock);
2150 
2151 	if (cm_entry->x_connected == FALSE) {
2152 		connmgr_release(cm_entry);
2153 		return (NULL);
2154 	}
2155 	return (cm_entry);
2156 }
2157 
2158 /*
2159  * Keep the cm_xprt entry on the connecton list when making a connection. This
2160  * is to prevent multiple connections to a slow server from appearing.
2161  * We use the bit field x_thread to tell if a thread is doing a connection
2162  * which keeps other interested threads from messing with connection.
2163  * Those other threads just wait if x_thread is set.
2164  *
2165  * If x_thread is not set, then we do the actual work of connecting via
2166  * connmgr_connect().
2167  *
2168  * mutex convention: called with connmgr_lock held, returns with it released.
2169  */
2170 static struct cm_xprt *
2171 connmgr_wrapconnect(
2172 	struct cm_xprt	*cm_entry,
2173 	const struct timeval	*waitp,
2174 	struct netbuf	*destaddr,
2175 	int		addrfmly,
2176 	struct netbuf	*srcaddr,
2177 	struct rpc_err	*rpcerr,
2178 	bool_t		reconnect,
2179 	bool_t		nosignal)
2180 {
2181 	ASSERT(MUTEX_HELD(&connmgr_lock));
2182 	/*
2183 	 * Hold this entry as we are about to drop connmgr_lock.
2184 	 */
2185 	CONN_HOLD(cm_entry);
2186 
2187 	/*
2188 	 * If there is a thread already making a connection for us, then
2189 	 * wait for it to complete the connection.
2190 	 */
2191 	if (cm_entry->x_thread == TRUE) {
2192 		rpcerr->re_status = connmgr_cwait(cm_entry, waitp, nosignal);
2193 
2194 		if (rpcerr->re_status != RPC_SUCCESS) {
2195 			mutex_exit(&connmgr_lock);
2196 			connmgr_release(cm_entry);
2197 			return (NULL);
2198 		}
2199 	} else {
2200 		bool_t connected;
2201 		calllist_t call;
2202 
2203 		cm_entry->x_thread = TRUE;
2204 
2205 		while (cm_entry->x_needrel == TRUE) {
2206 			cm_entry->x_needrel = FALSE;
2207 
2208 			connmgr_sndrel(cm_entry);
2209 			delay(drv_usectohz(1000000));
2210 
2211 			mutex_enter(&connmgr_lock);
2212 		}
2213 
2214 		/*
2215 		 * If we need to send a T_DISCON_REQ, send one.
2216 		 */
2217 		connmgr_dis_and_wait(cm_entry);
2218 
2219 		mutex_exit(&connmgr_lock);
2220 
2221 		bzero(&call, sizeof (call));
2222 		cv_init(&call.call_cv, NULL, CV_DEFAULT, NULL);
2223 
2224 		connected = connmgr_connect(cm_entry, cm_entry->x_wq,
2225 					    destaddr, addrfmly, &call,
2226 					    &cm_entry->x_tidu_size,
2227 					    reconnect, waitp, nosignal);
2228 
2229 		*rpcerr = call.call_err;
2230 		cv_destroy(&call.call_cv);
2231 
2232 		mutex_enter(&connmgr_lock);
2233 
2234 
2235 		if (cm_entry->x_early_disc)
2236 			cm_entry->x_connected = FALSE;
2237 		else
2238 			cm_entry->x_connected = connected;
2239 
2240 		/*
2241 		 * There could be a discrepancy here such that
2242 		 * x_early_disc is TRUE yet connected is TRUE as well
2243 		 * and the connection is actually connected. In that case
2244 		 * lets be conservative and declare the connection as not
2245 		 * connected.
2246 		 */
2247 
2248 		cm_entry->x_early_disc = FALSE;
2249 		cm_entry->x_needdis = (cm_entry->x_connected == FALSE);
2250 
2251 
2252 		/*
2253 		 * connmgr_connect() may have given up before the connection
2254 		 * actually timed out. So ensure that before the next
2255 		 * connection attempt we do a disconnect.
2256 		 */
2257 		cm_entry->x_ctime = lbolt;
2258 		cm_entry->x_thread = FALSE;
2259 
2260 		cv_broadcast(&cm_entry->x_conn_cv);
2261 
2262 		if (cm_entry->x_connected == FALSE) {
2263 			mutex_exit(&connmgr_lock);
2264 			connmgr_release(cm_entry);
2265 			return (NULL);
2266 		}
2267 	}
2268 
2269 	if (srcaddr != NULL) {
2270 		/*
2271 		 * Copy into the handle the
2272 		 * source address of the
2273 		 * connection, which we will use
2274 		 * in case of a later retry.
2275 		 */
2276 		if (srcaddr->len != cm_entry->x_src.len) {
2277 			if (srcaddr->maxlen > 0)
2278 				kmem_free(srcaddr->buf, srcaddr->maxlen);
2279 			srcaddr->buf = kmem_zalloc(cm_entry->x_src.len,
2280 			    KM_SLEEP);
2281 			srcaddr->maxlen = srcaddr->len =
2282 			    cm_entry->x_src.len;
2283 		}
2284 		bcopy(cm_entry->x_src.buf, srcaddr->buf, srcaddr->len);
2285 	}
2286 	cm_entry->x_time = lbolt;
2287 	mutex_exit(&connmgr_lock);
2288 	return (cm_entry);
2289 }
2290 
2291 /*
2292  * If we need to send a T_DISCON_REQ, send one.
2293  */
2294 static void
2295 connmgr_dis_and_wait(struct cm_xprt *cm_entry)
2296 {
2297 	ASSERT(MUTEX_HELD(&connmgr_lock));
2298 	for (;;) {
2299 		while (cm_entry->x_needdis == TRUE) {
2300 			RPCLOG(8, "connmgr_dis_and_wait: need "
2301 				"T_DISCON_REQ for connection 0x%p\n",
2302 				(void *)cm_entry);
2303 			cm_entry->x_needdis = FALSE;
2304 			cm_entry->x_waitdis = TRUE;
2305 
2306 			connmgr_snddis(cm_entry);
2307 
2308 			mutex_enter(&connmgr_lock);
2309 		}
2310 
2311 		if (cm_entry->x_waitdis == TRUE) {
2312 			clock_t curlbolt;
2313 			clock_t timout;
2314 
2315 			RPCLOG(8, "connmgr_dis_and_wait waiting for "
2316 				"T_DISCON_REQ's ACK for connection %p\n",
2317 				(void *)cm_entry);
2318 			curlbolt = ddi_get_lbolt();
2319 
2320 			timout = clnt_cots_min_conntout *
2321 				drv_usectohz(1000000) + curlbolt;
2322 
2323 			/*
2324 			 * The TPI spec says that the T_DISCON_REQ
2325 			 * will get acknowledged, but in practice
2326 			 * the ACK may never get sent. So don't
2327 			 * block forever.
2328 			 */
2329 			(void) cv_timedwait(&cm_entry->x_dis_cv,
2330 					    &connmgr_lock, timout);
2331 		}
2332 		/*
2333 		 * If we got the ACK, break. If we didn't,
2334 		 * then send another T_DISCON_REQ.
2335 		 */
2336 		if (cm_entry->x_waitdis == FALSE) {
2337 			break;
2338 		} else {
2339 			RPCLOG(8, "connmgr_dis_and_wait: did"
2340 				"not get T_DISCON_REQ's ACK for "
2341 				"connection  %p\n", (void *)cm_entry);
2342 			cm_entry->x_needdis = TRUE;
2343 		}
2344 	}
2345 }
2346 
2347 static void
2348 connmgr_cancelconn(struct cm_xprt *cm_entry)
2349 {
2350 	/*
2351 	 * Mark the connection table entry as dead; the next thread that
2352 	 * goes through connmgr_release() will notice this and deal with it.
2353 	 */
2354 	mutex_enter(&connmgr_lock);
2355 	cm_entry->x_dead = TRUE;
2356 
2357 	/*
2358 	 * Notify any threads waiting for the connection that it isn't
2359 	 * going to happen.
2360 	 */
2361 	cm_entry->x_thread = FALSE;
2362 	cv_broadcast(&cm_entry->x_conn_cv);
2363 	mutex_exit(&connmgr_lock);
2364 
2365 	connmgr_release(cm_entry);
2366 }
2367 
2368 static void
2369 connmgr_close(struct cm_xprt *cm_entry)
2370 {
2371 	mutex_enter(&cm_entry->x_lock);
2372 	while (cm_entry->x_ref != 0) {
2373 		/*
2374 		 * Must be a noninterruptible wait.
2375 		 */
2376 		cv_wait(&cm_entry->x_cv, &cm_entry->x_lock);
2377 	}
2378 
2379 	if (cm_entry->x_tiptr != NULL)
2380 		(void) t_kclose(cm_entry->x_tiptr, 1);
2381 
2382 	mutex_exit(&cm_entry->x_lock);
2383 	if (cm_entry->x_ksp != NULL) {
2384 		mutex_enter(&connmgr_lock);
2385 		cm_entry->x_ksp->ks_private = NULL;
2386 		mutex_exit(&connmgr_lock);
2387 
2388 		/*
2389 		 * Must free the buffer we allocated for the
2390 		 * server address in the update function
2391 		 */
2392 		if (((struct cm_kstat_xprt *)(cm_entry->x_ksp->ks_data))->
2393 		    x_server.value.str.addr.ptr != NULL)
2394 			kmem_free(((struct cm_kstat_xprt *)(cm_entry->x_ksp->
2395 			    ks_data))->x_server.value.str.addr.ptr,
2396 				    INET6_ADDRSTRLEN);
2397 		kmem_free(cm_entry->x_ksp->ks_data,
2398 			    cm_entry->x_ksp->ks_data_size);
2399 		kstat_delete(cm_entry->x_ksp);
2400 	}
2401 
2402 	mutex_destroy(&cm_entry->x_lock);
2403 	cv_destroy(&cm_entry->x_cv);
2404 	cv_destroy(&cm_entry->x_conn_cv);
2405 	cv_destroy(&cm_entry->x_dis_cv);
2406 
2407 	if (cm_entry->x_server.buf != NULL)
2408 		kmem_free(cm_entry->x_server.buf, cm_entry->x_server.maxlen);
2409 	if (cm_entry->x_src.buf != NULL)
2410 		kmem_free(cm_entry->x_src.buf, cm_entry->x_src.maxlen);
2411 	kmem_free(cm_entry, sizeof (struct cm_xprt));
2412 }
2413 
2414 /*
2415  * Called by KRPC after sending the call message to release the connection
2416  * it was using.
2417  */
2418 static void
2419 connmgr_release(struct cm_xprt *cm_entry)
2420 {
2421 	mutex_enter(&cm_entry->x_lock);
2422 	cm_entry->x_ref--;
2423 	if (cm_entry->x_ref == 0)
2424 		cv_signal(&cm_entry->x_cv);
2425 	mutex_exit(&cm_entry->x_lock);
2426 }
2427 
2428 /*
2429  * Given an open stream, connect to the remote.  Returns true if connected,
2430  * false otherwise.
2431  */
2432 static bool_t
2433 connmgr_connect(
2434 	struct cm_xprt		*cm_entry,
2435 	queue_t			*wq,
2436 	struct netbuf		*addr,
2437 	int			addrfmly,
2438 	calllist_t 		*e,
2439 	int 			*tidu_ptr,
2440 	bool_t 			reconnect,
2441 	const struct timeval 	*waitp,
2442 	bool_t 			nosignal)
2443 {
2444 	mblk_t *mp;
2445 	struct T_conn_req *tcr;
2446 	struct T_info_ack *tinfo;
2447 	int interrupted, error;
2448 	int tidu_size, kstat_instance;
2449 
2450 	/* if it's a reconnect, flush any lingering data messages */
2451 	if (reconnect)
2452 		(void) putctl1(wq, M_FLUSH, FLUSHRW);
2453 
2454 	mp = allocb(sizeof (*tcr) + addr->len, BPRI_LO);
2455 	if (mp == NULL) {
2456 		/*
2457 		 * This is unfortunate, but we need to look up the stats for
2458 		 * this zone to increment the "memory allocation failed"
2459 		 * counter.  curproc->p_zone is safe since we're initiating a
2460 		 * connection and not in some strange streams context.
2461 		 */
2462 		struct rpcstat *rpcstat;
2463 
2464 		rpcstat = zone_getspecific(rpcstat_zone_key, curproc->p_zone);
2465 		ASSERT(rpcstat != NULL);
2466 
2467 		RPCLOG0(1, "connmgr_connect: cannot alloc mp for "
2468 		    "sending conn request\n");
2469 		COTSRCSTAT_INCR(rpcstat->rpc_cots_client, rcnomem);
2470 		e->call_status = RPC_SYSTEMERROR;
2471 		e->call_reason = ENOSR;
2472 		return (FALSE);
2473 	}
2474 
2475 	mp->b_datap->db_type = M_PROTO;
2476 	tcr = (struct T_conn_req *)mp->b_rptr;
2477 	bzero(tcr, sizeof (*tcr));
2478 	tcr->PRIM_type = T_CONN_REQ;
2479 	tcr->DEST_length = addr->len;
2480 	tcr->DEST_offset = sizeof (struct T_conn_req);
2481 	mp->b_wptr = mp->b_rptr + sizeof (*tcr);
2482 
2483 	bcopy(addr->buf, mp->b_wptr, tcr->DEST_length);
2484 	mp->b_wptr += tcr->DEST_length;
2485 
2486 	RPCLOG(8, "connmgr_connect: sending conn request on queue "
2487 	    "%p", (void *)wq);
2488 	RPCLOG(8, " call %p\n", (void *)wq);
2489 	/*
2490 	 * We use the entry in the handle that is normally used for
2491 	 * waiting for RPC replies to wait for the connection accept.
2492 	 */
2493 	clnt_dispatch_send(wq, mp, e, 0, 0);
2494 
2495 	mutex_enter(&clnt_pending_lock);
2496 
2497 	/*
2498 	 * We wait for the transport connection to be made, or an
2499 	 * indication that it could not be made.
2500 	 */
2501 	interrupted = 0;
2502 
2503 	/*
2504 	 * waitforack should have been called with T_OK_ACK, but the
2505 	 * present implementation needs to be passed T_INFO_ACK to
2506 	 * work correctly.
2507 	 */
2508 	error = waitforack(e, T_INFO_ACK, waitp, nosignal);
2509 	if (error == EINTR)
2510 		interrupted = 1;
2511 	if (zone_status_get(curproc->p_zone) >= ZONE_IS_EMPTY) {
2512 		/*
2513 		 * No time to lose; we essentially have been signaled to
2514 		 * quit.
2515 		 */
2516 		interrupted = 1;
2517 	}
2518 #ifdef RPCDEBUG
2519 	if (error == ETIME)
2520 		RPCLOG0(8, "connmgr_connect: giving up "
2521 		    "on connection attempt; "
2522 		    "clnt_dispatch notifyconn "
2523 		    "diagnostic 'no one waiting for "
2524 		    "connection' should not be "
2525 		    "unexpected\n");
2526 #endif
2527 	if (e->call_prev)
2528 		e->call_prev->call_next = e->call_next;
2529 	else
2530 		clnt_pending = e->call_next;
2531 	if (e->call_next)
2532 		e->call_next->call_prev = e->call_prev;
2533 	mutex_exit(&clnt_pending_lock);
2534 
2535 	if (e->call_status != RPC_SUCCESS || error != 0) {
2536 		if (interrupted)
2537 			e->call_status = RPC_INTR;
2538 		else if (error == ETIME)
2539 			e->call_status = RPC_TIMEDOUT;
2540 		else if (error == EPROTO)
2541 			e->call_status = RPC_SYSTEMERROR;
2542 
2543 		RPCLOG(8, "connmgr_connect: can't connect, status: "
2544 		    "%s\n", clnt_sperrno(e->call_status));
2545 
2546 		if (e->call_reply) {
2547 			freemsg(e->call_reply);
2548 			e->call_reply = NULL;
2549 		}
2550 
2551 		return (FALSE);
2552 	}
2553 	/*
2554 	 * The result of the "connection accept" is a T_info_ack
2555 	 * in the call_reply field.
2556 	 */
2557 	ASSERT(e->call_reply != NULL);
2558 	mp = e->call_reply;
2559 	e->call_reply = NULL;
2560 	tinfo = (struct T_info_ack *)mp->b_rptr;
2561 
2562 	tidu_size = tinfo->TIDU_size;
2563 	tidu_size -= (tidu_size % BYTES_PER_XDR_UNIT);
2564 	if (tidu_size > COTS_DEFAULT_ALLOCSIZE || (tidu_size <= 0))
2565 		tidu_size = COTS_DEFAULT_ALLOCSIZE;
2566 	*tidu_ptr = tidu_size;
2567 
2568 	freemsg(mp);
2569 
2570 	/*
2571 	 * Set up the pertinent options.  NODELAY is so the transport doesn't
2572 	 * buffer up RPC messages on either end.  This may not be valid for
2573 	 * all transports.  Failure to set this option is not cause to
2574 	 * bail out so we return success anyway.  Note that lack of NODELAY
2575 	 * or some other way to flush the message on both ends will cause
2576 	 * lots of retries and terrible performance.
2577 	 */
2578 	if (addrfmly == AF_INET || addrfmly == AF_INET6) {
2579 		(void) connmgr_setopt(wq, IPPROTO_TCP, TCP_NODELAY, e);
2580 		if (e->call_status == RPC_XPRTFAILED)
2581 			return (FALSE);
2582 	}
2583 
2584 	/*
2585 	 * Since we have a connection, we now need to figure out if
2586 	 * we need to create a kstat. If x_ksp is not NULL then we
2587 	 * are reusing a connection and so we do not need to create
2588 	 * another kstat -- lets just return.
2589 	 */
2590 	if (cm_entry->x_ksp != NULL)
2591 		return (TRUE);
2592 
2593 	/*
2594 	 * We need to increment rpc_kstat_instance atomically to prevent
2595 	 * two kstats being created with the same instance.
2596 	 */
2597 	kstat_instance = atomic_add_32_nv((uint32_t *)&rpc_kstat_instance, 1);
2598 
2599 	if ((cm_entry->x_ksp = kstat_create_zone("unix", kstat_instance,
2600 	    "rpc_cots_connections", "rpc", KSTAT_TYPE_NAMED,
2601 	    (uint_t)(sizeof (cm_kstat_xprt_t) / sizeof (kstat_named_t)),
2602 	    KSTAT_FLAG_VIRTUAL, cm_entry->x_zoneid)) == NULL) {
2603 		return (TRUE);
2604 	    }
2605 
2606 	cm_entry->x_ksp->ks_lock = &connmgr_lock;
2607 	cm_entry->x_ksp->ks_private = cm_entry;
2608 	cm_entry->x_ksp->ks_data_size = ((INET6_ADDRSTRLEN * sizeof (char))
2609 					    + sizeof (cm_kstat_template));
2610 	cm_entry->x_ksp->ks_data = kmem_alloc(cm_entry->x_ksp->ks_data_size,
2611 					    KM_SLEEP);
2612 	bcopy(&cm_kstat_template, cm_entry->x_ksp->ks_data,
2613 	    cm_entry->x_ksp->ks_data_size);
2614 	((struct cm_kstat_xprt *)(cm_entry->x_ksp->ks_data))->
2615 		    x_server.value.str.addr.ptr =
2616 		    kmem_alloc(INET6_ADDRSTRLEN, KM_SLEEP);
2617 
2618 	cm_entry->x_ksp->ks_update = conn_kstat_update;
2619 	kstat_install(cm_entry->x_ksp);
2620 	return (TRUE);
2621 }
2622 
2623 /*
2624  * Called by connmgr_connect to set an option on the new stream.
2625  */
2626 static bool_t
2627 connmgr_setopt(queue_t *wq, int level, int name, calllist_t *e)
2628 {
2629 	mblk_t *mp;
2630 	struct opthdr *opt;
2631 	struct T_optmgmt_req *tor;
2632 	struct timeval waitp;
2633 	int error;
2634 
2635 	mp = allocb(sizeof (struct T_optmgmt_req) + sizeof (struct opthdr) +
2636 	    sizeof (int), BPRI_LO);
2637 	if (mp == NULL) {
2638 		RPCLOG0(1, "connmgr_setopt: cannot alloc mp for option "
2639 		    "request\n");
2640 		return (FALSE);
2641 	}
2642 
2643 	mp->b_datap->db_type = M_PROTO;
2644 	tor = (struct T_optmgmt_req *)(mp->b_rptr);
2645 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
2646 	tor->MGMT_flags = T_NEGOTIATE;
2647 	tor->OPT_length = sizeof (struct opthdr) + sizeof (int);
2648 	tor->OPT_offset = sizeof (struct T_optmgmt_req);
2649 
2650 	opt = (struct opthdr *)(mp->b_rptr + sizeof (struct T_optmgmt_req));
2651 	opt->level = level;
2652 	opt->name = name;
2653 	opt->len = sizeof (int);
2654 	*(int *)((char *)opt + sizeof (*opt)) = 1;
2655 	mp->b_wptr += sizeof (struct T_optmgmt_req) + sizeof (struct opthdr) +
2656 	    sizeof (int);
2657 
2658 	/*
2659 	 * We will use this connection regardless
2660 	 * of whether or not the option is settable.
2661 	 */
2662 	clnt_dispatch_send(wq, mp, e, 0, 0);
2663 	mutex_enter(&clnt_pending_lock);
2664 
2665 	waitp.tv_sec = clnt_cots_min_conntout;
2666 	waitp.tv_usec = 0;
2667 	error = waitforack(e, T_OPTMGMT_ACK, &waitp, 1);
2668 
2669 	if (e->call_prev)
2670 		e->call_prev->call_next = e->call_next;
2671 	else
2672 		clnt_pending = e->call_next;
2673 	if (e->call_next)
2674 		e->call_next->call_prev = e->call_prev;
2675 	mutex_exit(&clnt_pending_lock);
2676 
2677 	if (e->call_reply != NULL) {
2678 		freemsg(e->call_reply);
2679 		e->call_reply = NULL;
2680 	}
2681 
2682 	if (e->call_status != RPC_SUCCESS || error != 0) {
2683 		RPCLOG(1, "connmgr_setopt: can't set option: %d\n", name);
2684 		return (FALSE);
2685 	}
2686 	RPCLOG(8, "connmgr_setopt: successfully set option: %d\n", name);
2687 	return (TRUE);
2688 }
2689 
2690 #ifdef	DEBUG
2691 
2692 /*
2693  * This is a knob to let us force code coverage in allocation failure
2694  * case.
2695  */
2696 static int	connmgr_failsnd;
2697 #define	CONN_SND_ALLOC(Size, Pri)	\
2698 	((connmgr_failsnd-- > 0) ? NULL : allocb(Size, Pri))
2699 
2700 #else
2701 
2702 #define	CONN_SND_ALLOC(Size, Pri)	allocb(Size, Pri)
2703 
2704 #endif
2705 
2706 /*
2707  * Sends an orderly release on the specified queue.
2708  * Entered with connmgr_lock. Exited without connmgr_lock
2709  */
2710 static void
2711 connmgr_sndrel(struct cm_xprt *cm_entry)
2712 {
2713 	struct T_ordrel_req *torr;
2714 	mblk_t *mp;
2715 	queue_t *q = cm_entry->x_wq;
2716 	ASSERT(MUTEX_HELD(&connmgr_lock));
2717 	mp = CONN_SND_ALLOC(sizeof (struct T_ordrel_req), BPRI_LO);
2718 	if (mp == NULL) {
2719 		cm_entry->x_needrel = TRUE;
2720 		mutex_exit(&connmgr_lock);
2721 		RPCLOG(1, "connmgr_sndrel: cannot alloc mp for sending ordrel "
2722 			"to queue %p\n", (void *)q);
2723 		return;
2724 	}
2725 	mutex_exit(&connmgr_lock);
2726 
2727 	mp->b_datap->db_type = M_PROTO;
2728 	torr = (struct T_ordrel_req *)(mp->b_rptr);
2729 	torr->PRIM_type = T_ORDREL_REQ;
2730 	mp->b_wptr = mp->b_rptr + sizeof (struct T_ordrel_req);
2731 
2732 	RPCLOG(8, "connmgr_sndrel: sending ordrel to queue %p\n", (void *)q);
2733 	put(q, mp);
2734 }
2735 
2736 /*
2737  * Sends an disconnect on the specified queue.
2738  * Entered with connmgr_lock. Exited without connmgr_lock
2739  */
2740 static void
2741 connmgr_snddis(struct cm_xprt *cm_entry)
2742 {
2743 	struct T_discon_req *tdis;
2744 	mblk_t *mp;
2745 	queue_t *q = cm_entry->x_wq;
2746 
2747 	ASSERT(MUTEX_HELD(&connmgr_lock));
2748 	mp = CONN_SND_ALLOC(sizeof (*tdis), BPRI_LO);
2749 	if (mp == NULL) {
2750 		cm_entry->x_needdis = TRUE;
2751 		mutex_exit(&connmgr_lock);
2752 		RPCLOG(1, "connmgr_snddis: cannot alloc mp for sending discon "
2753 		    "to queue %p\n", (void *)q);
2754 		return;
2755 	}
2756 	mutex_exit(&connmgr_lock);
2757 
2758 	mp->b_datap->db_type = M_PROTO;
2759 	tdis = (struct T_discon_req *)mp->b_rptr;
2760 	tdis->PRIM_type = T_DISCON_REQ;
2761 	mp->b_wptr = mp->b_rptr + sizeof (*tdis);
2762 
2763 	RPCLOG(8, "connmgr_snddis: sending discon to queue %p\n", (void *)q);
2764 	put(q, mp);
2765 }
2766 
2767 /*
2768  * Sets up the entry for receiving replies, and calls rpcmod's write put proc
2769  * (through put) to send the call.
2770  */
2771 static void
2772 clnt_dispatch_send(queue_t *q, mblk_t *mp, calllist_t *e, uint_t xid,
2773 			uint_t queue_flag)
2774 {
2775 	ASSERT(e != NULL);
2776 
2777 	e->call_status = RPC_TIMEDOUT;	/* optimistic, eh? */
2778 	e->call_reason = 0;
2779 	e->call_wq = q;
2780 	e->call_xid = xid;
2781 	e->call_notified = FALSE;
2782 
2783 	/*
2784 	 * If queue_flag is set then the calllist_t is already on the hash
2785 	 * queue.  In this case just send the message and return.
2786 	 */
2787 	if (queue_flag) {
2788 		put(q, mp);
2789 		return;
2790 	}
2791 
2792 	/*
2793 	 * Set up calls for RPC requests (with XID != 0) on the hash
2794 	 * queue for fast lookups and place other calls (i.e.
2795 	 * connection management) on the linked list.
2796 	 */
2797 	if (xid != 0) {
2798 		RPCLOG(64, "clnt_dispatch_send: putting xid 0x%x on "
2799 			"dispatch list\n", xid);
2800 		e->call_hash = call_hash(xid, clnt_cots_hash_size);
2801 		e->call_bucket = &cots_call_ht[e->call_hash];
2802 		call_table_enter(e);
2803 	} else {
2804 		mutex_enter(&clnt_pending_lock);
2805 		if (clnt_pending)
2806 			clnt_pending->call_prev = e;
2807 		e->call_next = clnt_pending;
2808 		e->call_prev = NULL;
2809 		clnt_pending = e;
2810 		mutex_exit(&clnt_pending_lock);
2811 	}
2812 
2813 	put(q, mp);
2814 }
2815 
2816 /*
2817  * Called by rpcmod to notify a client with a clnt_pending call that its reply
2818  * has arrived.  If we can't find a client waiting for this reply, we log
2819  * the error and return.
2820  */
2821 bool_t
2822 clnt_dispatch_notify(mblk_t *mp, zoneid_t zoneid)
2823 {
2824 	calllist_t *e = NULL;
2825 	call_table_t *chtp;
2826 	uint32_t xid;
2827 	uint_t hash;
2828 
2829 	if ((IS_P2ALIGNED(mp->b_rptr, sizeof (uint32_t))) &&
2830 	    (mp->b_wptr - mp->b_rptr) >= sizeof (xid))
2831 		xid = *((uint32_t *)mp->b_rptr);
2832 	else {
2833 		int i = 0;
2834 		unsigned char *p = (unsigned char *)&xid;
2835 		unsigned char *rptr;
2836 		mblk_t *tmp = mp;
2837 
2838 		/*
2839 		 * Copy the xid, byte-by-byte into xid.
2840 		 */
2841 		while (tmp) {
2842 			rptr = tmp->b_rptr;
2843 			while (rptr < tmp->b_wptr) {
2844 				*p++ = *rptr++;
2845 				if (++i >= sizeof (xid))
2846 					goto done_xid_copy;
2847 			}
2848 			tmp = tmp->b_cont;
2849 		}
2850 
2851 		/*
2852 		 * If we got here, we ran out of mblk space before the
2853 		 * xid could be copied.
2854 		 */
2855 		ASSERT(tmp == NULL && i < sizeof (xid));
2856 
2857 		RPCLOG0(1,
2858 		    "clnt_dispatch_notify: message less than size of xid\n");
2859 		return (FALSE);
2860 
2861 	}
2862 done_xid_copy:
2863 
2864 	hash = call_hash(xid, clnt_cots_hash_size);
2865 	chtp = &cots_call_ht[hash];
2866 	/* call_table_find returns with the hash bucket locked */
2867 	call_table_find(chtp, xid, e);
2868 
2869 	if (e != NULL) {
2870 		/*
2871 		 * Found thread waiting for this reply
2872 		 */
2873 		mutex_enter(&e->call_lock);
2874 		if (e->call_reply)
2875 			/*
2876 			 * This can happen under the following scenario:
2877 			 * clnt_cots_kcallit() times out on the response,
2878 			 * rfscall() repeats the CLNT_CALL() with
2879 			 * the same xid, clnt_cots_kcallit() sends the retry,
2880 			 * thereby putting the clnt handle on the pending list,
2881 			 * the first response arrives, signalling the thread
2882 			 * in clnt_cots_kcallit(). Before that thread is
2883 			 * dispatched, the second response arrives as well,
2884 			 * and clnt_dispatch_notify still finds the handle on
2885 			 * the pending list, with call_reply set. So free the
2886 			 * old reply now.
2887 			 *
2888 			 * It is also possible for a response intended for
2889 			 * an RPC call with a different xid to reside here.
2890 			 * This can happen if the thread that owned this
2891 			 * client handle prior to the current owner bailed
2892 			 * out and left its call record on the dispatch
2893 			 * queue.  A window exists where the response can
2894 			 * arrive before the current owner dispatches its
2895 			 * RPC call.
2896 			 *
2897 			 * In any case, this is the very last point where we
2898 			 * can safely check the call_reply field before
2899 			 * placing the new response there.
2900 			 */
2901 			freemsg(e->call_reply);
2902 		e->call_reply = mp;
2903 		e->call_status = RPC_SUCCESS;
2904 		e->call_notified = TRUE;
2905 		cv_signal(&e->call_cv);
2906 		mutex_exit(&e->call_lock);
2907 		mutex_exit(&chtp->ct_lock);
2908 		return (TRUE);
2909 	} else {
2910 		zone_t *zone;
2911 		struct rpcstat *rpcstat;
2912 
2913 		mutex_exit(&chtp->ct_lock);
2914 		RPCLOG(65, "clnt_dispatch_notify: no caller for reply 0x%x\n",
2915 		    xid);
2916 		/*
2917 		 * This is unfortunate, but we need to lookup the zone so we
2918 		 * can increment its "rcbadxids" counter.
2919 		 */
2920 		zone = zone_find_by_id(zoneid);
2921 		if (zone == NULL) {
2922 			/*
2923 			 * The zone went away...
2924 			 */
2925 			return (FALSE);
2926 		}
2927 		rpcstat = zone_getspecific(rpcstat_zone_key, zone);
2928 		if (zone_status_get(zone) >= ZONE_IS_SHUTTING_DOWN) {
2929 			/*
2930 			 * Not interested
2931 			 */
2932 			zone_rele(zone);
2933 			return (FALSE);
2934 		}
2935 		COTSRCSTAT_INCR(rpcstat->rpc_cots_client, rcbadxids);
2936 		zone_rele(zone);
2937 	}
2938 	return (FALSE);
2939 }
2940 
2941 /*
2942  * Called by rpcmod when a non-data indication arrives.  The ones in which we
2943  * are interested are connection indications and options acks.  We dispatch
2944  * based on the queue the indication came in on.  If we are not interested in
2945  * what came in, we return false to rpcmod, who will then pass it upstream.
2946  */
2947 bool_t
2948 clnt_dispatch_notifyconn(queue_t *q, mblk_t *mp)
2949 {
2950 	calllist_t *e;
2951 	int type;
2952 
2953 	ASSERT((q->q_flag & QREADR) == 0);
2954 
2955 	type = ((union T_primitives *)mp->b_rptr)->type;
2956 	RPCLOG(8, "clnt_dispatch_notifyconn: prim type: [%s]\n",
2957 	    rpc_tpiprim2name(type));
2958 	mutex_enter(&clnt_pending_lock);
2959 	for (e = clnt_pending; /* NO CONDITION */; e = e->call_next) {
2960 		if (e == NULL) {
2961 			mutex_exit(&clnt_pending_lock);
2962 			RPCLOG(1, "clnt_dispatch_notifyconn: no one waiting "
2963 			    "for connection on queue 0x%p\n", (void *)q);
2964 			return (FALSE);
2965 		}
2966 		if (e->call_wq == q)
2967 			break;
2968 	}
2969 
2970 	switch (type) {
2971 	case T_CONN_CON:
2972 		/*
2973 		 * The transport is now connected, send a T_INFO_REQ to get
2974 		 * the tidu size.
2975 		 */
2976 		mutex_exit(&clnt_pending_lock);
2977 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
2978 			sizeof (struct T_info_req));
2979 		mp->b_rptr = mp->b_datap->db_base;
2980 		((union T_primitives *)mp->b_rptr)->type = T_INFO_REQ;
2981 		mp->b_wptr = mp->b_rptr + sizeof (struct T_info_req);
2982 		mp->b_datap->db_type = M_PCPROTO;
2983 		put(q, mp);
2984 		return (TRUE);
2985 	case T_INFO_ACK:
2986 	case T_OPTMGMT_ACK:
2987 		e->call_status = RPC_SUCCESS;
2988 		e->call_reply = mp;
2989 		e->call_notified = TRUE;
2990 		cv_signal(&e->call_cv);
2991 		break;
2992 	case T_ERROR_ACK:
2993 		e->call_status = RPC_CANTCONNECT;
2994 		e->call_reply = mp;
2995 		e->call_notified = TRUE;
2996 		cv_signal(&e->call_cv);
2997 		break;
2998 	case T_OK_ACK:
2999 		/*
3000 		 * Great, but we are really waiting for a T_CONN_CON
3001 		 */
3002 		freemsg(mp);
3003 		break;
3004 	default:
3005 		mutex_exit(&clnt_pending_lock);
3006 		RPCLOG(1, "clnt_dispatch_notifyconn: bad type %d\n", type);
3007 		return (FALSE);
3008 	}
3009 
3010 	mutex_exit(&clnt_pending_lock);
3011 	return (TRUE);
3012 }
3013 
3014 /*
3015  * Called by rpcmod when the transport is (or should be) going away.  Informs
3016  * all callers waiting for replies and marks the entry in the connection
3017  * manager's list as unconnected, and either closing (close handshake in
3018  * progress) or dead.
3019  */
3020 void
3021 clnt_dispatch_notifyall(queue_t *q, int32_t msg_type, int32_t reason)
3022 {
3023 	calllist_t *e;
3024 	call_table_t *ctp;
3025 	struct cm_xprt *cm_entry;
3026 	int have_connmgr_lock;
3027 	int i;
3028 
3029 	ASSERT((q->q_flag & QREADR) == 0);
3030 
3031 	RPCLOG(1, "clnt_dispatch_notifyall on queue %p", (void *)q);
3032 	RPCLOG(1, " received a notifcation prim type [%s]",
3033 	    rpc_tpiprim2name(msg_type));
3034 	RPCLOG(1, " and reason %d\n", reason);
3035 
3036 	/*
3037 	 * Find the transport entry in the connection manager's list, close
3038 	 * the transport and delete the entry.  In the case where rpcmod's
3039 	 * idle timer goes off, it sends us a T_ORDREL_REQ, indicating we
3040 	 * should gracefully close the connection.
3041 	 */
3042 	have_connmgr_lock = 1;
3043 	mutex_enter(&connmgr_lock);
3044 	for (cm_entry = cm_hd; cm_entry; cm_entry = cm_entry->x_next) {
3045 		ASSERT(cm_entry != cm_entry->x_next);
3046 		if (cm_entry->x_wq == q) {
3047 			ASSERT(MUTEX_HELD(&connmgr_lock));
3048 			ASSERT(have_connmgr_lock == 1);
3049 			switch (msg_type) {
3050 			case T_ORDREL_REQ:
3051 
3052 				if (cm_entry->x_dead) {
3053 					RPCLOG(1, "idle timeout on dead "
3054 					    "connection: %p\n",
3055 					    (void *)cm_entry);
3056 					if (clnt_stop_idle != NULL)
3057 						(*clnt_stop_idle)(q);
3058 					break;
3059 				}
3060 
3061 				/*
3062 				 * Only mark the connection as dead if it is
3063 				 * connected and idle.
3064 				 * An unconnected connection has probably
3065 				 * gone idle because the server is down,
3066 				 * and when it comes back up there will be
3067 				 * retries that need to use that connection.
3068 				 */
3069 				if (cm_entry->x_connected ||
3070 				    cm_entry->x_doomed) {
3071 				    if (cm_entry->x_ordrel) {
3072 					if (cm_entry->x_closing == TRUE) {
3073 					/*
3074 					 * The connection is obviously
3075 					 * wedged due to a bug or problem
3076 					 * with the transport. Mark it
3077 					 * as dead. Otherwise we can leak
3078 					 * connections.
3079 					 */
3080 					    cm_entry->x_dead = TRUE;
3081 					    mutex_exit(&connmgr_lock);
3082 					    have_connmgr_lock = 0;
3083 					    if (clnt_stop_idle != NULL)
3084 						(*clnt_stop_idle)(q);
3085 					    break;
3086 					}
3087 					cm_entry->x_closing = TRUE;
3088 					connmgr_sndrel(cm_entry);
3089 					have_connmgr_lock = 0;
3090 				    } else {
3091 					cm_entry->x_dead = TRUE;
3092 					mutex_exit(&connmgr_lock);
3093 					have_connmgr_lock = 0;
3094 					if (clnt_stop_idle != NULL)
3095 						(*clnt_stop_idle)(q);
3096 				    }
3097 				} else {
3098 					/*
3099 					 * We don't mark the connection
3100 					 * as dead, but we turn off the
3101 					 * idle timer.
3102 					 */
3103 					mutex_exit(&connmgr_lock);
3104 					have_connmgr_lock = 0;
3105 					if (clnt_stop_idle != NULL)
3106 						(*clnt_stop_idle)(q);
3107 					RPCLOG(1, "clnt_dispatch_notifyall:"
3108 					    " ignoring timeout from rpcmod"
3109 					    " (q %p) because we are not "
3110 					    " connected\n", (void *)q);
3111 				}
3112 				break;
3113 			case T_ORDREL_IND:
3114 				/*
3115 				 * If this entry is marked closing, then we are
3116 				 * completing a close handshake, and the
3117 				 * connection is dead.  Otherwise, the server is
3118 				 * trying to close. Since the server will not
3119 				 * be sending any more RPC replies, we abort
3120 				 * the connection, including flushing
3121 				 * any RPC requests that are in-transit.
3122 				 */
3123 				if (cm_entry->x_closing) {
3124 					cm_entry->x_dead = TRUE;
3125 					mutex_exit(&connmgr_lock);
3126 					have_connmgr_lock = 0;
3127 					if (clnt_stop_idle != NULL)
3128 						(*clnt_stop_idle)(q);
3129 				} else {
3130 					/*
3131 					 * if we're getting a disconnect
3132 					 * before we've finished our
3133 					 * connect attempt, mark it for
3134 					 * later processing
3135 					 */
3136 					if (cm_entry->x_thread)
3137 						cm_entry->x_early_disc = TRUE;
3138 					else
3139 						cm_entry->x_connected = FALSE;
3140 					cm_entry->x_waitdis = TRUE;
3141 					connmgr_snddis(cm_entry);
3142 					have_connmgr_lock = 0;
3143 				}
3144 				break;
3145 
3146 			case T_ERROR_ACK:
3147 			case T_OK_ACK:
3148 				cm_entry->x_waitdis = FALSE;
3149 				cv_signal(&cm_entry->x_dis_cv);
3150 				mutex_exit(&connmgr_lock);
3151 				return;
3152 
3153 			case T_DISCON_REQ:
3154 				if (cm_entry->x_thread)
3155 					cm_entry->x_early_disc = TRUE;
3156 				else
3157 					cm_entry->x_connected = FALSE;
3158 				cm_entry->x_waitdis = TRUE;
3159 
3160 				connmgr_snddis(cm_entry);
3161 				have_connmgr_lock = 0;
3162 				break;
3163 
3164 			case T_DISCON_IND:
3165 			default:
3166 				/*
3167 				 * if we're getting a disconnect before
3168 				 * we've finished our connect attempt,
3169 				 * mark it for later processing
3170 				 */
3171 				if (cm_entry->x_closing) {
3172 					cm_entry->x_dead = TRUE;
3173 					mutex_exit(&connmgr_lock);
3174 					have_connmgr_lock = 0;
3175 					if (clnt_stop_idle != NULL)
3176 						(*clnt_stop_idle)(q);
3177 				} else {
3178 					if (cm_entry->x_thread) {
3179 						cm_entry->x_early_disc = TRUE;
3180 					} else {
3181 						cm_entry->x_dead = TRUE;
3182 						cm_entry->x_connected = FALSE;
3183 					}
3184 				}
3185 				break;
3186 			}
3187 			break;
3188 		}
3189 	}
3190 
3191 	if (have_connmgr_lock)
3192 		mutex_exit(&connmgr_lock);
3193 
3194 	if (msg_type == T_ERROR_ACK || msg_type == T_OK_ACK) {
3195 		RPCLOG(1, "clnt_dispatch_notifyall: (wq %p) could not find "
3196 		    "connmgr entry for discon ack\n", (void *)q);
3197 		return;
3198 	}
3199 
3200 	/*
3201 	 * Then kick all the clnt_pending calls out of their wait.  There
3202 	 * should be no clnt_pending calls in the case of rpcmod's idle
3203 	 * timer firing.
3204 	 */
3205 	for (i = 0; i < clnt_cots_hash_size; i++) {
3206 		ctp = &cots_call_ht[i];
3207 		mutex_enter(&ctp->ct_lock);
3208 		for (e = ctp->ct_call_next;
3209 			e != (calllist_t *)ctp;
3210 			e = e->call_next) {
3211 			if (e->call_wq == q && e->call_notified == FALSE) {
3212 				RPCLOG(1,
3213 				"clnt_dispatch_notifyall for queue %p ",
3214 					(void *)q);
3215 				RPCLOG(1, "aborting clnt_pending call %p\n",
3216 					(void *)e);
3217 
3218 				if (msg_type == T_DISCON_IND)
3219 					e->call_reason = reason;
3220 				e->call_notified = TRUE;
3221 				e->call_status = RPC_XPRTFAILED;
3222 				cv_signal(&e->call_cv);
3223 			}
3224 		}
3225 		mutex_exit(&ctp->ct_lock);
3226 	}
3227 
3228 	mutex_enter(&clnt_pending_lock);
3229 	for (e = clnt_pending; e; e = e->call_next) {
3230 		/*
3231 		 * Only signal those RPC handles that haven't been
3232 		 * signalled yet. Otherwise we can get a bogus call_reason.
3233 		 * This can happen if thread A is making a call over a
3234 		 * connection. If the server is killed, it will cause
3235 		 * reset, and reason will default to EIO as a result of
3236 		 * a T_ORDREL_IND. Thread B then attempts to recreate
3237 		 * the connection but gets a T_DISCON_IND. If we set the
3238 		 * call_reason code for all threads, then if thread A
3239 		 * hasn't been dispatched yet, it will get the wrong
3240 		 * reason. The bogus call_reason can make it harder to
3241 		 * discriminate between calls that fail because the
3242 		 * connection attempt failed versus those where the call
3243 		 * may have been executed on the server.
3244 		 */
3245 		if (e->call_wq == q && e->call_notified == FALSE) {
3246 			RPCLOG(1, "clnt_dispatch_notifyall for queue %p ",
3247 			    (void *)q);
3248 			RPCLOG(1, " aborting clnt_pending call %p\n",
3249 			    (void *)e);
3250 
3251 			if (msg_type == T_DISCON_IND)
3252 				e->call_reason = reason;
3253 			e->call_notified = TRUE;
3254 			/*
3255 			 * Let the caller timeout, else he will retry
3256 			 * immediately.
3257 			 */
3258 			e->call_status = RPC_XPRTFAILED;
3259 
3260 			/*
3261 			 * We used to just signal those threads
3262 			 * waiting for a connection, (call_xid = 0).
3263 			 * That meant that threads waiting for a response
3264 			 * waited till their timeout expired. This
3265 			 * could be a long time if they've specified a
3266 			 * maximum timeout. (2^31 - 1). So we
3267 			 * Signal all threads now.
3268 			 */
3269 			cv_signal(&e->call_cv);
3270 		}
3271 	}
3272 	mutex_exit(&clnt_pending_lock);
3273 }
3274 
3275 
3276 /*ARGSUSED*/
3277 /*
3278  * after resuming a system that's been suspended for longer than the
3279  * NFS server's idle timeout (svc_idle_timeout for Solaris 2), rfscall()
3280  * generates "NFS server X not responding" and "NFS server X ok" messages;
3281  * here we reset inet connections to cause a re-connect and avoid those
3282  * NFS messages.  see 4045054
3283  */
3284 boolean_t
3285 connmgr_cpr_reset(void *arg, int code)
3286 {
3287 	struct cm_xprt *cxp;
3288 
3289 	if (code == CB_CODE_CPR_CHKPT)
3290 		return (B_TRUE);
3291 
3292 	if (mutex_tryenter(&connmgr_lock) == 0)
3293 		return (B_FALSE);
3294 	for (cxp = cm_hd; cxp; cxp = cxp->x_next) {
3295 		if ((cxp->x_family == AF_INET || cxp->x_family == AF_INET6) &&
3296 			cxp->x_connected == TRUE) {
3297 			if (cxp->x_thread)
3298 				cxp->x_early_disc = TRUE;
3299 			else
3300 				cxp->x_connected = FALSE;
3301 			cxp->x_needdis = TRUE;
3302 		}
3303 	}
3304 	mutex_exit(&connmgr_lock);
3305 	return (B_TRUE);
3306 }
3307 
3308 void
3309 clnt_cots_stats_init(zoneid_t zoneid, struct rpc_cots_client **statsp)
3310 {
3311 
3312 	*statsp = (struct rpc_cots_client *)rpcstat_zone_init_common(zoneid,
3313 	    "unix", "rpc_cots_client", (const kstat_named_t *)&cots_rcstat_tmpl,
3314 	    sizeof (cots_rcstat_tmpl));
3315 }
3316 
3317 void
3318 clnt_cots_stats_fini(zoneid_t zoneid, struct rpc_cots_client **statsp)
3319 {
3320 	rpcstat_zone_fini_common(zoneid, "unix", "rpc_cots_client");
3321 	kmem_free(*statsp, sizeof (cots_rcstat_tmpl));
3322 }
3323 
3324 void
3325 clnt_cots_init(void)
3326 {
3327 	mutex_init(&connmgr_lock, NULL, MUTEX_DEFAULT, NULL);
3328 	mutex_init(&clnt_pending_lock, NULL, MUTEX_DEFAULT, NULL);
3329 
3330 	if (clnt_cots_hash_size < DEFAULT_MIN_HASH_SIZE)
3331 		clnt_cots_hash_size = DEFAULT_MIN_HASH_SIZE;
3332 
3333 	cots_call_ht = call_table_init(clnt_cots_hash_size);
3334 	zone_key_create(&zone_cots_key, NULL, NULL, clnt_zone_destroy);
3335 }
3336 
3337 void
3338 clnt_cots_fini(void)
3339 {
3340 	(void) zone_key_delete(zone_cots_key);
3341 }
3342 
3343 /*
3344  * Wait for TPI ack, returns success only if expected ack is received
3345  * within timeout period.
3346  */
3347 
3348 static int
3349 waitforack(calllist_t *e, t_scalar_t ack_prim, const struct timeval *waitp,
3350     bool_t nosignal)
3351 {
3352 	union T_primitives *tpr;
3353 	clock_t timout;
3354 	int cv_stat = 1;
3355 
3356 	ASSERT(MUTEX_HELD(&clnt_pending_lock));
3357 	while (e->call_reply == NULL) {
3358 		if (waitp != NULL) {
3359 			timout = waitp->tv_sec * drv_usectohz(MICROSEC) +
3360 			    drv_usectohz(waitp->tv_usec) + lbolt;
3361 			if (nosignal)
3362 				cv_stat = cv_timedwait(&e->call_cv,
3363 				    &clnt_pending_lock, timout);
3364 			else
3365 				cv_stat = cv_timedwait_sig(&e->call_cv,
3366 				    &clnt_pending_lock, timout);
3367 		} else {
3368 			if (nosignal)
3369 				cv_wait(&e->call_cv, &clnt_pending_lock);
3370 			else
3371 				cv_stat = cv_wait_sig(&e->call_cv,
3372 				    &clnt_pending_lock);
3373 		}
3374 		if (cv_stat == -1)
3375 			return (ETIME);
3376 		if (cv_stat == 0)
3377 			return (EINTR);
3378 	}
3379 	tpr = (union T_primitives *)e->call_reply->b_rptr;
3380 	if (tpr->type == ack_prim)
3381 		return (0); /* Success */
3382 
3383 	if (tpr->type == T_ERROR_ACK) {
3384 		if (tpr->error_ack.TLI_error == TSYSERR)
3385 			return (tpr->error_ack.UNIX_error);
3386 		else
3387 			return (t_tlitosyserr(tpr->error_ack.TLI_error));
3388 	}
3389 
3390 	return (EPROTO); /* unknown or unexpected primitive */
3391 }
3392