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>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/sockio.h>
66 #include <sys/refcount.h>
68 #include <sys/kernel.h>
69 #include <sys/sysctl.h>
78 #include <net/if_var.h>
79 #include <net/if_types.h>
80 #include <net/if_llatbl.h>
81 #include <net/route.h>
82 #include <net/rss_config.h>
85 #if defined(INET) || defined(INET6)
86 #include <netinet/in.h>
87 #include <netinet/in_pcb.h>
88 #include <netinet/ip_var.h>
89 #include <netinet/tcp_var.h>
90 #include <netinet/udp.h>
91 #include <netinet/udp_var.h>
94 #include <netinet/in_var.h>
97 #include <netinet/ip6.h>
98 #include <netinet6/in6_pcb.h>
99 #include <netinet6/in6_var.h>
100 #include <netinet6/ip6_var.h>
103 #include <netipsec/ipsec_support.h>
105 #include <security/mac/mac_framework.h>
107 static struct callout ipport_tick_callout;
110 * These configure the range of local port addresses assigned to
111 * "unspecified" outgoing connections/packets/whatever.
113 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1; /* 1023 */
114 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART; /* 600 */
115 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST; /* 10000 */
116 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST; /* 65535 */
117 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO; /* 49152 */
118 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO; /* 65535 */
121 * Reserved ports accessible only to root. There are significant
122 * security considerations that must be accounted for when changing these,
123 * but the security benefits can be great. Please be careful.
125 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1; /* 1023 */
126 VNET_DEFINE(int, ipport_reservedlow);
128 /* Variables dealing with random ephemeral port allocation. */
129 VNET_DEFINE(int, ipport_randomized) = 1; /* user controlled via sysctl */
130 VNET_DEFINE(int, ipport_randomcps) = 10; /* user controlled via sysctl */
131 VNET_DEFINE(int, ipport_randomtime) = 45; /* user controlled via sysctl */
132 VNET_DEFINE(int, ipport_stoprandom); /* toggled by ipport_tick */
133 VNET_DEFINE(int, ipport_tcpallocs);
134 static VNET_DEFINE(int, ipport_tcplastcount);
136 #define V_ipport_tcplastcount VNET(ipport_tcplastcount)
138 static void in_pcbremlists(struct inpcb *inp);
140 static struct inpcb *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
141 struct in_addr faddr, u_int fport_arg,
142 struct in_addr laddr, u_int lport_arg,
143 int lookupflags, struct ifnet *ifp);
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, CTLFLAG_RW, 0,
171 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
172 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
173 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I", "");
174 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
175 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
176 &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I", "");
177 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
178 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
179 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I", "");
180 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
181 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
182 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I", "");
183 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
184 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
185 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I", "");
186 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
187 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
188 &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I", "");
189 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
190 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
191 &VNET_NAME(ipport_reservedhigh), 0, "");
192 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
193 CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
194 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
195 CTLFLAG_VNET | CTLFLAG_RW,
196 &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
197 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
198 CTLFLAG_VNET | CTLFLAG_RW,
199 &VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
200 "allocations before switching to a sequental one");
201 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
202 CTLFLAG_VNET | CTLFLAG_RW,
203 &VNET_NAME(ipport_randomtime), 0,
204 "Minimum time to keep sequental port "
205 "allocation before switching to a random one");
209 * in_pcb.c: manage the Protocol Control Blocks.
211 * NOTE: It is assumed that most of these functions will be called with
212 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
213 * functions often modify hash chains or addresses in pcbs.
217 * Different protocols initialize their inpcbs differently - giving
218 * different name to the lock. But they all are disposed the same.
221 inpcb_fini(void *mem, int size)
223 struct inpcb *inp = mem;
225 INP_LOCK_DESTROY(inp);
229 * Initialize an inpcbinfo -- we should be able to reduce the number of
233 in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
234 struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
235 char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
238 INP_INFO_LOCK_INIT(pcbinfo, name);
239 INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash"); /* XXXRW: argument? */
240 INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
242 pcbinfo->ipi_vnet = curvnet;
244 pcbinfo->ipi_listhead = listhead;
245 LIST_INIT(pcbinfo->ipi_listhead);
246 pcbinfo->ipi_count = 0;
247 pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
248 &pcbinfo->ipi_hashmask);
249 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
250 &pcbinfo->ipi_porthashmask);
252 in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
254 pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
255 NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
256 uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
257 uma_zone_set_warning(pcbinfo->ipi_zone,
258 "kern.ipc.maxsockets limit reached");
262 * Destroy an inpcbinfo.
265 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
268 KASSERT(pcbinfo->ipi_count == 0,
269 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
271 hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
272 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
273 pcbinfo->ipi_porthashmask);
275 in_pcbgroup_destroy(pcbinfo);
277 uma_zdestroy(pcbinfo->ipi_zone);
278 INP_LIST_LOCK_DESTROY(pcbinfo);
279 INP_HASH_LOCK_DESTROY(pcbinfo);
280 INP_INFO_LOCK_DESTROY(pcbinfo);
284 * Allocate a PCB and associate it with the socket.
285 * On success return with the PCB locked.
288 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
294 if (pcbinfo == &V_tcbinfo) {
295 INP_INFO_RLOCK_ASSERT(pcbinfo);
297 INP_INFO_WLOCK_ASSERT(pcbinfo);
302 inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
305 bzero(&inp->inp_start_zero, inp_zero_size);
306 inp->inp_pcbinfo = pcbinfo;
307 inp->inp_socket = so;
308 inp->inp_cred = crhold(so->so_cred);
309 inp->inp_inc.inc_fibnum = so->so_fibnum;
311 error = mac_inpcb_init(inp, M_NOWAIT);
314 mac_inpcb_create(so, inp);
316 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
317 error = ipsec_init_pcbpolicy(inp);
320 mac_inpcb_destroy(inp);
326 if (INP_SOCKAF(so) == AF_INET6) {
327 inp->inp_vflag |= INP_IPV6PROTO;
329 inp->inp_flags |= IN6P_IPV6_V6ONLY;
333 INP_LIST_WLOCK(pcbinfo);
334 LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
335 pcbinfo->ipi_count++;
336 so->so_pcb = (caddr_t)inp;
338 if (V_ip6_auto_flowlabel)
339 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
341 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
342 refcount_init(&inp->inp_refcount, 1); /* Reference from inpcbinfo */
345 * Routes in inpcb's can cache L2 as well; they are guaranteed
348 inp->inp_route.ro_flags = RT_LLE_CACHE;
349 INP_LIST_WUNLOCK(pcbinfo);
350 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
353 crfree(inp->inp_cred);
354 uma_zfree(pcbinfo->ipi_zone, inp);
362 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
366 INP_WLOCK_ASSERT(inp);
367 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
369 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
371 anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
372 error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
373 &inp->inp_lport, cred);
376 if (in_pcbinshash(inp) != 0) {
377 inp->inp_laddr.s_addr = INADDR_ANY;
382 inp->inp_flags |= INP_ANONPORT;
388 * Select a local port (number) to use.
390 #if defined(INET) || defined(INET6)
392 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
393 struct ucred *cred, int lookupflags)
395 struct inpcbinfo *pcbinfo;
396 struct inpcb *tmpinp;
397 unsigned short *lastport;
398 int count, dorandom, error;
399 u_short aux, first, last, lport;
401 struct in_addr laddr;
404 pcbinfo = inp->inp_pcbinfo;
407 * Because no actual state changes occur here, a global write lock on
408 * the pcbinfo isn't required.
410 INP_LOCK_ASSERT(inp);
411 INP_HASH_LOCK_ASSERT(pcbinfo);
413 if (inp->inp_flags & INP_HIGHPORT) {
414 first = V_ipport_hifirstauto; /* sysctl */
415 last = V_ipport_hilastauto;
416 lastport = &pcbinfo->ipi_lasthi;
417 } else if (inp->inp_flags & INP_LOWPORT) {
418 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
421 first = V_ipport_lowfirstauto; /* 1023 */
422 last = V_ipport_lowlastauto; /* 600 */
423 lastport = &pcbinfo->ipi_lastlow;
425 first = V_ipport_firstauto; /* sysctl */
426 last = V_ipport_lastauto;
427 lastport = &pcbinfo->ipi_lastport;
430 * For UDP(-Lite), use random port allocation as long as the user
431 * allows it. For TCP (and as of yet unknown) connections,
432 * use random port allocation only if the user allows it AND
433 * ipport_tick() allows it.
435 if (V_ipport_randomized &&
436 (!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
437 pcbinfo == &V_ulitecbinfo))
442 * It makes no sense to do random port allocation if
443 * we have the only port available.
447 /* Make sure to not include UDP(-Lite) packets in the count. */
448 if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
449 V_ipport_tcpallocs++;
451 * Instead of having two loops further down counting up or down
452 * make sure that first is always <= last and go with only one
453 * code path implementing all logic.
462 /* Make the compiler happy. */
464 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
465 KASSERT(laddrp != NULL, ("%s: laddrp NULL for v4 inp %p",
470 tmpinp = NULL; /* Make compiler happy. */
474 *lastport = first + (arc4random() % (last - first));
476 count = last - first;
479 if (count-- < 0) /* completely used? */
480 return (EADDRNOTAVAIL);
482 if (*lastport < first || *lastport > last)
484 lport = htons(*lastport);
487 if ((inp->inp_vflag & INP_IPV6) != 0)
488 tmpinp = in6_pcblookup_local(pcbinfo,
489 &inp->in6p_laddr, lport, lookupflags, cred);
491 #if defined(INET) && defined(INET6)
495 tmpinp = in_pcblookup_local(pcbinfo, laddr,
496 lport, lookupflags, cred);
498 } while (tmpinp != NULL);
501 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4)
502 laddrp->s_addr = laddr.s_addr;
510 * Return cached socket options.
513 inp_so_options(const struct inpcb *inp)
519 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
520 so_options |= SO_REUSEPORT;
521 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
522 so_options |= SO_REUSEADDR;
525 #endif /* INET || INET6 */
528 * Check if a new BINDMULTI socket is allowed to be created.
530 * ni points to the new inp.
531 * oi points to the exisitng inp.
533 * This checks whether the existing inp also has BINDMULTI and
534 * whether the credentials match.
537 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
539 /* Check permissions match */
540 if ((ni->inp_flags2 & INP_BINDMULTI) &&
541 (ni->inp_cred->cr_uid !=
542 oi->inp_cred->cr_uid))
545 /* Check the existing inp has BINDMULTI set */
546 if ((ni->inp_flags2 & INP_BINDMULTI) &&
547 ((oi->inp_flags2 & INP_BINDMULTI) == 0))
551 * We're okay - either INP_BINDMULTI isn't set on ni, or
552 * it is and it matches the checks.
559 * Set up a bind operation on a PCB, performing port allocation
560 * as required, but do not actually modify the PCB. Callers can
561 * either complete the bind by setting inp_laddr/inp_lport and
562 * calling in_pcbinshash(), or they can just use the resulting
563 * port and address to authorise the sending of a once-off packet.
565 * On error, the values of *laddrp and *lportp are not changed.
568 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
569 u_short *lportp, struct ucred *cred)
571 struct socket *so = inp->inp_socket;
572 struct sockaddr_in *sin;
573 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
574 struct in_addr laddr;
576 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
580 * No state changes, so read locks are sufficient here.
582 INP_LOCK_ASSERT(inp);
583 INP_HASH_LOCK_ASSERT(pcbinfo);
585 if (TAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
586 return (EADDRNOTAVAIL);
587 laddr.s_addr = *laddrp;
588 if (nam != NULL && laddr.s_addr != INADDR_ANY)
590 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
591 lookupflags = INPLOOKUP_WILDCARD;
593 if ((error = prison_local_ip4(cred, &laddr)) != 0)
596 sin = (struct sockaddr_in *)nam;
597 if (nam->sa_len != sizeof (*sin))
601 * We should check the family, but old programs
602 * incorrectly fail to initialize it.
604 if (sin->sin_family != AF_INET)
605 return (EAFNOSUPPORT);
607 error = prison_local_ip4(cred, &sin->sin_addr);
610 if (sin->sin_port != *lportp) {
611 /* Don't allow the port to change. */
614 lport = sin->sin_port;
616 /* NB: lport is left as 0 if the port isn't being changed. */
617 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
619 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
620 * allow complete duplication of binding if
621 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
622 * and a multicast address is bound on both
623 * new and duplicated sockets.
625 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
626 reuseport = SO_REUSEADDR|SO_REUSEPORT;
627 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
628 sin->sin_port = 0; /* yech... */
629 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
631 * Is the address a local IP address?
632 * If INP_BINDANY is set, then the socket may be bound
633 * to any endpoint address, local or not.
635 if ((inp->inp_flags & INP_BINDANY) == 0 &&
636 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
637 return (EADDRNOTAVAIL);
639 laddr = sin->sin_addr;
645 if (ntohs(lport) <= V_ipport_reservedhigh &&
646 ntohs(lport) >= V_ipport_reservedlow &&
647 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
650 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
651 priv_check_cred(inp->inp_cred,
652 PRIV_NETINET_REUSEPORT, 0) != 0) {
653 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
654 lport, INPLOOKUP_WILDCARD, cred);
657 * This entire block sorely needs a rewrite.
660 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
661 ((t->inp_flags & INP_TIMEWAIT) == 0) &&
662 (so->so_type != SOCK_STREAM ||
663 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
664 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
665 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
666 (t->inp_flags2 & INP_REUSEPORT) == 0) &&
667 (inp->inp_cred->cr_uid !=
668 t->inp_cred->cr_uid))
672 * If the socket is a BINDMULTI socket, then
673 * the credentials need to match and the
674 * original socket also has to have been bound
677 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
680 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
681 lport, lookupflags, cred);
682 if (t && (t->inp_flags & INP_TIMEWAIT)) {
684 * XXXRW: If an incpb has had its timewait
685 * state recycled, we treat the address as
686 * being in use (for now). This is better
687 * than a panic, but not desirable.
691 (reuseport & tw->tw_so_options) == 0)
694 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
695 (reuseport & inp_so_options(t)) == 0) {
697 if (ntohl(sin->sin_addr.s_addr) !=
699 ntohl(t->inp_laddr.s_addr) !=
701 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
702 (t->inp_vflag & INP_IPV6PROTO) == 0)
705 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
713 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
718 *laddrp = laddr.s_addr;
724 * Connect from a socket to a specified address.
725 * Both address and port must be specified in argument sin.
726 * If don't have a local address for this socket yet,
730 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
731 struct ucred *cred, struct mbuf *m)
733 u_short lport, fport;
734 in_addr_t laddr, faddr;
737 INP_WLOCK_ASSERT(inp);
738 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
740 lport = inp->inp_lport;
741 laddr = inp->inp_laddr.s_addr;
742 anonport = (lport == 0);
743 error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
748 /* Do the initial binding of the local address if required. */
749 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
750 inp->inp_lport = lport;
751 inp->inp_laddr.s_addr = laddr;
752 if (in_pcbinshash(inp) != 0) {
753 inp->inp_laddr.s_addr = INADDR_ANY;
759 /* Commit the remaining changes. */
760 inp->inp_lport = lport;
761 inp->inp_laddr.s_addr = laddr;
762 inp->inp_faddr.s_addr = faddr;
763 inp->inp_fport = fport;
764 in_pcbrehash_mbuf(inp, m);
767 inp->inp_flags |= INP_ANONPORT;
772 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
775 return (in_pcbconnect_mbuf(inp, nam, cred, NULL));
779 * Do proper source address selection on an unbound socket in case
780 * of connect. Take jails into account as well.
783 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
788 struct sockaddr_in *sin;
792 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
795 * Bypass source address selection and use the primary jail IP
798 if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
802 bzero(&sro, sizeof(sro));
804 sin = (struct sockaddr_in *)&sro.ro_dst;
805 sin->sin_family = AF_INET;
806 sin->sin_len = sizeof(struct sockaddr_in);
807 sin->sin_addr.s_addr = faddr->s_addr;
810 * If route is known our src addr is taken from the i/f,
813 * Find out route to destination.
815 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
816 in_rtalloc_ign(&sro, 0, inp->inp_inc.inc_fibnum);
819 * If we found a route, use the address corresponding to
820 * the outgoing interface.
822 * Otherwise assume faddr is reachable on a directly connected
823 * network and try to find a corresponding interface to take
824 * the source address from.
826 if (sro.ro_rt == NULL || sro.ro_rt->rt_ifp == NULL) {
827 struct in_ifaddr *ia;
830 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
831 inp->inp_socket->so_fibnum));
833 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
834 inp->inp_socket->so_fibnum));
840 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
841 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
842 ifa_free(&ia->ia_ifa);
847 ifa_free(&ia->ia_ifa);
850 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
853 if (sa->sa_family != AF_INET)
855 sin = (struct sockaddr_in *)sa;
856 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
857 ia = (struct in_ifaddr *)ifa;
862 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
863 IF_ADDR_RUNLOCK(ifp);
866 IF_ADDR_RUNLOCK(ifp);
868 /* 3. As a last resort return the 'default' jail address. */
869 error = prison_get_ip4(cred, laddr);
874 * If the outgoing interface on the route found is not
875 * a loopback interface, use the address from that interface.
876 * In case of jails do those three steps:
877 * 1. check if the interface address belongs to the jail. If so use it.
878 * 2. check if we have any address on the outgoing interface
879 * belonging to this jail. If so use it.
880 * 3. as a last resort return the 'default' jail address.
882 if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
883 struct in_ifaddr *ia;
886 /* If not jailed, use the default returned. */
887 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
888 ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
889 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
894 /* 1. Check if the iface address belongs to the jail. */
895 sin = (struct sockaddr_in *)sro.ro_rt->rt_ifa->ifa_addr;
896 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
897 ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
898 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
903 * 2. Check if we have any address on the outgoing interface
904 * belonging to this jail.
907 ifp = sro.ro_rt->rt_ifp;
909 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
911 if (sa->sa_family != AF_INET)
913 sin = (struct sockaddr_in *)sa;
914 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
915 ia = (struct in_ifaddr *)ifa;
920 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
921 IF_ADDR_RUNLOCK(ifp);
924 IF_ADDR_RUNLOCK(ifp);
926 /* 3. As a last resort return the 'default' jail address. */
927 error = prison_get_ip4(cred, laddr);
932 * The outgoing interface is marked with 'loopback net', so a route
933 * to ourselves is here.
934 * Try to find the interface of the destination address and then
935 * take the address from there. That interface is not necessarily
936 * a loopback interface.
937 * In case of jails, check that it is an address of the jail
938 * and if we cannot find, fall back to the 'default' jail address.
940 if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
941 struct sockaddr_in sain;
942 struct in_ifaddr *ia;
944 bzero(&sain, sizeof(struct sockaddr_in));
945 sain.sin_family = AF_INET;
946 sain.sin_len = sizeof(struct sockaddr_in);
947 sain.sin_addr.s_addr = faddr->s_addr;
949 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sain),
950 inp->inp_socket->so_fibnum));
952 ia = ifatoia(ifa_ifwithnet(sintosa(&sain), 0,
953 inp->inp_socket->so_fibnum));
955 ia = ifatoia(ifa_ifwithaddr(sintosa(&sain)));
957 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
962 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
963 ifa_free(&ia->ia_ifa);
972 ifa_free(&ia->ia_ifa);
975 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
978 if (sa->sa_family != AF_INET)
980 sin = (struct sockaddr_in *)sa;
981 if (prison_check_ip4(cred,
982 &sin->sin_addr) == 0) {
983 ia = (struct in_ifaddr *)ifa;
988 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
989 IF_ADDR_RUNLOCK(ifp);
992 IF_ADDR_RUNLOCK(ifp);
995 /* 3. As a last resort return the 'default' jail address. */
996 error = prison_get_ip4(cred, laddr);
1001 if (sro.ro_rt != NULL)
1007 * Set up for a connect from a socket to the specified address.
1008 * On entry, *laddrp and *lportp should contain the current local
1009 * address and port for the PCB; these are updated to the values
1010 * that should be placed in inp_laddr and inp_lport to complete
1013 * On success, *faddrp and *fportp will be set to the remote address
1014 * and port. These are not updated in the error case.
1016 * If the operation fails because the connection already exists,
1017 * *oinpp will be set to the PCB of that connection so that the
1018 * caller can decide to override it. In all other cases, *oinpp
1022 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1023 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1024 struct inpcb **oinpp, struct ucred *cred)
1026 struct rm_priotracker in_ifa_tracker;
1027 struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1028 struct in_ifaddr *ia;
1030 struct in_addr laddr, faddr;
1031 u_short lport, fport;
1035 * Because a global state change doesn't actually occur here, a read
1036 * lock is sufficient.
1038 INP_LOCK_ASSERT(inp);
1039 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1043 if (nam->sa_len != sizeof (*sin))
1045 if (sin->sin_family != AF_INET)
1046 return (EAFNOSUPPORT);
1047 if (sin->sin_port == 0)
1048 return (EADDRNOTAVAIL);
1049 laddr.s_addr = *laddrp;
1051 faddr = sin->sin_addr;
1052 fport = sin->sin_port;
1054 if (!TAILQ_EMPTY(&V_in_ifaddrhead)) {
1056 * If the destination address is INADDR_ANY,
1057 * use the primary local address.
1058 * If the supplied address is INADDR_BROADCAST,
1059 * and the primary interface supports broadcast,
1060 * choose the broadcast address for that interface.
1062 if (faddr.s_addr == INADDR_ANY) {
1063 IN_IFADDR_RLOCK(&in_ifa_tracker);
1065 IA_SIN(TAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1066 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1068 (error = prison_get_ip4(cred, &faddr)) != 0)
1070 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1071 IN_IFADDR_RLOCK(&in_ifa_tracker);
1072 if (TAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1074 faddr = satosin(&TAILQ_FIRST(
1075 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1076 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1079 if (laddr.s_addr == INADDR_ANY) {
1080 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1082 * If the destination address is multicast and an outgoing
1083 * interface has been set as a multicast option, prefer the
1084 * address of that interface as our source address.
1086 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1087 inp->inp_moptions != NULL) {
1088 struct ip_moptions *imo;
1091 imo = inp->inp_moptions;
1092 if (imo->imo_multicast_ifp != NULL) {
1093 ifp = imo->imo_multicast_ifp;
1094 IN_IFADDR_RLOCK(&in_ifa_tracker);
1095 TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1096 if ((ia->ia_ifp == ifp) &&
1098 prison_check_ip4(cred,
1099 &ia->ia_addr.sin_addr) == 0))
1103 error = EADDRNOTAVAIL;
1105 laddr = ia->ia_addr.sin_addr;
1108 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1114 oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr, fport,
1115 laddr, lport, 0, NULL);
1119 return (EADDRINUSE);
1122 error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1127 *laddrp = laddr.s_addr;
1129 *faddrp = faddr.s_addr;
1135 in_pcbdisconnect(struct inpcb *inp)
1138 INP_WLOCK_ASSERT(inp);
1139 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1141 inp->inp_faddr.s_addr = INADDR_ANY;
1148 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1149 * For most protocols, this will be invoked immediately prior to calling
1150 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1151 * socket, in which case in_pcbfree() is deferred.
1154 in_pcbdetach(struct inpcb *inp)
1157 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1160 if (inp->inp_snd_tag != NULL)
1161 in_pcbdetach_txrtlmt(inp);
1163 inp->inp_socket->so_pcb = NULL;
1164 inp->inp_socket = NULL;
1168 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1169 * stability of an inpcb pointer despite the inpcb lock being released. This
1170 * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1171 * but where the inpcb lock may already held, or when acquiring a reference
1174 * in_pcbref() should be used only to provide brief memory stability, and
1175 * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1176 * garbage collect the inpcb if it has been in_pcbfree()'d from another
1177 * context. Until in_pcbrele() has returned that the inpcb is still valid,
1178 * lock and rele are the *only* safe operations that may be performed on the
1181 * While the inpcb will not be freed, releasing the inpcb lock means that the
1182 * connection's state may change, so the caller should be careful to
1183 * revalidate any cached state on reacquiring the lock. Drop the reference
1184 * using in_pcbrele().
1187 in_pcbref(struct inpcb *inp)
1190 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1192 refcount_acquire(&inp->inp_refcount);
1196 * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1197 * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1198 * return a flag indicating whether or not the inpcb remains valid. If it is
1199 * valid, we return with the inpcb lock held.
1201 * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1202 * reference on an inpcb. Historically more work was done here (actually, in
1203 * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1204 * need for the pcbinfo lock in in_pcbrele(). Deferring the free is entirely
1205 * about memory stability (and continued use of the write lock).
1208 in_pcbrele_rlocked(struct inpcb *inp)
1210 struct inpcbinfo *pcbinfo;
1212 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1214 INP_RLOCK_ASSERT(inp);
1216 if (refcount_release(&inp->inp_refcount) == 0) {
1218 * If the inpcb has been freed, let the caller know, even if
1219 * this isn't the last reference.
1221 if (inp->inp_flags2 & INP_FREED) {
1228 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1231 pcbinfo = inp->inp_pcbinfo;
1232 uma_zfree(pcbinfo->ipi_zone, inp);
1237 in_pcbrele_wlocked(struct inpcb *inp)
1239 struct inpcbinfo *pcbinfo;
1241 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1243 INP_WLOCK_ASSERT(inp);
1245 if (refcount_release(&inp->inp_refcount) == 0) {
1247 * If the inpcb has been freed, let the caller know, even if
1248 * this isn't the last reference.
1250 if (inp->inp_flags2 & INP_FREED) {
1257 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1260 pcbinfo = inp->inp_pcbinfo;
1261 uma_zfree(pcbinfo->ipi_zone, inp);
1266 * Temporary wrapper.
1269 in_pcbrele(struct inpcb *inp)
1272 return (in_pcbrele_wlocked(inp));
1276 * Unconditionally schedule an inpcb to be freed by decrementing its
1277 * reference count, which should occur only after the inpcb has been detached
1278 * from its socket. If another thread holds a temporary reference (acquired
1279 * using in_pcbref()) then the free is deferred until that reference is
1280 * released using in_pcbrele(), but the inpcb is still unlocked. Almost all
1281 * work, including removal from global lists, is done in this context, where
1282 * the pcbinfo lock is held.
1285 in_pcbfree(struct inpcb *inp)
1287 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1289 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1292 if (pcbinfo == &V_tcbinfo) {
1293 INP_INFO_LOCK_ASSERT(pcbinfo);
1295 INP_INFO_WLOCK_ASSERT(pcbinfo);
1298 INP_WLOCK_ASSERT(inp);
1300 /* XXXRW: Do as much as possible here. */
1301 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1302 if (inp->inp_sp != NULL)
1303 ipsec_delete_pcbpolicy(inp);
1305 INP_LIST_WLOCK(pcbinfo);
1306 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1307 in_pcbremlists(inp);
1308 INP_LIST_WUNLOCK(pcbinfo);
1310 if (inp->inp_vflag & INP_IPV6PROTO) {
1311 ip6_freepcbopts(inp->in6p_outputopts);
1312 if (inp->in6p_moptions != NULL)
1313 ip6_freemoptions(inp->in6p_moptions);
1316 if (inp->inp_options)
1317 (void)m_free(inp->inp_options);
1319 if (inp->inp_moptions != NULL)
1320 inp_freemoptions(inp->inp_moptions);
1322 RO_INVALIDATE_CACHE(&inp->inp_route);
1325 inp->inp_flags2 |= INP_FREED;
1326 crfree(inp->inp_cred);
1328 mac_inpcb_destroy(inp);
1330 if (!in_pcbrele_wlocked(inp))
1335 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1336 * port reservation, and preventing it from being returned by inpcb lookups.
1338 * It is used by TCP to mark an inpcb as unused and avoid future packet
1339 * delivery or event notification when a socket remains open but TCP has
1340 * closed. This might occur as a result of a shutdown()-initiated TCP close
1341 * or a RST on the wire, and allows the port binding to be reused while still
1342 * maintaining the invariant that so_pcb always points to a valid inpcb until
1345 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1346 * in_pcbnotifyall() and in_pcbpurgeif0()?
1349 in_pcbdrop(struct inpcb *inp)
1352 INP_WLOCK_ASSERT(inp);
1355 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1358 inp->inp_flags |= INP_DROPPED;
1359 if (inp->inp_flags & INP_INHASHLIST) {
1360 struct inpcbport *phd = inp->inp_phd;
1362 INP_HASH_WLOCK(inp->inp_pcbinfo);
1363 LIST_REMOVE(inp, inp_hash);
1364 LIST_REMOVE(inp, inp_portlist);
1365 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1366 LIST_REMOVE(phd, phd_hash);
1369 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1370 inp->inp_flags &= ~INP_INHASHLIST;
1372 in_pcbgroup_remove(inp);
1379 * Common routines to return the socket addresses associated with inpcbs.
1382 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1384 struct sockaddr_in *sin;
1386 sin = malloc(sizeof *sin, M_SONAME,
1388 sin->sin_family = AF_INET;
1389 sin->sin_len = sizeof(*sin);
1390 sin->sin_addr = *addr_p;
1391 sin->sin_port = port;
1393 return (struct sockaddr *)sin;
1397 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1400 struct in_addr addr;
1403 inp = sotoinpcb(so);
1404 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1407 port = inp->inp_lport;
1408 addr = inp->inp_laddr;
1411 *nam = in_sockaddr(port, &addr);
1416 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1419 struct in_addr addr;
1422 inp = sotoinpcb(so);
1423 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1426 port = inp->inp_fport;
1427 addr = inp->inp_faddr;
1430 *nam = in_sockaddr(port, &addr);
1435 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1436 struct inpcb *(*notify)(struct inpcb *, int))
1438 struct inpcb *inp, *inp_temp;
1440 INP_INFO_WLOCK(pcbinfo);
1441 LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1444 if ((inp->inp_vflag & INP_IPV4) == 0) {
1449 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1450 inp->inp_socket == NULL) {
1454 if ((*notify)(inp, errno))
1457 INP_INFO_WUNLOCK(pcbinfo);
1461 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1464 struct ip_moptions *imo;
1467 INP_INFO_WLOCK(pcbinfo);
1468 LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1470 imo = inp->inp_moptions;
1471 if ((inp->inp_vflag & INP_IPV4) &&
1474 * Unselect the outgoing interface if it is being
1477 if (imo->imo_multicast_ifp == ifp)
1478 imo->imo_multicast_ifp = NULL;
1481 * Drop multicast group membership if we joined
1482 * through the interface being detached.
1484 for (i = 0, gap = 0; i < imo->imo_num_memberships;
1486 if (imo->imo_membership[i]->inm_ifp == ifp) {
1487 in_delmulti(imo->imo_membership[i]);
1489 } else if (gap != 0)
1490 imo->imo_membership[i - gap] =
1491 imo->imo_membership[i];
1493 imo->imo_num_memberships -= gap;
1497 INP_INFO_WUNLOCK(pcbinfo);
1501 * Lookup a PCB based on the local address and port. Caller must hold the
1502 * hash lock. No inpcb locks or references are acquired.
1504 #define INP_LOOKUP_MAPPED_PCB_COST 3
1506 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1507 u_short lport, int lookupflags, struct ucred *cred)
1511 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1517 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1518 ("%s: invalid lookup flags %d", __func__, lookupflags));
1520 INP_HASH_LOCK_ASSERT(pcbinfo);
1522 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1523 struct inpcbhead *head;
1525 * Look for an unconnected (wildcard foreign addr) PCB that
1526 * matches the local address and port we're looking for.
1528 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1529 0, pcbinfo->ipi_hashmask)];
1530 LIST_FOREACH(inp, head, inp_hash) {
1532 /* XXX inp locking */
1533 if ((inp->inp_vflag & INP_IPV4) == 0)
1536 if (inp->inp_faddr.s_addr == INADDR_ANY &&
1537 inp->inp_laddr.s_addr == laddr.s_addr &&
1538 inp->inp_lport == lport) {
1543 prison_equal_ip4(cred->cr_prison,
1544 inp->inp_cred->cr_prison))
1553 struct inpcbporthead *porthash;
1554 struct inpcbport *phd;
1555 struct inpcb *match = NULL;
1557 * Best fit PCB lookup.
1559 * First see if this local port is in use by looking on the
1562 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1563 pcbinfo->ipi_porthashmask)];
1564 LIST_FOREACH(phd, porthash, phd_hash) {
1565 if (phd->phd_port == lport)
1570 * Port is in use by one or more PCBs. Look for best
1573 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1576 !prison_equal_ip4(inp->inp_cred->cr_prison,
1580 /* XXX inp locking */
1581 if ((inp->inp_vflag & INP_IPV4) == 0)
1584 * We never select the PCB that has
1585 * INP_IPV6 flag and is bound to :: if
1586 * we have another PCB which is bound
1587 * to 0.0.0.0. If a PCB has the
1588 * INP_IPV6 flag, then we set its cost
1589 * higher than IPv4 only PCBs.
1591 * Note that the case only happens
1592 * when a socket is bound to ::, under
1593 * the condition that the use of the
1594 * mapped address is allowed.
1596 if ((inp->inp_vflag & INP_IPV6) != 0)
1597 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1599 if (inp->inp_faddr.s_addr != INADDR_ANY)
1601 if (inp->inp_laddr.s_addr != INADDR_ANY) {
1602 if (laddr.s_addr == INADDR_ANY)
1604 else if (inp->inp_laddr.s_addr != laddr.s_addr)
1607 if (laddr.s_addr != INADDR_ANY)
1610 if (wildcard < matchwild) {
1612 matchwild = wildcard;
1621 #undef INP_LOOKUP_MAPPED_PCB_COST
1625 * Lookup PCB in hash list, using pcbgroup tables.
1627 static struct inpcb *
1628 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1629 struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1630 u_int lport_arg, int lookupflags, struct ifnet *ifp)
1632 struct inpcbhead *head;
1633 struct inpcb *inp, *tmpinp;
1634 u_short fport = fport_arg, lport = lport_arg;
1637 * First look for an exact match.
1640 INP_GROUP_LOCK(pcbgroup);
1641 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1642 pcbgroup->ipg_hashmask)];
1643 LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1645 /* XXX inp locking */
1646 if ((inp->inp_vflag & INP_IPV4) == 0)
1649 if (inp->inp_faddr.s_addr == faddr.s_addr &&
1650 inp->inp_laddr.s_addr == laddr.s_addr &&
1651 inp->inp_fport == fport &&
1652 inp->inp_lport == lport) {
1654 * XXX We should be able to directly return
1655 * the inp here, without any checks.
1656 * Well unless both bound with SO_REUSEPORT?
1658 if (prison_flag(inp->inp_cred, PR_IP4))
1664 if (tmpinp != NULL) {
1671 * For incoming connections, we may wish to do a wildcard
1672 * match for an RSS-local socket.
1674 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1675 struct inpcb *local_wild = NULL, *local_exact = NULL;
1677 struct inpcb *local_wild_mapped = NULL;
1679 struct inpcb *jail_wild = NULL;
1680 struct inpcbhead *head;
1684 * Order of socket selection - we always prefer jails.
1685 * 1. jailed, non-wild.
1687 * 3. non-jailed, non-wild.
1688 * 4. non-jailed, wild.
1691 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
1692 lport, 0, pcbgroup->ipg_hashmask)];
1693 LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1695 /* XXX inp locking */
1696 if ((inp->inp_vflag & INP_IPV4) == 0)
1699 if (inp->inp_faddr.s_addr != INADDR_ANY ||
1700 inp->inp_lport != lport)
1703 injail = prison_flag(inp->inp_cred, PR_IP4);
1705 if (prison_check_ip4(inp->inp_cred,
1709 if (local_exact != NULL)
1713 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1718 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1720 /* XXX inp locking, NULL check */
1721 if (inp->inp_vflag & INP_IPV6PROTO)
1722 local_wild_mapped = inp;
1730 } /* LIST_FOREACH */
1739 inp = local_wild_mapped;
1747 * Then look for a wildcard match, if requested.
1749 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1750 struct inpcb *local_wild = NULL, *local_exact = NULL;
1752 struct inpcb *local_wild_mapped = NULL;
1754 struct inpcb *jail_wild = NULL;
1755 struct inpcbhead *head;
1759 * Order of socket selection - we always prefer jails.
1760 * 1. jailed, non-wild.
1762 * 3. non-jailed, non-wild.
1763 * 4. non-jailed, wild.
1765 head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
1766 0, pcbinfo->ipi_wildmask)];
1767 LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
1769 /* XXX inp locking */
1770 if ((inp->inp_vflag & INP_IPV4) == 0)
1773 if (inp->inp_faddr.s_addr != INADDR_ANY ||
1774 inp->inp_lport != lport)
1777 injail = prison_flag(inp->inp_cred, PR_IP4);
1779 if (prison_check_ip4(inp->inp_cred,
1783 if (local_exact != NULL)
1787 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1792 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1794 /* XXX inp locking, NULL check */
1795 if (inp->inp_vflag & INP_IPV6PROTO)
1796 local_wild_mapped = inp;
1804 } /* LIST_FOREACH */
1812 inp = local_wild_mapped;
1816 } /* if (lookupflags & INPLOOKUP_WILDCARD) */
1817 INP_GROUP_UNLOCK(pcbgroup);
1822 INP_GROUP_UNLOCK(pcbgroup);
1823 if (lookupflags & INPLOOKUP_WLOCKPCB) {
1825 if (in_pcbrele_wlocked(inp))
1827 } else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1829 if (in_pcbrele_rlocked(inp))
1832 panic("%s: locking bug", __func__);
1835 #endif /* PCBGROUP */
1838 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
1839 * that the caller has locked the hash list, and will not perform any further
1840 * locking or reference operations on either the hash list or the connection.
1842 static struct inpcb *
1843 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1844 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
1847 struct inpcbhead *head;
1848 struct inpcb *inp, *tmpinp;
1849 u_short fport = fport_arg, lport = lport_arg;
1851 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1852 ("%s: invalid lookup flags %d", __func__, lookupflags));
1854 INP_HASH_LOCK_ASSERT(pcbinfo);
1857 * First look for an exact match.
1860 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1861 pcbinfo->ipi_hashmask)];
1862 LIST_FOREACH(inp, head, inp_hash) {
1864 /* XXX inp locking */
1865 if ((inp->inp_vflag & INP_IPV4) == 0)
1868 if (inp->inp_faddr.s_addr == faddr.s_addr &&
1869 inp->inp_laddr.s_addr == laddr.s_addr &&
1870 inp->inp_fport == fport &&
1871 inp->inp_lport == lport) {
1873 * XXX We should be able to directly return
1874 * the inp here, without any checks.
1875 * Well unless both bound with SO_REUSEPORT?
1877 if (prison_flag(inp->inp_cred, PR_IP4))
1887 * Then look for a wildcard match, if requested.
1889 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1890 struct inpcb *local_wild = NULL, *local_exact = NULL;
1892 struct inpcb *local_wild_mapped = NULL;
1894 struct inpcb *jail_wild = NULL;
1898 * Order of socket selection - we always prefer jails.
1899 * 1. jailed, non-wild.
1901 * 3. non-jailed, non-wild.
1902 * 4. non-jailed, wild.
1905 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1906 0, pcbinfo->ipi_hashmask)];
1907 LIST_FOREACH(inp, head, inp_hash) {
1909 /* XXX inp locking */
1910 if ((inp->inp_vflag & INP_IPV4) == 0)
1913 if (inp->inp_faddr.s_addr != INADDR_ANY ||
1914 inp->inp_lport != lport)
1917 injail = prison_flag(inp->inp_cred, PR_IP4);
1919 if (prison_check_ip4(inp->inp_cred,
1923 if (local_exact != NULL)
1927 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1932 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1934 /* XXX inp locking, NULL check */
1935 if (inp->inp_vflag & INP_IPV6PROTO)
1936 local_wild_mapped = inp;
1944 } /* LIST_FOREACH */
1945 if (jail_wild != NULL)
1947 if (local_exact != NULL)
1948 return (local_exact);
1949 if (local_wild != NULL)
1950 return (local_wild);
1952 if (local_wild_mapped != NULL)
1953 return (local_wild_mapped);
1955 } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
1961 * Lookup PCB in hash list, using pcbinfo tables. This variation locks the
1962 * hash list lock, and will return the inpcb locked (i.e., requires
1963 * INPLOOKUP_LOCKPCB).
1965 static struct inpcb *
1966 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1967 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
1972 INP_HASH_RLOCK(pcbinfo);
1973 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
1974 (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
1977 INP_HASH_RUNLOCK(pcbinfo);
1978 if (lookupflags & INPLOOKUP_WLOCKPCB) {
1980 if (in_pcbrele_wlocked(inp))
1982 } else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1984 if (in_pcbrele_rlocked(inp))
1987 panic("%s: locking bug", __func__);
1989 INP_HASH_RUNLOCK(pcbinfo);
1994 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
1995 * from which a pre-calculated hash value may be extracted.
1997 * Possibly more of this logic should be in in_pcbgroup.c.
2000 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2001 struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2003 #if defined(PCBGROUP) && !defined(RSS)
2004 struct inpcbgroup *pcbgroup;
2007 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2008 ("%s: invalid lookup flags %d", __func__, lookupflags));
2009 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2010 ("%s: LOCKPCB not set", __func__));
2013 * When not using RSS, use connection groups in preference to the
2014 * reservation table when looking up 4-tuples. When using RSS, just
2015 * use the reservation table, due to the cost of the Toeplitz hash
2018 * XXXRW: This policy belongs in the pcbgroup code, as in principle
2019 * we could be doing RSS with a non-Toeplitz hash that is affordable
2022 #if defined(PCBGROUP) && !defined(RSS)
2023 if (in_pcbgroup_enabled(pcbinfo)) {
2024 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2026 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2027 laddr, lport, lookupflags, ifp));
2030 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2035 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2036 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2037 struct ifnet *ifp, struct mbuf *m)
2040 struct inpcbgroup *pcbgroup;
2043 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2044 ("%s: invalid lookup flags %d", __func__, lookupflags));
2045 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2046 ("%s: LOCKPCB not set", __func__));
2050 * If we can use a hardware-generated hash to look up the connection
2051 * group, use that connection group to find the inpcb. Otherwise
2052 * fall back on a software hash -- or the reservation table if we're
2055 * XXXRW: As above, that policy belongs in the pcbgroup code.
2057 if (in_pcbgroup_enabled(pcbinfo) &&
2058 !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2059 pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2060 m->m_pkthdr.flowid);
2061 if (pcbgroup != NULL)
2062 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2063 fport, laddr, lport, lookupflags, ifp));
2065 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2067 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2068 laddr, lport, lookupflags, ifp));
2072 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2078 * Insert PCB onto various hash lists.
2081 in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
2083 struct inpcbhead *pcbhash;
2084 struct inpcbporthead *pcbporthash;
2085 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2086 struct inpcbport *phd;
2087 u_int32_t hashkey_faddr;
2089 INP_WLOCK_ASSERT(inp);
2090 INP_HASH_WLOCK_ASSERT(pcbinfo);
2092 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2093 ("in_pcbinshash: INP_INHASHLIST"));
2096 if (inp->inp_vflag & INP_IPV6)
2097 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2100 hashkey_faddr = inp->inp_faddr.s_addr;
2102 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2103 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2105 pcbporthash = &pcbinfo->ipi_porthashbase[
2106 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2109 * Go through port list and look for a head for this lport.
2111 LIST_FOREACH(phd, pcbporthash, phd_hash) {
2112 if (phd->phd_port == inp->inp_lport)
2116 * If none exists, malloc one and tack it on.
2119 phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2121 return (ENOBUFS); /* XXX */
2123 phd->phd_port = inp->inp_lport;
2124 LIST_INIT(&phd->phd_pcblist);
2125 LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2128 LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2129 LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2130 inp->inp_flags |= INP_INHASHLIST;
2132 if (do_pcbgroup_update)
2133 in_pcbgroup_update(inp);
2139 * For now, there are two public interfaces to insert an inpcb into the hash
2140 * lists -- one that does update pcbgroups, and one that doesn't. The latter
2141 * is used only in the TCP syncache, where in_pcbinshash is called before the
2142 * full 4-tuple is set for the inpcb, and we don't want to install in the
2143 * pcbgroup until later.
2145 * XXXRW: This seems like a misfeature. in_pcbinshash should always update
2146 * connection groups, and partially initialised inpcbs should not be exposed
2147 * to either reservation hash tables or pcbgroups.
2150 in_pcbinshash(struct inpcb *inp)
2153 return (in_pcbinshash_internal(inp, 1));
2157 in_pcbinshash_nopcbgroup(struct inpcb *inp)
2160 return (in_pcbinshash_internal(inp, 0));
2164 * Move PCB to the proper hash bucket when { faddr, fport } have been
2165 * changed. NOTE: This does not handle the case of the lport changing (the
2166 * hashed port list would have to be updated as well), so the lport must
2167 * not change after in_pcbinshash() has been called.
2170 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2172 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2173 struct inpcbhead *head;
2174 u_int32_t hashkey_faddr;
2176 INP_WLOCK_ASSERT(inp);
2177 INP_HASH_WLOCK_ASSERT(pcbinfo);
2179 KASSERT(inp->inp_flags & INP_INHASHLIST,
2180 ("in_pcbrehash: !INP_INHASHLIST"));
2183 if (inp->inp_vflag & INP_IPV6)
2184 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2187 hashkey_faddr = inp->inp_faddr.s_addr;
2189 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2190 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2192 LIST_REMOVE(inp, inp_hash);
2193 LIST_INSERT_HEAD(head, inp, inp_hash);
2197 in_pcbgroup_update_mbuf(inp, m);
2199 in_pcbgroup_update(inp);
2204 in_pcbrehash(struct inpcb *inp)
2207 in_pcbrehash_mbuf(inp, NULL);
2211 * Remove PCB from various lists.
2214 in_pcbremlists(struct inpcb *inp)
2216 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2219 if (pcbinfo == &V_tcbinfo) {
2220 INP_INFO_RLOCK_ASSERT(pcbinfo);
2222 INP_INFO_WLOCK_ASSERT(pcbinfo);
2226 INP_WLOCK_ASSERT(inp);
2227 INP_LIST_WLOCK_ASSERT(pcbinfo);
2229 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2230 if (inp->inp_flags & INP_INHASHLIST) {
2231 struct inpcbport *phd = inp->inp_phd;
2233 INP_HASH_WLOCK(pcbinfo);
2234 LIST_REMOVE(inp, inp_hash);
2235 LIST_REMOVE(inp, inp_portlist);
2236 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
2237 LIST_REMOVE(phd, phd_hash);
2240 INP_HASH_WUNLOCK(pcbinfo);
2241 inp->inp_flags &= ~INP_INHASHLIST;
2243 LIST_REMOVE(inp, inp_list);
2244 pcbinfo->ipi_count--;
2246 in_pcbgroup_remove(inp);
2251 * Check for alternatives when higher level complains
2252 * about service problems. For now, invalidate cached
2253 * routing information. If the route was created dynamically
2254 * (by a redirect), time to try a default gateway again.
2257 in_losing(struct inpcb *inp)
2260 RO_INVALIDATE_CACHE(&inp->inp_route);
2265 * A set label operation has occurred at the socket layer, propagate the
2266 * label change into the in_pcb for the socket.
2269 in_pcbsosetlabel(struct socket *so)
2274 inp = sotoinpcb(so);
2275 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2279 mac_inpcb_sosetlabel(so, inp);
2286 * ipport_tick runs once per second, determining if random port allocation
2287 * should be continued. If more than ipport_randomcps ports have been
2288 * allocated in the last second, then we return to sequential port
2289 * allocation. We return to random allocation only once we drop below
2290 * ipport_randomcps for at least ipport_randomtime seconds.
2293 ipport_tick(void *xtp)
2295 VNET_ITERATOR_DECL(vnet_iter);
2297 VNET_LIST_RLOCK_NOSLEEP();
2298 VNET_FOREACH(vnet_iter) {
2299 CURVNET_SET(vnet_iter); /* XXX appease INVARIANTS here */
2300 if (V_ipport_tcpallocs <=
2301 V_ipport_tcplastcount + V_ipport_randomcps) {
2302 if (V_ipport_stoprandom > 0)
2303 V_ipport_stoprandom--;
2305 V_ipport_stoprandom = V_ipport_randomtime;
2306 V_ipport_tcplastcount = V_ipport_tcpallocs;
2309 VNET_LIST_RUNLOCK_NOSLEEP();
2310 callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2317 callout_stop(&ipport_tick_callout);
2321 * The ipport_callout should start running at about the time we attach the
2322 * inet or inet6 domains.
2325 ipport_tick_init(const void *unused __unused)
2328 /* Start ipport_tick. */
2329 callout_init(&ipport_tick_callout, 1);
2330 callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2331 EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2332 SHUTDOWN_PRI_DEFAULT);
2334 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2335 ipport_tick_init, NULL);
2338 inp_wlock(struct inpcb *inp)
2345 inp_wunlock(struct inpcb *inp)
2352 inp_rlock(struct inpcb *inp)
2359 inp_runlock(struct inpcb *inp)
2365 #ifdef INVARIANT_SUPPORT
2367 inp_lock_assert(struct inpcb *inp)
2370 INP_WLOCK_ASSERT(inp);
2374 inp_unlock_assert(struct inpcb *inp)
2377 INP_UNLOCK_ASSERT(inp);
2382 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2386 INP_INFO_WLOCK(&V_tcbinfo);
2387 LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2392 INP_INFO_WUNLOCK(&V_tcbinfo);
2396 inp_inpcbtosocket(struct inpcb *inp)
2399 INP_WLOCK_ASSERT(inp);
2400 return (inp->inp_socket);
2404 inp_inpcbtotcpcb(struct inpcb *inp)
2407 INP_WLOCK_ASSERT(inp);
2408 return ((struct tcpcb *)inp->inp_ppcb);
2412 inp_ip_tos_get(const struct inpcb *inp)
2415 return (inp->inp_ip_tos);
2419 inp_ip_tos_set(struct inpcb *inp, int val)
2422 inp->inp_ip_tos = val;
2426 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2427 uint32_t *faddr, uint16_t *fp)
2430 INP_LOCK_ASSERT(inp);
2431 *laddr = inp->inp_laddr.s_addr;
2432 *faddr = inp->inp_faddr.s_addr;
2433 *lp = inp->inp_lport;
2434 *fp = inp->inp_fport;
2438 so_sotoinpcb(struct socket *so)
2441 return (sotoinpcb(so));
2445 so_sototcpcb(struct socket *so)
2448 return (sototcpcb(so));
2452 * Create an external-format (``xinpcb'') structure using the information in
2453 * the kernel-format in_pcb structure pointed to by inp. This is done to
2454 * reduce the spew of irrelevant information over this interface, to isolate
2455 * user code from changes in the kernel structure, and potentially to provide
2456 * information-hiding if we decide that some of this information should be
2457 * hidden from users.
2460 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2463 xi->xi_len = sizeof(struct xinpcb);
2464 if (inp->inp_socket)
2465 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2467 bzero(&xi->xi_socket, sizeof(struct xsocket));
2468 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2469 xi->inp_gencnt = inp->inp_gencnt;
2470 xi->inp_ppcb = inp->inp_ppcb;
2471 xi->inp_flow = inp->inp_flow;
2472 xi->inp_flowid = inp->inp_flowid;
2473 xi->inp_flowtype = inp->inp_flowtype;
2474 xi->inp_flags = inp->inp_flags;
2475 xi->inp_flags2 = inp->inp_flags2;
2476 xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2477 xi->in6p_cksum = inp->in6p_cksum;
2478 xi->in6p_hops = inp->in6p_hops;
2479 xi->inp_ip_tos = inp->inp_ip_tos;
2480 xi->inp_vflag = inp->inp_vflag;
2481 xi->inp_ip_ttl = inp->inp_ip_ttl;
2482 xi->inp_ip_p = inp->inp_ip_p;
2483 xi->inp_ip_minttl = inp->inp_ip_minttl;
2488 db_print_indent(int indent)
2492 for (i = 0; i < indent; i++)
2497 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2499 char faddr_str[48], laddr_str[48];
2501 db_print_indent(indent);
2502 db_printf("%s at %p\n", name, inc);
2507 if (inc->inc_flags & INC_ISIPV6) {
2509 ip6_sprintf(laddr_str, &inc->inc6_laddr);
2510 ip6_sprintf(faddr_str, &inc->inc6_faddr);
2515 inet_ntoa_r(inc->inc_laddr, laddr_str);
2516 inet_ntoa_r(inc->inc_faddr, faddr_str);
2518 db_print_indent(indent);
2519 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
2520 ntohs(inc->inc_lport));
2521 db_print_indent(indent);
2522 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
2523 ntohs(inc->inc_fport));
2527 db_print_inpflags(int inp_flags)
2532 if (inp_flags & INP_RECVOPTS) {
2533 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2536 if (inp_flags & INP_RECVRETOPTS) {
2537 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2540 if (inp_flags & INP_RECVDSTADDR) {
2541 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2544 if (inp_flags & INP_ORIGDSTADDR) {
2545 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2548 if (inp_flags & INP_HDRINCL) {
2549 db_printf("%sINP_HDRINCL", comma ? ", " : "");
2552 if (inp_flags & INP_HIGHPORT) {
2553 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2556 if (inp_flags & INP_LOWPORT) {
2557 db_printf("%sINP_LOWPORT", comma ? ", " : "");
2560 if (inp_flags & INP_ANONPORT) {
2561 db_printf("%sINP_ANONPORT", comma ? ", " : "");
2564 if (inp_flags & INP_RECVIF) {
2565 db_printf("%sINP_RECVIF", comma ? ", " : "");
2568 if (inp_flags & INP_MTUDISC) {
2569 db_printf("%sINP_MTUDISC", comma ? ", " : "");
2572 if (inp_flags & INP_RECVTTL) {
2573 db_printf("%sINP_RECVTTL", comma ? ", " : "");
2576 if (inp_flags & INP_DONTFRAG) {
2577 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2580 if (inp_flags & INP_RECVTOS) {
2581 db_printf("%sINP_RECVTOS", comma ? ", " : "");
2584 if (inp_flags & IN6P_IPV6_V6ONLY) {
2585 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2588 if (inp_flags & IN6P_PKTINFO) {
2589 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2592 if (inp_flags & IN6P_HOPLIMIT) {
2593 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2596 if (inp_flags & IN6P_HOPOPTS) {
2597 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2600 if (inp_flags & IN6P_DSTOPTS) {
2601 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2604 if (inp_flags & IN6P_RTHDR) {
2605 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2608 if (inp_flags & IN6P_RTHDRDSTOPTS) {
2609 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2612 if (inp_flags & IN6P_TCLASS) {
2613 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2616 if (inp_flags & IN6P_AUTOFLOWLABEL) {
2617 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2620 if (inp_flags & INP_TIMEWAIT) {
2621 db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
2624 if (inp_flags & INP_ONESBCAST) {
2625 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2628 if (inp_flags & INP_DROPPED) {
2629 db_printf("%sINP_DROPPED", comma ? ", " : "");
2632 if (inp_flags & INP_SOCKREF) {
2633 db_printf("%sINP_SOCKREF", comma ? ", " : "");
2636 if (inp_flags & IN6P_RFC2292) {
2637 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2640 if (inp_flags & IN6P_MTU) {
2641 db_printf("IN6P_MTU%s", comma ? ", " : "");
2647 db_print_inpvflag(u_char inp_vflag)
2652 if (inp_vflag & INP_IPV4) {
2653 db_printf("%sINP_IPV4", comma ? ", " : "");
2656 if (inp_vflag & INP_IPV6) {
2657 db_printf("%sINP_IPV6", comma ? ", " : "");
2660 if (inp_vflag & INP_IPV6PROTO) {
2661 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2667 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2670 db_print_indent(indent);
2671 db_printf("%s at %p\n", name, inp);
2675 db_print_indent(indent);
2676 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2678 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2680 db_print_indent(indent);
2681 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
2682 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2684 db_print_indent(indent);
2685 db_printf("inp_label: %p inp_flags: 0x%x (",
2686 inp->inp_label, inp->inp_flags);
2687 db_print_inpflags(inp->inp_flags);
2690 db_print_indent(indent);
2691 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
2693 db_print_inpvflag(inp->inp_vflag);
2696 db_print_indent(indent);
2697 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
2698 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2700 db_print_indent(indent);
2702 if (inp->inp_vflag & INP_IPV6) {
2703 db_printf("in6p_options: %p in6p_outputopts: %p "
2704 "in6p_moptions: %p\n", inp->in6p_options,
2705 inp->in6p_outputopts, inp->in6p_moptions);
2706 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
2707 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2712 db_printf("inp_ip_tos: %d inp_ip_options: %p "
2713 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2714 inp->inp_options, inp->inp_moptions);
2717 db_print_indent(indent);
2718 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
2719 (uintmax_t)inp->inp_gencnt);
2722 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
2727 db_printf("usage: show inpcb <addr>\n");
2730 inp = (struct inpcb *)addr;
2732 db_print_inpcb(inp, "inpcb", 0);
2738 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
2742 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
2744 union if_snd_tag_modify_params params = {
2745 .rate_limit.max_rate = max_pacing_rate,
2747 struct m_snd_tag *mst;
2751 mst = inp->inp_snd_tag;
2759 if (ifp->if_snd_tag_modify == NULL) {
2762 error = ifp->if_snd_tag_modify(mst, ¶ms);
2768 * Query existing TX rate limit based on the existing
2769 * "inp->inp_snd_tag", if any.
2772 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
2774 union if_snd_tag_query_params params = { };
2775 struct m_snd_tag *mst;
2779 mst = inp->inp_snd_tag;
2787 if (ifp->if_snd_tag_query == NULL) {
2790 error = ifp->if_snd_tag_query(mst, ¶ms);
2791 if (error == 0 && p_max_pacing_rate != NULL)
2792 *p_max_pacing_rate = params.rate_limit.max_rate;
2798 * Query existing TX queue level based on the existing
2799 * "inp->inp_snd_tag", if any.
2802 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
2804 union if_snd_tag_query_params params = { };
2805 struct m_snd_tag *mst;
2809 mst = inp->inp_snd_tag;
2817 if (ifp->if_snd_tag_query == NULL)
2818 return (EOPNOTSUPP);
2820 error = ifp->if_snd_tag_query(mst, ¶ms);
2821 if (error == 0 && p_txqueue_level != NULL)
2822 *p_txqueue_level = params.rate_limit.queue_level;
2827 * Allocate a new TX rate limit send tag from the network interface
2828 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
2831 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
2832 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate)
2834 union if_snd_tag_alloc_params params = {
2835 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
2836 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
2837 .rate_limit.hdr.flowid = flowid,
2838 .rate_limit.hdr.flowtype = flowtype,
2839 .rate_limit.max_rate = max_pacing_rate,
2843 INP_WLOCK_ASSERT(inp);
2845 if (inp->inp_snd_tag != NULL)
2848 if (ifp->if_snd_tag_alloc == NULL) {
2851 error = ifp->if_snd_tag_alloc(ifp, ¶ms, &inp->inp_snd_tag);
2854 * At success increment the refcount on
2855 * the send tag's network interface:
2858 if_ref(inp->inp_snd_tag->ifp);
2864 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
2868 in_pcbdetach_txrtlmt(struct inpcb *inp)
2870 struct m_snd_tag *mst;
2873 INP_WLOCK_ASSERT(inp);
2875 mst = inp->inp_snd_tag;
2876 inp->inp_snd_tag = NULL;
2886 * If the device was detached while we still had reference(s)
2887 * on the ifp, we assume if_snd_tag_free() was replaced with
2890 ifp->if_snd_tag_free(mst);
2892 /* release reference count on network interface */
2897 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
2898 * is set in the fast path and will attach/detach/modify the TX rate
2899 * limit send tag based on the socket's so_max_pacing_rate value.
2902 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
2904 struct socket *socket;
2905 uint32_t max_pacing_rate;
2912 socket = inp->inp_socket;
2916 if (!INP_WLOCKED(inp)) {
2918 * NOTE: If the write locking fails, we need to bail
2919 * out and use the non-ratelimited ring for the
2920 * transmit until there is a new chance to get the
2923 if (!INP_TRY_UPGRADE(inp))
2931 * NOTE: The so_max_pacing_rate value is read unlocked,
2932 * because atomic updates are not required since the variable
2933 * is checked at every mbuf we send. It is assumed that the
2934 * variable read itself will be atomic.
2936 max_pacing_rate = socket->so_max_pacing_rate;
2939 * NOTE: When attaching to a network interface a reference is
2940 * made to ensure the network interface doesn't go away until
2941 * all ratelimit connections are gone. The network interface
2942 * pointers compared below represent valid network interfaces,
2943 * except when comparing towards NULL.
2945 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
2947 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
2948 if (inp->inp_snd_tag != NULL)
2949 in_pcbdetach_txrtlmt(inp);
2951 } else if (inp->inp_snd_tag == NULL) {
2953 * In order to utilize packet pacing with RSS, we need
2954 * to wait until there is a valid RSS hash before we
2957 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
2960 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
2961 mb->m_pkthdr.flowid, max_pacing_rate);
2964 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
2966 if (error == 0 || error == EOPNOTSUPP)
2967 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
2973 * Track route changes for TX rate limiting.
2976 in_pcboutput_eagain(struct inpcb *inp)
2978 struct socket *socket;
2984 socket = inp->inp_socket;
2988 if (inp->inp_snd_tag == NULL)
2991 if (!INP_WLOCKED(inp)) {
2993 * NOTE: If the write locking fails, we need to bail
2994 * out and use the non-ratelimited ring for the
2995 * transmit until there is a new chance to get the
2998 if (!INP_TRY_UPGRADE(inp))
3005 /* detach rate limiting */
3006 in_pcbdetach_txrtlmt(inp);
3008 /* make sure new mbuf send tag allocation is made */
3009 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3014 #endif /* RATELIMIT */