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_route.h"
51 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/libkern.h>
56 #include <sys/malloc.h>
58 #include <sys/eventhandler.h>
59 #include <sys/domain.h>
60 #include <sys/protosw.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sockio.h>
67 #include <sys/refcount.h>
69 #include <sys/kernel.h>
70 #include <sys/sysctl.h>
80 #include <net/if_var.h>
81 #include <net/if_types.h>
82 #include <net/if_llatbl.h>
83 #include <net/route.h>
84 #include <net/rss_config.h>
87 #if defined(INET) || defined(INET6)
88 #include <netinet/in.h>
89 #include <netinet/in_pcb.h>
90 #include <netinet/in_pcb_var.h>
91 #include <netinet/tcp.h>
93 #include <netinet/in_var.h>
94 #include <netinet/in_fib.h>
96 #include <netinet/ip_var.h>
98 #include <netinet/ip6.h>
99 #include <netinet6/in6_pcb.h>
100 #include <netinet6/in6_var.h>
101 #include <netinet6/ip6_var.h>
103 #include <net/route/nhop.h>
106 #include <netipsec/ipsec_support.h>
108 #include <security/mac/mac_framework.h>
110 #define INPCBLBGROUP_SIZMIN 8
111 #define INPCBLBGROUP_SIZMAX 256
112 #define INP_FREED 0x00000200 /* See in_pcb.h. */
115 * These configure the range of local port addresses assigned to
116 * "unspecified" outgoing connections/packets/whatever.
118 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1; /* 1023 */
119 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART; /* 600 */
120 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST; /* 10000 */
121 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST; /* 65535 */
122 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO; /* 49152 */
123 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO; /* 65535 */
126 * Reserved ports accessible only to root. There are significant
127 * security considerations that must be accounted for when changing these,
128 * but the security benefits can be great. Please be careful.
130 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1; /* 1023 */
131 VNET_DEFINE(int, ipport_reservedlow);
133 /* Enable random ephemeral port allocation by default. */
134 VNET_DEFINE(int, ipport_randomized) = 1;
137 static struct inpcb *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
138 struct in_addr faddr, u_int fport_arg,
139 struct in_addr laddr, u_int lport_arg,
140 int lookupflags, struct ifnet *ifp,
141 uint8_t numa_domain);
143 #define RANGECHK(var, min, max) \
144 if ((var) < (min)) { (var) = (min); } \
145 else if ((var) > (max)) { (var) = (max); }
148 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
152 error = sysctl_handle_int(oidp, arg1, arg2, req);
154 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
155 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
156 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
157 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
158 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
159 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
166 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
167 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
170 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
171 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
172 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
174 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
175 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
176 &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
178 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
179 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
180 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
182 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
183 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
184 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
186 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
187 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
188 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
190 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
191 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
192 &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
194 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
195 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
196 &VNET_NAME(ipport_reservedhigh), 0, "");
197 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
198 CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
199 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
200 CTLFLAG_VNET | CTLFLAG_RW,
201 &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
204 counter_u64_t rate_limit_new;
205 counter_u64_t rate_limit_chg;
206 counter_u64_t rate_limit_active;
207 counter_u64_t rate_limit_alloc_fail;
208 counter_u64_t rate_limit_set_ok;
210 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
212 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
213 &rate_limit_active, "Active rate limited connections");
214 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
215 &rate_limit_alloc_fail, "Rate limited connection failures");
216 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
217 &rate_limit_set_ok, "Rate limited setting succeeded");
218 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
219 &rate_limit_new, "Total Rate limit new attempts");
220 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
221 &rate_limit_chg, "Total Rate limited change attempts");
223 #endif /* RATELIMIT */
227 VNET_DEFINE(uint32_t, in_pcbhashseed);
229 in_pcbhashseed_init(void)
232 V_in_pcbhashseed = arc4random();
234 VNET_SYSINIT(in_pcbhashseed_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
235 in_pcbhashseed_init, 0);
237 static void in_pcbremhash(struct inpcb *);
240 * in_pcb.c: manage the Protocol Control Blocks.
242 * NOTE: It is assumed that most of these functions will be called with
243 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
244 * functions often modify hash chains or addresses in pcbs.
247 static struct inpcblbgroup *
248 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, struct ucred *cred,
249 u_char vflag, uint16_t port, const union in_dependaddr *addr, int size,
252 struct inpcblbgroup *grp;
255 bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
256 grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
259 grp->il_cred = crhold(cred);
260 grp->il_vflag = vflag;
261 grp->il_lport = port;
262 grp->il_numa_domain = numa_domain;
263 grp->il_dependladdr = *addr;
264 grp->il_inpsiz = size;
265 CK_LIST_INSERT_HEAD(hdr, grp, il_list);
270 in_pcblbgroup_free_deferred(epoch_context_t ctx)
272 struct inpcblbgroup *grp;
274 grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
275 crfree(grp->il_cred);
280 in_pcblbgroup_free(struct inpcblbgroup *grp)
283 CK_LIST_REMOVE(grp, il_list);
284 NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
287 static struct inpcblbgroup *
288 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
289 struct inpcblbgroup *old_grp, int size)
291 struct inpcblbgroup *grp;
294 grp = in_pcblbgroup_alloc(hdr, old_grp->il_cred, old_grp->il_vflag,
295 old_grp->il_lport, &old_grp->il_dependladdr, size,
296 old_grp->il_numa_domain);
300 KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
301 ("invalid new local group size %d and old local group count %d",
302 grp->il_inpsiz, old_grp->il_inpcnt));
304 for (i = 0; i < old_grp->il_inpcnt; ++i)
305 grp->il_inp[i] = old_grp->il_inp[i];
306 grp->il_inpcnt = old_grp->il_inpcnt;
307 in_pcblbgroup_free(old_grp);
312 * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
313 * and shrink group if possible.
316 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
319 struct inpcblbgroup *grp, *new_grp;
322 for (; i + 1 < grp->il_inpcnt; ++i)
323 grp->il_inp[i] = grp->il_inp[i + 1];
326 if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
327 grp->il_inpcnt <= grp->il_inpsiz / 4) {
328 /* Shrink this group. */
329 new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
336 * Add PCB to load balance group for SO_REUSEPORT_LB option.
339 in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
341 const static struct timeval interval = { 60, 0 };
342 static struct timeval lastprint;
343 struct inpcbinfo *pcbinfo;
344 struct inpcblbgrouphead *hdr;
345 struct inpcblbgroup *grp;
348 pcbinfo = inp->inp_pcbinfo;
350 INP_WLOCK_ASSERT(inp);
351 INP_HASH_WLOCK_ASSERT(pcbinfo);
355 * Don't allow IPv4 mapped INET6 wild socket.
357 if ((inp->inp_vflag & INP_IPV4) &&
358 inp->inp_laddr.s_addr == INADDR_ANY &&
359 INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
364 idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
365 hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
366 CK_LIST_FOREACH(grp, hdr, il_list) {
367 if (grp->il_cred->cr_prison == inp->inp_cred->cr_prison &&
368 grp->il_vflag == inp->inp_vflag &&
369 grp->il_lport == inp->inp_lport &&
370 grp->il_numa_domain == numa_domain &&
371 memcmp(&grp->il_dependladdr,
372 &inp->inp_inc.inc_ie.ie_dependladdr,
373 sizeof(grp->il_dependladdr)) == 0) {
378 /* Create new load balance group. */
379 grp = in_pcblbgroup_alloc(hdr, inp->inp_cred, inp->inp_vflag,
380 inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
381 INPCBLBGROUP_SIZMIN, numa_domain);
384 } else if (grp->il_inpcnt == grp->il_inpsiz) {
385 if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
386 if (ratecheck(&lastprint, &interval))
387 printf("lb group port %d, limit reached\n",
388 ntohs(grp->il_lport));
392 /* Expand this local group. */
393 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
398 KASSERT(grp->il_inpcnt < grp->il_inpsiz,
399 ("invalid local group size %d and count %d", grp->il_inpsiz,
402 grp->il_inp[grp->il_inpcnt] = inp;
408 * Remove PCB from load balance group.
411 in_pcbremlbgrouphash(struct inpcb *inp)
413 struct inpcbinfo *pcbinfo;
414 struct inpcblbgrouphead *hdr;
415 struct inpcblbgroup *grp;
418 pcbinfo = inp->inp_pcbinfo;
420 INP_WLOCK_ASSERT(inp);
421 INP_HASH_WLOCK_ASSERT(pcbinfo);
423 hdr = &pcbinfo->ipi_lbgrouphashbase[
424 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
425 CK_LIST_FOREACH(grp, hdr, il_list) {
426 for (i = 0; i < grp->il_inpcnt; ++i) {
427 if (grp->il_inp[i] != inp)
430 if (grp->il_inpcnt == 1) {
431 /* We are the last, free this local group. */
432 in_pcblbgroup_free(grp);
434 /* Pull up inpcbs, shrink group if possible. */
435 in_pcblbgroup_reorder(hdr, &grp, i);
443 in_pcblbgroup_numa(struct inpcb *inp, int arg)
445 struct inpcbinfo *pcbinfo;
446 struct inpcblbgrouphead *hdr;
447 struct inpcblbgroup *grp;
452 case TCP_REUSPORT_LB_NUMA_NODOM:
453 numa_domain = M_NODOM;
455 case TCP_REUSPORT_LB_NUMA_CURDOM:
456 numa_domain = PCPU_GET(domain);
459 if (arg < 0 || arg >= vm_ndomains)
465 pcbinfo = inp->inp_pcbinfo;
466 INP_WLOCK_ASSERT(inp);
467 INP_HASH_WLOCK(pcbinfo);
468 hdr = &pcbinfo->ipi_lbgrouphashbase[
469 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
470 CK_LIST_FOREACH(grp, hdr, il_list) {
471 for (i = 0; i < grp->il_inpcnt; ++i) {
472 if (grp->il_inp[i] != inp)
475 if (grp->il_numa_domain == numa_domain) {
476 goto abort_with_hash_wlock;
479 /* Remove it from the old group. */
480 in_pcbremlbgrouphash(inp);
482 /* Add it to the new group based on numa domain. */
483 in_pcbinslbgrouphash(inp, numa_domain);
484 goto abort_with_hash_wlock;
488 abort_with_hash_wlock:
489 INP_HASH_WUNLOCK(pcbinfo);
493 /* Make sure it is safe to use hashinit(9) on CK_LIST. */
494 CTASSERT(sizeof(struct inpcbhead) == sizeof(LIST_HEAD(, inpcb)));
497 * Initialize an inpcbinfo - a per-VNET instance of connections db.
500 in_pcbinfo_init(struct inpcbinfo *pcbinfo, struct inpcbstorage *pcbstor,
501 u_int hash_nelements, u_int porthash_nelements)
504 mtx_init(&pcbinfo->ipi_lock, pcbstor->ips_infolock_name, NULL, MTX_DEF);
505 mtx_init(&pcbinfo->ipi_hash_lock, pcbstor->ips_hashlock_name,
508 pcbinfo->ipi_vnet = curvnet;
510 CK_LIST_INIT(&pcbinfo->ipi_listhead);
511 pcbinfo->ipi_count = 0;
512 pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
513 &pcbinfo->ipi_hashmask);
514 porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
515 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
516 &pcbinfo->ipi_porthashmask);
517 pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
518 &pcbinfo->ipi_lbgrouphashmask);
519 pcbinfo->ipi_zone = pcbstor->ips_zone;
520 pcbinfo->ipi_portzone = pcbstor->ips_portzone;
521 pcbinfo->ipi_smr = uma_zone_get_smr(pcbinfo->ipi_zone);
525 * Destroy an inpcbinfo.
528 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
531 KASSERT(pcbinfo->ipi_count == 0,
532 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
534 hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
535 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
536 pcbinfo->ipi_porthashmask);
537 hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
538 pcbinfo->ipi_lbgrouphashmask);
539 mtx_destroy(&pcbinfo->ipi_hash_lock);
540 mtx_destroy(&pcbinfo->ipi_lock);
544 * Initialize a pcbstorage - per protocol zones to allocate inpcbs.
546 static void inpcb_dtor(void *, int, void *);
547 static void inpcb_fini(void *, int);
549 in_pcbstorage_init(void *arg)
551 struct inpcbstorage *pcbstor = arg;
553 pcbstor->ips_zone = uma_zcreate(pcbstor->ips_zone_name,
554 pcbstor->ips_size, NULL, inpcb_dtor, pcbstor->ips_pcbinit,
555 inpcb_fini, UMA_ALIGN_CACHE, UMA_ZONE_SMR);
556 pcbstor->ips_portzone = uma_zcreate(pcbstor->ips_portzone_name,
557 sizeof(struct inpcbport), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
558 uma_zone_set_smr(pcbstor->ips_portzone,
559 uma_zone_get_smr(pcbstor->ips_zone));
563 * Destroy a pcbstorage - used by unloadable protocols.
566 in_pcbstorage_destroy(void *arg)
568 struct inpcbstorage *pcbstor = arg;
570 uma_zdestroy(pcbstor->ips_zone);
571 uma_zdestroy(pcbstor->ips_portzone);
575 * Allocate a PCB and associate it with the socket.
576 * On success return with the PCB locked.
579 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
582 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
586 inp = uma_zalloc_smr(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 | INP_IPV6;
616 inp->inp_flags |= IN6P_IPV6_V6ONLY;
619 inp->inp_vflag |= INP_IPV4;
621 if (V_ip6_auto_flowlabel)
622 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
623 inp->in6p_hops = -1; /* use kernel default */
626 #if defined(INET) && defined(INET6)
630 inp->inp_vflag |= INP_IPV4;
633 * Routes in inpcb's can cache L2 as well; they are guaranteed
636 inp->inp_route.ro_flags = RT_LLE_CACHE;
637 refcount_init(&inp->inp_refcount, 1); /* Reference from socket. */
639 INP_INFO_WLOCK(pcbinfo);
640 pcbinfo->ipi_count++;
641 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
642 CK_LIST_INSERT_HEAD(&pcbinfo->ipi_listhead, inp, inp_list);
643 INP_INFO_WUNLOCK(pcbinfo);
648 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
650 uma_zfree_smr(pcbinfo->ipi_zone, inp);
657 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
661 KASSERT(nam == NULL || nam->sa_family == AF_INET,
662 ("%s: invalid address family for %p", __func__, nam));
663 KASSERT(nam == NULL || nam->sa_len == sizeof(struct sockaddr_in),
664 ("%s: invalid address length for %p", __func__, nam));
665 INP_WLOCK_ASSERT(inp);
666 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
668 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
670 anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
671 error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
672 &inp->inp_lport, cred);
675 if (in_pcbinshash(inp) != 0) {
676 inp->inp_laddr.s_addr = INADDR_ANY;
681 inp->inp_flags |= INP_ANONPORT;
686 #if defined(INET) || defined(INET6)
688 * Assign a local port like in_pcb_lport(), but also used with connect()
689 * and a foreign address and port. If fsa is non-NULL, choose a local port
690 * that is unused with those, otherwise one that is completely unused.
691 * lsa can be NULL for IPv6.
694 in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
695 struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
697 struct inpcbinfo *pcbinfo;
698 struct inpcb *tmpinp;
699 unsigned short *lastport;
701 u_short aux, first, last, lport;
703 struct in_addr laddr, faddr;
706 struct in6_addr *laddr6, *faddr6;
709 pcbinfo = inp->inp_pcbinfo;
712 * Because no actual state changes occur here, a global write lock on
713 * the pcbinfo isn't required.
715 INP_LOCK_ASSERT(inp);
716 INP_HASH_LOCK_ASSERT(pcbinfo);
718 if (inp->inp_flags & INP_HIGHPORT) {
719 first = V_ipport_hifirstauto; /* sysctl */
720 last = V_ipport_hilastauto;
721 lastport = &pcbinfo->ipi_lasthi;
722 } else if (inp->inp_flags & INP_LOWPORT) {
723 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
726 first = V_ipport_lowfirstauto; /* 1023 */
727 last = V_ipport_lowlastauto; /* 600 */
728 lastport = &pcbinfo->ipi_lastlow;
730 first = V_ipport_firstauto; /* sysctl */
731 last = V_ipport_lastauto;
732 lastport = &pcbinfo->ipi_lastport;
736 * Instead of having two loops further down counting up or down
737 * make sure that first is always <= last and go with only one
738 * code path implementing all logic.
747 laddr.s_addr = INADDR_ANY; /* used by INET6+INET below too */
748 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
750 laddr = ((struct sockaddr_in *)lsa)->sin_addr;
752 faddr = ((struct sockaddr_in *)fsa)->sin_addr;
757 if ((inp->inp_vflag & INP_IPV6) != 0) {
759 laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
761 faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
768 if (V_ipport_randomized)
769 *lastport = first + (arc4random() % (last - first));
771 count = last - first;
774 if (count-- < 0) /* completely used? */
775 return (EADDRNOTAVAIL);
777 if (*lastport < first || *lastport > last)
779 lport = htons(*lastport);
783 if (lsa->sa_family == AF_INET) {
784 tmpinp = in_pcblookup_hash_locked(pcbinfo,
785 faddr, fport, laddr, lport, lookupflags,
790 if (lsa->sa_family == AF_INET6) {
791 tmpinp = in6_pcblookup_hash_locked(pcbinfo,
792 faddr6, fport, laddr6, lport, lookupflags,
798 if ((inp->inp_vflag & INP_IPV6) != 0) {
799 tmpinp = in6_pcblookup_local(pcbinfo,
800 &inp->in6p_laddr, lport, lookupflags, cred);
802 if (tmpinp == NULL &&
803 (inp->inp_vflag & INP_IPV4))
804 tmpinp = in_pcblookup_local(pcbinfo,
805 laddr, lport, lookupflags, cred);
809 #if defined(INET) && defined(INET6)
813 tmpinp = in_pcblookup_local(pcbinfo, laddr,
814 lport, lookupflags, cred);
817 } while (tmpinp != NULL);
825 * Select a local port (number) to use.
828 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
829 struct ucred *cred, int lookupflags)
831 struct sockaddr_in laddr;
834 bzero(&laddr, sizeof(laddr));
835 laddr.sin_family = AF_INET;
836 laddr.sin_addr = *laddrp;
838 return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
839 NULL, lportp, NULL, 0, cred, lookupflags));
843 * Return cached socket options.
846 inp_so_options(const struct inpcb *inp)
852 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
853 so_options |= SO_REUSEPORT_LB;
854 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
855 so_options |= SO_REUSEPORT;
856 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
857 so_options |= SO_REUSEADDR;
860 #endif /* INET || INET6 */
863 * Check if a new BINDMULTI socket is allowed to be created.
865 * ni points to the new inp.
866 * oi points to the existing inp.
868 * This checks whether the existing inp also has BINDMULTI and
869 * whether the credentials match.
872 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
874 /* Check permissions match */
875 if ((ni->inp_flags2 & INP_BINDMULTI) &&
876 (ni->inp_cred->cr_uid !=
877 oi->inp_cred->cr_uid))
880 /* Check the existing inp has BINDMULTI set */
881 if ((ni->inp_flags2 & INP_BINDMULTI) &&
882 ((oi->inp_flags2 & INP_BINDMULTI) == 0))
886 * We're okay - either INP_BINDMULTI isn't set on ni, or
887 * it is and it matches the checks.
894 * Set up a bind operation on a PCB, performing port allocation
895 * as required, but do not actually modify the PCB. Callers can
896 * either complete the bind by setting inp_laddr/inp_lport and
897 * calling in_pcbinshash(), or they can just use the resulting
898 * port and address to authorise the sending of a once-off packet.
900 * On error, the values of *laddrp and *lportp are not changed.
903 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
904 u_short *lportp, struct ucred *cred)
906 struct socket *so = inp->inp_socket;
907 struct sockaddr_in *sin;
908 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
909 struct in_addr laddr;
911 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
915 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
916 * so that we don't have to add to the (already messy) code below.
918 int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
921 * No state changes, so read locks are sufficient here.
923 INP_LOCK_ASSERT(inp);
924 INP_HASH_LOCK_ASSERT(pcbinfo);
926 laddr.s_addr = *laddrp;
927 if (nam != NULL && laddr.s_addr != INADDR_ANY)
929 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
930 lookupflags = INPLOOKUP_WILDCARD;
932 if ((error = prison_local_ip4(cred, &laddr)) != 0)
935 sin = (struct sockaddr_in *)nam;
936 KASSERT(sin->sin_family == AF_INET,
937 ("%s: invalid family for address %p", __func__, sin));
938 KASSERT(sin->sin_len == sizeof(*sin),
939 ("%s: invalid length for address %p", __func__, sin));
941 error = prison_local_ip4(cred, &sin->sin_addr);
944 if (sin->sin_port != *lportp) {
945 /* Don't allow the port to change. */
948 lport = sin->sin_port;
950 /* NB: lport is left as 0 if the port isn't being changed. */
951 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
953 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
954 * allow complete duplication of binding if
955 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
956 * and a multicast address is bound on both
957 * new and duplicated sockets.
959 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
960 reuseport = SO_REUSEADDR|SO_REUSEPORT;
962 * XXX: How to deal with SO_REUSEPORT_LB here?
963 * Treat same as SO_REUSEPORT for now.
965 if ((so->so_options &
966 (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
967 reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
968 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
969 sin->sin_port = 0; /* yech... */
970 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
972 * Is the address a local IP address?
973 * If INP_BINDANY is set, then the socket may be bound
974 * to any endpoint address, local or not.
976 if ((inp->inp_flags & INP_BINDANY) == 0 &&
977 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
978 return (EADDRNOTAVAIL);
980 laddr = sin->sin_addr;
985 if (ntohs(lport) <= V_ipport_reservedhigh &&
986 ntohs(lport) >= V_ipport_reservedlow &&
987 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
989 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
990 priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
991 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
992 lport, INPLOOKUP_WILDCARD, cred);
995 * This entire block sorely needs a rewrite.
998 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
999 (so->so_type != SOCK_STREAM ||
1000 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
1001 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
1002 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
1003 (t->inp_flags2 & INP_REUSEPORT) ||
1004 (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
1005 (inp->inp_cred->cr_uid !=
1006 t->inp_cred->cr_uid))
1007 return (EADDRINUSE);
1010 * If the socket is a BINDMULTI socket, then
1011 * the credentials need to match and the
1012 * original socket also has to have been bound
1015 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1016 return (EADDRINUSE);
1018 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1019 lport, lookupflags, cred);
1020 if (t && ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1021 (reuseport & inp_so_options(t)) == 0 &&
1022 (reuseport_lb & inp_so_options(t)) == 0) {
1024 if (ntohl(sin->sin_addr.s_addr) !=
1026 ntohl(t->inp_laddr.s_addr) !=
1028 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1029 (t->inp_vflag & INP_IPV6PROTO) == 0)
1031 return (EADDRINUSE);
1032 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1033 return (EADDRINUSE);
1040 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1044 *laddrp = laddr.s_addr;
1050 * Connect from a socket to a specified address.
1051 * Both address and port must be specified in argument sin.
1052 * If don't have a local address for this socket yet,
1056 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred,
1059 u_short lport, fport;
1060 in_addr_t laddr, faddr;
1061 int anonport, error;
1063 INP_WLOCK_ASSERT(inp);
1064 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1066 lport = inp->inp_lport;
1067 laddr = inp->inp_laddr.s_addr;
1068 anonport = (lport == 0);
1069 error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
1074 /* Do the initial binding of the local address if required. */
1075 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1076 KASSERT(rehash == true,
1077 ("Rehashing required for unbound inps"));
1078 inp->inp_lport = lport;
1079 inp->inp_laddr.s_addr = laddr;
1080 if (in_pcbinshash(inp) != 0) {
1081 inp->inp_laddr.s_addr = INADDR_ANY;
1087 /* Commit the remaining changes. */
1088 inp->inp_lport = lport;
1089 inp->inp_laddr.s_addr = laddr;
1090 inp->inp_faddr.s_addr = faddr;
1091 inp->inp_fport = fport;
1099 inp->inp_flags |= INP_ANONPORT;
1104 * Do proper source address selection on an unbound socket in case
1105 * of connect. Take jails into account as well.
1108 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1112 struct sockaddr *sa;
1113 struct sockaddr_in *sin, dst;
1114 struct nhop_object *nh;
1118 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1121 * Bypass source address selection and use the primary jail IP
1124 if (!prison_saddrsel_ip4(cred, laddr))
1130 bzero(&dst, sizeof(dst));
1132 sin->sin_family = AF_INET;
1133 sin->sin_len = sizeof(struct sockaddr_in);
1134 sin->sin_addr.s_addr = faddr->s_addr;
1137 * If route is known our src addr is taken from the i/f,
1140 * Find out route to destination.
1142 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1143 nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
1147 * If we found a route, use the address corresponding to
1148 * the outgoing interface.
1150 * Otherwise assume faddr is reachable on a directly connected
1151 * network and try to find a corresponding interface to take
1152 * the source address from.
1154 if (nh == NULL || nh->nh_ifp == NULL) {
1155 struct in_ifaddr *ia;
1158 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1159 inp->inp_socket->so_fibnum));
1161 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1162 inp->inp_socket->so_fibnum));
1165 error = ENETUNREACH;
1169 if (!prison_flag(cred, PR_IP4)) {
1170 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1176 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1178 if (sa->sa_family != AF_INET)
1180 sin = (struct sockaddr_in *)sa;
1181 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1182 ia = (struct in_ifaddr *)ifa;
1187 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1191 /* 3. As a last resort return the 'default' jail address. */
1192 error = prison_get_ip4(cred, laddr);
1197 * If the outgoing interface on the route found is not
1198 * a loopback interface, use the address from that interface.
1199 * In case of jails do those three steps:
1200 * 1. check if the interface address belongs to the jail. If so use it.
1201 * 2. check if we have any address on the outgoing interface
1202 * belonging to this jail. If so use it.
1203 * 3. as a last resort return the 'default' jail address.
1205 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
1206 struct in_ifaddr *ia;
1209 /* If not jailed, use the default returned. */
1210 if (!prison_flag(cred, PR_IP4)) {
1211 ia = (struct in_ifaddr *)nh->nh_ifa;
1212 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1217 /* 1. Check if the iface address belongs to the jail. */
1218 sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1219 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1220 ia = (struct in_ifaddr *)nh->nh_ifa;
1221 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1226 * 2. Check if we have any address on the outgoing interface
1227 * belonging to this jail.
1231 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1233 if (sa->sa_family != AF_INET)
1235 sin = (struct sockaddr_in *)sa;
1236 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1237 ia = (struct in_ifaddr *)ifa;
1242 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1246 /* 3. As a last resort return the 'default' jail address. */
1247 error = prison_get_ip4(cred, laddr);
1252 * The outgoing interface is marked with 'loopback net', so a route
1253 * to ourselves is here.
1254 * Try to find the interface of the destination address and then
1255 * take the address from there. That interface is not necessarily
1256 * a loopback interface.
1257 * In case of jails, check that it is an address of the jail
1258 * and if we cannot find, fall back to the 'default' jail address.
1260 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
1261 struct in_ifaddr *ia;
1263 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
1264 inp->inp_socket->so_fibnum));
1266 ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
1267 inp->inp_socket->so_fibnum));
1269 ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
1271 if (!prison_flag(cred, PR_IP4)) {
1273 error = ENETUNREACH;
1276 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1286 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1288 if (sa->sa_family != AF_INET)
1290 sin = (struct sockaddr_in *)sa;
1291 if (prison_check_ip4(cred,
1292 &sin->sin_addr) == 0) {
1293 ia = (struct in_ifaddr *)ifa;
1298 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1303 /* 3. As a last resort return the 'default' jail address. */
1304 error = prison_get_ip4(cred, laddr);
1313 * Set up for a connect from a socket to the specified address.
1314 * On entry, *laddrp and *lportp should contain the current local
1315 * address and port for the PCB; these are updated to the values
1316 * that should be placed in inp_laddr and inp_lport to complete
1319 * On success, *faddrp and *fportp will be set to the remote address
1320 * and port. These are not updated in the error case.
1322 * If the operation fails because the connection already exists,
1323 * *oinpp will be set to the PCB of that connection so that the
1324 * caller can decide to override it. In all other cases, *oinpp
1328 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1329 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1330 struct inpcb **oinpp, struct ucred *cred)
1332 struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1333 struct in_ifaddr *ia;
1335 struct in_addr laddr, faddr;
1336 u_short lport, fport;
1339 KASSERT(sin->sin_family == AF_INET,
1340 ("%s: invalid address family for %p", __func__, sin));
1341 KASSERT(sin->sin_len == sizeof(*sin),
1342 ("%s: invalid address length for %p", __func__, sin));
1345 * Because a global state change doesn't actually occur here, a read
1346 * lock is sufficient.
1349 INP_LOCK_ASSERT(inp);
1350 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1354 if (sin->sin_port == 0)
1355 return (EADDRNOTAVAIL);
1356 laddr.s_addr = *laddrp;
1358 faddr = sin->sin_addr;
1359 fport = sin->sin_port;
1361 if (CALC_FLOWID_OUTBOUND) {
1362 uint32_t hash_val, hash_type;
1364 hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
1365 inp->inp_socket->so_proto->pr_protocol, &hash_type);
1367 inp->inp_flowid = hash_val;
1368 inp->inp_flowtype = hash_type;
1371 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1373 * If the destination address is INADDR_ANY,
1374 * use the primary local address.
1375 * If the supplied address is INADDR_BROADCAST,
1376 * and the primary interface supports broadcast,
1377 * choose the broadcast address for that interface.
1379 if (faddr.s_addr == INADDR_ANY) {
1381 IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1382 if ((error = prison_get_ip4(cred, &faddr)) != 0)
1384 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1385 if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1387 faddr = satosin(&CK_STAILQ_FIRST(
1388 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1391 if (laddr.s_addr == INADDR_ANY) {
1392 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1394 * If the destination address is multicast and an outgoing
1395 * interface has been set as a multicast option, prefer the
1396 * address of that interface as our source address.
1398 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1399 inp->inp_moptions != NULL) {
1400 struct ip_moptions *imo;
1403 imo = inp->inp_moptions;
1404 if (imo->imo_multicast_ifp != NULL) {
1405 ifp = imo->imo_multicast_ifp;
1406 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1407 if (ia->ia_ifp == ifp &&
1408 prison_check_ip4(cred,
1409 &ia->ia_addr.sin_addr) == 0)
1413 error = EADDRNOTAVAIL;
1415 laddr = ia->ia_addr.sin_addr;
1425 oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1426 fport, laddr, lport, 0, NULL, M_NODOM);
1430 return (EADDRINUSE);
1433 struct sockaddr_in lsin, fsin;
1435 bzero(&lsin, sizeof(lsin));
1436 bzero(&fsin, sizeof(fsin));
1437 lsin.sin_family = AF_INET;
1438 lsin.sin_addr = laddr;
1439 fsin.sin_family = AF_INET;
1440 fsin.sin_addr = faddr;
1441 error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
1442 &lport, (struct sockaddr *)& fsin, fport, cred,
1443 INPLOOKUP_WILDCARD);
1447 *laddrp = laddr.s_addr;
1449 *faddrp = faddr.s_addr;
1455 in_pcbdisconnect(struct inpcb *inp)
1458 INP_WLOCK_ASSERT(inp);
1459 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1461 inp->inp_faddr.s_addr = INADDR_ANY;
1468 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1469 * For most protocols, this will be invoked immediately prior to calling
1470 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1471 * socket, in which case in_pcbfree() is deferred.
1474 in_pcbdetach(struct inpcb *inp)
1477 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1480 if (inp->inp_snd_tag != NULL)
1481 in_pcbdetach_txrtlmt(inp);
1483 inp->inp_socket->so_pcb = NULL;
1484 inp->inp_socket = NULL;
1488 * inpcb hash lookups are protected by SMR section.
1490 * Once desired pcb has been found, switching from SMR section to a pcb
1491 * lock is performed with inp_smr_lock(). We can not use INP_(W|R)LOCK
1492 * here because SMR is a critical section.
1493 * In 99%+ cases inp_smr_lock() would obtain the lock immediately.
1496 inp_lock(struct inpcb *inp, const inp_lookup_t lock)
1499 lock == INPLOOKUP_RLOCKPCB ?
1500 rw_rlock(&inp->inp_lock) : rw_wlock(&inp->inp_lock);
1504 inp_unlock(struct inpcb *inp, const inp_lookup_t lock)
1507 lock == INPLOOKUP_RLOCKPCB ?
1508 rw_runlock(&inp->inp_lock) : rw_wunlock(&inp->inp_lock);
1512 inp_trylock(struct inpcb *inp, const inp_lookup_t lock)
1515 return (lock == INPLOOKUP_RLOCKPCB ?
1516 rw_try_rlock(&inp->inp_lock) : rw_try_wlock(&inp->inp_lock));
1520 in_pcbrele(struct inpcb *inp, const inp_lookup_t lock)
1523 return (lock == INPLOOKUP_RLOCKPCB ?
1524 in_pcbrele_rlocked(inp) : in_pcbrele_wlocked(inp));
1528 _inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock, const int ignflags)
1531 MPASS(lock == INPLOOKUP_RLOCKPCB || lock == INPLOOKUP_WLOCKPCB);
1532 SMR_ASSERT_ENTERED(inp->inp_pcbinfo->ipi_smr);
1534 if (__predict_true(inp_trylock(inp, lock))) {
1535 if (__predict_false(inp->inp_flags & ignflags)) {
1536 smr_exit(inp->inp_pcbinfo->ipi_smr);
1537 inp_unlock(inp, lock);
1540 smr_exit(inp->inp_pcbinfo->ipi_smr);
1544 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1545 smr_exit(inp->inp_pcbinfo->ipi_smr);
1546 inp_lock(inp, lock);
1547 if (__predict_false(in_pcbrele(inp, lock)))
1550 * inp acquired through refcount & lock for sure didn't went
1551 * through uma_zfree(). However, it may have already went
1552 * through in_pcbfree() and has another reference, that
1553 * prevented its release by our in_pcbrele().
1555 if (__predict_false(inp->inp_flags & ignflags)) {
1556 inp_unlock(inp, lock);
1561 smr_exit(inp->inp_pcbinfo->ipi_smr);
1567 inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock)
1571 * in_pcblookup() family of functions ignore not only freed entries,
1572 * that may be found due to lockless access to the hash, but dropped
1575 return (_inp_smr_lock(inp, lock, INP_FREED | INP_DROPPED));
1579 * inp_next() - inpcb hash/list traversal iterator
1581 * Requires initialized struct inpcb_iterator for context.
1582 * The structure can be initialized with INP_ITERATOR() or INP_ALL_ITERATOR().
1584 * - Iterator can have either write-lock or read-lock semantics, that can not
1586 * - Iterator can iterate either over all pcbs list (INP_ALL_LIST), or through
1587 * a single hash slot. Note: only rip_input() does the latter.
1588 * - Iterator may have optional bool matching function. The matching function
1589 * will be executed for each inpcb in the SMR context, so it can not acquire
1590 * locks and can safely access only immutable fields of inpcb.
1592 * A fresh initialized iterator has NULL inpcb in its context and that
1593 * means that inp_next() call would return the very first inpcb on the list
1594 * locked with desired semantic. In all following calls the context pointer
1595 * shall hold the current inpcb pointer. The KPI user is not supposed to
1596 * unlock the current inpcb! Upon end of traversal inp_next() will return NULL
1597 * and write NULL to its context. After end of traversal an iterator can be
1600 * List traversals have the following features/constraints:
1601 * - New entries won't be seen, as they are always added to the head of a list.
1602 * - Removed entries won't stop traversal as long as they are not added to
1603 * a different list. This is violated by in_pcbrehash().
1605 #define II_LIST_FIRST(ipi, hash) \
1606 (((hash) == INP_ALL_LIST) ? \
1607 CK_LIST_FIRST(&(ipi)->ipi_listhead) : \
1608 CK_LIST_FIRST(&(ipi)->ipi_hashbase[(hash)]))
1609 #define II_LIST_NEXT(inp, hash) \
1610 (((hash) == INP_ALL_LIST) ? \
1611 CK_LIST_NEXT((inp), inp_list) : \
1612 CK_LIST_NEXT((inp), inp_hash))
1613 #define II_LOCK_ASSERT(inp, lock) \
1614 rw_assert(&(inp)->inp_lock, \
1615 (lock) == INPLOOKUP_RLOCKPCB ? RA_RLOCKED : RA_WLOCKED )
1617 inp_next(struct inpcb_iterator *ii)
1619 const struct inpcbinfo *ipi = ii->ipi;
1620 inp_match_t *match = ii->match;
1621 void *ctx = ii->ctx;
1622 inp_lookup_t lock = ii->lock;
1623 int hash = ii->hash;
1626 if (ii->inp == NULL) { /* First call. */
1627 smr_enter(ipi->ipi_smr);
1628 /* This is unrolled CK_LIST_FOREACH(). */
1629 for (inp = II_LIST_FIRST(ipi, hash);
1631 inp = II_LIST_NEXT(inp, hash)) {
1632 if (match != NULL && (match)(inp, ctx) == false)
1634 if (__predict_true(_inp_smr_lock(inp, lock, INP_FREED)))
1637 smr_enter(ipi->ipi_smr);
1638 MPASS(inp != II_LIST_FIRST(ipi, hash));
1639 inp = II_LIST_FIRST(ipi, hash);
1646 smr_exit(ipi->ipi_smr);
1653 /* Not a first call. */
1654 smr_enter(ipi->ipi_smr);
1657 II_LOCK_ASSERT(inp, lock);
1659 inp = II_LIST_NEXT(inp, hash);
1661 smr_exit(ipi->ipi_smr);
1665 if (match != NULL && (match)(inp, ctx) == false)
1668 if (__predict_true(inp_trylock(inp, lock))) {
1669 if (__predict_false(inp->inp_flags & INP_FREED)) {
1671 * Entries are never inserted in middle of a list, thus
1672 * as long as we are in SMR, we can continue traversal.
1673 * Jump to 'restart' should yield in the same result,
1674 * but could produce unnecessary looping. Could this
1675 * looping be unbound?
1677 inp_unlock(inp, lock);
1680 smr_exit(ipi->ipi_smr);
1686 * Can't obtain lock immediately, thus going hard. Once we exit the
1687 * SMR section we can no longer jump to 'next', and our only stable
1688 * anchoring point is ii->inp, which we keep locked for this case, so
1689 * we jump to 'restart'.
1691 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1692 smr_exit(ipi->ipi_smr);
1693 inp_lock(inp, lock);
1694 if (__predict_false(in_pcbrele(inp, lock))) {
1695 smr_enter(ipi->ipi_smr);
1699 * See comment in inp_smr_lock().
1701 if (__predict_false(inp->inp_flags & INP_FREED)) {
1702 inp_unlock(inp, lock);
1703 smr_enter(ipi->ipi_smr);
1710 inp_unlock(ii->inp, lock);
1717 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1718 * stability of an inpcb pointer despite the inpcb lock being released or
1719 * SMR section exited.
1721 * To free a reference later in_pcbrele_(r|w)locked() must be performed.
1724 in_pcbref(struct inpcb *inp)
1726 u_int old __diagused;
1728 old = refcount_acquire(&inp->inp_refcount);
1729 KASSERT(old > 0, ("%s: refcount 0", __func__));
1733 * Drop a refcount on an inpcb elevated using in_pcbref(), potentially
1734 * freeing the pcb, if the reference was very last.
1737 in_pcbrele_rlocked(struct inpcb *inp)
1740 INP_RLOCK_ASSERT(inp);
1742 if (refcount_release(&inp->inp_refcount) == 0)
1745 MPASS(inp->inp_flags & INP_FREED);
1746 MPASS(inp->inp_socket == NULL);
1747 MPASS(inp->inp_in_hpts == 0);
1749 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1754 in_pcbrele_wlocked(struct inpcb *inp)
1757 INP_WLOCK_ASSERT(inp);
1759 if (refcount_release(&inp->inp_refcount) == 0)
1762 MPASS(inp->inp_flags & INP_FREED);
1763 MPASS(inp->inp_socket == NULL);
1764 MPASS(inp->inp_in_hpts == 0);
1766 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1771 * Unconditionally schedule an inpcb to be freed by decrementing its
1772 * reference count, which should occur only after the inpcb has been detached
1773 * from its socket. If another thread holds a temporary reference (acquired
1774 * using in_pcbref()) then the free is deferred until that reference is
1775 * released using in_pcbrele_(r|w)locked(), but the inpcb is still unlocked.
1776 * Almost all work, including removal from global lists, is done in this
1777 * context, where the pcbinfo lock is held.
1780 in_pcbfree(struct inpcb *inp)
1782 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1784 struct ip_moptions *imo;
1787 struct ip6_moptions *im6o;
1790 INP_WLOCK_ASSERT(inp);
1791 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1792 KASSERT((inp->inp_flags & INP_FREED) == 0,
1793 ("%s: called twice for pcb %p", __func__, inp));
1795 inp->inp_flags |= INP_FREED;
1796 INP_INFO_WLOCK(pcbinfo);
1797 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1798 pcbinfo->ipi_count--;
1799 CK_LIST_REMOVE(inp, inp_list);
1800 INP_INFO_WUNLOCK(pcbinfo);
1802 if (inp->inp_flags & INP_INHASHLIST)
1805 RO_INVALIDATE_CACHE(&inp->inp_route);
1807 mac_inpcb_destroy(inp);
1809 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1810 if (inp->inp_sp != NULL)
1811 ipsec_delete_pcbpolicy(inp);
1814 if (inp->inp_options)
1815 (void)m_free(inp->inp_options);
1816 imo = inp->inp_moptions;
1819 if (inp->inp_vflag & INP_IPV6PROTO) {
1820 ip6_freepcbopts(inp->in6p_outputopts);
1821 im6o = inp->in6p_moptions;
1826 if (__predict_false(in_pcbrele_wlocked(inp) == false)) {
1830 ip6_freemoptions(im6o);
1833 inp_freemoptions(imo);
1835 /* Destruction is finalized in inpcb_dtor(). */
1839 inpcb_dtor(void *mem, int size, void *arg)
1841 struct inpcb *inp = mem;
1843 crfree(inp->inp_cred);
1845 inp->inp_cred = NULL;
1850 * Different protocols initialize their inpcbs differently - giving
1851 * different name to the lock. But they all are disposed the same.
1854 inpcb_fini(void *mem, int size)
1856 struct inpcb *inp = mem;
1858 INP_LOCK_DESTROY(inp);
1862 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1863 * port reservation, and preventing it from being returned by inpcb lookups.
1865 * It is used by TCP to mark an inpcb as unused and avoid future packet
1866 * delivery or event notification when a socket remains open but TCP has
1867 * closed. This might occur as a result of a shutdown()-initiated TCP close
1868 * or a RST on the wire, and allows the port binding to be reused while still
1869 * maintaining the invariant that so_pcb always points to a valid inpcb until
1872 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1873 * in_pcbnotifyall() and in_pcbpurgeif0()?
1876 in_pcbdrop(struct inpcb *inp)
1879 INP_WLOCK_ASSERT(inp);
1881 if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1882 MPASS(inp->inp_refcount > 1);
1885 inp->inp_flags |= INP_DROPPED;
1886 if (inp->inp_flags & INP_INHASHLIST)
1892 * Common routines to return the socket addresses associated with inpcbs.
1895 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1897 struct sockaddr_in *sin;
1899 sin = malloc(sizeof *sin, M_SONAME,
1901 sin->sin_family = AF_INET;
1902 sin->sin_len = sizeof(*sin);
1903 sin->sin_addr = *addr_p;
1904 sin->sin_port = port;
1906 return (struct sockaddr *)sin;
1910 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1913 struct in_addr addr;
1916 inp = sotoinpcb(so);
1917 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1920 port = inp->inp_lport;
1921 addr = inp->inp_laddr;
1924 *nam = in_sockaddr(port, &addr);
1929 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1932 struct in_addr addr;
1935 inp = sotoinpcb(so);
1936 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1939 port = inp->inp_fport;
1940 addr = inp->inp_faddr;
1943 *nam = in_sockaddr(port, &addr);
1948 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1949 struct inpcb *(*notify)(struct inpcb *, int))
1951 struct inpcb *inp, *inp_temp;
1953 INP_INFO_WLOCK(pcbinfo);
1954 CK_LIST_FOREACH_SAFE(inp, &pcbinfo->ipi_listhead, inp_list, inp_temp) {
1957 if ((inp->inp_vflag & INP_IPV4) == 0) {
1962 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1963 inp->inp_socket == NULL) {
1967 if ((*notify)(inp, errno))
1970 INP_INFO_WUNLOCK(pcbinfo);
1974 inp_v4_multi_match(const struct inpcb *inp, void *v __unused)
1977 if ((inp->inp_vflag & INP_IPV4) && inp->inp_moptions != NULL)
1984 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1986 struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
1987 inp_v4_multi_match, NULL);
1989 struct in_multi *inm;
1990 struct in_mfilter *imf;
1991 struct ip_moptions *imo;
1993 IN_MULTI_LOCK_ASSERT();
1995 while ((inp = inp_next(&inpi)) != NULL) {
1996 INP_WLOCK_ASSERT(inp);
1998 imo = inp->inp_moptions;
2000 * Unselect the outgoing interface if it is being
2003 if (imo->imo_multicast_ifp == ifp)
2004 imo->imo_multicast_ifp = NULL;
2007 * Drop multicast group membership if we joined
2008 * through the interface being detached.
2010 * XXX This can all be deferred to an epoch_call
2013 IP_MFILTER_FOREACH(imf, &imo->imo_head) {
2014 if ((inm = imf->imf_inm) == NULL)
2016 if (inm->inm_ifp != ifp)
2018 ip_mfilter_remove(&imo->imo_head, imf);
2019 in_leavegroup_locked(inm, NULL);
2020 ip_mfilter_free(imf);
2027 * Lookup a PCB based on the local address and port. Caller must hold the
2028 * hash lock. No inpcb locks or references are acquired.
2030 #define INP_LOOKUP_MAPPED_PCB_COST 3
2032 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
2033 u_short lport, int lookupflags, struct ucred *cred)
2037 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
2043 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2044 ("%s: invalid lookup flags %d", __func__, lookupflags));
2045 INP_HASH_LOCK_ASSERT(pcbinfo);
2047 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
2048 struct inpcbhead *head;
2050 * Look for an unconnected (wildcard foreign addr) PCB that
2051 * matches the local address and port we're looking for.
2053 head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2054 pcbinfo->ipi_hashmask)];
2055 CK_LIST_FOREACH(inp, head, inp_hash) {
2057 /* XXX inp locking */
2058 if ((inp->inp_vflag & INP_IPV4) == 0)
2061 if (inp->inp_faddr.s_addr == INADDR_ANY &&
2062 inp->inp_laddr.s_addr == laddr.s_addr &&
2063 inp->inp_lport == lport) {
2067 if (prison_equal_ip4(cred->cr_prison,
2068 inp->inp_cred->cr_prison))
2077 struct inpcbporthead *porthash;
2078 struct inpcbport *phd;
2079 struct inpcb *match = NULL;
2081 * Best fit PCB lookup.
2083 * First see if this local port is in use by looking on the
2086 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2087 pcbinfo->ipi_porthashmask)];
2088 CK_LIST_FOREACH(phd, porthash, phd_hash) {
2089 if (phd->phd_port == lport)
2094 * Port is in use by one or more PCBs. Look for best
2097 CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2099 if (!prison_equal_ip4(inp->inp_cred->cr_prison,
2103 /* XXX inp locking */
2104 if ((inp->inp_vflag & INP_IPV4) == 0)
2107 * We never select the PCB that has
2108 * INP_IPV6 flag and is bound to :: if
2109 * we have another PCB which is bound
2110 * to 0.0.0.0. If a PCB has the
2111 * INP_IPV6 flag, then we set its cost
2112 * higher than IPv4 only PCBs.
2114 * Note that the case only happens
2115 * when a socket is bound to ::, under
2116 * the condition that the use of the
2117 * mapped address is allowed.
2119 if ((inp->inp_vflag & INP_IPV6) != 0)
2120 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2122 if (inp->inp_faddr.s_addr != INADDR_ANY)
2124 if (inp->inp_laddr.s_addr != INADDR_ANY) {
2125 if (laddr.s_addr == INADDR_ANY)
2127 else if (inp->inp_laddr.s_addr != laddr.s_addr)
2130 if (laddr.s_addr != INADDR_ANY)
2133 if (wildcard < matchwild) {
2135 matchwild = wildcard;
2144 #undef INP_LOOKUP_MAPPED_PCB_COST
2147 in_pcblookup_lb_numa_match(const struct inpcblbgroup *grp, int domain)
2149 return (domain == M_NODOM || domain == grp->il_numa_domain);
2152 static struct inpcb *
2153 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
2154 const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
2155 uint16_t fport, int lookupflags, int domain)
2157 const struct inpcblbgrouphead *hdr;
2158 struct inpcblbgroup *grp;
2159 struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
2161 INP_HASH_LOCK_ASSERT(pcbinfo);
2163 hdr = &pcbinfo->ipi_lbgrouphashbase[
2164 INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
2167 * Search for an LB group match based on the following criteria:
2168 * - prefer jailed groups to non-jailed groups
2169 * - prefer exact source address matches to wildcard matches
2170 * - prefer groups bound to the specified NUMA domain
2172 jail_exact = jail_wild = local_exact = local_wild = NULL;
2173 CK_LIST_FOREACH(grp, hdr, il_list) {
2177 if (!(grp->il_vflag & INP_IPV4))
2180 if (grp->il_lport != lport)
2183 injail = prison_flag(grp->il_cred, PR_IP4) != 0;
2184 if (injail && prison_check_ip4_locked(grp->il_cred->cr_prison,
2188 if (grp->il_laddr.s_addr == laddr->s_addr) {
2191 if (in_pcblookup_lb_numa_match(grp, domain))
2192 /* This is a perfect match. */
2194 } else if (local_exact == NULL ||
2195 in_pcblookup_lb_numa_match(grp, domain)) {
2198 } else if (grp->il_laddr.s_addr == INADDR_ANY &&
2199 (lookupflags & INPLOOKUP_WILDCARD) != 0) {
2201 if (jail_wild == NULL ||
2202 in_pcblookup_lb_numa_match(grp, domain))
2204 } else if (local_wild == NULL ||
2205 in_pcblookup_lb_numa_match(grp, domain)) {
2211 if (jail_exact != NULL)
2213 else if (jail_wild != NULL)
2215 else if (local_exact != NULL)
2222 return (grp->il_inp[INP_PCBLBGROUP_PKTHASH(faddr, lport, fport) %
2227 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
2228 * that the caller has either locked the hash list, which usually happens
2229 * for bind(2) operations, or is in SMR section, which happens when sorting
2230 * out incoming packets.
2232 static struct inpcb *
2233 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2234 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2235 struct ifnet *ifp, uint8_t numa_domain)
2237 struct inpcbhead *head;
2238 struct inpcb *inp, *tmpinp;
2239 u_short fport = fport_arg, lport = lport_arg;
2241 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2242 ("%s: invalid lookup flags %d", __func__, lookupflags));
2243 INP_HASH_LOCK_ASSERT(pcbinfo);
2246 * First look for an exact match.
2249 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&faddr, lport, fport,
2250 pcbinfo->ipi_hashmask)];
2251 CK_LIST_FOREACH(inp, head, inp_hash) {
2253 /* XXX inp locking */
2254 if ((inp->inp_vflag & INP_IPV4) == 0)
2257 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2258 inp->inp_laddr.s_addr == laddr.s_addr &&
2259 inp->inp_fport == fport &&
2260 inp->inp_lport == lport) {
2262 * XXX We should be able to directly return
2263 * the inp here, without any checks.
2264 * Well unless both bound with SO_REUSEPORT?
2266 if (prison_flag(inp->inp_cred, PR_IP4))
2276 * Then look for a wildcard match, if requested.
2278 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2279 struct inpcb *local_wild = NULL, *local_exact = NULL;
2281 struct inpcb *local_wild_mapped = NULL;
2283 struct inpcb *jail_wild = NULL;
2287 * First see if an LB group matches the request before scanning
2288 * all sockets on this port.
2290 inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2291 fport, lookupflags, numa_domain);
2296 * Order of socket selection - we always prefer jails.
2297 * 1. jailed, non-wild.
2299 * 3. non-jailed, non-wild.
2300 * 4. non-jailed, wild.
2303 head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2304 pcbinfo->ipi_hashmask)];
2305 CK_LIST_FOREACH(inp, head, inp_hash) {
2307 /* XXX inp locking */
2308 if ((inp->inp_vflag & INP_IPV4) == 0)
2311 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2312 inp->inp_lport != lport)
2315 injail = prison_flag(inp->inp_cred, PR_IP4);
2317 if (prison_check_ip4_locked(
2318 inp->inp_cred->cr_prison, &laddr) != 0)
2321 if (local_exact != NULL)
2325 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2330 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2332 /* XXX inp locking, NULL check */
2333 if (inp->inp_vflag & INP_IPV6PROTO)
2334 local_wild_mapped = inp;
2342 } /* LIST_FOREACH */
2343 if (jail_wild != NULL)
2345 if (local_exact != NULL)
2346 return (local_exact);
2347 if (local_wild != NULL)
2348 return (local_wild);
2350 if (local_wild_mapped != NULL)
2351 return (local_wild_mapped);
2353 } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2359 * Lookup PCB in hash list, using pcbinfo tables. This variation locks the
2360 * hash list lock, and will return the inpcb locked (i.e., requires
2361 * INPLOOKUP_LOCKPCB).
2363 static struct inpcb *
2364 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2365 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2366 struct ifnet *ifp, uint8_t numa_domain)
2370 smr_enter(pcbinfo->ipi_smr);
2371 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2372 lookupflags & INPLOOKUP_WILDCARD, ifp, numa_domain);
2374 if (__predict_false(inp_smr_lock(inp,
2375 (lookupflags & INPLOOKUP_LOCKMASK)) == false))
2378 smr_exit(pcbinfo->ipi_smr);
2384 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2385 * from which a pre-calculated hash value may be extracted.
2388 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2389 struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2392 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2393 ("%s: invalid lookup flags %d", __func__, lookupflags));
2394 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2395 ("%s: LOCKPCB not set", __func__));
2397 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2398 lookupflags, ifp, M_NODOM));
2402 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2403 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2404 struct ifnet *ifp, struct mbuf *m)
2407 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2408 ("%s: invalid lookup flags %d", __func__, lookupflags));
2409 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2410 ("%s: LOCKPCB not set", __func__));
2412 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2413 lookupflags, ifp, m->m_pkthdr.numa_domain));
2418 * Insert PCB onto various hash lists.
2421 in_pcbinshash(struct inpcb *inp)
2423 struct inpcbhead *pcbhash;
2424 struct inpcbporthead *pcbporthash;
2425 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2426 struct inpcbport *phd;
2428 INP_WLOCK_ASSERT(inp);
2429 INP_HASH_WLOCK_ASSERT(pcbinfo);
2431 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2432 ("in_pcbinshash: INP_INHASHLIST"));
2435 if (inp->inp_vflag & INP_IPV6)
2436 pcbhash = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2437 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2440 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2441 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2443 pcbporthash = &pcbinfo->ipi_porthashbase[
2444 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2447 * Add entry to load balance group.
2448 * Only do this if SO_REUSEPORT_LB is set.
2450 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0) {
2451 int error = in_pcbinslbgrouphash(inp, M_NODOM);
2457 * Go through port list and look for a head for this lport.
2459 CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2460 if (phd->phd_port == inp->inp_lport)
2465 * If none exists, malloc one and tack it on.
2468 phd = uma_zalloc_smr(pcbinfo->ipi_portzone, M_NOWAIT);
2470 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2471 in_pcbremlbgrouphash(inp);
2474 phd->phd_port = inp->inp_lport;
2475 CK_LIST_INIT(&phd->phd_pcblist);
2476 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2479 CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2480 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2481 inp->inp_flags |= INP_INHASHLIST;
2487 in_pcbremhash(struct inpcb *inp)
2489 struct inpcbport *phd = inp->inp_phd;
2491 INP_WLOCK_ASSERT(inp);
2492 MPASS(inp->inp_flags & INP_INHASHLIST);
2494 INP_HASH_WLOCK(inp->inp_pcbinfo);
2495 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2496 in_pcbremlbgrouphash(inp);
2497 CK_LIST_REMOVE(inp, inp_hash);
2498 CK_LIST_REMOVE(inp, inp_portlist);
2499 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2500 CK_LIST_REMOVE(phd, phd_hash);
2501 uma_zfree_smr(inp->inp_pcbinfo->ipi_portzone, phd);
2503 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
2504 inp->inp_flags &= ~INP_INHASHLIST;
2508 * Move PCB to the proper hash bucket when { faddr, fport } have been
2509 * changed. NOTE: This does not handle the case of the lport changing (the
2510 * hashed port list would have to be updated as well), so the lport must
2511 * not change after in_pcbinshash() has been called.
2513 * XXXGL: a race between this function and SMR-protected hash iterator
2514 * will lead to iterator traversing a possibly wrong hash list. However,
2515 * this race should have been here since change from rwlock to epoch.
2518 in_pcbrehash(struct inpcb *inp)
2520 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2521 struct inpcbhead *head;
2523 INP_WLOCK_ASSERT(inp);
2524 INP_HASH_WLOCK_ASSERT(pcbinfo);
2526 KASSERT(inp->inp_flags & INP_INHASHLIST,
2527 ("in_pcbrehash: !INP_INHASHLIST"));
2530 if (inp->inp_vflag & INP_IPV6)
2531 head = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2532 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2535 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2536 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2538 CK_LIST_REMOVE(inp, inp_hash);
2539 CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2543 * Check for alternatives when higher level complains
2544 * about service problems. For now, invalidate cached
2545 * routing information. If the route was created dynamically
2546 * (by a redirect), time to try a default gateway again.
2549 in_losing(struct inpcb *inp)
2552 RO_INVALIDATE_CACHE(&inp->inp_route);
2557 * A set label operation has occurred at the socket layer, propagate the
2558 * label change into the in_pcb for the socket.
2561 in_pcbsosetlabel(struct socket *so)
2566 inp = sotoinpcb(so);
2567 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2571 mac_inpcb_sosetlabel(so, inp);
2578 inp_wlock(struct inpcb *inp)
2585 inp_wunlock(struct inpcb *inp)
2592 inp_rlock(struct inpcb *inp)
2599 inp_runlock(struct inpcb *inp)
2605 #ifdef INVARIANT_SUPPORT
2607 inp_lock_assert(struct inpcb *inp)
2610 INP_WLOCK_ASSERT(inp);
2614 inp_unlock_assert(struct inpcb *inp)
2617 INP_UNLOCK_ASSERT(inp);
2622 inp_apply_all(struct inpcbinfo *pcbinfo,
2623 void (*func)(struct inpcb *, void *), void *arg)
2625 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2626 INPLOOKUP_WLOCKPCB);
2629 while ((inp = inp_next(&inpi)) != NULL)
2634 inp_inpcbtosocket(struct inpcb *inp)
2637 INP_WLOCK_ASSERT(inp);
2638 return (inp->inp_socket);
2642 inp_inpcbtotcpcb(struct inpcb *inp)
2645 INP_WLOCK_ASSERT(inp);
2646 return ((struct tcpcb *)inp->inp_ppcb);
2650 inp_ip_tos_get(const struct inpcb *inp)
2653 return (inp->inp_ip_tos);
2657 inp_ip_tos_set(struct inpcb *inp, int val)
2660 inp->inp_ip_tos = val;
2664 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2665 uint32_t *faddr, uint16_t *fp)
2668 INP_LOCK_ASSERT(inp);
2669 *laddr = inp->inp_laddr.s_addr;
2670 *faddr = inp->inp_faddr.s_addr;
2671 *lp = inp->inp_lport;
2672 *fp = inp->inp_fport;
2676 so_sotoinpcb(struct socket *so)
2679 return (sotoinpcb(so));
2683 * Create an external-format (``xinpcb'') structure using the information in
2684 * the kernel-format in_pcb structure pointed to by inp. This is done to
2685 * reduce the spew of irrelevant information over this interface, to isolate
2686 * user code from changes in the kernel structure, and potentially to provide
2687 * information-hiding if we decide that some of this information should be
2688 * hidden from users.
2691 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2694 bzero(xi, sizeof(*xi));
2695 xi->xi_len = sizeof(struct xinpcb);
2696 if (inp->inp_socket)
2697 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2698 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2699 xi->inp_gencnt = inp->inp_gencnt;
2700 xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2701 xi->inp_flow = inp->inp_flow;
2702 xi->inp_flowid = inp->inp_flowid;
2703 xi->inp_flowtype = inp->inp_flowtype;
2704 xi->inp_flags = inp->inp_flags;
2705 xi->inp_flags2 = inp->inp_flags2;
2706 xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2707 xi->in6p_cksum = inp->in6p_cksum;
2708 xi->in6p_hops = inp->in6p_hops;
2709 xi->inp_ip_tos = inp->inp_ip_tos;
2710 xi->inp_vflag = inp->inp_vflag;
2711 xi->inp_ip_ttl = inp->inp_ip_ttl;
2712 xi->inp_ip_p = inp->inp_ip_p;
2713 xi->inp_ip_minttl = inp->inp_ip_minttl;
2717 sysctl_setsockopt(SYSCTL_HANDLER_ARGS, struct inpcbinfo *pcbinfo,
2718 int (*ctloutput_set)(struct inpcb *, struct sockopt *))
2720 struct sockopt sopt;
2721 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2722 INPLOOKUP_WLOCKPCB);
2724 struct sockopt_parameters *params;
2729 if (req->oldptr != NULL || req->oldlen != 0)
2731 if (req->newptr == NULL)
2733 if (req->newlen > sizeof(buf))
2735 error = SYSCTL_IN(req, buf, req->newlen);
2738 if (req->newlen < sizeof(struct sockopt_parameters))
2740 params = (struct sockopt_parameters *)buf;
2741 sopt.sopt_level = params->sop_level;
2742 sopt.sopt_name = params->sop_optname;
2743 sopt.sopt_dir = SOPT_SET;
2744 sopt.sopt_val = params->sop_optval;
2745 sopt.sopt_valsize = req->newlen - sizeof(struct sockopt_parameters);
2746 sopt.sopt_td = NULL;
2748 if (params->sop_inc.inc_flags & INC_ISIPV6) {
2749 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_laddr))
2750 params->sop_inc.inc6_laddr.s6_addr16[1] =
2751 htons(params->sop_inc.inc6_zoneid & 0xffff);
2752 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_faddr))
2753 params->sop_inc.inc6_faddr.s6_addr16[1] =
2754 htons(params->sop_inc.inc6_zoneid & 0xffff);
2757 if (params->sop_inc.inc_lport != htons(0)) {
2758 if (params->sop_inc.inc_fport == htons(0))
2759 inpi.hash = INP_PCBHASH_WILD(params->sop_inc.inc_lport,
2760 pcbinfo->ipi_hashmask);
2763 if (params->sop_inc.inc_flags & INC_ISIPV6)
2764 inpi.hash = INP6_PCBHASH(
2765 ¶ms->sop_inc.inc6_faddr,
2766 params->sop_inc.inc_lport,
2767 params->sop_inc.inc_fport,
2768 pcbinfo->ipi_hashmask);
2771 inpi.hash = INP_PCBHASH(
2772 ¶ms->sop_inc.inc_faddr,
2773 params->sop_inc.inc_lport,
2774 params->sop_inc.inc_fport,
2775 pcbinfo->ipi_hashmask);
2777 while ((inp = inp_next(&inpi)) != NULL)
2778 if (inp->inp_gencnt == params->sop_id) {
2779 if (inp->inp_flags & INP_DROPPED) {
2781 return (ECONNRESET);
2783 so = inp->inp_socket;
2784 KASSERT(so != NULL, ("inp_socket == NULL"));
2786 error = (*ctloutput_set)(inp, &sopt);
2797 db_print_indent(int indent)
2801 for (i = 0; i < indent; i++)
2806 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2808 char faddr_str[48], laddr_str[48];
2810 db_print_indent(indent);
2811 db_printf("%s at %p\n", name, inc);
2816 if (inc->inc_flags & INC_ISIPV6) {
2818 ip6_sprintf(laddr_str, &inc->inc6_laddr);
2819 ip6_sprintf(faddr_str, &inc->inc6_faddr);
2824 inet_ntoa_r(inc->inc_laddr, laddr_str);
2825 inet_ntoa_r(inc->inc_faddr, faddr_str);
2827 db_print_indent(indent);
2828 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
2829 ntohs(inc->inc_lport));
2830 db_print_indent(indent);
2831 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
2832 ntohs(inc->inc_fport));
2836 db_print_inpflags(int inp_flags)
2841 if (inp_flags & INP_RECVOPTS) {
2842 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2845 if (inp_flags & INP_RECVRETOPTS) {
2846 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2849 if (inp_flags & INP_RECVDSTADDR) {
2850 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2853 if (inp_flags & INP_ORIGDSTADDR) {
2854 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2857 if (inp_flags & INP_HDRINCL) {
2858 db_printf("%sINP_HDRINCL", comma ? ", " : "");
2861 if (inp_flags & INP_HIGHPORT) {
2862 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2865 if (inp_flags & INP_LOWPORT) {
2866 db_printf("%sINP_LOWPORT", comma ? ", " : "");
2869 if (inp_flags & INP_ANONPORT) {
2870 db_printf("%sINP_ANONPORT", comma ? ", " : "");
2873 if (inp_flags & INP_RECVIF) {
2874 db_printf("%sINP_RECVIF", comma ? ", " : "");
2877 if (inp_flags & INP_MTUDISC) {
2878 db_printf("%sINP_MTUDISC", comma ? ", " : "");
2881 if (inp_flags & INP_RECVTTL) {
2882 db_printf("%sINP_RECVTTL", comma ? ", " : "");
2885 if (inp_flags & INP_DONTFRAG) {
2886 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2889 if (inp_flags & INP_RECVTOS) {
2890 db_printf("%sINP_RECVTOS", comma ? ", " : "");
2893 if (inp_flags & IN6P_IPV6_V6ONLY) {
2894 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2897 if (inp_flags & IN6P_PKTINFO) {
2898 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2901 if (inp_flags & IN6P_HOPLIMIT) {
2902 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2905 if (inp_flags & IN6P_HOPOPTS) {
2906 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2909 if (inp_flags & IN6P_DSTOPTS) {
2910 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2913 if (inp_flags & IN6P_RTHDR) {
2914 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2917 if (inp_flags & IN6P_RTHDRDSTOPTS) {
2918 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2921 if (inp_flags & IN6P_TCLASS) {
2922 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2925 if (inp_flags & IN6P_AUTOFLOWLABEL) {
2926 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2929 if (inp_flags & INP_ONESBCAST) {
2930 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2933 if (inp_flags & INP_DROPPED) {
2934 db_printf("%sINP_DROPPED", comma ? ", " : "");
2937 if (inp_flags & INP_SOCKREF) {
2938 db_printf("%sINP_SOCKREF", comma ? ", " : "");
2941 if (inp_flags & IN6P_RFC2292) {
2942 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2945 if (inp_flags & IN6P_MTU) {
2946 db_printf("IN6P_MTU%s", comma ? ", " : "");
2952 db_print_inpvflag(u_char inp_vflag)
2957 if (inp_vflag & INP_IPV4) {
2958 db_printf("%sINP_IPV4", comma ? ", " : "");
2961 if (inp_vflag & INP_IPV6) {
2962 db_printf("%sINP_IPV6", comma ? ", " : "");
2965 if (inp_vflag & INP_IPV6PROTO) {
2966 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2972 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2975 db_print_indent(indent);
2976 db_printf("%s at %p\n", name, inp);
2980 db_print_indent(indent);
2981 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2983 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2985 db_print_indent(indent);
2986 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
2987 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2989 db_print_indent(indent);
2990 db_printf("inp_label: %p inp_flags: 0x%x (",
2991 inp->inp_label, inp->inp_flags);
2992 db_print_inpflags(inp->inp_flags);
2995 db_print_indent(indent);
2996 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
2998 db_print_inpvflag(inp->inp_vflag);
3001 db_print_indent(indent);
3002 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
3003 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3005 db_print_indent(indent);
3007 if (inp->inp_vflag & INP_IPV6) {
3008 db_printf("in6p_options: %p in6p_outputopts: %p "
3009 "in6p_moptions: %p\n", inp->in6p_options,
3010 inp->in6p_outputopts, inp->in6p_moptions);
3011 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
3012 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3017 db_printf("inp_ip_tos: %d inp_ip_options: %p "
3018 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3019 inp->inp_options, inp->inp_moptions);
3022 db_print_indent(indent);
3023 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
3024 (uintmax_t)inp->inp_gencnt);
3027 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3032 db_printf("usage: show inpcb <addr>\n");
3035 inp = (struct inpcb *)addr;
3037 db_print_inpcb(inp, "inpcb", 0);
3043 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3047 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3049 union if_snd_tag_modify_params params = {
3050 .rate_limit.max_rate = max_pacing_rate,
3051 .rate_limit.flags = M_NOWAIT,
3053 struct m_snd_tag *mst;
3056 mst = inp->inp_snd_tag;
3060 if (mst->sw->snd_tag_modify == NULL) {
3063 error = mst->sw->snd_tag_modify(mst, ¶ms);
3069 * Query existing TX rate limit based on the existing
3070 * "inp->inp_snd_tag", if any.
3073 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3075 union if_snd_tag_query_params params = { };
3076 struct m_snd_tag *mst;
3079 mst = inp->inp_snd_tag;
3083 if (mst->sw->snd_tag_query == NULL) {
3086 error = mst->sw->snd_tag_query(mst, ¶ms);
3087 if (error == 0 && p_max_pacing_rate != NULL)
3088 *p_max_pacing_rate = params.rate_limit.max_rate;
3094 * Query existing TX queue level based on the existing
3095 * "inp->inp_snd_tag", if any.
3098 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3100 union if_snd_tag_query_params params = { };
3101 struct m_snd_tag *mst;
3104 mst = inp->inp_snd_tag;
3108 if (mst->sw->snd_tag_query == NULL)
3109 return (EOPNOTSUPP);
3111 error = mst->sw->snd_tag_query(mst, ¶ms);
3112 if (error == 0 && p_txqueue_level != NULL)
3113 *p_txqueue_level = params.rate_limit.queue_level;
3118 * Allocate a new TX rate limit send tag from the network interface
3119 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3122 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3123 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
3126 union if_snd_tag_alloc_params params = {
3127 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3128 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3129 .rate_limit.hdr.flowid = flowid,
3130 .rate_limit.hdr.flowtype = flowtype,
3131 .rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3132 .rate_limit.max_rate = max_pacing_rate,
3133 .rate_limit.flags = M_NOWAIT,
3137 INP_WLOCK_ASSERT(inp);
3140 * If there is already a send tag, or the INP is being torn
3141 * down, allocating a new send tag is not allowed. Else send
3144 if (*st != NULL || (inp->inp_flags & INP_DROPPED) != 0)
3147 error = m_snd_tag_alloc(ifp, ¶ms, st);
3150 counter_u64_add(rate_limit_set_ok, 1);
3151 counter_u64_add(rate_limit_active, 1);
3152 } else if (error != EOPNOTSUPP)
3153 counter_u64_add(rate_limit_alloc_fail, 1);
3159 in_pcbdetach_tag(struct m_snd_tag *mst)
3162 m_snd_tag_rele(mst);
3164 counter_u64_add(rate_limit_active, -1);
3169 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3173 in_pcbdetach_txrtlmt(struct inpcb *inp)
3175 struct m_snd_tag *mst;
3177 INP_WLOCK_ASSERT(inp);
3179 mst = inp->inp_snd_tag;
3180 inp->inp_snd_tag = NULL;
3185 m_snd_tag_rele(mst);
3187 counter_u64_add(rate_limit_active, -1);
3192 in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
3197 * If the existing send tag is for the wrong interface due to
3198 * a route change, first drop the existing tag. Set the
3199 * CHANGED flag so that we will keep trying to allocate a new
3200 * tag if we fail to allocate one this time.
3202 if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
3203 in_pcbdetach_txrtlmt(inp);
3204 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3208 * NOTE: When attaching to a network interface a reference is
3209 * made to ensure the network interface doesn't go away until
3210 * all ratelimit connections are gone. The network interface
3211 * pointers compared below represent valid network interfaces,
3212 * except when comparing towards NULL.
3214 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3216 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3217 if (inp->inp_snd_tag != NULL)
3218 in_pcbdetach_txrtlmt(inp);
3220 } else if (inp->inp_snd_tag == NULL) {
3222 * In order to utilize packet pacing with RSS, we need
3223 * to wait until there is a valid RSS hash before we
3226 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3229 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3230 mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
3233 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3235 if (error == 0 || error == EOPNOTSUPP)
3236 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3242 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3243 * is set in the fast path and will attach/detach/modify the TX rate
3244 * limit send tag based on the socket's so_max_pacing_rate value.
3247 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3249 struct socket *socket;
3250 uint32_t max_pacing_rate;
3256 socket = inp->inp_socket;
3260 if (!INP_WLOCKED(inp)) {
3262 * NOTE: If the write locking fails, we need to bail
3263 * out and use the non-ratelimited ring for the
3264 * transmit until there is a new chance to get the
3267 if (!INP_TRY_UPGRADE(inp))
3275 * NOTE: The so_max_pacing_rate value is read unlocked,
3276 * because atomic updates are not required since the variable
3277 * is checked at every mbuf we send. It is assumed that the
3278 * variable read itself will be atomic.
3280 max_pacing_rate = socket->so_max_pacing_rate;
3282 in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3289 * Track route changes for TX rate limiting.
3292 in_pcboutput_eagain(struct inpcb *inp)
3299 if (inp->inp_snd_tag == NULL)
3302 if (!INP_WLOCKED(inp)) {
3304 * NOTE: If the write locking fails, we need to bail
3305 * out and use the non-ratelimited ring for the
3306 * transmit until there is a new chance to get the
3309 if (!INP_TRY_UPGRADE(inp))
3316 /* detach rate limiting */
3317 in_pcbdetach_txrtlmt(inp);
3319 /* make sure new mbuf send tag allocation is made */
3320 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3330 rate_limit_new = counter_u64_alloc(M_WAITOK);
3331 rate_limit_chg = counter_u64_alloc(M_WAITOK);
3332 rate_limit_active = counter_u64_alloc(M_WAITOK);
3333 rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
3334 rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
3337 SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3339 #endif /* RATELIMIT */