xref: /freebsd/sys/netinet/in_pcb.c (revision 88f578841fd49ff796b62a8d3531bd73afd1a88e)
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993, 1995
3  *	The Regents of the University of California.
4  * Copyright (c) 2007-2009 Robert N. M. Watson
5  * Copyright (c) 2010-2011 Juniper Networks, Inc.
6  * All rights reserved.
7  *
8  * Portions of this software were developed by Robert N. M. Watson under
9  * contract to Juniper Networks, Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
36  */
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include "opt_ddb.h"
42 #include "opt_ipsec.h"
43 #include "opt_inet.h"
44 #include "opt_inet6.h"
45 #include "opt_pcbgroup.h"
46 #include "opt_rss.h"
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mbuf.h>
53 #include <sys/callout.h>
54 #include <sys/domain.h>
55 #include <sys/protosw.h>
56 #include <sys/rmlock.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/priv.h>
60 #include <sys/proc.h>
61 #include <sys/refcount.h>
62 #include <sys/jail.h>
63 #include <sys/kernel.h>
64 #include <sys/sysctl.h>
65 
66 #ifdef DDB
67 #include <ddb/ddb.h>
68 #endif
69 
70 #include <vm/uma.h>
71 
72 #include <net/if.h>
73 #include <net/if_var.h>
74 #include <net/if_types.h>
75 #include <net/route.h>
76 #include <net/rss_config.h>
77 #include <net/vnet.h>
78 
79 #if defined(INET) || defined(INET6)
80 #include <netinet/in.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/ip_var.h>
83 #include <netinet/tcp_var.h>
84 #include <netinet/udp.h>
85 #include <netinet/udp_var.h>
86 #endif
87 #ifdef INET
88 #include <netinet/in_var.h>
89 #endif
90 #ifdef INET6
91 #include <netinet/ip6.h>
92 #include <netinet6/in6_pcb.h>
93 #include <netinet6/in6_var.h>
94 #include <netinet6/ip6_var.h>
95 #endif /* INET6 */
96 
97 
98 #ifdef IPSEC
99 #include <netipsec/ipsec.h>
100 #include <netipsec/key.h>
101 #endif /* IPSEC */
102 
103 #include <security/mac/mac_framework.h>
104 
105 static struct callout	ipport_tick_callout;
106 
107 /*
108  * These configure the range of local port addresses assigned to
109  * "unspecified" outgoing connections/packets/whatever.
110  */
111 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
112 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
113 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
114 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
115 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
116 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
117 
118 /*
119  * Reserved ports accessible only to root. There are significant
120  * security considerations that must be accounted for when changing these,
121  * but the security benefits can be great. Please be careful.
122  */
123 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
124 VNET_DEFINE(int, ipport_reservedlow);
125 
126 /* Variables dealing with random ephemeral port allocation. */
127 VNET_DEFINE(int, ipport_randomized) = 1;	/* user controlled via sysctl */
128 VNET_DEFINE(int, ipport_randomcps) = 10;	/* user controlled via sysctl */
129 VNET_DEFINE(int, ipport_randomtime) = 45;	/* user controlled via sysctl */
130 VNET_DEFINE(int, ipport_stoprandom);		/* toggled by ipport_tick */
131 VNET_DEFINE(int, ipport_tcpallocs);
132 static VNET_DEFINE(int, ipport_tcplastcount);
133 
134 #define	V_ipport_tcplastcount		VNET(ipport_tcplastcount)
135 
136 static void	in_pcbremlists(struct inpcb *inp);
137 #ifdef INET
138 static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
139 			    struct in_addr faddr, u_int fport_arg,
140 			    struct in_addr laddr, u_int lport_arg,
141 			    int lookupflags, struct ifnet *ifp);
142 
143 #define RANGECHK(var, min, max) \
144 	if ((var) < (min)) { (var) = (min); } \
145 	else if ((var) > (max)) { (var) = (max); }
146 
147 static int
148 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
149 {
150 	int error;
151 
152 	error = sysctl_handle_int(oidp, arg1, arg2, req);
153 	if (error == 0) {
154 		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
155 		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
156 		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
157 		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
158 		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
159 		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
160 	}
161 	return (error);
162 }
163 
164 #undef RANGECHK
165 
166 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0,
167     "IP Ports");
168 
169 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
170 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
171 	&VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I", "");
172 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
173 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
174 	&VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I", "");
175 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
176 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
177 	&VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I", "");
178 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
179 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
180 	&VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I", "");
181 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
182 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
183 	&VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I", "");
184 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
185 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
186 	&VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I", "");
187 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
188 	CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
189 	&VNET_NAME(ipport_reservedhigh), 0, "");
190 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
191 	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
192 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
193 	CTLFLAG_VNET | CTLFLAG_RW,
194 	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
195 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
196 	CTLFLAG_VNET | CTLFLAG_RW,
197 	&VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
198 	"allocations before switching to a sequental one");
199 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
200 	CTLFLAG_VNET | CTLFLAG_RW,
201 	&VNET_NAME(ipport_randomtime), 0,
202 	"Minimum time to keep sequental port "
203 	"allocation before switching to a random one");
204 #endif /* INET */
205 
206 /*
207  * in_pcb.c: manage the Protocol Control Blocks.
208  *
209  * NOTE: It is assumed that most of these functions will be called with
210  * the pcbinfo lock held, and often, the inpcb lock held, as these utility
211  * functions often modify hash chains or addresses in pcbs.
212  */
213 
214 /*
215  * Initialize an inpcbinfo -- we should be able to reduce the number of
216  * arguments in time.
217  */
218 void
219 in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
220     struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
221     char *inpcbzone_name, uma_init inpcbzone_init, uma_fini inpcbzone_fini,
222     uint32_t inpcbzone_flags, u_int hashfields)
223 {
224 
225 	INP_INFO_LOCK_INIT(pcbinfo, name);
226 	INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash");	/* XXXRW: argument? */
227 #ifdef VIMAGE
228 	pcbinfo->ipi_vnet = curvnet;
229 #endif
230 	pcbinfo->ipi_listhead = listhead;
231 	LIST_INIT(pcbinfo->ipi_listhead);
232 	pcbinfo->ipi_count = 0;
233 	pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
234 	    &pcbinfo->ipi_hashmask);
235 	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
236 	    &pcbinfo->ipi_porthashmask);
237 #ifdef PCBGROUP
238 	in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
239 #endif
240 	pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
241 	    NULL, NULL, inpcbzone_init, inpcbzone_fini, UMA_ALIGN_PTR,
242 	    inpcbzone_flags);
243 	uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
244 	uma_zone_set_warning(pcbinfo->ipi_zone,
245 	    "kern.ipc.maxsockets limit reached");
246 }
247 
248 /*
249  * Destroy an inpcbinfo.
250  */
251 void
252 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
253 {
254 
255 	KASSERT(pcbinfo->ipi_count == 0,
256 	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
257 
258 	hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
259 	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
260 	    pcbinfo->ipi_porthashmask);
261 #ifdef PCBGROUP
262 	in_pcbgroup_destroy(pcbinfo);
263 #endif
264 	uma_zdestroy(pcbinfo->ipi_zone);
265 	INP_HASH_LOCK_DESTROY(pcbinfo);
266 	INP_INFO_LOCK_DESTROY(pcbinfo);
267 }
268 
269 /*
270  * Allocate a PCB and associate it with the socket.
271  * On success return with the PCB locked.
272  */
273 int
274 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
275 {
276 	struct inpcb *inp;
277 	int error;
278 
279 	INP_INFO_WLOCK_ASSERT(pcbinfo);
280 	error = 0;
281 	inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
282 	if (inp == NULL)
283 		return (ENOBUFS);
284 	bzero(inp, inp_zero_size);
285 	inp->inp_pcbinfo = pcbinfo;
286 	inp->inp_socket = so;
287 	inp->inp_cred = crhold(so->so_cred);
288 	inp->inp_inc.inc_fibnum = so->so_fibnum;
289 #ifdef MAC
290 	error = mac_inpcb_init(inp, M_NOWAIT);
291 	if (error != 0)
292 		goto out;
293 	mac_inpcb_create(so, inp);
294 #endif
295 #ifdef IPSEC
296 	error = ipsec_init_policy(so, &inp->inp_sp);
297 	if (error != 0) {
298 #ifdef MAC
299 		mac_inpcb_destroy(inp);
300 #endif
301 		goto out;
302 	}
303 #endif /*IPSEC*/
304 #ifdef INET6
305 	if (INP_SOCKAF(so) == AF_INET6) {
306 		inp->inp_vflag |= INP_IPV6PROTO;
307 		if (V_ip6_v6only)
308 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
309 	}
310 #endif
311 	LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
312 	pcbinfo->ipi_count++;
313 	so->so_pcb = (caddr_t)inp;
314 #ifdef INET6
315 	if (V_ip6_auto_flowlabel)
316 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
317 #endif
318 	INP_WLOCK(inp);
319 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
320 	refcount_init(&inp->inp_refcount, 1);	/* Reference from inpcbinfo */
321 #if defined(IPSEC) || defined(MAC)
322 out:
323 	if (error != 0) {
324 		crfree(inp->inp_cred);
325 		uma_zfree(pcbinfo->ipi_zone, inp);
326 	}
327 #endif
328 	return (error);
329 }
330 
331 #ifdef INET
332 int
333 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
334 {
335 	int anonport, error;
336 
337 	INP_WLOCK_ASSERT(inp);
338 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
339 
340 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
341 		return (EINVAL);
342 	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
343 	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
344 	    &inp->inp_lport, cred);
345 	if (error)
346 		return (error);
347 	if (in_pcbinshash(inp) != 0) {
348 		inp->inp_laddr.s_addr = INADDR_ANY;
349 		inp->inp_lport = 0;
350 		return (EAGAIN);
351 	}
352 	if (anonport)
353 		inp->inp_flags |= INP_ANONPORT;
354 	return (0);
355 }
356 #endif
357 
358 /*
359  * Select a local port (number) to use.
360  */
361 #if defined(INET) || defined(INET6)
362 int
363 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
364     struct ucred *cred, int lookupflags)
365 {
366 	struct inpcbinfo *pcbinfo;
367 	struct inpcb *tmpinp;
368 	unsigned short *lastport;
369 	int count, dorandom, error;
370 	u_short aux, first, last, lport;
371 #ifdef INET
372 	struct in_addr laddr;
373 #endif
374 
375 	pcbinfo = inp->inp_pcbinfo;
376 
377 	/*
378 	 * Because no actual state changes occur here, a global write lock on
379 	 * the pcbinfo isn't required.
380 	 */
381 	INP_LOCK_ASSERT(inp);
382 	INP_HASH_LOCK_ASSERT(pcbinfo);
383 
384 	if (inp->inp_flags & INP_HIGHPORT) {
385 		first = V_ipport_hifirstauto;	/* sysctl */
386 		last  = V_ipport_hilastauto;
387 		lastport = &pcbinfo->ipi_lasthi;
388 	} else if (inp->inp_flags & INP_LOWPORT) {
389 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
390 		if (error)
391 			return (error);
392 		first = V_ipport_lowfirstauto;	/* 1023 */
393 		last  = V_ipport_lowlastauto;	/* 600 */
394 		lastport = &pcbinfo->ipi_lastlow;
395 	} else {
396 		first = V_ipport_firstauto;	/* sysctl */
397 		last  = V_ipport_lastauto;
398 		lastport = &pcbinfo->ipi_lastport;
399 	}
400 	/*
401 	 * For UDP(-Lite), use random port allocation as long as the user
402 	 * allows it.  For TCP (and as of yet unknown) connections,
403 	 * use random port allocation only if the user allows it AND
404 	 * ipport_tick() allows it.
405 	 */
406 	if (V_ipport_randomized &&
407 		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
408 		pcbinfo == &V_ulitecbinfo))
409 		dorandom = 1;
410 	else
411 		dorandom = 0;
412 	/*
413 	 * It makes no sense to do random port allocation if
414 	 * we have the only port available.
415 	 */
416 	if (first == last)
417 		dorandom = 0;
418 	/* Make sure to not include UDP(-Lite) packets in the count. */
419 	if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
420 		V_ipport_tcpallocs++;
421 	/*
422 	 * Instead of having two loops further down counting up or down
423 	 * make sure that first is always <= last and go with only one
424 	 * code path implementing all logic.
425 	 */
426 	if (first > last) {
427 		aux = first;
428 		first = last;
429 		last = aux;
430 	}
431 
432 #ifdef INET
433 	/* Make the compiler happy. */
434 	laddr.s_addr = 0;
435 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
436 		KASSERT(laddrp != NULL, ("%s: laddrp NULL for v4 inp %p",
437 		    __func__, inp));
438 		laddr = *laddrp;
439 	}
440 #endif
441 	tmpinp = NULL;	/* Make compiler happy. */
442 	lport = *lportp;
443 
444 	if (dorandom)
445 		*lastport = first + (arc4random() % (last - first));
446 
447 	count = last - first;
448 
449 	do {
450 		if (count-- < 0)	/* completely used? */
451 			return (EADDRNOTAVAIL);
452 		++*lastport;
453 		if (*lastport < first || *lastport > last)
454 			*lastport = first;
455 		lport = htons(*lastport);
456 
457 #ifdef INET6
458 		if ((inp->inp_vflag & INP_IPV6) != 0)
459 			tmpinp = in6_pcblookup_local(pcbinfo,
460 			    &inp->in6p_laddr, lport, lookupflags, cred);
461 #endif
462 #if defined(INET) && defined(INET6)
463 		else
464 #endif
465 #ifdef INET
466 			tmpinp = in_pcblookup_local(pcbinfo, laddr,
467 			    lport, lookupflags, cred);
468 #endif
469 	} while (tmpinp != NULL);
470 
471 #ifdef INET
472 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4)
473 		laddrp->s_addr = laddr.s_addr;
474 #endif
475 	*lportp = lport;
476 
477 	return (0);
478 }
479 
480 /*
481  * Return cached socket options.
482  */
483 short
484 inp_so_options(const struct inpcb *inp)
485 {
486    short so_options;
487 
488    so_options = 0;
489 
490    if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
491 	   so_options |= SO_REUSEPORT;
492    if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
493 	   so_options |= SO_REUSEADDR;
494    return (so_options);
495 }
496 #endif /* INET || INET6 */
497 
498 /*
499  * Check if a new BINDMULTI socket is allowed to be created.
500  *
501  * ni points to the new inp.
502  * oi points to the exisitng inp.
503  *
504  * This checks whether the existing inp also has BINDMULTI and
505  * whether the credentials match.
506  */
507 int
508 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
509 {
510 	/* Check permissions match */
511 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
512 	    (ni->inp_cred->cr_uid !=
513 	    oi->inp_cred->cr_uid))
514 		return (0);
515 
516 	/* Check the existing inp has BINDMULTI set */
517 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
518 	    ((oi->inp_flags2 & INP_BINDMULTI) == 0))
519 		return (0);
520 
521 	/*
522 	 * We're okay - either INP_BINDMULTI isn't set on ni, or
523 	 * it is and it matches the checks.
524 	 */
525 	return (1);
526 }
527 
528 #ifdef INET
529 /*
530  * Set up a bind operation on a PCB, performing port allocation
531  * as required, but do not actually modify the PCB. Callers can
532  * either complete the bind by setting inp_laddr/inp_lport and
533  * calling in_pcbinshash(), or they can just use the resulting
534  * port and address to authorise the sending of a once-off packet.
535  *
536  * On error, the values of *laddrp and *lportp are not changed.
537  */
538 int
539 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
540     u_short *lportp, struct ucred *cred)
541 {
542 	struct socket *so = inp->inp_socket;
543 	struct sockaddr_in *sin;
544 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
545 	struct in_addr laddr;
546 	u_short lport = 0;
547 	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
548 	int error;
549 
550 	/*
551 	 * No state changes, so read locks are sufficient here.
552 	 */
553 	INP_LOCK_ASSERT(inp);
554 	INP_HASH_LOCK_ASSERT(pcbinfo);
555 
556 	if (TAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
557 		return (EADDRNOTAVAIL);
558 	laddr.s_addr = *laddrp;
559 	if (nam != NULL && laddr.s_addr != INADDR_ANY)
560 		return (EINVAL);
561 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
562 		lookupflags = INPLOOKUP_WILDCARD;
563 	if (nam == NULL) {
564 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
565 			return (error);
566 	} else {
567 		sin = (struct sockaddr_in *)nam;
568 		if (nam->sa_len != sizeof (*sin))
569 			return (EINVAL);
570 #ifdef notdef
571 		/*
572 		 * We should check the family, but old programs
573 		 * incorrectly fail to initialize it.
574 		 */
575 		if (sin->sin_family != AF_INET)
576 			return (EAFNOSUPPORT);
577 #endif
578 		error = prison_local_ip4(cred, &sin->sin_addr);
579 		if (error)
580 			return (error);
581 		if (sin->sin_port != *lportp) {
582 			/* Don't allow the port to change. */
583 			if (*lportp != 0)
584 				return (EINVAL);
585 			lport = sin->sin_port;
586 		}
587 		/* NB: lport is left as 0 if the port isn't being changed. */
588 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
589 			/*
590 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
591 			 * allow complete duplication of binding if
592 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
593 			 * and a multicast address is bound on both
594 			 * new and duplicated sockets.
595 			 */
596 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
597 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
598 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
599 			sin->sin_port = 0;		/* yech... */
600 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
601 			/*
602 			 * Is the address a local IP address?
603 			 * If INP_BINDANY is set, then the socket may be bound
604 			 * to any endpoint address, local or not.
605 			 */
606 			if ((inp->inp_flags & INP_BINDANY) == 0 &&
607 			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
608 				return (EADDRNOTAVAIL);
609 		}
610 		laddr = sin->sin_addr;
611 		if (lport) {
612 			struct inpcb *t;
613 			struct tcptw *tw;
614 
615 			/* GROSS */
616 			if (ntohs(lport) <= V_ipport_reservedhigh &&
617 			    ntohs(lport) >= V_ipport_reservedlow &&
618 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
619 			    0))
620 				return (EACCES);
621 			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
622 			    priv_check_cred(inp->inp_cred,
623 			    PRIV_NETINET_REUSEPORT, 0) != 0) {
624 				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
625 				    lport, INPLOOKUP_WILDCARD, cred);
626 	/*
627 	 * XXX
628 	 * This entire block sorely needs a rewrite.
629 	 */
630 				if (t &&
631 				    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
632 				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
633 				    (so->so_type != SOCK_STREAM ||
634 				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
635 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
636 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
637 				     (t->inp_flags2 & INP_REUSEPORT) == 0) &&
638 				    (inp->inp_cred->cr_uid !=
639 				     t->inp_cred->cr_uid))
640 					return (EADDRINUSE);
641 
642 				/*
643 				 * If the socket is a BINDMULTI socket, then
644 				 * the credentials need to match and the
645 				 * original socket also has to have been bound
646 				 * with BINDMULTI.
647 				 */
648 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
649 					return (EADDRINUSE);
650 			}
651 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
652 			    lport, lookupflags, cred);
653 			if (t && (t->inp_flags & INP_TIMEWAIT)) {
654 				/*
655 				 * XXXRW: If an incpb has had its timewait
656 				 * state recycled, we treat the address as
657 				 * being in use (for now).  This is better
658 				 * than a panic, but not desirable.
659 				 */
660 				tw = intotw(t);
661 				if (tw == NULL ||
662 				    (reuseport & tw->tw_so_options) == 0)
663 					return (EADDRINUSE);
664 			} else if (t &&
665 			    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
666 			    (reuseport & inp_so_options(t)) == 0) {
667 #ifdef INET6
668 				if (ntohl(sin->sin_addr.s_addr) !=
669 				    INADDR_ANY ||
670 				    ntohl(t->inp_laddr.s_addr) !=
671 				    INADDR_ANY ||
672 				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
673 				    (t->inp_vflag & INP_IPV6PROTO) == 0)
674 #endif
675 				return (EADDRINUSE);
676 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
677 					return (EADDRINUSE);
678 			}
679 		}
680 	}
681 	if (*lportp != 0)
682 		lport = *lportp;
683 	if (lport == 0) {
684 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
685 		if (error != 0)
686 			return (error);
687 
688 	}
689 	*laddrp = laddr.s_addr;
690 	*lportp = lport;
691 	return (0);
692 }
693 
694 /*
695  * Connect from a socket to a specified address.
696  * Both address and port must be specified in argument sin.
697  * If don't have a local address for this socket yet,
698  * then pick one.
699  */
700 int
701 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
702     struct ucred *cred, struct mbuf *m)
703 {
704 	u_short lport, fport;
705 	in_addr_t laddr, faddr;
706 	int anonport, error;
707 
708 	INP_WLOCK_ASSERT(inp);
709 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
710 
711 	lport = inp->inp_lport;
712 	laddr = inp->inp_laddr.s_addr;
713 	anonport = (lport == 0);
714 	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
715 	    NULL, cred);
716 	if (error)
717 		return (error);
718 
719 	/* Do the initial binding of the local address if required. */
720 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
721 		inp->inp_lport = lport;
722 		inp->inp_laddr.s_addr = laddr;
723 		if (in_pcbinshash(inp) != 0) {
724 			inp->inp_laddr.s_addr = INADDR_ANY;
725 			inp->inp_lport = 0;
726 			return (EAGAIN);
727 		}
728 	}
729 
730 	/* Commit the remaining changes. */
731 	inp->inp_lport = lport;
732 	inp->inp_laddr.s_addr = laddr;
733 	inp->inp_faddr.s_addr = faddr;
734 	inp->inp_fport = fport;
735 	in_pcbrehash_mbuf(inp, m);
736 
737 	if (anonport)
738 		inp->inp_flags |= INP_ANONPORT;
739 	return (0);
740 }
741 
742 int
743 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
744 {
745 
746 	return (in_pcbconnect_mbuf(inp, nam, cred, NULL));
747 }
748 
749 /*
750  * Do proper source address selection on an unbound socket in case
751  * of connect. Take jails into account as well.
752  */
753 int
754 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
755     struct ucred *cred)
756 {
757 	struct ifaddr *ifa;
758 	struct sockaddr *sa;
759 	struct sockaddr_in *sin;
760 	struct route sro;
761 	int error;
762 
763 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
764 
765 	/*
766 	 * Bypass source address selection and use the primary jail IP
767 	 * if requested.
768 	 */
769 	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
770 		return (0);
771 
772 	error = 0;
773 	bzero(&sro, sizeof(sro));
774 
775 	sin = (struct sockaddr_in *)&sro.ro_dst;
776 	sin->sin_family = AF_INET;
777 	sin->sin_len = sizeof(struct sockaddr_in);
778 	sin->sin_addr.s_addr = faddr->s_addr;
779 
780 	/*
781 	 * If route is known our src addr is taken from the i/f,
782 	 * else punt.
783 	 *
784 	 * Find out route to destination.
785 	 */
786 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
787 		in_rtalloc_ign(&sro, 0, inp->inp_inc.inc_fibnum);
788 
789 	/*
790 	 * If we found a route, use the address corresponding to
791 	 * the outgoing interface.
792 	 *
793 	 * Otherwise assume faddr is reachable on a directly connected
794 	 * network and try to find a corresponding interface to take
795 	 * the source address from.
796 	 */
797 	if (sro.ro_rt == NULL || sro.ro_rt->rt_ifp == NULL) {
798 		struct in_ifaddr *ia;
799 		struct ifnet *ifp;
800 
801 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
802 					inp->inp_socket->so_fibnum));
803 		if (ia == NULL)
804 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
805 						inp->inp_socket->so_fibnum));
806 		if (ia == NULL) {
807 			error = ENETUNREACH;
808 			goto done;
809 		}
810 
811 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
812 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
813 			ifa_free(&ia->ia_ifa);
814 			goto done;
815 		}
816 
817 		ifp = ia->ia_ifp;
818 		ifa_free(&ia->ia_ifa);
819 		ia = NULL;
820 		IF_ADDR_RLOCK(ifp);
821 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
822 
823 			sa = ifa->ifa_addr;
824 			if (sa->sa_family != AF_INET)
825 				continue;
826 			sin = (struct sockaddr_in *)sa;
827 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
828 				ia = (struct in_ifaddr *)ifa;
829 				break;
830 			}
831 		}
832 		if (ia != NULL) {
833 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
834 			IF_ADDR_RUNLOCK(ifp);
835 			goto done;
836 		}
837 		IF_ADDR_RUNLOCK(ifp);
838 
839 		/* 3. As a last resort return the 'default' jail address. */
840 		error = prison_get_ip4(cred, laddr);
841 		goto done;
842 	}
843 
844 	/*
845 	 * If the outgoing interface on the route found is not
846 	 * a loopback interface, use the address from that interface.
847 	 * In case of jails do those three steps:
848 	 * 1. check if the interface address belongs to the jail. If so use it.
849 	 * 2. check if we have any address on the outgoing interface
850 	 *    belonging to this jail. If so use it.
851 	 * 3. as a last resort return the 'default' jail address.
852 	 */
853 	if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
854 		struct in_ifaddr *ia;
855 		struct ifnet *ifp;
856 
857 		/* If not jailed, use the default returned. */
858 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
859 			ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
860 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
861 			goto done;
862 		}
863 
864 		/* Jailed. */
865 		/* 1. Check if the iface address belongs to the jail. */
866 		sin = (struct sockaddr_in *)sro.ro_rt->rt_ifa->ifa_addr;
867 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
868 			ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
869 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
870 			goto done;
871 		}
872 
873 		/*
874 		 * 2. Check if we have any address on the outgoing interface
875 		 *    belonging to this jail.
876 		 */
877 		ia = NULL;
878 		ifp = sro.ro_rt->rt_ifp;
879 		IF_ADDR_RLOCK(ifp);
880 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
881 			sa = ifa->ifa_addr;
882 			if (sa->sa_family != AF_INET)
883 				continue;
884 			sin = (struct sockaddr_in *)sa;
885 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
886 				ia = (struct in_ifaddr *)ifa;
887 				break;
888 			}
889 		}
890 		if (ia != NULL) {
891 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
892 			IF_ADDR_RUNLOCK(ifp);
893 			goto done;
894 		}
895 		IF_ADDR_RUNLOCK(ifp);
896 
897 		/* 3. As a last resort return the 'default' jail address. */
898 		error = prison_get_ip4(cred, laddr);
899 		goto done;
900 	}
901 
902 	/*
903 	 * The outgoing interface is marked with 'loopback net', so a route
904 	 * to ourselves is here.
905 	 * Try to find the interface of the destination address and then
906 	 * take the address from there. That interface is not necessarily
907 	 * a loopback interface.
908 	 * In case of jails, check that it is an address of the jail
909 	 * and if we cannot find, fall back to the 'default' jail address.
910 	 */
911 	if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
912 		struct sockaddr_in sain;
913 		struct in_ifaddr *ia;
914 
915 		bzero(&sain, sizeof(struct sockaddr_in));
916 		sain.sin_family = AF_INET;
917 		sain.sin_len = sizeof(struct sockaddr_in);
918 		sain.sin_addr.s_addr = faddr->s_addr;
919 
920 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sain),
921 					inp->inp_socket->so_fibnum));
922 		if (ia == NULL)
923 			ia = ifatoia(ifa_ifwithnet(sintosa(&sain), 0,
924 						inp->inp_socket->so_fibnum));
925 		if (ia == NULL)
926 			ia = ifatoia(ifa_ifwithaddr(sintosa(&sain)));
927 
928 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
929 			if (ia == NULL) {
930 				error = ENETUNREACH;
931 				goto done;
932 			}
933 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
934 			ifa_free(&ia->ia_ifa);
935 			goto done;
936 		}
937 
938 		/* Jailed. */
939 		if (ia != NULL) {
940 			struct ifnet *ifp;
941 
942 			ifp = ia->ia_ifp;
943 			ifa_free(&ia->ia_ifa);
944 			ia = NULL;
945 			IF_ADDR_RLOCK(ifp);
946 			TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
947 
948 				sa = ifa->ifa_addr;
949 				if (sa->sa_family != AF_INET)
950 					continue;
951 				sin = (struct sockaddr_in *)sa;
952 				if (prison_check_ip4(cred,
953 				    &sin->sin_addr) == 0) {
954 					ia = (struct in_ifaddr *)ifa;
955 					break;
956 				}
957 			}
958 			if (ia != NULL) {
959 				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
960 				IF_ADDR_RUNLOCK(ifp);
961 				goto done;
962 			}
963 			IF_ADDR_RUNLOCK(ifp);
964 		}
965 
966 		/* 3. As a last resort return the 'default' jail address. */
967 		error = prison_get_ip4(cred, laddr);
968 		goto done;
969 	}
970 
971 done:
972 	if (sro.ro_rt != NULL)
973 		RTFREE(sro.ro_rt);
974 	return (error);
975 }
976 
977 /*
978  * Set up for a connect from a socket to the specified address.
979  * On entry, *laddrp and *lportp should contain the current local
980  * address and port for the PCB; these are updated to the values
981  * that should be placed in inp_laddr and inp_lport to complete
982  * the connect.
983  *
984  * On success, *faddrp and *fportp will be set to the remote address
985  * and port. These are not updated in the error case.
986  *
987  * If the operation fails because the connection already exists,
988  * *oinpp will be set to the PCB of that connection so that the
989  * caller can decide to override it. In all other cases, *oinpp
990  * is set to NULL.
991  */
992 int
993 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
994     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
995     struct inpcb **oinpp, struct ucred *cred)
996 {
997 	struct rm_priotracker in_ifa_tracker;
998 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
999 	struct in_ifaddr *ia;
1000 	struct inpcb *oinp;
1001 	struct in_addr laddr, faddr;
1002 	u_short lport, fport;
1003 	int error;
1004 
1005 	/*
1006 	 * Because a global state change doesn't actually occur here, a read
1007 	 * lock is sufficient.
1008 	 */
1009 	INP_LOCK_ASSERT(inp);
1010 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1011 
1012 	if (oinpp != NULL)
1013 		*oinpp = NULL;
1014 	if (nam->sa_len != sizeof (*sin))
1015 		return (EINVAL);
1016 	if (sin->sin_family != AF_INET)
1017 		return (EAFNOSUPPORT);
1018 	if (sin->sin_port == 0)
1019 		return (EADDRNOTAVAIL);
1020 	laddr.s_addr = *laddrp;
1021 	lport = *lportp;
1022 	faddr = sin->sin_addr;
1023 	fport = sin->sin_port;
1024 
1025 	if (!TAILQ_EMPTY(&V_in_ifaddrhead)) {
1026 		/*
1027 		 * If the destination address is INADDR_ANY,
1028 		 * use the primary local address.
1029 		 * If the supplied address is INADDR_BROADCAST,
1030 		 * and the primary interface supports broadcast,
1031 		 * choose the broadcast address for that interface.
1032 		 */
1033 		if (faddr.s_addr == INADDR_ANY) {
1034 			IN_IFADDR_RLOCK(&in_ifa_tracker);
1035 			faddr =
1036 			    IA_SIN(TAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1037 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1038 			if (cred != NULL &&
1039 			    (error = prison_get_ip4(cred, &faddr)) != 0)
1040 				return (error);
1041 		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1042 			IN_IFADDR_RLOCK(&in_ifa_tracker);
1043 			if (TAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1044 			    IFF_BROADCAST)
1045 				faddr = satosin(&TAILQ_FIRST(
1046 				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1047 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1048 		}
1049 	}
1050 	if (laddr.s_addr == INADDR_ANY) {
1051 		error = in_pcbladdr(inp, &faddr, &laddr, cred);
1052 		/*
1053 		 * If the destination address is multicast and an outgoing
1054 		 * interface has been set as a multicast option, prefer the
1055 		 * address of that interface as our source address.
1056 		 */
1057 		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1058 		    inp->inp_moptions != NULL) {
1059 			struct ip_moptions *imo;
1060 			struct ifnet *ifp;
1061 
1062 			imo = inp->inp_moptions;
1063 			if (imo->imo_multicast_ifp != NULL) {
1064 				ifp = imo->imo_multicast_ifp;
1065 				IN_IFADDR_RLOCK(&in_ifa_tracker);
1066 				TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1067 					if ((ia->ia_ifp == ifp) &&
1068 					    (cred == NULL ||
1069 					    prison_check_ip4(cred,
1070 					    &ia->ia_addr.sin_addr) == 0))
1071 						break;
1072 				}
1073 				if (ia == NULL)
1074 					error = EADDRNOTAVAIL;
1075 				else {
1076 					laddr = ia->ia_addr.sin_addr;
1077 					error = 0;
1078 				}
1079 				IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1080 			}
1081 		}
1082 		if (error)
1083 			return (error);
1084 	}
1085 	oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr, fport,
1086 	    laddr, lport, 0, NULL);
1087 	if (oinp != NULL) {
1088 		if (oinpp != NULL)
1089 			*oinpp = oinp;
1090 		return (EADDRINUSE);
1091 	}
1092 	if (lport == 0) {
1093 		error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1094 		    cred);
1095 		if (error)
1096 			return (error);
1097 	}
1098 	*laddrp = laddr.s_addr;
1099 	*lportp = lport;
1100 	*faddrp = faddr.s_addr;
1101 	*fportp = fport;
1102 	return (0);
1103 }
1104 
1105 void
1106 in_pcbdisconnect(struct inpcb *inp)
1107 {
1108 
1109 	INP_WLOCK_ASSERT(inp);
1110 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1111 
1112 	inp->inp_faddr.s_addr = INADDR_ANY;
1113 	inp->inp_fport = 0;
1114 	in_pcbrehash(inp);
1115 }
1116 #endif /* INET */
1117 
1118 /*
1119  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1120  * For most protocols, this will be invoked immediately prior to calling
1121  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
1122  * socket, in which case in_pcbfree() is deferred.
1123  */
1124 void
1125 in_pcbdetach(struct inpcb *inp)
1126 {
1127 
1128 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1129 
1130 	inp->inp_socket->so_pcb = NULL;
1131 	inp->inp_socket = NULL;
1132 }
1133 
1134 /*
1135  * in_pcbref() bumps the reference count on an inpcb in order to maintain
1136  * stability of an inpcb pointer despite the inpcb lock being released.  This
1137  * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1138  * but where the inpcb lock may already held, or when acquiring a reference
1139  * via a pcbgroup.
1140  *
1141  * in_pcbref() should be used only to provide brief memory stability, and
1142  * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1143  * garbage collect the inpcb if it has been in_pcbfree()'d from another
1144  * context.  Until in_pcbrele() has returned that the inpcb is still valid,
1145  * lock and rele are the *only* safe operations that may be performed on the
1146  * inpcb.
1147  *
1148  * While the inpcb will not be freed, releasing the inpcb lock means that the
1149  * connection's state may change, so the caller should be careful to
1150  * revalidate any cached state on reacquiring the lock.  Drop the reference
1151  * using in_pcbrele().
1152  */
1153 void
1154 in_pcbref(struct inpcb *inp)
1155 {
1156 
1157 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1158 
1159 	refcount_acquire(&inp->inp_refcount);
1160 }
1161 
1162 /*
1163  * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1164  * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1165  * return a flag indicating whether or not the inpcb remains valid.  If it is
1166  * valid, we return with the inpcb lock held.
1167  *
1168  * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1169  * reference on an inpcb.  Historically more work was done here (actually, in
1170  * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1171  * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
1172  * about memory stability (and continued use of the write lock).
1173  */
1174 int
1175 in_pcbrele_rlocked(struct inpcb *inp)
1176 {
1177 	struct inpcbinfo *pcbinfo;
1178 
1179 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1180 
1181 	INP_RLOCK_ASSERT(inp);
1182 
1183 	if (refcount_release(&inp->inp_refcount) == 0) {
1184 		/*
1185 		 * If the inpcb has been freed, let the caller know, even if
1186 		 * this isn't the last reference.
1187 		 */
1188 		if (inp->inp_flags2 & INP_FREED) {
1189 			INP_RUNLOCK(inp);
1190 			return (1);
1191 		}
1192 		return (0);
1193 	}
1194 
1195 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1196 
1197 	INP_RUNLOCK(inp);
1198 	pcbinfo = inp->inp_pcbinfo;
1199 	uma_zfree(pcbinfo->ipi_zone, inp);
1200 	return (1);
1201 }
1202 
1203 int
1204 in_pcbrele_wlocked(struct inpcb *inp)
1205 {
1206 	struct inpcbinfo *pcbinfo;
1207 
1208 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1209 
1210 	INP_WLOCK_ASSERT(inp);
1211 
1212 	if (refcount_release(&inp->inp_refcount) == 0)
1213 		return (0);
1214 
1215 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1216 
1217 	INP_WUNLOCK(inp);
1218 	pcbinfo = inp->inp_pcbinfo;
1219 	uma_zfree(pcbinfo->ipi_zone, inp);
1220 	return (1);
1221 }
1222 
1223 /*
1224  * Temporary wrapper.
1225  */
1226 int
1227 in_pcbrele(struct inpcb *inp)
1228 {
1229 
1230 	return (in_pcbrele_wlocked(inp));
1231 }
1232 
1233 /*
1234  * Unconditionally schedule an inpcb to be freed by decrementing its
1235  * reference count, which should occur only after the inpcb has been detached
1236  * from its socket.  If another thread holds a temporary reference (acquired
1237  * using in_pcbref()) then the free is deferred until that reference is
1238  * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
1239  * work, including removal from global lists, is done in this context, where
1240  * the pcbinfo lock is held.
1241  */
1242 void
1243 in_pcbfree(struct inpcb *inp)
1244 {
1245 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1246 
1247 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1248 
1249 	INP_INFO_WLOCK_ASSERT(pcbinfo);
1250 	INP_WLOCK_ASSERT(inp);
1251 
1252 	/* XXXRW: Do as much as possible here. */
1253 #ifdef IPSEC
1254 	if (inp->inp_sp != NULL)
1255 		ipsec_delete_pcbpolicy(inp);
1256 #endif
1257 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1258 	in_pcbremlists(inp);
1259 #ifdef INET6
1260 	if (inp->inp_vflag & INP_IPV6PROTO) {
1261 		ip6_freepcbopts(inp->in6p_outputopts);
1262 		if (inp->in6p_moptions != NULL)
1263 			ip6_freemoptions(inp->in6p_moptions);
1264 	}
1265 #endif
1266 	if (inp->inp_options)
1267 		(void)m_free(inp->inp_options);
1268 #ifdef INET
1269 	if (inp->inp_moptions != NULL)
1270 		inp_freemoptions(inp->inp_moptions);
1271 #endif
1272 	inp->inp_vflag = 0;
1273 	inp->inp_flags2 |= INP_FREED;
1274 	crfree(inp->inp_cred);
1275 #ifdef MAC
1276 	mac_inpcb_destroy(inp);
1277 #endif
1278 	if (!in_pcbrele_wlocked(inp))
1279 		INP_WUNLOCK(inp);
1280 }
1281 
1282 /*
1283  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1284  * port reservation, and preventing it from being returned by inpcb lookups.
1285  *
1286  * It is used by TCP to mark an inpcb as unused and avoid future packet
1287  * delivery or event notification when a socket remains open but TCP has
1288  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1289  * or a RST on the wire, and allows the port binding to be reused while still
1290  * maintaining the invariant that so_pcb always points to a valid inpcb until
1291  * in_pcbdetach().
1292  *
1293  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1294  * in_pcbnotifyall() and in_pcbpurgeif0()?
1295  */
1296 void
1297 in_pcbdrop(struct inpcb *inp)
1298 {
1299 
1300 	INP_WLOCK_ASSERT(inp);
1301 
1302 	/*
1303 	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1304 	 * the hash lock...?
1305 	 */
1306 	inp->inp_flags |= INP_DROPPED;
1307 	if (inp->inp_flags & INP_INHASHLIST) {
1308 		struct inpcbport *phd = inp->inp_phd;
1309 
1310 		INP_HASH_WLOCK(inp->inp_pcbinfo);
1311 		LIST_REMOVE(inp, inp_hash);
1312 		LIST_REMOVE(inp, inp_portlist);
1313 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1314 			LIST_REMOVE(phd, phd_hash);
1315 			free(phd, M_PCB);
1316 		}
1317 		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1318 		inp->inp_flags &= ~INP_INHASHLIST;
1319 #ifdef PCBGROUP
1320 		in_pcbgroup_remove(inp);
1321 #endif
1322 	}
1323 }
1324 
1325 #ifdef INET
1326 /*
1327  * Common routines to return the socket addresses associated with inpcbs.
1328  */
1329 struct sockaddr *
1330 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1331 {
1332 	struct sockaddr_in *sin;
1333 
1334 	sin = malloc(sizeof *sin, M_SONAME,
1335 		M_WAITOK | M_ZERO);
1336 	sin->sin_family = AF_INET;
1337 	sin->sin_len = sizeof(*sin);
1338 	sin->sin_addr = *addr_p;
1339 	sin->sin_port = port;
1340 
1341 	return (struct sockaddr *)sin;
1342 }
1343 
1344 int
1345 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1346 {
1347 	struct inpcb *inp;
1348 	struct in_addr addr;
1349 	in_port_t port;
1350 
1351 	inp = sotoinpcb(so);
1352 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1353 
1354 	INP_RLOCK(inp);
1355 	port = inp->inp_lport;
1356 	addr = inp->inp_laddr;
1357 	INP_RUNLOCK(inp);
1358 
1359 	*nam = in_sockaddr(port, &addr);
1360 	return 0;
1361 }
1362 
1363 int
1364 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1365 {
1366 	struct inpcb *inp;
1367 	struct in_addr addr;
1368 	in_port_t port;
1369 
1370 	inp = sotoinpcb(so);
1371 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1372 
1373 	INP_RLOCK(inp);
1374 	port = inp->inp_fport;
1375 	addr = inp->inp_faddr;
1376 	INP_RUNLOCK(inp);
1377 
1378 	*nam = in_sockaddr(port, &addr);
1379 	return 0;
1380 }
1381 
1382 void
1383 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1384     struct inpcb *(*notify)(struct inpcb *, int))
1385 {
1386 	struct inpcb *inp, *inp_temp;
1387 
1388 	INP_INFO_WLOCK(pcbinfo);
1389 	LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1390 		INP_WLOCK(inp);
1391 #ifdef INET6
1392 		if ((inp->inp_vflag & INP_IPV4) == 0) {
1393 			INP_WUNLOCK(inp);
1394 			continue;
1395 		}
1396 #endif
1397 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1398 		    inp->inp_socket == NULL) {
1399 			INP_WUNLOCK(inp);
1400 			continue;
1401 		}
1402 		if ((*notify)(inp, errno))
1403 			INP_WUNLOCK(inp);
1404 	}
1405 	INP_INFO_WUNLOCK(pcbinfo);
1406 }
1407 
1408 void
1409 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1410 {
1411 	struct inpcb *inp;
1412 	struct ip_moptions *imo;
1413 	int i, gap;
1414 
1415 	INP_INFO_RLOCK(pcbinfo);
1416 	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1417 		INP_WLOCK(inp);
1418 		imo = inp->inp_moptions;
1419 		if ((inp->inp_vflag & INP_IPV4) &&
1420 		    imo != NULL) {
1421 			/*
1422 			 * Unselect the outgoing interface if it is being
1423 			 * detached.
1424 			 */
1425 			if (imo->imo_multicast_ifp == ifp)
1426 				imo->imo_multicast_ifp = NULL;
1427 
1428 			/*
1429 			 * Drop multicast group membership if we joined
1430 			 * through the interface being detached.
1431 			 */
1432 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1433 			    i++) {
1434 				if (imo->imo_membership[i]->inm_ifp == ifp) {
1435 					in_delmulti(imo->imo_membership[i]);
1436 					gap++;
1437 				} else if (gap != 0)
1438 					imo->imo_membership[i - gap] =
1439 					    imo->imo_membership[i];
1440 			}
1441 			imo->imo_num_memberships -= gap;
1442 		}
1443 		INP_WUNLOCK(inp);
1444 	}
1445 	INP_INFO_RUNLOCK(pcbinfo);
1446 }
1447 
1448 /*
1449  * Lookup a PCB based on the local address and port.  Caller must hold the
1450  * hash lock.  No inpcb locks or references are acquired.
1451  */
1452 #define INP_LOOKUP_MAPPED_PCB_COST	3
1453 struct inpcb *
1454 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1455     u_short lport, int lookupflags, struct ucred *cred)
1456 {
1457 	struct inpcb *inp;
1458 #ifdef INET6
1459 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1460 #else
1461 	int matchwild = 3;
1462 #endif
1463 	int wildcard;
1464 
1465 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1466 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1467 
1468 	INP_HASH_LOCK_ASSERT(pcbinfo);
1469 
1470 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1471 		struct inpcbhead *head;
1472 		/*
1473 		 * Look for an unconnected (wildcard foreign addr) PCB that
1474 		 * matches the local address and port we're looking for.
1475 		 */
1476 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1477 		    0, pcbinfo->ipi_hashmask)];
1478 		LIST_FOREACH(inp, head, inp_hash) {
1479 #ifdef INET6
1480 			/* XXX inp locking */
1481 			if ((inp->inp_vflag & INP_IPV4) == 0)
1482 				continue;
1483 #endif
1484 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1485 			    inp->inp_laddr.s_addr == laddr.s_addr &&
1486 			    inp->inp_lport == lport) {
1487 				/*
1488 				 * Found?
1489 				 */
1490 				if (cred == NULL ||
1491 				    prison_equal_ip4(cred->cr_prison,
1492 					inp->inp_cred->cr_prison))
1493 					return (inp);
1494 			}
1495 		}
1496 		/*
1497 		 * Not found.
1498 		 */
1499 		return (NULL);
1500 	} else {
1501 		struct inpcbporthead *porthash;
1502 		struct inpcbport *phd;
1503 		struct inpcb *match = NULL;
1504 		/*
1505 		 * Best fit PCB lookup.
1506 		 *
1507 		 * First see if this local port is in use by looking on the
1508 		 * port hash list.
1509 		 */
1510 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1511 		    pcbinfo->ipi_porthashmask)];
1512 		LIST_FOREACH(phd, porthash, phd_hash) {
1513 			if (phd->phd_port == lport)
1514 				break;
1515 		}
1516 		if (phd != NULL) {
1517 			/*
1518 			 * Port is in use by one or more PCBs. Look for best
1519 			 * fit.
1520 			 */
1521 			LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1522 				wildcard = 0;
1523 				if (cred != NULL &&
1524 				    !prison_equal_ip4(inp->inp_cred->cr_prison,
1525 					cred->cr_prison))
1526 					continue;
1527 #ifdef INET6
1528 				/* XXX inp locking */
1529 				if ((inp->inp_vflag & INP_IPV4) == 0)
1530 					continue;
1531 				/*
1532 				 * We never select the PCB that has
1533 				 * INP_IPV6 flag and is bound to :: if
1534 				 * we have another PCB which is bound
1535 				 * to 0.0.0.0.  If a PCB has the
1536 				 * INP_IPV6 flag, then we set its cost
1537 				 * higher than IPv4 only PCBs.
1538 				 *
1539 				 * Note that the case only happens
1540 				 * when a socket is bound to ::, under
1541 				 * the condition that the use of the
1542 				 * mapped address is allowed.
1543 				 */
1544 				if ((inp->inp_vflag & INP_IPV6) != 0)
1545 					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1546 #endif
1547 				if (inp->inp_faddr.s_addr != INADDR_ANY)
1548 					wildcard++;
1549 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
1550 					if (laddr.s_addr == INADDR_ANY)
1551 						wildcard++;
1552 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
1553 						continue;
1554 				} else {
1555 					if (laddr.s_addr != INADDR_ANY)
1556 						wildcard++;
1557 				}
1558 				if (wildcard < matchwild) {
1559 					match = inp;
1560 					matchwild = wildcard;
1561 					if (matchwild == 0)
1562 						break;
1563 				}
1564 			}
1565 		}
1566 		return (match);
1567 	}
1568 }
1569 #undef INP_LOOKUP_MAPPED_PCB_COST
1570 
1571 #ifdef PCBGROUP
1572 /*
1573  * Lookup PCB in hash list, using pcbgroup tables.
1574  */
1575 static struct inpcb *
1576 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1577     struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1578     u_int lport_arg, int lookupflags, struct ifnet *ifp)
1579 {
1580 	struct inpcbhead *head;
1581 	struct inpcb *inp, *tmpinp;
1582 	u_short fport = fport_arg, lport = lport_arg;
1583 
1584 	/*
1585 	 * First look for an exact match.
1586 	 */
1587 	tmpinp = NULL;
1588 	INP_GROUP_LOCK(pcbgroup);
1589 	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1590 	    pcbgroup->ipg_hashmask)];
1591 	LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1592 #ifdef INET6
1593 		/* XXX inp locking */
1594 		if ((inp->inp_vflag & INP_IPV4) == 0)
1595 			continue;
1596 #endif
1597 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1598 		    inp->inp_laddr.s_addr == laddr.s_addr &&
1599 		    inp->inp_fport == fport &&
1600 		    inp->inp_lport == lport) {
1601 			/*
1602 			 * XXX We should be able to directly return
1603 			 * the inp here, without any checks.
1604 			 * Well unless both bound with SO_REUSEPORT?
1605 			 */
1606 			if (prison_flag(inp->inp_cred, PR_IP4))
1607 				goto found;
1608 			if (tmpinp == NULL)
1609 				tmpinp = inp;
1610 		}
1611 	}
1612 	if (tmpinp != NULL) {
1613 		inp = tmpinp;
1614 		goto found;
1615 	}
1616 
1617 #ifdef	RSS
1618 	/*
1619 	 * For incoming connections, we may wish to do a wildcard
1620 	 * match for an RSS-local socket.
1621 	 */
1622 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1623 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1624 #ifdef INET6
1625 		struct inpcb *local_wild_mapped = NULL;
1626 #endif
1627 		struct inpcb *jail_wild = NULL;
1628 		struct inpcbhead *head;
1629 		int injail;
1630 
1631 		/*
1632 		 * Order of socket selection - we always prefer jails.
1633 		 *      1. jailed, non-wild.
1634 		 *      2. jailed, wild.
1635 		 *      3. non-jailed, non-wild.
1636 		 *      4. non-jailed, wild.
1637 		 */
1638 
1639 		head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
1640 		    lport, 0, pcbgroup->ipg_hashmask)];
1641 		LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1642 #ifdef INET6
1643 			/* XXX inp locking */
1644 			if ((inp->inp_vflag & INP_IPV4) == 0)
1645 				continue;
1646 #endif
1647 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1648 			    inp->inp_lport != lport)
1649 				continue;
1650 
1651 			injail = prison_flag(inp->inp_cred, PR_IP4);
1652 			if (injail) {
1653 				if (prison_check_ip4(inp->inp_cred,
1654 				    &laddr) != 0)
1655 					continue;
1656 			} else {
1657 				if (local_exact != NULL)
1658 					continue;
1659 			}
1660 
1661 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1662 				if (injail)
1663 					goto found;
1664 				else
1665 					local_exact = inp;
1666 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1667 #ifdef INET6
1668 				/* XXX inp locking, NULL check */
1669 				if (inp->inp_vflag & INP_IPV6PROTO)
1670 					local_wild_mapped = inp;
1671 				else
1672 #endif
1673 					if (injail)
1674 						jail_wild = inp;
1675 					else
1676 						local_wild = inp;
1677 			}
1678 		} /* LIST_FOREACH */
1679 
1680 		inp = jail_wild;
1681 		if (inp == NULL)
1682 			inp = local_exact;
1683 		if (inp == NULL)
1684 			inp = local_wild;
1685 #ifdef INET6
1686 		if (inp == NULL)
1687 			inp = local_wild_mapped;
1688 #endif
1689 		if (inp != NULL)
1690 			goto found;
1691 	}
1692 #endif
1693 
1694 	/*
1695 	 * Then look for a wildcard match, if requested.
1696 	 */
1697 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1698 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1699 #ifdef INET6
1700 		struct inpcb *local_wild_mapped = NULL;
1701 #endif
1702 		struct inpcb *jail_wild = NULL;
1703 		struct inpcbhead *head;
1704 		int injail;
1705 
1706 		/*
1707 		 * Order of socket selection - we always prefer jails.
1708 		 *      1. jailed, non-wild.
1709 		 *      2. jailed, wild.
1710 		 *      3. non-jailed, non-wild.
1711 		 *      4. non-jailed, wild.
1712 		 */
1713 		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
1714 		    0, pcbinfo->ipi_wildmask)];
1715 		LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
1716 #ifdef INET6
1717 			/* XXX inp locking */
1718 			if ((inp->inp_vflag & INP_IPV4) == 0)
1719 				continue;
1720 #endif
1721 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1722 			    inp->inp_lport != lport)
1723 				continue;
1724 
1725 			injail = prison_flag(inp->inp_cred, PR_IP4);
1726 			if (injail) {
1727 				if (prison_check_ip4(inp->inp_cred,
1728 				    &laddr) != 0)
1729 					continue;
1730 			} else {
1731 				if (local_exact != NULL)
1732 					continue;
1733 			}
1734 
1735 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1736 				if (injail)
1737 					goto found;
1738 				else
1739 					local_exact = inp;
1740 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1741 #ifdef INET6
1742 				/* XXX inp locking, NULL check */
1743 				if (inp->inp_vflag & INP_IPV6PROTO)
1744 					local_wild_mapped = inp;
1745 				else
1746 #endif
1747 					if (injail)
1748 						jail_wild = inp;
1749 					else
1750 						local_wild = inp;
1751 			}
1752 		} /* LIST_FOREACH */
1753 		inp = jail_wild;
1754 		if (inp == NULL)
1755 			inp = local_exact;
1756 		if (inp == NULL)
1757 			inp = local_wild;
1758 #ifdef INET6
1759 		if (inp == NULL)
1760 			inp = local_wild_mapped;
1761 #endif
1762 		if (inp != NULL)
1763 			goto found;
1764 	} /* if (lookupflags & INPLOOKUP_WILDCARD) */
1765 	INP_GROUP_UNLOCK(pcbgroup);
1766 	return (NULL);
1767 
1768 found:
1769 	in_pcbref(inp);
1770 	INP_GROUP_UNLOCK(pcbgroup);
1771 	if (lookupflags & INPLOOKUP_WLOCKPCB) {
1772 		INP_WLOCK(inp);
1773 		if (in_pcbrele_wlocked(inp))
1774 			return (NULL);
1775 	} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1776 		INP_RLOCK(inp);
1777 		if (in_pcbrele_rlocked(inp))
1778 			return (NULL);
1779 	} else
1780 		panic("%s: locking bug", __func__);
1781 	return (inp);
1782 }
1783 #endif /* PCBGROUP */
1784 
1785 /*
1786  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
1787  * that the caller has locked the hash list, and will not perform any further
1788  * locking or reference operations on either the hash list or the connection.
1789  */
1790 static struct inpcb *
1791 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1792     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
1793     struct ifnet *ifp)
1794 {
1795 	struct inpcbhead *head;
1796 	struct inpcb *inp, *tmpinp;
1797 	u_short fport = fport_arg, lport = lport_arg;
1798 
1799 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1800 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1801 
1802 	INP_HASH_LOCK_ASSERT(pcbinfo);
1803 
1804 	/*
1805 	 * First look for an exact match.
1806 	 */
1807 	tmpinp = NULL;
1808 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1809 	    pcbinfo->ipi_hashmask)];
1810 	LIST_FOREACH(inp, head, inp_hash) {
1811 #ifdef INET6
1812 		/* XXX inp locking */
1813 		if ((inp->inp_vflag & INP_IPV4) == 0)
1814 			continue;
1815 #endif
1816 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1817 		    inp->inp_laddr.s_addr == laddr.s_addr &&
1818 		    inp->inp_fport == fport &&
1819 		    inp->inp_lport == lport) {
1820 			/*
1821 			 * XXX We should be able to directly return
1822 			 * the inp here, without any checks.
1823 			 * Well unless both bound with SO_REUSEPORT?
1824 			 */
1825 			if (prison_flag(inp->inp_cred, PR_IP4))
1826 				return (inp);
1827 			if (tmpinp == NULL)
1828 				tmpinp = inp;
1829 		}
1830 	}
1831 	if (tmpinp != NULL)
1832 		return (tmpinp);
1833 
1834 	/*
1835 	 * Then look for a wildcard match, if requested.
1836 	 */
1837 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1838 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1839 #ifdef INET6
1840 		struct inpcb *local_wild_mapped = NULL;
1841 #endif
1842 		struct inpcb *jail_wild = NULL;
1843 		int injail;
1844 
1845 		/*
1846 		 * Order of socket selection - we always prefer jails.
1847 		 *      1. jailed, non-wild.
1848 		 *      2. jailed, wild.
1849 		 *      3. non-jailed, non-wild.
1850 		 *      4. non-jailed, wild.
1851 		 */
1852 
1853 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1854 		    0, pcbinfo->ipi_hashmask)];
1855 		LIST_FOREACH(inp, head, inp_hash) {
1856 #ifdef INET6
1857 			/* XXX inp locking */
1858 			if ((inp->inp_vflag & INP_IPV4) == 0)
1859 				continue;
1860 #endif
1861 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1862 			    inp->inp_lport != lport)
1863 				continue;
1864 
1865 			injail = prison_flag(inp->inp_cred, PR_IP4);
1866 			if (injail) {
1867 				if (prison_check_ip4(inp->inp_cred,
1868 				    &laddr) != 0)
1869 					continue;
1870 			} else {
1871 				if (local_exact != NULL)
1872 					continue;
1873 			}
1874 
1875 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1876 				if (injail)
1877 					return (inp);
1878 				else
1879 					local_exact = inp;
1880 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1881 #ifdef INET6
1882 				/* XXX inp locking, NULL check */
1883 				if (inp->inp_vflag & INP_IPV6PROTO)
1884 					local_wild_mapped = inp;
1885 				else
1886 #endif
1887 					if (injail)
1888 						jail_wild = inp;
1889 					else
1890 						local_wild = inp;
1891 			}
1892 		} /* LIST_FOREACH */
1893 		if (jail_wild != NULL)
1894 			return (jail_wild);
1895 		if (local_exact != NULL)
1896 			return (local_exact);
1897 		if (local_wild != NULL)
1898 			return (local_wild);
1899 #ifdef INET6
1900 		if (local_wild_mapped != NULL)
1901 			return (local_wild_mapped);
1902 #endif
1903 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
1904 
1905 	return (NULL);
1906 }
1907 
1908 /*
1909  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
1910  * hash list lock, and will return the inpcb locked (i.e., requires
1911  * INPLOOKUP_LOCKPCB).
1912  */
1913 static struct inpcb *
1914 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1915     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
1916     struct ifnet *ifp)
1917 {
1918 	struct inpcb *inp;
1919 
1920 	INP_HASH_RLOCK(pcbinfo);
1921 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
1922 	    (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
1923 	if (inp != NULL) {
1924 		in_pcbref(inp);
1925 		INP_HASH_RUNLOCK(pcbinfo);
1926 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
1927 			INP_WLOCK(inp);
1928 			if (in_pcbrele_wlocked(inp))
1929 				return (NULL);
1930 		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1931 			INP_RLOCK(inp);
1932 			if (in_pcbrele_rlocked(inp))
1933 				return (NULL);
1934 		} else
1935 			panic("%s: locking bug", __func__);
1936 	} else
1937 		INP_HASH_RUNLOCK(pcbinfo);
1938 	return (inp);
1939 }
1940 
1941 /*
1942  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
1943  * from which a pre-calculated hash value may be extracted.
1944  *
1945  * Possibly more of this logic should be in in_pcbgroup.c.
1946  */
1947 struct inpcb *
1948 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
1949     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
1950 {
1951 #if defined(PCBGROUP) && !defined(RSS)
1952 	struct inpcbgroup *pcbgroup;
1953 #endif
1954 
1955 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1956 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1957 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1958 	    ("%s: LOCKPCB not set", __func__));
1959 
1960 	/*
1961 	 * When not using RSS, use connection groups in preference to the
1962 	 * reservation table when looking up 4-tuples.  When using RSS, just
1963 	 * use the reservation table, due to the cost of the Toeplitz hash
1964 	 * in software.
1965 	 *
1966 	 * XXXRW: This policy belongs in the pcbgroup code, as in principle
1967 	 * we could be doing RSS with a non-Toeplitz hash that is affordable
1968 	 * in software.
1969 	 */
1970 #if defined(PCBGROUP) && !defined(RSS)
1971 	if (in_pcbgroup_enabled(pcbinfo)) {
1972 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
1973 		    fport);
1974 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
1975 		    laddr, lport, lookupflags, ifp));
1976 	}
1977 #endif
1978 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
1979 	    lookupflags, ifp));
1980 }
1981 
1982 struct inpcb *
1983 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1984     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
1985     struct ifnet *ifp, struct mbuf *m)
1986 {
1987 #ifdef PCBGROUP
1988 	struct inpcbgroup *pcbgroup;
1989 #endif
1990 
1991 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1992 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1993 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1994 	    ("%s: LOCKPCB not set", __func__));
1995 
1996 #ifdef PCBGROUP
1997 	/*
1998 	 * If we can use a hardware-generated hash to look up the connection
1999 	 * group, use that connection group to find the inpcb.  Otherwise
2000 	 * fall back on a software hash -- or the reservation table if we're
2001 	 * using RSS.
2002 	 *
2003 	 * XXXRW: As above, that policy belongs in the pcbgroup code.
2004 	 */
2005 	if (in_pcbgroup_enabled(pcbinfo) &&
2006 	    !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2007 		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2008 		    m->m_pkthdr.flowid);
2009 		if (pcbgroup != NULL)
2010 			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2011 			    fport, laddr, lport, lookupflags, ifp));
2012 #ifndef RSS
2013 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2014 		    fport);
2015 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2016 		    laddr, lport, lookupflags, ifp));
2017 #endif
2018 	}
2019 #endif
2020 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2021 	    lookupflags, ifp));
2022 }
2023 #endif /* INET */
2024 
2025 /*
2026  * Insert PCB onto various hash lists.
2027  */
2028 static int
2029 in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
2030 {
2031 	struct inpcbhead *pcbhash;
2032 	struct inpcbporthead *pcbporthash;
2033 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2034 	struct inpcbport *phd;
2035 	u_int32_t hashkey_faddr;
2036 
2037 	INP_WLOCK_ASSERT(inp);
2038 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2039 
2040 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2041 	    ("in_pcbinshash: INP_INHASHLIST"));
2042 
2043 #ifdef INET6
2044 	if (inp->inp_vflag & INP_IPV6)
2045 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2046 	else
2047 #endif
2048 	hashkey_faddr = inp->inp_faddr.s_addr;
2049 
2050 	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2051 		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2052 
2053 	pcbporthash = &pcbinfo->ipi_porthashbase[
2054 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2055 
2056 	/*
2057 	 * Go through port list and look for a head for this lport.
2058 	 */
2059 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
2060 		if (phd->phd_port == inp->inp_lport)
2061 			break;
2062 	}
2063 	/*
2064 	 * If none exists, malloc one and tack it on.
2065 	 */
2066 	if (phd == NULL) {
2067 		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2068 		if (phd == NULL) {
2069 			return (ENOBUFS); /* XXX */
2070 		}
2071 		phd->phd_port = inp->inp_lport;
2072 		LIST_INIT(&phd->phd_pcblist);
2073 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2074 	}
2075 	inp->inp_phd = phd;
2076 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2077 	LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2078 	inp->inp_flags |= INP_INHASHLIST;
2079 #ifdef PCBGROUP
2080 	if (do_pcbgroup_update)
2081 		in_pcbgroup_update(inp);
2082 #endif
2083 	return (0);
2084 }
2085 
2086 /*
2087  * For now, there are two public interfaces to insert an inpcb into the hash
2088  * lists -- one that does update pcbgroups, and one that doesn't.  The latter
2089  * is used only in the TCP syncache, where in_pcbinshash is called before the
2090  * full 4-tuple is set for the inpcb, and we don't want to install in the
2091  * pcbgroup until later.
2092  *
2093  * XXXRW: This seems like a misfeature.  in_pcbinshash should always update
2094  * connection groups, and partially initialised inpcbs should not be exposed
2095  * to either reservation hash tables or pcbgroups.
2096  */
2097 int
2098 in_pcbinshash(struct inpcb *inp)
2099 {
2100 
2101 	return (in_pcbinshash_internal(inp, 1));
2102 }
2103 
2104 int
2105 in_pcbinshash_nopcbgroup(struct inpcb *inp)
2106 {
2107 
2108 	return (in_pcbinshash_internal(inp, 0));
2109 }
2110 
2111 /*
2112  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2113  * changed. NOTE: This does not handle the case of the lport changing (the
2114  * hashed port list would have to be updated as well), so the lport must
2115  * not change after in_pcbinshash() has been called.
2116  */
2117 void
2118 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2119 {
2120 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2121 	struct inpcbhead *head;
2122 	u_int32_t hashkey_faddr;
2123 
2124 	INP_WLOCK_ASSERT(inp);
2125 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2126 
2127 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2128 	    ("in_pcbrehash: !INP_INHASHLIST"));
2129 
2130 #ifdef INET6
2131 	if (inp->inp_vflag & INP_IPV6)
2132 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2133 	else
2134 #endif
2135 	hashkey_faddr = inp->inp_faddr.s_addr;
2136 
2137 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2138 		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2139 
2140 	LIST_REMOVE(inp, inp_hash);
2141 	LIST_INSERT_HEAD(head, inp, inp_hash);
2142 
2143 #ifdef PCBGROUP
2144 	if (m != NULL)
2145 		in_pcbgroup_update_mbuf(inp, m);
2146 	else
2147 		in_pcbgroup_update(inp);
2148 #endif
2149 }
2150 
2151 void
2152 in_pcbrehash(struct inpcb *inp)
2153 {
2154 
2155 	in_pcbrehash_mbuf(inp, NULL);
2156 }
2157 
2158 /*
2159  * Remove PCB from various lists.
2160  */
2161 static void
2162 in_pcbremlists(struct inpcb *inp)
2163 {
2164 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2165 
2166 	INP_INFO_WLOCK_ASSERT(pcbinfo);
2167 	INP_WLOCK_ASSERT(inp);
2168 
2169 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2170 	if (inp->inp_flags & INP_INHASHLIST) {
2171 		struct inpcbport *phd = inp->inp_phd;
2172 
2173 		INP_HASH_WLOCK(pcbinfo);
2174 		LIST_REMOVE(inp, inp_hash);
2175 		LIST_REMOVE(inp, inp_portlist);
2176 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
2177 			LIST_REMOVE(phd, phd_hash);
2178 			free(phd, M_PCB);
2179 		}
2180 		INP_HASH_WUNLOCK(pcbinfo);
2181 		inp->inp_flags &= ~INP_INHASHLIST;
2182 	}
2183 	LIST_REMOVE(inp, inp_list);
2184 	pcbinfo->ipi_count--;
2185 #ifdef PCBGROUP
2186 	in_pcbgroup_remove(inp);
2187 #endif
2188 }
2189 
2190 /*
2191  * A set label operation has occurred at the socket layer, propagate the
2192  * label change into the in_pcb for the socket.
2193  */
2194 void
2195 in_pcbsosetlabel(struct socket *so)
2196 {
2197 #ifdef MAC
2198 	struct inpcb *inp;
2199 
2200 	inp = sotoinpcb(so);
2201 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2202 
2203 	INP_WLOCK(inp);
2204 	SOCK_LOCK(so);
2205 	mac_inpcb_sosetlabel(so, inp);
2206 	SOCK_UNLOCK(so);
2207 	INP_WUNLOCK(inp);
2208 #endif
2209 }
2210 
2211 /*
2212  * ipport_tick runs once per second, determining if random port allocation
2213  * should be continued.  If more than ipport_randomcps ports have been
2214  * allocated in the last second, then we return to sequential port
2215  * allocation. We return to random allocation only once we drop below
2216  * ipport_randomcps for at least ipport_randomtime seconds.
2217  */
2218 static void
2219 ipport_tick(void *xtp)
2220 {
2221 	VNET_ITERATOR_DECL(vnet_iter);
2222 
2223 	VNET_LIST_RLOCK_NOSLEEP();
2224 	VNET_FOREACH(vnet_iter) {
2225 		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
2226 		if (V_ipport_tcpallocs <=
2227 		    V_ipport_tcplastcount + V_ipport_randomcps) {
2228 			if (V_ipport_stoprandom > 0)
2229 				V_ipport_stoprandom--;
2230 		} else
2231 			V_ipport_stoprandom = V_ipport_randomtime;
2232 		V_ipport_tcplastcount = V_ipport_tcpallocs;
2233 		CURVNET_RESTORE();
2234 	}
2235 	VNET_LIST_RUNLOCK_NOSLEEP();
2236 	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2237 }
2238 
2239 static void
2240 ip_fini(void *xtp)
2241 {
2242 
2243 	callout_stop(&ipport_tick_callout);
2244 }
2245 
2246 /*
2247  * The ipport_callout should start running at about the time we attach the
2248  * inet or inet6 domains.
2249  */
2250 static void
2251 ipport_tick_init(const void *unused __unused)
2252 {
2253 
2254 	/* Start ipport_tick. */
2255 	callout_init(&ipport_tick_callout, 1);
2256 	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2257 	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2258 		SHUTDOWN_PRI_DEFAULT);
2259 }
2260 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2261     ipport_tick_init, NULL);
2262 
2263 void
2264 inp_wlock(struct inpcb *inp)
2265 {
2266 
2267 	INP_WLOCK(inp);
2268 }
2269 
2270 void
2271 inp_wunlock(struct inpcb *inp)
2272 {
2273 
2274 	INP_WUNLOCK(inp);
2275 }
2276 
2277 void
2278 inp_rlock(struct inpcb *inp)
2279 {
2280 
2281 	INP_RLOCK(inp);
2282 }
2283 
2284 void
2285 inp_runlock(struct inpcb *inp)
2286 {
2287 
2288 	INP_RUNLOCK(inp);
2289 }
2290 
2291 #ifdef INVARIANTS
2292 void
2293 inp_lock_assert(struct inpcb *inp)
2294 {
2295 
2296 	INP_WLOCK_ASSERT(inp);
2297 }
2298 
2299 void
2300 inp_unlock_assert(struct inpcb *inp)
2301 {
2302 
2303 	INP_UNLOCK_ASSERT(inp);
2304 }
2305 #endif
2306 
2307 void
2308 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2309 {
2310 	struct inpcb *inp;
2311 
2312 	INP_INFO_RLOCK(&V_tcbinfo);
2313 	LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2314 		INP_WLOCK(inp);
2315 		func(inp, arg);
2316 		INP_WUNLOCK(inp);
2317 	}
2318 	INP_INFO_RUNLOCK(&V_tcbinfo);
2319 }
2320 
2321 struct socket *
2322 inp_inpcbtosocket(struct inpcb *inp)
2323 {
2324 
2325 	INP_WLOCK_ASSERT(inp);
2326 	return (inp->inp_socket);
2327 }
2328 
2329 struct tcpcb *
2330 inp_inpcbtotcpcb(struct inpcb *inp)
2331 {
2332 
2333 	INP_WLOCK_ASSERT(inp);
2334 	return ((struct tcpcb *)inp->inp_ppcb);
2335 }
2336 
2337 int
2338 inp_ip_tos_get(const struct inpcb *inp)
2339 {
2340 
2341 	return (inp->inp_ip_tos);
2342 }
2343 
2344 void
2345 inp_ip_tos_set(struct inpcb *inp, int val)
2346 {
2347 
2348 	inp->inp_ip_tos = val;
2349 }
2350 
2351 void
2352 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2353     uint32_t *faddr, uint16_t *fp)
2354 {
2355 
2356 	INP_LOCK_ASSERT(inp);
2357 	*laddr = inp->inp_laddr.s_addr;
2358 	*faddr = inp->inp_faddr.s_addr;
2359 	*lp = inp->inp_lport;
2360 	*fp = inp->inp_fport;
2361 }
2362 
2363 struct inpcb *
2364 so_sotoinpcb(struct socket *so)
2365 {
2366 
2367 	return (sotoinpcb(so));
2368 }
2369 
2370 struct tcpcb *
2371 so_sototcpcb(struct socket *so)
2372 {
2373 
2374 	return (sototcpcb(so));
2375 }
2376 
2377 #ifdef DDB
2378 static void
2379 db_print_indent(int indent)
2380 {
2381 	int i;
2382 
2383 	for (i = 0; i < indent; i++)
2384 		db_printf(" ");
2385 }
2386 
2387 static void
2388 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2389 {
2390 	char faddr_str[48], laddr_str[48];
2391 
2392 	db_print_indent(indent);
2393 	db_printf("%s at %p\n", name, inc);
2394 
2395 	indent += 2;
2396 
2397 #ifdef INET6
2398 	if (inc->inc_flags & INC_ISIPV6) {
2399 		/* IPv6. */
2400 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
2401 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
2402 	} else
2403 #endif
2404 	{
2405 		/* IPv4. */
2406 		inet_ntoa_r(inc->inc_laddr, laddr_str);
2407 		inet_ntoa_r(inc->inc_faddr, faddr_str);
2408 	}
2409 	db_print_indent(indent);
2410 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
2411 	    ntohs(inc->inc_lport));
2412 	db_print_indent(indent);
2413 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
2414 	    ntohs(inc->inc_fport));
2415 }
2416 
2417 static void
2418 db_print_inpflags(int inp_flags)
2419 {
2420 	int comma;
2421 
2422 	comma = 0;
2423 	if (inp_flags & INP_RECVOPTS) {
2424 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2425 		comma = 1;
2426 	}
2427 	if (inp_flags & INP_RECVRETOPTS) {
2428 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2429 		comma = 1;
2430 	}
2431 	if (inp_flags & INP_RECVDSTADDR) {
2432 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2433 		comma = 1;
2434 	}
2435 	if (inp_flags & INP_HDRINCL) {
2436 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
2437 		comma = 1;
2438 	}
2439 	if (inp_flags & INP_HIGHPORT) {
2440 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2441 		comma = 1;
2442 	}
2443 	if (inp_flags & INP_LOWPORT) {
2444 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
2445 		comma = 1;
2446 	}
2447 	if (inp_flags & INP_ANONPORT) {
2448 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
2449 		comma = 1;
2450 	}
2451 	if (inp_flags & INP_RECVIF) {
2452 		db_printf("%sINP_RECVIF", comma ? ", " : "");
2453 		comma = 1;
2454 	}
2455 	if (inp_flags & INP_MTUDISC) {
2456 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
2457 		comma = 1;
2458 	}
2459 	if (inp_flags & INP_RECVTTL) {
2460 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
2461 		comma = 1;
2462 	}
2463 	if (inp_flags & INP_DONTFRAG) {
2464 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2465 		comma = 1;
2466 	}
2467 	if (inp_flags & INP_RECVTOS) {
2468 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
2469 		comma = 1;
2470 	}
2471 	if (inp_flags & IN6P_IPV6_V6ONLY) {
2472 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2473 		comma = 1;
2474 	}
2475 	if (inp_flags & IN6P_PKTINFO) {
2476 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2477 		comma = 1;
2478 	}
2479 	if (inp_flags & IN6P_HOPLIMIT) {
2480 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2481 		comma = 1;
2482 	}
2483 	if (inp_flags & IN6P_HOPOPTS) {
2484 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2485 		comma = 1;
2486 	}
2487 	if (inp_flags & IN6P_DSTOPTS) {
2488 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2489 		comma = 1;
2490 	}
2491 	if (inp_flags & IN6P_RTHDR) {
2492 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2493 		comma = 1;
2494 	}
2495 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
2496 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2497 		comma = 1;
2498 	}
2499 	if (inp_flags & IN6P_TCLASS) {
2500 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2501 		comma = 1;
2502 	}
2503 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
2504 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2505 		comma = 1;
2506 	}
2507 	if (inp_flags & INP_TIMEWAIT) {
2508 		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
2509 		comma  = 1;
2510 	}
2511 	if (inp_flags & INP_ONESBCAST) {
2512 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2513 		comma  = 1;
2514 	}
2515 	if (inp_flags & INP_DROPPED) {
2516 		db_printf("%sINP_DROPPED", comma ? ", " : "");
2517 		comma  = 1;
2518 	}
2519 	if (inp_flags & INP_SOCKREF) {
2520 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
2521 		comma  = 1;
2522 	}
2523 	if (inp_flags & IN6P_RFC2292) {
2524 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2525 		comma = 1;
2526 	}
2527 	if (inp_flags & IN6P_MTU) {
2528 		db_printf("IN6P_MTU%s", comma ? ", " : "");
2529 		comma = 1;
2530 	}
2531 }
2532 
2533 static void
2534 db_print_inpvflag(u_char inp_vflag)
2535 {
2536 	int comma;
2537 
2538 	comma = 0;
2539 	if (inp_vflag & INP_IPV4) {
2540 		db_printf("%sINP_IPV4", comma ? ", " : "");
2541 		comma  = 1;
2542 	}
2543 	if (inp_vflag & INP_IPV6) {
2544 		db_printf("%sINP_IPV6", comma ? ", " : "");
2545 		comma  = 1;
2546 	}
2547 	if (inp_vflag & INP_IPV6PROTO) {
2548 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2549 		comma  = 1;
2550 	}
2551 }
2552 
2553 static void
2554 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2555 {
2556 
2557 	db_print_indent(indent);
2558 	db_printf("%s at %p\n", name, inp);
2559 
2560 	indent += 2;
2561 
2562 	db_print_indent(indent);
2563 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2564 
2565 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2566 
2567 	db_print_indent(indent);
2568 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
2569 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2570 
2571 	db_print_indent(indent);
2572 	db_printf("inp_label: %p   inp_flags: 0x%x (",
2573 	   inp->inp_label, inp->inp_flags);
2574 	db_print_inpflags(inp->inp_flags);
2575 	db_printf(")\n");
2576 
2577 	db_print_indent(indent);
2578 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
2579 	    inp->inp_vflag);
2580 	db_print_inpvflag(inp->inp_vflag);
2581 	db_printf(")\n");
2582 
2583 	db_print_indent(indent);
2584 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
2585 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2586 
2587 	db_print_indent(indent);
2588 #ifdef INET6
2589 	if (inp->inp_vflag & INP_IPV6) {
2590 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
2591 		    "in6p_moptions: %p\n", inp->in6p_options,
2592 		    inp->in6p_outputopts, inp->in6p_moptions);
2593 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
2594 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2595 		    inp->in6p_hops);
2596 	} else
2597 #endif
2598 	{
2599 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
2600 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2601 		    inp->inp_options, inp->inp_moptions);
2602 	}
2603 
2604 	db_print_indent(indent);
2605 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
2606 	    (uintmax_t)inp->inp_gencnt);
2607 }
2608 
2609 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
2610 {
2611 	struct inpcb *inp;
2612 
2613 	if (!have_addr) {
2614 		db_printf("usage: show inpcb <addr>\n");
2615 		return;
2616 	}
2617 	inp = (struct inpcb *)addr;
2618 
2619 	db_print_inpcb(inp, "inpcb", 0);
2620 }
2621 #endif /* DDB */
2622