2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1991, 1993, 1995
5 * The Regents of the University of California.
6 * Copyright (c) 2007-2009 Robert N. M. Watson
7 * Copyright (c) 2010-2011 Juniper Networks, Inc.
8 * Copyright (c) 2021-2022 Gleb Smirnoff <glebius@FreeBSD.org>
11 * Portions of this software were developed by Robert N. M. Watson under
12 * contract to Juniper Networks, Inc.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)in_pcb.c 8.4 (Berkeley) 5/24/95
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
45 #include "opt_ipsec.h"
47 #include "opt_inet6.h"
48 #include "opt_ratelimit.h"
49 #include "opt_route.h"
52 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/libkern.h>
57 #include <sys/malloc.h>
59 #include <sys/eventhandler.h>
60 #include <sys/domain.h>
62 #include <sys/protosw.h>
65 #include <sys/socket.h>
66 #include <sys/socketvar.h>
67 #include <sys/sockio.h>
70 #include <sys/refcount.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
83 #include <net/if_var.h>
84 #include <net/if_private.h>
85 #include <net/if_types.h>
86 #include <net/if_llatbl.h>
87 #include <net/route.h>
88 #include <net/rss_config.h>
91 #if defined(INET) || defined(INET6)
92 #include <netinet/in.h>
93 #include <netinet/in_pcb.h>
94 #include <netinet/in_pcb_var.h>
95 #include <netinet/tcp.h>
97 #include <netinet/in_var.h>
98 #include <netinet/in_fib.h>
100 #include <netinet/ip_var.h>
102 #include <netinet/ip6.h>
103 #include <netinet6/in6_pcb.h>
104 #include <netinet6/in6_var.h>
105 #include <netinet6/ip6_var.h>
107 #include <net/route/nhop.h>
110 #include <netipsec/ipsec_support.h>
112 #include <security/mac/mac_framework.h>
114 #define INPCBLBGROUP_SIZMIN 8
115 #define INPCBLBGROUP_SIZMAX 256
116 #define INP_FREED 0x00000200 /* See in_pcb.h. */
119 * These configure the range of local port addresses assigned to
120 * "unspecified" outgoing connections/packets/whatever.
122 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1; /* 1023 */
123 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART; /* 600 */
124 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST; /* 10000 */
125 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST; /* 65535 */
126 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO; /* 49152 */
127 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO; /* 65535 */
130 * Reserved ports accessible only to root. There are significant
131 * security considerations that must be accounted for when changing these,
132 * but the security benefits can be great. Please be careful.
134 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1; /* 1023 */
135 VNET_DEFINE(int, ipport_reservedlow);
137 /* Enable random ephemeral port allocation by default. */
138 VNET_DEFINE(int, ipport_randomized) = 1;
141 static struct inpcb *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
142 struct in_addr faddr, u_int fport_arg,
143 struct in_addr laddr, u_int lport_arg,
144 int lookupflags, uint8_t numa_domain);
146 #define RANGECHK(var, min, max) \
147 if ((var) < (min)) { (var) = (min); } \
148 else if ((var) > (max)) { (var) = (max); }
151 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
155 error = sysctl_handle_int(oidp, arg1, arg2, req);
157 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
158 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
159 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
160 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
161 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
162 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
169 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
170 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
173 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
174 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
175 &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
177 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
178 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
179 &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 | CTLFLAG_NEEDGIANT,
183 &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
185 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
186 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
187 &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
189 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
190 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
191 &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
193 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
194 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
195 &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
197 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
198 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
199 &VNET_NAME(ipport_reservedhigh), 0, "");
200 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
201 CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
202 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
203 CTLFLAG_VNET | CTLFLAG_RW,
204 &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
207 counter_u64_t rate_limit_new;
208 counter_u64_t rate_limit_chg;
209 counter_u64_t rate_limit_active;
210 counter_u64_t rate_limit_alloc_fail;
211 counter_u64_t rate_limit_set_ok;
213 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
215 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
216 &rate_limit_active, "Active rate limited connections");
217 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
218 &rate_limit_alloc_fail, "Rate limited connection failures");
219 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
220 &rate_limit_set_ok, "Rate limited setting succeeded");
221 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
222 &rate_limit_new, "Total Rate limit new attempts");
223 SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
224 &rate_limit_chg, "Total Rate limited change attempts");
225 #endif /* RATELIMIT */
229 VNET_DEFINE(uint32_t, in_pcbhashseed);
231 in_pcbhashseed_init(void)
234 V_in_pcbhashseed = arc4random();
236 VNET_SYSINIT(in_pcbhashseed_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
237 in_pcbhashseed_init, 0);
239 static void in_pcbremhash(struct inpcb *);
242 * in_pcb.c: manage the Protocol Control Blocks.
244 * NOTE: It is assumed that most of these functions will be called with
245 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
246 * functions often modify hash chains or addresses in pcbs.
249 static struct inpcblbgroup *
250 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, struct ucred *cred,
251 u_char vflag, uint16_t port, const union in_dependaddr *addr, int size,
254 struct inpcblbgroup *grp;
257 bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
258 grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
261 grp->il_cred = crhold(cred);
262 grp->il_vflag = vflag;
263 grp->il_lport = port;
264 grp->il_numa_domain = numa_domain;
265 grp->il_dependladdr = *addr;
266 grp->il_inpsiz = size;
267 CK_LIST_INSERT_HEAD(hdr, grp, il_list);
272 in_pcblbgroup_free_deferred(epoch_context_t ctx)
274 struct inpcblbgroup *grp;
276 grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
277 crfree(grp->il_cred);
282 in_pcblbgroup_free(struct inpcblbgroup *grp)
285 CK_LIST_REMOVE(grp, il_list);
286 NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
289 static struct inpcblbgroup *
290 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
291 struct inpcblbgroup *old_grp, int size)
293 struct inpcblbgroup *grp;
296 grp = in_pcblbgroup_alloc(hdr, old_grp->il_cred, old_grp->il_vflag,
297 old_grp->il_lport, &old_grp->il_dependladdr, size,
298 old_grp->il_numa_domain);
302 KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
303 ("invalid new local group size %d and old local group count %d",
304 grp->il_inpsiz, old_grp->il_inpcnt));
306 for (i = 0; i < old_grp->il_inpcnt; ++i)
307 grp->il_inp[i] = old_grp->il_inp[i];
308 grp->il_inpcnt = old_grp->il_inpcnt;
309 in_pcblbgroup_free(old_grp);
314 * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
315 * and shrink group if possible.
318 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
321 struct inpcblbgroup *grp, *new_grp;
324 for (; i + 1 < grp->il_inpcnt; ++i)
325 grp->il_inp[i] = grp->il_inp[i + 1];
328 if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
329 grp->il_inpcnt <= grp->il_inpsiz / 4) {
330 /* Shrink this group. */
331 new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
338 * Add PCB to load balance group for SO_REUSEPORT_LB option.
341 in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
343 const static struct timeval interval = { 60, 0 };
344 static struct timeval lastprint;
345 struct inpcbinfo *pcbinfo;
346 struct inpcblbgrouphead *hdr;
347 struct inpcblbgroup *grp;
350 pcbinfo = inp->inp_pcbinfo;
352 INP_WLOCK_ASSERT(inp);
353 INP_HASH_WLOCK_ASSERT(pcbinfo);
357 * Don't allow IPv4 mapped INET6 wild socket.
359 if ((inp->inp_vflag & INP_IPV4) &&
360 inp->inp_laddr.s_addr == INADDR_ANY &&
361 INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
366 idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
367 hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
368 CK_LIST_FOREACH(grp, hdr, il_list) {
369 if (grp->il_cred->cr_prison == inp->inp_cred->cr_prison &&
370 grp->il_vflag == inp->inp_vflag &&
371 grp->il_lport == inp->inp_lport &&
372 grp->il_numa_domain == numa_domain &&
373 memcmp(&grp->il_dependladdr,
374 &inp->inp_inc.inc_ie.ie_dependladdr,
375 sizeof(grp->il_dependladdr)) == 0) {
380 /* Create new load balance group. */
381 grp = in_pcblbgroup_alloc(hdr, inp->inp_cred, inp->inp_vflag,
382 inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
383 INPCBLBGROUP_SIZMIN, numa_domain);
386 } else if (grp->il_inpcnt == grp->il_inpsiz) {
387 if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
388 if (ratecheck(&lastprint, &interval))
389 printf("lb group port %d, limit reached\n",
390 ntohs(grp->il_lport));
394 /* Expand this local group. */
395 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
400 KASSERT(grp->il_inpcnt < grp->il_inpsiz,
401 ("invalid local group size %d and count %d", grp->il_inpsiz,
404 grp->il_inp[grp->il_inpcnt] = inp;
410 * Remove PCB from load balance group.
413 in_pcbremlbgrouphash(struct inpcb *inp)
415 struct inpcbinfo *pcbinfo;
416 struct inpcblbgrouphead *hdr;
417 struct inpcblbgroup *grp;
420 pcbinfo = inp->inp_pcbinfo;
422 INP_WLOCK_ASSERT(inp);
423 INP_HASH_WLOCK_ASSERT(pcbinfo);
425 hdr = &pcbinfo->ipi_lbgrouphashbase[
426 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
427 CK_LIST_FOREACH(grp, hdr, il_list) {
428 for (i = 0; i < grp->il_inpcnt; ++i) {
429 if (grp->il_inp[i] != inp)
432 if (grp->il_inpcnt == 1) {
433 /* We are the last, free this local group. */
434 in_pcblbgroup_free(grp);
436 /* Pull up inpcbs, shrink group if possible. */
437 in_pcblbgroup_reorder(hdr, &grp, i);
445 in_pcblbgroup_numa(struct inpcb *inp, int arg)
447 struct inpcbinfo *pcbinfo;
448 struct inpcblbgrouphead *hdr;
449 struct inpcblbgroup *grp;
454 case TCP_REUSPORT_LB_NUMA_NODOM:
455 numa_domain = M_NODOM;
457 case TCP_REUSPORT_LB_NUMA_CURDOM:
458 numa_domain = PCPU_GET(domain);
461 if (arg < 0 || arg >= vm_ndomains)
467 pcbinfo = inp->inp_pcbinfo;
468 INP_WLOCK_ASSERT(inp);
469 INP_HASH_WLOCK(pcbinfo);
470 hdr = &pcbinfo->ipi_lbgrouphashbase[
471 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
472 CK_LIST_FOREACH(grp, hdr, il_list) {
473 for (i = 0; i < grp->il_inpcnt; ++i) {
474 if (grp->il_inp[i] != inp)
477 if (grp->il_numa_domain == numa_domain) {
478 goto abort_with_hash_wlock;
481 /* Remove it from the old group. */
482 in_pcbremlbgrouphash(inp);
484 /* Add it to the new group based on numa domain. */
485 in_pcbinslbgrouphash(inp, numa_domain);
486 goto abort_with_hash_wlock;
490 abort_with_hash_wlock:
491 INP_HASH_WUNLOCK(pcbinfo);
495 /* Make sure it is safe to use hashinit(9) on CK_LIST. */
496 CTASSERT(sizeof(struct inpcbhead) == sizeof(LIST_HEAD(, inpcb)));
499 * Initialize an inpcbinfo - a per-VNET instance of connections db.
502 in_pcbinfo_init(struct inpcbinfo *pcbinfo, struct inpcbstorage *pcbstor,
503 u_int hash_nelements, u_int porthash_nelements)
506 mtx_init(&pcbinfo->ipi_lock, pcbstor->ips_infolock_name, NULL, MTX_DEF);
507 mtx_init(&pcbinfo->ipi_hash_lock, pcbstor->ips_hashlock_name,
510 pcbinfo->ipi_vnet = curvnet;
512 CK_LIST_INIT(&pcbinfo->ipi_listhead);
513 pcbinfo->ipi_count = 0;
514 pcbinfo->ipi_hash_exact = hashinit(hash_nelements, M_PCB,
515 &pcbinfo->ipi_hashmask);
516 pcbinfo->ipi_hash_wild = hashinit(hash_nelements, M_PCB,
517 &pcbinfo->ipi_hashmask);
518 porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
519 pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
520 &pcbinfo->ipi_porthashmask);
521 pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
522 &pcbinfo->ipi_lbgrouphashmask);
523 pcbinfo->ipi_zone = pcbstor->ips_zone;
524 pcbinfo->ipi_portzone = pcbstor->ips_portzone;
525 pcbinfo->ipi_smr = uma_zone_get_smr(pcbinfo->ipi_zone);
529 * Destroy an inpcbinfo.
532 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
535 KASSERT(pcbinfo->ipi_count == 0,
536 ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
538 hashdestroy(pcbinfo->ipi_hash_exact, M_PCB, pcbinfo->ipi_hashmask);
539 hashdestroy(pcbinfo->ipi_hash_wild, M_PCB, pcbinfo->ipi_hashmask);
540 hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
541 pcbinfo->ipi_porthashmask);
542 hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
543 pcbinfo->ipi_lbgrouphashmask);
544 mtx_destroy(&pcbinfo->ipi_hash_lock);
545 mtx_destroy(&pcbinfo->ipi_lock);
549 * Initialize a pcbstorage - per protocol zones to allocate inpcbs.
551 static void inpcb_dtor(void *, int, void *);
552 static void inpcb_fini(void *, int);
554 in_pcbstorage_init(void *arg)
556 struct inpcbstorage *pcbstor = arg;
558 pcbstor->ips_zone = uma_zcreate(pcbstor->ips_zone_name,
559 pcbstor->ips_size, NULL, inpcb_dtor, pcbstor->ips_pcbinit,
560 inpcb_fini, UMA_ALIGN_CACHE, UMA_ZONE_SMR);
561 pcbstor->ips_portzone = uma_zcreate(pcbstor->ips_portzone_name,
562 sizeof(struct inpcbport), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
563 uma_zone_set_smr(pcbstor->ips_portzone,
564 uma_zone_get_smr(pcbstor->ips_zone));
568 * Destroy a pcbstorage - used by unloadable protocols.
571 in_pcbstorage_destroy(void *arg)
573 struct inpcbstorage *pcbstor = arg;
575 uma_zdestroy(pcbstor->ips_zone);
576 uma_zdestroy(pcbstor->ips_portzone);
580 * Allocate a PCB and associate it with the socket.
581 * On success return with the PCB locked.
584 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
587 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
591 inp = uma_zalloc_smr(pcbinfo->ipi_zone, M_NOWAIT);
594 bzero(&inp->inp_start_zero, inp_zero_size);
596 inp->inp_numa_domain = M_NODOM;
598 inp->inp_pcbinfo = pcbinfo;
599 inp->inp_socket = so;
600 inp->inp_cred = crhold(so->so_cred);
601 inp->inp_inc.inc_fibnum = so->so_fibnum;
603 error = mac_inpcb_init(inp, M_NOWAIT);
606 mac_inpcb_create(so, inp);
608 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
609 error = ipsec_init_pcbpolicy(inp);
612 mac_inpcb_destroy(inp);
618 if (INP_SOCKAF(so) == AF_INET6) {
619 inp->inp_vflag |= INP_IPV6PROTO | INP_IPV6;
621 inp->inp_flags |= IN6P_IPV6_V6ONLY;
624 inp->inp_vflag |= INP_IPV4;
626 if (V_ip6_auto_flowlabel)
627 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
628 inp->in6p_hops = -1; /* use kernel default */
631 #if defined(INET) && defined(INET6)
635 inp->inp_vflag |= INP_IPV4;
637 inp->inp_smr = SMR_SEQ_INVALID;
640 * Routes in inpcb's can cache L2 as well; they are guaranteed
643 inp->inp_route.ro_flags = RT_LLE_CACHE;
644 refcount_init(&inp->inp_refcount, 1); /* Reference from socket. */
646 INP_INFO_WLOCK(pcbinfo);
647 pcbinfo->ipi_count++;
648 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
649 CK_LIST_INSERT_HEAD(&pcbinfo->ipi_listhead, inp, inp_list);
650 INP_INFO_WUNLOCK(pcbinfo);
655 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
657 uma_zfree_smr(pcbinfo->ipi_zone, inp);
664 in_pcbbind(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred)
668 KASSERT(sin == NULL || sin->sin_family == AF_INET,
669 ("%s: invalid address family for %p", __func__, sin));
670 KASSERT(sin == NULL || sin->sin_len == sizeof(struct sockaddr_in),
671 ("%s: invalid address length for %p", __func__, sin));
672 INP_WLOCK_ASSERT(inp);
673 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
675 if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
677 anonport = sin == NULL || sin->sin_port == 0;
678 error = in_pcbbind_setup(inp, sin, &inp->inp_laddr.s_addr,
679 &inp->inp_lport, cred);
682 if (in_pcbinshash(inp) != 0) {
683 inp->inp_laddr.s_addr = INADDR_ANY;
688 inp->inp_flags |= INP_ANONPORT;
693 #if defined(INET) || defined(INET6)
695 * Assign a local port like in_pcb_lport(), but also used with connect()
696 * and a foreign address and port. If fsa is non-NULL, choose a local port
697 * that is unused with those, otherwise one that is completely unused.
698 * lsa can be NULL for IPv6.
701 in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
702 struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
704 struct inpcbinfo *pcbinfo;
705 struct inpcb *tmpinp;
706 unsigned short *lastport;
708 u_short aux, first, last, lport;
710 struct in_addr laddr, faddr;
713 struct in6_addr *laddr6, *faddr6;
716 pcbinfo = inp->inp_pcbinfo;
719 * Because no actual state changes occur here, a global write lock on
720 * the pcbinfo isn't required.
722 INP_LOCK_ASSERT(inp);
723 INP_HASH_LOCK_ASSERT(pcbinfo);
725 if (inp->inp_flags & INP_HIGHPORT) {
726 first = V_ipport_hifirstauto; /* sysctl */
727 last = V_ipport_hilastauto;
728 lastport = &pcbinfo->ipi_lasthi;
729 } else if (inp->inp_flags & INP_LOWPORT) {
730 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
733 first = V_ipport_lowfirstauto; /* 1023 */
734 last = V_ipport_lowlastauto; /* 600 */
735 lastport = &pcbinfo->ipi_lastlow;
737 first = V_ipport_firstauto; /* sysctl */
738 last = V_ipport_lastauto;
739 lastport = &pcbinfo->ipi_lastport;
743 * Instead of having two loops further down counting up or down
744 * make sure that first is always <= last and go with only one
745 * code path implementing all logic.
754 laddr.s_addr = INADDR_ANY; /* used by INET6+INET below too */
755 if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
757 laddr = ((struct sockaddr_in *)lsa)->sin_addr;
759 faddr = ((struct sockaddr_in *)fsa)->sin_addr;
764 if ((inp->inp_vflag & INP_IPV6) != 0) {
766 laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
768 faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
775 if (V_ipport_randomized)
776 *lastport = first + (arc4random() % (last - first));
778 count = last - first;
781 if (count-- < 0) /* completely used? */
782 return (EADDRNOTAVAIL);
784 if (*lastport < first || *lastport > last)
786 lport = htons(*lastport);
790 if (lsa->sa_family == AF_INET) {
791 tmpinp = in_pcblookup_hash_locked(pcbinfo,
792 faddr, fport, laddr, lport, lookupflags,
797 if (lsa->sa_family == AF_INET6) {
798 tmpinp = in6_pcblookup_hash_locked(pcbinfo,
799 faddr6, fport, laddr6, lport, lookupflags,
805 if ((inp->inp_vflag & INP_IPV6) != 0) {
806 tmpinp = in6_pcblookup_local(pcbinfo,
807 &inp->in6p_laddr, lport, lookupflags, cred);
809 if (tmpinp == NULL &&
810 (inp->inp_vflag & INP_IPV4))
811 tmpinp = in_pcblookup_local(pcbinfo,
812 laddr, lport, lookupflags, cred);
816 #if defined(INET) && defined(INET6)
820 tmpinp = in_pcblookup_local(pcbinfo, laddr,
821 lport, lookupflags, cred);
824 } while (tmpinp != NULL);
832 * Select a local port (number) to use.
835 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
836 struct ucred *cred, int lookupflags)
838 struct sockaddr_in laddr;
841 bzero(&laddr, sizeof(laddr));
842 laddr.sin_family = AF_INET;
843 laddr.sin_addr = *laddrp;
845 return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
846 NULL, lportp, NULL, 0, cred, lookupflags));
850 * Return cached socket options.
853 inp_so_options(const struct inpcb *inp)
859 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
860 so_options |= SO_REUSEPORT_LB;
861 if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
862 so_options |= SO_REUSEPORT;
863 if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
864 so_options |= SO_REUSEADDR;
867 #endif /* INET || INET6 */
871 * Set up a bind operation on a PCB, performing port allocation
872 * as required, but do not actually modify the PCB. Callers can
873 * either complete the bind by setting inp_laddr/inp_lport and
874 * calling in_pcbinshash(), or they can just use the resulting
875 * port and address to authorise the sending of a once-off packet.
877 * On error, the values of *laddrp and *lportp are not changed.
880 in_pcbbind_setup(struct inpcb *inp, struct sockaddr_in *sin, in_addr_t *laddrp,
881 u_short *lportp, struct ucred *cred)
883 struct socket *so = inp->inp_socket;
884 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
885 struct in_addr laddr;
887 int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
891 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
892 * so that we don't have to add to the (already messy) code below.
894 int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
897 * No state changes, so read locks are sufficient here.
899 INP_LOCK_ASSERT(inp);
900 INP_HASH_LOCK_ASSERT(pcbinfo);
902 laddr.s_addr = *laddrp;
903 if (sin != NULL && laddr.s_addr != INADDR_ANY)
905 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
906 lookupflags = INPLOOKUP_WILDCARD;
908 if ((error = prison_local_ip4(cred, &laddr)) != 0)
911 KASSERT(sin->sin_family == AF_INET,
912 ("%s: invalid family for address %p", __func__, sin));
913 KASSERT(sin->sin_len == sizeof(*sin),
914 ("%s: invalid length for address %p", __func__, sin));
916 error = prison_local_ip4(cred, &sin->sin_addr);
919 if (sin->sin_port != *lportp) {
920 /* Don't allow the port to change. */
923 lport = sin->sin_port;
925 /* NB: lport is left as 0 if the port isn't being changed. */
926 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
928 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
929 * allow complete duplication of binding if
930 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
931 * and a multicast address is bound on both
932 * new and duplicated sockets.
934 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
935 reuseport = SO_REUSEADDR|SO_REUSEPORT;
937 * XXX: How to deal with SO_REUSEPORT_LB here?
938 * Treat same as SO_REUSEPORT for now.
940 if ((so->so_options &
941 (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
942 reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
943 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
944 sin->sin_port = 0; /* yech... */
945 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
947 * Is the address a local IP address?
948 * If INP_BINDANY is set, then the socket may be bound
949 * to any endpoint address, local or not.
951 if ((inp->inp_flags & INP_BINDANY) == 0 &&
952 ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
953 return (EADDRNOTAVAIL);
955 laddr = sin->sin_addr;
960 if (ntohs(lport) <= V_ipport_reservedhigh &&
961 ntohs(lport) >= V_ipport_reservedlow &&
962 priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
964 if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
965 priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
966 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
967 lport, INPLOOKUP_WILDCARD, cred);
970 * This entire block sorely needs a rewrite.
973 (so->so_type != SOCK_STREAM ||
974 ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
975 (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
976 ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
977 (t->inp_flags2 & INP_REUSEPORT) ||
978 (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
979 (inp->inp_cred->cr_uid !=
980 t->inp_cred->cr_uid))
983 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
984 lport, lookupflags, cred);
985 if (t != NULL && (reuseport & inp_so_options(t)) == 0 &&
986 (reuseport_lb & inp_so_options(t)) == 0) {
988 if (ntohl(sin->sin_addr.s_addr) !=
990 ntohl(t->inp_laddr.s_addr) !=
992 (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
993 (t->inp_vflag & INP_IPV6PROTO) == 0)
1002 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1006 *laddrp = laddr.s_addr;
1012 * Connect from a socket to a specified address.
1013 * Both address and port must be specified in argument sin.
1014 * If don't have a local address for this socket yet,
1018 in_pcbconnect(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred,
1019 bool rehash __unused)
1021 u_short lport, fport;
1022 in_addr_t laddr, faddr;
1023 int anonport, error;
1025 INP_WLOCK_ASSERT(inp);
1026 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1027 KASSERT(in_nullhost(inp->inp_faddr),
1028 ("%s: inp is already connected", __func__));
1030 lport = inp->inp_lport;
1031 laddr = inp->inp_laddr.s_addr;
1032 anonport = (lport == 0);
1033 error = in_pcbconnect_setup(inp, sin, &laddr, &lport, &faddr, &fport,
1038 inp->inp_faddr.s_addr = faddr;
1039 inp->inp_fport = fport;
1041 /* Do the initial binding of the local address if required. */
1042 if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1043 inp->inp_lport = lport;
1044 inp->inp_laddr.s_addr = laddr;
1045 if (in_pcbinshash(inp) != 0) {
1046 inp->inp_laddr.s_addr = inp->inp_faddr.s_addr =
1048 inp->inp_lport = inp->inp_fport = 0;
1052 inp->inp_lport = lport;
1053 inp->inp_laddr.s_addr = laddr;
1054 if ((inp->inp_flags & INP_INHASHLIST) != 0)
1061 inp->inp_flags |= INP_ANONPORT;
1066 * Do proper source address selection on an unbound socket in case
1067 * of connect. Take jails into account as well.
1070 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1074 struct sockaddr *sa;
1075 struct sockaddr_in *sin, dst;
1076 struct nhop_object *nh;
1080 KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1083 * Bypass source address selection and use the primary jail IP
1086 if (!prison_saddrsel_ip4(cred, laddr))
1092 bzero(&dst, sizeof(dst));
1094 sin->sin_family = AF_INET;
1095 sin->sin_len = sizeof(struct sockaddr_in);
1096 sin->sin_addr.s_addr = faddr->s_addr;
1099 * If route is known our src addr is taken from the i/f,
1102 * Find out route to destination.
1104 if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1105 nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
1109 * If we found a route, use the address corresponding to
1110 * the outgoing interface.
1112 * Otherwise assume faddr is reachable on a directly connected
1113 * network and try to find a corresponding interface to take
1114 * the source address from.
1116 if (nh == NULL || nh->nh_ifp == NULL) {
1117 struct in_ifaddr *ia;
1120 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1121 inp->inp_socket->so_fibnum));
1123 ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1124 inp->inp_socket->so_fibnum));
1127 error = ENETUNREACH;
1131 if (!prison_flag(cred, PR_IP4)) {
1132 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1138 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1140 if (sa->sa_family != AF_INET)
1142 sin = (struct sockaddr_in *)sa;
1143 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1144 ia = (struct in_ifaddr *)ifa;
1149 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1153 /* 3. As a last resort return the 'default' jail address. */
1154 error = prison_get_ip4(cred, laddr);
1159 * If the outgoing interface on the route found is not
1160 * a loopback interface, use the address from that interface.
1161 * In case of jails do those three steps:
1162 * 1. check if the interface address belongs to the jail. If so use it.
1163 * 2. check if we have any address on the outgoing interface
1164 * belonging to this jail. If so use it.
1165 * 3. as a last resort return the 'default' jail address.
1167 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
1168 struct in_ifaddr *ia;
1171 /* If not jailed, use the default returned. */
1172 if (!prison_flag(cred, PR_IP4)) {
1173 ia = (struct in_ifaddr *)nh->nh_ifa;
1174 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1179 /* 1. Check if the iface address belongs to the jail. */
1180 sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1181 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1182 ia = (struct in_ifaddr *)nh->nh_ifa;
1183 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1188 * 2. Check if we have any address on the outgoing interface
1189 * belonging to this jail.
1193 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1195 if (sa->sa_family != AF_INET)
1197 sin = (struct sockaddr_in *)sa;
1198 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1199 ia = (struct in_ifaddr *)ifa;
1204 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1208 /* 3. As a last resort return the 'default' jail address. */
1209 error = prison_get_ip4(cred, laddr);
1214 * The outgoing interface is marked with 'loopback net', so a route
1215 * to ourselves is here.
1216 * Try to find the interface of the destination address and then
1217 * take the address from there. That interface is not necessarily
1218 * a loopback interface.
1219 * In case of jails, check that it is an address of the jail
1220 * and if we cannot find, fall back to the 'default' jail address.
1222 if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
1223 struct in_ifaddr *ia;
1225 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
1226 inp->inp_socket->so_fibnum));
1228 ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
1229 inp->inp_socket->so_fibnum));
1231 ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
1233 if (!prison_flag(cred, PR_IP4)) {
1235 error = ENETUNREACH;
1238 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1248 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1250 if (sa->sa_family != AF_INET)
1252 sin = (struct sockaddr_in *)sa;
1253 if (prison_check_ip4(cred,
1254 &sin->sin_addr) == 0) {
1255 ia = (struct in_ifaddr *)ifa;
1260 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1265 /* 3. As a last resort return the 'default' jail address. */
1266 error = prison_get_ip4(cred, laddr);
1271 if (error == 0 && laddr->s_addr == INADDR_ANY)
1272 return (EHOSTUNREACH);
1277 * Set up for a connect from a socket to the specified address.
1278 * On entry, *laddrp and *lportp should contain the current local
1279 * address and port for the PCB; these are updated to the values
1280 * that should be placed in inp_laddr and inp_lport to complete
1283 * On success, *faddrp and *fportp will be set to the remote address
1284 * and port. These are not updated in the error case.
1287 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr_in *sin,
1288 in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1291 struct in_ifaddr *ia;
1292 struct in_addr laddr, faddr;
1293 u_short lport, fport;
1296 KASSERT(sin->sin_family == AF_INET,
1297 ("%s: invalid address family for %p", __func__, sin));
1298 KASSERT(sin->sin_len == sizeof(*sin),
1299 ("%s: invalid address length for %p", __func__, sin));
1302 * Because a global state change doesn't actually occur here, a read
1303 * lock is sufficient.
1306 INP_LOCK_ASSERT(inp);
1307 INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1309 if (sin->sin_port == 0)
1310 return (EADDRNOTAVAIL);
1311 laddr.s_addr = *laddrp;
1313 faddr = sin->sin_addr;
1314 fport = sin->sin_port;
1316 if (CALC_FLOWID_OUTBOUND) {
1317 uint32_t hash_val, hash_type;
1319 hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
1320 inp->inp_socket->so_proto->pr_protocol, &hash_type);
1322 inp->inp_flowid = hash_val;
1323 inp->inp_flowtype = hash_type;
1326 if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1328 * If the destination address is INADDR_ANY,
1329 * use the primary local address.
1330 * If the supplied address is INADDR_BROADCAST,
1331 * and the primary interface supports broadcast,
1332 * choose the broadcast address for that interface.
1334 if (faddr.s_addr == INADDR_ANY) {
1336 IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1337 if ((error = prison_get_ip4(cred, &faddr)) != 0)
1339 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1340 if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1342 faddr = satosin(&CK_STAILQ_FIRST(
1343 &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1346 if (laddr.s_addr == INADDR_ANY) {
1347 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1349 * If the destination address is multicast and an outgoing
1350 * interface has been set as a multicast option, prefer the
1351 * address of that interface as our source address.
1353 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1354 inp->inp_moptions != NULL) {
1355 struct ip_moptions *imo;
1358 imo = inp->inp_moptions;
1359 if (imo->imo_multicast_ifp != NULL) {
1360 ifp = imo->imo_multicast_ifp;
1361 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1362 if (ia->ia_ifp == ifp &&
1363 prison_check_ip4(cred,
1364 &ia->ia_addr.sin_addr) == 0)
1368 error = EADDRNOTAVAIL;
1370 laddr = ia->ia_addr.sin_addr;
1380 if (in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1381 fport, laddr, lport, 0, M_NODOM) != NULL)
1382 return (EADDRINUSE);
1384 struct sockaddr_in lsin, fsin;
1386 bzero(&lsin, sizeof(lsin));
1387 bzero(&fsin, sizeof(fsin));
1388 lsin.sin_family = AF_INET;
1389 lsin.sin_addr = laddr;
1390 fsin.sin_family = AF_INET;
1391 fsin.sin_addr = faddr;
1392 error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
1393 &lport, (struct sockaddr *)& fsin, fport, cred,
1394 INPLOOKUP_WILDCARD);
1398 *laddrp = laddr.s_addr;
1400 *faddrp = faddr.s_addr;
1406 in_pcbdisconnect(struct inpcb *inp)
1409 INP_WLOCK_ASSERT(inp);
1410 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1411 KASSERT(inp->inp_smr == SMR_SEQ_INVALID,
1412 ("%s: inp %p was already disconnected", __func__, inp));
1414 in_pcbremhash_locked(inp);
1416 /* See the comment in in_pcbinshash(). */
1417 inp->inp_smr = smr_advance(inp->inp_pcbinfo->ipi_smr);
1418 inp->inp_laddr.s_addr = INADDR_ANY;
1419 inp->inp_faddr.s_addr = INADDR_ANY;
1425 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1426 * For most protocols, this will be invoked immediately prior to calling
1427 * in_pcbfree(). However, with TCP the inpcb may significantly outlive the
1428 * socket, in which case in_pcbfree() is deferred.
1431 in_pcbdetach(struct inpcb *inp)
1434 KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1437 if (inp->inp_snd_tag != NULL)
1438 in_pcbdetach_txrtlmt(inp);
1440 inp->inp_socket->so_pcb = NULL;
1441 inp->inp_socket = NULL;
1445 * inpcb hash lookups are protected by SMR section.
1447 * Once desired pcb has been found, switching from SMR section to a pcb
1448 * lock is performed with inp_smr_lock(). We can not use INP_(W|R)LOCK
1449 * here because SMR is a critical section.
1450 * In 99%+ cases inp_smr_lock() would obtain the lock immediately.
1453 inp_lock(struct inpcb *inp, const inp_lookup_t lock)
1456 lock == INPLOOKUP_RLOCKPCB ?
1457 rw_rlock(&inp->inp_lock) : rw_wlock(&inp->inp_lock);
1461 inp_unlock(struct inpcb *inp, const inp_lookup_t lock)
1464 lock == INPLOOKUP_RLOCKPCB ?
1465 rw_runlock(&inp->inp_lock) : rw_wunlock(&inp->inp_lock);
1469 inp_trylock(struct inpcb *inp, const inp_lookup_t lock)
1472 return (lock == INPLOOKUP_RLOCKPCB ?
1473 rw_try_rlock(&inp->inp_lock) : rw_try_wlock(&inp->inp_lock));
1477 _inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock, const int ignflags)
1480 MPASS(lock == INPLOOKUP_RLOCKPCB || lock == INPLOOKUP_WLOCKPCB);
1481 SMR_ASSERT_ENTERED(inp->inp_pcbinfo->ipi_smr);
1483 if (__predict_true(inp_trylock(inp, lock))) {
1484 if (__predict_false(inp->inp_flags & ignflags)) {
1485 smr_exit(inp->inp_pcbinfo->ipi_smr);
1486 inp_unlock(inp, lock);
1489 smr_exit(inp->inp_pcbinfo->ipi_smr);
1493 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1494 smr_exit(inp->inp_pcbinfo->ipi_smr);
1495 inp_lock(inp, lock);
1496 if (__predict_false(in_pcbrele(inp, lock)))
1499 * inp acquired through refcount & lock for sure didn't went
1500 * through uma_zfree(). However, it may have already went
1501 * through in_pcbfree() and has another reference, that
1502 * prevented its release by our in_pcbrele().
1504 if (__predict_false(inp->inp_flags & ignflags)) {
1505 inp_unlock(inp, lock);
1510 smr_exit(inp->inp_pcbinfo->ipi_smr);
1516 inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock)
1520 * in_pcblookup() family of functions ignore not only freed entries,
1521 * that may be found due to lockless access to the hash, but dropped
1524 return (_inp_smr_lock(inp, lock, INP_FREED | INP_DROPPED));
1528 * inp_next() - inpcb hash/list traversal iterator
1530 * Requires initialized struct inpcb_iterator for context.
1531 * The structure can be initialized with INP_ITERATOR() or INP_ALL_ITERATOR().
1533 * - Iterator can have either write-lock or read-lock semantics, that can not
1535 * - Iterator can iterate either over all pcbs list (INP_ALL_LIST), or through
1536 * a single hash slot. Note: only rip_input() does the latter.
1537 * - Iterator may have optional bool matching function. The matching function
1538 * will be executed for each inpcb in the SMR context, so it can not acquire
1539 * locks and can safely access only immutable fields of inpcb.
1541 * A fresh initialized iterator has NULL inpcb in its context and that
1542 * means that inp_next() call would return the very first inpcb on the list
1543 * locked with desired semantic. In all following calls the context pointer
1544 * shall hold the current inpcb pointer. The KPI user is not supposed to
1545 * unlock the current inpcb! Upon end of traversal inp_next() will return NULL
1546 * and write NULL to its context. After end of traversal an iterator can be
1549 * List traversals have the following features/constraints:
1550 * - New entries won't be seen, as they are always added to the head of a list.
1551 * - Removed entries won't stop traversal as long as they are not added to
1552 * a different list. This is violated by in_pcbrehash().
1554 #define II_LIST_FIRST(ipi, hash) \
1555 (((hash) == INP_ALL_LIST) ? \
1556 CK_LIST_FIRST(&(ipi)->ipi_listhead) : \
1557 CK_LIST_FIRST(&(ipi)->ipi_hash_exact[(hash)]))
1558 #define II_LIST_NEXT(inp, hash) \
1559 (((hash) == INP_ALL_LIST) ? \
1560 CK_LIST_NEXT((inp), inp_list) : \
1561 CK_LIST_NEXT((inp), inp_hash_exact))
1562 #define II_LOCK_ASSERT(inp, lock) \
1563 rw_assert(&(inp)->inp_lock, \
1564 (lock) == INPLOOKUP_RLOCKPCB ? RA_RLOCKED : RA_WLOCKED )
1566 inp_next(struct inpcb_iterator *ii)
1568 const struct inpcbinfo *ipi = ii->ipi;
1569 inp_match_t *match = ii->match;
1570 void *ctx = ii->ctx;
1571 inp_lookup_t lock = ii->lock;
1572 int hash = ii->hash;
1575 if (ii->inp == NULL) { /* First call. */
1576 smr_enter(ipi->ipi_smr);
1577 /* This is unrolled CK_LIST_FOREACH(). */
1578 for (inp = II_LIST_FIRST(ipi, hash);
1580 inp = II_LIST_NEXT(inp, hash)) {
1581 if (match != NULL && (match)(inp, ctx) == false)
1583 if (__predict_true(_inp_smr_lock(inp, lock, INP_FREED)))
1586 smr_enter(ipi->ipi_smr);
1587 MPASS(inp != II_LIST_FIRST(ipi, hash));
1588 inp = II_LIST_FIRST(ipi, hash);
1595 smr_exit(ipi->ipi_smr);
1602 /* Not a first call. */
1603 smr_enter(ipi->ipi_smr);
1606 II_LOCK_ASSERT(inp, lock);
1608 inp = II_LIST_NEXT(inp, hash);
1610 smr_exit(ipi->ipi_smr);
1614 if (match != NULL && (match)(inp, ctx) == false)
1617 if (__predict_true(inp_trylock(inp, lock))) {
1618 if (__predict_false(inp->inp_flags & INP_FREED)) {
1620 * Entries are never inserted in middle of a list, thus
1621 * as long as we are in SMR, we can continue traversal.
1622 * Jump to 'restart' should yield in the same result,
1623 * but could produce unnecessary looping. Could this
1624 * looping be unbound?
1626 inp_unlock(inp, lock);
1629 smr_exit(ipi->ipi_smr);
1635 * Can't obtain lock immediately, thus going hard. Once we exit the
1636 * SMR section we can no longer jump to 'next', and our only stable
1637 * anchoring point is ii->inp, which we keep locked for this case, so
1638 * we jump to 'restart'.
1640 if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1641 smr_exit(ipi->ipi_smr);
1642 inp_lock(inp, lock);
1643 if (__predict_false(in_pcbrele(inp, lock))) {
1644 smr_enter(ipi->ipi_smr);
1648 * See comment in inp_smr_lock().
1650 if (__predict_false(inp->inp_flags & INP_FREED)) {
1651 inp_unlock(inp, lock);
1652 smr_enter(ipi->ipi_smr);
1659 inp_unlock(ii->inp, lock);
1666 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1667 * stability of an inpcb pointer despite the inpcb lock being released or
1668 * SMR section exited.
1670 * To free a reference later in_pcbrele_(r|w)locked() must be performed.
1673 in_pcbref(struct inpcb *inp)
1675 u_int old __diagused;
1677 old = refcount_acquire(&inp->inp_refcount);
1678 KASSERT(old > 0, ("%s: refcount 0", __func__));
1682 * Drop a refcount on an inpcb elevated using in_pcbref(), potentially
1683 * freeing the pcb, if the reference was very last.
1686 in_pcbrele_rlocked(struct inpcb *inp)
1689 INP_RLOCK_ASSERT(inp);
1691 if (!refcount_release(&inp->inp_refcount))
1694 MPASS(inp->inp_flags & INP_FREED);
1695 MPASS(inp->inp_socket == NULL);
1696 MPASS(inp->inp_in_hpts == 0);
1698 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1703 in_pcbrele_wlocked(struct inpcb *inp)
1706 INP_WLOCK_ASSERT(inp);
1708 if (!refcount_release(&inp->inp_refcount))
1711 MPASS(inp->inp_flags & INP_FREED);
1712 MPASS(inp->inp_socket == NULL);
1713 MPASS(inp->inp_in_hpts == 0);
1715 uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1720 in_pcbrele(struct inpcb *inp, const inp_lookup_t lock)
1723 return (lock == INPLOOKUP_RLOCKPCB ?
1724 in_pcbrele_rlocked(inp) : in_pcbrele_wlocked(inp));
1728 * Unconditionally schedule an inpcb to be freed by decrementing its
1729 * reference count, which should occur only after the inpcb has been detached
1730 * from its socket. If another thread holds a temporary reference (acquired
1731 * using in_pcbref()) then the free is deferred until that reference is
1732 * released using in_pcbrele_(r|w)locked(), but the inpcb is still unlocked.
1733 * Almost all work, including removal from global lists, is done in this
1734 * context, where the pcbinfo lock is held.
1737 in_pcbfree(struct inpcb *inp)
1739 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1741 struct ip_moptions *imo;
1744 struct ip6_moptions *im6o;
1747 INP_WLOCK_ASSERT(inp);
1748 KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1749 KASSERT((inp->inp_flags & INP_FREED) == 0,
1750 ("%s: called twice for pcb %p", __func__, inp));
1752 inp->inp_flags |= INP_FREED;
1753 INP_INFO_WLOCK(pcbinfo);
1754 inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1755 pcbinfo->ipi_count--;
1756 CK_LIST_REMOVE(inp, inp_list);
1757 INP_INFO_WUNLOCK(pcbinfo);
1759 if (inp->inp_flags & INP_INHASHLIST)
1762 RO_INVALIDATE_CACHE(&inp->inp_route);
1764 mac_inpcb_destroy(inp);
1766 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1767 if (inp->inp_sp != NULL)
1768 ipsec_delete_pcbpolicy(inp);
1771 if (inp->inp_options)
1772 (void)m_free(inp->inp_options);
1773 imo = inp->inp_moptions;
1776 if (inp->inp_vflag & INP_IPV6PROTO) {
1777 ip6_freepcbopts(inp->in6p_outputopts);
1778 im6o = inp->in6p_moptions;
1783 if (__predict_false(in_pcbrele_wlocked(inp) == false)) {
1787 ip6_freemoptions(im6o);
1790 inp_freemoptions(imo);
1792 /* Destruction is finalized in inpcb_dtor(). */
1796 inpcb_dtor(void *mem, int size, void *arg)
1798 struct inpcb *inp = mem;
1800 crfree(inp->inp_cred);
1802 inp->inp_cred = NULL;
1807 * Different protocols initialize their inpcbs differently - giving
1808 * different name to the lock. But they all are disposed the same.
1811 inpcb_fini(void *mem, int size)
1813 struct inpcb *inp = mem;
1815 INP_LOCK_DESTROY(inp);
1819 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1820 * port reservation, and preventing it from being returned by inpcb lookups.
1822 * It is used by TCP to mark an inpcb as unused and avoid future packet
1823 * delivery or event notification when a socket remains open but TCP has
1824 * closed. This might occur as a result of a shutdown()-initiated TCP close
1825 * or a RST on the wire, and allows the port binding to be reused while still
1826 * maintaining the invariant that so_pcb always points to a valid inpcb until
1829 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1830 * in_pcbnotifyall() and in_pcbpurgeif0()?
1833 in_pcbdrop(struct inpcb *inp)
1836 INP_WLOCK_ASSERT(inp);
1838 if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1839 MPASS(inp->inp_refcount > 1);
1842 inp->inp_flags |= INP_DROPPED;
1843 if (inp->inp_flags & INP_INHASHLIST)
1849 * Common routines to return the socket addresses associated with inpcbs.
1852 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1854 struct sockaddr_in *sin;
1856 sin = malloc(sizeof *sin, M_SONAME,
1858 sin->sin_family = AF_INET;
1859 sin->sin_len = sizeof(*sin);
1860 sin->sin_addr = *addr_p;
1861 sin->sin_port = port;
1863 return (struct sockaddr *)sin;
1867 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1870 struct in_addr addr;
1873 inp = sotoinpcb(so);
1874 KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1877 port = inp->inp_lport;
1878 addr = inp->inp_laddr;
1881 *nam = in_sockaddr(port, &addr);
1886 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1889 struct in_addr addr;
1892 inp = sotoinpcb(so);
1893 KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1896 port = inp->inp_fport;
1897 addr = inp->inp_faddr;
1900 *nam = in_sockaddr(port, &addr);
1905 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1906 struct inpcb *(*notify)(struct inpcb *, int))
1908 struct inpcb *inp, *inp_temp;
1910 INP_INFO_WLOCK(pcbinfo);
1911 CK_LIST_FOREACH_SAFE(inp, &pcbinfo->ipi_listhead, inp_list, inp_temp) {
1914 if ((inp->inp_vflag & INP_IPV4) == 0) {
1919 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1920 inp->inp_socket == NULL) {
1924 if ((*notify)(inp, errno))
1927 INP_INFO_WUNLOCK(pcbinfo);
1931 inp_v4_multi_match(const struct inpcb *inp, void *v __unused)
1934 if ((inp->inp_vflag & INP_IPV4) && inp->inp_moptions != NULL)
1941 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1943 struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
1944 inp_v4_multi_match, NULL);
1946 struct in_multi *inm;
1947 struct in_mfilter *imf;
1948 struct ip_moptions *imo;
1950 IN_MULTI_LOCK_ASSERT();
1952 while ((inp = inp_next(&inpi)) != NULL) {
1953 INP_WLOCK_ASSERT(inp);
1955 imo = inp->inp_moptions;
1957 * Unselect the outgoing interface if it is being
1960 if (imo->imo_multicast_ifp == ifp)
1961 imo->imo_multicast_ifp = NULL;
1964 * Drop multicast group membership if we joined
1965 * through the interface being detached.
1967 * XXX This can all be deferred to an epoch_call
1970 IP_MFILTER_FOREACH(imf, &imo->imo_head) {
1971 if ((inm = imf->imf_inm) == NULL)
1973 if (inm->inm_ifp != ifp)
1975 ip_mfilter_remove(&imo->imo_head, imf);
1976 in_leavegroup_locked(inm, NULL);
1977 ip_mfilter_free(imf);
1984 * Lookup a PCB based on the local address and port. Caller must hold the
1985 * hash lock. No inpcb locks or references are acquired.
1987 #define INP_LOOKUP_MAPPED_PCB_COST 3
1989 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1990 u_short lport, int lookupflags, struct ucred *cred)
1994 int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
2000 KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2001 ("%s: invalid lookup flags %d", __func__, lookupflags));
2002 INP_HASH_LOCK_ASSERT(pcbinfo);
2004 if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
2005 struct inpcbhead *head;
2007 * Look for an unconnected (wildcard foreign addr) PCB that
2008 * matches the local address and port we're looking for.
2010 head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
2011 pcbinfo->ipi_hashmask)];
2012 CK_LIST_FOREACH(inp, head, inp_hash_wild) {
2014 /* XXX inp locking */
2015 if ((inp->inp_vflag & INP_IPV4) == 0)
2018 if (inp->inp_faddr.s_addr == INADDR_ANY &&
2019 inp->inp_laddr.s_addr == laddr.s_addr &&
2020 inp->inp_lport == lport) {
2024 if (prison_equal_ip4(cred->cr_prison,
2025 inp->inp_cred->cr_prison))
2034 struct inpcbporthead *porthash;
2035 struct inpcbport *phd;
2036 struct inpcb *match = NULL;
2038 * Best fit PCB lookup.
2040 * First see if this local port is in use by looking on the
2043 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2044 pcbinfo->ipi_porthashmask)];
2045 CK_LIST_FOREACH(phd, porthash, phd_hash) {
2046 if (phd->phd_port == lport)
2051 * Port is in use by one or more PCBs. Look for best
2054 CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2056 if (!prison_equal_ip4(inp->inp_cred->cr_prison,
2060 /* XXX inp locking */
2061 if ((inp->inp_vflag & INP_IPV4) == 0)
2064 * We never select the PCB that has
2065 * INP_IPV6 flag and is bound to :: if
2066 * we have another PCB which is bound
2067 * to 0.0.0.0. If a PCB has the
2068 * INP_IPV6 flag, then we set its cost
2069 * higher than IPv4 only PCBs.
2071 * Note that the case only happens
2072 * when a socket is bound to ::, under
2073 * the condition that the use of the
2074 * mapped address is allowed.
2076 if ((inp->inp_vflag & INP_IPV6) != 0)
2077 wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2079 if (inp->inp_faddr.s_addr != INADDR_ANY)
2081 if (inp->inp_laddr.s_addr != INADDR_ANY) {
2082 if (laddr.s_addr == INADDR_ANY)
2084 else if (inp->inp_laddr.s_addr != laddr.s_addr)
2087 if (laddr.s_addr != INADDR_ANY)
2090 if (wildcard < matchwild) {
2092 matchwild = wildcard;
2101 #undef INP_LOOKUP_MAPPED_PCB_COST
2104 in_pcblookup_lb_numa_match(const struct inpcblbgroup *grp, int domain)
2106 return (domain == M_NODOM || domain == grp->il_numa_domain);
2109 static struct inpcb *
2110 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
2111 const struct in_addr *faddr, uint16_t fport, const struct in_addr *laddr,
2112 uint16_t lport, int domain)
2114 const struct inpcblbgrouphead *hdr;
2115 struct inpcblbgroup *grp;
2116 struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
2118 INP_HASH_LOCK_ASSERT(pcbinfo);
2120 hdr = &pcbinfo->ipi_lbgrouphashbase[
2121 INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
2124 * Search for an LB group match based on the following criteria:
2125 * - prefer jailed groups to non-jailed groups
2126 * - prefer exact source address matches to wildcard matches
2127 * - prefer groups bound to the specified NUMA domain
2129 jail_exact = jail_wild = local_exact = local_wild = NULL;
2130 CK_LIST_FOREACH(grp, hdr, il_list) {
2134 if (!(grp->il_vflag & INP_IPV4))
2137 if (grp->il_lport != lport)
2140 injail = prison_flag(grp->il_cred, PR_IP4) != 0;
2141 if (injail && prison_check_ip4_locked(grp->il_cred->cr_prison,
2145 if (grp->il_laddr.s_addr == laddr->s_addr) {
2148 if (in_pcblookup_lb_numa_match(grp, domain))
2149 /* This is a perfect match. */
2151 } else if (local_exact == NULL ||
2152 in_pcblookup_lb_numa_match(grp, domain)) {
2155 } else if (grp->il_laddr.s_addr == INADDR_ANY) {
2157 if (jail_wild == NULL ||
2158 in_pcblookup_lb_numa_match(grp, domain))
2160 } else if (local_wild == NULL ||
2161 in_pcblookup_lb_numa_match(grp, domain)) {
2167 if (jail_exact != NULL)
2169 else if (jail_wild != NULL)
2171 else if (local_exact != NULL)
2178 return (grp->il_inp[INP_PCBLBGROUP_PKTHASH(faddr, lport, fport) %
2183 in_pcblookup_exact_match(const struct inpcb *inp, struct in_addr faddr,
2184 u_short fport, struct in_addr laddr, u_short lport)
2187 /* XXX inp locking */
2188 if ((inp->inp_vflag & INP_IPV4) == 0)
2191 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2192 inp->inp_laddr.s_addr == laddr.s_addr &&
2193 inp->inp_fport == fport &&
2194 inp->inp_lport == lport)
2199 static struct inpcb *
2200 in_pcblookup_hash_exact(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2201 u_short fport, struct in_addr laddr, u_short lport)
2203 struct inpcbhead *head;
2206 INP_HASH_LOCK_ASSERT(pcbinfo);
2208 head = &pcbinfo->ipi_hash_exact[INP_PCBHASH(&faddr, lport, fport,
2209 pcbinfo->ipi_hashmask)];
2210 CK_LIST_FOREACH(inp, head, inp_hash_exact) {
2211 if (in_pcblookup_exact_match(inp, faddr, fport, laddr, lport))
2218 INPLOOKUP_MATCH_NONE = 0,
2219 INPLOOKUP_MATCH_WILD = 1,
2220 INPLOOKUP_MATCH_LADDR = 2,
2221 } inp_lookup_match_t;
2223 static inp_lookup_match_t
2224 in_pcblookup_wild_match(const struct inpcb *inp, struct in_addr laddr,
2228 /* XXX inp locking */
2229 if ((inp->inp_vflag & INP_IPV4) == 0)
2230 return (INPLOOKUP_MATCH_NONE);
2232 if (inp->inp_faddr.s_addr != INADDR_ANY || inp->inp_lport != lport)
2233 return (INPLOOKUP_MATCH_NONE);
2234 if (inp->inp_laddr.s_addr == INADDR_ANY)
2235 return (INPLOOKUP_MATCH_WILD);
2236 if (inp->inp_laddr.s_addr == laddr.s_addr)
2237 return (INPLOOKUP_MATCH_LADDR);
2238 return (INPLOOKUP_MATCH_NONE);
2241 #define INP_LOOKUP_AGAIN ((struct inpcb *)(uintptr_t)-1)
2243 static struct inpcb *
2244 in_pcblookup_hash_wild_smr(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2245 u_short fport, struct in_addr laddr, u_short lport,
2246 const inp_lookup_t lockflags)
2248 struct inpcbhead *head;
2251 KASSERT(SMR_ENTERED(pcbinfo->ipi_smr),
2252 ("%s: not in SMR read section", __func__));
2254 head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
2255 pcbinfo->ipi_hashmask)];
2256 CK_LIST_FOREACH(inp, head, inp_hash_wild) {
2257 inp_lookup_match_t match;
2259 match = in_pcblookup_wild_match(inp, laddr, lport);
2260 if (match == INPLOOKUP_MATCH_NONE)
2263 if (__predict_true(inp_smr_lock(inp, lockflags))) {
2264 if (__predict_true(in_pcblookup_wild_match(inp, laddr,
2265 lport) != INPLOOKUP_MATCH_NONE))
2267 inp_unlock(inp, lockflags);
2271 * The matching socket disappeared out from under us. Fall back
2272 * to a serialized lookup.
2274 return (INP_LOOKUP_AGAIN);
2279 static struct inpcb *
2280 in_pcblookup_hash_wild_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2281 u_short fport, struct in_addr laddr, u_short lport)
2283 struct inpcbhead *head;
2284 struct inpcb *inp, *local_wild, *local_exact, *jail_wild;
2286 struct inpcb *local_wild_mapped;
2289 INP_HASH_LOCK_ASSERT(pcbinfo);
2292 * Order of socket selection - we always prefer jails.
2293 * 1. jailed, non-wild.
2295 * 3. non-jailed, non-wild.
2296 * 4. non-jailed, wild.
2298 head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
2299 pcbinfo->ipi_hashmask)];
2300 local_wild = local_exact = jail_wild = NULL;
2302 local_wild_mapped = NULL;
2304 CK_LIST_FOREACH(inp, head, inp_hash_wild) {
2305 inp_lookup_match_t match;
2308 match = in_pcblookup_wild_match(inp, laddr, lport);
2309 if (match == INPLOOKUP_MATCH_NONE)
2312 injail = prison_flag(inp->inp_cred, PR_IP4) != 0;
2314 if (prison_check_ip4_locked(inp->inp_cred->cr_prison,
2318 if (local_exact != NULL)
2322 if (match == INPLOOKUP_MATCH_LADDR) {
2328 /* XXX inp locking, NULL check */
2329 if (inp->inp_vflag & INP_IPV6PROTO)
2330 local_wild_mapped = inp;
2339 if (jail_wild != NULL)
2341 if (local_exact != NULL)
2342 return (local_exact);
2343 if (local_wild != NULL)
2344 return (local_wild);
2346 if (local_wild_mapped != NULL)
2347 return (local_wild_mapped);
2353 * Lookup PCB in hash list, using pcbinfo tables. This variation assumes
2354 * that the caller has either locked the hash list, which usually happens
2355 * for bind(2) operations, or is in SMR section, which happens when sorting
2356 * out incoming packets.
2358 static struct inpcb *
2359 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2360 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2361 uint8_t numa_domain)
2364 const u_short fport = fport_arg, lport = lport_arg;
2366 KASSERT((lookupflags & ~INPLOOKUP_WILDCARD) == 0,
2367 ("%s: invalid lookup flags %d", __func__, lookupflags));
2368 KASSERT(faddr.s_addr != INADDR_ANY,
2369 ("%s: invalid foreign address", __func__));
2370 KASSERT(laddr.s_addr != INADDR_ANY,
2371 ("%s: invalid local address", __func__));
2372 INP_HASH_WLOCK_ASSERT(pcbinfo);
2374 inp = in_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
2378 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2379 inp = in_pcblookup_lbgroup(pcbinfo, &faddr, fport,
2380 &laddr, lport, numa_domain);
2382 inp = in_pcblookup_hash_wild_locked(pcbinfo, faddr,
2383 fport, laddr, lport);
2390 static struct inpcb *
2391 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2392 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2393 uint8_t numa_domain)
2396 const inp_lookup_t lockflags = lookupflags & INPLOOKUP_LOCKMASK;
2398 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2399 ("%s: LOCKPCB not set", __func__));
2401 INP_HASH_WLOCK(pcbinfo);
2402 inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2403 lookupflags & ~INPLOOKUP_LOCKMASK, numa_domain);
2404 if (inp != NULL && !inp_trylock(inp, lockflags)) {
2406 INP_HASH_WUNLOCK(pcbinfo);
2407 inp_lock(inp, lockflags);
2408 if (in_pcbrele(inp, lockflags))
2409 /* XXX-MJ or retry until we get a negative match? */
2412 INP_HASH_WUNLOCK(pcbinfo);
2417 static struct inpcb *
2418 in_pcblookup_hash_smr(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2419 u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2420 uint8_t numa_domain)
2423 const inp_lookup_t lockflags = lookupflags & INPLOOKUP_LOCKMASK;
2424 const u_short fport = fport_arg, lport = lport_arg;
2426 KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2427 ("%s: invalid lookup flags %d", __func__, lookupflags));
2428 KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2429 ("%s: LOCKPCB not set", __func__));
2431 smr_enter(pcbinfo->ipi_smr);
2432 inp = in_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
2434 if (__predict_true(inp_smr_lock(inp, lockflags))) {
2436 * Revalidate the 4-tuple, the socket could have been
2439 if (__predict_true(in_pcblookup_exact_match(inp,
2440 faddr, fport, laddr, lport)))
2442 inp_unlock(inp, lockflags);
2446 * We failed to lock the inpcb, or its connection state changed
2447 * out from under us. Fall back to a precise search.
2449 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2450 lookupflags, numa_domain));
2453 if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2454 inp = in_pcblookup_lbgroup(pcbinfo, &faddr, fport,
2455 &laddr, lport, numa_domain);
2457 if (__predict_true(inp_smr_lock(inp, lockflags))) {
2458 if (__predict_true(in_pcblookup_wild_match(inp,
2459 laddr, lport) != INPLOOKUP_MATCH_NONE))
2461 inp_unlock(inp, lockflags);
2463 inp = INP_LOOKUP_AGAIN;
2465 inp = in_pcblookup_hash_wild_smr(pcbinfo, faddr, fport,
2466 laddr, lport, lockflags);
2468 if (inp == INP_LOOKUP_AGAIN) {
2469 return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr,
2470 lport, lookupflags, numa_domain));
2475 smr_exit(pcbinfo->ipi_smr);
2481 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2482 * from which a pre-calculated hash value may be extracted.
2485 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2486 struct in_addr laddr, u_int lport, int lookupflags,
2487 struct ifnet *ifp __unused)
2489 return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
2490 lookupflags, M_NODOM));
2494 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2495 u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2496 struct ifnet *ifp __unused, struct mbuf *m)
2498 return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
2499 lookupflags, m->m_pkthdr.numa_domain));
2504 in_pcbjailed(const struct inpcb *inp, unsigned int flag)
2506 return (prison_flag(inp->inp_cred, flag) != 0);
2510 * Insert the PCB into a hash chain using ordering rules which ensure that
2511 * in_pcblookup_hash_wild_*() always encounter the highest-ranking PCB first.
2513 * Specifically, keep jailed PCBs in front of non-jailed PCBs, and keep PCBs
2514 * with exact local addresses ahead of wildcard PCBs.
2517 _in_pcbinshash_wild(struct inpcbhead *pcbhash, struct inpcb *inp)
2522 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
2525 bound = inp->inp_laddr.s_addr != INADDR_ANY;
2526 injail = in_pcbjailed(inp, PR_IP4);
2528 CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
2529 if (in_pcbjailed(inp, PR_IP4))
2531 if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
2532 CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
2536 } else if (!CK_LIST_EMPTY(pcbhash) &&
2537 !in_pcbjailed(CK_LIST_FIRST(pcbhash), PR_IP4)) {
2538 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
2542 CK_LIST_FOREACH_FROM(last, pcbhash, inp_hash_wild) {
2543 if (last->inp_laddr.s_addr == INADDR_ANY)
2545 if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
2546 CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
2552 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
2554 CK_LIST_INSERT_BEFORE(last, inp, inp_hash_wild);
2559 * See the comment above _in_pcbinshash_wild().
2562 _in6_pcbinshash_wild(struct inpcbhead *pcbhash, struct inpcb *inp)
2567 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
2570 bound = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr);
2571 injail = in_pcbjailed(inp, PR_IP6);
2573 CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
2574 if (in_pcbjailed(last, PR_IP6))
2576 if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
2577 CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
2581 } else if (!CK_LIST_EMPTY(pcbhash) &&
2582 !in_pcbjailed(CK_LIST_FIRST(pcbhash), PR_IP6)) {
2583 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
2587 CK_LIST_FOREACH_FROM(last, pcbhash, inp_hash_wild) {
2588 if (IN6_IS_ADDR_UNSPECIFIED(&last->in6p_laddr))
2590 if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
2591 CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
2597 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
2599 CK_LIST_INSERT_BEFORE(last, inp, inp_hash_wild);
2604 * Insert PCB onto various hash lists.
2607 in_pcbinshash(struct inpcb *inp)
2609 struct inpcbhead *pcbhash;
2610 struct inpcbporthead *pcbporthash;
2611 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2612 struct inpcbport *phd;
2616 INP_WLOCK_ASSERT(inp);
2617 INP_HASH_WLOCK_ASSERT(pcbinfo);
2618 KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2619 ("in_pcbinshash: INP_INHASHLIST"));
2622 if (inp->inp_vflag & INP_IPV6) {
2623 hash = INP6_PCBHASH(&inp->in6p_faddr, inp->inp_lport,
2624 inp->inp_fport, pcbinfo->ipi_hashmask);
2625 connected = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr);
2629 hash = INP_PCBHASH(&inp->inp_faddr, inp->inp_lport,
2630 inp->inp_fport, pcbinfo->ipi_hashmask);
2631 connected = !in_nullhost(inp->inp_faddr);
2635 pcbhash = &pcbinfo->ipi_hash_exact[hash];
2637 pcbhash = &pcbinfo->ipi_hash_wild[hash];
2639 pcbporthash = &pcbinfo->ipi_porthashbase[
2640 INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2643 * Add entry to load balance group.
2644 * Only do this if SO_REUSEPORT_LB is set.
2646 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0) {
2647 int error = in_pcbinslbgrouphash(inp, M_NODOM);
2653 * Go through port list and look for a head for this lport.
2655 CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2656 if (phd->phd_port == inp->inp_lport)
2661 * If none exists, malloc one and tack it on.
2664 phd = uma_zalloc_smr(pcbinfo->ipi_portzone, M_NOWAIT);
2666 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2667 in_pcbremlbgrouphash(inp);
2670 phd->phd_port = inp->inp_lport;
2671 CK_LIST_INIT(&phd->phd_pcblist);
2672 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2675 CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2678 * The PCB may have been disconnected in the past. Before we can safely
2679 * make it visible in the hash table, we must wait for all readers which
2680 * may be traversing this PCB to finish.
2682 if (inp->inp_smr != SMR_SEQ_INVALID) {
2683 smr_wait(pcbinfo->ipi_smr, inp->inp_smr);
2684 inp->inp_smr = SMR_SEQ_INVALID;
2688 CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_exact);
2691 if ((inp->inp_vflag & INP_IPV6) != 0)
2692 _in6_pcbinshash_wild(pcbhash, inp);
2695 _in_pcbinshash_wild(pcbhash, inp);
2697 inp->inp_flags |= INP_INHASHLIST;
2703 in_pcbremhash_locked(struct inpcb *inp)
2705 struct inpcbport *phd = inp->inp_phd;
2707 INP_WLOCK_ASSERT(inp);
2708 INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
2709 MPASS(inp->inp_flags & INP_INHASHLIST);
2711 if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2712 in_pcbremlbgrouphash(inp);
2714 if (inp->inp_vflag & INP_IPV6) {
2715 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
2716 CK_LIST_REMOVE(inp, inp_hash_wild);
2718 CK_LIST_REMOVE(inp, inp_hash_exact);
2722 if (in_nullhost(inp->inp_faddr))
2723 CK_LIST_REMOVE(inp, inp_hash_wild);
2725 CK_LIST_REMOVE(inp, inp_hash_exact);
2727 CK_LIST_REMOVE(inp, inp_portlist);
2728 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2729 CK_LIST_REMOVE(phd, phd_hash);
2730 uma_zfree_smr(inp->inp_pcbinfo->ipi_portzone, phd);
2732 inp->inp_flags &= ~INP_INHASHLIST;
2736 in_pcbremhash(struct inpcb *inp)
2738 INP_HASH_WLOCK(inp->inp_pcbinfo);
2739 in_pcbremhash_locked(inp);
2740 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
2744 * Move PCB to the proper hash bucket when { faddr, fport } have been
2745 * changed. NOTE: This does not handle the case of the lport changing (the
2746 * hashed port list would have to be updated as well), so the lport must
2747 * not change after in_pcbinshash() has been called.
2750 in_pcbrehash(struct inpcb *inp)
2752 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2753 struct inpcbhead *head;
2757 INP_WLOCK_ASSERT(inp);
2758 INP_HASH_WLOCK_ASSERT(pcbinfo);
2759 KASSERT(inp->inp_flags & INP_INHASHLIST,
2760 ("%s: !INP_INHASHLIST", __func__));
2761 KASSERT(inp->inp_smr == SMR_SEQ_INVALID,
2762 ("%s: inp was disconnected", __func__));
2765 if (inp->inp_vflag & INP_IPV6) {
2766 hash = INP6_PCBHASH(&inp->in6p_faddr, inp->inp_lport,
2767 inp->inp_fport, pcbinfo->ipi_hashmask);
2768 connected = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr);
2772 hash = INP_PCBHASH(&inp->inp_faddr, inp->inp_lport,
2773 inp->inp_fport, pcbinfo->ipi_hashmask);
2774 connected = !in_nullhost(inp->inp_faddr);
2778 * When rehashing, the caller must ensure that either the new or the old
2779 * foreign address was unspecified.
2782 CK_LIST_REMOVE(inp, inp_hash_wild);
2784 CK_LIST_REMOVE(inp, inp_hash_exact);
2787 head = &pcbinfo->ipi_hash_exact[hash];
2788 CK_LIST_INSERT_HEAD(head, inp, inp_hash_exact);
2790 head = &pcbinfo->ipi_hash_wild[hash];
2791 CK_LIST_INSERT_HEAD(head, inp, inp_hash_wild);
2796 * Check for alternatives when higher level complains
2797 * about service problems. For now, invalidate cached
2798 * routing information. If the route was created dynamically
2799 * (by a redirect), time to try a default gateway again.
2802 in_losing(struct inpcb *inp)
2805 RO_INVALIDATE_CACHE(&inp->inp_route);
2810 * A set label operation has occurred at the socket layer, propagate the
2811 * label change into the in_pcb for the socket.
2814 in_pcbsosetlabel(struct socket *so)
2819 inp = sotoinpcb(so);
2820 KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2824 mac_inpcb_sosetlabel(so, inp);
2831 inp_wlock(struct inpcb *inp)
2838 inp_wunlock(struct inpcb *inp)
2845 inp_rlock(struct inpcb *inp)
2852 inp_runlock(struct inpcb *inp)
2858 #ifdef INVARIANT_SUPPORT
2860 inp_lock_assert(struct inpcb *inp)
2863 INP_WLOCK_ASSERT(inp);
2867 inp_unlock_assert(struct inpcb *inp)
2870 INP_UNLOCK_ASSERT(inp);
2875 inp_apply_all(struct inpcbinfo *pcbinfo,
2876 void (*func)(struct inpcb *, void *), void *arg)
2878 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2879 INPLOOKUP_WLOCKPCB);
2882 while ((inp = inp_next(&inpi)) != NULL)
2887 inp_inpcbtosocket(struct inpcb *inp)
2890 INP_WLOCK_ASSERT(inp);
2891 return (inp->inp_socket);
2895 inp_inpcbtotcpcb(struct inpcb *inp)
2898 INP_WLOCK_ASSERT(inp);
2899 return ((struct tcpcb *)inp->inp_ppcb);
2903 inp_ip_tos_get(const struct inpcb *inp)
2906 return (inp->inp_ip_tos);
2910 inp_ip_tos_set(struct inpcb *inp, int val)
2913 inp->inp_ip_tos = val;
2917 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2918 uint32_t *faddr, uint16_t *fp)
2921 INP_LOCK_ASSERT(inp);
2922 *laddr = inp->inp_laddr.s_addr;
2923 *faddr = inp->inp_faddr.s_addr;
2924 *lp = inp->inp_lport;
2925 *fp = inp->inp_fport;
2929 so_sotoinpcb(struct socket *so)
2932 return (sotoinpcb(so));
2936 * Create an external-format (``xinpcb'') structure using the information in
2937 * the kernel-format in_pcb structure pointed to by inp. This is done to
2938 * reduce the spew of irrelevant information over this interface, to isolate
2939 * user code from changes in the kernel structure, and potentially to provide
2940 * information-hiding if we decide that some of this information should be
2941 * hidden from users.
2944 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2947 bzero(xi, sizeof(*xi));
2948 xi->xi_len = sizeof(struct xinpcb);
2949 if (inp->inp_socket)
2950 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2951 bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2952 xi->inp_gencnt = inp->inp_gencnt;
2953 xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2954 xi->inp_flow = inp->inp_flow;
2955 xi->inp_flowid = inp->inp_flowid;
2956 xi->inp_flowtype = inp->inp_flowtype;
2957 xi->inp_flags = inp->inp_flags;
2958 xi->inp_flags2 = inp->inp_flags2;
2959 xi->in6p_cksum = inp->in6p_cksum;
2960 xi->in6p_hops = inp->in6p_hops;
2961 xi->inp_ip_tos = inp->inp_ip_tos;
2962 xi->inp_vflag = inp->inp_vflag;
2963 xi->inp_ip_ttl = inp->inp_ip_ttl;
2964 xi->inp_ip_p = inp->inp_ip_p;
2965 xi->inp_ip_minttl = inp->inp_ip_minttl;
2969 sysctl_setsockopt(SYSCTL_HANDLER_ARGS, struct inpcbinfo *pcbinfo,
2970 int (*ctloutput_set)(struct inpcb *, struct sockopt *))
2972 struct sockopt sopt;
2973 struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2974 INPLOOKUP_WLOCKPCB);
2976 struct sockopt_parameters *params;
2981 if (req->oldptr != NULL || req->oldlen != 0)
2983 if (req->newptr == NULL)
2985 if (req->newlen > sizeof(buf))
2987 error = SYSCTL_IN(req, buf, req->newlen);
2990 if (req->newlen < sizeof(struct sockopt_parameters))
2992 params = (struct sockopt_parameters *)buf;
2993 sopt.sopt_level = params->sop_level;
2994 sopt.sopt_name = params->sop_optname;
2995 sopt.sopt_dir = SOPT_SET;
2996 sopt.sopt_val = params->sop_optval;
2997 sopt.sopt_valsize = req->newlen - sizeof(struct sockopt_parameters);
2998 sopt.sopt_td = NULL;
3000 if (params->sop_inc.inc_flags & INC_ISIPV6) {
3001 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_laddr))
3002 params->sop_inc.inc6_laddr.s6_addr16[1] =
3003 htons(params->sop_inc.inc6_zoneid & 0xffff);
3004 if (IN6_IS_SCOPE_LINKLOCAL(¶ms->sop_inc.inc6_faddr))
3005 params->sop_inc.inc6_faddr.s6_addr16[1] =
3006 htons(params->sop_inc.inc6_zoneid & 0xffff);
3009 if (params->sop_inc.inc_lport != htons(0)) {
3010 if (params->sop_inc.inc_fport == htons(0))
3011 inpi.hash = INP_PCBHASH_WILD(params->sop_inc.inc_lport,
3012 pcbinfo->ipi_hashmask);
3015 if (params->sop_inc.inc_flags & INC_ISIPV6)
3016 inpi.hash = INP6_PCBHASH(
3017 ¶ms->sop_inc.inc6_faddr,
3018 params->sop_inc.inc_lport,
3019 params->sop_inc.inc_fport,
3020 pcbinfo->ipi_hashmask);
3023 inpi.hash = INP_PCBHASH(
3024 ¶ms->sop_inc.inc_faddr,
3025 params->sop_inc.inc_lport,
3026 params->sop_inc.inc_fport,
3027 pcbinfo->ipi_hashmask);
3029 while ((inp = inp_next(&inpi)) != NULL)
3030 if (inp->inp_gencnt == params->sop_id) {
3031 if (inp->inp_flags & INP_DROPPED) {
3033 return (ECONNRESET);
3035 so = inp->inp_socket;
3036 KASSERT(so != NULL, ("inp_socket == NULL"));
3038 error = (*ctloutput_set)(inp, &sopt);
3049 db_print_indent(int indent)
3053 for (i = 0; i < indent; i++)
3058 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3060 char faddr_str[48], laddr_str[48];
3062 db_print_indent(indent);
3063 db_printf("%s at %p\n", name, inc);
3068 if (inc->inc_flags & INC_ISIPV6) {
3070 ip6_sprintf(laddr_str, &inc->inc6_laddr);
3071 ip6_sprintf(faddr_str, &inc->inc6_faddr);
3076 inet_ntoa_r(inc->inc_laddr, laddr_str);
3077 inet_ntoa_r(inc->inc_faddr, faddr_str);
3079 db_print_indent(indent);
3080 db_printf("inc_laddr %s inc_lport %u\n", laddr_str,
3081 ntohs(inc->inc_lport));
3082 db_print_indent(indent);
3083 db_printf("inc_faddr %s inc_fport %u\n", faddr_str,
3084 ntohs(inc->inc_fport));
3088 db_print_inpflags(int inp_flags)
3093 if (inp_flags & INP_RECVOPTS) {
3094 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3097 if (inp_flags & INP_RECVRETOPTS) {
3098 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3101 if (inp_flags & INP_RECVDSTADDR) {
3102 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3105 if (inp_flags & INP_ORIGDSTADDR) {
3106 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3109 if (inp_flags & INP_HDRINCL) {
3110 db_printf("%sINP_HDRINCL", comma ? ", " : "");
3113 if (inp_flags & INP_HIGHPORT) {
3114 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3117 if (inp_flags & INP_LOWPORT) {
3118 db_printf("%sINP_LOWPORT", comma ? ", " : "");
3121 if (inp_flags & INP_ANONPORT) {
3122 db_printf("%sINP_ANONPORT", comma ? ", " : "");
3125 if (inp_flags & INP_RECVIF) {
3126 db_printf("%sINP_RECVIF", comma ? ", " : "");
3129 if (inp_flags & INP_MTUDISC) {
3130 db_printf("%sINP_MTUDISC", comma ? ", " : "");
3133 if (inp_flags & INP_RECVTTL) {
3134 db_printf("%sINP_RECVTTL", comma ? ", " : "");
3137 if (inp_flags & INP_DONTFRAG) {
3138 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3141 if (inp_flags & INP_RECVTOS) {
3142 db_printf("%sINP_RECVTOS", comma ? ", " : "");
3145 if (inp_flags & IN6P_IPV6_V6ONLY) {
3146 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3149 if (inp_flags & IN6P_PKTINFO) {
3150 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3153 if (inp_flags & IN6P_HOPLIMIT) {
3154 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3157 if (inp_flags & IN6P_HOPOPTS) {
3158 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3161 if (inp_flags & IN6P_DSTOPTS) {
3162 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3165 if (inp_flags & IN6P_RTHDR) {
3166 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3169 if (inp_flags & IN6P_RTHDRDSTOPTS) {
3170 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3173 if (inp_flags & IN6P_TCLASS) {
3174 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3177 if (inp_flags & IN6P_AUTOFLOWLABEL) {
3178 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3181 if (inp_flags & INP_ONESBCAST) {
3182 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3185 if (inp_flags & INP_DROPPED) {
3186 db_printf("%sINP_DROPPED", comma ? ", " : "");
3189 if (inp_flags & INP_SOCKREF) {
3190 db_printf("%sINP_SOCKREF", comma ? ", " : "");
3193 if (inp_flags & IN6P_RFC2292) {
3194 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3197 if (inp_flags & IN6P_MTU) {
3198 db_printf("IN6P_MTU%s", comma ? ", " : "");
3204 db_print_inpvflag(u_char inp_vflag)
3209 if (inp_vflag & INP_IPV4) {
3210 db_printf("%sINP_IPV4", comma ? ", " : "");
3213 if (inp_vflag & INP_IPV6) {
3214 db_printf("%sINP_IPV6", comma ? ", " : "");
3217 if (inp_vflag & INP_IPV6PROTO) {
3218 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3224 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3227 db_print_indent(indent);
3228 db_printf("%s at %p\n", name, inp);
3232 db_print_indent(indent);
3233 db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3235 db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3237 db_print_indent(indent);
3238 db_printf("inp_ppcb: %p inp_pcbinfo: %p inp_socket: %p\n",
3239 inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3241 db_print_indent(indent);
3242 db_printf("inp_label: %p inp_flags: 0x%x (",
3243 inp->inp_label, inp->inp_flags);
3244 db_print_inpflags(inp->inp_flags);
3247 db_print_indent(indent);
3248 db_printf("inp_sp: %p inp_vflag: 0x%x (", inp->inp_sp,
3250 db_print_inpvflag(inp->inp_vflag);
3253 db_print_indent(indent);
3254 db_printf("inp_ip_ttl: %d inp_ip_p: %d inp_ip_minttl: %d\n",
3255 inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3257 db_print_indent(indent);
3259 if (inp->inp_vflag & INP_IPV6) {
3260 db_printf("in6p_options: %p in6p_outputopts: %p "
3261 "in6p_moptions: %p\n", inp->in6p_options,
3262 inp->in6p_outputopts, inp->in6p_moptions);
3263 db_printf("in6p_icmp6filt: %p in6p_cksum %d "
3264 "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3269 db_printf("inp_ip_tos: %d inp_ip_options: %p "
3270 "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3271 inp->inp_options, inp->inp_moptions);
3274 db_print_indent(indent);
3275 db_printf("inp_phd: %p inp_gencnt: %ju\n", inp->inp_phd,
3276 (uintmax_t)inp->inp_gencnt);
3279 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3284 db_printf("usage: show inpcb <addr>\n");
3287 inp = (struct inpcb *)addr;
3289 db_print_inpcb(inp, "inpcb", 0);
3295 * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3299 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3301 union if_snd_tag_modify_params params = {
3302 .rate_limit.max_rate = max_pacing_rate,
3303 .rate_limit.flags = M_NOWAIT,
3305 struct m_snd_tag *mst;
3308 mst = inp->inp_snd_tag;
3312 if (mst->sw->snd_tag_modify == NULL) {
3315 error = mst->sw->snd_tag_modify(mst, ¶ms);
3321 * Query existing TX rate limit based on the existing
3322 * "inp->inp_snd_tag", if any.
3325 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3327 union if_snd_tag_query_params params = { };
3328 struct m_snd_tag *mst;
3331 mst = inp->inp_snd_tag;
3335 if (mst->sw->snd_tag_query == NULL) {
3338 error = mst->sw->snd_tag_query(mst, ¶ms);
3339 if (error == 0 && p_max_pacing_rate != NULL)
3340 *p_max_pacing_rate = params.rate_limit.max_rate;
3346 * Query existing TX queue level based on the existing
3347 * "inp->inp_snd_tag", if any.
3350 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3352 union if_snd_tag_query_params params = { };
3353 struct m_snd_tag *mst;
3356 mst = inp->inp_snd_tag;
3360 if (mst->sw->snd_tag_query == NULL)
3361 return (EOPNOTSUPP);
3363 error = mst->sw->snd_tag_query(mst, ¶ms);
3364 if (error == 0 && p_txqueue_level != NULL)
3365 *p_txqueue_level = params.rate_limit.queue_level;
3370 * Allocate a new TX rate limit send tag from the network interface
3371 * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3374 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3375 uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
3378 union if_snd_tag_alloc_params params = {
3379 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3380 IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3381 .rate_limit.hdr.flowid = flowid,
3382 .rate_limit.hdr.flowtype = flowtype,
3383 .rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3384 .rate_limit.max_rate = max_pacing_rate,
3385 .rate_limit.flags = M_NOWAIT,
3389 INP_WLOCK_ASSERT(inp);
3392 * If there is already a send tag, or the INP is being torn
3393 * down, allocating a new send tag is not allowed. Else send
3396 if (*st != NULL || (inp->inp_flags & INP_DROPPED) != 0)
3399 error = m_snd_tag_alloc(ifp, ¶ms, st);
3402 counter_u64_add(rate_limit_set_ok, 1);
3403 counter_u64_add(rate_limit_active, 1);
3404 } else if (error != EOPNOTSUPP)
3405 counter_u64_add(rate_limit_alloc_fail, 1);
3411 in_pcbdetach_tag(struct m_snd_tag *mst)
3414 m_snd_tag_rele(mst);
3416 counter_u64_add(rate_limit_active, -1);
3421 * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3425 in_pcbdetach_txrtlmt(struct inpcb *inp)
3427 struct m_snd_tag *mst;
3429 INP_WLOCK_ASSERT(inp);
3431 mst = inp->inp_snd_tag;
3432 inp->inp_snd_tag = NULL;
3437 m_snd_tag_rele(mst);
3439 counter_u64_add(rate_limit_active, -1);
3444 in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
3449 * If the existing send tag is for the wrong interface due to
3450 * a route change, first drop the existing tag. Set the
3451 * CHANGED flag so that we will keep trying to allocate a new
3452 * tag if we fail to allocate one this time.
3454 if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
3455 in_pcbdetach_txrtlmt(inp);
3456 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3460 * NOTE: When attaching to a network interface a reference is
3461 * made to ensure the network interface doesn't go away until
3462 * all ratelimit connections are gone. The network interface
3463 * pointers compared below represent valid network interfaces,
3464 * except when comparing towards NULL.
3466 if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3468 } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3469 if (inp->inp_snd_tag != NULL)
3470 in_pcbdetach_txrtlmt(inp);
3472 } else if (inp->inp_snd_tag == NULL) {
3474 * In order to utilize packet pacing with RSS, we need
3475 * to wait until there is a valid RSS hash before we
3478 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3481 error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3482 mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
3485 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3487 if (error == 0 || error == EOPNOTSUPP)
3488 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3494 * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3495 * is set in the fast path and will attach/detach/modify the TX rate
3496 * limit send tag based on the socket's so_max_pacing_rate value.
3499 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3501 struct socket *socket;
3502 uint32_t max_pacing_rate;
3508 socket = inp->inp_socket;
3512 if (!INP_WLOCKED(inp)) {
3514 * NOTE: If the write locking fails, we need to bail
3515 * out and use the non-ratelimited ring for the
3516 * transmit until there is a new chance to get the
3519 if (!INP_TRY_UPGRADE(inp))
3527 * NOTE: The so_max_pacing_rate value is read unlocked,
3528 * because atomic updates are not required since the variable
3529 * is checked at every mbuf we send. It is assumed that the
3530 * variable read itself will be atomic.
3532 max_pacing_rate = socket->so_max_pacing_rate;
3534 in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3541 * Track route changes for TX rate limiting.
3544 in_pcboutput_eagain(struct inpcb *inp)
3551 if (inp->inp_snd_tag == NULL)
3554 if (!INP_WLOCKED(inp)) {
3556 * NOTE: If the write locking fails, we need to bail
3557 * out and use the non-ratelimited ring for the
3558 * transmit until there is a new chance to get the
3561 if (!INP_TRY_UPGRADE(inp))
3568 /* detach rate limiting */
3569 in_pcbdetach_txrtlmt(inp);
3571 /* make sure new mbuf send tag allocation is made */
3572 inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3582 rate_limit_new = counter_u64_alloc(M_WAITOK);
3583 rate_limit_chg = counter_u64_alloc(M_WAITOK);
3584 rate_limit_active = counter_u64_alloc(M_WAITOK);
3585 rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
3586 rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
3589 SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3591 #endif /* RATELIMIT */