2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1991, 1993, 1995
5 * The Regents of the University of California.
6 * Copyright (c) 2007-2009 Robert N. M. Watson
7 * Copyright (c) 2010-2011 Juniper Networks, Inc.
10 * Portions of this software were developed by Robert N. M. Watson under
11 * contract to Juniper Networks, Inc.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @(#)in_pcb.c 8.4 (Berkeley) 5/24/95
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
44 #include "opt_ipsec.h"
46 #include "opt_inet6.h"
47 #include "opt_ratelimit.h"
48 #include "opt_pcbgroup.h"
51 #include <sys/param.h>
52 #include <sys/systm.h>
54 #include <sys/malloc.h>
56 #include <sys/callout.h>
57 #include <sys/eventhandler.h>
58 #include <sys/domain.h>
59 #include <sys/protosw.h>
60 #include <sys/rmlock.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sockio.h>
67 #include <sys/refcount.h>
69 #include <sys/kernel.h>
70 #include <sys/sysctl.h>
79 #include <net/if_var.h>
80 #include <net/if_types.h>
81 #include <net/if_llatbl.h>
82 #include <net/route.h>
83 #include <net/rss_config.h>
86 #if defined(INET) || defined(INET6)
87 #include <netinet/in.h>
88 #include <netinet/in_pcb.h>
89 #include <netinet/ip_var.h>
90 #include <netinet/tcp_var.h>
92 #include <netinet/tcp_hpts.h>
94 #include <netinet/udp.h>
95 #include <netinet/udp_var.h>
98 #include <netinet/in_var.h>
101 #include <netinet/ip6.h>
102 #include <netinet6/in6_pcb.h>
103 #include <netinet6/in6_var.h>
104 #include <netinet6/ip6_var.h>
107 #include <netipsec/ipsec_support.h>
109 #include <security/mac/mac_framework.h>
111 #define INPCBLBGROUP_SIZMIN 8
112 #define INPCBLBGROUP_SIZMAX 256
114 static struct callout ipport_tick_callout;
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 /* Variables dealing with random ephemeral port allocation. */
136 VNET_DEFINE(int, ipport_randomized) = 1; /* user controlled via sysctl */
137 VNET_DEFINE(int, ipport_randomcps) = 10; /* user controlled via sysctl */
138 VNET_DEFINE(int, ipport_randomtime) = 45; /* user controlled via sysctl */
139 VNET_DEFINE(int, ipport_stoprandom); /* toggled by ipport_tick */
140 VNET_DEFINE(int, ipport_tcpallocs);
141 VNET_DEFINE_STATIC(int, ipport_tcplastcount);
143 #define V_ipport_tcplastcount VNET(ipport_tcplastcount)
145 static void in_pcbremlists(struct inpcb *inp);
147 static struct inpcb *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
148 struct in_addr faddr, u_int fport_arg,
149 struct in_addr laddr, u_int lport_arg,
150 int lookupflags, struct ifnet *ifp);
152 #define RANGECHK(var, min, max) \
153 if ((var) < (min)) { (var) = (min); } \
154 else if ((var) > (max)) { (var) = (max); }
157 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
161 error = sysctl_handle_int(oidp, arg1, arg2, req);
163 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
164 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
165 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
166 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
167 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
168 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
175 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0,
178 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
179 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
180 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I", "");
181 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
182 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
183 &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I", "");
184 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
185 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
186 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I", "");
187 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
188 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
189 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I", "");
190 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
191 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
192 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I", "");
193 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
194 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
195 &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");
204 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
205 CTLFLAG_VNET | CTLFLAG_RW,
206 &VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
207 "allocations before switching to a sequental one");
208 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
209 CTLFLAG_VNET | CTLFLAG_RW,
210 &VNET_NAME(ipport_randomtime), 0,
211 "Minimum time to keep sequental port "
212 "allocation before switching to a random one");
216 * in_pcb.c: manage the Protocol Control Blocks.
218 * NOTE: It is assumed that most of these functions will be called with
219 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
220 * functions often modify hash chains or addresses in pcbs.
223 static struct inpcblbgroup *
224 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, u_char vflag,
225 uint16_t port, const union in_dependaddr *addr, int size)
227 struct inpcblbgroup *grp;
230 bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
231 grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
234 grp->il_vflag = vflag;
235 grp->il_lport = port;
236 grp->il_dependladdr = *addr;
237 grp->il_inpsiz = size;
238 CK_LIST_INSERT_HEAD(hdr, grp, il_list);
243 in_pcblbgroup_free_deferred(epoch_context_t ctx)
245 struct inpcblbgroup *grp;
247 grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
252 in_pcblbgroup_free(struct inpcblbgroup *grp)
255 CK_LIST_REMOVE(grp, il_list);
256 epoch_call(net_epoch_preempt, &grp->il_epoch_ctx,
257 in_pcblbgroup_free_deferred);
260 static struct inpcblbgroup *
261 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
262 struct inpcblbgroup *old_grp, int size)
264 struct inpcblbgroup *grp;
267 grp = in_pcblbgroup_alloc(hdr, old_grp->il_vflag,
268 old_grp->il_lport, &old_grp->il_dependladdr, size);
272 KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
273 ("invalid new local group size %d and old local group count %d",
274 grp->il_inpsiz, old_grp->il_inpcnt));
276 for (i = 0; i < old_grp->il_inpcnt; ++i)
277 grp->il_inp[i] = old_grp->il_inp[i];
278 grp->il_inpcnt = old_grp->il_inpcnt;
279 in_pcblbgroup_free(old_grp);
284 * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
285 * and shrink group if possible.
288 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
291 struct inpcblbgroup *grp, *new_grp;
294 for (; i + 1 < grp->il_inpcnt; ++i)
295 grp->il_inp[i] = grp->il_inp[i + 1];
298 if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
299 grp->il_inpcnt <= grp->il_inpsiz / 4) {
300 /* Shrink this group. */
301 new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
308 * Add PCB to load balance group for SO_REUSEPORT_LB option.
311 in_pcbinslbgrouphash(struct inpcb *inp)
313 const static struct timeval interval = { 60, 0 };
314 static struct timeval lastprint;
315 struct inpcbinfo *pcbinfo;
316 struct inpcblbgrouphead *hdr;
317 struct inpcblbgroup *grp;
320 pcbinfo = inp->inp_pcbinfo;
322 INP_WLOCK_ASSERT(inp);
323 INP_HASH_WLOCK_ASSERT(pcbinfo);
325 if (pcbinfo->ipi_lbgrouphashbase == NULL)
329 * Don't allow jailed socket to join local group.
331 if (inp->inp_socket != NULL && jailed(inp->inp_socket->so_cred))
336 * Don't allow IPv4 mapped INET6 wild socket.
338 if ((inp->inp_vflag & INP_IPV4) &&
339 inp->inp_laddr.s_addr == INADDR_ANY &&
340 INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
345 idx = INP_PCBLBGROUP_PORTHASH(inp->inp_lport,
346 pcbinfo->ipi_lbgrouphashmask);
347 hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
348 CK_LIST_FOREACH(grp, hdr, il_list) {
349 if (grp->il_vflag == inp->inp_vflag &&
350 grp->il_lport == inp->inp_lport &&
351 memcmp(&grp->il_dependladdr,
352 &inp->inp_inc.inc_ie.ie_dependladdr,
353 sizeof(grp->il_dependladdr)) == 0)
357 /* Create new load balance group. */
358 grp = in_pcblbgroup_alloc(hdr, inp->inp_vflag,
359 inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
360 INPCBLBGROUP_SIZMIN);
363 } else if (grp->il_inpcnt == grp->il_inpsiz) {
364 if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
365 if (ratecheck(&lastprint, &interval))
366 printf("lb group port %d, limit reached\n",
367 ntohs(grp->il_lport));
371 /* Expand this local group. */
372 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
377 KASSERT(grp->il_inpcnt < grp->il_inpsiz,
378 ("invalid local group size %d and count %d", grp->il_inpsiz,
381 grp->il_inp[grp->il_inpcnt] = inp;
387 * Remove PCB from load balance group.
390 in_pcbremlbgrouphash(struct inpcb *inp)
392 struct inpcbinfo *pcbinfo;
393 struct inpcblbgrouphead *hdr;
394 struct inpcblbgroup *grp;
397 pcbinfo = inp->inp_pcbinfo;
399 INP_WLOCK_ASSERT(inp);
400 INP_HASH_WLOCK_ASSERT(pcbinfo);
402 if (pcbinfo->ipi_lbgrouphashbase == NULL)
405 hdr = &pcbinfo->ipi_lbgrouphashbase[
406 INP_PCBLBGROUP_PORTHASH(inp->inp_lport,
407 pcbinfo->ipi_lbgrouphashmask)];
409 CK_LIST_FOREACH(grp, hdr, il_list) {
410 for (i = 0; i < grp->il_inpcnt; ++i) {
411 if (grp->il_inp[i] != inp)
414 if (grp->il_inpcnt == 1) {
415 /* We are the last, free this local group. */
416 in_pcblbgroup_free(grp);
418 /* Pull up inpcbs, shrink group if possible. */
419 in_pcblbgroup_reorder(hdr, &grp, i);
427 * Different protocols initialize their inpcbs differently - giving
428 * different name to the lock. But they all are disposed the same.
431 inpcb_fini(void *mem, int size)
433 struct inpcb *inp = mem;
435 INP_LOCK_DESTROY(inp);
439 * Initialize an inpcbinfo -- we should be able to reduce the number of
443 in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
444 struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
445 char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
448 INP_INFO_LOCK_INIT(pcbinfo, name);
449 INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash"); /* XXXRW: argument? */
450 INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
452 pcbinfo->ipi_vnet = curvnet;
454 pcbinfo->ipi_listhead = listhead;
455 CK_LIST_INIT(pcbinfo->ipi_listhead);
456 pcbinfo->ipi_count = 0;
457 pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
458 &pcbinfo->ipi_hashmask);
459 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
460 &pcbinfo->ipi_porthashmask);
461 pcbinfo->ipi_lbgrouphashbase = hashinit(hash_nelements, M_PCB,
462 &pcbinfo->ipi_lbgrouphashmask);
464 in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
466 pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
467 NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
468 uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
469 uma_zone_set_warning(pcbinfo->ipi_zone,
470 "kern.ipc.maxsockets limit reached");
474 * Destroy an inpcbinfo.
477 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
480 KASSERT(pcbinfo->ipi_count == 0,
481 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
483 hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
484 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
485 pcbinfo->ipi_porthashmask);
486 hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
487 pcbinfo->ipi_lbgrouphashmask);
489 in_pcbgroup_destroy(pcbinfo);
491 uma_zdestroy(pcbinfo->ipi_zone);
492 INP_LIST_LOCK_DESTROY(pcbinfo);
493 INP_HASH_LOCK_DESTROY(pcbinfo);
494 INP_INFO_LOCK_DESTROY(pcbinfo);
498 * Allocate a PCB and associate it with the socket.
499 * On success return with the PCB locked.
502 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
508 if (pcbinfo == &V_tcbinfo) {
509 INP_INFO_RLOCK_ASSERT(pcbinfo);
511 INP_INFO_WLOCK_ASSERT(pcbinfo);
516 inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
519 bzero(&inp->inp_start_zero, inp_zero_size);
520 inp->inp_pcbinfo = pcbinfo;
521 inp->inp_socket = so;
522 inp->inp_cred = crhold(so->so_cred);
523 inp->inp_inc.inc_fibnum = so->so_fibnum;
525 error = mac_inpcb_init(inp, M_NOWAIT);
528 mac_inpcb_create(so, inp);
530 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
531 error = ipsec_init_pcbpolicy(inp);
534 mac_inpcb_destroy(inp);
540 if (INP_SOCKAF(so) == AF_INET6) {
541 inp->inp_vflag |= INP_IPV6PROTO;
543 inp->inp_flags |= IN6P_IPV6_V6ONLY;
547 INP_LIST_WLOCK(pcbinfo);
548 CK_LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
549 pcbinfo->ipi_count++;
550 so->so_pcb = (caddr_t)inp;
552 if (V_ip6_auto_flowlabel)
553 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
555 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
556 refcount_init(&inp->inp_refcount, 1); /* Reference from inpcbinfo */
559 * Routes in inpcb's can cache L2 as well; they are guaranteed
562 inp->inp_route.ro_flags = RT_LLE_CACHE;
563 INP_LIST_WUNLOCK(pcbinfo);
564 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
567 crfree(inp->inp_cred);
568 uma_zfree(pcbinfo->ipi_zone, inp);
576 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
580 INP_WLOCK_ASSERT(inp);
581 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
583 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
585 anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
586 error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
587 &inp->inp_lport, cred);
590 if (in_pcbinshash(inp) != 0) {
591 inp->inp_laddr.s_addr = INADDR_ANY;
596 inp->inp_flags |= INP_ANONPORT;
602 * Select a local port (number) to use.
604 #if defined(INET) || defined(INET6)
606 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
607 struct ucred *cred, int lookupflags)
609 struct inpcbinfo *pcbinfo;
610 struct inpcb *tmpinp;
611 unsigned short *lastport;
612 int count, dorandom, error;
613 u_short aux, first, last, lport;
615 struct in_addr laddr;
618 pcbinfo = inp->inp_pcbinfo;
621 * Because no actual state changes occur here, a global write lock on
622 * the pcbinfo isn't required.
624 INP_LOCK_ASSERT(inp);
625 INP_HASH_LOCK_ASSERT(pcbinfo);
627 if (inp->inp_flags & INP_HIGHPORT) {
628 first = V_ipport_hifirstauto; /* sysctl */
629 last = V_ipport_hilastauto;
630 lastport = &pcbinfo->ipi_lasthi;
631 } else if (inp->inp_flags & INP_LOWPORT) {
632 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
635 first = V_ipport_lowfirstauto; /* 1023 */
636 last = V_ipport_lowlastauto; /* 600 */
637 lastport = &pcbinfo->ipi_lastlow;
639 first = V_ipport_firstauto; /* sysctl */
640 last = V_ipport_lastauto;
641 lastport = &pcbinfo->ipi_lastport;
644 * For UDP(-Lite), use random port allocation as long as the user
645 * allows it. For TCP (and as of yet unknown) connections,
646 * use random port allocation only if the user allows it AND
647 * ipport_tick() allows it.
649 if (V_ipport_randomized &&
650 (!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
651 pcbinfo == &V_ulitecbinfo))
656 * It makes no sense to do random port allocation if
657 * we have the only port available.
661 /* Make sure to not include UDP(-Lite) packets in the count. */
662 if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
663 V_ipport_tcpallocs++;
665 * Instead of having two loops further down counting up or down
666 * make sure that first is always <= last and go with only one
667 * code path implementing all logic.
676 /* Make the compiler happy. */
678 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
679 KASSERT(laddrp != NULL, ("%s: laddrp NULL for v4 inp %p",
684 tmpinp = NULL; /* Make compiler happy. */
688 *lastport = first + (arc4random() % (last - first));
690 count = last - first;
693 if (count-- < 0) /* completely used? */
694 return (EADDRNOTAVAIL);
696 if (*lastport < first || *lastport > last)
698 lport = htons(*lastport);
701 if ((inp->inp_vflag & INP_IPV6) != 0)
702 tmpinp = in6_pcblookup_local(pcbinfo,
703 &inp->in6p_laddr, lport, lookupflags, cred);
705 #if defined(INET) && defined(INET6)
709 tmpinp = in_pcblookup_local(pcbinfo, laddr,
710 lport, lookupflags, cred);
712 } while (tmpinp != NULL);
715 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4)
716 laddrp->s_addr = laddr.s_addr;
724 * Return cached socket options.
727 inp_so_options(const struct inpcb *inp)
733 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
734 so_options |= SO_REUSEPORT_LB;
735 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
736 so_options |= SO_REUSEPORT;
737 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
738 so_options |= SO_REUSEADDR;
741 #endif /* INET || INET6 */
744 * Check if a new BINDMULTI socket is allowed to be created.
746 * ni points to the new inp.
747 * oi points to the exisitng inp.
749 * This checks whether the existing inp also has BINDMULTI and
750 * whether the credentials match.
753 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
755 /* Check permissions match */
756 if ((ni->inp_flags2 & INP_BINDMULTI) &&
757 (ni->inp_cred->cr_uid !=
758 oi->inp_cred->cr_uid))
761 /* Check the existing inp has BINDMULTI set */
762 if ((ni->inp_flags2 & INP_BINDMULTI) &&
763 ((oi->inp_flags2 & INP_BINDMULTI) == 0))
767 * We're okay - either INP_BINDMULTI isn't set on ni, or
768 * it is and it matches the checks.
775 * Set up a bind operation on a PCB, performing port allocation
776 * as required, but do not actually modify the PCB. Callers can
777 * either complete the bind by setting inp_laddr/inp_lport and
778 * calling in_pcbinshash(), or they can just use the resulting
779 * port and address to authorise the sending of a once-off packet.
781 * On error, the values of *laddrp and *lportp are not changed.
784 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
785 u_short *lportp, struct ucred *cred)
787 struct socket *so = inp->inp_socket;
788 struct sockaddr_in *sin;
789 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
790 struct in_addr laddr;
792 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
796 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
797 * so that we don't have to add to the (already messy) code below.
799 int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
802 * No state changes, so read locks are sufficient here.
804 INP_LOCK_ASSERT(inp);
805 INP_HASH_LOCK_ASSERT(pcbinfo);
807 if (CK_STAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
808 return (EADDRNOTAVAIL);
809 laddr.s_addr = *laddrp;
810 if (nam != NULL && laddr.s_addr != INADDR_ANY)
812 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
813 lookupflags = INPLOOKUP_WILDCARD;
815 if ((error = prison_local_ip4(cred, &laddr)) != 0)
818 sin = (struct sockaddr_in *)nam;
819 if (nam->sa_len != sizeof (*sin))
823 * We should check the family, but old programs
824 * incorrectly fail to initialize it.
826 if (sin->sin_family != AF_INET)
827 return (EAFNOSUPPORT);
829 error = prison_local_ip4(cred, &sin->sin_addr);
832 if (sin->sin_port != *lportp) {
833 /* Don't allow the port to change. */
836 lport = sin->sin_port;
838 /* NB: lport is left as 0 if the port isn't being changed. */
839 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
841 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
842 * allow complete duplication of binding if
843 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
844 * and a multicast address is bound on both
845 * new and duplicated sockets.
847 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
848 reuseport = SO_REUSEADDR|SO_REUSEPORT;
850 * XXX: How to deal with SO_REUSEPORT_LB here?
851 * Treat same as SO_REUSEPORT for now.
853 if ((so->so_options &
854 (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
855 reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
856 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
857 sin->sin_port = 0; /* yech... */
858 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
860 * Is the address a local IP address?
861 * If INP_BINDANY is set, then the socket may be bound
862 * to any endpoint address, local or not.
864 if ((inp->inp_flags & INP_BINDANY) == 0 &&
865 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
866 return (EADDRNOTAVAIL);
868 laddr = sin->sin_addr;
874 if (ntohs(lport) <= V_ipport_reservedhigh &&
875 ntohs(lport) >= V_ipport_reservedlow &&
876 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
879 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
880 priv_check_cred(inp->inp_cred,
881 PRIV_NETINET_REUSEPORT, 0) != 0) {
882 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
883 lport, INPLOOKUP_WILDCARD, cred);
886 * This entire block sorely needs a rewrite.
889 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
890 ((t->inp_flags & INP_TIMEWAIT) == 0) &&
891 (so->so_type != SOCK_STREAM ||
892 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
893 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
894 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
895 (t->inp_flags2 & INP_REUSEPORT) ||
896 (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
897 (inp->inp_cred->cr_uid !=
898 t->inp_cred->cr_uid))
902 * If the socket is a BINDMULTI socket, then
903 * the credentials need to match and the
904 * original socket also has to have been bound
907 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
910 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
911 lport, lookupflags, cred);
912 if (t && (t->inp_flags & INP_TIMEWAIT)) {
914 * XXXRW: If an incpb has had its timewait
915 * state recycled, we treat the address as
916 * being in use (for now). This is better
917 * than a panic, but not desirable.
921 ((reuseport & tw->tw_so_options) == 0 &&
923 tw->tw_so_options) == 0)) {
927 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
928 (reuseport & inp_so_options(t)) == 0 &&
929 (reuseport_lb & inp_so_options(t)) == 0) {
931 if (ntohl(sin->sin_addr.s_addr) !=
933 ntohl(t->inp_laddr.s_addr) !=
935 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
936 (t->inp_vflag & INP_IPV6PROTO) == 0)
939 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
947 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
952 *laddrp = laddr.s_addr;
958 * Connect from a socket to a specified address.
959 * Both address and port must be specified in argument sin.
960 * If don't have a local address for this socket yet,
964 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
965 struct ucred *cred, struct mbuf *m)
967 u_short lport, fport;
968 in_addr_t laddr, faddr;
971 INP_WLOCK_ASSERT(inp);
972 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
974 lport = inp->inp_lport;
975 laddr = inp->inp_laddr.s_addr;
976 anonport = (lport == 0);
977 error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
982 /* Do the initial binding of the local address if required. */
983 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
984 inp->inp_lport = lport;
985 inp->inp_laddr.s_addr = laddr;
986 if (in_pcbinshash(inp) != 0) {
987 inp->inp_laddr.s_addr = INADDR_ANY;
993 /* Commit the remaining changes. */
994 inp->inp_lport = lport;
995 inp->inp_laddr.s_addr = laddr;
996 inp->inp_faddr.s_addr = faddr;
997 inp->inp_fport = fport;
998 in_pcbrehash_mbuf(inp, m);
1001 inp->inp_flags |= INP_ANONPORT;
1006 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1009 return (in_pcbconnect_mbuf(inp, nam, cred, NULL));
1013 * Do proper source address selection on an unbound socket in case
1014 * of connect. Take jails into account as well.
1017 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1021 struct sockaddr *sa;
1022 struct sockaddr_in *sin;
1026 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1028 * Bypass source address selection and use the primary jail IP
1031 if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1035 bzero(&sro, sizeof(sro));
1037 sin = (struct sockaddr_in *)&sro.ro_dst;
1038 sin->sin_family = AF_INET;
1039 sin->sin_len = sizeof(struct sockaddr_in);
1040 sin->sin_addr.s_addr = faddr->s_addr;
1043 * If route is known our src addr is taken from the i/f,
1046 * Find out route to destination.
1048 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1049 in_rtalloc_ign(&sro, 0, inp->inp_inc.inc_fibnum);
1052 * If we found a route, use the address corresponding to
1053 * the outgoing interface.
1055 * Otherwise assume faddr is reachable on a directly connected
1056 * network and try to find a corresponding interface to take
1057 * the source address from.
1060 if (sro.ro_rt == NULL || sro.ro_rt->rt_ifp == NULL) {
1061 struct in_ifaddr *ia;
1064 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1065 inp->inp_socket->so_fibnum));
1067 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1068 inp->inp_socket->so_fibnum));
1072 error = ENETUNREACH;
1076 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1077 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1083 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1086 if (sa->sa_family != AF_INET)
1088 sin = (struct sockaddr_in *)sa;
1089 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1090 ia = (struct in_ifaddr *)ifa;
1095 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1099 /* 3. As a last resort return the 'default' jail address. */
1100 error = prison_get_ip4(cred, laddr);
1105 * If the outgoing interface on the route found is not
1106 * a loopback interface, use the address from that interface.
1107 * In case of jails do those three steps:
1108 * 1. check if the interface address belongs to the jail. If so use it.
1109 * 2. check if we have any address on the outgoing interface
1110 * belonging to this jail. If so use it.
1111 * 3. as a last resort return the 'default' jail address.
1113 if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
1114 struct in_ifaddr *ia;
1117 /* If not jailed, use the default returned. */
1118 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1119 ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
1120 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1125 /* 1. Check if the iface address belongs to the jail. */
1126 sin = (struct sockaddr_in *)sro.ro_rt->rt_ifa->ifa_addr;
1127 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1128 ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
1129 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1134 * 2. Check if we have any address on the outgoing interface
1135 * belonging to this jail.
1138 ifp = sro.ro_rt->rt_ifp;
1139 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1141 if (sa->sa_family != AF_INET)
1143 sin = (struct sockaddr_in *)sa;
1144 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1145 ia = (struct in_ifaddr *)ifa;
1150 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1154 /* 3. As a last resort return the 'default' jail address. */
1155 error = prison_get_ip4(cred, laddr);
1160 * The outgoing interface is marked with 'loopback net', so a route
1161 * to ourselves is here.
1162 * Try to find the interface of the destination address and then
1163 * take the address from there. That interface is not necessarily
1164 * a loopback interface.
1165 * In case of jails, check that it is an address of the jail
1166 * and if we cannot find, fall back to the 'default' jail address.
1168 if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
1169 struct sockaddr_in sain;
1170 struct in_ifaddr *ia;
1172 bzero(&sain, sizeof(struct sockaddr_in));
1173 sain.sin_family = AF_INET;
1174 sain.sin_len = sizeof(struct sockaddr_in);
1175 sain.sin_addr.s_addr = faddr->s_addr;
1177 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sain),
1178 inp->inp_socket->so_fibnum));
1180 ia = ifatoia(ifa_ifwithnet(sintosa(&sain), 0,
1181 inp->inp_socket->so_fibnum));
1183 ia = ifatoia(ifa_ifwithaddr(sintosa(&sain)));
1185 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1187 error = ENETUNREACH;
1190 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1200 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1202 if (sa->sa_family != AF_INET)
1204 sin = (struct sockaddr_in *)sa;
1205 if (prison_check_ip4(cred,
1206 &sin->sin_addr) == 0) {
1207 ia = (struct in_ifaddr *)ifa;
1212 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1217 /* 3. As a last resort return the 'default' jail address. */
1218 error = prison_get_ip4(cred, laddr);
1224 if (sro.ro_rt != NULL)
1230 * Set up for a connect from a socket to the specified address.
1231 * On entry, *laddrp and *lportp should contain the current local
1232 * address and port for the PCB; these are updated to the values
1233 * that should be placed in inp_laddr and inp_lport to complete
1236 * On success, *faddrp and *fportp will be set to the remote address
1237 * and port. These are not updated in the error case.
1239 * If the operation fails because the connection already exists,
1240 * *oinpp will be set to the PCB of that connection so that the
1241 * caller can decide to override it. In all other cases, *oinpp
1245 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1246 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1247 struct inpcb **oinpp, struct ucred *cred)
1249 struct rm_priotracker in_ifa_tracker;
1250 struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1251 struct in_ifaddr *ia;
1253 struct in_addr laddr, faddr;
1254 u_short lport, fport;
1258 * Because a global state change doesn't actually occur here, a read
1259 * lock is sufficient.
1261 INP_LOCK_ASSERT(inp);
1262 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1266 if (nam->sa_len != sizeof (*sin))
1268 if (sin->sin_family != AF_INET)
1269 return (EAFNOSUPPORT);
1270 if (sin->sin_port == 0)
1271 return (EADDRNOTAVAIL);
1272 laddr.s_addr = *laddrp;
1274 faddr = sin->sin_addr;
1275 fport = sin->sin_port;
1277 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1279 * If the destination address is INADDR_ANY,
1280 * use the primary local address.
1281 * If the supplied address is INADDR_BROADCAST,
1282 * and the primary interface supports broadcast,
1283 * choose the broadcast address for that interface.
1285 if (faddr.s_addr == INADDR_ANY) {
1286 IN_IFADDR_RLOCK(&in_ifa_tracker);
1288 IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1289 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1291 (error = prison_get_ip4(cred, &faddr)) != 0)
1293 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1294 IN_IFADDR_RLOCK(&in_ifa_tracker);
1295 if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1297 faddr = satosin(&CK_STAILQ_FIRST(
1298 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1299 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1302 if (laddr.s_addr == INADDR_ANY) {
1303 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1305 * If the destination address is multicast and an outgoing
1306 * interface has been set as a multicast option, prefer the
1307 * address of that interface as our source address.
1309 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1310 inp->inp_moptions != NULL) {
1311 struct ip_moptions *imo;
1314 imo = inp->inp_moptions;
1315 if (imo->imo_multicast_ifp != NULL) {
1316 ifp = imo->imo_multicast_ifp;
1317 IN_IFADDR_RLOCK(&in_ifa_tracker);
1318 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1319 if ((ia->ia_ifp == ifp) &&
1321 prison_check_ip4(cred,
1322 &ia->ia_addr.sin_addr) == 0))
1326 error = EADDRNOTAVAIL;
1328 laddr = ia->ia_addr.sin_addr;
1331 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1337 oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr, fport,
1338 laddr, lport, 0, NULL);
1342 return (EADDRINUSE);
1345 error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1350 *laddrp = laddr.s_addr;
1352 *faddrp = faddr.s_addr;
1358 in_pcbdisconnect(struct inpcb *inp)
1361 INP_WLOCK_ASSERT(inp);
1362 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1364 inp->inp_faddr.s_addr = INADDR_ANY;
1371 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1372 * For most protocols, this will be invoked immediately prior to calling
1373 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1374 * socket, in which case in_pcbfree() is deferred.
1377 in_pcbdetach(struct inpcb *inp)
1380 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1383 if (inp->inp_snd_tag != NULL)
1384 in_pcbdetach_txrtlmt(inp);
1386 inp->inp_socket->so_pcb = NULL;
1387 inp->inp_socket = NULL;
1391 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1392 * stability of an inpcb pointer despite the inpcb lock being released. This
1393 * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1394 * but where the inpcb lock may already held, or when acquiring a reference
1397 * in_pcbref() should be used only to provide brief memory stability, and
1398 * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1399 * garbage collect the inpcb if it has been in_pcbfree()'d from another
1400 * context. Until in_pcbrele() has returned that the inpcb is still valid,
1401 * lock and rele are the *only* safe operations that may be performed on the
1404 * While the inpcb will not be freed, releasing the inpcb lock means that the
1405 * connection's state may change, so the caller should be careful to
1406 * revalidate any cached state on reacquiring the lock. Drop the reference
1407 * using in_pcbrele().
1410 in_pcbref(struct inpcb *inp)
1413 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1415 refcount_acquire(&inp->inp_refcount);
1419 * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1420 * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1421 * return a flag indicating whether or not the inpcb remains valid. If it is
1422 * valid, we return with the inpcb lock held.
1424 * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1425 * reference on an inpcb. Historically more work was done here (actually, in
1426 * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1427 * need for the pcbinfo lock in in_pcbrele(). Deferring the free is entirely
1428 * about memory stability (and continued use of the write lock).
1431 in_pcbrele_rlocked(struct inpcb *inp)
1433 struct inpcbinfo *pcbinfo;
1435 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1437 INP_RLOCK_ASSERT(inp);
1439 if (refcount_release(&inp->inp_refcount) == 0) {
1441 * If the inpcb has been freed, let the caller know, even if
1442 * this isn't the last reference.
1444 if (inp->inp_flags2 & INP_FREED) {
1451 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1453 if (inp->inp_in_hpts || inp->inp_in_input) {
1454 struct tcp_hpts_entry *hpts;
1456 * We should not be on the hpts at
1457 * this point in any form. we must
1458 * get the lock to be sure.
1460 hpts = tcp_hpts_lock(inp);
1461 if (inp->inp_in_hpts)
1462 panic("Hpts:%p inp:%p at free still on hpts",
1464 mtx_unlock(&hpts->p_mtx);
1465 hpts = tcp_input_lock(inp);
1466 if (inp->inp_in_input)
1467 panic("Hpts:%p inp:%p at free still on input hpts",
1469 mtx_unlock(&hpts->p_mtx);
1473 pcbinfo = inp->inp_pcbinfo;
1474 uma_zfree(pcbinfo->ipi_zone, inp);
1479 in_pcbrele_wlocked(struct inpcb *inp)
1481 struct inpcbinfo *pcbinfo;
1483 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1485 INP_WLOCK_ASSERT(inp);
1487 if (refcount_release(&inp->inp_refcount) == 0) {
1489 * If the inpcb has been freed, let the caller know, even if
1490 * this isn't the last reference.
1492 if (inp->inp_flags2 & INP_FREED) {
1499 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1501 if (inp->inp_in_hpts || inp->inp_in_input) {
1502 struct tcp_hpts_entry *hpts;
1504 * We should not be on the hpts at
1505 * this point in any form. we must
1506 * get the lock to be sure.
1508 hpts = tcp_hpts_lock(inp);
1509 if (inp->inp_in_hpts)
1510 panic("Hpts:%p inp:%p at free still on hpts",
1512 mtx_unlock(&hpts->p_mtx);
1513 hpts = tcp_input_lock(inp);
1514 if (inp->inp_in_input)
1515 panic("Hpts:%p inp:%p at free still on input hpts",
1517 mtx_unlock(&hpts->p_mtx);
1521 pcbinfo = inp->inp_pcbinfo;
1522 uma_zfree(pcbinfo->ipi_zone, inp);
1527 * Temporary wrapper.
1530 in_pcbrele(struct inpcb *inp)
1533 return (in_pcbrele_wlocked(inp));
1537 in_pcblist_rele_rlocked(epoch_context_t ctx)
1539 struct in_pcblist *il;
1541 struct inpcbinfo *pcbinfo;
1544 il = __containerof(ctx, struct in_pcblist, il_epoch_ctx);
1545 pcbinfo = il->il_pcbinfo;
1547 INP_INFO_WLOCK(pcbinfo);
1548 for (i = 0; i < n; i++) {
1549 inp = il->il_inp_list[i];
1551 if (!in_pcbrele_rlocked(inp))
1554 INP_INFO_WUNLOCK(pcbinfo);
1559 inpcbport_free(epoch_context_t ctx)
1561 struct inpcbport *phd;
1563 phd = __containerof(ctx, struct inpcbport, phd_epoch_ctx);
1568 in_pcbfree_deferred(epoch_context_t ctx)
1571 int released __unused;
1573 inp = __containerof(ctx, struct inpcb, inp_epoch_ctx);
1577 struct ip_moptions *imo = inp->inp_moptions;
1578 inp->inp_moptions = NULL;
1580 /* XXXRW: Do as much as possible here. */
1581 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1582 if (inp->inp_sp != NULL)
1583 ipsec_delete_pcbpolicy(inp);
1586 struct ip6_moptions *im6o = NULL;
1587 if (inp->inp_vflag & INP_IPV6PROTO) {
1588 ip6_freepcbopts(inp->in6p_outputopts);
1589 im6o = inp->in6p_moptions;
1590 inp->in6p_moptions = NULL;
1593 if (inp->inp_options)
1594 (void)m_free(inp->inp_options);
1596 crfree(inp->inp_cred);
1598 mac_inpcb_destroy(inp);
1600 released = in_pcbrele_wlocked(inp);
1603 ip6_freemoptions(im6o);
1606 inp_freemoptions(imo);
1611 * Unconditionally schedule an inpcb to be freed by decrementing its
1612 * reference count, which should occur only after the inpcb has been detached
1613 * from its socket. If another thread holds a temporary reference (acquired
1614 * using in_pcbref()) then the free is deferred until that reference is
1615 * released using in_pcbrele(), but the inpcb is still unlocked. Almost all
1616 * work, including removal from global lists, is done in this context, where
1617 * the pcbinfo lock is held.
1620 in_pcbfree(struct inpcb *inp)
1622 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1624 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1625 KASSERT((inp->inp_flags2 & INP_FREED) == 0,
1626 ("%s: called twice for pcb %p", __func__, inp));
1627 if (inp->inp_flags2 & INP_FREED) {
1633 if (pcbinfo == &V_tcbinfo) {
1634 INP_INFO_LOCK_ASSERT(pcbinfo);
1636 INP_INFO_WLOCK_ASSERT(pcbinfo);
1639 INP_WLOCK_ASSERT(inp);
1640 INP_LIST_WLOCK(pcbinfo);
1641 in_pcbremlists(inp);
1642 INP_LIST_WUNLOCK(pcbinfo);
1643 RO_INVALIDATE_CACHE(&inp->inp_route);
1644 /* mark as destruction in progress */
1645 inp->inp_flags2 |= INP_FREED;
1647 epoch_call(net_epoch_preempt, &inp->inp_epoch_ctx, in_pcbfree_deferred);
1651 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1652 * port reservation, and preventing it from being returned by inpcb lookups.
1654 * It is used by TCP to mark an inpcb as unused and avoid future packet
1655 * delivery or event notification when a socket remains open but TCP has
1656 * closed. This might occur as a result of a shutdown()-initiated TCP close
1657 * or a RST on the wire, and allows the port binding to be reused while still
1658 * maintaining the invariant that so_pcb always points to a valid inpcb until
1661 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1662 * in_pcbnotifyall() and in_pcbpurgeif0()?
1665 in_pcbdrop(struct inpcb *inp)
1668 INP_WLOCK_ASSERT(inp);
1670 if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1671 MPASS(inp->inp_refcount > 1);
1675 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1678 inp->inp_flags |= INP_DROPPED;
1679 if (inp->inp_flags & INP_INHASHLIST) {
1680 struct inpcbport *phd = inp->inp_phd;
1682 INP_HASH_WLOCK(inp->inp_pcbinfo);
1683 in_pcbremlbgrouphash(inp);
1684 CK_LIST_REMOVE(inp, inp_hash);
1685 CK_LIST_REMOVE(inp, inp_portlist);
1686 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1687 CK_LIST_REMOVE(phd, phd_hash);
1688 epoch_call(net_epoch_preempt, &phd->phd_epoch_ctx, inpcbport_free);
1690 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1691 inp->inp_flags &= ~INP_INHASHLIST;
1693 in_pcbgroup_remove(inp);
1700 * Common routines to return the socket addresses associated with inpcbs.
1703 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1705 struct sockaddr_in *sin;
1707 sin = malloc(sizeof *sin, M_SONAME,
1709 sin->sin_family = AF_INET;
1710 sin->sin_len = sizeof(*sin);
1711 sin->sin_addr = *addr_p;
1712 sin->sin_port = port;
1714 return (struct sockaddr *)sin;
1718 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1721 struct in_addr addr;
1724 inp = sotoinpcb(so);
1725 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1728 port = inp->inp_lport;
1729 addr = inp->inp_laddr;
1732 *nam = in_sockaddr(port, &addr);
1737 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1740 struct in_addr addr;
1743 inp = sotoinpcb(so);
1744 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1747 port = inp->inp_fport;
1748 addr = inp->inp_faddr;
1751 *nam = in_sockaddr(port, &addr);
1756 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1757 struct inpcb *(*notify)(struct inpcb *, int))
1759 struct inpcb *inp, *inp_temp;
1761 INP_INFO_WLOCK(pcbinfo);
1762 CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1765 if ((inp->inp_vflag & INP_IPV4) == 0) {
1770 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1771 inp->inp_socket == NULL) {
1775 if ((*notify)(inp, errno))
1778 INP_INFO_WUNLOCK(pcbinfo);
1782 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1785 struct ip_moptions *imo;
1788 INP_INFO_WLOCK(pcbinfo);
1789 CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1791 imo = inp->inp_moptions;
1792 if ((inp->inp_vflag & INP_IPV4) &&
1795 * Unselect the outgoing interface if it is being
1798 if (imo->imo_multicast_ifp == ifp)
1799 imo->imo_multicast_ifp = NULL;
1802 * Drop multicast group membership if we joined
1803 * through the interface being detached.
1805 * XXX This can all be deferred to an epoch_call
1807 for (i = 0, gap = 0; i < imo->imo_num_memberships;
1809 if (imo->imo_membership[i]->inm_ifp == ifp) {
1810 IN_MULTI_LOCK_ASSERT();
1811 in_leavegroup_locked(imo->imo_membership[i], NULL);
1813 } else if (gap != 0)
1814 imo->imo_membership[i - gap] =
1815 imo->imo_membership[i];
1817 imo->imo_num_memberships -= gap;
1821 INP_INFO_WUNLOCK(pcbinfo);
1825 * Lookup a PCB based on the local address and port. Caller must hold the
1826 * hash lock. No inpcb locks or references are acquired.
1828 #define INP_LOOKUP_MAPPED_PCB_COST 3
1830 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1831 u_short lport, int lookupflags, struct ucred *cred)
1835 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1841 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1842 ("%s: invalid lookup flags %d", __func__, lookupflags));
1844 INP_HASH_LOCK_ASSERT(pcbinfo);
1846 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1847 struct inpcbhead *head;
1849 * Look for an unconnected (wildcard foreign addr) PCB that
1850 * matches the local address and port we're looking for.
1852 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1853 0, pcbinfo->ipi_hashmask)];
1854 CK_LIST_FOREACH(inp, head, inp_hash) {
1856 /* XXX inp locking */
1857 if ((inp->inp_vflag & INP_IPV4) == 0)
1860 if (inp->inp_faddr.s_addr == INADDR_ANY &&
1861 inp->inp_laddr.s_addr == laddr.s_addr &&
1862 inp->inp_lport == lport) {
1867 prison_equal_ip4(cred->cr_prison,
1868 inp->inp_cred->cr_prison))
1877 struct inpcbporthead *porthash;
1878 struct inpcbport *phd;
1879 struct inpcb *match = NULL;
1881 * Best fit PCB lookup.
1883 * First see if this local port is in use by looking on the
1886 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1887 pcbinfo->ipi_porthashmask)];
1888 CK_LIST_FOREACH(phd, porthash, phd_hash) {
1889 if (phd->phd_port == lport)
1894 * Port is in use by one or more PCBs. Look for best
1897 CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1900 !prison_equal_ip4(inp->inp_cred->cr_prison,
1904 /* XXX inp locking */
1905 if ((inp->inp_vflag & INP_IPV4) == 0)
1908 * We never select the PCB that has
1909 * INP_IPV6 flag and is bound to :: if
1910 * we have another PCB which is bound
1911 * to 0.0.0.0. If a PCB has the
1912 * INP_IPV6 flag, then we set its cost
1913 * higher than IPv4 only PCBs.
1915 * Note that the case only happens
1916 * when a socket is bound to ::, under
1917 * the condition that the use of the
1918 * mapped address is allowed.
1920 if ((inp->inp_vflag & INP_IPV6) != 0)
1921 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1923 if (inp->inp_faddr.s_addr != INADDR_ANY)
1925 if (inp->inp_laddr.s_addr != INADDR_ANY) {
1926 if (laddr.s_addr == INADDR_ANY)
1928 else if (inp->inp_laddr.s_addr != laddr.s_addr)
1931 if (laddr.s_addr != INADDR_ANY)
1934 if (wildcard < matchwild) {
1936 matchwild = wildcard;
1945 #undef INP_LOOKUP_MAPPED_PCB_COST
1947 static struct inpcb *
1948 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
1949 const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
1950 uint16_t fport, int lookupflags)
1952 struct inpcb *local_wild;
1953 const struct inpcblbgrouphead *hdr;
1954 struct inpcblbgroup *grp;
1957 INP_HASH_LOCK_ASSERT(pcbinfo);
1959 hdr = &pcbinfo->ipi_lbgrouphashbase[INP_PCBLBGROUP_PORTHASH(lport,
1960 pcbinfo->ipi_lbgrouphashmask)];
1963 * Order of socket selection:
1965 * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
1968 * - Load balanced group does not contain jailed sockets
1969 * - Load balanced group does not contain IPv4 mapped INET6 wild sockets
1972 CK_LIST_FOREACH(grp, hdr, il_list) {
1974 if (!(grp->il_vflag & INP_IPV4))
1977 if (grp->il_lport != lport)
1980 idx = INP_PCBLBGROUP_PKTHASH(faddr->s_addr, lport, fport) %
1982 if (grp->il_laddr.s_addr == laddr->s_addr)
1983 return (grp->il_inp[idx]);
1984 if (grp->il_laddr.s_addr == INADDR_ANY &&
1985 (lookupflags & INPLOOKUP_WILDCARD) != 0)
1986 local_wild = grp->il_inp[idx];
1988 return (local_wild);
1993 * Lookup PCB in hash list, using pcbgroup tables.
1995 static struct inpcb *
1996 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1997 struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1998 u_int lport_arg, int lookupflags, struct ifnet *ifp)
2000 struct inpcbhead *head;
2001 struct inpcb *inp, *tmpinp;
2002 u_short fport = fport_arg, lport = lport_arg;
2006 * First look for an exact match.
2009 INP_GROUP_LOCK(pcbgroup);
2010 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2011 pcbgroup->ipg_hashmask)];
2012 CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2014 /* XXX inp locking */
2015 if ((inp->inp_vflag & INP_IPV4) == 0)
2018 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2019 inp->inp_laddr.s_addr == laddr.s_addr &&
2020 inp->inp_fport == fport &&
2021 inp->inp_lport == lport) {
2023 * XXX We should be able to directly return
2024 * the inp here, without any checks.
2025 * Well unless both bound with SO_REUSEPORT?
2027 if (prison_flag(inp->inp_cred, PR_IP4))
2033 if (tmpinp != NULL) {
2040 * For incoming connections, we may wish to do a wildcard
2041 * match for an RSS-local socket.
2043 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2044 struct inpcb *local_wild = NULL, *local_exact = NULL;
2046 struct inpcb *local_wild_mapped = NULL;
2048 struct inpcb *jail_wild = NULL;
2049 struct inpcbhead *head;
2053 * Order of socket selection - we always prefer jails.
2054 * 1. jailed, non-wild.
2056 * 3. non-jailed, non-wild.
2057 * 4. non-jailed, wild.
2060 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
2061 lport, 0, pcbgroup->ipg_hashmask)];
2062 CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2064 /* XXX inp locking */
2065 if ((inp->inp_vflag & INP_IPV4) == 0)
2068 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2069 inp->inp_lport != lport)
2072 injail = prison_flag(inp->inp_cred, PR_IP4);
2074 if (prison_check_ip4(inp->inp_cred,
2078 if (local_exact != NULL)
2082 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2087 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2089 /* XXX inp locking, NULL check */
2090 if (inp->inp_vflag & INP_IPV6PROTO)
2091 local_wild_mapped = inp;
2099 } /* LIST_FOREACH */
2108 inp = local_wild_mapped;
2116 * Then look for a wildcard match, if requested.
2118 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2119 struct inpcb *local_wild = NULL, *local_exact = NULL;
2121 struct inpcb *local_wild_mapped = NULL;
2123 struct inpcb *jail_wild = NULL;
2124 struct inpcbhead *head;
2128 * Order of socket selection - we always prefer jails.
2129 * 1. jailed, non-wild.
2131 * 3. non-jailed, non-wild.
2132 * 4. non-jailed, wild.
2134 head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
2135 0, pcbinfo->ipi_wildmask)];
2136 CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
2138 /* XXX inp locking */
2139 if ((inp->inp_vflag & INP_IPV4) == 0)
2142 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2143 inp->inp_lport != lport)
2146 injail = prison_flag(inp->inp_cred, PR_IP4);
2148 if (prison_check_ip4(inp->inp_cred,
2152 if (local_exact != NULL)
2156 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2161 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2163 /* XXX inp locking, NULL check */
2164 if (inp->inp_vflag & INP_IPV6PROTO)
2165 local_wild_mapped = inp;
2173 } /* LIST_FOREACH */
2181 inp = local_wild_mapped;
2185 } /* if (lookupflags & INPLOOKUP_WILDCARD) */
2186 INP_GROUP_UNLOCK(pcbgroup);
2190 if (lookupflags & INPLOOKUP_WLOCKPCB)
2191 locked = INP_TRY_WLOCK(inp);
2192 else if (lookupflags & INPLOOKUP_RLOCKPCB)
2193 locked = INP_TRY_RLOCK(inp);
2195 panic("%s: locking bug", __func__);
2196 if (__predict_false(locked && (inp->inp_flags2 & INP_FREED))) {
2197 if (lookupflags & INPLOOKUP_WLOCKPCB)
2204 INP_GROUP_UNLOCK(pcbgroup);
2206 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2208 if (in_pcbrele_wlocked(inp))
2212 if (in_pcbrele_rlocked(inp))
2217 if (lookupflags & INPLOOKUP_WLOCKPCB)
2218 INP_WLOCK_ASSERT(inp);
2220 INP_RLOCK_ASSERT(inp);
2224 #endif /* PCBGROUP */
2227 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
2228 * that the caller has locked the hash list, and will not perform any further
2229 * locking or reference operations on either the hash list or the connection.
2231 static struct inpcb *
2232 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2233 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2236 struct inpcbhead *head;
2237 struct inpcb *inp, *tmpinp;
2238 u_short fport = fport_arg, lport = lport_arg;
2241 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2242 ("%s: invalid lookup flags %d", __func__, lookupflags));
2243 if (!mtx_owned(&pcbinfo->ipi_hash_lock))
2244 MPASS(in_epoch_verbose(net_epoch_preempt, 1));
2247 * First look for an exact match.
2250 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2251 pcbinfo->ipi_hashmask)];
2252 CK_LIST_FOREACH(inp, head, inp_hash) {
2254 /* XXX inp locking */
2255 if ((inp->inp_vflag & INP_IPV4) == 0)
2258 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2259 inp->inp_laddr.s_addr == laddr.s_addr &&
2260 inp->inp_fport == fport &&
2261 inp->inp_lport == lport) {
2263 * XXX We should be able to directly return
2264 * the inp here, without any checks.
2265 * Well unless both bound with SO_REUSEPORT?
2267 if (prison_flag(inp->inp_cred, PR_IP4))
2277 * Then look in lb group (for wildcard match).
2279 if (pcbinfo->ipi_lbgrouphashbase != NULL &&
2280 (lookupflags & INPLOOKUP_WILDCARD)) {
2281 inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2282 fport, lookupflags);
2289 * Then look for a wildcard match, if requested.
2291 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2292 struct inpcb *local_wild = NULL, *local_exact = NULL;
2294 struct inpcb *local_wild_mapped = NULL;
2296 struct inpcb *jail_wild = NULL;
2300 * Order of socket selection - we always prefer jails.
2301 * 1. jailed, non-wild.
2303 * 3. non-jailed, non-wild.
2304 * 4. non-jailed, wild.
2307 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2308 0, pcbinfo->ipi_hashmask)];
2309 CK_LIST_FOREACH(inp, head, inp_hash) {
2311 /* XXX inp locking */
2312 if ((inp->inp_vflag & INP_IPV4) == 0)
2315 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2316 inp->inp_lport != lport)
2319 injail = prison_flag(inp->inp_cred, PR_IP4);
2321 if (prison_check_ip4(inp->inp_cred,
2325 if (local_exact != NULL)
2329 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2334 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2336 /* XXX inp locking, NULL check */
2337 if (inp->inp_vflag & INP_IPV6PROTO)
2338 local_wild_mapped = inp;
2346 } /* LIST_FOREACH */
2347 if (jail_wild != NULL)
2349 if (local_exact != NULL)
2350 return (local_exact);
2351 if (local_wild != NULL)
2352 return (local_wild);
2354 if (local_wild_mapped != NULL)
2355 return (local_wild_mapped);
2357 } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2363 * Lookup PCB in hash list, using pcbinfo tables. This variation locks the
2364 * hash list lock, and will return the inpcb locked (i.e., requires
2365 * INPLOOKUP_LOCKPCB).
2367 static struct inpcb *
2368 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2369 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2374 INP_HASH_RLOCK(pcbinfo);
2375 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2376 (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
2378 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2380 if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2384 } else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2386 if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2391 panic("%s: locking bug", __func__);
2394 if (lookupflags & INPLOOKUP_WLOCKPCB)
2395 INP_WLOCK_ASSERT(inp);
2397 INP_RLOCK_ASSERT(inp);
2401 INP_HASH_RUNLOCK(pcbinfo);
2406 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2407 * from which a pre-calculated hash value may be extracted.
2409 * Possibly more of this logic should be in in_pcbgroup.c.
2412 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2413 struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2415 #if defined(PCBGROUP) && !defined(RSS)
2416 struct inpcbgroup *pcbgroup;
2419 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2420 ("%s: invalid lookup flags %d", __func__, lookupflags));
2421 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2422 ("%s: LOCKPCB not set", __func__));
2425 * When not using RSS, use connection groups in preference to the
2426 * reservation table when looking up 4-tuples. When using RSS, just
2427 * use the reservation table, due to the cost of the Toeplitz hash
2430 * XXXRW: This policy belongs in the pcbgroup code, as in principle
2431 * we could be doing RSS with a non-Toeplitz hash that is affordable
2434 #if defined(PCBGROUP) && !defined(RSS)
2435 if (in_pcbgroup_enabled(pcbinfo)) {
2436 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2438 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2439 laddr, lport, lookupflags, ifp));
2442 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2447 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2448 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2449 struct ifnet *ifp, struct mbuf *m)
2452 struct inpcbgroup *pcbgroup;
2455 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2456 ("%s: invalid lookup flags %d", __func__, lookupflags));
2457 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2458 ("%s: LOCKPCB not set", __func__));
2462 * If we can use a hardware-generated hash to look up the connection
2463 * group, use that connection group to find the inpcb. Otherwise
2464 * fall back on a software hash -- or the reservation table if we're
2467 * XXXRW: As above, that policy belongs in the pcbgroup code.
2469 if (in_pcbgroup_enabled(pcbinfo) &&
2470 !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2471 pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2472 m->m_pkthdr.flowid);
2473 if (pcbgroup != NULL)
2474 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2475 fport, laddr, lport, lookupflags, ifp));
2477 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2479 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2480 laddr, lport, lookupflags, ifp));
2484 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2490 * Insert PCB onto various hash lists.
2493 in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
2495 struct inpcbhead *pcbhash;
2496 struct inpcbporthead *pcbporthash;
2497 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2498 struct inpcbport *phd;
2499 u_int32_t hashkey_faddr;
2502 INP_WLOCK_ASSERT(inp);
2503 INP_HASH_WLOCK_ASSERT(pcbinfo);
2505 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2506 ("in_pcbinshash: INP_INHASHLIST"));
2509 if (inp->inp_vflag & INP_IPV6)
2510 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2513 hashkey_faddr = inp->inp_faddr.s_addr;
2515 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2516 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2518 pcbporthash = &pcbinfo->ipi_porthashbase[
2519 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2522 * Add entry to load balance group.
2523 * Only do this if SO_REUSEPORT_LB is set.
2525 so_options = inp_so_options(inp);
2526 if (so_options & SO_REUSEPORT_LB) {
2527 int ret = in_pcbinslbgrouphash(inp);
2529 /* pcb lb group malloc fail (ret=ENOBUFS). */
2535 * Go through port list and look for a head for this lport.
2537 CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2538 if (phd->phd_port == inp->inp_lport)
2542 * If none exists, malloc one and tack it on.
2545 phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2547 return (ENOBUFS); /* XXX */
2549 bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2550 phd->phd_port = inp->inp_lport;
2551 CK_LIST_INIT(&phd->phd_pcblist);
2552 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2555 CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2556 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2557 inp->inp_flags |= INP_INHASHLIST;
2559 if (do_pcbgroup_update)
2560 in_pcbgroup_update(inp);
2566 * For now, there are two public interfaces to insert an inpcb into the hash
2567 * lists -- one that does update pcbgroups, and one that doesn't. The latter
2568 * is used only in the TCP syncache, where in_pcbinshash is called before the
2569 * full 4-tuple is set for the inpcb, and we don't want to install in the
2570 * pcbgroup until later.
2572 * XXXRW: This seems like a misfeature. in_pcbinshash should always update
2573 * connection groups, and partially initialised inpcbs should not be exposed
2574 * to either reservation hash tables or pcbgroups.
2577 in_pcbinshash(struct inpcb *inp)
2580 return (in_pcbinshash_internal(inp, 1));
2584 in_pcbinshash_nopcbgroup(struct inpcb *inp)
2587 return (in_pcbinshash_internal(inp, 0));
2591 * Move PCB to the proper hash bucket when { faddr, fport } have been
2592 * changed. NOTE: This does not handle the case of the lport changing (the
2593 * hashed port list would have to be updated as well), so the lport must
2594 * not change after in_pcbinshash() has been called.
2597 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2599 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2600 struct inpcbhead *head;
2601 u_int32_t hashkey_faddr;
2603 INP_WLOCK_ASSERT(inp);
2604 INP_HASH_WLOCK_ASSERT(pcbinfo);
2606 KASSERT(inp->inp_flags & INP_INHASHLIST,
2607 ("in_pcbrehash: !INP_INHASHLIST"));
2610 if (inp->inp_vflag & INP_IPV6)
2611 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2614 hashkey_faddr = inp->inp_faddr.s_addr;
2616 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2617 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2619 CK_LIST_REMOVE(inp, inp_hash);
2620 CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2624 in_pcbgroup_update_mbuf(inp, m);
2626 in_pcbgroup_update(inp);
2631 in_pcbrehash(struct inpcb *inp)
2634 in_pcbrehash_mbuf(inp, NULL);
2638 * Remove PCB from various lists.
2641 in_pcbremlists(struct inpcb *inp)
2643 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2646 if (pcbinfo == &V_tcbinfo) {
2647 INP_INFO_RLOCK_ASSERT(pcbinfo);
2649 INP_INFO_WLOCK_ASSERT(pcbinfo);
2653 INP_WLOCK_ASSERT(inp);
2654 INP_LIST_WLOCK_ASSERT(pcbinfo);
2656 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2657 if (inp->inp_flags & INP_INHASHLIST) {
2658 struct inpcbport *phd = inp->inp_phd;
2660 INP_HASH_WLOCK(pcbinfo);
2662 /* XXX: Only do if SO_REUSEPORT_LB set? */
2663 in_pcbremlbgrouphash(inp);
2665 CK_LIST_REMOVE(inp, inp_hash);
2666 CK_LIST_REMOVE(inp, inp_portlist);
2667 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2668 CK_LIST_REMOVE(phd, phd_hash);
2669 epoch_call(net_epoch_preempt, &phd->phd_epoch_ctx, inpcbport_free);
2671 INP_HASH_WUNLOCK(pcbinfo);
2672 inp->inp_flags &= ~INP_INHASHLIST;
2674 CK_LIST_REMOVE(inp, inp_list);
2675 pcbinfo->ipi_count--;
2677 in_pcbgroup_remove(inp);
2682 * Check for alternatives when higher level complains
2683 * about service problems. For now, invalidate cached
2684 * routing information. If the route was created dynamically
2685 * (by a redirect), time to try a default gateway again.
2688 in_losing(struct inpcb *inp)
2691 RO_INVALIDATE_CACHE(&inp->inp_route);
2696 * A set label operation has occurred at the socket layer, propagate the
2697 * label change into the in_pcb for the socket.
2700 in_pcbsosetlabel(struct socket *so)
2705 inp = sotoinpcb(so);
2706 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2710 mac_inpcb_sosetlabel(so, inp);
2717 * ipport_tick runs once per second, determining if random port allocation
2718 * should be continued. If more than ipport_randomcps ports have been
2719 * allocated in the last second, then we return to sequential port
2720 * allocation. We return to random allocation only once we drop below
2721 * ipport_randomcps for at least ipport_randomtime seconds.
2724 ipport_tick(void *xtp)
2726 VNET_ITERATOR_DECL(vnet_iter);
2728 VNET_LIST_RLOCK_NOSLEEP();
2729 VNET_FOREACH(vnet_iter) {
2730 CURVNET_SET(vnet_iter); /* XXX appease INVARIANTS here */
2731 if (V_ipport_tcpallocs <=
2732 V_ipport_tcplastcount + V_ipport_randomcps) {
2733 if (V_ipport_stoprandom > 0)
2734 V_ipport_stoprandom--;
2736 V_ipport_stoprandom = V_ipport_randomtime;
2737 V_ipport_tcplastcount = V_ipport_tcpallocs;
2740 VNET_LIST_RUNLOCK_NOSLEEP();
2741 callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2748 callout_stop(&ipport_tick_callout);
2752 * The ipport_callout should start running at about the time we attach the
2753 * inet or inet6 domains.
2756 ipport_tick_init(const void *unused __unused)
2759 /* Start ipport_tick. */
2760 callout_init(&ipport_tick_callout, 1);
2761 callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2762 EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2763 SHUTDOWN_PRI_DEFAULT);
2765 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2766 ipport_tick_init, NULL);
2769 inp_wlock(struct inpcb *inp)
2776 inp_wunlock(struct inpcb *inp)
2783 inp_rlock(struct inpcb *inp)
2790 inp_runlock(struct inpcb *inp)
2796 #ifdef INVARIANT_SUPPORT
2798 inp_lock_assert(struct inpcb *inp)
2801 INP_WLOCK_ASSERT(inp);
2805 inp_unlock_assert(struct inpcb *inp)
2808 INP_UNLOCK_ASSERT(inp);
2813 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2817 INP_INFO_WLOCK(&V_tcbinfo);
2818 CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2823 INP_INFO_WUNLOCK(&V_tcbinfo);
2827 inp_inpcbtosocket(struct inpcb *inp)
2830 INP_WLOCK_ASSERT(inp);
2831 return (inp->inp_socket);
2835 inp_inpcbtotcpcb(struct inpcb *inp)
2838 INP_WLOCK_ASSERT(inp);
2839 return ((struct tcpcb *)inp->inp_ppcb);
2843 inp_ip_tos_get(const struct inpcb *inp)
2846 return (inp->inp_ip_tos);
2850 inp_ip_tos_set(struct inpcb *inp, int val)
2853 inp->inp_ip_tos = val;
2857 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2858 uint32_t *faddr, uint16_t *fp)
2861 INP_LOCK_ASSERT(inp);
2862 *laddr = inp->inp_laddr.s_addr;
2863 *faddr = inp->inp_faddr.s_addr;
2864 *lp = inp->inp_lport;
2865 *fp = inp->inp_fport;
2869 so_sotoinpcb(struct socket *so)
2872 return (sotoinpcb(so));
2876 so_sototcpcb(struct socket *so)
2879 return (sototcpcb(so));
2883 * Create an external-format (``xinpcb'') structure using the information in
2884 * the kernel-format in_pcb structure pointed to by inp. This is done to
2885 * reduce the spew of irrelevant information over this interface, to isolate
2886 * user code from changes in the kernel structure, and potentially to provide
2887 * information-hiding if we decide that some of this information should be
2888 * hidden from users.
2891 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2894 xi->xi_len = sizeof(struct xinpcb);
2895 if (inp->inp_socket)
2896 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2898 bzero(&xi->xi_socket, sizeof(struct xsocket));
2899 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2900 xi->inp_gencnt = inp->inp_gencnt;
2901 xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2902 xi->inp_flow = inp->inp_flow;
2903 xi->inp_flowid = inp->inp_flowid;
2904 xi->inp_flowtype = inp->inp_flowtype;
2905 xi->inp_flags = inp->inp_flags;
2906 xi->inp_flags2 = inp->inp_flags2;
2907 xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2908 xi->in6p_cksum = inp->in6p_cksum;
2909 xi->in6p_hops = inp->in6p_hops;
2910 xi->inp_ip_tos = inp->inp_ip_tos;
2911 xi->inp_vflag = inp->inp_vflag;
2912 xi->inp_ip_ttl = inp->inp_ip_ttl;
2913 xi->inp_ip_p = inp->inp_ip_p;
2914 xi->inp_ip_minttl = inp->inp_ip_minttl;
2919 db_print_indent(int indent)
2923 for (i = 0; i < indent; i++)
2928 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2930 char faddr_str[48], laddr_str[48];
2932 db_print_indent(indent);
2933 db_printf("%s at %p\n", name, inc);
2938 if (inc->inc_flags & INC_ISIPV6) {
2940 ip6_sprintf(laddr_str, &inc->inc6_laddr);
2941 ip6_sprintf(faddr_str, &inc->inc6_faddr);
2946 inet_ntoa_r(inc->inc_laddr, laddr_str);
2947 inet_ntoa_r(inc->inc_faddr, faddr_str);
2949 db_print_indent(indent);
2950 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
2951 ntohs(inc->inc_lport));
2952 db_print_indent(indent);
2953 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
2954 ntohs(inc->inc_fport));
2958 db_print_inpflags(int inp_flags)
2963 if (inp_flags & INP_RECVOPTS) {
2964 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2967 if (inp_flags & INP_RECVRETOPTS) {
2968 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2971 if (inp_flags & INP_RECVDSTADDR) {
2972 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2975 if (inp_flags & INP_ORIGDSTADDR) {
2976 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2979 if (inp_flags & INP_HDRINCL) {
2980 db_printf("%sINP_HDRINCL", comma ? ", " : "");
2983 if (inp_flags & INP_HIGHPORT) {
2984 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2987 if (inp_flags & INP_LOWPORT) {
2988 db_printf("%sINP_LOWPORT", comma ? ", " : "");
2991 if (inp_flags & INP_ANONPORT) {
2992 db_printf("%sINP_ANONPORT", comma ? ", " : "");
2995 if (inp_flags & INP_RECVIF) {
2996 db_printf("%sINP_RECVIF", comma ? ", " : "");
2999 if (inp_flags & INP_MTUDISC) {
3000 db_printf("%sINP_MTUDISC", comma ? ", " : "");
3003 if (inp_flags & INP_RECVTTL) {
3004 db_printf("%sINP_RECVTTL", comma ? ", " : "");
3007 if (inp_flags & INP_DONTFRAG) {
3008 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3011 if (inp_flags & INP_RECVTOS) {
3012 db_printf("%sINP_RECVTOS", comma ? ", " : "");
3015 if (inp_flags & IN6P_IPV6_V6ONLY) {
3016 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3019 if (inp_flags & IN6P_PKTINFO) {
3020 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3023 if (inp_flags & IN6P_HOPLIMIT) {
3024 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3027 if (inp_flags & IN6P_HOPOPTS) {
3028 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3031 if (inp_flags & IN6P_DSTOPTS) {
3032 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3035 if (inp_flags & IN6P_RTHDR) {
3036 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3039 if (inp_flags & IN6P_RTHDRDSTOPTS) {
3040 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3043 if (inp_flags & IN6P_TCLASS) {
3044 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3047 if (inp_flags & IN6P_AUTOFLOWLABEL) {
3048 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3051 if (inp_flags & INP_TIMEWAIT) {
3052 db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3055 if (inp_flags & INP_ONESBCAST) {
3056 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3059 if (inp_flags & INP_DROPPED) {
3060 db_printf("%sINP_DROPPED", comma ? ", " : "");
3063 if (inp_flags & INP_SOCKREF) {
3064 db_printf("%sINP_SOCKREF", comma ? ", " : "");
3067 if (inp_flags & IN6P_RFC2292) {
3068 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3071 if (inp_flags & IN6P_MTU) {
3072 db_printf("IN6P_MTU%s", comma ? ", " : "");
3078 db_print_inpvflag(u_char inp_vflag)
3083 if (inp_vflag & INP_IPV4) {
3084 db_printf("%sINP_IPV4", comma ? ", " : "");
3087 if (inp_vflag & INP_IPV6) {
3088 db_printf("%sINP_IPV6", comma ? ", " : "");
3091 if (inp_vflag & INP_IPV6PROTO) {
3092 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3098 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3101 db_print_indent(indent);
3102 db_printf("%s at %p\n", name, inp);
3106 db_print_indent(indent);
3107 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3109 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3111 db_print_indent(indent);
3112 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
3113 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3115 db_print_indent(indent);
3116 db_printf("inp_label: %p inp_flags: 0x%x (",
3117 inp->inp_label, inp->inp_flags);
3118 db_print_inpflags(inp->inp_flags);
3121 db_print_indent(indent);
3122 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
3124 db_print_inpvflag(inp->inp_vflag);
3127 db_print_indent(indent);
3128 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
3129 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3131 db_print_indent(indent);
3133 if (inp->inp_vflag & INP_IPV6) {
3134 db_printf("in6p_options: %p in6p_outputopts: %p "
3135 "in6p_moptions: %p\n", inp->in6p_options,
3136 inp->in6p_outputopts, inp->in6p_moptions);
3137 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
3138 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3143 db_printf("inp_ip_tos: %d inp_ip_options: %p "
3144 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3145 inp->inp_options, inp->inp_moptions);
3148 db_print_indent(indent);
3149 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
3150 (uintmax_t)inp->inp_gencnt);
3153 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3158 db_printf("usage: show inpcb <addr>\n");
3161 inp = (struct inpcb *)addr;
3163 db_print_inpcb(inp, "inpcb", 0);
3169 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3173 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3175 union if_snd_tag_modify_params params = {
3176 .rate_limit.max_rate = max_pacing_rate,
3178 struct m_snd_tag *mst;
3182 mst = inp->inp_snd_tag;
3190 if (ifp->if_snd_tag_modify == NULL) {
3193 error = ifp->if_snd_tag_modify(mst, ¶ms);
3199 * Query existing TX rate limit based on the existing
3200 * "inp->inp_snd_tag", if any.
3203 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3205 union if_snd_tag_query_params params = { };
3206 struct m_snd_tag *mst;
3210 mst = inp->inp_snd_tag;
3218 if (ifp->if_snd_tag_query == NULL) {
3221 error = ifp->if_snd_tag_query(mst, ¶ms);
3222 if (error == 0 && p_max_pacing_rate != NULL)
3223 *p_max_pacing_rate = params.rate_limit.max_rate;
3229 * Query existing TX queue level based on the existing
3230 * "inp->inp_snd_tag", if any.
3233 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3235 union if_snd_tag_query_params params = { };
3236 struct m_snd_tag *mst;
3240 mst = inp->inp_snd_tag;
3248 if (ifp->if_snd_tag_query == NULL)
3249 return (EOPNOTSUPP);
3251 error = ifp->if_snd_tag_query(mst, ¶ms);
3252 if (error == 0 && p_txqueue_level != NULL)
3253 *p_txqueue_level = params.rate_limit.queue_level;
3258 * Allocate a new TX rate limit send tag from the network interface
3259 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3262 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3263 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate)
3265 union if_snd_tag_alloc_params params = {
3266 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3267 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3268 .rate_limit.hdr.flowid = flowid,
3269 .rate_limit.hdr.flowtype = flowtype,
3270 .rate_limit.max_rate = max_pacing_rate,
3274 INP_WLOCK_ASSERT(inp);
3276 if (inp->inp_snd_tag != NULL)
3279 if (ifp->if_snd_tag_alloc == NULL) {
3282 error = ifp->if_snd_tag_alloc(ifp, ¶ms, &inp->inp_snd_tag);
3285 * At success increment the refcount on
3286 * the send tag's network interface:
3289 if_ref(inp->inp_snd_tag->ifp);
3295 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3299 in_pcbdetach_txrtlmt(struct inpcb *inp)
3301 struct m_snd_tag *mst;
3304 INP_WLOCK_ASSERT(inp);
3306 mst = inp->inp_snd_tag;
3307 inp->inp_snd_tag = NULL;
3317 * If the device was detached while we still had reference(s)
3318 * on the ifp, we assume if_snd_tag_free() was replaced with
3321 ifp->if_snd_tag_free(mst);
3323 /* release reference count on network interface */
3328 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3329 * is set in the fast path and will attach/detach/modify the TX rate
3330 * limit send tag based on the socket's so_max_pacing_rate value.
3333 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3335 struct socket *socket;
3336 uint32_t max_pacing_rate;
3343 socket = inp->inp_socket;
3347 if (!INP_WLOCKED(inp)) {
3349 * NOTE: If the write locking fails, we need to bail
3350 * out and use the non-ratelimited ring for the
3351 * transmit until there is a new chance to get the
3354 if (!INP_TRY_UPGRADE(inp))
3362 * NOTE: The so_max_pacing_rate value is read unlocked,
3363 * because atomic updates are not required since the variable
3364 * is checked at every mbuf we send. It is assumed that the
3365 * variable read itself will be atomic.
3367 max_pacing_rate = socket->so_max_pacing_rate;
3370 * NOTE: When attaching to a network interface a reference is
3371 * made to ensure the network interface doesn't go away until
3372 * all ratelimit connections are gone. The network interface
3373 * pointers compared below represent valid network interfaces,
3374 * except when comparing towards NULL.
3376 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3378 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3379 if (inp->inp_snd_tag != NULL)
3380 in_pcbdetach_txrtlmt(inp);
3382 } else if (inp->inp_snd_tag == NULL) {
3384 * In order to utilize packet pacing with RSS, we need
3385 * to wait until there is a valid RSS hash before we
3388 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3391 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3392 mb->m_pkthdr.flowid, max_pacing_rate);
3395 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3397 if (error == 0 || error == EOPNOTSUPP)
3398 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3404 * Track route changes for TX rate limiting.
3407 in_pcboutput_eagain(struct inpcb *inp)
3409 struct socket *socket;
3415 socket = inp->inp_socket;
3419 if (inp->inp_snd_tag == NULL)
3422 if (!INP_WLOCKED(inp)) {
3424 * NOTE: If the write locking fails, we need to bail
3425 * out and use the non-ratelimited ring for the
3426 * transmit until there is a new chance to get the
3429 if (!INP_TRY_UPGRADE(inp))
3436 /* detach rate limiting */
3437 in_pcbdetach_txrtlmt(inp);
3439 /* make sure new mbuf send tag allocation is made */
3440 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3445 #endif /* RATELIMIT */