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