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.
8 * Copyright (c) 2021-2022 Gleb Smirnoff <glebius@FreeBSD.org>
11 * Portions of this software were developed by Robert N. M. Watson under
12 * contract to Juniper Networks, Inc.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)in_pcb.c 8.4 (Berkeley) 5/24/95
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
45 #include "opt_ipsec.h"
47 #include "opt_inet6.h"
48 #include "opt_ratelimit.h"
49 #include "opt_route.h"
52 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/libkern.h>
57 #include <sys/malloc.h>
59 #include <sys/eventhandler.h>
60 #include <sys/domain.h>
61 #include <sys/protosw.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_private.h>
83 #include <net/if_types.h>
84 #include <net/if_llatbl.h>
85 #include <net/route.h>
86 #include <net/rss_config.h>
89 #if defined(INET) || defined(INET6)
90 #include <netinet/in.h>
91 #include <netinet/in_pcb.h>
92 #include <netinet/in_pcb_var.h>
93 #include <netinet/tcp.h>
95 #include <netinet/in_var.h>
96 #include <netinet/in_fib.h>
98 #include <netinet/ip_var.h>
100 #include <netinet/ip6.h>
101 #include <netinet6/in6_pcb.h>
102 #include <netinet6/in6_var.h>
103 #include <netinet6/ip6_var.h>
105 #include <net/route/nhop.h>
108 #include <netipsec/ipsec_support.h>
110 #include <security/mac/mac_framework.h>
112 #define INPCBLBGROUP_SIZMIN 8
113 #define INPCBLBGROUP_SIZMAX 256
114 #define INP_FREED 0x00000200 /* See in_pcb.h. */
117 * These configure the range of local port addresses assigned to
118 * "unspecified" outgoing connections/packets/whatever.
120 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1; /* 1023 */
121 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART; /* 600 */
122 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST; /* 10000 */
123 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST; /* 65535 */
124 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO; /* 49152 */
125 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO; /* 65535 */
128 * Reserved ports accessible only to root. There are significant
129 * security considerations that must be accounted for when changing these,
130 * but the security benefits can be great. Please be careful.
132 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1; /* 1023 */
133 VNET_DEFINE(int, ipport_reservedlow);
135 /* Enable random ephemeral port allocation by default. */
136 VNET_DEFINE(int, ipport_randomized) = 1;
139 static struct inpcb *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
140 struct in_addr faddr, u_int fport_arg,
141 struct in_addr laddr, u_int lport_arg,
142 int lookupflags, uint8_t numa_domain);
144 #define RANGECHK(var, min, max) \
145 if ((var) < (min)) { (var) = (min); } \
146 else if ((var) > (max)) { (var) = (max); }
149 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
153 error = sysctl_handle_int(oidp, arg1, arg2, req);
155 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
156 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
157 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
158 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
159 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
160 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
167 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
168 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
171 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
172 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
173 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
175 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
176 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
177 &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
179 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
180 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
181 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
183 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
184 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
185 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
187 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
188 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
189 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
191 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
192 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
193 &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
195 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
196 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
197 &VNET_NAME(ipport_reservedhigh), 0, "");
198 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
199 CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
200 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
201 CTLFLAG_VNET | CTLFLAG_RW,
202 &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
205 counter_u64_t rate_limit_new;
206 counter_u64_t rate_limit_chg;
207 counter_u64_t rate_limit_active;
208 counter_u64_t rate_limit_alloc_fail;
209 counter_u64_t rate_limit_set_ok;
211 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
213 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
214 &rate_limit_active, "Active rate limited connections");
215 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
216 &rate_limit_alloc_fail, "Rate limited connection failures");
217 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
218 &rate_limit_set_ok, "Rate limited setting succeeded");
219 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
220 &rate_limit_new, "Total Rate limit new attempts");
221 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
222 &rate_limit_chg, "Total Rate limited change attempts");
224 #endif /* RATELIMIT */
228 VNET_DEFINE(uint32_t, in_pcbhashseed);
230 in_pcbhashseed_init(void)
233 V_in_pcbhashseed = arc4random();
235 VNET_SYSINIT(in_pcbhashseed_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
236 in_pcbhashseed_init, 0);
238 static void in_pcbremhash(struct inpcb *);
241 * in_pcb.c: manage the Protocol Control Blocks.
243 * NOTE: It is assumed that most of these functions will be called with
244 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
245 * functions often modify hash chains or addresses in pcbs.
248 static struct inpcblbgroup *
249 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, struct ucred *cred,
250 u_char vflag, uint16_t port, const union in_dependaddr *addr, int size,
253 struct inpcblbgroup *grp;
256 bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
257 grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
260 grp->il_cred = crhold(cred);
261 grp->il_vflag = vflag;
262 grp->il_lport = port;
263 grp->il_numa_domain = numa_domain;
264 grp->il_dependladdr = *addr;
265 grp->il_inpsiz = size;
266 CK_LIST_INSERT_HEAD(hdr, grp, il_list);
271 in_pcblbgroup_free_deferred(epoch_context_t ctx)
273 struct inpcblbgroup *grp;
275 grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
276 crfree(grp->il_cred);
281 in_pcblbgroup_free(struct inpcblbgroup *grp)
284 CK_LIST_REMOVE(grp, il_list);
285 NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
288 static struct inpcblbgroup *
289 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
290 struct inpcblbgroup *old_grp, int size)
292 struct inpcblbgroup *grp;
295 grp = in_pcblbgroup_alloc(hdr, old_grp->il_cred, old_grp->il_vflag,
296 old_grp->il_lport, &old_grp->il_dependladdr, size,
297 old_grp->il_numa_domain);
301 KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
302 ("invalid new local group size %d and old local group count %d",
303 grp->il_inpsiz, old_grp->il_inpcnt));
305 for (i = 0; i < old_grp->il_inpcnt; ++i)
306 grp->il_inp[i] = old_grp->il_inp[i];
307 grp->il_inpcnt = old_grp->il_inpcnt;
308 in_pcblbgroup_free(old_grp);
313 * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
314 * and shrink group if possible.
317 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
320 struct inpcblbgroup *grp, *new_grp;
323 for (; i + 1 < grp->il_inpcnt; ++i)
324 grp->il_inp[i] = grp->il_inp[i + 1];
327 if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
328 grp->il_inpcnt <= grp->il_inpsiz / 4) {
329 /* Shrink this group. */
330 new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
337 * Add PCB to load balance group for SO_REUSEPORT_LB option.
340 in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
342 const static struct timeval interval = { 60, 0 };
343 static struct timeval lastprint;
344 struct inpcbinfo *pcbinfo;
345 struct inpcblbgrouphead *hdr;
346 struct inpcblbgroup *grp;
349 pcbinfo = inp->inp_pcbinfo;
351 INP_WLOCK_ASSERT(inp);
352 INP_HASH_WLOCK_ASSERT(pcbinfo);
356 * Don't allow IPv4 mapped INET6 wild socket.
358 if ((inp->inp_vflag & INP_IPV4) &&
359 inp->inp_laddr.s_addr == INADDR_ANY &&
360 INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
365 idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
366 hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
367 CK_LIST_FOREACH(grp, hdr, il_list) {
368 if (grp->il_cred->cr_prison == inp->inp_cred->cr_prison &&
369 grp->il_vflag == inp->inp_vflag &&
370 grp->il_lport == inp->inp_lport &&
371 grp->il_numa_domain == numa_domain &&
372 memcmp(&grp->il_dependladdr,
373 &inp->inp_inc.inc_ie.ie_dependladdr,
374 sizeof(grp->il_dependladdr)) == 0) {
379 /* Create new load balance group. */
380 grp = in_pcblbgroup_alloc(hdr, inp->inp_cred, inp->inp_vflag,
381 inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
382 INPCBLBGROUP_SIZMIN, numa_domain);
385 } else if (grp->il_inpcnt == grp->il_inpsiz) {
386 if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
387 if (ratecheck(&lastprint, &interval))
388 printf("lb group port %d, limit reached\n",
389 ntohs(grp->il_lport));
393 /* Expand this local group. */
394 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
399 KASSERT(grp->il_inpcnt < grp->il_inpsiz,
400 ("invalid local group size %d and count %d", grp->il_inpsiz,
403 grp->il_inp[grp->il_inpcnt] = inp;
409 * Remove PCB from load balance group.
412 in_pcbremlbgrouphash(struct inpcb *inp)
414 struct inpcbinfo *pcbinfo;
415 struct inpcblbgrouphead *hdr;
416 struct inpcblbgroup *grp;
419 pcbinfo = inp->inp_pcbinfo;
421 INP_WLOCK_ASSERT(inp);
422 INP_HASH_WLOCK_ASSERT(pcbinfo);
424 hdr = &pcbinfo->ipi_lbgrouphashbase[
425 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
426 CK_LIST_FOREACH(grp, hdr, il_list) {
427 for (i = 0; i < grp->il_inpcnt; ++i) {
428 if (grp->il_inp[i] != inp)
431 if (grp->il_inpcnt == 1) {
432 /* We are the last, free this local group. */
433 in_pcblbgroup_free(grp);
435 /* Pull up inpcbs, shrink group if possible. */
436 in_pcblbgroup_reorder(hdr, &grp, i);
444 in_pcblbgroup_numa(struct inpcb *inp, int arg)
446 struct inpcbinfo *pcbinfo;
447 struct inpcblbgrouphead *hdr;
448 struct inpcblbgroup *grp;
453 case TCP_REUSPORT_LB_NUMA_NODOM:
454 numa_domain = M_NODOM;
456 case TCP_REUSPORT_LB_NUMA_CURDOM:
457 numa_domain = PCPU_GET(domain);
460 if (arg < 0 || arg >= vm_ndomains)
466 pcbinfo = inp->inp_pcbinfo;
467 INP_WLOCK_ASSERT(inp);
468 INP_HASH_WLOCK(pcbinfo);
469 hdr = &pcbinfo->ipi_lbgrouphashbase[
470 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
471 CK_LIST_FOREACH(grp, hdr, il_list) {
472 for (i = 0; i < grp->il_inpcnt; ++i) {
473 if (grp->il_inp[i] != inp)
476 if (grp->il_numa_domain == numa_domain) {
477 goto abort_with_hash_wlock;
480 /* Remove it from the old group. */
481 in_pcbremlbgrouphash(inp);
483 /* Add it to the new group based on numa domain. */
484 in_pcbinslbgrouphash(inp, numa_domain);
485 goto abort_with_hash_wlock;
489 abort_with_hash_wlock:
490 INP_HASH_WUNLOCK(pcbinfo);
494 /* Make sure it is safe to use hashinit(9) on CK_LIST. */
495 CTASSERT(sizeof(struct inpcbhead) == sizeof(LIST_HEAD(, inpcb)));
498 * Initialize an inpcbinfo - a per-VNET instance of connections db.
501 in_pcbinfo_init(struct inpcbinfo *pcbinfo, struct inpcbstorage *pcbstor,
502 u_int hash_nelements, u_int porthash_nelements)
505 mtx_init(&pcbinfo->ipi_lock, pcbstor->ips_infolock_name, NULL, MTX_DEF);
506 mtx_init(&pcbinfo->ipi_hash_lock, pcbstor->ips_hashlock_name,
509 pcbinfo->ipi_vnet = curvnet;
511 CK_LIST_INIT(&pcbinfo->ipi_listhead);
512 pcbinfo->ipi_count = 0;
513 pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
514 &pcbinfo->ipi_hashmask);
515 porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
516 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
517 &pcbinfo->ipi_porthashmask);
518 pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
519 &pcbinfo->ipi_lbgrouphashmask);
520 pcbinfo->ipi_zone = pcbstor->ips_zone;
521 pcbinfo->ipi_portzone = pcbstor->ips_portzone;
522 pcbinfo->ipi_smr = uma_zone_get_smr(pcbinfo->ipi_zone);
526 * Destroy an inpcbinfo.
529 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
532 KASSERT(pcbinfo->ipi_count == 0,
533 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
535 hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
536 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
537 pcbinfo->ipi_porthashmask);
538 hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
539 pcbinfo->ipi_lbgrouphashmask);
540 mtx_destroy(&pcbinfo->ipi_hash_lock);
541 mtx_destroy(&pcbinfo->ipi_lock);
545 * Initialize a pcbstorage - per protocol zones to allocate inpcbs.
547 static void inpcb_dtor(void *, int, void *);
548 static void inpcb_fini(void *, int);
550 in_pcbstorage_init(void *arg)
552 struct inpcbstorage *pcbstor = arg;
554 pcbstor->ips_zone = uma_zcreate(pcbstor->ips_zone_name,
555 pcbstor->ips_size, NULL, inpcb_dtor, pcbstor->ips_pcbinit,
556 inpcb_fini, UMA_ALIGN_CACHE, UMA_ZONE_SMR);
557 pcbstor->ips_portzone = uma_zcreate(pcbstor->ips_portzone_name,
558 sizeof(struct inpcbport), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
559 uma_zone_set_smr(pcbstor->ips_portzone,
560 uma_zone_get_smr(pcbstor->ips_zone));
564 * Destroy a pcbstorage - used by unloadable protocols.
567 in_pcbstorage_destroy(void *arg)
569 struct inpcbstorage *pcbstor = arg;
571 uma_zdestroy(pcbstor->ips_zone);
572 uma_zdestroy(pcbstor->ips_portzone);
576 * Allocate a PCB and associate it with the socket.
577 * On success return with the PCB locked.
580 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
583 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
587 inp = uma_zalloc_smr(pcbinfo->ipi_zone, M_NOWAIT);
590 bzero(&inp->inp_start_zero, inp_zero_size);
592 inp->inp_numa_domain = M_NODOM;
594 inp->inp_pcbinfo = pcbinfo;
595 inp->inp_socket = so;
596 inp->inp_cred = crhold(so->so_cred);
597 inp->inp_inc.inc_fibnum = so->so_fibnum;
599 error = mac_inpcb_init(inp, M_NOWAIT);
602 mac_inpcb_create(so, inp);
604 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
605 error = ipsec_init_pcbpolicy(inp);
608 mac_inpcb_destroy(inp);
614 if (INP_SOCKAF(so) == AF_INET6) {
615 inp->inp_vflag |= INP_IPV6PROTO | INP_IPV6;
617 inp->inp_flags |= IN6P_IPV6_V6ONLY;
620 inp->inp_vflag |= INP_IPV4;
622 if (V_ip6_auto_flowlabel)
623 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
624 inp->in6p_hops = -1; /* use kernel default */
627 #if defined(INET) && defined(INET6)
631 inp->inp_vflag |= INP_IPV4;
634 * Routes in inpcb's can cache L2 as well; they are guaranteed
637 inp->inp_route.ro_flags = RT_LLE_CACHE;
638 refcount_init(&inp->inp_refcount, 1); /* Reference from socket. */
640 INP_INFO_WLOCK(pcbinfo);
641 pcbinfo->ipi_count++;
642 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
643 CK_LIST_INSERT_HEAD(&pcbinfo->ipi_listhead, inp, inp_list);
644 INP_INFO_WUNLOCK(pcbinfo);
649 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
651 uma_zfree_smr(pcbinfo->ipi_zone, inp);
658 in_pcbbind(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred)
662 KASSERT(sin == NULL || sin->sin_family == AF_INET,
663 ("%s: invalid address family for %p", __func__, sin));
664 KASSERT(sin == NULL || sin->sin_len == sizeof(struct sockaddr_in),
665 ("%s: invalid address length for %p", __func__, sin));
666 INP_WLOCK_ASSERT(inp);
667 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
669 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
671 anonport = sin == NULL || sin->sin_port == 0;
672 error = in_pcbbind_setup(inp, sin, &inp->inp_laddr.s_addr,
673 &inp->inp_lport, cred);
676 if (in_pcbinshash(inp) != 0) {
677 inp->inp_laddr.s_addr = INADDR_ANY;
682 inp->inp_flags |= INP_ANONPORT;
687 #if defined(INET) || defined(INET6)
689 * Assign a local port like in_pcb_lport(), but also used with connect()
690 * and a foreign address and port. If fsa is non-NULL, choose a local port
691 * that is unused with those, otherwise one that is completely unused.
692 * lsa can be NULL for IPv6.
695 in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
696 struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
698 struct inpcbinfo *pcbinfo;
699 struct inpcb *tmpinp;
700 unsigned short *lastport;
702 u_short aux, first, last, lport;
704 struct in_addr laddr, faddr;
707 struct in6_addr *laddr6, *faddr6;
710 pcbinfo = inp->inp_pcbinfo;
713 * Because no actual state changes occur here, a global write lock on
714 * the pcbinfo isn't required.
716 INP_LOCK_ASSERT(inp);
717 INP_HASH_LOCK_ASSERT(pcbinfo);
719 if (inp->inp_flags & INP_HIGHPORT) {
720 first = V_ipport_hifirstauto; /* sysctl */
721 last = V_ipport_hilastauto;
722 lastport = &pcbinfo->ipi_lasthi;
723 } else if (inp->inp_flags & INP_LOWPORT) {
724 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
727 first = V_ipport_lowfirstauto; /* 1023 */
728 last = V_ipport_lowlastauto; /* 600 */
729 lastport = &pcbinfo->ipi_lastlow;
731 first = V_ipport_firstauto; /* sysctl */
732 last = V_ipport_lastauto;
733 lastport = &pcbinfo->ipi_lastport;
737 * Instead of having two loops further down counting up or down
738 * make sure that first is always <= last and go with only one
739 * code path implementing all logic.
748 laddr.s_addr = INADDR_ANY; /* used by INET6+INET below too */
749 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
751 laddr = ((struct sockaddr_in *)lsa)->sin_addr;
753 faddr = ((struct sockaddr_in *)fsa)->sin_addr;
758 if ((inp->inp_vflag & INP_IPV6) != 0) {
760 laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
762 faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
769 if (V_ipport_randomized)
770 *lastport = first + (arc4random() % (last - first));
772 count = last - first;
775 if (count-- < 0) /* completely used? */
776 return (EADDRNOTAVAIL);
778 if (*lastport < first || *lastport > last)
780 lport = htons(*lastport);
784 if (lsa->sa_family == AF_INET) {
785 tmpinp = in_pcblookup_hash_locked(pcbinfo,
786 faddr, fport, laddr, lport, lookupflags,
791 if (lsa->sa_family == AF_INET6) {
792 tmpinp = in6_pcblookup_hash_locked(pcbinfo,
793 faddr6, fport, laddr6, lport, lookupflags,
799 if ((inp->inp_vflag & INP_IPV6) != 0) {
800 tmpinp = in6_pcblookup_local(pcbinfo,
801 &inp->in6p_laddr, lport, lookupflags, cred);
803 if (tmpinp == NULL &&
804 (inp->inp_vflag & INP_IPV4))
805 tmpinp = in_pcblookup_local(pcbinfo,
806 laddr, lport, lookupflags, cred);
810 #if defined(INET) && defined(INET6)
814 tmpinp = in_pcblookup_local(pcbinfo, laddr,
815 lport, lookupflags, cred);
818 } while (tmpinp != NULL);
826 * Select a local port (number) to use.
829 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
830 struct ucred *cred, int lookupflags)
832 struct sockaddr_in laddr;
835 bzero(&laddr, sizeof(laddr));
836 laddr.sin_family = AF_INET;
837 laddr.sin_addr = *laddrp;
839 return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
840 NULL, lportp, NULL, 0, cred, lookupflags));
844 * Return cached socket options.
847 inp_so_options(const struct inpcb *inp)
853 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
854 so_options |= SO_REUSEPORT_LB;
855 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
856 so_options |= SO_REUSEPORT;
857 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
858 so_options |= SO_REUSEADDR;
861 #endif /* INET || INET6 */
865 * Set up a bind operation on a PCB, performing port allocation
866 * as required, but do not actually modify the PCB. Callers can
867 * either complete the bind by setting inp_laddr/inp_lport and
868 * calling in_pcbinshash(), or they can just use the resulting
869 * port and address to authorise the sending of a once-off packet.
871 * On error, the values of *laddrp and *lportp are not changed.
874 in_pcbbind_setup(struct inpcb *inp, struct sockaddr_in *sin, in_addr_t *laddrp,
875 u_short *lportp, struct ucred *cred)
877 struct socket *so = inp->inp_socket;
878 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
879 struct in_addr laddr;
881 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
885 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
886 * so that we don't have to add to the (already messy) code below.
888 int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
891 * No state changes, so read locks are sufficient here.
893 INP_LOCK_ASSERT(inp);
894 INP_HASH_LOCK_ASSERT(pcbinfo);
896 laddr.s_addr = *laddrp;
897 if (sin != NULL && laddr.s_addr != INADDR_ANY)
899 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
900 lookupflags = INPLOOKUP_WILDCARD;
902 if ((error = prison_local_ip4(cred, &laddr)) != 0)
905 KASSERT(sin->sin_family == AF_INET,
906 ("%s: invalid family for address %p", __func__, sin));
907 KASSERT(sin->sin_len == sizeof(*sin),
908 ("%s: invalid length for address %p", __func__, sin));
910 error = prison_local_ip4(cred, &sin->sin_addr);
913 if (sin->sin_port != *lportp) {
914 /* Don't allow the port to change. */
917 lport = sin->sin_port;
919 /* NB: lport is left as 0 if the port isn't being changed. */
920 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
922 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
923 * allow complete duplication of binding if
924 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
925 * and a multicast address is bound on both
926 * new and duplicated sockets.
928 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
929 reuseport = SO_REUSEADDR|SO_REUSEPORT;
931 * XXX: How to deal with SO_REUSEPORT_LB here?
932 * Treat same as SO_REUSEPORT for now.
934 if ((so->so_options &
935 (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
936 reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
937 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
938 sin->sin_port = 0; /* yech... */
939 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
941 * Is the address a local IP address?
942 * If INP_BINDANY is set, then the socket may be bound
943 * to any endpoint address, local or not.
945 if ((inp->inp_flags & INP_BINDANY) == 0 &&
946 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
947 return (EADDRNOTAVAIL);
949 laddr = sin->sin_addr;
954 if (ntohs(lport) <= V_ipport_reservedhigh &&
955 ntohs(lport) >= V_ipport_reservedlow &&
956 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
958 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
959 priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
960 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
961 lport, INPLOOKUP_WILDCARD, cred);
964 * This entire block sorely needs a rewrite.
967 (so->so_type != SOCK_STREAM ||
968 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
969 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
970 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
971 (t->inp_flags2 & INP_REUSEPORT) ||
972 (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
973 (inp->inp_cred->cr_uid !=
974 t->inp_cred->cr_uid))
977 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
978 lport, lookupflags, cred);
979 if (t != NULL && (reuseport & inp_so_options(t)) == 0 &&
980 (reuseport_lb & inp_so_options(t)) == 0) {
982 if (ntohl(sin->sin_addr.s_addr) !=
984 ntohl(t->inp_laddr.s_addr) !=
986 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
987 (t->inp_vflag & INP_IPV6PROTO) == 0)
996 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1000 *laddrp = laddr.s_addr;
1006 * Connect from a socket to a specified address.
1007 * Both address and port must be specified in argument sin.
1008 * If don't have a local address for this socket yet,
1012 in_pcbconnect(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred,
1015 u_short lport, fport;
1016 in_addr_t laddr, faddr;
1017 int anonport, error;
1019 INP_WLOCK_ASSERT(inp);
1020 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1022 lport = inp->inp_lport;
1023 laddr = inp->inp_laddr.s_addr;
1024 anonport = (lport == 0);
1025 error = in_pcbconnect_setup(inp, sin, &laddr, &lport, &faddr, &fport,
1030 /* Do the initial binding of the local address if required. */
1031 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1032 KASSERT(rehash == true,
1033 ("Rehashing required for unbound inps"));
1034 inp->inp_lport = lport;
1035 inp->inp_laddr.s_addr = laddr;
1036 if (in_pcbinshash(inp) != 0) {
1037 inp->inp_laddr.s_addr = INADDR_ANY;
1043 /* Commit the remaining changes. */
1044 inp->inp_lport = lport;
1045 inp->inp_laddr.s_addr = laddr;
1046 inp->inp_faddr.s_addr = faddr;
1047 inp->inp_fport = fport;
1055 inp->inp_flags |= INP_ANONPORT;
1060 * Do proper source address selection on an unbound socket in case
1061 * of connect. Take jails into account as well.
1064 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1068 struct sockaddr *sa;
1069 struct sockaddr_in *sin, dst;
1070 struct nhop_object *nh;
1074 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1077 * Bypass source address selection and use the primary jail IP
1080 if (!prison_saddrsel_ip4(cred, laddr))
1086 bzero(&dst, sizeof(dst));
1088 sin->sin_family = AF_INET;
1089 sin->sin_len = sizeof(struct sockaddr_in);
1090 sin->sin_addr.s_addr = faddr->s_addr;
1093 * If route is known our src addr is taken from the i/f,
1096 * Find out route to destination.
1098 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1099 nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
1103 * If we found a route, use the address corresponding to
1104 * the outgoing interface.
1106 * Otherwise assume faddr is reachable on a directly connected
1107 * network and try to find a corresponding interface to take
1108 * the source address from.
1110 if (nh == NULL || nh->nh_ifp == NULL) {
1111 struct in_ifaddr *ia;
1114 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1115 inp->inp_socket->so_fibnum));
1117 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1118 inp->inp_socket->so_fibnum));
1121 error = ENETUNREACH;
1125 if (!prison_flag(cred, PR_IP4)) {
1126 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1132 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1134 if (sa->sa_family != AF_INET)
1136 sin = (struct sockaddr_in *)sa;
1137 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1138 ia = (struct in_ifaddr *)ifa;
1143 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1147 /* 3. As a last resort return the 'default' jail address. */
1148 error = prison_get_ip4(cred, laddr);
1153 * If the outgoing interface on the route found is not
1154 * a loopback interface, use the address from that interface.
1155 * In case of jails do those three steps:
1156 * 1. check if the interface address belongs to the jail. If so use it.
1157 * 2. check if we have any address on the outgoing interface
1158 * belonging to this jail. If so use it.
1159 * 3. as a last resort return the 'default' jail address.
1161 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
1162 struct in_ifaddr *ia;
1165 /* If not jailed, use the default returned. */
1166 if (!prison_flag(cred, PR_IP4)) {
1167 ia = (struct in_ifaddr *)nh->nh_ifa;
1168 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1173 /* 1. Check if the iface address belongs to the jail. */
1174 sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1175 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1176 ia = (struct in_ifaddr *)nh->nh_ifa;
1177 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1182 * 2. Check if we have any address on the outgoing interface
1183 * belonging to this jail.
1187 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1189 if (sa->sa_family != AF_INET)
1191 sin = (struct sockaddr_in *)sa;
1192 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1193 ia = (struct in_ifaddr *)ifa;
1198 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1202 /* 3. As a last resort return the 'default' jail address. */
1203 error = prison_get_ip4(cred, laddr);
1208 * The outgoing interface is marked with 'loopback net', so a route
1209 * to ourselves is here.
1210 * Try to find the interface of the destination address and then
1211 * take the address from there. That interface is not necessarily
1212 * a loopback interface.
1213 * In case of jails, check that it is an address of the jail
1214 * and if we cannot find, fall back to the 'default' jail address.
1216 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
1217 struct in_ifaddr *ia;
1219 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
1220 inp->inp_socket->so_fibnum));
1222 ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
1223 inp->inp_socket->so_fibnum));
1225 ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
1227 if (!prison_flag(cred, PR_IP4)) {
1229 error = ENETUNREACH;
1232 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1242 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1244 if (sa->sa_family != AF_INET)
1246 sin = (struct sockaddr_in *)sa;
1247 if (prison_check_ip4(cred,
1248 &sin->sin_addr) == 0) {
1249 ia = (struct in_ifaddr *)ifa;
1254 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1259 /* 3. As a last resort return the 'default' jail address. */
1260 error = prison_get_ip4(cred, laddr);
1265 if (error == 0 && laddr->s_addr == INADDR_ANY)
1266 return (EHOSTUNREACH);
1271 * Set up for a connect from a socket to the specified address.
1272 * On entry, *laddrp and *lportp should contain the current local
1273 * address and port for the PCB; these are updated to the values
1274 * that should be placed in inp_laddr and inp_lport to complete
1277 * On success, *faddrp and *fportp will be set to the remote address
1278 * and port. These are not updated in the error case.
1281 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr_in *sin,
1282 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1285 struct in_ifaddr *ia;
1286 struct in_addr laddr, faddr;
1287 u_short lport, fport;
1290 KASSERT(sin->sin_family == AF_INET,
1291 ("%s: invalid address family for %p", __func__, sin));
1292 KASSERT(sin->sin_len == sizeof(*sin),
1293 ("%s: invalid address length for %p", __func__, sin));
1296 * Because a global state change doesn't actually occur here, a read
1297 * lock is sufficient.
1300 INP_LOCK_ASSERT(inp);
1301 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1303 if (sin->sin_port == 0)
1304 return (EADDRNOTAVAIL);
1305 laddr.s_addr = *laddrp;
1307 faddr = sin->sin_addr;
1308 fport = sin->sin_port;
1310 if (CALC_FLOWID_OUTBOUND) {
1311 uint32_t hash_val, hash_type;
1313 hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
1314 inp->inp_socket->so_proto->pr_protocol, &hash_type);
1316 inp->inp_flowid = hash_val;
1317 inp->inp_flowtype = hash_type;
1320 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1322 * If the destination address is INADDR_ANY,
1323 * use the primary local address.
1324 * If the supplied address is INADDR_BROADCAST,
1325 * and the primary interface supports broadcast,
1326 * choose the broadcast address for that interface.
1328 if (faddr.s_addr == INADDR_ANY) {
1330 IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1331 if ((error = prison_get_ip4(cred, &faddr)) != 0)
1333 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1334 if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1336 faddr = satosin(&CK_STAILQ_FIRST(
1337 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1340 if (laddr.s_addr == INADDR_ANY) {
1341 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1343 * If the destination address is multicast and an outgoing
1344 * interface has been set as a multicast option, prefer the
1345 * address of that interface as our source address.
1347 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1348 inp->inp_moptions != NULL) {
1349 struct ip_moptions *imo;
1352 imo = inp->inp_moptions;
1353 if (imo->imo_multicast_ifp != NULL) {
1354 ifp = imo->imo_multicast_ifp;
1355 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1356 if (ia->ia_ifp == ifp &&
1357 prison_check_ip4(cred,
1358 &ia->ia_addr.sin_addr) == 0)
1362 error = EADDRNOTAVAIL;
1364 laddr = ia->ia_addr.sin_addr;
1374 if (in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1375 fport, laddr, lport, 0, M_NODOM) != NULL)
1376 return (EADDRINUSE);
1378 struct sockaddr_in lsin, fsin;
1380 bzero(&lsin, sizeof(lsin));
1381 bzero(&fsin, sizeof(fsin));
1382 lsin.sin_family = AF_INET;
1383 lsin.sin_addr = laddr;
1384 fsin.sin_family = AF_INET;
1385 fsin.sin_addr = faddr;
1386 error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
1387 &lport, (struct sockaddr *)& fsin, fport, cred,
1388 INPLOOKUP_WILDCARD);
1392 *laddrp = laddr.s_addr;
1394 *faddrp = faddr.s_addr;
1400 in_pcbdisconnect(struct inpcb *inp)
1403 INP_WLOCK_ASSERT(inp);
1404 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1406 inp->inp_laddr.s_addr = INADDR_ANY;
1407 inp->inp_faddr.s_addr = INADDR_ANY;
1414 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1415 * For most protocols, this will be invoked immediately prior to calling
1416 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1417 * socket, in which case in_pcbfree() is deferred.
1420 in_pcbdetach(struct inpcb *inp)
1423 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1426 if (inp->inp_snd_tag != NULL)
1427 in_pcbdetach_txrtlmt(inp);
1429 inp->inp_socket->so_pcb = NULL;
1430 inp->inp_socket = NULL;
1434 * inpcb hash lookups are protected by SMR section.
1436 * Once desired pcb has been found, switching from SMR section to a pcb
1437 * lock is performed with inp_smr_lock(). We can not use INP_(W|R)LOCK
1438 * here because SMR is a critical section.
1439 * In 99%+ cases inp_smr_lock() would obtain the lock immediately.
1442 inp_lock(struct inpcb *inp, const inp_lookup_t lock)
1445 lock == INPLOOKUP_RLOCKPCB ?
1446 rw_rlock(&inp->inp_lock) : rw_wlock(&inp->inp_lock);
1450 inp_unlock(struct inpcb *inp, const inp_lookup_t lock)
1453 lock == INPLOOKUP_RLOCKPCB ?
1454 rw_runlock(&inp->inp_lock) : rw_wunlock(&inp->inp_lock);
1458 inp_trylock(struct inpcb *inp, const inp_lookup_t lock)
1461 return (lock == INPLOOKUP_RLOCKPCB ?
1462 rw_try_rlock(&inp->inp_lock) : rw_try_wlock(&inp->inp_lock));
1466 in_pcbrele(struct inpcb *inp, const inp_lookup_t lock)
1469 return (lock == INPLOOKUP_RLOCKPCB ?
1470 in_pcbrele_rlocked(inp) : in_pcbrele_wlocked(inp));
1474 _inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock, const int ignflags)
1477 MPASS(lock == INPLOOKUP_RLOCKPCB || lock == INPLOOKUP_WLOCKPCB);
1478 SMR_ASSERT_ENTERED(inp->inp_pcbinfo->ipi_smr);
1480 if (__predict_true(inp_trylock(inp, lock))) {
1481 if (__predict_false(inp->inp_flags & ignflags)) {
1482 smr_exit(inp->inp_pcbinfo->ipi_smr);
1483 inp_unlock(inp, lock);
1486 smr_exit(inp->inp_pcbinfo->ipi_smr);
1490 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1491 smr_exit(inp->inp_pcbinfo->ipi_smr);
1492 inp_lock(inp, lock);
1493 if (__predict_false(in_pcbrele(inp, lock)))
1496 * inp acquired through refcount & lock for sure didn't went
1497 * through uma_zfree(). However, it may have already went
1498 * through in_pcbfree() and has another reference, that
1499 * prevented its release by our in_pcbrele().
1501 if (__predict_false(inp->inp_flags & ignflags)) {
1502 inp_unlock(inp, lock);
1507 smr_exit(inp->inp_pcbinfo->ipi_smr);
1513 inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock)
1517 * in_pcblookup() family of functions ignore not only freed entries,
1518 * that may be found due to lockless access to the hash, but dropped
1521 return (_inp_smr_lock(inp, lock, INP_FREED | INP_DROPPED));
1525 * inp_next() - inpcb hash/list traversal iterator
1527 * Requires initialized struct inpcb_iterator for context.
1528 * The structure can be initialized with INP_ITERATOR() or INP_ALL_ITERATOR().
1530 * - Iterator can have either write-lock or read-lock semantics, that can not
1532 * - Iterator can iterate either over all pcbs list (INP_ALL_LIST), or through
1533 * a single hash slot. Note: only rip_input() does the latter.
1534 * - Iterator may have optional bool matching function. The matching function
1535 * will be executed for each inpcb in the SMR context, so it can not acquire
1536 * locks and can safely access only immutable fields of inpcb.
1538 * A fresh initialized iterator has NULL inpcb in its context and that
1539 * means that inp_next() call would return the very first inpcb on the list
1540 * locked with desired semantic. In all following calls the context pointer
1541 * shall hold the current inpcb pointer. The KPI user is not supposed to
1542 * unlock the current inpcb! Upon end of traversal inp_next() will return NULL
1543 * and write NULL to its context. After end of traversal an iterator can be
1546 * List traversals have the following features/constraints:
1547 * - New entries won't be seen, as they are always added to the head of a list.
1548 * - Removed entries won't stop traversal as long as they are not added to
1549 * a different list. This is violated by in_pcbrehash().
1551 #define II_LIST_FIRST(ipi, hash) \
1552 (((hash) == INP_ALL_LIST) ? \
1553 CK_LIST_FIRST(&(ipi)->ipi_listhead) : \
1554 CK_LIST_FIRST(&(ipi)->ipi_hashbase[(hash)]))
1555 #define II_LIST_NEXT(inp, hash) \
1556 (((hash) == INP_ALL_LIST) ? \
1557 CK_LIST_NEXT((inp), inp_list) : \
1558 CK_LIST_NEXT((inp), inp_hash))
1559 #define II_LOCK_ASSERT(inp, lock) \
1560 rw_assert(&(inp)->inp_lock, \
1561 (lock) == INPLOOKUP_RLOCKPCB ? RA_RLOCKED : RA_WLOCKED )
1563 inp_next(struct inpcb_iterator *ii)
1565 const struct inpcbinfo *ipi = ii->ipi;
1566 inp_match_t *match = ii->match;
1567 void *ctx = ii->ctx;
1568 inp_lookup_t lock = ii->lock;
1569 int hash = ii->hash;
1572 if (ii->inp == NULL) { /* First call. */
1573 smr_enter(ipi->ipi_smr);
1574 /* This is unrolled CK_LIST_FOREACH(). */
1575 for (inp = II_LIST_FIRST(ipi, hash);
1577 inp = II_LIST_NEXT(inp, hash)) {
1578 if (match != NULL && (match)(inp, ctx) == false)
1580 if (__predict_true(_inp_smr_lock(inp, lock, INP_FREED)))
1583 smr_enter(ipi->ipi_smr);
1584 MPASS(inp != II_LIST_FIRST(ipi, hash));
1585 inp = II_LIST_FIRST(ipi, hash);
1592 smr_exit(ipi->ipi_smr);
1599 /* Not a first call. */
1600 smr_enter(ipi->ipi_smr);
1603 II_LOCK_ASSERT(inp, lock);
1605 inp = II_LIST_NEXT(inp, hash);
1607 smr_exit(ipi->ipi_smr);
1611 if (match != NULL && (match)(inp, ctx) == false)
1614 if (__predict_true(inp_trylock(inp, lock))) {
1615 if (__predict_false(inp->inp_flags & INP_FREED)) {
1617 * Entries are never inserted in middle of a list, thus
1618 * as long as we are in SMR, we can continue traversal.
1619 * Jump to 'restart' should yield in the same result,
1620 * but could produce unnecessary looping. Could this
1621 * looping be unbound?
1623 inp_unlock(inp, lock);
1626 smr_exit(ipi->ipi_smr);
1632 * Can't obtain lock immediately, thus going hard. Once we exit the
1633 * SMR section we can no longer jump to 'next', and our only stable
1634 * anchoring point is ii->inp, which we keep locked for this case, so
1635 * we jump to 'restart'.
1637 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1638 smr_exit(ipi->ipi_smr);
1639 inp_lock(inp, lock);
1640 if (__predict_false(in_pcbrele(inp, lock))) {
1641 smr_enter(ipi->ipi_smr);
1645 * See comment in inp_smr_lock().
1647 if (__predict_false(inp->inp_flags & INP_FREED)) {
1648 inp_unlock(inp, lock);
1649 smr_enter(ipi->ipi_smr);
1656 inp_unlock(ii->inp, lock);
1663 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1664 * stability of an inpcb pointer despite the inpcb lock being released or
1665 * SMR section exited.
1667 * To free a reference later in_pcbrele_(r|w)locked() must be performed.
1670 in_pcbref(struct inpcb *inp)
1672 u_int old __diagused;
1674 old = refcount_acquire(&inp->inp_refcount);
1675 KASSERT(old > 0, ("%s: refcount 0", __func__));
1679 * Drop a refcount on an inpcb elevated using in_pcbref(), potentially
1680 * freeing the pcb, if the reference was very last.
1683 in_pcbrele_rlocked(struct inpcb *inp)
1686 INP_RLOCK_ASSERT(inp);
1688 if (!refcount_release(&inp->inp_refcount))
1691 MPASS(inp->inp_flags & INP_FREED);
1692 MPASS(inp->inp_socket == NULL);
1693 MPASS(inp->inp_in_hpts == 0);
1695 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1700 in_pcbrele_wlocked(struct inpcb *inp)
1703 INP_WLOCK_ASSERT(inp);
1705 if (!refcount_release(&inp->inp_refcount))
1708 MPASS(inp->inp_flags & INP_FREED);
1709 MPASS(inp->inp_socket == NULL);
1710 MPASS(inp->inp_in_hpts == 0);
1712 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1717 * Unconditionally schedule an inpcb to be freed by decrementing its
1718 * reference count, which should occur only after the inpcb has been detached
1719 * from its socket. If another thread holds a temporary reference (acquired
1720 * using in_pcbref()) then the free is deferred until that reference is
1721 * released using in_pcbrele_(r|w)locked(), but the inpcb is still unlocked.
1722 * Almost all work, including removal from global lists, is done in this
1723 * context, where the pcbinfo lock is held.
1726 in_pcbfree(struct inpcb *inp)
1728 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1730 struct ip_moptions *imo;
1733 struct ip6_moptions *im6o;
1736 INP_WLOCK_ASSERT(inp);
1737 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1738 KASSERT((inp->inp_flags & INP_FREED) == 0,
1739 ("%s: called twice for pcb %p", __func__, inp));
1741 inp->inp_flags |= INP_FREED;
1742 INP_INFO_WLOCK(pcbinfo);
1743 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1744 pcbinfo->ipi_count--;
1745 CK_LIST_REMOVE(inp, inp_list);
1746 INP_INFO_WUNLOCK(pcbinfo);
1748 if (inp->inp_flags & INP_INHASHLIST)
1751 RO_INVALIDATE_CACHE(&inp->inp_route);
1753 mac_inpcb_destroy(inp);
1755 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1756 if (inp->inp_sp != NULL)
1757 ipsec_delete_pcbpolicy(inp);
1760 if (inp->inp_options)
1761 (void)m_free(inp->inp_options);
1762 imo = inp->inp_moptions;
1765 if (inp->inp_vflag & INP_IPV6PROTO) {
1766 ip6_freepcbopts(inp->in6p_outputopts);
1767 im6o = inp->in6p_moptions;
1772 if (__predict_false(in_pcbrele_wlocked(inp) == false)) {
1776 ip6_freemoptions(im6o);
1779 inp_freemoptions(imo);
1781 /* Destruction is finalized in inpcb_dtor(). */
1785 inpcb_dtor(void *mem, int size, void *arg)
1787 struct inpcb *inp = mem;
1789 crfree(inp->inp_cred);
1791 inp->inp_cred = NULL;
1796 * Different protocols initialize their inpcbs differently - giving
1797 * different name to the lock. But they all are disposed the same.
1800 inpcb_fini(void *mem, int size)
1802 struct inpcb *inp = mem;
1804 INP_LOCK_DESTROY(inp);
1808 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1809 * port reservation, and preventing it from being returned by inpcb lookups.
1811 * It is used by TCP to mark an inpcb as unused and avoid future packet
1812 * delivery or event notification when a socket remains open but TCP has
1813 * closed. This might occur as a result of a shutdown()-initiated TCP close
1814 * or a RST on the wire, and allows the port binding to be reused while still
1815 * maintaining the invariant that so_pcb always points to a valid inpcb until
1818 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1819 * in_pcbnotifyall() and in_pcbpurgeif0()?
1822 in_pcbdrop(struct inpcb *inp)
1825 INP_WLOCK_ASSERT(inp);
1827 if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1828 MPASS(inp->inp_refcount > 1);
1831 inp->inp_flags |= INP_DROPPED;
1832 if (inp->inp_flags & INP_INHASHLIST)
1838 * Common routines to return the socket addresses associated with inpcbs.
1841 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1843 struct sockaddr_in *sin;
1845 sin = malloc(sizeof *sin, M_SONAME,
1847 sin->sin_family = AF_INET;
1848 sin->sin_len = sizeof(*sin);
1849 sin->sin_addr = *addr_p;
1850 sin->sin_port = port;
1852 return (struct sockaddr *)sin;
1856 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1859 struct in_addr addr;
1862 inp = sotoinpcb(so);
1863 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1866 port = inp->inp_lport;
1867 addr = inp->inp_laddr;
1870 *nam = in_sockaddr(port, &addr);
1875 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1878 struct in_addr addr;
1881 inp = sotoinpcb(so);
1882 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1885 port = inp->inp_fport;
1886 addr = inp->inp_faddr;
1889 *nam = in_sockaddr(port, &addr);
1894 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1895 struct inpcb *(*notify)(struct inpcb *, int))
1897 struct inpcb *inp, *inp_temp;
1899 INP_INFO_WLOCK(pcbinfo);
1900 CK_LIST_FOREACH_SAFE(inp, &pcbinfo->ipi_listhead, inp_list, inp_temp) {
1903 if ((inp->inp_vflag & INP_IPV4) == 0) {
1908 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1909 inp->inp_socket == NULL) {
1913 if ((*notify)(inp, errno))
1916 INP_INFO_WUNLOCK(pcbinfo);
1920 inp_v4_multi_match(const struct inpcb *inp, void *v __unused)
1923 if ((inp->inp_vflag & INP_IPV4) && inp->inp_moptions != NULL)
1930 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1932 struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
1933 inp_v4_multi_match, NULL);
1935 struct in_multi *inm;
1936 struct in_mfilter *imf;
1937 struct ip_moptions *imo;
1939 IN_MULTI_LOCK_ASSERT();
1941 while ((inp = inp_next(&inpi)) != NULL) {
1942 INP_WLOCK_ASSERT(inp);
1944 imo = inp->inp_moptions;
1946 * Unselect the outgoing interface if it is being
1949 if (imo->imo_multicast_ifp == ifp)
1950 imo->imo_multicast_ifp = NULL;
1953 * Drop multicast group membership if we joined
1954 * through the interface being detached.
1956 * XXX This can all be deferred to an epoch_call
1959 IP_MFILTER_FOREACH(imf, &imo->imo_head) {
1960 if ((inm = imf->imf_inm) == NULL)
1962 if (inm->inm_ifp != ifp)
1964 ip_mfilter_remove(&imo->imo_head, imf);
1965 in_leavegroup_locked(inm, NULL);
1966 ip_mfilter_free(imf);
1973 * Lookup a PCB based on the local address and port. Caller must hold the
1974 * hash lock. No inpcb locks or references are acquired.
1976 #define INP_LOOKUP_MAPPED_PCB_COST 3
1978 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1979 u_short lport, int lookupflags, struct ucred *cred)
1983 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1989 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1990 ("%s: invalid lookup flags %d", __func__, lookupflags));
1991 INP_HASH_LOCK_ASSERT(pcbinfo);
1993 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1994 struct inpcbhead *head;
1996 * Look for an unconnected (wildcard foreign addr) PCB that
1997 * matches the local address and port we're looking for.
1999 head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2000 pcbinfo->ipi_hashmask)];
2001 CK_LIST_FOREACH(inp, head, inp_hash) {
2003 /* XXX inp locking */
2004 if ((inp->inp_vflag & INP_IPV4) == 0)
2007 if (inp->inp_faddr.s_addr == INADDR_ANY &&
2008 inp->inp_laddr.s_addr == laddr.s_addr &&
2009 inp->inp_lport == lport) {
2013 if (prison_equal_ip4(cred->cr_prison,
2014 inp->inp_cred->cr_prison))
2023 struct inpcbporthead *porthash;
2024 struct inpcbport *phd;
2025 struct inpcb *match = NULL;
2027 * Best fit PCB lookup.
2029 * First see if this local port is in use by looking on the
2032 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2033 pcbinfo->ipi_porthashmask)];
2034 CK_LIST_FOREACH(phd, porthash, phd_hash) {
2035 if (phd->phd_port == lport)
2040 * Port is in use by one or more PCBs. Look for best
2043 CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2045 if (!prison_equal_ip4(inp->inp_cred->cr_prison,
2049 /* XXX inp locking */
2050 if ((inp->inp_vflag & INP_IPV4) == 0)
2053 * We never select the PCB that has
2054 * INP_IPV6 flag and is bound to :: if
2055 * we have another PCB which is bound
2056 * to 0.0.0.0. If a PCB has the
2057 * INP_IPV6 flag, then we set its cost
2058 * higher than IPv4 only PCBs.
2060 * Note that the case only happens
2061 * when a socket is bound to ::, under
2062 * the condition that the use of the
2063 * mapped address is allowed.
2065 if ((inp->inp_vflag & INP_IPV6) != 0)
2066 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2068 if (inp->inp_faddr.s_addr != INADDR_ANY)
2070 if (inp->inp_laddr.s_addr != INADDR_ANY) {
2071 if (laddr.s_addr == INADDR_ANY)
2073 else if (inp->inp_laddr.s_addr != laddr.s_addr)
2076 if (laddr.s_addr != INADDR_ANY)
2079 if (wildcard < matchwild) {
2081 matchwild = wildcard;
2090 #undef INP_LOOKUP_MAPPED_PCB_COST
2093 in_pcblookup_lb_numa_match(const struct inpcblbgroup *grp, int domain)
2095 return (domain == M_NODOM || domain == grp->il_numa_domain);
2098 static struct inpcb *
2099 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
2100 const struct in_addr *faddr, uint16_t fport, const struct in_addr *laddr,
2101 uint16_t lport, int domain)
2103 const struct inpcblbgrouphead *hdr;
2104 struct inpcblbgroup *grp;
2105 struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
2107 INP_HASH_LOCK_ASSERT(pcbinfo);
2109 hdr = &pcbinfo->ipi_lbgrouphashbase[
2110 INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
2113 * Search for an LB group match based on the following criteria:
2114 * - prefer jailed groups to non-jailed groups
2115 * - prefer exact source address matches to wildcard matches
2116 * - prefer groups bound to the specified NUMA domain
2118 jail_exact = jail_wild = local_exact = local_wild = NULL;
2119 CK_LIST_FOREACH(grp, hdr, il_list) {
2123 if (!(grp->il_vflag & INP_IPV4))
2126 if (grp->il_lport != lport)
2129 injail = prison_flag(grp->il_cred, PR_IP4) != 0;
2130 if (injail && prison_check_ip4_locked(grp->il_cred->cr_prison,
2134 if (grp->il_laddr.s_addr == laddr->s_addr) {
2137 if (in_pcblookup_lb_numa_match(grp, domain))
2138 /* This is a perfect match. */
2140 } else if (local_exact == NULL ||
2141 in_pcblookup_lb_numa_match(grp, domain)) {
2144 } else if (grp->il_laddr.s_addr == INADDR_ANY) {
2146 if (jail_wild == NULL ||
2147 in_pcblookup_lb_numa_match(grp, domain))
2149 } else if (local_wild == NULL ||
2150 in_pcblookup_lb_numa_match(grp, domain)) {
2156 if (jail_exact != NULL)
2158 else if (jail_wild != NULL)
2160 else if (local_exact != NULL)
2167 return (grp->il_inp[INP_PCBLBGROUP_PKTHASH(faddr, lport, fport) %
2171 static struct inpcb *
2172 in_pcblookup_hash_exact(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2173 u_short fport, struct in_addr laddr, u_short lport)
2175 struct inpcbhead *head;
2176 struct inpcb *inp, *match;
2178 INP_HASH_LOCK_ASSERT(pcbinfo);
2181 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&faddr, lport, fport,
2182 pcbinfo->ipi_hashmask)];
2183 CK_LIST_FOREACH(inp, head, inp_hash) {
2185 /* XXX inp locking */
2186 if ((inp->inp_vflag & INP_IPV4) == 0)
2189 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2190 inp->inp_laddr.s_addr == laddr.s_addr &&
2191 inp->inp_fport == fport &&
2192 inp->inp_lport == lport)
2198 static struct inpcb *
2199 in_pcblookup_hash_wild_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2200 u_short fport, struct in_addr laddr, u_short lport)
2202 struct inpcbhead *head;
2203 struct inpcb *inp, *local_wild, *local_exact, *jail_wild;
2205 struct inpcb *local_wild_mapped;
2208 INP_HASH_LOCK_ASSERT(pcbinfo);
2211 * Order of socket selection - we always prefer jails.
2212 * 1. jailed, non-wild.
2214 * 3. non-jailed, non-wild.
2215 * 4. non-jailed, wild.
2217 head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2218 pcbinfo->ipi_hashmask)];
2219 local_wild = local_exact = jail_wild = NULL;
2221 local_wild_mapped = NULL;
2223 CK_LIST_FOREACH(inp, head, inp_hash) {
2227 /* XXX inp locking */
2228 if ((inp->inp_vflag & INP_IPV4) == 0)
2231 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2232 inp->inp_lport != lport)
2235 injail = prison_flag(inp->inp_cred, PR_IP4) != 0;
2237 if (prison_check_ip4_locked(inp->inp_cred->cr_prison,
2241 if (local_exact != NULL)
2245 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2249 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2251 /* XXX inp locking, NULL check */
2252 if (inp->inp_vflag & INP_IPV6PROTO)
2253 local_wild_mapped = inp;
2262 if (jail_wild != NULL)
2264 if (local_exact != NULL)
2265 return (local_exact);
2266 if (local_wild != NULL)
2267 return (local_wild);
2269 if (local_wild_mapped != NULL)
2270 return (local_wild_mapped);
2276 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
2277 * that the caller has either locked the hash list, which usually happens
2278 * for bind(2) operations, or is in SMR section, which happens when sorting
2279 * out incoming packets.
2281 static struct inpcb *
2282 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2283 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2284 uint8_t numa_domain)
2287 const u_short fport = fport_arg, lport = lport_arg;
2289 KASSERT((lookupflags & ~INPLOOKUP_WILDCARD) == 0,
2290 ("%s: invalid lookup flags %d", __func__, lookupflags));
2291 KASSERT(faddr.s_addr != INADDR_ANY,
2292 ("%s: invalid foreign address", __func__));
2293 KASSERT(laddr.s_addr != INADDR_ANY,
2294 ("%s: invalid local address", __func__));
2295 INP_HASH_LOCK_ASSERT(pcbinfo);
2297 inp = in_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
2301 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2302 inp = in_pcblookup_lbgroup(pcbinfo, &faddr, fport, &laddr,
2303 lport, numa_domain);
2305 inp = in_pcblookup_hash_wild_locked(pcbinfo, faddr,
2306 fport, laddr, lport);
2313 static struct inpcb *
2314 in_pcblookup_hash_smr(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2315 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2316 uint8_t numa_domain)
2320 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2321 ("%s: invalid lookup flags %d", __func__, lookupflags));
2322 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2323 ("%s: LOCKPCB not set", __func__));
2325 smr_enter(pcbinfo->ipi_smr);
2326 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2327 lookupflags & INPLOOKUP_WILDCARD, numa_domain);
2329 if (__predict_false(inp_smr_lock(inp,
2330 (lookupflags & INPLOOKUP_LOCKMASK)) == false))
2333 smr_exit(pcbinfo->ipi_smr);
2339 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2340 * from which a pre-calculated hash value may be extracted.
2343 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2344 struct in_addr laddr, u_int lport, int lookupflags,
2345 struct ifnet *ifp __unused)
2347 return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
2348 lookupflags, M_NODOM));
2352 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2353 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2354 struct ifnet *ifp __unused, struct mbuf *m)
2356 return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
2357 lookupflags, m->m_pkthdr.numa_domain));
2362 * Insert PCB onto various hash lists.
2365 in_pcbinshash(struct inpcb *inp)
2367 struct inpcbhead *pcbhash;
2368 struct inpcbporthead *pcbporthash;
2369 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2370 struct inpcbport *phd;
2372 INP_WLOCK_ASSERT(inp);
2373 INP_HASH_WLOCK_ASSERT(pcbinfo);
2375 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2376 ("in_pcbinshash: INP_INHASHLIST"));
2379 if (inp->inp_vflag & INP_IPV6)
2380 pcbhash = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2381 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2384 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2385 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2387 pcbporthash = &pcbinfo->ipi_porthashbase[
2388 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2391 * Add entry to load balance group.
2392 * Only do this if SO_REUSEPORT_LB is set.
2394 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0) {
2395 int error = in_pcbinslbgrouphash(inp, M_NODOM);
2401 * Go through port list and look for a head for this lport.
2403 CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2404 if (phd->phd_port == inp->inp_lport)
2409 * If none exists, malloc one and tack it on.
2412 phd = uma_zalloc_smr(pcbinfo->ipi_portzone, M_NOWAIT);
2414 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2415 in_pcbremlbgrouphash(inp);
2418 phd->phd_port = inp->inp_lport;
2419 CK_LIST_INIT(&phd->phd_pcblist);
2420 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2423 CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2424 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2425 inp->inp_flags |= INP_INHASHLIST;
2431 in_pcbremhash(struct inpcb *inp)
2433 struct inpcbport *phd = inp->inp_phd;
2435 INP_WLOCK_ASSERT(inp);
2436 MPASS(inp->inp_flags & INP_INHASHLIST);
2438 INP_HASH_WLOCK(inp->inp_pcbinfo);
2439 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2440 in_pcbremlbgrouphash(inp);
2441 CK_LIST_REMOVE(inp, inp_hash);
2442 CK_LIST_REMOVE(inp, inp_portlist);
2443 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2444 CK_LIST_REMOVE(phd, phd_hash);
2445 uma_zfree_smr(inp->inp_pcbinfo->ipi_portzone, phd);
2447 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
2448 inp->inp_flags &= ~INP_INHASHLIST;
2452 * Move PCB to the proper hash bucket when { faddr, fport } have been
2453 * changed. NOTE: This does not handle the case of the lport changing (the
2454 * hashed port list would have to be updated as well), so the lport must
2455 * not change after in_pcbinshash() has been called.
2457 * XXXGL: a race between this function and SMR-protected hash iterator
2458 * will lead to iterator traversing a possibly wrong hash list. However,
2459 * this race should have been here since change from rwlock to epoch.
2462 in_pcbrehash(struct inpcb *inp)
2464 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2465 struct inpcbhead *head;
2467 INP_WLOCK_ASSERT(inp);
2468 INP_HASH_WLOCK_ASSERT(pcbinfo);
2470 KASSERT(inp->inp_flags & INP_INHASHLIST,
2471 ("in_pcbrehash: !INP_INHASHLIST"));
2474 if (inp->inp_vflag & INP_IPV6)
2475 head = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2476 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2479 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2480 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2482 CK_LIST_REMOVE(inp, inp_hash);
2483 CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2487 * Check for alternatives when higher level complains
2488 * about service problems. For now, invalidate cached
2489 * routing information. If the route was created dynamically
2490 * (by a redirect), time to try a default gateway again.
2493 in_losing(struct inpcb *inp)
2496 RO_INVALIDATE_CACHE(&inp->inp_route);
2501 * A set label operation has occurred at the socket layer, propagate the
2502 * label change into the in_pcb for the socket.
2505 in_pcbsosetlabel(struct socket *so)
2510 inp = sotoinpcb(so);
2511 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2515 mac_inpcb_sosetlabel(so, inp);
2522 inp_wlock(struct inpcb *inp)
2529 inp_wunlock(struct inpcb *inp)
2536 inp_rlock(struct inpcb *inp)
2543 inp_runlock(struct inpcb *inp)
2549 #ifdef INVARIANT_SUPPORT
2551 inp_lock_assert(struct inpcb *inp)
2554 INP_WLOCK_ASSERT(inp);
2558 inp_unlock_assert(struct inpcb *inp)
2561 INP_UNLOCK_ASSERT(inp);
2566 inp_apply_all(struct inpcbinfo *pcbinfo,
2567 void (*func)(struct inpcb *, void *), void *arg)
2569 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2570 INPLOOKUP_WLOCKPCB);
2573 while ((inp = inp_next(&inpi)) != NULL)
2578 inp_inpcbtosocket(struct inpcb *inp)
2581 INP_WLOCK_ASSERT(inp);
2582 return (inp->inp_socket);
2586 inp_inpcbtotcpcb(struct inpcb *inp)
2589 INP_WLOCK_ASSERT(inp);
2590 return ((struct tcpcb *)inp->inp_ppcb);
2594 inp_ip_tos_get(const struct inpcb *inp)
2597 return (inp->inp_ip_tos);
2601 inp_ip_tos_set(struct inpcb *inp, int val)
2604 inp->inp_ip_tos = val;
2608 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2609 uint32_t *faddr, uint16_t *fp)
2612 INP_LOCK_ASSERT(inp);
2613 *laddr = inp->inp_laddr.s_addr;
2614 *faddr = inp->inp_faddr.s_addr;
2615 *lp = inp->inp_lport;
2616 *fp = inp->inp_fport;
2620 so_sotoinpcb(struct socket *so)
2623 return (sotoinpcb(so));
2627 * Create an external-format (``xinpcb'') structure using the information in
2628 * the kernel-format in_pcb structure pointed to by inp. This is done to
2629 * reduce the spew of irrelevant information over this interface, to isolate
2630 * user code from changes in the kernel structure, and potentially to provide
2631 * information-hiding if we decide that some of this information should be
2632 * hidden from users.
2635 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2638 bzero(xi, sizeof(*xi));
2639 xi->xi_len = sizeof(struct xinpcb);
2640 if (inp->inp_socket)
2641 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2642 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2643 xi->inp_gencnt = inp->inp_gencnt;
2644 xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2645 xi->inp_flow = inp->inp_flow;
2646 xi->inp_flowid = inp->inp_flowid;
2647 xi->inp_flowtype = inp->inp_flowtype;
2648 xi->inp_flags = inp->inp_flags;
2649 xi->inp_flags2 = inp->inp_flags2;
2650 xi->in6p_cksum = inp->in6p_cksum;
2651 xi->in6p_hops = inp->in6p_hops;
2652 xi->inp_ip_tos = inp->inp_ip_tos;
2653 xi->inp_vflag = inp->inp_vflag;
2654 xi->inp_ip_ttl = inp->inp_ip_ttl;
2655 xi->inp_ip_p = inp->inp_ip_p;
2656 xi->inp_ip_minttl = inp->inp_ip_minttl;
2660 sysctl_setsockopt(SYSCTL_HANDLER_ARGS, struct inpcbinfo *pcbinfo,
2661 int (*ctloutput_set)(struct inpcb *, struct sockopt *))
2663 struct sockopt sopt;
2664 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2665 INPLOOKUP_WLOCKPCB);
2667 struct sockopt_parameters *params;
2672 if (req->oldptr != NULL || req->oldlen != 0)
2674 if (req->newptr == NULL)
2676 if (req->newlen > sizeof(buf))
2678 error = SYSCTL_IN(req, buf, req->newlen);
2681 if (req->newlen < sizeof(struct sockopt_parameters))
2683 params = (struct sockopt_parameters *)buf;
2684 sopt.sopt_level = params->sop_level;
2685 sopt.sopt_name = params->sop_optname;
2686 sopt.sopt_dir = SOPT_SET;
2687 sopt.sopt_val = params->sop_optval;
2688 sopt.sopt_valsize = req->newlen - sizeof(struct sockopt_parameters);
2689 sopt.sopt_td = NULL;
2691 if (params->sop_inc.inc_flags & INC_ISIPV6) {
2692 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_laddr))
2693 params->sop_inc.inc6_laddr.s6_addr16[1] =
2694 htons(params->sop_inc.inc6_zoneid & 0xffff);
2695 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_faddr))
2696 params->sop_inc.inc6_faddr.s6_addr16[1] =
2697 htons(params->sop_inc.inc6_zoneid & 0xffff);
2700 if (params->sop_inc.inc_lport != htons(0)) {
2701 if (params->sop_inc.inc_fport == htons(0))
2702 inpi.hash = INP_PCBHASH_WILD(params->sop_inc.inc_lport,
2703 pcbinfo->ipi_hashmask);
2706 if (params->sop_inc.inc_flags & INC_ISIPV6)
2707 inpi.hash = INP6_PCBHASH(
2708 ¶ms->sop_inc.inc6_faddr,
2709 params->sop_inc.inc_lport,
2710 params->sop_inc.inc_fport,
2711 pcbinfo->ipi_hashmask);
2714 inpi.hash = INP_PCBHASH(
2715 ¶ms->sop_inc.inc_faddr,
2716 params->sop_inc.inc_lport,
2717 params->sop_inc.inc_fport,
2718 pcbinfo->ipi_hashmask);
2720 while ((inp = inp_next(&inpi)) != NULL)
2721 if (inp->inp_gencnt == params->sop_id) {
2722 if (inp->inp_flags & INP_DROPPED) {
2724 return (ECONNRESET);
2726 so = inp->inp_socket;
2727 KASSERT(so != NULL, ("inp_socket == NULL"));
2729 error = (*ctloutput_set)(inp, &sopt);
2740 db_print_indent(int indent)
2744 for (i = 0; i < indent; i++)
2749 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2751 char faddr_str[48], laddr_str[48];
2753 db_print_indent(indent);
2754 db_printf("%s at %p\n", name, inc);
2759 if (inc->inc_flags & INC_ISIPV6) {
2761 ip6_sprintf(laddr_str, &inc->inc6_laddr);
2762 ip6_sprintf(faddr_str, &inc->inc6_faddr);
2767 inet_ntoa_r(inc->inc_laddr, laddr_str);
2768 inet_ntoa_r(inc->inc_faddr, faddr_str);
2770 db_print_indent(indent);
2771 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
2772 ntohs(inc->inc_lport));
2773 db_print_indent(indent);
2774 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
2775 ntohs(inc->inc_fport));
2779 db_print_inpflags(int inp_flags)
2784 if (inp_flags & INP_RECVOPTS) {
2785 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2788 if (inp_flags & INP_RECVRETOPTS) {
2789 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2792 if (inp_flags & INP_RECVDSTADDR) {
2793 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2796 if (inp_flags & INP_ORIGDSTADDR) {
2797 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2800 if (inp_flags & INP_HDRINCL) {
2801 db_printf("%sINP_HDRINCL", comma ? ", " : "");
2804 if (inp_flags & INP_HIGHPORT) {
2805 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2808 if (inp_flags & INP_LOWPORT) {
2809 db_printf("%sINP_LOWPORT", comma ? ", " : "");
2812 if (inp_flags & INP_ANONPORT) {
2813 db_printf("%sINP_ANONPORT", comma ? ", " : "");
2816 if (inp_flags & INP_RECVIF) {
2817 db_printf("%sINP_RECVIF", comma ? ", " : "");
2820 if (inp_flags & INP_MTUDISC) {
2821 db_printf("%sINP_MTUDISC", comma ? ", " : "");
2824 if (inp_flags & INP_RECVTTL) {
2825 db_printf("%sINP_RECVTTL", comma ? ", " : "");
2828 if (inp_flags & INP_DONTFRAG) {
2829 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2832 if (inp_flags & INP_RECVTOS) {
2833 db_printf("%sINP_RECVTOS", comma ? ", " : "");
2836 if (inp_flags & IN6P_IPV6_V6ONLY) {
2837 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2840 if (inp_flags & IN6P_PKTINFO) {
2841 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2844 if (inp_flags & IN6P_HOPLIMIT) {
2845 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2848 if (inp_flags & IN6P_HOPOPTS) {
2849 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2852 if (inp_flags & IN6P_DSTOPTS) {
2853 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2856 if (inp_flags & IN6P_RTHDR) {
2857 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2860 if (inp_flags & IN6P_RTHDRDSTOPTS) {
2861 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2864 if (inp_flags & IN6P_TCLASS) {
2865 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2868 if (inp_flags & IN6P_AUTOFLOWLABEL) {
2869 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2872 if (inp_flags & INP_ONESBCAST) {
2873 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2876 if (inp_flags & INP_DROPPED) {
2877 db_printf("%sINP_DROPPED", comma ? ", " : "");
2880 if (inp_flags & INP_SOCKREF) {
2881 db_printf("%sINP_SOCKREF", comma ? ", " : "");
2884 if (inp_flags & IN6P_RFC2292) {
2885 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2888 if (inp_flags & IN6P_MTU) {
2889 db_printf("IN6P_MTU%s", comma ? ", " : "");
2895 db_print_inpvflag(u_char inp_vflag)
2900 if (inp_vflag & INP_IPV4) {
2901 db_printf("%sINP_IPV4", comma ? ", " : "");
2904 if (inp_vflag & INP_IPV6) {
2905 db_printf("%sINP_IPV6", comma ? ", " : "");
2908 if (inp_vflag & INP_IPV6PROTO) {
2909 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2915 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2918 db_print_indent(indent);
2919 db_printf("%s at %p\n", name, inp);
2923 db_print_indent(indent);
2924 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2926 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2928 db_print_indent(indent);
2929 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
2930 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2932 db_print_indent(indent);
2933 db_printf("inp_label: %p inp_flags: 0x%x (",
2934 inp->inp_label, inp->inp_flags);
2935 db_print_inpflags(inp->inp_flags);
2938 db_print_indent(indent);
2939 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
2941 db_print_inpvflag(inp->inp_vflag);
2944 db_print_indent(indent);
2945 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
2946 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2948 db_print_indent(indent);
2950 if (inp->inp_vflag & INP_IPV6) {
2951 db_printf("in6p_options: %p in6p_outputopts: %p "
2952 "in6p_moptions: %p\n", inp->in6p_options,
2953 inp->in6p_outputopts, inp->in6p_moptions);
2954 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
2955 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2960 db_printf("inp_ip_tos: %d inp_ip_options: %p "
2961 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2962 inp->inp_options, inp->inp_moptions);
2965 db_print_indent(indent);
2966 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
2967 (uintmax_t)inp->inp_gencnt);
2970 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
2975 db_printf("usage: show inpcb <addr>\n");
2978 inp = (struct inpcb *)addr;
2980 db_print_inpcb(inp, "inpcb", 0);
2986 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
2990 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
2992 union if_snd_tag_modify_params params = {
2993 .rate_limit.max_rate = max_pacing_rate,
2994 .rate_limit.flags = M_NOWAIT,
2996 struct m_snd_tag *mst;
2999 mst = inp->inp_snd_tag;
3003 if (mst->sw->snd_tag_modify == NULL) {
3006 error = mst->sw->snd_tag_modify(mst, ¶ms);
3012 * Query existing TX rate limit based on the existing
3013 * "inp->inp_snd_tag", if any.
3016 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3018 union if_snd_tag_query_params params = { };
3019 struct m_snd_tag *mst;
3022 mst = inp->inp_snd_tag;
3026 if (mst->sw->snd_tag_query == NULL) {
3029 error = mst->sw->snd_tag_query(mst, ¶ms);
3030 if (error == 0 && p_max_pacing_rate != NULL)
3031 *p_max_pacing_rate = params.rate_limit.max_rate;
3037 * Query existing TX queue level based on the existing
3038 * "inp->inp_snd_tag", if any.
3041 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3043 union if_snd_tag_query_params params = { };
3044 struct m_snd_tag *mst;
3047 mst = inp->inp_snd_tag;
3051 if (mst->sw->snd_tag_query == NULL)
3052 return (EOPNOTSUPP);
3054 error = mst->sw->snd_tag_query(mst, ¶ms);
3055 if (error == 0 && p_txqueue_level != NULL)
3056 *p_txqueue_level = params.rate_limit.queue_level;
3061 * Allocate a new TX rate limit send tag from the network interface
3062 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3065 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3066 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
3069 union if_snd_tag_alloc_params params = {
3070 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3071 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3072 .rate_limit.hdr.flowid = flowid,
3073 .rate_limit.hdr.flowtype = flowtype,
3074 .rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3075 .rate_limit.max_rate = max_pacing_rate,
3076 .rate_limit.flags = M_NOWAIT,
3080 INP_WLOCK_ASSERT(inp);
3083 * If there is already a send tag, or the INP is being torn
3084 * down, allocating a new send tag is not allowed. Else send
3087 if (*st != NULL || (inp->inp_flags & INP_DROPPED) != 0)
3090 error = m_snd_tag_alloc(ifp, ¶ms, st);
3093 counter_u64_add(rate_limit_set_ok, 1);
3094 counter_u64_add(rate_limit_active, 1);
3095 } else if (error != EOPNOTSUPP)
3096 counter_u64_add(rate_limit_alloc_fail, 1);
3102 in_pcbdetach_tag(struct m_snd_tag *mst)
3105 m_snd_tag_rele(mst);
3107 counter_u64_add(rate_limit_active, -1);
3112 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3116 in_pcbdetach_txrtlmt(struct inpcb *inp)
3118 struct m_snd_tag *mst;
3120 INP_WLOCK_ASSERT(inp);
3122 mst = inp->inp_snd_tag;
3123 inp->inp_snd_tag = NULL;
3128 m_snd_tag_rele(mst);
3130 counter_u64_add(rate_limit_active, -1);
3135 in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
3140 * If the existing send tag is for the wrong interface due to
3141 * a route change, first drop the existing tag. Set the
3142 * CHANGED flag so that we will keep trying to allocate a new
3143 * tag if we fail to allocate one this time.
3145 if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
3146 in_pcbdetach_txrtlmt(inp);
3147 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3151 * NOTE: When attaching to a network interface a reference is
3152 * made to ensure the network interface doesn't go away until
3153 * all ratelimit connections are gone. The network interface
3154 * pointers compared below represent valid network interfaces,
3155 * except when comparing towards NULL.
3157 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3159 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3160 if (inp->inp_snd_tag != NULL)
3161 in_pcbdetach_txrtlmt(inp);
3163 } else if (inp->inp_snd_tag == NULL) {
3165 * In order to utilize packet pacing with RSS, we need
3166 * to wait until there is a valid RSS hash before we
3169 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3172 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3173 mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
3176 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3178 if (error == 0 || error == EOPNOTSUPP)
3179 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3185 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3186 * is set in the fast path and will attach/detach/modify the TX rate
3187 * limit send tag based on the socket's so_max_pacing_rate value.
3190 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3192 struct socket *socket;
3193 uint32_t max_pacing_rate;
3199 socket = inp->inp_socket;
3203 if (!INP_WLOCKED(inp)) {
3205 * NOTE: If the write locking fails, we need to bail
3206 * out and use the non-ratelimited ring for the
3207 * transmit until there is a new chance to get the
3210 if (!INP_TRY_UPGRADE(inp))
3218 * NOTE: The so_max_pacing_rate value is read unlocked,
3219 * because atomic updates are not required since the variable
3220 * is checked at every mbuf we send. It is assumed that the
3221 * variable read itself will be atomic.
3223 max_pacing_rate = socket->so_max_pacing_rate;
3225 in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3232 * Track route changes for TX rate limiting.
3235 in_pcboutput_eagain(struct inpcb *inp)
3242 if (inp->inp_snd_tag == NULL)
3245 if (!INP_WLOCKED(inp)) {
3247 * NOTE: If the write locking fails, we need to bail
3248 * out and use the non-ratelimited ring for the
3249 * transmit until there is a new chance to get the
3252 if (!INP_TRY_UPGRADE(inp))
3259 /* detach rate limiting */
3260 in_pcbdetach_txrtlmt(inp);
3262 /* make sure new mbuf send tag allocation is made */
3263 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3273 rate_limit_new = counter_u64_alloc(M_WAITOK);
3274 rate_limit_chg = counter_u64_alloc(M_WAITOK);
3275 rate_limit_active = counter_u64_alloc(M_WAITOK);
3276 rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
3277 rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
3280 SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3282 #endif /* RATELIMIT */