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 static struct callout ipport_tick_callout;
114 * These configure the range of local port addresses assigned to
115 * "unspecified" outgoing connections/packets/whatever.
117 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1; /* 1023 */
118 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART; /* 600 */
119 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST; /* 10000 */
120 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST; /* 65535 */
121 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO; /* 49152 */
122 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO; /* 65535 */
125 * Reserved ports accessible only to root. There are significant
126 * security considerations that must be accounted for when changing these,
127 * but the security benefits can be great. Please be careful.
129 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1; /* 1023 */
130 VNET_DEFINE(int, ipport_reservedlow);
132 /* Variables dealing with random ephemeral port allocation. */
133 VNET_DEFINE(int, ipport_randomized) = 1; /* user controlled via sysctl */
134 VNET_DEFINE(int, ipport_randomcps) = 10; /* user controlled via sysctl */
135 VNET_DEFINE(int, ipport_randomtime) = 45; /* user controlled via sysctl */
136 VNET_DEFINE(int, ipport_stoprandom); /* toggled by ipport_tick */
137 VNET_DEFINE(int, ipport_tcpallocs);
138 static VNET_DEFINE(int, ipport_tcplastcount);
140 #define V_ipport_tcplastcount VNET(ipport_tcplastcount)
142 static void in_pcbremlists(struct inpcb *inp);
144 static struct inpcb *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
145 struct in_addr faddr, u_int fport_arg,
146 struct in_addr laddr, u_int lport_arg,
147 int lookupflags, struct ifnet *ifp);
149 #define RANGECHK(var, min, max) \
150 if ((var) < (min)) { (var) = (min); } \
151 else if ((var) > (max)) { (var) = (max); }
154 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
158 error = sysctl_handle_int(oidp, arg1, arg2, req);
160 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
161 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
162 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
163 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
164 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
165 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
172 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0,
175 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
176 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
177 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I", "");
178 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
179 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
180 &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I", "");
181 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
182 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
183 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I", "");
184 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
185 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
186 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I", "");
187 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
188 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
189 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I", "");
190 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
191 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
192 &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I", "");
193 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
194 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
195 &VNET_NAME(ipport_reservedhigh), 0, "");
196 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
197 CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
198 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
199 CTLFLAG_VNET | CTLFLAG_RW,
200 &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
201 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
202 CTLFLAG_VNET | CTLFLAG_RW,
203 &VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
204 "allocations before switching to a sequental one");
205 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
206 CTLFLAG_VNET | CTLFLAG_RW,
207 &VNET_NAME(ipport_randomtime), 0,
208 "Minimum time to keep sequental port "
209 "allocation before switching to a random one");
213 * in_pcb.c: manage the Protocol Control Blocks.
215 * NOTE: It is assumed that most of these functions will be called with
216 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
217 * functions often modify hash chains or addresses in pcbs.
221 * Different protocols initialize their inpcbs differently - giving
222 * different name to the lock. But they all are disposed the same.
225 inpcb_fini(void *mem, int size)
227 struct inpcb *inp = mem;
229 INP_LOCK_DESTROY(inp);
233 * Initialize an inpcbinfo -- we should be able to reduce the number of
237 in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
238 struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
239 char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
242 INP_INFO_LOCK_INIT(pcbinfo, name);
243 INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash"); /* XXXRW: argument? */
244 INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
246 pcbinfo->ipi_vnet = curvnet;
248 pcbinfo->ipi_listhead = listhead;
249 LIST_INIT(pcbinfo->ipi_listhead);
250 pcbinfo->ipi_count = 0;
251 pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
252 &pcbinfo->ipi_hashmask);
253 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
254 &pcbinfo->ipi_porthashmask);
256 in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
258 pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
259 NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
260 uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
261 uma_zone_set_warning(pcbinfo->ipi_zone,
262 "kern.ipc.maxsockets limit reached");
266 * Destroy an inpcbinfo.
269 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
272 KASSERT(pcbinfo->ipi_count == 0,
273 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
275 hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
276 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
277 pcbinfo->ipi_porthashmask);
279 in_pcbgroup_destroy(pcbinfo);
281 uma_zdestroy(pcbinfo->ipi_zone);
282 INP_LIST_LOCK_DESTROY(pcbinfo);
283 INP_HASH_LOCK_DESTROY(pcbinfo);
284 INP_INFO_LOCK_DESTROY(pcbinfo);
288 * Allocate a PCB and associate it with the socket.
289 * On success return with the PCB locked.
292 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
298 if (pcbinfo == &V_tcbinfo) {
299 INP_INFO_RLOCK_ASSERT(pcbinfo);
301 INP_INFO_WLOCK_ASSERT(pcbinfo);
306 inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
309 bzero(&inp->inp_start_zero, inp_zero_size);
310 inp->inp_pcbinfo = pcbinfo;
311 inp->inp_socket = so;
312 inp->inp_cred = crhold(so->so_cred);
313 inp->inp_inc.inc_fibnum = so->so_fibnum;
315 error = mac_inpcb_init(inp, M_NOWAIT);
318 mac_inpcb_create(so, inp);
320 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
321 error = ipsec_init_pcbpolicy(inp);
324 mac_inpcb_destroy(inp);
330 if (INP_SOCKAF(so) == AF_INET6) {
331 inp->inp_vflag |= INP_IPV6PROTO;
333 inp->inp_flags |= IN6P_IPV6_V6ONLY;
337 INP_LIST_WLOCK(pcbinfo);
338 LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
339 pcbinfo->ipi_count++;
340 so->so_pcb = (caddr_t)inp;
342 if (V_ip6_auto_flowlabel)
343 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
345 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
346 refcount_init(&inp->inp_refcount, 1); /* Reference from inpcbinfo */
349 * Routes in inpcb's can cache L2 as well; they are guaranteed
352 inp->inp_route.ro_flags = RT_LLE_CACHE;
353 INP_LIST_WUNLOCK(pcbinfo);
354 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
357 crfree(inp->inp_cred);
358 uma_zfree(pcbinfo->ipi_zone, inp);
366 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
370 INP_WLOCK_ASSERT(inp);
371 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
373 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
375 anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
376 error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
377 &inp->inp_lport, cred);
380 if (in_pcbinshash(inp) != 0) {
381 inp->inp_laddr.s_addr = INADDR_ANY;
386 inp->inp_flags |= INP_ANONPORT;
392 * Select a local port (number) to use.
394 #if defined(INET) || defined(INET6)
396 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
397 struct ucred *cred, int lookupflags)
399 struct inpcbinfo *pcbinfo;
400 struct inpcb *tmpinp;
401 unsigned short *lastport;
402 int count, dorandom, error;
403 u_short aux, first, last, lport;
405 struct in_addr laddr;
408 pcbinfo = inp->inp_pcbinfo;
411 * Because no actual state changes occur here, a global write lock on
412 * the pcbinfo isn't required.
414 INP_LOCK_ASSERT(inp);
415 INP_HASH_LOCK_ASSERT(pcbinfo);
417 if (inp->inp_flags & INP_HIGHPORT) {
418 first = V_ipport_hifirstauto; /* sysctl */
419 last = V_ipport_hilastauto;
420 lastport = &pcbinfo->ipi_lasthi;
421 } else if (inp->inp_flags & INP_LOWPORT) {
422 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
425 first = V_ipport_lowfirstauto; /* 1023 */
426 last = V_ipport_lowlastauto; /* 600 */
427 lastport = &pcbinfo->ipi_lastlow;
429 first = V_ipport_firstauto; /* sysctl */
430 last = V_ipport_lastauto;
431 lastport = &pcbinfo->ipi_lastport;
434 * For UDP(-Lite), use random port allocation as long as the user
435 * allows it. For TCP (and as of yet unknown) connections,
436 * use random port allocation only if the user allows it AND
437 * ipport_tick() allows it.
439 if (V_ipport_randomized &&
440 (!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
441 pcbinfo == &V_ulitecbinfo))
446 * It makes no sense to do random port allocation if
447 * we have the only port available.
451 /* Make sure to not include UDP(-Lite) packets in the count. */
452 if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
453 V_ipport_tcpallocs++;
455 * Instead of having two loops further down counting up or down
456 * make sure that first is always <= last and go with only one
457 * code path implementing all logic.
466 /* Make the compiler happy. */
468 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
469 KASSERT(laddrp != NULL, ("%s: laddrp NULL for v4 inp %p",
474 tmpinp = NULL; /* Make compiler happy. */
478 *lastport = first + (arc4random() % (last - first));
480 count = last - first;
483 if (count-- < 0) /* completely used? */
484 return (EADDRNOTAVAIL);
486 if (*lastport < first || *lastport > last)
488 lport = htons(*lastport);
491 if ((inp->inp_vflag & INP_IPV6) != 0)
492 tmpinp = in6_pcblookup_local(pcbinfo,
493 &inp->in6p_laddr, lport, lookupflags, cred);
495 #if defined(INET) && defined(INET6)
499 tmpinp = in_pcblookup_local(pcbinfo, laddr,
500 lport, lookupflags, cred);
502 } while (tmpinp != NULL);
505 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4)
506 laddrp->s_addr = laddr.s_addr;
514 * Return cached socket options.
517 inp_so_options(const struct inpcb *inp)
523 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
524 so_options |= SO_REUSEPORT;
525 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
526 so_options |= SO_REUSEADDR;
529 #endif /* INET || INET6 */
532 * Check if a new BINDMULTI socket is allowed to be created.
534 * ni points to the new inp.
535 * oi points to the exisitng inp.
537 * This checks whether the existing inp also has BINDMULTI and
538 * whether the credentials match.
541 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
543 /* Check permissions match */
544 if ((ni->inp_flags2 & INP_BINDMULTI) &&
545 (ni->inp_cred->cr_uid !=
546 oi->inp_cred->cr_uid))
549 /* Check the existing inp has BINDMULTI set */
550 if ((ni->inp_flags2 & INP_BINDMULTI) &&
551 ((oi->inp_flags2 & INP_BINDMULTI) == 0))
555 * We're okay - either INP_BINDMULTI isn't set on ni, or
556 * it is and it matches the checks.
563 * Set up a bind operation on a PCB, performing port allocation
564 * as required, but do not actually modify the PCB. Callers can
565 * either complete the bind by setting inp_laddr/inp_lport and
566 * calling in_pcbinshash(), or they can just use the resulting
567 * port and address to authorise the sending of a once-off packet.
569 * On error, the values of *laddrp and *lportp are not changed.
572 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
573 u_short *lportp, struct ucred *cred)
575 struct socket *so = inp->inp_socket;
576 struct sockaddr_in *sin;
577 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
578 struct in_addr laddr;
580 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
584 * No state changes, so read locks are sufficient here.
586 INP_LOCK_ASSERT(inp);
587 INP_HASH_LOCK_ASSERT(pcbinfo);
589 if (CK_STAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
590 return (EADDRNOTAVAIL);
591 laddr.s_addr = *laddrp;
592 if (nam != NULL && laddr.s_addr != INADDR_ANY)
594 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
595 lookupflags = INPLOOKUP_WILDCARD;
597 if ((error = prison_local_ip4(cred, &laddr)) != 0)
600 sin = (struct sockaddr_in *)nam;
601 if (nam->sa_len != sizeof (*sin))
605 * We should check the family, but old programs
606 * incorrectly fail to initialize it.
608 if (sin->sin_family != AF_INET)
609 return (EAFNOSUPPORT);
611 error = prison_local_ip4(cred, &sin->sin_addr);
614 if (sin->sin_port != *lportp) {
615 /* Don't allow the port to change. */
618 lport = sin->sin_port;
620 /* NB: lport is left as 0 if the port isn't being changed. */
621 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
623 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
624 * allow complete duplication of binding if
625 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
626 * and a multicast address is bound on both
627 * new and duplicated sockets.
629 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
630 reuseport = SO_REUSEADDR|SO_REUSEPORT;
631 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
632 sin->sin_port = 0; /* yech... */
633 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
635 * Is the address a local IP address?
636 * If INP_BINDANY is set, then the socket may be bound
637 * to any endpoint address, local or not.
639 if ((inp->inp_flags & INP_BINDANY) == 0 &&
640 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
641 return (EADDRNOTAVAIL);
643 laddr = sin->sin_addr;
649 if (ntohs(lport) <= V_ipport_reservedhigh &&
650 ntohs(lport) >= V_ipport_reservedlow &&
651 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
654 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
655 priv_check_cred(inp->inp_cred,
656 PRIV_NETINET_REUSEPORT, 0) != 0) {
657 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
658 lport, INPLOOKUP_WILDCARD, cred);
661 * This entire block sorely needs a rewrite.
664 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
665 ((t->inp_flags & INP_TIMEWAIT) == 0) &&
666 (so->so_type != SOCK_STREAM ||
667 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
668 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
669 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
670 (t->inp_flags2 & INP_REUSEPORT) == 0) &&
671 (inp->inp_cred->cr_uid !=
672 t->inp_cred->cr_uid))
676 * If the socket is a BINDMULTI socket, then
677 * the credentials need to match and the
678 * original socket also has to have been bound
681 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
684 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
685 lport, lookupflags, cred);
686 if (t && (t->inp_flags & INP_TIMEWAIT)) {
688 * XXXRW: If an incpb has had its timewait
689 * state recycled, we treat the address as
690 * being in use (for now). This is better
691 * than a panic, but not desirable.
695 (reuseport & tw->tw_so_options) == 0)
698 ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
699 (reuseport & inp_so_options(t)) == 0) {
701 if (ntohl(sin->sin_addr.s_addr) !=
703 ntohl(t->inp_laddr.s_addr) !=
705 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
706 (t->inp_vflag & INP_IPV6PROTO) == 0)
709 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
717 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
722 *laddrp = laddr.s_addr;
728 * Connect from a socket to a specified address.
729 * Both address and port must be specified in argument sin.
730 * If don't have a local address for this socket yet,
734 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
735 struct ucred *cred, struct mbuf *m)
737 u_short lport, fport;
738 in_addr_t laddr, faddr;
741 INP_WLOCK_ASSERT(inp);
742 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
744 lport = inp->inp_lport;
745 laddr = inp->inp_laddr.s_addr;
746 anonport = (lport == 0);
747 error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
752 /* Do the initial binding of the local address if required. */
753 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
754 inp->inp_lport = lport;
755 inp->inp_laddr.s_addr = laddr;
756 if (in_pcbinshash(inp) != 0) {
757 inp->inp_laddr.s_addr = INADDR_ANY;
763 /* Commit the remaining changes. */
764 inp->inp_lport = lport;
765 inp->inp_laddr.s_addr = laddr;
766 inp->inp_faddr.s_addr = faddr;
767 inp->inp_fport = fport;
768 in_pcbrehash_mbuf(inp, m);
771 inp->inp_flags |= INP_ANONPORT;
776 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
779 return (in_pcbconnect_mbuf(inp, nam, cred, NULL));
783 * Do proper source address selection on an unbound socket in case
784 * of connect. Take jails into account as well.
787 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
792 struct sockaddr_in *sin;
796 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
798 * Bypass source address selection and use the primary jail IP
801 if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
805 bzero(&sro, sizeof(sro));
807 sin = (struct sockaddr_in *)&sro.ro_dst;
808 sin->sin_family = AF_INET;
809 sin->sin_len = sizeof(struct sockaddr_in);
810 sin->sin_addr.s_addr = faddr->s_addr;
813 * If route is known our src addr is taken from the i/f,
816 * Find out route to destination.
818 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
819 in_rtalloc_ign(&sro, 0, inp->inp_inc.inc_fibnum);
822 * If we found a route, use the address corresponding to
823 * the outgoing interface.
825 * Otherwise assume faddr is reachable on a directly connected
826 * network and try to find a corresponding interface to take
827 * the source address from.
830 if (sro.ro_rt == NULL || sro.ro_rt->rt_ifp == NULL) {
831 struct in_ifaddr *ia;
834 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
835 inp->inp_socket->so_fibnum));
837 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
838 inp->inp_socket->so_fibnum));
846 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
847 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
854 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
857 if (sa->sa_family != AF_INET)
859 sin = (struct sockaddr_in *)sa;
860 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
861 ia = (struct in_ifaddr *)ifa;
866 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
867 IF_ADDR_RUNLOCK(ifp);
870 IF_ADDR_RUNLOCK(ifp);
872 /* 3. As a last resort return the 'default' jail address. */
873 error = prison_get_ip4(cred, laddr);
878 * If the outgoing interface on the route found is not
879 * a loopback interface, use the address from that interface.
880 * In case of jails do those three steps:
881 * 1. check if the interface address belongs to the jail. If so use it.
882 * 2. check if we have any address on the outgoing interface
883 * belonging to this jail. If so use it.
884 * 3. as a last resort return the 'default' jail address.
886 if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
887 struct in_ifaddr *ia;
890 /* If not jailed, use the default returned. */
891 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
892 ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
893 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
898 /* 1. Check if the iface address belongs to the jail. */
899 sin = (struct sockaddr_in *)sro.ro_rt->rt_ifa->ifa_addr;
900 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
901 ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
902 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
907 * 2. Check if we have any address on the outgoing interface
908 * belonging to this jail.
911 ifp = sro.ro_rt->rt_ifp;
913 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
915 if (sa->sa_family != AF_INET)
917 sin = (struct sockaddr_in *)sa;
918 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
919 ia = (struct in_ifaddr *)ifa;
924 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
925 IF_ADDR_RUNLOCK(ifp);
928 IF_ADDR_RUNLOCK(ifp);
930 /* 3. As a last resort return the 'default' jail address. */
931 error = prison_get_ip4(cred, laddr);
936 * The outgoing interface is marked with 'loopback net', so a route
937 * to ourselves is here.
938 * Try to find the interface of the destination address and then
939 * take the address from there. That interface is not necessarily
940 * a loopback interface.
941 * In case of jails, check that it is an address of the jail
942 * and if we cannot find, fall back to the 'default' jail address.
944 if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
945 struct sockaddr_in sain;
946 struct in_ifaddr *ia;
948 bzero(&sain, sizeof(struct sockaddr_in));
949 sain.sin_family = AF_INET;
950 sain.sin_len = sizeof(struct sockaddr_in);
951 sain.sin_addr.s_addr = faddr->s_addr;
953 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sain),
954 inp->inp_socket->so_fibnum));
956 ia = ifatoia(ifa_ifwithnet(sintosa(&sain), 0,
957 inp->inp_socket->so_fibnum));
959 ia = ifatoia(ifa_ifwithaddr(sintosa(&sain)));
961 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
966 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
977 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
980 if (sa->sa_family != AF_INET)
982 sin = (struct sockaddr_in *)sa;
983 if (prison_check_ip4(cred,
984 &sin->sin_addr) == 0) {
985 ia = (struct in_ifaddr *)ifa;
990 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
991 IF_ADDR_RUNLOCK(ifp);
994 IF_ADDR_RUNLOCK(ifp);
997 /* 3. As a last resort return the 'default' jail address. */
998 error = prison_get_ip4(cred, laddr);
1004 if (sro.ro_rt != NULL)
1010 * Set up for a connect from a socket to the specified address.
1011 * On entry, *laddrp and *lportp should contain the current local
1012 * address and port for the PCB; these are updated to the values
1013 * that should be placed in inp_laddr and inp_lport to complete
1016 * On success, *faddrp and *fportp will be set to the remote address
1017 * and port. These are not updated in the error case.
1019 * If the operation fails because the connection already exists,
1020 * *oinpp will be set to the PCB of that connection so that the
1021 * caller can decide to override it. In all other cases, *oinpp
1025 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1026 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1027 struct inpcb **oinpp, struct ucred *cred)
1029 struct rm_priotracker in_ifa_tracker;
1030 struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1031 struct in_ifaddr *ia;
1033 struct in_addr laddr, faddr;
1034 u_short lport, fport;
1038 * Because a global state change doesn't actually occur here, a read
1039 * lock is sufficient.
1041 INP_LOCK_ASSERT(inp);
1042 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1046 if (nam->sa_len != sizeof (*sin))
1048 if (sin->sin_family != AF_INET)
1049 return (EAFNOSUPPORT);
1050 if (sin->sin_port == 0)
1051 return (EADDRNOTAVAIL);
1052 laddr.s_addr = *laddrp;
1054 faddr = sin->sin_addr;
1055 fport = sin->sin_port;
1057 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1059 * If the destination address is INADDR_ANY,
1060 * use the primary local address.
1061 * If the supplied address is INADDR_BROADCAST,
1062 * and the primary interface supports broadcast,
1063 * choose the broadcast address for that interface.
1065 if (faddr.s_addr == INADDR_ANY) {
1066 IN_IFADDR_RLOCK(&in_ifa_tracker);
1068 IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1069 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1071 (error = prison_get_ip4(cred, &faddr)) != 0)
1073 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1074 IN_IFADDR_RLOCK(&in_ifa_tracker);
1075 if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1077 faddr = satosin(&CK_STAILQ_FIRST(
1078 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1079 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1082 if (laddr.s_addr == INADDR_ANY) {
1083 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1085 * If the destination address is multicast and an outgoing
1086 * interface has been set as a multicast option, prefer the
1087 * address of that interface as our source address.
1089 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1090 inp->inp_moptions != NULL) {
1091 struct ip_moptions *imo;
1094 imo = inp->inp_moptions;
1095 if (imo->imo_multicast_ifp != NULL) {
1096 ifp = imo->imo_multicast_ifp;
1097 IN_IFADDR_RLOCK(&in_ifa_tracker);
1098 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1099 if ((ia->ia_ifp == ifp) &&
1101 prison_check_ip4(cred,
1102 &ia->ia_addr.sin_addr) == 0))
1106 error = EADDRNOTAVAIL;
1108 laddr = ia->ia_addr.sin_addr;
1111 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1117 oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr, fport,
1118 laddr, lport, 0, NULL);
1122 return (EADDRINUSE);
1125 error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1130 *laddrp = laddr.s_addr;
1132 *faddrp = faddr.s_addr;
1138 in_pcbdisconnect(struct inpcb *inp)
1141 INP_WLOCK_ASSERT(inp);
1142 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1144 inp->inp_faddr.s_addr = INADDR_ANY;
1151 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1152 * For most protocols, this will be invoked immediately prior to calling
1153 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1154 * socket, in which case in_pcbfree() is deferred.
1157 in_pcbdetach(struct inpcb *inp)
1160 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1163 if (inp->inp_snd_tag != NULL)
1164 in_pcbdetach_txrtlmt(inp);
1166 inp->inp_socket->so_pcb = NULL;
1167 inp->inp_socket = NULL;
1171 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1172 * stability of an inpcb pointer despite the inpcb lock being released. This
1173 * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1174 * but where the inpcb lock may already held, or when acquiring a reference
1177 * in_pcbref() should be used only to provide brief memory stability, and
1178 * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1179 * garbage collect the inpcb if it has been in_pcbfree()'d from another
1180 * context. Until in_pcbrele() has returned that the inpcb is still valid,
1181 * lock and rele are the *only* safe operations that may be performed on the
1184 * While the inpcb will not be freed, releasing the inpcb lock means that the
1185 * connection's state may change, so the caller should be careful to
1186 * revalidate any cached state on reacquiring the lock. Drop the reference
1187 * using in_pcbrele().
1190 in_pcbref(struct inpcb *inp)
1193 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1195 refcount_acquire(&inp->inp_refcount);
1199 * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1200 * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1201 * return a flag indicating whether or not the inpcb remains valid. If it is
1202 * valid, we return with the inpcb lock held.
1204 * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1205 * reference on an inpcb. Historically more work was done here (actually, in
1206 * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1207 * need for the pcbinfo lock in in_pcbrele(). Deferring the free is entirely
1208 * about memory stability (and continued use of the write lock).
1211 in_pcbrele_rlocked(struct inpcb *inp)
1213 struct inpcbinfo *pcbinfo;
1215 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1217 INP_RLOCK_ASSERT(inp);
1219 if (refcount_release(&inp->inp_refcount) == 0) {
1221 * If the inpcb has been freed, let the caller know, even if
1222 * this isn't the last reference.
1224 if (inp->inp_flags2 & INP_FREED) {
1231 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1233 if (inp->inp_in_hpts || inp->inp_in_input) {
1234 struct tcp_hpts_entry *hpts;
1236 * We should not be on the hpts at
1237 * this point in any form. we must
1238 * get the lock to be sure.
1240 hpts = tcp_hpts_lock(inp);
1241 if (inp->inp_in_hpts)
1242 panic("Hpts:%p inp:%p at free still on hpts",
1244 mtx_unlock(&hpts->p_mtx);
1245 hpts = tcp_input_lock(inp);
1246 if (inp->inp_in_input)
1247 panic("Hpts:%p inp:%p at free still on input hpts",
1249 mtx_unlock(&hpts->p_mtx);
1253 pcbinfo = inp->inp_pcbinfo;
1254 uma_zfree(pcbinfo->ipi_zone, inp);
1259 in_pcbrele_wlocked(struct inpcb *inp)
1261 struct inpcbinfo *pcbinfo;
1263 KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1265 INP_WLOCK_ASSERT(inp);
1267 if (refcount_release(&inp->inp_refcount) == 0) {
1269 * If the inpcb has been freed, let the caller know, even if
1270 * this isn't the last reference.
1272 if (inp->inp_flags2 & INP_FREED) {
1279 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1281 if (inp->inp_in_hpts || inp->inp_in_input) {
1282 struct tcp_hpts_entry *hpts;
1284 * We should not be on the hpts at
1285 * this point in any form. we must
1286 * get the lock to be sure.
1288 hpts = tcp_hpts_lock(inp);
1289 if (inp->inp_in_hpts)
1290 panic("Hpts:%p inp:%p at free still on hpts",
1292 mtx_unlock(&hpts->p_mtx);
1293 hpts = tcp_input_lock(inp);
1294 if (inp->inp_in_input)
1295 panic("Hpts:%p inp:%p at free still on input hpts",
1297 mtx_unlock(&hpts->p_mtx);
1301 pcbinfo = inp->inp_pcbinfo;
1302 uma_zfree(pcbinfo->ipi_zone, inp);
1307 * Temporary wrapper.
1310 in_pcbrele(struct inpcb *inp)
1313 return (in_pcbrele_wlocked(inp));
1317 in_pcblist_rele_rlocked(epoch_context_t ctx)
1319 struct in_pcblist *il;
1321 struct inpcbinfo *pcbinfo;
1324 il = __containerof(ctx, struct in_pcblist, il_epoch_ctx);
1325 pcbinfo = il->il_pcbinfo;
1327 INP_INFO_WLOCK(pcbinfo);
1328 for (i = 0; i < n; i++) {
1329 inp = il->il_inp_list[i];
1331 if (!in_pcbrele_rlocked(inp))
1334 INP_INFO_WUNLOCK(pcbinfo);
1339 * Unconditionally schedule an inpcb to be freed by decrementing its
1340 * reference count, which should occur only after the inpcb has been detached
1341 * from its socket. If another thread holds a temporary reference (acquired
1342 * using in_pcbref()) then the free is deferred until that reference is
1343 * released using in_pcbrele(), but the inpcb is still unlocked. Almost all
1344 * work, including removal from global lists, is done in this context, where
1345 * the pcbinfo lock is held.
1348 in_pcbfree(struct inpcb *inp)
1350 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1353 struct ip6_moptions *im6o = NULL;
1356 struct ip_moptions *imo = NULL;
1358 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1360 KASSERT((inp->inp_flags2 & INP_FREED) == 0,
1361 ("%s: called twice for pcb %p", __func__, inp));
1362 if (inp->inp_flags2 & INP_FREED) {
1368 if (pcbinfo == &V_tcbinfo) {
1369 INP_INFO_LOCK_ASSERT(pcbinfo);
1371 INP_INFO_WLOCK_ASSERT(pcbinfo);
1374 INP_WLOCK_ASSERT(inp);
1377 imo = inp->inp_moptions;
1378 inp->inp_moptions = NULL;
1380 /* XXXRW: Do as much as possible here. */
1381 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1382 if (inp->inp_sp != NULL)
1383 ipsec_delete_pcbpolicy(inp);
1385 INP_LIST_WLOCK(pcbinfo);
1386 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1387 in_pcbremlists(inp);
1388 INP_LIST_WUNLOCK(pcbinfo);
1390 if (inp->inp_vflag & INP_IPV6PROTO) {
1391 ip6_freepcbopts(inp->in6p_outputopts);
1392 im6o = inp->in6p_moptions;
1393 inp->in6p_moptions = NULL;
1396 if (inp->inp_options)
1397 (void)m_free(inp->inp_options);
1398 RO_INVALIDATE_CACHE(&inp->inp_route);
1401 inp->inp_flags2 |= INP_FREED;
1402 crfree(inp->inp_cred);
1404 mac_inpcb_destroy(inp);
1407 ip6_freemoptions(im6o);
1410 inp_freemoptions(imo);
1412 if (!in_pcbrele_wlocked(inp))
1417 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1418 * port reservation, and preventing it from being returned by inpcb lookups.
1420 * It is used by TCP to mark an inpcb as unused and avoid future packet
1421 * delivery or event notification when a socket remains open but TCP has
1422 * closed. This might occur as a result of a shutdown()-initiated TCP close
1423 * or a RST on the wire, and allows the port binding to be reused while still
1424 * maintaining the invariant that so_pcb always points to a valid inpcb until
1427 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1428 * in_pcbnotifyall() and in_pcbpurgeif0()?
1431 in_pcbdrop(struct inpcb *inp)
1434 INP_WLOCK_ASSERT(inp);
1437 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1440 inp->inp_flags |= INP_DROPPED;
1441 if (inp->inp_flags & INP_INHASHLIST) {
1442 struct inpcbport *phd = inp->inp_phd;
1444 INP_HASH_WLOCK(inp->inp_pcbinfo);
1445 LIST_REMOVE(inp, inp_hash);
1446 LIST_REMOVE(inp, inp_portlist);
1447 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1448 LIST_REMOVE(phd, phd_hash);
1451 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1452 inp->inp_flags &= ~INP_INHASHLIST;
1454 in_pcbgroup_remove(inp);
1461 * Common routines to return the socket addresses associated with inpcbs.
1464 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1466 struct sockaddr_in *sin;
1468 sin = malloc(sizeof *sin, M_SONAME,
1470 sin->sin_family = AF_INET;
1471 sin->sin_len = sizeof(*sin);
1472 sin->sin_addr = *addr_p;
1473 sin->sin_port = port;
1475 return (struct sockaddr *)sin;
1479 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1482 struct in_addr addr;
1485 inp = sotoinpcb(so);
1486 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1489 port = inp->inp_lport;
1490 addr = inp->inp_laddr;
1493 *nam = in_sockaddr(port, &addr);
1498 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1501 struct in_addr addr;
1504 inp = sotoinpcb(so);
1505 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1508 port = inp->inp_fport;
1509 addr = inp->inp_faddr;
1512 *nam = in_sockaddr(port, &addr);
1517 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1518 struct inpcb *(*notify)(struct inpcb *, int))
1520 struct inpcb *inp, *inp_temp;
1522 INP_INFO_WLOCK(pcbinfo);
1523 LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1526 if ((inp->inp_vflag & INP_IPV4) == 0) {
1531 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1532 inp->inp_socket == NULL) {
1536 if ((*notify)(inp, errno))
1539 INP_INFO_WUNLOCK(pcbinfo);
1543 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1546 struct ip_moptions *imo;
1549 INP_INFO_WLOCK(pcbinfo);
1550 LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1552 imo = inp->inp_moptions;
1553 if ((inp->inp_vflag & INP_IPV4) &&
1556 * Unselect the outgoing interface if it is being
1559 if (imo->imo_multicast_ifp == ifp)
1560 imo->imo_multicast_ifp = NULL;
1563 * Drop multicast group membership if we joined
1564 * through the interface being detached.
1566 * XXX This can all be deferred to an epoch_call
1568 for (i = 0, gap = 0; i < imo->imo_num_memberships;
1570 if (imo->imo_membership[i]->inm_ifp == ifp) {
1571 IN_MULTI_LOCK_ASSERT();
1572 in_leavegroup_locked(imo->imo_membership[i], NULL);
1574 } else if (gap != 0)
1575 imo->imo_membership[i - gap] =
1576 imo->imo_membership[i];
1578 imo->imo_num_memberships -= gap;
1582 INP_INFO_WUNLOCK(pcbinfo);
1586 * Lookup a PCB based on the local address and port. Caller must hold the
1587 * hash lock. No inpcb locks or references are acquired.
1589 #define INP_LOOKUP_MAPPED_PCB_COST 3
1591 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1592 u_short lport, int lookupflags, struct ucred *cred)
1596 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1602 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1603 ("%s: invalid lookup flags %d", __func__, lookupflags));
1605 INP_HASH_LOCK_ASSERT(pcbinfo);
1607 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1608 struct inpcbhead *head;
1610 * Look for an unconnected (wildcard foreign addr) PCB that
1611 * matches the local address and port we're looking for.
1613 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1614 0, pcbinfo->ipi_hashmask)];
1615 LIST_FOREACH(inp, head, inp_hash) {
1617 /* XXX inp locking */
1618 if ((inp->inp_vflag & INP_IPV4) == 0)
1621 if (inp->inp_faddr.s_addr == INADDR_ANY &&
1622 inp->inp_laddr.s_addr == laddr.s_addr &&
1623 inp->inp_lport == lport) {
1628 prison_equal_ip4(cred->cr_prison,
1629 inp->inp_cred->cr_prison))
1638 struct inpcbporthead *porthash;
1639 struct inpcbport *phd;
1640 struct inpcb *match = NULL;
1642 * Best fit PCB lookup.
1644 * First see if this local port is in use by looking on the
1647 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1648 pcbinfo->ipi_porthashmask)];
1649 LIST_FOREACH(phd, porthash, phd_hash) {
1650 if (phd->phd_port == lport)
1655 * Port is in use by one or more PCBs. Look for best
1658 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1661 !prison_equal_ip4(inp->inp_cred->cr_prison,
1665 /* XXX inp locking */
1666 if ((inp->inp_vflag & INP_IPV4) == 0)
1669 * We never select the PCB that has
1670 * INP_IPV6 flag and is bound to :: if
1671 * we have another PCB which is bound
1672 * to 0.0.0.0. If a PCB has the
1673 * INP_IPV6 flag, then we set its cost
1674 * higher than IPv4 only PCBs.
1676 * Note that the case only happens
1677 * when a socket is bound to ::, under
1678 * the condition that the use of the
1679 * mapped address is allowed.
1681 if ((inp->inp_vflag & INP_IPV6) != 0)
1682 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1684 if (inp->inp_faddr.s_addr != INADDR_ANY)
1686 if (inp->inp_laddr.s_addr != INADDR_ANY) {
1687 if (laddr.s_addr == INADDR_ANY)
1689 else if (inp->inp_laddr.s_addr != laddr.s_addr)
1692 if (laddr.s_addr != INADDR_ANY)
1695 if (wildcard < matchwild) {
1697 matchwild = wildcard;
1706 #undef INP_LOOKUP_MAPPED_PCB_COST
1710 * Lookup PCB in hash list, using pcbgroup tables.
1712 static struct inpcb *
1713 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1714 struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1715 u_int lport_arg, int lookupflags, struct ifnet *ifp)
1717 struct inpcbhead *head;
1718 struct inpcb *inp, *tmpinp;
1719 u_short fport = fport_arg, lport = lport_arg;
1723 * First look for an exact match.
1726 INP_GROUP_LOCK(pcbgroup);
1727 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1728 pcbgroup->ipg_hashmask)];
1729 LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1731 /* XXX inp locking */
1732 if ((inp->inp_vflag & INP_IPV4) == 0)
1735 if (inp->inp_faddr.s_addr == faddr.s_addr &&
1736 inp->inp_laddr.s_addr == laddr.s_addr &&
1737 inp->inp_fport == fport &&
1738 inp->inp_lport == lport) {
1740 * XXX We should be able to directly return
1741 * the inp here, without any checks.
1742 * Well unless both bound with SO_REUSEPORT?
1744 if (prison_flag(inp->inp_cred, PR_IP4))
1750 if (tmpinp != NULL) {
1757 * For incoming connections, we may wish to do a wildcard
1758 * match for an RSS-local socket.
1760 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1761 struct inpcb *local_wild = NULL, *local_exact = NULL;
1763 struct inpcb *local_wild_mapped = NULL;
1765 struct inpcb *jail_wild = NULL;
1766 struct inpcbhead *head;
1770 * Order of socket selection - we always prefer jails.
1771 * 1. jailed, non-wild.
1773 * 3. non-jailed, non-wild.
1774 * 4. non-jailed, wild.
1777 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
1778 lport, 0, pcbgroup->ipg_hashmask)];
1779 LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1781 /* XXX inp locking */
1782 if ((inp->inp_vflag & INP_IPV4) == 0)
1785 if (inp->inp_faddr.s_addr != INADDR_ANY ||
1786 inp->inp_lport != lport)
1789 injail = prison_flag(inp->inp_cred, PR_IP4);
1791 if (prison_check_ip4(inp->inp_cred,
1795 if (local_exact != NULL)
1799 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1804 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1806 /* XXX inp locking, NULL check */
1807 if (inp->inp_vflag & INP_IPV6PROTO)
1808 local_wild_mapped = inp;
1816 } /* LIST_FOREACH */
1825 inp = local_wild_mapped;
1833 * Then look for a wildcard match, if requested.
1835 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1836 struct inpcb *local_wild = NULL, *local_exact = NULL;
1838 struct inpcb *local_wild_mapped = NULL;
1840 struct inpcb *jail_wild = NULL;
1841 struct inpcbhead *head;
1845 * Order of socket selection - we always prefer jails.
1846 * 1. jailed, non-wild.
1848 * 3. non-jailed, non-wild.
1849 * 4. non-jailed, wild.
1851 head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
1852 0, pcbinfo->ipi_wildmask)];
1853 LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
1855 /* XXX inp locking */
1856 if ((inp->inp_vflag & INP_IPV4) == 0)
1859 if (inp->inp_faddr.s_addr != INADDR_ANY ||
1860 inp->inp_lport != lport)
1863 injail = prison_flag(inp->inp_cred, PR_IP4);
1865 if (prison_check_ip4(inp->inp_cred,
1869 if (local_exact != NULL)
1873 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1878 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1880 /* XXX inp locking, NULL check */
1881 if (inp->inp_vflag & INP_IPV6PROTO)
1882 local_wild_mapped = inp;
1890 } /* LIST_FOREACH */
1898 inp = local_wild_mapped;
1902 } /* if (lookupflags & INPLOOKUP_WILDCARD) */
1903 INP_GROUP_UNLOCK(pcbgroup);
1907 if (lookupflags & INPLOOKUP_WLOCKPCB)
1908 locked = INP_TRY_WLOCK(inp);
1909 else if (lookupflags & INPLOOKUP_RLOCKPCB)
1910 locked = INP_TRY_RLOCK(inp);
1912 panic("%s: locking bug", __func__);
1915 INP_GROUP_UNLOCK(pcbgroup);
1917 if (lookupflags & INPLOOKUP_WLOCKPCB) {
1919 if (in_pcbrele_wlocked(inp))
1923 if (in_pcbrele_rlocked(inp))
1928 if (lookupflags & INPLOOKUP_WLOCKPCB)
1929 INP_WLOCK_ASSERT(inp);
1931 INP_RLOCK_ASSERT(inp);
1935 #endif /* PCBGROUP */
1938 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
1939 * that the caller has locked the hash list, and will not perform any further
1940 * locking or reference operations on either the hash list or the connection.
1942 static struct inpcb *
1943 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1944 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
1947 struct inpcbhead *head;
1948 struct inpcb *inp, *tmpinp;
1949 u_short fport = fport_arg, lport = lport_arg;
1951 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1952 ("%s: invalid lookup flags %d", __func__, lookupflags));
1954 INP_HASH_LOCK_ASSERT(pcbinfo);
1957 * First look for an exact match.
1960 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1961 pcbinfo->ipi_hashmask)];
1962 LIST_FOREACH(inp, head, inp_hash) {
1964 /* XXX inp locking */
1965 if ((inp->inp_vflag & INP_IPV4) == 0)
1968 if (inp->inp_faddr.s_addr == faddr.s_addr &&
1969 inp->inp_laddr.s_addr == laddr.s_addr &&
1970 inp->inp_fport == fport &&
1971 inp->inp_lport == lport) {
1973 * XXX We should be able to directly return
1974 * the inp here, without any checks.
1975 * Well unless both bound with SO_REUSEPORT?
1977 if (prison_flag(inp->inp_cred, PR_IP4))
1987 * Then look for a wildcard match, if requested.
1989 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1990 struct inpcb *local_wild = NULL, *local_exact = NULL;
1992 struct inpcb *local_wild_mapped = NULL;
1994 struct inpcb *jail_wild = NULL;
1998 * Order of socket selection - we always prefer jails.
1999 * 1. jailed, non-wild.
2001 * 3. non-jailed, non-wild.
2002 * 4. non-jailed, wild.
2005 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2006 0, pcbinfo->ipi_hashmask)];
2007 LIST_FOREACH(inp, head, inp_hash) {
2009 /* XXX inp locking */
2010 if ((inp->inp_vflag & INP_IPV4) == 0)
2013 if (inp->inp_faddr.s_addr != INADDR_ANY ||
2014 inp->inp_lport != lport)
2017 injail = prison_flag(inp->inp_cred, PR_IP4);
2019 if (prison_check_ip4(inp->inp_cred,
2023 if (local_exact != NULL)
2027 if (inp->inp_laddr.s_addr == laddr.s_addr) {
2032 } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2034 /* XXX inp locking, NULL check */
2035 if (inp->inp_vflag & INP_IPV6PROTO)
2036 local_wild_mapped = inp;
2044 } /* LIST_FOREACH */
2045 if (jail_wild != NULL)
2047 if (local_exact != NULL)
2048 return (local_exact);
2049 if (local_wild != NULL)
2050 return (local_wild);
2052 if (local_wild_mapped != NULL)
2053 return (local_wild_mapped);
2055 } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2061 * Lookup PCB in hash list, using pcbinfo tables. This variation locks the
2062 * hash list lock, and will return the inpcb locked (i.e., requires
2063 * INPLOOKUP_LOCKPCB).
2065 static struct inpcb *
2066 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2067 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2073 INP_HASH_RLOCK(pcbinfo);
2074 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2075 (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
2077 if (lookupflags & INPLOOKUP_WLOCKPCB)
2078 locked = INP_TRY_WLOCK(inp);
2079 else if (lookupflags & INPLOOKUP_RLOCKPCB)
2080 locked = INP_TRY_RLOCK(inp);
2082 panic("%s: locking bug", __func__);
2085 INP_HASH_RUNLOCK(pcbinfo);
2087 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2089 if (in_pcbrele_wlocked(inp))
2093 if (in_pcbrele_rlocked(inp))
2098 if (lookupflags & INPLOOKUP_WLOCKPCB)
2099 INP_WLOCK_ASSERT(inp);
2101 INP_RLOCK_ASSERT(inp);
2104 INP_HASH_RUNLOCK(pcbinfo);
2109 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2110 * from which a pre-calculated hash value may be extracted.
2112 * Possibly more of this logic should be in in_pcbgroup.c.
2115 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2116 struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2118 #if defined(PCBGROUP) && !defined(RSS)
2119 struct inpcbgroup *pcbgroup;
2122 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2123 ("%s: invalid lookup flags %d", __func__, lookupflags));
2124 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2125 ("%s: LOCKPCB not set", __func__));
2128 * When not using RSS, use connection groups in preference to the
2129 * reservation table when looking up 4-tuples. When using RSS, just
2130 * use the reservation table, due to the cost of the Toeplitz hash
2133 * XXXRW: This policy belongs in the pcbgroup code, as in principle
2134 * we could be doing RSS with a non-Toeplitz hash that is affordable
2137 #if defined(PCBGROUP) && !defined(RSS)
2138 if (in_pcbgroup_enabled(pcbinfo)) {
2139 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2141 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2142 laddr, lport, lookupflags, ifp));
2145 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2150 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2151 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2152 struct ifnet *ifp, struct mbuf *m)
2155 struct inpcbgroup *pcbgroup;
2158 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2159 ("%s: invalid lookup flags %d", __func__, lookupflags));
2160 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2161 ("%s: LOCKPCB not set", __func__));
2165 * If we can use a hardware-generated hash to look up the connection
2166 * group, use that connection group to find the inpcb. Otherwise
2167 * fall back on a software hash -- or the reservation table if we're
2170 * XXXRW: As above, that policy belongs in the pcbgroup code.
2172 if (in_pcbgroup_enabled(pcbinfo) &&
2173 !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2174 pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2175 m->m_pkthdr.flowid);
2176 if (pcbgroup != NULL)
2177 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2178 fport, laddr, lport, lookupflags, ifp));
2180 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2182 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2183 laddr, lport, lookupflags, ifp));
2187 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2193 * Insert PCB onto various hash lists.
2196 in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
2198 struct inpcbhead *pcbhash;
2199 struct inpcbporthead *pcbporthash;
2200 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2201 struct inpcbport *phd;
2202 u_int32_t hashkey_faddr;
2204 INP_WLOCK_ASSERT(inp);
2205 INP_HASH_WLOCK_ASSERT(pcbinfo);
2207 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2208 ("in_pcbinshash: INP_INHASHLIST"));
2211 if (inp->inp_vflag & INP_IPV6)
2212 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2215 hashkey_faddr = inp->inp_faddr.s_addr;
2217 pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2218 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2220 pcbporthash = &pcbinfo->ipi_porthashbase[
2221 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2224 * Go through port list and look for a head for this lport.
2226 LIST_FOREACH(phd, pcbporthash, phd_hash) {
2227 if (phd->phd_port == inp->inp_lport)
2231 * If none exists, malloc one and tack it on.
2234 phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2236 return (ENOBUFS); /* XXX */
2238 phd->phd_port = inp->inp_lport;
2239 LIST_INIT(&phd->phd_pcblist);
2240 LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2243 LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2244 LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2245 inp->inp_flags |= INP_INHASHLIST;
2247 if (do_pcbgroup_update)
2248 in_pcbgroup_update(inp);
2254 * For now, there are two public interfaces to insert an inpcb into the hash
2255 * lists -- one that does update pcbgroups, and one that doesn't. The latter
2256 * is used only in the TCP syncache, where in_pcbinshash is called before the
2257 * full 4-tuple is set for the inpcb, and we don't want to install in the
2258 * pcbgroup until later.
2260 * XXXRW: This seems like a misfeature. in_pcbinshash should always update
2261 * connection groups, and partially initialised inpcbs should not be exposed
2262 * to either reservation hash tables or pcbgroups.
2265 in_pcbinshash(struct inpcb *inp)
2268 return (in_pcbinshash_internal(inp, 1));
2272 in_pcbinshash_nopcbgroup(struct inpcb *inp)
2275 return (in_pcbinshash_internal(inp, 0));
2279 * Move PCB to the proper hash bucket when { faddr, fport } have been
2280 * changed. NOTE: This does not handle the case of the lport changing (the
2281 * hashed port list would have to be updated as well), so the lport must
2282 * not change after in_pcbinshash() has been called.
2285 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2287 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2288 struct inpcbhead *head;
2289 u_int32_t hashkey_faddr;
2291 INP_WLOCK_ASSERT(inp);
2292 INP_HASH_WLOCK_ASSERT(pcbinfo);
2294 KASSERT(inp->inp_flags & INP_INHASHLIST,
2295 ("in_pcbrehash: !INP_INHASHLIST"));
2298 if (inp->inp_vflag & INP_IPV6)
2299 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2302 hashkey_faddr = inp->inp_faddr.s_addr;
2304 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2305 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2307 LIST_REMOVE(inp, inp_hash);
2308 LIST_INSERT_HEAD(head, inp, inp_hash);
2312 in_pcbgroup_update_mbuf(inp, m);
2314 in_pcbgroup_update(inp);
2319 in_pcbrehash(struct inpcb *inp)
2322 in_pcbrehash_mbuf(inp, NULL);
2326 * Remove PCB from various lists.
2329 in_pcbremlists(struct inpcb *inp)
2331 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2334 if (pcbinfo == &V_tcbinfo) {
2335 INP_INFO_RLOCK_ASSERT(pcbinfo);
2337 INP_INFO_WLOCK_ASSERT(pcbinfo);
2341 INP_WLOCK_ASSERT(inp);
2342 INP_LIST_WLOCK_ASSERT(pcbinfo);
2344 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2345 if (inp->inp_flags & INP_INHASHLIST) {
2346 struct inpcbport *phd = inp->inp_phd;
2348 INP_HASH_WLOCK(pcbinfo);
2349 LIST_REMOVE(inp, inp_hash);
2350 LIST_REMOVE(inp, inp_portlist);
2351 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
2352 LIST_REMOVE(phd, phd_hash);
2355 INP_HASH_WUNLOCK(pcbinfo);
2356 inp->inp_flags &= ~INP_INHASHLIST;
2358 LIST_REMOVE(inp, inp_list);
2359 pcbinfo->ipi_count--;
2361 in_pcbgroup_remove(inp);
2366 * Check for alternatives when higher level complains
2367 * about service problems. For now, invalidate cached
2368 * routing information. If the route was created dynamically
2369 * (by a redirect), time to try a default gateway again.
2372 in_losing(struct inpcb *inp)
2375 RO_INVALIDATE_CACHE(&inp->inp_route);
2380 * A set label operation has occurred at the socket layer, propagate the
2381 * label change into the in_pcb for the socket.
2384 in_pcbsosetlabel(struct socket *so)
2389 inp = sotoinpcb(so);
2390 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2394 mac_inpcb_sosetlabel(so, inp);
2401 * ipport_tick runs once per second, determining if random port allocation
2402 * should be continued. If more than ipport_randomcps ports have been
2403 * allocated in the last second, then we return to sequential port
2404 * allocation. We return to random allocation only once we drop below
2405 * ipport_randomcps for at least ipport_randomtime seconds.
2408 ipport_tick(void *xtp)
2410 VNET_ITERATOR_DECL(vnet_iter);
2412 VNET_LIST_RLOCK_NOSLEEP();
2413 VNET_FOREACH(vnet_iter) {
2414 CURVNET_SET(vnet_iter); /* XXX appease INVARIANTS here */
2415 if (V_ipport_tcpallocs <=
2416 V_ipport_tcplastcount + V_ipport_randomcps) {
2417 if (V_ipport_stoprandom > 0)
2418 V_ipport_stoprandom--;
2420 V_ipport_stoprandom = V_ipport_randomtime;
2421 V_ipport_tcplastcount = V_ipport_tcpallocs;
2424 VNET_LIST_RUNLOCK_NOSLEEP();
2425 callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2432 callout_stop(&ipport_tick_callout);
2436 * The ipport_callout should start running at about the time we attach the
2437 * inet or inet6 domains.
2440 ipport_tick_init(const void *unused __unused)
2443 /* Start ipport_tick. */
2444 callout_init(&ipport_tick_callout, 1);
2445 callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2446 EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2447 SHUTDOWN_PRI_DEFAULT);
2449 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2450 ipport_tick_init, NULL);
2453 inp_wlock(struct inpcb *inp)
2460 inp_wunlock(struct inpcb *inp)
2467 inp_rlock(struct inpcb *inp)
2474 inp_runlock(struct inpcb *inp)
2480 #ifdef INVARIANT_SUPPORT
2482 inp_lock_assert(struct inpcb *inp)
2485 INP_WLOCK_ASSERT(inp);
2489 inp_unlock_assert(struct inpcb *inp)
2492 INP_UNLOCK_ASSERT(inp);
2497 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2501 INP_INFO_WLOCK(&V_tcbinfo);
2502 LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2507 INP_INFO_WUNLOCK(&V_tcbinfo);
2511 inp_inpcbtosocket(struct inpcb *inp)
2514 INP_WLOCK_ASSERT(inp);
2515 return (inp->inp_socket);
2519 inp_inpcbtotcpcb(struct inpcb *inp)
2522 INP_WLOCK_ASSERT(inp);
2523 return ((struct tcpcb *)inp->inp_ppcb);
2527 inp_ip_tos_get(const struct inpcb *inp)
2530 return (inp->inp_ip_tos);
2534 inp_ip_tos_set(struct inpcb *inp, int val)
2537 inp->inp_ip_tos = val;
2541 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2542 uint32_t *faddr, uint16_t *fp)
2545 INP_LOCK_ASSERT(inp);
2546 *laddr = inp->inp_laddr.s_addr;
2547 *faddr = inp->inp_faddr.s_addr;
2548 *lp = inp->inp_lport;
2549 *fp = inp->inp_fport;
2553 so_sotoinpcb(struct socket *so)
2556 return (sotoinpcb(so));
2560 so_sototcpcb(struct socket *so)
2563 return (sototcpcb(so));
2567 * Create an external-format (``xinpcb'') structure using the information in
2568 * the kernel-format in_pcb structure pointed to by inp. This is done to
2569 * reduce the spew of irrelevant information over this interface, to isolate
2570 * user code from changes in the kernel structure, and potentially to provide
2571 * information-hiding if we decide that some of this information should be
2572 * hidden from users.
2575 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2578 xi->xi_len = sizeof(struct xinpcb);
2579 if (inp->inp_socket)
2580 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2582 bzero(&xi->xi_socket, sizeof(struct xsocket));
2583 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2584 xi->inp_gencnt = inp->inp_gencnt;
2585 xi->inp_ppcb = inp->inp_ppcb;
2586 xi->inp_flow = inp->inp_flow;
2587 xi->inp_flowid = inp->inp_flowid;
2588 xi->inp_flowtype = inp->inp_flowtype;
2589 xi->inp_flags = inp->inp_flags;
2590 xi->inp_flags2 = inp->inp_flags2;
2591 xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2592 xi->in6p_cksum = inp->in6p_cksum;
2593 xi->in6p_hops = inp->in6p_hops;
2594 xi->inp_ip_tos = inp->inp_ip_tos;
2595 xi->inp_vflag = inp->inp_vflag;
2596 xi->inp_ip_ttl = inp->inp_ip_ttl;
2597 xi->inp_ip_p = inp->inp_ip_p;
2598 xi->inp_ip_minttl = inp->inp_ip_minttl;
2603 db_print_indent(int indent)
2607 for (i = 0; i < indent; i++)
2612 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2614 char faddr_str[48], laddr_str[48];
2616 db_print_indent(indent);
2617 db_printf("%s at %p\n", name, inc);
2622 if (inc->inc_flags & INC_ISIPV6) {
2624 ip6_sprintf(laddr_str, &inc->inc6_laddr);
2625 ip6_sprintf(faddr_str, &inc->inc6_faddr);
2630 inet_ntoa_r(inc->inc_laddr, laddr_str);
2631 inet_ntoa_r(inc->inc_faddr, faddr_str);
2633 db_print_indent(indent);
2634 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
2635 ntohs(inc->inc_lport));
2636 db_print_indent(indent);
2637 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
2638 ntohs(inc->inc_fport));
2642 db_print_inpflags(int inp_flags)
2647 if (inp_flags & INP_RECVOPTS) {
2648 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2651 if (inp_flags & INP_RECVRETOPTS) {
2652 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2655 if (inp_flags & INP_RECVDSTADDR) {
2656 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2659 if (inp_flags & INP_ORIGDSTADDR) {
2660 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2663 if (inp_flags & INP_HDRINCL) {
2664 db_printf("%sINP_HDRINCL", comma ? ", " : "");
2667 if (inp_flags & INP_HIGHPORT) {
2668 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2671 if (inp_flags & INP_LOWPORT) {
2672 db_printf("%sINP_LOWPORT", comma ? ", " : "");
2675 if (inp_flags & INP_ANONPORT) {
2676 db_printf("%sINP_ANONPORT", comma ? ", " : "");
2679 if (inp_flags & INP_RECVIF) {
2680 db_printf("%sINP_RECVIF", comma ? ", " : "");
2683 if (inp_flags & INP_MTUDISC) {
2684 db_printf("%sINP_MTUDISC", comma ? ", " : "");
2687 if (inp_flags & INP_RECVTTL) {
2688 db_printf("%sINP_RECVTTL", comma ? ", " : "");
2691 if (inp_flags & INP_DONTFRAG) {
2692 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2695 if (inp_flags & INP_RECVTOS) {
2696 db_printf("%sINP_RECVTOS", comma ? ", " : "");
2699 if (inp_flags & IN6P_IPV6_V6ONLY) {
2700 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2703 if (inp_flags & IN6P_PKTINFO) {
2704 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2707 if (inp_flags & IN6P_HOPLIMIT) {
2708 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2711 if (inp_flags & IN6P_HOPOPTS) {
2712 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2715 if (inp_flags & IN6P_DSTOPTS) {
2716 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2719 if (inp_flags & IN6P_RTHDR) {
2720 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2723 if (inp_flags & IN6P_RTHDRDSTOPTS) {
2724 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2727 if (inp_flags & IN6P_TCLASS) {
2728 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2731 if (inp_flags & IN6P_AUTOFLOWLABEL) {
2732 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2735 if (inp_flags & INP_TIMEWAIT) {
2736 db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
2739 if (inp_flags & INP_ONESBCAST) {
2740 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2743 if (inp_flags & INP_DROPPED) {
2744 db_printf("%sINP_DROPPED", comma ? ", " : "");
2747 if (inp_flags & INP_SOCKREF) {
2748 db_printf("%sINP_SOCKREF", comma ? ", " : "");
2751 if (inp_flags & IN6P_RFC2292) {
2752 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2755 if (inp_flags & IN6P_MTU) {
2756 db_printf("IN6P_MTU%s", comma ? ", " : "");
2762 db_print_inpvflag(u_char inp_vflag)
2767 if (inp_vflag & INP_IPV4) {
2768 db_printf("%sINP_IPV4", comma ? ", " : "");
2771 if (inp_vflag & INP_IPV6) {
2772 db_printf("%sINP_IPV6", comma ? ", " : "");
2775 if (inp_vflag & INP_IPV6PROTO) {
2776 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2782 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2785 db_print_indent(indent);
2786 db_printf("%s at %p\n", name, inp);
2790 db_print_indent(indent);
2791 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2793 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2795 db_print_indent(indent);
2796 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
2797 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2799 db_print_indent(indent);
2800 db_printf("inp_label: %p inp_flags: 0x%x (",
2801 inp->inp_label, inp->inp_flags);
2802 db_print_inpflags(inp->inp_flags);
2805 db_print_indent(indent);
2806 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
2808 db_print_inpvflag(inp->inp_vflag);
2811 db_print_indent(indent);
2812 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
2813 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2815 db_print_indent(indent);
2817 if (inp->inp_vflag & INP_IPV6) {
2818 db_printf("in6p_options: %p in6p_outputopts: %p "
2819 "in6p_moptions: %p\n", inp->in6p_options,
2820 inp->in6p_outputopts, inp->in6p_moptions);
2821 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
2822 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2827 db_printf("inp_ip_tos: %d inp_ip_options: %p "
2828 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2829 inp->inp_options, inp->inp_moptions);
2832 db_print_indent(indent);
2833 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
2834 (uintmax_t)inp->inp_gencnt);
2837 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
2842 db_printf("usage: show inpcb <addr>\n");
2845 inp = (struct inpcb *)addr;
2847 db_print_inpcb(inp, "inpcb", 0);
2853 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
2857 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
2859 union if_snd_tag_modify_params params = {
2860 .rate_limit.max_rate = max_pacing_rate,
2862 struct m_snd_tag *mst;
2866 mst = inp->inp_snd_tag;
2874 if (ifp->if_snd_tag_modify == NULL) {
2877 error = ifp->if_snd_tag_modify(mst, ¶ms);
2883 * Query existing TX rate limit based on the existing
2884 * "inp->inp_snd_tag", if any.
2887 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
2889 union if_snd_tag_query_params params = { };
2890 struct m_snd_tag *mst;
2894 mst = inp->inp_snd_tag;
2902 if (ifp->if_snd_tag_query == NULL) {
2905 error = ifp->if_snd_tag_query(mst, ¶ms);
2906 if (error == 0 && p_max_pacing_rate != NULL)
2907 *p_max_pacing_rate = params.rate_limit.max_rate;
2913 * Query existing TX queue level based on the existing
2914 * "inp->inp_snd_tag", if any.
2917 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
2919 union if_snd_tag_query_params params = { };
2920 struct m_snd_tag *mst;
2924 mst = inp->inp_snd_tag;
2932 if (ifp->if_snd_tag_query == NULL)
2933 return (EOPNOTSUPP);
2935 error = ifp->if_snd_tag_query(mst, ¶ms);
2936 if (error == 0 && p_txqueue_level != NULL)
2937 *p_txqueue_level = params.rate_limit.queue_level;
2942 * Allocate a new TX rate limit send tag from the network interface
2943 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
2946 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
2947 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate)
2949 union if_snd_tag_alloc_params params = {
2950 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
2951 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
2952 .rate_limit.hdr.flowid = flowid,
2953 .rate_limit.hdr.flowtype = flowtype,
2954 .rate_limit.max_rate = max_pacing_rate,
2958 INP_WLOCK_ASSERT(inp);
2960 if (inp->inp_snd_tag != NULL)
2963 if (ifp->if_snd_tag_alloc == NULL) {
2966 error = ifp->if_snd_tag_alloc(ifp, ¶ms, &inp->inp_snd_tag);
2969 * At success increment the refcount on
2970 * the send tag's network interface:
2973 if_ref(inp->inp_snd_tag->ifp);
2979 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
2983 in_pcbdetach_txrtlmt(struct inpcb *inp)
2985 struct m_snd_tag *mst;
2988 INP_WLOCK_ASSERT(inp);
2990 mst = inp->inp_snd_tag;
2991 inp->inp_snd_tag = NULL;
3001 * If the device was detached while we still had reference(s)
3002 * on the ifp, we assume if_snd_tag_free() was replaced with
3005 ifp->if_snd_tag_free(mst);
3007 /* release reference count on network interface */
3012 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3013 * is set in the fast path and will attach/detach/modify the TX rate
3014 * limit send tag based on the socket's so_max_pacing_rate value.
3017 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3019 struct socket *socket;
3020 uint32_t max_pacing_rate;
3027 socket = inp->inp_socket;
3031 if (!INP_WLOCKED(inp)) {
3033 * NOTE: If the write locking fails, we need to bail
3034 * out and use the non-ratelimited ring for the
3035 * transmit until there is a new chance to get the
3038 if (!INP_TRY_UPGRADE(inp))
3046 * NOTE: The so_max_pacing_rate value is read unlocked,
3047 * because atomic updates are not required since the variable
3048 * is checked at every mbuf we send. It is assumed that the
3049 * variable read itself will be atomic.
3051 max_pacing_rate = socket->so_max_pacing_rate;
3054 * NOTE: When attaching to a network interface a reference is
3055 * made to ensure the network interface doesn't go away until
3056 * all ratelimit connections are gone. The network interface
3057 * pointers compared below represent valid network interfaces,
3058 * except when comparing towards NULL.
3060 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3062 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3063 if (inp->inp_snd_tag != NULL)
3064 in_pcbdetach_txrtlmt(inp);
3066 } else if (inp->inp_snd_tag == NULL) {
3068 * In order to utilize packet pacing with RSS, we need
3069 * to wait until there is a valid RSS hash before we
3072 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3075 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3076 mb->m_pkthdr.flowid, max_pacing_rate);
3079 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3081 if (error == 0 || error == EOPNOTSUPP)
3082 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3088 * Track route changes for TX rate limiting.
3091 in_pcboutput_eagain(struct inpcb *inp)
3093 struct socket *socket;
3099 socket = inp->inp_socket;
3103 if (inp->inp_snd_tag == NULL)
3106 if (!INP_WLOCKED(inp)) {
3108 * NOTE: If the write locking fails, we need to bail
3109 * out and use the non-ratelimited ring for the
3110 * transmit until there is a new chance to get the
3113 if (!INP_TRY_UPGRADE(inp))
3120 /* detach rate limiting */
3121 in_pcbdetach_txrtlmt(inp);
3123 /* make sure new mbuf send tag allocation is made */
3124 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3129 #endif /* RATELIMIT */