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