2 * SPDX-License-Identifier: BSD-3-Clause
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.
10 * Portions of this software were developed by Robert N. M. Watson under
11 * contract to Juniper Networks, Inc.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
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.
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
37 * @(#)in_pcb.c 8.4 (Berkeley) 5/24/95
40 #include <sys/cdefs.h>
42 #include "opt_ipsec.h"
44 #include "opt_inet6.h"
45 #include "opt_ratelimit.h"
46 #include "opt_pcbgroup.h"
47 #include "opt_route.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
53 #include <sys/malloc.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>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/sockio.h>
66 #include <sys/refcount.h>
68 #include <sys/kernel.h>
69 #include <sys/sysctl.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>
86 #if defined(INET) || defined(INET6)
87 #include <netinet/in.h>
88 #include <netinet/in_pcb.h>
90 #include <netinet/in_var.h>
91 #include <netinet/in_fib.h>
93 #include <netinet/ip_var.h>
94 #include <netinet/tcp_var.h>
96 #include <netinet/tcp_hpts.h>
98 #include <netinet/udp.h>
99 #include <netinet/udp_var.h>
101 #include <netinet/ip6.h>
102 #include <netinet6/in6_pcb.h>
103 #include <netinet6/in6_var.h>
104 #include <netinet6/ip6_var.h>
106 #include <net/route/nhop.h>
109 #include <netipsec/ipsec_support.h>
111 #include <security/mac/mac_framework.h>
113 #define INPCBLBGROUP_SIZMIN 8
114 #define INPCBLBGROUP_SIZMAX 256
116 static struct callout ipport_tick_callout;
119 * These configure the range of local port addresses assigned to
120 * "unspecified" outgoing connections/packets/whatever.
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 */
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.
134 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1; /* 1023 */
135 VNET_DEFINE(int, ipport_reservedlow);
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);
145 #define V_ipport_tcplastcount VNET(ipport_tcplastcount)
147 static void in_pcbremlists(struct inpcb *inp);
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);
155 #define RANGECHK(var, min, max) \
156 if ((var) < (min)) { (var) = (min); } \
157 else if ((var) > (max)) { (var) = (max); }
160 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
164 error = sysctl_handle_int(oidp, arg1, arg2, req);
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);
178 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
179 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
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",
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",
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",
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",
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",
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",
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");
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;
231 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
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");
244 #endif /* RATELIMIT */
249 * in_pcb.c: manage the Protocol Control Blocks.
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.
256 static struct inpcblbgroup *
257 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, struct ucred *cred,
258 u_char vflag, uint16_t port, const union in_dependaddr *addr, int size,
261 struct inpcblbgroup *grp;
264 bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
265 grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
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);
279 in_pcblbgroup_free_deferred(epoch_context_t ctx)
281 struct inpcblbgroup *grp;
283 grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
284 crfree(grp->il_cred);
289 in_pcblbgroup_free(struct inpcblbgroup *grp)
292 CK_LIST_REMOVE(grp, il_list);
293 NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
296 static struct inpcblbgroup *
297 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
298 struct inpcblbgroup *old_grp, int size)
300 struct inpcblbgroup *grp;
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);
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));
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);
321 * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
322 * and shrink group if possible.
325 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
328 struct inpcblbgroup *grp, *new_grp;
331 for (; i + 1 < grp->il_inpcnt; ++i)
332 grp->il_inp[i] = grp->il_inp[i + 1];
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);
345 * Add PCB to load balance group for SO_REUSEPORT_LB option.
348 in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
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;
357 pcbinfo = inp->inp_pcbinfo;
359 INP_WLOCK_ASSERT(inp);
360 INP_HASH_WLOCK_ASSERT(pcbinfo);
364 * Don't allow IPv4 mapped INET6 wild socket.
366 if ((inp->inp_vflag & INP_IPV4) &&
367 inp->inp_laddr.s_addr == INADDR_ANY &&
368 INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
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) {
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);
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));
401 /* Expand this local group. */
402 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
407 KASSERT(grp->il_inpcnt < grp->il_inpsiz,
408 ("invalid local group size %d and count %d", grp->il_inpsiz,
411 grp->il_inp[grp->il_inpcnt] = inp;
417 * Remove PCB from load balance group.
420 in_pcbremlbgrouphash(struct inpcb *inp)
422 struct inpcbinfo *pcbinfo;
423 struct inpcblbgrouphead *hdr;
424 struct inpcblbgroup *grp;
427 pcbinfo = inp->inp_pcbinfo;
429 INP_WLOCK_ASSERT(inp);
430 INP_HASH_WLOCK_ASSERT(pcbinfo);
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)
439 if (grp->il_inpcnt == 1) {
440 /* We are the last, free this local group. */
441 in_pcblbgroup_free(grp);
443 /* Pull up inpcbs, shrink group if possible. */
444 in_pcblbgroup_reorder(hdr, &grp, i);
452 in_pcblbgroup_numa(struct inpcb *inp, int arg)
454 struct inpcbinfo *pcbinfo;
455 struct inpcblbgrouphead *hdr;
456 struct inpcblbgroup *grp;
461 case TCP_REUSPORT_LB_NUMA_NODOM:
462 numa_domain = M_NODOM;
464 case TCP_REUSPORT_LB_NUMA_CURDOM:
465 numa_domain = PCPU_GET(domain);
468 if (arg < 0 || arg >= vm_ndomains)
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)
484 if (grp->il_numa_domain == numa_domain) {
485 goto abort_with_hash_wlock;
488 /* Remove it from the old group. */
489 in_pcbremlbgrouphash(inp);
491 /* Add it to the new group based on numa domain. */
492 in_pcbinslbgrouphash(inp, numa_domain);
493 goto abort_with_hash_wlock;
497 abort_with_hash_wlock:
498 INP_HASH_WUNLOCK(pcbinfo);
503 * Different protocols initialize their inpcbs differently - giving
504 * different name to the lock. But they all are disposed the same.
507 inpcb_fini(void *mem, int size)
509 struct inpcb *inp = mem;
511 INP_LOCK_DESTROY(inp);
515 * Initialize an inpcbinfo -- we should be able to reduce the number of
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)
524 porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
526 INP_INFO_LOCK_INIT(pcbinfo, name);
527 INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash"); /* XXXRW: argument? */
528 INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
530 pcbinfo->ipi_vnet = curvnet;
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);
542 in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
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");
552 * Destroy an inpcbinfo.
555 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
558 KASSERT(pcbinfo->ipi_count == 0,
559 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
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);
567 in_pcbgroup_destroy(pcbinfo);
569 uma_zdestroy(pcbinfo->ipi_zone);
570 INP_LIST_LOCK_DESTROY(pcbinfo);
571 INP_HASH_LOCK_DESTROY(pcbinfo);
572 INP_INFO_LOCK_DESTROY(pcbinfo);
576 * Allocate a PCB and associate it with the socket.
577 * On success return with the PCB locked.
580 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
586 inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
589 bzero(&inp->inp_start_zero, inp_zero_size);
591 inp->inp_numa_domain = M_NODOM;
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;
598 error = mac_inpcb_init(inp, M_NOWAIT);
601 mac_inpcb_create(so, inp);
603 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
604 error = ipsec_init_pcbpolicy(inp);
607 mac_inpcb_destroy(inp);
613 if (INP_SOCKAF(so) == AF_INET6) {
614 inp->inp_vflag |= INP_IPV6PROTO;
616 inp->inp_flags |= IN6P_IPV6_V6ONLY;
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;
625 if (V_ip6_auto_flowlabel)
626 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
628 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
629 refcount_init(&inp->inp_refcount, 1); /* Reference from inpcbinfo */
632 * Routes in inpcb's can cache L2 as well; they are guaranteed
635 inp->inp_route.ro_flags = RT_LLE_CACHE;
636 INP_LIST_WUNLOCK(pcbinfo);
637 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
640 crfree(inp->inp_cred);
641 uma_zfree(pcbinfo->ipi_zone, inp);
649 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
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);
660 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
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);
667 if (in_pcbinshash(inp) != 0) {
668 inp->inp_laddr.s_addr = INADDR_ANY;
673 inp->inp_flags |= INP_ANONPORT;
678 #if defined(INET) || defined(INET6)
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.
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)
689 struct inpcbinfo *pcbinfo;
690 struct inpcb *tmpinp;
691 unsigned short *lastport;
692 int count, dorandom, error;
693 u_short aux, first, last, lport;
695 struct in_addr laddr, faddr;
698 struct in6_addr *laddr6, *faddr6;
701 pcbinfo = inp->inp_pcbinfo;
704 * Because no actual state changes occur here, a global write lock on
705 * the pcbinfo isn't required.
707 INP_LOCK_ASSERT(inp);
708 INP_HASH_LOCK_ASSERT(pcbinfo);
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);
718 first = V_ipport_lowfirstauto; /* 1023 */
719 last = V_ipport_lowlastauto; /* 600 */
720 lastport = &pcbinfo->ipi_lastlow;
722 first = V_ipport_firstauto; /* sysctl */
723 last = V_ipport_lastauto;
724 lastport = &pcbinfo->ipi_lastport;
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.
732 if (V_ipport_randomized &&
733 (!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
734 pcbinfo == &V_ulitecbinfo))
739 * It makes no sense to do random port allocation if
740 * we have the only port available.
744 /* Make sure to not include UDP(-Lite) packets in the count. */
745 if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
746 V_ipport_tcpallocs++;
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.
759 laddr.s_addr = INADDR_ANY; /* used by INET6+INET below too */
760 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
762 laddr = ((struct sockaddr_in *)lsa)->sin_addr;
764 faddr = ((struct sockaddr_in *)fsa)->sin_addr;
769 if ((inp->inp_vflag & INP_IPV6) != 0) {
771 laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
773 faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
781 *lastport = first + (arc4random() % (last - first));
783 count = last - first;
786 if (count-- < 0) /* completely used? */
787 return (EADDRNOTAVAIL);
789 if (*lastport < first || *lastport > last)
791 lport = htons(*lastport);
795 if (lsa->sa_family == AF_INET) {
796 tmpinp = in_pcblookup_hash_locked(pcbinfo,
797 faddr, fport, laddr, lport, lookupflags,
802 if (lsa->sa_family == AF_INET6) {
803 tmpinp = in6_pcblookup_hash_locked(pcbinfo,
804 faddr6, fport, laddr6, lport, lookupflags,
810 if ((inp->inp_vflag & INP_IPV6) != 0) {
811 tmpinp = in6_pcblookup_local(pcbinfo,
812 &inp->in6p_laddr, lport, lookupflags, cred);
814 if (tmpinp == NULL &&
815 (inp->inp_vflag & INP_IPV4))
816 tmpinp = in_pcblookup_local(pcbinfo,
817 laddr, lport, lookupflags, cred);
821 #if defined(INET) && defined(INET6)
825 tmpinp = in_pcblookup_local(pcbinfo, laddr,
826 lport, lookupflags, cred);
829 } while (tmpinp != NULL);
837 * Select a local port (number) to use.
840 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
841 struct ucred *cred, int lookupflags)
843 struct sockaddr_in laddr;
846 bzero(&laddr, sizeof(laddr));
847 laddr.sin_family = AF_INET;
848 laddr.sin_addr = *laddrp;
850 return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
851 NULL, lportp, NULL, 0, cred, lookupflags));
855 * Return cached socket options.
858 inp_so_options(const struct inpcb *inp)
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;
872 #endif /* INET || INET6 */
875 * Check if a new BINDMULTI socket is allowed to be created.
877 * ni points to the new inp.
878 * oi points to the existing inp.
880 * This checks whether the existing inp also has BINDMULTI and
881 * whether the credentials match.
884 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
886 /* Check permissions match */
887 if ((ni->inp_flags2 & INP_BINDMULTI) &&
888 (ni->inp_cred->cr_uid !=
889 oi->inp_cred->cr_uid))
892 /* Check the existing inp has BINDMULTI set */
893 if ((ni->inp_flags2 & INP_BINDMULTI) &&
894 ((oi->inp_flags2 & INP_BINDMULTI) == 0))
898 * We're okay - either INP_BINDMULTI isn't set on ni, or
899 * it is and it matches the checks.
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.
912 * On error, the values of *laddrp and *lportp are not changed.
915 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
916 u_short *lportp, struct ucred *cred)
918 struct socket *so = inp->inp_socket;
919 struct sockaddr_in *sin;
920 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
921 struct in_addr laddr;
923 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
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.
930 int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
933 * No state changes, so read locks are sufficient here.
935 INP_LOCK_ASSERT(inp);
936 INP_HASH_LOCK_ASSERT(pcbinfo);
938 laddr.s_addr = *laddrp;
939 if (nam != NULL && laddr.s_addr != INADDR_ANY)
941 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
942 lookupflags = INPLOOKUP_WILDCARD;
944 if ((error = prison_local_ip4(cred, &laddr)) != 0)
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));
953 error = prison_local_ip4(cred, &sin->sin_addr);
956 if (sin->sin_port != *lportp) {
957 /* Don't allow the port to change. */
960 lport = sin->sin_port;
962 /* NB: lport is left as 0 if the port isn't being changed. */
963 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
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.
971 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
972 reuseport = SO_REUSEADDR|SO_REUSEPORT;
974 * XXX: How to deal with SO_REUSEPORT_LB here?
975 * Treat same as SO_REUSEPORT for now.
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));
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.
988 if ((inp->inp_flags & INP_BINDANY) == 0 &&
989 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
990 return (EADDRNOTAVAIL);
992 laddr = sin->sin_addr;
998 if (ntohs(lport) <= V_ipport_reservedhigh &&
999 ntohs(lport) >= V_ipport_reservedlow &&
1000 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
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);
1008 * This entire block sorely needs a rewrite.
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);
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
1029 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1030 return (EADDRINUSE);
1032 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1033 lport, lookupflags, cred);
1034 if (t && (t->inp_flags & INP_TIMEWAIT)) {
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.
1043 ((reuseport & tw->tw_so_options) == 0 &&
1045 tw->tw_so_options) == 0)) {
1046 return (EADDRINUSE);
1049 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1050 (reuseport & inp_so_options(t)) == 0 &&
1051 (reuseport_lb & inp_so_options(t)) == 0) {
1053 if (ntohl(sin->sin_addr.s_addr) !=
1055 ntohl(t->inp_laddr.s_addr) !=
1057 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1058 (t->inp_vflag & INP_IPV6PROTO) == 0)
1060 return (EADDRINUSE);
1061 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1062 return (EADDRINUSE);
1069 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1073 *laddrp = laddr.s_addr;
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,
1085 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
1086 struct ucred *cred, struct mbuf *m, bool rehash)
1088 u_short lport, fport;
1089 in_addr_t laddr, faddr;
1090 int anonport, error;
1092 INP_WLOCK_ASSERT(inp);
1093 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
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,
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;
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;
1122 in_pcbrehash_mbuf(inp, m);
1124 in_pcbinshash_mbuf(inp, m);
1128 inp->inp_flags |= INP_ANONPORT;
1133 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1136 return (in_pcbconnect_mbuf(inp, nam, cred, NULL, true));
1140 * Do proper source address selection on an unbound socket in case
1141 * of connect. Take jails into account as well.
1144 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1148 struct sockaddr *sa;
1149 struct sockaddr_in *sin, dst;
1150 struct nhop_object *nh;
1154 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1157 * Bypass source address selection and use the primary jail IP
1160 if (!prison_saddrsel_ip4(cred, laddr))
1166 bzero(&dst, sizeof(dst));
1168 sin->sin_family = AF_INET;
1169 sin->sin_len = sizeof(struct sockaddr_in);
1170 sin->sin_addr.s_addr = faddr->s_addr;
1173 * If route is known our src addr is taken from the i/f,
1176 * Find out route to destination.
1178 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1179 nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
1183 * If we found a route, use the address corresponding to
1184 * the outgoing interface.
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.
1190 if (nh == NULL || nh->nh_ifp == NULL) {
1191 struct in_ifaddr *ia;
1194 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1195 inp->inp_socket->so_fibnum));
1197 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1198 inp->inp_socket->so_fibnum));
1201 error = ENETUNREACH;
1205 if (!prison_flag(cred, PR_IP4)) {
1206 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1212 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1214 if (sa->sa_family != AF_INET)
1216 sin = (struct sockaddr_in *)sa;
1217 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1218 ia = (struct in_ifaddr *)ifa;
1223 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1227 /* 3. As a last resort return the 'default' jail address. */
1228 error = prison_get_ip4(cred, laddr);
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.
1241 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
1242 struct in_ifaddr *ia;
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;
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;
1262 * 2. Check if we have any address on the outgoing interface
1263 * belonging to this jail.
1267 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1269 if (sa->sa_family != AF_INET)
1271 sin = (struct sockaddr_in *)sa;
1272 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1273 ia = (struct in_ifaddr *)ifa;
1278 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1282 /* 3. As a last resort return the 'default' jail address. */
1283 error = prison_get_ip4(cred, laddr);
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.
1296 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
1297 struct in_ifaddr *ia;
1299 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
1300 inp->inp_socket->so_fibnum));
1302 ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
1303 inp->inp_socket->so_fibnum));
1305 ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
1307 if (!prison_flag(cred, PR_IP4)) {
1309 error = ENETUNREACH;
1312 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1322 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1324 if (sa->sa_family != AF_INET)
1326 sin = (struct sockaddr_in *)sa;
1327 if (prison_check_ip4(cred,
1328 &sin->sin_addr) == 0) {
1329 ia = (struct in_ifaddr *)ifa;
1334 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1339 /* 3. As a last resort return the 'default' jail address. */
1340 error = prison_get_ip4(cred, laddr);
1345 if (error == 0 && laddr->s_addr == INADDR_ANY)
1346 return (EHOSTUNREACH);
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
1357 * On success, *faddrp and *fportp will be set to the remote address
1358 * and port. These are not updated in the error case.
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
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)
1370 struct rm_priotracker in_ifa_tracker;
1371 struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1372 struct in_ifaddr *ia;
1374 struct in_addr laddr, faddr;
1375 u_short lport, fport;
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));
1384 * Because a global state change doesn't actually occur here, a read
1385 * lock is sufficient.
1388 INP_LOCK_ASSERT(inp);
1389 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1393 if (sin->sin_port == 0)
1394 return (EADDRNOTAVAIL);
1395 laddr.s_addr = *laddrp;
1397 faddr = sin->sin_addr;
1398 fport = sin->sin_port;
1400 if (CALC_FLOWID_OUTBOUND) {
1401 uint32_t hash_val, hash_type;
1403 hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
1404 inp->inp_socket->so_proto->pr_protocol, &hash_type);
1406 inp->inp_flowid = hash_val;
1407 inp->inp_flowtype = hash_type;
1410 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
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.
1418 if (faddr.s_addr == INADDR_ANY) {
1419 IN_IFADDR_RLOCK(&in_ifa_tracker);
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)
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 &
1429 faddr = satosin(&CK_STAILQ_FIRST(
1430 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1431 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1434 if (laddr.s_addr == INADDR_ANY) {
1435 error = in_pcbladdr(inp, &faddr, &laddr, cred);
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.
1441 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1442 inp->inp_moptions != NULL) {
1443 struct ip_moptions *imo;
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)
1457 error = EADDRNOTAVAIL;
1459 laddr = ia->ia_addr.sin_addr;
1462 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1470 oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1471 fport, laddr, lport, 0, NULL, M_NODOM);
1475 return (EADDRINUSE);
1478 struct sockaddr_in lsin, fsin;
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);
1492 *laddrp = laddr.s_addr;
1494 *faddrp = faddr.s_addr;
1500 in_pcbdisconnect(struct inpcb *inp)
1503 INP_WLOCK_ASSERT(inp);
1504 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1506 inp->inp_laddr.s_addr = INADDR_ANY;
1507 inp->inp_faddr.s_addr = INADDR_ANY;
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.
1520 in_pcbdetach(struct inpcb *inp)
1523 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1526 if (inp->inp_snd_tag != NULL)
1527 in_pcbdetach_txrtlmt(inp);
1529 inp->inp_socket->so_pcb = NULL;
1530 inp->inp_socket = NULL;
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
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
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().
1553 in_pcbref(struct inpcb *inp)
1556 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1558 refcount_acquire(&inp->inp_refcount);
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.
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).
1574 in_pcbrele_rlocked(struct inpcb *inp)
1576 struct inpcbinfo *pcbinfo;
1578 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1580 INP_RLOCK_ASSERT(inp);
1582 if (refcount_release(&inp->inp_refcount) == 0) {
1584 * If the inpcb has been freed, let the caller know, even if
1585 * this isn't the last reference.
1587 if (inp->inp_flags2 & INP_FREED) {
1594 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1596 if (inp->inp_in_hpts || inp->inp_in_input) {
1597 struct tcp_hpts_entry *hpts;
1599 * We should not be on the hpts at
1600 * this point in any form. we must
1601 * get the lock to be sure.
1603 hpts = tcp_hpts_lock(inp);
1604 if (inp->inp_in_hpts)
1605 panic("Hpts:%p inp:%p at free still on hpts",
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",
1612 mtx_unlock(&hpts->p_mtx);
1616 pcbinfo = inp->inp_pcbinfo;
1617 uma_zfree(pcbinfo->ipi_zone, inp);
1622 in_pcbrele_wlocked(struct inpcb *inp)
1624 struct inpcbinfo *pcbinfo;
1626 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1628 INP_WLOCK_ASSERT(inp);
1630 if (refcount_release(&inp->inp_refcount) == 0) {
1632 * If the inpcb has been freed, let the caller know, even if
1633 * this isn't the last reference.
1635 if (inp->inp_flags2 & INP_FREED) {
1642 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1644 if (inp->inp_in_hpts || inp->inp_in_input) {
1645 struct tcp_hpts_entry *hpts;
1647 * We should not be on the hpts at
1648 * this point in any form. we must
1649 * get the lock to be sure.
1651 hpts = tcp_hpts_lock(inp);
1652 if (inp->inp_in_hpts)
1653 panic("Hpts:%p inp:%p at free still on hpts",
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",
1660 mtx_unlock(&hpts->p_mtx);
1664 pcbinfo = inp->inp_pcbinfo;
1665 uma_zfree(pcbinfo->ipi_zone, inp);
1670 * Temporary wrapper.
1673 in_pcbrele(struct inpcb *inp)
1676 return (in_pcbrele_wlocked(inp));
1680 in_pcblist_rele_rlocked(epoch_context_t ctx)
1682 struct in_pcblist *il;
1684 struct inpcbinfo *pcbinfo;
1687 il = __containerof(ctx, struct in_pcblist, il_epoch_ctx);
1688 pcbinfo = il->il_pcbinfo;
1690 INP_INFO_WLOCK(pcbinfo);
1691 for (i = 0; i < n; i++) {
1692 inp = il->il_inp_list[i];
1694 if (!in_pcbrele_rlocked(inp))
1697 INP_INFO_WUNLOCK(pcbinfo);
1702 inpcbport_free(epoch_context_t ctx)
1704 struct inpcbport *phd;
1706 phd = __containerof(ctx, struct inpcbport, phd_epoch_ctx);
1711 in_pcbfree_deferred(epoch_context_t ctx)
1714 int released __unused;
1716 inp = __containerof(ctx, struct inpcb, inp_epoch_ctx);
1719 CURVNET_SET(inp->inp_vnet);
1721 struct ip_moptions *imo = inp->inp_moptions;
1722 inp->inp_moptions = NULL;
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);
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;
1737 if (inp->inp_options)
1738 (void)m_free(inp->inp_options);
1740 crfree(inp->inp_cred);
1742 mac_inpcb_destroy(inp);
1744 released = in_pcbrele_wlocked(inp);
1747 ip6_freemoptions(im6o);
1750 inp_freemoptions(imo);
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.
1765 in_pcbfree(struct inpcb *inp)
1767 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
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) {
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;
1785 NET_EPOCH_CALL(in_pcbfree_deferred, &inp->inp_epoch_ctx);
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.
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
1799 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1800 * in_pcbnotifyall() and in_pcbpurgeif0()?
1803 in_pcbdrop(struct inpcb *inp)
1806 INP_WLOCK_ASSERT(inp);
1808 if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1809 MPASS(inp->inp_refcount > 1);
1813 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1816 inp->inp_flags |= INP_DROPPED;
1817 if (inp->inp_flags & INP_INHASHLIST) {
1818 struct inpcbport *phd = inp->inp_phd;
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);
1828 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1829 inp->inp_flags &= ~INP_INHASHLIST;
1831 in_pcbgroup_remove(inp);
1838 * Common routines to return the socket addresses associated with inpcbs.
1841 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1843 struct sockaddr_in *sin;
1845 sin = malloc(sizeof *sin, M_SONAME,
1847 sin->sin_family = AF_INET;
1848 sin->sin_len = sizeof(*sin);
1849 sin->sin_addr = *addr_p;
1850 sin->sin_port = port;
1852 return (struct sockaddr *)sin;
1856 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1859 struct in_addr addr;
1862 inp = sotoinpcb(so);
1863 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1866 port = inp->inp_lport;
1867 addr = inp->inp_laddr;
1870 *nam = in_sockaddr(port, &addr);
1875 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1878 struct in_addr addr;
1881 inp = sotoinpcb(so);
1882 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1885 port = inp->inp_fport;
1886 addr = inp->inp_faddr;
1889 *nam = in_sockaddr(port, &addr);
1894 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1895 struct inpcb *(*notify)(struct inpcb *, int))
1897 struct inpcb *inp, *inp_temp;
1899 INP_INFO_WLOCK(pcbinfo);
1900 CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1903 if ((inp->inp_vflag & INP_IPV4) == 0) {
1908 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1909 inp->inp_socket == NULL) {
1913 if ((*notify)(inp, errno))
1916 INP_INFO_WUNLOCK(pcbinfo);
1920 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1923 struct in_multi *inm;
1924 struct in_mfilter *imf;
1925 struct ip_moptions *imo;
1927 INP_INFO_WLOCK(pcbinfo);
1928 CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1930 imo = inp->inp_moptions;
1931 if ((inp->inp_vflag & INP_IPV4) &&
1934 * Unselect the outgoing interface if it is being
1937 if (imo->imo_multicast_ifp == ifp)
1938 imo->imo_multicast_ifp = NULL;
1941 * Drop multicast group membership if we joined
1942 * through the interface being detached.
1944 * XXX This can all be deferred to an epoch_call
1947 IP_MFILTER_FOREACH(imf, &imo->imo_head) {
1948 if ((inm = imf->imf_inm) == NULL)
1950 if (inm->inm_ifp != ifp)
1952 ip_mfilter_remove(&imo->imo_head, imf);
1953 IN_MULTI_LOCK_ASSERT();
1954 in_leavegroup_locked(inm, NULL);
1955 ip_mfilter_free(imf);
1961 INP_INFO_WUNLOCK(pcbinfo);
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.
1968 #define INP_LOOKUP_MAPPED_PCB_COST 3
1970 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1971 u_short lport, int lookupflags, struct ucred *cred)
1975 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1981 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1982 ("%s: invalid lookup flags %d", __func__, lookupflags));
1984 INP_HASH_LOCK_ASSERT(pcbinfo);
1986 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1987 struct inpcbhead *head;
1989 * Look for an unconnected (wildcard foreign addr) PCB that
1990 * matches the local address and port we're looking for.
1992 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1993 0, pcbinfo->ipi_hashmask)];
1994 CK_LIST_FOREACH(inp, head, inp_hash) {
1996 /* XXX inp locking */
1997 if ((inp->inp_vflag & INP_IPV4) == 0)
2000 if (inp->inp_faddr.s_addr == INADDR_ANY &&
2001 inp->inp_laddr.s_addr == laddr.s_addr &&
2002 inp->inp_lport == lport) {
2006 if (prison_equal_ip4(cred->cr_prison,
2007 inp->inp_cred->cr_prison))
2016 struct inpcbporthead *porthash;
2017 struct inpcbport *phd;
2018 struct inpcb *match = NULL;
2020 * Best fit PCB lookup.
2022 * First see if this local port is in use by looking on the
2025 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2026 pcbinfo->ipi_porthashmask)];
2027 CK_LIST_FOREACH(phd, porthash, phd_hash) {
2028 if (phd->phd_port == lport)
2033 * Port is in use by one or more PCBs. Look for best
2036 CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2038 if (!prison_equal_ip4(inp->inp_cred->cr_prison,
2042 /* XXX inp locking */
2043 if ((inp->inp_vflag & INP_IPV4) == 0)
2046 * We never select the PCB that has
2047 * INP_IPV6 flag and is bound to :: if
2048 * we have another PCB which is bound
2049 * to 0.0.0.0. If a PCB has the
2050 * INP_IPV6 flag, then we set its cost
2051 * higher than IPv4 only PCBs.
2053 * Note that the case only happens
2054 * when a socket is bound to ::, under
2055 * the condition that the use of the
2056 * mapped address is allowed.
2058 if ((inp->inp_vflag & INP_IPV6) != 0)
2059 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2061 if (inp->inp_faddr.s_addr != INADDR_ANY)
2063 if (inp->inp_laddr.s_addr != INADDR_ANY) {
2064 if (laddr.s_addr == INADDR_ANY)
2066 else if (inp->inp_laddr.s_addr != laddr.s_addr)
2069 if (laddr.s_addr != INADDR_ANY)
2072 if (wildcard < matchwild) {
2074 matchwild = wildcard;
2083 #undef INP_LOOKUP_MAPPED_PCB_COST
2086 in_pcblookup_lb_numa_match(const struct inpcblbgroup *grp, int domain)
2088 return (domain == M_NODOM || domain == grp->il_numa_domain);
2091 static struct inpcb *
2092 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
2093 const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
2094 uint16_t fport, int lookupflags, int domain)
2096 const struct inpcblbgrouphead *hdr;
2097 struct inpcblbgroup *grp;
2098 struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
2100 INP_HASH_LOCK_ASSERT(pcbinfo);
2102 hdr = &pcbinfo->ipi_lbgrouphashbase[
2103 INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
2106 * Search for an LB group match based on the following criteria:
2107 * - prefer jailed groups to non-jailed groups
2108 * - prefer exact source address matches to wildcard matches
2109 * - prefer groups bound to the specified NUMA domain
2111 jail_exact = jail_wild = local_exact = local_wild = NULL;
2112 CK_LIST_FOREACH(grp, hdr, il_list) {
2116 if (!(grp->il_vflag & INP_IPV4))
2119 if (grp->il_lport != lport)
2122 injail = prison_flag(grp->il_cred, PR_IP4) != 0;
2123 if (injail && prison_check_ip4_locked(grp->il_cred->cr_prison,
2127 if (grp->il_laddr.s_addr == laddr->s_addr) {
2130 if (in_pcblookup_lb_numa_match(grp, domain))
2131 /* This is a perfect match. */
2133 } else if (local_exact == NULL ||
2134 in_pcblookup_lb_numa_match(grp, domain)) {
2137 } else if (grp->il_laddr.s_addr == INADDR_ANY &&
2138 (lookupflags & INPLOOKUP_WILDCARD) != 0) {
2140 if (jail_wild == NULL ||
2141 in_pcblookup_lb_numa_match(grp, domain))
2143 } else if (local_wild == NULL ||
2144 in_pcblookup_lb_numa_match(grp, domain)) {
2150 if (jail_exact != NULL)
2152 else if (jail_wild != NULL)
2154 else if (local_exact != NULL)
2161 return (grp->il_inp[INP_PCBLBGROUP_PKTHASH(faddr->s_addr, lport, fport) %
2167 * Lookup PCB in hash list, using pcbgroup tables.
2169 static struct inpcb *
2170 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
2171 struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
2172 u_int lport_arg, int lookupflags, struct ifnet *ifp)
2174 struct inpcbhead *head;
2175 struct inpcb *inp, *tmpinp;
2176 u_short fport = fport_arg, lport = lport_arg;
2180 * First look for an exact match.
2183 INP_GROUP_LOCK(pcbgroup);
2184 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2185 pcbgroup->ipg_hashmask)];
2186 CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2188 /* XXX inp locking */
2189 if ((inp->inp_vflag & INP_IPV4) == 0)
2192 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2193 inp->inp_laddr.s_addr == laddr.s_addr &&
2194 inp->inp_fport == fport &&
2195 inp->inp_lport == lport) {
2197 * XXX We should be able to directly return
2198 * the inp here, without any checks.
2199 * Well unless both bound with SO_REUSEPORT?
2201 if (prison_flag(inp->inp_cred, PR_IP4))
2207 if (tmpinp != NULL) {
2214 * For incoming connections, we may wish to do a wildcard
2215 * match for an RSS-local socket.
2217 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2218 struct inpcb *local_wild = NULL, *local_exact = NULL;
2220 struct inpcb *local_wild_mapped = NULL;
2222 struct inpcb *jail_wild = NULL;
2223 struct inpcbhead *head;
2227 * Order of socket selection - we always prefer jails.
2228 * 1. jailed, non-wild.
2230 * 3. non-jailed, non-wild.
2231 * 4. non-jailed, wild.
2234 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
2235 lport, 0, pcbgroup->ipg_hashmask)];
2236 CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2238 /* XXX inp locking */
2239 if ((inp->inp_vflag & INP_IPV4) == 0)
2242 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2243 inp->inp_lport != lport)
2246 injail = prison_flag(inp->inp_cred, PR_IP4);
2248 if (prison_check_ip4(inp->inp_cred,
2252 if (local_exact != NULL)
2256 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2261 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2263 /* XXX inp locking, NULL check */
2264 if (inp->inp_vflag & INP_IPV6PROTO)
2265 local_wild_mapped = inp;
2273 } /* LIST_FOREACH */
2282 inp = local_wild_mapped;
2290 * Then look for a wildcard match, if requested.
2292 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2293 struct inpcb *local_wild = NULL, *local_exact = NULL;
2295 struct inpcb *local_wild_mapped = NULL;
2297 struct inpcb *jail_wild = NULL;
2298 struct inpcbhead *head;
2302 * Order of socket selection - we always prefer jails.
2303 * 1. jailed, non-wild.
2305 * 3. non-jailed, non-wild.
2306 * 4. non-jailed, wild.
2308 head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
2309 0, pcbinfo->ipi_wildmask)];
2310 CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
2312 /* XXX inp locking */
2313 if ((inp->inp_vflag & INP_IPV4) == 0)
2316 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2317 inp->inp_lport != lport)
2320 injail = prison_flag(inp->inp_cred, PR_IP4);
2322 if (prison_check_ip4(inp->inp_cred,
2326 if (local_exact != NULL)
2330 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2335 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2337 /* XXX inp locking, NULL check */
2338 if (inp->inp_vflag & INP_IPV6PROTO)
2339 local_wild_mapped = inp;
2347 } /* LIST_FOREACH */
2355 inp = local_wild_mapped;
2359 } /* if (lookupflags & INPLOOKUP_WILDCARD) */
2360 INP_GROUP_UNLOCK(pcbgroup);
2364 if (lookupflags & INPLOOKUP_WLOCKPCB)
2365 locked = INP_TRY_WLOCK(inp);
2366 else if (lookupflags & INPLOOKUP_RLOCKPCB)
2367 locked = INP_TRY_RLOCK(inp);
2369 panic("%s: locking bug", __func__);
2370 if (__predict_false(locked && (inp->inp_flags2 & INP_FREED))) {
2371 if (lookupflags & INPLOOKUP_WLOCKPCB)
2378 INP_GROUP_UNLOCK(pcbgroup);
2380 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2382 if (in_pcbrele_wlocked(inp))
2386 if (in_pcbrele_rlocked(inp))
2391 if (lookupflags & INPLOOKUP_WLOCKPCB)
2392 INP_WLOCK_ASSERT(inp);
2394 INP_RLOCK_ASSERT(inp);
2398 #endif /* PCBGROUP */
2401 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
2402 * that the caller has locked the hash list, and will not perform any further
2403 * locking or reference operations on either the hash list or the connection.
2405 static struct inpcb *
2406 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2407 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2408 struct ifnet *ifp, uint8_t numa_domain)
2410 struct inpcbhead *head;
2411 struct inpcb *inp, *tmpinp;
2412 u_short fport = fport_arg, lport = lport_arg;
2414 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2415 ("%s: invalid lookup flags %d", __func__, lookupflags));
2416 INP_HASH_LOCK_ASSERT(pcbinfo);
2419 * First look for an exact match.
2422 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2423 pcbinfo->ipi_hashmask)];
2424 CK_LIST_FOREACH(inp, head, inp_hash) {
2426 /* XXX inp locking */
2427 if ((inp->inp_vflag & INP_IPV4) == 0)
2430 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2431 inp->inp_laddr.s_addr == laddr.s_addr &&
2432 inp->inp_fport == fport &&
2433 inp->inp_lport == lport) {
2435 * XXX We should be able to directly return
2436 * the inp here, without any checks.
2437 * Well unless both bound with SO_REUSEPORT?
2439 if (prison_flag(inp->inp_cred, PR_IP4))
2449 * Then look for a wildcard match, if requested.
2451 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2452 struct inpcb *local_wild = NULL, *local_exact = NULL;
2454 struct inpcb *local_wild_mapped = NULL;
2456 struct inpcb *jail_wild = NULL;
2460 * First see if an LB group matches the request before scanning
2461 * all sockets on this port.
2463 inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2464 fport, lookupflags, numa_domain);
2469 * Order of socket selection - we always prefer jails.
2470 * 1. jailed, non-wild.
2472 * 3. non-jailed, non-wild.
2473 * 4. non-jailed, wild.
2476 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2477 0, pcbinfo->ipi_hashmask)];
2478 CK_LIST_FOREACH(inp, head, inp_hash) {
2480 /* XXX inp locking */
2481 if ((inp->inp_vflag & INP_IPV4) == 0)
2484 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2485 inp->inp_lport != lport)
2488 injail = prison_flag(inp->inp_cred, PR_IP4);
2490 if (prison_check_ip4(inp->inp_cred,
2494 if (local_exact != NULL)
2498 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2503 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2505 /* XXX inp locking, NULL check */
2506 if (inp->inp_vflag & INP_IPV6PROTO)
2507 local_wild_mapped = inp;
2515 } /* LIST_FOREACH */
2516 if (jail_wild != NULL)
2518 if (local_exact != NULL)
2519 return (local_exact);
2520 if (local_wild != NULL)
2521 return (local_wild);
2523 if (local_wild_mapped != NULL)
2524 return (local_wild_mapped);
2526 } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2532 * Lookup PCB in hash list, using pcbinfo tables. This variation locks the
2533 * hash list lock, and will return the inpcb locked (i.e., requires
2534 * INPLOOKUP_LOCKPCB).
2536 static struct inpcb *
2537 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2538 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2539 struct ifnet *ifp, uint8_t numa_domain)
2543 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2544 (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp,
2547 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2549 if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2553 } else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2555 if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2560 panic("%s: locking bug", __func__);
2563 if (lookupflags & INPLOOKUP_WLOCKPCB)
2564 INP_WLOCK_ASSERT(inp);
2566 INP_RLOCK_ASSERT(inp);
2575 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2576 * from which a pre-calculated hash value may be extracted.
2578 * Possibly more of this logic should be in in_pcbgroup.c.
2581 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2582 struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2584 #if defined(PCBGROUP) && !defined(RSS)
2585 struct inpcbgroup *pcbgroup;
2588 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2589 ("%s: invalid lookup flags %d", __func__, lookupflags));
2590 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2591 ("%s: LOCKPCB not set", __func__));
2594 * When not using RSS, use connection groups in preference to the
2595 * reservation table when looking up 4-tuples. When using RSS, just
2596 * use the reservation table, due to the cost of the Toeplitz hash
2599 * XXXRW: This policy belongs in the pcbgroup code, as in principle
2600 * we could be doing RSS with a non-Toeplitz hash that is affordable
2603 #if defined(PCBGROUP) && !defined(RSS)
2604 if (in_pcbgroup_enabled(pcbinfo)) {
2605 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2607 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2608 laddr, lport, lookupflags, ifp));
2611 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2612 lookupflags, ifp, M_NODOM));
2616 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2617 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2618 struct ifnet *ifp, struct mbuf *m)
2621 struct inpcbgroup *pcbgroup;
2624 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2625 ("%s: invalid lookup flags %d", __func__, lookupflags));
2626 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2627 ("%s: LOCKPCB not set", __func__));
2631 * If we can use a hardware-generated hash to look up the connection
2632 * group, use that connection group to find the inpcb. Otherwise
2633 * fall back on a software hash -- or the reservation table if we're
2636 * XXXRW: As above, that policy belongs in the pcbgroup code.
2638 if (in_pcbgroup_enabled(pcbinfo) &&
2639 !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2640 pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2641 m->m_pkthdr.flowid);
2642 if (pcbgroup != NULL)
2643 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2644 fport, laddr, lport, lookupflags, ifp));
2646 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2648 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2649 laddr, lport, lookupflags, ifp));
2653 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2654 lookupflags, ifp, m->m_pkthdr.numa_domain));
2659 * Insert PCB onto various hash lists.
2662 in_pcbinshash_internal(struct inpcb *inp, struct mbuf *m)
2664 struct inpcbhead *pcbhash;
2665 struct inpcbporthead *pcbporthash;
2666 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2667 struct inpcbport *phd;
2668 u_int32_t hashkey_faddr;
2670 INP_WLOCK_ASSERT(inp);
2671 INP_HASH_WLOCK_ASSERT(pcbinfo);
2673 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2674 ("in_pcbinshash: INP_INHASHLIST"));
2677 if (inp->inp_vflag & INP_IPV6)
2678 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2681 hashkey_faddr = inp->inp_faddr.s_addr;
2683 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2684 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2686 pcbporthash = &pcbinfo->ipi_porthashbase[
2687 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2690 * Add entry to load balance group.
2691 * Only do this if SO_REUSEPORT_LB is set.
2693 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0) {
2694 int error = in_pcbinslbgrouphash(inp, M_NODOM);
2700 * Go through port list and look for a head for this lport.
2702 CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2703 if (phd->phd_port == inp->inp_lport)
2708 * If none exists, malloc one and tack it on.
2711 phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2713 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2714 in_pcbremlbgrouphash(inp);
2717 bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2718 phd->phd_port = inp->inp_lport;
2719 CK_LIST_INIT(&phd->phd_pcblist);
2720 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2723 CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2724 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2725 inp->inp_flags |= INP_INHASHLIST;
2728 in_pcbgroup_update_mbuf(inp, m);
2730 in_pcbgroup_update(inp);
2737 in_pcbinshash(struct inpcb *inp)
2740 return (in_pcbinshash_internal(inp, NULL));
2744 in_pcbinshash_mbuf(struct inpcb *inp, struct mbuf *m)
2747 return (in_pcbinshash_internal(inp, m));
2751 * Move PCB to the proper hash bucket when { faddr, fport } have been
2752 * changed. NOTE: This does not handle the case of the lport changing (the
2753 * hashed port list would have to be updated as well), so the lport must
2754 * not change after in_pcbinshash() has been called.
2757 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2759 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2760 struct inpcbhead *head;
2761 u_int32_t hashkey_faddr;
2763 INP_WLOCK_ASSERT(inp);
2764 INP_HASH_WLOCK_ASSERT(pcbinfo);
2766 KASSERT(inp->inp_flags & INP_INHASHLIST,
2767 ("in_pcbrehash: !INP_INHASHLIST"));
2770 if (inp->inp_vflag & INP_IPV6)
2771 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2774 hashkey_faddr = inp->inp_faddr.s_addr;
2776 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2777 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2779 CK_LIST_REMOVE(inp, inp_hash);
2780 CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2784 in_pcbgroup_update_mbuf(inp, m);
2786 in_pcbgroup_update(inp);
2791 in_pcbrehash(struct inpcb *inp)
2794 in_pcbrehash_mbuf(inp, NULL);
2798 * Remove PCB from various lists.
2801 in_pcbremlists(struct inpcb *inp)
2803 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2805 INP_WLOCK_ASSERT(inp);
2806 INP_LIST_WLOCK_ASSERT(pcbinfo);
2808 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2809 if (inp->inp_flags & INP_INHASHLIST) {
2810 struct inpcbport *phd = inp->inp_phd;
2812 INP_HASH_WLOCK(pcbinfo);
2814 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2815 in_pcbremlbgrouphash(inp);
2817 CK_LIST_REMOVE(inp, inp_hash);
2818 CK_LIST_REMOVE(inp, inp_portlist);
2819 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2820 CK_LIST_REMOVE(phd, phd_hash);
2821 NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
2823 INP_HASH_WUNLOCK(pcbinfo);
2824 inp->inp_flags &= ~INP_INHASHLIST;
2826 CK_LIST_REMOVE(inp, inp_list);
2827 pcbinfo->ipi_count--;
2829 in_pcbgroup_remove(inp);
2834 * Check for alternatives when higher level complains
2835 * about service problems. For now, invalidate cached
2836 * routing information. If the route was created dynamically
2837 * (by a redirect), time to try a default gateway again.
2840 in_losing(struct inpcb *inp)
2843 RO_INVALIDATE_CACHE(&inp->inp_route);
2848 * A set label operation has occurred at the socket layer, propagate the
2849 * label change into the in_pcb for the socket.
2852 in_pcbsosetlabel(struct socket *so)
2857 inp = sotoinpcb(so);
2858 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2862 mac_inpcb_sosetlabel(so, inp);
2869 * ipport_tick runs once per second, determining if random port allocation
2870 * should be continued. If more than ipport_randomcps ports have been
2871 * allocated in the last second, then we return to sequential port
2872 * allocation. We return to random allocation only once we drop below
2873 * ipport_randomcps for at least ipport_randomtime seconds.
2876 ipport_tick(void *xtp)
2878 VNET_ITERATOR_DECL(vnet_iter);
2880 VNET_LIST_RLOCK_NOSLEEP();
2881 VNET_FOREACH(vnet_iter) {
2882 CURVNET_SET(vnet_iter); /* XXX appease INVARIANTS here */
2883 if (V_ipport_tcpallocs <=
2884 V_ipport_tcplastcount + V_ipport_randomcps) {
2885 if (V_ipport_stoprandom > 0)
2886 V_ipport_stoprandom--;
2888 V_ipport_stoprandom = V_ipport_randomtime;
2889 V_ipport_tcplastcount = V_ipport_tcpallocs;
2892 VNET_LIST_RUNLOCK_NOSLEEP();
2893 callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2900 callout_stop(&ipport_tick_callout);
2904 * The ipport_callout should start running at about the time we attach the
2905 * inet or inet6 domains.
2908 ipport_tick_init(const void *unused __unused)
2911 /* Start ipport_tick. */
2912 callout_init(&ipport_tick_callout, 1);
2913 callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2914 EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2915 SHUTDOWN_PRI_DEFAULT);
2917 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2918 ipport_tick_init, NULL);
2921 inp_wlock(struct inpcb *inp)
2928 inp_wunlock(struct inpcb *inp)
2935 inp_rlock(struct inpcb *inp)
2942 inp_runlock(struct inpcb *inp)
2948 #ifdef INVARIANT_SUPPORT
2950 inp_lock_assert(struct inpcb *inp)
2953 INP_WLOCK_ASSERT(inp);
2957 inp_unlock_assert(struct inpcb *inp)
2960 INP_UNLOCK_ASSERT(inp);
2965 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2969 INP_INFO_WLOCK(&V_tcbinfo);
2970 CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2975 INP_INFO_WUNLOCK(&V_tcbinfo);
2979 inp_inpcbtosocket(struct inpcb *inp)
2982 INP_WLOCK_ASSERT(inp);
2983 return (inp->inp_socket);
2987 inp_inpcbtotcpcb(struct inpcb *inp)
2990 INP_WLOCK_ASSERT(inp);
2991 return ((struct tcpcb *)inp->inp_ppcb);
2995 inp_ip_tos_get(const struct inpcb *inp)
2998 return (inp->inp_ip_tos);
3002 inp_ip_tos_set(struct inpcb *inp, int val)
3005 inp->inp_ip_tos = val;
3009 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
3010 uint32_t *faddr, uint16_t *fp)
3013 INP_LOCK_ASSERT(inp);
3014 *laddr = inp->inp_laddr.s_addr;
3015 *faddr = inp->inp_faddr.s_addr;
3016 *lp = inp->inp_lport;
3017 *fp = inp->inp_fport;
3021 so_sotoinpcb(struct socket *so)
3024 return (sotoinpcb(so));
3028 so_sototcpcb(struct socket *so)
3031 return (sototcpcb(so));
3035 * Create an external-format (``xinpcb'') structure using the information in
3036 * the kernel-format in_pcb structure pointed to by inp. This is done to
3037 * reduce the spew of irrelevant information over this interface, to isolate
3038 * user code from changes in the kernel structure, and potentially to provide
3039 * information-hiding if we decide that some of this information should be
3040 * hidden from users.
3043 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
3046 bzero(xi, sizeof(*xi));
3047 xi->xi_len = sizeof(struct xinpcb);
3048 if (inp->inp_socket)
3049 sotoxsocket(inp->inp_socket, &xi->xi_socket);
3050 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
3051 xi->inp_gencnt = inp->inp_gencnt;
3052 xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
3053 xi->inp_flow = inp->inp_flow;
3054 xi->inp_flowid = inp->inp_flowid;
3055 xi->inp_flowtype = inp->inp_flowtype;
3056 xi->inp_flags = inp->inp_flags;
3057 xi->inp_flags2 = inp->inp_flags2;
3058 xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
3059 xi->in6p_cksum = inp->in6p_cksum;
3060 xi->in6p_hops = inp->in6p_hops;
3061 xi->inp_ip_tos = inp->inp_ip_tos;
3062 xi->inp_vflag = inp->inp_vflag;
3063 xi->inp_ip_ttl = inp->inp_ip_ttl;
3064 xi->inp_ip_p = inp->inp_ip_p;
3065 xi->inp_ip_minttl = inp->inp_ip_minttl;
3070 db_print_indent(int indent)
3074 for (i = 0; i < indent; i++)
3079 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3081 char faddr_str[48], laddr_str[48];
3083 db_print_indent(indent);
3084 db_printf("%s at %p\n", name, inc);
3089 if (inc->inc_flags & INC_ISIPV6) {
3091 ip6_sprintf(laddr_str, &inc->inc6_laddr);
3092 ip6_sprintf(faddr_str, &inc->inc6_faddr);
3097 inet_ntoa_r(inc->inc_laddr, laddr_str);
3098 inet_ntoa_r(inc->inc_faddr, faddr_str);
3100 db_print_indent(indent);
3101 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
3102 ntohs(inc->inc_lport));
3103 db_print_indent(indent);
3104 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
3105 ntohs(inc->inc_fport));
3109 db_print_inpflags(int inp_flags)
3114 if (inp_flags & INP_RECVOPTS) {
3115 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3118 if (inp_flags & INP_RECVRETOPTS) {
3119 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3122 if (inp_flags & INP_RECVDSTADDR) {
3123 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3126 if (inp_flags & INP_ORIGDSTADDR) {
3127 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3130 if (inp_flags & INP_HDRINCL) {
3131 db_printf("%sINP_HDRINCL", comma ? ", " : "");
3134 if (inp_flags & INP_HIGHPORT) {
3135 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3138 if (inp_flags & INP_LOWPORT) {
3139 db_printf("%sINP_LOWPORT", comma ? ", " : "");
3142 if (inp_flags & INP_ANONPORT) {
3143 db_printf("%sINP_ANONPORT", comma ? ", " : "");
3146 if (inp_flags & INP_RECVIF) {
3147 db_printf("%sINP_RECVIF", comma ? ", " : "");
3150 if (inp_flags & INP_MTUDISC) {
3151 db_printf("%sINP_MTUDISC", comma ? ", " : "");
3154 if (inp_flags & INP_RECVTTL) {
3155 db_printf("%sINP_RECVTTL", comma ? ", " : "");
3158 if (inp_flags & INP_DONTFRAG) {
3159 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3162 if (inp_flags & INP_RECVTOS) {
3163 db_printf("%sINP_RECVTOS", comma ? ", " : "");
3166 if (inp_flags & IN6P_IPV6_V6ONLY) {
3167 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3170 if (inp_flags & IN6P_PKTINFO) {
3171 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3174 if (inp_flags & IN6P_HOPLIMIT) {
3175 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3178 if (inp_flags & IN6P_HOPOPTS) {
3179 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3182 if (inp_flags & IN6P_DSTOPTS) {
3183 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3186 if (inp_flags & IN6P_RTHDR) {
3187 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3190 if (inp_flags & IN6P_RTHDRDSTOPTS) {
3191 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3194 if (inp_flags & IN6P_TCLASS) {
3195 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3198 if (inp_flags & IN6P_AUTOFLOWLABEL) {
3199 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3202 if (inp_flags & INP_TIMEWAIT) {
3203 db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3206 if (inp_flags & INP_ONESBCAST) {
3207 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3210 if (inp_flags & INP_DROPPED) {
3211 db_printf("%sINP_DROPPED", comma ? ", " : "");
3214 if (inp_flags & INP_SOCKREF) {
3215 db_printf("%sINP_SOCKREF", comma ? ", " : "");
3218 if (inp_flags & IN6P_RFC2292) {
3219 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3222 if (inp_flags & IN6P_MTU) {
3223 db_printf("IN6P_MTU%s", comma ? ", " : "");
3229 db_print_inpvflag(u_char inp_vflag)
3234 if (inp_vflag & INP_IPV4) {
3235 db_printf("%sINP_IPV4", comma ? ", " : "");
3238 if (inp_vflag & INP_IPV6) {
3239 db_printf("%sINP_IPV6", comma ? ", " : "");
3242 if (inp_vflag & INP_IPV6PROTO) {
3243 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3249 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3252 db_print_indent(indent);
3253 db_printf("%s at %p\n", name, inp);
3257 db_print_indent(indent);
3258 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3260 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3262 db_print_indent(indent);
3263 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
3264 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3266 db_print_indent(indent);
3267 db_printf("inp_label: %p inp_flags: 0x%x (",
3268 inp->inp_label, inp->inp_flags);
3269 db_print_inpflags(inp->inp_flags);
3272 db_print_indent(indent);
3273 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
3275 db_print_inpvflag(inp->inp_vflag);
3278 db_print_indent(indent);
3279 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
3280 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3282 db_print_indent(indent);
3284 if (inp->inp_vflag & INP_IPV6) {
3285 db_printf("in6p_options: %p in6p_outputopts: %p "
3286 "in6p_moptions: %p\n", inp->in6p_options,
3287 inp->in6p_outputopts, inp->in6p_moptions);
3288 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
3289 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3294 db_printf("inp_ip_tos: %d inp_ip_options: %p "
3295 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3296 inp->inp_options, inp->inp_moptions);
3299 db_print_indent(indent);
3300 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
3301 (uintmax_t)inp->inp_gencnt);
3304 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3309 db_printf("usage: show inpcb <addr>\n");
3312 inp = (struct inpcb *)addr;
3314 db_print_inpcb(inp, "inpcb", 0);
3320 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3324 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3326 union if_snd_tag_modify_params params = {
3327 .rate_limit.max_rate = max_pacing_rate,
3328 .rate_limit.flags = M_NOWAIT,
3330 struct m_snd_tag *mst;
3334 mst = inp->inp_snd_tag;
3342 if (ifp->if_snd_tag_modify == NULL) {
3345 error = ifp->if_snd_tag_modify(mst, ¶ms);
3351 * Query existing TX rate limit based on the existing
3352 * "inp->inp_snd_tag", if any.
3355 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3357 union if_snd_tag_query_params params = { };
3358 struct m_snd_tag *mst;
3362 mst = inp->inp_snd_tag;
3370 if (ifp->if_snd_tag_query == NULL) {
3373 error = ifp->if_snd_tag_query(mst, ¶ms);
3374 if (error == 0 && p_max_pacing_rate != NULL)
3375 *p_max_pacing_rate = params.rate_limit.max_rate;
3381 * Query existing TX queue level based on the existing
3382 * "inp->inp_snd_tag", if any.
3385 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3387 union if_snd_tag_query_params params = { };
3388 struct m_snd_tag *mst;
3392 mst = inp->inp_snd_tag;
3400 if (ifp->if_snd_tag_query == NULL)
3401 return (EOPNOTSUPP);
3403 error = ifp->if_snd_tag_query(mst, ¶ms);
3404 if (error == 0 && p_txqueue_level != NULL)
3405 *p_txqueue_level = params.rate_limit.queue_level;
3410 * Allocate a new TX rate limit send tag from the network interface
3411 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3414 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3415 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
3418 union if_snd_tag_alloc_params params = {
3419 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3420 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3421 .rate_limit.hdr.flowid = flowid,
3422 .rate_limit.hdr.flowtype = flowtype,
3423 .rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3424 .rate_limit.max_rate = max_pacing_rate,
3425 .rate_limit.flags = M_NOWAIT,
3429 INP_WLOCK_ASSERT(inp);
3432 * If there is already a send tag, or the INP is being torn
3433 * down, allocating a new send tag is not allowed. Else send
3436 if (*st != NULL || (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0)
3439 error = m_snd_tag_alloc(ifp, ¶ms, st);
3442 counter_u64_add(rate_limit_set_ok, 1);
3443 counter_u64_add(rate_limit_active, 1);
3444 } else if (error != EOPNOTSUPP)
3445 counter_u64_add(rate_limit_alloc_fail, 1);
3451 in_pcbdetach_tag(struct m_snd_tag *mst)
3454 m_snd_tag_rele(mst);
3456 counter_u64_add(rate_limit_active, -1);
3461 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3465 in_pcbdetach_txrtlmt(struct inpcb *inp)
3467 struct m_snd_tag *mst;
3469 INP_WLOCK_ASSERT(inp);
3471 mst = inp->inp_snd_tag;
3472 inp->inp_snd_tag = NULL;
3477 m_snd_tag_rele(mst);
3479 counter_u64_add(rate_limit_active, -1);
3484 in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
3489 * If the existing send tag is for the wrong interface due to
3490 * a route change, first drop the existing tag. Set the
3491 * CHANGED flag so that we will keep trying to allocate a new
3492 * tag if we fail to allocate one this time.
3494 if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
3495 in_pcbdetach_txrtlmt(inp);
3496 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3500 * NOTE: When attaching to a network interface a reference is
3501 * made to ensure the network interface doesn't go away until
3502 * all ratelimit connections are gone. The network interface
3503 * pointers compared below represent valid network interfaces,
3504 * except when comparing towards NULL.
3506 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3508 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3509 if (inp->inp_snd_tag != NULL)
3510 in_pcbdetach_txrtlmt(inp);
3512 } else if (inp->inp_snd_tag == NULL) {
3514 * In order to utilize packet pacing with RSS, we need
3515 * to wait until there is a valid RSS hash before we
3518 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3521 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3522 mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
3525 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3527 if (error == 0 || error == EOPNOTSUPP)
3528 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3534 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3535 * is set in the fast path and will attach/detach/modify the TX rate
3536 * limit send tag based on the socket's so_max_pacing_rate value.
3539 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3541 struct socket *socket;
3542 uint32_t max_pacing_rate;
3549 socket = inp->inp_socket;
3553 if (!INP_WLOCKED(inp)) {
3555 * NOTE: If the write locking fails, we need to bail
3556 * out and use the non-ratelimited ring for the
3557 * transmit until there is a new chance to get the
3560 if (!INP_TRY_UPGRADE(inp))
3568 * NOTE: The so_max_pacing_rate value is read unlocked,
3569 * because atomic updates are not required since the variable
3570 * is checked at every mbuf we send. It is assumed that the
3571 * variable read itself will be atomic.
3573 max_pacing_rate = socket->so_max_pacing_rate;
3575 error = in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3582 * Track route changes for TX rate limiting.
3585 in_pcboutput_eagain(struct inpcb *inp)
3592 if (inp->inp_snd_tag == NULL)
3595 if (!INP_WLOCKED(inp)) {
3597 * NOTE: If the write locking fails, we need to bail
3598 * out and use the non-ratelimited ring for the
3599 * transmit until there is a new chance to get the
3602 if (!INP_TRY_UPGRADE(inp))
3609 /* detach rate limiting */
3610 in_pcbdetach_txrtlmt(inp);
3612 /* make sure new mbuf send tag allocation is made */
3613 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3623 rate_limit_new = counter_u64_alloc(M_WAITOK);
3624 rate_limit_chg = counter_u64_alloc(M_WAITOK);
3625 rate_limit_active = counter_u64_alloc(M_WAITOK);
3626 rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
3627 rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
3630 SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3632 #endif /* RATELIMIT */