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