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