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