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