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