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