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