xref: /freebsd/sys/netinet/in_pcb.c (revision 81b22a98)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1991, 1993, 1995
5  *	The Regents of the University of California.
6  * Copyright (c) 2007-2009 Robert N. M. Watson
7  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8  * All rights reserved.
9  *
10  * Portions of this software were developed by Robert N. M. Watson under
11  * contract to Juniper Networks, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include "opt_ddb.h"
44 #include "opt_ipsec.h"
45 #include "opt_inet.h"
46 #include "opt_inet6.h"
47 #include "opt_ratelimit.h"
48 #include "opt_pcbgroup.h"
49 #include "opt_route.h"
50 #include "opt_rss.h"
51 
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/lock.h>
55 #include <sys/malloc.h>
56 #include <sys/mbuf.h>
57 #include <sys/callout.h>
58 #include <sys/eventhandler.h>
59 #include <sys/domain.h>
60 #include <sys/protosw.h>
61 #include <sys/smp.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sockio.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/refcount.h>
68 #include <sys/jail.h>
69 #include <sys/kernel.h>
70 #include <sys/sysctl.h>
71 
72 #ifdef DDB
73 #include <ddb/ddb.h>
74 #endif
75 
76 #include <vm/uma.h>
77 #include <vm/vm.h>
78 
79 #include <net/if.h>
80 #include <net/if_var.h>
81 #include <net/if_types.h>
82 #include <net/if_llatbl.h>
83 #include <net/route.h>
84 #include <net/rss_config.h>
85 #include <net/vnet.h>
86 
87 #if defined(INET) || defined(INET6)
88 #include <netinet/in.h>
89 #include <netinet/in_pcb.h>
90 #include <netinet/in_pcb_var.h>
91 #ifdef INET
92 #include <netinet/in_var.h>
93 #include <netinet/in_fib.h>
94 #endif
95 #include <netinet/ip_var.h>
96 #include <netinet/tcp_var.h>
97 #ifdef TCPHPTS
98 #include <netinet/tcp_hpts.h>
99 #endif
100 #include <netinet/udp.h>
101 #include <netinet/udp_var.h>
102 #ifdef INET6
103 #include <netinet/ip6.h>
104 #include <netinet6/in6_pcb.h>
105 #include <netinet6/in6_var.h>
106 #include <netinet6/ip6_var.h>
107 #endif /* INET6 */
108 #include <net/route/nhop.h>
109 #endif
110 
111 #include <netipsec/ipsec_support.h>
112 
113 #include <security/mac/mac_framework.h>
114 
115 #define	INPCBLBGROUP_SIZMIN	8
116 #define	INPCBLBGROUP_SIZMAX	256
117 
118 static struct callout	ipport_tick_callout;
119 
120 /*
121  * These configure the range of local port addresses assigned to
122  * "unspecified" outgoing connections/packets/whatever.
123  */
124 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
125 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
126 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
127 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
128 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
129 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
130 
131 /*
132  * Reserved ports accessible only to root. There are significant
133  * security considerations that must be accounted for when changing these,
134  * but the security benefits can be great. Please be careful.
135  */
136 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
137 VNET_DEFINE(int, ipport_reservedlow);
138 
139 /* Variables dealing with random ephemeral port allocation. */
140 VNET_DEFINE(int, ipport_randomized) = 1;	/* user controlled via sysctl */
141 VNET_DEFINE(int, ipport_randomcps) = 10;	/* user controlled via sysctl */
142 VNET_DEFINE(int, ipport_randomtime) = 45;	/* user controlled via sysctl */
143 VNET_DEFINE(int, ipport_stoprandom);		/* toggled by ipport_tick */
144 VNET_DEFINE(int, ipport_tcpallocs);
145 VNET_DEFINE_STATIC(int, ipport_tcplastcount);
146 
147 #define	V_ipport_tcplastcount		VNET(ipport_tcplastcount)
148 
149 static void	in_pcbremlists(struct inpcb *inp);
150 #ifdef INET
151 static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
152 			    struct in_addr faddr, u_int fport_arg,
153 			    struct in_addr laddr, u_int lport_arg,
154 			    int lookupflags, struct ifnet *ifp,
155 			    uint8_t numa_domain);
156 
157 #define RANGECHK(var, min, max) \
158 	if ((var) < (min)) { (var) = (min); } \
159 	else if ((var) > (max)) { (var) = (max); }
160 
161 static int
162 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
163 {
164 	int error;
165 
166 	error = sysctl_handle_int(oidp, arg1, arg2, req);
167 	if (error == 0) {
168 		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
169 		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
170 		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
171 		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
172 		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
173 		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
174 	}
175 	return (error);
176 }
177 
178 #undef RANGECHK
179 
180 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
181     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
182     "IP Ports");
183 
184 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
185     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
186     &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
187     "");
188 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
189     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
190     &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
191     "");
192 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
193     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
194     &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
195     "");
196 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
197     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
198     &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
199     "");
200 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
201     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
202     &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
203     "");
204 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
205     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
206     &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
207     "");
208 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
209 	CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
210 	&VNET_NAME(ipport_reservedhigh), 0, "");
211 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
212 	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
213 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
214 	CTLFLAG_VNET | CTLFLAG_RW,
215 	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
216 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
217 	CTLFLAG_VNET | CTLFLAG_RW,
218 	&VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
219 	"allocations before switching to a sequental one");
220 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
221 	CTLFLAG_VNET | CTLFLAG_RW,
222 	&VNET_NAME(ipport_randomtime), 0,
223 	"Minimum time to keep sequental port "
224 	"allocation before switching to a random one");
225 
226 #ifdef RATELIMIT
227 counter_u64_t rate_limit_new;
228 counter_u64_t rate_limit_chg;
229 counter_u64_t rate_limit_active;
230 counter_u64_t rate_limit_alloc_fail;
231 counter_u64_t rate_limit_set_ok;
232 
233 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
234     "IP Rate Limiting");
235 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
236     &rate_limit_active, "Active rate limited connections");
237 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
238    &rate_limit_alloc_fail, "Rate limited connection failures");
239 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
240    &rate_limit_set_ok, "Rate limited setting succeeded");
241 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
242    &rate_limit_new, "Total Rate limit new attempts");
243 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
244    &rate_limit_chg, "Total Rate limited change attempts");
245 
246 #endif /* RATELIMIT */
247 
248 #endif /* INET */
249 
250 /*
251  * in_pcb.c: manage the Protocol Control Blocks.
252  *
253  * NOTE: It is assumed that most of these functions will be called with
254  * the pcbinfo lock held, and often, the inpcb lock held, as these utility
255  * functions often modify hash chains or addresses in pcbs.
256  */
257 
258 static struct inpcblbgroup *
259 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, u_char vflag,
260     uint16_t port, const union in_dependaddr *addr, int size,
261     uint8_t numa_domain)
262 {
263 	struct inpcblbgroup *grp;
264 	size_t bytes;
265 
266 	bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
267 	grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
268 	if (!grp)
269 		return (NULL);
270 	grp->il_vflag = vflag;
271 	grp->il_lport = port;
272 	grp->il_numa_domain = numa_domain;
273 	grp->il_dependladdr = *addr;
274 	grp->il_inpsiz = size;
275 	CK_LIST_INSERT_HEAD(hdr, grp, il_list);
276 	return (grp);
277 }
278 
279 static void
280 in_pcblbgroup_free_deferred(epoch_context_t ctx)
281 {
282 	struct inpcblbgroup *grp;
283 
284 	grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
285 	free(grp, M_PCB);
286 }
287 
288 static void
289 in_pcblbgroup_free(struct inpcblbgroup *grp)
290 {
291 
292 	CK_LIST_REMOVE(grp, il_list);
293 	NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
294 }
295 
296 static struct inpcblbgroup *
297 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
298     struct inpcblbgroup *old_grp, int size)
299 {
300 	struct inpcblbgroup *grp;
301 	int i;
302 
303 	grp = in_pcblbgroup_alloc(hdr, old_grp->il_vflag,
304 	    old_grp->il_lport, &old_grp->il_dependladdr, size,
305 	    old_grp->il_numa_domain);
306 	if (grp == NULL)
307 		return (NULL);
308 
309 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
310 	    ("invalid new local group size %d and old local group count %d",
311 	     grp->il_inpsiz, old_grp->il_inpcnt));
312 
313 	for (i = 0; i < old_grp->il_inpcnt; ++i)
314 		grp->il_inp[i] = old_grp->il_inp[i];
315 	grp->il_inpcnt = old_grp->il_inpcnt;
316 	in_pcblbgroup_free(old_grp);
317 	return (grp);
318 }
319 
320 /*
321  * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
322  * and shrink group if possible.
323  */
324 static void
325 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
326     int i)
327 {
328 	struct inpcblbgroup *grp, *new_grp;
329 
330 	grp = *grpp;
331 	for (; i + 1 < grp->il_inpcnt; ++i)
332 		grp->il_inp[i] = grp->il_inp[i + 1];
333 	grp->il_inpcnt--;
334 
335 	if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
336 	    grp->il_inpcnt <= grp->il_inpsiz / 4) {
337 		/* Shrink this group. */
338 		new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
339 		if (new_grp != NULL)
340 			*grpp = new_grp;
341 	}
342 }
343 
344 /*
345  * Add PCB to load balance group for SO_REUSEPORT_LB option.
346  */
347 static int
348 in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
349 {
350 	const static struct timeval interval = { 60, 0 };
351 	static struct timeval lastprint;
352 	struct inpcbinfo *pcbinfo;
353 	struct inpcblbgrouphead *hdr;
354 	struct inpcblbgroup *grp;
355 	uint32_t idx;
356 
357 	pcbinfo = inp->inp_pcbinfo;
358 
359 	INP_WLOCK_ASSERT(inp);
360 	INP_HASH_WLOCK_ASSERT(pcbinfo);
361 
362 	/*
363 	 * Don't allow jailed socket to join local group.
364 	 */
365 	if (inp->inp_socket != NULL && jailed(inp->inp_socket->so_cred))
366 		return (0);
367 
368 #ifdef INET6
369 	/*
370 	 * Don't allow IPv4 mapped INET6 wild socket.
371 	 */
372 	if ((inp->inp_vflag & INP_IPV4) &&
373 	    inp->inp_laddr.s_addr == INADDR_ANY &&
374 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
375 		return (0);
376 	}
377 #endif
378 
379 	idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
380 	hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
381 	CK_LIST_FOREACH(grp, hdr, il_list) {
382 		if (grp->il_vflag == inp->inp_vflag &&
383 		    grp->il_lport == inp->inp_lport &&
384 		    grp->il_numa_domain == numa_domain &&
385 		    memcmp(&grp->il_dependladdr,
386 		    &inp->inp_inc.inc_ie.ie_dependladdr,
387 		    sizeof(grp->il_dependladdr)) == 0)
388 			break;
389 	}
390 	if (grp == NULL) {
391 		/* Create new load balance group. */
392 		grp = in_pcblbgroup_alloc(hdr, inp->inp_vflag,
393 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
394 		    INPCBLBGROUP_SIZMIN, numa_domain);
395 		if (grp == NULL)
396 			return (ENOBUFS);
397 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
398 		if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
399 			if (ratecheck(&lastprint, &interval))
400 				printf("lb group port %d, limit reached\n",
401 				    ntohs(grp->il_lport));
402 			return (0);
403 		}
404 
405 		/* Expand this local group. */
406 		grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
407 		if (grp == NULL)
408 			return (ENOBUFS);
409 	}
410 
411 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
412 	    ("invalid local group size %d and count %d", grp->il_inpsiz,
413 	    grp->il_inpcnt));
414 
415 	grp->il_inp[grp->il_inpcnt] = inp;
416 	grp->il_inpcnt++;
417 	return (0);
418 }
419 
420 /*
421  * Remove PCB from load balance group.
422  */
423 static void
424 in_pcbremlbgrouphash(struct inpcb *inp)
425 {
426 	struct inpcbinfo *pcbinfo;
427 	struct inpcblbgrouphead *hdr;
428 	struct inpcblbgroup *grp;
429 	int i;
430 
431 	pcbinfo = inp->inp_pcbinfo;
432 
433 	INP_WLOCK_ASSERT(inp);
434 	INP_HASH_WLOCK_ASSERT(pcbinfo);
435 
436 	hdr = &pcbinfo->ipi_lbgrouphashbase[
437 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
438 	CK_LIST_FOREACH(grp, hdr, il_list) {
439 		for (i = 0; i < grp->il_inpcnt; ++i) {
440 			if (grp->il_inp[i] != inp)
441 				continue;
442 
443 			if (grp->il_inpcnt == 1) {
444 				/* We are the last, free this local group. */
445 				in_pcblbgroup_free(grp);
446 			} else {
447 				/* Pull up inpcbs, shrink group if possible. */
448 				in_pcblbgroup_reorder(hdr, &grp, i);
449 			}
450 			return;
451 		}
452 	}
453 }
454 
455 int
456 in_pcblbgroup_numa(struct inpcb *inp, int arg)
457 {
458 	struct inpcbinfo *pcbinfo;
459 	struct inpcblbgrouphead *hdr;
460 	struct inpcblbgroup *grp;
461 	int err, i;
462 	uint8_t numa_domain;
463 
464 	switch (arg) {
465 	case TCP_REUSPORT_LB_NUMA_NODOM:
466 		numa_domain = M_NODOM;
467 		break;
468 	case TCP_REUSPORT_LB_NUMA_CURDOM:
469 		numa_domain = PCPU_GET(domain);
470 		break;
471 	default:
472 		if (arg < 0 || arg >= vm_ndomains)
473 			return (EINVAL);
474 		numa_domain = arg;
475 	}
476 
477 	err = 0;
478 	pcbinfo = inp->inp_pcbinfo;
479 	INP_WLOCK_ASSERT(inp);
480 	INP_HASH_WLOCK(pcbinfo);
481 	hdr = &pcbinfo->ipi_lbgrouphashbase[
482 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
483 	CK_LIST_FOREACH(grp, hdr, il_list) {
484 		for (i = 0; i < grp->il_inpcnt; ++i) {
485 			if (grp->il_inp[i] != inp)
486 				continue;
487 
488 			if (grp->il_numa_domain == numa_domain) {
489 				goto abort_with_hash_wlock;
490 			}
491 
492 			/* Remove it from the old group. */
493 			in_pcbremlbgrouphash(inp);
494 
495 			/* Add it to the new group based on numa domain. */
496 			in_pcbinslbgrouphash(inp, numa_domain);
497 			goto abort_with_hash_wlock;
498 		}
499 	}
500 	err = ENOENT;
501 abort_with_hash_wlock:
502 	INP_HASH_WUNLOCK(pcbinfo);
503 	return (err);
504 }
505 
506 /*
507  * Different protocols initialize their inpcbs differently - giving
508  * different name to the lock.  But they all are disposed the same.
509  */
510 static void
511 inpcb_fini(void *mem, int size)
512 {
513 	struct inpcb *inp = mem;
514 
515 	INP_LOCK_DESTROY(inp);
516 }
517 
518 /*
519  * Initialize an inpcbinfo -- we should be able to reduce the number of
520  * arguments in time.
521  */
522 void
523 in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
524     struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
525     char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
526 {
527 
528 	porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
529 
530 	INP_INFO_LOCK_INIT(pcbinfo, name);
531 	INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash");	/* XXXRW: argument? */
532 	INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
533 #ifdef VIMAGE
534 	pcbinfo->ipi_vnet = curvnet;
535 #endif
536 	pcbinfo->ipi_listhead = listhead;
537 	CK_LIST_INIT(pcbinfo->ipi_listhead);
538 	pcbinfo->ipi_count = 0;
539 	pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
540 	    &pcbinfo->ipi_hashmask);
541 	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
542 	    &pcbinfo->ipi_porthashmask);
543 	pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
544 	    &pcbinfo->ipi_lbgrouphashmask);
545 #ifdef PCBGROUP
546 	in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
547 #endif
548 	pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
549 	    NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
550 	uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
551 	uma_zone_set_warning(pcbinfo->ipi_zone,
552 	    "kern.ipc.maxsockets limit reached");
553 }
554 
555 /*
556  * Destroy an inpcbinfo.
557  */
558 void
559 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
560 {
561 
562 	KASSERT(pcbinfo->ipi_count == 0,
563 	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
564 
565 	hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
566 	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
567 	    pcbinfo->ipi_porthashmask);
568 	hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
569 	    pcbinfo->ipi_lbgrouphashmask);
570 #ifdef PCBGROUP
571 	in_pcbgroup_destroy(pcbinfo);
572 #endif
573 	uma_zdestroy(pcbinfo->ipi_zone);
574 	INP_LIST_LOCK_DESTROY(pcbinfo);
575 	INP_HASH_LOCK_DESTROY(pcbinfo);
576 	INP_INFO_LOCK_DESTROY(pcbinfo);
577 }
578 
579 /*
580  * Allocate a PCB and associate it with the socket.
581  * On success return with the PCB locked.
582  */
583 int
584 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
585 {
586 	struct inpcb *inp;
587 	int error;
588 
589 	error = 0;
590 	inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
591 	if (inp == NULL)
592 		return (ENOBUFS);
593 	bzero(&inp->inp_start_zero, inp_zero_size);
594 #ifdef NUMA
595 	inp->inp_numa_domain = M_NODOM;
596 #endif
597 	inp->inp_pcbinfo = pcbinfo;
598 	inp->inp_socket = so;
599 	inp->inp_cred = crhold(so->so_cred);
600 	inp->inp_inc.inc_fibnum = so->so_fibnum;
601 #ifdef MAC
602 	error = mac_inpcb_init(inp, M_NOWAIT);
603 	if (error != 0)
604 		goto out;
605 	mac_inpcb_create(so, inp);
606 #endif
607 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
608 	error = ipsec_init_pcbpolicy(inp);
609 	if (error != 0) {
610 #ifdef MAC
611 		mac_inpcb_destroy(inp);
612 #endif
613 		goto out;
614 	}
615 #endif /*IPSEC*/
616 #ifdef INET6
617 	if (INP_SOCKAF(so) == AF_INET6) {
618 		inp->inp_vflag |= INP_IPV6PROTO;
619 		if (V_ip6_v6only)
620 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
621 	}
622 #endif
623 	INP_WLOCK(inp);
624 	INP_LIST_WLOCK(pcbinfo);
625 	CK_LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
626 	pcbinfo->ipi_count++;
627 	so->so_pcb = (caddr_t)inp;
628 #ifdef INET6
629 	if (V_ip6_auto_flowlabel)
630 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
631 #endif
632 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
633 	refcount_init(&inp->inp_refcount, 1);	/* Reference from inpcbinfo */
634 
635 	/*
636 	 * Routes in inpcb's can cache L2 as well; they are guaranteed
637 	 * to be cleaned up.
638 	 */
639 	inp->inp_route.ro_flags = RT_LLE_CACHE;
640 	INP_LIST_WUNLOCK(pcbinfo);
641 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
642 out:
643 	if (error != 0) {
644 		crfree(inp->inp_cred);
645 		uma_zfree(pcbinfo->ipi_zone, inp);
646 	}
647 #endif
648 	return (error);
649 }
650 
651 #ifdef INET
652 int
653 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
654 {
655 	int anonport, error;
656 
657 	KASSERT(nam == NULL || nam->sa_family == AF_INET,
658 	    ("%s: invalid address family for %p", __func__, nam));
659 	KASSERT(nam == NULL || nam->sa_len == sizeof(struct sockaddr_in),
660 	    ("%s: invalid address length for %p", __func__, nam));
661 	INP_WLOCK_ASSERT(inp);
662 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
663 
664 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
665 		return (EINVAL);
666 	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
667 	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
668 	    &inp->inp_lport, cred);
669 	if (error)
670 		return (error);
671 	if (in_pcbinshash(inp) != 0) {
672 		inp->inp_laddr.s_addr = INADDR_ANY;
673 		inp->inp_lport = 0;
674 		return (EAGAIN);
675 	}
676 	if (anonport)
677 		inp->inp_flags |= INP_ANONPORT;
678 	return (0);
679 }
680 #endif
681 
682 #if defined(INET) || defined(INET6)
683 /*
684  * Assign a local port like in_pcb_lport(), but also used with connect()
685  * and a foreign address and port.  If fsa is non-NULL, choose a local port
686  * that is unused with those, otherwise one that is completely unused.
687  * lsa can be NULL for IPv6.
688  */
689 int
690 in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
691     struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
692 {
693 	struct inpcbinfo *pcbinfo;
694 	struct inpcb *tmpinp;
695 	unsigned short *lastport;
696 	int count, dorandom, error;
697 	u_short aux, first, last, lport;
698 #ifdef INET
699 	struct in_addr laddr, faddr;
700 #endif
701 #ifdef INET6
702 	struct in6_addr *laddr6, *faddr6;
703 #endif
704 
705 	pcbinfo = inp->inp_pcbinfo;
706 
707 	/*
708 	 * Because no actual state changes occur here, a global write lock on
709 	 * the pcbinfo isn't required.
710 	 */
711 	INP_LOCK_ASSERT(inp);
712 	INP_HASH_LOCK_ASSERT(pcbinfo);
713 
714 	if (inp->inp_flags & INP_HIGHPORT) {
715 		first = V_ipport_hifirstauto;	/* sysctl */
716 		last  = V_ipport_hilastauto;
717 		lastport = &pcbinfo->ipi_lasthi;
718 	} else if (inp->inp_flags & INP_LOWPORT) {
719 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
720 		if (error)
721 			return (error);
722 		first = V_ipport_lowfirstauto;	/* 1023 */
723 		last  = V_ipport_lowlastauto;	/* 600 */
724 		lastport = &pcbinfo->ipi_lastlow;
725 	} else {
726 		first = V_ipport_firstauto;	/* sysctl */
727 		last  = V_ipport_lastauto;
728 		lastport = &pcbinfo->ipi_lastport;
729 	}
730 	/*
731 	 * For UDP(-Lite), use random port allocation as long as the user
732 	 * allows it.  For TCP (and as of yet unknown) connections,
733 	 * use random port allocation only if the user allows it AND
734 	 * ipport_tick() allows it.
735 	 */
736 	if (V_ipport_randomized &&
737 		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
738 		pcbinfo == &V_ulitecbinfo))
739 		dorandom = 1;
740 	else
741 		dorandom = 0;
742 	/*
743 	 * It makes no sense to do random port allocation if
744 	 * we have the only port available.
745 	 */
746 	if (first == last)
747 		dorandom = 0;
748 	/* Make sure to not include UDP(-Lite) packets in the count. */
749 	if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
750 		V_ipport_tcpallocs++;
751 	/*
752 	 * Instead of having two loops further down counting up or down
753 	 * make sure that first is always <= last and go with only one
754 	 * code path implementing all logic.
755 	 */
756 	if (first > last) {
757 		aux = first;
758 		first = last;
759 		last = aux;
760 	}
761 
762 #ifdef INET
763 	laddr.s_addr = INADDR_ANY;
764 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
765 		if (lsa != NULL)
766 			laddr = ((struct sockaddr_in *)lsa)->sin_addr;
767 		if (fsa != NULL)
768 			faddr = ((struct sockaddr_in *)fsa)->sin_addr;
769 	}
770 #endif
771 #ifdef INET6
772 	laddr6 = NULL;
773 	if ((inp->inp_vflag & INP_IPV6) != 0) {
774 		if (lsa != NULL)
775 			laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
776 		if (fsa != NULL)
777 			faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
778 	}
779 #endif
780 
781 	tmpinp = NULL;
782 	lport = *lportp;
783 
784 	if (dorandom)
785 		*lastport = first + (arc4random() % (last - first));
786 
787 	count = last - first;
788 
789 	do {
790 		if (count-- < 0)	/* completely used? */
791 			return (EADDRNOTAVAIL);
792 		++*lastport;
793 		if (*lastport < first || *lastport > last)
794 			*lastport = first;
795 		lport = htons(*lastport);
796 
797 		if (fsa != NULL) {
798 #ifdef INET
799 			if (lsa->sa_family == AF_INET) {
800 				tmpinp = in_pcblookup_hash_locked(pcbinfo,
801 				    faddr, fport, laddr, lport, lookupflags,
802 				    NULL, M_NODOM);
803 			}
804 #endif
805 #ifdef INET6
806 			if (lsa->sa_family == AF_INET6) {
807 				tmpinp = in6_pcblookup_hash_locked(pcbinfo,
808 				    faddr6, fport, laddr6, lport, lookupflags,
809 				    NULL, M_NODOM);
810 			}
811 #endif
812 		} else {
813 #ifdef INET6
814 			if ((inp->inp_vflag & INP_IPV6) != 0)
815 				tmpinp = in6_pcblookup_local(pcbinfo,
816 				    &inp->in6p_laddr, lport, lookupflags, cred);
817 #endif
818 #if defined(INET) && defined(INET6)
819 			else
820 #endif
821 #ifdef INET
822 				tmpinp = in_pcblookup_local(pcbinfo, laddr,
823 				    lport, lookupflags, cred);
824 #endif
825 		}
826 	} while (tmpinp != NULL);
827 
828 	*lportp = lport;
829 
830 	return (0);
831 }
832 
833 /*
834  * Select a local port (number) to use.
835  */
836 int
837 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
838     struct ucred *cred, int lookupflags)
839 {
840 	struct sockaddr_in laddr;
841 
842 	if (laddrp) {
843 		bzero(&laddr, sizeof(laddr));
844 		laddr.sin_family = AF_INET;
845 		laddr.sin_addr = *laddrp;
846 	}
847 	return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
848 	    NULL, lportp, NULL, 0, cred, lookupflags));
849 }
850 
851 /*
852  * Return cached socket options.
853  */
854 int
855 inp_so_options(const struct inpcb *inp)
856 {
857 	int so_options;
858 
859 	so_options = 0;
860 
861 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
862 		so_options |= SO_REUSEPORT_LB;
863 	if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
864 		so_options |= SO_REUSEPORT;
865 	if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
866 		so_options |= SO_REUSEADDR;
867 	return (so_options);
868 }
869 #endif /* INET || INET6 */
870 
871 /*
872  * Check if a new BINDMULTI socket is allowed to be created.
873  *
874  * ni points to the new inp.
875  * oi points to the exisitng inp.
876  *
877  * This checks whether the existing inp also has BINDMULTI and
878  * whether the credentials match.
879  */
880 int
881 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
882 {
883 	/* Check permissions match */
884 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
885 	    (ni->inp_cred->cr_uid !=
886 	    oi->inp_cred->cr_uid))
887 		return (0);
888 
889 	/* Check the existing inp has BINDMULTI set */
890 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
891 	    ((oi->inp_flags2 & INP_BINDMULTI) == 0))
892 		return (0);
893 
894 	/*
895 	 * We're okay - either INP_BINDMULTI isn't set on ni, or
896 	 * it is and it matches the checks.
897 	 */
898 	return (1);
899 }
900 
901 #ifdef INET
902 /*
903  * Set up a bind operation on a PCB, performing port allocation
904  * as required, but do not actually modify the PCB. Callers can
905  * either complete the bind by setting inp_laddr/inp_lport and
906  * calling in_pcbinshash(), or they can just use the resulting
907  * port and address to authorise the sending of a once-off packet.
908  *
909  * On error, the values of *laddrp and *lportp are not changed.
910  */
911 int
912 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
913     u_short *lportp, struct ucred *cred)
914 {
915 	struct socket *so = inp->inp_socket;
916 	struct sockaddr_in *sin;
917 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
918 	struct in_addr laddr;
919 	u_short lport = 0;
920 	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
921 	int error;
922 
923 	/*
924 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
925 	 * so that we don't have to add to the (already messy) code below.
926 	 */
927 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
928 
929 	/*
930 	 * No state changes, so read locks are sufficient here.
931 	 */
932 	INP_LOCK_ASSERT(inp);
933 	INP_HASH_LOCK_ASSERT(pcbinfo);
934 
935 	laddr.s_addr = *laddrp;
936 	if (nam != NULL && laddr.s_addr != INADDR_ANY)
937 		return (EINVAL);
938 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
939 		lookupflags = INPLOOKUP_WILDCARD;
940 	if (nam == NULL) {
941 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
942 			return (error);
943 	} else {
944 		sin = (struct sockaddr_in *)nam;
945 		KASSERT(sin->sin_family == AF_INET,
946 		    ("%s: invalid family for address %p", __func__, sin));
947 		KASSERT(sin->sin_len == sizeof(*sin),
948 		    ("%s: invalid length for address %p", __func__, sin));
949 
950 		error = prison_local_ip4(cred, &sin->sin_addr);
951 		if (error)
952 			return (error);
953 		if (sin->sin_port != *lportp) {
954 			/* Don't allow the port to change. */
955 			if (*lportp != 0)
956 				return (EINVAL);
957 			lport = sin->sin_port;
958 		}
959 		/* NB: lport is left as 0 if the port isn't being changed. */
960 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
961 			/*
962 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
963 			 * allow complete duplication of binding if
964 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
965 			 * and a multicast address is bound on both
966 			 * new and duplicated sockets.
967 			 */
968 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
969 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
970 			/*
971 			 * XXX: How to deal with SO_REUSEPORT_LB here?
972 			 * Treat same as SO_REUSEPORT for now.
973 			 */
974 			if ((so->so_options &
975 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
976 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
977 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
978 			sin->sin_port = 0;		/* yech... */
979 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
980 			/*
981 			 * Is the address a local IP address?
982 			 * If INP_BINDANY is set, then the socket may be bound
983 			 * to any endpoint address, local or not.
984 			 */
985 			if ((inp->inp_flags & INP_BINDANY) == 0 &&
986 			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
987 				return (EADDRNOTAVAIL);
988 		}
989 		laddr = sin->sin_addr;
990 		if (lport) {
991 			struct inpcb *t;
992 			struct tcptw *tw;
993 
994 			/* GROSS */
995 			if (ntohs(lport) <= V_ipport_reservedhigh &&
996 			    ntohs(lport) >= V_ipport_reservedlow &&
997 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
998 				return (EACCES);
999 			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
1000 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
1001 				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1002 				    lport, INPLOOKUP_WILDCARD, cred);
1003 	/*
1004 	 * XXX
1005 	 * This entire block sorely needs a rewrite.
1006 	 */
1007 				if (t &&
1008 				    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1009 				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
1010 				    (so->so_type != SOCK_STREAM ||
1011 				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
1012 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
1013 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
1014 				     (t->inp_flags2 & INP_REUSEPORT) ||
1015 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
1016 				    (inp->inp_cred->cr_uid !=
1017 				     t->inp_cred->cr_uid))
1018 					return (EADDRINUSE);
1019 
1020 				/*
1021 				 * If the socket is a BINDMULTI socket, then
1022 				 * the credentials need to match and the
1023 				 * original socket also has to have been bound
1024 				 * with BINDMULTI.
1025 				 */
1026 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1027 					return (EADDRINUSE);
1028 			}
1029 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1030 			    lport, lookupflags, cred);
1031 			if (t && (t->inp_flags & INP_TIMEWAIT)) {
1032 				/*
1033 				 * XXXRW: If an incpb has had its timewait
1034 				 * state recycled, we treat the address as
1035 				 * being in use (for now).  This is better
1036 				 * than a panic, but not desirable.
1037 				 */
1038 				tw = intotw(t);
1039 				if (tw == NULL ||
1040 				    ((reuseport & tw->tw_so_options) == 0 &&
1041 					(reuseport_lb &
1042 				            tw->tw_so_options) == 0)) {
1043 					return (EADDRINUSE);
1044 				}
1045 			} else if (t &&
1046 				   ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1047 				   (reuseport & inp_so_options(t)) == 0 &&
1048 				   (reuseport_lb & inp_so_options(t)) == 0) {
1049 #ifdef INET6
1050 				if (ntohl(sin->sin_addr.s_addr) !=
1051 				    INADDR_ANY ||
1052 				    ntohl(t->inp_laddr.s_addr) !=
1053 				    INADDR_ANY ||
1054 				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1055 				    (t->inp_vflag & INP_IPV6PROTO) == 0)
1056 #endif
1057 						return (EADDRINUSE);
1058 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1059 					return (EADDRINUSE);
1060 			}
1061 		}
1062 	}
1063 	if (*lportp != 0)
1064 		lport = *lportp;
1065 	if (lport == 0) {
1066 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1067 		if (error != 0)
1068 			return (error);
1069 	}
1070 	*laddrp = laddr.s_addr;
1071 	*lportp = lport;
1072 	return (0);
1073 }
1074 
1075 /*
1076  * Connect from a socket to a specified address.
1077  * Both address and port must be specified in argument sin.
1078  * If don't have a local address for this socket yet,
1079  * then pick one.
1080  */
1081 int
1082 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
1083     struct ucred *cred, struct mbuf *m, bool rehash)
1084 {
1085 	u_short lport, fport;
1086 	in_addr_t laddr, faddr;
1087 	int anonport, error;
1088 
1089 	INP_WLOCK_ASSERT(inp);
1090 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1091 
1092 	lport = inp->inp_lport;
1093 	laddr = inp->inp_laddr.s_addr;
1094 	anonport = (lport == 0);
1095 	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
1096 	    NULL, cred);
1097 	if (error)
1098 		return (error);
1099 
1100 	/* Do the initial binding of the local address if required. */
1101 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1102 		KASSERT(rehash == true,
1103 		    ("Rehashing required for unbound inps"));
1104 		inp->inp_lport = lport;
1105 		inp->inp_laddr.s_addr = laddr;
1106 		if (in_pcbinshash(inp) != 0) {
1107 			inp->inp_laddr.s_addr = INADDR_ANY;
1108 			inp->inp_lport = 0;
1109 			return (EAGAIN);
1110 		}
1111 	}
1112 
1113 	/* Commit the remaining changes. */
1114 	inp->inp_lport = lport;
1115 	inp->inp_laddr.s_addr = laddr;
1116 	inp->inp_faddr.s_addr = faddr;
1117 	inp->inp_fport = fport;
1118 	if (rehash) {
1119 		in_pcbrehash_mbuf(inp, m);
1120 	} else {
1121 		in_pcbinshash_mbuf(inp, m);
1122 	}
1123 
1124 	if (anonport)
1125 		inp->inp_flags |= INP_ANONPORT;
1126 	return (0);
1127 }
1128 
1129 int
1130 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1131 {
1132 
1133 	return (in_pcbconnect_mbuf(inp, nam, cred, NULL, true));
1134 }
1135 
1136 /*
1137  * Do proper source address selection on an unbound socket in case
1138  * of connect. Take jails into account as well.
1139  */
1140 int
1141 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1142     struct ucred *cred)
1143 {
1144 	struct ifaddr *ifa;
1145 	struct sockaddr *sa;
1146 	struct sockaddr_in *sin, dst;
1147 	struct nhop_object *nh;
1148 	int error;
1149 
1150 	NET_EPOCH_ASSERT();
1151 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1152 	/*
1153 	 * Bypass source address selection and use the primary jail IP
1154 	 * if requested.
1155 	 */
1156 	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1157 		return (0);
1158 
1159 	error = 0;
1160 
1161 	nh = NULL;
1162 	bzero(&dst, sizeof(dst));
1163 	sin = &dst;
1164 	sin->sin_family = AF_INET;
1165 	sin->sin_len = sizeof(struct sockaddr_in);
1166 	sin->sin_addr.s_addr = faddr->s_addr;
1167 
1168 	/*
1169 	 * If route is known our src addr is taken from the i/f,
1170 	 * else punt.
1171 	 *
1172 	 * Find out route to destination.
1173 	 */
1174 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1175 		nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
1176 		    0, NHR_NONE, 0);
1177 
1178 	/*
1179 	 * If we found a route, use the address corresponding to
1180 	 * the outgoing interface.
1181 	 *
1182 	 * Otherwise assume faddr is reachable on a directly connected
1183 	 * network and try to find a corresponding interface to take
1184 	 * the source address from.
1185 	 */
1186 	if (nh == NULL || nh->nh_ifp == NULL) {
1187 		struct in_ifaddr *ia;
1188 		struct ifnet *ifp;
1189 
1190 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1191 					inp->inp_socket->so_fibnum));
1192 		if (ia == NULL) {
1193 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1194 						inp->inp_socket->so_fibnum));
1195 		}
1196 		if (ia == NULL) {
1197 			error = ENETUNREACH;
1198 			goto done;
1199 		}
1200 
1201 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1202 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1203 			goto done;
1204 		}
1205 
1206 		ifp = ia->ia_ifp;
1207 		ia = NULL;
1208 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1209 			sa = ifa->ifa_addr;
1210 			if (sa->sa_family != AF_INET)
1211 				continue;
1212 			sin = (struct sockaddr_in *)sa;
1213 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1214 				ia = (struct in_ifaddr *)ifa;
1215 				break;
1216 			}
1217 		}
1218 		if (ia != NULL) {
1219 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1220 			goto done;
1221 		}
1222 
1223 		/* 3. As a last resort return the 'default' jail address. */
1224 		error = prison_get_ip4(cred, laddr);
1225 		goto done;
1226 	}
1227 
1228 	/*
1229 	 * If the outgoing interface on the route found is not
1230 	 * a loopback interface, use the address from that interface.
1231 	 * In case of jails do those three steps:
1232 	 * 1. check if the interface address belongs to the jail. If so use it.
1233 	 * 2. check if we have any address on the outgoing interface
1234 	 *    belonging to this jail. If so use it.
1235 	 * 3. as a last resort return the 'default' jail address.
1236 	 */
1237 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
1238 		struct in_ifaddr *ia;
1239 		struct ifnet *ifp;
1240 
1241 		/* If not jailed, use the default returned. */
1242 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1243 			ia = (struct in_ifaddr *)nh->nh_ifa;
1244 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1245 			goto done;
1246 		}
1247 
1248 		/* Jailed. */
1249 		/* 1. Check if the iface address belongs to the jail. */
1250 		sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1251 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1252 			ia = (struct in_ifaddr *)nh->nh_ifa;
1253 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1254 			goto done;
1255 		}
1256 
1257 		/*
1258 		 * 2. Check if we have any address on the outgoing interface
1259 		 *    belonging to this jail.
1260 		 */
1261 		ia = NULL;
1262 		ifp = nh->nh_ifp;
1263 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1264 			sa = ifa->ifa_addr;
1265 			if (sa->sa_family != AF_INET)
1266 				continue;
1267 			sin = (struct sockaddr_in *)sa;
1268 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1269 				ia = (struct in_ifaddr *)ifa;
1270 				break;
1271 			}
1272 		}
1273 		if (ia != NULL) {
1274 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1275 			goto done;
1276 		}
1277 
1278 		/* 3. As a last resort return the 'default' jail address. */
1279 		error = prison_get_ip4(cred, laddr);
1280 		goto done;
1281 	}
1282 
1283 	/*
1284 	 * The outgoing interface is marked with 'loopback net', so a route
1285 	 * to ourselves is here.
1286 	 * Try to find the interface of the destination address and then
1287 	 * take the address from there. That interface is not necessarily
1288 	 * a loopback interface.
1289 	 * In case of jails, check that it is an address of the jail
1290 	 * and if we cannot find, fall back to the 'default' jail address.
1291 	 */
1292 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
1293 		struct in_ifaddr *ia;
1294 
1295 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
1296 					inp->inp_socket->so_fibnum));
1297 		if (ia == NULL)
1298 			ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
1299 						inp->inp_socket->so_fibnum));
1300 		if (ia == NULL)
1301 			ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
1302 
1303 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1304 			if (ia == NULL) {
1305 				error = ENETUNREACH;
1306 				goto done;
1307 			}
1308 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1309 			goto done;
1310 		}
1311 
1312 		/* Jailed. */
1313 		if (ia != NULL) {
1314 			struct ifnet *ifp;
1315 
1316 			ifp = ia->ia_ifp;
1317 			ia = NULL;
1318 			CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1319 				sa = ifa->ifa_addr;
1320 				if (sa->sa_family != AF_INET)
1321 					continue;
1322 				sin = (struct sockaddr_in *)sa;
1323 				if (prison_check_ip4(cred,
1324 				    &sin->sin_addr) == 0) {
1325 					ia = (struct in_ifaddr *)ifa;
1326 					break;
1327 				}
1328 			}
1329 			if (ia != NULL) {
1330 				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1331 				goto done;
1332 			}
1333 		}
1334 
1335 		/* 3. As a last resort return the 'default' jail address. */
1336 		error = prison_get_ip4(cred, laddr);
1337 		goto done;
1338 	}
1339 
1340 done:
1341 	return (error);
1342 }
1343 
1344 /*
1345  * Set up for a connect from a socket to the specified address.
1346  * On entry, *laddrp and *lportp should contain the current local
1347  * address and port for the PCB; these are updated to the values
1348  * that should be placed in inp_laddr and inp_lport to complete
1349  * the connect.
1350  *
1351  * On success, *faddrp and *fportp will be set to the remote address
1352  * and port. These are not updated in the error case.
1353  *
1354  * If the operation fails because the connection already exists,
1355  * *oinpp will be set to the PCB of that connection so that the
1356  * caller can decide to override it. In all other cases, *oinpp
1357  * is set to NULL.
1358  */
1359 int
1360 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1361     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1362     struct inpcb **oinpp, struct ucred *cred)
1363 {
1364 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1365 	struct in_ifaddr *ia;
1366 	struct inpcb *oinp;
1367 	struct in_addr laddr, faddr;
1368 	u_short lport, fport;
1369 	int error;
1370 
1371 	KASSERT(sin->sin_family == AF_INET,
1372 	    ("%s: invalid address family for %p", __func__, sin));
1373 	KASSERT(sin->sin_len == sizeof(*sin),
1374 	    ("%s: invalid address length for %p", __func__, sin));
1375 
1376 	/*
1377 	 * Because a global state change doesn't actually occur here, a read
1378 	 * lock is sufficient.
1379 	 */
1380 	NET_EPOCH_ASSERT();
1381 	INP_LOCK_ASSERT(inp);
1382 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1383 
1384 	if (oinpp != NULL)
1385 		*oinpp = NULL;
1386 	if (sin->sin_port == 0)
1387 		return (EADDRNOTAVAIL);
1388 	laddr.s_addr = *laddrp;
1389 	lport = *lportp;
1390 	faddr = sin->sin_addr;
1391 	fport = sin->sin_port;
1392 #ifdef ROUTE_MPATH
1393 	if (CALC_FLOWID_OUTBOUND) {
1394 		uint32_t hash_val, hash_type;
1395 
1396 		hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
1397 		    inp->inp_socket->so_proto->pr_protocol, &hash_type);
1398 
1399 		inp->inp_flowid = hash_val;
1400 		inp->inp_flowtype = hash_type;
1401 	}
1402 #endif
1403 	if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1404 		/*
1405 		 * If the destination address is INADDR_ANY,
1406 		 * use the primary local address.
1407 		 * If the supplied address is INADDR_BROADCAST,
1408 		 * and the primary interface supports broadcast,
1409 		 * choose the broadcast address for that interface.
1410 		 */
1411 		if (faddr.s_addr == INADDR_ANY) {
1412 			faddr =
1413 			    IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1414 			if (cred != NULL &&
1415 			    (error = prison_get_ip4(cred, &faddr)) != 0)
1416 				return (error);
1417 		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1418 			if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1419 			    IFF_BROADCAST)
1420 				faddr = satosin(&CK_STAILQ_FIRST(
1421 				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1422 		}
1423 	}
1424 	if (laddr.s_addr == INADDR_ANY) {
1425 		error = in_pcbladdr(inp, &faddr, &laddr, cred);
1426 		/*
1427 		 * If the destination address is multicast and an outgoing
1428 		 * interface has been set as a multicast option, prefer the
1429 		 * address of that interface as our source address.
1430 		 */
1431 		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1432 		    inp->inp_moptions != NULL) {
1433 			struct ip_moptions *imo;
1434 			struct ifnet *ifp;
1435 
1436 			imo = inp->inp_moptions;
1437 			if (imo->imo_multicast_ifp != NULL) {
1438 				ifp = imo->imo_multicast_ifp;
1439 				CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1440 					if ((ia->ia_ifp == ifp) &&
1441 					    (cred == NULL ||
1442 					    prison_check_ip4(cred,
1443 					    &ia->ia_addr.sin_addr) == 0))
1444 						break;
1445 				}
1446 				if (ia == NULL)
1447 					error = EADDRNOTAVAIL;
1448 				else {
1449 					laddr = ia->ia_addr.sin_addr;
1450 					error = 0;
1451 				}
1452 			}
1453 		}
1454 		if (error)
1455 			return (error);
1456 	}
1457 
1458 	if (lport != 0) {
1459 		oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1460 		    fport, laddr, lport, 0, NULL, M_NODOM);
1461 		if (oinp != NULL) {
1462 			if (oinpp != NULL)
1463 				*oinpp = oinp;
1464 			return (EADDRINUSE);
1465 		}
1466 	} else {
1467 		struct sockaddr_in lsin, fsin;
1468 
1469 		bzero(&lsin, sizeof(lsin));
1470 		bzero(&fsin, sizeof(fsin));
1471 		lsin.sin_family = AF_INET;
1472 		lsin.sin_addr = laddr;
1473 		fsin.sin_family = AF_INET;
1474 		fsin.sin_addr = faddr;
1475 		error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
1476 		    &lport, (struct sockaddr *)& fsin, fport, cred,
1477 		    INPLOOKUP_WILDCARD);
1478 		if (error)
1479 			return (error);
1480 	}
1481 	*laddrp = laddr.s_addr;
1482 	*lportp = lport;
1483 	*faddrp = faddr.s_addr;
1484 	*fportp = fport;
1485 	return (0);
1486 }
1487 
1488 void
1489 in_pcbdisconnect(struct inpcb *inp)
1490 {
1491 
1492 	INP_WLOCK_ASSERT(inp);
1493 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1494 
1495 	inp->inp_faddr.s_addr = INADDR_ANY;
1496 	inp->inp_fport = 0;
1497 	in_pcbrehash(inp);
1498 }
1499 #endif /* INET */
1500 
1501 /*
1502  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1503  * For most protocols, this will be invoked immediately prior to calling
1504  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
1505  * socket, in which case in_pcbfree() is deferred.
1506  */
1507 void
1508 in_pcbdetach(struct inpcb *inp)
1509 {
1510 
1511 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1512 
1513 #ifdef RATELIMIT
1514 	if (inp->inp_snd_tag != NULL)
1515 		in_pcbdetach_txrtlmt(inp);
1516 #endif
1517 	inp->inp_socket->so_pcb = NULL;
1518 	inp->inp_socket = NULL;
1519 }
1520 
1521 /*
1522  * in_pcbref() bumps the reference count on an inpcb in order to maintain
1523  * stability of an inpcb pointer despite the inpcb lock being released.  This
1524  * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1525  * but where the inpcb lock may already held, or when acquiring a reference
1526  * via a pcbgroup.
1527  *
1528  * in_pcbref() should be used only to provide brief memory stability, and
1529  * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1530  * garbage collect the inpcb if it has been in_pcbfree()'d from another
1531  * context.  Until in_pcbrele() has returned that the inpcb is still valid,
1532  * lock and rele are the *only* safe operations that may be performed on the
1533  * inpcb.
1534  *
1535  * While the inpcb will not be freed, releasing the inpcb lock means that the
1536  * connection's state may change, so the caller should be careful to
1537  * revalidate any cached state on reacquiring the lock.  Drop the reference
1538  * using in_pcbrele().
1539  */
1540 void
1541 in_pcbref(struct inpcb *inp)
1542 {
1543 
1544 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1545 
1546 	refcount_acquire(&inp->inp_refcount);
1547 }
1548 
1549 /*
1550  * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1551  * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1552  * return a flag indicating whether or not the inpcb remains valid.  If it is
1553  * valid, we return with the inpcb lock held.
1554  *
1555  * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1556  * reference on an inpcb.  Historically more work was done here (actually, in
1557  * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1558  * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
1559  * about memory stability (and continued use of the write lock).
1560  */
1561 int
1562 in_pcbrele_rlocked(struct inpcb *inp)
1563 {
1564 	struct inpcbinfo *pcbinfo;
1565 
1566 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1567 
1568 	INP_RLOCK_ASSERT(inp);
1569 
1570 	if (refcount_release(&inp->inp_refcount) == 0) {
1571 		/*
1572 		 * If the inpcb has been freed, let the caller know, even if
1573 		 * this isn't the last reference.
1574 		 */
1575 		if (inp->inp_flags2 & INP_FREED) {
1576 			INP_RUNLOCK(inp);
1577 			return (1);
1578 		}
1579 		return (0);
1580 	}
1581 
1582 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1583 #ifdef TCPHPTS
1584 	if (inp->inp_in_hpts || inp->inp_in_input) {
1585 		struct tcp_hpts_entry *hpts;
1586 		/*
1587 		 * We should not be on the hpts at
1588 		 * this point in any form. we must
1589 		 * get the lock to be sure.
1590 		 */
1591 		hpts = tcp_hpts_lock(inp);
1592 		if (inp->inp_in_hpts)
1593 			panic("Hpts:%p inp:%p at free still on hpts",
1594 			      hpts, inp);
1595 		mtx_unlock(&hpts->p_mtx);
1596 		hpts = tcp_input_lock(inp);
1597 		if (inp->inp_in_input)
1598 			panic("Hpts:%p inp:%p at free still on input hpts",
1599 			      hpts, inp);
1600 		mtx_unlock(&hpts->p_mtx);
1601 	}
1602 #endif
1603 	INP_RUNLOCK(inp);
1604 	pcbinfo = inp->inp_pcbinfo;
1605 	uma_zfree(pcbinfo->ipi_zone, inp);
1606 	return (1);
1607 }
1608 
1609 int
1610 in_pcbrele_wlocked(struct inpcb *inp)
1611 {
1612 	struct inpcbinfo *pcbinfo;
1613 
1614 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1615 
1616 	INP_WLOCK_ASSERT(inp);
1617 
1618 	if (refcount_release(&inp->inp_refcount) == 0) {
1619 		/*
1620 		 * If the inpcb has been freed, let the caller know, even if
1621 		 * this isn't the last reference.
1622 		 */
1623 		if (inp->inp_flags2 & INP_FREED) {
1624 			INP_WUNLOCK(inp);
1625 			return (1);
1626 		}
1627 		return (0);
1628 	}
1629 
1630 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1631 #ifdef TCPHPTS
1632 	if (inp->inp_in_hpts || inp->inp_in_input) {
1633 		struct tcp_hpts_entry *hpts;
1634 		/*
1635 		 * We should not be on the hpts at
1636 		 * this point in any form. we must
1637 		 * get the lock to be sure.
1638 		 */
1639 		hpts = tcp_hpts_lock(inp);
1640 		if (inp->inp_in_hpts)
1641 			panic("Hpts:%p inp:%p at free still on hpts",
1642 			      hpts, inp);
1643 		mtx_unlock(&hpts->p_mtx);
1644 		hpts = tcp_input_lock(inp);
1645 		if (inp->inp_in_input)
1646 			panic("Hpts:%p inp:%p at free still on input hpts",
1647 			      hpts, inp);
1648 		mtx_unlock(&hpts->p_mtx);
1649 	}
1650 #endif
1651 	INP_WUNLOCK(inp);
1652 	pcbinfo = inp->inp_pcbinfo;
1653 	uma_zfree(pcbinfo->ipi_zone, inp);
1654 	return (1);
1655 }
1656 
1657 static void
1658 inpcbport_free(epoch_context_t ctx)
1659 {
1660 	struct inpcbport *phd;
1661 
1662 	phd = __containerof(ctx, struct inpcbport, phd_epoch_ctx);
1663 	free(phd, M_PCB);
1664 }
1665 
1666 static void
1667 in_pcbfree_deferred(epoch_context_t ctx)
1668 {
1669 	struct inpcb *inp;
1670 	int released __unused;
1671 
1672 	inp = __containerof(ctx, struct inpcb, inp_epoch_ctx);
1673 
1674 	INP_WLOCK(inp);
1675 	CURVNET_SET(inp->inp_vnet);
1676 #ifdef INET
1677 	struct ip_moptions *imo = inp->inp_moptions;
1678 	inp->inp_moptions = NULL;
1679 #endif
1680 	/* XXXRW: Do as much as possible here. */
1681 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1682 	if (inp->inp_sp != NULL)
1683 		ipsec_delete_pcbpolicy(inp);
1684 #endif
1685 #ifdef INET6
1686 	struct ip6_moptions *im6o = NULL;
1687 	if (inp->inp_vflag & INP_IPV6PROTO) {
1688 		ip6_freepcbopts(inp->in6p_outputopts);
1689 		im6o = inp->in6p_moptions;
1690 		inp->in6p_moptions = NULL;
1691 	}
1692 #endif
1693 	if (inp->inp_options)
1694 		(void)m_free(inp->inp_options);
1695 	inp->inp_vflag = 0;
1696 	crfree(inp->inp_cred);
1697 #ifdef MAC
1698 	mac_inpcb_destroy(inp);
1699 #endif
1700 	released = in_pcbrele_wlocked(inp);
1701 	MPASS(released);
1702 #ifdef INET6
1703 	ip6_freemoptions(im6o);
1704 #endif
1705 #ifdef INET
1706 	inp_freemoptions(imo);
1707 #endif
1708 	CURVNET_RESTORE();
1709 }
1710 
1711 /*
1712  * Unconditionally schedule an inpcb to be freed by decrementing its
1713  * reference count, which should occur only after the inpcb has been detached
1714  * from its socket.  If another thread holds a temporary reference (acquired
1715  * using in_pcbref()) then the free is deferred until that reference is
1716  * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
1717  * work, including removal from global lists, is done in this context, where
1718  * the pcbinfo lock is held.
1719  */
1720 void
1721 in_pcbfree(struct inpcb *inp)
1722 {
1723 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1724 
1725 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1726 	KASSERT((inp->inp_flags2 & INP_FREED) == 0,
1727 	    ("%s: called twice for pcb %p", __func__, inp));
1728 	if (inp->inp_flags2 & INP_FREED) {
1729 		INP_WUNLOCK(inp);
1730 		return;
1731 	}
1732 
1733 	INP_WLOCK_ASSERT(inp);
1734 	INP_LIST_WLOCK(pcbinfo);
1735 	in_pcbremlists(inp);
1736 	INP_LIST_WUNLOCK(pcbinfo);
1737 	RO_INVALIDATE_CACHE(&inp->inp_route);
1738 	/* mark as destruction in progress */
1739 	inp->inp_flags2 |= INP_FREED;
1740 	INP_WUNLOCK(inp);
1741 	NET_EPOCH_CALL(in_pcbfree_deferred, &inp->inp_epoch_ctx);
1742 }
1743 
1744 /*
1745  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1746  * port reservation, and preventing it from being returned by inpcb lookups.
1747  *
1748  * It is used by TCP to mark an inpcb as unused and avoid future packet
1749  * delivery or event notification when a socket remains open but TCP has
1750  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1751  * or a RST on the wire, and allows the port binding to be reused while still
1752  * maintaining the invariant that so_pcb always points to a valid inpcb until
1753  * in_pcbdetach().
1754  *
1755  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1756  * in_pcbnotifyall() and in_pcbpurgeif0()?
1757  */
1758 void
1759 in_pcbdrop(struct inpcb *inp)
1760 {
1761 
1762 	INP_WLOCK_ASSERT(inp);
1763 #ifdef INVARIANTS
1764 	if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1765 		MPASS(inp->inp_refcount > 1);
1766 #endif
1767 
1768 	/*
1769 	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1770 	 * the hash lock...?
1771 	 */
1772 	inp->inp_flags |= INP_DROPPED;
1773 	if (inp->inp_flags & INP_INHASHLIST) {
1774 		struct inpcbport *phd = inp->inp_phd;
1775 
1776 		INP_HASH_WLOCK(inp->inp_pcbinfo);
1777 		in_pcbremlbgrouphash(inp);
1778 		CK_LIST_REMOVE(inp, inp_hash);
1779 		CK_LIST_REMOVE(inp, inp_portlist);
1780 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1781 			CK_LIST_REMOVE(phd, phd_hash);
1782 			NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
1783 		}
1784 		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1785 		inp->inp_flags &= ~INP_INHASHLIST;
1786 #ifdef PCBGROUP
1787 		in_pcbgroup_remove(inp);
1788 #endif
1789 	}
1790 }
1791 
1792 #ifdef INET
1793 /*
1794  * Common routines to return the socket addresses associated with inpcbs.
1795  */
1796 struct sockaddr *
1797 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1798 {
1799 	struct sockaddr_in *sin;
1800 
1801 	sin = malloc(sizeof *sin, M_SONAME,
1802 		M_WAITOK | M_ZERO);
1803 	sin->sin_family = AF_INET;
1804 	sin->sin_len = sizeof(*sin);
1805 	sin->sin_addr = *addr_p;
1806 	sin->sin_port = port;
1807 
1808 	return (struct sockaddr *)sin;
1809 }
1810 
1811 int
1812 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1813 {
1814 	struct inpcb *inp;
1815 	struct in_addr addr;
1816 	in_port_t port;
1817 
1818 	inp = sotoinpcb(so);
1819 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1820 
1821 	INP_RLOCK(inp);
1822 	port = inp->inp_lport;
1823 	addr = inp->inp_laddr;
1824 	INP_RUNLOCK(inp);
1825 
1826 	*nam = in_sockaddr(port, &addr);
1827 	return 0;
1828 }
1829 
1830 int
1831 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1832 {
1833 	struct inpcb *inp;
1834 	struct in_addr addr;
1835 	in_port_t port;
1836 
1837 	inp = sotoinpcb(so);
1838 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1839 
1840 	INP_RLOCK(inp);
1841 	port = inp->inp_fport;
1842 	addr = inp->inp_faddr;
1843 	INP_RUNLOCK(inp);
1844 
1845 	*nam = in_sockaddr(port, &addr);
1846 	return 0;
1847 }
1848 
1849 void
1850 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1851     struct inpcb *(*notify)(struct inpcb *, int))
1852 {
1853 	struct inpcb *inp, *inp_temp;
1854 
1855 	INP_INFO_WLOCK(pcbinfo);
1856 	CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1857 		INP_WLOCK(inp);
1858 #ifdef INET6
1859 		if ((inp->inp_vflag & INP_IPV4) == 0) {
1860 			INP_WUNLOCK(inp);
1861 			continue;
1862 		}
1863 #endif
1864 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1865 		    inp->inp_socket == NULL) {
1866 			INP_WUNLOCK(inp);
1867 			continue;
1868 		}
1869 		if ((*notify)(inp, errno))
1870 			INP_WUNLOCK(inp);
1871 	}
1872 	INP_INFO_WUNLOCK(pcbinfo);
1873 }
1874 
1875 void
1876 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1877 {
1878 	struct inpcb *inp;
1879 	struct in_multi *inm;
1880 	struct in_mfilter *imf;
1881 	struct ip_moptions *imo;
1882 
1883 	INP_INFO_WLOCK(pcbinfo);
1884 	CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1885 		INP_WLOCK(inp);
1886 		imo = inp->inp_moptions;
1887 		if ((inp->inp_vflag & INP_IPV4) &&
1888 		    imo != NULL) {
1889 			/*
1890 			 * Unselect the outgoing interface if it is being
1891 			 * detached.
1892 			 */
1893 			if (imo->imo_multicast_ifp == ifp)
1894 				imo->imo_multicast_ifp = NULL;
1895 
1896 			/*
1897 			 * Drop multicast group membership if we joined
1898 			 * through the interface being detached.
1899 			 *
1900 			 * XXX This can all be deferred to an epoch_call
1901 			 */
1902 restart:
1903 			IP_MFILTER_FOREACH(imf, &imo->imo_head) {
1904 				if ((inm = imf->imf_inm) == NULL)
1905 					continue;
1906 				if (inm->inm_ifp != ifp)
1907 					continue;
1908 				ip_mfilter_remove(&imo->imo_head, imf);
1909 				IN_MULTI_LOCK_ASSERT();
1910 				in_leavegroup_locked(inm, NULL);
1911 				ip_mfilter_free(imf);
1912 				goto restart;
1913 			}
1914 		}
1915 		INP_WUNLOCK(inp);
1916 	}
1917 	INP_INFO_WUNLOCK(pcbinfo);
1918 }
1919 
1920 /*
1921  * Lookup a PCB based on the local address and port.  Caller must hold the
1922  * hash lock.  No inpcb locks or references are acquired.
1923  */
1924 #define INP_LOOKUP_MAPPED_PCB_COST	3
1925 struct inpcb *
1926 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1927     u_short lport, int lookupflags, struct ucred *cred)
1928 {
1929 	struct inpcb *inp;
1930 #ifdef INET6
1931 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1932 #else
1933 	int matchwild = 3;
1934 #endif
1935 	int wildcard;
1936 
1937 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1938 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1939 
1940 	INP_HASH_LOCK_ASSERT(pcbinfo);
1941 
1942 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1943 		struct inpcbhead *head;
1944 		/*
1945 		 * Look for an unconnected (wildcard foreign addr) PCB that
1946 		 * matches the local address and port we're looking for.
1947 		 */
1948 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1949 		    0, pcbinfo->ipi_hashmask)];
1950 		CK_LIST_FOREACH(inp, head, inp_hash) {
1951 #ifdef INET6
1952 			/* XXX inp locking */
1953 			if ((inp->inp_vflag & INP_IPV4) == 0)
1954 				continue;
1955 #endif
1956 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1957 			    inp->inp_laddr.s_addr == laddr.s_addr &&
1958 			    inp->inp_lport == lport) {
1959 				/*
1960 				 * Found?
1961 				 */
1962 				if (cred == NULL ||
1963 				    prison_equal_ip4(cred->cr_prison,
1964 					inp->inp_cred->cr_prison))
1965 					return (inp);
1966 			}
1967 		}
1968 		/*
1969 		 * Not found.
1970 		 */
1971 		return (NULL);
1972 	} else {
1973 		struct inpcbporthead *porthash;
1974 		struct inpcbport *phd;
1975 		struct inpcb *match = NULL;
1976 		/*
1977 		 * Best fit PCB lookup.
1978 		 *
1979 		 * First see if this local port is in use by looking on the
1980 		 * port hash list.
1981 		 */
1982 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1983 		    pcbinfo->ipi_porthashmask)];
1984 		CK_LIST_FOREACH(phd, porthash, phd_hash) {
1985 			if (phd->phd_port == lport)
1986 				break;
1987 		}
1988 		if (phd != NULL) {
1989 			/*
1990 			 * Port is in use by one or more PCBs. Look for best
1991 			 * fit.
1992 			 */
1993 			CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1994 				wildcard = 0;
1995 				if (cred != NULL &&
1996 				    !prison_equal_ip4(inp->inp_cred->cr_prison,
1997 					cred->cr_prison))
1998 					continue;
1999 #ifdef INET6
2000 				/* XXX inp locking */
2001 				if ((inp->inp_vflag & INP_IPV4) == 0)
2002 					continue;
2003 				/*
2004 				 * We never select the PCB that has
2005 				 * INP_IPV6 flag and is bound to :: if
2006 				 * we have another PCB which is bound
2007 				 * to 0.0.0.0.  If a PCB has the
2008 				 * INP_IPV6 flag, then we set its cost
2009 				 * higher than IPv4 only PCBs.
2010 				 *
2011 				 * Note that the case only happens
2012 				 * when a socket is bound to ::, under
2013 				 * the condition that the use of the
2014 				 * mapped address is allowed.
2015 				 */
2016 				if ((inp->inp_vflag & INP_IPV6) != 0)
2017 					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2018 #endif
2019 				if (inp->inp_faddr.s_addr != INADDR_ANY)
2020 					wildcard++;
2021 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
2022 					if (laddr.s_addr == INADDR_ANY)
2023 						wildcard++;
2024 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
2025 						continue;
2026 				} else {
2027 					if (laddr.s_addr != INADDR_ANY)
2028 						wildcard++;
2029 				}
2030 				if (wildcard < matchwild) {
2031 					match = inp;
2032 					matchwild = wildcard;
2033 					if (matchwild == 0)
2034 						break;
2035 				}
2036 			}
2037 		}
2038 		return (match);
2039 	}
2040 }
2041 #undef INP_LOOKUP_MAPPED_PCB_COST
2042 
2043 static struct inpcb *
2044 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
2045     const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
2046     uint16_t fport, int lookupflags, int numa_domain)
2047 {
2048 	struct inpcb *local_wild, *numa_wild;
2049 	const struct inpcblbgrouphead *hdr;
2050 	struct inpcblbgroup *grp;
2051 	uint32_t idx;
2052 
2053 	INP_HASH_LOCK_ASSERT(pcbinfo);
2054 
2055 	hdr = &pcbinfo->ipi_lbgrouphashbase[
2056 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
2057 
2058 	/*
2059 	 * Order of socket selection:
2060 	 * 1. non-wild.
2061 	 * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
2062 	 *
2063 	 * NOTE:
2064 	 * - Load balanced group does not contain jailed sockets
2065 	 * - Load balanced group does not contain IPv4 mapped INET6 wild sockets
2066 	 */
2067 	local_wild = NULL;
2068 	numa_wild = NULL;
2069 	CK_LIST_FOREACH(grp, hdr, il_list) {
2070 #ifdef INET6
2071 		if (!(grp->il_vflag & INP_IPV4))
2072 			continue;
2073 #endif
2074 		if (grp->il_lport != lport)
2075 			continue;
2076 
2077 		idx = INP_PCBLBGROUP_PKTHASH(faddr->s_addr, lport, fport) %
2078 		    grp->il_inpcnt;
2079 		if (grp->il_laddr.s_addr == laddr->s_addr) {
2080 			if (numa_domain == M_NODOM ||
2081 			    grp->il_numa_domain == numa_domain) {
2082 				return (grp->il_inp[idx]);
2083 			} else {
2084 				numa_wild = grp->il_inp[idx];
2085 			}
2086 		}
2087 		if (grp->il_laddr.s_addr == INADDR_ANY &&
2088 		    (lookupflags & INPLOOKUP_WILDCARD) != 0 &&
2089 		    (local_wild == NULL || numa_domain == M_NODOM ||
2090 			grp->il_numa_domain == numa_domain)) {
2091 			local_wild = grp->il_inp[idx];
2092 		}
2093 	}
2094 	if (numa_wild != NULL)
2095 		return (numa_wild);
2096 
2097 	return (local_wild);
2098 }
2099 
2100 #ifdef PCBGROUP
2101 /*
2102  * Lookup PCB in hash list, using pcbgroup tables.
2103  */
2104 static struct inpcb *
2105 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
2106     struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
2107     u_int lport_arg, int lookupflags, struct ifnet *ifp)
2108 {
2109 	struct inpcbhead *head;
2110 	struct inpcb *inp, *tmpinp;
2111 	u_short fport = fport_arg, lport = lport_arg;
2112 	bool locked;
2113 
2114 	/*
2115 	 * First look for an exact match.
2116 	 */
2117 	tmpinp = NULL;
2118 	INP_GROUP_LOCK(pcbgroup);
2119 	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2120 	    pcbgroup->ipg_hashmask)];
2121 	CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2122 #ifdef INET6
2123 		/* XXX inp locking */
2124 		if ((inp->inp_vflag & INP_IPV4) == 0)
2125 			continue;
2126 #endif
2127 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
2128 		    inp->inp_laddr.s_addr == laddr.s_addr &&
2129 		    inp->inp_fport == fport &&
2130 		    inp->inp_lport == lport) {
2131 			/*
2132 			 * XXX We should be able to directly return
2133 			 * the inp here, without any checks.
2134 			 * Well unless both bound with SO_REUSEPORT?
2135 			 */
2136 			if (prison_flag(inp->inp_cred, PR_IP4))
2137 				goto found;
2138 			if (tmpinp == NULL)
2139 				tmpinp = inp;
2140 		}
2141 	}
2142 	if (tmpinp != NULL) {
2143 		inp = tmpinp;
2144 		goto found;
2145 	}
2146 
2147 #ifdef	RSS
2148 	/*
2149 	 * For incoming connections, we may wish to do a wildcard
2150 	 * match for an RSS-local socket.
2151 	 */
2152 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2153 		struct inpcb *local_wild = NULL, *local_exact = NULL;
2154 #ifdef INET6
2155 		struct inpcb *local_wild_mapped = NULL;
2156 #endif
2157 		struct inpcb *jail_wild = NULL;
2158 		struct inpcbhead *head;
2159 		int injail;
2160 
2161 		/*
2162 		 * Order of socket selection - we always prefer jails.
2163 		 *      1. jailed, non-wild.
2164 		 *      2. jailed, wild.
2165 		 *      3. non-jailed, non-wild.
2166 		 *      4. non-jailed, wild.
2167 		 */
2168 
2169 		head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
2170 		    lport, 0, pcbgroup->ipg_hashmask)];
2171 		CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2172 #ifdef INET6
2173 			/* XXX inp locking */
2174 			if ((inp->inp_vflag & INP_IPV4) == 0)
2175 				continue;
2176 #endif
2177 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
2178 			    inp->inp_lport != lport)
2179 				continue;
2180 
2181 			injail = prison_flag(inp->inp_cred, PR_IP4);
2182 			if (injail) {
2183 				if (prison_check_ip4(inp->inp_cred,
2184 				    &laddr) != 0)
2185 					continue;
2186 			} else {
2187 				if (local_exact != NULL)
2188 					continue;
2189 			}
2190 
2191 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
2192 				if (injail)
2193 					goto found;
2194 				else
2195 					local_exact = inp;
2196 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2197 #ifdef INET6
2198 				/* XXX inp locking, NULL check */
2199 				if (inp->inp_vflag & INP_IPV6PROTO)
2200 					local_wild_mapped = inp;
2201 				else
2202 #endif
2203 					if (injail)
2204 						jail_wild = inp;
2205 					else
2206 						local_wild = inp;
2207 			}
2208 		} /* LIST_FOREACH */
2209 
2210 		inp = jail_wild;
2211 		if (inp == NULL)
2212 			inp = local_exact;
2213 		if (inp == NULL)
2214 			inp = local_wild;
2215 #ifdef INET6
2216 		if (inp == NULL)
2217 			inp = local_wild_mapped;
2218 #endif
2219 		if (inp != NULL)
2220 			goto found;
2221 	}
2222 #endif
2223 
2224 	/*
2225 	 * Then look for a wildcard match, if requested.
2226 	 */
2227 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2228 		struct inpcb *local_wild = NULL, *local_exact = NULL;
2229 #ifdef INET6
2230 		struct inpcb *local_wild_mapped = NULL;
2231 #endif
2232 		struct inpcb *jail_wild = NULL;
2233 		struct inpcbhead *head;
2234 		int injail;
2235 
2236 		/*
2237 		 * Order of socket selection - we always prefer jails.
2238 		 *      1. jailed, non-wild.
2239 		 *      2. jailed, wild.
2240 		 *      3. non-jailed, non-wild.
2241 		 *      4. non-jailed, wild.
2242 		 */
2243 		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
2244 		    0, pcbinfo->ipi_wildmask)];
2245 		CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
2246 #ifdef INET6
2247 			/* XXX inp locking */
2248 			if ((inp->inp_vflag & INP_IPV4) == 0)
2249 				continue;
2250 #endif
2251 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
2252 			    inp->inp_lport != lport)
2253 				continue;
2254 
2255 			injail = prison_flag(inp->inp_cred, PR_IP4);
2256 			if (injail) {
2257 				if (prison_check_ip4(inp->inp_cred,
2258 				    &laddr) != 0)
2259 					continue;
2260 			} else {
2261 				if (local_exact != NULL)
2262 					continue;
2263 			}
2264 
2265 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
2266 				if (injail)
2267 					goto found;
2268 				else
2269 					local_exact = inp;
2270 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2271 #ifdef INET6
2272 				/* XXX inp locking, NULL check */
2273 				if (inp->inp_vflag & INP_IPV6PROTO)
2274 					local_wild_mapped = inp;
2275 				else
2276 #endif
2277 					if (injail)
2278 						jail_wild = inp;
2279 					else
2280 						local_wild = inp;
2281 			}
2282 		} /* LIST_FOREACH */
2283 		inp = jail_wild;
2284 		if (inp == NULL)
2285 			inp = local_exact;
2286 		if (inp == NULL)
2287 			inp = local_wild;
2288 #ifdef INET6
2289 		if (inp == NULL)
2290 			inp = local_wild_mapped;
2291 #endif
2292 		if (inp != NULL)
2293 			goto found;
2294 	} /* if (lookupflags & INPLOOKUP_WILDCARD) */
2295 	INP_GROUP_UNLOCK(pcbgroup);
2296 	return (NULL);
2297 
2298 found:
2299 	if (lookupflags & INPLOOKUP_WLOCKPCB)
2300 		locked = INP_TRY_WLOCK(inp);
2301 	else if (lookupflags & INPLOOKUP_RLOCKPCB)
2302 		locked = INP_TRY_RLOCK(inp);
2303 	else
2304 		panic("%s: locking bug", __func__);
2305 	if (__predict_false(locked && (inp->inp_flags2 & INP_FREED))) {
2306 		if (lookupflags & INPLOOKUP_WLOCKPCB)
2307 			INP_WUNLOCK(inp);
2308 		else
2309 			INP_RUNLOCK(inp);
2310 		return (NULL);
2311 	} else if (!locked)
2312 		in_pcbref(inp);
2313 	INP_GROUP_UNLOCK(pcbgroup);
2314 	if (!locked) {
2315 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
2316 			INP_WLOCK(inp);
2317 			if (in_pcbrele_wlocked(inp))
2318 				return (NULL);
2319 		} else {
2320 			INP_RLOCK(inp);
2321 			if (in_pcbrele_rlocked(inp))
2322 				return (NULL);
2323 		}
2324 	}
2325 #ifdef INVARIANTS
2326 	if (lookupflags & INPLOOKUP_WLOCKPCB)
2327 		INP_WLOCK_ASSERT(inp);
2328 	else
2329 		INP_RLOCK_ASSERT(inp);
2330 #endif
2331 	return (inp);
2332 }
2333 #endif /* PCBGROUP */
2334 
2335 /*
2336  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
2337  * that the caller has locked the hash list, and will not perform any further
2338  * locking or reference operations on either the hash list or the connection.
2339  */
2340 static struct inpcb *
2341 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2342     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2343     struct ifnet *ifp, uint8_t numa_domain)
2344 {
2345 	struct inpcbhead *head;
2346 	struct inpcb *inp, *tmpinp;
2347 	u_short fport = fport_arg, lport = lport_arg;
2348 
2349 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2350 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2351 	INP_HASH_LOCK_ASSERT(pcbinfo);
2352 
2353 	/*
2354 	 * First look for an exact match.
2355 	 */
2356 	tmpinp = NULL;
2357 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2358 	    pcbinfo->ipi_hashmask)];
2359 	CK_LIST_FOREACH(inp, head, inp_hash) {
2360 #ifdef INET6
2361 		/* XXX inp locking */
2362 		if ((inp->inp_vflag & INP_IPV4) == 0)
2363 			continue;
2364 #endif
2365 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
2366 		    inp->inp_laddr.s_addr == laddr.s_addr &&
2367 		    inp->inp_fport == fport &&
2368 		    inp->inp_lport == lport) {
2369 			/*
2370 			 * XXX We should be able to directly return
2371 			 * the inp here, without any checks.
2372 			 * Well unless both bound with SO_REUSEPORT?
2373 			 */
2374 			if (prison_flag(inp->inp_cred, PR_IP4))
2375 				return (inp);
2376 			if (tmpinp == NULL)
2377 				tmpinp = inp;
2378 		}
2379 	}
2380 	if (tmpinp != NULL)
2381 		return (tmpinp);
2382 
2383 	/*
2384 	 * Then look in lb group (for wildcard match).
2385 	 */
2386 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2387 		inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2388 		    fport, lookupflags, numa_domain);
2389 		if (inp != NULL)
2390 			return (inp);
2391 	}
2392 
2393 	/*
2394 	 * Then look for a wildcard match, if requested.
2395 	 */
2396 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2397 		struct inpcb *local_wild = NULL, *local_exact = NULL;
2398 #ifdef INET6
2399 		struct inpcb *local_wild_mapped = NULL;
2400 #endif
2401 		struct inpcb *jail_wild = NULL;
2402 		int injail;
2403 
2404 		/*
2405 		 * Order of socket selection - we always prefer jails.
2406 		 *      1. jailed, non-wild.
2407 		 *      2. jailed, wild.
2408 		 *      3. non-jailed, non-wild.
2409 		 *      4. non-jailed, wild.
2410 		 */
2411 
2412 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2413 		    0, pcbinfo->ipi_hashmask)];
2414 		CK_LIST_FOREACH(inp, head, inp_hash) {
2415 #ifdef INET6
2416 			/* XXX inp locking */
2417 			if ((inp->inp_vflag & INP_IPV4) == 0)
2418 				continue;
2419 #endif
2420 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
2421 			    inp->inp_lport != lport)
2422 				continue;
2423 
2424 			injail = prison_flag(inp->inp_cred, PR_IP4);
2425 			if (injail) {
2426 				if (prison_check_ip4(inp->inp_cred,
2427 				    &laddr) != 0)
2428 					continue;
2429 			} else {
2430 				if (local_exact != NULL)
2431 					continue;
2432 			}
2433 
2434 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
2435 				if (injail)
2436 					return (inp);
2437 				else
2438 					local_exact = inp;
2439 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2440 #ifdef INET6
2441 				/* XXX inp locking, NULL check */
2442 				if (inp->inp_vflag & INP_IPV6PROTO)
2443 					local_wild_mapped = inp;
2444 				else
2445 #endif
2446 					if (injail)
2447 						jail_wild = inp;
2448 					else
2449 						local_wild = inp;
2450 			}
2451 		} /* LIST_FOREACH */
2452 		if (jail_wild != NULL)
2453 			return (jail_wild);
2454 		if (local_exact != NULL)
2455 			return (local_exact);
2456 		if (local_wild != NULL)
2457 			return (local_wild);
2458 #ifdef INET6
2459 		if (local_wild_mapped != NULL)
2460 			return (local_wild_mapped);
2461 #endif
2462 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2463 
2464 	return (NULL);
2465 }
2466 
2467 /*
2468  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
2469  * hash list lock, and will return the inpcb locked (i.e., requires
2470  * INPLOOKUP_LOCKPCB).
2471  */
2472 static struct inpcb *
2473 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2474     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2475     struct ifnet *ifp, uint8_t numa_domain)
2476 {
2477 	struct inpcb *inp;
2478 
2479 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2480 	    lookupflags & INPLOOKUP_WILDCARD, ifp, numa_domain);
2481 	if (inp != NULL) {
2482 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
2483 			INP_WLOCK(inp);
2484 		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2485 			INP_RLOCK(inp);
2486 		} else
2487 			panic("%s: locking bug", __func__);
2488 		if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2489 			INP_UNLOCK(inp);
2490 			inp = NULL;
2491 		}
2492 	}
2493 
2494 	return (inp);
2495 }
2496 
2497 /*
2498  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2499  * from which a pre-calculated hash value may be extracted.
2500  *
2501  * Possibly more of this logic should be in in_pcbgroup.c.
2502  */
2503 struct inpcb *
2504 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2505     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2506 {
2507 #if defined(PCBGROUP) && !defined(RSS)
2508 	struct inpcbgroup *pcbgroup;
2509 #endif
2510 
2511 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2512 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2513 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2514 	    ("%s: LOCKPCB not set", __func__));
2515 
2516 	/*
2517 	 * When not using RSS, use connection groups in preference to the
2518 	 * reservation table when looking up 4-tuples.  When using RSS, just
2519 	 * use the reservation table, due to the cost of the Toeplitz hash
2520 	 * in software.
2521 	 *
2522 	 * XXXRW: This policy belongs in the pcbgroup code, as in principle
2523 	 * we could be doing RSS with a non-Toeplitz hash that is affordable
2524 	 * in software.
2525 	 */
2526 #if defined(PCBGROUP) && !defined(RSS)
2527 	if (in_pcbgroup_enabled(pcbinfo)) {
2528 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2529 		    fport);
2530 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2531 		    laddr, lport, lookupflags, ifp));
2532 	}
2533 #endif
2534 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2535 	    lookupflags, ifp, M_NODOM));
2536 }
2537 
2538 struct inpcb *
2539 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2540     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2541     struct ifnet *ifp, struct mbuf *m)
2542 {
2543 #ifdef PCBGROUP
2544 	struct inpcbgroup *pcbgroup;
2545 #endif
2546 
2547 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2548 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2549 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2550 	    ("%s: LOCKPCB not set", __func__));
2551 
2552 #ifdef PCBGROUP
2553 	/*
2554 	 * If we can use a hardware-generated hash to look up the connection
2555 	 * group, use that connection group to find the inpcb.  Otherwise
2556 	 * fall back on a software hash -- or the reservation table if we're
2557 	 * using RSS.
2558 	 *
2559 	 * XXXRW: As above, that policy belongs in the pcbgroup code.
2560 	 */
2561 	if (in_pcbgroup_enabled(pcbinfo) &&
2562 	    !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2563 		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2564 		    m->m_pkthdr.flowid);
2565 		if (pcbgroup != NULL)
2566 			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2567 			    fport, laddr, lport, lookupflags, ifp));
2568 #ifndef RSS
2569 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2570 		    fport);
2571 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2572 		    laddr, lport, lookupflags, ifp));
2573 #endif
2574 	}
2575 #endif
2576 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2577 	    lookupflags, ifp, m->m_pkthdr.numa_domain));
2578 }
2579 #endif /* INET */
2580 
2581 /*
2582  * Insert PCB onto various hash lists.
2583  */
2584 static int
2585 in_pcbinshash_internal(struct inpcb *inp, struct mbuf *m)
2586 {
2587 	struct inpcbhead *pcbhash;
2588 	struct inpcbporthead *pcbporthash;
2589 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2590 	struct inpcbport *phd;
2591 	u_int32_t hashkey_faddr;
2592 	int so_options;
2593 
2594 	INP_WLOCK_ASSERT(inp);
2595 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2596 
2597 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2598 	    ("in_pcbinshash: INP_INHASHLIST"));
2599 
2600 #ifdef INET6
2601 	if (inp->inp_vflag & INP_IPV6)
2602 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2603 	else
2604 #endif
2605 	hashkey_faddr = inp->inp_faddr.s_addr;
2606 
2607 	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2608 		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2609 
2610 	pcbporthash = &pcbinfo->ipi_porthashbase[
2611 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2612 
2613 	/*
2614 	 * Add entry to load balance group.
2615 	 * Only do this if SO_REUSEPORT_LB is set.
2616 	 */
2617 	so_options = inp_so_options(inp);
2618 	if (so_options & SO_REUSEPORT_LB) {
2619 		int ret = in_pcbinslbgrouphash(inp, M_NODOM);
2620 		if (ret) {
2621 			/* pcb lb group malloc fail (ret=ENOBUFS). */
2622 			return (ret);
2623 		}
2624 	}
2625 
2626 	/*
2627 	 * Go through port list and look for a head for this lport.
2628 	 */
2629 	CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2630 		if (phd->phd_port == inp->inp_lport)
2631 			break;
2632 	}
2633 	/*
2634 	 * If none exists, malloc one and tack it on.
2635 	 */
2636 	if (phd == NULL) {
2637 		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2638 		if (phd == NULL) {
2639 			return (ENOBUFS); /* XXX */
2640 		}
2641 		bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2642 		phd->phd_port = inp->inp_lport;
2643 		CK_LIST_INIT(&phd->phd_pcblist);
2644 		CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2645 	}
2646 	inp->inp_phd = phd;
2647 	CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2648 	CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2649 	inp->inp_flags |= INP_INHASHLIST;
2650 #ifdef PCBGROUP
2651 	if (m != NULL) {
2652 		in_pcbgroup_update_mbuf(inp, m);
2653 	} else {
2654 		in_pcbgroup_update(inp);
2655 	}
2656 #endif
2657 	return (0);
2658 }
2659 
2660 int
2661 in_pcbinshash(struct inpcb *inp)
2662 {
2663 
2664 	return (in_pcbinshash_internal(inp, NULL));
2665 }
2666 
2667 int
2668 in_pcbinshash_mbuf(struct inpcb *inp, struct mbuf *m)
2669 {
2670 
2671 	return (in_pcbinshash_internal(inp, m));
2672 }
2673 
2674 /*
2675  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2676  * changed. NOTE: This does not handle the case of the lport changing (the
2677  * hashed port list would have to be updated as well), so the lport must
2678  * not change after in_pcbinshash() has been called.
2679  */
2680 void
2681 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2682 {
2683 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2684 	struct inpcbhead *head;
2685 	u_int32_t hashkey_faddr;
2686 
2687 	INP_WLOCK_ASSERT(inp);
2688 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2689 
2690 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2691 	    ("in_pcbrehash: !INP_INHASHLIST"));
2692 
2693 #ifdef INET6
2694 	if (inp->inp_vflag & INP_IPV6)
2695 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2696 	else
2697 #endif
2698 	hashkey_faddr = inp->inp_faddr.s_addr;
2699 
2700 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2701 		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2702 
2703 	CK_LIST_REMOVE(inp, inp_hash);
2704 	CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2705 
2706 #ifdef PCBGROUP
2707 	if (m != NULL)
2708 		in_pcbgroup_update_mbuf(inp, m);
2709 	else
2710 		in_pcbgroup_update(inp);
2711 #endif
2712 }
2713 
2714 void
2715 in_pcbrehash(struct inpcb *inp)
2716 {
2717 
2718 	in_pcbrehash_mbuf(inp, NULL);
2719 }
2720 
2721 /*
2722  * Remove PCB from various lists.
2723  */
2724 static void
2725 in_pcbremlists(struct inpcb *inp)
2726 {
2727 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2728 
2729 	INP_WLOCK_ASSERT(inp);
2730 	INP_LIST_WLOCK_ASSERT(pcbinfo);
2731 
2732 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2733 	if (inp->inp_flags & INP_INHASHLIST) {
2734 		struct inpcbport *phd = inp->inp_phd;
2735 
2736 		INP_HASH_WLOCK(pcbinfo);
2737 
2738 		/* XXX: Only do if SO_REUSEPORT_LB set? */
2739 		in_pcbremlbgrouphash(inp);
2740 
2741 		CK_LIST_REMOVE(inp, inp_hash);
2742 		CK_LIST_REMOVE(inp, inp_portlist);
2743 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2744 			CK_LIST_REMOVE(phd, phd_hash);
2745 			NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
2746 		}
2747 		INP_HASH_WUNLOCK(pcbinfo);
2748 		inp->inp_flags &= ~INP_INHASHLIST;
2749 	}
2750 	CK_LIST_REMOVE(inp, inp_list);
2751 	pcbinfo->ipi_count--;
2752 #ifdef PCBGROUP
2753 	in_pcbgroup_remove(inp);
2754 #endif
2755 }
2756 
2757 /*
2758  * Check for alternatives when higher level complains
2759  * about service problems.  For now, invalidate cached
2760  * routing information.  If the route was created dynamically
2761  * (by a redirect), time to try a default gateway again.
2762  */
2763 void
2764 in_losing(struct inpcb *inp)
2765 {
2766 
2767 	RO_INVALIDATE_CACHE(&inp->inp_route);
2768 	return;
2769 }
2770 
2771 /*
2772  * A set label operation has occurred at the socket layer, propagate the
2773  * label change into the in_pcb for the socket.
2774  */
2775 void
2776 in_pcbsosetlabel(struct socket *so)
2777 {
2778 #ifdef MAC
2779 	struct inpcb *inp;
2780 
2781 	inp = sotoinpcb(so);
2782 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2783 
2784 	INP_WLOCK(inp);
2785 	SOCK_LOCK(so);
2786 	mac_inpcb_sosetlabel(so, inp);
2787 	SOCK_UNLOCK(so);
2788 	INP_WUNLOCK(inp);
2789 #endif
2790 }
2791 
2792 /*
2793  * ipport_tick runs once per second, determining if random port allocation
2794  * should be continued.  If more than ipport_randomcps ports have been
2795  * allocated in the last second, then we return to sequential port
2796  * allocation. We return to random allocation only once we drop below
2797  * ipport_randomcps for at least ipport_randomtime seconds.
2798  */
2799 static void
2800 ipport_tick(void *xtp)
2801 {
2802 	VNET_ITERATOR_DECL(vnet_iter);
2803 
2804 	VNET_LIST_RLOCK_NOSLEEP();
2805 	VNET_FOREACH(vnet_iter) {
2806 		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
2807 		if (V_ipport_tcpallocs <=
2808 		    V_ipport_tcplastcount + V_ipport_randomcps) {
2809 			if (V_ipport_stoprandom > 0)
2810 				V_ipport_stoprandom--;
2811 		} else
2812 			V_ipport_stoprandom = V_ipport_randomtime;
2813 		V_ipport_tcplastcount = V_ipport_tcpallocs;
2814 		CURVNET_RESTORE();
2815 	}
2816 	VNET_LIST_RUNLOCK_NOSLEEP();
2817 	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2818 }
2819 
2820 static void
2821 ip_fini(void *xtp)
2822 {
2823 
2824 	callout_stop(&ipport_tick_callout);
2825 }
2826 
2827 /*
2828  * The ipport_callout should start running at about the time we attach the
2829  * inet or inet6 domains.
2830  */
2831 static void
2832 ipport_tick_init(const void *unused __unused)
2833 {
2834 
2835 	/* Start ipport_tick. */
2836 	callout_init(&ipport_tick_callout, 1);
2837 	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2838 	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2839 		SHUTDOWN_PRI_DEFAULT);
2840 }
2841 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2842     ipport_tick_init, NULL);
2843 
2844 void
2845 inp_wlock(struct inpcb *inp)
2846 {
2847 
2848 	INP_WLOCK(inp);
2849 }
2850 
2851 void
2852 inp_wunlock(struct inpcb *inp)
2853 {
2854 
2855 	INP_WUNLOCK(inp);
2856 }
2857 
2858 void
2859 inp_rlock(struct inpcb *inp)
2860 {
2861 
2862 	INP_RLOCK(inp);
2863 }
2864 
2865 void
2866 inp_runlock(struct inpcb *inp)
2867 {
2868 
2869 	INP_RUNLOCK(inp);
2870 }
2871 
2872 #ifdef INVARIANT_SUPPORT
2873 void
2874 inp_lock_assert(struct inpcb *inp)
2875 {
2876 
2877 	INP_WLOCK_ASSERT(inp);
2878 }
2879 
2880 void
2881 inp_unlock_assert(struct inpcb *inp)
2882 {
2883 
2884 	INP_UNLOCK_ASSERT(inp);
2885 }
2886 #endif
2887 
2888 void
2889 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2890 {
2891 	struct inpcb *inp;
2892 
2893 	INP_INFO_WLOCK(&V_tcbinfo);
2894 	CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2895 		INP_WLOCK(inp);
2896 		func(inp, arg);
2897 		INP_WUNLOCK(inp);
2898 	}
2899 	INP_INFO_WUNLOCK(&V_tcbinfo);
2900 }
2901 
2902 struct socket *
2903 inp_inpcbtosocket(struct inpcb *inp)
2904 {
2905 
2906 	INP_WLOCK_ASSERT(inp);
2907 	return (inp->inp_socket);
2908 }
2909 
2910 struct tcpcb *
2911 inp_inpcbtotcpcb(struct inpcb *inp)
2912 {
2913 
2914 	INP_WLOCK_ASSERT(inp);
2915 	return ((struct tcpcb *)inp->inp_ppcb);
2916 }
2917 
2918 int
2919 inp_ip_tos_get(const struct inpcb *inp)
2920 {
2921 
2922 	return (inp->inp_ip_tos);
2923 }
2924 
2925 void
2926 inp_ip_tos_set(struct inpcb *inp, int val)
2927 {
2928 
2929 	inp->inp_ip_tos = val;
2930 }
2931 
2932 void
2933 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2934     uint32_t *faddr, uint16_t *fp)
2935 {
2936 
2937 	INP_LOCK_ASSERT(inp);
2938 	*laddr = inp->inp_laddr.s_addr;
2939 	*faddr = inp->inp_faddr.s_addr;
2940 	*lp = inp->inp_lport;
2941 	*fp = inp->inp_fport;
2942 }
2943 
2944 struct inpcb *
2945 so_sotoinpcb(struct socket *so)
2946 {
2947 
2948 	return (sotoinpcb(so));
2949 }
2950 
2951 struct tcpcb *
2952 so_sototcpcb(struct socket *so)
2953 {
2954 
2955 	return (sototcpcb(so));
2956 }
2957 
2958 /*
2959  * Create an external-format (``xinpcb'') structure using the information in
2960  * the kernel-format in_pcb structure pointed to by inp.  This is done to
2961  * reduce the spew of irrelevant information over this interface, to isolate
2962  * user code from changes in the kernel structure, and potentially to provide
2963  * information-hiding if we decide that some of this information should be
2964  * hidden from users.
2965  */
2966 void
2967 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2968 {
2969 
2970 	bzero(xi, sizeof(*xi));
2971 	xi->xi_len = sizeof(struct xinpcb);
2972 	if (inp->inp_socket)
2973 		sotoxsocket(inp->inp_socket, &xi->xi_socket);
2974 	bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2975 	xi->inp_gencnt = inp->inp_gencnt;
2976 	xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2977 	xi->inp_flow = inp->inp_flow;
2978 	xi->inp_flowid = inp->inp_flowid;
2979 	xi->inp_flowtype = inp->inp_flowtype;
2980 	xi->inp_flags = inp->inp_flags;
2981 	xi->inp_flags2 = inp->inp_flags2;
2982 	xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2983 	xi->in6p_cksum = inp->in6p_cksum;
2984 	xi->in6p_hops = inp->in6p_hops;
2985 	xi->inp_ip_tos = inp->inp_ip_tos;
2986 	xi->inp_vflag = inp->inp_vflag;
2987 	xi->inp_ip_ttl = inp->inp_ip_ttl;
2988 	xi->inp_ip_p = inp->inp_ip_p;
2989 	xi->inp_ip_minttl = inp->inp_ip_minttl;
2990 }
2991 
2992 #ifdef DDB
2993 static void
2994 db_print_indent(int indent)
2995 {
2996 	int i;
2997 
2998 	for (i = 0; i < indent; i++)
2999 		db_printf(" ");
3000 }
3001 
3002 static void
3003 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3004 {
3005 	char faddr_str[48], laddr_str[48];
3006 
3007 	db_print_indent(indent);
3008 	db_printf("%s at %p\n", name, inc);
3009 
3010 	indent += 2;
3011 
3012 #ifdef INET6
3013 	if (inc->inc_flags & INC_ISIPV6) {
3014 		/* IPv6. */
3015 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
3016 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
3017 	} else
3018 #endif
3019 	{
3020 		/* IPv4. */
3021 		inet_ntoa_r(inc->inc_laddr, laddr_str);
3022 		inet_ntoa_r(inc->inc_faddr, faddr_str);
3023 	}
3024 	db_print_indent(indent);
3025 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
3026 	    ntohs(inc->inc_lport));
3027 	db_print_indent(indent);
3028 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
3029 	    ntohs(inc->inc_fport));
3030 }
3031 
3032 static void
3033 db_print_inpflags(int inp_flags)
3034 {
3035 	int comma;
3036 
3037 	comma = 0;
3038 	if (inp_flags & INP_RECVOPTS) {
3039 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3040 		comma = 1;
3041 	}
3042 	if (inp_flags & INP_RECVRETOPTS) {
3043 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3044 		comma = 1;
3045 	}
3046 	if (inp_flags & INP_RECVDSTADDR) {
3047 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3048 		comma = 1;
3049 	}
3050 	if (inp_flags & INP_ORIGDSTADDR) {
3051 		db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3052 		comma = 1;
3053 	}
3054 	if (inp_flags & INP_HDRINCL) {
3055 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
3056 		comma = 1;
3057 	}
3058 	if (inp_flags & INP_HIGHPORT) {
3059 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3060 		comma = 1;
3061 	}
3062 	if (inp_flags & INP_LOWPORT) {
3063 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
3064 		comma = 1;
3065 	}
3066 	if (inp_flags & INP_ANONPORT) {
3067 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
3068 		comma = 1;
3069 	}
3070 	if (inp_flags & INP_RECVIF) {
3071 		db_printf("%sINP_RECVIF", comma ? ", " : "");
3072 		comma = 1;
3073 	}
3074 	if (inp_flags & INP_MTUDISC) {
3075 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
3076 		comma = 1;
3077 	}
3078 	if (inp_flags & INP_RECVTTL) {
3079 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
3080 		comma = 1;
3081 	}
3082 	if (inp_flags & INP_DONTFRAG) {
3083 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3084 		comma = 1;
3085 	}
3086 	if (inp_flags & INP_RECVTOS) {
3087 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
3088 		comma = 1;
3089 	}
3090 	if (inp_flags & IN6P_IPV6_V6ONLY) {
3091 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3092 		comma = 1;
3093 	}
3094 	if (inp_flags & IN6P_PKTINFO) {
3095 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3096 		comma = 1;
3097 	}
3098 	if (inp_flags & IN6P_HOPLIMIT) {
3099 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3100 		comma = 1;
3101 	}
3102 	if (inp_flags & IN6P_HOPOPTS) {
3103 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3104 		comma = 1;
3105 	}
3106 	if (inp_flags & IN6P_DSTOPTS) {
3107 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3108 		comma = 1;
3109 	}
3110 	if (inp_flags & IN6P_RTHDR) {
3111 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3112 		comma = 1;
3113 	}
3114 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
3115 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3116 		comma = 1;
3117 	}
3118 	if (inp_flags & IN6P_TCLASS) {
3119 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3120 		comma = 1;
3121 	}
3122 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
3123 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3124 		comma = 1;
3125 	}
3126 	if (inp_flags & INP_TIMEWAIT) {
3127 		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3128 		comma  = 1;
3129 	}
3130 	if (inp_flags & INP_ONESBCAST) {
3131 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3132 		comma  = 1;
3133 	}
3134 	if (inp_flags & INP_DROPPED) {
3135 		db_printf("%sINP_DROPPED", comma ? ", " : "");
3136 		comma  = 1;
3137 	}
3138 	if (inp_flags & INP_SOCKREF) {
3139 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
3140 		comma  = 1;
3141 	}
3142 	if (inp_flags & IN6P_RFC2292) {
3143 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3144 		comma = 1;
3145 	}
3146 	if (inp_flags & IN6P_MTU) {
3147 		db_printf("IN6P_MTU%s", comma ? ", " : "");
3148 		comma = 1;
3149 	}
3150 }
3151 
3152 static void
3153 db_print_inpvflag(u_char inp_vflag)
3154 {
3155 	int comma;
3156 
3157 	comma = 0;
3158 	if (inp_vflag & INP_IPV4) {
3159 		db_printf("%sINP_IPV4", comma ? ", " : "");
3160 		comma  = 1;
3161 	}
3162 	if (inp_vflag & INP_IPV6) {
3163 		db_printf("%sINP_IPV6", comma ? ", " : "");
3164 		comma  = 1;
3165 	}
3166 	if (inp_vflag & INP_IPV6PROTO) {
3167 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3168 		comma  = 1;
3169 	}
3170 }
3171 
3172 static void
3173 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3174 {
3175 
3176 	db_print_indent(indent);
3177 	db_printf("%s at %p\n", name, inp);
3178 
3179 	indent += 2;
3180 
3181 	db_print_indent(indent);
3182 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3183 
3184 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3185 
3186 	db_print_indent(indent);
3187 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
3188 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3189 
3190 	db_print_indent(indent);
3191 	db_printf("inp_label: %p   inp_flags: 0x%x (",
3192 	   inp->inp_label, inp->inp_flags);
3193 	db_print_inpflags(inp->inp_flags);
3194 	db_printf(")\n");
3195 
3196 	db_print_indent(indent);
3197 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3198 	    inp->inp_vflag);
3199 	db_print_inpvflag(inp->inp_vflag);
3200 	db_printf(")\n");
3201 
3202 	db_print_indent(indent);
3203 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3204 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3205 
3206 	db_print_indent(indent);
3207 #ifdef INET6
3208 	if (inp->inp_vflag & INP_IPV6) {
3209 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
3210 		    "in6p_moptions: %p\n", inp->in6p_options,
3211 		    inp->in6p_outputopts, inp->in6p_moptions);
3212 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3213 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3214 		    inp->in6p_hops);
3215 	} else
3216 #endif
3217 	{
3218 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3219 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3220 		    inp->inp_options, inp->inp_moptions);
3221 	}
3222 
3223 	db_print_indent(indent);
3224 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
3225 	    (uintmax_t)inp->inp_gencnt);
3226 }
3227 
3228 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3229 {
3230 	struct inpcb *inp;
3231 
3232 	if (!have_addr) {
3233 		db_printf("usage: show inpcb <addr>\n");
3234 		return;
3235 	}
3236 	inp = (struct inpcb *)addr;
3237 
3238 	db_print_inpcb(inp, "inpcb", 0);
3239 }
3240 #endif /* DDB */
3241 
3242 #ifdef RATELIMIT
3243 /*
3244  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3245  * if any.
3246  */
3247 int
3248 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3249 {
3250 	union if_snd_tag_modify_params params = {
3251 		.rate_limit.max_rate = max_pacing_rate,
3252 		.rate_limit.flags = M_NOWAIT,
3253 	};
3254 	struct m_snd_tag *mst;
3255 	int error;
3256 
3257 	mst = inp->inp_snd_tag;
3258 	if (mst == NULL)
3259 		return (EINVAL);
3260 
3261 	if (mst->sw->snd_tag_modify == NULL) {
3262 		error = EOPNOTSUPP;
3263 	} else {
3264 		error = mst->sw->snd_tag_modify(mst, &params);
3265 	}
3266 	return (error);
3267 }
3268 
3269 /*
3270  * Query existing TX rate limit based on the existing
3271  * "inp->inp_snd_tag", if any.
3272  */
3273 int
3274 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3275 {
3276 	union if_snd_tag_query_params params = { };
3277 	struct m_snd_tag *mst;
3278 	int error;
3279 
3280 	mst = inp->inp_snd_tag;
3281 	if (mst == NULL)
3282 		return (EINVAL);
3283 
3284 	if (mst->sw->snd_tag_query == NULL) {
3285 		error = EOPNOTSUPP;
3286 	} else {
3287 		error = mst->sw->snd_tag_query(mst, &params);
3288 		if (error == 0 && p_max_pacing_rate != NULL)
3289 			*p_max_pacing_rate = params.rate_limit.max_rate;
3290 	}
3291 	return (error);
3292 }
3293 
3294 /*
3295  * Query existing TX queue level based on the existing
3296  * "inp->inp_snd_tag", if any.
3297  */
3298 int
3299 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3300 {
3301 	union if_snd_tag_query_params params = { };
3302 	struct m_snd_tag *mst;
3303 	int error;
3304 
3305 	mst = inp->inp_snd_tag;
3306 	if (mst == NULL)
3307 		return (EINVAL);
3308 
3309 	if (mst->sw->snd_tag_query == NULL)
3310 		return (EOPNOTSUPP);
3311 
3312 	error = mst->sw->snd_tag_query(mst, &params);
3313 	if (error == 0 && p_txqueue_level != NULL)
3314 		*p_txqueue_level = params.rate_limit.queue_level;
3315 	return (error);
3316 }
3317 
3318 /*
3319  * Allocate a new TX rate limit send tag from the network interface
3320  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3321  */
3322 int
3323 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3324     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
3325 
3326 {
3327 	union if_snd_tag_alloc_params params = {
3328 		.rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3329 		    IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3330 		.rate_limit.hdr.flowid = flowid,
3331 		.rate_limit.hdr.flowtype = flowtype,
3332 		.rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3333 		.rate_limit.max_rate = max_pacing_rate,
3334 		.rate_limit.flags = M_NOWAIT,
3335 	};
3336 	int error;
3337 
3338 	INP_WLOCK_ASSERT(inp);
3339 
3340 	/*
3341 	 * If there is already a send tag, or the INP is being torn
3342 	 * down, allocating a new send tag is not allowed. Else send
3343 	 * tags may leak.
3344 	 */
3345 	if (*st != NULL || (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0)
3346 		return (EINVAL);
3347 
3348 	error = m_snd_tag_alloc(ifp, &params, st);
3349 #ifdef INET
3350 	if (error == 0) {
3351 		counter_u64_add(rate_limit_set_ok, 1);
3352 		counter_u64_add(rate_limit_active, 1);
3353 	} else if (error != EOPNOTSUPP)
3354 		  counter_u64_add(rate_limit_alloc_fail, 1);
3355 #endif
3356 	return (error);
3357 }
3358 
3359 void
3360 in_pcbdetach_tag(struct m_snd_tag *mst)
3361 {
3362 
3363 	m_snd_tag_rele(mst);
3364 #ifdef INET
3365 	counter_u64_add(rate_limit_active, -1);
3366 #endif
3367 }
3368 
3369 /*
3370  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3371  * if any:
3372  */
3373 void
3374 in_pcbdetach_txrtlmt(struct inpcb *inp)
3375 {
3376 	struct m_snd_tag *mst;
3377 
3378 	INP_WLOCK_ASSERT(inp);
3379 
3380 	mst = inp->inp_snd_tag;
3381 	inp->inp_snd_tag = NULL;
3382 
3383 	if (mst == NULL)
3384 		return;
3385 
3386 	m_snd_tag_rele(mst);
3387 #ifdef INET
3388 	counter_u64_add(rate_limit_active, -1);
3389 #endif
3390 }
3391 
3392 int
3393 in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
3394 {
3395 	int error;
3396 
3397 	/*
3398 	 * If the existing send tag is for the wrong interface due to
3399 	 * a route change, first drop the existing tag.  Set the
3400 	 * CHANGED flag so that we will keep trying to allocate a new
3401 	 * tag if we fail to allocate one this time.
3402 	 */
3403 	if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
3404 		in_pcbdetach_txrtlmt(inp);
3405 		inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3406 	}
3407 
3408 	/*
3409 	 * NOTE: When attaching to a network interface a reference is
3410 	 * made to ensure the network interface doesn't go away until
3411 	 * all ratelimit connections are gone. The network interface
3412 	 * pointers compared below represent valid network interfaces,
3413 	 * except when comparing towards NULL.
3414 	 */
3415 	if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3416 		error = 0;
3417 	} else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3418 		if (inp->inp_snd_tag != NULL)
3419 			in_pcbdetach_txrtlmt(inp);
3420 		error = 0;
3421 	} else if (inp->inp_snd_tag == NULL) {
3422 		/*
3423 		 * In order to utilize packet pacing with RSS, we need
3424 		 * to wait until there is a valid RSS hash before we
3425 		 * can proceed:
3426 		 */
3427 		if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3428 			error = EAGAIN;
3429 		} else {
3430 			error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3431 			    mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
3432 		}
3433 	} else {
3434 		error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3435 	}
3436 	if (error == 0 || error == EOPNOTSUPP)
3437 		inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3438 
3439 	return (error);
3440 }
3441 
3442 /*
3443  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3444  * is set in the fast path and will attach/detach/modify the TX rate
3445  * limit send tag based on the socket's so_max_pacing_rate value.
3446  */
3447 void
3448 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3449 {
3450 	struct socket *socket;
3451 	uint32_t max_pacing_rate;
3452 	bool did_upgrade;
3453 	int error;
3454 
3455 	if (inp == NULL)
3456 		return;
3457 
3458 	socket = inp->inp_socket;
3459 	if (socket == NULL)
3460 		return;
3461 
3462 	if (!INP_WLOCKED(inp)) {
3463 		/*
3464 		 * NOTE: If the write locking fails, we need to bail
3465 		 * out and use the non-ratelimited ring for the
3466 		 * transmit until there is a new chance to get the
3467 		 * write lock.
3468 		 */
3469 		if (!INP_TRY_UPGRADE(inp))
3470 			return;
3471 		did_upgrade = 1;
3472 	} else {
3473 		did_upgrade = 0;
3474 	}
3475 
3476 	/*
3477 	 * NOTE: The so_max_pacing_rate value is read unlocked,
3478 	 * because atomic updates are not required since the variable
3479 	 * is checked at every mbuf we send. It is assumed that the
3480 	 * variable read itself will be atomic.
3481 	 */
3482 	max_pacing_rate = socket->so_max_pacing_rate;
3483 
3484 	error = in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3485 
3486 	if (did_upgrade)
3487 		INP_DOWNGRADE(inp);
3488 }
3489 
3490 /*
3491  * Track route changes for TX rate limiting.
3492  */
3493 void
3494 in_pcboutput_eagain(struct inpcb *inp)
3495 {
3496 	bool did_upgrade;
3497 
3498 	if (inp == NULL)
3499 		return;
3500 
3501 	if (inp->inp_snd_tag == NULL)
3502 		return;
3503 
3504 	if (!INP_WLOCKED(inp)) {
3505 		/*
3506 		 * NOTE: If the write locking fails, we need to bail
3507 		 * out and use the non-ratelimited ring for the
3508 		 * transmit until there is a new chance to get the
3509 		 * write lock.
3510 		 */
3511 		if (!INP_TRY_UPGRADE(inp))
3512 			return;
3513 		did_upgrade = 1;
3514 	} else {
3515 		did_upgrade = 0;
3516 	}
3517 
3518 	/* detach rate limiting */
3519 	in_pcbdetach_txrtlmt(inp);
3520 
3521 	/* make sure new mbuf send tag allocation is made */
3522 	inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3523 
3524 	if (did_upgrade)
3525 		INP_DOWNGRADE(inp);
3526 }
3527 
3528 #ifdef INET
3529 static void
3530 rl_init(void *st)
3531 {
3532 	rate_limit_new = counter_u64_alloc(M_WAITOK);
3533 	rate_limit_chg = counter_u64_alloc(M_WAITOK);
3534 	rate_limit_active = counter_u64_alloc(M_WAITOK);
3535 	rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
3536 	rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
3537 }
3538 
3539 SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3540 #endif
3541 #endif /* RATELIMIT */
3542