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