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