xref: /titanic_52/usr/src/uts/common/rpc/clnt_clts.c (revision 0eb822a1c0c2bea495647510b75f77f0e57633eb)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T
28  * All Rights Reserved
29  */
30 
31 /*
32  * Portions of this source code were derived from Berkeley 4.3 BSD
33  * under license from the Regents of the University of California.
34  */
35 
36 #pragma ident	"%Z%%M%	%I%	%E% SMI"
37 
38 /*
39  * Implements a kernel based, client side RPC.
40  */
41 
42 #include <sys/param.h>
43 #include <sys/types.h>
44 #include <sys/systm.h>
45 #include <sys/sysmacros.h>
46 #include <sys/stream.h>
47 #include <sys/strsubr.h>
48 #include <sys/ddi.h>
49 #include <sys/tiuser.h>
50 #include <sys/tihdr.h>
51 #include <sys/t_kuser.h>
52 #include <sys/errno.h>
53 #include <sys/kmem.h>
54 #include <sys/debug.h>
55 #include <sys/kstat.h>
56 #include <sys/t_lock.h>
57 #include <sys/cmn_err.h>
58 #include <sys/conf.h>
59 #include <sys/disp.h>
60 #include <sys/taskq.h>
61 #include <sys/list.h>
62 #include <sys/atomic.h>
63 #include <sys/zone.h>
64 #include <netinet/in.h>
65 #include <rpc/types.h>
66 #include <rpc/xdr.h>
67 #include <rpc/auth.h>
68 #include <rpc/clnt.h>
69 #include <rpc/rpc_msg.h>
70 
71 static enum clnt_stat clnt_clts_kcallit(CLIENT *, rpcproc_t, xdrproc_t,
72 		    caddr_t, xdrproc_t, caddr_t, struct timeval);
73 static void	clnt_clts_kabort(CLIENT *);
74 static void	clnt_clts_kerror(CLIENT *, struct rpc_err *);
75 static bool_t	clnt_clts_kfreeres(CLIENT *, xdrproc_t, caddr_t);
76 static bool_t	clnt_clts_kcontrol(CLIENT *, int, char *);
77 static void	clnt_clts_kdestroy(CLIENT *);
78 static int	clnt_clts_ksettimers(CLIENT *, struct rpc_timers *,
79 		    struct rpc_timers *, int, void (*)(), caddr_t, uint32_t);
80 
81 /*
82  * Operations vector for CLTS based RPC
83  */
84 static struct clnt_ops clts_ops = {
85 	clnt_clts_kcallit,	/* do rpc call */
86 	clnt_clts_kabort,	/* abort call */
87 	clnt_clts_kerror,	/* return error status */
88 	clnt_clts_kfreeres,	/* free results */
89 	clnt_clts_kdestroy,	/* destroy rpc handle */
90 	clnt_clts_kcontrol,	/* the ioctl() of rpc */
91 	clnt_clts_ksettimers	/* set retry timers */
92 };
93 
94 /*
95  * Endpoint for CLTS (INET, INET6, loopback, etc.)
96  */
97 typedef struct endpnt_type {
98 	struct endpnt_type *e_next;	/* pointer to next endpoint type */
99 	list_t		e_pool;		/* list of available endpoints */
100 	list_t		e_ilist;	/* list of idle endpints */
101 	struct endpnt	*e_pcurr;	/* pointer to current endpoint */
102 	char		e_protofmly[KNC_STRSIZE];	/* protocol family */
103 	dev_t		e_rdev;		/* device */
104 	kmutex_t	e_plock;	/* pool lock */
105 	kmutex_t	e_ilock;	/* idle list lock */
106 	timeout_id_t	e_itimer;	/* timer to dispatch the taskq */
107 	uint_t		e_cnt;		/* number of endpoints in the pool */
108 	zoneid_t	e_zoneid;	/* zoneid of endpoint type */
109 	kcondvar_t	e_async_cv;	/* cv for asynchronous reap threads */
110 	uint_t		e_async_count;	/* count of asynchronous reap threads */
111 } endpnt_type_t;
112 
113 typedef struct endpnt {
114 	list_node_t	e_node;		/* link to the pool */
115 	list_node_t	e_idle;		/* link to the idle list */
116 	endpnt_type_t	*e_type;	/* back pointer to endpoint type */
117 	TIUSER		*e_tiptr;	/* pointer to transport endpoint */
118 	queue_t		*e_wq;		/* write queue */
119 	uint_t		e_flags;	/* endpoint flags */
120 	uint_t		e_ref;		/* ref count on endpoint */
121 	kcondvar_t	e_cv;		/* condition variable */
122 	kmutex_t	e_lock;		/* protects cv and flags */
123 	time_t		e_itime;	/* time when rele'd */
124 } endpnt_t;
125 
126 #define	ENDPNT_ESTABLISHED	0x1	/* endpoint is established */
127 #define	ENDPNT_WAITING		0x2	/* thread waiting for endpoint */
128 #define	ENDPNT_BOUND		0x4	/* endpoint is bound */
129 #define	ENDPNT_STALE		0x8	/* endpoint is dead */
130 #define	ENDPNT_ONIDLE		0x10	/* endpoint is on the idle list */
131 
132 static krwlock_t	endpnt_type_lock; /* protects endpnt_type_list */
133 static endpnt_type_t	*endpnt_type_list = NULL; /* list of CLTS endpoints */
134 static struct kmem_cache	*endpnt_cache; /* cache of endpnt_t's */
135 static taskq_t			*endpnt_taskq; /* endpnt_t reaper thread */
136 static bool_t			taskq_created; /* flag for endpnt_taskq */
137 static kmutex_t			endpnt_taskq_lock; /* taskq lock */
138 static zone_key_t		endpnt_destructor_key;
139 
140 #define	DEFAULT_ENDPOINT_REAP_INTERVAL 60 /* 1 minute */
141 #define	DEFAULT_INTERVAL_SHIFT 30 /* 30 seconds */
142 
143 /*
144  * Endpoint tunables
145  */
146 static int	clnt_clts_max_endpoints = -1;
147 static int	clnt_clts_hash_size = DEFAULT_HASH_SIZE;
148 static time_t	clnt_clts_endpoint_reap_interval = -1;
149 static clock_t	clnt_clts_taskq_dispatch_interval;
150 
151 /*
152  * Response completion hash queue
153  */
154 static call_table_t *clts_call_ht;
155 
156 /*
157  * Routines for the endpoint manager
158  */
159 static struct endpnt_type *endpnt_type_create(struct knetconfig *);
160 static void endpnt_type_free(struct endpnt_type *);
161 static int check_endpnt(struct endpnt *, struct endpnt **);
162 static struct endpnt *endpnt_get(struct knetconfig *, int);
163 static void endpnt_rele(struct endpnt *);
164 static void endpnt_reap_settimer(endpnt_type_t *);
165 static void endpnt_reap(endpnt_type_t *);
166 static void endpnt_reap_dispatch(void *);
167 static void endpnt_reclaim(zoneid_t);
168 
169 
170 /*
171  * Request dipatching function.
172  */
173 static int clnt_clts_dispatch_send(queue_t *q, mblk_t *, struct netbuf *addr,
174 					calllist_t *, uint_t);
175 
176 /*
177  * The size of the preserialized RPC header information.
178  */
179 #define	CKU_HDRSIZE	20
180 /*
181  * The initial allocation size.  It is small to reduce space requirements.
182  */
183 #define	CKU_INITSIZE	2048
184 /*
185  * The size of additional allocations, if required.  It is larger to
186  * reduce the number of actual allocations.
187  */
188 #define	CKU_ALLOCSIZE	8192
189 
190 /*
191  * Private data per rpc handle.  This structure is allocated by
192  * clnt_clts_kcreate, and freed by clnt_clts_kdestroy.
193  */
194 struct cku_private {
195 	CLIENT			 cku_client;	/* client handle */
196 	int			 cku_retrys;	/* request retrys */
197 	calllist_t		 cku_call;
198 	struct endpnt		*cku_endpnt;	/* open end point */
199 	struct knetconfig	 cku_config;
200 	struct netbuf		 cku_addr;	/* remote address */
201 	struct rpc_err		 cku_err;	/* error status */
202 	XDR			 cku_outxdr;	/* xdr stream for output */
203 	XDR			 cku_inxdr;	/* xdr stream for input */
204 	char			 cku_rpchdr[CKU_HDRSIZE + 4]; /* rpc header */
205 	struct cred		*cku_cred;	/* credentials */
206 	struct rpc_timers	*cku_timers;	/* for estimating RTT */
207 	struct rpc_timers	*cku_timeall;	/* for estimating RTT */
208 	void			 (*cku_feedback)(int, int, caddr_t);
209 						/* ptr to feedback rtn */
210 	caddr_t			 cku_feedarg;	/* argument for feedback func */
211 	uint32_t		 cku_xid;	/* current XID */
212 	bool_t			 cku_bcast;	/* RPC broadcast hint */
213 	int			cku_useresvport; /* Use reserved port */
214 	struct rpc_clts_client	*cku_stats;	/* counters for the zone */
215 };
216 
217 static const struct rpc_clts_client {
218 	kstat_named_t	rccalls;
219 	kstat_named_t	rcbadcalls;
220 	kstat_named_t	rcretrans;
221 	kstat_named_t	rcbadxids;
222 	kstat_named_t	rctimeouts;
223 	kstat_named_t	rcnewcreds;
224 	kstat_named_t	rcbadverfs;
225 	kstat_named_t	rctimers;
226 	kstat_named_t	rcnomem;
227 	kstat_named_t	rccantsend;
228 } clts_rcstat_tmpl = {
229 	{ "calls",	KSTAT_DATA_UINT64 },
230 	{ "badcalls",	KSTAT_DATA_UINT64 },
231 	{ "retrans",	KSTAT_DATA_UINT64 },
232 	{ "badxids",	KSTAT_DATA_UINT64 },
233 	{ "timeouts",	KSTAT_DATA_UINT64 },
234 	{ "newcreds",	KSTAT_DATA_UINT64 },
235 	{ "badverfs",	KSTAT_DATA_UINT64 },
236 	{ "timers",	KSTAT_DATA_UINT64 },
237 	{ "nomem",	KSTAT_DATA_UINT64 },
238 	{ "cantsend",	KSTAT_DATA_UINT64 },
239 };
240 
241 static uint_t clts_rcstat_ndata =
242 	sizeof (clts_rcstat_tmpl) / sizeof (kstat_named_t);
243 
244 #define	RCSTAT_INCR(s, x)			\
245 	atomic_add_64(&(s)->x.value.ui64, 1)
246 
247 #define	ptoh(p)		(&((p)->cku_client))
248 #define	htop(h)		((struct cku_private *)((h)->cl_private))
249 
250 /*
251  * Times to retry
252  */
253 #define	SNDTRIES	4
254 #define	REFRESHES	2	/* authentication refreshes */
255 
256 /*
257  * The following is used to determine the global default behavior for
258  * CLTS when binding to a local port.
259  *
260  * If the value is set to 1 the default will be to select a reserved
261  * (aka privileged) port, if the value is zero the default will be to
262  * use non-reserved ports.  Users of kRPC may override this by using
263  * CLNT_CONTROL() and CLSET_BINDRESVPORT.
264  */
265 static int clnt_clts_do_bindresvport = 1;
266 
267 #define	BINDRESVPORT_RETRIES 5
268 
269 void
270 clnt_clts_stats_init(zoneid_t zoneid, struct rpc_clts_client **statsp)
271 {
272 	kstat_t *ksp;
273 	kstat_named_t *knp;
274 
275 	knp = rpcstat_zone_init_common(zoneid, "unix", "rpc_clts_client",
276 	    (const kstat_named_t *)&clts_rcstat_tmpl,
277 	    sizeof (clts_rcstat_tmpl));
278 	/*
279 	 * Backwards compatibility for old kstat clients
280 	 */
281 	ksp = kstat_create_zone("unix", 0, "rpc_client", "rpc",
282 	    KSTAT_TYPE_NAMED, clts_rcstat_ndata,
283 	    KSTAT_FLAG_VIRTUAL | KSTAT_FLAG_WRITABLE, zoneid);
284 	if (ksp) {
285 		ksp->ks_data = knp;
286 		kstat_install(ksp);
287 	}
288 	*statsp = (struct rpc_clts_client *)knp;
289 }
290 
291 void
292 clnt_clts_stats_fini(zoneid_t zoneid, struct rpc_clts_client **statsp)
293 {
294 	rpcstat_zone_fini_common(zoneid, "unix", "rpc_clts_client");
295 	kstat_delete_byname_zone("unix", 0, "rpc_client", zoneid);
296 	kmem_free(*statsp, sizeof (clts_rcstat_tmpl));
297 }
298 
299 /*
300  * Create an rpc handle for a clts rpc connection.
301  * Allocates space for the handle structure and the private data.
302  */
303 /* ARGSUSED */
304 int
305 clnt_clts_kcreate(struct knetconfig *config, struct netbuf *addr,
306 	rpcprog_t pgm, rpcvers_t vers, int retrys, struct cred *cred,
307 	CLIENT **cl)
308 {
309 	CLIENT *h;
310 	struct cku_private *p;
311 	struct rpc_msg call_msg;
312 	int error;
313 	int plen;
314 
315 	if (cl == NULL)
316 		return (EINVAL);
317 
318 	*cl = NULL;
319 	error = 0;
320 
321 	p = kmem_zalloc(sizeof (*p), KM_SLEEP);
322 
323 	h = ptoh(p);
324 
325 	/* handle */
326 	h->cl_ops = &clts_ops;
327 	h->cl_private = (caddr_t)p;
328 	h->cl_auth = authkern_create();
329 
330 	/* call message, just used to pre-serialize below */
331 	call_msg.rm_xid = 0;
332 	call_msg.rm_direction = CALL;
333 	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
334 	call_msg.rm_call.cb_prog = pgm;
335 	call_msg.rm_call.cb_vers = vers;
336 
337 	/* private */
338 	clnt_clts_kinit(h, addr, retrys, cred);
339 
340 	xdrmem_create(&p->cku_outxdr, p->cku_rpchdr, CKU_HDRSIZE, XDR_ENCODE);
341 
342 	/* pre-serialize call message header */
343 	if (!xdr_callhdr(&p->cku_outxdr, &call_msg)) {
344 		error = EINVAL;		/* XXX */
345 		goto bad;
346 	}
347 
348 	p->cku_config.knc_rdev = config->knc_rdev;
349 	p->cku_config.knc_semantics = config->knc_semantics;
350 	plen = strlen(config->knc_protofmly) + 1;
351 	p->cku_config.knc_protofmly = kmem_alloc(plen, KM_SLEEP);
352 	bcopy(config->knc_protofmly, p->cku_config.knc_protofmly, plen);
353 	p->cku_useresvport = -1; /* value is has not been set */
354 
355 	cv_init(&p->cku_call.call_cv, NULL, CV_DEFAULT, NULL);
356 	mutex_init(&p->cku_call.call_lock, NULL, MUTEX_DEFAULT, NULL);
357 
358 	*cl = h;
359 	return (0);
360 
361 bad:
362 	auth_destroy(h->cl_auth);
363 	kmem_free(p->cku_addr.buf, addr->maxlen);
364 	kmem_free(p, sizeof (struct cku_private));
365 
366 	return (error);
367 }
368 
369 void
370 clnt_clts_kinit(CLIENT *h, struct netbuf *addr, int retrys, cred_t *cred)
371 {
372 	/* LINTED pointer alignment */
373 	struct cku_private *p = htop(h);
374 	struct rpcstat *rsp;
375 
376 	rsp = zone_getspecific(rpcstat_zone_key, rpc_zone());
377 	ASSERT(rsp != NULL);
378 
379 	p->cku_retrys = retrys;
380 
381 	if (p->cku_addr.maxlen < addr->len) {
382 		if (p->cku_addr.maxlen != 0 && p->cku_addr.buf != NULL)
383 			kmem_free(p->cku_addr.buf, p->cku_addr.maxlen);
384 
385 		p->cku_addr.buf = kmem_zalloc(addr->maxlen, KM_SLEEP);
386 		p->cku_addr.maxlen = addr->maxlen;
387 	}
388 
389 	p->cku_addr.len = addr->len;
390 	bcopy(addr->buf, p->cku_addr.buf, addr->len);
391 
392 	p->cku_cred = cred;
393 	p->cku_xid = 0;
394 	p->cku_timers = NULL;
395 	p->cku_timeall = NULL;
396 	p->cku_feedback = NULL;
397 	p->cku_bcast = FALSE;
398 	p->cku_call.call_xid = 0;
399 	p->cku_call.call_hash = 0;
400 	p->cku_call.call_notified = FALSE;
401 	p->cku_call.call_next = NULL;
402 	p->cku_call.call_prev = NULL;
403 	p->cku_call.call_reply = NULL;
404 	p->cku_call.call_wq = NULL;
405 	p->cku_stats = rsp->rpc_clts_client;
406 }
407 
408 /*
409  * set the timers.  Return current retransmission timeout.
410  */
411 static int
412 clnt_clts_ksettimers(CLIENT *h, struct rpc_timers *t, struct rpc_timers *all,
413 	int minimum, void (*feedback)(int, int, caddr_t), caddr_t arg,
414 	uint32_t xid)
415 {
416 	/* LINTED pointer alignment */
417 	struct cku_private *p = htop(h);
418 	int value;
419 
420 	p->cku_feedback = feedback;
421 	p->cku_feedarg = arg;
422 	p->cku_timers = t;
423 	p->cku_timeall = all;
424 	if (xid)
425 		p->cku_xid = xid;
426 	value = all->rt_rtxcur;
427 	value += t->rt_rtxcur;
428 	if (value < minimum)
429 		return (minimum);
430 	RCSTAT_INCR(p->cku_stats, rctimers);
431 	return (value);
432 }
433 
434 /*
435  * Time out back off function. tim is in HZ
436  */
437 #define	MAXTIMO	(20 * hz)
438 #define	backoff(tim)	(((tim) < MAXTIMO) ? dobackoff(tim) : (tim))
439 #define	dobackoff(tim)	((((tim) << 1) > MAXTIMO) ? MAXTIMO : ((tim) << 1))
440 
441 #define	RETRY_POLL_TIMO	30
442 
443 /*
444  * Call remote procedure.
445  * Most of the work of rpc is done here.  We serialize what is left
446  * of the header (some was pre-serialized in the handle), serialize
447  * the arguments, and send it off.  We wait for a reply or a time out.
448  * Timeout causes an immediate return, other packet problems may cause
449  * a retry on the receive.  When a good packet is received we deserialize
450  * it, and check verification.  A bad reply code will cause one retry
451  * with full (longhand) credentials.
452  */
453 enum clnt_stat
454 clnt_clts_kcallit_addr(CLIENT *h, rpcproc_t procnum, xdrproc_t xdr_args,
455 	caddr_t argsp, xdrproc_t xdr_results, caddr_t resultsp,
456 	struct timeval wait, struct netbuf *sin)
457 {
458 	/* LINTED pointer alignment */
459 	struct cku_private *p = htop(h);
460 	XDR *xdrs;
461 	int stries = p->cku_retrys;
462 	int refreshes = REFRESHES;	/* number of times to refresh cred */
463 	int round_trip;			/* time the RPC */
464 	int error;
465 	int hdrsz;
466 	mblk_t *mp;
467 	mblk_t *mpdup;
468 	mblk_t *resp = NULL;
469 	mblk_t *tmp;
470 	calllist_t *call = &p->cku_call;
471 	clock_t timout = 0;
472 	bool_t interrupted;
473 	enum clnt_stat status;
474 	struct rpc_msg reply_msg;
475 	enum clnt_stat re_status;
476 	endpnt_t *endpt;
477 
478 	RCSTAT_INCR(p->cku_stats, rccalls);
479 
480 	RPCLOG(2, "clnt_clts_kcallit_addr: wait.tv_sec: %ld\n", wait.tv_sec);
481 	RPCLOG(2, "clnt_clts_kcallit_addr: wait.tv_usec: %ld\n", wait.tv_usec);
482 
483 	timout = TIMEVAL_TO_TICK(&wait);
484 
485 	if (p->cku_xid == 0) {
486 		p->cku_xid = alloc_xid();
487 		if (p->cku_endpnt != NULL)
488 			endpnt_rele(p->cku_endpnt);
489 		p->cku_endpnt = NULL;
490 	}
491 
492 	mpdup = NULL;
493 call_again:
494 
495 	if (mpdup == NULL) {
496 
497 		while ((mp = allocb(CKU_INITSIZE, BPRI_LO)) == NULL) {
498 			if (strwaitbuf(CKU_INITSIZE, BPRI_LO)) {
499 				p->cku_err.re_status = RPC_SYSTEMERROR;
500 				p->cku_err.re_errno = ENOSR;
501 				goto done;
502 			}
503 		}
504 
505 		xdrs = &p->cku_outxdr;
506 		xdrmblk_init(xdrs, mp, XDR_ENCODE, CKU_ALLOCSIZE);
507 
508 		if (h->cl_auth->ah_cred.oa_flavor != RPCSEC_GSS) {
509 			/*
510 			 * Copy in the preserialized RPC header
511 			 * information.
512 			 */
513 			bcopy(p->cku_rpchdr, mp->b_rptr, CKU_HDRSIZE);
514 
515 			/*
516 			 * transaction id is the 1st thing in the output
517 			 * buffer.
518 			 */
519 			/* LINTED pointer alignment */
520 			(*(uint32_t *)(mp->b_rptr)) = p->cku_xid;
521 
522 			/* Skip the preserialized stuff. */
523 			XDR_SETPOS(xdrs, CKU_HDRSIZE);
524 
525 			/* Serialize dynamic stuff into the output buffer. */
526 			if ((!XDR_PUTINT32(xdrs, (int32_t *)&procnum)) ||
527 			    (!AUTH_MARSHALL(h->cl_auth, xdrs, p->cku_cred)) ||
528 			    (!(*xdr_args)(xdrs, argsp))) {
529 				freemsg(mp);
530 				p->cku_err.re_status = RPC_CANTENCODEARGS;
531 				p->cku_err.re_errno = EIO;
532 				goto done;
533 			}
534 		} else {
535 			uint32_t *uproc = (uint32_t *)
536 			    &p->cku_rpchdr[CKU_HDRSIZE];
537 			IXDR_PUT_U_INT32(uproc, procnum);
538 
539 			(*(uint32_t *)(&p->cku_rpchdr[0])) = p->cku_xid;
540 			XDR_SETPOS(xdrs, 0);
541 
542 			/* Serialize the procedure number and the arguments. */
543 			if (!AUTH_WRAP(h->cl_auth, (caddr_t)p->cku_rpchdr,
544 			    CKU_HDRSIZE+4, xdrs, xdr_args, argsp)) {
545 				freemsg(mp);
546 				p->cku_err.re_status = RPC_CANTENCODEARGS;
547 				p->cku_err.re_errno = EIO;
548 				goto done;
549 			}
550 		}
551 	} else
552 		mp = mpdup;
553 
554 	mpdup = dupmsg(mp);
555 	if (mpdup == NULL) {
556 		freemsg(mp);
557 		p->cku_err.re_status = RPC_SYSTEMERROR;
558 		p->cku_err.re_errno = ENOSR;
559 		goto done;
560 	}
561 
562 	/*
563 	 * Grab an endpnt only if the endpoint is NULL.  We could be retrying
564 	 * the request and in this case we want to go through the same
565 	 * source port, so that the duplicate request cache may detect a
566 	 * retry.
567 	 */
568 
569 	if (p->cku_endpnt == NULL)
570 		p->cku_endpnt = endpnt_get(&p->cku_config, p->cku_useresvport);
571 
572 	if (p->cku_endpnt == NULL) {
573 		freemsg(mp);
574 		p->cku_err.re_status = RPC_SYSTEMERROR;
575 		p->cku_err.re_errno = ENOSR;
576 		goto done;
577 	}
578 
579 	round_trip = lbolt;
580 
581 	error = clnt_clts_dispatch_send(p->cku_endpnt->e_wq, mp,
582 					&p->cku_addr, call, p->cku_xid);
583 
584 	if (error != 0) {
585 		freemsg(mp);
586 		p->cku_err.re_status = RPC_CANTSEND;
587 		p->cku_err.re_errno = error;
588 		RCSTAT_INCR(p->cku_stats, rccantsend);
589 		goto done1;
590 	}
591 
592 	RPCLOG(64, "clnt_clts_kcallit_addr: sent call for xid 0x%x\n",
593 		p->cku_xid);
594 
595 	/*
596 	 * There are two reasons for which we go back to to tryread.
597 	 *
598 	 * a) In case the status is RPC_PROCUNAVAIL and we sent out a
599 	 *    broadcast we should not get any invalid messages with the
600 	 *    RPC_PROCUNAVAIL error back. Some broken RPC implementations
601 	 *    send them and for this we have to ignore them ( as we would
602 	 *    have never received them ) and look for another message
603 	 *    which might contain the valid response because we don't know
604 	 *    how many broken implementations are in the network. So we are
605 	 *    going to loop until
606 	 *    - we received a valid response
607 	 *    - we have processed all invalid responses and
608 	 *	got a time out when we try to receive again a
609 	 *	message.
610 	 *
611 	 * b) We will jump back to tryread also in case we failed
612 	 *    within the AUTH_VALIDATE. In this case we should move
613 	 *    on and loop until we received a valid response or we
614 	 *    have processed all responses with broken authentication
615 	 *    and we got a time out when we try to receive a message.
616 	 */
617 tryread:
618 	mutex_enter(&call->call_lock);
619 	interrupted = FALSE;
620 	if (call->call_notified == FALSE) {
621 		klwp_t *lwp = ttolwp(curthread);
622 		clock_t cv_wait_ret = 1; /* init to > 0 */
623 		clock_t cv_timout = timout;
624 
625 		if (lwp != NULL)
626 			lwp->lwp_nostop++;
627 
628 		cv_timout += lbolt;
629 
630 		if (h->cl_nosignal)
631 			while ((cv_wait_ret =
632 				cv_timedwait(&call->call_cv,
633 				&call->call_lock, cv_timout)) > 0 &&
634 				call->call_notified == FALSE);
635 		else
636 			while ((cv_wait_ret =
637 				cv_timedwait_sig(&call->call_cv,
638 				&call->call_lock, cv_timout)) > 0 &&
639 				call->call_notified == FALSE);
640 
641 		if (cv_wait_ret == 0)
642 			interrupted = TRUE;
643 
644 		if (lwp != NULL)
645 			lwp->lwp_nostop--;
646 	}
647 	resp = call->call_reply;
648 	call->call_reply = NULL;
649 	status = call->call_status;
650 	/*
651 	 * We have to reset the call_notified here. In case we have
652 	 * to do a retry ( e.g. in case we got a RPC_PROCUNAVAIL
653 	 * error ) we need to set this to false to ensure that
654 	 * we will wait for the next message. When the next message
655 	 * is going to arrive the function clnt_clts_dispatch_notify
656 	 * will set this to true again.
657 	 */
658 	call->call_notified = FALSE;
659 	mutex_exit(&call->call_lock);
660 
661 	if (status == RPC_TIMEDOUT) {
662 		if (interrupted) {
663 			/*
664 			 * We got interrupted, bail out
665 			 */
666 			p->cku_err.re_status = RPC_INTR;
667 			p->cku_err.re_errno = EINTR;
668 			goto done1;
669 		} else {
670 			/*
671 			 * It's possible that our response arrived
672 			 * right after we timed out.  Check to see
673 			 * if it has arrived before we remove the
674 			 * calllist from the dispatch queue.
675 			 */
676 			mutex_enter(&call->call_lock);
677 			if (call->call_notified == TRUE) {
678 				resp = call->call_reply;
679 				call->call_reply = NULL;
680 				mutex_exit(&call->call_lock);
681 				RPCLOG(8, "clnt_clts_kcallit_addr: "
682 				"response received for request "
683 				"w/xid 0x%x after timeout\n",
684 				p->cku_xid);
685 				goto getresponse;
686 			}
687 			mutex_exit(&call->call_lock);
688 
689 			RPCLOG(8, "clnt_clts_kcallit_addr: "
690 				"request w/xid 0x%x timedout "
691 				"waiting for reply\n", p->cku_xid);
692 #if 0 /* XXX not yet */
693 			/*
694 			 * Timeout may be due to a dead gateway. Send
695 			 * an ioctl downstream advising deletion of
696 			 * route when we reach the half-way point to
697 			 * timing out.
698 			 */
699 			if (stries == p->cku_retrys/2) {
700 				t_kadvise(p->cku_endpnt->e_tiptr,
701 					(uchar_t *)p->cku_addr.buf,
702 					p->cku_addr.len);
703 			}
704 #endif /* not yet */
705 			p->cku_err.re_status = RPC_TIMEDOUT;
706 			p->cku_err.re_errno = ETIMEDOUT;
707 			RCSTAT_INCR(p->cku_stats, rctimeouts);
708 			goto done1;
709 		}
710 	}
711 
712 getresponse:
713 	/*
714 	 * Check to see if a response arrived.  If it one is
715 	 * present then proceed to process the reponse.  Otherwise
716 	 * fall through to retry or retransmit the request.  This
717 	 * is probably not the optimal thing to do, but since we
718 	 * are most likely dealing with a unrealiable transport it
719 	 * is the safe thing to so.
720 	 */
721 	if (resp == NULL) {
722 		p->cku_err.re_status = RPC_CANTRECV;
723 		p->cku_err.re_errno = EIO;
724 		goto done1;
725 	}
726 
727 	/*
728 	 * Prepare the message for further processing.  We need to remove
729 	 * the datagram header and copy the source address if necessary.  No
730 	 * need to verify the header since rpcmod took care of that.
731 	 */
732 	/*
733 	 * Copy the source address if the caller has supplied a netbuf.
734 	 */
735 	if (sin != NULL) {
736 		union T_primitives *pptr;
737 
738 		pptr = (union T_primitives *)resp->b_rptr;
739 		bcopy(resp->b_rptr + pptr->unitdata_ind.SRC_offset, sin->buf,
740 			pptr->unitdata_ind.SRC_length);
741 		sin->len = pptr->unitdata_ind.SRC_length;
742 	}
743 
744 	/*
745 	 * Pop off the datagram header.
746 	 */
747 	hdrsz = resp->b_wptr - resp->b_rptr;
748 	if ((resp->b_wptr - (resp->b_rptr + hdrsz)) == 0) {
749 		tmp = resp;
750 		resp = resp->b_cont;
751 		tmp->b_cont = NULL;
752 		freeb(tmp);
753 	} else {
754 		unsigned char *ud_off = resp->b_rptr;
755 		resp->b_rptr += hdrsz;
756 		tmp = dupb(resp);
757 		if (tmp == NULL) {
758 			p->cku_err.re_status = RPC_SYSTEMERROR;
759 			p->cku_err.re_errno = ENOSR;
760 			freemsg(resp);
761 			goto done1;
762 		}
763 		tmp->b_cont = resp->b_cont;
764 		resp->b_rptr = ud_off;
765 		freeb(resp);
766 		resp = tmp;
767 	}
768 
769 	round_trip = lbolt - round_trip;
770 	/*
771 	 * Van Jacobson timer algorithm here, only if NOT a retransmission.
772 	 */
773 	if (p->cku_timers != NULL && stries == p->cku_retrys) {
774 		int rt;
775 
776 		rt = round_trip;
777 		rt -= (p->cku_timers->rt_srtt >> 3);
778 		p->cku_timers->rt_srtt += rt;
779 		if (rt < 0)
780 			rt = - rt;
781 		rt -= (p->cku_timers->rt_deviate >> 2);
782 		p->cku_timers->rt_deviate += rt;
783 		p->cku_timers->rt_rtxcur =
784 		    (clock_t)((p->cku_timers->rt_srtt >> 2) +
785 		    p->cku_timers->rt_deviate) >> 1;
786 
787 		rt = round_trip;
788 		rt -= (p->cku_timeall->rt_srtt >> 3);
789 		p->cku_timeall->rt_srtt += rt;
790 		if (rt < 0)
791 			rt = - rt;
792 		rt -= (p->cku_timeall->rt_deviate >> 2);
793 		p->cku_timeall->rt_deviate += rt;
794 		p->cku_timeall->rt_rtxcur =
795 		    (clock_t)((p->cku_timeall->rt_srtt >> 2) +
796 		    p->cku_timeall->rt_deviate) >> 1;
797 		if (p->cku_feedback != NULL) {
798 			(*p->cku_feedback)(FEEDBACK_OK, procnum,
799 			    p->cku_feedarg);
800 		}
801 	}
802 
803 	/*
804 	 * Process reply
805 	 */
806 	xdrs = &(p->cku_inxdr);
807 	xdrmblk_init(xdrs, resp, XDR_DECODE, 0);
808 
809 	reply_msg.rm_direction = REPLY;
810 	reply_msg.rm_reply.rp_stat = MSG_ACCEPTED;
811 	reply_msg.acpted_rply.ar_stat = SUCCESS;
812 	reply_msg.acpted_rply.ar_verf = _null_auth;
813 	/*
814 	 *  xdr_results will be done in AUTH_UNWRAP.
815 	 */
816 	reply_msg.acpted_rply.ar_results.where = NULL;
817 	reply_msg.acpted_rply.ar_results.proc = xdr_void;
818 
819 	/*
820 	 * Decode and validate the response.
821 	 */
822 	if (!xdr_replymsg(xdrs, &reply_msg)) {
823 		p->cku_err.re_status = RPC_CANTDECODERES;
824 		p->cku_err.re_errno = EIO;
825 		(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
826 		goto done1;
827 	}
828 
829 	_seterr_reply(&reply_msg, &(p->cku_err));
830 
831 	re_status = p->cku_err.re_status;
832 	if (re_status == RPC_SUCCESS) {
833 		/*
834 		 * Reply is good, check auth.
835 		 */
836 		if (!AUTH_VALIDATE(h->cl_auth,
837 				    &reply_msg.acpted_rply.ar_verf)) {
838 			p->cku_err.re_status = RPC_AUTHERROR;
839 			p->cku_err.re_why = AUTH_INVALIDRESP;
840 			RCSTAT_INCR(p->cku_stats, rcbadverfs);
841 			(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
842 			goto tryread;
843 		}
844 		if (!AUTH_UNWRAP(h->cl_auth, xdrs, xdr_results, resultsp)) {
845 			p->cku_err.re_status = RPC_CANTDECODERES;
846 			p->cku_err.re_errno = EIO;
847 		}
848 		(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
849 		goto done1;
850 	}
851 	/* set errno in case we can't recover */
852 	if (re_status != RPC_VERSMISMATCH &&
853 			    re_status != RPC_AUTHERROR &&
854 			    re_status != RPC_PROGVERSMISMATCH)
855 		p->cku_err.re_errno = EIO;
856 	/*
857 	 * Determine whether or not we're doing an RPC
858 	 * broadcast. Some server implementations don't
859 	 * follow RFC 1050, section 7.4.2 in that they
860 	 * don't remain silent when they see a proc
861 	 * they don't support. Therefore we keep trying
862 	 * to receive on RPC_PROCUNAVAIL, hoping to get
863 	 * a valid response from a compliant server.
864 	 */
865 	if (re_status == RPC_PROCUNAVAIL && p->cku_bcast) {
866 		(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
867 		goto tryread;
868 	}
869 	if (re_status == RPC_AUTHERROR) {
870 		/*
871 		 * Maybe our credential need to be refreshed
872 		 */
873 		if (refreshes > 0 &&
874 		    AUTH_REFRESH(h->cl_auth, &reply_msg, p->cku_cred)) {
875 			/*
876 			 * The credential is refreshed. Try the request again.
877 			 * Even if stries == 0, we still retry as long as
878 			 * refreshes > 0. This prevents a soft authentication
879 			 * error turning into a hard one at an upper level.
880 			 */
881 			refreshes--;
882 			RCSTAT_INCR(p->cku_stats, rcbadcalls);
883 			RCSTAT_INCR(p->cku_stats, rcnewcreds);
884 
885 			(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
886 			freemsg(mpdup);
887 			call_table_remove(call);
888 			mutex_enter(&call->call_lock);
889 			if (call->call_reply != NULL) {
890 				freemsg(call->call_reply);
891 				call->call_reply = NULL;
892 			}
893 			mutex_exit(&call->call_lock);
894 
895 			freemsg(resp);
896 			mpdup = NULL;
897 			goto call_again;
898 		}
899 		/*
900 		 * We have used the client handle to do an AUTH_REFRESH
901 		 * and the RPC status may be set to RPC_SUCCESS;
902 		 * Let's make sure to set it to RPC_AUTHERROR.
903 		 */
904 		p->cku_err.re_status = RPC_CANTDECODERES;
905 
906 		/*
907 		 * Map recoverable and unrecoverable
908 		 * authentication errors to appropriate errno
909 		 */
910 		switch (p->cku_err.re_why) {
911 		case AUTH_TOOWEAK:
912 			/*
913 			 * Could be an nfsportmon failure, set
914 			 * useresvport and try again.
915 			 */
916 			if (p->cku_useresvport != 1) {
917 				p->cku_useresvport = 1;
918 				(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
919 				freemsg(mpdup);
920 
921 				call_table_remove(call);
922 				mutex_enter(&call->call_lock);
923 				if (call->call_reply != NULL) {
924 					freemsg(call->call_reply);
925 					call->call_reply = NULL;
926 				}
927 				mutex_exit(&call->call_lock);
928 
929 				freemsg(resp);
930 				mpdup = NULL;
931 				endpt = p->cku_endpnt;
932 				if (endpt->e_tiptr != NULL) {
933 					mutex_enter(&endpt->e_lock);
934 					endpt->e_flags &= ~ENDPNT_BOUND;
935 					(void) t_kclose(endpt->e_tiptr, 1);
936 					endpt->e_tiptr = NULL;
937 					mutex_exit(&endpt->e_lock);
938 
939 				}
940 
941 				p->cku_xid = alloc_xid();
942 				endpnt_rele(p->cku_endpnt);
943 				p->cku_endpnt = NULL;
944 				goto call_again;
945 			}
946 			/* FALLTHRU */
947 		case AUTH_BADCRED:
948 		case AUTH_BADVERF:
949 		case AUTH_INVALIDRESP:
950 		case AUTH_FAILED:
951 		case RPCSEC_GSS_NOCRED:
952 		case RPCSEC_GSS_FAILED:
953 			p->cku_err.re_errno = EACCES;
954 			break;
955 		case AUTH_REJECTEDCRED:
956 		case AUTH_REJECTEDVERF:
957 		default:
958 			p->cku_err.re_errno = EIO;
959 			break;
960 		}
961 		RPCLOG(1, "clnt_clts_kcallit : authentication failed "
962 		    "with RPC_AUTHERROR of type %d\n",
963 		    p->cku_err.re_why);
964 	}
965 
966 	(void) xdr_rpc_free_verifier(xdrs, &reply_msg);
967 
968 done1:
969 	call_table_remove(call);
970 	mutex_enter(&call->call_lock);
971 	if (call->call_reply != NULL) {
972 		freemsg(call->call_reply);
973 		call->call_reply = NULL;
974 	}
975 	mutex_exit(&call->call_lock);
976 	RPCLOG(64, "clnt_clts_kcallit_addr: xid 0x%x taken off dispatch list",
977 		p->cku_xid);
978 
979 done:
980 	if (resp != NULL) {
981 		freemsg(resp);
982 		resp = NULL;
983 	}
984 
985 	if ((p->cku_err.re_status != RPC_SUCCESS) &&
986 	    (p->cku_err.re_status != RPC_INTR) &&
987 	    (p->cku_err.re_status != RPC_UDERROR) &&
988 	    !IS_UNRECOVERABLE_RPC(p->cku_err.re_status)) {
989 		if (p->cku_feedback != NULL && stries == p->cku_retrys) {
990 			(*p->cku_feedback)(FEEDBACK_REXMIT1, procnum,
991 			    p->cku_feedarg);
992 		}
993 
994 		timout = backoff(timout);
995 		if (p->cku_timeall != (struct rpc_timers *)0)
996 			p->cku_timeall->rt_rtxcur = timout;
997 
998 		if (p->cku_err.re_status == RPC_SYSTEMERROR ||
999 		    p->cku_err.re_status == RPC_CANTSEND) {
1000 			/*
1001 			 * Errors due to lack of resources, wait a bit
1002 			 * and try again.
1003 			 */
1004 			(void) delay(hz/10);
1005 			/* (void) sleep((caddr_t)&lbolt, PZERO-4); */
1006 		}
1007 		if (stries-- > 0) {
1008 			RCSTAT_INCR(p->cku_stats, rcretrans);
1009 			goto call_again;
1010 		}
1011 	}
1012 
1013 	if (mpdup != NULL)
1014 		freemsg(mpdup);
1015 
1016 	if (p->cku_err.re_status != RPC_SUCCESS) {
1017 		RCSTAT_INCR(p->cku_stats, rcbadcalls);
1018 	}
1019 
1020 	/*
1021 	 * Allow the endpoint to be held by the client handle in case this
1022 	 * RPC was not successful.  A retry may occur at a higher level and
1023 	 * in this case we may want to send the request over the same
1024 	 * source port.
1025 	 */
1026 	if (p->cku_err.re_status == RPC_SUCCESS && p->cku_endpnt != NULL) {
1027 		endpnt_rele(p->cku_endpnt);
1028 		p->cku_endpnt = NULL;
1029 	}
1030 
1031 	return (p->cku_err.re_status);
1032 }
1033 
1034 static enum clnt_stat
1035 clnt_clts_kcallit(CLIENT *h, rpcproc_t procnum, xdrproc_t xdr_args,
1036 	caddr_t argsp, xdrproc_t xdr_results, caddr_t resultsp,
1037 	struct timeval wait)
1038 {
1039 	return (clnt_clts_kcallit_addr(h, procnum, xdr_args, argsp,
1040 				xdr_results, resultsp, wait, NULL));
1041 }
1042 
1043 /*
1044  * Return error info on this handle.
1045  */
1046 static void
1047 clnt_clts_kerror(CLIENT *h, struct rpc_err *err)
1048 {
1049 	/* LINTED pointer alignment */
1050 	struct cku_private *p = htop(h);
1051 
1052 	*err = p->cku_err;
1053 }
1054 
1055 static bool_t
1056 clnt_clts_kfreeres(CLIENT *h, xdrproc_t xdr_res, caddr_t res_ptr)
1057 {
1058 	/* LINTED pointer alignment */
1059 	struct cku_private *p = htop(h);
1060 	XDR *xdrs;
1061 
1062 	xdrs = &(p->cku_outxdr);
1063 	xdrs->x_op = XDR_FREE;
1064 	return ((*xdr_res)(xdrs, res_ptr));
1065 }
1066 
1067 /*ARGSUSED*/
1068 static void
1069 clnt_clts_kabort(CLIENT *h)
1070 {
1071 }
1072 
1073 static bool_t
1074 clnt_clts_kcontrol(CLIENT *h, int cmd, char *arg)
1075 {
1076 	/* LINTED pointer alignment */
1077 	struct cku_private *p = htop(h);
1078 
1079 	switch (cmd) {
1080 	case CLSET_XID:
1081 		p->cku_xid = *((uint32_t *)arg);
1082 		return (TRUE);
1083 
1084 	case CLGET_XID:
1085 		*((uint32_t *)arg) = p->cku_xid;
1086 		return (TRUE);
1087 
1088 	case CLSET_BCAST:
1089 		p->cku_bcast = *((uint32_t *)arg);
1090 		return (TRUE);
1091 
1092 	case CLGET_BCAST:
1093 		*((uint32_t *)arg) = p->cku_bcast;
1094 		return (TRUE);
1095 	case CLSET_BINDRESVPORT:
1096 		if (arg == NULL)
1097 			return (FALSE);
1098 
1099 		if (*(int *)arg != 1 && *(int *)arg != 0)
1100 			return (FALSE);
1101 
1102 		p->cku_useresvport = *(int *)arg;
1103 
1104 		return (TRUE);
1105 
1106 	case CLGET_BINDRESVPORT:
1107 		if (arg == NULL)
1108 			return (FALSE);
1109 
1110 		*(int *)arg = p->cku_useresvport;
1111 
1112 		return (TRUE);
1113 
1114 	default:
1115 		return (FALSE);
1116 	}
1117 }
1118 
1119 /*
1120  * Destroy rpc handle.
1121  * Frees the space used for output buffer, private data, and handle
1122  * structure, and the file pointer/TLI data on last reference.
1123  */
1124 static void
1125 clnt_clts_kdestroy(CLIENT *h)
1126 {
1127 	/* LINTED pointer alignment */
1128 	struct cku_private *p = htop(h);
1129 	calllist_t *call = &p->cku_call;
1130 
1131 	int plen;
1132 
1133 	RPCLOG(8, "clnt_clts_kdestroy h: %p\n", (void *)h);
1134 	RPCLOG(8, "clnt_clts_kdestroy h: xid=0x%x\n", p->cku_xid);
1135 
1136 	if (p->cku_endpnt != NULL)
1137 		endpnt_rele(p->cku_endpnt);
1138 
1139 	cv_destroy(&call->call_cv);
1140 	mutex_destroy(&call->call_lock);
1141 
1142 	plen = strlen(p->cku_config.knc_protofmly) + 1;
1143 	kmem_free(p->cku_config.knc_protofmly, plen);
1144 	kmem_free(p->cku_addr.buf, p->cku_addr.maxlen);
1145 	kmem_free(p, sizeof (*p));
1146 }
1147 
1148 /*
1149  * The connectionless (CLTS) kRPC endpoint management subsystem.
1150  *
1151  * Because endpoints are potentially shared among threads making RPC calls,
1152  * they are managed in a pool according to type (endpnt_type_t).  Each
1153  * endpnt_type_t points to a list of usable endpoints through the e_pool
1154  * field, which is of type list_t.  list_t is a doubly-linked list.
1155  * The number of endpoints in the pool is stored in the e_cnt field of
1156  * endpnt_type_t and the endpoints are reference counted using the e_ref field
1157  * in the endpnt_t structure.
1158  *
1159  * As an optimization, endpoints that have no references are also linked
1160  * to an idle list via e_ilist which is also of type list_t.  When a thread
1161  * calls endpnt_get() to obtain a transport endpoint, the idle list is first
1162  * consulted and if such an endpoint exists, it is removed from the idle list
1163  * and returned to the caller.
1164  *
1165  * If the idle list is empty, then a check is made to see if more endpoints
1166  * can be created.  If so, we proceed and create a new endpoint which is added
1167  * to the pool and returned to the caller.  If we have reached the limit and
1168  * cannot make a new endpoint then one is returned to the caller via round-
1169  * robin policy.
1170  *
1171  * When an endpoint is placed on the idle list by a thread calling
1172  * endpnt_rele(), it is timestamped and then a reaper taskq is scheduled to
1173  * be dispatched if one hasn't already been.  When the timer fires, the
1174  * taskq traverses the idle list and checks to see which endpoints are
1175  * eligible to be closed.  It determines this by checking if the timestamp
1176  * when the endpoint was released has exceeded the the threshold for how long
1177  * it should stay alive.
1178  *
1179  * endpnt_t structures remain persistent until the memory reclaim callback,
1180  * endpnt_reclaim(), is invoked.
1181  *
1182  * Here is an example of how the data structures would be laid out by the
1183  * subsystem:
1184  *
1185  *       endpnt_type_t
1186  *
1187  *	 loopback		                  inet
1188  *	 _______________	                  ______________
1189  *	| e_next        |----------------------->| e_next       |---->>
1190  *	| e_pool        |<---+                   | e_pool       |<----+
1191  *	| e_ilist       |<---+--+                | e_ilist      |<----+--+
1192  *   +->| e_pcurr       |----+--+--+	      +->| e_pcurr      |-----+--+--+
1193  *   |	| ...           |    |  |  |	      |	 | ...	        |     |  |  |
1194  *   |	| e_itimer (90) |    |  |  |	      |	 | e_itimer (0) |     |  |  |
1195  *   |	| e_cnt (1)     |    |  |  |	      |	 | e_cnt (3)    |     |  |  |
1196  *   |	+---------------+    |  |  |	      |	 +--------------+     |  |  |
1197  *   |			     |  |  |	      |			      |  |  |
1198  *   |   endpnt_t            |  |  |          |	                      |  |  |
1199  *   |	 ____________        |  |  |	      |	  ____________        |  |  |
1200  *   |	| e_node     |<------+  |  |	      |	 | e_node     |<------+  |  |
1201  *   |	| e_idle     |<---------+  |	      |	 | e_idle     |       |  |  |
1202  *   +--| e_type     |<------------+	      +--| e_type     |       |  |  |
1203  *	| e_tiptr    |                        |  | e_tiptr    |       |  |  |
1204  *      | ...	     |		              |	 | ...	      |       |  |  |
1205  *	| e_lock     |		              |	 | e_lock     |       |  |  |
1206  *	| ...        |		              |	 | ...	      |       |  |  |
1207  *      | e_ref (0)  |		              |	 | e_ref (2)  |       |  |  |
1208  *	| e_itime    |	                      |	 | e_itime    |       |  |  |
1209  *	+------------+		              |	 +------------+       |  |  |
1210  *					      |			      |  |  |
1211  *					      |			      |  |  |
1212  *					      |	  ____________        |  |  |
1213  *					      |	 | e_node     |<------+  |  |
1214  *					      |	 | e_idle     |<------+--+  |
1215  *					      +--| e_type     |       |     |
1216  *					      |	 | e_tiptr    |       |     |
1217  *					      |	 | ...	      |       |     |
1218  *					      |	 | e_lock     |       |     |
1219  *					      |	 | ...	      |       |     |
1220  *					      |	 | e_ref (0)  |       |     |
1221  *					      |	 | e_itime    |       |     |
1222  *					      |	 +------------+       |     |
1223  *					      |			      |     |
1224  *					      |			      |     |
1225  *					      |	  ____________        |     |
1226  *					      |	 | e_node     |<------+     |
1227  *					      |	 | e_idle     |             |
1228  *					      +--| e_type     |<------------+
1229  *						 | e_tiptr    |
1230  *						 | ...	      |
1231  *						 | e_lock     |
1232  *						 | ...	      |
1233  *						 | e_ref (1)  |
1234  *						 | e_itime    |
1235  *						 +------------+
1236  *
1237  * Endpoint locking strategy:
1238  *
1239  * The following functions manipulate lists which hold the endpoint and the
1240  * endpoints themselves:
1241  *
1242  * endpnt_get()/check_endpnt()/endpnt_rele()/endpnt_reap()/do_endpnt_reclaim()
1243  *
1244  * Lock description follows:
1245  *
1246  * endpnt_type_lock: Global reader/writer lock which protects accesses to the
1247  *		     endpnt_type_list.
1248  *
1249  * e_plock: Lock defined in the endpnt_type_t.  It is intended to
1250  *	    protect accesses to the pool of endopints (e_pool) for a given
1251  *	    endpnt_type_t.
1252  *
1253  * e_ilock: Lock defined in endpnt_type_t.  It is intended to protect accesses
1254  *	    to the idle list (e_ilist) of available endpoints for a given
1255  *	    endpnt_type_t.  It also protects access to the e_itimer, e_async_cv,
1256  *	    and e_async_count fields in endpnt_type_t.
1257  *
1258  * e_lock: Lock defined in the endpnt structure.  It is intended to protect
1259  *	   flags, cv, and ref count.
1260  *
1261  * The order goes as follows so as not to induce deadlock.
1262  *
1263  * endpnt_type_lock -> e_plock -> e_ilock -> e_lock
1264  *
1265  * Interaction with Zones and shutting down:
1266  *
1267  * endpnt_type_ts are uniquely identified by the (e_zoneid, e_rdev, e_protofmly)
1268  * tuple, which means that a zone may not reuse another zone's idle endpoints
1269  * without first doing a t_kclose().
1270  *
1271  * A zone's endpnt_type_ts are destroyed when a zone is shut down; e_async_cv
1272  * and e_async_count are used to keep track of the threads in endpnt_taskq
1273  * trying to reap endpnt_ts in the endpnt_type_t.
1274  */
1275 
1276 /*
1277  * Allocate and initialize an endpnt_type_t
1278  */
1279 static struct endpnt_type *
1280 endpnt_type_create(struct knetconfig *config)
1281 {
1282 	struct endpnt_type	*etype;
1283 
1284 	/*
1285 	 * Allocate a new endpoint type to hang a list of
1286 	 * endpoints off of it.
1287 	 */
1288 	etype = kmem_alloc(sizeof (struct endpnt_type), KM_SLEEP);
1289 	etype->e_next = NULL;
1290 	etype->e_pcurr = NULL;
1291 	etype->e_itimer = 0;
1292 	etype->e_cnt = 0;
1293 
1294 	(void) strncpy(etype->e_protofmly, config->knc_protofmly, KNC_STRSIZE);
1295 	mutex_init(&etype->e_plock, NULL, MUTEX_DEFAULT, NULL);
1296 	mutex_init(&etype->e_ilock, NULL, MUTEX_DEFAULT, NULL);
1297 	etype->e_rdev = config->knc_rdev;
1298 	etype->e_zoneid = rpc_zoneid();
1299 	etype->e_async_count = 0;
1300 	cv_init(&etype->e_async_cv, NULL, CV_DEFAULT, NULL);
1301 
1302 	list_create(&etype->e_pool, sizeof (endpnt_t),
1303 			offsetof(endpnt_t, e_node));
1304 	list_create(&etype->e_ilist, sizeof (endpnt_t),
1305 			offsetof(endpnt_t, e_idle));
1306 
1307 	/*
1308 	 * Check to see if we need to create a taskq for endpoint
1309 	 * reaping
1310 	 */
1311 	mutex_enter(&endpnt_taskq_lock);
1312 	if (taskq_created == FALSE) {
1313 		taskq_created = TRUE;
1314 		mutex_exit(&endpnt_taskq_lock);
1315 		ASSERT(endpnt_taskq == NULL);
1316 		endpnt_taskq = taskq_create("clts_endpnt_taskq", 1,
1317 						minclsyspri, 200, INT_MAX, 0);
1318 	} else
1319 		mutex_exit(&endpnt_taskq_lock);
1320 
1321 	return (etype);
1322 }
1323 
1324 /*
1325  * Free an endpnt_type_t
1326  */
1327 static void
1328 endpnt_type_free(struct endpnt_type *etype)
1329 {
1330 	mutex_destroy(&etype->e_plock);
1331 	mutex_destroy(&etype->e_ilock);
1332 	list_destroy(&etype->e_pool);
1333 	list_destroy(&etype->e_ilist);
1334 	kmem_free(etype, sizeof (endpnt_type_t));
1335 }
1336 
1337 /*
1338  * Check the endpoint to ensure that it is suitable for use.
1339  *
1340  * Possible return values:
1341  *
1342  * return (1) - Endpoint is established, but needs to be re-opened.
1343  * return (0) && *newp == NULL - Endpoint is established, but unusable.
1344  * return (0) && *newp != NULL - Endpoint is established and usable.
1345  */
1346 static int
1347 check_endpnt(struct endpnt *endp, struct endpnt **newp)
1348 {
1349 	*newp = endp;
1350 
1351 	mutex_enter(&endp->e_lock);
1352 	ASSERT(endp->e_ref >= 1);
1353 
1354 	/*
1355 	 * The first condition we check for is if the endpoint has been
1356 	 * allocated, but is unusable either because it has been closed or
1357 	 * has been marked stale.  Only *one* thread will be allowed to
1358 	 * execute the then clause.  This is enforced becuase the first thread
1359 	 * to check this condition will clear the flags, so that subsequent
1360 	 * thread(s) checking this endpoint will move on.
1361 	 */
1362 	if ((endp->e_flags & ENDPNT_ESTABLISHED) &&
1363 		(!(endp->e_flags & ENDPNT_BOUND) ||
1364 		(endp->e_flags & ENDPNT_STALE))) {
1365 		/*
1366 		 * Clear the flags here since they will be
1367 		 * set again by this thread.  They need to be
1368 		 * individually cleared because we want to maintain
1369 		 * the state for ENDPNT_ONIDLE.
1370 		 */
1371 		endp->e_flags &= ~(ENDPNT_ESTABLISHED |
1372 				ENDPNT_WAITING | ENDPNT_BOUND |	ENDPNT_STALE);
1373 		mutex_exit(&endp->e_lock);
1374 		return (1);
1375 	}
1376 
1377 	/*
1378 	 * The second condition is meant for any thread that is waiting for
1379 	 * an endpoint to become established.  It will cv_wait() until
1380 	 * the condition for the endpoint has been changed to ENDPNT_BOUND or
1381 	 * ENDPNT_STALE.
1382 	 */
1383 	while (!(endp->e_flags & ENDPNT_BOUND) &&
1384 		!(endp->e_flags & ENDPNT_STALE)) {
1385 		endp->e_flags |= ENDPNT_WAITING;
1386 		cv_wait(&endp->e_cv, &endp->e_lock);
1387 	}
1388 
1389 	ASSERT(endp->e_flags & ENDPNT_ESTABLISHED);
1390 
1391 	/*
1392 	 * The last case we check for is if the endpoint has been marked stale.
1393 	 * If this is the case then set *newp to NULL and return, so that the
1394 	 * caller is notified of the error and can take appropriate action.
1395 	 */
1396 	if (endp->e_flags & ENDPNT_STALE) {
1397 		endp->e_ref--;
1398 		*newp = NULL;
1399 	}
1400 	mutex_exit(&endp->e_lock);
1401 	return (0);
1402 }
1403 
1404 #ifdef DEBUG
1405 /*
1406  * Provide a fault injection setting to test error conditions.
1407  */
1408 static int endpnt_get_return_null = 0;
1409 #endif
1410 
1411 /*
1412  * Returns a handle (struct endpnt *) to an open and bound endpoint
1413  * specified by the knetconfig passed in.  Returns NULL if no valid endpoint
1414  * can be obtained.
1415  */
1416 static struct endpnt *
1417 endpnt_get(struct knetconfig *config, int useresvport)
1418 {
1419 	struct endpnt_type	*n_etype = NULL;
1420 	struct endpnt_type	*np = NULL;
1421 	struct endpnt		*new = NULL;
1422 	struct endpnt		*endp = NULL;
1423 	struct endpnt		*next = NULL;
1424 	TIUSER			*tiptr = NULL;
1425 	int			rtries = BINDRESVPORT_RETRIES;
1426 	int			i = 0;
1427 	int			error;
1428 	int			retval;
1429 	zoneid_t		zoneid = rpc_zoneid();
1430 	cred_t			*cr;
1431 
1432 	RPCLOG(1, "endpnt_get: protofmly %s, ", config->knc_protofmly);
1433 	RPCLOG(1, "rdev %ld\n", config->knc_rdev);
1434 
1435 #ifdef DEBUG
1436 	/*
1437 	 * Inject fault if desired.  Pretend we have a stale endpoint
1438 	 * and return NULL.
1439 	 */
1440 	if (endpnt_get_return_null > 0) {
1441 		endpnt_get_return_null--;
1442 		return (NULL);
1443 	}
1444 #endif
1445 	rw_enter(&endpnt_type_lock, RW_READER);
1446 
1447 top:
1448 	for (np = endpnt_type_list; np != NULL; np = np->e_next)
1449 		if ((np->e_zoneid == zoneid) &&
1450 		    (np->e_rdev == config->knc_rdev) &&
1451 		    (strcmp(np->e_protofmly,
1452 			    config->knc_protofmly) == 0))
1453 			break;
1454 
1455 	if (np == NULL && n_etype != NULL) {
1456 		ASSERT(rw_write_held(&endpnt_type_lock));
1457 
1458 		/*
1459 		 * Link the endpoint type onto the list
1460 		 */
1461 		n_etype->e_next = endpnt_type_list;
1462 		endpnt_type_list = n_etype;
1463 		np = n_etype;
1464 		n_etype = NULL;
1465 	}
1466 
1467 	if (np == NULL) {
1468 		/*
1469 		 * The logic here is that we were unable to find an
1470 		 * endpnt_type_t that matched our criteria, so we allocate a
1471 		 * new one.  Because kmem_alloc() needs to be called with
1472 		 * KM_SLEEP, we drop our locks so that we don't induce
1473 		 * deadlock.  After allocating and initializing the
1474 		 * endpnt_type_t, we reaquire the lock and go back to check
1475 		 * if this entry needs to be added to the list.  Since we do
1476 		 * some operations without any locking other threads may
1477 		 * have been looking for the same endpnt_type_t and gone
1478 		 * through this code path.  We check for this case and allow
1479 		 * one thread to link its endpnt_type_t to the list and the
1480 		 * other threads will simply free theirs.
1481 		 */
1482 		rw_exit(&endpnt_type_lock);
1483 		n_etype = endpnt_type_create(config);
1484 
1485 		/*
1486 		 * We need to reaquire the lock with RW_WRITER here so that
1487 		 * we can safely link the new endpoint type onto the list.
1488 		 */
1489 		rw_enter(&endpnt_type_lock, RW_WRITER);
1490 		goto top;
1491 	}
1492 
1493 	rw_exit(&endpnt_type_lock);
1494 	/*
1495 	 * If n_etype is not NULL, then another thread was able to
1496 	 * insert an endpnt_type_t of this type  onto the list before
1497 	 * we did.  Go ahead and free ours.
1498 	 */
1499 	if (n_etype != NULL)
1500 		endpnt_type_free(n_etype);
1501 
1502 	mutex_enter(&np->e_ilock);
1503 	/*
1504 	 * The algorithm to hand out endpoints is to first
1505 	 * give out those that are idle if such endpoints
1506 	 * exist.  Otherwise, create a new one if we haven't
1507 	 * reached the max threshold.  Finally, we give out
1508 	 * endpoints in a pseudo LRU fashion (round-robin).
1509 	 *
1510 	 * Note:  The idle list is merely a hint of those endpoints
1511 	 * that should be idle.  There exists a window after the
1512 	 * endpoint is released and before it is linked back onto the
1513 	 * idle list where a thread could get a reference to it and
1514 	 * use it.  This is okay, since the reference counts will
1515 	 * still be consistent.
1516 	 */
1517 	if ((endp = (endpnt_t *)list_head(&np->e_ilist)) != NULL) {
1518 		timeout_id_t t_id = 0;
1519 
1520 		mutex_enter(&endp->e_lock);
1521 		endp->e_ref++;
1522 		endp->e_itime = 0;
1523 		endp->e_flags &= ~ENDPNT_ONIDLE;
1524 		mutex_exit(&endp->e_lock);
1525 
1526 		/*
1527 		 * Pop the endpoint off the idle list and hand it off
1528 		 */
1529 		list_remove(&np->e_ilist, endp);
1530 
1531 		if (np->e_itimer != 0) {
1532 			t_id = np->e_itimer;
1533 			np->e_itimer = 0;
1534 		}
1535 		mutex_exit(&np->e_ilock);
1536 		/*
1537 		 * Reset the idle timer if it has been set
1538 		 */
1539 		if (t_id != (timeout_id_t)0)
1540 			(void) untimeout(t_id);
1541 
1542 		if (check_endpnt(endp, &new) == 0)
1543 			return (new);
1544 	} else if (np->e_cnt >= clnt_clts_max_endpoints) {
1545 		/*
1546 		 * There are no idle endpoints currently, so
1547 		 * create a new one if we have not reached the maximum or
1548 		 * hand one out in round-robin.
1549 		 */
1550 		mutex_exit(&np->e_ilock);
1551 		mutex_enter(&np->e_plock);
1552 		endp = np->e_pcurr;
1553 		mutex_enter(&endp->e_lock);
1554 		endp->e_ref++;
1555 		mutex_exit(&endp->e_lock);
1556 
1557 		ASSERT(endp != NULL);
1558 		/*
1559 		 * Advance the pointer to the next eligible endpoint, if
1560 		 * necessary.
1561 		 */
1562 		if (np->e_cnt > 1) {
1563 			next = (endpnt_t *)list_next(&np->e_pool, np->e_pcurr);
1564 			if (next == NULL)
1565 				next = (endpnt_t *)list_head(&np->e_pool);
1566 			np->e_pcurr = next;
1567 		}
1568 
1569 		mutex_exit(&np->e_plock);
1570 
1571 		/*
1572 		 * We need to check to see if this endpoint is bound or
1573 		 * not.  If it is in progress then just wait until
1574 		 * the set up is complete
1575 		 */
1576 		if (check_endpnt(endp, &new) == 0)
1577 			return (new);
1578 	} else {
1579 		mutex_exit(&np->e_ilock);
1580 		mutex_enter(&np->e_plock);
1581 
1582 		/*
1583 		 * Allocate a new endpoint to use.  If we can't allocate any
1584 		 * more memory then use one that is already established if any
1585 		 * such endpoints exist.
1586 		 */
1587 		new = kmem_cache_alloc(endpnt_cache, KM_NOSLEEP);
1588 		if (new == NULL) {
1589 			RPCLOG0(1, "endpnt_get: kmem_cache_alloc failed\n");
1590 			/*
1591 			 * Try to recover by using an existing endpoint.
1592 			 */
1593 			if (np->e_cnt <= 0) {
1594 				mutex_exit(&np->e_plock);
1595 				return (NULL);
1596 			}
1597 			endp = np->e_pcurr;
1598 			if ((next = list_next(&np->e_pool, np->e_pcurr)) !=
1599 				NULL)
1600 				np->e_pcurr = next;
1601 			ASSERT(endp != NULL);
1602 			mutex_enter(&endp->e_lock);
1603 			endp->e_ref++;
1604 			mutex_exit(&endp->e_lock);
1605 			mutex_exit(&np->e_plock);
1606 
1607 			if (check_endpnt(endp, &new) == 0)
1608 				return (new);
1609 		} else {
1610 			/*
1611 			 * Partially init an endpoint structure and put
1612 			 * it on the list, so that other interested threads
1613 			 * know that one is being created
1614 			 */
1615 			bzero(new, sizeof (struct endpnt));
1616 
1617 			cv_init(&new->e_cv, NULL, CV_DEFAULT, NULL);
1618 			mutex_init(&new->e_lock, NULL, MUTEX_DEFAULT, NULL);
1619 			new->e_ref = 1;
1620 			new->e_type = np;
1621 
1622 			/*
1623 			 * Link the endpoint into the pool.
1624 			 */
1625 			list_insert_head(&np->e_pool, new);
1626 			np->e_cnt++;
1627 			if (np->e_pcurr == NULL)
1628 				np->e_pcurr = new;
1629 			mutex_exit(&np->e_plock);
1630 		}
1631 	}
1632 
1633 	/*
1634 	 * The transport should be opened with sufficient privs
1635 	 */
1636 	cr = zone_kcred();
1637 	error = t_kopen(NULL, config->knc_rdev, FREAD|FWRITE|FNDELAY, &tiptr,
1638 	    cr);
1639 	if (error) {
1640 		RPCLOG(1, "endpnt_get: t_kopen: %d\n", error);
1641 		goto bad;
1642 	}
1643 
1644 	new->e_tiptr = tiptr;
1645 	rpc_poptimod(tiptr->fp->f_vnode);
1646 
1647 	/*
1648 	 * Allow the kernel to push the module on behalf of the user.
1649 	 */
1650 	error = strioctl(tiptr->fp->f_vnode, I_PUSH, (intptr_t)"rpcmod", 0,
1651 	    K_TO_K, cr, &retval);
1652 	if (error) {
1653 		RPCLOG(1, "endpnt_get: kstr_push on rpcmod failed %d\n", error);
1654 		goto bad;
1655 	}
1656 
1657 	error = strioctl(tiptr->fp->f_vnode, RPC_CLIENT, 0, 0, K_TO_K,
1658 	    cr, &retval);
1659 	if (error) {
1660 		RPCLOG(1, "endpnt_get: strioctl failed %d\n", error);
1661 		goto bad;
1662 	}
1663 
1664 	/*
1665 	 * Connectionless data flow should bypass the stream head.
1666 	 */
1667 	new->e_wq = tiptr->fp->f_vnode->v_stream->sd_wrq->q_next;
1668 
1669 	error = strioctl(tiptr->fp->f_vnode, I_PUSH, (intptr_t)"timod", 0,
1670 	    K_TO_K, cr, &retval);
1671 	if (error) {
1672 		RPCLOG(1, "endpnt_get: kstr_push on timod failed %d\n", error);
1673 		goto bad;
1674 	}
1675 
1676 	/*
1677 	 * Attempt to bind the endpoint.  If we fail then propogate
1678 	 * error back to calling subsystem, so that it can be handled
1679 	 * appropriately.
1680 	 * If the caller has not specified reserved port usage then
1681 	 * take the system default.
1682 	 */
1683 	if (useresvport == -1)
1684 		useresvport = clnt_clts_do_bindresvport;
1685 
1686 	if (useresvport &&
1687 	    (strcmp(config->knc_protofmly, NC_INET) == 0 ||
1688 		strcmp(config->knc_protofmly, NC_INET6) == 0)) {
1689 
1690 		while ((error =
1691 			bindresvport(new->e_tiptr, NULL, NULL, FALSE)) != 0) {
1692 			RPCLOG(1,
1693 				"endpnt_get: bindresvport error %d\n",
1694 				error);
1695 			if (error != EPROTO) {
1696 				if (rtries-- <= 0)
1697 					goto bad;
1698 
1699 				delay(hz << i++);
1700 				continue;
1701 			}
1702 
1703 			(void) t_kclose(new->e_tiptr, 1);
1704 			/*
1705 			 * reopen with all privileges
1706 			 */
1707 			error = t_kopen(NULL, config->knc_rdev,
1708 			    FREAD|FWRITE|FNDELAY,
1709 			    &new->e_tiptr, cr);
1710 			if (error) {
1711 				RPCLOG(1, "endpnt_get: t_kopen: %d\n", error);
1712 					new->e_tiptr = NULL;
1713 					goto bad;
1714 			}
1715 		}
1716 	} else if ((error = t_kbind(new->e_tiptr, NULL, NULL)) != 0) {
1717 		RPCLOG(1, "endpnt_get: t_kbind failed: %d\n", error);
1718 		goto bad;
1719 	}
1720 
1721 	/*
1722 	 * Set the flags and notify and waiters that we have an established
1723 	 * endpoint.
1724 	 */
1725 	mutex_enter(&new->e_lock);
1726 	new->e_flags |= ENDPNT_ESTABLISHED;
1727 	new->e_flags |= ENDPNT_BOUND;
1728 	if (new->e_flags & ENDPNT_WAITING) {
1729 		cv_broadcast(&new->e_cv);
1730 		new->e_flags &= ~ENDPNT_WAITING;
1731 	}
1732 	mutex_exit(&new->e_lock);
1733 
1734 	return (new);
1735 
1736 bad:
1737 	ASSERT(new != NULL);
1738 	/*
1739 	 * mark this endpoint as stale and notify any threads waiting
1740 	 * on this endpoint that it will be going away.
1741 	 */
1742 	mutex_enter(&new->e_lock);
1743 	if (new->e_ref > 0) {
1744 		new->e_flags |= ENDPNT_ESTABLISHED;
1745 		new->e_flags |= ENDPNT_STALE;
1746 		if (new->e_flags & ENDPNT_WAITING) {
1747 			cv_broadcast(&new->e_cv);
1748 			new->e_flags &= ~ENDPNT_WAITING;
1749 		}
1750 	}
1751 	new->e_ref--;
1752 	new->e_tiptr = NULL;
1753 	mutex_exit(&new->e_lock);
1754 
1755 	/*
1756 	 * If there was a transport endopoint opened, then close it.
1757 	 */
1758 	if (tiptr != NULL)
1759 		(void) t_kclose(tiptr, 1);
1760 
1761 	return (NULL);
1762 }
1763 
1764 /*
1765  * Release a referece to the endpoint
1766  */
1767 static void
1768 endpnt_rele(struct endpnt *sp)
1769 {
1770 	mutex_enter(&sp->e_lock);
1771 	ASSERT(sp->e_ref > 0);
1772 	sp->e_ref--;
1773 	/*
1774 	 * If the ref count is zero, then start the idle timer and link
1775 	 * the endpoint onto the idle list.
1776 	 */
1777 	if (sp->e_ref == 0) {
1778 		sp->e_itime = gethrestime_sec();
1779 
1780 		/*
1781 		 * Check to see if the endpoint is already linked to the idle
1782 		 * list, so that we don't try to reinsert it.
1783 		 */
1784 		if (sp->e_flags & ENDPNT_ONIDLE) {
1785 			mutex_exit(&sp->e_lock);
1786 			mutex_enter(&sp->e_type->e_ilock);
1787 			endpnt_reap_settimer(sp->e_type);
1788 			mutex_exit(&sp->e_type->e_ilock);
1789 			return;
1790 		}
1791 
1792 		sp->e_flags |= ENDPNT_ONIDLE;
1793 		mutex_exit(&sp->e_lock);
1794 		mutex_enter(&sp->e_type->e_ilock);
1795 		list_insert_tail(&sp->e_type->e_ilist, sp);
1796 		endpnt_reap_settimer(sp->e_type);
1797 		mutex_exit(&sp->e_type->e_ilock);
1798 	} else
1799 		mutex_exit(&sp->e_lock);
1800 }
1801 
1802 static void
1803 endpnt_reap_settimer(endpnt_type_t *etp)
1804 {
1805 	if (etp->e_itimer == (timeout_id_t)0)
1806 		etp->e_itimer = timeout(endpnt_reap_dispatch, (void *)etp,
1807 					clnt_clts_taskq_dispatch_interval);
1808 }
1809 
1810 static void
1811 endpnt_reap_dispatch(void *a)
1812 {
1813 	endpnt_type_t *etp = a;
1814 
1815 	/*
1816 	 * The idle timer has fired, so dispatch the taskq to close the
1817 	 * endpoint.
1818 	 */
1819 	if (taskq_dispatch(endpnt_taskq, (task_func_t *)endpnt_reap, etp,
1820 	    TQ_NOSLEEP) == NULL)
1821 		return;
1822 	mutex_enter(&etp->e_ilock);
1823 	etp->e_async_count++;
1824 	mutex_exit(&etp->e_ilock);
1825 }
1826 
1827 /*
1828  * Traverse the idle list and close those endpoints that have reached their
1829  * timeout interval.
1830  */
1831 static void
1832 endpnt_reap(endpnt_type_t *etp)
1833 {
1834 	struct endpnt *e;
1835 	struct endpnt *next_node = NULL;
1836 
1837 	mutex_enter(&etp->e_ilock);
1838 	e = list_head(&etp->e_ilist);
1839 	while (e != NULL) {
1840 		next_node = list_next(&etp->e_ilist, e);
1841 
1842 		mutex_enter(&e->e_lock);
1843 		if (e->e_ref > 0) {
1844 			mutex_exit(&e->e_lock);
1845 			e = next_node;
1846 			continue;
1847 		}
1848 
1849 		ASSERT(e->e_ref == 0);
1850 		if (e->e_itime > 0 &&
1851 		    (e->e_itime + clnt_clts_endpoint_reap_interval) <
1852 		    gethrestime_sec()) {
1853 			e->e_flags &= ~ENDPNT_BOUND;
1854 			(void) t_kclose(e->e_tiptr, 1);
1855 			e->e_tiptr = NULL;
1856 			e->e_itime = 0;
1857 		}
1858 		mutex_exit(&e->e_lock);
1859 		e = next_node;
1860 	}
1861 	etp->e_itimer = 0;
1862 	if (--etp->e_async_count == 0)
1863 		cv_signal(&etp->e_async_cv);
1864 	mutex_exit(&etp->e_ilock);
1865 }
1866 
1867 static void
1868 endpnt_reclaim(zoneid_t zoneid)
1869 {
1870 	struct endpnt_type *np;
1871 	struct endpnt *e;
1872 	struct endpnt *next_node = NULL;
1873 	list_t free_list;
1874 	int rcnt = 0;
1875 
1876 	list_create(&free_list, sizeof (endpnt_t), offsetof(endpnt_t, e_node));
1877 
1878 	RPCLOG0(1, "endpnt_reclaim: reclaim callback started\n");
1879 	rw_enter(&endpnt_type_lock, RW_READER);
1880 	for (np = endpnt_type_list; np != NULL; np = np->e_next) {
1881 		if (zoneid != ALL_ZONES && zoneid != np->e_zoneid)
1882 			continue;
1883 
1884 		mutex_enter(&np->e_plock);
1885 		RPCLOG(1, "endpnt_reclaim: protofmly %s, ",
1886 			np->e_protofmly);
1887 		RPCLOG(1, "rdev %ld\n", np->e_rdev);
1888 		RPCLOG(1, "endpnt_reclaim: found %d endpoint(s)\n",
1889 			np->e_cnt);
1890 
1891 		if (np->e_cnt == 0) {
1892 			mutex_exit(&np->e_plock);
1893 			continue;
1894 		}
1895 
1896 		/*
1897 		 * The nice thing about maintaining an idle list is that if
1898 		 * there are any endpoints to reclaim, they are going to be
1899 		 * on this list.  Just go through and reap the one's that
1900 		 * have ref counts of zero.
1901 		 */
1902 		mutex_enter(&np->e_ilock);
1903 		e = list_head(&np->e_ilist);
1904 		while (e != NULL) {
1905 			next_node = list_next(&np->e_ilist, e);
1906 			mutex_enter(&e->e_lock);
1907 			if (e->e_ref > 0) {
1908 				mutex_exit(&e->e_lock);
1909 				e = next_node;
1910 				continue;
1911 			}
1912 			ASSERT(e->e_ref == 0);
1913 			mutex_exit(&e->e_lock);
1914 
1915 			list_remove(&np->e_ilist, e);
1916 			list_remove(&np->e_pool, e);
1917 			list_insert_head(&free_list, e);
1918 
1919 			rcnt++;
1920 			np->e_cnt--;
1921 			e = next_node;
1922 		}
1923 		mutex_exit(&np->e_ilock);
1924 		/*
1925 		 * Reset the current pointer to be safe
1926 		 */
1927 		if ((e = (struct endpnt *)list_head(&np->e_pool)) != NULL)
1928 			np->e_pcurr = e;
1929 		else {
1930 			ASSERT(np->e_cnt == 0);
1931 			np->e_pcurr = NULL;
1932 		}
1933 
1934 		mutex_exit(&np->e_plock);
1935 	}
1936 	rw_exit(&endpnt_type_lock);
1937 
1938 	while ((e = list_head(&free_list)) != NULL) {
1939 		list_remove(&free_list, e);
1940 		if (e->e_tiptr != NULL)
1941 			(void) t_kclose(e->e_tiptr, 1);
1942 
1943 		cv_destroy(&e->e_cv);
1944 		mutex_destroy(&e->e_lock);
1945 		kmem_cache_free(endpnt_cache, e);
1946 	}
1947 	list_destroy(&free_list);
1948 	RPCLOG(1, "endpnt_reclaim: reclaimed %d endpoint(s)\n", rcnt);
1949 }
1950 
1951 /*
1952  * Endpoint reclaim zones destructor callback routine.
1953  *
1954  * After reclaiming any cached entries, we basically go through the endpnt_type
1955  * list, canceling outstanding timeouts and free'ing data structures.
1956  */
1957 /* ARGSUSED */
1958 static void
1959 endpnt_destructor(zoneid_t zoneid, void *a)
1960 {
1961 	struct endpnt_type **npp;
1962 	struct endpnt_type *np;
1963 	struct endpnt_type *free_list = NULL;
1964 	timeout_id_t t_id = 0;
1965 	extern void clcleanup_zone(zoneid_t);
1966 	extern void clcleanup4_zone(zoneid_t);
1967 
1968 	/* Make sure NFS client handles are released. */
1969 	clcleanup_zone(zoneid);
1970 	clcleanup4_zone(zoneid);
1971 
1972 	endpnt_reclaim(zoneid);
1973 	/*
1974 	 * We don't need to be holding on to any locks across the call to
1975 	 * endpnt_reclaim() and the code below; we know that no-one can
1976 	 * be holding open connections for this zone (all processes and kernel
1977 	 * threads are gone), so nothing could be adding anything to the list.
1978 	 */
1979 	rw_enter(&endpnt_type_lock, RW_WRITER);
1980 	npp = &endpnt_type_list;
1981 	while ((np = *npp) != NULL) {
1982 		if (np->e_zoneid != zoneid) {
1983 			npp = &np->e_next;
1984 			continue;
1985 		}
1986 		mutex_enter(&np->e_plock);
1987 		mutex_enter(&np->e_ilock);
1988 		if (np->e_itimer != 0) {
1989 			t_id = np->e_itimer;
1990 			np->e_itimer = 0;
1991 		}
1992 		ASSERT(np->e_cnt == 0);
1993 		ASSERT(list_head(&np->e_pool) == NULL);
1994 		ASSERT(list_head(&np->e_ilist) == NULL);
1995 
1996 		mutex_exit(&np->e_ilock);
1997 		mutex_exit(&np->e_plock);
1998 
1999 		/*
2000 		 * untimeout() any outstanding timers that have not yet fired.
2001 		 */
2002 		if (t_id != (timeout_id_t)0)
2003 			(void) untimeout(t_id);
2004 		*npp = np->e_next;
2005 		np->e_next = free_list;
2006 		free_list = np;
2007 	}
2008 	rw_exit(&endpnt_type_lock);
2009 
2010 	while (free_list != NULL) {
2011 		np = free_list;
2012 		free_list = free_list->e_next;
2013 		/*
2014 		 * Wait for threads in endpnt_taskq trying to reap endpnt_ts in
2015 		 * the endpnt_type_t.
2016 		 */
2017 		mutex_enter(&np->e_ilock);
2018 		while (np->e_async_count > 0)
2019 			cv_wait(&np->e_async_cv, &np->e_ilock);
2020 		cv_destroy(&np->e_async_cv);
2021 		mutex_destroy(&np->e_plock);
2022 		mutex_destroy(&np->e_ilock);
2023 		list_destroy(&np->e_pool);
2024 		list_destroy(&np->e_ilist);
2025 		kmem_free(np, sizeof (endpnt_type_t));
2026 	}
2027 }
2028 
2029 /*
2030  * Endpoint reclaim kmem callback routine.
2031  */
2032 /* ARGSUSED */
2033 static void
2034 endpnt_repossess(void *a)
2035 {
2036 	/*
2037 	 * Reclaim idle endpnt's from all zones.
2038 	 */
2039 	if (endpnt_taskq != NULL)
2040 		(void) taskq_dispatch(endpnt_taskq,
2041 		    (task_func_t *)endpnt_reclaim, (void *)ALL_ZONES,
2042 		    TQ_NOSLEEP);
2043 }
2044 
2045 /*
2046  * RPC request dispatch routine.  Constructs a datagram message and wraps it
2047  * around the RPC request to pass downstream.
2048  */
2049 static int
2050 clnt_clts_dispatch_send(queue_t *q, mblk_t *mp, struct netbuf *addr,
2051 			calllist_t *cp,	uint_t xid)
2052 {
2053 	mblk_t *bp;
2054 	int msgsz;
2055 	struct T_unitdata_req *udreq;
2056 
2057 	/*
2058 	 * Set up the call record.
2059 	 */
2060 	cp->call_wq = q;
2061 	cp->call_xid = xid;
2062 	cp->call_status = RPC_TIMEDOUT;
2063 	cp->call_notified = FALSE;
2064 	RPCLOG(64,
2065 		"clnt_clts_dispatch_send: putting xid 0x%x on "
2066 		"dispatch list\n", xid);
2067 	cp->call_hash = call_hash(xid, clnt_clts_hash_size);
2068 	cp->call_bucket = &clts_call_ht[cp->call_hash];
2069 	call_table_enter(cp);
2070 
2071 	/*
2072 	 * Construct the datagram
2073 	 */
2074 	msgsz = (int)TUNITDATAREQSZ;
2075 	while (!(bp = allocb(msgsz + addr->len, BPRI_LO))) {
2076 		if (strwaitbuf(msgsz + addr->len, BPRI_LO))
2077 			return (ENOSR);
2078 	}
2079 
2080 	udreq = (struct T_unitdata_req *)bp->b_wptr;
2081 	udreq->PRIM_type = T_UNITDATA_REQ;
2082 	udreq->DEST_length = addr->len;
2083 
2084 	if (addr->len) {
2085 		bcopy(addr->buf, bp->b_wptr + msgsz, addr->len);
2086 		udreq->DEST_offset = (t_scalar_t)msgsz;
2087 		msgsz += addr->len;
2088 	} else
2089 		udreq->DEST_offset = 0;
2090 	udreq->OPT_length = 0;
2091 	udreq->OPT_offset = 0;
2092 
2093 	bp->b_datap->db_type = M_PROTO;
2094 	bp->b_wptr += msgsz;
2095 
2096 	/*
2097 	 * Link the datagram header with the actual data
2098 	 */
2099 	linkb(bp, mp);
2100 
2101 	/*
2102 	 * Send downstream.
2103 	 */
2104 	put(cp->call_wq, bp);
2105 
2106 	return (0);
2107 }
2108 
2109 /*
2110  * RPC response delivery routine.  Deliver the response to the waiting
2111  * thread by matching the xid.
2112  */
2113 void
2114 clnt_clts_dispatch_notify(mblk_t *mp, int resp_off, zoneid_t zoneid)
2115 {
2116 	calllist_t *e = NULL;
2117 	call_table_t *chtp;
2118 	uint32_t xid;
2119 	uint_t hash;
2120 	unsigned char *hdr_offset;
2121 	mblk_t *resp;
2122 
2123 	/*
2124 	 * If the RPC response is not contained in the same mblk as the
2125 	 * datagram header, then move to the next mblk.
2126 	 */
2127 	hdr_offset = mp->b_rptr;
2128 	resp = mp;
2129 	if ((mp->b_wptr - (mp->b_rptr + resp_off)) == 0)
2130 		resp = mp->b_cont;
2131 	else
2132 		resp->b_rptr += resp_off;
2133 
2134 	ASSERT(resp != NULL);
2135 
2136 	if ((IS_P2ALIGNED(resp->b_rptr, sizeof (uint32_t))) &&
2137 	    (resp->b_wptr - resp->b_rptr) >= sizeof (xid))
2138 		xid = *((uint32_t *)resp->b_rptr);
2139 	else {
2140 		int i = 0;
2141 		unsigned char *p = (unsigned char *)&xid;
2142 		unsigned char *rptr;
2143 		mblk_t *tmp = resp;
2144 
2145 		/*
2146 		 * Copy the xid, byte-by-byte into xid.
2147 		 */
2148 		while (tmp) {
2149 			rptr = tmp->b_rptr;
2150 			while (rptr < tmp->b_wptr) {
2151 				*p++ = *rptr++;
2152 				if (++i >= sizeof (xid))
2153 					goto done_xid_copy;
2154 			}
2155 			tmp = tmp->b_cont;
2156 		}
2157 
2158 		/*
2159 		 * If we got here, we ran out of mblk space before the
2160 		 * xid could be copied.
2161 		 */
2162 		ASSERT(tmp == NULL && i < sizeof (xid));
2163 
2164 		RPCLOG0(1,
2165 			"clnt_dispatch_notify(clts): message less than "
2166 			"size of xid\n");
2167 
2168 		freemsg(mp);
2169 		return;
2170 	}
2171 
2172 done_xid_copy:
2173 
2174 	/*
2175 	 * Reset the read pointer back to the beginning of the protocol
2176 	 * header if we moved it.
2177 	 */
2178 	if (mp->b_rptr != hdr_offset)
2179 		mp->b_rptr = hdr_offset;
2180 
2181 	hash = call_hash(xid, clnt_clts_hash_size);
2182 	chtp = &clts_call_ht[hash];
2183 	/* call_table_find returns with the hash bucket locked */
2184 	call_table_find(chtp, xid, e);
2185 
2186 	if (e != NULL) {
2187 		mutex_enter(&e->call_lock);
2188 		/*
2189 		 * found thread waiting for this reply.
2190 		 */
2191 		if (e->call_reply) {
2192 			RPCLOG(8,
2193 				"clnt_dispatch_notify (clts): discarding old "
2194 				"reply for xid 0x%x\n",
2195 				xid);
2196 			freemsg(e->call_reply);
2197 		}
2198 		e->call_notified = TRUE;
2199 		e->call_reply = mp;
2200 		e->call_status = RPC_SUCCESS;
2201 		cv_signal(&e->call_cv);
2202 		mutex_exit(&e->call_lock);
2203 		mutex_exit(&chtp->ct_lock);
2204 	} else {
2205 		zone_t *zone;
2206 		struct rpcstat *rpcstat;
2207 
2208 		mutex_exit(&chtp->ct_lock);
2209 		RPCLOG(8, "clnt_dispatch_notify (clts): no caller for reply "
2210 			"0x%x\n", xid);
2211 		freemsg(mp);
2212 		/*
2213 		 * This is unfortunate, but we need to lookup the zone so we
2214 		 * can increment its "rcbadxids" counter.
2215 		 */
2216 		zone = zone_find_by_id(zoneid);
2217 		if (zone == NULL) {
2218 			/*
2219 			 * The zone went away...
2220 			 */
2221 			return;
2222 		}
2223 		rpcstat = zone_getspecific(rpcstat_zone_key, zone);
2224 		if (zone_status_get(zone) >= ZONE_IS_SHUTTING_DOWN) {
2225 			/*
2226 			 * Not interested
2227 			 */
2228 			zone_rele(zone);
2229 			return;
2230 		}
2231 		RCSTAT_INCR(rpcstat->rpc_clts_client, rcbadxids);
2232 		zone_rele(zone);
2233 	}
2234 }
2235 
2236 /*
2237  * Init routine.  Called when rpcmod is loaded.
2238  */
2239 void
2240 clnt_clts_init(void)
2241 {
2242 	endpnt_cache = kmem_cache_create("clnt_clts_endpnt_cache",
2243 	    sizeof (struct endpnt), 0, NULL, NULL, endpnt_repossess, NULL,
2244 	    NULL, 0);
2245 
2246 	rw_init(&endpnt_type_lock, NULL, RW_DEFAULT, NULL);
2247 
2248 	/*
2249 	 * Perform simple bounds checking to make sure that the setting is
2250 	 * reasonable
2251 	 */
2252 	if (clnt_clts_max_endpoints <= 0) {
2253 		if (clnt_clts_do_bindresvport)
2254 			clnt_clts_max_endpoints = RESERVED_PORTSPACE;
2255 		else
2256 			clnt_clts_max_endpoints = NONRESERVED_PORTSPACE;
2257 	}
2258 
2259 	if (clnt_clts_do_bindresvport &&
2260 	    clnt_clts_max_endpoints > RESERVED_PORTSPACE)
2261 		clnt_clts_max_endpoints = RESERVED_PORTSPACE;
2262 	else if (clnt_clts_max_endpoints > NONRESERVED_PORTSPACE)
2263 		clnt_clts_max_endpoints = NONRESERVED_PORTSPACE;
2264 
2265 	if (clnt_clts_hash_size < DEFAULT_MIN_HASH_SIZE)
2266 		clnt_clts_hash_size = DEFAULT_MIN_HASH_SIZE;
2267 
2268 	/*
2269 	 * Defer creating the taskq until rpcmod gets pushed.  If we are
2270 	 * in diskless boot mode, rpcmod will get loaded early even before
2271 	 * thread_create() is available.
2272 	 */
2273 	endpnt_taskq = NULL;
2274 	taskq_created = FALSE;
2275 	mutex_init(&endpnt_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
2276 
2277 	if (clnt_clts_endpoint_reap_interval < DEFAULT_ENDPOINT_REAP_INTERVAL)
2278 		clnt_clts_endpoint_reap_interval =
2279 			DEFAULT_ENDPOINT_REAP_INTERVAL;
2280 
2281 	/*
2282 	 * Dispatch the taskq at an interval which is offset from the
2283 	 * interval that the endpoints should be reaped.
2284 	 */
2285 	clnt_clts_taskq_dispatch_interval =
2286 		(clnt_clts_endpoint_reap_interval + DEFAULT_INTERVAL_SHIFT)
2287 		* hz;
2288 
2289 	/*
2290 	 * Initialize the completion queue
2291 	 */
2292 	clts_call_ht = call_table_init(clnt_clts_hash_size);
2293 	/*
2294 	 * Initialize the zone destructor callback.
2295 	 */
2296 	zone_key_create(&endpnt_destructor_key, NULL, NULL, endpnt_destructor);
2297 }
2298 
2299 void
2300 clnt_clts_fini(void)
2301 {
2302 	(void) zone_key_delete(endpnt_destructor_key);
2303 }
2304