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