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