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