xref: /freebsd/sys/netinet/in_pcb.c (revision c782ea8bb50bf49f5da20da66417952b0e77472e)
1c398230bSWarner Losh /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
42469dd60SGarrett Wollman  * Copyright (c) 1982, 1986, 1991, 1993, 1995
5497057eeSRobert Watson  *	The Regents of the University of California.
6111d57a6SRobert Watson  * Copyright (c) 2007-2009 Robert N. M. Watson
779bdc6e5SRobert Watson  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8497057eeSRobert Watson  * All rights reserved.
9df8bae1dSRodney W. Grimes  *
1079bdc6e5SRobert Watson  * Portions of this software were developed by Robert N. M. Watson under
1179bdc6e5SRobert Watson  * contract to Juniper Networks, Inc.
1279bdc6e5SRobert Watson  *
13df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
14df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
15df8bae1dSRodney W. Grimes  * are met:
16df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
17df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
18df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
19df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
20df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
21fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
22df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
23df8bae1dSRodney W. Grimes  *    without specific prior written permission.
24df8bae1dSRodney W. Grimes  *
25df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
36df8bae1dSRodney W. Grimes  *
372469dd60SGarrett Wollman  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
38df8bae1dSRodney W. Grimes  */
39df8bae1dSRodney W. Grimes 
404b421e2dSMike Silbersack #include <sys/cdefs.h>
414b421e2dSMike Silbersack __FBSDID("$FreeBSD$");
424b421e2dSMike Silbersack 
43497057eeSRobert Watson #include "opt_ddb.h"
446a800098SYoshinobu Inoue #include "opt_ipsec.h"
45efc76f72SBjoern A. Zeeb #include "opt_inet.h"
46cfa1ca9dSYoshinobu Inoue #include "opt_inet6.h"
47f3e7afe2SHans Petter Selasky #include "opt_ratelimit.h"
4852cd27cbSRobert Watson #include "opt_pcbgroup.h"
490c325f53SAlexander V. Chernikov #include "opt_route.h"
507527624eSRobert Watson #include "opt_rss.h"
51cfa1ca9dSYoshinobu Inoue 
52df8bae1dSRodney W. Grimes #include <sys/param.h>
53df8bae1dSRodney W. Grimes #include <sys/systm.h>
54cc0a3c8cSAndrey V. Elsukov #include <sys/lock.h>
55df8bae1dSRodney W. Grimes #include <sys/malloc.h>
56df8bae1dSRodney W. Grimes #include <sys/mbuf.h>
57aae49dd3SBjoern A. Zeeb #include <sys/callout.h>
58ea8d1492SAlexander V. Chernikov #include <sys/eventhandler.h>
59cfa1ca9dSYoshinobu Inoue #include <sys/domain.h>
60df8bae1dSRodney W. Grimes #include <sys/protosw.h>
61cc0a3c8cSAndrey V. Elsukov #include <sys/rmlock.h>
623ee9c3c4SRandall Stewart #include <sys/smp.h>
63df8bae1dSRodney W. Grimes #include <sys/socket.h>
64df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
65f3e7afe2SHans Petter Selasky #include <sys/sockio.h>
66acd3428bSRobert Watson #include <sys/priv.h>
67df8bae1dSRodney W. Grimes #include <sys/proc.h>
6879bdc6e5SRobert Watson #include <sys/refcount.h>
6975c13541SPoul-Henning Kamp #include <sys/jail.h>
70101f9fc8SPeter Wemm #include <sys/kernel.h>
71101f9fc8SPeter Wemm #include <sys/sysctl.h>
728781d8e9SBruce Evans 
73497057eeSRobert Watson #ifdef DDB
74497057eeSRobert Watson #include <ddb/ddb.h>
75497057eeSRobert Watson #endif
76497057eeSRobert Watson 
7769c2d429SJeff Roberson #include <vm/uma.h>
78a034518aSAndrew Gallatin #include <vm/vm.h>
79df8bae1dSRodney W. Grimes 
80df8bae1dSRodney W. Grimes #include <net/if.h>
8176039bc8SGleb Smirnoff #include <net/if_var.h>
82cfa1ca9dSYoshinobu Inoue #include <net/if_types.h>
836d768226SGeorge V. Neville-Neil #include <net/if_llatbl.h>
84df8bae1dSRodney W. Grimes #include <net/route.h>
85b2bdc62aSAdrian Chadd #include <net/rss_config.h>
86530c0060SRobert Watson #include <net/vnet.h>
87df8bae1dSRodney W. Grimes 
8867107f45SBjoern A. Zeeb #if defined(INET) || defined(INET6)
89df8bae1dSRodney W. Grimes #include <netinet/in.h>
90df8bae1dSRodney W. Grimes #include <netinet/in_pcb.h>
9159854ecfSHans Petter Selasky #ifdef INET
9259854ecfSHans Petter Selasky #include <netinet/in_var.h>
939ac7c6cfSAlexander V. Chernikov #include <netinet/in_fib.h>
9459854ecfSHans Petter Selasky #endif
95df8bae1dSRodney W. Grimes #include <netinet/ip_var.h>
96340c35deSJonathan Lemon #include <netinet/tcp_var.h>
973ee9c3c4SRandall Stewart #ifdef TCPHPTS
983ee9c3c4SRandall Stewart #include <netinet/tcp_hpts.h>
993ee9c3c4SRandall Stewart #endif
1005f311da2SMike Silbersack #include <netinet/udp.h>
1015f311da2SMike Silbersack #include <netinet/udp_var.h>
102cfa1ca9dSYoshinobu Inoue #ifdef INET6
103cfa1ca9dSYoshinobu Inoue #include <netinet/ip6.h>
104efc76f72SBjoern A. Zeeb #include <netinet6/in6_pcb.h>
10567107f45SBjoern A. Zeeb #include <netinet6/in6_var.h>
10667107f45SBjoern A. Zeeb #include <netinet6/ip6_var.h>
107cfa1ca9dSYoshinobu Inoue #endif /* INET6 */
1089ac7c6cfSAlexander V. Chernikov #include <net/route/nhop.h>
10959854ecfSHans Petter Selasky #endif
110cfa1ca9dSYoshinobu Inoue 
111fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
112b9234fafSSam Leffler 
113aed55708SRobert Watson #include <security/mac/mac_framework.h>
114aed55708SRobert Watson 
1151a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMIN	8
1161a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMAX	256
1171a43cff9SSean Bruno 
118aae49dd3SBjoern A. Zeeb static struct callout	ipport_tick_callout;
119aae49dd3SBjoern A. Zeeb 
120101f9fc8SPeter Wemm /*
121101f9fc8SPeter Wemm  * These configure the range of local port addresses assigned to
122101f9fc8SPeter Wemm  * "unspecified" outgoing connections/packets/whatever.
123101f9fc8SPeter Wemm  */
124eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
125eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
126eddfbb76SRobert Watson VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
127eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
128eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
129eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
130101f9fc8SPeter Wemm 
131b0d22693SCrist J. Clark /*
132b0d22693SCrist J. Clark  * Reserved ports accessible only to root. There are significant
133b0d22693SCrist J. Clark  * security considerations that must be accounted for when changing these,
134b0d22693SCrist J. Clark  * but the security benefits can be great. Please be careful.
135b0d22693SCrist J. Clark  */
136eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
137eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedlow);
138b0d22693SCrist J. Clark 
1395f311da2SMike Silbersack /* Variables dealing with random ephemeral port allocation. */
140eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomized) = 1;	/* user controlled via sysctl */
141eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomcps) = 10;	/* user controlled via sysctl */
142eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomtime) = 45;	/* user controlled via sysctl */
143eddfbb76SRobert Watson VNET_DEFINE(int, ipport_stoprandom);		/* toggled by ipport_tick */
144eddfbb76SRobert Watson VNET_DEFINE(int, ipport_tcpallocs);
1455f901c92SAndrew Turner VNET_DEFINE_STATIC(int, ipport_tcplastcount);
146eddfbb76SRobert Watson 
1471e77c105SRobert Watson #define	V_ipport_tcplastcount		VNET(ipport_tcplastcount)
1486ac48b74SMike Silbersack 
149d2025bd0SBjoern A. Zeeb static void	in_pcbremlists(struct inpcb *inp);
150d2025bd0SBjoern A. Zeeb #ifdef INET
151fa046d87SRobert Watson static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
152fa046d87SRobert Watson 			    struct in_addr faddr, u_int fport_arg,
153fa046d87SRobert Watson 			    struct in_addr laddr, u_int lport_arg,
154a034518aSAndrew Gallatin 			    int lookupflags, struct ifnet *ifp,
155a034518aSAndrew Gallatin 			    uint8_t numa_domain);
15667107f45SBjoern A. Zeeb 
157bbd42ad0SPeter Wemm #define RANGECHK(var, min, max) \
158bbd42ad0SPeter Wemm 	if ((var) < (min)) { (var) = (min); } \
159bbd42ad0SPeter Wemm 	else if ((var) > (max)) { (var) = (max); }
160bbd42ad0SPeter Wemm 
161bbd42ad0SPeter Wemm static int
16282d9ae4eSPoul-Henning Kamp sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
163bbd42ad0SPeter Wemm {
16430a4ab08SBruce Evans 	int error;
16530a4ab08SBruce Evans 
166f6dfe47aSMarko Zec 	error = sysctl_handle_int(oidp, arg1, arg2, req);
16730a4ab08SBruce Evans 	if (error == 0) {
168603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
169603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
170603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
171603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
172603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
173603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
174bbd42ad0SPeter Wemm 	}
17530a4ab08SBruce Evans 	return (error);
176bbd42ad0SPeter Wemm }
177bbd42ad0SPeter Wemm 
178bbd42ad0SPeter Wemm #undef RANGECHK
179bbd42ad0SPeter Wemm 
1807029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
1817029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1826472ac3dSEd Schouten     "IP Ports");
18333b3ac06SPeter Wemm 
1846df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
1857029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1867029da5cSPawel Biernacki     &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
1877029da5cSPawel Biernacki     "");
1886df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
1897029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1907029da5cSPawel Biernacki     &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
1917029da5cSPawel Biernacki     "");
1926df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
1937029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1947029da5cSPawel Biernacki     &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
1957029da5cSPawel Biernacki     "");
1966df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
1977029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1987029da5cSPawel Biernacki     &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
1997029da5cSPawel Biernacki     "");
2006df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
2017029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
2027029da5cSPawel Biernacki     &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
2037029da5cSPawel Biernacki     "");
2046df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
2057029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
2067029da5cSPawel Biernacki     &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
2077029da5cSPawel Biernacki     "");
2086df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
2096df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
2106df8a710SGleb Smirnoff 	&VNET_NAME(ipport_reservedhigh), 0, "");
2116df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
212eddfbb76SRobert Watson 	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
2136df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
2146df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
215eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
2166df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
2176df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
218eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
2196ee79c59SMaxim Konovalov 	"allocations before switching to a sequental one");
2206df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
2216df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
222eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomtime), 0,
2238b615593SMarko Zec 	"Minimum time to keep sequental port "
2246ee79c59SMaxim Konovalov 	"allocation before switching to a random one");
22520abea66SRandall Stewart 
22620abea66SRandall Stewart #ifdef RATELIMIT
2271a714ff2SRandall Stewart counter_u64_t rate_limit_new;
2281a714ff2SRandall Stewart counter_u64_t rate_limit_chg;
22920abea66SRandall Stewart counter_u64_t rate_limit_active;
23020abea66SRandall Stewart counter_u64_t rate_limit_alloc_fail;
23120abea66SRandall Stewart counter_u64_t rate_limit_set_ok;
23220abea66SRandall Stewart 
2337029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
23420abea66SRandall Stewart     "IP Rate Limiting");
23520abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
23620abea66SRandall Stewart     &rate_limit_active, "Active rate limited connections");
23720abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
23820abea66SRandall Stewart    &rate_limit_alloc_fail, "Rate limited connection failures");
23920abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
24020abea66SRandall Stewart    &rate_limit_set_ok, "Rate limited setting succeeded");
2411a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
2421a714ff2SRandall Stewart    &rate_limit_new, "Total Rate limit new attempts");
2431a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
2441a714ff2SRandall Stewart    &rate_limit_chg, "Total Rate limited change attempts");
2451a714ff2SRandall Stewart 
24620abea66SRandall Stewart #endif /* RATELIMIT */
24720abea66SRandall Stewart 
24883e521ecSBjoern A. Zeeb #endif /* INET */
2490312fbe9SPoul-Henning Kamp 
250c3229e05SDavid Greenman /*
251c3229e05SDavid Greenman  * in_pcb.c: manage the Protocol Control Blocks.
252c3229e05SDavid Greenman  *
253de35559fSRobert Watson  * NOTE: It is assumed that most of these functions will be called with
254de35559fSRobert Watson  * the pcbinfo lock held, and often, the inpcb lock held, as these utility
255de35559fSRobert Watson  * functions often modify hash chains or addresses in pcbs.
256c3229e05SDavid Greenman  */
257c3229e05SDavid Greenman 
2581a43cff9SSean Bruno static struct inpcblbgroup *
2591a43cff9SSean Bruno in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, u_char vflag,
260a034518aSAndrew Gallatin     uint16_t port, const union in_dependaddr *addr, int size,
261a034518aSAndrew Gallatin     uint8_t numa_domain)
2621a43cff9SSean Bruno {
2631a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2641a43cff9SSean Bruno 	size_t bytes;
2651a43cff9SSean Bruno 
2661a43cff9SSean Bruno 	bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
2671a43cff9SSean Bruno 	grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
2681a43cff9SSean Bruno 	if (!grp)
2691a43cff9SSean Bruno 		return (NULL);
2701a43cff9SSean Bruno 	grp->il_vflag = vflag;
2711a43cff9SSean Bruno 	grp->il_lport = port;
272a034518aSAndrew Gallatin 	grp->il_numa_domain = numa_domain;
2731a43cff9SSean Bruno 	grp->il_dependladdr = *addr;
2741a43cff9SSean Bruno 	grp->il_inpsiz = size;
27554af3d0dSMark Johnston 	CK_LIST_INSERT_HEAD(hdr, grp, il_list);
2761a43cff9SSean Bruno 	return (grp);
2771a43cff9SSean Bruno }
2781a43cff9SSean Bruno 
2791a43cff9SSean Bruno static void
28054af3d0dSMark Johnston in_pcblbgroup_free_deferred(epoch_context_t ctx)
28154af3d0dSMark Johnston {
28254af3d0dSMark Johnston 	struct inpcblbgroup *grp;
28354af3d0dSMark Johnston 
28454af3d0dSMark Johnston 	grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
28554af3d0dSMark Johnston 	free(grp, M_PCB);
28654af3d0dSMark Johnston }
28754af3d0dSMark Johnston 
28854af3d0dSMark Johnston static void
2891a43cff9SSean Bruno in_pcblbgroup_free(struct inpcblbgroup *grp)
2901a43cff9SSean Bruno {
2911a43cff9SSean Bruno 
29254af3d0dSMark Johnston 	CK_LIST_REMOVE(grp, il_list);
2932a4bd982SGleb Smirnoff 	NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
2941a43cff9SSean Bruno }
2951a43cff9SSean Bruno 
2961a43cff9SSean Bruno static struct inpcblbgroup *
2971a43cff9SSean Bruno in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
2981a43cff9SSean Bruno     struct inpcblbgroup *old_grp, int size)
2991a43cff9SSean Bruno {
3001a43cff9SSean Bruno 	struct inpcblbgroup *grp;
3011a43cff9SSean Bruno 	int i;
3021a43cff9SSean Bruno 
3031a43cff9SSean Bruno 	grp = in_pcblbgroup_alloc(hdr, old_grp->il_vflag,
304a034518aSAndrew Gallatin 	    old_grp->il_lport, &old_grp->il_dependladdr, size,
305a034518aSAndrew Gallatin 	    old_grp->il_numa_domain);
30679ee680bSMark Johnston 	if (grp == NULL)
3071a43cff9SSean Bruno 		return (NULL);
3081a43cff9SSean Bruno 
3091a43cff9SSean Bruno 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
3101a43cff9SSean Bruno 	    ("invalid new local group size %d and old local group count %d",
3111a43cff9SSean Bruno 	     grp->il_inpsiz, old_grp->il_inpcnt));
3121a43cff9SSean Bruno 
3131a43cff9SSean Bruno 	for (i = 0; i < old_grp->il_inpcnt; ++i)
3141a43cff9SSean Bruno 		grp->il_inp[i] = old_grp->il_inp[i];
3151a43cff9SSean Bruno 	grp->il_inpcnt = old_grp->il_inpcnt;
3161a43cff9SSean Bruno 	in_pcblbgroup_free(old_grp);
3171a43cff9SSean Bruno 	return (grp);
3181a43cff9SSean Bruno }
3191a43cff9SSean Bruno 
3201a43cff9SSean Bruno /*
3211a43cff9SSean Bruno  * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
3221a43cff9SSean Bruno  * and shrink group if possible.
3231a43cff9SSean Bruno  */
3241a43cff9SSean Bruno static void
3251a43cff9SSean Bruno in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
3261a43cff9SSean Bruno     int i)
3271a43cff9SSean Bruno {
32879ee680bSMark Johnston 	struct inpcblbgroup *grp, *new_grp;
3291a43cff9SSean Bruno 
33079ee680bSMark Johnston 	grp = *grpp;
3311a43cff9SSean Bruno 	for (; i + 1 < grp->il_inpcnt; ++i)
3321a43cff9SSean Bruno 		grp->il_inp[i] = grp->il_inp[i + 1];
3331a43cff9SSean Bruno 	grp->il_inpcnt--;
3341a43cff9SSean Bruno 
3351a43cff9SSean Bruno 	if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
33679ee680bSMark Johnston 	    grp->il_inpcnt <= grp->il_inpsiz / 4) {
3371a43cff9SSean Bruno 		/* Shrink this group. */
33879ee680bSMark Johnston 		new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
33979ee680bSMark Johnston 		if (new_grp != NULL)
3401a43cff9SSean Bruno 			*grpp = new_grp;
3411a43cff9SSean Bruno 	}
3421a43cff9SSean Bruno }
3431a43cff9SSean Bruno 
3441a43cff9SSean Bruno /*
3451a43cff9SSean Bruno  * Add PCB to load balance group for SO_REUSEPORT_LB option.
3461a43cff9SSean Bruno  */
3471a43cff9SSean Bruno static int
348a034518aSAndrew Gallatin in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
3491a43cff9SSean Bruno {
350a7026c7fSMark Johnston 	const static struct timeval interval = { 60, 0 };
351a7026c7fSMark Johnston 	static struct timeval lastprint;
3521a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
3531a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
3541a43cff9SSean Bruno 	struct inpcblbgroup *grp;
35579ee680bSMark Johnston 	uint32_t idx;
3561a43cff9SSean Bruno 
3571a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
3581a43cff9SSean Bruno 
3591a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
3601a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
3611a43cff9SSean Bruno 
3621a43cff9SSean Bruno 	/*
3631a43cff9SSean Bruno 	 * Don't allow jailed socket to join local group.
3641a43cff9SSean Bruno 	 */
36579ee680bSMark Johnston 	if (inp->inp_socket != NULL && jailed(inp->inp_socket->so_cred))
3661a43cff9SSean Bruno 		return (0);
3671a43cff9SSean Bruno 
3681a43cff9SSean Bruno #ifdef INET6
3691a43cff9SSean Bruno 	/*
3701a43cff9SSean Bruno 	 * Don't allow IPv4 mapped INET6 wild socket.
3711a43cff9SSean Bruno 	 */
3721a43cff9SSean Bruno 	if ((inp->inp_vflag & INP_IPV4) &&
3731a43cff9SSean Bruno 	    inp->inp_laddr.s_addr == INADDR_ANY &&
3741a43cff9SSean Bruno 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
3751a43cff9SSean Bruno 		return (0);
3761a43cff9SSean Bruno 	}
3771a43cff9SSean Bruno #endif
3781a43cff9SSean Bruno 
3799d2877fcSMark Johnston 	idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
38079ee680bSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
38154af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
3821a43cff9SSean Bruno 		if (grp->il_vflag == inp->inp_vflag &&
3831a43cff9SSean Bruno 		    grp->il_lport == inp->inp_lport &&
384a034518aSAndrew Gallatin 		    grp->il_numa_domain == numa_domain &&
3851a43cff9SSean Bruno 		    memcmp(&grp->il_dependladdr,
3861a43cff9SSean Bruno 		    &inp->inp_inc.inc_ie.ie_dependladdr,
38779ee680bSMark Johnston 		    sizeof(grp->il_dependladdr)) == 0)
3881a43cff9SSean Bruno 			break;
3891a43cff9SSean Bruno 	}
3901a43cff9SSean Bruno 	if (grp == NULL) {
3911a43cff9SSean Bruno 		/* Create new load balance group. */
3921a43cff9SSean Bruno 		grp = in_pcblbgroup_alloc(hdr, inp->inp_vflag,
3931a43cff9SSean Bruno 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
394a034518aSAndrew Gallatin 		    INPCBLBGROUP_SIZMIN, numa_domain);
39579ee680bSMark Johnston 		if (grp == NULL)
3961a43cff9SSean Bruno 			return (ENOBUFS);
3971a43cff9SSean Bruno 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
3981a43cff9SSean Bruno 		if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
399a7026c7fSMark Johnston 			if (ratecheck(&lastprint, &interval))
4001a43cff9SSean Bruno 				printf("lb group port %d, limit reached\n",
4011a43cff9SSean Bruno 				    ntohs(grp->il_lport));
4021a43cff9SSean Bruno 			return (0);
4031a43cff9SSean Bruno 		}
4041a43cff9SSean Bruno 
4051a43cff9SSean Bruno 		/* Expand this local group. */
4061a43cff9SSean Bruno 		grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
40779ee680bSMark Johnston 		if (grp == NULL)
4081a43cff9SSean Bruno 			return (ENOBUFS);
4091a43cff9SSean Bruno 	}
4101a43cff9SSean Bruno 
4111a43cff9SSean Bruno 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
41279ee680bSMark Johnston 	    ("invalid local group size %d and count %d", grp->il_inpsiz,
41379ee680bSMark Johnston 	    grp->il_inpcnt));
4141a43cff9SSean Bruno 
4151a43cff9SSean Bruno 	grp->il_inp[grp->il_inpcnt] = inp;
4161a43cff9SSean Bruno 	grp->il_inpcnt++;
4171a43cff9SSean Bruno 	return (0);
4181a43cff9SSean Bruno }
4191a43cff9SSean Bruno 
4201a43cff9SSean Bruno /*
4211a43cff9SSean Bruno  * Remove PCB from load balance group.
4221a43cff9SSean Bruno  */
4231a43cff9SSean Bruno static void
4241a43cff9SSean Bruno in_pcbremlbgrouphash(struct inpcb *inp)
4251a43cff9SSean Bruno {
4261a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
4271a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
4281a43cff9SSean Bruno 	struct inpcblbgroup *grp;
4291a43cff9SSean Bruno 	int i;
4301a43cff9SSean Bruno 
4311a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
4321a43cff9SSean Bruno 
4331a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
4341a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
4351a43cff9SSean Bruno 
4361a43cff9SSean Bruno 	hdr = &pcbinfo->ipi_lbgrouphashbase[
4379d2877fcSMark Johnston 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
43854af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
4391a43cff9SSean Bruno 		for (i = 0; i < grp->il_inpcnt; ++i) {
4401a43cff9SSean Bruno 			if (grp->il_inp[i] != inp)
4411a43cff9SSean Bruno 				continue;
4421a43cff9SSean Bruno 
4431a43cff9SSean Bruno 			if (grp->il_inpcnt == 1) {
4441a43cff9SSean Bruno 				/* We are the last, free this local group. */
4451a43cff9SSean Bruno 				in_pcblbgroup_free(grp);
4461a43cff9SSean Bruno 			} else {
4471a43cff9SSean Bruno 				/* Pull up inpcbs, shrink group if possible. */
4481a43cff9SSean Bruno 				in_pcblbgroup_reorder(hdr, &grp, i);
4491a43cff9SSean Bruno 			}
4501a43cff9SSean Bruno 			return;
4511a43cff9SSean Bruno 		}
4521a43cff9SSean Bruno 	}
4531a43cff9SSean Bruno }
4541a43cff9SSean Bruno 
455a034518aSAndrew Gallatin int
456a034518aSAndrew Gallatin in_pcblbgroup_numa(struct inpcb *inp, int arg)
457a034518aSAndrew Gallatin {
458a034518aSAndrew Gallatin 	struct inpcbinfo *pcbinfo;
459a034518aSAndrew Gallatin 	struct inpcblbgrouphead *hdr;
460a034518aSAndrew Gallatin 	struct inpcblbgroup *grp;
461a034518aSAndrew Gallatin 	int err, i;
462a034518aSAndrew Gallatin 	uint8_t numa_domain;
463a034518aSAndrew Gallatin 
464a034518aSAndrew Gallatin 	switch (arg) {
465a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_NODOM:
466a034518aSAndrew Gallatin 		numa_domain = M_NODOM;
467a034518aSAndrew Gallatin 		break;
468a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_CURDOM:
469a034518aSAndrew Gallatin 		numa_domain = PCPU_GET(domain);
470a034518aSAndrew Gallatin 		break;
471a034518aSAndrew Gallatin 	default:
472a034518aSAndrew Gallatin 		if (arg < 0 || arg >= vm_ndomains)
473a034518aSAndrew Gallatin 			return (EINVAL);
474a034518aSAndrew Gallatin 		numa_domain = arg;
475a034518aSAndrew Gallatin 	}
476a034518aSAndrew Gallatin 
477a034518aSAndrew Gallatin 	err = 0;
478a034518aSAndrew Gallatin 	pcbinfo = inp->inp_pcbinfo;
479a034518aSAndrew Gallatin 	INP_WLOCK_ASSERT(inp);
480a034518aSAndrew Gallatin 	INP_HASH_WLOCK(pcbinfo);
481a034518aSAndrew Gallatin 	hdr = &pcbinfo->ipi_lbgrouphashbase[
482a034518aSAndrew Gallatin 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
483a034518aSAndrew Gallatin 	CK_LIST_FOREACH(grp, hdr, il_list) {
484a034518aSAndrew Gallatin 		for (i = 0; i < grp->il_inpcnt; ++i) {
485a034518aSAndrew Gallatin 			if (grp->il_inp[i] != inp)
486a034518aSAndrew Gallatin 				continue;
487a034518aSAndrew Gallatin 
488a034518aSAndrew Gallatin 			if (grp->il_numa_domain == numa_domain) {
489a034518aSAndrew Gallatin 				goto abort_with_hash_wlock;
490a034518aSAndrew Gallatin 			}
491a034518aSAndrew Gallatin 
492a034518aSAndrew Gallatin 			/* Remove it from the old group. */
493a034518aSAndrew Gallatin 			in_pcbremlbgrouphash(inp);
494a034518aSAndrew Gallatin 
495a034518aSAndrew Gallatin 			/* Add it to the new group based on numa domain. */
496a034518aSAndrew Gallatin 			in_pcbinslbgrouphash(inp, numa_domain);
497a034518aSAndrew Gallatin 			goto abort_with_hash_wlock;
498a034518aSAndrew Gallatin 		}
499a034518aSAndrew Gallatin 	}
500a034518aSAndrew Gallatin 	err = ENOENT;
501a034518aSAndrew Gallatin abort_with_hash_wlock:
502a034518aSAndrew Gallatin 	INP_HASH_WUNLOCK(pcbinfo);
503a034518aSAndrew Gallatin 	return (err);
504a034518aSAndrew Gallatin }
505a034518aSAndrew Gallatin 
506c3229e05SDavid Greenman /*
507cc487c16SGleb Smirnoff  * Different protocols initialize their inpcbs differently - giving
508cc487c16SGleb Smirnoff  * different name to the lock.  But they all are disposed the same.
509cc487c16SGleb Smirnoff  */
510cc487c16SGleb Smirnoff static void
511cc487c16SGleb Smirnoff inpcb_fini(void *mem, int size)
512cc487c16SGleb Smirnoff {
513cc487c16SGleb Smirnoff 	struct inpcb *inp = mem;
514cc487c16SGleb Smirnoff 
515cc487c16SGleb Smirnoff 	INP_LOCK_DESTROY(inp);
516cc487c16SGleb Smirnoff }
517cc487c16SGleb Smirnoff 
518cc487c16SGleb Smirnoff /*
5199bcd427bSRobert Watson  * Initialize an inpcbinfo -- we should be able to reduce the number of
5209bcd427bSRobert Watson  * arguments in time.
5219bcd427bSRobert Watson  */
5229bcd427bSRobert Watson void
5239bcd427bSRobert Watson in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
5249bcd427bSRobert Watson     struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
525cc487c16SGleb Smirnoff     char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
5269bcd427bSRobert Watson {
5279bcd427bSRobert Watson 
5289d2877fcSMark Johnston 	porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
5299d2877fcSMark Johnston 
5309bcd427bSRobert Watson 	INP_INFO_LOCK_INIT(pcbinfo, name);
531fa046d87SRobert Watson 	INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash");	/* XXXRW: argument? */
532ff9b006dSJulien Charbon 	INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
5339bcd427bSRobert Watson #ifdef VIMAGE
5349bcd427bSRobert Watson 	pcbinfo->ipi_vnet = curvnet;
5359bcd427bSRobert Watson #endif
5369bcd427bSRobert Watson 	pcbinfo->ipi_listhead = listhead;
537b872626dSMatt Macy 	CK_LIST_INIT(pcbinfo->ipi_listhead);
538fa046d87SRobert Watson 	pcbinfo->ipi_count = 0;
5399bcd427bSRobert Watson 	pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
5409bcd427bSRobert Watson 	    &pcbinfo->ipi_hashmask);
5419bcd427bSRobert Watson 	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
5429bcd427bSRobert Watson 	    &pcbinfo->ipi_porthashmask);
5439d2877fcSMark Johnston 	pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
5441a43cff9SSean Bruno 	    &pcbinfo->ipi_lbgrouphashmask);
54552cd27cbSRobert Watson #ifdef PCBGROUP
54652cd27cbSRobert Watson 	in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
54752cd27cbSRobert Watson #endif
5489bcd427bSRobert Watson 	pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
549cc487c16SGleb Smirnoff 	    NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
5509bcd427bSRobert Watson 	uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
5516acd596eSPawel Jakub Dawidek 	uma_zone_set_warning(pcbinfo->ipi_zone,
5526acd596eSPawel Jakub Dawidek 	    "kern.ipc.maxsockets limit reached");
5539bcd427bSRobert Watson }
5549bcd427bSRobert Watson 
5559bcd427bSRobert Watson /*
5569bcd427bSRobert Watson  * Destroy an inpcbinfo.
5579bcd427bSRobert Watson  */
5589bcd427bSRobert Watson void
5599bcd427bSRobert Watson in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
5609bcd427bSRobert Watson {
5619bcd427bSRobert Watson 
562fa046d87SRobert Watson 	KASSERT(pcbinfo->ipi_count == 0,
563fa046d87SRobert Watson 	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
564fa046d87SRobert Watson 
5659bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
5669bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
5679bcd427bSRobert Watson 	    pcbinfo->ipi_porthashmask);
5681a43cff9SSean Bruno 	hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
5691a43cff9SSean Bruno 	    pcbinfo->ipi_lbgrouphashmask);
57052cd27cbSRobert Watson #ifdef PCBGROUP
57152cd27cbSRobert Watson 	in_pcbgroup_destroy(pcbinfo);
57252cd27cbSRobert Watson #endif
5739bcd427bSRobert Watson 	uma_zdestroy(pcbinfo->ipi_zone);
574ff9b006dSJulien Charbon 	INP_LIST_LOCK_DESTROY(pcbinfo);
575fa046d87SRobert Watson 	INP_HASH_LOCK_DESTROY(pcbinfo);
5769bcd427bSRobert Watson 	INP_INFO_LOCK_DESTROY(pcbinfo);
5779bcd427bSRobert Watson }
5789bcd427bSRobert Watson 
5799bcd427bSRobert Watson /*
580c3229e05SDavid Greenman  * Allocate a PCB and associate it with the socket.
581d915b280SStephan Uphoff  * On success return with the PCB locked.
582c3229e05SDavid Greenman  */
583df8bae1dSRodney W. Grimes int
584d915b280SStephan Uphoff in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
585df8bae1dSRodney W. Grimes {
586136d4f1cSRobert Watson 	struct inpcb *inp;
58713cf67f3SHajimu UMEMOTO 	int error;
588a557af22SRobert Watson 
589a557af22SRobert Watson 	error = 0;
590d915b280SStephan Uphoff 	inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
591df8bae1dSRodney W. Grimes 	if (inp == NULL)
592df8bae1dSRodney W. Grimes 		return (ENOBUFS);
5936a6cefacSGleb Smirnoff 	bzero(&inp->inp_start_zero, inp_zero_size);
59450575ce1SAndrew Gallatin #ifdef NUMA
59550575ce1SAndrew Gallatin 	inp->inp_numa_domain = M_NODOM;
59650575ce1SAndrew Gallatin #endif
59715bd2b43SDavid Greenman 	inp->inp_pcbinfo = pcbinfo;
598df8bae1dSRodney W. Grimes 	inp->inp_socket = so;
59986d02c5cSBjoern A. Zeeb 	inp->inp_cred = crhold(so->so_cred);
6008b07e49aSJulian Elischer 	inp->inp_inc.inc_fibnum = so->so_fibnum;
601a557af22SRobert Watson #ifdef MAC
60230d239bcSRobert Watson 	error = mac_inpcb_init(inp, M_NOWAIT);
603a557af22SRobert Watson 	if (error != 0)
604a557af22SRobert Watson 		goto out;
60530d239bcSRobert Watson 	mac_inpcb_create(so, inp);
606a557af22SRobert Watson #endif
607fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
608fcf59617SAndrey V. Elsukov 	error = ipsec_init_pcbpolicy(inp);
6090bffde27SRobert Watson 	if (error != 0) {
6100bffde27SRobert Watson #ifdef MAC
6110bffde27SRobert Watson 		mac_inpcb_destroy(inp);
6120bffde27SRobert Watson #endif
613a557af22SRobert Watson 		goto out;
6140bffde27SRobert Watson 	}
615b2630c29SGeorge V. Neville-Neil #endif /*IPSEC*/
616e3fd5ffdSRobert Watson #ifdef INET6
617340c35deSJonathan Lemon 	if (INP_SOCKAF(so) == AF_INET6) {
618340c35deSJonathan Lemon 		inp->inp_vflag |= INP_IPV6PROTO;
619603724d3SBjoern A. Zeeb 		if (V_ip6_v6only)
62033841545SHajimu UMEMOTO 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
621340c35deSJonathan Lemon 	}
62275daea93SPaul Saab #endif
623ff9b006dSJulien Charbon 	INP_WLOCK(inp);
624ff9b006dSJulien Charbon 	INP_LIST_WLOCK(pcbinfo);
625b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
6263d4d47f3SGarrett Wollman 	pcbinfo->ipi_count++;
627df8bae1dSRodney W. Grimes 	so->so_pcb = (caddr_t)inp;
62833841545SHajimu UMEMOTO #ifdef INET6
629603724d3SBjoern A. Zeeb 	if (V_ip6_auto_flowlabel)
63033841545SHajimu UMEMOTO 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
63133841545SHajimu UMEMOTO #endif
632d915b280SStephan Uphoff 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
63379bdc6e5SRobert Watson 	refcount_init(&inp->inp_refcount, 1);	/* Reference from inpcbinfo */
6348c1960d5SMike Karels 
6358c1960d5SMike Karels 	/*
6368c1960d5SMike Karels 	 * Routes in inpcb's can cache L2 as well; they are guaranteed
6378c1960d5SMike Karels 	 * to be cleaned up.
6388c1960d5SMike Karels 	 */
6398c1960d5SMike Karels 	inp->inp_route.ro_flags = RT_LLE_CACHE;
640ff9b006dSJulien Charbon 	INP_LIST_WUNLOCK(pcbinfo);
6417a60a910SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
642a557af22SRobert Watson out:
64386d02c5cSBjoern A. Zeeb 	if (error != 0) {
64486d02c5cSBjoern A. Zeeb 		crfree(inp->inp_cred);
645a557af22SRobert Watson 		uma_zfree(pcbinfo->ipi_zone, inp);
64686d02c5cSBjoern A. Zeeb 	}
647a557af22SRobert Watson #endif
648a557af22SRobert Watson 	return (error);
649df8bae1dSRodney W. Grimes }
650df8bae1dSRodney W. Grimes 
65167107f45SBjoern A. Zeeb #ifdef INET
652df8bae1dSRodney W. Grimes int
653136d4f1cSRobert Watson in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
654df8bae1dSRodney W. Grimes {
6554b932371SIan Dowse 	int anonport, error;
6564b932371SIan Dowse 
657f161d294SMark Johnston 	KASSERT(nam == NULL || nam->sa_family == AF_INET,
658f161d294SMark Johnston 	    ("%s: invalid address family for %p", __func__, nam));
659f161d294SMark Johnston 	KASSERT(nam == NULL || nam->sa_len == sizeof(struct sockaddr_in),
660f161d294SMark Johnston 	    ("%s: invalid address length for %p", __func__, nam));
6618501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
662fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
66359daba27SSam Leffler 
6644b932371SIan Dowse 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
6654b932371SIan Dowse 		return (EINVAL);
6665cd3dcaaSNavdeep Parhar 	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
6674b932371SIan Dowse 	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
668b0330ed9SPawel Jakub Dawidek 	    &inp->inp_lport, cred);
6694b932371SIan Dowse 	if (error)
6704b932371SIan Dowse 		return (error);
6714b932371SIan Dowse 	if (in_pcbinshash(inp) != 0) {
6724b932371SIan Dowse 		inp->inp_laddr.s_addr = INADDR_ANY;
6734b932371SIan Dowse 		inp->inp_lport = 0;
6744b932371SIan Dowse 		return (EAGAIN);
6754b932371SIan Dowse 	}
6764b932371SIan Dowse 	if (anonport)
6774b932371SIan Dowse 		inp->inp_flags |= INP_ANONPORT;
6784b932371SIan Dowse 	return (0);
6794b932371SIan Dowse }
68067107f45SBjoern A. Zeeb #endif
6814b932371SIan Dowse 
682efc76f72SBjoern A. Zeeb #if defined(INET) || defined(INET6)
68325102351SMike Karels /*
68425102351SMike Karels  * Assign a local port like in_pcb_lport(), but also used with connect()
68525102351SMike Karels  * and a foreign address and port.  If fsa is non-NULL, choose a local port
68625102351SMike Karels  * that is unused with those, otherwise one that is completely unused.
6872fdbcbeaSMike Karels  * lsa can be NULL for IPv6.
68825102351SMike Karels  */
689efc76f72SBjoern A. Zeeb int
69025102351SMike Karels in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
69125102351SMike Karels     struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
692efc76f72SBjoern A. Zeeb {
693efc76f72SBjoern A. Zeeb 	struct inpcbinfo *pcbinfo;
694efc76f72SBjoern A. Zeeb 	struct inpcb *tmpinp;
695efc76f72SBjoern A. Zeeb 	unsigned short *lastport;
696efc76f72SBjoern A. Zeeb 	int count, dorandom, error;
697efc76f72SBjoern A. Zeeb 	u_short aux, first, last, lport;
698efc76f72SBjoern A. Zeeb #ifdef INET
69925102351SMike Karels 	struct in_addr laddr, faddr;
70025102351SMike Karels #endif
70125102351SMike Karels #ifdef INET6
70225102351SMike Karels 	struct in6_addr *laddr6, *faddr6;
703efc76f72SBjoern A. Zeeb #endif
704efc76f72SBjoern A. Zeeb 
705efc76f72SBjoern A. Zeeb 	pcbinfo = inp->inp_pcbinfo;
706efc76f72SBjoern A. Zeeb 
707efc76f72SBjoern A. Zeeb 	/*
708efc76f72SBjoern A. Zeeb 	 * Because no actual state changes occur here, a global write lock on
709efc76f72SBjoern A. Zeeb 	 * the pcbinfo isn't required.
710efc76f72SBjoern A. Zeeb 	 */
711efc76f72SBjoern A. Zeeb 	INP_LOCK_ASSERT(inp);
712fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
713efc76f72SBjoern A. Zeeb 
714efc76f72SBjoern A. Zeeb 	if (inp->inp_flags & INP_HIGHPORT) {
715efc76f72SBjoern A. Zeeb 		first = V_ipport_hifirstauto;	/* sysctl */
716efc76f72SBjoern A. Zeeb 		last  = V_ipport_hilastauto;
717efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lasthi;
718efc76f72SBjoern A. Zeeb 	} else if (inp->inp_flags & INP_LOWPORT) {
719cc426dd3SMateusz Guzik 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
720efc76f72SBjoern A. Zeeb 		if (error)
721efc76f72SBjoern A. Zeeb 			return (error);
722efc76f72SBjoern A. Zeeb 		first = V_ipport_lowfirstauto;	/* 1023 */
723efc76f72SBjoern A. Zeeb 		last  = V_ipport_lowlastauto;	/* 600 */
724efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastlow;
725efc76f72SBjoern A. Zeeb 	} else {
726efc76f72SBjoern A. Zeeb 		first = V_ipport_firstauto;	/* sysctl */
727efc76f72SBjoern A. Zeeb 		last  = V_ipport_lastauto;
728efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastport;
729efc76f72SBjoern A. Zeeb 	}
730efc76f72SBjoern A. Zeeb 	/*
731e06e816fSKevin Lo 	 * For UDP(-Lite), use random port allocation as long as the user
732efc76f72SBjoern A. Zeeb 	 * allows it.  For TCP (and as of yet unknown) connections,
733efc76f72SBjoern A. Zeeb 	 * use random port allocation only if the user allows it AND
734efc76f72SBjoern A. Zeeb 	 * ipport_tick() allows it.
735efc76f72SBjoern A. Zeeb 	 */
736efc76f72SBjoern A. Zeeb 	if (V_ipport_randomized &&
737e06e816fSKevin Lo 		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
738e06e816fSKevin Lo 		pcbinfo == &V_ulitecbinfo))
739efc76f72SBjoern A. Zeeb 		dorandom = 1;
740efc76f72SBjoern A. Zeeb 	else
741efc76f72SBjoern A. Zeeb 		dorandom = 0;
742efc76f72SBjoern A. Zeeb 	/*
743efc76f72SBjoern A. Zeeb 	 * It makes no sense to do random port allocation if
744efc76f72SBjoern A. Zeeb 	 * we have the only port available.
745efc76f72SBjoern A. Zeeb 	 */
746efc76f72SBjoern A. Zeeb 	if (first == last)
747efc76f72SBjoern A. Zeeb 		dorandom = 0;
748e06e816fSKevin Lo 	/* Make sure to not include UDP(-Lite) packets in the count. */
749e06e816fSKevin Lo 	if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
750efc76f72SBjoern A. Zeeb 		V_ipport_tcpallocs++;
751efc76f72SBjoern A. Zeeb 	/*
752efc76f72SBjoern A. Zeeb 	 * Instead of having two loops further down counting up or down
753efc76f72SBjoern A. Zeeb 	 * make sure that first is always <= last and go with only one
754efc76f72SBjoern A. Zeeb 	 * code path implementing all logic.
755efc76f72SBjoern A. Zeeb 	 */
756efc76f72SBjoern A. Zeeb 	if (first > last) {
757efc76f72SBjoern A. Zeeb 		aux = first;
758efc76f72SBjoern A. Zeeb 		first = last;
759efc76f72SBjoern A. Zeeb 		last = aux;
760efc76f72SBjoern A. Zeeb 	}
761efc76f72SBjoern A. Zeeb 
762efc76f72SBjoern A. Zeeb #ifdef INET
76325102351SMike Karels 	laddr.s_addr = INADDR_ANY;
7644d457387SBjoern A. Zeeb 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
7652fdbcbeaSMike Karels 		if (lsa != NULL)
76625102351SMike Karels 			laddr = ((struct sockaddr_in *)lsa)->sin_addr;
76725102351SMike Karels 		if (fsa != NULL)
76825102351SMike Karels 			faddr = ((struct sockaddr_in *)fsa)->sin_addr;
769efc76f72SBjoern A. Zeeb 	}
770efc76f72SBjoern A. Zeeb #endif
77125102351SMike Karels #ifdef INET6
7722fdbcbeaSMike Karels 	laddr6 = NULL;
7732fdbcbeaSMike Karels 	if ((inp->inp_vflag & INP_IPV6) != 0) {
7742fdbcbeaSMike Karels 		if (lsa != NULL)
77525102351SMike Karels 			laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
77625102351SMike Karels 		if (fsa != NULL)
77725102351SMike Karels 			faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
77825102351SMike Karels 	}
77925102351SMike Karels #endif
78025102351SMike Karels 
78125102351SMike Karels 	tmpinp = NULL;
782efc76f72SBjoern A. Zeeb 	lport = *lportp;
783efc76f72SBjoern A. Zeeb 
784efc76f72SBjoern A. Zeeb 	if (dorandom)
785efc76f72SBjoern A. Zeeb 		*lastport = first + (arc4random() % (last - first));
786efc76f72SBjoern A. Zeeb 
787efc76f72SBjoern A. Zeeb 	count = last - first;
788efc76f72SBjoern A. Zeeb 
789efc76f72SBjoern A. Zeeb 	do {
790efc76f72SBjoern A. Zeeb 		if (count-- < 0)	/* completely used? */
791efc76f72SBjoern A. Zeeb 			return (EADDRNOTAVAIL);
792efc76f72SBjoern A. Zeeb 		++*lastport;
793efc76f72SBjoern A. Zeeb 		if (*lastport < first || *lastport > last)
794efc76f72SBjoern A. Zeeb 			*lastport = first;
795efc76f72SBjoern A. Zeeb 		lport = htons(*lastport);
796efc76f72SBjoern A. Zeeb 
79725102351SMike Karels 		if (fsa != NULL) {
79825102351SMike Karels #ifdef INET
79925102351SMike Karels 			if (lsa->sa_family == AF_INET) {
80025102351SMike Karels 				tmpinp = in_pcblookup_hash_locked(pcbinfo,
80125102351SMike Karels 				    faddr, fport, laddr, lport, lookupflags,
802a034518aSAndrew Gallatin 				    NULL, M_NODOM);
80325102351SMike Karels 			}
80425102351SMike Karels #endif
80525102351SMike Karels #ifdef INET6
80625102351SMike Karels 			if (lsa->sa_family == AF_INET6) {
80725102351SMike Karels 				tmpinp = in6_pcblookup_hash_locked(pcbinfo,
80825102351SMike Karels 				    faddr6, fport, laddr6, lport, lookupflags,
809a034518aSAndrew Gallatin 				    NULL, M_NODOM);
81025102351SMike Karels 			}
81125102351SMike Karels #endif
81225102351SMike Karels 		} else {
813efc76f72SBjoern A. Zeeb #ifdef INET6
8144616026fSErmal Luçi 			if ((inp->inp_vflag & INP_IPV6) != 0)
815efc76f72SBjoern A. Zeeb 				tmpinp = in6_pcblookup_local(pcbinfo,
81668e0d7e0SRobert Watson 				    &inp->in6p_laddr, lport, lookupflags, cred);
817efc76f72SBjoern A. Zeeb #endif
818efc76f72SBjoern A. Zeeb #if defined(INET) && defined(INET6)
819efc76f72SBjoern A. Zeeb 			else
820efc76f72SBjoern A. Zeeb #endif
821efc76f72SBjoern A. Zeeb #ifdef INET
822efc76f72SBjoern A. Zeeb 				tmpinp = in_pcblookup_local(pcbinfo, laddr,
82368e0d7e0SRobert Watson 				    lport, lookupflags, cred);
824efc76f72SBjoern A. Zeeb #endif
82525102351SMike Karels 		}
826efc76f72SBjoern A. Zeeb 	} while (tmpinp != NULL);
827efc76f72SBjoern A. Zeeb 
828efc76f72SBjoern A. Zeeb 	*lportp = lport;
829efc76f72SBjoern A. Zeeb 
830efc76f72SBjoern A. Zeeb 	return (0);
831efc76f72SBjoern A. Zeeb }
832efdf104bSMikolaj Golub 
833efdf104bSMikolaj Golub /*
83425102351SMike Karels  * Select a local port (number) to use.
83525102351SMike Karels  */
83625102351SMike Karels int
83725102351SMike Karels in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
83825102351SMike Karels     struct ucred *cred, int lookupflags)
83925102351SMike Karels {
84025102351SMike Karels 	struct sockaddr_in laddr;
84125102351SMike Karels 
84225102351SMike Karels 	if (laddrp) {
84325102351SMike Karels 		bzero(&laddr, sizeof(laddr));
84425102351SMike Karels 		laddr.sin_family = AF_INET;
84525102351SMike Karels 		laddr.sin_addr = *laddrp;
84625102351SMike Karels 	}
84725102351SMike Karels 	return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
84825102351SMike Karels 	    NULL, lportp, NULL, 0, cred, lookupflags));
84925102351SMike Karels }
85025102351SMike Karels 
85125102351SMike Karels /*
852efdf104bSMikolaj Golub  * Return cached socket options.
853efdf104bSMikolaj Golub  */
8541a43cff9SSean Bruno int
855efdf104bSMikolaj Golub inp_so_options(const struct inpcb *inp)
856efdf104bSMikolaj Golub {
8571a43cff9SSean Bruno 	int so_options;
858efdf104bSMikolaj Golub 
859efdf104bSMikolaj Golub 	so_options = 0;
860efdf104bSMikolaj Golub 
8611a43cff9SSean Bruno 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
8621a43cff9SSean Bruno 		so_options |= SO_REUSEPORT_LB;
863efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
864efdf104bSMikolaj Golub 		so_options |= SO_REUSEPORT;
865efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
866efdf104bSMikolaj Golub 		so_options |= SO_REUSEADDR;
867efdf104bSMikolaj Golub 	return (so_options);
868efdf104bSMikolaj Golub }
869efc76f72SBjoern A. Zeeb #endif /* INET || INET6 */
870efc76f72SBjoern A. Zeeb 
8714b932371SIan Dowse /*
8720a100a6fSAdrian Chadd  * Check if a new BINDMULTI socket is allowed to be created.
8730a100a6fSAdrian Chadd  *
8740a100a6fSAdrian Chadd  * ni points to the new inp.
8750a100a6fSAdrian Chadd  * oi points to the exisitng inp.
8760a100a6fSAdrian Chadd  *
8770a100a6fSAdrian Chadd  * This checks whether the existing inp also has BINDMULTI and
8780a100a6fSAdrian Chadd  * whether the credentials match.
8790a100a6fSAdrian Chadd  */
880d5bb8bd3SAdrian Chadd int
8810a100a6fSAdrian Chadd in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
8820a100a6fSAdrian Chadd {
8830a100a6fSAdrian Chadd 	/* Check permissions match */
8840a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
8850a100a6fSAdrian Chadd 	    (ni->inp_cred->cr_uid !=
8860a100a6fSAdrian Chadd 	    oi->inp_cred->cr_uid))
8870a100a6fSAdrian Chadd 		return (0);
8880a100a6fSAdrian Chadd 
8890a100a6fSAdrian Chadd 	/* Check the existing inp has BINDMULTI set */
8900a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
8910a100a6fSAdrian Chadd 	    ((oi->inp_flags2 & INP_BINDMULTI) == 0))
8920a100a6fSAdrian Chadd 		return (0);
8930a100a6fSAdrian Chadd 
8940a100a6fSAdrian Chadd 	/*
8950a100a6fSAdrian Chadd 	 * We're okay - either INP_BINDMULTI isn't set on ni, or
8960a100a6fSAdrian Chadd 	 * it is and it matches the checks.
8970a100a6fSAdrian Chadd 	 */
8980a100a6fSAdrian Chadd 	return (1);
8990a100a6fSAdrian Chadd }
9000a100a6fSAdrian Chadd 
901d5bb8bd3SAdrian Chadd #ifdef INET
9020a100a6fSAdrian Chadd /*
9034b932371SIan Dowse  * Set up a bind operation on a PCB, performing port allocation
9044b932371SIan Dowse  * as required, but do not actually modify the PCB. Callers can
9054b932371SIan Dowse  * either complete the bind by setting inp_laddr/inp_lport and
9064b932371SIan Dowse  * calling in_pcbinshash(), or they can just use the resulting
9074b932371SIan Dowse  * port and address to authorise the sending of a once-off packet.
9084b932371SIan Dowse  *
9094b932371SIan Dowse  * On error, the values of *laddrp and *lportp are not changed.
9104b932371SIan Dowse  */
9114b932371SIan Dowse int
912136d4f1cSRobert Watson in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
913136d4f1cSRobert Watson     u_short *lportp, struct ucred *cred)
9144b932371SIan Dowse {
9154b932371SIan Dowse 	struct socket *so = inp->inp_socket;
91615bd2b43SDavid Greenman 	struct sockaddr_in *sin;
917c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
9184b932371SIan Dowse 	struct in_addr laddr;
919df8bae1dSRodney W. Grimes 	u_short lport = 0;
92068e0d7e0SRobert Watson 	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
921413628a7SBjoern A. Zeeb 	int error;
922df8bae1dSRodney W. Grimes 
9238501a69cSRobert Watson 	/*
9241a43cff9SSean Bruno 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
9251a43cff9SSean Bruno 	 * so that we don't have to add to the (already messy) code below.
9261a43cff9SSean Bruno 	 */
9271a43cff9SSean Bruno 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
9281a43cff9SSean Bruno 
9291a43cff9SSean Bruno 	/*
930fa046d87SRobert Watson 	 * No state changes, so read locks are sufficient here.
9318501a69cSRobert Watson 	 */
93259daba27SSam Leffler 	INP_LOCK_ASSERT(inp);
933fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
93459daba27SSam Leffler 
935d7c5a620SMatt Macy 	if (CK_STAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
936df8bae1dSRodney W. Grimes 		return (EADDRNOTAVAIL);
9374b932371SIan Dowse 	laddr.s_addr = *laddrp;
9384b932371SIan Dowse 	if (nam != NULL && laddr.s_addr != INADDR_ANY)
939df8bae1dSRodney W. Grimes 		return (EINVAL);
9401a43cff9SSean Bruno 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
94168e0d7e0SRobert Watson 		lookupflags = INPLOOKUP_WILDCARD;
9424616026fSErmal Luçi 	if (nam == NULL) {
9437c2f3cb9SJamie Gritton 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
9447c2f3cb9SJamie Gritton 			return (error);
9457c2f3cb9SJamie Gritton 	} else {
94657bf258eSGarrett Wollman 		sin = (struct sockaddr_in *)nam;
947f161d294SMark Johnston 		KASSERT(sin->sin_family == AF_INET,
948f161d294SMark Johnston 		    ("%s: invalid family for address %p", __func__, sin));
949f161d294SMark Johnston 		KASSERT(sin->sin_len == sizeof(*sin),
950f161d294SMark Johnston 		    ("%s: invalid length for address %p", __func__, sin));
951f161d294SMark Johnston 
952b89e82ddSJamie Gritton 		error = prison_local_ip4(cred, &sin->sin_addr);
953b89e82ddSJamie Gritton 		if (error)
954b89e82ddSJamie Gritton 			return (error);
9554b932371SIan Dowse 		if (sin->sin_port != *lportp) {
9564b932371SIan Dowse 			/* Don't allow the port to change. */
9574b932371SIan Dowse 			if (*lportp != 0)
9584b932371SIan Dowse 				return (EINVAL);
959df8bae1dSRodney W. Grimes 			lport = sin->sin_port;
9604b932371SIan Dowse 		}
9614b932371SIan Dowse 		/* NB: lport is left as 0 if the port isn't being changed. */
962df8bae1dSRodney W. Grimes 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
963df8bae1dSRodney W. Grimes 			/*
964df8bae1dSRodney W. Grimes 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
965df8bae1dSRodney W. Grimes 			 * allow complete duplication of binding if
966df8bae1dSRodney W. Grimes 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
967df8bae1dSRodney W. Grimes 			 * and a multicast address is bound on both
968df8bae1dSRodney W. Grimes 			 * new and duplicated sockets.
969df8bae1dSRodney W. Grimes 			 */
970f122b319SMikolaj Golub 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
971df8bae1dSRodney W. Grimes 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
9721a43cff9SSean Bruno 			/*
9731a43cff9SSean Bruno 			 * XXX: How to deal with SO_REUSEPORT_LB here?
9741a43cff9SSean Bruno 			 * Treat same as SO_REUSEPORT for now.
9751a43cff9SSean Bruno 			 */
9761a43cff9SSean Bruno 			if ((so->so_options &
9771a43cff9SSean Bruno 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
9781a43cff9SSean Bruno 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
979df8bae1dSRodney W. Grimes 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
980df8bae1dSRodney W. Grimes 			sin->sin_port = 0;		/* yech... */
98183103a73SAndrew R. Reiter 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
9824209e01aSAdrian Chadd 			/*
9834209e01aSAdrian Chadd 			 * Is the address a local IP address?
984f44270e7SPawel Jakub Dawidek 			 * If INP_BINDANY is set, then the socket may be bound
9858696873dSAdrian Chadd 			 * to any endpoint address, local or not.
9864209e01aSAdrian Chadd 			 */
987f44270e7SPawel Jakub Dawidek 			if ((inp->inp_flags & INP_BINDANY) == 0 &&
9888896f83aSRobert Watson 			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
989df8bae1dSRodney W. Grimes 				return (EADDRNOTAVAIL);
990df8bae1dSRodney W. Grimes 		}
9914b932371SIan Dowse 		laddr = sin->sin_addr;
992df8bae1dSRodney W. Grimes 		if (lport) {
993df8bae1dSRodney W. Grimes 			struct inpcb *t;
994ae0e7143SRobert Watson 			struct tcptw *tw;
995ae0e7143SRobert Watson 
996df8bae1dSRodney W. Grimes 			/* GROSS */
997603724d3SBjoern A. Zeeb 			if (ntohs(lport) <= V_ipport_reservedhigh &&
998603724d3SBjoern A. Zeeb 			    ntohs(lport) >= V_ipport_reservedlow &&
999cc426dd3SMateusz Guzik 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
10002469dd60SGarrett Wollman 				return (EACCES);
1001835d4b89SPawel Jakub Dawidek 			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
1002cc426dd3SMateusz Guzik 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
1003078b7042SBjoern A. Zeeb 				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1004413628a7SBjoern A. Zeeb 				    lport, INPLOOKUP_WILDCARD, cred);
1005340c35deSJonathan Lemon 	/*
1006340c35deSJonathan Lemon 	 * XXX
1007340c35deSJonathan Lemon 	 * This entire block sorely needs a rewrite.
1008340c35deSJonathan Lemon 	 */
10094cc20ab1SSeigo Tanimura 				if (t &&
10100a100a6fSAdrian Chadd 				    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1011ad71fe3cSRobert Watson 				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
10124658dc83SYaroslav Tykhiy 				    (so->so_type != SOCK_STREAM ||
10134658dc83SYaroslav Tykhiy 				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
10144cc20ab1SSeigo Tanimura 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
101552b65dbeSBill Fenner 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
10161a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT) ||
10171a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
101886d02c5cSBjoern A. Zeeb 				    (inp->inp_cred->cr_uid !=
101986d02c5cSBjoern A. Zeeb 				     t->inp_cred->cr_uid))
10204049a042SGuido van Rooij 					return (EADDRINUSE);
10210a100a6fSAdrian Chadd 
10220a100a6fSAdrian Chadd 				/*
10230a100a6fSAdrian Chadd 				 * If the socket is a BINDMULTI socket, then
10240a100a6fSAdrian Chadd 				 * the credentials need to match and the
10250a100a6fSAdrian Chadd 				 * original socket also has to have been bound
10260a100a6fSAdrian Chadd 				 * with BINDMULTI.
10270a100a6fSAdrian Chadd 				 */
10280a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
10290a100a6fSAdrian Chadd 					return (EADDRINUSE);
10304049a042SGuido van Rooij 			}
1031c3229e05SDavid Greenman 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
103268e0d7e0SRobert Watson 			    lport, lookupflags, cred);
1033ad71fe3cSRobert Watson 			if (t && (t->inp_flags & INP_TIMEWAIT)) {
1034ae0e7143SRobert Watson 				/*
1035ae0e7143SRobert Watson 				 * XXXRW: If an incpb has had its timewait
1036ae0e7143SRobert Watson 				 * state recycled, we treat the address as
1037ae0e7143SRobert Watson 				 * being in use (for now).  This is better
1038ae0e7143SRobert Watson 				 * than a panic, but not desirable.
1039ae0e7143SRobert Watson 				 */
1040ec95b709SMikolaj Golub 				tw = intotw(t);
1041ae0e7143SRobert Watson 				if (tw == NULL ||
10421a43cff9SSean Bruno 				    ((reuseport & tw->tw_so_options) == 0 &&
10431a43cff9SSean Bruno 					(reuseport_lb &
10441a43cff9SSean Bruno 				            tw->tw_so_options) == 0)) {
1045340c35deSJonathan Lemon 					return (EADDRINUSE);
10461a43cff9SSean Bruno 				}
10470a100a6fSAdrian Chadd 			} else if (t &&
10480a100a6fSAdrian Chadd 				   ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
10491a43cff9SSean Bruno 				   (reuseport & inp_so_options(t)) == 0 &&
10501a43cff9SSean Bruno 				   (reuseport_lb & inp_so_options(t)) == 0) {
1051e3fd5ffdSRobert Watson #ifdef INET6
105233841545SHajimu UMEMOTO 				if (ntohl(sin->sin_addr.s_addr) !=
1053cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
1054cfa1ca9dSYoshinobu Inoue 				    ntohl(t->inp_laddr.s_addr) !=
1055cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
1056fc06cd42SMikolaj Golub 				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1057fc06cd42SMikolaj Golub 				    (t->inp_vflag & INP_IPV6PROTO) == 0)
1058e3fd5ffdSRobert Watson #endif
1059df8bae1dSRodney W. Grimes 						return (EADDRINUSE);
10600a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
10610a100a6fSAdrian Chadd 					return (EADDRINUSE);
1062df8bae1dSRodney W. Grimes 			}
1063cfa1ca9dSYoshinobu Inoue 		}
1064df8bae1dSRodney W. Grimes 	}
10654b932371SIan Dowse 	if (*lportp != 0)
10664b932371SIan Dowse 		lport = *lportp;
106733b3ac06SPeter Wemm 	if (lport == 0) {
10684616026fSErmal Luçi 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1069efc76f72SBjoern A. Zeeb 		if (error != 0)
1070efc76f72SBjoern A. Zeeb 			return (error);
107133b3ac06SPeter Wemm 	}
10724b932371SIan Dowse 	*laddrp = laddr.s_addr;
10734b932371SIan Dowse 	*lportp = lport;
1074df8bae1dSRodney W. Grimes 	return (0);
1075df8bae1dSRodney W. Grimes }
1076df8bae1dSRodney W. Grimes 
1077999f1343SGarrett Wollman /*
10785200e00eSIan Dowse  * Connect from a socket to a specified address.
10795200e00eSIan Dowse  * Both address and port must be specified in argument sin.
10805200e00eSIan Dowse  * If don't have a local address for this socket yet,
10815200e00eSIan Dowse  * then pick one.
1082999f1343SGarrett Wollman  */
1083999f1343SGarrett Wollman int
1084d3c1f003SRobert Watson in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
1085fe1274eeSMichael Tuexen     struct ucred *cred, struct mbuf *m, bool rehash)
1086999f1343SGarrett Wollman {
10875200e00eSIan Dowse 	u_short lport, fport;
10885200e00eSIan Dowse 	in_addr_t laddr, faddr;
10895200e00eSIan Dowse 	int anonport, error;
1090df8bae1dSRodney W. Grimes 
10918501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1092fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
109327f74fd0SRobert Watson 
10945200e00eSIan Dowse 	lport = inp->inp_lport;
10955200e00eSIan Dowse 	laddr = inp->inp_laddr.s_addr;
10965200e00eSIan Dowse 	anonport = (lport == 0);
10975200e00eSIan Dowse 	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
1098b0330ed9SPawel Jakub Dawidek 	    NULL, cred);
10995200e00eSIan Dowse 	if (error)
11005200e00eSIan Dowse 		return (error);
11015200e00eSIan Dowse 
11025200e00eSIan Dowse 	/* Do the initial binding of the local address if required. */
11035200e00eSIan Dowse 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1104fe1274eeSMichael Tuexen 		KASSERT(rehash == true,
1105fe1274eeSMichael Tuexen 		    ("Rehashing required for unbound inps"));
11065200e00eSIan Dowse 		inp->inp_lport = lport;
11075200e00eSIan Dowse 		inp->inp_laddr.s_addr = laddr;
11085200e00eSIan Dowse 		if (in_pcbinshash(inp) != 0) {
11095200e00eSIan Dowse 			inp->inp_laddr.s_addr = INADDR_ANY;
11105200e00eSIan Dowse 			inp->inp_lport = 0;
11115200e00eSIan Dowse 			return (EAGAIN);
11125200e00eSIan Dowse 		}
11135200e00eSIan Dowse 	}
11145200e00eSIan Dowse 
11155200e00eSIan Dowse 	/* Commit the remaining changes. */
11165200e00eSIan Dowse 	inp->inp_lport = lport;
11175200e00eSIan Dowse 	inp->inp_laddr.s_addr = laddr;
11185200e00eSIan Dowse 	inp->inp_faddr.s_addr = faddr;
11195200e00eSIan Dowse 	inp->inp_fport = fport;
1120fe1274eeSMichael Tuexen 	if (rehash) {
1121d3c1f003SRobert Watson 		in_pcbrehash_mbuf(inp, m);
1122fe1274eeSMichael Tuexen 	} else {
1123fe1274eeSMichael Tuexen 		in_pcbinshash_mbuf(inp, m);
1124fe1274eeSMichael Tuexen 	}
11252cb64cb2SGeorge V. Neville-Neil 
11265200e00eSIan Dowse 	if (anonport)
11275200e00eSIan Dowse 		inp->inp_flags |= INP_ANONPORT;
11285200e00eSIan Dowse 	return (0);
11295200e00eSIan Dowse }
11305200e00eSIan Dowse 
1131d3c1f003SRobert Watson int
1132d3c1f003SRobert Watson in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1133d3c1f003SRobert Watson {
1134d3c1f003SRobert Watson 
1135fe1274eeSMichael Tuexen 	return (in_pcbconnect_mbuf(inp, nam, cred, NULL, true));
1136d3c1f003SRobert Watson }
1137d3c1f003SRobert Watson 
11385200e00eSIan Dowse /*
11390895aec3SBjoern A. Zeeb  * Do proper source address selection on an unbound socket in case
11400895aec3SBjoern A. Zeeb  * of connect. Take jails into account as well.
11410895aec3SBjoern A. Zeeb  */
1142ae190832SSteven Hartland int
11430895aec3SBjoern A. Zeeb in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
11440895aec3SBjoern A. Zeeb     struct ucred *cred)
11450895aec3SBjoern A. Zeeb {
11460895aec3SBjoern A. Zeeb 	struct ifaddr *ifa;
11470895aec3SBjoern A. Zeeb 	struct sockaddr *sa;
11489ac7c6cfSAlexander V. Chernikov 	struct sockaddr_in *sin, dst;
11499ac7c6cfSAlexander V. Chernikov 	struct nhop_object *nh;
11500895aec3SBjoern A. Zeeb 	int error;
11510895aec3SBjoern A. Zeeb 
1152c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
1153413628a7SBjoern A. Zeeb 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1154592bcae8SBjoern A. Zeeb 	/*
1155592bcae8SBjoern A. Zeeb 	 * Bypass source address selection and use the primary jail IP
1156592bcae8SBjoern A. Zeeb 	 * if requested.
1157592bcae8SBjoern A. Zeeb 	 */
1158592bcae8SBjoern A. Zeeb 	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1159592bcae8SBjoern A. Zeeb 		return (0);
1160592bcae8SBjoern A. Zeeb 
11610895aec3SBjoern A. Zeeb 	error = 0;
11620895aec3SBjoern A. Zeeb 
11639ac7c6cfSAlexander V. Chernikov 	nh = NULL;
11649ac7c6cfSAlexander V. Chernikov 	bzero(&dst, sizeof(dst));
11659ac7c6cfSAlexander V. Chernikov 	sin = &dst;
11660895aec3SBjoern A. Zeeb 	sin->sin_family = AF_INET;
11670895aec3SBjoern A. Zeeb 	sin->sin_len = sizeof(struct sockaddr_in);
11680895aec3SBjoern A. Zeeb 	sin->sin_addr.s_addr = faddr->s_addr;
11690895aec3SBjoern A. Zeeb 
11700895aec3SBjoern A. Zeeb 	/*
11710895aec3SBjoern A. Zeeb 	 * If route is known our src addr is taken from the i/f,
11720895aec3SBjoern A. Zeeb 	 * else punt.
11730895aec3SBjoern A. Zeeb 	 *
11740895aec3SBjoern A. Zeeb 	 * Find out route to destination.
11750895aec3SBjoern A. Zeeb 	 */
11760895aec3SBjoern A. Zeeb 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
11779ac7c6cfSAlexander V. Chernikov 		nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
11789ac7c6cfSAlexander V. Chernikov 		    0, NHR_NONE, 0);
11790895aec3SBjoern A. Zeeb 
11800895aec3SBjoern A. Zeeb 	/*
11810895aec3SBjoern A. Zeeb 	 * If we found a route, use the address corresponding to
11820895aec3SBjoern A. Zeeb 	 * the outgoing interface.
11830895aec3SBjoern A. Zeeb 	 *
11840895aec3SBjoern A. Zeeb 	 * Otherwise assume faddr is reachable on a directly connected
11850895aec3SBjoern A. Zeeb 	 * network and try to find a corresponding interface to take
11860895aec3SBjoern A. Zeeb 	 * the source address from.
11870895aec3SBjoern A. Zeeb 	 */
11889ac7c6cfSAlexander V. Chernikov 	if (nh == NULL || nh->nh_ifp == NULL) {
11898c0fec80SRobert Watson 		struct in_ifaddr *ia;
11900895aec3SBjoern A. Zeeb 		struct ifnet *ifp;
11910895aec3SBjoern A. Zeeb 
11924f8585e0SAlan Somers 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
119358a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
11944f6c66ccSMatt Macy 		if (ia == NULL) {
11954f8585e0SAlan Somers 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
119658a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
11974f6c66ccSMatt Macy 		}
11980895aec3SBjoern A. Zeeb 		if (ia == NULL) {
11990895aec3SBjoern A. Zeeb 			error = ENETUNREACH;
12000895aec3SBjoern A. Zeeb 			goto done;
12010895aec3SBjoern A. Zeeb 		}
12020895aec3SBjoern A. Zeeb 
12030304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
12040895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12050895aec3SBjoern A. Zeeb 			goto done;
12060895aec3SBjoern A. Zeeb 		}
12070895aec3SBjoern A. Zeeb 
12080895aec3SBjoern A. Zeeb 		ifp = ia->ia_ifp;
12090895aec3SBjoern A. Zeeb 		ia = NULL;
1210d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12110895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12120895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12130895aec3SBjoern A. Zeeb 				continue;
12140895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1215b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12160895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12170895aec3SBjoern A. Zeeb 				break;
12180895aec3SBjoern A. Zeeb 			}
12190895aec3SBjoern A. Zeeb 		}
12200895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12210895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12220895aec3SBjoern A. Zeeb 			goto done;
12230895aec3SBjoern A. Zeeb 		}
12240895aec3SBjoern A. Zeeb 
12250895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1226b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12270895aec3SBjoern A. Zeeb 		goto done;
12280895aec3SBjoern A. Zeeb 	}
12290895aec3SBjoern A. Zeeb 
12300895aec3SBjoern A. Zeeb 	/*
12310895aec3SBjoern A. Zeeb 	 * If the outgoing interface on the route found is not
12320895aec3SBjoern A. Zeeb 	 * a loopback interface, use the address from that interface.
12330895aec3SBjoern A. Zeeb 	 * In case of jails do those three steps:
12340895aec3SBjoern A. Zeeb 	 * 1. check if the interface address belongs to the jail. If so use it.
12350895aec3SBjoern A. Zeeb 	 * 2. check if we have any address on the outgoing interface
12360895aec3SBjoern A. Zeeb 	 *    belonging to this jail. If so use it.
12370895aec3SBjoern A. Zeeb 	 * 3. as a last resort return the 'default' jail address.
12380895aec3SBjoern A. Zeeb 	 */
12399ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
12408c0fec80SRobert Watson 		struct in_ifaddr *ia;
12419317b04eSRobert Watson 		struct ifnet *ifp;
12420895aec3SBjoern A. Zeeb 
12430895aec3SBjoern A. Zeeb 		/* If not jailed, use the default returned. */
12440304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
12459ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
12460895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12470895aec3SBjoern A. Zeeb 			goto done;
12480895aec3SBjoern A. Zeeb 		}
12490895aec3SBjoern A. Zeeb 
12500895aec3SBjoern A. Zeeb 		/* Jailed. */
12510895aec3SBjoern A. Zeeb 		/* 1. Check if the iface address belongs to the jail. */
12529ac7c6cfSAlexander V. Chernikov 		sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1253b89e82ddSJamie Gritton 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12549ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
12550895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12560895aec3SBjoern A. Zeeb 			goto done;
12570895aec3SBjoern A. Zeeb 		}
12580895aec3SBjoern A. Zeeb 
12590895aec3SBjoern A. Zeeb 		/*
12600895aec3SBjoern A. Zeeb 		 * 2. Check if we have any address on the outgoing interface
12610895aec3SBjoern A. Zeeb 		 *    belonging to this jail.
12620895aec3SBjoern A. Zeeb 		 */
12638c0fec80SRobert Watson 		ia = NULL;
12649ac7c6cfSAlexander V. Chernikov 		ifp = nh->nh_ifp;
1265d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12660895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12670895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12680895aec3SBjoern A. Zeeb 				continue;
12690895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1270b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12710895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12720895aec3SBjoern A. Zeeb 				break;
12730895aec3SBjoern A. Zeeb 			}
12740895aec3SBjoern A. Zeeb 		}
12750895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12760895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12770895aec3SBjoern A. Zeeb 			goto done;
12780895aec3SBjoern A. Zeeb 		}
12790895aec3SBjoern A. Zeeb 
12800895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1281b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12820895aec3SBjoern A. Zeeb 		goto done;
12830895aec3SBjoern A. Zeeb 	}
12840895aec3SBjoern A. Zeeb 
12850895aec3SBjoern A. Zeeb 	/*
12860895aec3SBjoern A. Zeeb 	 * The outgoing interface is marked with 'loopback net', so a route
12870895aec3SBjoern A. Zeeb 	 * to ourselves is here.
12880895aec3SBjoern A. Zeeb 	 * Try to find the interface of the destination address and then
12890895aec3SBjoern A. Zeeb 	 * take the address from there. That interface is not necessarily
12900895aec3SBjoern A. Zeeb 	 * a loopback interface.
12910895aec3SBjoern A. Zeeb 	 * In case of jails, check that it is an address of the jail
12920895aec3SBjoern A. Zeeb 	 * and if we cannot find, fall back to the 'default' jail address.
12930895aec3SBjoern A. Zeeb 	 */
12949ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
12958c0fec80SRobert Watson 		struct in_ifaddr *ia;
12960895aec3SBjoern A. Zeeb 
12979ac7c6cfSAlexander V. Chernikov 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
129858a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
12990895aec3SBjoern A. Zeeb 		if (ia == NULL)
13009ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
130158a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
1302f0bb05fcSQing Li 		if (ia == NULL)
13039ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
13040895aec3SBjoern A. Zeeb 
13050304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
13060895aec3SBjoern A. Zeeb 			if (ia == NULL) {
13070895aec3SBjoern A. Zeeb 				error = ENETUNREACH;
13080895aec3SBjoern A. Zeeb 				goto done;
13090895aec3SBjoern A. Zeeb 			}
13100895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13110895aec3SBjoern A. Zeeb 			goto done;
13120895aec3SBjoern A. Zeeb 		}
13130895aec3SBjoern A. Zeeb 
13140895aec3SBjoern A. Zeeb 		/* Jailed. */
13150895aec3SBjoern A. Zeeb 		if (ia != NULL) {
13160895aec3SBjoern A. Zeeb 			struct ifnet *ifp;
13170895aec3SBjoern A. Zeeb 
13180895aec3SBjoern A. Zeeb 			ifp = ia->ia_ifp;
13190895aec3SBjoern A. Zeeb 			ia = NULL;
1320d7c5a620SMatt Macy 			CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
13210895aec3SBjoern A. Zeeb 				sa = ifa->ifa_addr;
13220895aec3SBjoern A. Zeeb 				if (sa->sa_family != AF_INET)
13230895aec3SBjoern A. Zeeb 					continue;
13240895aec3SBjoern A. Zeeb 				sin = (struct sockaddr_in *)sa;
1325b89e82ddSJamie Gritton 				if (prison_check_ip4(cred,
1326b89e82ddSJamie Gritton 				    &sin->sin_addr) == 0) {
13270895aec3SBjoern A. Zeeb 					ia = (struct in_ifaddr *)ifa;
13280895aec3SBjoern A. Zeeb 					break;
13290895aec3SBjoern A. Zeeb 				}
13300895aec3SBjoern A. Zeeb 			}
13310895aec3SBjoern A. Zeeb 			if (ia != NULL) {
13320895aec3SBjoern A. Zeeb 				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13330895aec3SBjoern A. Zeeb 				goto done;
13340895aec3SBjoern A. Zeeb 			}
13350895aec3SBjoern A. Zeeb 		}
13360895aec3SBjoern A. Zeeb 
13370895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1338b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
13390895aec3SBjoern A. Zeeb 		goto done;
13400895aec3SBjoern A. Zeeb 	}
13410895aec3SBjoern A. Zeeb 
13420895aec3SBjoern A. Zeeb done:
13430895aec3SBjoern A. Zeeb 	return (error);
13440895aec3SBjoern A. Zeeb }
13450895aec3SBjoern A. Zeeb 
13460895aec3SBjoern A. Zeeb /*
13475200e00eSIan Dowse  * Set up for a connect from a socket to the specified address.
13485200e00eSIan Dowse  * On entry, *laddrp and *lportp should contain the current local
13495200e00eSIan Dowse  * address and port for the PCB; these are updated to the values
13505200e00eSIan Dowse  * that should be placed in inp_laddr and inp_lport to complete
13515200e00eSIan Dowse  * the connect.
13525200e00eSIan Dowse  *
13535200e00eSIan Dowse  * On success, *faddrp and *fportp will be set to the remote address
13545200e00eSIan Dowse  * and port. These are not updated in the error case.
13555200e00eSIan Dowse  *
13565200e00eSIan Dowse  * If the operation fails because the connection already exists,
13575200e00eSIan Dowse  * *oinpp will be set to the PCB of that connection so that the
13585200e00eSIan Dowse  * caller can decide to override it. In all other cases, *oinpp
13595200e00eSIan Dowse  * is set to NULL.
13605200e00eSIan Dowse  */
13615200e00eSIan Dowse int
1362136d4f1cSRobert Watson in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1363136d4f1cSRobert Watson     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1364136d4f1cSRobert Watson     struct inpcb **oinpp, struct ucred *cred)
13655200e00eSIan Dowse {
1366cc0a3c8cSAndrey V. Elsukov 	struct rm_priotracker in_ifa_tracker;
13675200e00eSIan Dowse 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
13685200e00eSIan Dowse 	struct in_ifaddr *ia;
13695200e00eSIan Dowse 	struct inpcb *oinp;
1370b89e82ddSJamie Gritton 	struct in_addr laddr, faddr;
13715200e00eSIan Dowse 	u_short lport, fport;
13725200e00eSIan Dowse 	int error;
13735200e00eSIan Dowse 
1374f161d294SMark Johnston 	KASSERT(sin->sin_family == AF_INET,
1375f161d294SMark Johnston 	    ("%s: invalid address family for %p", __func__, sin));
1376f161d294SMark Johnston 	KASSERT(sin->sin_len == sizeof(*sin),
1377f161d294SMark Johnston 	    ("%s: invalid address length for %p", __func__, sin));
1378f161d294SMark Johnston 
13798501a69cSRobert Watson 	/*
13808501a69cSRobert Watson 	 * Because a global state change doesn't actually occur here, a read
13818501a69cSRobert Watson 	 * lock is sufficient.
13828501a69cSRobert Watson 	 */
1383c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
138427f74fd0SRobert Watson 	INP_LOCK_ASSERT(inp);
1385fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
138627f74fd0SRobert Watson 
13875200e00eSIan Dowse 	if (oinpp != NULL)
13885200e00eSIan Dowse 		*oinpp = NULL;
1389df8bae1dSRodney W. Grimes 	if (sin->sin_port == 0)
1390df8bae1dSRodney W. Grimes 		return (EADDRNOTAVAIL);
13915200e00eSIan Dowse 	laddr.s_addr = *laddrp;
13925200e00eSIan Dowse 	lport = *lportp;
13935200e00eSIan Dowse 	faddr = sin->sin_addr;
13945200e00eSIan Dowse 	fport = sin->sin_port;
13950c325f53SAlexander V. Chernikov #ifdef ROUTE_MPATH
13960c325f53SAlexander V. Chernikov 	if (CALC_FLOWID_OUTBOUND) {
13970c325f53SAlexander V. Chernikov 		uint32_t hash_val, hash_type;
13980895aec3SBjoern A. Zeeb 
13990c325f53SAlexander V. Chernikov 		hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
14000c325f53SAlexander V. Chernikov 		    inp->inp_socket->so_proto->pr_protocol, &hash_type);
14010c325f53SAlexander V. Chernikov 
14020c325f53SAlexander V. Chernikov 		inp->inp_flowid = hash_val;
14030c325f53SAlexander V. Chernikov 		inp->inp_flowtype = hash_type;
14040c325f53SAlexander V. Chernikov 	}
14050c325f53SAlexander V. Chernikov #endif
1406d7c5a620SMatt Macy 	if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1407df8bae1dSRodney W. Grimes 		/*
1408df8bae1dSRodney W. Grimes 		 * If the destination address is INADDR_ANY,
1409df8bae1dSRodney W. Grimes 		 * use the primary local address.
1410df8bae1dSRodney W. Grimes 		 * If the supplied address is INADDR_BROADCAST,
1411df8bae1dSRodney W. Grimes 		 * and the primary interface supports broadcast,
1412df8bae1dSRodney W. Grimes 		 * choose the broadcast address for that interface.
1413df8bae1dSRodney W. Grimes 		 */
1414413628a7SBjoern A. Zeeb 		if (faddr.s_addr == INADDR_ANY) {
1415cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RLOCK(&in_ifa_tracker);
1416413628a7SBjoern A. Zeeb 			faddr =
1417d7c5a620SMatt Macy 			    IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1418cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1419b89e82ddSJamie Gritton 			if (cred != NULL &&
1420b89e82ddSJamie Gritton 			    (error = prison_get_ip4(cred, &faddr)) != 0)
1421b89e82ddSJamie Gritton 				return (error);
14222d9cfabaSRobert Watson 		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1423cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RLOCK(&in_ifa_tracker);
1424d7c5a620SMatt Macy 			if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
14252d9cfabaSRobert Watson 			    IFF_BROADCAST)
1426d7c5a620SMatt Macy 				faddr = satosin(&CK_STAILQ_FIRST(
1427603724d3SBjoern A. Zeeb 				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1428cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
14292d9cfabaSRobert Watson 		}
1430df8bae1dSRodney W. Grimes 	}
14315200e00eSIan Dowse 	if (laddr.s_addr == INADDR_ANY) {
1432d79fdd98SDaniel Eischen 		error = in_pcbladdr(inp, &faddr, &laddr, cred);
1433df8bae1dSRodney W. Grimes 		/*
1434df8bae1dSRodney W. Grimes 		 * If the destination address is multicast and an outgoing
1435d79fdd98SDaniel Eischen 		 * interface has been set as a multicast option, prefer the
1436df8bae1dSRodney W. Grimes 		 * address of that interface as our source address.
1437df8bae1dSRodney W. Grimes 		 */
14385200e00eSIan Dowse 		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1439df8bae1dSRodney W. Grimes 		    inp->inp_moptions != NULL) {
1440df8bae1dSRodney W. Grimes 			struct ip_moptions *imo;
1441df8bae1dSRodney W. Grimes 			struct ifnet *ifp;
1442df8bae1dSRodney W. Grimes 
1443df8bae1dSRodney W. Grimes 			imo = inp->inp_moptions;
1444df8bae1dSRodney W. Grimes 			if (imo->imo_multicast_ifp != NULL) {
1445df8bae1dSRodney W. Grimes 				ifp = imo->imo_multicast_ifp;
1446cc0a3c8cSAndrey V. Elsukov 				IN_IFADDR_RLOCK(&in_ifa_tracker);
1447d7c5a620SMatt Macy 				CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1448e691be70SDaniel Eischen 					if ((ia->ia_ifp == ifp) &&
1449e691be70SDaniel Eischen 					    (cred == NULL ||
1450e691be70SDaniel Eischen 					    prison_check_ip4(cred,
1451e691be70SDaniel Eischen 					    &ia->ia_addr.sin_addr) == 0))
1452df8bae1dSRodney W. Grimes 						break;
1453e691be70SDaniel Eischen 				}
1454e691be70SDaniel Eischen 				if (ia == NULL)
1455d79fdd98SDaniel Eischen 					error = EADDRNOTAVAIL;
1456e691be70SDaniel Eischen 				else {
14575200e00eSIan Dowse 					laddr = ia->ia_addr.sin_addr;
1458d79fdd98SDaniel Eischen 					error = 0;
1459999f1343SGarrett Wollman 				}
1460cc0a3c8cSAndrey V. Elsukov 				IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1461d79fdd98SDaniel Eischen 			}
1462d79fdd98SDaniel Eischen 		}
146304215ed2SRandall Stewart 		if (error)
146404215ed2SRandall Stewart 			return (error);
14650895aec3SBjoern A. Zeeb 	}
1466a034518aSAndrew Gallatin 
146725102351SMike Karels 	if (lport != 0) {
146825102351SMike Karels 		oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1469a034518aSAndrew Gallatin 		    fport, laddr, lport, 0, NULL, M_NODOM);
14705200e00eSIan Dowse 		if (oinp != NULL) {
14715200e00eSIan Dowse 			if (oinpp != NULL)
14725200e00eSIan Dowse 				*oinpp = oinp;
1473df8bae1dSRodney W. Grimes 			return (EADDRINUSE);
1474c3229e05SDavid Greenman 		}
147525102351SMike Karels 	} else {
147625102351SMike Karels 		struct sockaddr_in lsin, fsin;
147725102351SMike Karels 
147825102351SMike Karels 		bzero(&lsin, sizeof(lsin));
147925102351SMike Karels 		bzero(&fsin, sizeof(fsin));
148025102351SMike Karels 		lsin.sin_family = AF_INET;
148125102351SMike Karels 		lsin.sin_addr = laddr;
148225102351SMike Karels 		fsin.sin_family = AF_INET;
148325102351SMike Karels 		fsin.sin_addr = faddr;
148425102351SMike Karels 		error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
148525102351SMike Karels 		    &lport, (struct sockaddr *)& fsin, fport, cred,
148625102351SMike Karels 		    INPLOOKUP_WILDCARD);
14875a903f8dSPierre Beyssac 		if (error)
14885a903f8dSPierre Beyssac 			return (error);
14895a903f8dSPierre Beyssac 	}
14905200e00eSIan Dowse 	*laddrp = laddr.s_addr;
14915200e00eSIan Dowse 	*lportp = lport;
14925200e00eSIan Dowse 	*faddrp = faddr.s_addr;
14935200e00eSIan Dowse 	*fportp = fport;
1494df8bae1dSRodney W. Grimes 	return (0);
1495df8bae1dSRodney W. Grimes }
1496df8bae1dSRodney W. Grimes 
149726f9a767SRodney W. Grimes void
1498136d4f1cSRobert Watson in_pcbdisconnect(struct inpcb *inp)
1499df8bae1dSRodney W. Grimes {
15006b348152SRobert Watson 
15018501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1502fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1503df8bae1dSRodney W. Grimes 
1504df8bae1dSRodney W. Grimes 	inp->inp_faddr.s_addr = INADDR_ANY;
1505df8bae1dSRodney W. Grimes 	inp->inp_fport = 0;
150615bd2b43SDavid Greenman 	in_pcbrehash(inp);
1507df8bae1dSRodney W. Grimes }
150883e521ecSBjoern A. Zeeb #endif /* INET */
1509df8bae1dSRodney W. Grimes 
15104c7c478dSRobert Watson /*
151128696211SRobert Watson  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1512c0a211c5SRobert Watson  * For most protocols, this will be invoked immediately prior to calling
151328696211SRobert Watson  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
151428696211SRobert Watson  * socket, in which case in_pcbfree() is deferred.
15154c7c478dSRobert Watson  */
151626f9a767SRodney W. Grimes void
1517136d4f1cSRobert Watson in_pcbdetach(struct inpcb *inp)
1518df8bae1dSRodney W. Grimes {
15194c7c478dSRobert Watson 
1520a7df09e8SBjoern A. Zeeb 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1521c0a211c5SRobert Watson 
1522f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
1523f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag != NULL)
1524f3e7afe2SHans Petter Selasky 		in_pcbdetach_txrtlmt(inp);
1525f3e7afe2SHans Petter Selasky #endif
15264c7c478dSRobert Watson 	inp->inp_socket->so_pcb = NULL;
15274c7c478dSRobert Watson 	inp->inp_socket = NULL;
15284c7c478dSRobert Watson }
15294c7c478dSRobert Watson 
1530c0a211c5SRobert Watson /*
153179bdc6e5SRobert Watson  * in_pcbref() bumps the reference count on an inpcb in order to maintain
153279bdc6e5SRobert Watson  * stability of an inpcb pointer despite the inpcb lock being released.  This
153379bdc6e5SRobert Watson  * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
153452cd27cbSRobert Watson  * but where the inpcb lock may already held, or when acquiring a reference
153552cd27cbSRobert Watson  * via a pcbgroup.
153679bdc6e5SRobert Watson  *
153779bdc6e5SRobert Watson  * in_pcbref() should be used only to provide brief memory stability, and
153879bdc6e5SRobert Watson  * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
153979bdc6e5SRobert Watson  * garbage collect the inpcb if it has been in_pcbfree()'d from another
154079bdc6e5SRobert Watson  * context.  Until in_pcbrele() has returned that the inpcb is still valid,
154179bdc6e5SRobert Watson  * lock and rele are the *only* safe operations that may be performed on the
154279bdc6e5SRobert Watson  * inpcb.
154379bdc6e5SRobert Watson  *
154479bdc6e5SRobert Watson  * While the inpcb will not be freed, releasing the inpcb lock means that the
154579bdc6e5SRobert Watson  * connection's state may change, so the caller should be careful to
154679bdc6e5SRobert Watson  * revalidate any cached state on reacquiring the lock.  Drop the reference
154779bdc6e5SRobert Watson  * using in_pcbrele().
1548c0a211c5SRobert Watson  */
154979bdc6e5SRobert Watson void
155079bdc6e5SRobert Watson in_pcbref(struct inpcb *inp)
15514c7c478dSRobert Watson {
1552df8bae1dSRodney W. Grimes 
155379bdc6e5SRobert Watson 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
155479bdc6e5SRobert Watson 
155579bdc6e5SRobert Watson 	refcount_acquire(&inp->inp_refcount);
155679bdc6e5SRobert Watson }
155779bdc6e5SRobert Watson 
155879bdc6e5SRobert Watson /*
155979bdc6e5SRobert Watson  * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
156079bdc6e5SRobert Watson  * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
156179bdc6e5SRobert Watson  * return a flag indicating whether or not the inpcb remains valid.  If it is
156279bdc6e5SRobert Watson  * valid, we return with the inpcb lock held.
156379bdc6e5SRobert Watson  *
156479bdc6e5SRobert Watson  * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
156579bdc6e5SRobert Watson  * reference on an inpcb.  Historically more work was done here (actually, in
156679bdc6e5SRobert Watson  * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
156779bdc6e5SRobert Watson  * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
156879bdc6e5SRobert Watson  * about memory stability (and continued use of the write lock).
156979bdc6e5SRobert Watson  */
157079bdc6e5SRobert Watson int
157179bdc6e5SRobert Watson in_pcbrele_rlocked(struct inpcb *inp)
157279bdc6e5SRobert Watson {
157379bdc6e5SRobert Watson 	struct inpcbinfo *pcbinfo;
157479bdc6e5SRobert Watson 
157579bdc6e5SRobert Watson 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
157679bdc6e5SRobert Watson 
157779bdc6e5SRobert Watson 	INP_RLOCK_ASSERT(inp);
157879bdc6e5SRobert Watson 
1579df4e91d3SGleb Smirnoff 	if (refcount_release(&inp->inp_refcount) == 0) {
1580df4e91d3SGleb Smirnoff 		/*
1581df4e91d3SGleb Smirnoff 		 * If the inpcb has been freed, let the caller know, even if
1582df4e91d3SGleb Smirnoff 		 * this isn't the last reference.
1583df4e91d3SGleb Smirnoff 		 */
1584df4e91d3SGleb Smirnoff 		if (inp->inp_flags2 & INP_FREED) {
1585df4e91d3SGleb Smirnoff 			INP_RUNLOCK(inp);
1586df4e91d3SGleb Smirnoff 			return (1);
1587df4e91d3SGleb Smirnoff 		}
158879bdc6e5SRobert Watson 		return (0);
1589df4e91d3SGleb Smirnoff 	}
159079bdc6e5SRobert Watson 
159179bdc6e5SRobert Watson 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
15923ee9c3c4SRandall Stewart #ifdef TCPHPTS
15933ee9c3c4SRandall Stewart 	if (inp->inp_in_hpts || inp->inp_in_input) {
15943ee9c3c4SRandall Stewart 		struct tcp_hpts_entry *hpts;
15953ee9c3c4SRandall Stewart 		/*
15963ee9c3c4SRandall Stewart 		 * We should not be on the hpts at
15973ee9c3c4SRandall Stewart 		 * this point in any form. we must
15983ee9c3c4SRandall Stewart 		 * get the lock to be sure.
15993ee9c3c4SRandall Stewart 		 */
16003ee9c3c4SRandall Stewart 		hpts = tcp_hpts_lock(inp);
16013ee9c3c4SRandall Stewart 		if (inp->inp_in_hpts)
16023ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on hpts",
16033ee9c3c4SRandall Stewart 			      hpts, inp);
16043ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
16053ee9c3c4SRandall Stewart 		hpts = tcp_input_lock(inp);
16063ee9c3c4SRandall Stewart 		if (inp->inp_in_input)
16073ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on input hpts",
16083ee9c3c4SRandall Stewart 			      hpts, inp);
16093ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
16103ee9c3c4SRandall Stewart 	}
16113ee9c3c4SRandall Stewart #endif
161279bdc6e5SRobert Watson 	INP_RUNLOCK(inp);
161379bdc6e5SRobert Watson 	pcbinfo = inp->inp_pcbinfo;
161479bdc6e5SRobert Watson 	uma_zfree(pcbinfo->ipi_zone, inp);
161579bdc6e5SRobert Watson 	return (1);
161679bdc6e5SRobert Watson }
161779bdc6e5SRobert Watson 
161879bdc6e5SRobert Watson int
161979bdc6e5SRobert Watson in_pcbrele_wlocked(struct inpcb *inp)
162079bdc6e5SRobert Watson {
162179bdc6e5SRobert Watson 	struct inpcbinfo *pcbinfo;
162279bdc6e5SRobert Watson 
162379bdc6e5SRobert Watson 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
162479bdc6e5SRobert Watson 
162579bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
162679bdc6e5SRobert Watson 
1627edd0e0b0SFabien Thomas 	if (refcount_release(&inp->inp_refcount) == 0) {
1628edd0e0b0SFabien Thomas 		/*
1629edd0e0b0SFabien Thomas 		 * If the inpcb has been freed, let the caller know, even if
1630edd0e0b0SFabien Thomas 		 * this isn't the last reference.
1631edd0e0b0SFabien Thomas 		 */
1632edd0e0b0SFabien Thomas 		if (inp->inp_flags2 & INP_FREED) {
1633edd0e0b0SFabien Thomas 			INP_WUNLOCK(inp);
1634edd0e0b0SFabien Thomas 			return (1);
1635edd0e0b0SFabien Thomas 		}
163679bdc6e5SRobert Watson 		return (0);
1637edd0e0b0SFabien Thomas 	}
163879bdc6e5SRobert Watson 
163979bdc6e5SRobert Watson 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
16403ee9c3c4SRandall Stewart #ifdef TCPHPTS
16413ee9c3c4SRandall Stewart 	if (inp->inp_in_hpts || inp->inp_in_input) {
16423ee9c3c4SRandall Stewart 		struct tcp_hpts_entry *hpts;
16433ee9c3c4SRandall Stewart 		/*
16443ee9c3c4SRandall Stewart 		 * We should not be on the hpts at
16453ee9c3c4SRandall Stewart 		 * this point in any form. we must
16463ee9c3c4SRandall Stewart 		 * get the lock to be sure.
16473ee9c3c4SRandall Stewart 		 */
16483ee9c3c4SRandall Stewart 		hpts = tcp_hpts_lock(inp);
16493ee9c3c4SRandall Stewart 		if (inp->inp_in_hpts)
16503ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on hpts",
16513ee9c3c4SRandall Stewart 			      hpts, inp);
16523ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
16533ee9c3c4SRandall Stewart 		hpts = tcp_input_lock(inp);
16543ee9c3c4SRandall Stewart 		if (inp->inp_in_input)
16553ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on input hpts",
16563ee9c3c4SRandall Stewart 			      hpts, inp);
16573ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
16583ee9c3c4SRandall Stewart 	}
16593ee9c3c4SRandall Stewart #endif
166079bdc6e5SRobert Watson 	INP_WUNLOCK(inp);
166179bdc6e5SRobert Watson 	pcbinfo = inp->inp_pcbinfo;
166279bdc6e5SRobert Watson 	uma_zfree(pcbinfo->ipi_zone, inp);
166379bdc6e5SRobert Watson 	return (1);
166479bdc6e5SRobert Watson }
166579bdc6e5SRobert Watson 
166679bdc6e5SRobert Watson /*
166779bdc6e5SRobert Watson  * Temporary wrapper.
166879bdc6e5SRobert Watson  */
166979bdc6e5SRobert Watson int
167079bdc6e5SRobert Watson in_pcbrele(struct inpcb *inp)
167179bdc6e5SRobert Watson {
167279bdc6e5SRobert Watson 
167379bdc6e5SRobert Watson 	return (in_pcbrele_wlocked(inp));
167479bdc6e5SRobert Watson }
167579bdc6e5SRobert Watson 
1676ddece765SMatt Macy void
1677ddece765SMatt Macy in_pcblist_rele_rlocked(epoch_context_t ctx)
1678ddece765SMatt Macy {
1679ddece765SMatt Macy 	struct in_pcblist *il;
1680ddece765SMatt Macy 	struct inpcb *inp;
1681ddece765SMatt Macy 	struct inpcbinfo *pcbinfo;
1682ddece765SMatt Macy 	int i, n;
1683ddece765SMatt Macy 
1684ddece765SMatt Macy 	il = __containerof(ctx, struct in_pcblist, il_epoch_ctx);
1685ddece765SMatt Macy 	pcbinfo = il->il_pcbinfo;
1686ddece765SMatt Macy 	n = il->il_count;
1687ddece765SMatt Macy 	INP_INFO_WLOCK(pcbinfo);
1688ddece765SMatt Macy 	for (i = 0; i < n; i++) {
1689ddece765SMatt Macy 		inp = il->il_inp_list[i];
1690ddece765SMatt Macy 		INP_RLOCK(inp);
1691ddece765SMatt Macy 		if (!in_pcbrele_rlocked(inp))
1692ddece765SMatt Macy 			INP_RUNLOCK(inp);
1693ddece765SMatt Macy 	}
1694ddece765SMatt Macy 	INP_INFO_WUNLOCK(pcbinfo);
1695ddece765SMatt Macy 	free(il, M_TEMP);
1696ddece765SMatt Macy }
1697ddece765SMatt Macy 
1698addf2b20SMatt Macy static void
1699f09ee4fcSMatt Macy inpcbport_free(epoch_context_t ctx)
1700f09ee4fcSMatt Macy {
1701f09ee4fcSMatt Macy 	struct inpcbport *phd;
1702f09ee4fcSMatt Macy 
1703f09ee4fcSMatt Macy 	phd = __containerof(ctx, struct inpcbport, phd_epoch_ctx);
1704f09ee4fcSMatt Macy 	free(phd, M_PCB);
1705f09ee4fcSMatt Macy }
1706f09ee4fcSMatt Macy 
1707f09ee4fcSMatt Macy static void
1708addf2b20SMatt Macy in_pcbfree_deferred(epoch_context_t ctx)
1709addf2b20SMatt Macy {
1710addf2b20SMatt Macy 	struct inpcb *inp;
1711addf2b20SMatt Macy 	int released __unused;
1712addf2b20SMatt Macy 
1713addf2b20SMatt Macy 	inp = __containerof(ctx, struct inpcb, inp_epoch_ctx);
1714addf2b20SMatt Macy 
1715addf2b20SMatt Macy 	INP_WLOCK(inp);
1716c7ee62fcSAndrey V. Elsukov 	CURVNET_SET(inp->inp_vnet);
1717addf2b20SMatt Macy #ifdef INET
1718f9be0386SMatt Macy 	struct ip_moptions *imo = inp->inp_moptions;
1719addf2b20SMatt Macy 	inp->inp_moptions = NULL;
1720addf2b20SMatt Macy #endif
1721addf2b20SMatt Macy 	/* XXXRW: Do as much as possible here. */
1722addf2b20SMatt Macy #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1723addf2b20SMatt Macy 	if (inp->inp_sp != NULL)
1724addf2b20SMatt Macy 		ipsec_delete_pcbpolicy(inp);
1725addf2b20SMatt Macy #endif
1726addf2b20SMatt Macy #ifdef INET6
1727f9be0386SMatt Macy 	struct ip6_moptions *im6o = NULL;
1728addf2b20SMatt Macy 	if (inp->inp_vflag & INP_IPV6PROTO) {
1729addf2b20SMatt Macy 		ip6_freepcbopts(inp->in6p_outputopts);
1730f9be0386SMatt Macy 		im6o = inp->in6p_moptions;
1731addf2b20SMatt Macy 		inp->in6p_moptions = NULL;
1732addf2b20SMatt Macy 	}
1733addf2b20SMatt Macy #endif
1734addf2b20SMatt Macy 	if (inp->inp_options)
1735addf2b20SMatt Macy 		(void)m_free(inp->inp_options);
1736addf2b20SMatt Macy 	inp->inp_vflag = 0;
1737addf2b20SMatt Macy 	crfree(inp->inp_cred);
1738addf2b20SMatt Macy #ifdef MAC
1739addf2b20SMatt Macy 	mac_inpcb_destroy(inp);
1740addf2b20SMatt Macy #endif
1741addf2b20SMatt Macy 	released = in_pcbrele_wlocked(inp);
1742addf2b20SMatt Macy 	MPASS(released);
1743f9be0386SMatt Macy #ifdef INET6
1744f9be0386SMatt Macy 	ip6_freemoptions(im6o);
1745f9be0386SMatt Macy #endif
1746f9be0386SMatt Macy #ifdef INET
1747f9be0386SMatt Macy 	inp_freemoptions(imo);
1748f9be0386SMatt Macy #endif
1749c7ee62fcSAndrey V. Elsukov 	CURVNET_RESTORE();
1750addf2b20SMatt Macy }
1751addf2b20SMatt Macy 
175279bdc6e5SRobert Watson /*
175379bdc6e5SRobert Watson  * Unconditionally schedule an inpcb to be freed by decrementing its
175479bdc6e5SRobert Watson  * reference count, which should occur only after the inpcb has been detached
175579bdc6e5SRobert Watson  * from its socket.  If another thread holds a temporary reference (acquired
175679bdc6e5SRobert Watson  * using in_pcbref()) then the free is deferred until that reference is
175779bdc6e5SRobert Watson  * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
175879bdc6e5SRobert Watson  * work, including removal from global lists, is done in this context, where
175979bdc6e5SRobert Watson  * the pcbinfo lock is held.
176079bdc6e5SRobert Watson  */
176179bdc6e5SRobert Watson void
176279bdc6e5SRobert Watson in_pcbfree(struct inpcb *inp)
176379bdc6e5SRobert Watson {
1764f42a83f2SMatt Macy 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1765f42a83f2SMatt Macy 
176679bdc6e5SRobert Watson 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
176745a48d07SJonathan T. Looney 	KASSERT((inp->inp_flags2 & INP_FREED) == 0,
176845a48d07SJonathan T. Looney 	    ("%s: called twice for pcb %p", __func__, inp));
176945a48d07SJonathan T. Looney 	if (inp->inp_flags2 & INP_FREED) {
177045a48d07SJonathan T. Looney 		INP_WUNLOCK(inp);
177145a48d07SJonathan T. Looney 		return;
177245a48d07SJonathan T. Looney 	}
177345a48d07SJonathan T. Looney 
177479bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
1775f42a83f2SMatt Macy 	INP_LIST_WLOCK(pcbinfo);
1776f42a83f2SMatt Macy 	in_pcbremlists(inp);
1777f42a83f2SMatt Macy 	INP_LIST_WUNLOCK(pcbinfo);
1778fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
1779addf2b20SMatt Macy 	/* mark as destruction in progress */
1780f42a83f2SMatt Macy 	inp->inp_flags2 |= INP_FREED;
1781cb6bb230SMatt Macy 	INP_WUNLOCK(inp);
17822a4bd982SGleb Smirnoff 	NET_EPOCH_CALL(in_pcbfree_deferred, &inp->inp_epoch_ctx);
178328696211SRobert Watson }
178428696211SRobert Watson 
178528696211SRobert Watson /*
1786c0a211c5SRobert Watson  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1787c0a211c5SRobert Watson  * port reservation, and preventing it from being returned by inpcb lookups.
1788c0a211c5SRobert Watson  *
1789c0a211c5SRobert Watson  * It is used by TCP to mark an inpcb as unused and avoid future packet
1790c0a211c5SRobert Watson  * delivery or event notification when a socket remains open but TCP has
1791c0a211c5SRobert Watson  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1792c0a211c5SRobert Watson  * or a RST on the wire, and allows the port binding to be reused while still
1793c0a211c5SRobert Watson  * maintaining the invariant that so_pcb always points to a valid inpcb until
1794c0a211c5SRobert Watson  * in_pcbdetach().
1795c0a211c5SRobert Watson  *
1796c0a211c5SRobert Watson  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1797c0a211c5SRobert Watson  * in_pcbnotifyall() and in_pcbpurgeif0()?
179810702a28SRobert Watson  */
179910702a28SRobert Watson void
180010702a28SRobert Watson in_pcbdrop(struct inpcb *inp)
180110702a28SRobert Watson {
180210702a28SRobert Watson 
18038501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
18046573d758SMatt Macy #ifdef INVARIANTS
18056573d758SMatt Macy 	if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
18066573d758SMatt Macy 		MPASS(inp->inp_refcount > 1);
18076573d758SMatt Macy #endif
180810702a28SRobert Watson 
1809fa046d87SRobert Watson 	/*
1810fa046d87SRobert Watson 	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1811fa046d87SRobert Watson 	 * the hash lock...?
1812fa046d87SRobert Watson 	 */
1813ad71fe3cSRobert Watson 	inp->inp_flags |= INP_DROPPED;
1814111d57a6SRobert Watson 	if (inp->inp_flags & INP_INHASHLIST) {
181510702a28SRobert Watson 		struct inpcbport *phd = inp->inp_phd;
181610702a28SRobert Watson 
1817fa046d87SRobert Watson 		INP_HASH_WLOCK(inp->inp_pcbinfo);
18181a43cff9SSean Bruno 		in_pcbremlbgrouphash(inp);
1819b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_hash);
1820b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_portlist);
1821b872626dSMatt Macy 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1822b872626dSMatt Macy 			CK_LIST_REMOVE(phd, phd_hash);
18232a4bd982SGleb Smirnoff 			NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
182410702a28SRobert Watson 		}
1825fa046d87SRobert Watson 		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1826111d57a6SRobert Watson 		inp->inp_flags &= ~INP_INHASHLIST;
182752cd27cbSRobert Watson #ifdef PCBGROUP
182852cd27cbSRobert Watson 		in_pcbgroup_remove(inp);
182952cd27cbSRobert Watson #endif
183010702a28SRobert Watson 	}
183110702a28SRobert Watson }
183210702a28SRobert Watson 
183367107f45SBjoern A. Zeeb #ifdef INET
183454d642bbSRobert Watson /*
183554d642bbSRobert Watson  * Common routines to return the socket addresses associated with inpcbs.
183654d642bbSRobert Watson  */
183726ef6ac4SDon Lewis struct sockaddr *
1838136d4f1cSRobert Watson in_sockaddr(in_port_t port, struct in_addr *addr_p)
183926ef6ac4SDon Lewis {
184026ef6ac4SDon Lewis 	struct sockaddr_in *sin;
184126ef6ac4SDon Lewis 
18421ede983cSDag-Erling Smørgrav 	sin = malloc(sizeof *sin, M_SONAME,
1843a163d034SWarner Losh 		M_WAITOK | M_ZERO);
184426ef6ac4SDon Lewis 	sin->sin_family = AF_INET;
184526ef6ac4SDon Lewis 	sin->sin_len = sizeof(*sin);
184626ef6ac4SDon Lewis 	sin->sin_addr = *addr_p;
184726ef6ac4SDon Lewis 	sin->sin_port = port;
184826ef6ac4SDon Lewis 
184926ef6ac4SDon Lewis 	return (struct sockaddr *)sin;
185026ef6ac4SDon Lewis }
185126ef6ac4SDon Lewis 
1852117bcae7SGarrett Wollman int
185354d642bbSRobert Watson in_getsockaddr(struct socket *so, struct sockaddr **nam)
1854df8bae1dSRodney W. Grimes {
1855136d4f1cSRobert Watson 	struct inpcb *inp;
185626ef6ac4SDon Lewis 	struct in_addr addr;
185726ef6ac4SDon Lewis 	in_port_t port;
185842fa505bSDavid Greenman 
1859fdc984f7STor Egge 	inp = sotoinpcb(so);
186054d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
18616466b28aSRobert Watson 
1862a69042a5SRobert Watson 	INP_RLOCK(inp);
186326ef6ac4SDon Lewis 	port = inp->inp_lport;
186426ef6ac4SDon Lewis 	addr = inp->inp_laddr;
1865a69042a5SRobert Watson 	INP_RUNLOCK(inp);
186642fa505bSDavid Greenman 
186726ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
1868117bcae7SGarrett Wollman 	return 0;
1869df8bae1dSRodney W. Grimes }
1870df8bae1dSRodney W. Grimes 
1871117bcae7SGarrett Wollman int
187254d642bbSRobert Watson in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1873df8bae1dSRodney W. Grimes {
1874136d4f1cSRobert Watson 	struct inpcb *inp;
187526ef6ac4SDon Lewis 	struct in_addr addr;
187626ef6ac4SDon Lewis 	in_port_t port;
187742fa505bSDavid Greenman 
1878fdc984f7STor Egge 	inp = sotoinpcb(so);
187954d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
18806466b28aSRobert Watson 
1881a69042a5SRobert Watson 	INP_RLOCK(inp);
188226ef6ac4SDon Lewis 	port = inp->inp_fport;
188326ef6ac4SDon Lewis 	addr = inp->inp_faddr;
1884a69042a5SRobert Watson 	INP_RUNLOCK(inp);
188542fa505bSDavid Greenman 
188626ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
1887117bcae7SGarrett Wollman 	return 0;
1888df8bae1dSRodney W. Grimes }
1889df8bae1dSRodney W. Grimes 
189026f9a767SRodney W. Grimes void
1891136d4f1cSRobert Watson in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1892136d4f1cSRobert Watson     struct inpcb *(*notify)(struct inpcb *, int))
1893d1c54148SJesper Skriver {
1894f457d580SRobert Watson 	struct inpcb *inp, *inp_temp;
1895d1c54148SJesper Skriver 
18963dc7ebf9SJeffrey Hsu 	INP_INFO_WLOCK(pcbinfo);
1897b872626dSMatt Macy 	CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
18988501a69cSRobert Watson 		INP_WLOCK(inp);
1899d1c54148SJesper Skriver #ifdef INET6
1900f76fcf6dSJeffrey Hsu 		if ((inp->inp_vflag & INP_IPV4) == 0) {
19018501a69cSRobert Watson 			INP_WUNLOCK(inp);
1902d1c54148SJesper Skriver 			continue;
1903f76fcf6dSJeffrey Hsu 		}
1904d1c54148SJesper Skriver #endif
1905d1c54148SJesper Skriver 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1906f76fcf6dSJeffrey Hsu 		    inp->inp_socket == NULL) {
19078501a69cSRobert Watson 			INP_WUNLOCK(inp);
1908d1c54148SJesper Skriver 			continue;
1909d1c54148SJesper Skriver 		}
19103dc7ebf9SJeffrey Hsu 		if ((*notify)(inp, errno))
19118501a69cSRobert Watson 			INP_WUNLOCK(inp);
1912f76fcf6dSJeffrey Hsu 	}
19133dc7ebf9SJeffrey Hsu 	INP_INFO_WUNLOCK(pcbinfo);
1914d1c54148SJesper Skriver }
1915d1c54148SJesper Skriver 
1916e43cc4aeSHajimu UMEMOTO void
1917136d4f1cSRobert Watson in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1918e43cc4aeSHajimu UMEMOTO {
1919e43cc4aeSHajimu UMEMOTO 	struct inpcb *inp;
192059854ecfSHans Petter Selasky 	struct in_multi *inm;
192159854ecfSHans Petter Selasky 	struct in_mfilter *imf;
1922e43cc4aeSHajimu UMEMOTO 	struct ip_moptions *imo;
1923e43cc4aeSHajimu UMEMOTO 
1924ff9b006dSJulien Charbon 	INP_INFO_WLOCK(pcbinfo);
1925b872626dSMatt Macy 	CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
19268501a69cSRobert Watson 		INP_WLOCK(inp);
1927e43cc4aeSHajimu UMEMOTO 		imo = inp->inp_moptions;
1928e43cc4aeSHajimu UMEMOTO 		if ((inp->inp_vflag & INP_IPV4) &&
1929e43cc4aeSHajimu UMEMOTO 		    imo != NULL) {
1930e43cc4aeSHajimu UMEMOTO 			/*
1931e43cc4aeSHajimu UMEMOTO 			 * Unselect the outgoing interface if it is being
1932e43cc4aeSHajimu UMEMOTO 			 * detached.
1933e43cc4aeSHajimu UMEMOTO 			 */
1934e43cc4aeSHajimu UMEMOTO 			if (imo->imo_multicast_ifp == ifp)
1935e43cc4aeSHajimu UMEMOTO 				imo->imo_multicast_ifp = NULL;
1936e43cc4aeSHajimu UMEMOTO 
1937e43cc4aeSHajimu UMEMOTO 			/*
1938e43cc4aeSHajimu UMEMOTO 			 * Drop multicast group membership if we joined
1939e43cc4aeSHajimu UMEMOTO 			 * through the interface being detached.
1940cb6bb230SMatt Macy 			 *
1941cb6bb230SMatt Macy 			 * XXX This can all be deferred to an epoch_call
1942e43cc4aeSHajimu UMEMOTO 			 */
194359854ecfSHans Petter Selasky restart:
194459854ecfSHans Petter Selasky 			IP_MFILTER_FOREACH(imf, &imo->imo_head) {
194559854ecfSHans Petter Selasky 				if ((inm = imf->imf_inm) == NULL)
194659854ecfSHans Petter Selasky 					continue;
194759854ecfSHans Petter Selasky 				if (inm->inm_ifp != ifp)
194859854ecfSHans Petter Selasky 					continue;
194959854ecfSHans Petter Selasky 				ip_mfilter_remove(&imo->imo_head, imf);
1950f3e1324bSStephen Hurd 				IN_MULTI_LOCK_ASSERT();
195159854ecfSHans Petter Selasky 				in_leavegroup_locked(inm, NULL);
195259854ecfSHans Petter Selasky 				ip_mfilter_free(imf);
195359854ecfSHans Petter Selasky 				goto restart;
1954e43cc4aeSHajimu UMEMOTO 			}
1955e43cc4aeSHajimu UMEMOTO 		}
19568501a69cSRobert Watson 		INP_WUNLOCK(inp);
1957e43cc4aeSHajimu UMEMOTO 	}
1958ff9b006dSJulien Charbon 	INP_INFO_WUNLOCK(pcbinfo);
1959e43cc4aeSHajimu UMEMOTO }
1960e43cc4aeSHajimu UMEMOTO 
1961df8bae1dSRodney W. Grimes /*
1962fa046d87SRobert Watson  * Lookup a PCB based on the local address and port.  Caller must hold the
1963fa046d87SRobert Watson  * hash lock.  No inpcb locks or references are acquired.
1964c3229e05SDavid Greenman  */
1965d5e8a67eSHajimu UMEMOTO #define INP_LOOKUP_MAPPED_PCB_COST	3
1966df8bae1dSRodney W. Grimes struct inpcb *
1967136d4f1cSRobert Watson in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
196868e0d7e0SRobert Watson     u_short lport, int lookupflags, struct ucred *cred)
1969df8bae1dSRodney W. Grimes {
1970136d4f1cSRobert Watson 	struct inpcb *inp;
1971d5e8a67eSHajimu UMEMOTO #ifdef INET6
1972d5e8a67eSHajimu UMEMOTO 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1973d5e8a67eSHajimu UMEMOTO #else
1974d5e8a67eSHajimu UMEMOTO 	int matchwild = 3;
1975d5e8a67eSHajimu UMEMOTO #endif
1976d5e8a67eSHajimu UMEMOTO 	int wildcard;
19777bc4aca7SDavid Greenman 
197868e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
197968e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
198068e0d7e0SRobert Watson 
1981fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
19821b73ca0bSSam Leffler 
198368e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1984c3229e05SDavid Greenman 		struct inpcbhead *head;
1985c3229e05SDavid Greenman 		/*
1986c3229e05SDavid Greenman 		 * Look for an unconnected (wildcard foreign addr) PCB that
1987c3229e05SDavid Greenman 		 * matches the local address and port we're looking for.
1988c3229e05SDavid Greenman 		 */
1989712fc218SRobert Watson 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1990712fc218SRobert Watson 		    0, pcbinfo->ipi_hashmask)];
1991b872626dSMatt Macy 		CK_LIST_FOREACH(inp, head, inp_hash) {
1992cfa1ca9dSYoshinobu Inoue #ifdef INET6
1993413628a7SBjoern A. Zeeb 			/* XXX inp locking */
1994369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
1995cfa1ca9dSYoshinobu Inoue 				continue;
1996cfa1ca9dSYoshinobu Inoue #endif
1997c3229e05SDavid Greenman 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1998c3229e05SDavid Greenman 			    inp->inp_laddr.s_addr == laddr.s_addr &&
1999c3229e05SDavid Greenman 			    inp->inp_lport == lport) {
2000c3229e05SDavid Greenman 				/*
2001413628a7SBjoern A. Zeeb 				 * Found?
2002c3229e05SDavid Greenman 				 */
2003413628a7SBjoern A. Zeeb 				if (cred == NULL ||
20040304c731SJamie Gritton 				    prison_equal_ip4(cred->cr_prison,
20050304c731SJamie Gritton 					inp->inp_cred->cr_prison))
2006c3229e05SDavid Greenman 					return (inp);
2007df8bae1dSRodney W. Grimes 			}
2008c3229e05SDavid Greenman 		}
2009c3229e05SDavid Greenman 		/*
2010c3229e05SDavid Greenman 		 * Not found.
2011c3229e05SDavid Greenman 		 */
2012c3229e05SDavid Greenman 		return (NULL);
2013c3229e05SDavid Greenman 	} else {
2014c3229e05SDavid Greenman 		struct inpcbporthead *porthash;
2015c3229e05SDavid Greenman 		struct inpcbport *phd;
2016c3229e05SDavid Greenman 		struct inpcb *match = NULL;
2017c3229e05SDavid Greenman 		/*
2018c3229e05SDavid Greenman 		 * Best fit PCB lookup.
2019c3229e05SDavid Greenman 		 *
2020c3229e05SDavid Greenman 		 * First see if this local port is in use by looking on the
2021c3229e05SDavid Greenman 		 * port hash list.
2022c3229e05SDavid Greenman 		 */
2023712fc218SRobert Watson 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2024712fc218SRobert Watson 		    pcbinfo->ipi_porthashmask)];
2025b872626dSMatt Macy 		CK_LIST_FOREACH(phd, porthash, phd_hash) {
2026c3229e05SDavid Greenman 			if (phd->phd_port == lport)
2027c3229e05SDavid Greenman 				break;
2028c3229e05SDavid Greenman 		}
2029c3229e05SDavid Greenman 		if (phd != NULL) {
2030c3229e05SDavid Greenman 			/*
2031c3229e05SDavid Greenman 			 * Port is in use by one or more PCBs. Look for best
2032c3229e05SDavid Greenman 			 * fit.
2033c3229e05SDavid Greenman 			 */
2034b872626dSMatt Macy 			CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2035c3229e05SDavid Greenman 				wildcard = 0;
2036413628a7SBjoern A. Zeeb 				if (cred != NULL &&
20370304c731SJamie Gritton 				    !prison_equal_ip4(inp->inp_cred->cr_prison,
20380304c731SJamie Gritton 					cred->cr_prison))
2039413628a7SBjoern A. Zeeb 					continue;
2040cfa1ca9dSYoshinobu Inoue #ifdef INET6
2041413628a7SBjoern A. Zeeb 				/* XXX inp locking */
2042369dc8ceSEivind Eklund 				if ((inp->inp_vflag & INP_IPV4) == 0)
2043cfa1ca9dSYoshinobu Inoue 					continue;
2044d5e8a67eSHajimu UMEMOTO 				/*
2045d5e8a67eSHajimu UMEMOTO 				 * We never select the PCB that has
2046d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag and is bound to :: if
2047d5e8a67eSHajimu UMEMOTO 				 * we have another PCB which is bound
2048d5e8a67eSHajimu UMEMOTO 				 * to 0.0.0.0.  If a PCB has the
2049d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag, then we set its cost
2050d5e8a67eSHajimu UMEMOTO 				 * higher than IPv4 only PCBs.
2051d5e8a67eSHajimu UMEMOTO 				 *
2052d5e8a67eSHajimu UMEMOTO 				 * Note that the case only happens
2053d5e8a67eSHajimu UMEMOTO 				 * when a socket is bound to ::, under
2054d5e8a67eSHajimu UMEMOTO 				 * the condition that the use of the
2055d5e8a67eSHajimu UMEMOTO 				 * mapped address is allowed.
2056d5e8a67eSHajimu UMEMOTO 				 */
2057d5e8a67eSHajimu UMEMOTO 				if ((inp->inp_vflag & INP_IPV6) != 0)
2058d5e8a67eSHajimu UMEMOTO 					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2059cfa1ca9dSYoshinobu Inoue #endif
2060c3229e05SDavid Greenman 				if (inp->inp_faddr.s_addr != INADDR_ANY)
2061c3229e05SDavid Greenman 					wildcard++;
206215bd2b43SDavid Greenman 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
206315bd2b43SDavid Greenman 					if (laddr.s_addr == INADDR_ANY)
206415bd2b43SDavid Greenman 						wildcard++;
206515bd2b43SDavid Greenman 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
206615bd2b43SDavid Greenman 						continue;
206715bd2b43SDavid Greenman 				} else {
206815bd2b43SDavid Greenman 					if (laddr.s_addr != INADDR_ANY)
206915bd2b43SDavid Greenman 						wildcard++;
207015bd2b43SDavid Greenman 				}
2071df8bae1dSRodney W. Grimes 				if (wildcard < matchwild) {
2072df8bae1dSRodney W. Grimes 					match = inp;
2073df8bae1dSRodney W. Grimes 					matchwild = wildcard;
2074413628a7SBjoern A. Zeeb 					if (matchwild == 0)
2075df8bae1dSRodney W. Grimes 						break;
2076df8bae1dSRodney W. Grimes 				}
2077df8bae1dSRodney W. Grimes 			}
20783dbdc25cSDavid Greenman 		}
2079df8bae1dSRodney W. Grimes 		return (match);
2080df8bae1dSRodney W. Grimes 	}
2081c3229e05SDavid Greenman }
2082d5e8a67eSHajimu UMEMOTO #undef INP_LOOKUP_MAPPED_PCB_COST
208315bd2b43SDavid Greenman 
20841a43cff9SSean Bruno static struct inpcb *
20851a43cff9SSean Bruno in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
20861a43cff9SSean Bruno     const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
2087a034518aSAndrew Gallatin     uint16_t fport, int lookupflags, int numa_domain)
20881a43cff9SSean Bruno {
2089a034518aSAndrew Gallatin 	struct inpcb *local_wild, *numa_wild;
20901a43cff9SSean Bruno 	const struct inpcblbgrouphead *hdr;
20911a43cff9SSean Bruno 	struct inpcblbgroup *grp;
20928be02ee4SMark Johnston 	uint32_t idx;
20931a43cff9SSean Bruno 
20941a43cff9SSean Bruno 	INP_HASH_LOCK_ASSERT(pcbinfo);
20951a43cff9SSean Bruno 
20969d2877fcSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[
20979d2877fcSMark Johnston 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
20981a43cff9SSean Bruno 
20991a43cff9SSean Bruno 	/*
21001a43cff9SSean Bruno 	 * Order of socket selection:
21011a43cff9SSean Bruno 	 * 1. non-wild.
21021a43cff9SSean Bruno 	 * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
21031a43cff9SSean Bruno 	 *
21041a43cff9SSean Bruno 	 * NOTE:
21051a43cff9SSean Bruno 	 * - Load balanced group does not contain jailed sockets
21061a43cff9SSean Bruno 	 * - Load balanced group does not contain IPv4 mapped INET6 wild sockets
21071a43cff9SSean Bruno 	 */
21088be02ee4SMark Johnston 	local_wild = NULL;
2109a034518aSAndrew Gallatin 	numa_wild = NULL;
211054af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
21111a43cff9SSean Bruno #ifdef INET6
21121a43cff9SSean Bruno 		if (!(grp->il_vflag & INP_IPV4))
21131a43cff9SSean Bruno 			continue;
21141a43cff9SSean Bruno #endif
21158be02ee4SMark Johnston 		if (grp->il_lport != lport)
21168be02ee4SMark Johnston 			continue;
21171a43cff9SSean Bruno 
21188be02ee4SMark Johnston 		idx = INP_PCBLBGROUP_PKTHASH(faddr->s_addr, lport, fport) %
21198be02ee4SMark Johnston 		    grp->il_inpcnt;
2120a034518aSAndrew Gallatin 		if (grp->il_laddr.s_addr == laddr->s_addr) {
2121a034518aSAndrew Gallatin 			if (numa_domain == M_NODOM ||
2122a034518aSAndrew Gallatin 			    grp->il_numa_domain == numa_domain) {
21231a43cff9SSean Bruno 				return (grp->il_inp[idx]);
2124a034518aSAndrew Gallatin 			} else {
2125a034518aSAndrew Gallatin 				numa_wild = grp->il_inp[idx];
2126a034518aSAndrew Gallatin 			}
2127a034518aSAndrew Gallatin 		}
21281a43cff9SSean Bruno 		if (grp->il_laddr.s_addr == INADDR_ANY &&
2129a034518aSAndrew Gallatin 		    (lookupflags & INPLOOKUP_WILDCARD) != 0 &&
2130a034518aSAndrew Gallatin 		    (local_wild == NULL || numa_domain == M_NODOM ||
2131a034518aSAndrew Gallatin 			grp->il_numa_domain == numa_domain)) {
21321a43cff9SSean Bruno 			local_wild = grp->il_inp[idx];
21331a43cff9SSean Bruno 		}
2134a034518aSAndrew Gallatin 	}
2135a034518aSAndrew Gallatin 	if (numa_wild != NULL)
2136a034518aSAndrew Gallatin 		return (numa_wild);
2137a034518aSAndrew Gallatin 
21381a43cff9SSean Bruno 	return (local_wild);
21391a43cff9SSean Bruno }
21401a43cff9SSean Bruno 
214152cd27cbSRobert Watson #ifdef PCBGROUP
214252cd27cbSRobert Watson /*
214352cd27cbSRobert Watson  * Lookup PCB in hash list, using pcbgroup tables.
214452cd27cbSRobert Watson  */
214552cd27cbSRobert Watson static struct inpcb *
214652cd27cbSRobert Watson in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
214752cd27cbSRobert Watson     struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
214852cd27cbSRobert Watson     u_int lport_arg, int lookupflags, struct ifnet *ifp)
214952cd27cbSRobert Watson {
215052cd27cbSRobert Watson 	struct inpcbhead *head;
215152cd27cbSRobert Watson 	struct inpcb *inp, *tmpinp;
215252cd27cbSRobert Watson 	u_short fport = fport_arg, lport = lport_arg;
21537fb2986fSJonathan T. Looney 	bool locked;
215452cd27cbSRobert Watson 
215552cd27cbSRobert Watson 	/*
215652cd27cbSRobert Watson 	 * First look for an exact match.
215752cd27cbSRobert Watson 	 */
215852cd27cbSRobert Watson 	tmpinp = NULL;
215952cd27cbSRobert Watson 	INP_GROUP_LOCK(pcbgroup);
216052cd27cbSRobert Watson 	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
216152cd27cbSRobert Watson 	    pcbgroup->ipg_hashmask)];
2162feeef850SMatt Macy 	CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
216352cd27cbSRobert Watson #ifdef INET6
216452cd27cbSRobert Watson 		/* XXX inp locking */
216552cd27cbSRobert Watson 		if ((inp->inp_vflag & INP_IPV4) == 0)
216652cd27cbSRobert Watson 			continue;
216752cd27cbSRobert Watson #endif
216852cd27cbSRobert Watson 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
216952cd27cbSRobert Watson 		    inp->inp_laddr.s_addr == laddr.s_addr &&
217052cd27cbSRobert Watson 		    inp->inp_fport == fport &&
217152cd27cbSRobert Watson 		    inp->inp_lport == lport) {
217252cd27cbSRobert Watson 			/*
217352cd27cbSRobert Watson 			 * XXX We should be able to directly return
217452cd27cbSRobert Watson 			 * the inp here, without any checks.
217552cd27cbSRobert Watson 			 * Well unless both bound with SO_REUSEPORT?
217652cd27cbSRobert Watson 			 */
217752cd27cbSRobert Watson 			if (prison_flag(inp->inp_cred, PR_IP4))
217852cd27cbSRobert Watson 				goto found;
217952cd27cbSRobert Watson 			if (tmpinp == NULL)
218052cd27cbSRobert Watson 				tmpinp = inp;
218152cd27cbSRobert Watson 		}
218252cd27cbSRobert Watson 	}
218352cd27cbSRobert Watson 	if (tmpinp != NULL) {
218452cd27cbSRobert Watson 		inp = tmpinp;
218552cd27cbSRobert Watson 		goto found;
218652cd27cbSRobert Watson 	}
218752cd27cbSRobert Watson 
21880a100a6fSAdrian Chadd #ifdef	RSS
21890a100a6fSAdrian Chadd 	/*
21900a100a6fSAdrian Chadd 	 * For incoming connections, we may wish to do a wildcard
21910a100a6fSAdrian Chadd 	 * match for an RSS-local socket.
21920a100a6fSAdrian Chadd 	 */
21930a100a6fSAdrian Chadd 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
21940a100a6fSAdrian Chadd 		struct inpcb *local_wild = NULL, *local_exact = NULL;
21950a100a6fSAdrian Chadd #ifdef INET6
21960a100a6fSAdrian Chadd 		struct inpcb *local_wild_mapped = NULL;
21970a100a6fSAdrian Chadd #endif
21980a100a6fSAdrian Chadd 		struct inpcb *jail_wild = NULL;
21990a100a6fSAdrian Chadd 		struct inpcbhead *head;
22000a100a6fSAdrian Chadd 		int injail;
22010a100a6fSAdrian Chadd 
22020a100a6fSAdrian Chadd 		/*
22030a100a6fSAdrian Chadd 		 * Order of socket selection - we always prefer jails.
22040a100a6fSAdrian Chadd 		 *      1. jailed, non-wild.
22050a100a6fSAdrian Chadd 		 *      2. jailed, wild.
22060a100a6fSAdrian Chadd 		 *      3. non-jailed, non-wild.
22070a100a6fSAdrian Chadd 		 *      4. non-jailed, wild.
22080a100a6fSAdrian Chadd 		 */
22090a100a6fSAdrian Chadd 
22100a100a6fSAdrian Chadd 		head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
22110a100a6fSAdrian Chadd 		    lport, 0, pcbgroup->ipg_hashmask)];
2212feeef850SMatt Macy 		CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
22130a100a6fSAdrian Chadd #ifdef INET6
22140a100a6fSAdrian Chadd 			/* XXX inp locking */
22150a100a6fSAdrian Chadd 			if ((inp->inp_vflag & INP_IPV4) == 0)
22160a100a6fSAdrian Chadd 				continue;
22170a100a6fSAdrian Chadd #endif
22180a100a6fSAdrian Chadd 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
22190a100a6fSAdrian Chadd 			    inp->inp_lport != lport)
22200a100a6fSAdrian Chadd 				continue;
22210a100a6fSAdrian Chadd 
22220a100a6fSAdrian Chadd 			injail = prison_flag(inp->inp_cred, PR_IP4);
22230a100a6fSAdrian Chadd 			if (injail) {
22240a100a6fSAdrian Chadd 				if (prison_check_ip4(inp->inp_cred,
22250a100a6fSAdrian Chadd 				    &laddr) != 0)
22260a100a6fSAdrian Chadd 					continue;
22270a100a6fSAdrian Chadd 			} else {
22280a100a6fSAdrian Chadd 				if (local_exact != NULL)
22290a100a6fSAdrian Chadd 					continue;
22300a100a6fSAdrian Chadd 			}
22310a100a6fSAdrian Chadd 
22320a100a6fSAdrian Chadd 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
22330a100a6fSAdrian Chadd 				if (injail)
22340a100a6fSAdrian Chadd 					goto found;
22350a100a6fSAdrian Chadd 				else
22360a100a6fSAdrian Chadd 					local_exact = inp;
22370a100a6fSAdrian Chadd 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
22380a100a6fSAdrian Chadd #ifdef INET6
22390a100a6fSAdrian Chadd 				/* XXX inp locking, NULL check */
22400a100a6fSAdrian Chadd 				if (inp->inp_vflag & INP_IPV6PROTO)
22410a100a6fSAdrian Chadd 					local_wild_mapped = inp;
22420a100a6fSAdrian Chadd 				else
22430a100a6fSAdrian Chadd #endif
22440a100a6fSAdrian Chadd 					if (injail)
22450a100a6fSAdrian Chadd 						jail_wild = inp;
22460a100a6fSAdrian Chadd 					else
22470a100a6fSAdrian Chadd 						local_wild = inp;
22480a100a6fSAdrian Chadd 			}
22490a100a6fSAdrian Chadd 		} /* LIST_FOREACH */
22500a100a6fSAdrian Chadd 
22510a100a6fSAdrian Chadd 		inp = jail_wild;
22520a100a6fSAdrian Chadd 		if (inp == NULL)
22530a100a6fSAdrian Chadd 			inp = local_exact;
22540a100a6fSAdrian Chadd 		if (inp == NULL)
22550a100a6fSAdrian Chadd 			inp = local_wild;
22560a100a6fSAdrian Chadd #ifdef INET6
22570a100a6fSAdrian Chadd 		if (inp == NULL)
22580a100a6fSAdrian Chadd 			inp = local_wild_mapped;
22590a100a6fSAdrian Chadd #endif
22600a100a6fSAdrian Chadd 		if (inp != NULL)
22610a100a6fSAdrian Chadd 			goto found;
22620a100a6fSAdrian Chadd 	}
22630a100a6fSAdrian Chadd #endif
22640a100a6fSAdrian Chadd 
226552cd27cbSRobert Watson 	/*
226652cd27cbSRobert Watson 	 * Then look for a wildcard match, if requested.
226752cd27cbSRobert Watson 	 */
226852cd27cbSRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
226952cd27cbSRobert Watson 		struct inpcb *local_wild = NULL, *local_exact = NULL;
227052cd27cbSRobert Watson #ifdef INET6
227152cd27cbSRobert Watson 		struct inpcb *local_wild_mapped = NULL;
227252cd27cbSRobert Watson #endif
227352cd27cbSRobert Watson 		struct inpcb *jail_wild = NULL;
227452cd27cbSRobert Watson 		struct inpcbhead *head;
227552cd27cbSRobert Watson 		int injail;
227652cd27cbSRobert Watson 
227752cd27cbSRobert Watson 		/*
227852cd27cbSRobert Watson 		 * Order of socket selection - we always prefer jails.
227952cd27cbSRobert Watson 		 *      1. jailed, non-wild.
228052cd27cbSRobert Watson 		 *      2. jailed, wild.
228152cd27cbSRobert Watson 		 *      3. non-jailed, non-wild.
228252cd27cbSRobert Watson 		 *      4. non-jailed, wild.
228352cd27cbSRobert Watson 		 */
228452cd27cbSRobert Watson 		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
228552cd27cbSRobert Watson 		    0, pcbinfo->ipi_wildmask)];
2286feeef850SMatt Macy 		CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
228752cd27cbSRobert Watson #ifdef INET6
228852cd27cbSRobert Watson 			/* XXX inp locking */
228952cd27cbSRobert Watson 			if ((inp->inp_vflag & INP_IPV4) == 0)
229052cd27cbSRobert Watson 				continue;
229152cd27cbSRobert Watson #endif
229252cd27cbSRobert Watson 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
229352cd27cbSRobert Watson 			    inp->inp_lport != lport)
229452cd27cbSRobert Watson 				continue;
229552cd27cbSRobert Watson 
229652cd27cbSRobert Watson 			injail = prison_flag(inp->inp_cred, PR_IP4);
229752cd27cbSRobert Watson 			if (injail) {
229852cd27cbSRobert Watson 				if (prison_check_ip4(inp->inp_cred,
229952cd27cbSRobert Watson 				    &laddr) != 0)
230052cd27cbSRobert Watson 					continue;
230152cd27cbSRobert Watson 			} else {
230252cd27cbSRobert Watson 				if (local_exact != NULL)
230352cd27cbSRobert Watson 					continue;
230452cd27cbSRobert Watson 			}
230552cd27cbSRobert Watson 
230652cd27cbSRobert Watson 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
230752cd27cbSRobert Watson 				if (injail)
230852cd27cbSRobert Watson 					goto found;
230952cd27cbSRobert Watson 				else
231052cd27cbSRobert Watson 					local_exact = inp;
231152cd27cbSRobert Watson 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
231252cd27cbSRobert Watson #ifdef INET6
231352cd27cbSRobert Watson 				/* XXX inp locking, NULL check */
231452cd27cbSRobert Watson 				if (inp->inp_vflag & INP_IPV6PROTO)
231552cd27cbSRobert Watson 					local_wild_mapped = inp;
231652cd27cbSRobert Watson 				else
231783e521ecSBjoern A. Zeeb #endif
231852cd27cbSRobert Watson 					if (injail)
231952cd27cbSRobert Watson 						jail_wild = inp;
232052cd27cbSRobert Watson 					else
232152cd27cbSRobert Watson 						local_wild = inp;
232252cd27cbSRobert Watson 			}
232352cd27cbSRobert Watson 		} /* LIST_FOREACH */
232452cd27cbSRobert Watson 		inp = jail_wild;
232552cd27cbSRobert Watson 		if (inp == NULL)
232652cd27cbSRobert Watson 			inp = local_exact;
232752cd27cbSRobert Watson 		if (inp == NULL)
232852cd27cbSRobert Watson 			inp = local_wild;
232952cd27cbSRobert Watson #ifdef INET6
233052cd27cbSRobert Watson 		if (inp == NULL)
233152cd27cbSRobert Watson 			inp = local_wild_mapped;
233283e521ecSBjoern A. Zeeb #endif
233352cd27cbSRobert Watson 		if (inp != NULL)
233452cd27cbSRobert Watson 			goto found;
233552cd27cbSRobert Watson 	} /* if (lookupflags & INPLOOKUP_WILDCARD) */
233652cd27cbSRobert Watson 	INP_GROUP_UNLOCK(pcbgroup);
233752cd27cbSRobert Watson 	return (NULL);
233852cd27cbSRobert Watson 
233952cd27cbSRobert Watson found:
23407fb2986fSJonathan T. Looney 	if (lookupflags & INPLOOKUP_WLOCKPCB)
2341b9a9e8e9SNavdeep Parhar 		locked = INP_TRY_WLOCK(inp);
23427fb2986fSJonathan T. Looney 	else if (lookupflags & INPLOOKUP_RLOCKPCB)
2343b9a9e8e9SNavdeep Parhar 		locked = INP_TRY_RLOCK(inp);
23447fb2986fSJonathan T. Looney 	else
23457fb2986fSJonathan T. Looney 		panic("%s: locking bug", __func__);
2346483305b9SMatt Macy 	if (__predict_false(locked && (inp->inp_flags2 & INP_FREED))) {
2347483305b9SMatt Macy 		if (lookupflags & INPLOOKUP_WLOCKPCB)
2348483305b9SMatt Macy 			INP_WUNLOCK(inp);
2349483305b9SMatt Macy 		else
2350483305b9SMatt Macy 			INP_RUNLOCK(inp);
2351483305b9SMatt Macy 		return (NULL);
2352483305b9SMatt Macy 	} else if (!locked)
235352cd27cbSRobert Watson 		in_pcbref(inp);
235452cd27cbSRobert Watson 	INP_GROUP_UNLOCK(pcbgroup);
23557fb2986fSJonathan T. Looney 	if (!locked) {
235652cd27cbSRobert Watson 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
235752cd27cbSRobert Watson 			INP_WLOCK(inp);
235852cd27cbSRobert Watson 			if (in_pcbrele_wlocked(inp))
235952cd27cbSRobert Watson 				return (NULL);
23607fb2986fSJonathan T. Looney 		} else {
236152cd27cbSRobert Watson 			INP_RLOCK(inp);
236252cd27cbSRobert Watson 			if (in_pcbrele_rlocked(inp))
236352cd27cbSRobert Watson 				return (NULL);
23647fb2986fSJonathan T. Looney 		}
23657fb2986fSJonathan T. Looney 	}
23667fb2986fSJonathan T. Looney #ifdef INVARIANTS
23677fb2986fSJonathan T. Looney 	if (lookupflags & INPLOOKUP_WLOCKPCB)
23687fb2986fSJonathan T. Looney 		INP_WLOCK_ASSERT(inp);
23697fb2986fSJonathan T. Looney 	else
23707fb2986fSJonathan T. Looney 		INP_RLOCK_ASSERT(inp);
23717fb2986fSJonathan T. Looney #endif
237252cd27cbSRobert Watson 	return (inp);
237352cd27cbSRobert Watson }
237452cd27cbSRobert Watson #endif /* PCBGROUP */
237552cd27cbSRobert Watson 
237615bd2b43SDavid Greenman /*
2377fa046d87SRobert Watson  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
2378fa046d87SRobert Watson  * that the caller has locked the hash list, and will not perform any further
2379fa046d87SRobert Watson  * locking or reference operations on either the hash list or the connection.
238015bd2b43SDavid Greenman  */
2381fa046d87SRobert Watson static struct inpcb *
2382fa046d87SRobert Watson in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
238368e0d7e0SRobert Watson     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2384a034518aSAndrew Gallatin     struct ifnet *ifp, uint8_t numa_domain)
238515bd2b43SDavid Greenman {
238615bd2b43SDavid Greenman 	struct inpcbhead *head;
2387413628a7SBjoern A. Zeeb 	struct inpcb *inp, *tmpinp;
238815bd2b43SDavid Greenman 	u_short fport = fport_arg, lport = lport_arg;
238915bd2b43SDavid Greenman 
239068e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
239168e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2392d797164aSGleb Smirnoff 	INP_HASH_LOCK_ASSERT(pcbinfo);
2393d797164aSGleb Smirnoff 
239415bd2b43SDavid Greenman 	/*
239515bd2b43SDavid Greenman 	 * First look for an exact match.
239615bd2b43SDavid Greenman 	 */
2397413628a7SBjoern A. Zeeb 	tmpinp = NULL;
2398712fc218SRobert Watson 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2399712fc218SRobert Watson 	    pcbinfo->ipi_hashmask)];
2400b872626dSMatt Macy 	CK_LIST_FOREACH(inp, head, inp_hash) {
2401cfa1ca9dSYoshinobu Inoue #ifdef INET6
2402413628a7SBjoern A. Zeeb 		/* XXX inp locking */
2403369dc8ceSEivind Eklund 		if ((inp->inp_vflag & INP_IPV4) == 0)
2404cfa1ca9dSYoshinobu Inoue 			continue;
2405cfa1ca9dSYoshinobu Inoue #endif
24066d6a026bSDavid Greenman 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
2407ca98b82cSDavid Greenman 		    inp->inp_laddr.s_addr == laddr.s_addr &&
2408ca98b82cSDavid Greenman 		    inp->inp_fport == fport &&
2409413628a7SBjoern A. Zeeb 		    inp->inp_lport == lport) {
2410413628a7SBjoern A. Zeeb 			/*
2411413628a7SBjoern A. Zeeb 			 * XXX We should be able to directly return
2412413628a7SBjoern A. Zeeb 			 * the inp here, without any checks.
2413413628a7SBjoern A. Zeeb 			 * Well unless both bound with SO_REUSEPORT?
2414413628a7SBjoern A. Zeeb 			 */
24150304c731SJamie Gritton 			if (prison_flag(inp->inp_cred, PR_IP4))
2416c3229e05SDavid Greenman 				return (inp);
2417413628a7SBjoern A. Zeeb 			if (tmpinp == NULL)
2418413628a7SBjoern A. Zeeb 				tmpinp = inp;
2419c3229e05SDavid Greenman 		}
2420413628a7SBjoern A. Zeeb 	}
2421413628a7SBjoern A. Zeeb 	if (tmpinp != NULL)
2422413628a7SBjoern A. Zeeb 		return (tmpinp);
2423e3fd5ffdSRobert Watson 
2424e3fd5ffdSRobert Watson 	/*
24251a43cff9SSean Bruno 	 * Then look in lb group (for wildcard match).
24261a43cff9SSean Bruno 	 */
2427d9ff5789SMark Johnston 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
24281a43cff9SSean Bruno 		inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2429a034518aSAndrew Gallatin 		    fport, lookupflags, numa_domain);
2430d9ff5789SMark Johnston 		if (inp != NULL)
24311a43cff9SSean Bruno 			return (inp);
24321a43cff9SSean Bruno 	}
24331a43cff9SSean Bruno 
24341a43cff9SSean Bruno 	/*
2435e3fd5ffdSRobert Watson 	 * Then look for a wildcard match, if requested.
2436e3fd5ffdSRobert Watson 	 */
243768e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2438413628a7SBjoern A. Zeeb 		struct inpcb *local_wild = NULL, *local_exact = NULL;
2439e3fd5ffdSRobert Watson #ifdef INET6
2440cfa1ca9dSYoshinobu Inoue 		struct inpcb *local_wild_mapped = NULL;
2441e3fd5ffdSRobert Watson #endif
2442413628a7SBjoern A. Zeeb 		struct inpcb *jail_wild = NULL;
2443413628a7SBjoern A. Zeeb 		int injail;
2444413628a7SBjoern A. Zeeb 
2445413628a7SBjoern A. Zeeb 		/*
2446413628a7SBjoern A. Zeeb 		 * Order of socket selection - we always prefer jails.
2447413628a7SBjoern A. Zeeb 		 *      1. jailed, non-wild.
2448413628a7SBjoern A. Zeeb 		 *      2. jailed, wild.
2449413628a7SBjoern A. Zeeb 		 *      3. non-jailed, non-wild.
2450413628a7SBjoern A. Zeeb 		 *      4. non-jailed, wild.
2451413628a7SBjoern A. Zeeb 		 */
24526d6a026bSDavid Greenman 
2453712fc218SRobert Watson 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2454712fc218SRobert Watson 		    0, pcbinfo->ipi_hashmask)];
2455b872626dSMatt Macy 		CK_LIST_FOREACH(inp, head, inp_hash) {
2456cfa1ca9dSYoshinobu Inoue #ifdef INET6
2457413628a7SBjoern A. Zeeb 			/* XXX inp locking */
2458369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
2459cfa1ca9dSYoshinobu Inoue 				continue;
2460cfa1ca9dSYoshinobu Inoue #endif
2461413628a7SBjoern A. Zeeb 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
2462413628a7SBjoern A. Zeeb 			    inp->inp_lport != lport)
2463413628a7SBjoern A. Zeeb 				continue;
2464413628a7SBjoern A. Zeeb 
24650304c731SJamie Gritton 			injail = prison_flag(inp->inp_cred, PR_IP4);
2466413628a7SBjoern A. Zeeb 			if (injail) {
2467b89e82ddSJamie Gritton 				if (prison_check_ip4(inp->inp_cred,
2468b89e82ddSJamie Gritton 				    &laddr) != 0)
2469413628a7SBjoern A. Zeeb 					continue;
2470413628a7SBjoern A. Zeeb 			} else {
2471413628a7SBjoern A. Zeeb 				if (local_exact != NULL)
2472413628a7SBjoern A. Zeeb 					continue;
2473413628a7SBjoern A. Zeeb 			}
2474413628a7SBjoern A. Zeeb 
2475413628a7SBjoern A. Zeeb 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
2476413628a7SBjoern A. Zeeb 				if (injail)
2477c3229e05SDavid Greenman 					return (inp);
2478413628a7SBjoern A. Zeeb 				else
2479413628a7SBjoern A. Zeeb 					local_exact = inp;
2480413628a7SBjoern A. Zeeb 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2481e3fd5ffdSRobert Watson #ifdef INET6
2482413628a7SBjoern A. Zeeb 				/* XXX inp locking, NULL check */
24835cd54324SBjoern A. Zeeb 				if (inp->inp_vflag & INP_IPV6PROTO)
2484cfa1ca9dSYoshinobu Inoue 					local_wild_mapped = inp;
2485cfa1ca9dSYoshinobu Inoue 				else
248683e521ecSBjoern A. Zeeb #endif
2487413628a7SBjoern A. Zeeb 					if (injail)
2488413628a7SBjoern A. Zeeb 						jail_wild = inp;
2489413628a7SBjoern A. Zeeb 					else
24906d6a026bSDavid Greenman 						local_wild = inp;
24916d6a026bSDavid Greenman 			}
2492413628a7SBjoern A. Zeeb 		} /* LIST_FOREACH */
2493413628a7SBjoern A. Zeeb 		if (jail_wild != NULL)
2494413628a7SBjoern A. Zeeb 			return (jail_wild);
2495413628a7SBjoern A. Zeeb 		if (local_exact != NULL)
2496413628a7SBjoern A. Zeeb 			return (local_exact);
2497413628a7SBjoern A. Zeeb 		if (local_wild != NULL)
2498c3229e05SDavid Greenman 			return (local_wild);
2499413628a7SBjoern A. Zeeb #ifdef INET6
2500413628a7SBjoern A. Zeeb 		if (local_wild_mapped != NULL)
2501413628a7SBjoern A. Zeeb 			return (local_wild_mapped);
250283e521ecSBjoern A. Zeeb #endif
250368e0d7e0SRobert Watson 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2504413628a7SBjoern A. Zeeb 
25056d6a026bSDavid Greenman 	return (NULL);
250615bd2b43SDavid Greenman }
2507fa046d87SRobert Watson 
2508fa046d87SRobert Watson /*
2509fa046d87SRobert Watson  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
2510fa046d87SRobert Watson  * hash list lock, and will return the inpcb locked (i.e., requires
2511fa046d87SRobert Watson  * INPLOOKUP_LOCKPCB).
2512fa046d87SRobert Watson  */
2513fa046d87SRobert Watson static struct inpcb *
2514fa046d87SRobert Watson in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2515fa046d87SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2516a034518aSAndrew Gallatin     struct ifnet *ifp, uint8_t numa_domain)
2517fa046d87SRobert Watson {
2518fa046d87SRobert Watson 	struct inpcb *inp;
2519fa046d87SRobert Watson 
2520fa046d87SRobert Watson 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
252108d9c920SGleb Smirnoff 	    lookupflags & INPLOOKUP_WILDCARD, ifp, numa_domain);
2522fa046d87SRobert Watson 	if (inp != NULL) {
2523fa046d87SRobert Watson 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
2524fa046d87SRobert Watson 			INP_WLOCK(inp);
25253d348772SMatt Macy 		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2526fa046d87SRobert Watson 			INP_RLOCK(inp);
25273d348772SMatt Macy 		} else
25283d348772SMatt Macy 			panic("%s: locking bug", __func__);
252908d9c920SGleb Smirnoff 		if (__predict_false(inp->inp_flags2 & INP_FREED)) {
253008d9c920SGleb Smirnoff 			INP_UNLOCK(inp);
253108d9c920SGleb Smirnoff 			inp = NULL;
25323d348772SMatt Macy 		}
25333d348772SMatt Macy 	}
2534d797164aSGleb Smirnoff 
2535fa046d87SRobert Watson 	return (inp);
2536fa046d87SRobert Watson }
2537fa046d87SRobert Watson 
2538fa046d87SRobert Watson /*
2539d3c1f003SRobert Watson  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2540d3c1f003SRobert Watson  * from which a pre-calculated hash value may be extracted.
254152cd27cbSRobert Watson  *
254252cd27cbSRobert Watson  * Possibly more of this logic should be in in_pcbgroup.c.
2543fa046d87SRobert Watson  */
2544fa046d87SRobert Watson struct inpcb *
2545fa046d87SRobert Watson in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2546fa046d87SRobert Watson     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2547fa046d87SRobert Watson {
25487527624eSRobert Watson #if defined(PCBGROUP) && !defined(RSS)
254952cd27cbSRobert Watson 	struct inpcbgroup *pcbgroup;
255052cd27cbSRobert Watson #endif
2551fa046d87SRobert Watson 
2552fa046d87SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2553fa046d87SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
25541db08fbeSGleb Smirnoff 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
25551db08fbeSGleb Smirnoff 	    ("%s: LOCKPCB not set", __func__));
2556fa046d87SRobert Watson 
25577527624eSRobert Watson 	/*
25587527624eSRobert Watson 	 * When not using RSS, use connection groups in preference to the
25597527624eSRobert Watson 	 * reservation table when looking up 4-tuples.  When using RSS, just
25607527624eSRobert Watson 	 * use the reservation table, due to the cost of the Toeplitz hash
25617527624eSRobert Watson 	 * in software.
25627527624eSRobert Watson 	 *
25637527624eSRobert Watson 	 * XXXRW: This policy belongs in the pcbgroup code, as in principle
25647527624eSRobert Watson 	 * we could be doing RSS with a non-Toeplitz hash that is affordable
25657527624eSRobert Watson 	 * in software.
25667527624eSRobert Watson 	 */
25677527624eSRobert Watson #if defined(PCBGROUP) && !defined(RSS)
256852cd27cbSRobert Watson 	if (in_pcbgroup_enabled(pcbinfo)) {
256952cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
257052cd27cbSRobert Watson 		    fport);
257152cd27cbSRobert Watson 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
257252cd27cbSRobert Watson 		    laddr, lport, lookupflags, ifp));
257352cd27cbSRobert Watson 	}
257452cd27cbSRobert Watson #endif
2575fa046d87SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2576a034518aSAndrew Gallatin 	    lookupflags, ifp, M_NODOM));
2577fa046d87SRobert Watson }
2578d3c1f003SRobert Watson 
2579d3c1f003SRobert Watson struct inpcb *
2580d3c1f003SRobert Watson in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2581d3c1f003SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2582d3c1f003SRobert Watson     struct ifnet *ifp, struct mbuf *m)
2583d3c1f003SRobert Watson {
258452cd27cbSRobert Watson #ifdef PCBGROUP
258552cd27cbSRobert Watson 	struct inpcbgroup *pcbgroup;
258652cd27cbSRobert Watson #endif
2587d3c1f003SRobert Watson 
2588d3c1f003SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2589d3c1f003SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
25901db08fbeSGleb Smirnoff 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
25911db08fbeSGleb Smirnoff 	    ("%s: LOCKPCB not set", __func__));
2592d3c1f003SRobert Watson 
259352cd27cbSRobert Watson #ifdef PCBGROUP
25947527624eSRobert Watson 	/*
25957527624eSRobert Watson 	 * If we can use a hardware-generated hash to look up the connection
25967527624eSRobert Watson 	 * group, use that connection group to find the inpcb.  Otherwise
25977527624eSRobert Watson 	 * fall back on a software hash -- or the reservation table if we're
25987527624eSRobert Watson 	 * using RSS.
25997527624eSRobert Watson 	 *
26007527624eSRobert Watson 	 * XXXRW: As above, that policy belongs in the pcbgroup code.
26017527624eSRobert Watson 	 */
26027527624eSRobert Watson 	if (in_pcbgroup_enabled(pcbinfo) &&
26037527624eSRobert Watson 	    !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
260452cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
260552cd27cbSRobert Watson 		    m->m_pkthdr.flowid);
260652cd27cbSRobert Watson 		if (pcbgroup != NULL)
260752cd27cbSRobert Watson 			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
260852cd27cbSRobert Watson 			    fport, laddr, lport, lookupflags, ifp));
26097527624eSRobert Watson #ifndef RSS
261052cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
261152cd27cbSRobert Watson 		    fport);
261252cd27cbSRobert Watson 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
261352cd27cbSRobert Watson 		    laddr, lport, lookupflags, ifp));
26147527624eSRobert Watson #endif
261552cd27cbSRobert Watson 	}
261652cd27cbSRobert Watson #endif
2617d3c1f003SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2618a034518aSAndrew Gallatin 	    lookupflags, ifp, m->m_pkthdr.numa_domain));
2619d3c1f003SRobert Watson }
262067107f45SBjoern A. Zeeb #endif /* INET */
262115bd2b43SDavid Greenman 
26227bc4aca7SDavid Greenman /*
2623c3229e05SDavid Greenman  * Insert PCB onto various hash lists.
26247bc4aca7SDavid Greenman  */
262552cd27cbSRobert Watson static int
2626fe1274eeSMichael Tuexen in_pcbinshash_internal(struct inpcb *inp, struct mbuf *m)
262715bd2b43SDavid Greenman {
2628c3229e05SDavid Greenman 	struct inpcbhead *pcbhash;
2629c3229e05SDavid Greenman 	struct inpcbporthead *pcbporthash;
2630c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2631c3229e05SDavid Greenman 	struct inpcbport *phd;
2632cfa1ca9dSYoshinobu Inoue 	u_int32_t hashkey_faddr;
26331a43cff9SSean Bruno 	int so_options;
263415bd2b43SDavid Greenman 
26358501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2636fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2637fa046d87SRobert Watson 
2638111d57a6SRobert Watson 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2639111d57a6SRobert Watson 	    ("in_pcbinshash: INP_INHASHLIST"));
2640602cc7f1SRobert Watson 
2641cfa1ca9dSYoshinobu Inoue #ifdef INET6
2642cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
26431b44e5ffSAndrey V. Elsukov 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2644cfa1ca9dSYoshinobu Inoue 	else
264583e521ecSBjoern A. Zeeb #endif
2646cfa1ca9dSYoshinobu Inoue 	hashkey_faddr = inp->inp_faddr.s_addr;
2647cfa1ca9dSYoshinobu Inoue 
2648712fc218SRobert Watson 	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2649712fc218SRobert Watson 		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
265015bd2b43SDavid Greenman 
2651712fc218SRobert Watson 	pcbporthash = &pcbinfo->ipi_porthashbase[
2652712fc218SRobert Watson 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2653c3229e05SDavid Greenman 
2654c3229e05SDavid Greenman 	/*
26551a43cff9SSean Bruno 	 * Add entry to load balance group.
26561a43cff9SSean Bruno 	 * Only do this if SO_REUSEPORT_LB is set.
26571a43cff9SSean Bruno 	 */
26581a43cff9SSean Bruno 	so_options = inp_so_options(inp);
26591a43cff9SSean Bruno 	if (so_options & SO_REUSEPORT_LB) {
2660a034518aSAndrew Gallatin 		int ret = in_pcbinslbgrouphash(inp, M_NODOM);
26611a43cff9SSean Bruno 		if (ret) {
26621a43cff9SSean Bruno 			/* pcb lb group malloc fail (ret=ENOBUFS). */
26631a43cff9SSean Bruno 			return (ret);
26641a43cff9SSean Bruno 		}
26651a43cff9SSean Bruno 	}
26661a43cff9SSean Bruno 
26671a43cff9SSean Bruno 	/*
2668c3229e05SDavid Greenman 	 * Go through port list and look for a head for this lport.
2669c3229e05SDavid Greenman 	 */
2670b872626dSMatt Macy 	CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2671c3229e05SDavid Greenman 		if (phd->phd_port == inp->inp_lport)
2672c3229e05SDavid Greenman 			break;
2673c3229e05SDavid Greenman 	}
2674c3229e05SDavid Greenman 	/*
2675c3229e05SDavid Greenman 	 * If none exists, malloc one and tack it on.
2676c3229e05SDavid Greenman 	 */
2677c3229e05SDavid Greenman 	if (phd == NULL) {
26781ede983cSDag-Erling Smørgrav 		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2679c3229e05SDavid Greenman 		if (phd == NULL) {
2680c3229e05SDavid Greenman 			return (ENOBUFS); /* XXX */
2681c3229e05SDavid Greenman 		}
2682f09ee4fcSMatt Macy 		bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2683c3229e05SDavid Greenman 		phd->phd_port = inp->inp_lport;
2684b872626dSMatt Macy 		CK_LIST_INIT(&phd->phd_pcblist);
2685b872626dSMatt Macy 		CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2686c3229e05SDavid Greenman 	}
2687c3229e05SDavid Greenman 	inp->inp_phd = phd;
2688b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2689b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2690111d57a6SRobert Watson 	inp->inp_flags |= INP_INHASHLIST;
269152cd27cbSRobert Watson #ifdef PCBGROUP
2692fe1274eeSMichael Tuexen 	if (m != NULL) {
2693fe1274eeSMichael Tuexen 		in_pcbgroup_update_mbuf(inp, m);
2694fe1274eeSMichael Tuexen 	} else {
269552cd27cbSRobert Watson 		in_pcbgroup_update(inp);
2696fe1274eeSMichael Tuexen 	}
269752cd27cbSRobert Watson #endif
2698c3229e05SDavid Greenman 	return (0);
269915bd2b43SDavid Greenman }
270015bd2b43SDavid Greenman 
270152cd27cbSRobert Watson int
270252cd27cbSRobert Watson in_pcbinshash(struct inpcb *inp)
270352cd27cbSRobert Watson {
270452cd27cbSRobert Watson 
2705fe1274eeSMichael Tuexen 	return (in_pcbinshash_internal(inp, NULL));
270652cd27cbSRobert Watson }
270752cd27cbSRobert Watson 
270852cd27cbSRobert Watson int
2709fe1274eeSMichael Tuexen in_pcbinshash_mbuf(struct inpcb *inp, struct mbuf *m)
271052cd27cbSRobert Watson {
271152cd27cbSRobert Watson 
2712fe1274eeSMichael Tuexen 	return (in_pcbinshash_internal(inp, m));
271352cd27cbSRobert Watson }
271452cd27cbSRobert Watson 
271552cd27cbSRobert Watson /*
2716c3229e05SDavid Greenman  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2717c3229e05SDavid Greenman  * changed. NOTE: This does not handle the case of the lport changing (the
2718c3229e05SDavid Greenman  * hashed port list would have to be updated as well), so the lport must
2719c3229e05SDavid Greenman  * not change after in_pcbinshash() has been called.
2720c3229e05SDavid Greenman  */
272115bd2b43SDavid Greenman void
2722d3c1f003SRobert Watson in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
272315bd2b43SDavid Greenman {
272459daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
272515bd2b43SDavid Greenman 	struct inpcbhead *head;
2726cfa1ca9dSYoshinobu Inoue 	u_int32_t hashkey_faddr;
272715bd2b43SDavid Greenman 
27288501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2729fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2730fa046d87SRobert Watson 
2731111d57a6SRobert Watson 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2732111d57a6SRobert Watson 	    ("in_pcbrehash: !INP_INHASHLIST"));
2733602cc7f1SRobert Watson 
2734cfa1ca9dSYoshinobu Inoue #ifdef INET6
2735cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
27361b44e5ffSAndrey V. Elsukov 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2737cfa1ca9dSYoshinobu Inoue 	else
273883e521ecSBjoern A. Zeeb #endif
2739cfa1ca9dSYoshinobu Inoue 	hashkey_faddr = inp->inp_faddr.s_addr;
2740cfa1ca9dSYoshinobu Inoue 
2741712fc218SRobert Watson 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2742712fc218SRobert Watson 		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
274315bd2b43SDavid Greenman 
2744b872626dSMatt Macy 	CK_LIST_REMOVE(inp, inp_hash);
2745b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(head, inp, inp_hash);
274652cd27cbSRobert Watson 
274752cd27cbSRobert Watson #ifdef PCBGROUP
274852cd27cbSRobert Watson 	if (m != NULL)
274952cd27cbSRobert Watson 		in_pcbgroup_update_mbuf(inp, m);
275052cd27cbSRobert Watson 	else
275152cd27cbSRobert Watson 		in_pcbgroup_update(inp);
275252cd27cbSRobert Watson #endif
2753c3229e05SDavid Greenman }
2754c3229e05SDavid Greenman 
2755d3c1f003SRobert Watson void
2756d3c1f003SRobert Watson in_pcbrehash(struct inpcb *inp)
2757d3c1f003SRobert Watson {
2758d3c1f003SRobert Watson 
2759d3c1f003SRobert Watson 	in_pcbrehash_mbuf(inp, NULL);
2760d3c1f003SRobert Watson }
2761d3c1f003SRobert Watson 
2762c3229e05SDavid Greenman /*
2763c3229e05SDavid Greenman  * Remove PCB from various lists.
2764c3229e05SDavid Greenman  */
27656d888973SRobert Watson static void
2766136d4f1cSRobert Watson in_pcbremlists(struct inpcb *inp)
2767c3229e05SDavid Greenman {
276859daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
276959daba27SSam Leffler 
27708501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2771ff9b006dSJulien Charbon 	INP_LIST_WLOCK_ASSERT(pcbinfo);
277259daba27SSam Leffler 
277359daba27SSam Leffler 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2774111d57a6SRobert Watson 	if (inp->inp_flags & INP_INHASHLIST) {
2775c3229e05SDavid Greenman 		struct inpcbport *phd = inp->inp_phd;
2776c3229e05SDavid Greenman 
2777fa046d87SRobert Watson 		INP_HASH_WLOCK(pcbinfo);
27781a43cff9SSean Bruno 
27791a43cff9SSean Bruno 		/* XXX: Only do if SO_REUSEPORT_LB set? */
27801a43cff9SSean Bruno 		in_pcbremlbgrouphash(inp);
27811a43cff9SSean Bruno 
2782b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_hash);
2783b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_portlist);
2784b872626dSMatt Macy 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2785b872626dSMatt Macy 			CK_LIST_REMOVE(phd, phd_hash);
27862a4bd982SGleb Smirnoff 			NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
2787c3229e05SDavid Greenman 		}
2788fa046d87SRobert Watson 		INP_HASH_WUNLOCK(pcbinfo);
2789111d57a6SRobert Watson 		inp->inp_flags &= ~INP_INHASHLIST;
2790c3229e05SDavid Greenman 	}
2791b872626dSMatt Macy 	CK_LIST_REMOVE(inp, inp_list);
279259daba27SSam Leffler 	pcbinfo->ipi_count--;
279352cd27cbSRobert Watson #ifdef PCBGROUP
279452cd27cbSRobert Watson 	in_pcbgroup_remove(inp);
279552cd27cbSRobert Watson #endif
279615bd2b43SDavid Greenman }
279775c13541SPoul-Henning Kamp 
2798a557af22SRobert Watson /*
279984cc0778SGeorge V. Neville-Neil  * Check for alternatives when higher level complains
280084cc0778SGeorge V. Neville-Neil  * about service problems.  For now, invalidate cached
280184cc0778SGeorge V. Neville-Neil  * routing information.  If the route was created dynamically
280284cc0778SGeorge V. Neville-Neil  * (by a redirect), time to try a default gateway again.
280384cc0778SGeorge V. Neville-Neil  */
280484cc0778SGeorge V. Neville-Neil void
280584cc0778SGeorge V. Neville-Neil in_losing(struct inpcb *inp)
280684cc0778SGeorge V. Neville-Neil {
280784cc0778SGeorge V. Neville-Neil 
2808fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
280984cc0778SGeorge V. Neville-Neil 	return;
281084cc0778SGeorge V. Neville-Neil }
281184cc0778SGeorge V. Neville-Neil 
281284cc0778SGeorge V. Neville-Neil /*
2813a557af22SRobert Watson  * A set label operation has occurred at the socket layer, propagate the
2814a557af22SRobert Watson  * label change into the in_pcb for the socket.
2815a557af22SRobert Watson  */
2816a557af22SRobert Watson void
2817136d4f1cSRobert Watson in_pcbsosetlabel(struct socket *so)
2818a557af22SRobert Watson {
2819a557af22SRobert Watson #ifdef MAC
2820a557af22SRobert Watson 	struct inpcb *inp;
2821a557af22SRobert Watson 
28224c7c478dSRobert Watson 	inp = sotoinpcb(so);
28234c7c478dSRobert Watson 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2824602cc7f1SRobert Watson 
28258501a69cSRobert Watson 	INP_WLOCK(inp);
2826310e7cebSRobert Watson 	SOCK_LOCK(so);
2827a557af22SRobert Watson 	mac_inpcb_sosetlabel(so, inp);
2828310e7cebSRobert Watson 	SOCK_UNLOCK(so);
28298501a69cSRobert Watson 	INP_WUNLOCK(inp);
2830a557af22SRobert Watson #endif
2831a557af22SRobert Watson }
28325f311da2SMike Silbersack 
28335f311da2SMike Silbersack /*
2834ad3a630fSRobert Watson  * ipport_tick runs once per second, determining if random port allocation
2835ad3a630fSRobert Watson  * should be continued.  If more than ipport_randomcps ports have been
2836ad3a630fSRobert Watson  * allocated in the last second, then we return to sequential port
2837ad3a630fSRobert Watson  * allocation. We return to random allocation only once we drop below
2838ad3a630fSRobert Watson  * ipport_randomcps for at least ipport_randomtime seconds.
28395f311da2SMike Silbersack  */
2840aae49dd3SBjoern A. Zeeb static void
2841136d4f1cSRobert Watson ipport_tick(void *xtp)
28425f311da2SMike Silbersack {
28438b615593SMarko Zec 	VNET_ITERATOR_DECL(vnet_iter);
2844ad3a630fSRobert Watson 
28455ee847d3SRobert Watson 	VNET_LIST_RLOCK_NOSLEEP();
28468b615593SMarko Zec 	VNET_FOREACH(vnet_iter) {
28478b615593SMarko Zec 		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
28488b615593SMarko Zec 		if (V_ipport_tcpallocs <=
28498b615593SMarko Zec 		    V_ipport_tcplastcount + V_ipport_randomcps) {
2850603724d3SBjoern A. Zeeb 			if (V_ipport_stoprandom > 0)
2851603724d3SBjoern A. Zeeb 				V_ipport_stoprandom--;
2852ad3a630fSRobert Watson 		} else
2853603724d3SBjoern A. Zeeb 			V_ipport_stoprandom = V_ipport_randomtime;
2854603724d3SBjoern A. Zeeb 		V_ipport_tcplastcount = V_ipport_tcpallocs;
28558b615593SMarko Zec 		CURVNET_RESTORE();
28568b615593SMarko Zec 	}
28575ee847d3SRobert Watson 	VNET_LIST_RUNLOCK_NOSLEEP();
28585f311da2SMike Silbersack 	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
28595f311da2SMike Silbersack }
2860497057eeSRobert Watson 
2861aae49dd3SBjoern A. Zeeb static void
2862aae49dd3SBjoern A. Zeeb ip_fini(void *xtp)
2863aae49dd3SBjoern A. Zeeb {
2864aae49dd3SBjoern A. Zeeb 
2865aae49dd3SBjoern A. Zeeb 	callout_stop(&ipport_tick_callout);
2866aae49dd3SBjoern A. Zeeb }
2867aae49dd3SBjoern A. Zeeb 
2868aae49dd3SBjoern A. Zeeb /*
2869aae49dd3SBjoern A. Zeeb  * The ipport_callout should start running at about the time we attach the
2870aae49dd3SBjoern A. Zeeb  * inet or inet6 domains.
2871aae49dd3SBjoern A. Zeeb  */
2872aae49dd3SBjoern A. Zeeb static void
2873aae49dd3SBjoern A. Zeeb ipport_tick_init(const void *unused __unused)
2874aae49dd3SBjoern A. Zeeb {
2875aae49dd3SBjoern A. Zeeb 
2876aae49dd3SBjoern A. Zeeb 	/* Start ipport_tick. */
2877fd90e2edSJung-uk Kim 	callout_init(&ipport_tick_callout, 1);
2878aae49dd3SBjoern A. Zeeb 	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2879aae49dd3SBjoern A. Zeeb 	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2880aae49dd3SBjoern A. Zeeb 		SHUTDOWN_PRI_DEFAULT);
2881aae49dd3SBjoern A. Zeeb }
2882aae49dd3SBjoern A. Zeeb SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2883aae49dd3SBjoern A. Zeeb     ipport_tick_init, NULL);
2884aae49dd3SBjoern A. Zeeb 
28853d585327SKip Macy void
28863d585327SKip Macy inp_wlock(struct inpcb *inp)
28873d585327SKip Macy {
28883d585327SKip Macy 
28898501a69cSRobert Watson 	INP_WLOCK(inp);
28903d585327SKip Macy }
28913d585327SKip Macy 
28923d585327SKip Macy void
28933d585327SKip Macy inp_wunlock(struct inpcb *inp)
28943d585327SKip Macy {
28953d585327SKip Macy 
28968501a69cSRobert Watson 	INP_WUNLOCK(inp);
28973d585327SKip Macy }
28983d585327SKip Macy 
28993d585327SKip Macy void
29003d585327SKip Macy inp_rlock(struct inpcb *inp)
29013d585327SKip Macy {
29023d585327SKip Macy 
2903a69042a5SRobert Watson 	INP_RLOCK(inp);
29043d585327SKip Macy }
29053d585327SKip Macy 
29063d585327SKip Macy void
29073d585327SKip Macy inp_runlock(struct inpcb *inp)
29083d585327SKip Macy {
29093d585327SKip Macy 
2910a69042a5SRobert Watson 	INP_RUNLOCK(inp);
29113d585327SKip Macy }
29123d585327SKip Macy 
2913c75e2666SGleb Smirnoff #ifdef INVARIANT_SUPPORT
29143d585327SKip Macy void
2915e79dd20dSKip Macy inp_lock_assert(struct inpcb *inp)
29163d585327SKip Macy {
29173d585327SKip Macy 
29188501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
29193d585327SKip Macy }
29203d585327SKip Macy 
29213d585327SKip Macy void
2922e79dd20dSKip Macy inp_unlock_assert(struct inpcb *inp)
29233d585327SKip Macy {
29243d585327SKip Macy 
29253d585327SKip Macy 	INP_UNLOCK_ASSERT(inp);
29263d585327SKip Macy }
29273d585327SKip Macy #endif
29283d585327SKip Macy 
29299378e437SKip Macy void
29309378e437SKip Macy inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
29319378e437SKip Macy {
29329378e437SKip Macy 	struct inpcb *inp;
29339378e437SKip Macy 
2934ff9b006dSJulien Charbon 	INP_INFO_WLOCK(&V_tcbinfo);
2935b872626dSMatt Macy 	CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
29369378e437SKip Macy 		INP_WLOCK(inp);
29379378e437SKip Macy 		func(inp, arg);
29389378e437SKip Macy 		INP_WUNLOCK(inp);
29399378e437SKip Macy 	}
2940ff9b006dSJulien Charbon 	INP_INFO_WUNLOCK(&V_tcbinfo);
29419378e437SKip Macy }
29429378e437SKip Macy 
29439378e437SKip Macy struct socket *
29449378e437SKip Macy inp_inpcbtosocket(struct inpcb *inp)
29459378e437SKip Macy {
29469378e437SKip Macy 
29479378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
29489378e437SKip Macy 	return (inp->inp_socket);
29499378e437SKip Macy }
29509378e437SKip Macy 
29519378e437SKip Macy struct tcpcb *
29529378e437SKip Macy inp_inpcbtotcpcb(struct inpcb *inp)
29539378e437SKip Macy {
29549378e437SKip Macy 
29559378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
29569378e437SKip Macy 	return ((struct tcpcb *)inp->inp_ppcb);
29579378e437SKip Macy }
29589378e437SKip Macy 
29599378e437SKip Macy int
29609378e437SKip Macy inp_ip_tos_get(const struct inpcb *inp)
29619378e437SKip Macy {
29629378e437SKip Macy 
29639378e437SKip Macy 	return (inp->inp_ip_tos);
29649378e437SKip Macy }
29659378e437SKip Macy 
29669378e437SKip Macy void
29679378e437SKip Macy inp_ip_tos_set(struct inpcb *inp, int val)
29689378e437SKip Macy {
29699378e437SKip Macy 
29709378e437SKip Macy 	inp->inp_ip_tos = val;
29719378e437SKip Macy }
29729378e437SKip Macy 
29739378e437SKip Macy void
2974df9cf830STai-hwa Liang inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
29759d29c635SKip Macy     uint32_t *faddr, uint16_t *fp)
29769378e437SKip Macy {
29779378e437SKip Macy 
29789d29c635SKip Macy 	INP_LOCK_ASSERT(inp);
2979df9cf830STai-hwa Liang 	*laddr = inp->inp_laddr.s_addr;
2980df9cf830STai-hwa Liang 	*faddr = inp->inp_faddr.s_addr;
29819378e437SKip Macy 	*lp = inp->inp_lport;
29829378e437SKip Macy 	*fp = inp->inp_fport;
29839378e437SKip Macy }
29849378e437SKip Macy 
2985dd0e6c38SKip Macy struct inpcb *
2986dd0e6c38SKip Macy so_sotoinpcb(struct socket *so)
2987dd0e6c38SKip Macy {
2988dd0e6c38SKip Macy 
2989dd0e6c38SKip Macy 	return (sotoinpcb(so));
2990dd0e6c38SKip Macy }
2991dd0e6c38SKip Macy 
2992dd0e6c38SKip Macy struct tcpcb *
2993dd0e6c38SKip Macy so_sototcpcb(struct socket *so)
2994dd0e6c38SKip Macy {
2995dd0e6c38SKip Macy 
2996dd0e6c38SKip Macy 	return (sototcpcb(so));
2997dd0e6c38SKip Macy }
2998dd0e6c38SKip Macy 
2999cc65eb4eSGleb Smirnoff /*
3000cc65eb4eSGleb Smirnoff  * Create an external-format (``xinpcb'') structure using the information in
3001cc65eb4eSGleb Smirnoff  * the kernel-format in_pcb structure pointed to by inp.  This is done to
3002cc65eb4eSGleb Smirnoff  * reduce the spew of irrelevant information over this interface, to isolate
3003cc65eb4eSGleb Smirnoff  * user code from changes in the kernel structure, and potentially to provide
3004cc65eb4eSGleb Smirnoff  * information-hiding if we decide that some of this information should be
3005cc65eb4eSGleb Smirnoff  * hidden from users.
3006cc65eb4eSGleb Smirnoff  */
3007cc65eb4eSGleb Smirnoff void
3008cc65eb4eSGleb Smirnoff in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
3009cc65eb4eSGleb Smirnoff {
3010cc65eb4eSGleb Smirnoff 
301179db6fe7SMark Johnston 	bzero(xi, sizeof(*xi));
3012cc65eb4eSGleb Smirnoff 	xi->xi_len = sizeof(struct xinpcb);
3013cc65eb4eSGleb Smirnoff 	if (inp->inp_socket)
3014cc65eb4eSGleb Smirnoff 		sotoxsocket(inp->inp_socket, &xi->xi_socket);
3015cc65eb4eSGleb Smirnoff 	bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
3016cc65eb4eSGleb Smirnoff 	xi->inp_gencnt = inp->inp_gencnt;
30173a20f06aSBrooks Davis 	xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
3018cc65eb4eSGleb Smirnoff 	xi->inp_flow = inp->inp_flow;
3019cc65eb4eSGleb Smirnoff 	xi->inp_flowid = inp->inp_flowid;
3020cc65eb4eSGleb Smirnoff 	xi->inp_flowtype = inp->inp_flowtype;
3021cc65eb4eSGleb Smirnoff 	xi->inp_flags = inp->inp_flags;
3022cc65eb4eSGleb Smirnoff 	xi->inp_flags2 = inp->inp_flags2;
3023cc65eb4eSGleb Smirnoff 	xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
3024cc65eb4eSGleb Smirnoff 	xi->in6p_cksum = inp->in6p_cksum;
3025cc65eb4eSGleb Smirnoff 	xi->in6p_hops = inp->in6p_hops;
3026cc65eb4eSGleb Smirnoff 	xi->inp_ip_tos = inp->inp_ip_tos;
3027cc65eb4eSGleb Smirnoff 	xi->inp_vflag = inp->inp_vflag;
3028cc65eb4eSGleb Smirnoff 	xi->inp_ip_ttl = inp->inp_ip_ttl;
3029cc65eb4eSGleb Smirnoff 	xi->inp_ip_p = inp->inp_ip_p;
3030cc65eb4eSGleb Smirnoff 	xi->inp_ip_minttl = inp->inp_ip_minttl;
3031cc65eb4eSGleb Smirnoff }
3032cc65eb4eSGleb Smirnoff 
3033497057eeSRobert Watson #ifdef DDB
3034497057eeSRobert Watson static void
3035497057eeSRobert Watson db_print_indent(int indent)
3036497057eeSRobert Watson {
3037497057eeSRobert Watson 	int i;
3038497057eeSRobert Watson 
3039497057eeSRobert Watson 	for (i = 0; i < indent; i++)
3040497057eeSRobert Watson 		db_printf(" ");
3041497057eeSRobert Watson }
3042497057eeSRobert Watson 
3043497057eeSRobert Watson static void
3044497057eeSRobert Watson db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3045497057eeSRobert Watson {
3046497057eeSRobert Watson 	char faddr_str[48], laddr_str[48];
3047497057eeSRobert Watson 
3048497057eeSRobert Watson 	db_print_indent(indent);
3049497057eeSRobert Watson 	db_printf("%s at %p\n", name, inc);
3050497057eeSRobert Watson 
3051497057eeSRobert Watson 	indent += 2;
3052497057eeSRobert Watson 
305303dc38a4SRobert Watson #ifdef INET6
3054dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
3055497057eeSRobert Watson 		/* IPv6. */
3056497057eeSRobert Watson 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
3057497057eeSRobert Watson 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
305883e521ecSBjoern A. Zeeb 	} else
305903dc38a4SRobert Watson #endif
306083e521ecSBjoern A. Zeeb 	{
3061497057eeSRobert Watson 		/* IPv4. */
3062497057eeSRobert Watson 		inet_ntoa_r(inc->inc_laddr, laddr_str);
3063497057eeSRobert Watson 		inet_ntoa_r(inc->inc_faddr, faddr_str);
3064497057eeSRobert Watson 	}
3065497057eeSRobert Watson 	db_print_indent(indent);
3066497057eeSRobert Watson 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
3067497057eeSRobert Watson 	    ntohs(inc->inc_lport));
3068497057eeSRobert Watson 	db_print_indent(indent);
3069497057eeSRobert Watson 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
3070497057eeSRobert Watson 	    ntohs(inc->inc_fport));
3071497057eeSRobert Watson }
3072497057eeSRobert Watson 
3073497057eeSRobert Watson static void
3074497057eeSRobert Watson db_print_inpflags(int inp_flags)
3075497057eeSRobert Watson {
3076497057eeSRobert Watson 	int comma;
3077497057eeSRobert Watson 
3078497057eeSRobert Watson 	comma = 0;
3079497057eeSRobert Watson 	if (inp_flags & INP_RECVOPTS) {
3080497057eeSRobert Watson 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3081497057eeSRobert Watson 		comma = 1;
3082497057eeSRobert Watson 	}
3083497057eeSRobert Watson 	if (inp_flags & INP_RECVRETOPTS) {
3084497057eeSRobert Watson 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3085497057eeSRobert Watson 		comma = 1;
3086497057eeSRobert Watson 	}
3087497057eeSRobert Watson 	if (inp_flags & INP_RECVDSTADDR) {
3088497057eeSRobert Watson 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3089497057eeSRobert Watson 		comma = 1;
3090497057eeSRobert Watson 	}
3091dce33a45SErmal Luçi 	if (inp_flags & INP_ORIGDSTADDR) {
3092dce33a45SErmal Luçi 		db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3093dce33a45SErmal Luçi 		comma = 1;
3094dce33a45SErmal Luçi 	}
3095497057eeSRobert Watson 	if (inp_flags & INP_HDRINCL) {
3096497057eeSRobert Watson 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
3097497057eeSRobert Watson 		comma = 1;
3098497057eeSRobert Watson 	}
3099497057eeSRobert Watson 	if (inp_flags & INP_HIGHPORT) {
3100497057eeSRobert Watson 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3101497057eeSRobert Watson 		comma = 1;
3102497057eeSRobert Watson 	}
3103497057eeSRobert Watson 	if (inp_flags & INP_LOWPORT) {
3104497057eeSRobert Watson 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
3105497057eeSRobert Watson 		comma = 1;
3106497057eeSRobert Watson 	}
3107497057eeSRobert Watson 	if (inp_flags & INP_ANONPORT) {
3108497057eeSRobert Watson 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
3109497057eeSRobert Watson 		comma = 1;
3110497057eeSRobert Watson 	}
3111497057eeSRobert Watson 	if (inp_flags & INP_RECVIF) {
3112497057eeSRobert Watson 		db_printf("%sINP_RECVIF", comma ? ", " : "");
3113497057eeSRobert Watson 		comma = 1;
3114497057eeSRobert Watson 	}
3115497057eeSRobert Watson 	if (inp_flags & INP_MTUDISC) {
3116497057eeSRobert Watson 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
3117497057eeSRobert Watson 		comma = 1;
3118497057eeSRobert Watson 	}
3119497057eeSRobert Watson 	if (inp_flags & INP_RECVTTL) {
3120497057eeSRobert Watson 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
3121497057eeSRobert Watson 		comma = 1;
3122497057eeSRobert Watson 	}
3123497057eeSRobert Watson 	if (inp_flags & INP_DONTFRAG) {
3124497057eeSRobert Watson 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3125497057eeSRobert Watson 		comma = 1;
3126497057eeSRobert Watson 	}
31273cca425bSMichael Tuexen 	if (inp_flags & INP_RECVTOS) {
31283cca425bSMichael Tuexen 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
31293cca425bSMichael Tuexen 		comma = 1;
31303cca425bSMichael Tuexen 	}
3131497057eeSRobert Watson 	if (inp_flags & IN6P_IPV6_V6ONLY) {
3132497057eeSRobert Watson 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3133497057eeSRobert Watson 		comma = 1;
3134497057eeSRobert Watson 	}
3135497057eeSRobert Watson 	if (inp_flags & IN6P_PKTINFO) {
3136497057eeSRobert Watson 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3137497057eeSRobert Watson 		comma = 1;
3138497057eeSRobert Watson 	}
3139497057eeSRobert Watson 	if (inp_flags & IN6P_HOPLIMIT) {
3140497057eeSRobert Watson 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3141497057eeSRobert Watson 		comma = 1;
3142497057eeSRobert Watson 	}
3143497057eeSRobert Watson 	if (inp_flags & IN6P_HOPOPTS) {
3144497057eeSRobert Watson 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3145497057eeSRobert Watson 		comma = 1;
3146497057eeSRobert Watson 	}
3147497057eeSRobert Watson 	if (inp_flags & IN6P_DSTOPTS) {
3148497057eeSRobert Watson 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3149497057eeSRobert Watson 		comma = 1;
3150497057eeSRobert Watson 	}
3151497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDR) {
3152497057eeSRobert Watson 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3153497057eeSRobert Watson 		comma = 1;
3154497057eeSRobert Watson 	}
3155497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
3156497057eeSRobert Watson 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3157497057eeSRobert Watson 		comma = 1;
3158497057eeSRobert Watson 	}
3159497057eeSRobert Watson 	if (inp_flags & IN6P_TCLASS) {
3160497057eeSRobert Watson 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3161497057eeSRobert Watson 		comma = 1;
3162497057eeSRobert Watson 	}
3163497057eeSRobert Watson 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
3164497057eeSRobert Watson 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3165497057eeSRobert Watson 		comma = 1;
3166497057eeSRobert Watson 	}
3167ad71fe3cSRobert Watson 	if (inp_flags & INP_TIMEWAIT) {
3168ad71fe3cSRobert Watson 		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3169ad71fe3cSRobert Watson 		comma  = 1;
3170ad71fe3cSRobert Watson 	}
3171ad71fe3cSRobert Watson 	if (inp_flags & INP_ONESBCAST) {
3172ad71fe3cSRobert Watson 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3173ad71fe3cSRobert Watson 		comma  = 1;
3174ad71fe3cSRobert Watson 	}
3175ad71fe3cSRobert Watson 	if (inp_flags & INP_DROPPED) {
3176ad71fe3cSRobert Watson 		db_printf("%sINP_DROPPED", comma ? ", " : "");
3177ad71fe3cSRobert Watson 		comma  = 1;
3178ad71fe3cSRobert Watson 	}
3179ad71fe3cSRobert Watson 	if (inp_flags & INP_SOCKREF) {
3180ad71fe3cSRobert Watson 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
3181ad71fe3cSRobert Watson 		comma  = 1;
3182ad71fe3cSRobert Watson 	}
3183497057eeSRobert Watson 	if (inp_flags & IN6P_RFC2292) {
3184497057eeSRobert Watson 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3185497057eeSRobert Watson 		comma = 1;
3186497057eeSRobert Watson 	}
3187497057eeSRobert Watson 	if (inp_flags & IN6P_MTU) {
3188497057eeSRobert Watson 		db_printf("IN6P_MTU%s", comma ? ", " : "");
3189497057eeSRobert Watson 		comma = 1;
3190497057eeSRobert Watson 	}
3191497057eeSRobert Watson }
3192497057eeSRobert Watson 
3193497057eeSRobert Watson static void
3194497057eeSRobert Watson db_print_inpvflag(u_char inp_vflag)
3195497057eeSRobert Watson {
3196497057eeSRobert Watson 	int comma;
3197497057eeSRobert Watson 
3198497057eeSRobert Watson 	comma = 0;
3199497057eeSRobert Watson 	if (inp_vflag & INP_IPV4) {
3200497057eeSRobert Watson 		db_printf("%sINP_IPV4", comma ? ", " : "");
3201497057eeSRobert Watson 		comma  = 1;
3202497057eeSRobert Watson 	}
3203497057eeSRobert Watson 	if (inp_vflag & INP_IPV6) {
3204497057eeSRobert Watson 		db_printf("%sINP_IPV6", comma ? ", " : "");
3205497057eeSRobert Watson 		comma  = 1;
3206497057eeSRobert Watson 	}
3207497057eeSRobert Watson 	if (inp_vflag & INP_IPV6PROTO) {
3208497057eeSRobert Watson 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3209497057eeSRobert Watson 		comma  = 1;
3210497057eeSRobert Watson 	}
3211497057eeSRobert Watson }
3212497057eeSRobert Watson 
32136d888973SRobert Watson static void
3214497057eeSRobert Watson db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3215497057eeSRobert Watson {
3216497057eeSRobert Watson 
3217497057eeSRobert Watson 	db_print_indent(indent);
3218497057eeSRobert Watson 	db_printf("%s at %p\n", name, inp);
3219497057eeSRobert Watson 
3220497057eeSRobert Watson 	indent += 2;
3221497057eeSRobert Watson 
3222497057eeSRobert Watson 	db_print_indent(indent);
3223497057eeSRobert Watson 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3224497057eeSRobert Watson 
3225497057eeSRobert Watson 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3226497057eeSRobert Watson 
3227497057eeSRobert Watson 	db_print_indent(indent);
3228497057eeSRobert Watson 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
3229497057eeSRobert Watson 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3230497057eeSRobert Watson 
3231497057eeSRobert Watson 	db_print_indent(indent);
3232497057eeSRobert Watson 	db_printf("inp_label: %p   inp_flags: 0x%x (",
3233497057eeSRobert Watson 	   inp->inp_label, inp->inp_flags);
3234497057eeSRobert Watson 	db_print_inpflags(inp->inp_flags);
3235497057eeSRobert Watson 	db_printf(")\n");
3236497057eeSRobert Watson 
3237497057eeSRobert Watson 	db_print_indent(indent);
3238497057eeSRobert Watson 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3239497057eeSRobert Watson 	    inp->inp_vflag);
3240497057eeSRobert Watson 	db_print_inpvflag(inp->inp_vflag);
3241497057eeSRobert Watson 	db_printf(")\n");
3242497057eeSRobert Watson 
3243497057eeSRobert Watson 	db_print_indent(indent);
3244497057eeSRobert Watson 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3245497057eeSRobert Watson 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3246497057eeSRobert Watson 
3247497057eeSRobert Watson 	db_print_indent(indent);
3248497057eeSRobert Watson #ifdef INET6
3249497057eeSRobert Watson 	if (inp->inp_vflag & INP_IPV6) {
3250497057eeSRobert Watson 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
3251497057eeSRobert Watson 		    "in6p_moptions: %p\n", inp->in6p_options,
3252497057eeSRobert Watson 		    inp->in6p_outputopts, inp->in6p_moptions);
3253497057eeSRobert Watson 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3254497057eeSRobert Watson 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3255497057eeSRobert Watson 		    inp->in6p_hops);
3256497057eeSRobert Watson 	} else
3257497057eeSRobert Watson #endif
3258497057eeSRobert Watson 	{
3259497057eeSRobert Watson 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3260497057eeSRobert Watson 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3261497057eeSRobert Watson 		    inp->inp_options, inp->inp_moptions);
3262497057eeSRobert Watson 	}
3263497057eeSRobert Watson 
3264497057eeSRobert Watson 	db_print_indent(indent);
3265497057eeSRobert Watson 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
3266497057eeSRobert Watson 	    (uintmax_t)inp->inp_gencnt);
3267497057eeSRobert Watson }
3268497057eeSRobert Watson 
3269497057eeSRobert Watson DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3270497057eeSRobert Watson {
3271497057eeSRobert Watson 	struct inpcb *inp;
3272497057eeSRobert Watson 
3273497057eeSRobert Watson 	if (!have_addr) {
3274497057eeSRobert Watson 		db_printf("usage: show inpcb <addr>\n");
3275497057eeSRobert Watson 		return;
3276497057eeSRobert Watson 	}
3277497057eeSRobert Watson 	inp = (struct inpcb *)addr;
3278497057eeSRobert Watson 
3279497057eeSRobert Watson 	db_print_inpcb(inp, "inpcb", 0);
3280497057eeSRobert Watson }
328183e521ecSBjoern A. Zeeb #endif /* DDB */
3282f3e7afe2SHans Petter Selasky 
3283f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
3284f3e7afe2SHans Petter Selasky /*
3285f3e7afe2SHans Petter Selasky  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3286f3e7afe2SHans Petter Selasky  * if any.
3287f3e7afe2SHans Petter Selasky  */
3288f3e7afe2SHans Petter Selasky int
3289f3e7afe2SHans Petter Selasky in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3290f3e7afe2SHans Petter Selasky {
3291f3e7afe2SHans Petter Selasky 	union if_snd_tag_modify_params params = {
3292f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
329320abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3294f3e7afe2SHans Petter Selasky 	};
3295f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3296f3e7afe2SHans Petter Selasky 	int error;
3297f3e7afe2SHans Petter Selasky 
3298f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3299f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3300f3e7afe2SHans Petter Selasky 		return (EINVAL);
3301f3e7afe2SHans Petter Selasky 
3302*c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_modify == NULL) {
3303f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3304f3e7afe2SHans Petter Selasky 	} else {
3305*c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_modify(mst, &params);
3306f3e7afe2SHans Petter Selasky 	}
3307f3e7afe2SHans Petter Selasky 	return (error);
3308f3e7afe2SHans Petter Selasky }
3309f3e7afe2SHans Petter Selasky 
3310f3e7afe2SHans Petter Selasky /*
3311f3e7afe2SHans Petter Selasky  * Query existing TX rate limit based on the existing
3312f3e7afe2SHans Petter Selasky  * "inp->inp_snd_tag", if any.
3313f3e7afe2SHans Petter Selasky  */
3314f3e7afe2SHans Petter Selasky int
3315f3e7afe2SHans Petter Selasky in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3316f3e7afe2SHans Petter Selasky {
3317f3e7afe2SHans Petter Selasky 	union if_snd_tag_query_params params = { };
3318f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3319f3e7afe2SHans Petter Selasky 	int error;
3320f3e7afe2SHans Petter Selasky 
3321f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3322f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3323f3e7afe2SHans Petter Selasky 		return (EINVAL);
3324f3e7afe2SHans Petter Selasky 
3325*c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL) {
3326f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3327f3e7afe2SHans Petter Selasky 	} else {
3328*c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_query(mst, &params);
3329f3e7afe2SHans Petter Selasky 		if (error == 0 && p_max_pacing_rate != NULL)
3330f3e7afe2SHans Petter Selasky 			*p_max_pacing_rate = params.rate_limit.max_rate;
3331f3e7afe2SHans Petter Selasky 	}
3332f3e7afe2SHans Petter Selasky 	return (error);
3333f3e7afe2SHans Petter Selasky }
3334f3e7afe2SHans Petter Selasky 
3335f3e7afe2SHans Petter Selasky /*
333695ed5015SHans Petter Selasky  * Query existing TX queue level based on the existing
333795ed5015SHans Petter Selasky  * "inp->inp_snd_tag", if any.
333895ed5015SHans Petter Selasky  */
333995ed5015SHans Petter Selasky int
334095ed5015SHans Petter Selasky in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
334195ed5015SHans Petter Selasky {
334295ed5015SHans Petter Selasky 	union if_snd_tag_query_params params = { };
334395ed5015SHans Petter Selasky 	struct m_snd_tag *mst;
334495ed5015SHans Petter Selasky 	int error;
334595ed5015SHans Petter Selasky 
334695ed5015SHans Petter Selasky 	mst = inp->inp_snd_tag;
334795ed5015SHans Petter Selasky 	if (mst == NULL)
334895ed5015SHans Petter Selasky 		return (EINVAL);
334995ed5015SHans Petter Selasky 
3350*c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL)
335195ed5015SHans Petter Selasky 		return (EOPNOTSUPP);
335295ed5015SHans Petter Selasky 
3353*c782ea8bSJohn Baldwin 	error = mst->sw->snd_tag_query(mst, &params);
335495ed5015SHans Petter Selasky 	if (error == 0 && p_txqueue_level != NULL)
335595ed5015SHans Petter Selasky 		*p_txqueue_level = params.rate_limit.queue_level;
335695ed5015SHans Petter Selasky 	return (error);
335795ed5015SHans Petter Selasky }
335895ed5015SHans Petter Selasky 
335995ed5015SHans Petter Selasky /*
3360f3e7afe2SHans Petter Selasky  * Allocate a new TX rate limit send tag from the network interface
3361f3e7afe2SHans Petter Selasky  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3362f3e7afe2SHans Petter Selasky  */
3363f3e7afe2SHans Petter Selasky int
3364f3e7afe2SHans Petter Selasky in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
336520abea66SRandall Stewart     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
336620abea66SRandall Stewart 
3367f3e7afe2SHans Petter Selasky {
3368f3e7afe2SHans Petter Selasky 	union if_snd_tag_alloc_params params = {
336995ed5015SHans Petter Selasky 		.rate_limit.hdr.type = (max_pacing_rate == -1U) ?
337095ed5015SHans Petter Selasky 		    IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3371f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowid = flowid,
3372f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowtype = flowtype,
337398085baeSAndrew Gallatin 		.rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3374f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
337520abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3376f3e7afe2SHans Petter Selasky 	};
3377f3e7afe2SHans Petter Selasky 	int error;
3378f3e7afe2SHans Petter Selasky 
3379f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3380f3e7afe2SHans Petter Selasky 
338185d8d30fSHans Petter Selasky 	/*
338285d8d30fSHans Petter Selasky 	 * If there is already a send tag, or the INP is being torn
338385d8d30fSHans Petter Selasky 	 * down, allocating a new send tag is not allowed. Else send
338485d8d30fSHans Petter Selasky 	 * tags may leak.
338585d8d30fSHans Petter Selasky 	 */
338685d8d30fSHans Petter Selasky 	if (*st != NULL || (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0)
3387f3e7afe2SHans Petter Selasky 		return (EINVAL);
3388f3e7afe2SHans Petter Selasky 
338936e0a362SJohn Baldwin 	error = m_snd_tag_alloc(ifp, &params, st);
3390903c4ee6SXin LI #ifdef INET
339120abea66SRandall Stewart 	if (error == 0) {
339220abea66SRandall Stewart 		counter_u64_add(rate_limit_set_ok, 1);
339320abea66SRandall Stewart 		counter_u64_add(rate_limit_active, 1);
339436e0a362SJohn Baldwin 	} else if (error != EOPNOTSUPP)
339520abea66SRandall Stewart 		  counter_u64_add(rate_limit_alloc_fail, 1);
3396903c4ee6SXin LI #endif
3397f3e7afe2SHans Petter Selasky 	return (error);
3398f3e7afe2SHans Petter Selasky }
3399f3e7afe2SHans Petter Selasky 
340020abea66SRandall Stewart void
340198d7a8d9SJohn Baldwin in_pcbdetach_tag(struct m_snd_tag *mst)
340220abea66SRandall Stewart {
340320abea66SRandall Stewart 
340498d7a8d9SJohn Baldwin 	m_snd_tag_rele(mst);
3405903c4ee6SXin LI #ifdef INET
340620abea66SRandall Stewart 	counter_u64_add(rate_limit_active, -1);
3407903c4ee6SXin LI #endif
340820abea66SRandall Stewart }
340920abea66SRandall Stewart 
3410f3e7afe2SHans Petter Selasky /*
3411f3e7afe2SHans Petter Selasky  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3412f3e7afe2SHans Petter Selasky  * if any:
3413f3e7afe2SHans Petter Selasky  */
3414f3e7afe2SHans Petter Selasky void
3415f3e7afe2SHans Petter Selasky in_pcbdetach_txrtlmt(struct inpcb *inp)
3416f3e7afe2SHans Petter Selasky {
3417f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3418f3e7afe2SHans Petter Selasky 
3419f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3420f3e7afe2SHans Petter Selasky 
3421f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3422f3e7afe2SHans Petter Selasky 	inp->inp_snd_tag = NULL;
3423f3e7afe2SHans Petter Selasky 
3424f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3425f3e7afe2SHans Petter Selasky 		return;
3426f3e7afe2SHans Petter Selasky 
3427fb3bc596SJohn Baldwin 	m_snd_tag_rele(mst);
3428093e7231SHans Petter Selasky #ifdef INET
3429093e7231SHans Petter Selasky 	counter_u64_add(rate_limit_active, -1);
3430093e7231SHans Petter Selasky #endif
3431f3e7afe2SHans Petter Selasky }
3432f3e7afe2SHans Petter Selasky 
343320abea66SRandall Stewart int
343420abea66SRandall Stewart in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
343520abea66SRandall Stewart {
343620abea66SRandall Stewart 	int error;
343720abea66SRandall Stewart 
343820abea66SRandall Stewart 	/*
343920abea66SRandall Stewart 	 * If the existing send tag is for the wrong interface due to
344020abea66SRandall Stewart 	 * a route change, first drop the existing tag.  Set the
344120abea66SRandall Stewart 	 * CHANGED flag so that we will keep trying to allocate a new
344220abea66SRandall Stewart 	 * tag if we fail to allocate one this time.
344320abea66SRandall Stewart 	 */
344420abea66SRandall Stewart 	if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
344520abea66SRandall Stewart 		in_pcbdetach_txrtlmt(inp);
344620abea66SRandall Stewart 		inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
344720abea66SRandall Stewart 	}
344820abea66SRandall Stewart 
344920abea66SRandall Stewart 	/*
345020abea66SRandall Stewart 	 * NOTE: When attaching to a network interface a reference is
345120abea66SRandall Stewart 	 * made to ensure the network interface doesn't go away until
345220abea66SRandall Stewart 	 * all ratelimit connections are gone. The network interface
345320abea66SRandall Stewart 	 * pointers compared below represent valid network interfaces,
345420abea66SRandall Stewart 	 * except when comparing towards NULL.
345520abea66SRandall Stewart 	 */
345620abea66SRandall Stewart 	if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
345720abea66SRandall Stewart 		error = 0;
345820abea66SRandall Stewart 	} else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
345920abea66SRandall Stewart 		if (inp->inp_snd_tag != NULL)
346020abea66SRandall Stewart 			in_pcbdetach_txrtlmt(inp);
346120abea66SRandall Stewart 		error = 0;
346220abea66SRandall Stewart 	} else if (inp->inp_snd_tag == NULL) {
346320abea66SRandall Stewart 		/*
346420abea66SRandall Stewart 		 * In order to utilize packet pacing with RSS, we need
346520abea66SRandall Stewart 		 * to wait until there is a valid RSS hash before we
346620abea66SRandall Stewart 		 * can proceed:
346720abea66SRandall Stewart 		 */
346820abea66SRandall Stewart 		if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
346920abea66SRandall Stewart 			error = EAGAIN;
347020abea66SRandall Stewart 		} else {
347120abea66SRandall Stewart 			error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
347220abea66SRandall Stewart 			    mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
347320abea66SRandall Stewart 		}
347420abea66SRandall Stewart 	} else {
347520abea66SRandall Stewart 		error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
347620abea66SRandall Stewart 	}
347720abea66SRandall Stewart 	if (error == 0 || error == EOPNOTSUPP)
347820abea66SRandall Stewart 		inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
347920abea66SRandall Stewart 
348020abea66SRandall Stewart 	return (error);
348120abea66SRandall Stewart }
348220abea66SRandall Stewart 
3483f3e7afe2SHans Petter Selasky /*
3484f3e7afe2SHans Petter Selasky  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3485f3e7afe2SHans Petter Selasky  * is set in the fast path and will attach/detach/modify the TX rate
3486f3e7afe2SHans Petter Selasky  * limit send tag based on the socket's so_max_pacing_rate value.
3487f3e7afe2SHans Petter Selasky  */
3488f3e7afe2SHans Petter Selasky void
3489f3e7afe2SHans Petter Selasky in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3490f3e7afe2SHans Petter Selasky {
3491f3e7afe2SHans Petter Selasky 	struct socket *socket;
3492f3e7afe2SHans Petter Selasky 	uint32_t max_pacing_rate;
3493f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3494f3e7afe2SHans Petter Selasky 	int error;
3495f3e7afe2SHans Petter Selasky 
3496f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3497f3e7afe2SHans Petter Selasky 		return;
3498f3e7afe2SHans Petter Selasky 
3499f3e7afe2SHans Petter Selasky 	socket = inp->inp_socket;
3500f3e7afe2SHans Petter Selasky 	if (socket == NULL)
3501f3e7afe2SHans Petter Selasky 		return;
3502f3e7afe2SHans Petter Selasky 
3503f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3504f3e7afe2SHans Petter Selasky 		/*
3505f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3506f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3507f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3508f3e7afe2SHans Petter Selasky 		 * write lock.
3509f3e7afe2SHans Petter Selasky 		 */
3510f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3511f3e7afe2SHans Petter Selasky 			return;
3512f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3513f3e7afe2SHans Petter Selasky 	} else {
3514f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3515f3e7afe2SHans Petter Selasky 	}
3516f3e7afe2SHans Petter Selasky 
3517f3e7afe2SHans Petter Selasky 	/*
3518f3e7afe2SHans Petter Selasky 	 * NOTE: The so_max_pacing_rate value is read unlocked,
3519f3e7afe2SHans Petter Selasky 	 * because atomic updates are not required since the variable
3520f3e7afe2SHans Petter Selasky 	 * is checked at every mbuf we send. It is assumed that the
3521f3e7afe2SHans Petter Selasky 	 * variable read itself will be atomic.
3522f3e7afe2SHans Petter Selasky 	 */
3523f3e7afe2SHans Petter Selasky 	max_pacing_rate = socket->so_max_pacing_rate;
3524f3e7afe2SHans Petter Selasky 
352520abea66SRandall Stewart 	error = in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3526fb3bc596SJohn Baldwin 
3527f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3528f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3529f3e7afe2SHans Petter Selasky }
3530f3e7afe2SHans Petter Selasky 
3531f3e7afe2SHans Petter Selasky /*
3532f3e7afe2SHans Petter Selasky  * Track route changes for TX rate limiting.
3533f3e7afe2SHans Petter Selasky  */
3534f3e7afe2SHans Petter Selasky void
3535f3e7afe2SHans Petter Selasky in_pcboutput_eagain(struct inpcb *inp)
3536f3e7afe2SHans Petter Selasky {
3537f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3538f3e7afe2SHans Petter Selasky 
3539f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3540f3e7afe2SHans Petter Selasky 		return;
3541f3e7afe2SHans Petter Selasky 
3542f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag == NULL)
3543f3e7afe2SHans Petter Selasky 		return;
3544f3e7afe2SHans Petter Selasky 
3545f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3546f3e7afe2SHans Petter Selasky 		/*
3547f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3548f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3549f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3550f3e7afe2SHans Petter Selasky 		 * write lock.
3551f3e7afe2SHans Petter Selasky 		 */
3552f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3553f3e7afe2SHans Petter Selasky 			return;
3554f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3555f3e7afe2SHans Petter Selasky 	} else {
3556f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3557f3e7afe2SHans Petter Selasky 	}
3558f3e7afe2SHans Petter Selasky 
3559f3e7afe2SHans Petter Selasky 	/* detach rate limiting */
3560f3e7afe2SHans Petter Selasky 	in_pcbdetach_txrtlmt(inp);
3561f3e7afe2SHans Petter Selasky 
3562f3e7afe2SHans Petter Selasky 	/* make sure new mbuf send tag allocation is made */
3563f3e7afe2SHans Petter Selasky 	inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3564f3e7afe2SHans Petter Selasky 
3565f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3566f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3567f3e7afe2SHans Petter Selasky }
356820abea66SRandall Stewart 
3569903c4ee6SXin LI #ifdef INET
357020abea66SRandall Stewart static void
357120abea66SRandall Stewart rl_init(void *st)
357220abea66SRandall Stewart {
35731a714ff2SRandall Stewart 	rate_limit_new = counter_u64_alloc(M_WAITOK);
35741a714ff2SRandall Stewart 	rate_limit_chg = counter_u64_alloc(M_WAITOK);
357520abea66SRandall Stewart 	rate_limit_active = counter_u64_alloc(M_WAITOK);
357620abea66SRandall Stewart 	rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
357720abea66SRandall Stewart 	rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
357820abea66SRandall Stewart }
357920abea66SRandall Stewart 
358020abea66SRandall Stewart SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3581903c4ee6SXin LI #endif
3582f3e7afe2SHans Petter Selasky #endif /* RATELIMIT */
3583