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>
41 __FBSDID("$FreeBSD$");
44 #include "opt_ipsec.h"
46 #include "opt_inet6.h"
47 #include "opt_ratelimit.h"
48 #include "opt_pcbgroup.h"
49 #include "opt_route.h"
52 #include <sys/param.h>
53 #include <sys/systm.h>
55 #include <sys/malloc.h>
57 #include <sys/callout.h>
58 #include <sys/eventhandler.h>
59 #include <sys/domain.h>
60 #include <sys/protosw.h>
61 #include <sys/rmlock.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
65 #include <sys/sockio.h>
68 #include <sys/refcount.h>
70 #include <sys/kernel.h>
71 #include <sys/sysctl.h>
81 #include <net/if_var.h>
82 #include <net/if_types.h>
83 #include <net/if_llatbl.h>
84 #include <net/route.h>
85 #include <net/rss_config.h>
88 #if defined(INET) || defined(INET6)
89 #include <netinet/in.h>
90 #include <netinet/in_pcb.h>
92 #include <netinet/in_var.h>
93 #include <netinet/in_fib.h>
95 #include <netinet/ip_var.h>
96 #include <netinet/tcp_var.h>
98 #include <netinet/tcp_hpts.h>
100 #include <netinet/udp.h>
101 #include <netinet/udp_var.h>
103 #include <netinet/ip6.h>
104 #include <netinet6/in6_pcb.h>
105 #include <netinet6/in6_var.h>
106 #include <netinet6/ip6_var.h>
108 #include <net/route/nhop.h>
111 #include <netipsec/ipsec_support.h>
113 #include <security/mac/mac_framework.h>
115 #define INPCBLBGROUP_SIZMIN 8
116 #define INPCBLBGROUP_SIZMAX 256
118 static struct callout ipport_tick_callout;
121 * These configure the range of local port addresses assigned to
122 * "unspecified" outgoing connections/packets/whatever.
124 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1; /* 1023 */
125 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART; /* 600 */
126 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST; /* 10000 */
127 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST; /* 65535 */
128 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO; /* 49152 */
129 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO; /* 65535 */
132 * Reserved ports accessible only to root. There are significant
133 * security considerations that must be accounted for when changing these,
134 * but the security benefits can be great. Please be careful.
136 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1; /* 1023 */
137 VNET_DEFINE(int, ipport_reservedlow);
139 /* Variables dealing with random ephemeral port allocation. */
140 VNET_DEFINE(int, ipport_randomized) = 1; /* user controlled via sysctl */
141 VNET_DEFINE(int, ipport_randomcps) = 10; /* user controlled via sysctl */
142 VNET_DEFINE(int, ipport_randomtime) = 45; /* user controlled via sysctl */
143 VNET_DEFINE(int, ipport_stoprandom); /* toggled by ipport_tick */
144 VNET_DEFINE(int, ipport_tcpallocs);
145 VNET_DEFINE_STATIC(int, ipport_tcplastcount);
147 #define V_ipport_tcplastcount VNET(ipport_tcplastcount)
149 static void in_pcbremlists(struct inpcb *inp);
151 static struct inpcb *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
152 struct in_addr faddr, u_int fport_arg,
153 struct in_addr laddr, u_int lport_arg,
154 int lookupflags, struct ifnet *ifp,
155 uint8_t numa_domain);
157 #define RANGECHK(var, min, max) \
158 if ((var) < (min)) { (var) = (min); } \
159 else if ((var) > (max)) { (var) = (max); }
162 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
166 error = sysctl_handle_int(oidp, arg1, arg2, req);
168 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
169 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
170 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
171 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
172 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
173 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
180 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
181 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
184 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
185 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
186 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
188 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
189 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
190 &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
192 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
193 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
194 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
196 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
197 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
198 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
200 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
201 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
202 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
204 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
205 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
206 &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
208 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
209 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
210 &VNET_NAME(ipport_reservedhigh), 0, "");
211 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
212 CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
213 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
214 CTLFLAG_VNET | CTLFLAG_RW,
215 &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
216 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
217 CTLFLAG_VNET | CTLFLAG_RW,
218 &VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
219 "allocations before switching to a sequential one");
220 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
221 CTLFLAG_VNET | CTLFLAG_RW,
222 &VNET_NAME(ipport_randomtime), 0,
223 "Minimum time to keep sequential port "
224 "allocation before switching to a random one");
227 counter_u64_t rate_limit_new;
228 counter_u64_t rate_limit_chg;
229 counter_u64_t rate_limit_active;
230 counter_u64_t rate_limit_alloc_fail;
231 counter_u64_t rate_limit_set_ok;
233 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
235 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
236 &rate_limit_active, "Active rate limited connections");
237 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
238 &rate_limit_alloc_fail, "Rate limited connection failures");
239 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
240 &rate_limit_set_ok, "Rate limited setting succeeded");
241 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
242 &rate_limit_new, "Total Rate limit new attempts");
243 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
244 &rate_limit_chg, "Total Rate limited change attempts");
246 #endif /* RATELIMIT */
251 * in_pcb.c: manage the Protocol Control Blocks.
253 * NOTE: It is assumed that most of these functions will be called with
254 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
255 * functions often modify hash chains or addresses in pcbs.
258 static struct inpcblbgroup *
259 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, u_char vflag,
260 uint16_t port, const union in_dependaddr *addr, int size,
263 struct inpcblbgroup *grp;
266 bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
267 grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
270 grp->il_vflag = vflag;
271 grp->il_lport = port;
272 grp->il_numa_domain = numa_domain;
273 grp->il_dependladdr = *addr;
274 grp->il_inpsiz = size;
275 CK_LIST_INSERT_HEAD(hdr, grp, il_list);
280 in_pcblbgroup_free_deferred(epoch_context_t ctx)
282 struct inpcblbgroup *grp;
284 grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
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_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);
363 * Don't allow jailed socket to join local group.
365 if (inp->inp_socket != NULL && jailed(inp->inp_socket->so_cred))
370 * Don't allow IPv4 mapped INET6 wild socket.
372 if ((inp->inp_vflag & INP_IPV4) &&
373 inp->inp_laddr.s_addr == INADDR_ANY &&
374 INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
379 idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
380 hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
381 CK_LIST_FOREACH(grp, hdr, il_list) {
382 if (grp->il_vflag == inp->inp_vflag &&
383 grp->il_lport == inp->inp_lport &&
384 grp->il_numa_domain == numa_domain &&
385 memcmp(&grp->il_dependladdr,
386 &inp->inp_inc.inc_ie.ie_dependladdr,
387 sizeof(grp->il_dependladdr)) == 0)
391 /* Create new load balance group. */
392 grp = in_pcblbgroup_alloc(hdr, inp->inp_vflag,
393 inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
394 INPCBLBGROUP_SIZMIN, numa_domain);
397 } else if (grp->il_inpcnt == grp->il_inpsiz) {
398 if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
399 if (ratecheck(&lastprint, &interval))
400 printf("lb group port %d, limit reached\n",
401 ntohs(grp->il_lport));
405 /* Expand this local group. */
406 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
411 KASSERT(grp->il_inpcnt < grp->il_inpsiz,
412 ("invalid local group size %d and count %d", grp->il_inpsiz,
415 grp->il_inp[grp->il_inpcnt] = inp;
421 * Remove PCB from load balance group.
424 in_pcbremlbgrouphash(struct inpcb *inp)
426 struct inpcbinfo *pcbinfo;
427 struct inpcblbgrouphead *hdr;
428 struct inpcblbgroup *grp;
431 pcbinfo = inp->inp_pcbinfo;
433 INP_WLOCK_ASSERT(inp);
434 INP_HASH_WLOCK_ASSERT(pcbinfo);
436 hdr = &pcbinfo->ipi_lbgrouphashbase[
437 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
438 CK_LIST_FOREACH(grp, hdr, il_list) {
439 for (i = 0; i < grp->il_inpcnt; ++i) {
440 if (grp->il_inp[i] != inp)
443 if (grp->il_inpcnt == 1) {
444 /* We are the last, free this local group. */
445 in_pcblbgroup_free(grp);
447 /* Pull up inpcbs, shrink group if possible. */
448 in_pcblbgroup_reorder(hdr, &grp, i);
456 in_pcblbgroup_numa(struct inpcb *inp, int arg)
458 struct inpcbinfo *pcbinfo;
459 struct inpcblbgrouphead *hdr;
460 struct inpcblbgroup *grp;
465 case TCP_REUSPORT_LB_NUMA_NODOM:
466 numa_domain = M_NODOM;
468 case TCP_REUSPORT_LB_NUMA_CURDOM:
469 numa_domain = PCPU_GET(domain);
472 if (arg < 0 || arg >= vm_ndomains)
478 pcbinfo = inp->inp_pcbinfo;
479 INP_WLOCK_ASSERT(inp);
480 INP_HASH_WLOCK(pcbinfo);
481 hdr = &pcbinfo->ipi_lbgrouphashbase[
482 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
483 CK_LIST_FOREACH(grp, hdr, il_list) {
484 for (i = 0; i < grp->il_inpcnt; ++i) {
485 if (grp->il_inp[i] != inp)
488 if (grp->il_numa_domain == numa_domain) {
489 goto abort_with_hash_wlock;
492 /* Remove it from the old group. */
493 in_pcbremlbgrouphash(inp);
495 /* Add it to the new group based on numa domain. */
496 in_pcbinslbgrouphash(inp, numa_domain);
497 goto abort_with_hash_wlock;
501 abort_with_hash_wlock:
502 INP_HASH_WUNLOCK(pcbinfo);
507 * Different protocols initialize their inpcbs differently - giving
508 * different name to the lock. But they all are disposed the same.
511 inpcb_fini(void *mem, int size)
513 struct inpcb *inp = mem;
515 INP_LOCK_DESTROY(inp);
519 * Initialize an inpcbinfo -- we should be able to reduce the number of
523 in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
524 struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
525 char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
528 porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
530 INP_INFO_LOCK_INIT(pcbinfo, name);
531 INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash"); /* XXXRW: argument? */
532 INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
534 pcbinfo->ipi_vnet = curvnet;
536 pcbinfo->ipi_listhead = listhead;
537 CK_LIST_INIT(pcbinfo->ipi_listhead);
538 pcbinfo->ipi_count = 0;
539 pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
540 &pcbinfo->ipi_hashmask);
541 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
542 &pcbinfo->ipi_porthashmask);
543 pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
544 &pcbinfo->ipi_lbgrouphashmask);
546 in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
548 pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
549 NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
550 uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
551 uma_zone_set_warning(pcbinfo->ipi_zone,
552 "kern.ipc.maxsockets limit reached");
556 * Destroy an inpcbinfo.
559 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
562 KASSERT(pcbinfo->ipi_count == 0,
563 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
565 hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
566 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
567 pcbinfo->ipi_porthashmask);
568 hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
569 pcbinfo->ipi_lbgrouphashmask);
571 in_pcbgroup_destroy(pcbinfo);
573 uma_zdestroy(pcbinfo->ipi_zone);
574 INP_LIST_LOCK_DESTROY(pcbinfo);
575 INP_HASH_LOCK_DESTROY(pcbinfo);
576 INP_INFO_LOCK_DESTROY(pcbinfo);
580 * Allocate a PCB and associate it with the socket.
581 * On success return with the PCB locked.
584 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
590 inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
593 bzero(&inp->inp_start_zero, inp_zero_size);
595 inp->inp_numa_domain = M_NODOM;
597 inp->inp_pcbinfo = pcbinfo;
598 inp->inp_socket = so;
599 inp->inp_cred = crhold(so->so_cred);
600 inp->inp_inc.inc_fibnum = so->so_fibnum;
602 error = mac_inpcb_init(inp, M_NOWAIT);
605 mac_inpcb_create(so, inp);
607 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
608 error = ipsec_init_pcbpolicy(inp);
611 mac_inpcb_destroy(inp);
617 if (INP_SOCKAF(so) == AF_INET6) {
618 inp->inp_vflag |= INP_IPV6PROTO;
620 inp->inp_flags |= IN6P_IPV6_V6ONLY;
624 INP_LIST_WLOCK(pcbinfo);
625 CK_LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
626 pcbinfo->ipi_count++;
627 so->so_pcb = (caddr_t)inp;
629 if (V_ip6_auto_flowlabel)
630 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
632 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
633 refcount_init(&inp->inp_refcount, 1); /* Reference from inpcbinfo */
636 * Routes in inpcb's can cache L2 as well; they are guaranteed
639 inp->inp_route.ro_flags = RT_LLE_CACHE;
640 INP_LIST_WUNLOCK(pcbinfo);
641 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
644 crfree(inp->inp_cred);
645 uma_zfree(pcbinfo->ipi_zone, inp);
653 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
657 KASSERT(nam == NULL || nam->sa_family == AF_INET,
658 ("%s: invalid address family for %p", __func__, nam));
659 KASSERT(nam == NULL || nam->sa_len == sizeof(struct sockaddr_in),
660 ("%s: invalid address length for %p", __func__, nam));
661 INP_WLOCK_ASSERT(inp);
662 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
664 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
666 anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
667 error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
668 &inp->inp_lport, cred);
671 if (in_pcbinshash(inp) != 0) {
672 inp->inp_laddr.s_addr = INADDR_ANY;
677 inp->inp_flags |= INP_ANONPORT;
682 #if defined(INET) || defined(INET6)
684 * Assign a local port like in_pcb_lport(), but also used with connect()
685 * and a foreign address and port. If fsa is non-NULL, choose a local port
686 * that is unused with those, otherwise one that is completely unused.
687 * lsa can be NULL for IPv6.
690 in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
691 struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
693 struct inpcbinfo *pcbinfo;
694 struct inpcb *tmpinp;
695 unsigned short *lastport;
696 int count, dorandom, error;
697 u_short aux, first, last, lport;
699 struct in_addr laddr, faddr;
702 struct in6_addr *laddr6, *faddr6;
705 pcbinfo = inp->inp_pcbinfo;
708 * Because no actual state changes occur here, a global write lock on
709 * the pcbinfo isn't required.
711 INP_LOCK_ASSERT(inp);
712 INP_HASH_LOCK_ASSERT(pcbinfo);
714 if (inp->inp_flags & INP_HIGHPORT) {
715 first = V_ipport_hifirstauto; /* sysctl */
716 last = V_ipport_hilastauto;
717 lastport = &pcbinfo->ipi_lasthi;
718 } else if (inp->inp_flags & INP_LOWPORT) {
719 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
722 first = V_ipport_lowfirstauto; /* 1023 */
723 last = V_ipport_lowlastauto; /* 600 */
724 lastport = &pcbinfo->ipi_lastlow;
726 first = V_ipport_firstauto; /* sysctl */
727 last = V_ipport_lastauto;
728 lastport = &pcbinfo->ipi_lastport;
731 * For UDP(-Lite), use random port allocation as long as the user
732 * allows it. For TCP (and as of yet unknown) connections,
733 * use random port allocation only if the user allows it AND
734 * ipport_tick() allows it.
736 if (V_ipport_randomized &&
737 (!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
738 pcbinfo == &V_ulitecbinfo))
743 * It makes no sense to do random port allocation if
744 * we have the only port available.
748 /* Make sure to not include UDP(-Lite) packets in the count. */
749 if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
750 V_ipport_tcpallocs++;
752 * Instead of having two loops further down counting up or down
753 * make sure that first is always <= last and go with only one
754 * code path implementing all logic.
763 laddr.s_addr = INADDR_ANY;
764 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
766 laddr = ((struct sockaddr_in *)lsa)->sin_addr;
768 faddr = ((struct sockaddr_in *)fsa)->sin_addr;
773 if ((inp->inp_vflag & INP_IPV6) != 0) {
775 laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
777 faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
785 *lastport = first + (arc4random() % (last - first));
787 count = last - first;
790 if (count-- < 0) /* completely used? */
791 return (EADDRNOTAVAIL);
793 if (*lastport < first || *lastport > last)
795 lport = htons(*lastport);
799 if (lsa->sa_family == AF_INET) {
800 tmpinp = in_pcblookup_hash_locked(pcbinfo,
801 faddr, fport, laddr, lport, lookupflags,
806 if (lsa->sa_family == AF_INET6) {
807 tmpinp = in6_pcblookup_hash_locked(pcbinfo,
808 faddr6, fport, laddr6, lport, lookupflags,
814 if ((inp->inp_vflag & INP_IPV6) != 0)
815 tmpinp = in6_pcblookup_local(pcbinfo,
816 &inp->in6p_laddr, lport, lookupflags, cred);
818 #if defined(INET) && defined(INET6)
822 tmpinp = in_pcblookup_local(pcbinfo, laddr,
823 lport, lookupflags, cred);
826 } while (tmpinp != NULL);
834 * Select a local port (number) to use.
837 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
838 struct ucred *cred, int lookupflags)
840 struct sockaddr_in laddr;
843 bzero(&laddr, sizeof(laddr));
844 laddr.sin_family = AF_INET;
845 laddr.sin_addr = *laddrp;
847 return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
848 NULL, lportp, NULL, 0, cred, lookupflags));
852 * Return cached socket options.
855 inp_so_options(const struct inpcb *inp)
861 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
862 so_options |= SO_REUSEPORT_LB;
863 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
864 so_options |= SO_REUSEPORT;
865 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
866 so_options |= SO_REUSEADDR;
869 #endif /* INET || INET6 */
872 * Check if a new BINDMULTI socket is allowed to be created.
874 * ni points to the new inp.
875 * oi points to the existing inp.
877 * This checks whether the existing inp also has BINDMULTI and
878 * whether the credentials match.
881 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
883 /* Check permissions match */
884 if ((ni->inp_flags2 & INP_BINDMULTI) &&
885 (ni->inp_cred->cr_uid !=
886 oi->inp_cred->cr_uid))
889 /* Check the existing inp has BINDMULTI set */
890 if ((ni->inp_flags2 & INP_BINDMULTI) &&
891 ((oi->inp_flags2 & INP_BINDMULTI) == 0))
895 * We're okay - either INP_BINDMULTI isn't set on ni, or
896 * it is and it matches the checks.
903 * Set up a bind operation on a PCB, performing port allocation
904 * as required, but do not actually modify the PCB. Callers can
905 * either complete the bind by setting inp_laddr/inp_lport and
906 * calling in_pcbinshash(), or they can just use the resulting
907 * port and address to authorise the sending of a once-off packet.
909 * On error, the values of *laddrp and *lportp are not changed.
912 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
913 u_short *lportp, struct ucred *cred)
915 struct socket *so = inp->inp_socket;
916 struct sockaddr_in *sin;
917 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
918 struct in_addr laddr;
920 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
924 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
925 * so that we don't have to add to the (already messy) code below.
927 int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
930 * No state changes, so read locks are sufficient here.
932 INP_LOCK_ASSERT(inp);
933 INP_HASH_LOCK_ASSERT(pcbinfo);
935 laddr.s_addr = *laddrp;
936 if (nam != NULL && laddr.s_addr != INADDR_ANY)
938 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
939 lookupflags = INPLOOKUP_WILDCARD;
941 if ((error = prison_local_ip4(cred, &laddr)) != 0)
944 sin = (struct sockaddr_in *)nam;
945 KASSERT(sin->sin_family == AF_INET,
946 ("%s: invalid family for address %p", __func__, sin));
947 KASSERT(sin->sin_len == sizeof(*sin),
948 ("%s: invalid length for address %p", __func__, sin));
950 error = prison_local_ip4(cred, &sin->sin_addr);
953 if (sin->sin_port != *lportp) {
954 /* Don't allow the port to change. */
957 lport = sin->sin_port;
959 /* NB: lport is left as 0 if the port isn't being changed. */
960 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
962 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
963 * allow complete duplication of binding if
964 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
965 * and a multicast address is bound on both
966 * new and duplicated sockets.
968 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
969 reuseport = SO_REUSEADDR|SO_REUSEPORT;
971 * XXX: How to deal with SO_REUSEPORT_LB here?
972 * Treat same as SO_REUSEPORT for now.
974 if ((so->so_options &
975 (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
976 reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
977 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
978 sin->sin_port = 0; /* yech... */
979 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
981 * Is the address a local IP address?
982 * If INP_BINDANY is set, then the socket may be bound
983 * to any endpoint address, local or not.
985 if ((inp->inp_flags & INP_BINDANY) == 0 &&
986 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
987 return (EADDRNOTAVAIL);
989 laddr = sin->sin_addr;
995 if (ntohs(lport) <= V_ipport_reservedhigh &&
996 ntohs(lport) >= V_ipport_reservedlow &&
997 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
999 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
1000 priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
1001 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1002 lport, INPLOOKUP_WILDCARD, cred);
1005 * This entire block sorely needs a rewrite.
1008 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1009 ((t->inp_flags & INP_TIMEWAIT) == 0) &&
1010 (so->so_type != SOCK_STREAM ||
1011 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
1012 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
1013 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
1014 (t->inp_flags2 & INP_REUSEPORT) ||
1015 (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
1016 (inp->inp_cred->cr_uid !=
1017 t->inp_cred->cr_uid))
1018 return (EADDRINUSE);
1021 * If the socket is a BINDMULTI socket, then
1022 * the credentials need to match and the
1023 * original socket also has to have been bound
1026 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1027 return (EADDRINUSE);
1029 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1030 lport, lookupflags, cred);
1031 if (t && (t->inp_flags & INP_TIMEWAIT)) {
1033 * XXXRW: If an incpb has had its timewait
1034 * state recycled, we treat the address as
1035 * being in use (for now). This is better
1036 * than a panic, but not desirable.
1040 ((reuseport & tw->tw_so_options) == 0 &&
1042 tw->tw_so_options) == 0)) {
1043 return (EADDRINUSE);
1046 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1047 (reuseport & inp_so_options(t)) == 0 &&
1048 (reuseport_lb & inp_so_options(t)) == 0) {
1050 if (ntohl(sin->sin_addr.s_addr) !=
1052 ntohl(t->inp_laddr.s_addr) !=
1054 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1055 (t->inp_vflag & INP_IPV6PROTO) == 0)
1057 return (EADDRINUSE);
1058 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1059 return (EADDRINUSE);
1066 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1070 *laddrp = laddr.s_addr;
1076 * Connect from a socket to a specified address.
1077 * Both address and port must be specified in argument sin.
1078 * If don't have a local address for this socket yet,
1082 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
1083 struct ucred *cred, struct mbuf *m, bool rehash)
1085 u_short lport, fport;
1086 in_addr_t laddr, faddr;
1087 int anonport, error;
1089 INP_WLOCK_ASSERT(inp);
1090 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1092 lport = inp->inp_lport;
1093 laddr = inp->inp_laddr.s_addr;
1094 anonport = (lport == 0);
1095 error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
1100 /* Do the initial binding of the local address if required. */
1101 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1102 KASSERT(rehash == true,
1103 ("Rehashing required for unbound inps"));
1104 inp->inp_lport = lport;
1105 inp->inp_laddr.s_addr = laddr;
1106 if (in_pcbinshash(inp) != 0) {
1107 inp->inp_laddr.s_addr = INADDR_ANY;
1113 /* Commit the remaining changes. */
1114 inp->inp_lport = lport;
1115 inp->inp_laddr.s_addr = laddr;
1116 inp->inp_faddr.s_addr = faddr;
1117 inp->inp_fport = fport;
1119 in_pcbrehash_mbuf(inp, m);
1121 in_pcbinshash_mbuf(inp, m);
1125 inp->inp_flags |= INP_ANONPORT;
1130 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1133 return (in_pcbconnect_mbuf(inp, nam, cred, NULL, true));
1137 * Do proper source address selection on an unbound socket in case
1138 * of connect. Take jails into account as well.
1141 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1145 struct sockaddr *sa;
1146 struct sockaddr_in *sin, dst;
1147 struct nhop_object *nh;
1151 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1153 * Bypass source address selection and use the primary jail IP
1156 if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1162 bzero(&dst, sizeof(dst));
1164 sin->sin_family = AF_INET;
1165 sin->sin_len = sizeof(struct sockaddr_in);
1166 sin->sin_addr.s_addr = faddr->s_addr;
1169 * If route is known our src addr is taken from the i/f,
1172 * Find out route to destination.
1174 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1175 nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
1179 * If we found a route, use the address corresponding to
1180 * the outgoing interface.
1182 * Otherwise assume faddr is reachable on a directly connected
1183 * network and try to find a corresponding interface to take
1184 * the source address from.
1186 if (nh == NULL || nh->nh_ifp == NULL) {
1187 struct in_ifaddr *ia;
1190 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1191 inp->inp_socket->so_fibnum));
1193 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1194 inp->inp_socket->so_fibnum));
1197 error = ENETUNREACH;
1201 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1202 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1208 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1210 if (sa->sa_family != AF_INET)
1212 sin = (struct sockaddr_in *)sa;
1213 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1214 ia = (struct in_ifaddr *)ifa;
1219 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1223 /* 3. As a last resort return the 'default' jail address. */
1224 error = prison_get_ip4(cred, laddr);
1229 * If the outgoing interface on the route found is not
1230 * a loopback interface, use the address from that interface.
1231 * In case of jails do those three steps:
1232 * 1. check if the interface address belongs to the jail. If so use it.
1233 * 2. check if we have any address on the outgoing interface
1234 * belonging to this jail. If so use it.
1235 * 3. as a last resort return the 'default' jail address.
1237 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
1238 struct in_ifaddr *ia;
1241 /* If not jailed, use the default returned. */
1242 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1243 ia = (struct in_ifaddr *)nh->nh_ifa;
1244 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1249 /* 1. Check if the iface address belongs to the jail. */
1250 sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1251 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1252 ia = (struct in_ifaddr *)nh->nh_ifa;
1253 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1258 * 2. Check if we have any address on the outgoing interface
1259 * belonging to this jail.
1263 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1265 if (sa->sa_family != AF_INET)
1267 sin = (struct sockaddr_in *)sa;
1268 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1269 ia = (struct in_ifaddr *)ifa;
1274 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1278 /* 3. As a last resort return the 'default' jail address. */
1279 error = prison_get_ip4(cred, laddr);
1284 * The outgoing interface is marked with 'loopback net', so a route
1285 * to ourselves is here.
1286 * Try to find the interface of the destination address and then
1287 * take the address from there. That interface is not necessarily
1288 * a loopback interface.
1289 * In case of jails, check that it is an address of the jail
1290 * and if we cannot find, fall back to the 'default' jail address.
1292 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
1293 struct in_ifaddr *ia;
1295 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
1296 inp->inp_socket->so_fibnum));
1298 ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
1299 inp->inp_socket->so_fibnum));
1301 ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
1303 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1305 error = ENETUNREACH;
1308 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1318 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1320 if (sa->sa_family != AF_INET)
1322 sin = (struct sockaddr_in *)sa;
1323 if (prison_check_ip4(cred,
1324 &sin->sin_addr) == 0) {
1325 ia = (struct in_ifaddr *)ifa;
1330 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1335 /* 3. As a last resort return the 'default' jail address. */
1336 error = prison_get_ip4(cred, laddr);
1345 * Set up for a connect from a socket to the specified address.
1346 * On entry, *laddrp and *lportp should contain the current local
1347 * address and port for the PCB; these are updated to the values
1348 * that should be placed in inp_laddr and inp_lport to complete
1351 * On success, *faddrp and *fportp will be set to the remote address
1352 * and port. These are not updated in the error case.
1354 * If the operation fails because the connection already exists,
1355 * *oinpp will be set to the PCB of that connection so that the
1356 * caller can decide to override it. In all other cases, *oinpp
1360 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1361 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1362 struct inpcb **oinpp, struct ucred *cred)
1364 struct rm_priotracker in_ifa_tracker;
1365 struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1366 struct in_ifaddr *ia;
1368 struct in_addr laddr, faddr;
1369 u_short lport, fport;
1372 KASSERT(sin->sin_family == AF_INET,
1373 ("%s: invalid address family for %p", __func__, sin));
1374 KASSERT(sin->sin_len == sizeof(*sin),
1375 ("%s: invalid address length for %p", __func__, sin));
1378 * Because a global state change doesn't actually occur here, a read
1379 * lock is sufficient.
1382 INP_LOCK_ASSERT(inp);
1383 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1387 if (sin->sin_port == 0)
1388 return (EADDRNOTAVAIL);
1389 laddr.s_addr = *laddrp;
1391 faddr = sin->sin_addr;
1392 fport = sin->sin_port;
1394 if (CALC_FLOWID_OUTBOUND) {
1395 uint32_t hash_val, hash_type;
1397 hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
1398 inp->inp_socket->so_proto->pr_protocol, &hash_type);
1400 inp->inp_flowid = hash_val;
1401 inp->inp_flowtype = hash_type;
1404 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1406 * If the destination address is INADDR_ANY,
1407 * use the primary local address.
1408 * If the supplied address is INADDR_BROADCAST,
1409 * and the primary interface supports broadcast,
1410 * choose the broadcast address for that interface.
1412 if (faddr.s_addr == INADDR_ANY) {
1413 IN_IFADDR_RLOCK(&in_ifa_tracker);
1415 IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1416 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1418 (error = prison_get_ip4(cred, &faddr)) != 0)
1420 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1421 IN_IFADDR_RLOCK(&in_ifa_tracker);
1422 if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1424 faddr = satosin(&CK_STAILQ_FIRST(
1425 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1426 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1429 if (laddr.s_addr == INADDR_ANY) {
1430 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1432 * If the destination address is multicast and an outgoing
1433 * interface has been set as a multicast option, prefer the
1434 * address of that interface as our source address.
1436 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1437 inp->inp_moptions != NULL) {
1438 struct ip_moptions *imo;
1441 imo = inp->inp_moptions;
1442 if (imo->imo_multicast_ifp != NULL) {
1443 ifp = imo->imo_multicast_ifp;
1444 IN_IFADDR_RLOCK(&in_ifa_tracker);
1445 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1446 if ((ia->ia_ifp == ifp) &&
1448 prison_check_ip4(cred,
1449 &ia->ia_addr.sin_addr) == 0))
1453 error = EADDRNOTAVAIL;
1455 laddr = ia->ia_addr.sin_addr;
1458 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1466 oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1467 fport, laddr, lport, 0, NULL, M_NODOM);
1471 return (EADDRINUSE);
1474 struct sockaddr_in lsin, fsin;
1476 bzero(&lsin, sizeof(lsin));
1477 bzero(&fsin, sizeof(fsin));
1478 lsin.sin_family = AF_INET;
1479 lsin.sin_addr = laddr;
1480 fsin.sin_family = AF_INET;
1481 fsin.sin_addr = faddr;
1482 error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
1483 &lport, (struct sockaddr *)& fsin, fport, cred,
1484 INPLOOKUP_WILDCARD);
1488 *laddrp = laddr.s_addr;
1490 *faddrp = faddr.s_addr;
1496 in_pcbdisconnect(struct inpcb *inp)
1499 INP_WLOCK_ASSERT(inp);
1500 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1502 inp->inp_laddr.s_addr = INADDR_ANY;
1503 inp->inp_faddr.s_addr = INADDR_ANY;
1510 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1511 * For most protocols, this will be invoked immediately prior to calling
1512 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1513 * socket, in which case in_pcbfree() is deferred.
1516 in_pcbdetach(struct inpcb *inp)
1519 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1522 if (inp->inp_snd_tag != NULL)
1523 in_pcbdetach_txrtlmt(inp);
1525 inp->inp_socket->so_pcb = NULL;
1526 inp->inp_socket = NULL;
1530 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1531 * stability of an inpcb pointer despite the inpcb lock being released. This
1532 * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1533 * but where the inpcb lock may already held, or when acquiring a reference
1536 * in_pcbref() should be used only to provide brief memory stability, and
1537 * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1538 * garbage collect the inpcb if it has been in_pcbfree()'d from another
1539 * context. Until in_pcbrele() has returned that the inpcb is still valid,
1540 * lock and rele are the *only* safe operations that may be performed on the
1543 * While the inpcb will not be freed, releasing the inpcb lock means that the
1544 * connection's state may change, so the caller should be careful to
1545 * revalidate any cached state on reacquiring the lock. Drop the reference
1546 * using in_pcbrele().
1549 in_pcbref(struct inpcb *inp)
1552 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1554 refcount_acquire(&inp->inp_refcount);
1558 * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1559 * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1560 * return a flag indicating whether or not the inpcb remains valid. If it is
1561 * valid, we return with the inpcb lock held.
1563 * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1564 * reference on an inpcb. Historically more work was done here (actually, in
1565 * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1566 * need for the pcbinfo lock in in_pcbrele(). Deferring the free is entirely
1567 * about memory stability (and continued use of the write lock).
1570 in_pcbrele_rlocked(struct inpcb *inp)
1572 struct inpcbinfo *pcbinfo;
1574 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1576 INP_RLOCK_ASSERT(inp);
1578 if (refcount_release(&inp->inp_refcount) == 0) {
1580 * If the inpcb has been freed, let the caller know, even if
1581 * this isn't the last reference.
1583 if (inp->inp_flags2 & INP_FREED) {
1590 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1592 if (inp->inp_in_hpts || inp->inp_in_input) {
1593 struct tcp_hpts_entry *hpts;
1595 * We should not be on the hpts at
1596 * this point in any form. we must
1597 * get the lock to be sure.
1599 hpts = tcp_hpts_lock(inp);
1600 if (inp->inp_in_hpts)
1601 panic("Hpts:%p inp:%p at free still on hpts",
1603 mtx_unlock(&hpts->p_mtx);
1604 hpts = tcp_input_lock(inp);
1605 if (inp->inp_in_input)
1606 panic("Hpts:%p inp:%p at free still on input hpts",
1608 mtx_unlock(&hpts->p_mtx);
1612 pcbinfo = inp->inp_pcbinfo;
1613 uma_zfree(pcbinfo->ipi_zone, inp);
1618 in_pcbrele_wlocked(struct inpcb *inp)
1620 struct inpcbinfo *pcbinfo;
1622 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1624 INP_WLOCK_ASSERT(inp);
1626 if (refcount_release(&inp->inp_refcount) == 0) {
1628 * If the inpcb has been freed, let the caller know, even if
1629 * this isn't the last reference.
1631 if (inp->inp_flags2 & INP_FREED) {
1638 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1640 if (inp->inp_in_hpts || inp->inp_in_input) {
1641 struct tcp_hpts_entry *hpts;
1643 * We should not be on the hpts at
1644 * this point in any form. we must
1645 * get the lock to be sure.
1647 hpts = tcp_hpts_lock(inp);
1648 if (inp->inp_in_hpts)
1649 panic("Hpts:%p inp:%p at free still on hpts",
1651 mtx_unlock(&hpts->p_mtx);
1652 hpts = tcp_input_lock(inp);
1653 if (inp->inp_in_input)
1654 panic("Hpts:%p inp:%p at free still on input hpts",
1656 mtx_unlock(&hpts->p_mtx);
1660 pcbinfo = inp->inp_pcbinfo;
1661 uma_zfree(pcbinfo->ipi_zone, inp);
1666 * Temporary wrapper.
1669 in_pcbrele(struct inpcb *inp)
1672 return (in_pcbrele_wlocked(inp));
1676 in_pcblist_rele_rlocked(epoch_context_t ctx)
1678 struct in_pcblist *il;
1680 struct inpcbinfo *pcbinfo;
1683 il = __containerof(ctx, struct in_pcblist, il_epoch_ctx);
1684 pcbinfo = il->il_pcbinfo;
1686 INP_INFO_WLOCK(pcbinfo);
1687 for (i = 0; i < n; i++) {
1688 inp = il->il_inp_list[i];
1690 if (!in_pcbrele_rlocked(inp))
1693 INP_INFO_WUNLOCK(pcbinfo);
1698 inpcbport_free(epoch_context_t ctx)
1700 struct inpcbport *phd;
1702 phd = __containerof(ctx, struct inpcbport, phd_epoch_ctx);
1707 in_pcbfree_deferred(epoch_context_t ctx)
1710 int released __unused;
1712 inp = __containerof(ctx, struct inpcb, inp_epoch_ctx);
1715 CURVNET_SET(inp->inp_vnet);
1717 struct ip_moptions *imo = inp->inp_moptions;
1718 inp->inp_moptions = NULL;
1720 /* XXXRW: Do as much as possible here. */
1721 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1722 if (inp->inp_sp != NULL)
1723 ipsec_delete_pcbpolicy(inp);
1726 struct ip6_moptions *im6o = NULL;
1727 if (inp->inp_vflag & INP_IPV6PROTO) {
1728 ip6_freepcbopts(inp->in6p_outputopts);
1729 im6o = inp->in6p_moptions;
1730 inp->in6p_moptions = NULL;
1733 if (inp->inp_options)
1734 (void)m_free(inp->inp_options);
1736 crfree(inp->inp_cred);
1738 mac_inpcb_destroy(inp);
1740 released = in_pcbrele_wlocked(inp);
1743 ip6_freemoptions(im6o);
1746 inp_freemoptions(imo);
1752 * Unconditionally schedule an inpcb to be freed by decrementing its
1753 * reference count, which should occur only after the inpcb has been detached
1754 * from its socket. If another thread holds a temporary reference (acquired
1755 * using in_pcbref()) then the free is deferred until that reference is
1756 * released using in_pcbrele(), but the inpcb is still unlocked. Almost all
1757 * work, including removal from global lists, is done in this context, where
1758 * the pcbinfo lock is held.
1761 in_pcbfree(struct inpcb *inp)
1763 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1765 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1766 KASSERT((inp->inp_flags2 & INP_FREED) == 0,
1767 ("%s: called twice for pcb %p", __func__, inp));
1768 if (inp->inp_flags2 & INP_FREED) {
1773 INP_WLOCK_ASSERT(inp);
1774 INP_LIST_WLOCK(pcbinfo);
1775 in_pcbremlists(inp);
1776 INP_LIST_WUNLOCK(pcbinfo);
1777 RO_INVALIDATE_CACHE(&inp->inp_route);
1778 /* mark as destruction in progress */
1779 inp->inp_flags2 |= INP_FREED;
1781 NET_EPOCH_CALL(in_pcbfree_deferred, &inp->inp_epoch_ctx);
1785 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1786 * port reservation, and preventing it from being returned by inpcb lookups.
1788 * It is used by TCP to mark an inpcb as unused and avoid future packet
1789 * delivery or event notification when a socket remains open but TCP has
1790 * closed. This might occur as a result of a shutdown()-initiated TCP close
1791 * or a RST on the wire, and allows the port binding to be reused while still
1792 * maintaining the invariant that so_pcb always points to a valid inpcb until
1795 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1796 * in_pcbnotifyall() and in_pcbpurgeif0()?
1799 in_pcbdrop(struct inpcb *inp)
1802 INP_WLOCK_ASSERT(inp);
1804 if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1805 MPASS(inp->inp_refcount > 1);
1809 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1812 inp->inp_flags |= INP_DROPPED;
1813 if (inp->inp_flags & INP_INHASHLIST) {
1814 struct inpcbport *phd = inp->inp_phd;
1816 INP_HASH_WLOCK(inp->inp_pcbinfo);
1817 in_pcbremlbgrouphash(inp);
1818 CK_LIST_REMOVE(inp, inp_hash);
1819 CK_LIST_REMOVE(inp, inp_portlist);
1820 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1821 CK_LIST_REMOVE(phd, phd_hash);
1822 NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
1824 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1825 inp->inp_flags &= ~INP_INHASHLIST;
1827 in_pcbgroup_remove(inp);
1834 * Common routines to return the socket addresses associated with inpcbs.
1837 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1839 struct sockaddr_in *sin;
1841 sin = malloc(sizeof *sin, M_SONAME,
1843 sin->sin_family = AF_INET;
1844 sin->sin_len = sizeof(*sin);
1845 sin->sin_addr = *addr_p;
1846 sin->sin_port = port;
1848 return (struct sockaddr *)sin;
1852 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1855 struct in_addr addr;
1858 inp = sotoinpcb(so);
1859 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1862 port = inp->inp_lport;
1863 addr = inp->inp_laddr;
1866 *nam = in_sockaddr(port, &addr);
1871 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1874 struct in_addr addr;
1877 inp = sotoinpcb(so);
1878 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1881 port = inp->inp_fport;
1882 addr = inp->inp_faddr;
1885 *nam = in_sockaddr(port, &addr);
1890 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1891 struct inpcb *(*notify)(struct inpcb *, int))
1893 struct inpcb *inp, *inp_temp;
1895 INP_INFO_WLOCK(pcbinfo);
1896 CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1899 if ((inp->inp_vflag & INP_IPV4) == 0) {
1904 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1905 inp->inp_socket == NULL) {
1909 if ((*notify)(inp, errno))
1912 INP_INFO_WUNLOCK(pcbinfo);
1916 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1919 struct in_multi *inm;
1920 struct in_mfilter *imf;
1921 struct ip_moptions *imo;
1923 INP_INFO_WLOCK(pcbinfo);
1924 CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1926 imo = inp->inp_moptions;
1927 if ((inp->inp_vflag & INP_IPV4) &&
1930 * Unselect the outgoing interface if it is being
1933 if (imo->imo_multicast_ifp == ifp)
1934 imo->imo_multicast_ifp = NULL;
1937 * Drop multicast group membership if we joined
1938 * through the interface being detached.
1940 * XXX This can all be deferred to an epoch_call
1943 IP_MFILTER_FOREACH(imf, &imo->imo_head) {
1944 if ((inm = imf->imf_inm) == NULL)
1946 if (inm->inm_ifp != ifp)
1948 ip_mfilter_remove(&imo->imo_head, imf);
1949 IN_MULTI_LOCK_ASSERT();
1950 in_leavegroup_locked(inm, NULL);
1951 ip_mfilter_free(imf);
1957 INP_INFO_WUNLOCK(pcbinfo);
1961 * Lookup a PCB based on the local address and port. Caller must hold the
1962 * hash lock. No inpcb locks or references are acquired.
1964 #define INP_LOOKUP_MAPPED_PCB_COST 3
1966 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1967 u_short lport, int lookupflags, struct ucred *cred)
1971 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1977 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1978 ("%s: invalid lookup flags %d", __func__, lookupflags));
1980 INP_HASH_LOCK_ASSERT(pcbinfo);
1982 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1983 struct inpcbhead *head;
1985 * Look for an unconnected (wildcard foreign addr) PCB that
1986 * matches the local address and port we're looking for.
1988 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1989 0, pcbinfo->ipi_hashmask)];
1990 CK_LIST_FOREACH(inp, head, inp_hash) {
1992 /* XXX inp locking */
1993 if ((inp->inp_vflag & INP_IPV4) == 0)
1996 if (inp->inp_faddr.s_addr == INADDR_ANY &&
1997 inp->inp_laddr.s_addr == laddr.s_addr &&
1998 inp->inp_lport == lport) {
2003 prison_equal_ip4(cred->cr_prison,
2004 inp->inp_cred->cr_prison))
2013 struct inpcbporthead *porthash;
2014 struct inpcbport *phd;
2015 struct inpcb *match = NULL;
2017 * Best fit PCB lookup.
2019 * First see if this local port is in use by looking on the
2022 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2023 pcbinfo->ipi_porthashmask)];
2024 CK_LIST_FOREACH(phd, porthash, phd_hash) {
2025 if (phd->phd_port == lport)
2030 * Port is in use by one or more PCBs. Look for best
2033 CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2036 !prison_equal_ip4(inp->inp_cred->cr_prison,
2040 /* XXX inp locking */
2041 if ((inp->inp_vflag & INP_IPV4) == 0)
2044 * We never select the PCB that has
2045 * INP_IPV6 flag and is bound to :: if
2046 * we have another PCB which is bound
2047 * to 0.0.0.0. If a PCB has the
2048 * INP_IPV6 flag, then we set its cost
2049 * higher than IPv4 only PCBs.
2051 * Note that the case only happens
2052 * when a socket is bound to ::, under
2053 * the condition that the use of the
2054 * mapped address is allowed.
2056 if ((inp->inp_vflag & INP_IPV6) != 0)
2057 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2059 if (inp->inp_faddr.s_addr != INADDR_ANY)
2061 if (inp->inp_laddr.s_addr != INADDR_ANY) {
2062 if (laddr.s_addr == INADDR_ANY)
2064 else if (inp->inp_laddr.s_addr != laddr.s_addr)
2067 if (laddr.s_addr != INADDR_ANY)
2070 if (wildcard < matchwild) {
2072 matchwild = wildcard;
2081 #undef INP_LOOKUP_MAPPED_PCB_COST
2083 static struct inpcb *
2084 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
2085 const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
2086 uint16_t fport, int lookupflags, int numa_domain)
2088 struct inpcb *local_wild, *numa_wild;
2089 const struct inpcblbgrouphead *hdr;
2090 struct inpcblbgroup *grp;
2093 INP_HASH_LOCK_ASSERT(pcbinfo);
2095 hdr = &pcbinfo->ipi_lbgrouphashbase[
2096 INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
2099 * Order of socket selection:
2101 * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
2104 * - Load balanced group does not contain jailed sockets
2105 * - Load balanced group does not contain IPv4 mapped INET6 wild sockets
2109 CK_LIST_FOREACH(grp, hdr, il_list) {
2111 if (!(grp->il_vflag & INP_IPV4))
2114 if (grp->il_lport != lport)
2117 idx = INP_PCBLBGROUP_PKTHASH(faddr->s_addr, lport, fport) %
2119 if (grp->il_laddr.s_addr == laddr->s_addr) {
2120 if (numa_domain == M_NODOM ||
2121 grp->il_numa_domain == numa_domain) {
2122 return (grp->il_inp[idx]);
2124 numa_wild = grp->il_inp[idx];
2127 if (grp->il_laddr.s_addr == INADDR_ANY &&
2128 (lookupflags & INPLOOKUP_WILDCARD) != 0 &&
2129 (local_wild == NULL || numa_domain == M_NODOM ||
2130 grp->il_numa_domain == numa_domain)) {
2131 local_wild = grp->il_inp[idx];
2134 if (numa_wild != NULL)
2137 return (local_wild);
2142 * Lookup PCB in hash list, using pcbgroup tables.
2144 static struct inpcb *
2145 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
2146 struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
2147 u_int lport_arg, int lookupflags, struct ifnet *ifp)
2149 struct inpcbhead *head;
2150 struct inpcb *inp, *tmpinp;
2151 u_short fport = fport_arg, lport = lport_arg;
2155 * First look for an exact match.
2158 INP_GROUP_LOCK(pcbgroup);
2159 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2160 pcbgroup->ipg_hashmask)];
2161 CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2163 /* XXX inp locking */
2164 if ((inp->inp_vflag & INP_IPV4) == 0)
2167 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2168 inp->inp_laddr.s_addr == laddr.s_addr &&
2169 inp->inp_fport == fport &&
2170 inp->inp_lport == lport) {
2172 * XXX We should be able to directly return
2173 * the inp here, without any checks.
2174 * Well unless both bound with SO_REUSEPORT?
2176 if (prison_flag(inp->inp_cred, PR_IP4))
2182 if (tmpinp != NULL) {
2189 * For incoming connections, we may wish to do a wildcard
2190 * match for an RSS-local socket.
2192 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2193 struct inpcb *local_wild = NULL, *local_exact = NULL;
2195 struct inpcb *local_wild_mapped = NULL;
2197 struct inpcb *jail_wild = NULL;
2198 struct inpcbhead *head;
2202 * Order of socket selection - we always prefer jails.
2203 * 1. jailed, non-wild.
2205 * 3. non-jailed, non-wild.
2206 * 4. non-jailed, wild.
2209 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
2210 lport, 0, pcbgroup->ipg_hashmask)];
2211 CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2213 /* XXX inp locking */
2214 if ((inp->inp_vflag & INP_IPV4) == 0)
2217 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2218 inp->inp_lport != lport)
2221 injail = prison_flag(inp->inp_cred, PR_IP4);
2223 if (prison_check_ip4(inp->inp_cred,
2227 if (local_exact != NULL)
2231 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2236 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2238 /* XXX inp locking, NULL check */
2239 if (inp->inp_vflag & INP_IPV6PROTO)
2240 local_wild_mapped = inp;
2248 } /* LIST_FOREACH */
2257 inp = local_wild_mapped;
2265 * Then look for a wildcard match, if requested.
2267 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2268 struct inpcb *local_wild = NULL, *local_exact = NULL;
2270 struct inpcb *local_wild_mapped = NULL;
2272 struct inpcb *jail_wild = NULL;
2273 struct inpcbhead *head;
2277 * Order of socket selection - we always prefer jails.
2278 * 1. jailed, non-wild.
2280 * 3. non-jailed, non-wild.
2281 * 4. non-jailed, wild.
2283 head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
2284 0, pcbinfo->ipi_wildmask)];
2285 CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
2287 /* XXX inp locking */
2288 if ((inp->inp_vflag & INP_IPV4) == 0)
2291 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2292 inp->inp_lport != lport)
2295 injail = prison_flag(inp->inp_cred, PR_IP4);
2297 if (prison_check_ip4(inp->inp_cred,
2301 if (local_exact != NULL)
2305 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2310 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2312 /* XXX inp locking, NULL check */
2313 if (inp->inp_vflag & INP_IPV6PROTO)
2314 local_wild_mapped = inp;
2322 } /* LIST_FOREACH */
2330 inp = local_wild_mapped;
2334 } /* if (lookupflags & INPLOOKUP_WILDCARD) */
2335 INP_GROUP_UNLOCK(pcbgroup);
2339 if (lookupflags & INPLOOKUP_WLOCKPCB)
2340 locked = INP_TRY_WLOCK(inp);
2341 else if (lookupflags & INPLOOKUP_RLOCKPCB)
2342 locked = INP_TRY_RLOCK(inp);
2344 panic("%s: locking bug", __func__);
2345 if (__predict_false(locked && (inp->inp_flags2 & INP_FREED))) {
2346 if (lookupflags & INPLOOKUP_WLOCKPCB)
2353 INP_GROUP_UNLOCK(pcbgroup);
2355 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2357 if (in_pcbrele_wlocked(inp))
2361 if (in_pcbrele_rlocked(inp))
2366 if (lookupflags & INPLOOKUP_WLOCKPCB)
2367 INP_WLOCK_ASSERT(inp);
2369 INP_RLOCK_ASSERT(inp);
2373 #endif /* PCBGROUP */
2376 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
2377 * that the caller has locked the hash list, and will not perform any further
2378 * locking or reference operations on either the hash list or the connection.
2380 static struct inpcb *
2381 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2382 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2383 struct ifnet *ifp, uint8_t numa_domain)
2385 struct inpcbhead *head;
2386 struct inpcb *inp, *tmpinp;
2387 u_short fport = fport_arg, lport = lport_arg;
2389 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2390 ("%s: invalid lookup flags %d", __func__, lookupflags));
2391 INP_HASH_LOCK_ASSERT(pcbinfo);
2394 * First look for an exact match.
2397 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2398 pcbinfo->ipi_hashmask)];
2399 CK_LIST_FOREACH(inp, head, inp_hash) {
2401 /* XXX inp locking */
2402 if ((inp->inp_vflag & INP_IPV4) == 0)
2405 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2406 inp->inp_laddr.s_addr == laddr.s_addr &&
2407 inp->inp_fport == fport &&
2408 inp->inp_lport == lport) {
2410 * XXX We should be able to directly return
2411 * the inp here, without any checks.
2412 * Well unless both bound with SO_REUSEPORT?
2414 if (prison_flag(inp->inp_cred, PR_IP4))
2424 * Then look in lb group (for wildcard match).
2426 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2427 inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2428 fport, lookupflags, numa_domain);
2434 * Then look for a wildcard match, if requested.
2436 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2437 struct inpcb *local_wild = NULL, *local_exact = NULL;
2439 struct inpcb *local_wild_mapped = NULL;
2441 struct inpcb *jail_wild = NULL;
2445 * Order of socket selection - we always prefer jails.
2446 * 1. jailed, non-wild.
2448 * 3. non-jailed, non-wild.
2449 * 4. non-jailed, wild.
2452 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2453 0, pcbinfo->ipi_hashmask)];
2454 CK_LIST_FOREACH(inp, head, inp_hash) {
2456 /* XXX inp locking */
2457 if ((inp->inp_vflag & INP_IPV4) == 0)
2460 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2461 inp->inp_lport != lport)
2464 injail = prison_flag(inp->inp_cred, PR_IP4);
2466 if (prison_check_ip4(inp->inp_cred,
2470 if (local_exact != NULL)
2474 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2479 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2481 /* XXX inp locking, NULL check */
2482 if (inp->inp_vflag & INP_IPV6PROTO)
2483 local_wild_mapped = inp;
2491 } /* LIST_FOREACH */
2492 if (jail_wild != NULL)
2494 if (local_exact != NULL)
2495 return (local_exact);
2496 if (local_wild != NULL)
2497 return (local_wild);
2499 if (local_wild_mapped != NULL)
2500 return (local_wild_mapped);
2502 } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2508 * Lookup PCB in hash list, using pcbinfo tables. This variation locks the
2509 * hash list lock, and will return the inpcb locked (i.e., requires
2510 * INPLOOKUP_LOCKPCB).
2512 static struct inpcb *
2513 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2514 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2515 struct ifnet *ifp, uint8_t numa_domain)
2519 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2520 (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp,
2523 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2525 if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2529 } else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2531 if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2536 panic("%s: locking bug", __func__);
2539 if (lookupflags & INPLOOKUP_WLOCKPCB)
2540 INP_WLOCK_ASSERT(inp);
2542 INP_RLOCK_ASSERT(inp);
2551 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2552 * from which a pre-calculated hash value may be extracted.
2554 * Possibly more of this logic should be in in_pcbgroup.c.
2557 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2558 struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2560 #if defined(PCBGROUP) && !defined(RSS)
2561 struct inpcbgroup *pcbgroup;
2564 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2565 ("%s: invalid lookup flags %d", __func__, lookupflags));
2566 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2567 ("%s: LOCKPCB not set", __func__));
2570 * When not using RSS, use connection groups in preference to the
2571 * reservation table when looking up 4-tuples. When using RSS, just
2572 * use the reservation table, due to the cost of the Toeplitz hash
2575 * XXXRW: This policy belongs in the pcbgroup code, as in principle
2576 * we could be doing RSS with a non-Toeplitz hash that is affordable
2579 #if defined(PCBGROUP) && !defined(RSS)
2580 if (in_pcbgroup_enabled(pcbinfo)) {
2581 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2583 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2584 laddr, lport, lookupflags, ifp));
2587 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2588 lookupflags, ifp, M_NODOM));
2592 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2593 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2594 struct ifnet *ifp, struct mbuf *m)
2597 struct inpcbgroup *pcbgroup;
2600 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2601 ("%s: invalid lookup flags %d", __func__, lookupflags));
2602 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2603 ("%s: LOCKPCB not set", __func__));
2607 * If we can use a hardware-generated hash to look up the connection
2608 * group, use that connection group to find the inpcb. Otherwise
2609 * fall back on a software hash -- or the reservation table if we're
2612 * XXXRW: As above, that policy belongs in the pcbgroup code.
2614 if (in_pcbgroup_enabled(pcbinfo) &&
2615 !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2616 pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2617 m->m_pkthdr.flowid);
2618 if (pcbgroup != NULL)
2619 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2620 fport, laddr, lport, lookupflags, ifp));
2622 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2624 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2625 laddr, lport, lookupflags, ifp));
2629 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2630 lookupflags, ifp, m->m_pkthdr.numa_domain));
2635 * Insert PCB onto various hash lists.
2638 in_pcbinshash_internal(struct inpcb *inp, struct mbuf *m)
2640 struct inpcbhead *pcbhash;
2641 struct inpcbporthead *pcbporthash;
2642 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2643 struct inpcbport *phd;
2644 u_int32_t hashkey_faddr;
2647 INP_WLOCK_ASSERT(inp);
2648 INP_HASH_WLOCK_ASSERT(pcbinfo);
2650 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2651 ("in_pcbinshash: INP_INHASHLIST"));
2654 if (inp->inp_vflag & INP_IPV6)
2655 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2658 hashkey_faddr = inp->inp_faddr.s_addr;
2660 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2661 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2663 pcbporthash = &pcbinfo->ipi_porthashbase[
2664 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2667 * Add entry to load balance group.
2668 * Only do this if SO_REUSEPORT_LB is set.
2670 so_options = inp_so_options(inp);
2671 if (so_options & SO_REUSEPORT_LB) {
2672 int ret = in_pcbinslbgrouphash(inp, M_NODOM);
2674 /* pcb lb group malloc fail (ret=ENOBUFS). */
2680 * Go through port list and look for a head for this lport.
2682 CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2683 if (phd->phd_port == inp->inp_lport)
2687 * If none exists, malloc one and tack it on.
2690 phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2692 return (ENOBUFS); /* XXX */
2694 bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2695 phd->phd_port = inp->inp_lport;
2696 CK_LIST_INIT(&phd->phd_pcblist);
2697 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2700 CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2701 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2702 inp->inp_flags |= INP_INHASHLIST;
2705 in_pcbgroup_update_mbuf(inp, m);
2707 in_pcbgroup_update(inp);
2714 in_pcbinshash(struct inpcb *inp)
2717 return (in_pcbinshash_internal(inp, NULL));
2721 in_pcbinshash_mbuf(struct inpcb *inp, struct mbuf *m)
2724 return (in_pcbinshash_internal(inp, m));
2728 * Move PCB to the proper hash bucket when { faddr, fport } have been
2729 * changed. NOTE: This does not handle the case of the lport changing (the
2730 * hashed port list would have to be updated as well), so the lport must
2731 * not change after in_pcbinshash() has been called.
2734 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2736 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2737 struct inpcbhead *head;
2738 u_int32_t hashkey_faddr;
2740 INP_WLOCK_ASSERT(inp);
2741 INP_HASH_WLOCK_ASSERT(pcbinfo);
2743 KASSERT(inp->inp_flags & INP_INHASHLIST,
2744 ("in_pcbrehash: !INP_INHASHLIST"));
2747 if (inp->inp_vflag & INP_IPV6)
2748 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2751 hashkey_faddr = inp->inp_faddr.s_addr;
2753 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2754 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2756 CK_LIST_REMOVE(inp, inp_hash);
2757 CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2761 in_pcbgroup_update_mbuf(inp, m);
2763 in_pcbgroup_update(inp);
2768 in_pcbrehash(struct inpcb *inp)
2771 in_pcbrehash_mbuf(inp, NULL);
2775 * Remove PCB from various lists.
2778 in_pcbremlists(struct inpcb *inp)
2780 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2782 INP_WLOCK_ASSERT(inp);
2783 INP_LIST_WLOCK_ASSERT(pcbinfo);
2785 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2786 if (inp->inp_flags & INP_INHASHLIST) {
2787 struct inpcbport *phd = inp->inp_phd;
2789 INP_HASH_WLOCK(pcbinfo);
2791 /* XXX: Only do if SO_REUSEPORT_LB set? */
2792 in_pcbremlbgrouphash(inp);
2794 CK_LIST_REMOVE(inp, inp_hash);
2795 CK_LIST_REMOVE(inp, inp_portlist);
2796 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2797 CK_LIST_REMOVE(phd, phd_hash);
2798 NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
2800 INP_HASH_WUNLOCK(pcbinfo);
2801 inp->inp_flags &= ~INP_INHASHLIST;
2803 CK_LIST_REMOVE(inp, inp_list);
2804 pcbinfo->ipi_count--;
2806 in_pcbgroup_remove(inp);
2811 * Check for alternatives when higher level complains
2812 * about service problems. For now, invalidate cached
2813 * routing information. If the route was created dynamically
2814 * (by a redirect), time to try a default gateway again.
2817 in_losing(struct inpcb *inp)
2820 RO_INVALIDATE_CACHE(&inp->inp_route);
2825 * A set label operation has occurred at the socket layer, propagate the
2826 * label change into the in_pcb for the socket.
2829 in_pcbsosetlabel(struct socket *so)
2834 inp = sotoinpcb(so);
2835 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2839 mac_inpcb_sosetlabel(so, inp);
2846 * ipport_tick runs once per second, determining if random port allocation
2847 * should be continued. If more than ipport_randomcps ports have been
2848 * allocated in the last second, then we return to sequential port
2849 * allocation. We return to random allocation only once we drop below
2850 * ipport_randomcps for at least ipport_randomtime seconds.
2853 ipport_tick(void *xtp)
2855 VNET_ITERATOR_DECL(vnet_iter);
2857 VNET_LIST_RLOCK_NOSLEEP();
2858 VNET_FOREACH(vnet_iter) {
2859 CURVNET_SET(vnet_iter); /* XXX appease INVARIANTS here */
2860 if (V_ipport_tcpallocs <=
2861 V_ipport_tcplastcount + V_ipport_randomcps) {
2862 if (V_ipport_stoprandom > 0)
2863 V_ipport_stoprandom--;
2865 V_ipport_stoprandom = V_ipport_randomtime;
2866 V_ipport_tcplastcount = V_ipport_tcpallocs;
2869 VNET_LIST_RUNLOCK_NOSLEEP();
2870 callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2877 callout_stop(&ipport_tick_callout);
2881 * The ipport_callout should start running at about the time we attach the
2882 * inet or inet6 domains.
2885 ipport_tick_init(const void *unused __unused)
2888 /* Start ipport_tick. */
2889 callout_init(&ipport_tick_callout, 1);
2890 callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2891 EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2892 SHUTDOWN_PRI_DEFAULT);
2894 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2895 ipport_tick_init, NULL);
2898 inp_wlock(struct inpcb *inp)
2905 inp_wunlock(struct inpcb *inp)
2912 inp_rlock(struct inpcb *inp)
2919 inp_runlock(struct inpcb *inp)
2925 #ifdef INVARIANT_SUPPORT
2927 inp_lock_assert(struct inpcb *inp)
2930 INP_WLOCK_ASSERT(inp);
2934 inp_unlock_assert(struct inpcb *inp)
2937 INP_UNLOCK_ASSERT(inp);
2942 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2946 INP_INFO_WLOCK(&V_tcbinfo);
2947 CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2952 INP_INFO_WUNLOCK(&V_tcbinfo);
2956 inp_inpcbtosocket(struct inpcb *inp)
2959 INP_WLOCK_ASSERT(inp);
2960 return (inp->inp_socket);
2964 inp_inpcbtotcpcb(struct inpcb *inp)
2967 INP_WLOCK_ASSERT(inp);
2968 return ((struct tcpcb *)inp->inp_ppcb);
2972 inp_ip_tos_get(const struct inpcb *inp)
2975 return (inp->inp_ip_tos);
2979 inp_ip_tos_set(struct inpcb *inp, int val)
2982 inp->inp_ip_tos = val;
2986 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2987 uint32_t *faddr, uint16_t *fp)
2990 INP_LOCK_ASSERT(inp);
2991 *laddr = inp->inp_laddr.s_addr;
2992 *faddr = inp->inp_faddr.s_addr;
2993 *lp = inp->inp_lport;
2994 *fp = inp->inp_fport;
2998 so_sotoinpcb(struct socket *so)
3001 return (sotoinpcb(so));
3005 so_sototcpcb(struct socket *so)
3008 return (sototcpcb(so));
3012 * Create an external-format (``xinpcb'') structure using the information in
3013 * the kernel-format in_pcb structure pointed to by inp. This is done to
3014 * reduce the spew of irrelevant information over this interface, to isolate
3015 * user code from changes in the kernel structure, and potentially to provide
3016 * information-hiding if we decide that some of this information should be
3017 * hidden from users.
3020 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
3023 bzero(xi, sizeof(*xi));
3024 xi->xi_len = sizeof(struct xinpcb);
3025 if (inp->inp_socket)
3026 sotoxsocket(inp->inp_socket, &xi->xi_socket);
3027 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
3028 xi->inp_gencnt = inp->inp_gencnt;
3029 xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
3030 xi->inp_flow = inp->inp_flow;
3031 xi->inp_flowid = inp->inp_flowid;
3032 xi->inp_flowtype = inp->inp_flowtype;
3033 xi->inp_flags = inp->inp_flags;
3034 xi->inp_flags2 = inp->inp_flags2;
3035 xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
3036 xi->in6p_cksum = inp->in6p_cksum;
3037 xi->in6p_hops = inp->in6p_hops;
3038 xi->inp_ip_tos = inp->inp_ip_tos;
3039 xi->inp_vflag = inp->inp_vflag;
3040 xi->inp_ip_ttl = inp->inp_ip_ttl;
3041 xi->inp_ip_p = inp->inp_ip_p;
3042 xi->inp_ip_minttl = inp->inp_ip_minttl;
3047 db_print_indent(int indent)
3051 for (i = 0; i < indent; i++)
3056 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3058 char faddr_str[48], laddr_str[48];
3060 db_print_indent(indent);
3061 db_printf("%s at %p\n", name, inc);
3066 if (inc->inc_flags & INC_ISIPV6) {
3068 ip6_sprintf(laddr_str, &inc->inc6_laddr);
3069 ip6_sprintf(faddr_str, &inc->inc6_faddr);
3074 inet_ntoa_r(inc->inc_laddr, laddr_str);
3075 inet_ntoa_r(inc->inc_faddr, faddr_str);
3077 db_print_indent(indent);
3078 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
3079 ntohs(inc->inc_lport));
3080 db_print_indent(indent);
3081 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
3082 ntohs(inc->inc_fport));
3086 db_print_inpflags(int inp_flags)
3091 if (inp_flags & INP_RECVOPTS) {
3092 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3095 if (inp_flags & INP_RECVRETOPTS) {
3096 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3099 if (inp_flags & INP_RECVDSTADDR) {
3100 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3103 if (inp_flags & INP_ORIGDSTADDR) {
3104 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3107 if (inp_flags & INP_HDRINCL) {
3108 db_printf("%sINP_HDRINCL", comma ? ", " : "");
3111 if (inp_flags & INP_HIGHPORT) {
3112 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3115 if (inp_flags & INP_LOWPORT) {
3116 db_printf("%sINP_LOWPORT", comma ? ", " : "");
3119 if (inp_flags & INP_ANONPORT) {
3120 db_printf("%sINP_ANONPORT", comma ? ", " : "");
3123 if (inp_flags & INP_RECVIF) {
3124 db_printf("%sINP_RECVIF", comma ? ", " : "");
3127 if (inp_flags & INP_MTUDISC) {
3128 db_printf("%sINP_MTUDISC", comma ? ", " : "");
3131 if (inp_flags & INP_RECVTTL) {
3132 db_printf("%sINP_RECVTTL", comma ? ", " : "");
3135 if (inp_flags & INP_DONTFRAG) {
3136 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3139 if (inp_flags & INP_RECVTOS) {
3140 db_printf("%sINP_RECVTOS", comma ? ", " : "");
3143 if (inp_flags & IN6P_IPV6_V6ONLY) {
3144 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3147 if (inp_flags & IN6P_PKTINFO) {
3148 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3151 if (inp_flags & IN6P_HOPLIMIT) {
3152 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3155 if (inp_flags & IN6P_HOPOPTS) {
3156 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3159 if (inp_flags & IN6P_DSTOPTS) {
3160 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3163 if (inp_flags & IN6P_RTHDR) {
3164 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3167 if (inp_flags & IN6P_RTHDRDSTOPTS) {
3168 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3171 if (inp_flags & IN6P_TCLASS) {
3172 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3175 if (inp_flags & IN6P_AUTOFLOWLABEL) {
3176 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3179 if (inp_flags & INP_TIMEWAIT) {
3180 db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3183 if (inp_flags & INP_ONESBCAST) {
3184 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3187 if (inp_flags & INP_DROPPED) {
3188 db_printf("%sINP_DROPPED", comma ? ", " : "");
3191 if (inp_flags & INP_SOCKREF) {
3192 db_printf("%sINP_SOCKREF", comma ? ", " : "");
3195 if (inp_flags & IN6P_RFC2292) {
3196 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3199 if (inp_flags & IN6P_MTU) {
3200 db_printf("IN6P_MTU%s", comma ? ", " : "");
3206 db_print_inpvflag(u_char inp_vflag)
3211 if (inp_vflag & INP_IPV4) {
3212 db_printf("%sINP_IPV4", comma ? ", " : "");
3215 if (inp_vflag & INP_IPV6) {
3216 db_printf("%sINP_IPV6", comma ? ", " : "");
3219 if (inp_vflag & INP_IPV6PROTO) {
3220 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3226 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3229 db_print_indent(indent);
3230 db_printf("%s at %p\n", name, inp);
3234 db_print_indent(indent);
3235 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3237 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3239 db_print_indent(indent);
3240 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
3241 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3243 db_print_indent(indent);
3244 db_printf("inp_label: %p inp_flags: 0x%x (",
3245 inp->inp_label, inp->inp_flags);
3246 db_print_inpflags(inp->inp_flags);
3249 db_print_indent(indent);
3250 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
3252 db_print_inpvflag(inp->inp_vflag);
3255 db_print_indent(indent);
3256 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
3257 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3259 db_print_indent(indent);
3261 if (inp->inp_vflag & INP_IPV6) {
3262 db_printf("in6p_options: %p in6p_outputopts: %p "
3263 "in6p_moptions: %p\n", inp->in6p_options,
3264 inp->in6p_outputopts, inp->in6p_moptions);
3265 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
3266 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3271 db_printf("inp_ip_tos: %d inp_ip_options: %p "
3272 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3273 inp->inp_options, inp->inp_moptions);
3276 db_print_indent(indent);
3277 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
3278 (uintmax_t)inp->inp_gencnt);
3281 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3286 db_printf("usage: show inpcb <addr>\n");
3289 inp = (struct inpcb *)addr;
3291 db_print_inpcb(inp, "inpcb", 0);
3297 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3301 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3303 union if_snd_tag_modify_params params = {
3304 .rate_limit.max_rate = max_pacing_rate,
3305 .rate_limit.flags = M_NOWAIT,
3307 struct m_snd_tag *mst;
3311 mst = inp->inp_snd_tag;
3319 if (ifp->if_snd_tag_modify == NULL) {
3322 error = ifp->if_snd_tag_modify(mst, ¶ms);
3328 * Query existing TX rate limit based on the existing
3329 * "inp->inp_snd_tag", if any.
3332 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3334 union if_snd_tag_query_params params = { };
3335 struct m_snd_tag *mst;
3339 mst = inp->inp_snd_tag;
3347 if (ifp->if_snd_tag_query == NULL) {
3350 error = ifp->if_snd_tag_query(mst, ¶ms);
3351 if (error == 0 && p_max_pacing_rate != NULL)
3352 *p_max_pacing_rate = params.rate_limit.max_rate;
3358 * Query existing TX queue level based on the existing
3359 * "inp->inp_snd_tag", if any.
3362 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3364 union if_snd_tag_query_params params = { };
3365 struct m_snd_tag *mst;
3369 mst = inp->inp_snd_tag;
3377 if (ifp->if_snd_tag_query == NULL)
3378 return (EOPNOTSUPP);
3380 error = ifp->if_snd_tag_query(mst, ¶ms);
3381 if (error == 0 && p_txqueue_level != NULL)
3382 *p_txqueue_level = params.rate_limit.queue_level;
3387 * Allocate a new TX rate limit send tag from the network interface
3388 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3391 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3392 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
3395 union if_snd_tag_alloc_params params = {
3396 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3397 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3398 .rate_limit.hdr.flowid = flowid,
3399 .rate_limit.hdr.flowtype = flowtype,
3400 .rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3401 .rate_limit.max_rate = max_pacing_rate,
3402 .rate_limit.flags = M_NOWAIT,
3406 INP_WLOCK_ASSERT(inp);
3409 * If there is already a send tag, or the INP is being torn
3410 * down, allocating a new send tag is not allowed. Else send
3413 if (*st != NULL || (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0)
3416 error = m_snd_tag_alloc(ifp, ¶ms, st);
3419 counter_u64_add(rate_limit_set_ok, 1);
3420 counter_u64_add(rate_limit_active, 1);
3421 } else if (error != EOPNOTSUPP)
3422 counter_u64_add(rate_limit_alloc_fail, 1);
3428 in_pcbdetach_tag(struct m_snd_tag *mst)
3431 m_snd_tag_rele(mst);
3433 counter_u64_add(rate_limit_active, -1);
3438 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3442 in_pcbdetach_txrtlmt(struct inpcb *inp)
3444 struct m_snd_tag *mst;
3446 INP_WLOCK_ASSERT(inp);
3448 mst = inp->inp_snd_tag;
3449 inp->inp_snd_tag = NULL;
3454 m_snd_tag_rele(mst);
3456 counter_u64_add(rate_limit_active, -1);
3461 in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
3466 * If the existing send tag is for the wrong interface due to
3467 * a route change, first drop the existing tag. Set the
3468 * CHANGED flag so that we will keep trying to allocate a new
3469 * tag if we fail to allocate one this time.
3471 if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
3472 in_pcbdetach_txrtlmt(inp);
3473 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3477 * NOTE: When attaching to a network interface a reference is
3478 * made to ensure the network interface doesn't go away until
3479 * all ratelimit connections are gone. The network interface
3480 * pointers compared below represent valid network interfaces,
3481 * except when comparing towards NULL.
3483 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3485 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3486 if (inp->inp_snd_tag != NULL)
3487 in_pcbdetach_txrtlmt(inp);
3489 } else if (inp->inp_snd_tag == NULL) {
3491 * In order to utilize packet pacing with RSS, we need
3492 * to wait until there is a valid RSS hash before we
3495 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3498 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3499 mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
3502 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3504 if (error == 0 || error == EOPNOTSUPP)
3505 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3511 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3512 * is set in the fast path and will attach/detach/modify the TX rate
3513 * limit send tag based on the socket's so_max_pacing_rate value.
3516 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3518 struct socket *socket;
3519 uint32_t max_pacing_rate;
3526 socket = inp->inp_socket;
3530 if (!INP_WLOCKED(inp)) {
3532 * NOTE: If the write locking fails, we need to bail
3533 * out and use the non-ratelimited ring for the
3534 * transmit until there is a new chance to get the
3537 if (!INP_TRY_UPGRADE(inp))
3545 * NOTE: The so_max_pacing_rate value is read unlocked,
3546 * because atomic updates are not required since the variable
3547 * is checked at every mbuf we send. It is assumed that the
3548 * variable read itself will be atomic.
3550 max_pacing_rate = socket->so_max_pacing_rate;
3552 error = in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3559 * Track route changes for TX rate limiting.
3562 in_pcboutput_eagain(struct inpcb *inp)
3569 if (inp->inp_snd_tag == NULL)
3572 if (!INP_WLOCKED(inp)) {
3574 * NOTE: If the write locking fails, we need to bail
3575 * out and use the non-ratelimited ring for the
3576 * transmit until there is a new chance to get the
3579 if (!INP_TRY_UPGRADE(inp))
3586 /* detach rate limiting */
3587 in_pcbdetach_txrtlmt(inp);
3589 /* make sure new mbuf send tag allocation is made */
3590 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3600 rate_limit_new = counter_u64_alloc(M_WAITOK);
3601 rate_limit_chg = counter_u64_alloc(M_WAITOK);
3602 rate_limit_active = counter_u64_alloc(M_WAITOK);
3603 rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
3604 rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
3607 SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3609 #endif /* RATELIMIT */