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