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