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