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