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