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