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, struct ifnet *ifp,
143 uint8_t numa_domain);
145 #define RANGECHK(var, min, max) \
146 if ((var) < (min)) { (var) = (min); } \
147 else if ((var) > (max)) { (var) = (max); }
150 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
154 error = sysctl_handle_int(oidp, arg1, arg2, req);
156 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
157 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
158 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
159 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
160 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
161 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
168 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
169 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
172 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
173 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
174 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
176 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
177 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
178 &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
180 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
181 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
182 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
184 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
185 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
186 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
188 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
189 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
190 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
192 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
193 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
194 &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
196 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
197 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
198 &VNET_NAME(ipport_reservedhigh), 0, "");
199 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
200 CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
201 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
202 CTLFLAG_VNET | CTLFLAG_RW,
203 &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
206 counter_u64_t rate_limit_new;
207 counter_u64_t rate_limit_chg;
208 counter_u64_t rate_limit_active;
209 counter_u64_t rate_limit_alloc_fail;
210 counter_u64_t rate_limit_set_ok;
212 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
214 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
215 &rate_limit_active, "Active rate limited connections");
216 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
217 &rate_limit_alloc_fail, "Rate limited connection failures");
218 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
219 &rate_limit_set_ok, "Rate limited setting succeeded");
220 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
221 &rate_limit_new, "Total Rate limit new attempts");
222 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
223 &rate_limit_chg, "Total Rate limited change attempts");
225 #endif /* RATELIMIT */
229 VNET_DEFINE(uint32_t, in_pcbhashseed);
231 in_pcbhashseed_init(void)
234 V_in_pcbhashseed = arc4random();
236 VNET_SYSINIT(in_pcbhashseed_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
237 in_pcbhashseed_init, 0);
239 static void in_pcbremhash(struct inpcb *);
242 * in_pcb.c: manage the Protocol Control Blocks.
244 * NOTE: It is assumed that most of these functions will be called with
245 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
246 * functions often modify hash chains or addresses in pcbs.
249 static struct inpcblbgroup *
250 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, struct ucred *cred,
251 u_char vflag, uint16_t port, const union in_dependaddr *addr, int size,
254 struct inpcblbgroup *grp;
257 bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
258 grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
261 grp->il_cred = crhold(cred);
262 grp->il_vflag = vflag;
263 grp->il_lport = port;
264 grp->il_numa_domain = numa_domain;
265 grp->il_dependladdr = *addr;
266 grp->il_inpsiz = size;
267 CK_LIST_INSERT_HEAD(hdr, grp, il_list);
272 in_pcblbgroup_free_deferred(epoch_context_t ctx)
274 struct inpcblbgroup *grp;
276 grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
277 crfree(grp->il_cred);
282 in_pcblbgroup_free(struct inpcblbgroup *grp)
285 CK_LIST_REMOVE(grp, il_list);
286 NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
289 static struct inpcblbgroup *
290 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
291 struct inpcblbgroup *old_grp, int size)
293 struct inpcblbgroup *grp;
296 grp = in_pcblbgroup_alloc(hdr, old_grp->il_cred, old_grp->il_vflag,
297 old_grp->il_lport, &old_grp->il_dependladdr, size,
298 old_grp->il_numa_domain);
302 KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
303 ("invalid new local group size %d and old local group count %d",
304 grp->il_inpsiz, old_grp->il_inpcnt));
306 for (i = 0; i < old_grp->il_inpcnt; ++i)
307 grp->il_inp[i] = old_grp->il_inp[i];
308 grp->il_inpcnt = old_grp->il_inpcnt;
309 in_pcblbgroup_free(old_grp);
314 * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
315 * and shrink group if possible.
318 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
321 struct inpcblbgroup *grp, *new_grp;
324 for (; i + 1 < grp->il_inpcnt; ++i)
325 grp->il_inp[i] = grp->il_inp[i + 1];
328 if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
329 grp->il_inpcnt <= grp->il_inpsiz / 4) {
330 /* Shrink this group. */
331 new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
338 * Add PCB to load balance group for SO_REUSEPORT_LB option.
341 in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
343 const static struct timeval interval = { 60, 0 };
344 static struct timeval lastprint;
345 struct inpcbinfo *pcbinfo;
346 struct inpcblbgrouphead *hdr;
347 struct inpcblbgroup *grp;
350 pcbinfo = inp->inp_pcbinfo;
352 INP_WLOCK_ASSERT(inp);
353 INP_HASH_WLOCK_ASSERT(pcbinfo);
357 * Don't allow IPv4 mapped INET6 wild socket.
359 if ((inp->inp_vflag & INP_IPV4) &&
360 inp->inp_laddr.s_addr == INADDR_ANY &&
361 INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
366 idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
367 hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
368 CK_LIST_FOREACH(grp, hdr, il_list) {
369 if (grp->il_cred->cr_prison == inp->inp_cred->cr_prison &&
370 grp->il_vflag == inp->inp_vflag &&
371 grp->il_lport == inp->inp_lport &&
372 grp->il_numa_domain == numa_domain &&
373 memcmp(&grp->il_dependladdr,
374 &inp->inp_inc.inc_ie.ie_dependladdr,
375 sizeof(grp->il_dependladdr)) == 0) {
380 /* Create new load balance group. */
381 grp = in_pcblbgroup_alloc(hdr, inp->inp_cred, inp->inp_vflag,
382 inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
383 INPCBLBGROUP_SIZMIN, numa_domain);
386 } else if (grp->il_inpcnt == grp->il_inpsiz) {
387 if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
388 if (ratecheck(&lastprint, &interval))
389 printf("lb group port %d, limit reached\n",
390 ntohs(grp->il_lport));
394 /* Expand this local group. */
395 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
400 KASSERT(grp->il_inpcnt < grp->il_inpsiz,
401 ("invalid local group size %d and count %d", grp->il_inpsiz,
404 grp->il_inp[grp->il_inpcnt] = inp;
410 * Remove PCB from load balance group.
413 in_pcbremlbgrouphash(struct inpcb *inp)
415 struct inpcbinfo *pcbinfo;
416 struct inpcblbgrouphead *hdr;
417 struct inpcblbgroup *grp;
420 pcbinfo = inp->inp_pcbinfo;
422 INP_WLOCK_ASSERT(inp);
423 INP_HASH_WLOCK_ASSERT(pcbinfo);
425 hdr = &pcbinfo->ipi_lbgrouphashbase[
426 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
427 CK_LIST_FOREACH(grp, hdr, il_list) {
428 for (i = 0; i < grp->il_inpcnt; ++i) {
429 if (grp->il_inp[i] != inp)
432 if (grp->il_inpcnt == 1) {
433 /* We are the last, free this local group. */
434 in_pcblbgroup_free(grp);
436 /* Pull up inpcbs, shrink group if possible. */
437 in_pcblbgroup_reorder(hdr, &grp, i);
445 in_pcblbgroup_numa(struct inpcb *inp, int arg)
447 struct inpcbinfo *pcbinfo;
448 struct inpcblbgrouphead *hdr;
449 struct inpcblbgroup *grp;
454 case TCP_REUSPORT_LB_NUMA_NODOM:
455 numa_domain = M_NODOM;
457 case TCP_REUSPORT_LB_NUMA_CURDOM:
458 numa_domain = PCPU_GET(domain);
461 if (arg < 0 || arg >= vm_ndomains)
467 pcbinfo = inp->inp_pcbinfo;
468 INP_WLOCK_ASSERT(inp);
469 INP_HASH_WLOCK(pcbinfo);
470 hdr = &pcbinfo->ipi_lbgrouphashbase[
471 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
472 CK_LIST_FOREACH(grp, hdr, il_list) {
473 for (i = 0; i < grp->il_inpcnt; ++i) {
474 if (grp->il_inp[i] != inp)
477 if (grp->il_numa_domain == numa_domain) {
478 goto abort_with_hash_wlock;
481 /* Remove it from the old group. */
482 in_pcbremlbgrouphash(inp);
484 /* Add it to the new group based on numa domain. */
485 in_pcbinslbgrouphash(inp, numa_domain);
486 goto abort_with_hash_wlock;
490 abort_with_hash_wlock:
491 INP_HASH_WUNLOCK(pcbinfo);
495 /* Make sure it is safe to use hashinit(9) on CK_LIST. */
496 CTASSERT(sizeof(struct inpcbhead) == sizeof(LIST_HEAD(, inpcb)));
499 * Initialize an inpcbinfo - a per-VNET instance of connections db.
502 in_pcbinfo_init(struct inpcbinfo *pcbinfo, struct inpcbstorage *pcbstor,
503 u_int hash_nelements, u_int porthash_nelements)
506 mtx_init(&pcbinfo->ipi_lock, pcbstor->ips_infolock_name, NULL, MTX_DEF);
507 mtx_init(&pcbinfo->ipi_hash_lock, pcbstor->ips_hashlock_name,
510 pcbinfo->ipi_vnet = curvnet;
512 CK_LIST_INIT(&pcbinfo->ipi_listhead);
513 pcbinfo->ipi_count = 0;
514 pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
515 &pcbinfo->ipi_hashmask);
516 porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
517 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
518 &pcbinfo->ipi_porthashmask);
519 pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
520 &pcbinfo->ipi_lbgrouphashmask);
521 pcbinfo->ipi_zone = pcbstor->ips_zone;
522 pcbinfo->ipi_portzone = pcbstor->ips_portzone;
523 pcbinfo->ipi_smr = uma_zone_get_smr(pcbinfo->ipi_zone);
527 * Destroy an inpcbinfo.
530 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
533 KASSERT(pcbinfo->ipi_count == 0,
534 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
536 hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
537 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
538 pcbinfo->ipi_porthashmask);
539 hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
540 pcbinfo->ipi_lbgrouphashmask);
541 mtx_destroy(&pcbinfo->ipi_hash_lock);
542 mtx_destroy(&pcbinfo->ipi_lock);
546 * Initialize a pcbstorage - per protocol zones to allocate inpcbs.
548 static void inpcb_dtor(void *, int, void *);
549 static void inpcb_fini(void *, int);
551 in_pcbstorage_init(void *arg)
553 struct inpcbstorage *pcbstor = arg;
555 pcbstor->ips_zone = uma_zcreate(pcbstor->ips_zone_name,
556 pcbstor->ips_size, NULL, inpcb_dtor, pcbstor->ips_pcbinit,
557 inpcb_fini, UMA_ALIGN_CACHE, UMA_ZONE_SMR);
558 pcbstor->ips_portzone = uma_zcreate(pcbstor->ips_portzone_name,
559 sizeof(struct inpcbport), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
560 uma_zone_set_smr(pcbstor->ips_portzone,
561 uma_zone_get_smr(pcbstor->ips_zone));
565 * Destroy a pcbstorage - used by unloadable protocols.
568 in_pcbstorage_destroy(void *arg)
570 struct inpcbstorage *pcbstor = arg;
572 uma_zdestroy(pcbstor->ips_zone);
573 uma_zdestroy(pcbstor->ips_portzone);
577 * Allocate a PCB and associate it with the socket.
578 * On success return with the PCB locked.
581 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
584 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
588 inp = uma_zalloc_smr(pcbinfo->ipi_zone, M_NOWAIT);
591 bzero(&inp->inp_start_zero, inp_zero_size);
593 inp->inp_numa_domain = M_NODOM;
595 inp->inp_pcbinfo = pcbinfo;
596 inp->inp_socket = so;
597 inp->inp_cred = crhold(so->so_cred);
598 inp->inp_inc.inc_fibnum = so->so_fibnum;
600 error = mac_inpcb_init(inp, M_NOWAIT);
603 mac_inpcb_create(so, inp);
605 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
606 error = ipsec_init_pcbpolicy(inp);
609 mac_inpcb_destroy(inp);
615 if (INP_SOCKAF(so) == AF_INET6) {
616 inp->inp_vflag |= INP_IPV6PROTO | INP_IPV6;
618 inp->inp_flags |= IN6P_IPV6_V6ONLY;
621 inp->inp_vflag |= INP_IPV4;
623 if (V_ip6_auto_flowlabel)
624 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
625 inp->in6p_hops = -1; /* use kernel default */
628 #if defined(INET) && defined(INET6)
632 inp->inp_vflag |= INP_IPV4;
635 * Routes in inpcb's can cache L2 as well; they are guaranteed
638 inp->inp_route.ro_flags = RT_LLE_CACHE;
639 refcount_init(&inp->inp_refcount, 1); /* Reference from socket. */
641 INP_INFO_WLOCK(pcbinfo);
642 pcbinfo->ipi_count++;
643 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
644 CK_LIST_INSERT_HEAD(&pcbinfo->ipi_listhead, inp, inp_list);
645 INP_INFO_WUNLOCK(pcbinfo);
650 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
652 uma_zfree_smr(pcbinfo->ipi_zone, inp);
659 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
663 KASSERT(nam == NULL || nam->sa_family == AF_INET,
664 ("%s: invalid address family for %p", __func__, nam));
665 KASSERT(nam == NULL || nam->sa_len == sizeof(struct sockaddr_in),
666 ("%s: invalid address length for %p", __func__, nam));
667 INP_WLOCK_ASSERT(inp);
668 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
670 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
672 anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
673 error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
674 &inp->inp_lport, cred);
677 if (in_pcbinshash(inp) != 0) {
678 inp->inp_laddr.s_addr = INADDR_ANY;
683 inp->inp_flags |= INP_ANONPORT;
688 #if defined(INET) || defined(INET6)
690 * Assign a local port like in_pcb_lport(), but also used with connect()
691 * and a foreign address and port. If fsa is non-NULL, choose a local port
692 * that is unused with those, otherwise one that is completely unused.
693 * lsa can be NULL for IPv6.
696 in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
697 struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
699 struct inpcbinfo *pcbinfo;
700 struct inpcb *tmpinp;
701 unsigned short *lastport;
703 u_short aux, first, last, lport;
705 struct in_addr laddr, faddr;
708 struct in6_addr *laddr6, *faddr6;
711 pcbinfo = inp->inp_pcbinfo;
714 * Because no actual state changes occur here, a global write lock on
715 * the pcbinfo isn't required.
717 INP_LOCK_ASSERT(inp);
718 INP_HASH_LOCK_ASSERT(pcbinfo);
720 if (inp->inp_flags & INP_HIGHPORT) {
721 first = V_ipport_hifirstauto; /* sysctl */
722 last = V_ipport_hilastauto;
723 lastport = &pcbinfo->ipi_lasthi;
724 } else if (inp->inp_flags & INP_LOWPORT) {
725 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
728 first = V_ipport_lowfirstauto; /* 1023 */
729 last = V_ipport_lowlastauto; /* 600 */
730 lastport = &pcbinfo->ipi_lastlow;
732 first = V_ipport_firstauto; /* sysctl */
733 last = V_ipport_lastauto;
734 lastport = &pcbinfo->ipi_lastport;
738 * Instead of having two loops further down counting up or down
739 * make sure that first is always <= last and go with only one
740 * code path implementing all logic.
749 laddr.s_addr = INADDR_ANY; /* used by INET6+INET below too */
750 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
752 laddr = ((struct sockaddr_in *)lsa)->sin_addr;
754 faddr = ((struct sockaddr_in *)fsa)->sin_addr;
759 if ((inp->inp_vflag & INP_IPV6) != 0) {
761 laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
763 faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
770 if (V_ipport_randomized)
771 *lastport = first + (arc4random() % (last - first));
773 count = last - first;
776 if (count-- < 0) /* completely used? */
777 return (EADDRNOTAVAIL);
779 if (*lastport < first || *lastport > last)
781 lport = htons(*lastport);
785 if (lsa->sa_family == AF_INET) {
786 tmpinp = in_pcblookup_hash_locked(pcbinfo,
787 faddr, fport, laddr, lport, lookupflags,
792 if (lsa->sa_family == AF_INET6) {
793 tmpinp = in6_pcblookup_hash_locked(pcbinfo,
794 faddr6, fport, laddr6, lport, lookupflags,
800 if ((inp->inp_vflag & INP_IPV6) != 0) {
801 tmpinp = in6_pcblookup_local(pcbinfo,
802 &inp->in6p_laddr, lport, lookupflags, cred);
804 if (tmpinp == NULL &&
805 (inp->inp_vflag & INP_IPV4))
806 tmpinp = in_pcblookup_local(pcbinfo,
807 laddr, lport, lookupflags, cred);
811 #if defined(INET) && defined(INET6)
815 tmpinp = in_pcblookup_local(pcbinfo, laddr,
816 lport, lookupflags, cred);
819 } while (tmpinp != NULL);
827 * Select a local port (number) to use.
830 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
831 struct ucred *cred, int lookupflags)
833 struct sockaddr_in laddr;
836 bzero(&laddr, sizeof(laddr));
837 laddr.sin_family = AF_INET;
838 laddr.sin_addr = *laddrp;
840 return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
841 NULL, lportp, NULL, 0, cred, lookupflags));
845 * Return cached socket options.
848 inp_so_options(const struct inpcb *inp)
854 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
855 so_options |= SO_REUSEPORT_LB;
856 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
857 so_options |= SO_REUSEPORT;
858 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
859 so_options |= SO_REUSEADDR;
862 #endif /* INET || INET6 */
865 * Check if a new BINDMULTI socket is allowed to be created.
867 * ni points to the new inp.
868 * oi points to the existing inp.
870 * This checks whether the existing inp also has BINDMULTI and
871 * whether the credentials match.
874 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
876 /* Check permissions match */
877 if ((ni->inp_flags2 & INP_BINDMULTI) &&
878 (ni->inp_cred->cr_uid !=
879 oi->inp_cred->cr_uid))
882 /* Check the existing inp has BINDMULTI set */
883 if ((ni->inp_flags2 & INP_BINDMULTI) &&
884 ((oi->inp_flags2 & INP_BINDMULTI) == 0))
888 * We're okay - either INP_BINDMULTI isn't set on ni, or
889 * it is and it matches the checks.
896 * Set up a bind operation on a PCB, performing port allocation
897 * as required, but do not actually modify the PCB. Callers can
898 * either complete the bind by setting inp_laddr/inp_lport and
899 * calling in_pcbinshash(), or they can just use the resulting
900 * port and address to authorise the sending of a once-off packet.
902 * On error, the values of *laddrp and *lportp are not changed.
905 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
906 u_short *lportp, struct ucred *cred)
908 struct socket *so = inp->inp_socket;
909 struct sockaddr_in *sin;
910 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
911 struct in_addr laddr;
913 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
917 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
918 * so that we don't have to add to the (already messy) code below.
920 int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
923 * No state changes, so read locks are sufficient here.
925 INP_LOCK_ASSERT(inp);
926 INP_HASH_LOCK_ASSERT(pcbinfo);
928 laddr.s_addr = *laddrp;
929 if (nam != NULL && laddr.s_addr != INADDR_ANY)
931 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
932 lookupflags = INPLOOKUP_WILDCARD;
934 if ((error = prison_local_ip4(cred, &laddr)) != 0)
937 sin = (struct sockaddr_in *)nam;
938 KASSERT(sin->sin_family == AF_INET,
939 ("%s: invalid family for address %p", __func__, sin));
940 KASSERT(sin->sin_len == sizeof(*sin),
941 ("%s: invalid length for address %p", __func__, sin));
943 error = prison_local_ip4(cred, &sin->sin_addr);
946 if (sin->sin_port != *lportp) {
947 /* Don't allow the port to change. */
950 lport = sin->sin_port;
952 /* NB: lport is left as 0 if the port isn't being changed. */
953 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
955 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
956 * allow complete duplication of binding if
957 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
958 * and a multicast address is bound on both
959 * new and duplicated sockets.
961 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
962 reuseport = SO_REUSEADDR|SO_REUSEPORT;
964 * XXX: How to deal with SO_REUSEPORT_LB here?
965 * Treat same as SO_REUSEPORT for now.
967 if ((so->so_options &
968 (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
969 reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
970 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
971 sin->sin_port = 0; /* yech... */
972 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
974 * Is the address a local IP address?
975 * If INP_BINDANY is set, then the socket may be bound
976 * to any endpoint address, local or not.
978 if ((inp->inp_flags & INP_BINDANY) == 0 &&
979 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
980 return (EADDRNOTAVAIL);
982 laddr = sin->sin_addr;
987 if (ntohs(lport) <= V_ipport_reservedhigh &&
988 ntohs(lport) >= V_ipport_reservedlow &&
989 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
991 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
992 priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
993 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
994 lport, INPLOOKUP_WILDCARD, cred);
997 * This entire block sorely needs a rewrite.
1000 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1001 (so->so_type != SOCK_STREAM ||
1002 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
1003 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
1004 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
1005 (t->inp_flags2 & INP_REUSEPORT) ||
1006 (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
1007 (inp->inp_cred->cr_uid !=
1008 t->inp_cred->cr_uid))
1009 return (EADDRINUSE);
1012 * If the socket is a BINDMULTI socket, then
1013 * the credentials need to match and the
1014 * original socket also has to have been bound
1017 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1018 return (EADDRINUSE);
1020 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1021 lport, lookupflags, cred);
1022 if (t && ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1023 (reuseport & inp_so_options(t)) == 0 &&
1024 (reuseport_lb & inp_so_options(t)) == 0) {
1026 if (ntohl(sin->sin_addr.s_addr) !=
1028 ntohl(t->inp_laddr.s_addr) !=
1030 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1031 (t->inp_vflag & INP_IPV6PROTO) == 0)
1033 return (EADDRINUSE);
1034 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
1035 return (EADDRINUSE);
1042 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1046 *laddrp = laddr.s_addr;
1052 * Connect from a socket to a specified address.
1053 * Both address and port must be specified in argument sin.
1054 * If don't have a local address for this socket yet,
1058 in_pcbconnect(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred,
1061 u_short lport, fport;
1062 in_addr_t laddr, faddr;
1063 int anonport, error;
1065 INP_WLOCK_ASSERT(inp);
1066 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1068 lport = inp->inp_lport;
1069 laddr = inp->inp_laddr.s_addr;
1070 anonport = (lport == 0);
1071 error = in_pcbconnect_setup(inp, sin, &laddr, &lport, &faddr, &fport,
1076 /* Do the initial binding of the local address if required. */
1077 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1078 KASSERT(rehash == true,
1079 ("Rehashing required for unbound inps"));
1080 inp->inp_lport = lport;
1081 inp->inp_laddr.s_addr = laddr;
1082 if (in_pcbinshash(inp) != 0) {
1083 inp->inp_laddr.s_addr = INADDR_ANY;
1089 /* Commit the remaining changes. */
1090 inp->inp_lport = lport;
1091 inp->inp_laddr.s_addr = laddr;
1092 inp->inp_faddr.s_addr = faddr;
1093 inp->inp_fport = fport;
1101 inp->inp_flags |= INP_ANONPORT;
1106 * Do proper source address selection on an unbound socket in case
1107 * of connect. Take jails into account as well.
1110 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1114 struct sockaddr *sa;
1115 struct sockaddr_in *sin, dst;
1116 struct nhop_object *nh;
1120 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1123 * Bypass source address selection and use the primary jail IP
1126 if (!prison_saddrsel_ip4(cred, laddr))
1132 bzero(&dst, sizeof(dst));
1134 sin->sin_family = AF_INET;
1135 sin->sin_len = sizeof(struct sockaddr_in);
1136 sin->sin_addr.s_addr = faddr->s_addr;
1139 * If route is known our src addr is taken from the i/f,
1142 * Find out route to destination.
1144 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1145 nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
1149 * If we found a route, use the address corresponding to
1150 * the outgoing interface.
1152 * Otherwise assume faddr is reachable on a directly connected
1153 * network and try to find a corresponding interface to take
1154 * the source address from.
1156 if (nh == NULL || nh->nh_ifp == NULL) {
1157 struct in_ifaddr *ia;
1160 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1161 inp->inp_socket->so_fibnum));
1163 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1164 inp->inp_socket->so_fibnum));
1167 error = ENETUNREACH;
1171 if (!prison_flag(cred, PR_IP4)) {
1172 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1178 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1180 if (sa->sa_family != AF_INET)
1182 sin = (struct sockaddr_in *)sa;
1183 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1184 ia = (struct in_ifaddr *)ifa;
1189 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1193 /* 3. As a last resort return the 'default' jail address. */
1194 error = prison_get_ip4(cred, laddr);
1199 * If the outgoing interface on the route found is not
1200 * a loopback interface, use the address from that interface.
1201 * In case of jails do those three steps:
1202 * 1. check if the interface address belongs to the jail. If so use it.
1203 * 2. check if we have any address on the outgoing interface
1204 * belonging to this jail. If so use it.
1205 * 3. as a last resort return the 'default' jail address.
1207 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
1208 struct in_ifaddr *ia;
1211 /* If not jailed, use the default returned. */
1212 if (!prison_flag(cred, PR_IP4)) {
1213 ia = (struct in_ifaddr *)nh->nh_ifa;
1214 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1219 /* 1. Check if the iface address belongs to the jail. */
1220 sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1221 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1222 ia = (struct in_ifaddr *)nh->nh_ifa;
1223 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1228 * 2. Check if we have any address on the outgoing interface
1229 * belonging to this jail.
1233 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1235 if (sa->sa_family != AF_INET)
1237 sin = (struct sockaddr_in *)sa;
1238 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1239 ia = (struct in_ifaddr *)ifa;
1244 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1248 /* 3. As a last resort return the 'default' jail address. */
1249 error = prison_get_ip4(cred, laddr);
1254 * The outgoing interface is marked with 'loopback net', so a route
1255 * to ourselves is here.
1256 * Try to find the interface of the destination address and then
1257 * take the address from there. That interface is not necessarily
1258 * a loopback interface.
1259 * In case of jails, check that it is an address of the jail
1260 * and if we cannot find, fall back to the 'default' jail address.
1262 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
1263 struct in_ifaddr *ia;
1265 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
1266 inp->inp_socket->so_fibnum));
1268 ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
1269 inp->inp_socket->so_fibnum));
1271 ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
1273 if (!prison_flag(cred, PR_IP4)) {
1275 error = ENETUNREACH;
1278 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1288 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1290 if (sa->sa_family != AF_INET)
1292 sin = (struct sockaddr_in *)sa;
1293 if (prison_check_ip4(cred,
1294 &sin->sin_addr) == 0) {
1295 ia = (struct in_ifaddr *)ifa;
1300 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1305 /* 3. As a last resort return the 'default' jail address. */
1306 error = prison_get_ip4(cred, laddr);
1315 * Set up for a connect from a socket to the specified address.
1316 * On entry, *laddrp and *lportp should contain the current local
1317 * address and port for the PCB; these are updated to the values
1318 * that should be placed in inp_laddr and inp_lport to complete
1321 * On success, *faddrp and *fportp will be set to the remote address
1322 * and port. These are not updated in the error case.
1325 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr_in *sin,
1326 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1329 struct in_ifaddr *ia;
1330 struct in_addr laddr, faddr;
1331 u_short lport, fport;
1334 KASSERT(sin->sin_family == AF_INET,
1335 ("%s: invalid address family for %p", __func__, sin));
1336 KASSERT(sin->sin_len == sizeof(*sin),
1337 ("%s: invalid address length for %p", __func__, sin));
1340 * Because a global state change doesn't actually occur here, a read
1341 * lock is sufficient.
1344 INP_LOCK_ASSERT(inp);
1345 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1347 if (sin->sin_port == 0)
1348 return (EADDRNOTAVAIL);
1349 laddr.s_addr = *laddrp;
1351 faddr = sin->sin_addr;
1352 fport = sin->sin_port;
1354 if (CALC_FLOWID_OUTBOUND) {
1355 uint32_t hash_val, hash_type;
1357 hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
1358 inp->inp_socket->so_proto->pr_protocol, &hash_type);
1360 inp->inp_flowid = hash_val;
1361 inp->inp_flowtype = hash_type;
1364 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1366 * If the destination address is INADDR_ANY,
1367 * use the primary local address.
1368 * If the supplied address is INADDR_BROADCAST,
1369 * and the primary interface supports broadcast,
1370 * choose the broadcast address for that interface.
1372 if (faddr.s_addr == INADDR_ANY) {
1374 IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1375 if ((error = prison_get_ip4(cred, &faddr)) != 0)
1377 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1378 if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1380 faddr = satosin(&CK_STAILQ_FIRST(
1381 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1384 if (laddr.s_addr == INADDR_ANY) {
1385 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1387 * If the destination address is multicast and an outgoing
1388 * interface has been set as a multicast option, prefer the
1389 * address of that interface as our source address.
1391 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1392 inp->inp_moptions != NULL) {
1393 struct ip_moptions *imo;
1396 imo = inp->inp_moptions;
1397 if (imo->imo_multicast_ifp != NULL) {
1398 ifp = imo->imo_multicast_ifp;
1399 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1400 if (ia->ia_ifp == ifp &&
1401 prison_check_ip4(cred,
1402 &ia->ia_addr.sin_addr) == 0)
1406 error = EADDRNOTAVAIL;
1408 laddr = ia->ia_addr.sin_addr;
1418 if (in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1419 fport, laddr, lport, 0, NULL, M_NODOM) != NULL)
1420 return (EADDRINUSE);
1422 struct sockaddr_in lsin, fsin;
1424 bzero(&lsin, sizeof(lsin));
1425 bzero(&fsin, sizeof(fsin));
1426 lsin.sin_family = AF_INET;
1427 lsin.sin_addr = laddr;
1428 fsin.sin_family = AF_INET;
1429 fsin.sin_addr = faddr;
1430 error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
1431 &lport, (struct sockaddr *)& fsin, fport, cred,
1432 INPLOOKUP_WILDCARD);
1436 *laddrp = laddr.s_addr;
1438 *faddrp = faddr.s_addr;
1444 in_pcbdisconnect(struct inpcb *inp)
1447 INP_WLOCK_ASSERT(inp);
1448 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1450 inp->inp_laddr.s_addr = INADDR_ANY;
1451 inp->inp_faddr.s_addr = INADDR_ANY;
1458 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1459 * For most protocols, this will be invoked immediately prior to calling
1460 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1461 * socket, in which case in_pcbfree() is deferred.
1464 in_pcbdetach(struct inpcb *inp)
1467 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1470 if (inp->inp_snd_tag != NULL)
1471 in_pcbdetach_txrtlmt(inp);
1473 inp->inp_socket->so_pcb = NULL;
1474 inp->inp_socket = NULL;
1478 * inpcb hash lookups are protected by SMR section.
1480 * Once desired pcb has been found, switching from SMR section to a pcb
1481 * lock is performed with inp_smr_lock(). We can not use INP_(W|R)LOCK
1482 * here because SMR is a critical section.
1483 * In 99%+ cases inp_smr_lock() would obtain the lock immediately.
1486 inp_lock(struct inpcb *inp, const inp_lookup_t lock)
1489 lock == INPLOOKUP_RLOCKPCB ?
1490 rw_rlock(&inp->inp_lock) : rw_wlock(&inp->inp_lock);
1494 inp_unlock(struct inpcb *inp, const inp_lookup_t lock)
1497 lock == INPLOOKUP_RLOCKPCB ?
1498 rw_runlock(&inp->inp_lock) : rw_wunlock(&inp->inp_lock);
1502 inp_trylock(struct inpcb *inp, const inp_lookup_t lock)
1505 return (lock == INPLOOKUP_RLOCKPCB ?
1506 rw_try_rlock(&inp->inp_lock) : rw_try_wlock(&inp->inp_lock));
1510 in_pcbrele(struct inpcb *inp, const inp_lookup_t lock)
1513 return (lock == INPLOOKUP_RLOCKPCB ?
1514 in_pcbrele_rlocked(inp) : in_pcbrele_wlocked(inp));
1518 _inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock, const int ignflags)
1521 MPASS(lock == INPLOOKUP_RLOCKPCB || lock == INPLOOKUP_WLOCKPCB);
1522 SMR_ASSERT_ENTERED(inp->inp_pcbinfo->ipi_smr);
1524 if (__predict_true(inp_trylock(inp, lock))) {
1525 if (__predict_false(inp->inp_flags & ignflags)) {
1526 smr_exit(inp->inp_pcbinfo->ipi_smr);
1527 inp_unlock(inp, lock);
1530 smr_exit(inp->inp_pcbinfo->ipi_smr);
1534 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1535 smr_exit(inp->inp_pcbinfo->ipi_smr);
1536 inp_lock(inp, lock);
1537 if (__predict_false(in_pcbrele(inp, lock)))
1540 * inp acquired through refcount & lock for sure didn't went
1541 * through uma_zfree(). However, it may have already went
1542 * through in_pcbfree() and has another reference, that
1543 * prevented its release by our in_pcbrele().
1545 if (__predict_false(inp->inp_flags & ignflags)) {
1546 inp_unlock(inp, lock);
1551 smr_exit(inp->inp_pcbinfo->ipi_smr);
1557 inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock)
1561 * in_pcblookup() family of functions ignore not only freed entries,
1562 * that may be found due to lockless access to the hash, but dropped
1565 return (_inp_smr_lock(inp, lock, INP_FREED | INP_DROPPED));
1569 * inp_next() - inpcb hash/list traversal iterator
1571 * Requires initialized struct inpcb_iterator for context.
1572 * The structure can be initialized with INP_ITERATOR() or INP_ALL_ITERATOR().
1574 * - Iterator can have either write-lock or read-lock semantics, that can not
1576 * - Iterator can iterate either over all pcbs list (INP_ALL_LIST), or through
1577 * a single hash slot. Note: only rip_input() does the latter.
1578 * - Iterator may have optional bool matching function. The matching function
1579 * will be executed for each inpcb in the SMR context, so it can not acquire
1580 * locks and can safely access only immutable fields of inpcb.
1582 * A fresh initialized iterator has NULL inpcb in its context and that
1583 * means that inp_next() call would return the very first inpcb on the list
1584 * locked with desired semantic. In all following calls the context pointer
1585 * shall hold the current inpcb pointer. The KPI user is not supposed to
1586 * unlock the current inpcb! Upon end of traversal inp_next() will return NULL
1587 * and write NULL to its context. After end of traversal an iterator can be
1590 * List traversals have the following features/constraints:
1591 * - New entries won't be seen, as they are always added to the head of a list.
1592 * - Removed entries won't stop traversal as long as they are not added to
1593 * a different list. This is violated by in_pcbrehash().
1595 #define II_LIST_FIRST(ipi, hash) \
1596 (((hash) == INP_ALL_LIST) ? \
1597 CK_LIST_FIRST(&(ipi)->ipi_listhead) : \
1598 CK_LIST_FIRST(&(ipi)->ipi_hashbase[(hash)]))
1599 #define II_LIST_NEXT(inp, hash) \
1600 (((hash) == INP_ALL_LIST) ? \
1601 CK_LIST_NEXT((inp), inp_list) : \
1602 CK_LIST_NEXT((inp), inp_hash))
1603 #define II_LOCK_ASSERT(inp, lock) \
1604 rw_assert(&(inp)->inp_lock, \
1605 (lock) == INPLOOKUP_RLOCKPCB ? RA_RLOCKED : RA_WLOCKED )
1607 inp_next(struct inpcb_iterator *ii)
1609 const struct inpcbinfo *ipi = ii->ipi;
1610 inp_match_t *match = ii->match;
1611 void *ctx = ii->ctx;
1612 inp_lookup_t lock = ii->lock;
1613 int hash = ii->hash;
1616 if (ii->inp == NULL) { /* First call. */
1617 smr_enter(ipi->ipi_smr);
1618 /* This is unrolled CK_LIST_FOREACH(). */
1619 for (inp = II_LIST_FIRST(ipi, hash);
1621 inp = II_LIST_NEXT(inp, hash)) {
1622 if (match != NULL && (match)(inp, ctx) == false)
1624 if (__predict_true(_inp_smr_lock(inp, lock, INP_FREED)))
1627 smr_enter(ipi->ipi_smr);
1628 MPASS(inp != II_LIST_FIRST(ipi, hash));
1629 inp = II_LIST_FIRST(ipi, hash);
1636 smr_exit(ipi->ipi_smr);
1643 /* Not a first call. */
1644 smr_enter(ipi->ipi_smr);
1647 II_LOCK_ASSERT(inp, lock);
1649 inp = II_LIST_NEXT(inp, hash);
1651 smr_exit(ipi->ipi_smr);
1655 if (match != NULL && (match)(inp, ctx) == false)
1658 if (__predict_true(inp_trylock(inp, lock))) {
1659 if (__predict_false(inp->inp_flags & INP_FREED)) {
1661 * Entries are never inserted in middle of a list, thus
1662 * as long as we are in SMR, we can continue traversal.
1663 * Jump to 'restart' should yield in the same result,
1664 * but could produce unnecessary looping. Could this
1665 * looping be unbound?
1667 inp_unlock(inp, lock);
1670 smr_exit(ipi->ipi_smr);
1676 * Can't obtain lock immediately, thus going hard. Once we exit the
1677 * SMR section we can no longer jump to 'next', and our only stable
1678 * anchoring point is ii->inp, which we keep locked for this case, so
1679 * we jump to 'restart'.
1681 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1682 smr_exit(ipi->ipi_smr);
1683 inp_lock(inp, lock);
1684 if (__predict_false(in_pcbrele(inp, lock))) {
1685 smr_enter(ipi->ipi_smr);
1689 * See comment in inp_smr_lock().
1691 if (__predict_false(inp->inp_flags & INP_FREED)) {
1692 inp_unlock(inp, lock);
1693 smr_enter(ipi->ipi_smr);
1700 inp_unlock(ii->inp, lock);
1707 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1708 * stability of an inpcb pointer despite the inpcb lock being released or
1709 * SMR section exited.
1711 * To free a reference later in_pcbrele_(r|w)locked() must be performed.
1714 in_pcbref(struct inpcb *inp)
1716 u_int old __diagused;
1718 old = refcount_acquire(&inp->inp_refcount);
1719 KASSERT(old > 0, ("%s: refcount 0", __func__));
1723 * Drop a refcount on an inpcb elevated using in_pcbref(), potentially
1724 * freeing the pcb, if the reference was very last.
1727 in_pcbrele_rlocked(struct inpcb *inp)
1730 INP_RLOCK_ASSERT(inp);
1732 if (refcount_release(&inp->inp_refcount) == 0)
1735 MPASS(inp->inp_flags & INP_FREED);
1736 MPASS(inp->inp_socket == NULL);
1737 MPASS(inp->inp_in_hpts == 0);
1739 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1744 in_pcbrele_wlocked(struct inpcb *inp)
1747 INP_WLOCK_ASSERT(inp);
1749 if (refcount_release(&inp->inp_refcount) == 0)
1752 MPASS(inp->inp_flags & INP_FREED);
1753 MPASS(inp->inp_socket == NULL);
1754 MPASS(inp->inp_in_hpts == 0);
1756 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1761 * Unconditionally schedule an inpcb to be freed by decrementing its
1762 * reference count, which should occur only after the inpcb has been detached
1763 * from its socket. If another thread holds a temporary reference (acquired
1764 * using in_pcbref()) then the free is deferred until that reference is
1765 * released using in_pcbrele_(r|w)locked(), but the inpcb is still unlocked.
1766 * Almost all work, including removal from global lists, is done in this
1767 * context, where the pcbinfo lock is held.
1770 in_pcbfree(struct inpcb *inp)
1772 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1774 struct ip_moptions *imo;
1777 struct ip6_moptions *im6o;
1780 INP_WLOCK_ASSERT(inp);
1781 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1782 KASSERT((inp->inp_flags & INP_FREED) == 0,
1783 ("%s: called twice for pcb %p", __func__, inp));
1785 inp->inp_flags |= INP_FREED;
1786 INP_INFO_WLOCK(pcbinfo);
1787 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1788 pcbinfo->ipi_count--;
1789 CK_LIST_REMOVE(inp, inp_list);
1790 INP_INFO_WUNLOCK(pcbinfo);
1792 if (inp->inp_flags & INP_INHASHLIST)
1795 RO_INVALIDATE_CACHE(&inp->inp_route);
1797 mac_inpcb_destroy(inp);
1799 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1800 if (inp->inp_sp != NULL)
1801 ipsec_delete_pcbpolicy(inp);
1804 if (inp->inp_options)
1805 (void)m_free(inp->inp_options);
1806 imo = inp->inp_moptions;
1809 if (inp->inp_vflag & INP_IPV6PROTO) {
1810 ip6_freepcbopts(inp->in6p_outputopts);
1811 im6o = inp->in6p_moptions;
1816 if (__predict_false(in_pcbrele_wlocked(inp) == false)) {
1820 ip6_freemoptions(im6o);
1823 inp_freemoptions(imo);
1825 /* Destruction is finalized in inpcb_dtor(). */
1829 inpcb_dtor(void *mem, int size, void *arg)
1831 struct inpcb *inp = mem;
1833 crfree(inp->inp_cred);
1835 inp->inp_cred = NULL;
1840 * Different protocols initialize their inpcbs differently - giving
1841 * different name to the lock. But they all are disposed the same.
1844 inpcb_fini(void *mem, int size)
1846 struct inpcb *inp = mem;
1848 INP_LOCK_DESTROY(inp);
1852 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1853 * port reservation, and preventing it from being returned by inpcb lookups.
1855 * It is used by TCP to mark an inpcb as unused and avoid future packet
1856 * delivery or event notification when a socket remains open but TCP has
1857 * closed. This might occur as a result of a shutdown()-initiated TCP close
1858 * or a RST on the wire, and allows the port binding to be reused while still
1859 * maintaining the invariant that so_pcb always points to a valid inpcb until
1862 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1863 * in_pcbnotifyall() and in_pcbpurgeif0()?
1866 in_pcbdrop(struct inpcb *inp)
1869 INP_WLOCK_ASSERT(inp);
1871 if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1872 MPASS(inp->inp_refcount > 1);
1875 inp->inp_flags |= INP_DROPPED;
1876 if (inp->inp_flags & INP_INHASHLIST)
1882 * Common routines to return the socket addresses associated with inpcbs.
1885 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1887 struct sockaddr_in *sin;
1889 sin = malloc(sizeof *sin, M_SONAME,
1891 sin->sin_family = AF_INET;
1892 sin->sin_len = sizeof(*sin);
1893 sin->sin_addr = *addr_p;
1894 sin->sin_port = port;
1896 return (struct sockaddr *)sin;
1900 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1903 struct in_addr addr;
1906 inp = sotoinpcb(so);
1907 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1910 port = inp->inp_lport;
1911 addr = inp->inp_laddr;
1914 *nam = in_sockaddr(port, &addr);
1919 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1922 struct in_addr addr;
1925 inp = sotoinpcb(so);
1926 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1929 port = inp->inp_fport;
1930 addr = inp->inp_faddr;
1933 *nam = in_sockaddr(port, &addr);
1938 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1939 struct inpcb *(*notify)(struct inpcb *, int))
1941 struct inpcb *inp, *inp_temp;
1943 INP_INFO_WLOCK(pcbinfo);
1944 CK_LIST_FOREACH_SAFE(inp, &pcbinfo->ipi_listhead, inp_list, inp_temp) {
1947 if ((inp->inp_vflag & INP_IPV4) == 0) {
1952 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1953 inp->inp_socket == NULL) {
1957 if ((*notify)(inp, errno))
1960 INP_INFO_WUNLOCK(pcbinfo);
1964 inp_v4_multi_match(const struct inpcb *inp, void *v __unused)
1967 if ((inp->inp_vflag & INP_IPV4) && inp->inp_moptions != NULL)
1974 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1976 struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
1977 inp_v4_multi_match, NULL);
1979 struct in_multi *inm;
1980 struct in_mfilter *imf;
1981 struct ip_moptions *imo;
1983 IN_MULTI_LOCK_ASSERT();
1985 while ((inp = inp_next(&inpi)) != NULL) {
1986 INP_WLOCK_ASSERT(inp);
1988 imo = inp->inp_moptions;
1990 * Unselect the outgoing interface if it is being
1993 if (imo->imo_multicast_ifp == ifp)
1994 imo->imo_multicast_ifp = NULL;
1997 * Drop multicast group membership if we joined
1998 * through the interface being detached.
2000 * XXX This can all be deferred to an epoch_call
2003 IP_MFILTER_FOREACH(imf, &imo->imo_head) {
2004 if ((inm = imf->imf_inm) == NULL)
2006 if (inm->inm_ifp != ifp)
2008 ip_mfilter_remove(&imo->imo_head, imf);
2009 in_leavegroup_locked(inm, NULL);
2010 ip_mfilter_free(imf);
2017 * Lookup a PCB based on the local address and port. Caller must hold the
2018 * hash lock. No inpcb locks or references are acquired.
2020 #define INP_LOOKUP_MAPPED_PCB_COST 3
2022 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
2023 u_short lport, int lookupflags, struct ucred *cred)
2027 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
2033 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2034 ("%s: invalid lookup flags %d", __func__, lookupflags));
2035 INP_HASH_LOCK_ASSERT(pcbinfo);
2037 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
2038 struct inpcbhead *head;
2040 * Look for an unconnected (wildcard foreign addr) PCB that
2041 * matches the local address and port we're looking for.
2043 head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2044 pcbinfo->ipi_hashmask)];
2045 CK_LIST_FOREACH(inp, head, inp_hash) {
2047 /* XXX inp locking */
2048 if ((inp->inp_vflag & INP_IPV4) == 0)
2051 if (inp->inp_faddr.s_addr == INADDR_ANY &&
2052 inp->inp_laddr.s_addr == laddr.s_addr &&
2053 inp->inp_lport == lport) {
2057 if (prison_equal_ip4(cred->cr_prison,
2058 inp->inp_cred->cr_prison))
2067 struct inpcbporthead *porthash;
2068 struct inpcbport *phd;
2069 struct inpcb *match = NULL;
2071 * Best fit PCB lookup.
2073 * First see if this local port is in use by looking on the
2076 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2077 pcbinfo->ipi_porthashmask)];
2078 CK_LIST_FOREACH(phd, porthash, phd_hash) {
2079 if (phd->phd_port == lport)
2084 * Port is in use by one or more PCBs. Look for best
2087 CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2089 if (!prison_equal_ip4(inp->inp_cred->cr_prison,
2093 /* XXX inp locking */
2094 if ((inp->inp_vflag & INP_IPV4) == 0)
2097 * We never select the PCB that has
2098 * INP_IPV6 flag and is bound to :: if
2099 * we have another PCB which is bound
2100 * to 0.0.0.0. If a PCB has the
2101 * INP_IPV6 flag, then we set its cost
2102 * higher than IPv4 only PCBs.
2104 * Note that the case only happens
2105 * when a socket is bound to ::, under
2106 * the condition that the use of the
2107 * mapped address is allowed.
2109 if ((inp->inp_vflag & INP_IPV6) != 0)
2110 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2112 if (inp->inp_faddr.s_addr != INADDR_ANY)
2114 if (inp->inp_laddr.s_addr != INADDR_ANY) {
2115 if (laddr.s_addr == INADDR_ANY)
2117 else if (inp->inp_laddr.s_addr != laddr.s_addr)
2120 if (laddr.s_addr != INADDR_ANY)
2123 if (wildcard < matchwild) {
2125 matchwild = wildcard;
2134 #undef INP_LOOKUP_MAPPED_PCB_COST
2137 in_pcblookup_lb_numa_match(const struct inpcblbgroup *grp, int domain)
2139 return (domain == M_NODOM || domain == grp->il_numa_domain);
2142 static struct inpcb *
2143 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
2144 const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
2145 uint16_t fport, int lookupflags, int domain)
2147 const struct inpcblbgrouphead *hdr;
2148 struct inpcblbgroup *grp;
2149 struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
2151 INP_HASH_LOCK_ASSERT(pcbinfo);
2153 hdr = &pcbinfo->ipi_lbgrouphashbase[
2154 INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
2157 * Search for an LB group match based on the following criteria:
2158 * - prefer jailed groups to non-jailed groups
2159 * - prefer exact source address matches to wildcard matches
2160 * - prefer groups bound to the specified NUMA domain
2162 jail_exact = jail_wild = local_exact = local_wild = NULL;
2163 CK_LIST_FOREACH(grp, hdr, il_list) {
2167 if (!(grp->il_vflag & INP_IPV4))
2170 if (grp->il_lport != lport)
2173 injail = prison_flag(grp->il_cred, PR_IP4) != 0;
2174 if (injail && prison_check_ip4_locked(grp->il_cred->cr_prison,
2178 if (grp->il_laddr.s_addr == laddr->s_addr) {
2181 if (in_pcblookup_lb_numa_match(grp, domain))
2182 /* This is a perfect match. */
2184 } else if (local_exact == NULL ||
2185 in_pcblookup_lb_numa_match(grp, domain)) {
2188 } else if (grp->il_laddr.s_addr == INADDR_ANY &&
2189 (lookupflags & INPLOOKUP_WILDCARD) != 0) {
2191 if (jail_wild == NULL ||
2192 in_pcblookup_lb_numa_match(grp, domain))
2194 } else if (local_wild == NULL ||
2195 in_pcblookup_lb_numa_match(grp, domain)) {
2201 if (jail_exact != NULL)
2203 else if (jail_wild != NULL)
2205 else if (local_exact != NULL)
2212 return (grp->il_inp[INP_PCBLBGROUP_PKTHASH(faddr, lport, fport) %
2217 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
2218 * that the caller has either locked the hash list, which usually happens
2219 * for bind(2) operations, or is in SMR section, which happens when sorting
2220 * out incoming packets.
2222 static struct inpcb *
2223 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2224 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2225 struct ifnet *ifp, uint8_t numa_domain)
2227 struct inpcbhead *head;
2229 u_short fport = fport_arg, lport = lport_arg;
2231 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2232 ("%s: invalid lookup flags %d", __func__, lookupflags));
2233 KASSERT(faddr.s_addr != INADDR_ANY,
2234 ("%s: invalid foreign address", __func__));
2235 KASSERT(laddr.s_addr != INADDR_ANY,
2236 ("%s: invalid local address", __func__));
2237 INP_HASH_LOCK_ASSERT(pcbinfo);
2240 * First look for an exact match.
2242 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&faddr, lport, fport,
2243 pcbinfo->ipi_hashmask)];
2244 CK_LIST_FOREACH(inp, head, inp_hash) {
2246 /* XXX inp locking */
2247 if ((inp->inp_vflag & INP_IPV4) == 0)
2250 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2251 inp->inp_laddr.s_addr == laddr.s_addr &&
2252 inp->inp_fport == fport &&
2253 inp->inp_lport == lport)
2258 * Then look for a wildcard match, if requested.
2260 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2261 struct inpcb *local_wild = NULL, *local_exact = NULL;
2263 struct inpcb *local_wild_mapped = NULL;
2265 struct inpcb *jail_wild = NULL;
2269 * First see if an LB group matches the request before scanning
2270 * all sockets on this port.
2272 inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2273 fport, lookupflags, numa_domain);
2278 * Order of socket selection - we always prefer jails.
2279 * 1. jailed, non-wild.
2281 * 3. non-jailed, non-wild.
2282 * 4. non-jailed, wild.
2285 head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2286 pcbinfo->ipi_hashmask)];
2287 CK_LIST_FOREACH(inp, head, inp_hash) {
2289 /* XXX inp locking */
2290 if ((inp->inp_vflag & INP_IPV4) == 0)
2293 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2294 inp->inp_lport != lport)
2297 injail = prison_flag(inp->inp_cred, PR_IP4);
2299 if (prison_check_ip4_locked(
2300 inp->inp_cred->cr_prison, &laddr) != 0)
2303 if (local_exact != NULL)
2307 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2312 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2314 /* XXX inp locking, NULL check */
2315 if (inp->inp_vflag & INP_IPV6PROTO)
2316 local_wild_mapped = inp;
2324 } /* LIST_FOREACH */
2325 if (jail_wild != NULL)
2327 if (local_exact != NULL)
2328 return (local_exact);
2329 if (local_wild != NULL)
2330 return (local_wild);
2332 if (local_wild_mapped != NULL)
2333 return (local_wild_mapped);
2335 } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2341 * Lookup PCB in hash list, using pcbinfo tables. This variation locks the
2342 * hash list lock, and will return the inpcb locked (i.e., requires
2343 * INPLOOKUP_LOCKPCB).
2345 static struct inpcb *
2346 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2347 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2348 struct ifnet *ifp, uint8_t numa_domain)
2352 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2353 ("%s: invalid lookup flags %d", __func__, lookupflags));
2354 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2355 ("%s: LOCKPCB not set", __func__));
2357 smr_enter(pcbinfo->ipi_smr);
2358 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2359 lookupflags & INPLOOKUP_WILDCARD, ifp, numa_domain);
2361 if (__predict_false(inp_smr_lock(inp,
2362 (lookupflags & INPLOOKUP_LOCKMASK)) == false))
2365 smr_exit(pcbinfo->ipi_smr);
2371 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2372 * from which a pre-calculated hash value may be extracted.
2375 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2376 struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2378 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2379 lookupflags, ifp, M_NODOM));
2383 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2384 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2385 struct ifnet *ifp, struct mbuf *m)
2387 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2388 lookupflags, ifp, m->m_pkthdr.numa_domain));
2393 * Insert PCB onto various hash lists.
2396 in_pcbinshash(struct inpcb *inp)
2398 struct inpcbhead *pcbhash;
2399 struct inpcbporthead *pcbporthash;
2400 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2401 struct inpcbport *phd;
2403 INP_WLOCK_ASSERT(inp);
2404 INP_HASH_WLOCK_ASSERT(pcbinfo);
2406 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2407 ("in_pcbinshash: INP_INHASHLIST"));
2410 if (inp->inp_vflag & INP_IPV6)
2411 pcbhash = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2412 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2415 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2416 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2418 pcbporthash = &pcbinfo->ipi_porthashbase[
2419 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2422 * Add entry to load balance group.
2423 * Only do this if SO_REUSEPORT_LB is set.
2425 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0) {
2426 int error = in_pcbinslbgrouphash(inp, M_NODOM);
2432 * Go through port list and look for a head for this lport.
2434 CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2435 if (phd->phd_port == inp->inp_lport)
2440 * If none exists, malloc one and tack it on.
2443 phd = uma_zalloc_smr(pcbinfo->ipi_portzone, M_NOWAIT);
2445 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2446 in_pcbremlbgrouphash(inp);
2449 phd->phd_port = inp->inp_lport;
2450 CK_LIST_INIT(&phd->phd_pcblist);
2451 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2454 CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2455 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2456 inp->inp_flags |= INP_INHASHLIST;
2462 in_pcbremhash(struct inpcb *inp)
2464 struct inpcbport *phd = inp->inp_phd;
2466 INP_WLOCK_ASSERT(inp);
2467 MPASS(inp->inp_flags & INP_INHASHLIST);
2469 INP_HASH_WLOCK(inp->inp_pcbinfo);
2470 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2471 in_pcbremlbgrouphash(inp);
2472 CK_LIST_REMOVE(inp, inp_hash);
2473 CK_LIST_REMOVE(inp, inp_portlist);
2474 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2475 CK_LIST_REMOVE(phd, phd_hash);
2476 uma_zfree_smr(inp->inp_pcbinfo->ipi_portzone, phd);
2478 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
2479 inp->inp_flags &= ~INP_INHASHLIST;
2483 * Move PCB to the proper hash bucket when { faddr, fport } have been
2484 * changed. NOTE: This does not handle the case of the lport changing (the
2485 * hashed port list would have to be updated as well), so the lport must
2486 * not change after in_pcbinshash() has been called.
2488 * XXXGL: a race between this function and SMR-protected hash iterator
2489 * will lead to iterator traversing a possibly wrong hash list. However,
2490 * this race should have been here since change from rwlock to epoch.
2493 in_pcbrehash(struct inpcb *inp)
2495 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2496 struct inpcbhead *head;
2498 INP_WLOCK_ASSERT(inp);
2499 INP_HASH_WLOCK_ASSERT(pcbinfo);
2501 KASSERT(inp->inp_flags & INP_INHASHLIST,
2502 ("in_pcbrehash: !INP_INHASHLIST"));
2505 if (inp->inp_vflag & INP_IPV6)
2506 head = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2507 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2510 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2511 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2513 CK_LIST_REMOVE(inp, inp_hash);
2514 CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2518 * Check for alternatives when higher level complains
2519 * about service problems. For now, invalidate cached
2520 * routing information. If the route was created dynamically
2521 * (by a redirect), time to try a default gateway again.
2524 in_losing(struct inpcb *inp)
2527 RO_INVALIDATE_CACHE(&inp->inp_route);
2532 * A set label operation has occurred at the socket layer, propagate the
2533 * label change into the in_pcb for the socket.
2536 in_pcbsosetlabel(struct socket *so)
2541 inp = sotoinpcb(so);
2542 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2546 mac_inpcb_sosetlabel(so, inp);
2553 inp_wlock(struct inpcb *inp)
2560 inp_wunlock(struct inpcb *inp)
2567 inp_rlock(struct inpcb *inp)
2574 inp_runlock(struct inpcb *inp)
2580 #ifdef INVARIANT_SUPPORT
2582 inp_lock_assert(struct inpcb *inp)
2585 INP_WLOCK_ASSERT(inp);
2589 inp_unlock_assert(struct inpcb *inp)
2592 INP_UNLOCK_ASSERT(inp);
2597 inp_apply_all(struct inpcbinfo *pcbinfo,
2598 void (*func)(struct inpcb *, void *), void *arg)
2600 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2601 INPLOOKUP_WLOCKPCB);
2604 while ((inp = inp_next(&inpi)) != NULL)
2609 inp_inpcbtosocket(struct inpcb *inp)
2612 INP_WLOCK_ASSERT(inp);
2613 return (inp->inp_socket);
2617 inp_inpcbtotcpcb(struct inpcb *inp)
2620 INP_WLOCK_ASSERT(inp);
2621 return ((struct tcpcb *)inp->inp_ppcb);
2625 inp_ip_tos_get(const struct inpcb *inp)
2628 return (inp->inp_ip_tos);
2632 inp_ip_tos_set(struct inpcb *inp, int val)
2635 inp->inp_ip_tos = val;
2639 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2640 uint32_t *faddr, uint16_t *fp)
2643 INP_LOCK_ASSERT(inp);
2644 *laddr = inp->inp_laddr.s_addr;
2645 *faddr = inp->inp_faddr.s_addr;
2646 *lp = inp->inp_lport;
2647 *fp = inp->inp_fport;
2651 so_sotoinpcb(struct socket *so)
2654 return (sotoinpcb(so));
2658 * Create an external-format (``xinpcb'') structure using the information in
2659 * the kernel-format in_pcb structure pointed to by inp. This is done to
2660 * reduce the spew of irrelevant information over this interface, to isolate
2661 * user code from changes in the kernel structure, and potentially to provide
2662 * information-hiding if we decide that some of this information should be
2663 * hidden from users.
2666 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2669 bzero(xi, sizeof(*xi));
2670 xi->xi_len = sizeof(struct xinpcb);
2671 if (inp->inp_socket)
2672 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2673 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2674 xi->inp_gencnt = inp->inp_gencnt;
2675 xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2676 xi->inp_flow = inp->inp_flow;
2677 xi->inp_flowid = inp->inp_flowid;
2678 xi->inp_flowtype = inp->inp_flowtype;
2679 xi->inp_flags = inp->inp_flags;
2680 xi->inp_flags2 = inp->inp_flags2;
2681 xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2682 xi->in6p_cksum = inp->in6p_cksum;
2683 xi->in6p_hops = inp->in6p_hops;
2684 xi->inp_ip_tos = inp->inp_ip_tos;
2685 xi->inp_vflag = inp->inp_vflag;
2686 xi->inp_ip_ttl = inp->inp_ip_ttl;
2687 xi->inp_ip_p = inp->inp_ip_p;
2688 xi->inp_ip_minttl = inp->inp_ip_minttl;
2692 sysctl_setsockopt(SYSCTL_HANDLER_ARGS, struct inpcbinfo *pcbinfo,
2693 int (*ctloutput_set)(struct inpcb *, struct sockopt *))
2695 struct sockopt sopt;
2696 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2697 INPLOOKUP_WLOCKPCB);
2699 struct sockopt_parameters *params;
2704 if (req->oldptr != NULL || req->oldlen != 0)
2706 if (req->newptr == NULL)
2708 if (req->newlen > sizeof(buf))
2710 error = SYSCTL_IN(req, buf, req->newlen);
2713 if (req->newlen < sizeof(struct sockopt_parameters))
2715 params = (struct sockopt_parameters *)buf;
2716 sopt.sopt_level = params->sop_level;
2717 sopt.sopt_name = params->sop_optname;
2718 sopt.sopt_dir = SOPT_SET;
2719 sopt.sopt_val = params->sop_optval;
2720 sopt.sopt_valsize = req->newlen - sizeof(struct sockopt_parameters);
2721 sopt.sopt_td = NULL;
2723 if (params->sop_inc.inc_flags & INC_ISIPV6) {
2724 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_laddr))
2725 params->sop_inc.inc6_laddr.s6_addr16[1] =
2726 htons(params->sop_inc.inc6_zoneid & 0xffff);
2727 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_faddr))
2728 params->sop_inc.inc6_faddr.s6_addr16[1] =
2729 htons(params->sop_inc.inc6_zoneid & 0xffff);
2732 if (params->sop_inc.inc_lport != htons(0)) {
2733 if (params->sop_inc.inc_fport == htons(0))
2734 inpi.hash = INP_PCBHASH_WILD(params->sop_inc.inc_lport,
2735 pcbinfo->ipi_hashmask);
2738 if (params->sop_inc.inc_flags & INC_ISIPV6)
2739 inpi.hash = INP6_PCBHASH(
2740 ¶ms->sop_inc.inc6_faddr,
2741 params->sop_inc.inc_lport,
2742 params->sop_inc.inc_fport,
2743 pcbinfo->ipi_hashmask);
2746 inpi.hash = INP_PCBHASH(
2747 ¶ms->sop_inc.inc_faddr,
2748 params->sop_inc.inc_lport,
2749 params->sop_inc.inc_fport,
2750 pcbinfo->ipi_hashmask);
2752 while ((inp = inp_next(&inpi)) != NULL)
2753 if (inp->inp_gencnt == params->sop_id) {
2754 if (inp->inp_flags & INP_DROPPED) {
2756 return (ECONNRESET);
2758 so = inp->inp_socket;
2759 KASSERT(so != NULL, ("inp_socket == NULL"));
2761 error = (*ctloutput_set)(inp, &sopt);
2772 db_print_indent(int indent)
2776 for (i = 0; i < indent; i++)
2781 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2783 char faddr_str[48], laddr_str[48];
2785 db_print_indent(indent);
2786 db_printf("%s at %p\n", name, inc);
2791 if (inc->inc_flags & INC_ISIPV6) {
2793 ip6_sprintf(laddr_str, &inc->inc6_laddr);
2794 ip6_sprintf(faddr_str, &inc->inc6_faddr);
2799 inet_ntoa_r(inc->inc_laddr, laddr_str);
2800 inet_ntoa_r(inc->inc_faddr, faddr_str);
2802 db_print_indent(indent);
2803 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
2804 ntohs(inc->inc_lport));
2805 db_print_indent(indent);
2806 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
2807 ntohs(inc->inc_fport));
2811 db_print_inpflags(int inp_flags)
2816 if (inp_flags & INP_RECVOPTS) {
2817 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2820 if (inp_flags & INP_RECVRETOPTS) {
2821 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2824 if (inp_flags & INP_RECVDSTADDR) {
2825 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2828 if (inp_flags & INP_ORIGDSTADDR) {
2829 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2832 if (inp_flags & INP_HDRINCL) {
2833 db_printf("%sINP_HDRINCL", comma ? ", " : "");
2836 if (inp_flags & INP_HIGHPORT) {
2837 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2840 if (inp_flags & INP_LOWPORT) {
2841 db_printf("%sINP_LOWPORT", comma ? ", " : "");
2844 if (inp_flags & INP_ANONPORT) {
2845 db_printf("%sINP_ANONPORT", comma ? ", " : "");
2848 if (inp_flags & INP_RECVIF) {
2849 db_printf("%sINP_RECVIF", comma ? ", " : "");
2852 if (inp_flags & INP_MTUDISC) {
2853 db_printf("%sINP_MTUDISC", comma ? ", " : "");
2856 if (inp_flags & INP_RECVTTL) {
2857 db_printf("%sINP_RECVTTL", comma ? ", " : "");
2860 if (inp_flags & INP_DONTFRAG) {
2861 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2864 if (inp_flags & INP_RECVTOS) {
2865 db_printf("%sINP_RECVTOS", comma ? ", " : "");
2868 if (inp_flags & IN6P_IPV6_V6ONLY) {
2869 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2872 if (inp_flags & IN6P_PKTINFO) {
2873 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2876 if (inp_flags & IN6P_HOPLIMIT) {
2877 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2880 if (inp_flags & IN6P_HOPOPTS) {
2881 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2884 if (inp_flags & IN6P_DSTOPTS) {
2885 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2888 if (inp_flags & IN6P_RTHDR) {
2889 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2892 if (inp_flags & IN6P_RTHDRDSTOPTS) {
2893 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2896 if (inp_flags & IN6P_TCLASS) {
2897 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2900 if (inp_flags & IN6P_AUTOFLOWLABEL) {
2901 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2904 if (inp_flags & INP_ONESBCAST) {
2905 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2908 if (inp_flags & INP_DROPPED) {
2909 db_printf("%sINP_DROPPED", comma ? ", " : "");
2912 if (inp_flags & INP_SOCKREF) {
2913 db_printf("%sINP_SOCKREF", comma ? ", " : "");
2916 if (inp_flags & IN6P_RFC2292) {
2917 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2920 if (inp_flags & IN6P_MTU) {
2921 db_printf("IN6P_MTU%s", comma ? ", " : "");
2927 db_print_inpvflag(u_char inp_vflag)
2932 if (inp_vflag & INP_IPV4) {
2933 db_printf("%sINP_IPV4", comma ? ", " : "");
2936 if (inp_vflag & INP_IPV6) {
2937 db_printf("%sINP_IPV6", comma ? ", " : "");
2940 if (inp_vflag & INP_IPV6PROTO) {
2941 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2947 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2950 db_print_indent(indent);
2951 db_printf("%s at %p\n", name, inp);
2955 db_print_indent(indent);
2956 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2958 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2960 db_print_indent(indent);
2961 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
2962 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2964 db_print_indent(indent);
2965 db_printf("inp_label: %p inp_flags: 0x%x (",
2966 inp->inp_label, inp->inp_flags);
2967 db_print_inpflags(inp->inp_flags);
2970 db_print_indent(indent);
2971 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
2973 db_print_inpvflag(inp->inp_vflag);
2976 db_print_indent(indent);
2977 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
2978 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2980 db_print_indent(indent);
2982 if (inp->inp_vflag & INP_IPV6) {
2983 db_printf("in6p_options: %p in6p_outputopts: %p "
2984 "in6p_moptions: %p\n", inp->in6p_options,
2985 inp->in6p_outputopts, inp->in6p_moptions);
2986 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
2987 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2992 db_printf("inp_ip_tos: %d inp_ip_options: %p "
2993 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2994 inp->inp_options, inp->inp_moptions);
2997 db_print_indent(indent);
2998 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
2999 (uintmax_t)inp->inp_gencnt);
3002 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3007 db_printf("usage: show inpcb <addr>\n");
3010 inp = (struct inpcb *)addr;
3012 db_print_inpcb(inp, "inpcb", 0);
3018 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3022 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3024 union if_snd_tag_modify_params params = {
3025 .rate_limit.max_rate = max_pacing_rate,
3026 .rate_limit.flags = M_NOWAIT,
3028 struct m_snd_tag *mst;
3031 mst = inp->inp_snd_tag;
3035 if (mst->sw->snd_tag_modify == NULL) {
3038 error = mst->sw->snd_tag_modify(mst, ¶ms);
3044 * Query existing TX rate limit based on the existing
3045 * "inp->inp_snd_tag", if any.
3048 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3050 union if_snd_tag_query_params params = { };
3051 struct m_snd_tag *mst;
3054 mst = inp->inp_snd_tag;
3058 if (mst->sw->snd_tag_query == NULL) {
3061 error = mst->sw->snd_tag_query(mst, ¶ms);
3062 if (error == 0 && p_max_pacing_rate != NULL)
3063 *p_max_pacing_rate = params.rate_limit.max_rate;
3069 * Query existing TX queue level based on the existing
3070 * "inp->inp_snd_tag", if any.
3073 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
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)
3084 return (EOPNOTSUPP);
3086 error = mst->sw->snd_tag_query(mst, ¶ms);
3087 if (error == 0 && p_txqueue_level != NULL)
3088 *p_txqueue_level = params.rate_limit.queue_level;
3093 * Allocate a new TX rate limit send tag from the network interface
3094 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3097 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3098 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
3101 union if_snd_tag_alloc_params params = {
3102 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3103 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3104 .rate_limit.hdr.flowid = flowid,
3105 .rate_limit.hdr.flowtype = flowtype,
3106 .rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3107 .rate_limit.max_rate = max_pacing_rate,
3108 .rate_limit.flags = M_NOWAIT,
3112 INP_WLOCK_ASSERT(inp);
3115 * If there is already a send tag, or the INP is being torn
3116 * down, allocating a new send tag is not allowed. Else send
3119 if (*st != NULL || (inp->inp_flags & INP_DROPPED) != 0)
3122 error = m_snd_tag_alloc(ifp, ¶ms, st);
3125 counter_u64_add(rate_limit_set_ok, 1);
3126 counter_u64_add(rate_limit_active, 1);
3127 } else if (error != EOPNOTSUPP)
3128 counter_u64_add(rate_limit_alloc_fail, 1);
3134 in_pcbdetach_tag(struct m_snd_tag *mst)
3137 m_snd_tag_rele(mst);
3139 counter_u64_add(rate_limit_active, -1);
3144 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3148 in_pcbdetach_txrtlmt(struct inpcb *inp)
3150 struct m_snd_tag *mst;
3152 INP_WLOCK_ASSERT(inp);
3154 mst = inp->inp_snd_tag;
3155 inp->inp_snd_tag = NULL;
3160 m_snd_tag_rele(mst);
3162 counter_u64_add(rate_limit_active, -1);
3167 in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
3172 * If the existing send tag is for the wrong interface due to
3173 * a route change, first drop the existing tag. Set the
3174 * CHANGED flag so that we will keep trying to allocate a new
3175 * tag if we fail to allocate one this time.
3177 if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
3178 in_pcbdetach_txrtlmt(inp);
3179 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3183 * NOTE: When attaching to a network interface a reference is
3184 * made to ensure the network interface doesn't go away until
3185 * all ratelimit connections are gone. The network interface
3186 * pointers compared below represent valid network interfaces,
3187 * except when comparing towards NULL.
3189 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3191 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3192 if (inp->inp_snd_tag != NULL)
3193 in_pcbdetach_txrtlmt(inp);
3195 } else if (inp->inp_snd_tag == NULL) {
3197 * In order to utilize packet pacing with RSS, we need
3198 * to wait until there is a valid RSS hash before we
3201 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3204 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3205 mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
3208 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3210 if (error == 0 || error == EOPNOTSUPP)
3211 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3217 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3218 * is set in the fast path and will attach/detach/modify the TX rate
3219 * limit send tag based on the socket's so_max_pacing_rate value.
3222 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3224 struct socket *socket;
3225 uint32_t max_pacing_rate;
3231 socket = inp->inp_socket;
3235 if (!INP_WLOCKED(inp)) {
3237 * NOTE: If the write locking fails, we need to bail
3238 * out and use the non-ratelimited ring for the
3239 * transmit until there is a new chance to get the
3242 if (!INP_TRY_UPGRADE(inp))
3250 * NOTE: The so_max_pacing_rate value is read unlocked,
3251 * because atomic updates are not required since the variable
3252 * is checked at every mbuf we send. It is assumed that the
3253 * variable read itself will be atomic.
3255 max_pacing_rate = socket->so_max_pacing_rate;
3257 in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3264 * Track route changes for TX rate limiting.
3267 in_pcboutput_eagain(struct inpcb *inp)
3274 if (inp->inp_snd_tag == NULL)
3277 if (!INP_WLOCKED(inp)) {
3279 * NOTE: If the write locking fails, we need to bail
3280 * out and use the non-ratelimited ring for the
3281 * transmit until there is a new chance to get the
3284 if (!INP_TRY_UPGRADE(inp))
3291 /* detach rate limiting */
3292 in_pcbdetach_txrtlmt(inp);
3294 /* make sure new mbuf send tag allocation is made */
3295 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3305 rate_limit_new = counter_u64_alloc(M_WAITOK);
3306 rate_limit_chg = counter_u64_alloc(M_WAITOK);
3307 rate_limit_active = counter_u64_alloc(M_WAITOK);
3308 rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
3309 rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
3312 SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3314 #endif /* RATELIMIT */