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