xref: /freebsd/sys/netinet/in_pcb.c (revision a0aeb1cef53ba782eb242597e5dcb715861ec270)
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"
480c325f53SAlexander V. Chernikov #include "opt_route.h"
497527624eSRobert Watson #include "opt_rss.h"
50cfa1ca9dSYoshinobu Inoue 
51df8bae1dSRodney W. Grimes #include <sys/param.h>
52a0577692SGleb Smirnoff #include <sys/hash.h>
53df8bae1dSRodney W. Grimes #include <sys/systm.h>
54a0577692SGleb Smirnoff #include <sys/libkern.h>
55cc0a3c8cSAndrey V. Elsukov #include <sys/lock.h>
56df8bae1dSRodney W. Grimes #include <sys/malloc.h>
57df8bae1dSRodney W. Grimes #include <sys/mbuf.h>
58aae49dd3SBjoern A. Zeeb #include <sys/callout.h>
59ea8d1492SAlexander V. Chernikov #include <sys/eventhandler.h>
60cfa1ca9dSYoshinobu Inoue #include <sys/domain.h>
61df8bae1dSRodney W. Grimes #include <sys/protosw.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>
910f617ae4SGleb Smirnoff #include <netinet/in_pcb_var.h>
9259854ecfSHans Petter Selasky #ifdef INET
9359854ecfSHans Petter Selasky #include <netinet/in_var.h>
949ac7c6cfSAlexander V. Chernikov #include <netinet/in_fib.h>
9559854ecfSHans Petter Selasky #endif
96df8bae1dSRodney W. Grimes #include <netinet/ip_var.h>
97340c35deSJonathan Lemon #include <netinet/tcp_var.h>
983ee9c3c4SRandall Stewart #ifdef TCPHPTS
993ee9c3c4SRandall Stewart #include <netinet/tcp_hpts.h>
1003ee9c3c4SRandall Stewart #endif
1015f311da2SMike Silbersack #include <netinet/udp.h>
1025f311da2SMike Silbersack #include <netinet/udp_var.h>
103cfa1ca9dSYoshinobu Inoue #ifdef INET6
104cfa1ca9dSYoshinobu Inoue #include <netinet/ip6.h>
105efc76f72SBjoern A. Zeeb #include <netinet6/in6_pcb.h>
10667107f45SBjoern A. Zeeb #include <netinet6/in6_var.h>
10767107f45SBjoern A. Zeeb #include <netinet6/ip6_var.h>
108cfa1ca9dSYoshinobu Inoue #endif /* INET6 */
1099ac7c6cfSAlexander V. Chernikov #include <net/route/nhop.h>
11059854ecfSHans Petter Selasky #endif
111cfa1ca9dSYoshinobu Inoue 
112fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
113b9234fafSSam Leffler 
114aed55708SRobert Watson #include <security/mac/mac_framework.h>
115aed55708SRobert Watson 
1161a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMIN	8
1171a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMAX	256
118db0ac6deSCy Schubert #define	INP_FREED	0x00000200	/* See in_pcb.h. */
1191a43cff9SSean Bruno 
120aae49dd3SBjoern A. Zeeb static struct callout	ipport_tick_callout;
121aae49dd3SBjoern A. Zeeb 
122101f9fc8SPeter Wemm /*
123101f9fc8SPeter Wemm  * These configure the range of local port addresses assigned to
124101f9fc8SPeter Wemm  * "unspecified" outgoing connections/packets/whatever.
125101f9fc8SPeter Wemm  */
126eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
127eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
128eddfbb76SRobert Watson VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
129eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
130eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
131eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
132101f9fc8SPeter Wemm 
133b0d22693SCrist J. Clark /*
134b0d22693SCrist J. Clark  * Reserved ports accessible only to root. There are significant
135b0d22693SCrist J. Clark  * security considerations that must be accounted for when changing these,
136b0d22693SCrist J. Clark  * but the security benefits can be great. Please be careful.
137b0d22693SCrist J. Clark  */
138eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
139eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedlow);
140b0d22693SCrist J. Clark 
1415f311da2SMike Silbersack /* Variables dealing with random ephemeral port allocation. */
142eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomized) = 1;	/* user controlled via sysctl */
143eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomcps) = 10;	/* user controlled via sysctl */
144eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomtime) = 45;	/* user controlled via sysctl */
145eddfbb76SRobert Watson VNET_DEFINE(int, ipport_stoprandom);		/* toggled by ipport_tick */
146eddfbb76SRobert Watson VNET_DEFINE(int, ipport_tcpallocs);
1475f901c92SAndrew Turner VNET_DEFINE_STATIC(int, ipport_tcplastcount);
148eddfbb76SRobert Watson 
1491e77c105SRobert Watson #define	V_ipport_tcplastcount		VNET(ipport_tcplastcount)
1506ac48b74SMike Silbersack 
151d2025bd0SBjoern A. Zeeb #ifdef INET
152fa046d87SRobert Watson static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
153fa046d87SRobert Watson 			    struct in_addr faddr, u_int fport_arg,
154fa046d87SRobert Watson 			    struct in_addr laddr, u_int lport_arg,
155a034518aSAndrew Gallatin 			    int lookupflags, struct ifnet *ifp,
156a034518aSAndrew Gallatin 			    uint8_t numa_domain);
15767107f45SBjoern A. Zeeb 
158bbd42ad0SPeter Wemm #define RANGECHK(var, min, max) \
159bbd42ad0SPeter Wemm 	if ((var) < (min)) { (var) = (min); } \
160bbd42ad0SPeter Wemm 	else if ((var) > (max)) { (var) = (max); }
161bbd42ad0SPeter Wemm 
162bbd42ad0SPeter Wemm static int
16382d9ae4eSPoul-Henning Kamp sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
164bbd42ad0SPeter Wemm {
16530a4ab08SBruce Evans 	int error;
16630a4ab08SBruce Evans 
167f6dfe47aSMarko Zec 	error = sysctl_handle_int(oidp, arg1, arg2, req);
16830a4ab08SBruce Evans 	if (error == 0) {
169603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
170603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
171603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
172603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
173603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
174603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
175bbd42ad0SPeter Wemm 	}
17630a4ab08SBruce Evans 	return (error);
177bbd42ad0SPeter Wemm }
178bbd42ad0SPeter Wemm 
179bbd42ad0SPeter Wemm #undef RANGECHK
180bbd42ad0SPeter Wemm 
1817029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
1827029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1836472ac3dSEd Schouten     "IP Ports");
18433b3ac06SPeter Wemm 
1856df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
1867029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1877029da5cSPawel Biernacki     &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
1887029da5cSPawel Biernacki     "");
1896df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
1907029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1917029da5cSPawel Biernacki     &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
1927029da5cSPawel Biernacki     "");
1936df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
1947029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1957029da5cSPawel Biernacki     &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
1967029da5cSPawel Biernacki     "");
1976df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
1987029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1997029da5cSPawel Biernacki     &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
2007029da5cSPawel Biernacki     "");
2016df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
2027029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
2037029da5cSPawel Biernacki     &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
2047029da5cSPawel Biernacki     "");
2056df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
2067029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
2077029da5cSPawel Biernacki     &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
2087029da5cSPawel Biernacki     "");
2096df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
2106df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
2116df8a710SGleb Smirnoff 	&VNET_NAME(ipport_reservedhigh), 0, "");
2126df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
213eddfbb76SRobert Watson 	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
2146df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
2156df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
216eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
2176df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
2186df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
219eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
22027c4abc7SGordon Bergling 	"allocations before switching to a sequential one");
2216df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
2226df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
223eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomtime), 0,
22427c4abc7SGordon Bergling 	"Minimum time to keep sequential port "
2256ee79c59SMaxim Konovalov 	"allocation before switching to a random one");
22620abea66SRandall Stewart 
22720abea66SRandall Stewart #ifdef RATELIMIT
2281a714ff2SRandall Stewart counter_u64_t rate_limit_new;
2291a714ff2SRandall Stewart counter_u64_t rate_limit_chg;
23020abea66SRandall Stewart counter_u64_t rate_limit_active;
23120abea66SRandall Stewart counter_u64_t rate_limit_alloc_fail;
23220abea66SRandall Stewart counter_u64_t rate_limit_set_ok;
23320abea66SRandall Stewart 
2347029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
23520abea66SRandall Stewart     "IP Rate Limiting");
23620abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
23720abea66SRandall Stewart     &rate_limit_active, "Active rate limited connections");
23820abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
23920abea66SRandall Stewart    &rate_limit_alloc_fail, "Rate limited connection failures");
24020abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
24120abea66SRandall Stewart    &rate_limit_set_ok, "Rate limited setting succeeded");
2421a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
2431a714ff2SRandall Stewart    &rate_limit_new, "Total Rate limit new attempts");
2441a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
2451a714ff2SRandall Stewart    &rate_limit_chg, "Total Rate limited change attempts");
2461a714ff2SRandall Stewart 
24720abea66SRandall Stewart #endif /* RATELIMIT */
24820abea66SRandall Stewart 
24983e521ecSBjoern A. Zeeb #endif /* INET */
2500312fbe9SPoul-Henning Kamp 
251a0577692SGleb Smirnoff VNET_DEFINE(uint32_t, in_pcbhashseed);
252a0577692SGleb Smirnoff static void
253a0577692SGleb Smirnoff in_pcbhashseed_init(void)
254a0577692SGleb Smirnoff {
255a0577692SGleb Smirnoff 
256a0577692SGleb Smirnoff 	V_in_pcbhashseed = arc4random();
257a0577692SGleb Smirnoff }
258a0577692SGleb Smirnoff VNET_SYSINIT(in_pcbhashseed_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
259a0577692SGleb Smirnoff     in_pcbhashseed_init, 0);
260a0577692SGleb Smirnoff 
261c3229e05SDavid Greenman /*
262c3229e05SDavid Greenman  * in_pcb.c: manage the Protocol Control Blocks.
263c3229e05SDavid Greenman  *
264de35559fSRobert Watson  * NOTE: It is assumed that most of these functions will be called with
265de35559fSRobert Watson  * the pcbinfo lock held, and often, the inpcb lock held, as these utility
266de35559fSRobert Watson  * functions often modify hash chains or addresses in pcbs.
267c3229e05SDavid Greenman  */
268c3229e05SDavid Greenman 
2691a43cff9SSean Bruno static struct inpcblbgroup *
2701a43cff9SSean Bruno in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, u_char vflag,
271a034518aSAndrew Gallatin     uint16_t port, const union in_dependaddr *addr, int size,
272a034518aSAndrew Gallatin     uint8_t numa_domain)
2731a43cff9SSean Bruno {
2741a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2751a43cff9SSean Bruno 	size_t bytes;
2761a43cff9SSean Bruno 
2771a43cff9SSean Bruno 	bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
2781a43cff9SSean Bruno 	grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
2791a43cff9SSean Bruno 	if (!grp)
2801a43cff9SSean Bruno 		return (NULL);
2811a43cff9SSean Bruno 	grp->il_vflag = vflag;
2821a43cff9SSean Bruno 	grp->il_lport = port;
283a034518aSAndrew Gallatin 	grp->il_numa_domain = numa_domain;
2841a43cff9SSean Bruno 	grp->il_dependladdr = *addr;
2851a43cff9SSean Bruno 	grp->il_inpsiz = size;
28654af3d0dSMark Johnston 	CK_LIST_INSERT_HEAD(hdr, grp, il_list);
2871a43cff9SSean Bruno 	return (grp);
2881a43cff9SSean Bruno }
2891a43cff9SSean Bruno 
2901a43cff9SSean Bruno static void
29154af3d0dSMark Johnston in_pcblbgroup_free_deferred(epoch_context_t ctx)
29254af3d0dSMark Johnston {
29354af3d0dSMark Johnston 	struct inpcblbgroup *grp;
29454af3d0dSMark Johnston 
29554af3d0dSMark Johnston 	grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
29654af3d0dSMark Johnston 	free(grp, M_PCB);
29754af3d0dSMark Johnston }
29854af3d0dSMark Johnston 
29954af3d0dSMark Johnston static void
3001a43cff9SSean Bruno in_pcblbgroup_free(struct inpcblbgroup *grp)
3011a43cff9SSean Bruno {
3021a43cff9SSean Bruno 
30354af3d0dSMark Johnston 	CK_LIST_REMOVE(grp, il_list);
3042a4bd982SGleb Smirnoff 	NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
3051a43cff9SSean Bruno }
3061a43cff9SSean Bruno 
3071a43cff9SSean Bruno static struct inpcblbgroup *
3081a43cff9SSean Bruno in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
3091a43cff9SSean Bruno     struct inpcblbgroup *old_grp, int size)
3101a43cff9SSean Bruno {
3111a43cff9SSean Bruno 	struct inpcblbgroup *grp;
3121a43cff9SSean Bruno 	int i;
3131a43cff9SSean Bruno 
3141a43cff9SSean Bruno 	grp = in_pcblbgroup_alloc(hdr, old_grp->il_vflag,
315a034518aSAndrew Gallatin 	    old_grp->il_lport, &old_grp->il_dependladdr, size,
316a034518aSAndrew Gallatin 	    old_grp->il_numa_domain);
31779ee680bSMark Johnston 	if (grp == NULL)
3181a43cff9SSean Bruno 		return (NULL);
3191a43cff9SSean Bruno 
3201a43cff9SSean Bruno 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
3211a43cff9SSean Bruno 	    ("invalid new local group size %d and old local group count %d",
3221a43cff9SSean Bruno 	     grp->il_inpsiz, old_grp->il_inpcnt));
3231a43cff9SSean Bruno 
3241a43cff9SSean Bruno 	for (i = 0; i < old_grp->il_inpcnt; ++i)
3251a43cff9SSean Bruno 		grp->il_inp[i] = old_grp->il_inp[i];
3261a43cff9SSean Bruno 	grp->il_inpcnt = old_grp->il_inpcnt;
3271a43cff9SSean Bruno 	in_pcblbgroup_free(old_grp);
3281a43cff9SSean Bruno 	return (grp);
3291a43cff9SSean Bruno }
3301a43cff9SSean Bruno 
3311a43cff9SSean Bruno /*
3321a43cff9SSean Bruno  * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
3331a43cff9SSean Bruno  * and shrink group if possible.
3341a43cff9SSean Bruno  */
3351a43cff9SSean Bruno static void
3361a43cff9SSean Bruno in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
3371a43cff9SSean Bruno     int i)
3381a43cff9SSean Bruno {
33979ee680bSMark Johnston 	struct inpcblbgroup *grp, *new_grp;
3401a43cff9SSean Bruno 
34179ee680bSMark Johnston 	grp = *grpp;
3421a43cff9SSean Bruno 	for (; i + 1 < grp->il_inpcnt; ++i)
3431a43cff9SSean Bruno 		grp->il_inp[i] = grp->il_inp[i + 1];
3441a43cff9SSean Bruno 	grp->il_inpcnt--;
3451a43cff9SSean Bruno 
3461a43cff9SSean Bruno 	if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
34779ee680bSMark Johnston 	    grp->il_inpcnt <= grp->il_inpsiz / 4) {
3481a43cff9SSean Bruno 		/* Shrink this group. */
34979ee680bSMark Johnston 		new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
35079ee680bSMark Johnston 		if (new_grp != NULL)
3511a43cff9SSean Bruno 			*grpp = new_grp;
3521a43cff9SSean Bruno 	}
3531a43cff9SSean Bruno }
3541a43cff9SSean Bruno 
3551a43cff9SSean Bruno /*
3561a43cff9SSean Bruno  * Add PCB to load balance group for SO_REUSEPORT_LB option.
3571a43cff9SSean Bruno  */
3581a43cff9SSean Bruno static int
359a034518aSAndrew Gallatin in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
3601a43cff9SSean Bruno {
361a7026c7fSMark Johnston 	const static struct timeval interval = { 60, 0 };
362a7026c7fSMark Johnston 	static struct timeval lastprint;
3631a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
3641a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
3651a43cff9SSean Bruno 	struct inpcblbgroup *grp;
36679ee680bSMark Johnston 	uint32_t idx;
3671a43cff9SSean Bruno 
3681a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
3691a43cff9SSean Bruno 
3701a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
3711a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
3721a43cff9SSean Bruno 
3731a43cff9SSean Bruno 	/*
3741a43cff9SSean Bruno 	 * Don't allow jailed socket to join local group.
3751a43cff9SSean Bruno 	 */
37679ee680bSMark Johnston 	if (inp->inp_socket != NULL && jailed(inp->inp_socket->so_cred))
3771a43cff9SSean Bruno 		return (0);
3781a43cff9SSean Bruno 
3791a43cff9SSean Bruno #ifdef INET6
3801a43cff9SSean Bruno 	/*
3811a43cff9SSean Bruno 	 * Don't allow IPv4 mapped INET6 wild socket.
3821a43cff9SSean Bruno 	 */
3831a43cff9SSean Bruno 	if ((inp->inp_vflag & INP_IPV4) &&
3841a43cff9SSean Bruno 	    inp->inp_laddr.s_addr == INADDR_ANY &&
3851a43cff9SSean Bruno 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
3861a43cff9SSean Bruno 		return (0);
3871a43cff9SSean Bruno 	}
3881a43cff9SSean Bruno #endif
3891a43cff9SSean Bruno 
3909d2877fcSMark Johnston 	idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
39179ee680bSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
39254af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
3931a43cff9SSean Bruno 		if (grp->il_vflag == inp->inp_vflag &&
3941a43cff9SSean Bruno 		    grp->il_lport == inp->inp_lport &&
395a034518aSAndrew Gallatin 		    grp->il_numa_domain == numa_domain &&
3961a43cff9SSean Bruno 		    memcmp(&grp->il_dependladdr,
3971a43cff9SSean Bruno 		    &inp->inp_inc.inc_ie.ie_dependladdr,
39879ee680bSMark Johnston 		    sizeof(grp->il_dependladdr)) == 0)
3991a43cff9SSean Bruno 			break;
4001a43cff9SSean Bruno 	}
4011a43cff9SSean Bruno 	if (grp == NULL) {
4021a43cff9SSean Bruno 		/* Create new load balance group. */
4031a43cff9SSean Bruno 		grp = in_pcblbgroup_alloc(hdr, inp->inp_vflag,
4041a43cff9SSean Bruno 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
405a034518aSAndrew Gallatin 		    INPCBLBGROUP_SIZMIN, numa_domain);
40679ee680bSMark Johnston 		if (grp == NULL)
4071a43cff9SSean Bruno 			return (ENOBUFS);
4081a43cff9SSean Bruno 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
4091a43cff9SSean Bruno 		if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
410a7026c7fSMark Johnston 			if (ratecheck(&lastprint, &interval))
4111a43cff9SSean Bruno 				printf("lb group port %d, limit reached\n",
4121a43cff9SSean Bruno 				    ntohs(grp->il_lport));
4131a43cff9SSean Bruno 			return (0);
4141a43cff9SSean Bruno 		}
4151a43cff9SSean Bruno 
4161a43cff9SSean Bruno 		/* Expand this local group. */
4171a43cff9SSean Bruno 		grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
41879ee680bSMark Johnston 		if (grp == NULL)
4191a43cff9SSean Bruno 			return (ENOBUFS);
4201a43cff9SSean Bruno 	}
4211a43cff9SSean Bruno 
4221a43cff9SSean Bruno 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
42379ee680bSMark Johnston 	    ("invalid local group size %d and count %d", grp->il_inpsiz,
42479ee680bSMark Johnston 	    grp->il_inpcnt));
4251a43cff9SSean Bruno 
4261a43cff9SSean Bruno 	grp->il_inp[grp->il_inpcnt] = inp;
4271a43cff9SSean Bruno 	grp->il_inpcnt++;
4281a43cff9SSean Bruno 	return (0);
4291a43cff9SSean Bruno }
4301a43cff9SSean Bruno 
4311a43cff9SSean Bruno /*
4321a43cff9SSean Bruno  * Remove PCB from load balance group.
4331a43cff9SSean Bruno  */
4341a43cff9SSean Bruno static void
4351a43cff9SSean Bruno in_pcbremlbgrouphash(struct inpcb *inp)
4361a43cff9SSean Bruno {
4371a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
4381a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
4391a43cff9SSean Bruno 	struct inpcblbgroup *grp;
4401a43cff9SSean Bruno 	int i;
4411a43cff9SSean Bruno 
4421a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
4431a43cff9SSean Bruno 
4441a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
4451a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
4461a43cff9SSean Bruno 
4471a43cff9SSean Bruno 	hdr = &pcbinfo->ipi_lbgrouphashbase[
4489d2877fcSMark Johnston 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
44954af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
4501a43cff9SSean Bruno 		for (i = 0; i < grp->il_inpcnt; ++i) {
4511a43cff9SSean Bruno 			if (grp->il_inp[i] != inp)
4521a43cff9SSean Bruno 				continue;
4531a43cff9SSean Bruno 
4541a43cff9SSean Bruno 			if (grp->il_inpcnt == 1) {
4551a43cff9SSean Bruno 				/* We are the last, free this local group. */
4561a43cff9SSean Bruno 				in_pcblbgroup_free(grp);
4571a43cff9SSean Bruno 			} else {
4581a43cff9SSean Bruno 				/* Pull up inpcbs, shrink group if possible. */
4591a43cff9SSean Bruno 				in_pcblbgroup_reorder(hdr, &grp, i);
4601a43cff9SSean Bruno 			}
4611a43cff9SSean Bruno 			return;
4621a43cff9SSean Bruno 		}
4631a43cff9SSean Bruno 	}
4641a43cff9SSean Bruno }
4651a43cff9SSean Bruno 
466a034518aSAndrew Gallatin int
467a034518aSAndrew Gallatin in_pcblbgroup_numa(struct inpcb *inp, int arg)
468a034518aSAndrew Gallatin {
469a034518aSAndrew Gallatin 	struct inpcbinfo *pcbinfo;
470a034518aSAndrew Gallatin 	struct inpcblbgrouphead *hdr;
471a034518aSAndrew Gallatin 	struct inpcblbgroup *grp;
472a034518aSAndrew Gallatin 	int err, i;
473a034518aSAndrew Gallatin 	uint8_t numa_domain;
474a034518aSAndrew Gallatin 
475a034518aSAndrew Gallatin 	switch (arg) {
476a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_NODOM:
477a034518aSAndrew Gallatin 		numa_domain = M_NODOM;
478a034518aSAndrew Gallatin 		break;
479a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_CURDOM:
480a034518aSAndrew Gallatin 		numa_domain = PCPU_GET(domain);
481a034518aSAndrew Gallatin 		break;
482a034518aSAndrew Gallatin 	default:
483a034518aSAndrew Gallatin 		if (arg < 0 || arg >= vm_ndomains)
484a034518aSAndrew Gallatin 			return (EINVAL);
485a034518aSAndrew Gallatin 		numa_domain = arg;
486a034518aSAndrew Gallatin 	}
487a034518aSAndrew Gallatin 
488a034518aSAndrew Gallatin 	err = 0;
489a034518aSAndrew Gallatin 	pcbinfo = inp->inp_pcbinfo;
490a034518aSAndrew Gallatin 	INP_WLOCK_ASSERT(inp);
491a034518aSAndrew Gallatin 	INP_HASH_WLOCK(pcbinfo);
492a034518aSAndrew Gallatin 	hdr = &pcbinfo->ipi_lbgrouphashbase[
493a034518aSAndrew Gallatin 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
494a034518aSAndrew Gallatin 	CK_LIST_FOREACH(grp, hdr, il_list) {
495a034518aSAndrew Gallatin 		for (i = 0; i < grp->il_inpcnt; ++i) {
496a034518aSAndrew Gallatin 			if (grp->il_inp[i] != inp)
497a034518aSAndrew Gallatin 				continue;
498a034518aSAndrew Gallatin 
499a034518aSAndrew Gallatin 			if (grp->il_numa_domain == numa_domain) {
500a034518aSAndrew Gallatin 				goto abort_with_hash_wlock;
501a034518aSAndrew Gallatin 			}
502a034518aSAndrew Gallatin 
503a034518aSAndrew Gallatin 			/* Remove it from the old group. */
504a034518aSAndrew Gallatin 			in_pcbremlbgrouphash(inp);
505a034518aSAndrew Gallatin 
506a034518aSAndrew Gallatin 			/* Add it to the new group based on numa domain. */
507a034518aSAndrew Gallatin 			in_pcbinslbgrouphash(inp, numa_domain);
508a034518aSAndrew Gallatin 			goto abort_with_hash_wlock;
509a034518aSAndrew Gallatin 		}
510a034518aSAndrew Gallatin 	}
511a034518aSAndrew Gallatin 	err = ENOENT;
512a034518aSAndrew Gallatin abort_with_hash_wlock:
513a034518aSAndrew Gallatin 	INP_HASH_WUNLOCK(pcbinfo);
514a034518aSAndrew Gallatin 	return (err);
515a034518aSAndrew Gallatin }
516a034518aSAndrew Gallatin 
517db0ac6deSCy Schubert /* Make sure it is safe to use hashinit(9) on CK_LIST. */
518db0ac6deSCy Schubert CTASSERT(sizeof(struct inpcbhead) == sizeof(LIST_HEAD(, inpcb)));
519db0ac6deSCy Schubert 
520cc487c16SGleb Smirnoff /*
521fec8a8c7SGleb Smirnoff  * Initialize an inpcbinfo - a per-VNET instance of connections db.
5229bcd427bSRobert Watson  */
5239bcd427bSRobert Watson void
524fec8a8c7SGleb Smirnoff in_pcbinfo_init(struct inpcbinfo *pcbinfo, struct inpcbstorage *pcbstor,
525fec8a8c7SGleb Smirnoff     u_int hash_nelements, u_int porthash_nelements)
5269bcd427bSRobert Watson {
5279bcd427bSRobert Watson 
528fec8a8c7SGleb Smirnoff 	mtx_init(&pcbinfo->ipi_lock, pcbstor->ips_infolock_name, NULL, MTX_DEF);
529fec8a8c7SGleb Smirnoff 	mtx_init(&pcbinfo->ipi_hash_lock, pcbstor->ips_hashlock_name,
530fec8a8c7SGleb Smirnoff 	    NULL, MTX_DEF);
5319bcd427bSRobert Watson #ifdef VIMAGE
5329bcd427bSRobert Watson 	pcbinfo->ipi_vnet = curvnet;
5339bcd427bSRobert Watson #endif
534db0ac6deSCy Schubert 	CK_LIST_INIT(&pcbinfo->ipi_listhead);
535fa046d87SRobert Watson 	pcbinfo->ipi_count = 0;
5369bcd427bSRobert Watson 	pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
5379bcd427bSRobert Watson 	    &pcbinfo->ipi_hashmask);
538db0ac6deSCy Schubert 	porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
5399bcd427bSRobert Watson 	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
5409bcd427bSRobert Watson 	    &pcbinfo->ipi_porthashmask);
5419d2877fcSMark Johnston 	pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
5421a43cff9SSean Bruno 	    &pcbinfo->ipi_lbgrouphashmask);
543fec8a8c7SGleb Smirnoff 	pcbinfo->ipi_zone = pcbstor->ips_zone;
544fec8a8c7SGleb Smirnoff 	pcbinfo->ipi_portzone = pcbstor->ips_portzone;
545db0ac6deSCy Schubert 	pcbinfo->ipi_smr = uma_zone_get_smr(pcbinfo->ipi_zone);
5469bcd427bSRobert Watson }
5479bcd427bSRobert Watson 
5489bcd427bSRobert Watson /*
5499bcd427bSRobert Watson  * Destroy an inpcbinfo.
5509bcd427bSRobert Watson  */
5519bcd427bSRobert Watson void
5529bcd427bSRobert Watson in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
5539bcd427bSRobert Watson {
5549bcd427bSRobert Watson 
555fa046d87SRobert Watson 	KASSERT(pcbinfo->ipi_count == 0,
556fa046d87SRobert Watson 	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
557fa046d87SRobert Watson 
5589bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
5599bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
5609bcd427bSRobert Watson 	    pcbinfo->ipi_porthashmask);
5611a43cff9SSean Bruno 	hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
5621a43cff9SSean Bruno 	    pcbinfo->ipi_lbgrouphashmask);
563db0ac6deSCy Schubert 	mtx_destroy(&pcbinfo->ipi_hash_lock);
564db0ac6deSCy Schubert 	mtx_destroy(&pcbinfo->ipi_lock);
5659bcd427bSRobert Watson }
5669bcd427bSRobert Watson 
5679bcd427bSRobert Watson /*
568fec8a8c7SGleb Smirnoff  * Initialize a pcbstorage - per protocol zones to allocate inpcbs.
569fec8a8c7SGleb Smirnoff  */
570fec8a8c7SGleb Smirnoff static void inpcb_dtor(void *, int, void *);
571fec8a8c7SGleb Smirnoff static void inpcb_fini(void *, int);
572fec8a8c7SGleb Smirnoff void
573fec8a8c7SGleb Smirnoff in_pcbstorage_init(void *arg)
574fec8a8c7SGleb Smirnoff {
575fec8a8c7SGleb Smirnoff 	struct inpcbstorage *pcbstor = arg;
576fec8a8c7SGleb Smirnoff 
577fec8a8c7SGleb Smirnoff 	pcbstor->ips_zone = uma_zcreate(pcbstor->ips_zone_name,
578fec8a8c7SGleb Smirnoff 	    sizeof(struct inpcb), NULL, inpcb_dtor, pcbstor->ips_pcbinit,
579fec8a8c7SGleb Smirnoff 	    inpcb_fini, UMA_ALIGN_PTR, UMA_ZONE_SMR);
580fec8a8c7SGleb Smirnoff 	pcbstor->ips_portzone = uma_zcreate(pcbstor->ips_portzone_name,
581fec8a8c7SGleb Smirnoff 	    sizeof(struct inpcbport), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
582fec8a8c7SGleb Smirnoff 	uma_zone_set_smr(pcbstor->ips_portzone,
583fec8a8c7SGleb Smirnoff 	    uma_zone_get_smr(pcbstor->ips_zone));
584fec8a8c7SGleb Smirnoff }
585fec8a8c7SGleb Smirnoff 
586fec8a8c7SGleb Smirnoff /*
587fec8a8c7SGleb Smirnoff  * Destroy a pcbstorage - used by unloadable protocols.
588fec8a8c7SGleb Smirnoff  */
589fec8a8c7SGleb Smirnoff void
590fec8a8c7SGleb Smirnoff in_pcbstorage_destroy(void *arg)
591fec8a8c7SGleb Smirnoff {
592fec8a8c7SGleb Smirnoff 	struct inpcbstorage *pcbstor = arg;
593fec8a8c7SGleb Smirnoff 
594fec8a8c7SGleb Smirnoff 	uma_zdestroy(pcbstor->ips_zone);
595fec8a8c7SGleb Smirnoff 	uma_zdestroy(pcbstor->ips_portzone);
596fec8a8c7SGleb Smirnoff }
597fec8a8c7SGleb Smirnoff 
598fec8a8c7SGleb Smirnoff /*
599c3229e05SDavid Greenman  * Allocate a PCB and associate it with the socket.
600d915b280SStephan Uphoff  * On success return with the PCB locked.
601c3229e05SDavid Greenman  */
602df8bae1dSRodney W. Grimes int
603d915b280SStephan Uphoff in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
604df8bae1dSRodney W. Grimes {
605136d4f1cSRobert Watson 	struct inpcb *inp;
60613cf67f3SHajimu UMEMOTO 	int error;
607a557af22SRobert Watson 
608a557af22SRobert Watson 	error = 0;
609db0ac6deSCy Schubert 	inp = uma_zalloc_smr(pcbinfo->ipi_zone, M_NOWAIT);
610df8bae1dSRodney W. Grimes 	if (inp == NULL)
611df8bae1dSRodney W. Grimes 		return (ENOBUFS);
6126a6cefacSGleb Smirnoff 	bzero(&inp->inp_start_zero, inp_zero_size);
61350575ce1SAndrew Gallatin #ifdef NUMA
61450575ce1SAndrew Gallatin 	inp->inp_numa_domain = M_NODOM;
61550575ce1SAndrew Gallatin #endif
61615bd2b43SDavid Greenman 	inp->inp_pcbinfo = pcbinfo;
617df8bae1dSRodney W. Grimes 	inp->inp_socket = so;
61886d02c5cSBjoern A. Zeeb 	inp->inp_cred = crhold(so->so_cred);
6198b07e49aSJulian Elischer 	inp->inp_inc.inc_fibnum = so->so_fibnum;
620a557af22SRobert Watson #ifdef MAC
62130d239bcSRobert Watson 	error = mac_inpcb_init(inp, M_NOWAIT);
622a557af22SRobert Watson 	if (error != 0)
623a557af22SRobert Watson 		goto out;
62430d239bcSRobert Watson 	mac_inpcb_create(so, inp);
625a557af22SRobert Watson #endif
626fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
627fcf59617SAndrey V. Elsukov 	error = ipsec_init_pcbpolicy(inp);
6280bffde27SRobert Watson 	if (error != 0) {
6290bffde27SRobert Watson #ifdef MAC
6300bffde27SRobert Watson 		mac_inpcb_destroy(inp);
6310bffde27SRobert Watson #endif
632a557af22SRobert Watson 		goto out;
6330bffde27SRobert Watson 	}
634b2630c29SGeorge V. Neville-Neil #endif /*IPSEC*/
635e3fd5ffdSRobert Watson #ifdef INET6
636340c35deSJonathan Lemon 	if (INP_SOCKAF(so) == AF_INET6) {
637340c35deSJonathan Lemon 		inp->inp_vflag |= INP_IPV6PROTO;
638603724d3SBjoern A. Zeeb 		if (V_ip6_v6only)
63933841545SHajimu UMEMOTO 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
640340c35deSJonathan Lemon 	}
641603724d3SBjoern A. Zeeb 	if (V_ip6_auto_flowlabel)
64233841545SHajimu UMEMOTO 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
64333841545SHajimu UMEMOTO #endif
6448c1960d5SMike Karels 	/*
6458c1960d5SMike Karels 	 * Routes in inpcb's can cache L2 as well; they are guaranteed
6468c1960d5SMike Karels 	 * to be cleaned up.
6478c1960d5SMike Karels 	 */
6488c1960d5SMike Karels 	inp->inp_route.ro_flags = RT_LLE_CACHE;
649db0ac6deSCy Schubert #ifdef TCPHPTS
650db0ac6deSCy Schubert 	/*
651db0ac6deSCy Schubert 	 * If using hpts lets drop a random number in so
652db0ac6deSCy Schubert 	 * not all new connections fall on the same CPU.
653db0ac6deSCy Schubert 	 */
654a370832bSGleb Smirnoff 	inp->inp_hpts_cpu = hpts_random_cpu(inp);
655db0ac6deSCy Schubert #endif
656db0ac6deSCy Schubert 	refcount_init(&inp->inp_refcount, 1);   /* Reference from socket. */
657db0ac6deSCy Schubert 	INP_WLOCK(inp);
658db0ac6deSCy Schubert 	INP_INFO_WLOCK(pcbinfo);
659db0ac6deSCy Schubert 	pcbinfo->ipi_count++;
660db0ac6deSCy Schubert 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
661db0ac6deSCy Schubert 	CK_LIST_INSERT_HEAD(&pcbinfo->ipi_listhead, inp, inp_list);
662db0ac6deSCy Schubert 	INP_INFO_WUNLOCK(pcbinfo);
663db0ac6deSCy Schubert 	so->so_pcb = inp;
664db0ac6deSCy Schubert 
665db0ac6deSCy Schubert 	return (0);
666db0ac6deSCy Schubert 
6677a60a910SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
668a557af22SRobert Watson out:
669db0ac6deSCy Schubert 	uma_zfree_smr(pcbinfo->ipi_zone, inp);
670266f97b5SCy Schubert 	return (error);
671db0ac6deSCy Schubert #endif
672df8bae1dSRodney W. Grimes }
673df8bae1dSRodney W. Grimes 
67467107f45SBjoern A. Zeeb #ifdef INET
675df8bae1dSRodney W. Grimes int
676136d4f1cSRobert Watson in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
677df8bae1dSRodney W. Grimes {
6784b932371SIan Dowse 	int anonport, error;
6794b932371SIan Dowse 
680f161d294SMark Johnston 	KASSERT(nam == NULL || nam->sa_family == AF_INET,
681f161d294SMark Johnston 	    ("%s: invalid address family for %p", __func__, nam));
682f161d294SMark Johnston 	KASSERT(nam == NULL || nam->sa_len == sizeof(struct sockaddr_in),
683f161d294SMark Johnston 	    ("%s: invalid address length for %p", __func__, nam));
6848501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
685fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
68659daba27SSam Leffler 
6874b932371SIan Dowse 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
6884b932371SIan Dowse 		return (EINVAL);
6895cd3dcaaSNavdeep Parhar 	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
6904b932371SIan Dowse 	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
691b0330ed9SPawel Jakub Dawidek 	    &inp->inp_lport, cred);
6924b932371SIan Dowse 	if (error)
6934b932371SIan Dowse 		return (error);
6944b932371SIan Dowse 	if (in_pcbinshash(inp) != 0) {
6954b932371SIan Dowse 		inp->inp_laddr.s_addr = INADDR_ANY;
6964b932371SIan Dowse 		inp->inp_lport = 0;
6974b932371SIan Dowse 		return (EAGAIN);
6984b932371SIan Dowse 	}
6994b932371SIan Dowse 	if (anonport)
7004b932371SIan Dowse 		inp->inp_flags |= INP_ANONPORT;
7014b932371SIan Dowse 	return (0);
7024b932371SIan Dowse }
70367107f45SBjoern A. Zeeb #endif
7044b932371SIan Dowse 
705efc76f72SBjoern A. Zeeb #if defined(INET) || defined(INET6)
70625102351SMike Karels /*
70725102351SMike Karels  * Assign a local port like in_pcb_lport(), but also used with connect()
70825102351SMike Karels  * and a foreign address and port.  If fsa is non-NULL, choose a local port
70925102351SMike Karels  * that is unused with those, otherwise one that is completely unused.
7102fdbcbeaSMike Karels  * lsa can be NULL for IPv6.
71125102351SMike Karels  */
712efc76f72SBjoern A. Zeeb int
71325102351SMike Karels in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
71425102351SMike Karels     struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
715efc76f72SBjoern A. Zeeb {
716efc76f72SBjoern A. Zeeb 	struct inpcbinfo *pcbinfo;
717efc76f72SBjoern A. Zeeb 	struct inpcb *tmpinp;
718efc76f72SBjoern A. Zeeb 	unsigned short *lastport;
719efc76f72SBjoern A. Zeeb 	int count, dorandom, error;
720efc76f72SBjoern A. Zeeb 	u_short aux, first, last, lport;
721efc76f72SBjoern A. Zeeb #ifdef INET
72225102351SMike Karels 	struct in_addr laddr, faddr;
72325102351SMike Karels #endif
72425102351SMike Karels #ifdef INET6
72525102351SMike Karels 	struct in6_addr *laddr6, *faddr6;
726efc76f72SBjoern A. Zeeb #endif
727efc76f72SBjoern A. Zeeb 
728efc76f72SBjoern A. Zeeb 	pcbinfo = inp->inp_pcbinfo;
729efc76f72SBjoern A. Zeeb 
730efc76f72SBjoern A. Zeeb 	/*
731efc76f72SBjoern A. Zeeb 	 * Because no actual state changes occur here, a global write lock on
732efc76f72SBjoern A. Zeeb 	 * the pcbinfo isn't required.
733efc76f72SBjoern A. Zeeb 	 */
734efc76f72SBjoern A. Zeeb 	INP_LOCK_ASSERT(inp);
735fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
736efc76f72SBjoern A. Zeeb 
737efc76f72SBjoern A. Zeeb 	if (inp->inp_flags & INP_HIGHPORT) {
738efc76f72SBjoern A. Zeeb 		first = V_ipport_hifirstauto;	/* sysctl */
739efc76f72SBjoern A. Zeeb 		last  = V_ipport_hilastauto;
740efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lasthi;
741efc76f72SBjoern A. Zeeb 	} else if (inp->inp_flags & INP_LOWPORT) {
742cc426dd3SMateusz Guzik 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
743efc76f72SBjoern A. Zeeb 		if (error)
744efc76f72SBjoern A. Zeeb 			return (error);
745efc76f72SBjoern A. Zeeb 		first = V_ipport_lowfirstauto;	/* 1023 */
746efc76f72SBjoern A. Zeeb 		last  = V_ipport_lowlastauto;	/* 600 */
747efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastlow;
748efc76f72SBjoern A. Zeeb 	} else {
749efc76f72SBjoern A. Zeeb 		first = V_ipport_firstauto;	/* sysctl */
750efc76f72SBjoern A. Zeeb 		last  = V_ipport_lastauto;
751efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastport;
752efc76f72SBjoern A. Zeeb 	}
753efc76f72SBjoern A. Zeeb 	/*
754e06e816fSKevin Lo 	 * For UDP(-Lite), use random port allocation as long as the user
755efc76f72SBjoern A. Zeeb 	 * allows it.  For TCP (and as of yet unknown) connections,
756efc76f72SBjoern A. Zeeb 	 * use random port allocation only if the user allows it AND
757efc76f72SBjoern A. Zeeb 	 * ipport_tick() allows it.
758efc76f72SBjoern A. Zeeb 	 */
759efc76f72SBjoern A. Zeeb 	if (V_ipport_randomized &&
760e06e816fSKevin Lo 		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
761e06e816fSKevin Lo 		pcbinfo == &V_ulitecbinfo))
762efc76f72SBjoern A. Zeeb 		dorandom = 1;
763efc76f72SBjoern A. Zeeb 	else
764efc76f72SBjoern A. Zeeb 		dorandom = 0;
765efc76f72SBjoern A. Zeeb 	/*
766efc76f72SBjoern A. Zeeb 	 * It makes no sense to do random port allocation if
767efc76f72SBjoern A. Zeeb 	 * we have the only port available.
768efc76f72SBjoern A. Zeeb 	 */
769efc76f72SBjoern A. Zeeb 	if (first == last)
770efc76f72SBjoern A. Zeeb 		dorandom = 0;
771e06e816fSKevin Lo 	/* Make sure to not include UDP(-Lite) packets in the count. */
77213e3f334SPeter Lei 	if (pcbinfo != &V_udbinfo && pcbinfo != &V_ulitecbinfo)
773efc76f72SBjoern A. Zeeb 		V_ipport_tcpallocs++;
774efc76f72SBjoern A. Zeeb 	/*
775efc76f72SBjoern A. Zeeb 	 * Instead of having two loops further down counting up or down
776efc76f72SBjoern A. Zeeb 	 * make sure that first is always <= last and go with only one
777efc76f72SBjoern A. Zeeb 	 * code path implementing all logic.
778efc76f72SBjoern A. Zeeb 	 */
779efc76f72SBjoern A. Zeeb 	if (first > last) {
780efc76f72SBjoern A. Zeeb 		aux = first;
781efc76f72SBjoern A. Zeeb 		first = last;
782efc76f72SBjoern A. Zeeb 		last = aux;
783efc76f72SBjoern A. Zeeb 	}
784efc76f72SBjoern A. Zeeb 
785efc76f72SBjoern A. Zeeb #ifdef INET
78625102351SMike Karels 	laddr.s_addr = INADDR_ANY;
7874d457387SBjoern A. Zeeb 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
7882fdbcbeaSMike Karels 		if (lsa != NULL)
78925102351SMike Karels 			laddr = ((struct sockaddr_in *)lsa)->sin_addr;
79025102351SMike Karels 		if (fsa != NULL)
79125102351SMike Karels 			faddr = ((struct sockaddr_in *)fsa)->sin_addr;
792efc76f72SBjoern A. Zeeb 	}
793efc76f72SBjoern A. Zeeb #endif
79425102351SMike Karels #ifdef INET6
7952fdbcbeaSMike Karels 	laddr6 = NULL;
7962fdbcbeaSMike Karels 	if ((inp->inp_vflag & INP_IPV6) != 0) {
7972fdbcbeaSMike Karels 		if (lsa != NULL)
79825102351SMike Karels 			laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
79925102351SMike Karels 		if (fsa != NULL)
80025102351SMike Karels 			faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
80125102351SMike Karels 	}
80225102351SMike Karels #endif
80325102351SMike Karels 
80425102351SMike Karels 	tmpinp = NULL;
805efc76f72SBjoern A. Zeeb 	lport = *lportp;
806efc76f72SBjoern A. Zeeb 
807efc76f72SBjoern A. Zeeb 	if (dorandom)
808efc76f72SBjoern A. Zeeb 		*lastport = first + (arc4random() % (last - first));
809efc76f72SBjoern A. Zeeb 
810efc76f72SBjoern A. Zeeb 	count = last - first;
811efc76f72SBjoern A. Zeeb 
812efc76f72SBjoern A. Zeeb 	do {
813efc76f72SBjoern A. Zeeb 		if (count-- < 0)	/* completely used? */
814efc76f72SBjoern A. Zeeb 			return (EADDRNOTAVAIL);
815efc76f72SBjoern A. Zeeb 		++*lastport;
816efc76f72SBjoern A. Zeeb 		if (*lastport < first || *lastport > last)
817efc76f72SBjoern A. Zeeb 			*lastport = first;
818efc76f72SBjoern A. Zeeb 		lport = htons(*lastport);
819efc76f72SBjoern A. Zeeb 
82025102351SMike Karels 		if (fsa != NULL) {
82125102351SMike Karels #ifdef INET
82225102351SMike Karels 			if (lsa->sa_family == AF_INET) {
82325102351SMike Karels 				tmpinp = in_pcblookup_hash_locked(pcbinfo,
82425102351SMike Karels 				    faddr, fport, laddr, lport, lookupflags,
825a034518aSAndrew Gallatin 				    NULL, M_NODOM);
82625102351SMike Karels 			}
82725102351SMike Karels #endif
82825102351SMike Karels #ifdef INET6
82925102351SMike Karels 			if (lsa->sa_family == AF_INET6) {
83025102351SMike Karels 				tmpinp = in6_pcblookup_hash_locked(pcbinfo,
83125102351SMike Karels 				    faddr6, fport, laddr6, lport, lookupflags,
832a034518aSAndrew Gallatin 				    NULL, M_NODOM);
83325102351SMike Karels 			}
83425102351SMike Karels #endif
83525102351SMike Karels 		} else {
836efc76f72SBjoern A. Zeeb #ifdef INET6
8374616026fSErmal Luçi 			if ((inp->inp_vflag & INP_IPV6) != 0)
838efc76f72SBjoern A. Zeeb 				tmpinp = in6_pcblookup_local(pcbinfo,
83968e0d7e0SRobert Watson 				    &inp->in6p_laddr, lport, lookupflags, cred);
840efc76f72SBjoern A. Zeeb #endif
841efc76f72SBjoern A. Zeeb #if defined(INET) && defined(INET6)
842efc76f72SBjoern A. Zeeb 			else
843efc76f72SBjoern A. Zeeb #endif
844efc76f72SBjoern A. Zeeb #ifdef INET
845efc76f72SBjoern A. Zeeb 				tmpinp = in_pcblookup_local(pcbinfo, laddr,
84668e0d7e0SRobert Watson 				    lport, lookupflags, cred);
847efc76f72SBjoern A. Zeeb #endif
84825102351SMike Karels 		}
849efc76f72SBjoern A. Zeeb 	} while (tmpinp != NULL);
850efc76f72SBjoern A. Zeeb 
851efc76f72SBjoern A. Zeeb 	*lportp = lport;
852efc76f72SBjoern A. Zeeb 
853efc76f72SBjoern A. Zeeb 	return (0);
854efc76f72SBjoern A. Zeeb }
855efdf104bSMikolaj Golub 
856efdf104bSMikolaj Golub /*
85725102351SMike Karels  * Select a local port (number) to use.
85825102351SMike Karels  */
85925102351SMike Karels int
86025102351SMike Karels in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
86125102351SMike Karels     struct ucred *cred, int lookupflags)
86225102351SMike Karels {
86325102351SMike Karels 	struct sockaddr_in laddr;
86425102351SMike Karels 
86525102351SMike Karels 	if (laddrp) {
86625102351SMike Karels 		bzero(&laddr, sizeof(laddr));
86725102351SMike Karels 		laddr.sin_family = AF_INET;
86825102351SMike Karels 		laddr.sin_addr = *laddrp;
86925102351SMike Karels 	}
87025102351SMike Karels 	return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
87125102351SMike Karels 	    NULL, lportp, NULL, 0, cred, lookupflags));
87225102351SMike Karels }
87325102351SMike Karels 
87425102351SMike Karels /*
875efdf104bSMikolaj Golub  * Return cached socket options.
876efdf104bSMikolaj Golub  */
8771a43cff9SSean Bruno int
878efdf104bSMikolaj Golub inp_so_options(const struct inpcb *inp)
879efdf104bSMikolaj Golub {
8801a43cff9SSean Bruno 	int so_options;
881efdf104bSMikolaj Golub 
882efdf104bSMikolaj Golub 	so_options = 0;
883efdf104bSMikolaj Golub 
8841a43cff9SSean Bruno 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
8851a43cff9SSean Bruno 		so_options |= SO_REUSEPORT_LB;
886efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
887efdf104bSMikolaj Golub 		so_options |= SO_REUSEPORT;
888efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
889efdf104bSMikolaj Golub 		so_options |= SO_REUSEADDR;
890efdf104bSMikolaj Golub 	return (so_options);
891efdf104bSMikolaj Golub }
892efc76f72SBjoern A. Zeeb #endif /* INET || INET6 */
893efc76f72SBjoern A. Zeeb 
8944b932371SIan Dowse /*
8950a100a6fSAdrian Chadd  * Check if a new BINDMULTI socket is allowed to be created.
8960a100a6fSAdrian Chadd  *
8970a100a6fSAdrian Chadd  * ni points to the new inp.
8980a100a6fSAdrian Chadd  * oi points to the exisitng inp.
8990a100a6fSAdrian Chadd  *
9000a100a6fSAdrian Chadd  * This checks whether the existing inp also has BINDMULTI and
9010a100a6fSAdrian Chadd  * whether the credentials match.
9020a100a6fSAdrian Chadd  */
903d5bb8bd3SAdrian Chadd int
9040a100a6fSAdrian Chadd in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
9050a100a6fSAdrian Chadd {
9060a100a6fSAdrian Chadd 	/* Check permissions match */
9070a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
9080a100a6fSAdrian Chadd 	    (ni->inp_cred->cr_uid !=
9090a100a6fSAdrian Chadd 	    oi->inp_cred->cr_uid))
9100a100a6fSAdrian Chadd 		return (0);
9110a100a6fSAdrian Chadd 
9120a100a6fSAdrian Chadd 	/* Check the existing inp has BINDMULTI set */
9130a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
9140a100a6fSAdrian Chadd 	    ((oi->inp_flags2 & INP_BINDMULTI) == 0))
9150a100a6fSAdrian Chadd 		return (0);
9160a100a6fSAdrian Chadd 
9170a100a6fSAdrian Chadd 	/*
9180a100a6fSAdrian Chadd 	 * We're okay - either INP_BINDMULTI isn't set on ni, or
9190a100a6fSAdrian Chadd 	 * it is and it matches the checks.
9200a100a6fSAdrian Chadd 	 */
9210a100a6fSAdrian Chadd 	return (1);
9220a100a6fSAdrian Chadd }
9230a100a6fSAdrian Chadd 
924d5bb8bd3SAdrian Chadd #ifdef INET
9250a100a6fSAdrian Chadd /*
9264b932371SIan Dowse  * Set up a bind operation on a PCB, performing port allocation
9274b932371SIan Dowse  * as required, but do not actually modify the PCB. Callers can
9284b932371SIan Dowse  * either complete the bind by setting inp_laddr/inp_lport and
9294b932371SIan Dowse  * calling in_pcbinshash(), or they can just use the resulting
9304b932371SIan Dowse  * port and address to authorise the sending of a once-off packet.
9314b932371SIan Dowse  *
9324b932371SIan Dowse  * On error, the values of *laddrp and *lportp are not changed.
9334b932371SIan Dowse  */
9344b932371SIan Dowse int
935136d4f1cSRobert Watson in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
936136d4f1cSRobert Watson     u_short *lportp, struct ucred *cred)
9374b932371SIan Dowse {
9384b932371SIan Dowse 	struct socket *so = inp->inp_socket;
93915bd2b43SDavid Greenman 	struct sockaddr_in *sin;
940c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
9414b932371SIan Dowse 	struct in_addr laddr;
942df8bae1dSRodney W. Grimes 	u_short lport = 0;
94368e0d7e0SRobert Watson 	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
944413628a7SBjoern A. Zeeb 	int error;
945df8bae1dSRodney W. Grimes 
9468501a69cSRobert Watson 	/*
9471a43cff9SSean Bruno 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
9481a43cff9SSean Bruno 	 * so that we don't have to add to the (already messy) code below.
9491a43cff9SSean Bruno 	 */
9501a43cff9SSean Bruno 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
9511a43cff9SSean Bruno 
9521a43cff9SSean Bruno 	/*
953fa046d87SRobert Watson 	 * No state changes, so read locks are sufficient here.
9548501a69cSRobert Watson 	 */
95559daba27SSam Leffler 	INP_LOCK_ASSERT(inp);
956fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
95759daba27SSam Leffler 
9584b932371SIan Dowse 	laddr.s_addr = *laddrp;
9594b932371SIan Dowse 	if (nam != NULL && laddr.s_addr != INADDR_ANY)
960df8bae1dSRodney W. Grimes 		return (EINVAL);
9611a43cff9SSean Bruno 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
96268e0d7e0SRobert Watson 		lookupflags = INPLOOKUP_WILDCARD;
9634616026fSErmal Luçi 	if (nam == NULL) {
9647c2f3cb9SJamie Gritton 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
9657c2f3cb9SJamie Gritton 			return (error);
9667c2f3cb9SJamie Gritton 	} else {
96757bf258eSGarrett Wollman 		sin = (struct sockaddr_in *)nam;
968f161d294SMark Johnston 		KASSERT(sin->sin_family == AF_INET,
969f161d294SMark Johnston 		    ("%s: invalid family for address %p", __func__, sin));
970f161d294SMark Johnston 		KASSERT(sin->sin_len == sizeof(*sin),
971f161d294SMark Johnston 		    ("%s: invalid length for address %p", __func__, sin));
972f161d294SMark Johnston 
973b89e82ddSJamie Gritton 		error = prison_local_ip4(cred, &sin->sin_addr);
974b89e82ddSJamie Gritton 		if (error)
975b89e82ddSJamie Gritton 			return (error);
9764b932371SIan Dowse 		if (sin->sin_port != *lportp) {
9774b932371SIan Dowse 			/* Don't allow the port to change. */
9784b932371SIan Dowse 			if (*lportp != 0)
9794b932371SIan Dowse 				return (EINVAL);
980df8bae1dSRodney W. Grimes 			lport = sin->sin_port;
9814b932371SIan Dowse 		}
9824b932371SIan Dowse 		/* NB: lport is left as 0 if the port isn't being changed. */
983df8bae1dSRodney W. Grimes 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
984df8bae1dSRodney W. Grimes 			/*
985df8bae1dSRodney W. Grimes 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
986df8bae1dSRodney W. Grimes 			 * allow complete duplication of binding if
987df8bae1dSRodney W. Grimes 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
988df8bae1dSRodney W. Grimes 			 * and a multicast address is bound on both
989df8bae1dSRodney W. Grimes 			 * new and duplicated sockets.
990df8bae1dSRodney W. Grimes 			 */
991f122b319SMikolaj Golub 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
992df8bae1dSRodney W. Grimes 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
9931a43cff9SSean Bruno 			/*
9941a43cff9SSean Bruno 			 * XXX: How to deal with SO_REUSEPORT_LB here?
9951a43cff9SSean Bruno 			 * Treat same as SO_REUSEPORT for now.
9961a43cff9SSean Bruno 			 */
9971a43cff9SSean Bruno 			if ((so->so_options &
9981a43cff9SSean Bruno 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
9991a43cff9SSean Bruno 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
1000df8bae1dSRodney W. Grimes 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
1001df8bae1dSRodney W. Grimes 			sin->sin_port = 0;		/* yech... */
100283103a73SAndrew R. Reiter 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
10034209e01aSAdrian Chadd 			/*
10044209e01aSAdrian Chadd 			 * Is the address a local IP address?
1005f44270e7SPawel Jakub Dawidek 			 * If INP_BINDANY is set, then the socket may be bound
10068696873dSAdrian Chadd 			 * to any endpoint address, local or not.
10074209e01aSAdrian Chadd 			 */
1008f44270e7SPawel Jakub Dawidek 			if ((inp->inp_flags & INP_BINDANY) == 0 &&
10098896f83aSRobert Watson 			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
1010df8bae1dSRodney W. Grimes 				return (EADDRNOTAVAIL);
1011df8bae1dSRodney W. Grimes 		}
10124b932371SIan Dowse 		laddr = sin->sin_addr;
1013df8bae1dSRodney W. Grimes 		if (lport) {
1014df8bae1dSRodney W. Grimes 			struct inpcb *t;
1015ae0e7143SRobert Watson 			struct tcptw *tw;
1016ae0e7143SRobert Watson 
1017df8bae1dSRodney W. Grimes 			/* GROSS */
1018603724d3SBjoern A. Zeeb 			if (ntohs(lport) <= V_ipport_reservedhigh &&
1019603724d3SBjoern A. Zeeb 			    ntohs(lport) >= V_ipport_reservedlow &&
1020cc426dd3SMateusz Guzik 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
10212469dd60SGarrett Wollman 				return (EACCES);
1022835d4b89SPawel Jakub Dawidek 			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
1023cc426dd3SMateusz Guzik 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
1024078b7042SBjoern A. Zeeb 				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
1025413628a7SBjoern A. Zeeb 				    lport, INPLOOKUP_WILDCARD, cred);
1026340c35deSJonathan Lemon 	/*
1027340c35deSJonathan Lemon 	 * XXX
1028340c35deSJonathan Lemon 	 * This entire block sorely needs a rewrite.
1029340c35deSJonathan Lemon 	 */
10304cc20ab1SSeigo Tanimura 				if (t &&
10310a100a6fSAdrian Chadd 				    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
1032ad71fe3cSRobert Watson 				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
10334658dc83SYaroslav Tykhiy 				    (so->so_type != SOCK_STREAM ||
10344658dc83SYaroslav Tykhiy 				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
10354cc20ab1SSeigo Tanimura 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
103652b65dbeSBill Fenner 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
10371a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT) ||
10381a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
103986d02c5cSBjoern A. Zeeb 				    (inp->inp_cred->cr_uid !=
104086d02c5cSBjoern A. Zeeb 				     t->inp_cred->cr_uid))
10414049a042SGuido van Rooij 					return (EADDRINUSE);
10420a100a6fSAdrian Chadd 
10430a100a6fSAdrian Chadd 				/*
10440a100a6fSAdrian Chadd 				 * If the socket is a BINDMULTI socket, then
10450a100a6fSAdrian Chadd 				 * the credentials need to match and the
10460a100a6fSAdrian Chadd 				 * original socket also has to have been bound
10470a100a6fSAdrian Chadd 				 * with BINDMULTI.
10480a100a6fSAdrian Chadd 				 */
10490a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
10500a100a6fSAdrian Chadd 					return (EADDRINUSE);
10514049a042SGuido van Rooij 			}
1052c3229e05SDavid Greenman 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
105368e0d7e0SRobert Watson 			    lport, lookupflags, cred);
1054ad71fe3cSRobert Watson 			if (t && (t->inp_flags & INP_TIMEWAIT)) {
1055ae0e7143SRobert Watson 				/*
1056ae0e7143SRobert Watson 				 * XXXRW: If an incpb has had its timewait
1057ae0e7143SRobert Watson 				 * state recycled, we treat the address as
1058ae0e7143SRobert Watson 				 * being in use (for now).  This is better
1059ae0e7143SRobert Watson 				 * than a panic, but not desirable.
1060ae0e7143SRobert Watson 				 */
1061ec95b709SMikolaj Golub 				tw = intotw(t);
1062ae0e7143SRobert Watson 				if (tw == NULL ||
10631a43cff9SSean Bruno 				    ((reuseport & tw->tw_so_options) == 0 &&
10641a43cff9SSean Bruno 					(reuseport_lb &
10651a43cff9SSean Bruno 				            tw->tw_so_options) == 0)) {
1066340c35deSJonathan Lemon 					return (EADDRINUSE);
10671a43cff9SSean Bruno 				}
10680a100a6fSAdrian Chadd 			} else if (t &&
10690a100a6fSAdrian Chadd 				   ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
10701a43cff9SSean Bruno 				   (reuseport & inp_so_options(t)) == 0 &&
10711a43cff9SSean Bruno 				   (reuseport_lb & inp_so_options(t)) == 0) {
1072e3fd5ffdSRobert Watson #ifdef INET6
107333841545SHajimu UMEMOTO 				if (ntohl(sin->sin_addr.s_addr) !=
1074cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
1075cfa1ca9dSYoshinobu Inoue 				    ntohl(t->inp_laddr.s_addr) !=
1076cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
1077fc06cd42SMikolaj Golub 				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
1078fc06cd42SMikolaj Golub 				    (t->inp_vflag & INP_IPV6PROTO) == 0)
1079e3fd5ffdSRobert Watson #endif
1080df8bae1dSRodney W. Grimes 						return (EADDRINUSE);
10810a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
10820a100a6fSAdrian Chadd 					return (EADDRINUSE);
1083df8bae1dSRodney W. Grimes 			}
1084cfa1ca9dSYoshinobu Inoue 		}
1085df8bae1dSRodney W. Grimes 	}
10864b932371SIan Dowse 	if (*lportp != 0)
10874b932371SIan Dowse 		lport = *lportp;
108833b3ac06SPeter Wemm 	if (lport == 0) {
10894616026fSErmal Luçi 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1090efc76f72SBjoern A. Zeeb 		if (error != 0)
1091efc76f72SBjoern A. Zeeb 			return (error);
109233b3ac06SPeter Wemm 	}
10934b932371SIan Dowse 	*laddrp = laddr.s_addr;
10944b932371SIan Dowse 	*lportp = lport;
1095df8bae1dSRodney W. Grimes 	return (0);
1096df8bae1dSRodney W. Grimes }
1097df8bae1dSRodney W. Grimes 
1098999f1343SGarrett Wollman /*
10995200e00eSIan Dowse  * Connect from a socket to a specified address.
11005200e00eSIan Dowse  * Both address and port must be specified in argument sin.
11015200e00eSIan Dowse  * If don't have a local address for this socket yet,
11025200e00eSIan Dowse  * then pick one.
1103999f1343SGarrett Wollman  */
1104999f1343SGarrett Wollman int
1105db0ac6deSCy Schubert in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred,
1106db0ac6deSCy Schubert     bool rehash)
1107999f1343SGarrett Wollman {
11085200e00eSIan Dowse 	u_short lport, fport;
11095200e00eSIan Dowse 	in_addr_t laddr, faddr;
11105200e00eSIan Dowse 	int anonport, error;
1111df8bae1dSRodney W. Grimes 
11128501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1113fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
111427f74fd0SRobert Watson 
11155200e00eSIan Dowse 	lport = inp->inp_lport;
11165200e00eSIan Dowse 	laddr = inp->inp_laddr.s_addr;
11175200e00eSIan Dowse 	anonport = (lport == 0);
11185200e00eSIan Dowse 	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
1119b0330ed9SPawel Jakub Dawidek 	    NULL, cred);
11205200e00eSIan Dowse 	if (error)
11215200e00eSIan Dowse 		return (error);
11225200e00eSIan Dowse 
11235200e00eSIan Dowse 	/* Do the initial binding of the local address if required. */
11245200e00eSIan Dowse 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1125fe1274eeSMichael Tuexen 		KASSERT(rehash == true,
1126fe1274eeSMichael Tuexen 		    ("Rehashing required for unbound inps"));
11275200e00eSIan Dowse 		inp->inp_lport = lport;
11285200e00eSIan Dowse 		inp->inp_laddr.s_addr = laddr;
11295200e00eSIan Dowse 		if (in_pcbinshash(inp) != 0) {
11305200e00eSIan Dowse 			inp->inp_laddr.s_addr = INADDR_ANY;
11315200e00eSIan Dowse 			inp->inp_lport = 0;
11325200e00eSIan Dowse 			return (EAGAIN);
11335200e00eSIan Dowse 		}
11345200e00eSIan Dowse 	}
11355200e00eSIan Dowse 
11365200e00eSIan Dowse 	/* Commit the remaining changes. */
11375200e00eSIan Dowse 	inp->inp_lport = lport;
11385200e00eSIan Dowse 	inp->inp_laddr.s_addr = laddr;
11395200e00eSIan Dowse 	inp->inp_faddr.s_addr = faddr;
11405200e00eSIan Dowse 	inp->inp_fport = fport;
1141fe1274eeSMichael Tuexen 	if (rehash) {
1142db0ac6deSCy Schubert 		in_pcbrehash(inp);
1143fe1274eeSMichael Tuexen 	} else {
1144db0ac6deSCy Schubert 		in_pcbinshash(inp);
1145fe1274eeSMichael Tuexen 	}
11462cb64cb2SGeorge V. Neville-Neil 
11475200e00eSIan Dowse 	if (anonport)
11485200e00eSIan Dowse 		inp->inp_flags |= INP_ANONPORT;
11495200e00eSIan Dowse 	return (0);
11505200e00eSIan Dowse }
11515200e00eSIan Dowse 
11525200e00eSIan Dowse /*
11530895aec3SBjoern A. Zeeb  * Do proper source address selection on an unbound socket in case
11540895aec3SBjoern A. Zeeb  * of connect. Take jails into account as well.
11550895aec3SBjoern A. Zeeb  */
1156ae190832SSteven Hartland int
11570895aec3SBjoern A. Zeeb in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
11580895aec3SBjoern A. Zeeb     struct ucred *cred)
11590895aec3SBjoern A. Zeeb {
11600895aec3SBjoern A. Zeeb 	struct ifaddr *ifa;
11610895aec3SBjoern A. Zeeb 	struct sockaddr *sa;
11629ac7c6cfSAlexander V. Chernikov 	struct sockaddr_in *sin, dst;
11639ac7c6cfSAlexander V. Chernikov 	struct nhop_object *nh;
11640895aec3SBjoern A. Zeeb 	int error;
11650895aec3SBjoern A. Zeeb 
1166c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
1167413628a7SBjoern A. Zeeb 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1168592bcae8SBjoern A. Zeeb 	/*
1169592bcae8SBjoern A. Zeeb 	 * Bypass source address selection and use the primary jail IP
1170592bcae8SBjoern A. Zeeb 	 * if requested.
1171592bcae8SBjoern A. Zeeb 	 */
1172592bcae8SBjoern A. Zeeb 	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1173592bcae8SBjoern A. Zeeb 		return (0);
1174592bcae8SBjoern A. Zeeb 
11750895aec3SBjoern A. Zeeb 	error = 0;
11760895aec3SBjoern A. Zeeb 
11779ac7c6cfSAlexander V. Chernikov 	nh = NULL;
11789ac7c6cfSAlexander V. Chernikov 	bzero(&dst, sizeof(dst));
11799ac7c6cfSAlexander V. Chernikov 	sin = &dst;
11800895aec3SBjoern A. Zeeb 	sin->sin_family = AF_INET;
11810895aec3SBjoern A. Zeeb 	sin->sin_len = sizeof(struct sockaddr_in);
11820895aec3SBjoern A. Zeeb 	sin->sin_addr.s_addr = faddr->s_addr;
11830895aec3SBjoern A. Zeeb 
11840895aec3SBjoern A. Zeeb 	/*
11850895aec3SBjoern A. Zeeb 	 * If route is known our src addr is taken from the i/f,
11860895aec3SBjoern A. Zeeb 	 * else punt.
11870895aec3SBjoern A. Zeeb 	 *
11880895aec3SBjoern A. Zeeb 	 * Find out route to destination.
11890895aec3SBjoern A. Zeeb 	 */
11900895aec3SBjoern A. Zeeb 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
11919ac7c6cfSAlexander V. Chernikov 		nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
11929ac7c6cfSAlexander V. Chernikov 		    0, NHR_NONE, 0);
11930895aec3SBjoern A. Zeeb 
11940895aec3SBjoern A. Zeeb 	/*
11950895aec3SBjoern A. Zeeb 	 * If we found a route, use the address corresponding to
11960895aec3SBjoern A. Zeeb 	 * the outgoing interface.
11970895aec3SBjoern A. Zeeb 	 *
11980895aec3SBjoern A. Zeeb 	 * Otherwise assume faddr is reachable on a directly connected
11990895aec3SBjoern A. Zeeb 	 * network and try to find a corresponding interface to take
12000895aec3SBjoern A. Zeeb 	 * the source address from.
12010895aec3SBjoern A. Zeeb 	 */
12029ac7c6cfSAlexander V. Chernikov 	if (nh == NULL || nh->nh_ifp == NULL) {
12038c0fec80SRobert Watson 		struct in_ifaddr *ia;
12040895aec3SBjoern A. Zeeb 		struct ifnet *ifp;
12050895aec3SBjoern A. Zeeb 
12064f8585e0SAlan Somers 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
120758a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
12084f6c66ccSMatt Macy 		if (ia == NULL) {
12094f8585e0SAlan Somers 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
121058a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
12114f6c66ccSMatt Macy 		}
12120895aec3SBjoern A. Zeeb 		if (ia == NULL) {
12130895aec3SBjoern A. Zeeb 			error = ENETUNREACH;
12140895aec3SBjoern A. Zeeb 			goto done;
12150895aec3SBjoern A. Zeeb 		}
12160895aec3SBjoern A. Zeeb 
12170304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
12180895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12190895aec3SBjoern A. Zeeb 			goto done;
12200895aec3SBjoern A. Zeeb 		}
12210895aec3SBjoern A. Zeeb 
12220895aec3SBjoern A. Zeeb 		ifp = ia->ia_ifp;
12230895aec3SBjoern A. Zeeb 		ia = NULL;
1224d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12250895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12260895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12270895aec3SBjoern A. Zeeb 				continue;
12280895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1229b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12300895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12310895aec3SBjoern A. Zeeb 				break;
12320895aec3SBjoern A. Zeeb 			}
12330895aec3SBjoern A. Zeeb 		}
12340895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12350895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12360895aec3SBjoern A. Zeeb 			goto done;
12370895aec3SBjoern A. Zeeb 		}
12380895aec3SBjoern A. Zeeb 
12390895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1240b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12410895aec3SBjoern A. Zeeb 		goto done;
12420895aec3SBjoern A. Zeeb 	}
12430895aec3SBjoern A. Zeeb 
12440895aec3SBjoern A. Zeeb 	/*
12450895aec3SBjoern A. Zeeb 	 * If the outgoing interface on the route found is not
12460895aec3SBjoern A. Zeeb 	 * a loopback interface, use the address from that interface.
12470895aec3SBjoern A. Zeeb 	 * In case of jails do those three steps:
12480895aec3SBjoern A. Zeeb 	 * 1. check if the interface address belongs to the jail. If so use it.
12490895aec3SBjoern A. Zeeb 	 * 2. check if we have any address on the outgoing interface
12500895aec3SBjoern A. Zeeb 	 *    belonging to this jail. If so use it.
12510895aec3SBjoern A. Zeeb 	 * 3. as a last resort return the 'default' jail address.
12520895aec3SBjoern A. Zeeb 	 */
12539ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
12548c0fec80SRobert Watson 		struct in_ifaddr *ia;
12559317b04eSRobert Watson 		struct ifnet *ifp;
12560895aec3SBjoern A. Zeeb 
12570895aec3SBjoern A. Zeeb 		/* If not jailed, use the default returned. */
12580304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
12599ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
12600895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12610895aec3SBjoern A. Zeeb 			goto done;
12620895aec3SBjoern A. Zeeb 		}
12630895aec3SBjoern A. Zeeb 
12640895aec3SBjoern A. Zeeb 		/* Jailed. */
12650895aec3SBjoern A. Zeeb 		/* 1. Check if the iface address belongs to the jail. */
12669ac7c6cfSAlexander V. Chernikov 		sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1267b89e82ddSJamie Gritton 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12689ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
12690895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12700895aec3SBjoern A. Zeeb 			goto done;
12710895aec3SBjoern A. Zeeb 		}
12720895aec3SBjoern A. Zeeb 
12730895aec3SBjoern A. Zeeb 		/*
12740895aec3SBjoern A. Zeeb 		 * 2. Check if we have any address on the outgoing interface
12750895aec3SBjoern A. Zeeb 		 *    belonging to this jail.
12760895aec3SBjoern A. Zeeb 		 */
12778c0fec80SRobert Watson 		ia = NULL;
12789ac7c6cfSAlexander V. Chernikov 		ifp = nh->nh_ifp;
1279d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12800895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12810895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12820895aec3SBjoern A. Zeeb 				continue;
12830895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1284b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12850895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12860895aec3SBjoern A. Zeeb 				break;
12870895aec3SBjoern A. Zeeb 			}
12880895aec3SBjoern A. Zeeb 		}
12890895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12900895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12910895aec3SBjoern A. Zeeb 			goto done;
12920895aec3SBjoern A. Zeeb 		}
12930895aec3SBjoern A. Zeeb 
12940895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1295b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12960895aec3SBjoern A. Zeeb 		goto done;
12970895aec3SBjoern A. Zeeb 	}
12980895aec3SBjoern A. Zeeb 
12990895aec3SBjoern A. Zeeb 	/*
13000895aec3SBjoern A. Zeeb 	 * The outgoing interface is marked with 'loopback net', so a route
13010895aec3SBjoern A. Zeeb 	 * to ourselves is here.
13020895aec3SBjoern A. Zeeb 	 * Try to find the interface of the destination address and then
13030895aec3SBjoern A. Zeeb 	 * take the address from there. That interface is not necessarily
13040895aec3SBjoern A. Zeeb 	 * a loopback interface.
13050895aec3SBjoern A. Zeeb 	 * In case of jails, check that it is an address of the jail
13060895aec3SBjoern A. Zeeb 	 * and if we cannot find, fall back to the 'default' jail address.
13070895aec3SBjoern A. Zeeb 	 */
13089ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
13098c0fec80SRobert Watson 		struct in_ifaddr *ia;
13100895aec3SBjoern A. Zeeb 
13119ac7c6cfSAlexander V. Chernikov 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
131258a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
13130895aec3SBjoern A. Zeeb 		if (ia == NULL)
13149ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
131558a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
1316f0bb05fcSQing Li 		if (ia == NULL)
13179ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
13180895aec3SBjoern A. Zeeb 
13190304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
13200895aec3SBjoern A. Zeeb 			if (ia == NULL) {
13210895aec3SBjoern A. Zeeb 				error = ENETUNREACH;
13220895aec3SBjoern A. Zeeb 				goto done;
13230895aec3SBjoern A. Zeeb 			}
13240895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13250895aec3SBjoern A. Zeeb 			goto done;
13260895aec3SBjoern A. Zeeb 		}
13270895aec3SBjoern A. Zeeb 
13280895aec3SBjoern A. Zeeb 		/* Jailed. */
13290895aec3SBjoern A. Zeeb 		if (ia != NULL) {
13300895aec3SBjoern A. Zeeb 			struct ifnet *ifp;
13310895aec3SBjoern A. Zeeb 
13320895aec3SBjoern A. Zeeb 			ifp = ia->ia_ifp;
13330895aec3SBjoern A. Zeeb 			ia = NULL;
1334d7c5a620SMatt Macy 			CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
13350895aec3SBjoern A. Zeeb 				sa = ifa->ifa_addr;
13360895aec3SBjoern A. Zeeb 				if (sa->sa_family != AF_INET)
13370895aec3SBjoern A. Zeeb 					continue;
13380895aec3SBjoern A. Zeeb 				sin = (struct sockaddr_in *)sa;
1339b89e82ddSJamie Gritton 				if (prison_check_ip4(cred,
1340b89e82ddSJamie Gritton 				    &sin->sin_addr) == 0) {
13410895aec3SBjoern A. Zeeb 					ia = (struct in_ifaddr *)ifa;
13420895aec3SBjoern A. Zeeb 					break;
13430895aec3SBjoern A. Zeeb 				}
13440895aec3SBjoern A. Zeeb 			}
13450895aec3SBjoern A. Zeeb 			if (ia != NULL) {
13460895aec3SBjoern A. Zeeb 				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13470895aec3SBjoern A. Zeeb 				goto done;
13480895aec3SBjoern A. Zeeb 			}
13490895aec3SBjoern A. Zeeb 		}
13500895aec3SBjoern A. Zeeb 
13510895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1352b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
13530895aec3SBjoern A. Zeeb 		goto done;
13540895aec3SBjoern A. Zeeb 	}
13550895aec3SBjoern A. Zeeb 
13560895aec3SBjoern A. Zeeb done:
13570895aec3SBjoern A. Zeeb 	return (error);
13580895aec3SBjoern A. Zeeb }
13590895aec3SBjoern A. Zeeb 
13600895aec3SBjoern A. Zeeb /*
13615200e00eSIan Dowse  * Set up for a connect from a socket to the specified address.
13625200e00eSIan Dowse  * On entry, *laddrp and *lportp should contain the current local
13635200e00eSIan Dowse  * address and port for the PCB; these are updated to the values
13645200e00eSIan Dowse  * that should be placed in inp_laddr and inp_lport to complete
13655200e00eSIan Dowse  * the connect.
13665200e00eSIan Dowse  *
13675200e00eSIan Dowse  * On success, *faddrp and *fportp will be set to the remote address
13685200e00eSIan Dowse  * and port. These are not updated in the error case.
13695200e00eSIan Dowse  *
13705200e00eSIan Dowse  * If the operation fails because the connection already exists,
13715200e00eSIan Dowse  * *oinpp will be set to the PCB of that connection so that the
13725200e00eSIan Dowse  * caller can decide to override it. In all other cases, *oinpp
13735200e00eSIan Dowse  * is set to NULL.
13745200e00eSIan Dowse  */
13755200e00eSIan Dowse int
1376136d4f1cSRobert Watson in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1377136d4f1cSRobert Watson     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1378136d4f1cSRobert Watson     struct inpcb **oinpp, struct ucred *cred)
13795200e00eSIan Dowse {
13805200e00eSIan Dowse 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
13815200e00eSIan Dowse 	struct in_ifaddr *ia;
13825200e00eSIan Dowse 	struct inpcb *oinp;
1383b89e82ddSJamie Gritton 	struct in_addr laddr, faddr;
13845200e00eSIan Dowse 	u_short lport, fport;
13855200e00eSIan Dowse 	int error;
13865200e00eSIan Dowse 
1387f161d294SMark Johnston 	KASSERT(sin->sin_family == AF_INET,
1388f161d294SMark Johnston 	    ("%s: invalid address family for %p", __func__, sin));
1389f161d294SMark Johnston 	KASSERT(sin->sin_len == sizeof(*sin),
1390f161d294SMark Johnston 	    ("%s: invalid address length for %p", __func__, sin));
1391f161d294SMark Johnston 
13928501a69cSRobert Watson 	/*
13938501a69cSRobert Watson 	 * Because a global state change doesn't actually occur here, a read
13948501a69cSRobert Watson 	 * lock is sufficient.
13958501a69cSRobert Watson 	 */
1396c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
139727f74fd0SRobert Watson 	INP_LOCK_ASSERT(inp);
1398fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
139927f74fd0SRobert Watson 
14005200e00eSIan Dowse 	if (oinpp != NULL)
14015200e00eSIan Dowse 		*oinpp = NULL;
1402df8bae1dSRodney W. Grimes 	if (sin->sin_port == 0)
1403df8bae1dSRodney W. Grimes 		return (EADDRNOTAVAIL);
14045200e00eSIan Dowse 	laddr.s_addr = *laddrp;
14055200e00eSIan Dowse 	lport = *lportp;
14065200e00eSIan Dowse 	faddr = sin->sin_addr;
14075200e00eSIan Dowse 	fport = sin->sin_port;
14080c325f53SAlexander V. Chernikov #ifdef ROUTE_MPATH
14090c325f53SAlexander V. Chernikov 	if (CALC_FLOWID_OUTBOUND) {
14100c325f53SAlexander V. Chernikov 		uint32_t hash_val, hash_type;
14110895aec3SBjoern A. Zeeb 
14120c325f53SAlexander V. Chernikov 		hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
14130c325f53SAlexander V. Chernikov 		    inp->inp_socket->so_proto->pr_protocol, &hash_type);
14140c325f53SAlexander V. Chernikov 
14150c325f53SAlexander V. Chernikov 		inp->inp_flowid = hash_val;
14160c325f53SAlexander V. Chernikov 		inp->inp_flowtype = hash_type;
14170c325f53SAlexander V. Chernikov 	}
14180c325f53SAlexander V. Chernikov #endif
1419d7c5a620SMatt Macy 	if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1420df8bae1dSRodney W. Grimes 		/*
1421df8bae1dSRodney W. Grimes 		 * If the destination address is INADDR_ANY,
1422df8bae1dSRodney W. Grimes 		 * use the primary local address.
1423df8bae1dSRodney W. Grimes 		 * If the supplied address is INADDR_BROADCAST,
1424df8bae1dSRodney W. Grimes 		 * and the primary interface supports broadcast,
1425df8bae1dSRodney W. Grimes 		 * choose the broadcast address for that interface.
1426df8bae1dSRodney W. Grimes 		 */
1427413628a7SBjoern A. Zeeb 		if (faddr.s_addr == INADDR_ANY) {
1428413628a7SBjoern A. Zeeb 			faddr =
1429d7c5a620SMatt Macy 			    IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1430b89e82ddSJamie Gritton 			if (cred != NULL &&
1431b89e82ddSJamie Gritton 			    (error = prison_get_ip4(cred, &faddr)) != 0)
1432b89e82ddSJamie Gritton 				return (error);
14332d9cfabaSRobert Watson 		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1434d7c5a620SMatt Macy 			if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
14352d9cfabaSRobert Watson 			    IFF_BROADCAST)
1436d7c5a620SMatt Macy 				faddr = satosin(&CK_STAILQ_FIRST(
1437603724d3SBjoern A. Zeeb 				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
14382d9cfabaSRobert Watson 		}
1439df8bae1dSRodney W. Grimes 	}
14405200e00eSIan Dowse 	if (laddr.s_addr == INADDR_ANY) {
1441d79fdd98SDaniel Eischen 		error = in_pcbladdr(inp, &faddr, &laddr, cred);
1442df8bae1dSRodney W. Grimes 		/*
1443df8bae1dSRodney W. Grimes 		 * If the destination address is multicast and an outgoing
1444d79fdd98SDaniel Eischen 		 * interface has been set as a multicast option, prefer the
1445df8bae1dSRodney W. Grimes 		 * address of that interface as our source address.
1446df8bae1dSRodney W. Grimes 		 */
14475200e00eSIan Dowse 		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1448df8bae1dSRodney W. Grimes 		    inp->inp_moptions != NULL) {
1449df8bae1dSRodney W. Grimes 			struct ip_moptions *imo;
1450df8bae1dSRodney W. Grimes 			struct ifnet *ifp;
1451df8bae1dSRodney W. Grimes 
1452df8bae1dSRodney W. Grimes 			imo = inp->inp_moptions;
1453df8bae1dSRodney W. Grimes 			if (imo->imo_multicast_ifp != NULL) {
1454df8bae1dSRodney W. Grimes 				ifp = imo->imo_multicast_ifp;
1455d7c5a620SMatt Macy 				CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1456e691be70SDaniel Eischen 					if ((ia->ia_ifp == ifp) &&
1457e691be70SDaniel Eischen 					    (cred == NULL ||
1458e691be70SDaniel Eischen 					    prison_check_ip4(cred,
1459e691be70SDaniel Eischen 					    &ia->ia_addr.sin_addr) == 0))
1460df8bae1dSRodney W. Grimes 						break;
1461e691be70SDaniel Eischen 				}
1462e691be70SDaniel Eischen 				if (ia == NULL)
1463d79fdd98SDaniel Eischen 					error = EADDRNOTAVAIL;
1464e691be70SDaniel Eischen 				else {
14655200e00eSIan Dowse 					laddr = ia->ia_addr.sin_addr;
1466d79fdd98SDaniel Eischen 					error = 0;
1467999f1343SGarrett Wollman 				}
1468d79fdd98SDaniel Eischen 			}
1469d79fdd98SDaniel Eischen 		}
147004215ed2SRandall Stewart 		if (error)
147104215ed2SRandall Stewart 			return (error);
14720895aec3SBjoern A. Zeeb 	}
1473a034518aSAndrew Gallatin 
147425102351SMike Karels 	if (lport != 0) {
147525102351SMike Karels 		oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
1476a034518aSAndrew Gallatin 		    fport, laddr, lport, 0, NULL, M_NODOM);
14775200e00eSIan Dowse 		if (oinp != NULL) {
14785200e00eSIan Dowse 			if (oinpp != NULL)
14795200e00eSIan Dowse 				*oinpp = oinp;
1480df8bae1dSRodney W. Grimes 			return (EADDRINUSE);
1481c3229e05SDavid Greenman 		}
148225102351SMike Karels 	} else {
148325102351SMike Karels 		struct sockaddr_in lsin, fsin;
148425102351SMike Karels 
148525102351SMike Karels 		bzero(&lsin, sizeof(lsin));
148625102351SMike Karels 		bzero(&fsin, sizeof(fsin));
148725102351SMike Karels 		lsin.sin_family = AF_INET;
148825102351SMike Karels 		lsin.sin_addr = laddr;
148925102351SMike Karels 		fsin.sin_family = AF_INET;
149025102351SMike Karels 		fsin.sin_addr = faddr;
149125102351SMike Karels 		error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
149225102351SMike Karels 		    &lport, (struct sockaddr *)& fsin, fport, cred,
149325102351SMike Karels 		    INPLOOKUP_WILDCARD);
14945a903f8dSPierre Beyssac 		if (error)
14955a903f8dSPierre Beyssac 			return (error);
14965a903f8dSPierre Beyssac 	}
14975200e00eSIan Dowse 	*laddrp = laddr.s_addr;
14985200e00eSIan Dowse 	*lportp = lport;
14995200e00eSIan Dowse 	*faddrp = faddr.s_addr;
15005200e00eSIan Dowse 	*fportp = fport;
1501df8bae1dSRodney W. Grimes 	return (0);
1502df8bae1dSRodney W. Grimes }
1503df8bae1dSRodney W. Grimes 
150426f9a767SRodney W. Grimes void
1505136d4f1cSRobert Watson in_pcbdisconnect(struct inpcb *inp)
1506df8bae1dSRodney W. Grimes {
15076b348152SRobert Watson 
15088501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1509fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1510df8bae1dSRodney W. Grimes 
1511df8bae1dSRodney W. Grimes 	inp->inp_faddr.s_addr = INADDR_ANY;
1512df8bae1dSRodney W. Grimes 	inp->inp_fport = 0;
151315bd2b43SDavid Greenman 	in_pcbrehash(inp);
1514df8bae1dSRodney W. Grimes }
151583e521ecSBjoern A. Zeeb #endif /* INET */
1516df8bae1dSRodney W. Grimes 
15174c7c478dSRobert Watson /*
151828696211SRobert Watson  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1519c0a211c5SRobert Watson  * For most protocols, this will be invoked immediately prior to calling
152028696211SRobert Watson  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
152128696211SRobert Watson  * socket, in which case in_pcbfree() is deferred.
15224c7c478dSRobert Watson  */
152326f9a767SRodney W. Grimes void
1524136d4f1cSRobert Watson in_pcbdetach(struct inpcb *inp)
1525df8bae1dSRodney W. Grimes {
15264c7c478dSRobert Watson 
1527a7df09e8SBjoern A. Zeeb 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1528c0a211c5SRobert Watson 
1529f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
1530f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag != NULL)
1531f3e7afe2SHans Petter Selasky 		in_pcbdetach_txrtlmt(inp);
1532f3e7afe2SHans Petter Selasky #endif
15334c7c478dSRobert Watson 	inp->inp_socket->so_pcb = NULL;
15344c7c478dSRobert Watson 	inp->inp_socket = NULL;
15354c7c478dSRobert Watson }
15364c7c478dSRobert Watson 
1537c0a211c5SRobert Watson /*
1538db0ac6deSCy Schubert  * inpcb hash lookups are protected by SMR section.
1539db0ac6deSCy Schubert  *
1540db0ac6deSCy Schubert  * Once desired pcb has been found, switching from SMR section to a pcb
1541db0ac6deSCy Schubert  * lock is performed with inp_smr_lock(). We can not use INP_(W|R)LOCK
1542db0ac6deSCy Schubert  * here because SMR is a critical section.
1543db0ac6deSCy Schubert  * In 99%+ cases inp_smr_lock() would obtain the lock immediately.
1544db0ac6deSCy Schubert  */
1545db0ac6deSCy Schubert static inline void
1546db0ac6deSCy Schubert inp_lock(struct inpcb *inp, const inp_lookup_t lock)
1547db0ac6deSCy Schubert {
1548db0ac6deSCy Schubert 
1549db0ac6deSCy Schubert 	lock == INPLOOKUP_RLOCKPCB ?
1550db0ac6deSCy Schubert 	    rw_rlock(&inp->inp_lock) : rw_wlock(&inp->inp_lock);
1551db0ac6deSCy Schubert }
1552db0ac6deSCy Schubert 
1553db0ac6deSCy Schubert static inline void
1554db0ac6deSCy Schubert inp_unlock(struct inpcb *inp, const inp_lookup_t lock)
1555db0ac6deSCy Schubert {
1556db0ac6deSCy Schubert 
1557db0ac6deSCy Schubert 	lock == INPLOOKUP_RLOCKPCB ?
1558db0ac6deSCy Schubert 	    rw_runlock(&inp->inp_lock) : rw_wunlock(&inp->inp_lock);
1559db0ac6deSCy Schubert }
1560db0ac6deSCy Schubert 
1561db0ac6deSCy Schubert static inline int
1562db0ac6deSCy Schubert inp_trylock(struct inpcb *inp, const inp_lookup_t lock)
1563db0ac6deSCy Schubert {
1564db0ac6deSCy Schubert 
1565db0ac6deSCy Schubert 	return (lock == INPLOOKUP_RLOCKPCB ?
1566db0ac6deSCy Schubert 	    rw_try_rlock(&inp->inp_lock) : rw_try_wlock(&inp->inp_lock));
1567db0ac6deSCy Schubert }
1568db0ac6deSCy Schubert 
1569db0ac6deSCy Schubert static inline bool
1570db0ac6deSCy Schubert in_pcbrele(struct inpcb *inp, const inp_lookup_t lock)
1571db0ac6deSCy Schubert {
1572db0ac6deSCy Schubert 
1573db0ac6deSCy Schubert 	return (lock == INPLOOKUP_RLOCKPCB ?
1574db0ac6deSCy Schubert 	    in_pcbrele_rlocked(inp) : in_pcbrele_wlocked(inp));
1575db0ac6deSCy Schubert }
1576db0ac6deSCy Schubert 
1577db0ac6deSCy Schubert bool
1578db0ac6deSCy Schubert inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock)
1579db0ac6deSCy Schubert {
1580db0ac6deSCy Schubert 
1581db0ac6deSCy Schubert 	MPASS(lock == INPLOOKUP_RLOCKPCB || lock == INPLOOKUP_WLOCKPCB);
1582db0ac6deSCy Schubert 	SMR_ASSERT_ENTERED(inp->inp_pcbinfo->ipi_smr);
1583db0ac6deSCy Schubert 
1584db0ac6deSCy Schubert 	if (__predict_true(inp_trylock(inp, lock))) {
1585db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1586db0ac6deSCy Schubert 			smr_exit(inp->inp_pcbinfo->ipi_smr);
1587db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1588db0ac6deSCy Schubert 			return (false);
1589db0ac6deSCy Schubert 		}
1590db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1591db0ac6deSCy Schubert 		return (true);
1592db0ac6deSCy Schubert 	}
1593db0ac6deSCy Schubert 
1594db0ac6deSCy Schubert 	if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1595db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1596db0ac6deSCy Schubert 		inp_lock(inp, lock);
1597db0ac6deSCy Schubert 		if (__predict_false(in_pcbrele(inp, lock)))
1598db0ac6deSCy Schubert 			return (false);
1599db0ac6deSCy Schubert 		/*
1600db0ac6deSCy Schubert 		 * inp acquired through refcount & lock for sure didn't went
1601db0ac6deSCy Schubert 		 * through uma_zfree().  However, it may have already went
1602db0ac6deSCy Schubert 		 * through in_pcbfree() and has another reference, that
1603db0ac6deSCy Schubert 		 * prevented its release by our in_pcbrele().
1604db0ac6deSCy Schubert 		 */
1605db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1606db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1607db0ac6deSCy Schubert 			return (false);
1608db0ac6deSCy Schubert 		}
1609db0ac6deSCy Schubert 		return (true);
1610db0ac6deSCy Schubert 	} else {
1611db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1612db0ac6deSCy Schubert 		return (false);
1613db0ac6deSCy Schubert 	}
1614db0ac6deSCy Schubert }
1615db0ac6deSCy Schubert 
1616db0ac6deSCy Schubert /*
1617db0ac6deSCy Schubert  * inp_next() - inpcb hash/list traversal iterator
1618db0ac6deSCy Schubert  *
1619db0ac6deSCy Schubert  * Requires initialized struct inpcb_iterator for context.
1620db0ac6deSCy Schubert  * The structure can be initialized with INP_ITERATOR() or INP_ALL_ITERATOR().
1621db0ac6deSCy Schubert  *
1622db0ac6deSCy Schubert  * - Iterator can have either write-lock or read-lock semantics, that can not
1623db0ac6deSCy Schubert  *   be changed later.
1624db0ac6deSCy Schubert  * - Iterator can iterate either over all pcbs list (INP_ALL_LIST), or through
1625db0ac6deSCy Schubert  *   a single hash slot.  Note: only rip_input() does the latter.
1626db0ac6deSCy Schubert  * - Iterator may have optional bool matching function.  The matching function
1627db0ac6deSCy Schubert  *   will be executed for each inpcb in the SMR context, so it can not acquire
1628db0ac6deSCy Schubert  *   locks and can safely access only immutable fields of inpcb.
1629db0ac6deSCy Schubert  *
1630db0ac6deSCy Schubert  * A fresh initialized iterator has NULL inpcb in its context and that
1631db0ac6deSCy Schubert  * means that inp_next() call would return the very first inpcb on the list
1632db0ac6deSCy Schubert  * locked with desired semantic.  In all following calls the context pointer
1633db0ac6deSCy Schubert  * shall hold the current inpcb pointer.  The KPI user is not supposed to
1634db0ac6deSCy Schubert  * unlock the current inpcb!  Upon end of traversal inp_next() will return NULL
1635db0ac6deSCy Schubert  * and write NULL to its context.  After end of traversal an iterator can be
1636db0ac6deSCy Schubert  * reused.
1637db0ac6deSCy Schubert  *
1638db0ac6deSCy Schubert  * List traversals have the following features/constraints:
1639db0ac6deSCy Schubert  * - New entries won't be seen, as they are always added to the head of a list.
1640db0ac6deSCy Schubert  * - Removed entries won't stop traversal as long as they are not added to
1641db0ac6deSCy Schubert  *   a different list. This is violated by in_pcbrehash().
1642db0ac6deSCy Schubert  */
1643db0ac6deSCy Schubert #define	II_LIST_FIRST(ipi, hash)					\
1644db0ac6deSCy Schubert 		(((hash) == INP_ALL_LIST) ?				\
1645db0ac6deSCy Schubert 		    CK_LIST_FIRST(&(ipi)->ipi_listhead) :		\
1646db0ac6deSCy Schubert 		    CK_LIST_FIRST(&(ipi)->ipi_hashbase[(hash)]))
1647db0ac6deSCy Schubert #define	II_LIST_NEXT(inp, hash)						\
1648db0ac6deSCy Schubert 		(((hash) == INP_ALL_LIST) ?				\
1649db0ac6deSCy Schubert 		    CK_LIST_NEXT((inp), inp_list) :			\
1650db0ac6deSCy Schubert 		    CK_LIST_NEXT((inp), inp_hash))
1651db0ac6deSCy Schubert #define	II_LOCK_ASSERT(inp, lock)					\
1652db0ac6deSCy Schubert 		rw_assert(&(inp)->inp_lock,				\
1653db0ac6deSCy Schubert 		    (lock) == INPLOOKUP_RLOCKPCB ?  RA_RLOCKED : RA_WLOCKED )
1654db0ac6deSCy Schubert struct inpcb *
1655db0ac6deSCy Schubert inp_next(struct inpcb_iterator *ii)
1656db0ac6deSCy Schubert {
1657db0ac6deSCy Schubert 	const struct inpcbinfo *ipi = ii->ipi;
1658db0ac6deSCy Schubert 	inp_match_t *match = ii->match;
1659db0ac6deSCy Schubert 	void *ctx = ii->ctx;
1660db0ac6deSCy Schubert 	inp_lookup_t lock = ii->lock;
1661db0ac6deSCy Schubert 	int hash = ii->hash;
1662db0ac6deSCy Schubert 	struct inpcb *inp;
1663db0ac6deSCy Schubert 
1664db0ac6deSCy Schubert 	if (ii->inp == NULL) {		/* First call. */
1665db0ac6deSCy Schubert 		smr_enter(ipi->ipi_smr);
1666db0ac6deSCy Schubert 		/* This is unrolled CK_LIST_FOREACH(). */
1667db0ac6deSCy Schubert 		for (inp = II_LIST_FIRST(ipi, hash);
1668db0ac6deSCy Schubert 		    inp != NULL;
1669db0ac6deSCy Schubert 		    inp = II_LIST_NEXT(inp, hash)) {
1670db0ac6deSCy Schubert 			if (match != NULL && (match)(inp, ctx) == false)
1671db0ac6deSCy Schubert 				continue;
1672db0ac6deSCy Schubert 			if (__predict_true(inp_smr_lock(inp, lock)))
1673db0ac6deSCy Schubert 				break;
1674db0ac6deSCy Schubert 			else {
1675db0ac6deSCy Schubert 				smr_enter(ipi->ipi_smr);
1676db0ac6deSCy Schubert 				MPASS(inp != II_LIST_FIRST(ipi, hash));
1677db0ac6deSCy Schubert 				inp = II_LIST_FIRST(ipi, hash);
1678430df2abSMichael Tuexen 				if (inp == NULL)
1679430df2abSMichael Tuexen 					break;
1680db0ac6deSCy Schubert 			}
1681db0ac6deSCy Schubert 		}
1682db0ac6deSCy Schubert 
1683db0ac6deSCy Schubert 		if (inp == NULL)
1684db0ac6deSCy Schubert 			smr_exit(ipi->ipi_smr);
1685db0ac6deSCy Schubert 		else
1686db0ac6deSCy Schubert 			ii->inp = inp;
1687db0ac6deSCy Schubert 
1688db0ac6deSCy Schubert 		return (inp);
1689db0ac6deSCy Schubert 	}
1690db0ac6deSCy Schubert 
1691db0ac6deSCy Schubert 	/* Not a first call. */
1692db0ac6deSCy Schubert 	smr_enter(ipi->ipi_smr);
1693db0ac6deSCy Schubert restart:
1694db0ac6deSCy Schubert 	inp = ii->inp;
1695db0ac6deSCy Schubert 	II_LOCK_ASSERT(inp, lock);
1696db0ac6deSCy Schubert next:
1697db0ac6deSCy Schubert 	inp = II_LIST_NEXT(inp, hash);
1698db0ac6deSCy Schubert 	if (inp == NULL) {
1699db0ac6deSCy Schubert 		smr_exit(ipi->ipi_smr);
1700db0ac6deSCy Schubert 		goto found;
1701db0ac6deSCy Schubert 	}
1702db0ac6deSCy Schubert 
1703db0ac6deSCy Schubert 	if (match != NULL && (match)(inp, ctx) == false)
1704db0ac6deSCy Schubert 		goto next;
1705db0ac6deSCy Schubert 
1706db0ac6deSCy Schubert 	if (__predict_true(inp_trylock(inp, lock))) {
1707db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1708db0ac6deSCy Schubert 			/*
1709db0ac6deSCy Schubert 			 * Entries are never inserted in middle of a list, thus
1710db0ac6deSCy Schubert 			 * as long as we are in SMR, we can continue traversal.
1711db0ac6deSCy Schubert 			 * Jump to 'restart' should yield in the same result,
1712db0ac6deSCy Schubert 			 * but could produce unnecessary looping.  Could this
1713db0ac6deSCy Schubert 			 * looping be unbound?
1714db0ac6deSCy Schubert 			 */
1715db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1716db0ac6deSCy Schubert 			goto next;
1717db0ac6deSCy Schubert 		} else {
1718db0ac6deSCy Schubert 			smr_exit(ipi->ipi_smr);
1719db0ac6deSCy Schubert 			goto found;
1720db0ac6deSCy Schubert 		}
1721db0ac6deSCy Schubert 	}
1722db0ac6deSCy Schubert 
1723db0ac6deSCy Schubert 	/*
1724db0ac6deSCy Schubert 	 * Can't obtain lock immediately, thus going hard.  Once we exit the
1725db0ac6deSCy Schubert 	 * SMR section we can no longer jump to 'next', and our only stable
1726db0ac6deSCy Schubert 	 * anchoring point is ii->inp, which we keep locked for this case, so
1727db0ac6deSCy Schubert 	 * we jump to 'restart'.
1728db0ac6deSCy Schubert 	 */
1729db0ac6deSCy Schubert 	if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1730db0ac6deSCy Schubert 		smr_exit(ipi->ipi_smr);
1731db0ac6deSCy Schubert 		inp_lock(inp, lock);
1732db0ac6deSCy Schubert 		if (__predict_false(in_pcbrele(inp, lock))) {
1733db0ac6deSCy Schubert 			smr_enter(ipi->ipi_smr);
1734db0ac6deSCy Schubert 			goto restart;
1735db0ac6deSCy Schubert 		}
1736db0ac6deSCy Schubert 		/*
1737db0ac6deSCy Schubert 		 * See comment in inp_smr_lock().
1738db0ac6deSCy Schubert 		 */
1739db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1740db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1741db0ac6deSCy Schubert 			smr_enter(ipi->ipi_smr);
1742db0ac6deSCy Schubert 			goto restart;
1743db0ac6deSCy Schubert 		}
1744db0ac6deSCy Schubert 	} else
1745db0ac6deSCy Schubert 		goto next;
1746db0ac6deSCy Schubert 
1747db0ac6deSCy Schubert found:
1748db0ac6deSCy Schubert 	inp_unlock(ii->inp, lock);
1749db0ac6deSCy Schubert 	ii->inp = inp;
1750db0ac6deSCy Schubert 
1751db0ac6deSCy Schubert 	return (ii->inp);
1752db0ac6deSCy Schubert }
1753db0ac6deSCy Schubert 
1754db0ac6deSCy Schubert /*
175579bdc6e5SRobert Watson  * in_pcbref() bumps the reference count on an inpcb in order to maintain
1756db0ac6deSCy Schubert  * stability of an inpcb pointer despite the inpcb lock being released or
1757db0ac6deSCy Schubert  * SMR section exited.
175879bdc6e5SRobert Watson  *
1759db0ac6deSCy Schubert  * To free a reference later in_pcbrele_(r|w)locked() must be performed.
1760c0a211c5SRobert Watson  */
176179bdc6e5SRobert Watson void
176279bdc6e5SRobert Watson in_pcbref(struct inpcb *inp)
17634c7c478dSRobert Watson {
1764db0ac6deSCy Schubert 	u_int old __diagused;
1765df8bae1dSRodney W. Grimes 
1766db0ac6deSCy Schubert 	old = refcount_acquire(&inp->inp_refcount);
1767db0ac6deSCy Schubert 	KASSERT(old > 0, ("%s: refcount 0", __func__));
176879bdc6e5SRobert Watson }
176979bdc6e5SRobert Watson 
177079bdc6e5SRobert Watson /*
1771db0ac6deSCy Schubert  * Drop a refcount on an inpcb elevated using in_pcbref(), potentially
1772db0ac6deSCy Schubert  * freeing the pcb, if the reference was very last.
177379bdc6e5SRobert Watson  */
1774db0ac6deSCy Schubert bool
177579bdc6e5SRobert Watson in_pcbrele_rlocked(struct inpcb *inp)
177679bdc6e5SRobert Watson {
177779bdc6e5SRobert Watson 
177879bdc6e5SRobert Watson 	INP_RLOCK_ASSERT(inp);
177979bdc6e5SRobert Watson 
1780db0ac6deSCy Schubert 	if (refcount_release(&inp->inp_refcount) == 0)
1781db0ac6deSCy Schubert 		return (false);
1782db0ac6deSCy Schubert 
1783db0ac6deSCy Schubert 	MPASS(inp->inp_flags & INP_FREED);
1784db0ac6deSCy Schubert 	MPASS(inp->inp_socket == NULL);
1785db0ac6deSCy Schubert 	MPASS(inp->inp_in_hpts == 0);
1786df4e91d3SGleb Smirnoff 	INP_RUNLOCK(inp);
1787db0ac6deSCy Schubert 	uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1788db0ac6deSCy Schubert 	return (true);
1789df4e91d3SGleb Smirnoff }
179079bdc6e5SRobert Watson 
1791db0ac6deSCy Schubert bool
179279bdc6e5SRobert Watson in_pcbrele_wlocked(struct inpcb *inp)
179379bdc6e5SRobert Watson {
179479bdc6e5SRobert Watson 
179579bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
179679bdc6e5SRobert Watson 
1797db0ac6deSCy Schubert 	if (refcount_release(&inp->inp_refcount) == 0)
1798db0ac6deSCy Schubert 		return (false);
1799db0ac6deSCy Schubert 
1800db0ac6deSCy Schubert 	MPASS(inp->inp_flags & INP_FREED);
1801db0ac6deSCy Schubert 	MPASS(inp->inp_socket == NULL);
1802db0ac6deSCy Schubert 	MPASS(inp->inp_in_hpts == 0);
1803edd0e0b0SFabien Thomas 	INP_WUNLOCK(inp);
1804db0ac6deSCy Schubert 	uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1805db0ac6deSCy Schubert 	return (true);
1806addf2b20SMatt Macy }
1807addf2b20SMatt Macy 
180879bdc6e5SRobert Watson /*
180979bdc6e5SRobert Watson  * Unconditionally schedule an inpcb to be freed by decrementing its
181079bdc6e5SRobert Watson  * reference count, which should occur only after the inpcb has been detached
181179bdc6e5SRobert Watson  * from its socket.  If another thread holds a temporary reference (acquired
181279bdc6e5SRobert Watson  * using in_pcbref()) then the free is deferred until that reference is
1813db0ac6deSCy Schubert  * released using in_pcbrele_(r|w)locked(), but the inpcb is still unlocked.
1814db0ac6deSCy Schubert  *  Almost all work, including removal from global lists, is done in this
1815db0ac6deSCy Schubert  * context, where the pcbinfo lock is held.
181679bdc6e5SRobert Watson  */
181779bdc6e5SRobert Watson void
181879bdc6e5SRobert Watson in_pcbfree(struct inpcb *inp)
181979bdc6e5SRobert Watson {
1820f42a83f2SMatt Macy 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1821db0ac6deSCy Schubert #ifdef INET
1822db0ac6deSCy Schubert 	struct ip_moptions *imo;
1823db0ac6deSCy Schubert #endif
1824db0ac6deSCy Schubert #ifdef INET6
1825db0ac6deSCy Schubert 	struct ip6_moptions *im6o;
1826db0ac6deSCy Schubert #endif
182745a48d07SJonathan T. Looney 
182879bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
1829db0ac6deSCy Schubert 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1830db0ac6deSCy Schubert 	KASSERT((inp->inp_flags & INP_FREED) == 0,
1831db0ac6deSCy Schubert 	    ("%s: called twice for pcb %p", __func__, inp));
1832db0ac6deSCy Schubert 
1833db0ac6deSCy Schubert 	inp->inp_flags |= INP_FREED;
1834db0ac6deSCy Schubert 	INP_INFO_WLOCK(pcbinfo);
1835db0ac6deSCy Schubert 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1836db0ac6deSCy Schubert 	pcbinfo->ipi_count--;
1837db0ac6deSCy Schubert 	CK_LIST_REMOVE(inp, inp_list);
1838db0ac6deSCy Schubert 	INP_INFO_WUNLOCK(pcbinfo);
1839db0ac6deSCy Schubert 
1840db0ac6deSCy Schubert 	if (inp->inp_flags & INP_INHASHLIST) {
1841db0ac6deSCy Schubert 		struct inpcbport *phd = inp->inp_phd;
1842db0ac6deSCy Schubert 
1843db0ac6deSCy Schubert 		INP_HASH_WLOCK(pcbinfo);
1844db0ac6deSCy Schubert 		/* XXX: Only do if SO_REUSEPORT_LB set? */
1845db0ac6deSCy Schubert 		in_pcbremlbgrouphash(inp);
1846db0ac6deSCy Schubert 
1847db0ac6deSCy Schubert 		CK_LIST_REMOVE(inp, inp_hash);
1848db0ac6deSCy Schubert 		CK_LIST_REMOVE(inp, inp_portlist);
1849db0ac6deSCy Schubert 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1850db0ac6deSCy Schubert 			CK_LIST_REMOVE(phd, phd_hash);
1851db0ac6deSCy Schubert 			uma_zfree_smr(pcbinfo->ipi_portzone, phd);
1852db0ac6deSCy Schubert 		}
1853db0ac6deSCy Schubert 		INP_HASH_WUNLOCK(pcbinfo);
1854db0ac6deSCy Schubert 		inp->inp_flags &= ~INP_INHASHLIST;
1855db0ac6deSCy Schubert 	}
1856db0ac6deSCy Schubert 
1857fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
1858db0ac6deSCy Schubert #ifdef MAC
1859db0ac6deSCy Schubert 	mac_inpcb_destroy(inp);
1860db0ac6deSCy Schubert #endif
1861db0ac6deSCy Schubert #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1862db0ac6deSCy Schubert 	if (inp->inp_sp != NULL)
1863db0ac6deSCy Schubert 		ipsec_delete_pcbpolicy(inp);
1864db0ac6deSCy Schubert #endif
1865db0ac6deSCy Schubert #ifdef INET
1866db0ac6deSCy Schubert 	if (inp->inp_options)
1867db0ac6deSCy Schubert 		(void)m_free(inp->inp_options);
1868db0ac6deSCy Schubert 	imo = inp->inp_moptions;
1869db0ac6deSCy Schubert #endif
1870db0ac6deSCy Schubert #ifdef INET6
1871db0ac6deSCy Schubert 	if (inp->inp_vflag & INP_IPV6PROTO) {
1872db0ac6deSCy Schubert 		ip6_freepcbopts(inp->in6p_outputopts);
1873db0ac6deSCy Schubert 		im6o = inp->in6p_moptions;
1874db0ac6deSCy Schubert 	} else
1875db0ac6deSCy Schubert 		im6o = NULL;
1876db0ac6deSCy Schubert #endif
1877db0ac6deSCy Schubert 
1878db0ac6deSCy Schubert 	if (__predict_false(in_pcbrele_wlocked(inp) == false)) {
1879cb6bb230SMatt Macy 		INP_WUNLOCK(inp);
1880db0ac6deSCy Schubert 	}
1881db0ac6deSCy Schubert #ifdef INET6
1882db0ac6deSCy Schubert 	ip6_freemoptions(im6o);
1883db0ac6deSCy Schubert #endif
1884db0ac6deSCy Schubert #ifdef INET
1885db0ac6deSCy Schubert 	inp_freemoptions(imo);
1886db0ac6deSCy Schubert #endif
1887eb93b99dSGleb Smirnoff 	/* Destruction is finalized in inpcb_dtor(). */
1888eb93b99dSGleb Smirnoff }
1889eb93b99dSGleb Smirnoff 
1890eb93b99dSGleb Smirnoff static void
1891eb93b99dSGleb Smirnoff inpcb_dtor(void *mem, int size, void *arg)
1892eb93b99dSGleb Smirnoff {
1893eb93b99dSGleb Smirnoff 	struct inpcb *inp = mem;
1894eb93b99dSGleb Smirnoff 
1895eb93b99dSGleb Smirnoff 	crfree(inp->inp_cred);
1896eb93b99dSGleb Smirnoff #ifdef INVARIANTS
1897eb93b99dSGleb Smirnoff 	inp->inp_cred = NULL;
1898eb93b99dSGleb Smirnoff #endif
1899eb93b99dSGleb Smirnoff }
1900eb93b99dSGleb Smirnoff 
1901eb93b99dSGleb Smirnoff /*
1902eb93b99dSGleb Smirnoff  * Different protocols initialize their inpcbs differently - giving
1903eb93b99dSGleb Smirnoff  * different name to the lock.  But they all are disposed the same.
1904eb93b99dSGleb Smirnoff  */
1905eb93b99dSGleb Smirnoff static void
1906eb93b99dSGleb Smirnoff inpcb_fini(void *mem, int size)
1907eb93b99dSGleb Smirnoff {
1908eb93b99dSGleb Smirnoff 	struct inpcb *inp = mem;
1909eb93b99dSGleb Smirnoff 
1910eb93b99dSGleb Smirnoff 	INP_LOCK_DESTROY(inp);
191128696211SRobert Watson }
191228696211SRobert Watson 
191328696211SRobert Watson /*
1914c0a211c5SRobert Watson  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1915c0a211c5SRobert Watson  * port reservation, and preventing it from being returned by inpcb lookups.
1916c0a211c5SRobert Watson  *
1917c0a211c5SRobert Watson  * It is used by TCP to mark an inpcb as unused and avoid future packet
1918c0a211c5SRobert Watson  * delivery or event notification when a socket remains open but TCP has
1919c0a211c5SRobert Watson  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1920c0a211c5SRobert Watson  * or a RST on the wire, and allows the port binding to be reused while still
1921c0a211c5SRobert Watson  * maintaining the invariant that so_pcb always points to a valid inpcb until
1922c0a211c5SRobert Watson  * in_pcbdetach().
1923c0a211c5SRobert Watson  *
1924c0a211c5SRobert Watson  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1925c0a211c5SRobert Watson  * in_pcbnotifyall() and in_pcbpurgeif0()?
192610702a28SRobert Watson  */
192710702a28SRobert Watson void
192810702a28SRobert Watson in_pcbdrop(struct inpcb *inp)
192910702a28SRobert Watson {
193010702a28SRobert Watson 
19318501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
19326573d758SMatt Macy #ifdef INVARIANTS
19336573d758SMatt Macy 	if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
19346573d758SMatt Macy 		MPASS(inp->inp_refcount > 1);
19356573d758SMatt Macy #endif
193610702a28SRobert Watson 
1937fa046d87SRobert Watson 	/*
1938fa046d87SRobert Watson 	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1939fa046d87SRobert Watson 	 * the hash lock...?
1940fa046d87SRobert Watson 	 */
1941ad71fe3cSRobert Watson 	inp->inp_flags |= INP_DROPPED;
1942111d57a6SRobert Watson 	if (inp->inp_flags & INP_INHASHLIST) {
194310702a28SRobert Watson 		struct inpcbport *phd = inp->inp_phd;
194410702a28SRobert Watson 
1945fa046d87SRobert Watson 		INP_HASH_WLOCK(inp->inp_pcbinfo);
19461a43cff9SSean Bruno 		in_pcbremlbgrouphash(inp);
1947b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_hash);
1948b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_portlist);
1949b872626dSMatt Macy 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1950b872626dSMatt Macy 			CK_LIST_REMOVE(phd, phd_hash);
1951db0ac6deSCy Schubert 			uma_zfree_smr(inp->inp_pcbinfo->ipi_portzone, phd);
195210702a28SRobert Watson 		}
1953fa046d87SRobert Watson 		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1954111d57a6SRobert Watson 		inp->inp_flags &= ~INP_INHASHLIST;
195510702a28SRobert Watson 	}
195610702a28SRobert Watson }
195710702a28SRobert Watson 
195867107f45SBjoern A. Zeeb #ifdef INET
195954d642bbSRobert Watson /*
196054d642bbSRobert Watson  * Common routines to return the socket addresses associated with inpcbs.
196154d642bbSRobert Watson  */
196226ef6ac4SDon Lewis struct sockaddr *
1963136d4f1cSRobert Watson in_sockaddr(in_port_t port, struct in_addr *addr_p)
196426ef6ac4SDon Lewis {
196526ef6ac4SDon Lewis 	struct sockaddr_in *sin;
196626ef6ac4SDon Lewis 
19671ede983cSDag-Erling Smørgrav 	sin = malloc(sizeof *sin, M_SONAME,
1968a163d034SWarner Losh 		M_WAITOK | M_ZERO);
196926ef6ac4SDon Lewis 	sin->sin_family = AF_INET;
197026ef6ac4SDon Lewis 	sin->sin_len = sizeof(*sin);
197126ef6ac4SDon Lewis 	sin->sin_addr = *addr_p;
197226ef6ac4SDon Lewis 	sin->sin_port = port;
197326ef6ac4SDon Lewis 
197426ef6ac4SDon Lewis 	return (struct sockaddr *)sin;
197526ef6ac4SDon Lewis }
197626ef6ac4SDon Lewis 
1977117bcae7SGarrett Wollman int
197854d642bbSRobert Watson in_getsockaddr(struct socket *so, struct sockaddr **nam)
1979df8bae1dSRodney W. Grimes {
1980136d4f1cSRobert Watson 	struct inpcb *inp;
198126ef6ac4SDon Lewis 	struct in_addr addr;
198226ef6ac4SDon Lewis 	in_port_t port;
198342fa505bSDavid Greenman 
1984fdc984f7STor Egge 	inp = sotoinpcb(so);
198554d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
19866466b28aSRobert Watson 
1987a69042a5SRobert Watson 	INP_RLOCK(inp);
198826ef6ac4SDon Lewis 	port = inp->inp_lport;
198926ef6ac4SDon Lewis 	addr = inp->inp_laddr;
1990a69042a5SRobert Watson 	INP_RUNLOCK(inp);
199142fa505bSDavid Greenman 
199226ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
1993117bcae7SGarrett Wollman 	return 0;
1994df8bae1dSRodney W. Grimes }
1995df8bae1dSRodney W. Grimes 
1996117bcae7SGarrett Wollman int
199754d642bbSRobert Watson in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1998df8bae1dSRodney W. Grimes {
1999136d4f1cSRobert Watson 	struct inpcb *inp;
200026ef6ac4SDon Lewis 	struct in_addr addr;
200126ef6ac4SDon Lewis 	in_port_t port;
200242fa505bSDavid Greenman 
2003fdc984f7STor Egge 	inp = sotoinpcb(so);
200454d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
20056466b28aSRobert Watson 
2006a69042a5SRobert Watson 	INP_RLOCK(inp);
200726ef6ac4SDon Lewis 	port = inp->inp_fport;
200826ef6ac4SDon Lewis 	addr = inp->inp_faddr;
2009a69042a5SRobert Watson 	INP_RUNLOCK(inp);
201042fa505bSDavid Greenman 
201126ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
2012117bcae7SGarrett Wollman 	return 0;
2013df8bae1dSRodney W. Grimes }
2014df8bae1dSRodney W. Grimes 
201526f9a767SRodney W. Grimes void
2016136d4f1cSRobert Watson in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
2017136d4f1cSRobert Watson     struct inpcb *(*notify)(struct inpcb *, int))
2018d1c54148SJesper Skriver {
2019f457d580SRobert Watson 	struct inpcb *inp, *inp_temp;
2020d1c54148SJesper Skriver 
20213dc7ebf9SJeffrey Hsu 	INP_INFO_WLOCK(pcbinfo);
2022db0ac6deSCy Schubert 	CK_LIST_FOREACH_SAFE(inp, &pcbinfo->ipi_listhead, inp_list, inp_temp) {
20238501a69cSRobert Watson 		INP_WLOCK(inp);
2024d1c54148SJesper Skriver #ifdef INET6
2025f76fcf6dSJeffrey Hsu 		if ((inp->inp_vflag & INP_IPV4) == 0) {
20268501a69cSRobert Watson 			INP_WUNLOCK(inp);
2027d1c54148SJesper Skriver 			continue;
2028f76fcf6dSJeffrey Hsu 		}
2029d1c54148SJesper Skriver #endif
2030d1c54148SJesper Skriver 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
2031f76fcf6dSJeffrey Hsu 		    inp->inp_socket == NULL) {
20328501a69cSRobert Watson 			INP_WUNLOCK(inp);
2033d1c54148SJesper Skriver 			continue;
2034d1c54148SJesper Skriver 		}
20353dc7ebf9SJeffrey Hsu 		if ((*notify)(inp, errno))
20368501a69cSRobert Watson 			INP_WUNLOCK(inp);
2037f76fcf6dSJeffrey Hsu 	}
20383dc7ebf9SJeffrey Hsu 	INP_INFO_WUNLOCK(pcbinfo);
2039d1c54148SJesper Skriver }
2040d1c54148SJesper Skriver 
2041db0ac6deSCy Schubert static bool
2042db0ac6deSCy Schubert inp_v4_multi_match(const struct inpcb *inp, void *v __unused)
2043db0ac6deSCy Schubert {
2044db0ac6deSCy Schubert 
2045db0ac6deSCy Schubert 	if ((inp->inp_vflag & INP_IPV4) && inp->inp_moptions != NULL)
2046db0ac6deSCy Schubert 		return (true);
2047db0ac6deSCy Schubert 	else
2048db0ac6deSCy Schubert 		return (false);
2049db0ac6deSCy Schubert }
2050db0ac6deSCy Schubert 
2051e43cc4aeSHajimu UMEMOTO void
2052136d4f1cSRobert Watson in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
2053e43cc4aeSHajimu UMEMOTO {
2054db0ac6deSCy Schubert 	struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
2055db0ac6deSCy Schubert 	    inp_v4_multi_match, NULL);
2056e43cc4aeSHajimu UMEMOTO 	struct inpcb *inp;
205759854ecfSHans Petter Selasky 	struct in_multi *inm;
205859854ecfSHans Petter Selasky 	struct in_mfilter *imf;
2059e43cc4aeSHajimu UMEMOTO 	struct ip_moptions *imo;
2060e43cc4aeSHajimu UMEMOTO 
2061db0ac6deSCy Schubert 	IN_MULTI_LOCK_ASSERT();
2062db0ac6deSCy Schubert 
2063db0ac6deSCy Schubert 	while ((inp = inp_next(&inpi)) != NULL) {
2064db0ac6deSCy Schubert 		INP_WLOCK_ASSERT(inp);
2065db0ac6deSCy Schubert 
2066e43cc4aeSHajimu UMEMOTO 		imo = inp->inp_moptions;
2067e43cc4aeSHajimu UMEMOTO 		/*
2068e43cc4aeSHajimu UMEMOTO 		 * Unselect the outgoing interface if it is being
2069e43cc4aeSHajimu UMEMOTO 		 * detached.
2070e43cc4aeSHajimu UMEMOTO 		 */
2071e43cc4aeSHajimu UMEMOTO 		if (imo->imo_multicast_ifp == ifp)
2072e43cc4aeSHajimu UMEMOTO 			imo->imo_multicast_ifp = NULL;
2073e43cc4aeSHajimu UMEMOTO 
2074e43cc4aeSHajimu UMEMOTO 		/*
2075e43cc4aeSHajimu UMEMOTO 		 * Drop multicast group membership if we joined
2076e43cc4aeSHajimu UMEMOTO 		 * through the interface being detached.
2077cb6bb230SMatt Macy 		 *
2078cb6bb230SMatt Macy 		 * XXX This can all be deferred to an epoch_call
2079e43cc4aeSHajimu UMEMOTO 		 */
208059854ecfSHans Petter Selasky restart:
208159854ecfSHans Petter Selasky 		IP_MFILTER_FOREACH(imf, &imo->imo_head) {
208259854ecfSHans Petter Selasky 			if ((inm = imf->imf_inm) == NULL)
208359854ecfSHans Petter Selasky 				continue;
208459854ecfSHans Petter Selasky 			if (inm->inm_ifp != ifp)
208559854ecfSHans Petter Selasky 				continue;
208659854ecfSHans Petter Selasky 			ip_mfilter_remove(&imo->imo_head, imf);
208759854ecfSHans Petter Selasky 			in_leavegroup_locked(inm, NULL);
208859854ecfSHans Petter Selasky 			ip_mfilter_free(imf);
208959854ecfSHans Petter Selasky 			goto restart;
2090e43cc4aeSHajimu UMEMOTO 		}
2091e43cc4aeSHajimu UMEMOTO 	}
2092e43cc4aeSHajimu UMEMOTO }
2093e43cc4aeSHajimu UMEMOTO 
2094df8bae1dSRodney W. Grimes /*
2095fa046d87SRobert Watson  * Lookup a PCB based on the local address and port.  Caller must hold the
2096fa046d87SRobert Watson  * hash lock.  No inpcb locks or references are acquired.
2097c3229e05SDavid Greenman  */
2098d5e8a67eSHajimu UMEMOTO #define INP_LOOKUP_MAPPED_PCB_COST	3
2099df8bae1dSRodney W. Grimes struct inpcb *
2100136d4f1cSRobert Watson in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
210168e0d7e0SRobert Watson     u_short lport, int lookupflags, struct ucred *cred)
2102df8bae1dSRodney W. Grimes {
2103136d4f1cSRobert Watson 	struct inpcb *inp;
2104d5e8a67eSHajimu UMEMOTO #ifdef INET6
2105d5e8a67eSHajimu UMEMOTO 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
2106d5e8a67eSHajimu UMEMOTO #else
2107d5e8a67eSHajimu UMEMOTO 	int matchwild = 3;
2108d5e8a67eSHajimu UMEMOTO #endif
2109d5e8a67eSHajimu UMEMOTO 	int wildcard;
21107bc4aca7SDavid Greenman 
211168e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
211268e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2113fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
21141b73ca0bSSam Leffler 
211568e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
2116c3229e05SDavid Greenman 		struct inpcbhead *head;
2117c3229e05SDavid Greenman 		/*
2118c3229e05SDavid Greenman 		 * Look for an unconnected (wildcard foreign addr) PCB that
2119c3229e05SDavid Greenman 		 * matches the local address and port we're looking for.
2120c3229e05SDavid Greenman 		 */
2121a0577692SGleb Smirnoff 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2122a0577692SGleb Smirnoff 		    pcbinfo->ipi_hashmask)];
2123b872626dSMatt Macy 		CK_LIST_FOREACH(inp, head, inp_hash) {
2124cfa1ca9dSYoshinobu Inoue #ifdef INET6
2125413628a7SBjoern A. Zeeb 			/* XXX inp locking */
2126369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
2127cfa1ca9dSYoshinobu Inoue 				continue;
2128cfa1ca9dSYoshinobu Inoue #endif
2129c3229e05SDavid Greenman 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
2130c3229e05SDavid Greenman 			    inp->inp_laddr.s_addr == laddr.s_addr &&
2131c3229e05SDavid Greenman 			    inp->inp_lport == lport) {
2132c3229e05SDavid Greenman 				/*
2133413628a7SBjoern A. Zeeb 				 * Found?
2134c3229e05SDavid Greenman 				 */
2135413628a7SBjoern A. Zeeb 				if (cred == NULL ||
21360304c731SJamie Gritton 				    prison_equal_ip4(cred->cr_prison,
21370304c731SJamie Gritton 					inp->inp_cred->cr_prison))
2138c3229e05SDavid Greenman 					return (inp);
2139df8bae1dSRodney W. Grimes 			}
2140c3229e05SDavid Greenman 		}
2141c3229e05SDavid Greenman 		/*
2142c3229e05SDavid Greenman 		 * Not found.
2143c3229e05SDavid Greenman 		 */
2144c3229e05SDavid Greenman 		return (NULL);
2145c3229e05SDavid Greenman 	} else {
2146c3229e05SDavid Greenman 		struct inpcbporthead *porthash;
2147c3229e05SDavid Greenman 		struct inpcbport *phd;
2148c3229e05SDavid Greenman 		struct inpcb *match = NULL;
2149c3229e05SDavid Greenman 		/*
2150c3229e05SDavid Greenman 		 * Best fit PCB lookup.
2151c3229e05SDavid Greenman 		 *
2152c3229e05SDavid Greenman 		 * First see if this local port is in use by looking on the
2153c3229e05SDavid Greenman 		 * port hash list.
2154c3229e05SDavid Greenman 		 */
2155712fc218SRobert Watson 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2156712fc218SRobert Watson 		    pcbinfo->ipi_porthashmask)];
2157b872626dSMatt Macy 		CK_LIST_FOREACH(phd, porthash, phd_hash) {
2158c3229e05SDavid Greenman 			if (phd->phd_port == lport)
2159c3229e05SDavid Greenman 				break;
2160c3229e05SDavid Greenman 		}
2161c3229e05SDavid Greenman 		if (phd != NULL) {
2162c3229e05SDavid Greenman 			/*
2163c3229e05SDavid Greenman 			 * Port is in use by one or more PCBs. Look for best
2164c3229e05SDavid Greenman 			 * fit.
2165c3229e05SDavid Greenman 			 */
2166b872626dSMatt Macy 			CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2167c3229e05SDavid Greenman 				wildcard = 0;
2168413628a7SBjoern A. Zeeb 				if (cred != NULL &&
21690304c731SJamie Gritton 				    !prison_equal_ip4(inp->inp_cred->cr_prison,
21700304c731SJamie Gritton 					cred->cr_prison))
2171413628a7SBjoern A. Zeeb 					continue;
2172cfa1ca9dSYoshinobu Inoue #ifdef INET6
2173413628a7SBjoern A. Zeeb 				/* XXX inp locking */
2174369dc8ceSEivind Eklund 				if ((inp->inp_vflag & INP_IPV4) == 0)
2175cfa1ca9dSYoshinobu Inoue 					continue;
2176d5e8a67eSHajimu UMEMOTO 				/*
2177d5e8a67eSHajimu UMEMOTO 				 * We never select the PCB that has
2178d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag and is bound to :: if
2179d5e8a67eSHajimu UMEMOTO 				 * we have another PCB which is bound
2180d5e8a67eSHajimu UMEMOTO 				 * to 0.0.0.0.  If a PCB has the
2181d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag, then we set its cost
2182d5e8a67eSHajimu UMEMOTO 				 * higher than IPv4 only PCBs.
2183d5e8a67eSHajimu UMEMOTO 				 *
2184d5e8a67eSHajimu UMEMOTO 				 * Note that the case only happens
2185d5e8a67eSHajimu UMEMOTO 				 * when a socket is bound to ::, under
2186d5e8a67eSHajimu UMEMOTO 				 * the condition that the use of the
2187d5e8a67eSHajimu UMEMOTO 				 * mapped address is allowed.
2188d5e8a67eSHajimu UMEMOTO 				 */
2189d5e8a67eSHajimu UMEMOTO 				if ((inp->inp_vflag & INP_IPV6) != 0)
2190d5e8a67eSHajimu UMEMOTO 					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2191cfa1ca9dSYoshinobu Inoue #endif
2192c3229e05SDavid Greenman 				if (inp->inp_faddr.s_addr != INADDR_ANY)
2193c3229e05SDavid Greenman 					wildcard++;
219415bd2b43SDavid Greenman 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
219515bd2b43SDavid Greenman 					if (laddr.s_addr == INADDR_ANY)
219615bd2b43SDavid Greenman 						wildcard++;
219715bd2b43SDavid Greenman 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
219815bd2b43SDavid Greenman 						continue;
219915bd2b43SDavid Greenman 				} else {
220015bd2b43SDavid Greenman 					if (laddr.s_addr != INADDR_ANY)
220115bd2b43SDavid Greenman 						wildcard++;
220215bd2b43SDavid Greenman 				}
2203df8bae1dSRodney W. Grimes 				if (wildcard < matchwild) {
2204df8bae1dSRodney W. Grimes 					match = inp;
2205df8bae1dSRodney W. Grimes 					matchwild = wildcard;
2206413628a7SBjoern A. Zeeb 					if (matchwild == 0)
2207df8bae1dSRodney W. Grimes 						break;
2208df8bae1dSRodney W. Grimes 				}
2209df8bae1dSRodney W. Grimes 			}
22103dbdc25cSDavid Greenman 		}
2211df8bae1dSRodney W. Grimes 		return (match);
2212df8bae1dSRodney W. Grimes 	}
2213c3229e05SDavid Greenman }
2214d5e8a67eSHajimu UMEMOTO #undef INP_LOOKUP_MAPPED_PCB_COST
221515bd2b43SDavid Greenman 
22161a43cff9SSean Bruno static struct inpcb *
22171a43cff9SSean Bruno in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
22181a43cff9SSean Bruno     const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
2219a034518aSAndrew Gallatin     uint16_t fport, int lookupflags, int numa_domain)
22201a43cff9SSean Bruno {
2221a034518aSAndrew Gallatin 	struct inpcb *local_wild, *numa_wild;
22221a43cff9SSean Bruno 	const struct inpcblbgrouphead *hdr;
22231a43cff9SSean Bruno 	struct inpcblbgroup *grp;
22248be02ee4SMark Johnston 	uint32_t idx;
22251a43cff9SSean Bruno 
22261a43cff9SSean Bruno 	INP_HASH_LOCK_ASSERT(pcbinfo);
22271a43cff9SSean Bruno 
22289d2877fcSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[
22299d2877fcSMark Johnston 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
22301a43cff9SSean Bruno 
22311a43cff9SSean Bruno 	/*
22321a43cff9SSean Bruno 	 * Order of socket selection:
22331a43cff9SSean Bruno 	 * 1. non-wild.
22341a43cff9SSean Bruno 	 * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
22351a43cff9SSean Bruno 	 *
22361a43cff9SSean Bruno 	 * NOTE:
22371a43cff9SSean Bruno 	 * - Load balanced group does not contain jailed sockets
22381a43cff9SSean Bruno 	 * - Load balanced group does not contain IPv4 mapped INET6 wild sockets
22391a43cff9SSean Bruno 	 */
22408be02ee4SMark Johnston 	local_wild = NULL;
2241a034518aSAndrew Gallatin 	numa_wild = NULL;
224254af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
22431a43cff9SSean Bruno #ifdef INET6
22441a43cff9SSean Bruno 		if (!(grp->il_vflag & INP_IPV4))
22451a43cff9SSean Bruno 			continue;
22461a43cff9SSean Bruno #endif
22478be02ee4SMark Johnston 		if (grp->il_lport != lport)
22488be02ee4SMark Johnston 			continue;
22491a43cff9SSean Bruno 
2250a0577692SGleb Smirnoff 		idx = INP_PCBLBGROUP_PKTHASH(faddr, lport, fport) %
22518be02ee4SMark Johnston 		    grp->il_inpcnt;
2252a034518aSAndrew Gallatin 		if (grp->il_laddr.s_addr == laddr->s_addr) {
2253a034518aSAndrew Gallatin 			if (numa_domain == M_NODOM ||
2254a034518aSAndrew Gallatin 			    grp->il_numa_domain == numa_domain) {
22551a43cff9SSean Bruno 				return (grp->il_inp[idx]);
2256a034518aSAndrew Gallatin 			} else {
2257a034518aSAndrew Gallatin 				numa_wild = grp->il_inp[idx];
2258a034518aSAndrew Gallatin 			}
2259a034518aSAndrew Gallatin 		}
22601a43cff9SSean Bruno 		if (grp->il_laddr.s_addr == INADDR_ANY &&
2261a034518aSAndrew Gallatin 		    (lookupflags & INPLOOKUP_WILDCARD) != 0 &&
2262a034518aSAndrew Gallatin 		    (local_wild == NULL || numa_domain == M_NODOM ||
2263a034518aSAndrew Gallatin 			grp->il_numa_domain == numa_domain)) {
22641a43cff9SSean Bruno 			local_wild = grp->il_inp[idx];
22651a43cff9SSean Bruno 		}
2266a034518aSAndrew Gallatin 	}
2267a034518aSAndrew Gallatin 	if (numa_wild != NULL)
2268a034518aSAndrew Gallatin 		return (numa_wild);
2269a034518aSAndrew Gallatin 
22701a43cff9SSean Bruno 	return (local_wild);
22711a43cff9SSean Bruno }
22721a43cff9SSean Bruno 
227315bd2b43SDavid Greenman /*
2274fa046d87SRobert Watson  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
2275db0ac6deSCy Schubert  * that the caller has either locked the hash list, which usually happens
2276db0ac6deSCy Schubert  * for bind(2) operations, or is in SMR section, which happens when sorting
2277db0ac6deSCy Schubert  * out incoming packets.
227815bd2b43SDavid Greenman  */
2279fa046d87SRobert Watson static struct inpcb *
2280fa046d87SRobert Watson in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
228168e0d7e0SRobert Watson     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2282a034518aSAndrew Gallatin     struct ifnet *ifp, uint8_t numa_domain)
228315bd2b43SDavid Greenman {
228415bd2b43SDavid Greenman 	struct inpcbhead *head;
2285413628a7SBjoern A. Zeeb 	struct inpcb *inp, *tmpinp;
228615bd2b43SDavid Greenman 	u_short fport = fport_arg, lport = lport_arg;
228715bd2b43SDavid Greenman 
228868e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
228968e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2290d797164aSGleb Smirnoff 	INP_HASH_LOCK_ASSERT(pcbinfo);
2291d797164aSGleb Smirnoff 
229215bd2b43SDavid Greenman 	/*
229315bd2b43SDavid Greenman 	 * First look for an exact match.
229415bd2b43SDavid Greenman 	 */
2295413628a7SBjoern A. Zeeb 	tmpinp = NULL;
2296a0577692SGleb Smirnoff 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&faddr, lport, fport,
2297712fc218SRobert Watson 	    pcbinfo->ipi_hashmask)];
2298b872626dSMatt Macy 	CK_LIST_FOREACH(inp, head, inp_hash) {
2299cfa1ca9dSYoshinobu Inoue #ifdef INET6
2300413628a7SBjoern A. Zeeb 		/* XXX inp locking */
2301369dc8ceSEivind Eklund 		if ((inp->inp_vflag & INP_IPV4) == 0)
2302cfa1ca9dSYoshinobu Inoue 			continue;
2303cfa1ca9dSYoshinobu Inoue #endif
23046d6a026bSDavid Greenman 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
2305ca98b82cSDavid Greenman 		    inp->inp_laddr.s_addr == laddr.s_addr &&
2306ca98b82cSDavid Greenman 		    inp->inp_fport == fport &&
2307413628a7SBjoern A. Zeeb 		    inp->inp_lport == lport) {
2308413628a7SBjoern A. Zeeb 			/*
2309413628a7SBjoern A. Zeeb 			 * XXX We should be able to directly return
2310413628a7SBjoern A. Zeeb 			 * the inp here, without any checks.
2311413628a7SBjoern A. Zeeb 			 * Well unless both bound with SO_REUSEPORT?
2312413628a7SBjoern A. Zeeb 			 */
23130304c731SJamie Gritton 			if (prison_flag(inp->inp_cred, PR_IP4))
2314c3229e05SDavid Greenman 				return (inp);
2315413628a7SBjoern A. Zeeb 			if (tmpinp == NULL)
2316413628a7SBjoern A. Zeeb 				tmpinp = inp;
2317c3229e05SDavid Greenman 		}
2318413628a7SBjoern A. Zeeb 	}
2319413628a7SBjoern A. Zeeb 	if (tmpinp != NULL)
2320413628a7SBjoern A. Zeeb 		return (tmpinp);
2321e3fd5ffdSRobert Watson 
2322e3fd5ffdSRobert Watson 	/*
23231a43cff9SSean Bruno 	 * Then look in lb group (for wildcard match).
23241a43cff9SSean Bruno 	 */
2325d9ff5789SMark Johnston 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
23261a43cff9SSean Bruno 		inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2327a034518aSAndrew Gallatin 		    fport, lookupflags, numa_domain);
2328d9ff5789SMark Johnston 		if (inp != NULL)
23291a43cff9SSean Bruno 			return (inp);
23301a43cff9SSean Bruno 	}
23311a43cff9SSean Bruno 
23321a43cff9SSean Bruno 	/*
2333e3fd5ffdSRobert Watson 	 * Then look for a wildcard match, if requested.
2334e3fd5ffdSRobert Watson 	 */
233568e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2336413628a7SBjoern A. Zeeb 		struct inpcb *local_wild = NULL, *local_exact = NULL;
2337e3fd5ffdSRobert Watson #ifdef INET6
2338cfa1ca9dSYoshinobu Inoue 		struct inpcb *local_wild_mapped = NULL;
2339e3fd5ffdSRobert Watson #endif
2340413628a7SBjoern A. Zeeb 		struct inpcb *jail_wild = NULL;
2341413628a7SBjoern A. Zeeb 		int injail;
2342413628a7SBjoern A. Zeeb 
2343413628a7SBjoern A. Zeeb 		/*
2344413628a7SBjoern A. Zeeb 		 * Order of socket selection - we always prefer jails.
2345413628a7SBjoern A. Zeeb 		 *      1. jailed, non-wild.
2346413628a7SBjoern A. Zeeb 		 *      2. jailed, wild.
2347413628a7SBjoern A. Zeeb 		 *      3. non-jailed, non-wild.
2348413628a7SBjoern A. Zeeb 		 *      4. non-jailed, wild.
2349413628a7SBjoern A. Zeeb 		 */
23506d6a026bSDavid Greenman 
2351a0577692SGleb Smirnoff 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
2352a0577692SGleb Smirnoff 		    pcbinfo->ipi_hashmask)];
2353b872626dSMatt Macy 		CK_LIST_FOREACH(inp, head, inp_hash) {
2354cfa1ca9dSYoshinobu Inoue #ifdef INET6
2355413628a7SBjoern A. Zeeb 			/* XXX inp locking */
2356369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
2357cfa1ca9dSYoshinobu Inoue 				continue;
2358cfa1ca9dSYoshinobu Inoue #endif
2359413628a7SBjoern A. Zeeb 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
2360413628a7SBjoern A. Zeeb 			    inp->inp_lport != lport)
2361413628a7SBjoern A. Zeeb 				continue;
2362413628a7SBjoern A. Zeeb 
23630304c731SJamie Gritton 			injail = prison_flag(inp->inp_cred, PR_IP4);
2364413628a7SBjoern A. Zeeb 			if (injail) {
2365185e659cSGleb Smirnoff 				if (prison_check_ip4_locked(
2366185e659cSGleb Smirnoff 				    inp->inp_cred->cr_prison, &laddr) != 0)
2367413628a7SBjoern A. Zeeb 					continue;
2368413628a7SBjoern A. Zeeb 			} else {
2369413628a7SBjoern A. Zeeb 				if (local_exact != NULL)
2370413628a7SBjoern A. Zeeb 					continue;
2371413628a7SBjoern A. Zeeb 			}
2372413628a7SBjoern A. Zeeb 
2373413628a7SBjoern A. Zeeb 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
2374413628a7SBjoern A. Zeeb 				if (injail)
2375c3229e05SDavid Greenman 					return (inp);
2376413628a7SBjoern A. Zeeb 				else
2377413628a7SBjoern A. Zeeb 					local_exact = inp;
2378413628a7SBjoern A. Zeeb 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2379e3fd5ffdSRobert Watson #ifdef INET6
2380413628a7SBjoern A. Zeeb 				/* XXX inp locking, NULL check */
23815cd54324SBjoern A. Zeeb 				if (inp->inp_vflag & INP_IPV6PROTO)
2382cfa1ca9dSYoshinobu Inoue 					local_wild_mapped = inp;
2383cfa1ca9dSYoshinobu Inoue 				else
238483e521ecSBjoern A. Zeeb #endif
2385413628a7SBjoern A. Zeeb 					if (injail)
2386413628a7SBjoern A. Zeeb 						jail_wild = inp;
2387413628a7SBjoern A. Zeeb 					else
23886d6a026bSDavid Greenman 						local_wild = inp;
23896d6a026bSDavid Greenman 			}
2390413628a7SBjoern A. Zeeb 		} /* LIST_FOREACH */
2391413628a7SBjoern A. Zeeb 		if (jail_wild != NULL)
2392413628a7SBjoern A. Zeeb 			return (jail_wild);
2393413628a7SBjoern A. Zeeb 		if (local_exact != NULL)
2394413628a7SBjoern A. Zeeb 			return (local_exact);
2395413628a7SBjoern A. Zeeb 		if (local_wild != NULL)
2396c3229e05SDavid Greenman 			return (local_wild);
2397413628a7SBjoern A. Zeeb #ifdef INET6
2398413628a7SBjoern A. Zeeb 		if (local_wild_mapped != NULL)
2399413628a7SBjoern A. Zeeb 			return (local_wild_mapped);
240083e521ecSBjoern A. Zeeb #endif
240168e0d7e0SRobert Watson 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2402413628a7SBjoern A. Zeeb 
24036d6a026bSDavid Greenman 	return (NULL);
240415bd2b43SDavid Greenman }
2405fa046d87SRobert Watson 
2406fa046d87SRobert Watson /*
2407fa046d87SRobert Watson  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
2408fa046d87SRobert Watson  * hash list lock, and will return the inpcb locked (i.e., requires
2409fa046d87SRobert Watson  * INPLOOKUP_LOCKPCB).
2410fa046d87SRobert Watson  */
2411fa046d87SRobert Watson static struct inpcb *
2412fa046d87SRobert Watson in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2413fa046d87SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2414a034518aSAndrew Gallatin     struct ifnet *ifp, uint8_t numa_domain)
2415fa046d87SRobert Watson {
2416fa046d87SRobert Watson 	struct inpcb *inp;
2417fa046d87SRobert Watson 
2418db0ac6deSCy Schubert 	smr_enter(pcbinfo->ipi_smr);
2419fa046d87SRobert Watson 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
242008d9c920SGleb Smirnoff 	    lookupflags & INPLOOKUP_WILDCARD, ifp, numa_domain);
2421fa046d87SRobert Watson 	if (inp != NULL) {
2422db0ac6deSCy Schubert 		if (__predict_false(inp_smr_lock(inp,
2423db0ac6deSCy Schubert 		    (lookupflags & INPLOOKUP_LOCKMASK)) == false))
2424266f97b5SCy Schubert 			inp = NULL;
2425db0ac6deSCy Schubert 	} else
2426db0ac6deSCy Schubert 		smr_exit(pcbinfo->ipi_smr);
2427d797164aSGleb Smirnoff 
2428fa046d87SRobert Watson 	return (inp);
2429fa046d87SRobert Watson }
2430fa046d87SRobert Watson 
2431fa046d87SRobert Watson /*
2432d3c1f003SRobert Watson  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2433d3c1f003SRobert Watson  * from which a pre-calculated hash value may be extracted.
2434fa046d87SRobert Watson  */
2435fa046d87SRobert Watson struct inpcb *
2436fa046d87SRobert Watson in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2437fa046d87SRobert Watson     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2438fa046d87SRobert Watson {
2439fa046d87SRobert Watson 
2440fa046d87SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2441fa046d87SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
24421db08fbeSGleb Smirnoff 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
24431db08fbeSGleb Smirnoff 	    ("%s: LOCKPCB not set", __func__));
2444fa046d87SRobert Watson 
2445fa046d87SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2446a034518aSAndrew Gallatin 	    lookupflags, ifp, M_NODOM));
2447fa046d87SRobert Watson }
2448d3c1f003SRobert Watson 
2449d3c1f003SRobert Watson struct inpcb *
2450d3c1f003SRobert Watson in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2451d3c1f003SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2452d3c1f003SRobert Watson     struct ifnet *ifp, struct mbuf *m)
2453d3c1f003SRobert Watson {
2454d3c1f003SRobert Watson 
2455d3c1f003SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2456d3c1f003SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
24571db08fbeSGleb Smirnoff 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
24581db08fbeSGleb Smirnoff 	    ("%s: LOCKPCB not set", __func__));
2459d3c1f003SRobert Watson 
2460d3c1f003SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2461a034518aSAndrew Gallatin 	    lookupflags, ifp, m->m_pkthdr.numa_domain));
2462d3c1f003SRobert Watson }
246367107f45SBjoern A. Zeeb #endif /* INET */
246415bd2b43SDavid Greenman 
24657bc4aca7SDavid Greenman /*
2466c3229e05SDavid Greenman  * Insert PCB onto various hash lists.
24677bc4aca7SDavid Greenman  */
2468db0ac6deSCy Schubert int
2469db0ac6deSCy Schubert in_pcbinshash(struct inpcb *inp)
247015bd2b43SDavid Greenman {
2471c3229e05SDavid Greenman 	struct inpcbhead *pcbhash;
2472c3229e05SDavid Greenman 	struct inpcbporthead *pcbporthash;
2473c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2474c3229e05SDavid Greenman 	struct inpcbport *phd;
24751a43cff9SSean Bruno 	int so_options;
247615bd2b43SDavid Greenman 
24778501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2478fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2479fa046d87SRobert Watson 
2480111d57a6SRobert Watson 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2481111d57a6SRobert Watson 	    ("in_pcbinshash: INP_INHASHLIST"));
2482602cc7f1SRobert Watson 
2483cfa1ca9dSYoshinobu Inoue #ifdef INET6
2484cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
2485a0577692SGleb Smirnoff 		pcbhash = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2486a0577692SGleb Smirnoff 		    inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2487cfa1ca9dSYoshinobu Inoue 	else
248883e521ecSBjoern A. Zeeb #endif
2489a0577692SGleb Smirnoff 		pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2490712fc218SRobert Watson 		    inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
249115bd2b43SDavid Greenman 
2492712fc218SRobert Watson 	pcbporthash = &pcbinfo->ipi_porthashbase[
2493712fc218SRobert Watson 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2494c3229e05SDavid Greenman 
2495c3229e05SDavid Greenman 	/*
24961a43cff9SSean Bruno 	 * Add entry to load balance group.
24971a43cff9SSean Bruno 	 * Only do this if SO_REUSEPORT_LB is set.
24981a43cff9SSean Bruno 	 */
24991a43cff9SSean Bruno 	so_options = inp_so_options(inp);
25001a43cff9SSean Bruno 	if (so_options & SO_REUSEPORT_LB) {
2501a034518aSAndrew Gallatin 		int ret = in_pcbinslbgrouphash(inp, M_NODOM);
25021a43cff9SSean Bruno 		if (ret) {
25031a43cff9SSean Bruno 			/* pcb lb group malloc fail (ret=ENOBUFS). */
25041a43cff9SSean Bruno 			return (ret);
25051a43cff9SSean Bruno 		}
25061a43cff9SSean Bruno 	}
25071a43cff9SSean Bruno 
25081a43cff9SSean Bruno 	/*
2509c3229e05SDavid Greenman 	 * Go through port list and look for a head for this lport.
2510c3229e05SDavid Greenman 	 */
2511b872626dSMatt Macy 	CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2512c3229e05SDavid Greenman 		if (phd->phd_port == inp->inp_lport)
2513c3229e05SDavid Greenman 			break;
2514c3229e05SDavid Greenman 	}
2515c3229e05SDavid Greenman 	/*
2516c3229e05SDavid Greenman 	 * If none exists, malloc one and tack it on.
2517c3229e05SDavid Greenman 	 */
2518c3229e05SDavid Greenman 	if (phd == NULL) {
2519db0ac6deSCy Schubert 		phd = uma_zalloc_smr(pcbinfo->ipi_portzone, M_NOWAIT);
2520c3229e05SDavid Greenman 		if (phd == NULL) {
2521c3229e05SDavid Greenman 			return (ENOBUFS); /* XXX */
2522c3229e05SDavid Greenman 		}
2523c3229e05SDavid Greenman 		phd->phd_port = inp->inp_lport;
2524b872626dSMatt Macy 		CK_LIST_INIT(&phd->phd_pcblist);
2525b872626dSMatt Macy 		CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2526c3229e05SDavid Greenman 	}
2527c3229e05SDavid Greenman 	inp->inp_phd = phd;
2528b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2529b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2530111d57a6SRobert Watson 	inp->inp_flags |= INP_INHASHLIST;
2531db0ac6deSCy Schubert 
2532c3229e05SDavid Greenman 	return (0);
253315bd2b43SDavid Greenman }
253415bd2b43SDavid Greenman 
253552cd27cbSRobert Watson /*
2536c3229e05SDavid Greenman  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2537c3229e05SDavid Greenman  * changed. NOTE: This does not handle the case of the lport changing (the
2538c3229e05SDavid Greenman  * hashed port list would have to be updated as well), so the lport must
2539c3229e05SDavid Greenman  * not change after in_pcbinshash() has been called.
2540db0ac6deSCy Schubert  *
2541db0ac6deSCy Schubert  * XXXGL: a race between this function and SMR-protected hash iterator
2542db0ac6deSCy Schubert  * will lead to iterator traversing a possibly wrong hash list. However,
2543db0ac6deSCy Schubert  * this race should have been here since change from rwlock to epoch.
2544c3229e05SDavid Greenman  */
254515bd2b43SDavid Greenman void
2546db0ac6deSCy Schubert in_pcbrehash(struct inpcb *inp)
254715bd2b43SDavid Greenman {
254859daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
254915bd2b43SDavid Greenman 	struct inpcbhead *head;
255015bd2b43SDavid Greenman 
25518501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2552fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2553fa046d87SRobert Watson 
2554111d57a6SRobert Watson 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2555111d57a6SRobert Watson 	    ("in_pcbrehash: !INP_INHASHLIST"));
2556602cc7f1SRobert Watson 
2557cfa1ca9dSYoshinobu Inoue #ifdef INET6
2558cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
2559a0577692SGleb Smirnoff 		head = &pcbinfo->ipi_hashbase[INP6_PCBHASH(&inp->in6p_faddr,
2560a0577692SGleb Smirnoff 		    inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2561cfa1ca9dSYoshinobu Inoue 	else
256283e521ecSBjoern A. Zeeb #endif
2563a0577692SGleb Smirnoff 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(&inp->inp_faddr,
2564712fc218SRobert Watson 		    inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
256515bd2b43SDavid Greenman 
2566b872626dSMatt Macy 	CK_LIST_REMOVE(inp, inp_hash);
2567b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2568c3229e05SDavid Greenman }
2569c3229e05SDavid Greenman 
2570c3229e05SDavid Greenman /*
257184cc0778SGeorge V. Neville-Neil  * Check for alternatives when higher level complains
257284cc0778SGeorge V. Neville-Neil  * about service problems.  For now, invalidate cached
257384cc0778SGeorge V. Neville-Neil  * routing information.  If the route was created dynamically
257484cc0778SGeorge V. Neville-Neil  * (by a redirect), time to try a default gateway again.
257584cc0778SGeorge V. Neville-Neil  */
257684cc0778SGeorge V. Neville-Neil void
257784cc0778SGeorge V. Neville-Neil in_losing(struct inpcb *inp)
257884cc0778SGeorge V. Neville-Neil {
257984cc0778SGeorge V. Neville-Neil 
2580fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
258184cc0778SGeorge V. Neville-Neil 	return;
258284cc0778SGeorge V. Neville-Neil }
258384cc0778SGeorge V. Neville-Neil 
258484cc0778SGeorge V. Neville-Neil /*
2585a557af22SRobert Watson  * A set label operation has occurred at the socket layer, propagate the
2586a557af22SRobert Watson  * label change into the in_pcb for the socket.
2587a557af22SRobert Watson  */
2588a557af22SRobert Watson void
2589136d4f1cSRobert Watson in_pcbsosetlabel(struct socket *so)
2590a557af22SRobert Watson {
2591a557af22SRobert Watson #ifdef MAC
2592a557af22SRobert Watson 	struct inpcb *inp;
2593a557af22SRobert Watson 
25944c7c478dSRobert Watson 	inp = sotoinpcb(so);
25954c7c478dSRobert Watson 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2596602cc7f1SRobert Watson 
25978501a69cSRobert Watson 	INP_WLOCK(inp);
2598310e7cebSRobert Watson 	SOCK_LOCK(so);
2599a557af22SRobert Watson 	mac_inpcb_sosetlabel(so, inp);
2600310e7cebSRobert Watson 	SOCK_UNLOCK(so);
26018501a69cSRobert Watson 	INP_WUNLOCK(inp);
2602a557af22SRobert Watson #endif
2603a557af22SRobert Watson }
26045f311da2SMike Silbersack 
26055f311da2SMike Silbersack /*
2606ad3a630fSRobert Watson  * ipport_tick runs once per second, determining if random port allocation
2607ad3a630fSRobert Watson  * should be continued.  If more than ipport_randomcps ports have been
2608ad3a630fSRobert Watson  * allocated in the last second, then we return to sequential port
2609ad3a630fSRobert Watson  * allocation. We return to random allocation only once we drop below
2610ad3a630fSRobert Watson  * ipport_randomcps for at least ipport_randomtime seconds.
26115f311da2SMike Silbersack  */
2612aae49dd3SBjoern A. Zeeb static void
2613136d4f1cSRobert Watson ipport_tick(void *xtp)
26145f311da2SMike Silbersack {
26158b615593SMarko Zec 	VNET_ITERATOR_DECL(vnet_iter);
2616ad3a630fSRobert Watson 
26175ee847d3SRobert Watson 	VNET_LIST_RLOCK_NOSLEEP();
26188b615593SMarko Zec 	VNET_FOREACH(vnet_iter) {
26198b615593SMarko Zec 		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
26204c018b5aSPeter Lei 		if (V_ipport_tcpallocs - V_ipport_tcplastcount <=
26214c018b5aSPeter Lei 		    V_ipport_randomcps) {
2622603724d3SBjoern A. Zeeb 			if (V_ipport_stoprandom > 0)
2623603724d3SBjoern A. Zeeb 				V_ipport_stoprandom--;
2624ad3a630fSRobert Watson 		} else
2625603724d3SBjoern A. Zeeb 			V_ipport_stoprandom = V_ipport_randomtime;
2626603724d3SBjoern A. Zeeb 		V_ipport_tcplastcount = V_ipport_tcpallocs;
26278b615593SMarko Zec 		CURVNET_RESTORE();
26288b615593SMarko Zec 	}
26295ee847d3SRobert Watson 	VNET_LIST_RUNLOCK_NOSLEEP();
26305f311da2SMike Silbersack 	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
26315f311da2SMike Silbersack }
2632497057eeSRobert Watson 
2633aae49dd3SBjoern A. Zeeb static void
2634aae49dd3SBjoern A. Zeeb ip_fini(void *xtp)
2635aae49dd3SBjoern A. Zeeb {
2636aae49dd3SBjoern A. Zeeb 
2637aae49dd3SBjoern A. Zeeb 	callout_stop(&ipport_tick_callout);
2638aae49dd3SBjoern A. Zeeb }
2639aae49dd3SBjoern A. Zeeb 
2640aae49dd3SBjoern A. Zeeb /*
2641aae49dd3SBjoern A. Zeeb  * The ipport_callout should start running at about the time we attach the
2642aae49dd3SBjoern A. Zeeb  * inet or inet6 domains.
2643aae49dd3SBjoern A. Zeeb  */
2644aae49dd3SBjoern A. Zeeb static void
2645aae49dd3SBjoern A. Zeeb ipport_tick_init(const void *unused __unused)
2646aae49dd3SBjoern A. Zeeb {
2647aae49dd3SBjoern A. Zeeb 
2648aae49dd3SBjoern A. Zeeb 	/* Start ipport_tick. */
2649fd90e2edSJung-uk Kim 	callout_init(&ipport_tick_callout, 1);
2650aae49dd3SBjoern A. Zeeb 	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2651aae49dd3SBjoern A. Zeeb 	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2652aae49dd3SBjoern A. Zeeb 		SHUTDOWN_PRI_DEFAULT);
2653aae49dd3SBjoern A. Zeeb }
2654aae49dd3SBjoern A. Zeeb SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2655aae49dd3SBjoern A. Zeeb     ipport_tick_init, NULL);
2656aae49dd3SBjoern A. Zeeb 
26573d585327SKip Macy void
26583d585327SKip Macy inp_wlock(struct inpcb *inp)
26593d585327SKip Macy {
26603d585327SKip Macy 
26618501a69cSRobert Watson 	INP_WLOCK(inp);
26623d585327SKip Macy }
26633d585327SKip Macy 
26643d585327SKip Macy void
26653d585327SKip Macy inp_wunlock(struct inpcb *inp)
26663d585327SKip Macy {
26673d585327SKip Macy 
26688501a69cSRobert Watson 	INP_WUNLOCK(inp);
26693d585327SKip Macy }
26703d585327SKip Macy 
26713d585327SKip Macy void
26723d585327SKip Macy inp_rlock(struct inpcb *inp)
26733d585327SKip Macy {
26743d585327SKip Macy 
2675a69042a5SRobert Watson 	INP_RLOCK(inp);
26763d585327SKip Macy }
26773d585327SKip Macy 
26783d585327SKip Macy void
26793d585327SKip Macy inp_runlock(struct inpcb *inp)
26803d585327SKip Macy {
26813d585327SKip Macy 
2682a69042a5SRobert Watson 	INP_RUNLOCK(inp);
26833d585327SKip Macy }
26843d585327SKip Macy 
2685c75e2666SGleb Smirnoff #ifdef INVARIANT_SUPPORT
26863d585327SKip Macy void
2687e79dd20dSKip Macy inp_lock_assert(struct inpcb *inp)
26883d585327SKip Macy {
26893d585327SKip Macy 
26908501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
26913d585327SKip Macy }
26923d585327SKip Macy 
26933d585327SKip Macy void
2694e79dd20dSKip Macy inp_unlock_assert(struct inpcb *inp)
26953d585327SKip Macy {
26963d585327SKip Macy 
26973d585327SKip Macy 	INP_UNLOCK_ASSERT(inp);
26983d585327SKip Macy }
26993d585327SKip Macy #endif
27003d585327SKip Macy 
27019378e437SKip Macy void
27029378e437SKip Macy inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
27039378e437SKip Macy {
2704db0ac6deSCy Schubert 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
2705db0ac6deSCy Schubert 	    INPLOOKUP_WLOCKPCB);
27069378e437SKip Macy 	struct inpcb *inp;
27079378e437SKip Macy 
2708db0ac6deSCy Schubert 	while ((inp = inp_next(&inpi)) != NULL)
27099378e437SKip Macy 		func(inp, arg);
27109378e437SKip Macy }
27119378e437SKip Macy 
27129378e437SKip Macy struct socket *
27139378e437SKip Macy inp_inpcbtosocket(struct inpcb *inp)
27149378e437SKip Macy {
27159378e437SKip Macy 
27169378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
27179378e437SKip Macy 	return (inp->inp_socket);
27189378e437SKip Macy }
27199378e437SKip Macy 
27209378e437SKip Macy struct tcpcb *
27219378e437SKip Macy inp_inpcbtotcpcb(struct inpcb *inp)
27229378e437SKip Macy {
27239378e437SKip Macy 
27249378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
27259378e437SKip Macy 	return ((struct tcpcb *)inp->inp_ppcb);
27269378e437SKip Macy }
27279378e437SKip Macy 
27289378e437SKip Macy int
27299378e437SKip Macy inp_ip_tos_get(const struct inpcb *inp)
27309378e437SKip Macy {
27319378e437SKip Macy 
27329378e437SKip Macy 	return (inp->inp_ip_tos);
27339378e437SKip Macy }
27349378e437SKip Macy 
27359378e437SKip Macy void
27369378e437SKip Macy inp_ip_tos_set(struct inpcb *inp, int val)
27379378e437SKip Macy {
27389378e437SKip Macy 
27399378e437SKip Macy 	inp->inp_ip_tos = val;
27409378e437SKip Macy }
27419378e437SKip Macy 
27429378e437SKip Macy void
2743df9cf830STai-hwa Liang inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
27449d29c635SKip Macy     uint32_t *faddr, uint16_t *fp)
27459378e437SKip Macy {
27469378e437SKip Macy 
27479d29c635SKip Macy 	INP_LOCK_ASSERT(inp);
2748df9cf830STai-hwa Liang 	*laddr = inp->inp_laddr.s_addr;
2749df9cf830STai-hwa Liang 	*faddr = inp->inp_faddr.s_addr;
27509378e437SKip Macy 	*lp = inp->inp_lport;
27519378e437SKip Macy 	*fp = inp->inp_fport;
27529378e437SKip Macy }
27539378e437SKip Macy 
2754dd0e6c38SKip Macy struct inpcb *
2755dd0e6c38SKip Macy so_sotoinpcb(struct socket *so)
2756dd0e6c38SKip Macy {
2757dd0e6c38SKip Macy 
2758dd0e6c38SKip Macy 	return (sotoinpcb(so));
2759dd0e6c38SKip Macy }
2760dd0e6c38SKip Macy 
2761dd0e6c38SKip Macy struct tcpcb *
2762dd0e6c38SKip Macy so_sototcpcb(struct socket *so)
2763dd0e6c38SKip Macy {
2764dd0e6c38SKip Macy 
2765dd0e6c38SKip Macy 	return (sototcpcb(so));
2766dd0e6c38SKip Macy }
2767dd0e6c38SKip Macy 
2768cc65eb4eSGleb Smirnoff /*
2769cc65eb4eSGleb Smirnoff  * Create an external-format (``xinpcb'') structure using the information in
2770cc65eb4eSGleb Smirnoff  * the kernel-format in_pcb structure pointed to by inp.  This is done to
2771cc65eb4eSGleb Smirnoff  * reduce the spew of irrelevant information over this interface, to isolate
2772cc65eb4eSGleb Smirnoff  * user code from changes in the kernel structure, and potentially to provide
2773cc65eb4eSGleb Smirnoff  * information-hiding if we decide that some of this information should be
2774cc65eb4eSGleb Smirnoff  * hidden from users.
2775cc65eb4eSGleb Smirnoff  */
2776cc65eb4eSGleb Smirnoff void
2777cc65eb4eSGleb Smirnoff in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2778cc65eb4eSGleb Smirnoff {
2779cc65eb4eSGleb Smirnoff 
278079db6fe7SMark Johnston 	bzero(xi, sizeof(*xi));
2781cc65eb4eSGleb Smirnoff 	xi->xi_len = sizeof(struct xinpcb);
2782cc65eb4eSGleb Smirnoff 	if (inp->inp_socket)
2783cc65eb4eSGleb Smirnoff 		sotoxsocket(inp->inp_socket, &xi->xi_socket);
2784cc65eb4eSGleb Smirnoff 	bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2785cc65eb4eSGleb Smirnoff 	xi->inp_gencnt = inp->inp_gencnt;
27863a20f06aSBrooks Davis 	xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2787cc65eb4eSGleb Smirnoff 	xi->inp_flow = inp->inp_flow;
2788cc65eb4eSGleb Smirnoff 	xi->inp_flowid = inp->inp_flowid;
2789cc65eb4eSGleb Smirnoff 	xi->inp_flowtype = inp->inp_flowtype;
2790cc65eb4eSGleb Smirnoff 	xi->inp_flags = inp->inp_flags;
2791cc65eb4eSGleb Smirnoff 	xi->inp_flags2 = inp->inp_flags2;
2792cc65eb4eSGleb Smirnoff 	xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2793cc65eb4eSGleb Smirnoff 	xi->in6p_cksum = inp->in6p_cksum;
2794cc65eb4eSGleb Smirnoff 	xi->in6p_hops = inp->in6p_hops;
2795cc65eb4eSGleb Smirnoff 	xi->inp_ip_tos = inp->inp_ip_tos;
2796cc65eb4eSGleb Smirnoff 	xi->inp_vflag = inp->inp_vflag;
2797cc65eb4eSGleb Smirnoff 	xi->inp_ip_ttl = inp->inp_ip_ttl;
2798cc65eb4eSGleb Smirnoff 	xi->inp_ip_p = inp->inp_ip_p;
2799cc65eb4eSGleb Smirnoff 	xi->inp_ip_minttl = inp->inp_ip_minttl;
2800cc65eb4eSGleb Smirnoff }
2801cc65eb4eSGleb Smirnoff 
2802a35bdd44SMichael Tuexen int
2803a35bdd44SMichael Tuexen sysctl_setsockopt(SYSCTL_HANDLER_ARGS, struct inpcbinfo *pcbinfo,
2804a35bdd44SMichael Tuexen     int (*ctloutput_set)(struct inpcb *, struct sockopt *))
2805a35bdd44SMichael Tuexen {
2806a35bdd44SMichael Tuexen 	struct sockopt sopt;
2807a35bdd44SMichael Tuexen 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2808a35bdd44SMichael Tuexen 	    INPLOOKUP_WLOCKPCB);
2809a35bdd44SMichael Tuexen 	struct inpcb *inp;
2810a35bdd44SMichael Tuexen 	struct sockopt_parameters *params;
2811a35bdd44SMichael Tuexen 	struct socket *so;
2812a35bdd44SMichael Tuexen 	int error;
2813a35bdd44SMichael Tuexen 	char buf[1024];
2814a35bdd44SMichael Tuexen 
2815a35bdd44SMichael Tuexen 	if (req->oldptr != NULL || req->oldlen != 0)
2816a35bdd44SMichael Tuexen 		return (EINVAL);
2817a35bdd44SMichael Tuexen 	if (req->newptr == NULL)
2818a35bdd44SMichael Tuexen 		return (EPERM);
2819a35bdd44SMichael Tuexen 	if (req->newlen > sizeof(buf))
2820a35bdd44SMichael Tuexen 		return (ENOMEM);
2821a35bdd44SMichael Tuexen 	error = SYSCTL_IN(req, buf, req->newlen);
2822a35bdd44SMichael Tuexen 	if (error != 0)
2823a35bdd44SMichael Tuexen 		return (error);
2824a35bdd44SMichael Tuexen 	if (req->newlen < sizeof(struct sockopt_parameters))
2825a35bdd44SMichael Tuexen 		return (EINVAL);
2826a35bdd44SMichael Tuexen 	params = (struct sockopt_parameters *)buf;
2827a35bdd44SMichael Tuexen 	sopt.sopt_level = params->sop_level;
2828a35bdd44SMichael Tuexen 	sopt.sopt_name = params->sop_optname;
2829a35bdd44SMichael Tuexen 	sopt.sopt_dir = SOPT_SET;
2830a35bdd44SMichael Tuexen 	sopt.sopt_val = params->sop_optval;
2831a35bdd44SMichael Tuexen 	sopt.sopt_valsize = req->newlen - sizeof(struct sockopt_parameters);
2832a35bdd44SMichael Tuexen 	sopt.sopt_td = NULL;
2833*a0aeb1ceSMichael Tuexen #ifdef INET6
2834a35bdd44SMichael Tuexen 	if (params->sop_inc.inc_flags & INC_ISIPV6) {
2835a35bdd44SMichael Tuexen 		if (IN6_IS_SCOPE_LINKLOCAL(&params->sop_inc.inc6_laddr))
2836a35bdd44SMichael Tuexen 			params->sop_inc.inc6_laddr.s6_addr16[1] =
2837a35bdd44SMichael Tuexen 			    htons(params->sop_inc.inc6_zoneid & 0xffff);
2838a35bdd44SMichael Tuexen 		if (IN6_IS_SCOPE_LINKLOCAL(&params->sop_inc.inc6_faddr))
2839a35bdd44SMichael Tuexen 			params->sop_inc.inc6_faddr.s6_addr16[1] =
2840a35bdd44SMichael Tuexen 			    htons(params->sop_inc.inc6_zoneid & 0xffff);
2841a35bdd44SMichael Tuexen 	}
2842*a0aeb1ceSMichael Tuexen #endif
2843a35bdd44SMichael Tuexen 	if (params->sop_inc.inc_lport != htons(0)) {
2844a35bdd44SMichael Tuexen 		if (params->sop_inc.inc_fport == htons(0))
2845a35bdd44SMichael Tuexen 			inpi.hash = INP_PCBHASH_WILD(params->sop_inc.inc_lport,
2846a35bdd44SMichael Tuexen 			    pcbinfo->ipi_hashmask);
2847a35bdd44SMichael Tuexen 		else
2848*a0aeb1ceSMichael Tuexen #ifdef INET6
2849a35bdd44SMichael Tuexen 			if (params->sop_inc.inc_flags & INC_ISIPV6)
2850a35bdd44SMichael Tuexen 				inpi.hash = INP6_PCBHASH(
2851a35bdd44SMichael Tuexen 				    &params->sop_inc.inc6_faddr,
2852a35bdd44SMichael Tuexen 				    params->sop_inc.inc_lport,
2853a35bdd44SMichael Tuexen 				    params->sop_inc.inc_fport,
2854a35bdd44SMichael Tuexen 				    pcbinfo->ipi_hashmask);
2855a35bdd44SMichael Tuexen 			else
2856*a0aeb1ceSMichael Tuexen #endif
2857a35bdd44SMichael Tuexen 				inpi.hash = INP_PCBHASH(
2858a35bdd44SMichael Tuexen 				    &params->sop_inc.inc_faddr,
2859a35bdd44SMichael Tuexen 				    params->sop_inc.inc_lport,
2860a35bdd44SMichael Tuexen 				    params->sop_inc.inc_fport,
2861a35bdd44SMichael Tuexen 				    pcbinfo->ipi_hashmask);
2862a35bdd44SMichael Tuexen 	}
2863a35bdd44SMichael Tuexen 	while ((inp = inp_next(&inpi)) != NULL)
2864a35bdd44SMichael Tuexen 		if (inp->inp_gencnt == params->sop_id) {
2865a35bdd44SMichael Tuexen 			if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
2866a35bdd44SMichael Tuexen 				INP_WUNLOCK(inp);
2867a35bdd44SMichael Tuexen 				return (ECONNRESET);
2868a35bdd44SMichael Tuexen 			}
2869a35bdd44SMichael Tuexen 			so = inp->inp_socket;
2870a35bdd44SMichael Tuexen 			KASSERT(so != NULL, ("inp_socket == NULL"));
2871a35bdd44SMichael Tuexen 			soref(so);
2872a35bdd44SMichael Tuexen 			error = (*ctloutput_set)(inp, &sopt);
2873a35bdd44SMichael Tuexen 			sorele(so);
2874a35bdd44SMichael Tuexen 			break;
2875a35bdd44SMichael Tuexen 		}
2876a35bdd44SMichael Tuexen 	if (inp == NULL)
2877a35bdd44SMichael Tuexen 		error = ESRCH;
2878a35bdd44SMichael Tuexen 	return (error);
2879a35bdd44SMichael Tuexen }
2880a35bdd44SMichael Tuexen 
2881497057eeSRobert Watson #ifdef DDB
2882497057eeSRobert Watson static void
2883497057eeSRobert Watson db_print_indent(int indent)
2884497057eeSRobert Watson {
2885497057eeSRobert Watson 	int i;
2886497057eeSRobert Watson 
2887497057eeSRobert Watson 	for (i = 0; i < indent; i++)
2888497057eeSRobert Watson 		db_printf(" ");
2889497057eeSRobert Watson }
2890497057eeSRobert Watson 
2891497057eeSRobert Watson static void
2892497057eeSRobert Watson db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2893497057eeSRobert Watson {
2894497057eeSRobert Watson 	char faddr_str[48], laddr_str[48];
2895497057eeSRobert Watson 
2896497057eeSRobert Watson 	db_print_indent(indent);
2897497057eeSRobert Watson 	db_printf("%s at %p\n", name, inc);
2898497057eeSRobert Watson 
2899497057eeSRobert Watson 	indent += 2;
2900497057eeSRobert Watson 
290103dc38a4SRobert Watson #ifdef INET6
2902dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
2903497057eeSRobert Watson 		/* IPv6. */
2904497057eeSRobert Watson 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
2905497057eeSRobert Watson 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
290683e521ecSBjoern A. Zeeb 	} else
290703dc38a4SRobert Watson #endif
290883e521ecSBjoern A. Zeeb 	{
2909497057eeSRobert Watson 		/* IPv4. */
2910497057eeSRobert Watson 		inet_ntoa_r(inc->inc_laddr, laddr_str);
2911497057eeSRobert Watson 		inet_ntoa_r(inc->inc_faddr, faddr_str);
2912497057eeSRobert Watson 	}
2913497057eeSRobert Watson 	db_print_indent(indent);
2914497057eeSRobert Watson 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
2915497057eeSRobert Watson 	    ntohs(inc->inc_lport));
2916497057eeSRobert Watson 	db_print_indent(indent);
2917497057eeSRobert Watson 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
2918497057eeSRobert Watson 	    ntohs(inc->inc_fport));
2919497057eeSRobert Watson }
2920497057eeSRobert Watson 
2921497057eeSRobert Watson static void
2922497057eeSRobert Watson db_print_inpflags(int inp_flags)
2923497057eeSRobert Watson {
2924497057eeSRobert Watson 	int comma;
2925497057eeSRobert Watson 
2926497057eeSRobert Watson 	comma = 0;
2927497057eeSRobert Watson 	if (inp_flags & INP_RECVOPTS) {
2928497057eeSRobert Watson 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2929497057eeSRobert Watson 		comma = 1;
2930497057eeSRobert Watson 	}
2931497057eeSRobert Watson 	if (inp_flags & INP_RECVRETOPTS) {
2932497057eeSRobert Watson 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2933497057eeSRobert Watson 		comma = 1;
2934497057eeSRobert Watson 	}
2935497057eeSRobert Watson 	if (inp_flags & INP_RECVDSTADDR) {
2936497057eeSRobert Watson 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2937497057eeSRobert Watson 		comma = 1;
2938497057eeSRobert Watson 	}
2939dce33a45SErmal Luçi 	if (inp_flags & INP_ORIGDSTADDR) {
2940dce33a45SErmal Luçi 		db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2941dce33a45SErmal Luçi 		comma = 1;
2942dce33a45SErmal Luçi 	}
2943497057eeSRobert Watson 	if (inp_flags & INP_HDRINCL) {
2944497057eeSRobert Watson 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
2945497057eeSRobert Watson 		comma = 1;
2946497057eeSRobert Watson 	}
2947497057eeSRobert Watson 	if (inp_flags & INP_HIGHPORT) {
2948497057eeSRobert Watson 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2949497057eeSRobert Watson 		comma = 1;
2950497057eeSRobert Watson 	}
2951497057eeSRobert Watson 	if (inp_flags & INP_LOWPORT) {
2952497057eeSRobert Watson 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
2953497057eeSRobert Watson 		comma = 1;
2954497057eeSRobert Watson 	}
2955497057eeSRobert Watson 	if (inp_flags & INP_ANONPORT) {
2956497057eeSRobert Watson 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
2957497057eeSRobert Watson 		comma = 1;
2958497057eeSRobert Watson 	}
2959497057eeSRobert Watson 	if (inp_flags & INP_RECVIF) {
2960497057eeSRobert Watson 		db_printf("%sINP_RECVIF", comma ? ", " : "");
2961497057eeSRobert Watson 		comma = 1;
2962497057eeSRobert Watson 	}
2963497057eeSRobert Watson 	if (inp_flags & INP_MTUDISC) {
2964497057eeSRobert Watson 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
2965497057eeSRobert Watson 		comma = 1;
2966497057eeSRobert Watson 	}
2967497057eeSRobert Watson 	if (inp_flags & INP_RECVTTL) {
2968497057eeSRobert Watson 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
2969497057eeSRobert Watson 		comma = 1;
2970497057eeSRobert Watson 	}
2971497057eeSRobert Watson 	if (inp_flags & INP_DONTFRAG) {
2972497057eeSRobert Watson 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2973497057eeSRobert Watson 		comma = 1;
2974497057eeSRobert Watson 	}
29753cca425bSMichael Tuexen 	if (inp_flags & INP_RECVTOS) {
29763cca425bSMichael Tuexen 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
29773cca425bSMichael Tuexen 		comma = 1;
29783cca425bSMichael Tuexen 	}
2979497057eeSRobert Watson 	if (inp_flags & IN6P_IPV6_V6ONLY) {
2980497057eeSRobert Watson 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2981497057eeSRobert Watson 		comma = 1;
2982497057eeSRobert Watson 	}
2983497057eeSRobert Watson 	if (inp_flags & IN6P_PKTINFO) {
2984497057eeSRobert Watson 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2985497057eeSRobert Watson 		comma = 1;
2986497057eeSRobert Watson 	}
2987497057eeSRobert Watson 	if (inp_flags & IN6P_HOPLIMIT) {
2988497057eeSRobert Watson 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2989497057eeSRobert Watson 		comma = 1;
2990497057eeSRobert Watson 	}
2991497057eeSRobert Watson 	if (inp_flags & IN6P_HOPOPTS) {
2992497057eeSRobert Watson 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2993497057eeSRobert Watson 		comma = 1;
2994497057eeSRobert Watson 	}
2995497057eeSRobert Watson 	if (inp_flags & IN6P_DSTOPTS) {
2996497057eeSRobert Watson 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2997497057eeSRobert Watson 		comma = 1;
2998497057eeSRobert Watson 	}
2999497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDR) {
3000497057eeSRobert Watson 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3001497057eeSRobert Watson 		comma = 1;
3002497057eeSRobert Watson 	}
3003497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
3004497057eeSRobert Watson 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3005497057eeSRobert Watson 		comma = 1;
3006497057eeSRobert Watson 	}
3007497057eeSRobert Watson 	if (inp_flags & IN6P_TCLASS) {
3008497057eeSRobert Watson 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3009497057eeSRobert Watson 		comma = 1;
3010497057eeSRobert Watson 	}
3011497057eeSRobert Watson 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
3012497057eeSRobert Watson 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3013497057eeSRobert Watson 		comma = 1;
3014497057eeSRobert Watson 	}
3015ad71fe3cSRobert Watson 	if (inp_flags & INP_TIMEWAIT) {
3016ad71fe3cSRobert Watson 		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3017ad71fe3cSRobert Watson 		comma  = 1;
3018ad71fe3cSRobert Watson 	}
3019ad71fe3cSRobert Watson 	if (inp_flags & INP_ONESBCAST) {
3020ad71fe3cSRobert Watson 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3021ad71fe3cSRobert Watson 		comma  = 1;
3022ad71fe3cSRobert Watson 	}
3023ad71fe3cSRobert Watson 	if (inp_flags & INP_DROPPED) {
3024ad71fe3cSRobert Watson 		db_printf("%sINP_DROPPED", comma ? ", " : "");
3025ad71fe3cSRobert Watson 		comma  = 1;
3026ad71fe3cSRobert Watson 	}
3027ad71fe3cSRobert Watson 	if (inp_flags & INP_SOCKREF) {
3028ad71fe3cSRobert Watson 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
3029ad71fe3cSRobert Watson 		comma  = 1;
3030ad71fe3cSRobert Watson 	}
3031497057eeSRobert Watson 	if (inp_flags & IN6P_RFC2292) {
3032497057eeSRobert Watson 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3033497057eeSRobert Watson 		comma = 1;
3034497057eeSRobert Watson 	}
3035497057eeSRobert Watson 	if (inp_flags & IN6P_MTU) {
3036497057eeSRobert Watson 		db_printf("IN6P_MTU%s", comma ? ", " : "");
3037497057eeSRobert Watson 		comma = 1;
3038497057eeSRobert Watson 	}
3039497057eeSRobert Watson }
3040497057eeSRobert Watson 
3041497057eeSRobert Watson static void
3042497057eeSRobert Watson db_print_inpvflag(u_char inp_vflag)
3043497057eeSRobert Watson {
3044497057eeSRobert Watson 	int comma;
3045497057eeSRobert Watson 
3046497057eeSRobert Watson 	comma = 0;
3047497057eeSRobert Watson 	if (inp_vflag & INP_IPV4) {
3048497057eeSRobert Watson 		db_printf("%sINP_IPV4", comma ? ", " : "");
3049497057eeSRobert Watson 		comma  = 1;
3050497057eeSRobert Watson 	}
3051497057eeSRobert Watson 	if (inp_vflag & INP_IPV6) {
3052497057eeSRobert Watson 		db_printf("%sINP_IPV6", comma ? ", " : "");
3053497057eeSRobert Watson 		comma  = 1;
3054497057eeSRobert Watson 	}
3055497057eeSRobert Watson 	if (inp_vflag & INP_IPV6PROTO) {
3056497057eeSRobert Watson 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3057497057eeSRobert Watson 		comma  = 1;
3058497057eeSRobert Watson 	}
3059497057eeSRobert Watson }
3060497057eeSRobert Watson 
30616d888973SRobert Watson static void
3062497057eeSRobert Watson db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3063497057eeSRobert Watson {
3064497057eeSRobert Watson 
3065497057eeSRobert Watson 	db_print_indent(indent);
3066497057eeSRobert Watson 	db_printf("%s at %p\n", name, inp);
3067497057eeSRobert Watson 
3068497057eeSRobert Watson 	indent += 2;
3069497057eeSRobert Watson 
3070497057eeSRobert Watson 	db_print_indent(indent);
3071497057eeSRobert Watson 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3072497057eeSRobert Watson 
3073497057eeSRobert Watson 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3074497057eeSRobert Watson 
3075497057eeSRobert Watson 	db_print_indent(indent);
3076497057eeSRobert Watson 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
3077497057eeSRobert Watson 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3078497057eeSRobert Watson 
3079497057eeSRobert Watson 	db_print_indent(indent);
3080497057eeSRobert Watson 	db_printf("inp_label: %p   inp_flags: 0x%x (",
3081497057eeSRobert Watson 	   inp->inp_label, inp->inp_flags);
3082497057eeSRobert Watson 	db_print_inpflags(inp->inp_flags);
3083497057eeSRobert Watson 	db_printf(")\n");
3084497057eeSRobert Watson 
3085497057eeSRobert Watson 	db_print_indent(indent);
3086497057eeSRobert Watson 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3087497057eeSRobert Watson 	    inp->inp_vflag);
3088497057eeSRobert Watson 	db_print_inpvflag(inp->inp_vflag);
3089497057eeSRobert Watson 	db_printf(")\n");
3090497057eeSRobert Watson 
3091497057eeSRobert Watson 	db_print_indent(indent);
3092497057eeSRobert Watson 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3093497057eeSRobert Watson 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3094497057eeSRobert Watson 
3095497057eeSRobert Watson 	db_print_indent(indent);
3096497057eeSRobert Watson #ifdef INET6
3097497057eeSRobert Watson 	if (inp->inp_vflag & INP_IPV6) {
3098497057eeSRobert Watson 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
3099497057eeSRobert Watson 		    "in6p_moptions: %p\n", inp->in6p_options,
3100497057eeSRobert Watson 		    inp->in6p_outputopts, inp->in6p_moptions);
3101497057eeSRobert Watson 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3102497057eeSRobert Watson 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3103497057eeSRobert Watson 		    inp->in6p_hops);
3104497057eeSRobert Watson 	} else
3105497057eeSRobert Watson #endif
3106497057eeSRobert Watson 	{
3107497057eeSRobert Watson 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3108497057eeSRobert Watson 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3109497057eeSRobert Watson 		    inp->inp_options, inp->inp_moptions);
3110497057eeSRobert Watson 	}
3111497057eeSRobert Watson 
3112497057eeSRobert Watson 	db_print_indent(indent);
3113497057eeSRobert Watson 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
3114497057eeSRobert Watson 	    (uintmax_t)inp->inp_gencnt);
3115497057eeSRobert Watson }
3116497057eeSRobert Watson 
3117497057eeSRobert Watson DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3118497057eeSRobert Watson {
3119497057eeSRobert Watson 	struct inpcb *inp;
3120497057eeSRobert Watson 
3121497057eeSRobert Watson 	if (!have_addr) {
3122497057eeSRobert Watson 		db_printf("usage: show inpcb <addr>\n");
3123497057eeSRobert Watson 		return;
3124497057eeSRobert Watson 	}
3125497057eeSRobert Watson 	inp = (struct inpcb *)addr;
3126497057eeSRobert Watson 
3127497057eeSRobert Watson 	db_print_inpcb(inp, "inpcb", 0);
3128497057eeSRobert Watson }
312983e521ecSBjoern A. Zeeb #endif /* DDB */
3130f3e7afe2SHans Petter Selasky 
3131f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
3132f3e7afe2SHans Petter Selasky /*
3133f3e7afe2SHans Petter Selasky  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3134f3e7afe2SHans Petter Selasky  * if any.
3135f3e7afe2SHans Petter Selasky  */
3136f3e7afe2SHans Petter Selasky int
3137f3e7afe2SHans Petter Selasky in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3138f3e7afe2SHans Petter Selasky {
3139f3e7afe2SHans Petter Selasky 	union if_snd_tag_modify_params params = {
3140f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
314120abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3142f3e7afe2SHans Petter Selasky 	};
3143f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3144f3e7afe2SHans Petter Selasky 	int error;
3145f3e7afe2SHans Petter Selasky 
3146f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3147f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3148f3e7afe2SHans Petter Selasky 		return (EINVAL);
3149f3e7afe2SHans Petter Selasky 
3150c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_modify == NULL) {
3151f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3152f3e7afe2SHans Petter Selasky 	} else {
3153c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_modify(mst, &params);
3154f3e7afe2SHans Petter Selasky 	}
3155f3e7afe2SHans Petter Selasky 	return (error);
3156f3e7afe2SHans Petter Selasky }
3157f3e7afe2SHans Petter Selasky 
3158f3e7afe2SHans Petter Selasky /*
3159f3e7afe2SHans Petter Selasky  * Query existing TX rate limit based on the existing
3160f3e7afe2SHans Petter Selasky  * "inp->inp_snd_tag", if any.
3161f3e7afe2SHans Petter Selasky  */
3162f3e7afe2SHans Petter Selasky int
3163f3e7afe2SHans Petter Selasky in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3164f3e7afe2SHans Petter Selasky {
3165f3e7afe2SHans Petter Selasky 	union if_snd_tag_query_params params = { };
3166f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3167f3e7afe2SHans Petter Selasky 	int error;
3168f3e7afe2SHans Petter Selasky 
3169f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3170f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3171f3e7afe2SHans Petter Selasky 		return (EINVAL);
3172f3e7afe2SHans Petter Selasky 
3173c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL) {
3174f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3175f3e7afe2SHans Petter Selasky 	} else {
3176c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_query(mst, &params);
3177f3e7afe2SHans Petter Selasky 		if (error == 0 && p_max_pacing_rate != NULL)
3178f3e7afe2SHans Petter Selasky 			*p_max_pacing_rate = params.rate_limit.max_rate;
3179f3e7afe2SHans Petter Selasky 	}
3180f3e7afe2SHans Petter Selasky 	return (error);
3181f3e7afe2SHans Petter Selasky }
3182f3e7afe2SHans Petter Selasky 
3183f3e7afe2SHans Petter Selasky /*
318495ed5015SHans Petter Selasky  * Query existing TX queue level based on the existing
318595ed5015SHans Petter Selasky  * "inp->inp_snd_tag", if any.
318695ed5015SHans Petter Selasky  */
318795ed5015SHans Petter Selasky int
318895ed5015SHans Petter Selasky in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
318995ed5015SHans Petter Selasky {
319095ed5015SHans Petter Selasky 	union if_snd_tag_query_params params = { };
319195ed5015SHans Petter Selasky 	struct m_snd_tag *mst;
319295ed5015SHans Petter Selasky 	int error;
319395ed5015SHans Petter Selasky 
319495ed5015SHans Petter Selasky 	mst = inp->inp_snd_tag;
319595ed5015SHans Petter Selasky 	if (mst == NULL)
319695ed5015SHans Petter Selasky 		return (EINVAL);
319795ed5015SHans Petter Selasky 
3198c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL)
319995ed5015SHans Petter Selasky 		return (EOPNOTSUPP);
320095ed5015SHans Petter Selasky 
3201c782ea8bSJohn Baldwin 	error = mst->sw->snd_tag_query(mst, &params);
320295ed5015SHans Petter Selasky 	if (error == 0 && p_txqueue_level != NULL)
320395ed5015SHans Petter Selasky 		*p_txqueue_level = params.rate_limit.queue_level;
320495ed5015SHans Petter Selasky 	return (error);
320595ed5015SHans Petter Selasky }
320695ed5015SHans Petter Selasky 
320795ed5015SHans Petter Selasky /*
3208f3e7afe2SHans Petter Selasky  * Allocate a new TX rate limit send tag from the network interface
3209f3e7afe2SHans Petter Selasky  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3210f3e7afe2SHans Petter Selasky  */
3211f3e7afe2SHans Petter Selasky int
3212f3e7afe2SHans Petter Selasky in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
321320abea66SRandall Stewart     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
321420abea66SRandall Stewart 
3215f3e7afe2SHans Petter Selasky {
3216f3e7afe2SHans Petter Selasky 	union if_snd_tag_alloc_params params = {
321795ed5015SHans Petter Selasky 		.rate_limit.hdr.type = (max_pacing_rate == -1U) ?
321895ed5015SHans Petter Selasky 		    IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3219f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowid = flowid,
3220f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowtype = flowtype,
322198085baeSAndrew Gallatin 		.rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3222f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
322320abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3224f3e7afe2SHans Petter Selasky 	};
3225f3e7afe2SHans Petter Selasky 	int error;
3226f3e7afe2SHans Petter Selasky 
3227f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3228f3e7afe2SHans Petter Selasky 
322985d8d30fSHans Petter Selasky 	/*
323085d8d30fSHans Petter Selasky 	 * If there is already a send tag, or the INP is being torn
323185d8d30fSHans Petter Selasky 	 * down, allocating a new send tag is not allowed. Else send
323285d8d30fSHans Petter Selasky 	 * tags may leak.
323385d8d30fSHans Petter Selasky 	 */
323485d8d30fSHans Petter Selasky 	if (*st != NULL || (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0)
3235f3e7afe2SHans Petter Selasky 		return (EINVAL);
3236f3e7afe2SHans Petter Selasky 
323736e0a362SJohn Baldwin 	error = m_snd_tag_alloc(ifp, &params, st);
3238903c4ee6SXin LI #ifdef INET
323920abea66SRandall Stewart 	if (error == 0) {
324020abea66SRandall Stewart 		counter_u64_add(rate_limit_set_ok, 1);
324120abea66SRandall Stewart 		counter_u64_add(rate_limit_active, 1);
324236e0a362SJohn Baldwin 	} else if (error != EOPNOTSUPP)
324320abea66SRandall Stewart 		  counter_u64_add(rate_limit_alloc_fail, 1);
3244903c4ee6SXin LI #endif
3245f3e7afe2SHans Petter Selasky 	return (error);
3246f3e7afe2SHans Petter Selasky }
3247f3e7afe2SHans Petter Selasky 
324820abea66SRandall Stewart void
324998d7a8d9SJohn Baldwin in_pcbdetach_tag(struct m_snd_tag *mst)
325020abea66SRandall Stewart {
325120abea66SRandall Stewart 
325298d7a8d9SJohn Baldwin 	m_snd_tag_rele(mst);
3253903c4ee6SXin LI #ifdef INET
325420abea66SRandall Stewart 	counter_u64_add(rate_limit_active, -1);
3255903c4ee6SXin LI #endif
325620abea66SRandall Stewart }
325720abea66SRandall Stewart 
3258f3e7afe2SHans Petter Selasky /*
3259f3e7afe2SHans Petter Selasky  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3260f3e7afe2SHans Petter Selasky  * if any:
3261f3e7afe2SHans Petter Selasky  */
3262f3e7afe2SHans Petter Selasky void
3263f3e7afe2SHans Petter Selasky in_pcbdetach_txrtlmt(struct inpcb *inp)
3264f3e7afe2SHans Petter Selasky {
3265f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3266f3e7afe2SHans Petter Selasky 
3267f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3268f3e7afe2SHans Petter Selasky 
3269f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3270f3e7afe2SHans Petter Selasky 	inp->inp_snd_tag = NULL;
3271f3e7afe2SHans Petter Selasky 
3272f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3273f3e7afe2SHans Petter Selasky 		return;
3274f3e7afe2SHans Petter Selasky 
3275fb3bc596SJohn Baldwin 	m_snd_tag_rele(mst);
3276093e7231SHans Petter Selasky #ifdef INET
3277093e7231SHans Petter Selasky 	counter_u64_add(rate_limit_active, -1);
3278093e7231SHans Petter Selasky #endif
3279f3e7afe2SHans Petter Selasky }
3280f3e7afe2SHans Petter Selasky 
328120abea66SRandall Stewart int
328220abea66SRandall Stewart in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
328320abea66SRandall Stewart {
328420abea66SRandall Stewart 	int error;
328520abea66SRandall Stewart 
328620abea66SRandall Stewart 	/*
328720abea66SRandall Stewart 	 * If the existing send tag is for the wrong interface due to
328820abea66SRandall Stewart 	 * a route change, first drop the existing tag.  Set the
328920abea66SRandall Stewart 	 * CHANGED flag so that we will keep trying to allocate a new
329020abea66SRandall Stewart 	 * tag if we fail to allocate one this time.
329120abea66SRandall Stewart 	 */
329220abea66SRandall Stewart 	if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
329320abea66SRandall Stewart 		in_pcbdetach_txrtlmt(inp);
329420abea66SRandall Stewart 		inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
329520abea66SRandall Stewart 	}
329620abea66SRandall Stewart 
329720abea66SRandall Stewart 	/*
329820abea66SRandall Stewart 	 * NOTE: When attaching to a network interface a reference is
329920abea66SRandall Stewart 	 * made to ensure the network interface doesn't go away until
330020abea66SRandall Stewart 	 * all ratelimit connections are gone. The network interface
330120abea66SRandall Stewart 	 * pointers compared below represent valid network interfaces,
330220abea66SRandall Stewart 	 * except when comparing towards NULL.
330320abea66SRandall Stewart 	 */
330420abea66SRandall Stewart 	if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
330520abea66SRandall Stewart 		error = 0;
330620abea66SRandall Stewart 	} else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
330720abea66SRandall Stewart 		if (inp->inp_snd_tag != NULL)
330820abea66SRandall Stewart 			in_pcbdetach_txrtlmt(inp);
330920abea66SRandall Stewart 		error = 0;
331020abea66SRandall Stewart 	} else if (inp->inp_snd_tag == NULL) {
331120abea66SRandall Stewart 		/*
331220abea66SRandall Stewart 		 * In order to utilize packet pacing with RSS, we need
331320abea66SRandall Stewart 		 * to wait until there is a valid RSS hash before we
331420abea66SRandall Stewart 		 * can proceed:
331520abea66SRandall Stewart 		 */
331620abea66SRandall Stewart 		if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
331720abea66SRandall Stewart 			error = EAGAIN;
331820abea66SRandall Stewart 		} else {
331920abea66SRandall Stewart 			error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
332020abea66SRandall Stewart 			    mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
332120abea66SRandall Stewart 		}
332220abea66SRandall Stewart 	} else {
332320abea66SRandall Stewart 		error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
332420abea66SRandall Stewart 	}
332520abea66SRandall Stewart 	if (error == 0 || error == EOPNOTSUPP)
332620abea66SRandall Stewart 		inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
332720abea66SRandall Stewart 
332820abea66SRandall Stewart 	return (error);
332920abea66SRandall Stewart }
333020abea66SRandall Stewart 
3331f3e7afe2SHans Petter Selasky /*
3332f3e7afe2SHans Petter Selasky  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3333f3e7afe2SHans Petter Selasky  * is set in the fast path and will attach/detach/modify the TX rate
3334f3e7afe2SHans Petter Selasky  * limit send tag based on the socket's so_max_pacing_rate value.
3335f3e7afe2SHans Petter Selasky  */
3336f3e7afe2SHans Petter Selasky void
3337f3e7afe2SHans Petter Selasky in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3338f3e7afe2SHans Petter Selasky {
3339f3e7afe2SHans Petter Selasky 	struct socket *socket;
3340f3e7afe2SHans Petter Selasky 	uint32_t max_pacing_rate;
3341f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3342f3e7afe2SHans Petter Selasky 	int error;
3343f3e7afe2SHans Petter Selasky 
3344f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3345f3e7afe2SHans Petter Selasky 		return;
3346f3e7afe2SHans Petter Selasky 
3347f3e7afe2SHans Petter Selasky 	socket = inp->inp_socket;
3348f3e7afe2SHans Petter Selasky 	if (socket == NULL)
3349f3e7afe2SHans Petter Selasky 		return;
3350f3e7afe2SHans Petter Selasky 
3351f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3352f3e7afe2SHans Petter Selasky 		/*
3353f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3354f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3355f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3356f3e7afe2SHans Petter Selasky 		 * write lock.
3357f3e7afe2SHans Petter Selasky 		 */
3358f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3359f3e7afe2SHans Petter Selasky 			return;
3360f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3361f3e7afe2SHans Petter Selasky 	} else {
3362f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3363f3e7afe2SHans Petter Selasky 	}
3364f3e7afe2SHans Petter Selasky 
3365f3e7afe2SHans Petter Selasky 	/*
3366f3e7afe2SHans Petter Selasky 	 * NOTE: The so_max_pacing_rate value is read unlocked,
3367f3e7afe2SHans Petter Selasky 	 * because atomic updates are not required since the variable
3368f3e7afe2SHans Petter Selasky 	 * is checked at every mbuf we send. It is assumed that the
3369f3e7afe2SHans Petter Selasky 	 * variable read itself will be atomic.
3370f3e7afe2SHans Petter Selasky 	 */
3371f3e7afe2SHans Petter Selasky 	max_pacing_rate = socket->so_max_pacing_rate;
3372f3e7afe2SHans Petter Selasky 
337320abea66SRandall Stewart 	error = in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3374fb3bc596SJohn Baldwin 
3375f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3376f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3377f3e7afe2SHans Petter Selasky }
3378f3e7afe2SHans Petter Selasky 
3379f3e7afe2SHans Petter Selasky /*
3380f3e7afe2SHans Petter Selasky  * Track route changes for TX rate limiting.
3381f3e7afe2SHans Petter Selasky  */
3382f3e7afe2SHans Petter Selasky void
3383f3e7afe2SHans Petter Selasky in_pcboutput_eagain(struct inpcb *inp)
3384f3e7afe2SHans Petter Selasky {
3385f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3386f3e7afe2SHans Petter Selasky 
3387f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3388f3e7afe2SHans Petter Selasky 		return;
3389f3e7afe2SHans Petter Selasky 
3390f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag == NULL)
3391f3e7afe2SHans Petter Selasky 		return;
3392f3e7afe2SHans Petter Selasky 
3393f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3394f3e7afe2SHans Petter Selasky 		/*
3395f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3396f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3397f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3398f3e7afe2SHans Petter Selasky 		 * write lock.
3399f3e7afe2SHans Petter Selasky 		 */
3400f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3401f3e7afe2SHans Petter Selasky 			return;
3402f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3403f3e7afe2SHans Petter Selasky 	} else {
3404f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3405f3e7afe2SHans Petter Selasky 	}
3406f3e7afe2SHans Petter Selasky 
3407f3e7afe2SHans Petter Selasky 	/* detach rate limiting */
3408f3e7afe2SHans Petter Selasky 	in_pcbdetach_txrtlmt(inp);
3409f3e7afe2SHans Petter Selasky 
3410f3e7afe2SHans Petter Selasky 	/* make sure new mbuf send tag allocation is made */
3411f3e7afe2SHans Petter Selasky 	inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3412f3e7afe2SHans Petter Selasky 
3413f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3414f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3415f3e7afe2SHans Petter Selasky }
341620abea66SRandall Stewart 
3417903c4ee6SXin LI #ifdef INET
341820abea66SRandall Stewart static void
341920abea66SRandall Stewart rl_init(void *st)
342020abea66SRandall Stewart {
34211a714ff2SRandall Stewart 	rate_limit_new = counter_u64_alloc(M_WAITOK);
34221a714ff2SRandall Stewart 	rate_limit_chg = counter_u64_alloc(M_WAITOK);
342320abea66SRandall Stewart 	rate_limit_active = counter_u64_alloc(M_WAITOK);
342420abea66SRandall Stewart 	rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
342520abea66SRandall Stewart 	rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
342620abea66SRandall Stewart }
342720abea66SRandall Stewart 
342820abea66SRandall Stewart SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3429903c4ee6SXin LI #endif
3430f3e7afe2SHans Petter Selasky #endif /* RATELIMIT */
3431