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