xref: /freebsd/sys/netinet/in_pcb.c (revision 1a714ff204193b9eb810426048e03f5d76e9730e)
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
227*1a714ff2SRandall Stewart counter_u64_t rate_limit_new;
228*1a714ff2SRandall 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");
241*1a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
242*1a714ff2SRandall Stewart    &rate_limit_new, "Total Rate limit new attempts");
243*1a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
244*1a714ff2SRandall Stewart    &rate_limit_chg, "Total Rate limited change attempts");
245*1a714ff2SRandall 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 
6578501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
658fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
65959daba27SSam Leffler 
6604b932371SIan Dowse 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
6614b932371SIan Dowse 		return (EINVAL);
6625cd3dcaaSNavdeep Parhar 	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
6634b932371SIan Dowse 	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
664b0330ed9SPawel Jakub Dawidek 	    &inp->inp_lport, cred);
6654b932371SIan Dowse 	if (error)
6664b932371SIan Dowse 		return (error);
6674b932371SIan Dowse 	if (in_pcbinshash(inp) != 0) {
6684b932371SIan Dowse 		inp->inp_laddr.s_addr = INADDR_ANY;
6694b932371SIan Dowse 		inp->inp_lport = 0;
6704b932371SIan Dowse 		return (EAGAIN);
6714b932371SIan Dowse 	}
6724b932371SIan Dowse 	if (anonport)
6734b932371SIan Dowse 		inp->inp_flags |= INP_ANONPORT;
6744b932371SIan Dowse 	return (0);
6754b932371SIan Dowse }
67667107f45SBjoern A. Zeeb #endif
6774b932371SIan Dowse 
678efc76f72SBjoern A. Zeeb #if defined(INET) || defined(INET6)
67925102351SMike Karels /*
68025102351SMike Karels  * Assign a local port like in_pcb_lport(), but also used with connect()
68125102351SMike Karels  * and a foreign address and port.  If fsa is non-NULL, choose a local port
68225102351SMike Karels  * that is unused with those, otherwise one that is completely unused.
6832fdbcbeaSMike Karels  * lsa can be NULL for IPv6.
68425102351SMike Karels  */
685efc76f72SBjoern A. Zeeb int
68625102351SMike Karels in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
68725102351SMike Karels     struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
688efc76f72SBjoern A. Zeeb {
689efc76f72SBjoern A. Zeeb 	struct inpcbinfo *pcbinfo;
690efc76f72SBjoern A. Zeeb 	struct inpcb *tmpinp;
691efc76f72SBjoern A. Zeeb 	unsigned short *lastport;
692efc76f72SBjoern A. Zeeb 	int count, dorandom, error;
693efc76f72SBjoern A. Zeeb 	u_short aux, first, last, lport;
694efc76f72SBjoern A. Zeeb #ifdef INET
69525102351SMike Karels 	struct in_addr laddr, faddr;
69625102351SMike Karels #endif
69725102351SMike Karels #ifdef INET6
69825102351SMike Karels 	struct in6_addr *laddr6, *faddr6;
699efc76f72SBjoern A. Zeeb #endif
700efc76f72SBjoern A. Zeeb 
701efc76f72SBjoern A. Zeeb 	pcbinfo = inp->inp_pcbinfo;
702efc76f72SBjoern A. Zeeb 
703efc76f72SBjoern A. Zeeb 	/*
704efc76f72SBjoern A. Zeeb 	 * Because no actual state changes occur here, a global write lock on
705efc76f72SBjoern A. Zeeb 	 * the pcbinfo isn't required.
706efc76f72SBjoern A. Zeeb 	 */
707efc76f72SBjoern A. Zeeb 	INP_LOCK_ASSERT(inp);
708fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
709efc76f72SBjoern A. Zeeb 
710efc76f72SBjoern A. Zeeb 	if (inp->inp_flags & INP_HIGHPORT) {
711efc76f72SBjoern A. Zeeb 		first = V_ipport_hifirstauto;	/* sysctl */
712efc76f72SBjoern A. Zeeb 		last  = V_ipport_hilastauto;
713efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lasthi;
714efc76f72SBjoern A. Zeeb 	} else if (inp->inp_flags & INP_LOWPORT) {
715cc426dd3SMateusz Guzik 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
716efc76f72SBjoern A. Zeeb 		if (error)
717efc76f72SBjoern A. Zeeb 			return (error);
718efc76f72SBjoern A. Zeeb 		first = V_ipport_lowfirstauto;	/* 1023 */
719efc76f72SBjoern A. Zeeb 		last  = V_ipport_lowlastauto;	/* 600 */
720efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastlow;
721efc76f72SBjoern A. Zeeb 	} else {
722efc76f72SBjoern A. Zeeb 		first = V_ipport_firstauto;	/* sysctl */
723efc76f72SBjoern A. Zeeb 		last  = V_ipport_lastauto;
724efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastport;
725efc76f72SBjoern A. Zeeb 	}
726efc76f72SBjoern A. Zeeb 	/*
727e06e816fSKevin Lo 	 * For UDP(-Lite), use random port allocation as long as the user
728efc76f72SBjoern A. Zeeb 	 * allows it.  For TCP (and as of yet unknown) connections,
729efc76f72SBjoern A. Zeeb 	 * use random port allocation only if the user allows it AND
730efc76f72SBjoern A. Zeeb 	 * ipport_tick() allows it.
731efc76f72SBjoern A. Zeeb 	 */
732efc76f72SBjoern A. Zeeb 	if (V_ipport_randomized &&
733e06e816fSKevin Lo 		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
734e06e816fSKevin Lo 		pcbinfo == &V_ulitecbinfo))
735efc76f72SBjoern A. Zeeb 		dorandom = 1;
736efc76f72SBjoern A. Zeeb 	else
737efc76f72SBjoern A. Zeeb 		dorandom = 0;
738efc76f72SBjoern A. Zeeb 	/*
739efc76f72SBjoern A. Zeeb 	 * It makes no sense to do random port allocation if
740efc76f72SBjoern A. Zeeb 	 * we have the only port available.
741efc76f72SBjoern A. Zeeb 	 */
742efc76f72SBjoern A. Zeeb 	if (first == last)
743efc76f72SBjoern A. Zeeb 		dorandom = 0;
744e06e816fSKevin Lo 	/* Make sure to not include UDP(-Lite) packets in the count. */
745e06e816fSKevin Lo 	if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
746efc76f72SBjoern A. Zeeb 		V_ipport_tcpallocs++;
747efc76f72SBjoern A. Zeeb 	/*
748efc76f72SBjoern A. Zeeb 	 * Instead of having two loops further down counting up or down
749efc76f72SBjoern A. Zeeb 	 * make sure that first is always <= last and go with only one
750efc76f72SBjoern A. Zeeb 	 * code path implementing all logic.
751efc76f72SBjoern A. Zeeb 	 */
752efc76f72SBjoern A. Zeeb 	if (first > last) {
753efc76f72SBjoern A. Zeeb 		aux = first;
754efc76f72SBjoern A. Zeeb 		first = last;
755efc76f72SBjoern A. Zeeb 		last = aux;
756efc76f72SBjoern A. Zeeb 	}
757efc76f72SBjoern A. Zeeb 
758efc76f72SBjoern A. Zeeb #ifdef INET
75925102351SMike Karels 	laddr.s_addr = INADDR_ANY;
7604d457387SBjoern A. Zeeb 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
7612fdbcbeaSMike Karels 		if (lsa != NULL)
76225102351SMike Karels 			laddr = ((struct sockaddr_in *)lsa)->sin_addr;
76325102351SMike Karels 		if (fsa != NULL)
76425102351SMike Karels 			faddr = ((struct sockaddr_in *)fsa)->sin_addr;
765efc76f72SBjoern A. Zeeb 	}
766efc76f72SBjoern A. Zeeb #endif
76725102351SMike Karels #ifdef INET6
7682fdbcbeaSMike Karels 	laddr6 = NULL;
7692fdbcbeaSMike Karels 	if ((inp->inp_vflag & INP_IPV6) != 0) {
7702fdbcbeaSMike Karels 		if (lsa != NULL)
77125102351SMike Karels 			laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
77225102351SMike Karels 		if (fsa != NULL)
77325102351SMike Karels 			faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
77425102351SMike Karels 	}
77525102351SMike Karels #endif
77625102351SMike Karels 
77725102351SMike Karels 	tmpinp = NULL;
778efc76f72SBjoern A. Zeeb 	lport = *lportp;
779efc76f72SBjoern A. Zeeb 
780efc76f72SBjoern A. Zeeb 	if (dorandom)
781efc76f72SBjoern A. Zeeb 		*lastport = first + (arc4random() % (last - first));
782efc76f72SBjoern A. Zeeb 
783efc76f72SBjoern A. Zeeb 	count = last - first;
784efc76f72SBjoern A. Zeeb 
785efc76f72SBjoern A. Zeeb 	do {
786efc76f72SBjoern A. Zeeb 		if (count-- < 0)	/* completely used? */
787efc76f72SBjoern A. Zeeb 			return (EADDRNOTAVAIL);
788efc76f72SBjoern A. Zeeb 		++*lastport;
789efc76f72SBjoern A. Zeeb 		if (*lastport < first || *lastport > last)
790efc76f72SBjoern A. Zeeb 			*lastport = first;
791efc76f72SBjoern A. Zeeb 		lport = htons(*lastport);
792efc76f72SBjoern A. Zeeb 
79325102351SMike Karels 		if (fsa != NULL) {
79425102351SMike Karels #ifdef INET
79525102351SMike Karels 			if (lsa->sa_family == AF_INET) {
79625102351SMike Karels 				tmpinp = in_pcblookup_hash_locked(pcbinfo,
79725102351SMike Karels 				    faddr, fport, laddr, lport, lookupflags,
798a034518aSAndrew Gallatin 				    NULL, M_NODOM);
79925102351SMike Karels 			}
80025102351SMike Karels #endif
80125102351SMike Karels #ifdef INET6
80225102351SMike Karels 			if (lsa->sa_family == AF_INET6) {
80325102351SMike Karels 				tmpinp = in6_pcblookup_hash_locked(pcbinfo,
80425102351SMike Karels 				    faddr6, fport, laddr6, lport, lookupflags,
805a034518aSAndrew Gallatin 				    NULL, M_NODOM);
80625102351SMike Karels 			}
80725102351SMike Karels #endif
80825102351SMike Karels 		} else {
809efc76f72SBjoern A. Zeeb #ifdef INET6
8104616026fSErmal Luçi 			if ((inp->inp_vflag & INP_IPV6) != 0)
811efc76f72SBjoern A. Zeeb 				tmpinp = in6_pcblookup_local(pcbinfo,
81268e0d7e0SRobert Watson 				    &inp->in6p_laddr, lport, lookupflags, cred);
813efc76f72SBjoern A. Zeeb #endif
814efc76f72SBjoern A. Zeeb #if defined(INET) && defined(INET6)
815efc76f72SBjoern A. Zeeb 			else
816efc76f72SBjoern A. Zeeb #endif
817efc76f72SBjoern A. Zeeb #ifdef INET
818efc76f72SBjoern A. Zeeb 				tmpinp = in_pcblookup_local(pcbinfo, laddr,
81968e0d7e0SRobert Watson 				    lport, lookupflags, cred);
820efc76f72SBjoern A. Zeeb #endif
82125102351SMike Karels 		}
822efc76f72SBjoern A. Zeeb 	} while (tmpinp != NULL);
823efc76f72SBjoern A. Zeeb 
824efc76f72SBjoern A. Zeeb 	*lportp = lport;
825efc76f72SBjoern A. Zeeb 
826efc76f72SBjoern A. Zeeb 	return (0);
827efc76f72SBjoern A. Zeeb }
828efdf104bSMikolaj Golub 
829efdf104bSMikolaj Golub /*
83025102351SMike Karels  * Select a local port (number) to use.
83125102351SMike Karels  */
83225102351SMike Karels int
83325102351SMike Karels in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
83425102351SMike Karels     struct ucred *cred, int lookupflags)
83525102351SMike Karels {
83625102351SMike Karels 	struct sockaddr_in laddr;
83725102351SMike Karels 
83825102351SMike Karels 	if (laddrp) {
83925102351SMike Karels 		bzero(&laddr, sizeof(laddr));
84025102351SMike Karels 		laddr.sin_family = AF_INET;
84125102351SMike Karels 		laddr.sin_addr = *laddrp;
84225102351SMike Karels 	}
84325102351SMike Karels 	return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
84425102351SMike Karels 	    NULL, lportp, NULL, 0, cred, lookupflags));
84525102351SMike Karels }
84625102351SMike Karels 
84725102351SMike Karels /*
848efdf104bSMikolaj Golub  * Return cached socket options.
849efdf104bSMikolaj Golub  */
8501a43cff9SSean Bruno int
851efdf104bSMikolaj Golub inp_so_options(const struct inpcb *inp)
852efdf104bSMikolaj Golub {
8531a43cff9SSean Bruno 	int so_options;
854efdf104bSMikolaj Golub 
855efdf104bSMikolaj Golub 	so_options = 0;
856efdf104bSMikolaj Golub 
8571a43cff9SSean Bruno 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
8581a43cff9SSean Bruno 		so_options |= SO_REUSEPORT_LB;
859efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
860efdf104bSMikolaj Golub 		so_options |= SO_REUSEPORT;
861efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
862efdf104bSMikolaj Golub 		so_options |= SO_REUSEADDR;
863efdf104bSMikolaj Golub 	return (so_options);
864efdf104bSMikolaj Golub }
865efc76f72SBjoern A. Zeeb #endif /* INET || INET6 */
866efc76f72SBjoern A. Zeeb 
8674b932371SIan Dowse /*
8680a100a6fSAdrian Chadd  * Check if a new BINDMULTI socket is allowed to be created.
8690a100a6fSAdrian Chadd  *
8700a100a6fSAdrian Chadd  * ni points to the new inp.
8710a100a6fSAdrian Chadd  * oi points to the exisitng inp.
8720a100a6fSAdrian Chadd  *
8730a100a6fSAdrian Chadd  * This checks whether the existing inp also has BINDMULTI and
8740a100a6fSAdrian Chadd  * whether the credentials match.
8750a100a6fSAdrian Chadd  */
876d5bb8bd3SAdrian Chadd int
8770a100a6fSAdrian Chadd in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
8780a100a6fSAdrian Chadd {
8790a100a6fSAdrian Chadd 	/* Check permissions match */
8800a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
8810a100a6fSAdrian Chadd 	    (ni->inp_cred->cr_uid !=
8820a100a6fSAdrian Chadd 	    oi->inp_cred->cr_uid))
8830a100a6fSAdrian Chadd 		return (0);
8840a100a6fSAdrian Chadd 
8850a100a6fSAdrian Chadd 	/* Check the existing inp has BINDMULTI set */
8860a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
8870a100a6fSAdrian Chadd 	    ((oi->inp_flags2 & INP_BINDMULTI) == 0))
8880a100a6fSAdrian Chadd 		return (0);
8890a100a6fSAdrian Chadd 
8900a100a6fSAdrian Chadd 	/*
8910a100a6fSAdrian Chadd 	 * We're okay - either INP_BINDMULTI isn't set on ni, or
8920a100a6fSAdrian Chadd 	 * it is and it matches the checks.
8930a100a6fSAdrian Chadd 	 */
8940a100a6fSAdrian Chadd 	return (1);
8950a100a6fSAdrian Chadd }
8960a100a6fSAdrian Chadd 
897d5bb8bd3SAdrian Chadd #ifdef INET
8980a100a6fSAdrian Chadd /*
8994b932371SIan Dowse  * Set up a bind operation on a PCB, performing port allocation
9004b932371SIan Dowse  * as required, but do not actually modify the PCB. Callers can
9014b932371SIan Dowse  * either complete the bind by setting inp_laddr/inp_lport and
9024b932371SIan Dowse  * calling in_pcbinshash(), or they can just use the resulting
9034b932371SIan Dowse  * port and address to authorise the sending of a once-off packet.
9044b932371SIan Dowse  *
9054b932371SIan Dowse  * On error, the values of *laddrp and *lportp are not changed.
9064b932371SIan Dowse  */
9074b932371SIan Dowse int
908136d4f1cSRobert Watson in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
909136d4f1cSRobert Watson     u_short *lportp, struct ucred *cred)
9104b932371SIan Dowse {
9114b932371SIan Dowse 	struct socket *so = inp->inp_socket;
91215bd2b43SDavid Greenman 	struct sockaddr_in *sin;
913c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
9144b932371SIan Dowse 	struct in_addr laddr;
915df8bae1dSRodney W. Grimes 	u_short lport = 0;
91668e0d7e0SRobert Watson 	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
917413628a7SBjoern A. Zeeb 	int error;
918df8bae1dSRodney W. Grimes 
9198501a69cSRobert Watson 	/*
9201a43cff9SSean Bruno 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
9211a43cff9SSean Bruno 	 * so that we don't have to add to the (already messy) code below.
9221a43cff9SSean Bruno 	 */
9231a43cff9SSean Bruno 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
9241a43cff9SSean Bruno 
9251a43cff9SSean Bruno 	/*
926fa046d87SRobert Watson 	 * No state changes, so read locks are sufficient here.
9278501a69cSRobert Watson 	 */
92859daba27SSam Leffler 	INP_LOCK_ASSERT(inp);
929fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
93059daba27SSam Leffler 
931d7c5a620SMatt Macy 	if (CK_STAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
932df8bae1dSRodney W. Grimes 		return (EADDRNOTAVAIL);
9334b932371SIan Dowse 	laddr.s_addr = *laddrp;
9344b932371SIan Dowse 	if (nam != NULL && laddr.s_addr != INADDR_ANY)
935df8bae1dSRodney W. Grimes 		return (EINVAL);
9361a43cff9SSean Bruno 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
93768e0d7e0SRobert Watson 		lookupflags = INPLOOKUP_WILDCARD;
9384616026fSErmal Luçi 	if (nam == NULL) {
9397c2f3cb9SJamie Gritton 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
9407c2f3cb9SJamie Gritton 			return (error);
9417c2f3cb9SJamie Gritton 	} else {
94257bf258eSGarrett Wollman 		sin = (struct sockaddr_in *)nam;
94357bf258eSGarrett Wollman 		if (nam->sa_len != sizeof (*sin))
944df8bae1dSRodney W. Grimes 			return (EINVAL);
945df8bae1dSRodney W. Grimes #ifdef notdef
946df8bae1dSRodney W. Grimes 		/*
947df8bae1dSRodney W. Grimes 		 * We should check the family, but old programs
948df8bae1dSRodney W. Grimes 		 * incorrectly fail to initialize it.
949df8bae1dSRodney W. Grimes 		 */
950df8bae1dSRodney W. Grimes 		if (sin->sin_family != AF_INET)
951df8bae1dSRodney W. Grimes 			return (EAFNOSUPPORT);
952df8bae1dSRodney W. Grimes #endif
953b89e82ddSJamie Gritton 		error = prison_local_ip4(cred, &sin->sin_addr);
954b89e82ddSJamie Gritton 		if (error)
955b89e82ddSJamie Gritton 			return (error);
9564b932371SIan Dowse 		if (sin->sin_port != *lportp) {
9574b932371SIan Dowse 			/* Don't allow the port to change. */
9584b932371SIan Dowse 			if (*lportp != 0)
9594b932371SIan Dowse 				return (EINVAL);
960df8bae1dSRodney W. Grimes 			lport = sin->sin_port;
9614b932371SIan Dowse 		}
9624b932371SIan Dowse 		/* NB: lport is left as 0 if the port isn't being changed. */
963df8bae1dSRodney W. Grimes 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
964df8bae1dSRodney W. Grimes 			/*
965df8bae1dSRodney W. Grimes 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
966df8bae1dSRodney W. Grimes 			 * allow complete duplication of binding if
967df8bae1dSRodney W. Grimes 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
968df8bae1dSRodney W. Grimes 			 * and a multicast address is bound on both
969df8bae1dSRodney W. Grimes 			 * new and duplicated sockets.
970df8bae1dSRodney W. Grimes 			 */
971f122b319SMikolaj Golub 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
972df8bae1dSRodney W. Grimes 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
9731a43cff9SSean Bruno 			/*
9741a43cff9SSean Bruno 			 * XXX: How to deal with SO_REUSEPORT_LB here?
9751a43cff9SSean Bruno 			 * Treat same as SO_REUSEPORT for now.
9761a43cff9SSean Bruno 			 */
9771a43cff9SSean Bruno 			if ((so->so_options &
9781a43cff9SSean Bruno 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
9791a43cff9SSean Bruno 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
980df8bae1dSRodney W. Grimes 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
981df8bae1dSRodney W. Grimes 			sin->sin_port = 0;		/* yech... */
98283103a73SAndrew R. Reiter 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
9834209e01aSAdrian Chadd 			/*
9844209e01aSAdrian Chadd 			 * Is the address a local IP address?
985f44270e7SPawel Jakub Dawidek 			 * If INP_BINDANY is set, then the socket may be bound
9868696873dSAdrian Chadd 			 * to any endpoint address, local or not.
9874209e01aSAdrian Chadd 			 */
988f44270e7SPawel Jakub Dawidek 			if ((inp->inp_flags & INP_BINDANY) == 0 &&
9898896f83aSRobert Watson 			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
990df8bae1dSRodney W. Grimes 				return (EADDRNOTAVAIL);
991df8bae1dSRodney W. Grimes 		}
9924b932371SIan Dowse 		laddr = sin->sin_addr;
993df8bae1dSRodney W. Grimes 		if (lport) {
994df8bae1dSRodney W. Grimes 			struct inpcb *t;
995ae0e7143SRobert Watson 			struct tcptw *tw;
996ae0e7143SRobert Watson 
997df8bae1dSRodney W. Grimes 			/* GROSS */
998603724d3SBjoern A. Zeeb 			if (ntohs(lport) <= V_ipport_reservedhigh &&
999603724d3SBjoern A. Zeeb 			    ntohs(lport) >= V_ipport_reservedlow &&
1000cc426dd3SMateusz Guzik 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
10012469dd60SGarrett Wollman 				return (EACCES);
1002835d4b89SPawel Jakub Dawidek 			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
1003cc426dd3SMateusz Guzik 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
1004078b7042SBjoern A. Zeeb 				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1005413628a7SBjoern A. Zeeb 				    lport, INPLOOKUP_WILDCARD, cred);
1006340c35deSJonathan Lemon 	/*
1007340c35deSJonathan Lemon 	 * XXX
1008340c35deSJonathan Lemon 	 * This entire block sorely needs a rewrite.
1009340c35deSJonathan Lemon 	 */
10104cc20ab1SSeigo Tanimura 				if (t &&
10110a100a6fSAdrian Chadd 				    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1012ad71fe3cSRobert Watson 				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
10134658dc83SYaroslav Tykhiy 				    (so->so_type != SOCK_STREAM ||
10144658dc83SYaroslav Tykhiy 				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
10154cc20ab1SSeigo Tanimura 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
101652b65dbeSBill Fenner 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
10171a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT) ||
10181a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
101986d02c5cSBjoern A. Zeeb 				    (inp->inp_cred->cr_uid !=
102086d02c5cSBjoern A. Zeeb 				     t->inp_cred->cr_uid))
10214049a042SGuido van Rooij 					return (EADDRINUSE);
10220a100a6fSAdrian Chadd 
10230a100a6fSAdrian Chadd 				/*
10240a100a6fSAdrian Chadd 				 * If the socket is a BINDMULTI socket, then
10250a100a6fSAdrian Chadd 				 * the credentials need to match and the
10260a100a6fSAdrian Chadd 				 * original socket also has to have been bound
10270a100a6fSAdrian Chadd 				 * with BINDMULTI.
10280a100a6fSAdrian Chadd 				 */
10290a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
10300a100a6fSAdrian Chadd 					return (EADDRINUSE);
10314049a042SGuido van Rooij 			}
1032c3229e05SDavid Greenman 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
103368e0d7e0SRobert Watson 			    lport, lookupflags, cred);
1034ad71fe3cSRobert Watson 			if (t && (t->inp_flags & INP_TIMEWAIT)) {
1035ae0e7143SRobert Watson 				/*
1036ae0e7143SRobert Watson 				 * XXXRW: If an incpb has had its timewait
1037ae0e7143SRobert Watson 				 * state recycled, we treat the address as
1038ae0e7143SRobert Watson 				 * being in use (for now).  This is better
1039ae0e7143SRobert Watson 				 * than a panic, but not desirable.
1040ae0e7143SRobert Watson 				 */
1041ec95b709SMikolaj Golub 				tw = intotw(t);
1042ae0e7143SRobert Watson 				if (tw == NULL ||
10431a43cff9SSean Bruno 				    ((reuseport & tw->tw_so_options) == 0 &&
10441a43cff9SSean Bruno 					(reuseport_lb &
10451a43cff9SSean Bruno 				            tw->tw_so_options) == 0)) {
1046340c35deSJonathan Lemon 					return (EADDRINUSE);
10471a43cff9SSean Bruno 				}
10480a100a6fSAdrian Chadd 			} else if (t &&
10490a100a6fSAdrian Chadd 				   ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
10501a43cff9SSean Bruno 				   (reuseport & inp_so_options(t)) == 0 &&
10511a43cff9SSean Bruno 				   (reuseport_lb & inp_so_options(t)) == 0) {
1052e3fd5ffdSRobert Watson #ifdef INET6
105333841545SHajimu UMEMOTO 				if (ntohl(sin->sin_addr.s_addr) !=
1054cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
1055cfa1ca9dSYoshinobu Inoue 				    ntohl(t->inp_laddr.s_addr) !=
1056cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
1057fc06cd42SMikolaj Golub 				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1058fc06cd42SMikolaj Golub 				    (t->inp_vflag & INP_IPV6PROTO) == 0)
1059e3fd5ffdSRobert Watson #endif
1060df8bae1dSRodney W. Grimes 						return (EADDRINUSE);
10610a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
10620a100a6fSAdrian Chadd 					return (EADDRINUSE);
1063df8bae1dSRodney W. Grimes 			}
1064cfa1ca9dSYoshinobu Inoue 		}
1065df8bae1dSRodney W. Grimes 	}
10664b932371SIan Dowse 	if (*lportp != 0)
10674b932371SIan Dowse 		lport = *lportp;
106833b3ac06SPeter Wemm 	if (lport == 0) {
10694616026fSErmal Luçi 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1070efc76f72SBjoern A. Zeeb 		if (error != 0)
1071efc76f72SBjoern A. Zeeb 			return (error);
107233b3ac06SPeter Wemm 	}
10734b932371SIan Dowse 	*laddrp = laddr.s_addr;
10744b932371SIan Dowse 	*lportp = lport;
1075df8bae1dSRodney W. Grimes 	return (0);
1076df8bae1dSRodney W. Grimes }
1077df8bae1dSRodney W. Grimes 
1078999f1343SGarrett Wollman /*
10795200e00eSIan Dowse  * Connect from a socket to a specified address.
10805200e00eSIan Dowse  * Both address and port must be specified in argument sin.
10815200e00eSIan Dowse  * If don't have a local address for this socket yet,
10825200e00eSIan Dowse  * then pick one.
1083999f1343SGarrett Wollman  */
1084999f1343SGarrett Wollman int
1085d3c1f003SRobert Watson in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
1086fe1274eeSMichael Tuexen     struct ucred *cred, struct mbuf *m, bool rehash)
1087999f1343SGarrett Wollman {
10885200e00eSIan Dowse 	u_short lport, fport;
10895200e00eSIan Dowse 	in_addr_t laddr, faddr;
10905200e00eSIan Dowse 	int anonport, error;
1091df8bae1dSRodney W. Grimes 
10928501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1093fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
109427f74fd0SRobert Watson 
10955200e00eSIan Dowse 	lport = inp->inp_lport;
10965200e00eSIan Dowse 	laddr = inp->inp_laddr.s_addr;
10975200e00eSIan Dowse 	anonport = (lport == 0);
10985200e00eSIan Dowse 	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
1099b0330ed9SPawel Jakub Dawidek 	    NULL, cred);
11005200e00eSIan Dowse 	if (error)
11015200e00eSIan Dowse 		return (error);
11025200e00eSIan Dowse 
11035200e00eSIan Dowse 	/* Do the initial binding of the local address if required. */
11045200e00eSIan Dowse 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1105fe1274eeSMichael Tuexen 		KASSERT(rehash == true,
1106fe1274eeSMichael Tuexen 		    ("Rehashing required for unbound inps"));
11075200e00eSIan Dowse 		inp->inp_lport = lport;
11085200e00eSIan Dowse 		inp->inp_laddr.s_addr = laddr;
11095200e00eSIan Dowse 		if (in_pcbinshash(inp) != 0) {
11105200e00eSIan Dowse 			inp->inp_laddr.s_addr = INADDR_ANY;
11115200e00eSIan Dowse 			inp->inp_lport = 0;
11125200e00eSIan Dowse 			return (EAGAIN);
11135200e00eSIan Dowse 		}
11145200e00eSIan Dowse 	}
11155200e00eSIan Dowse 
11165200e00eSIan Dowse 	/* Commit the remaining changes. */
11175200e00eSIan Dowse 	inp->inp_lport = lport;
11185200e00eSIan Dowse 	inp->inp_laddr.s_addr = laddr;
11195200e00eSIan Dowse 	inp->inp_faddr.s_addr = faddr;
11205200e00eSIan Dowse 	inp->inp_fport = fport;
1121fe1274eeSMichael Tuexen 	if (rehash) {
1122d3c1f003SRobert Watson 		in_pcbrehash_mbuf(inp, m);
1123fe1274eeSMichael Tuexen 	} else {
1124fe1274eeSMichael Tuexen 		in_pcbinshash_mbuf(inp, m);
1125fe1274eeSMichael Tuexen 	}
11262cb64cb2SGeorge V. Neville-Neil 
11275200e00eSIan Dowse 	if (anonport)
11285200e00eSIan Dowse 		inp->inp_flags |= INP_ANONPORT;
11295200e00eSIan Dowse 	return (0);
11305200e00eSIan Dowse }
11315200e00eSIan Dowse 
1132d3c1f003SRobert Watson int
1133d3c1f003SRobert Watson in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1134d3c1f003SRobert Watson {
1135d3c1f003SRobert Watson 
1136fe1274eeSMichael Tuexen 	return (in_pcbconnect_mbuf(inp, nam, cred, NULL, true));
1137d3c1f003SRobert Watson }
1138d3c1f003SRobert Watson 
11395200e00eSIan Dowse /*
11400895aec3SBjoern A. Zeeb  * Do proper source address selection on an unbound socket in case
11410895aec3SBjoern A. Zeeb  * of connect. Take jails into account as well.
11420895aec3SBjoern A. Zeeb  */
1143ae190832SSteven Hartland int
11440895aec3SBjoern A. Zeeb in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
11450895aec3SBjoern A. Zeeb     struct ucred *cred)
11460895aec3SBjoern A. Zeeb {
11470895aec3SBjoern A. Zeeb 	struct ifaddr *ifa;
11480895aec3SBjoern A. Zeeb 	struct sockaddr *sa;
11499ac7c6cfSAlexander V. Chernikov 	struct sockaddr_in *sin, dst;
11509ac7c6cfSAlexander V. Chernikov 	struct nhop_object *nh;
11510895aec3SBjoern A. Zeeb 	int error;
11520895aec3SBjoern A. Zeeb 
1153c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
1154413628a7SBjoern A. Zeeb 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1155592bcae8SBjoern A. Zeeb 	/*
1156592bcae8SBjoern A. Zeeb 	 * Bypass source address selection and use the primary jail IP
1157592bcae8SBjoern A. Zeeb 	 * if requested.
1158592bcae8SBjoern A. Zeeb 	 */
1159592bcae8SBjoern A. Zeeb 	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1160592bcae8SBjoern A. Zeeb 		return (0);
1161592bcae8SBjoern A. Zeeb 
11620895aec3SBjoern A. Zeeb 	error = 0;
11630895aec3SBjoern A. Zeeb 
11649ac7c6cfSAlexander V. Chernikov 	nh = NULL;
11659ac7c6cfSAlexander V. Chernikov 	bzero(&dst, sizeof(dst));
11669ac7c6cfSAlexander V. Chernikov 	sin = &dst;
11670895aec3SBjoern A. Zeeb 	sin->sin_family = AF_INET;
11680895aec3SBjoern A. Zeeb 	sin->sin_len = sizeof(struct sockaddr_in);
11690895aec3SBjoern A. Zeeb 	sin->sin_addr.s_addr = faddr->s_addr;
11700895aec3SBjoern A. Zeeb 
11710895aec3SBjoern A. Zeeb 	/*
11720895aec3SBjoern A. Zeeb 	 * If route is known our src addr is taken from the i/f,
11730895aec3SBjoern A. Zeeb 	 * else punt.
11740895aec3SBjoern A. Zeeb 	 *
11750895aec3SBjoern A. Zeeb 	 * Find out route to destination.
11760895aec3SBjoern A. Zeeb 	 */
11770895aec3SBjoern A. Zeeb 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
11789ac7c6cfSAlexander V. Chernikov 		nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
11799ac7c6cfSAlexander V. Chernikov 		    0, NHR_NONE, 0);
11800895aec3SBjoern A. Zeeb 
11810895aec3SBjoern A. Zeeb 	/*
11820895aec3SBjoern A. Zeeb 	 * If we found a route, use the address corresponding to
11830895aec3SBjoern A. Zeeb 	 * the outgoing interface.
11840895aec3SBjoern A. Zeeb 	 *
11850895aec3SBjoern A. Zeeb 	 * Otherwise assume faddr is reachable on a directly connected
11860895aec3SBjoern A. Zeeb 	 * network and try to find a corresponding interface to take
11870895aec3SBjoern A. Zeeb 	 * the source address from.
11880895aec3SBjoern A. Zeeb 	 */
11899ac7c6cfSAlexander V. Chernikov 	if (nh == NULL || nh->nh_ifp == NULL) {
11908c0fec80SRobert Watson 		struct in_ifaddr *ia;
11910895aec3SBjoern A. Zeeb 		struct ifnet *ifp;
11920895aec3SBjoern A. Zeeb 
11934f8585e0SAlan Somers 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
119458a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
11954f6c66ccSMatt Macy 		if (ia == NULL) {
11964f8585e0SAlan Somers 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
119758a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
11984f6c66ccSMatt Macy 		}
11990895aec3SBjoern A. Zeeb 		if (ia == NULL) {
12000895aec3SBjoern A. Zeeb 			error = ENETUNREACH;
12010895aec3SBjoern A. Zeeb 			goto done;
12020895aec3SBjoern A. Zeeb 		}
12030895aec3SBjoern A. Zeeb 
12040304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
12050895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12060895aec3SBjoern A. Zeeb 			goto done;
12070895aec3SBjoern A. Zeeb 		}
12080895aec3SBjoern A. Zeeb 
12090895aec3SBjoern A. Zeeb 		ifp = ia->ia_ifp;
12100895aec3SBjoern A. Zeeb 		ia = NULL;
1211d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12120895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12130895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12140895aec3SBjoern A. Zeeb 				continue;
12150895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1216b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12170895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12180895aec3SBjoern A. Zeeb 				break;
12190895aec3SBjoern A. Zeeb 			}
12200895aec3SBjoern A. Zeeb 		}
12210895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12220895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12230895aec3SBjoern A. Zeeb 			goto done;
12240895aec3SBjoern A. Zeeb 		}
12250895aec3SBjoern A. Zeeb 
12260895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1227b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12280895aec3SBjoern A. Zeeb 		goto done;
12290895aec3SBjoern A. Zeeb 	}
12300895aec3SBjoern A. Zeeb 
12310895aec3SBjoern A. Zeeb 	/*
12320895aec3SBjoern A. Zeeb 	 * If the outgoing interface on the route found is not
12330895aec3SBjoern A. Zeeb 	 * a loopback interface, use the address from that interface.
12340895aec3SBjoern A. Zeeb 	 * In case of jails do those three steps:
12350895aec3SBjoern A. Zeeb 	 * 1. check if the interface address belongs to the jail. If so use it.
12360895aec3SBjoern A. Zeeb 	 * 2. check if we have any address on the outgoing interface
12370895aec3SBjoern A. Zeeb 	 *    belonging to this jail. If so use it.
12380895aec3SBjoern A. Zeeb 	 * 3. as a last resort return the 'default' jail address.
12390895aec3SBjoern A. Zeeb 	 */
12409ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
12418c0fec80SRobert Watson 		struct in_ifaddr *ia;
12429317b04eSRobert Watson 		struct ifnet *ifp;
12430895aec3SBjoern A. Zeeb 
12440895aec3SBjoern A. Zeeb 		/* If not jailed, use the default returned. */
12450304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
12469ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
12470895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12480895aec3SBjoern A. Zeeb 			goto done;
12490895aec3SBjoern A. Zeeb 		}
12500895aec3SBjoern A. Zeeb 
12510895aec3SBjoern A. Zeeb 		/* Jailed. */
12520895aec3SBjoern A. Zeeb 		/* 1. Check if the iface address belongs to the jail. */
12539ac7c6cfSAlexander V. Chernikov 		sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1254b89e82ddSJamie Gritton 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12559ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
12560895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12570895aec3SBjoern A. Zeeb 			goto done;
12580895aec3SBjoern A. Zeeb 		}
12590895aec3SBjoern A. Zeeb 
12600895aec3SBjoern A. Zeeb 		/*
12610895aec3SBjoern A. Zeeb 		 * 2. Check if we have any address on the outgoing interface
12620895aec3SBjoern A. Zeeb 		 *    belonging to this jail.
12630895aec3SBjoern A. Zeeb 		 */
12648c0fec80SRobert Watson 		ia = NULL;
12659ac7c6cfSAlexander V. Chernikov 		ifp = nh->nh_ifp;
1266d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12670895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12680895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12690895aec3SBjoern A. Zeeb 				continue;
12700895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1271b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12720895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12730895aec3SBjoern A. Zeeb 				break;
12740895aec3SBjoern A. Zeeb 			}
12750895aec3SBjoern A. Zeeb 		}
12760895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12770895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12780895aec3SBjoern A. Zeeb 			goto done;
12790895aec3SBjoern A. Zeeb 		}
12800895aec3SBjoern A. Zeeb 
12810895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1282b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12830895aec3SBjoern A. Zeeb 		goto done;
12840895aec3SBjoern A. Zeeb 	}
12850895aec3SBjoern A. Zeeb 
12860895aec3SBjoern A. Zeeb 	/*
12870895aec3SBjoern A. Zeeb 	 * The outgoing interface is marked with 'loopback net', so a route
12880895aec3SBjoern A. Zeeb 	 * to ourselves is here.
12890895aec3SBjoern A. Zeeb 	 * Try to find the interface of the destination address and then
12900895aec3SBjoern A. Zeeb 	 * take the address from there. That interface is not necessarily
12910895aec3SBjoern A. Zeeb 	 * a loopback interface.
12920895aec3SBjoern A. Zeeb 	 * In case of jails, check that it is an address of the jail
12930895aec3SBjoern A. Zeeb 	 * and if we cannot find, fall back to the 'default' jail address.
12940895aec3SBjoern A. Zeeb 	 */
12959ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
12968c0fec80SRobert Watson 		struct in_ifaddr *ia;
12970895aec3SBjoern A. Zeeb 
12989ac7c6cfSAlexander V. Chernikov 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
129958a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
13000895aec3SBjoern A. Zeeb 		if (ia == NULL)
13019ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
130258a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
1303f0bb05fcSQing Li 		if (ia == NULL)
13049ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
13050895aec3SBjoern A. Zeeb 
13060304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
13070895aec3SBjoern A. Zeeb 			if (ia == NULL) {
13080895aec3SBjoern A. Zeeb 				error = ENETUNREACH;
13090895aec3SBjoern A. Zeeb 				goto done;
13100895aec3SBjoern A. Zeeb 			}
13110895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13120895aec3SBjoern A. Zeeb 			goto done;
13130895aec3SBjoern A. Zeeb 		}
13140895aec3SBjoern A. Zeeb 
13150895aec3SBjoern A. Zeeb 		/* Jailed. */
13160895aec3SBjoern A. Zeeb 		if (ia != NULL) {
13170895aec3SBjoern A. Zeeb 			struct ifnet *ifp;
13180895aec3SBjoern A. Zeeb 
13190895aec3SBjoern A. Zeeb 			ifp = ia->ia_ifp;
13200895aec3SBjoern A. Zeeb 			ia = NULL;
1321d7c5a620SMatt Macy 			CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
13220895aec3SBjoern A. Zeeb 				sa = ifa->ifa_addr;
13230895aec3SBjoern A. Zeeb 				if (sa->sa_family != AF_INET)
13240895aec3SBjoern A. Zeeb 					continue;
13250895aec3SBjoern A. Zeeb 				sin = (struct sockaddr_in *)sa;
1326b89e82ddSJamie Gritton 				if (prison_check_ip4(cred,
1327b89e82ddSJamie Gritton 				    &sin->sin_addr) == 0) {
13280895aec3SBjoern A. Zeeb 					ia = (struct in_ifaddr *)ifa;
13290895aec3SBjoern A. Zeeb 					break;
13300895aec3SBjoern A. Zeeb 				}
13310895aec3SBjoern A. Zeeb 			}
13320895aec3SBjoern A. Zeeb 			if (ia != NULL) {
13330895aec3SBjoern A. Zeeb 				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13340895aec3SBjoern A. Zeeb 				goto done;
13350895aec3SBjoern A. Zeeb 			}
13360895aec3SBjoern A. Zeeb 		}
13370895aec3SBjoern A. Zeeb 
13380895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1339b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
13400895aec3SBjoern A. Zeeb 		goto done;
13410895aec3SBjoern A. Zeeb 	}
13420895aec3SBjoern A. Zeeb 
13430895aec3SBjoern A. Zeeb done:
13440895aec3SBjoern A. Zeeb 	return (error);
13450895aec3SBjoern A. Zeeb }
13460895aec3SBjoern A. Zeeb 
13470895aec3SBjoern A. Zeeb /*
13485200e00eSIan Dowse  * Set up for a connect from a socket to the specified address.
13495200e00eSIan Dowse  * On entry, *laddrp and *lportp should contain the current local
13505200e00eSIan Dowse  * address and port for the PCB; these are updated to the values
13515200e00eSIan Dowse  * that should be placed in inp_laddr and inp_lport to complete
13525200e00eSIan Dowse  * the connect.
13535200e00eSIan Dowse  *
13545200e00eSIan Dowse  * On success, *faddrp and *fportp will be set to the remote address
13555200e00eSIan Dowse  * and port. These are not updated in the error case.
13565200e00eSIan Dowse  *
13575200e00eSIan Dowse  * If the operation fails because the connection already exists,
13585200e00eSIan Dowse  * *oinpp will be set to the PCB of that connection so that the
13595200e00eSIan Dowse  * caller can decide to override it. In all other cases, *oinpp
13605200e00eSIan Dowse  * is set to NULL.
13615200e00eSIan Dowse  */
13625200e00eSIan Dowse int
1363136d4f1cSRobert Watson in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1364136d4f1cSRobert Watson     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1365136d4f1cSRobert Watson     struct inpcb **oinpp, struct ucred *cred)
13665200e00eSIan Dowse {
1367cc0a3c8cSAndrey V. Elsukov 	struct rm_priotracker in_ifa_tracker;
13685200e00eSIan Dowse 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
13695200e00eSIan Dowse 	struct in_ifaddr *ia;
13705200e00eSIan Dowse 	struct inpcb *oinp;
1371b89e82ddSJamie Gritton 	struct in_addr laddr, faddr;
13725200e00eSIan Dowse 	u_short lport, fport;
13735200e00eSIan Dowse 	int error;
13745200e00eSIan Dowse 
13758501a69cSRobert Watson 	/*
13768501a69cSRobert Watson 	 * Because a global state change doesn't actually occur here, a read
13778501a69cSRobert Watson 	 * lock is sufficient.
13788501a69cSRobert Watson 	 */
1379c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
138027f74fd0SRobert Watson 	INP_LOCK_ASSERT(inp);
1381fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
138227f74fd0SRobert Watson 
13835200e00eSIan Dowse 	if (oinpp != NULL)
13845200e00eSIan Dowse 		*oinpp = NULL;
138557bf258eSGarrett Wollman 	if (nam->sa_len != sizeof (*sin))
1386df8bae1dSRodney W. Grimes 		return (EINVAL);
1387df8bae1dSRodney W. Grimes 	if (sin->sin_family != AF_INET)
1388df8bae1dSRodney W. Grimes 		return (EAFNOSUPPORT);
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,
2521a034518aSAndrew Gallatin 	    (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp,
2522a034518aSAndrew Gallatin 	    numa_domain);
2523fa046d87SRobert Watson 	if (inp != NULL) {
2524fa046d87SRobert Watson 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
2525fa046d87SRobert Watson 			INP_WLOCK(inp);
25263d348772SMatt Macy 			if (__predict_false(inp->inp_flags2 & INP_FREED)) {
25273d348772SMatt Macy 				INP_WUNLOCK(inp);
25283d348772SMatt Macy 				inp = NULL;
25293d348772SMatt Macy 			}
25303d348772SMatt Macy 		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2531fa046d87SRobert Watson 			INP_RLOCK(inp);
25323d348772SMatt Macy 			if (__predict_false(inp->inp_flags2 & INP_FREED)) {
25333d348772SMatt Macy 				INP_RUNLOCK(inp);
25343d348772SMatt Macy 				inp = NULL;
25357fb2986fSJonathan T. Looney 			}
25363d348772SMatt Macy 		} else
25373d348772SMatt Macy 			panic("%s: locking bug", __func__);
25387fb2986fSJonathan T. Looney #ifdef INVARIANTS
25393d348772SMatt Macy 		if (inp != NULL) {
25407fb2986fSJonathan T. Looney 			if (lookupflags & INPLOOKUP_WLOCKPCB)
25417fb2986fSJonathan T. Looney 				INP_WLOCK_ASSERT(inp);
25427fb2986fSJonathan T. Looney 			else
25437fb2986fSJonathan T. Looney 				INP_RLOCK_ASSERT(inp);
25443d348772SMatt Macy 		}
25457fb2986fSJonathan T. Looney #endif
25463d348772SMatt Macy 	}
2547d797164aSGleb Smirnoff 
2548fa046d87SRobert Watson 	return (inp);
2549fa046d87SRobert Watson }
2550fa046d87SRobert Watson 
2551fa046d87SRobert Watson /*
2552d3c1f003SRobert Watson  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2553d3c1f003SRobert Watson  * from which a pre-calculated hash value may be extracted.
255452cd27cbSRobert Watson  *
255552cd27cbSRobert Watson  * Possibly more of this logic should be in in_pcbgroup.c.
2556fa046d87SRobert Watson  */
2557fa046d87SRobert Watson struct inpcb *
2558fa046d87SRobert Watson in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2559fa046d87SRobert Watson     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2560fa046d87SRobert Watson {
25617527624eSRobert Watson #if defined(PCBGROUP) && !defined(RSS)
256252cd27cbSRobert Watson 	struct inpcbgroup *pcbgroup;
256352cd27cbSRobert Watson #endif
2564fa046d87SRobert Watson 
2565fa046d87SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2566fa046d87SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2567fa046d87SRobert Watson 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2568fa046d87SRobert Watson 	    ("%s: LOCKPCB not set", __func__));
2569fa046d87SRobert Watson 
25707527624eSRobert Watson 	/*
25717527624eSRobert Watson 	 * When not using RSS, use connection groups in preference to the
25727527624eSRobert Watson 	 * reservation table when looking up 4-tuples.  When using RSS, just
25737527624eSRobert Watson 	 * use the reservation table, due to the cost of the Toeplitz hash
25747527624eSRobert Watson 	 * in software.
25757527624eSRobert Watson 	 *
25767527624eSRobert Watson 	 * XXXRW: This policy belongs in the pcbgroup code, as in principle
25777527624eSRobert Watson 	 * we could be doing RSS with a non-Toeplitz hash that is affordable
25787527624eSRobert Watson 	 * in software.
25797527624eSRobert Watson 	 */
25807527624eSRobert Watson #if defined(PCBGROUP) && !defined(RSS)
258152cd27cbSRobert Watson 	if (in_pcbgroup_enabled(pcbinfo)) {
258252cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
258352cd27cbSRobert Watson 		    fport);
258452cd27cbSRobert Watson 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
258552cd27cbSRobert Watson 		    laddr, lport, lookupflags, ifp));
258652cd27cbSRobert Watson 	}
258752cd27cbSRobert Watson #endif
2588fa046d87SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2589a034518aSAndrew Gallatin 	    lookupflags, ifp, M_NODOM));
2590fa046d87SRobert Watson }
2591d3c1f003SRobert Watson 
2592d3c1f003SRobert Watson struct inpcb *
2593d3c1f003SRobert Watson in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2594d3c1f003SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2595d3c1f003SRobert Watson     struct ifnet *ifp, struct mbuf *m)
2596d3c1f003SRobert Watson {
259752cd27cbSRobert Watson #ifdef PCBGROUP
259852cd27cbSRobert Watson 	struct inpcbgroup *pcbgroup;
259952cd27cbSRobert Watson #endif
2600d3c1f003SRobert Watson 
2601d3c1f003SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2602d3c1f003SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2603d3c1f003SRobert Watson 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2604d3c1f003SRobert Watson 	    ("%s: LOCKPCB not set", __func__));
2605d3c1f003SRobert Watson 
260652cd27cbSRobert Watson #ifdef PCBGROUP
26077527624eSRobert Watson 	/*
26087527624eSRobert Watson 	 * If we can use a hardware-generated hash to look up the connection
26097527624eSRobert Watson 	 * group, use that connection group to find the inpcb.  Otherwise
26107527624eSRobert Watson 	 * fall back on a software hash -- or the reservation table if we're
26117527624eSRobert Watson 	 * using RSS.
26127527624eSRobert Watson 	 *
26137527624eSRobert Watson 	 * XXXRW: As above, that policy belongs in the pcbgroup code.
26147527624eSRobert Watson 	 */
26157527624eSRobert Watson 	if (in_pcbgroup_enabled(pcbinfo) &&
26167527624eSRobert Watson 	    !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
261752cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
261852cd27cbSRobert Watson 		    m->m_pkthdr.flowid);
261952cd27cbSRobert Watson 		if (pcbgroup != NULL)
262052cd27cbSRobert Watson 			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
262152cd27cbSRobert Watson 			    fport, laddr, lport, lookupflags, ifp));
26227527624eSRobert Watson #ifndef RSS
262352cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
262452cd27cbSRobert Watson 		    fport);
262552cd27cbSRobert Watson 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
262652cd27cbSRobert Watson 		    laddr, lport, lookupflags, ifp));
26277527624eSRobert Watson #endif
262852cd27cbSRobert Watson 	}
262952cd27cbSRobert Watson #endif
2630d3c1f003SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2631a034518aSAndrew Gallatin 	    lookupflags, ifp, m->m_pkthdr.numa_domain));
2632d3c1f003SRobert Watson }
263367107f45SBjoern A. Zeeb #endif /* INET */
263415bd2b43SDavid Greenman 
26357bc4aca7SDavid Greenman /*
2636c3229e05SDavid Greenman  * Insert PCB onto various hash lists.
26377bc4aca7SDavid Greenman  */
263852cd27cbSRobert Watson static int
2639fe1274eeSMichael Tuexen in_pcbinshash_internal(struct inpcb *inp, struct mbuf *m)
264015bd2b43SDavid Greenman {
2641c3229e05SDavid Greenman 	struct inpcbhead *pcbhash;
2642c3229e05SDavid Greenman 	struct inpcbporthead *pcbporthash;
2643c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2644c3229e05SDavid Greenman 	struct inpcbport *phd;
2645cfa1ca9dSYoshinobu Inoue 	u_int32_t hashkey_faddr;
26461a43cff9SSean Bruno 	int so_options;
264715bd2b43SDavid Greenman 
26488501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2649fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2650fa046d87SRobert Watson 
2651111d57a6SRobert Watson 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2652111d57a6SRobert Watson 	    ("in_pcbinshash: INP_INHASHLIST"));
2653602cc7f1SRobert Watson 
2654cfa1ca9dSYoshinobu Inoue #ifdef INET6
2655cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
26561b44e5ffSAndrey V. Elsukov 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2657cfa1ca9dSYoshinobu Inoue 	else
265883e521ecSBjoern A. Zeeb #endif
2659cfa1ca9dSYoshinobu Inoue 	hashkey_faddr = inp->inp_faddr.s_addr;
2660cfa1ca9dSYoshinobu Inoue 
2661712fc218SRobert Watson 	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2662712fc218SRobert Watson 		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
266315bd2b43SDavid Greenman 
2664712fc218SRobert Watson 	pcbporthash = &pcbinfo->ipi_porthashbase[
2665712fc218SRobert Watson 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2666c3229e05SDavid Greenman 
2667c3229e05SDavid Greenman 	/*
26681a43cff9SSean Bruno 	 * Add entry to load balance group.
26691a43cff9SSean Bruno 	 * Only do this if SO_REUSEPORT_LB is set.
26701a43cff9SSean Bruno 	 */
26711a43cff9SSean Bruno 	so_options = inp_so_options(inp);
26721a43cff9SSean Bruno 	if (so_options & SO_REUSEPORT_LB) {
2673a034518aSAndrew Gallatin 		int ret = in_pcbinslbgrouphash(inp, M_NODOM);
26741a43cff9SSean Bruno 		if (ret) {
26751a43cff9SSean Bruno 			/* pcb lb group malloc fail (ret=ENOBUFS). */
26761a43cff9SSean Bruno 			return (ret);
26771a43cff9SSean Bruno 		}
26781a43cff9SSean Bruno 	}
26791a43cff9SSean Bruno 
26801a43cff9SSean Bruno 	/*
2681c3229e05SDavid Greenman 	 * Go through port list and look for a head for this lport.
2682c3229e05SDavid Greenman 	 */
2683b872626dSMatt Macy 	CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2684c3229e05SDavid Greenman 		if (phd->phd_port == inp->inp_lport)
2685c3229e05SDavid Greenman 			break;
2686c3229e05SDavid Greenman 	}
2687c3229e05SDavid Greenman 	/*
2688c3229e05SDavid Greenman 	 * If none exists, malloc one and tack it on.
2689c3229e05SDavid Greenman 	 */
2690c3229e05SDavid Greenman 	if (phd == NULL) {
26911ede983cSDag-Erling Smørgrav 		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2692c3229e05SDavid Greenman 		if (phd == NULL) {
2693c3229e05SDavid Greenman 			return (ENOBUFS); /* XXX */
2694c3229e05SDavid Greenman 		}
2695f09ee4fcSMatt Macy 		bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2696c3229e05SDavid Greenman 		phd->phd_port = inp->inp_lport;
2697b872626dSMatt Macy 		CK_LIST_INIT(&phd->phd_pcblist);
2698b872626dSMatt Macy 		CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2699c3229e05SDavid Greenman 	}
2700c3229e05SDavid Greenman 	inp->inp_phd = phd;
2701b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2702b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2703111d57a6SRobert Watson 	inp->inp_flags |= INP_INHASHLIST;
270452cd27cbSRobert Watson #ifdef PCBGROUP
2705fe1274eeSMichael Tuexen 	if (m != NULL) {
2706fe1274eeSMichael Tuexen 		in_pcbgroup_update_mbuf(inp, m);
2707fe1274eeSMichael Tuexen 	} else {
270852cd27cbSRobert Watson 		in_pcbgroup_update(inp);
2709fe1274eeSMichael Tuexen 	}
271052cd27cbSRobert Watson #endif
2711c3229e05SDavid Greenman 	return (0);
271215bd2b43SDavid Greenman }
271315bd2b43SDavid Greenman 
271452cd27cbSRobert Watson int
271552cd27cbSRobert Watson in_pcbinshash(struct inpcb *inp)
271652cd27cbSRobert Watson {
271752cd27cbSRobert Watson 
2718fe1274eeSMichael Tuexen 	return (in_pcbinshash_internal(inp, NULL));
271952cd27cbSRobert Watson }
272052cd27cbSRobert Watson 
272152cd27cbSRobert Watson int
2722fe1274eeSMichael Tuexen in_pcbinshash_mbuf(struct inpcb *inp, struct mbuf *m)
272352cd27cbSRobert Watson {
272452cd27cbSRobert Watson 
2725fe1274eeSMichael Tuexen 	return (in_pcbinshash_internal(inp, m));
272652cd27cbSRobert Watson }
272752cd27cbSRobert Watson 
272852cd27cbSRobert Watson /*
2729c3229e05SDavid Greenman  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2730c3229e05SDavid Greenman  * changed. NOTE: This does not handle the case of the lport changing (the
2731c3229e05SDavid Greenman  * hashed port list would have to be updated as well), so the lport must
2732c3229e05SDavid Greenman  * not change after in_pcbinshash() has been called.
2733c3229e05SDavid Greenman  */
273415bd2b43SDavid Greenman void
2735d3c1f003SRobert Watson in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
273615bd2b43SDavid Greenman {
273759daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
273815bd2b43SDavid Greenman 	struct inpcbhead *head;
2739cfa1ca9dSYoshinobu Inoue 	u_int32_t hashkey_faddr;
274015bd2b43SDavid Greenman 
27418501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2742fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2743fa046d87SRobert Watson 
2744111d57a6SRobert Watson 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2745111d57a6SRobert Watson 	    ("in_pcbrehash: !INP_INHASHLIST"));
2746602cc7f1SRobert Watson 
2747cfa1ca9dSYoshinobu Inoue #ifdef INET6
2748cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
27491b44e5ffSAndrey V. Elsukov 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2750cfa1ca9dSYoshinobu Inoue 	else
275183e521ecSBjoern A. Zeeb #endif
2752cfa1ca9dSYoshinobu Inoue 	hashkey_faddr = inp->inp_faddr.s_addr;
2753cfa1ca9dSYoshinobu Inoue 
2754712fc218SRobert Watson 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2755712fc218SRobert Watson 		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
275615bd2b43SDavid Greenman 
2757b872626dSMatt Macy 	CK_LIST_REMOVE(inp, inp_hash);
2758b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(head, inp, inp_hash);
275952cd27cbSRobert Watson 
276052cd27cbSRobert Watson #ifdef PCBGROUP
276152cd27cbSRobert Watson 	if (m != NULL)
276252cd27cbSRobert Watson 		in_pcbgroup_update_mbuf(inp, m);
276352cd27cbSRobert Watson 	else
276452cd27cbSRobert Watson 		in_pcbgroup_update(inp);
276552cd27cbSRobert Watson #endif
2766c3229e05SDavid Greenman }
2767c3229e05SDavid Greenman 
2768d3c1f003SRobert Watson void
2769d3c1f003SRobert Watson in_pcbrehash(struct inpcb *inp)
2770d3c1f003SRobert Watson {
2771d3c1f003SRobert Watson 
2772d3c1f003SRobert Watson 	in_pcbrehash_mbuf(inp, NULL);
2773d3c1f003SRobert Watson }
2774d3c1f003SRobert Watson 
2775c3229e05SDavid Greenman /*
2776c3229e05SDavid Greenman  * Remove PCB from various lists.
2777c3229e05SDavid Greenman  */
27786d888973SRobert Watson static void
2779136d4f1cSRobert Watson in_pcbremlists(struct inpcb *inp)
2780c3229e05SDavid Greenman {
278159daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
278259daba27SSam Leffler 
27838501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2784ff9b006dSJulien Charbon 	INP_LIST_WLOCK_ASSERT(pcbinfo);
278559daba27SSam Leffler 
278659daba27SSam Leffler 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2787111d57a6SRobert Watson 	if (inp->inp_flags & INP_INHASHLIST) {
2788c3229e05SDavid Greenman 		struct inpcbport *phd = inp->inp_phd;
2789c3229e05SDavid Greenman 
2790fa046d87SRobert Watson 		INP_HASH_WLOCK(pcbinfo);
27911a43cff9SSean Bruno 
27921a43cff9SSean Bruno 		/* XXX: Only do if SO_REUSEPORT_LB set? */
27931a43cff9SSean Bruno 		in_pcbremlbgrouphash(inp);
27941a43cff9SSean Bruno 
2795b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_hash);
2796b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_portlist);
2797b872626dSMatt Macy 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2798b872626dSMatt Macy 			CK_LIST_REMOVE(phd, phd_hash);
27992a4bd982SGleb Smirnoff 			NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
2800c3229e05SDavid Greenman 		}
2801fa046d87SRobert Watson 		INP_HASH_WUNLOCK(pcbinfo);
2802111d57a6SRobert Watson 		inp->inp_flags &= ~INP_INHASHLIST;
2803c3229e05SDavid Greenman 	}
2804b872626dSMatt Macy 	CK_LIST_REMOVE(inp, inp_list);
280559daba27SSam Leffler 	pcbinfo->ipi_count--;
280652cd27cbSRobert Watson #ifdef PCBGROUP
280752cd27cbSRobert Watson 	in_pcbgroup_remove(inp);
280852cd27cbSRobert Watson #endif
280915bd2b43SDavid Greenman }
281075c13541SPoul-Henning Kamp 
2811a557af22SRobert Watson /*
281284cc0778SGeorge V. Neville-Neil  * Check for alternatives when higher level complains
281384cc0778SGeorge V. Neville-Neil  * about service problems.  For now, invalidate cached
281484cc0778SGeorge V. Neville-Neil  * routing information.  If the route was created dynamically
281584cc0778SGeorge V. Neville-Neil  * (by a redirect), time to try a default gateway again.
281684cc0778SGeorge V. Neville-Neil  */
281784cc0778SGeorge V. Neville-Neil void
281884cc0778SGeorge V. Neville-Neil in_losing(struct inpcb *inp)
281984cc0778SGeorge V. Neville-Neil {
282084cc0778SGeorge V. Neville-Neil 
2821fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
282284cc0778SGeorge V. Neville-Neil 	return;
282384cc0778SGeorge V. Neville-Neil }
282484cc0778SGeorge V. Neville-Neil 
282584cc0778SGeorge V. Neville-Neil /*
2826a557af22SRobert Watson  * A set label operation has occurred at the socket layer, propagate the
2827a557af22SRobert Watson  * label change into the in_pcb for the socket.
2828a557af22SRobert Watson  */
2829a557af22SRobert Watson void
2830136d4f1cSRobert Watson in_pcbsosetlabel(struct socket *so)
2831a557af22SRobert Watson {
2832a557af22SRobert Watson #ifdef MAC
2833a557af22SRobert Watson 	struct inpcb *inp;
2834a557af22SRobert Watson 
28354c7c478dSRobert Watson 	inp = sotoinpcb(so);
28364c7c478dSRobert Watson 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2837602cc7f1SRobert Watson 
28388501a69cSRobert Watson 	INP_WLOCK(inp);
2839310e7cebSRobert Watson 	SOCK_LOCK(so);
2840a557af22SRobert Watson 	mac_inpcb_sosetlabel(so, inp);
2841310e7cebSRobert Watson 	SOCK_UNLOCK(so);
28428501a69cSRobert Watson 	INP_WUNLOCK(inp);
2843a557af22SRobert Watson #endif
2844a557af22SRobert Watson }
28455f311da2SMike Silbersack 
28465f311da2SMike Silbersack /*
2847ad3a630fSRobert Watson  * ipport_tick runs once per second, determining if random port allocation
2848ad3a630fSRobert Watson  * should be continued.  If more than ipport_randomcps ports have been
2849ad3a630fSRobert Watson  * allocated in the last second, then we return to sequential port
2850ad3a630fSRobert Watson  * allocation. We return to random allocation only once we drop below
2851ad3a630fSRobert Watson  * ipport_randomcps for at least ipport_randomtime seconds.
28525f311da2SMike Silbersack  */
2853aae49dd3SBjoern A. Zeeb static void
2854136d4f1cSRobert Watson ipport_tick(void *xtp)
28555f311da2SMike Silbersack {
28568b615593SMarko Zec 	VNET_ITERATOR_DECL(vnet_iter);
2857ad3a630fSRobert Watson 
28585ee847d3SRobert Watson 	VNET_LIST_RLOCK_NOSLEEP();
28598b615593SMarko Zec 	VNET_FOREACH(vnet_iter) {
28608b615593SMarko Zec 		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
28618b615593SMarko Zec 		if (V_ipport_tcpallocs <=
28628b615593SMarko Zec 		    V_ipport_tcplastcount + V_ipport_randomcps) {
2863603724d3SBjoern A. Zeeb 			if (V_ipport_stoprandom > 0)
2864603724d3SBjoern A. Zeeb 				V_ipport_stoprandom--;
2865ad3a630fSRobert Watson 		} else
2866603724d3SBjoern A. Zeeb 			V_ipport_stoprandom = V_ipport_randomtime;
2867603724d3SBjoern A. Zeeb 		V_ipport_tcplastcount = V_ipport_tcpallocs;
28688b615593SMarko Zec 		CURVNET_RESTORE();
28698b615593SMarko Zec 	}
28705ee847d3SRobert Watson 	VNET_LIST_RUNLOCK_NOSLEEP();
28715f311da2SMike Silbersack 	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
28725f311da2SMike Silbersack }
2873497057eeSRobert Watson 
2874aae49dd3SBjoern A. Zeeb static void
2875aae49dd3SBjoern A. Zeeb ip_fini(void *xtp)
2876aae49dd3SBjoern A. Zeeb {
2877aae49dd3SBjoern A. Zeeb 
2878aae49dd3SBjoern A. Zeeb 	callout_stop(&ipport_tick_callout);
2879aae49dd3SBjoern A. Zeeb }
2880aae49dd3SBjoern A. Zeeb 
2881aae49dd3SBjoern A. Zeeb /*
2882aae49dd3SBjoern A. Zeeb  * The ipport_callout should start running at about the time we attach the
2883aae49dd3SBjoern A. Zeeb  * inet or inet6 domains.
2884aae49dd3SBjoern A. Zeeb  */
2885aae49dd3SBjoern A. Zeeb static void
2886aae49dd3SBjoern A. Zeeb ipport_tick_init(const void *unused __unused)
2887aae49dd3SBjoern A. Zeeb {
2888aae49dd3SBjoern A. Zeeb 
2889aae49dd3SBjoern A. Zeeb 	/* Start ipport_tick. */
2890fd90e2edSJung-uk Kim 	callout_init(&ipport_tick_callout, 1);
2891aae49dd3SBjoern A. Zeeb 	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2892aae49dd3SBjoern A. Zeeb 	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2893aae49dd3SBjoern A. Zeeb 		SHUTDOWN_PRI_DEFAULT);
2894aae49dd3SBjoern A. Zeeb }
2895aae49dd3SBjoern A. Zeeb SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2896aae49dd3SBjoern A. Zeeb     ipport_tick_init, NULL);
2897aae49dd3SBjoern A. Zeeb 
28983d585327SKip Macy void
28993d585327SKip Macy inp_wlock(struct inpcb *inp)
29003d585327SKip Macy {
29013d585327SKip Macy 
29028501a69cSRobert Watson 	INP_WLOCK(inp);
29033d585327SKip Macy }
29043d585327SKip Macy 
29053d585327SKip Macy void
29063d585327SKip Macy inp_wunlock(struct inpcb *inp)
29073d585327SKip Macy {
29083d585327SKip Macy 
29098501a69cSRobert Watson 	INP_WUNLOCK(inp);
29103d585327SKip Macy }
29113d585327SKip Macy 
29123d585327SKip Macy void
29133d585327SKip Macy inp_rlock(struct inpcb *inp)
29143d585327SKip Macy {
29153d585327SKip Macy 
2916a69042a5SRobert Watson 	INP_RLOCK(inp);
29173d585327SKip Macy }
29183d585327SKip Macy 
29193d585327SKip Macy void
29203d585327SKip Macy inp_runlock(struct inpcb *inp)
29213d585327SKip Macy {
29223d585327SKip Macy 
2923a69042a5SRobert Watson 	INP_RUNLOCK(inp);
29243d585327SKip Macy }
29253d585327SKip Macy 
2926c75e2666SGleb Smirnoff #ifdef INVARIANT_SUPPORT
29273d585327SKip Macy void
2928e79dd20dSKip Macy inp_lock_assert(struct inpcb *inp)
29293d585327SKip Macy {
29303d585327SKip Macy 
29318501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
29323d585327SKip Macy }
29333d585327SKip Macy 
29343d585327SKip Macy void
2935e79dd20dSKip Macy inp_unlock_assert(struct inpcb *inp)
29363d585327SKip Macy {
29373d585327SKip Macy 
29383d585327SKip Macy 	INP_UNLOCK_ASSERT(inp);
29393d585327SKip Macy }
29403d585327SKip Macy #endif
29413d585327SKip Macy 
29429378e437SKip Macy void
29439378e437SKip Macy inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
29449378e437SKip Macy {
29459378e437SKip Macy 	struct inpcb *inp;
29469378e437SKip Macy 
2947ff9b006dSJulien Charbon 	INP_INFO_WLOCK(&V_tcbinfo);
2948b872626dSMatt Macy 	CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
29499378e437SKip Macy 		INP_WLOCK(inp);
29509378e437SKip Macy 		func(inp, arg);
29519378e437SKip Macy 		INP_WUNLOCK(inp);
29529378e437SKip Macy 	}
2953ff9b006dSJulien Charbon 	INP_INFO_WUNLOCK(&V_tcbinfo);
29549378e437SKip Macy }
29559378e437SKip Macy 
29569378e437SKip Macy struct socket *
29579378e437SKip Macy inp_inpcbtosocket(struct inpcb *inp)
29589378e437SKip Macy {
29599378e437SKip Macy 
29609378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
29619378e437SKip Macy 	return (inp->inp_socket);
29629378e437SKip Macy }
29639378e437SKip Macy 
29649378e437SKip Macy struct tcpcb *
29659378e437SKip Macy inp_inpcbtotcpcb(struct inpcb *inp)
29669378e437SKip Macy {
29679378e437SKip Macy 
29689378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
29699378e437SKip Macy 	return ((struct tcpcb *)inp->inp_ppcb);
29709378e437SKip Macy }
29719378e437SKip Macy 
29729378e437SKip Macy int
29739378e437SKip Macy inp_ip_tos_get(const struct inpcb *inp)
29749378e437SKip Macy {
29759378e437SKip Macy 
29769378e437SKip Macy 	return (inp->inp_ip_tos);
29779378e437SKip Macy }
29789378e437SKip Macy 
29799378e437SKip Macy void
29809378e437SKip Macy inp_ip_tos_set(struct inpcb *inp, int val)
29819378e437SKip Macy {
29829378e437SKip Macy 
29839378e437SKip Macy 	inp->inp_ip_tos = val;
29849378e437SKip Macy }
29859378e437SKip Macy 
29869378e437SKip Macy void
2987df9cf830STai-hwa Liang inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
29889d29c635SKip Macy     uint32_t *faddr, uint16_t *fp)
29899378e437SKip Macy {
29909378e437SKip Macy 
29919d29c635SKip Macy 	INP_LOCK_ASSERT(inp);
2992df9cf830STai-hwa Liang 	*laddr = inp->inp_laddr.s_addr;
2993df9cf830STai-hwa Liang 	*faddr = inp->inp_faddr.s_addr;
29949378e437SKip Macy 	*lp = inp->inp_lport;
29959378e437SKip Macy 	*fp = inp->inp_fport;
29969378e437SKip Macy }
29979378e437SKip Macy 
2998dd0e6c38SKip Macy struct inpcb *
2999dd0e6c38SKip Macy so_sotoinpcb(struct socket *so)
3000dd0e6c38SKip Macy {
3001dd0e6c38SKip Macy 
3002dd0e6c38SKip Macy 	return (sotoinpcb(so));
3003dd0e6c38SKip Macy }
3004dd0e6c38SKip Macy 
3005dd0e6c38SKip Macy struct tcpcb *
3006dd0e6c38SKip Macy so_sototcpcb(struct socket *so)
3007dd0e6c38SKip Macy {
3008dd0e6c38SKip Macy 
3009dd0e6c38SKip Macy 	return (sototcpcb(so));
3010dd0e6c38SKip Macy }
3011dd0e6c38SKip Macy 
3012cc65eb4eSGleb Smirnoff /*
3013cc65eb4eSGleb Smirnoff  * Create an external-format (``xinpcb'') structure using the information in
3014cc65eb4eSGleb Smirnoff  * the kernel-format in_pcb structure pointed to by inp.  This is done to
3015cc65eb4eSGleb Smirnoff  * reduce the spew of irrelevant information over this interface, to isolate
3016cc65eb4eSGleb Smirnoff  * user code from changes in the kernel structure, and potentially to provide
3017cc65eb4eSGleb Smirnoff  * information-hiding if we decide that some of this information should be
3018cc65eb4eSGleb Smirnoff  * hidden from users.
3019cc65eb4eSGleb Smirnoff  */
3020cc65eb4eSGleb Smirnoff void
3021cc65eb4eSGleb Smirnoff in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
3022cc65eb4eSGleb Smirnoff {
3023cc65eb4eSGleb Smirnoff 
302479db6fe7SMark Johnston 	bzero(xi, sizeof(*xi));
3025cc65eb4eSGleb Smirnoff 	xi->xi_len = sizeof(struct xinpcb);
3026cc65eb4eSGleb Smirnoff 	if (inp->inp_socket)
3027cc65eb4eSGleb Smirnoff 		sotoxsocket(inp->inp_socket, &xi->xi_socket);
3028cc65eb4eSGleb Smirnoff 	bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
3029cc65eb4eSGleb Smirnoff 	xi->inp_gencnt = inp->inp_gencnt;
30303a20f06aSBrooks Davis 	xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
3031cc65eb4eSGleb Smirnoff 	xi->inp_flow = inp->inp_flow;
3032cc65eb4eSGleb Smirnoff 	xi->inp_flowid = inp->inp_flowid;
3033cc65eb4eSGleb Smirnoff 	xi->inp_flowtype = inp->inp_flowtype;
3034cc65eb4eSGleb Smirnoff 	xi->inp_flags = inp->inp_flags;
3035cc65eb4eSGleb Smirnoff 	xi->inp_flags2 = inp->inp_flags2;
3036cc65eb4eSGleb Smirnoff 	xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
3037cc65eb4eSGleb Smirnoff 	xi->in6p_cksum = inp->in6p_cksum;
3038cc65eb4eSGleb Smirnoff 	xi->in6p_hops = inp->in6p_hops;
3039cc65eb4eSGleb Smirnoff 	xi->inp_ip_tos = inp->inp_ip_tos;
3040cc65eb4eSGleb Smirnoff 	xi->inp_vflag = inp->inp_vflag;
3041cc65eb4eSGleb Smirnoff 	xi->inp_ip_ttl = inp->inp_ip_ttl;
3042cc65eb4eSGleb Smirnoff 	xi->inp_ip_p = inp->inp_ip_p;
3043cc65eb4eSGleb Smirnoff 	xi->inp_ip_minttl = inp->inp_ip_minttl;
3044cc65eb4eSGleb Smirnoff }
3045cc65eb4eSGleb Smirnoff 
3046497057eeSRobert Watson #ifdef DDB
3047497057eeSRobert Watson static void
3048497057eeSRobert Watson db_print_indent(int indent)
3049497057eeSRobert Watson {
3050497057eeSRobert Watson 	int i;
3051497057eeSRobert Watson 
3052497057eeSRobert Watson 	for (i = 0; i < indent; i++)
3053497057eeSRobert Watson 		db_printf(" ");
3054497057eeSRobert Watson }
3055497057eeSRobert Watson 
3056497057eeSRobert Watson static void
3057497057eeSRobert Watson db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3058497057eeSRobert Watson {
3059497057eeSRobert Watson 	char faddr_str[48], laddr_str[48];
3060497057eeSRobert Watson 
3061497057eeSRobert Watson 	db_print_indent(indent);
3062497057eeSRobert Watson 	db_printf("%s at %p\n", name, inc);
3063497057eeSRobert Watson 
3064497057eeSRobert Watson 	indent += 2;
3065497057eeSRobert Watson 
306603dc38a4SRobert Watson #ifdef INET6
3067dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
3068497057eeSRobert Watson 		/* IPv6. */
3069497057eeSRobert Watson 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
3070497057eeSRobert Watson 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
307183e521ecSBjoern A. Zeeb 	} else
307203dc38a4SRobert Watson #endif
307383e521ecSBjoern A. Zeeb 	{
3074497057eeSRobert Watson 		/* IPv4. */
3075497057eeSRobert Watson 		inet_ntoa_r(inc->inc_laddr, laddr_str);
3076497057eeSRobert Watson 		inet_ntoa_r(inc->inc_faddr, faddr_str);
3077497057eeSRobert Watson 	}
3078497057eeSRobert Watson 	db_print_indent(indent);
3079497057eeSRobert Watson 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
3080497057eeSRobert Watson 	    ntohs(inc->inc_lport));
3081497057eeSRobert Watson 	db_print_indent(indent);
3082497057eeSRobert Watson 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
3083497057eeSRobert Watson 	    ntohs(inc->inc_fport));
3084497057eeSRobert Watson }
3085497057eeSRobert Watson 
3086497057eeSRobert Watson static void
3087497057eeSRobert Watson db_print_inpflags(int inp_flags)
3088497057eeSRobert Watson {
3089497057eeSRobert Watson 	int comma;
3090497057eeSRobert Watson 
3091497057eeSRobert Watson 	comma = 0;
3092497057eeSRobert Watson 	if (inp_flags & INP_RECVOPTS) {
3093497057eeSRobert Watson 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3094497057eeSRobert Watson 		comma = 1;
3095497057eeSRobert Watson 	}
3096497057eeSRobert Watson 	if (inp_flags & INP_RECVRETOPTS) {
3097497057eeSRobert Watson 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3098497057eeSRobert Watson 		comma = 1;
3099497057eeSRobert Watson 	}
3100497057eeSRobert Watson 	if (inp_flags & INP_RECVDSTADDR) {
3101497057eeSRobert Watson 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3102497057eeSRobert Watson 		comma = 1;
3103497057eeSRobert Watson 	}
3104dce33a45SErmal Luçi 	if (inp_flags & INP_ORIGDSTADDR) {
3105dce33a45SErmal Luçi 		db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3106dce33a45SErmal Luçi 		comma = 1;
3107dce33a45SErmal Luçi 	}
3108497057eeSRobert Watson 	if (inp_flags & INP_HDRINCL) {
3109497057eeSRobert Watson 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
3110497057eeSRobert Watson 		comma = 1;
3111497057eeSRobert Watson 	}
3112497057eeSRobert Watson 	if (inp_flags & INP_HIGHPORT) {
3113497057eeSRobert Watson 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3114497057eeSRobert Watson 		comma = 1;
3115497057eeSRobert Watson 	}
3116497057eeSRobert Watson 	if (inp_flags & INP_LOWPORT) {
3117497057eeSRobert Watson 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
3118497057eeSRobert Watson 		comma = 1;
3119497057eeSRobert Watson 	}
3120497057eeSRobert Watson 	if (inp_flags & INP_ANONPORT) {
3121497057eeSRobert Watson 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
3122497057eeSRobert Watson 		comma = 1;
3123497057eeSRobert Watson 	}
3124497057eeSRobert Watson 	if (inp_flags & INP_RECVIF) {
3125497057eeSRobert Watson 		db_printf("%sINP_RECVIF", comma ? ", " : "");
3126497057eeSRobert Watson 		comma = 1;
3127497057eeSRobert Watson 	}
3128497057eeSRobert Watson 	if (inp_flags & INP_MTUDISC) {
3129497057eeSRobert Watson 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
3130497057eeSRobert Watson 		comma = 1;
3131497057eeSRobert Watson 	}
3132497057eeSRobert Watson 	if (inp_flags & INP_RECVTTL) {
3133497057eeSRobert Watson 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
3134497057eeSRobert Watson 		comma = 1;
3135497057eeSRobert Watson 	}
3136497057eeSRobert Watson 	if (inp_flags & INP_DONTFRAG) {
3137497057eeSRobert Watson 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3138497057eeSRobert Watson 		comma = 1;
3139497057eeSRobert Watson 	}
31403cca425bSMichael Tuexen 	if (inp_flags & INP_RECVTOS) {
31413cca425bSMichael Tuexen 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
31423cca425bSMichael Tuexen 		comma = 1;
31433cca425bSMichael Tuexen 	}
3144497057eeSRobert Watson 	if (inp_flags & IN6P_IPV6_V6ONLY) {
3145497057eeSRobert Watson 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3146497057eeSRobert Watson 		comma = 1;
3147497057eeSRobert Watson 	}
3148497057eeSRobert Watson 	if (inp_flags & IN6P_PKTINFO) {
3149497057eeSRobert Watson 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3150497057eeSRobert Watson 		comma = 1;
3151497057eeSRobert Watson 	}
3152497057eeSRobert Watson 	if (inp_flags & IN6P_HOPLIMIT) {
3153497057eeSRobert Watson 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3154497057eeSRobert Watson 		comma = 1;
3155497057eeSRobert Watson 	}
3156497057eeSRobert Watson 	if (inp_flags & IN6P_HOPOPTS) {
3157497057eeSRobert Watson 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3158497057eeSRobert Watson 		comma = 1;
3159497057eeSRobert Watson 	}
3160497057eeSRobert Watson 	if (inp_flags & IN6P_DSTOPTS) {
3161497057eeSRobert Watson 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3162497057eeSRobert Watson 		comma = 1;
3163497057eeSRobert Watson 	}
3164497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDR) {
3165497057eeSRobert Watson 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3166497057eeSRobert Watson 		comma = 1;
3167497057eeSRobert Watson 	}
3168497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
3169497057eeSRobert Watson 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3170497057eeSRobert Watson 		comma = 1;
3171497057eeSRobert Watson 	}
3172497057eeSRobert Watson 	if (inp_flags & IN6P_TCLASS) {
3173497057eeSRobert Watson 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3174497057eeSRobert Watson 		comma = 1;
3175497057eeSRobert Watson 	}
3176497057eeSRobert Watson 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
3177497057eeSRobert Watson 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3178497057eeSRobert Watson 		comma = 1;
3179497057eeSRobert Watson 	}
3180ad71fe3cSRobert Watson 	if (inp_flags & INP_TIMEWAIT) {
3181ad71fe3cSRobert Watson 		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3182ad71fe3cSRobert Watson 		comma  = 1;
3183ad71fe3cSRobert Watson 	}
3184ad71fe3cSRobert Watson 	if (inp_flags & INP_ONESBCAST) {
3185ad71fe3cSRobert Watson 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3186ad71fe3cSRobert Watson 		comma  = 1;
3187ad71fe3cSRobert Watson 	}
3188ad71fe3cSRobert Watson 	if (inp_flags & INP_DROPPED) {
3189ad71fe3cSRobert Watson 		db_printf("%sINP_DROPPED", comma ? ", " : "");
3190ad71fe3cSRobert Watson 		comma  = 1;
3191ad71fe3cSRobert Watson 	}
3192ad71fe3cSRobert Watson 	if (inp_flags & INP_SOCKREF) {
3193ad71fe3cSRobert Watson 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
3194ad71fe3cSRobert Watson 		comma  = 1;
3195ad71fe3cSRobert Watson 	}
3196497057eeSRobert Watson 	if (inp_flags & IN6P_RFC2292) {
3197497057eeSRobert Watson 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3198497057eeSRobert Watson 		comma = 1;
3199497057eeSRobert Watson 	}
3200497057eeSRobert Watson 	if (inp_flags & IN6P_MTU) {
3201497057eeSRobert Watson 		db_printf("IN6P_MTU%s", comma ? ", " : "");
3202497057eeSRobert Watson 		comma = 1;
3203497057eeSRobert Watson 	}
3204497057eeSRobert Watson }
3205497057eeSRobert Watson 
3206497057eeSRobert Watson static void
3207497057eeSRobert Watson db_print_inpvflag(u_char inp_vflag)
3208497057eeSRobert Watson {
3209497057eeSRobert Watson 	int comma;
3210497057eeSRobert Watson 
3211497057eeSRobert Watson 	comma = 0;
3212497057eeSRobert Watson 	if (inp_vflag & INP_IPV4) {
3213497057eeSRobert Watson 		db_printf("%sINP_IPV4", comma ? ", " : "");
3214497057eeSRobert Watson 		comma  = 1;
3215497057eeSRobert Watson 	}
3216497057eeSRobert Watson 	if (inp_vflag & INP_IPV6) {
3217497057eeSRobert Watson 		db_printf("%sINP_IPV6", comma ? ", " : "");
3218497057eeSRobert Watson 		comma  = 1;
3219497057eeSRobert Watson 	}
3220497057eeSRobert Watson 	if (inp_vflag & INP_IPV6PROTO) {
3221497057eeSRobert Watson 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3222497057eeSRobert Watson 		comma  = 1;
3223497057eeSRobert Watson 	}
3224497057eeSRobert Watson }
3225497057eeSRobert Watson 
32266d888973SRobert Watson static void
3227497057eeSRobert Watson db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3228497057eeSRobert Watson {
3229497057eeSRobert Watson 
3230497057eeSRobert Watson 	db_print_indent(indent);
3231497057eeSRobert Watson 	db_printf("%s at %p\n", name, inp);
3232497057eeSRobert Watson 
3233497057eeSRobert Watson 	indent += 2;
3234497057eeSRobert Watson 
3235497057eeSRobert Watson 	db_print_indent(indent);
3236497057eeSRobert Watson 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3237497057eeSRobert Watson 
3238497057eeSRobert Watson 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3239497057eeSRobert Watson 
3240497057eeSRobert Watson 	db_print_indent(indent);
3241497057eeSRobert Watson 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
3242497057eeSRobert Watson 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3243497057eeSRobert Watson 
3244497057eeSRobert Watson 	db_print_indent(indent);
3245497057eeSRobert Watson 	db_printf("inp_label: %p   inp_flags: 0x%x (",
3246497057eeSRobert Watson 	   inp->inp_label, inp->inp_flags);
3247497057eeSRobert Watson 	db_print_inpflags(inp->inp_flags);
3248497057eeSRobert Watson 	db_printf(")\n");
3249497057eeSRobert Watson 
3250497057eeSRobert Watson 	db_print_indent(indent);
3251497057eeSRobert Watson 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3252497057eeSRobert Watson 	    inp->inp_vflag);
3253497057eeSRobert Watson 	db_print_inpvflag(inp->inp_vflag);
3254497057eeSRobert Watson 	db_printf(")\n");
3255497057eeSRobert Watson 
3256497057eeSRobert Watson 	db_print_indent(indent);
3257497057eeSRobert Watson 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3258497057eeSRobert Watson 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3259497057eeSRobert Watson 
3260497057eeSRobert Watson 	db_print_indent(indent);
3261497057eeSRobert Watson #ifdef INET6
3262497057eeSRobert Watson 	if (inp->inp_vflag & INP_IPV6) {
3263497057eeSRobert Watson 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
3264497057eeSRobert Watson 		    "in6p_moptions: %p\n", inp->in6p_options,
3265497057eeSRobert Watson 		    inp->in6p_outputopts, inp->in6p_moptions);
3266497057eeSRobert Watson 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3267497057eeSRobert Watson 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3268497057eeSRobert Watson 		    inp->in6p_hops);
3269497057eeSRobert Watson 	} else
3270497057eeSRobert Watson #endif
3271497057eeSRobert Watson 	{
3272497057eeSRobert Watson 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3273497057eeSRobert Watson 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3274497057eeSRobert Watson 		    inp->inp_options, inp->inp_moptions);
3275497057eeSRobert Watson 	}
3276497057eeSRobert Watson 
3277497057eeSRobert Watson 	db_print_indent(indent);
3278497057eeSRobert Watson 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
3279497057eeSRobert Watson 	    (uintmax_t)inp->inp_gencnt);
3280497057eeSRobert Watson }
3281497057eeSRobert Watson 
3282497057eeSRobert Watson DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3283497057eeSRobert Watson {
3284497057eeSRobert Watson 	struct inpcb *inp;
3285497057eeSRobert Watson 
3286497057eeSRobert Watson 	if (!have_addr) {
3287497057eeSRobert Watson 		db_printf("usage: show inpcb <addr>\n");
3288497057eeSRobert Watson 		return;
3289497057eeSRobert Watson 	}
3290497057eeSRobert Watson 	inp = (struct inpcb *)addr;
3291497057eeSRobert Watson 
3292497057eeSRobert Watson 	db_print_inpcb(inp, "inpcb", 0);
3293497057eeSRobert Watson }
329483e521ecSBjoern A. Zeeb #endif /* DDB */
3295f3e7afe2SHans Petter Selasky 
3296f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
3297f3e7afe2SHans Petter Selasky /*
3298f3e7afe2SHans Petter Selasky  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3299f3e7afe2SHans Petter Selasky  * if any.
3300f3e7afe2SHans Petter Selasky  */
3301f3e7afe2SHans Petter Selasky int
3302f3e7afe2SHans Petter Selasky in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3303f3e7afe2SHans Petter Selasky {
3304f3e7afe2SHans Petter Selasky 	union if_snd_tag_modify_params params = {
3305f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
330620abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3307f3e7afe2SHans Petter Selasky 	};
3308f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3309f3e7afe2SHans Petter Selasky 	struct ifnet *ifp;
3310f3e7afe2SHans Petter Selasky 	int error;
3311f3e7afe2SHans Petter Selasky 
3312f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3313f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3314f3e7afe2SHans Petter Selasky 		return (EINVAL);
3315f3e7afe2SHans Petter Selasky 
3316f3e7afe2SHans Petter Selasky 	ifp = mst->ifp;
3317f3e7afe2SHans Petter Selasky 	if (ifp == NULL)
3318f3e7afe2SHans Petter Selasky 		return (EINVAL);
3319f3e7afe2SHans Petter Selasky 
3320f3e7afe2SHans Petter Selasky 	if (ifp->if_snd_tag_modify == NULL) {
3321f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3322f3e7afe2SHans Petter Selasky 	} else {
3323f3e7afe2SHans Petter Selasky 		error = ifp->if_snd_tag_modify(mst, &params);
3324f3e7afe2SHans Petter Selasky 	}
3325f3e7afe2SHans Petter Selasky 	return (error);
3326f3e7afe2SHans Petter Selasky }
3327f3e7afe2SHans Petter Selasky 
3328f3e7afe2SHans Petter Selasky /*
3329f3e7afe2SHans Petter Selasky  * Query existing TX rate limit based on the existing
3330f3e7afe2SHans Petter Selasky  * "inp->inp_snd_tag", if any.
3331f3e7afe2SHans Petter Selasky  */
3332f3e7afe2SHans Petter Selasky int
3333f3e7afe2SHans Petter Selasky in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3334f3e7afe2SHans Petter Selasky {
3335f3e7afe2SHans Petter Selasky 	union if_snd_tag_query_params params = { };
3336f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3337f3e7afe2SHans Petter Selasky 	struct ifnet *ifp;
3338f3e7afe2SHans Petter Selasky 	int error;
3339f3e7afe2SHans Petter Selasky 
3340f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3341f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3342f3e7afe2SHans Petter Selasky 		return (EINVAL);
3343f3e7afe2SHans Petter Selasky 
3344f3e7afe2SHans Petter Selasky 	ifp = mst->ifp;
3345f3e7afe2SHans Petter Selasky 	if (ifp == NULL)
3346f3e7afe2SHans Petter Selasky 		return (EINVAL);
3347f3e7afe2SHans Petter Selasky 
3348f3e7afe2SHans Petter Selasky 	if (ifp->if_snd_tag_query == NULL) {
3349f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3350f3e7afe2SHans Petter Selasky 	} else {
3351f3e7afe2SHans Petter Selasky 		error = ifp->if_snd_tag_query(mst, &params);
3352f3e7afe2SHans Petter Selasky 		if (error == 0 &&  p_max_pacing_rate != NULL)
3353f3e7afe2SHans Petter Selasky 			*p_max_pacing_rate = params.rate_limit.max_rate;
3354f3e7afe2SHans Petter Selasky 	}
3355f3e7afe2SHans Petter Selasky 	return (error);
3356f3e7afe2SHans Petter Selasky }
3357f3e7afe2SHans Petter Selasky 
3358f3e7afe2SHans Petter Selasky /*
335995ed5015SHans Petter Selasky  * Query existing TX queue level based on the existing
336095ed5015SHans Petter Selasky  * "inp->inp_snd_tag", if any.
336195ed5015SHans Petter Selasky  */
336295ed5015SHans Petter Selasky int
336395ed5015SHans Petter Selasky in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
336495ed5015SHans Petter Selasky {
336595ed5015SHans Petter Selasky 	union if_snd_tag_query_params params = { };
336695ed5015SHans Petter Selasky 	struct m_snd_tag *mst;
336795ed5015SHans Petter Selasky 	struct ifnet *ifp;
336895ed5015SHans Petter Selasky 	int error;
336995ed5015SHans Petter Selasky 
337095ed5015SHans Petter Selasky 	mst = inp->inp_snd_tag;
337195ed5015SHans Petter Selasky 	if (mst == NULL)
337295ed5015SHans Petter Selasky 		return (EINVAL);
337395ed5015SHans Petter Selasky 
337495ed5015SHans Petter Selasky 	ifp = mst->ifp;
337595ed5015SHans Petter Selasky 	if (ifp == NULL)
337695ed5015SHans Petter Selasky 		return (EINVAL);
337795ed5015SHans Petter Selasky 
337895ed5015SHans Petter Selasky 	if (ifp->if_snd_tag_query == NULL)
337995ed5015SHans Petter Selasky 		return (EOPNOTSUPP);
338095ed5015SHans Petter Selasky 
338195ed5015SHans Petter Selasky 	error = ifp->if_snd_tag_query(mst, &params);
338295ed5015SHans Petter Selasky 	if (error == 0 &&  p_txqueue_level != NULL)
338395ed5015SHans Petter Selasky 		*p_txqueue_level = params.rate_limit.queue_level;
338495ed5015SHans Petter Selasky 	return (error);
338595ed5015SHans Petter Selasky }
338695ed5015SHans Petter Selasky 
338795ed5015SHans Petter Selasky /*
3388f3e7afe2SHans Petter Selasky  * Allocate a new TX rate limit send tag from the network interface
3389f3e7afe2SHans Petter Selasky  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3390f3e7afe2SHans Petter Selasky  */
3391f3e7afe2SHans Petter Selasky int
3392f3e7afe2SHans Petter Selasky in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
339320abea66SRandall Stewart     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
339420abea66SRandall Stewart 
3395f3e7afe2SHans Petter Selasky {
3396f3e7afe2SHans Petter Selasky 	union if_snd_tag_alloc_params params = {
339795ed5015SHans Petter Selasky 		.rate_limit.hdr.type = (max_pacing_rate == -1U) ?
339895ed5015SHans Petter Selasky 		    IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3399f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowid = flowid,
3400f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowtype = flowtype,
340198085baeSAndrew Gallatin 		.rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3402f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
340320abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3404f3e7afe2SHans Petter Selasky 	};
3405f3e7afe2SHans Petter Selasky 	int error;
3406f3e7afe2SHans Petter Selasky 
3407f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3408f3e7afe2SHans Petter Selasky 
340985d8d30fSHans Petter Selasky 	/*
341085d8d30fSHans Petter Selasky 	 * If there is already a send tag, or the INP is being torn
341185d8d30fSHans Petter Selasky 	 * down, allocating a new send tag is not allowed. Else send
341285d8d30fSHans Petter Selasky 	 * tags may leak.
341385d8d30fSHans Petter Selasky 	 */
341485d8d30fSHans Petter Selasky 	if (*st != NULL || (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0)
3415f3e7afe2SHans Petter Selasky 		return (EINVAL);
3416f3e7afe2SHans Petter Selasky 
341736e0a362SJohn Baldwin 	error = m_snd_tag_alloc(ifp, &params, st);
3418903c4ee6SXin LI #ifdef INET
341920abea66SRandall Stewart 	if (error == 0) {
342020abea66SRandall Stewart 		counter_u64_add(rate_limit_set_ok, 1);
342120abea66SRandall Stewart 		counter_u64_add(rate_limit_active, 1);
342236e0a362SJohn Baldwin 	} else if (error != EOPNOTSUPP)
342320abea66SRandall Stewart 		  counter_u64_add(rate_limit_alloc_fail, 1);
3424903c4ee6SXin LI #endif
3425f3e7afe2SHans Petter Selasky 	return (error);
3426f3e7afe2SHans Petter Selasky }
3427f3e7afe2SHans Petter Selasky 
342820abea66SRandall Stewart void
342998d7a8d9SJohn Baldwin in_pcbdetach_tag(struct m_snd_tag *mst)
343020abea66SRandall Stewart {
343120abea66SRandall Stewart 
343298d7a8d9SJohn Baldwin 	m_snd_tag_rele(mst);
3433903c4ee6SXin LI #ifdef INET
343420abea66SRandall Stewart 	counter_u64_add(rate_limit_active, -1);
3435903c4ee6SXin LI #endif
343620abea66SRandall Stewart }
343720abea66SRandall Stewart 
3438f3e7afe2SHans Petter Selasky /*
3439f3e7afe2SHans Petter Selasky  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3440f3e7afe2SHans Petter Selasky  * if any:
3441f3e7afe2SHans Petter Selasky  */
3442f3e7afe2SHans Petter Selasky void
3443f3e7afe2SHans Petter Selasky in_pcbdetach_txrtlmt(struct inpcb *inp)
3444f3e7afe2SHans Petter Selasky {
3445f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3446f3e7afe2SHans Petter Selasky 
3447f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3448f3e7afe2SHans Petter Selasky 
3449f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3450f3e7afe2SHans Petter Selasky 	inp->inp_snd_tag = NULL;
3451f3e7afe2SHans Petter Selasky 
3452f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3453f3e7afe2SHans Petter Selasky 		return;
3454f3e7afe2SHans Petter Selasky 
3455fb3bc596SJohn Baldwin 	m_snd_tag_rele(mst);
3456093e7231SHans Petter Selasky #ifdef INET
3457093e7231SHans Petter Selasky 	counter_u64_add(rate_limit_active, -1);
3458093e7231SHans Petter Selasky #endif
3459f3e7afe2SHans Petter Selasky }
3460f3e7afe2SHans Petter Selasky 
346120abea66SRandall Stewart int
346220abea66SRandall Stewart in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
346320abea66SRandall Stewart {
346420abea66SRandall Stewart 	int error;
346520abea66SRandall Stewart 
346620abea66SRandall Stewart 	/*
346720abea66SRandall Stewart 	 * If the existing send tag is for the wrong interface due to
346820abea66SRandall Stewart 	 * a route change, first drop the existing tag.  Set the
346920abea66SRandall Stewart 	 * CHANGED flag so that we will keep trying to allocate a new
347020abea66SRandall Stewart 	 * tag if we fail to allocate one this time.
347120abea66SRandall Stewart 	 */
347220abea66SRandall Stewart 	if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
347320abea66SRandall Stewart 		in_pcbdetach_txrtlmt(inp);
347420abea66SRandall Stewart 		inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
347520abea66SRandall Stewart 	}
347620abea66SRandall Stewart 
347720abea66SRandall Stewart 	/*
347820abea66SRandall Stewart 	 * NOTE: When attaching to a network interface a reference is
347920abea66SRandall Stewart 	 * made to ensure the network interface doesn't go away until
348020abea66SRandall Stewart 	 * all ratelimit connections are gone. The network interface
348120abea66SRandall Stewart 	 * pointers compared below represent valid network interfaces,
348220abea66SRandall Stewart 	 * except when comparing towards NULL.
348320abea66SRandall Stewart 	 */
348420abea66SRandall Stewart 	if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
348520abea66SRandall Stewart 		error = 0;
348620abea66SRandall Stewart 	} else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
348720abea66SRandall Stewart 		if (inp->inp_snd_tag != NULL)
348820abea66SRandall Stewart 			in_pcbdetach_txrtlmt(inp);
348920abea66SRandall Stewart 		error = 0;
349020abea66SRandall Stewart 	} else if (inp->inp_snd_tag == NULL) {
349120abea66SRandall Stewart 		/*
349220abea66SRandall Stewart 		 * In order to utilize packet pacing with RSS, we need
349320abea66SRandall Stewart 		 * to wait until there is a valid RSS hash before we
349420abea66SRandall Stewart 		 * can proceed:
349520abea66SRandall Stewart 		 */
349620abea66SRandall Stewart 		if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
349720abea66SRandall Stewart 			error = EAGAIN;
349820abea66SRandall Stewart 		} else {
349920abea66SRandall Stewart 			error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
350020abea66SRandall Stewart 			    mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
350120abea66SRandall Stewart 		}
350220abea66SRandall Stewart 	} else {
350320abea66SRandall Stewart 		error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
350420abea66SRandall Stewart 	}
350520abea66SRandall Stewart 	if (error == 0 || error == EOPNOTSUPP)
350620abea66SRandall Stewart 		inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
350720abea66SRandall Stewart 
350820abea66SRandall Stewart 	return (error);
350920abea66SRandall Stewart }
351020abea66SRandall Stewart 
3511f3e7afe2SHans Petter Selasky /*
3512f3e7afe2SHans Petter Selasky  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3513f3e7afe2SHans Petter Selasky  * is set in the fast path and will attach/detach/modify the TX rate
3514f3e7afe2SHans Petter Selasky  * limit send tag based on the socket's so_max_pacing_rate value.
3515f3e7afe2SHans Petter Selasky  */
3516f3e7afe2SHans Petter Selasky void
3517f3e7afe2SHans Petter Selasky in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3518f3e7afe2SHans Petter Selasky {
3519f3e7afe2SHans Petter Selasky 	struct socket *socket;
3520f3e7afe2SHans Petter Selasky 	uint32_t max_pacing_rate;
3521f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3522f3e7afe2SHans Petter Selasky 	int error;
3523f3e7afe2SHans Petter Selasky 
3524f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3525f3e7afe2SHans Petter Selasky 		return;
3526f3e7afe2SHans Petter Selasky 
3527f3e7afe2SHans Petter Selasky 	socket = inp->inp_socket;
3528f3e7afe2SHans Petter Selasky 	if (socket == NULL)
3529f3e7afe2SHans Petter Selasky 		return;
3530f3e7afe2SHans Petter Selasky 
3531f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3532f3e7afe2SHans Petter Selasky 		/*
3533f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3534f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3535f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3536f3e7afe2SHans Petter Selasky 		 * write lock.
3537f3e7afe2SHans Petter Selasky 		 */
3538f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3539f3e7afe2SHans Petter Selasky 			return;
3540f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3541f3e7afe2SHans Petter Selasky 	} else {
3542f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3543f3e7afe2SHans Petter Selasky 	}
3544f3e7afe2SHans Petter Selasky 
3545f3e7afe2SHans Petter Selasky 	/*
3546f3e7afe2SHans Petter Selasky 	 * NOTE: The so_max_pacing_rate value is read unlocked,
3547f3e7afe2SHans Petter Selasky 	 * because atomic updates are not required since the variable
3548f3e7afe2SHans Petter Selasky 	 * is checked at every mbuf we send. It is assumed that the
3549f3e7afe2SHans Petter Selasky 	 * variable read itself will be atomic.
3550f3e7afe2SHans Petter Selasky 	 */
3551f3e7afe2SHans Petter Selasky 	max_pacing_rate = socket->so_max_pacing_rate;
3552f3e7afe2SHans Petter Selasky 
355320abea66SRandall Stewart 	error = in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3554fb3bc596SJohn Baldwin 
3555f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3556f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3557f3e7afe2SHans Petter Selasky }
3558f3e7afe2SHans Petter Selasky 
3559f3e7afe2SHans Petter Selasky /*
3560f3e7afe2SHans Petter Selasky  * Track route changes for TX rate limiting.
3561f3e7afe2SHans Petter Selasky  */
3562f3e7afe2SHans Petter Selasky void
3563f3e7afe2SHans Petter Selasky in_pcboutput_eagain(struct inpcb *inp)
3564f3e7afe2SHans Petter Selasky {
3565f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3566f3e7afe2SHans Petter Selasky 
3567f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3568f3e7afe2SHans Petter Selasky 		return;
3569f3e7afe2SHans Petter Selasky 
3570f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag == NULL)
3571f3e7afe2SHans Petter Selasky 		return;
3572f3e7afe2SHans Petter Selasky 
3573f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3574f3e7afe2SHans Petter Selasky 		/*
3575f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3576f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3577f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3578f3e7afe2SHans Petter Selasky 		 * write lock.
3579f3e7afe2SHans Petter Selasky 		 */
3580f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3581f3e7afe2SHans Petter Selasky 			return;
3582f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3583f3e7afe2SHans Petter Selasky 	} else {
3584f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3585f3e7afe2SHans Petter Selasky 	}
3586f3e7afe2SHans Petter Selasky 
3587f3e7afe2SHans Petter Selasky 	/* detach rate limiting */
3588f3e7afe2SHans Petter Selasky 	in_pcbdetach_txrtlmt(inp);
3589f3e7afe2SHans Petter Selasky 
3590f3e7afe2SHans Petter Selasky 	/* make sure new mbuf send tag allocation is made */
3591f3e7afe2SHans Petter Selasky 	inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3592f3e7afe2SHans Petter Selasky 
3593f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3594f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3595f3e7afe2SHans Petter Selasky }
359620abea66SRandall Stewart 
3597903c4ee6SXin LI #ifdef INET
359820abea66SRandall Stewart static void
359920abea66SRandall Stewart rl_init(void *st)
360020abea66SRandall Stewart {
3601*1a714ff2SRandall Stewart 	rate_limit_new = counter_u64_alloc(M_WAITOK);
3602*1a714ff2SRandall Stewart 	rate_limit_chg = counter_u64_alloc(M_WAITOK);
360320abea66SRandall Stewart 	rate_limit_active = counter_u64_alloc(M_WAITOK);
360420abea66SRandall Stewart 	rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
360520abea66SRandall Stewart 	rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
360620abea66SRandall Stewart }
360720abea66SRandall Stewart 
360820abea66SRandall Stewart SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3609903c4ee6SXin LI #endif
3610f3e7afe2SHans Petter Selasky #endif /* RATELIMIT */
3611