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