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