xref: /freebsd/sys/netinet/in_pcb.c (revision 98d7a8d9cddc1c3d2c0d4695da1294735a989070)
1c398230bSWarner Losh /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
42469dd60SGarrett Wollman  * Copyright (c) 1982, 1986, 1991, 1993, 1995
5497057eeSRobert Watson  *	The Regents of the University of California.
6111d57a6SRobert Watson  * Copyright (c) 2007-2009 Robert N. M. Watson
779bdc6e5SRobert Watson  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8497057eeSRobert Watson  * All rights reserved.
9df8bae1dSRodney W. Grimes  *
1079bdc6e5SRobert Watson  * Portions of this software were developed by Robert N. M. Watson under
1179bdc6e5SRobert Watson  * contract to Juniper Networks, Inc.
1279bdc6e5SRobert Watson  *
13df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
14df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
15df8bae1dSRodney W. Grimes  * are met:
16df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
17df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
18df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
19df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
20df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
21fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
22df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
23df8bae1dSRodney W. Grimes  *    without specific prior written permission.
24df8bae1dSRodney W. Grimes  *
25df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
36df8bae1dSRodney W. Grimes  *
372469dd60SGarrett Wollman  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
38df8bae1dSRodney W. Grimes  */
39df8bae1dSRodney W. Grimes 
404b421e2dSMike Silbersack #include <sys/cdefs.h>
414b421e2dSMike Silbersack __FBSDID("$FreeBSD$");
424b421e2dSMike Silbersack 
43497057eeSRobert Watson #include "opt_ddb.h"
446a800098SYoshinobu Inoue #include "opt_ipsec.h"
45efc76f72SBjoern A. Zeeb #include "opt_inet.h"
46cfa1ca9dSYoshinobu Inoue #include "opt_inet6.h"
47f3e7afe2SHans Petter Selasky #include "opt_ratelimit.h"
4852cd27cbSRobert Watson #include "opt_pcbgroup.h"
490c325f53SAlexander V. Chernikov #include "opt_route.h"
507527624eSRobert Watson #include "opt_rss.h"
51cfa1ca9dSYoshinobu Inoue 
52df8bae1dSRodney W. Grimes #include <sys/param.h>
53df8bae1dSRodney W. Grimes #include <sys/systm.h>
54cc0a3c8cSAndrey V. Elsukov #include <sys/lock.h>
55df8bae1dSRodney W. Grimes #include <sys/malloc.h>
56df8bae1dSRodney W. Grimes #include <sys/mbuf.h>
57aae49dd3SBjoern A. Zeeb #include <sys/callout.h>
58ea8d1492SAlexander V. Chernikov #include <sys/eventhandler.h>
59cfa1ca9dSYoshinobu Inoue #include <sys/domain.h>
60df8bae1dSRodney W. Grimes #include <sys/protosw.h>
61cc0a3c8cSAndrey V. Elsukov #include <sys/rmlock.h>
623ee9c3c4SRandall Stewart #include <sys/smp.h>
63df8bae1dSRodney W. Grimes #include <sys/socket.h>
64df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
65f3e7afe2SHans Petter Selasky #include <sys/sockio.h>
66acd3428bSRobert Watson #include <sys/priv.h>
67df8bae1dSRodney W. Grimes #include <sys/proc.h>
6879bdc6e5SRobert Watson #include <sys/refcount.h>
6975c13541SPoul-Henning Kamp #include <sys/jail.h>
70101f9fc8SPeter Wemm #include <sys/kernel.h>
71101f9fc8SPeter Wemm #include <sys/sysctl.h>
728781d8e9SBruce Evans 
73497057eeSRobert Watson #ifdef DDB
74497057eeSRobert Watson #include <ddb/ddb.h>
75497057eeSRobert Watson #endif
76497057eeSRobert Watson 
7769c2d429SJeff Roberson #include <vm/uma.h>
78df8bae1dSRodney W. Grimes 
79df8bae1dSRodney W. Grimes #include <net/if.h>
8076039bc8SGleb Smirnoff #include <net/if_var.h>
81cfa1ca9dSYoshinobu Inoue #include <net/if_types.h>
826d768226SGeorge V. Neville-Neil #include <net/if_llatbl.h>
83df8bae1dSRodney W. Grimes #include <net/route.h>
84b2bdc62aSAdrian Chadd #include <net/rss_config.h>
85530c0060SRobert Watson #include <net/vnet.h>
86df8bae1dSRodney W. Grimes 
8767107f45SBjoern A. Zeeb #if defined(INET) || defined(INET6)
88df8bae1dSRodney W. Grimes #include <netinet/in.h>
89df8bae1dSRodney W. Grimes #include <netinet/in_pcb.h>
9059854ecfSHans Petter Selasky #ifdef INET
9159854ecfSHans Petter Selasky #include <netinet/in_var.h>
929ac7c6cfSAlexander V. Chernikov #include <netinet/in_fib.h>
9359854ecfSHans Petter Selasky #endif
94df8bae1dSRodney W. Grimes #include <netinet/ip_var.h>
95340c35deSJonathan Lemon #include <netinet/tcp_var.h>
963ee9c3c4SRandall Stewart #ifdef TCPHPTS
973ee9c3c4SRandall Stewart #include <netinet/tcp_hpts.h>
983ee9c3c4SRandall Stewart #endif
995f311da2SMike Silbersack #include <netinet/udp.h>
1005f311da2SMike Silbersack #include <netinet/udp_var.h>
101cfa1ca9dSYoshinobu Inoue #ifdef INET6
102cfa1ca9dSYoshinobu Inoue #include <netinet/ip6.h>
103efc76f72SBjoern A. Zeeb #include <netinet6/in6_pcb.h>
10467107f45SBjoern A. Zeeb #include <netinet6/in6_var.h>
10567107f45SBjoern A. Zeeb #include <netinet6/ip6_var.h>
106cfa1ca9dSYoshinobu Inoue #endif /* INET6 */
1079ac7c6cfSAlexander V. Chernikov #include <net/route/nhop.h>
10859854ecfSHans Petter Selasky #endif
109cfa1ca9dSYoshinobu Inoue 
110fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
111b9234fafSSam Leffler 
112aed55708SRobert Watson #include <security/mac/mac_framework.h>
113aed55708SRobert Watson 
1141a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMIN	8
1151a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMAX	256
1161a43cff9SSean Bruno 
117aae49dd3SBjoern A. Zeeb static struct callout	ipport_tick_callout;
118aae49dd3SBjoern A. Zeeb 
119101f9fc8SPeter Wemm /*
120101f9fc8SPeter Wemm  * These configure the range of local port addresses assigned to
121101f9fc8SPeter Wemm  * "unspecified" outgoing connections/packets/whatever.
122101f9fc8SPeter Wemm  */
123eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
124eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
125eddfbb76SRobert Watson VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
126eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
127eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
128eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
129101f9fc8SPeter Wemm 
130b0d22693SCrist J. Clark /*
131b0d22693SCrist J. Clark  * Reserved ports accessible only to root. There are significant
132b0d22693SCrist J. Clark  * security considerations that must be accounted for when changing these,
133b0d22693SCrist J. Clark  * but the security benefits can be great. Please be careful.
134b0d22693SCrist J. Clark  */
135eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
136eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedlow);
137b0d22693SCrist J. Clark 
1385f311da2SMike Silbersack /* Variables dealing with random ephemeral port allocation. */
139eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomized) = 1;	/* user controlled via sysctl */
140eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomcps) = 10;	/* user controlled via sysctl */
141eddfbb76SRobert Watson VNET_DEFINE(int, ipport_randomtime) = 45;	/* user controlled via sysctl */
142eddfbb76SRobert Watson VNET_DEFINE(int, ipport_stoprandom);		/* toggled by ipport_tick */
143eddfbb76SRobert Watson VNET_DEFINE(int, ipport_tcpallocs);
1445f901c92SAndrew Turner VNET_DEFINE_STATIC(int, ipport_tcplastcount);
145eddfbb76SRobert Watson 
1461e77c105SRobert Watson #define	V_ipport_tcplastcount		VNET(ipport_tcplastcount)
1476ac48b74SMike Silbersack 
148d2025bd0SBjoern A. Zeeb static void	in_pcbremlists(struct inpcb *inp);
149d2025bd0SBjoern A. Zeeb #ifdef INET
150fa046d87SRobert Watson static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
151fa046d87SRobert Watson 			    struct in_addr faddr, u_int fport_arg,
152fa046d87SRobert Watson 			    struct in_addr laddr, u_int lport_arg,
153fa046d87SRobert Watson 			    int lookupflags, struct ifnet *ifp);
15467107f45SBjoern A. Zeeb 
155bbd42ad0SPeter Wemm #define RANGECHK(var, min, max) \
156bbd42ad0SPeter Wemm 	if ((var) < (min)) { (var) = (min); } \
157bbd42ad0SPeter Wemm 	else if ((var) > (max)) { (var) = (max); }
158bbd42ad0SPeter Wemm 
159bbd42ad0SPeter Wemm static int
16082d9ae4eSPoul-Henning Kamp sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
161bbd42ad0SPeter Wemm {
16230a4ab08SBruce Evans 	int error;
16330a4ab08SBruce Evans 
164f6dfe47aSMarko Zec 	error = sysctl_handle_int(oidp, arg1, arg2, req);
16530a4ab08SBruce Evans 	if (error == 0) {
166603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
167603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
168603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
169603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
170603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
171603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
172bbd42ad0SPeter Wemm 	}
17330a4ab08SBruce Evans 	return (error);
174bbd42ad0SPeter Wemm }
175bbd42ad0SPeter Wemm 
176bbd42ad0SPeter Wemm #undef RANGECHK
177bbd42ad0SPeter Wemm 
1787029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
1797029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1806472ac3dSEd Schouten     "IP Ports");
18133b3ac06SPeter Wemm 
1826df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
1837029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1847029da5cSPawel Biernacki     &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
1857029da5cSPawel Biernacki     "");
1866df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
1877029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1887029da5cSPawel Biernacki     &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
1897029da5cSPawel Biernacki     "");
1906df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
1917029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1927029da5cSPawel Biernacki     &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
1937029da5cSPawel Biernacki     "");
1946df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
1957029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1967029da5cSPawel Biernacki     &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
1977029da5cSPawel Biernacki     "");
1986df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
1997029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
2007029da5cSPawel Biernacki     &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
2017029da5cSPawel Biernacki     "");
2026df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
2037029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
2047029da5cSPawel Biernacki     &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
2057029da5cSPawel Biernacki     "");
2066df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
2076df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
2086df8a710SGleb Smirnoff 	&VNET_NAME(ipport_reservedhigh), 0, "");
2096df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
210eddfbb76SRobert Watson 	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
2116df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
2126df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
213eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
2146df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
2156df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
216eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
2176ee79c59SMaxim Konovalov 	"allocations before switching to a sequental one");
2186df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
2196df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
220eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomtime), 0,
2218b615593SMarko Zec 	"Minimum time to keep sequental port "
2226ee79c59SMaxim Konovalov 	"allocation before switching to a random one");
22320abea66SRandall Stewart 
22420abea66SRandall Stewart #ifdef RATELIMIT
22520abea66SRandall Stewart counter_u64_t rate_limit_active;
22620abea66SRandall Stewart counter_u64_t rate_limit_alloc_fail;
22720abea66SRandall Stewart counter_u64_t rate_limit_set_ok;
22820abea66SRandall Stewart 
2297029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
23020abea66SRandall Stewart     "IP Rate Limiting");
23120abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
23220abea66SRandall Stewart     &rate_limit_active, "Active rate limited connections");
23320abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
23420abea66SRandall Stewart    &rate_limit_alloc_fail, "Rate limited connection failures");
23520abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
23620abea66SRandall Stewart    &rate_limit_set_ok, "Rate limited setting succeeded");
23720abea66SRandall Stewart #endif /* RATELIMIT */
23820abea66SRandall Stewart 
23983e521ecSBjoern A. Zeeb #endif /* INET */
2400312fbe9SPoul-Henning Kamp 
241c3229e05SDavid Greenman /*
242c3229e05SDavid Greenman  * in_pcb.c: manage the Protocol Control Blocks.
243c3229e05SDavid Greenman  *
244de35559fSRobert Watson  * NOTE: It is assumed that most of these functions will be called with
245de35559fSRobert Watson  * the pcbinfo lock held, and often, the inpcb lock held, as these utility
246de35559fSRobert Watson  * functions often modify hash chains or addresses in pcbs.
247c3229e05SDavid Greenman  */
248c3229e05SDavid Greenman 
2491a43cff9SSean Bruno static struct inpcblbgroup *
2501a43cff9SSean Bruno in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, u_char vflag,
2511a43cff9SSean Bruno     uint16_t port, const union in_dependaddr *addr, int size)
2521a43cff9SSean Bruno {
2531a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2541a43cff9SSean Bruno 	size_t bytes;
2551a43cff9SSean Bruno 
2561a43cff9SSean Bruno 	bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
2571a43cff9SSean Bruno 	grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
2581a43cff9SSean Bruno 	if (!grp)
2591a43cff9SSean Bruno 		return (NULL);
2601a43cff9SSean Bruno 	grp->il_vflag = vflag;
2611a43cff9SSean Bruno 	grp->il_lport = port;
2621a43cff9SSean Bruno 	grp->il_dependladdr = *addr;
2631a43cff9SSean Bruno 	grp->il_inpsiz = size;
26454af3d0dSMark Johnston 	CK_LIST_INSERT_HEAD(hdr, grp, il_list);
2651a43cff9SSean Bruno 	return (grp);
2661a43cff9SSean Bruno }
2671a43cff9SSean Bruno 
2681a43cff9SSean Bruno static void
26954af3d0dSMark Johnston in_pcblbgroup_free_deferred(epoch_context_t ctx)
27054af3d0dSMark Johnston {
27154af3d0dSMark Johnston 	struct inpcblbgroup *grp;
27254af3d0dSMark Johnston 
27354af3d0dSMark Johnston 	grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
27454af3d0dSMark Johnston 	free(grp, M_PCB);
27554af3d0dSMark Johnston }
27654af3d0dSMark Johnston 
27754af3d0dSMark Johnston static void
2781a43cff9SSean Bruno in_pcblbgroup_free(struct inpcblbgroup *grp)
2791a43cff9SSean Bruno {
2801a43cff9SSean Bruno 
28154af3d0dSMark Johnston 	CK_LIST_REMOVE(grp, il_list);
2822a4bd982SGleb Smirnoff 	NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
2831a43cff9SSean Bruno }
2841a43cff9SSean Bruno 
2851a43cff9SSean Bruno static struct inpcblbgroup *
2861a43cff9SSean Bruno in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
2871a43cff9SSean Bruno     struct inpcblbgroup *old_grp, int size)
2881a43cff9SSean Bruno {
2891a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2901a43cff9SSean Bruno 	int i;
2911a43cff9SSean Bruno 
2921a43cff9SSean Bruno 	grp = in_pcblbgroup_alloc(hdr, old_grp->il_vflag,
2931a43cff9SSean Bruno 	    old_grp->il_lport, &old_grp->il_dependladdr, size);
29479ee680bSMark Johnston 	if (grp == NULL)
2951a43cff9SSean Bruno 		return (NULL);
2961a43cff9SSean Bruno 
2971a43cff9SSean Bruno 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
2981a43cff9SSean Bruno 	    ("invalid new local group size %d and old local group count %d",
2991a43cff9SSean Bruno 	     grp->il_inpsiz, old_grp->il_inpcnt));
3001a43cff9SSean Bruno 
3011a43cff9SSean Bruno 	for (i = 0; i < old_grp->il_inpcnt; ++i)
3021a43cff9SSean Bruno 		grp->il_inp[i] = old_grp->il_inp[i];
3031a43cff9SSean Bruno 	grp->il_inpcnt = old_grp->il_inpcnt;
3041a43cff9SSean Bruno 	in_pcblbgroup_free(old_grp);
3051a43cff9SSean Bruno 	return (grp);
3061a43cff9SSean Bruno }
3071a43cff9SSean Bruno 
3081a43cff9SSean Bruno /*
3091a43cff9SSean Bruno  * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
3101a43cff9SSean Bruno  * and shrink group if possible.
3111a43cff9SSean Bruno  */
3121a43cff9SSean Bruno static void
3131a43cff9SSean Bruno in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
3141a43cff9SSean Bruno     int i)
3151a43cff9SSean Bruno {
31679ee680bSMark Johnston 	struct inpcblbgroup *grp, *new_grp;
3171a43cff9SSean Bruno 
31879ee680bSMark Johnston 	grp = *grpp;
3191a43cff9SSean Bruno 	for (; i + 1 < grp->il_inpcnt; ++i)
3201a43cff9SSean Bruno 		grp->il_inp[i] = grp->il_inp[i + 1];
3211a43cff9SSean Bruno 	grp->il_inpcnt--;
3221a43cff9SSean Bruno 
3231a43cff9SSean Bruno 	if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
32479ee680bSMark Johnston 	    grp->il_inpcnt <= grp->il_inpsiz / 4) {
3251a43cff9SSean Bruno 		/* Shrink this group. */
32679ee680bSMark Johnston 		new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
32779ee680bSMark Johnston 		if (new_grp != NULL)
3281a43cff9SSean Bruno 			*grpp = new_grp;
3291a43cff9SSean Bruno 	}
3301a43cff9SSean Bruno }
3311a43cff9SSean Bruno 
3321a43cff9SSean Bruno /*
3331a43cff9SSean Bruno  * Add PCB to load balance group for SO_REUSEPORT_LB option.
3341a43cff9SSean Bruno  */
3351a43cff9SSean Bruno static int
3361a43cff9SSean Bruno in_pcbinslbgrouphash(struct inpcb *inp)
3371a43cff9SSean Bruno {
338a7026c7fSMark Johnston 	const static struct timeval interval = { 60, 0 };
339a7026c7fSMark Johnston 	static struct timeval lastprint;
3401a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
3411a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
3421a43cff9SSean Bruno 	struct inpcblbgroup *grp;
34379ee680bSMark Johnston 	uint32_t idx;
3441a43cff9SSean Bruno 
3451a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
3461a43cff9SSean Bruno 
3471a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
3481a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
3491a43cff9SSean Bruno 
3501a43cff9SSean Bruno 	/*
3511a43cff9SSean Bruno 	 * Don't allow jailed socket to join local group.
3521a43cff9SSean Bruno 	 */
35379ee680bSMark Johnston 	if (inp->inp_socket != NULL && jailed(inp->inp_socket->so_cred))
3541a43cff9SSean Bruno 		return (0);
3551a43cff9SSean Bruno 
3561a43cff9SSean Bruno #ifdef INET6
3571a43cff9SSean Bruno 	/*
3581a43cff9SSean Bruno 	 * Don't allow IPv4 mapped INET6 wild socket.
3591a43cff9SSean Bruno 	 */
3601a43cff9SSean Bruno 	if ((inp->inp_vflag & INP_IPV4) &&
3611a43cff9SSean Bruno 	    inp->inp_laddr.s_addr == INADDR_ANY &&
3621a43cff9SSean Bruno 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
3631a43cff9SSean Bruno 		return (0);
3641a43cff9SSean Bruno 	}
3651a43cff9SSean Bruno #endif
3661a43cff9SSean Bruno 
3679d2877fcSMark Johnston 	idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
36879ee680bSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
36954af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
3701a43cff9SSean Bruno 		if (grp->il_vflag == inp->inp_vflag &&
3711a43cff9SSean Bruno 		    grp->il_lport == inp->inp_lport &&
3721a43cff9SSean Bruno 		    memcmp(&grp->il_dependladdr,
3731a43cff9SSean Bruno 		    &inp->inp_inc.inc_ie.ie_dependladdr,
37479ee680bSMark Johnston 		    sizeof(grp->il_dependladdr)) == 0)
3751a43cff9SSean Bruno 			break;
3761a43cff9SSean Bruno 	}
3771a43cff9SSean Bruno 	if (grp == NULL) {
3781a43cff9SSean Bruno 		/* Create new load balance group. */
3791a43cff9SSean Bruno 		grp = in_pcblbgroup_alloc(hdr, inp->inp_vflag,
3801a43cff9SSean Bruno 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
3811a43cff9SSean Bruno 		    INPCBLBGROUP_SIZMIN);
38279ee680bSMark Johnston 		if (grp == NULL)
3831a43cff9SSean Bruno 			return (ENOBUFS);
3841a43cff9SSean Bruno 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
3851a43cff9SSean Bruno 		if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
386a7026c7fSMark Johnston 			if (ratecheck(&lastprint, &interval))
3871a43cff9SSean Bruno 				printf("lb group port %d, limit reached\n",
3881a43cff9SSean Bruno 				    ntohs(grp->il_lport));
3891a43cff9SSean Bruno 			return (0);
3901a43cff9SSean Bruno 		}
3911a43cff9SSean Bruno 
3921a43cff9SSean Bruno 		/* Expand this local group. */
3931a43cff9SSean Bruno 		grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
39479ee680bSMark Johnston 		if (grp == NULL)
3951a43cff9SSean Bruno 			return (ENOBUFS);
3961a43cff9SSean Bruno 	}
3971a43cff9SSean Bruno 
3981a43cff9SSean Bruno 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
39979ee680bSMark Johnston 	    ("invalid local group size %d and count %d", grp->il_inpsiz,
40079ee680bSMark Johnston 	    grp->il_inpcnt));
4011a43cff9SSean Bruno 
4021a43cff9SSean Bruno 	grp->il_inp[grp->il_inpcnt] = inp;
4031a43cff9SSean Bruno 	grp->il_inpcnt++;
4041a43cff9SSean Bruno 	return (0);
4051a43cff9SSean Bruno }
4061a43cff9SSean Bruno 
4071a43cff9SSean Bruno /*
4081a43cff9SSean Bruno  * Remove PCB from load balance group.
4091a43cff9SSean Bruno  */
4101a43cff9SSean Bruno static void
4111a43cff9SSean Bruno in_pcbremlbgrouphash(struct inpcb *inp)
4121a43cff9SSean Bruno {
4131a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
4141a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
4151a43cff9SSean Bruno 	struct inpcblbgroup *grp;
4161a43cff9SSean Bruno 	int i;
4171a43cff9SSean Bruno 
4181a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
4191a43cff9SSean Bruno 
4201a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
4211a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
4221a43cff9SSean Bruno 
4231a43cff9SSean Bruno 	hdr = &pcbinfo->ipi_lbgrouphashbase[
4249d2877fcSMark Johnston 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
42554af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
4261a43cff9SSean Bruno 		for (i = 0; i < grp->il_inpcnt; ++i) {
4271a43cff9SSean Bruno 			if (grp->il_inp[i] != inp)
4281a43cff9SSean Bruno 				continue;
4291a43cff9SSean Bruno 
4301a43cff9SSean Bruno 			if (grp->il_inpcnt == 1) {
4311a43cff9SSean Bruno 				/* We are the last, free this local group. */
4321a43cff9SSean Bruno 				in_pcblbgroup_free(grp);
4331a43cff9SSean Bruno 			} else {
4341a43cff9SSean Bruno 				/* Pull up inpcbs, shrink group if possible. */
4351a43cff9SSean Bruno 				in_pcblbgroup_reorder(hdr, &grp, i);
4361a43cff9SSean Bruno 			}
4371a43cff9SSean Bruno 			return;
4381a43cff9SSean Bruno 		}
4391a43cff9SSean Bruno 	}
4401a43cff9SSean Bruno }
4411a43cff9SSean Bruno 
442c3229e05SDavid Greenman /*
443cc487c16SGleb Smirnoff  * Different protocols initialize their inpcbs differently - giving
444cc487c16SGleb Smirnoff  * different name to the lock.  But they all are disposed the same.
445cc487c16SGleb Smirnoff  */
446cc487c16SGleb Smirnoff static void
447cc487c16SGleb Smirnoff inpcb_fini(void *mem, int size)
448cc487c16SGleb Smirnoff {
449cc487c16SGleb Smirnoff 	struct inpcb *inp = mem;
450cc487c16SGleb Smirnoff 
451cc487c16SGleb Smirnoff 	INP_LOCK_DESTROY(inp);
452cc487c16SGleb Smirnoff }
453cc487c16SGleb Smirnoff 
454cc487c16SGleb Smirnoff /*
4559bcd427bSRobert Watson  * Initialize an inpcbinfo -- we should be able to reduce the number of
4569bcd427bSRobert Watson  * arguments in time.
4579bcd427bSRobert Watson  */
4589bcd427bSRobert Watson void
4599bcd427bSRobert Watson in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
4609bcd427bSRobert Watson     struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
461cc487c16SGleb Smirnoff     char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
4629bcd427bSRobert Watson {
4639bcd427bSRobert Watson 
4649d2877fcSMark Johnston 	porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
4659d2877fcSMark Johnston 
4669bcd427bSRobert Watson 	INP_INFO_LOCK_INIT(pcbinfo, name);
467fa046d87SRobert Watson 	INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash");	/* XXXRW: argument? */
468ff9b006dSJulien Charbon 	INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
4699bcd427bSRobert Watson #ifdef VIMAGE
4709bcd427bSRobert Watson 	pcbinfo->ipi_vnet = curvnet;
4719bcd427bSRobert Watson #endif
4729bcd427bSRobert Watson 	pcbinfo->ipi_listhead = listhead;
473b872626dSMatt Macy 	CK_LIST_INIT(pcbinfo->ipi_listhead);
474fa046d87SRobert Watson 	pcbinfo->ipi_count = 0;
4759bcd427bSRobert Watson 	pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
4769bcd427bSRobert Watson 	    &pcbinfo->ipi_hashmask);
4779bcd427bSRobert Watson 	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
4789bcd427bSRobert Watson 	    &pcbinfo->ipi_porthashmask);
4799d2877fcSMark Johnston 	pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
4801a43cff9SSean Bruno 	    &pcbinfo->ipi_lbgrouphashmask);
48152cd27cbSRobert Watson #ifdef PCBGROUP
48252cd27cbSRobert Watson 	in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
48352cd27cbSRobert Watson #endif
4849bcd427bSRobert Watson 	pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
485cc487c16SGleb Smirnoff 	    NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
4869bcd427bSRobert Watson 	uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
4876acd596eSPawel Jakub Dawidek 	uma_zone_set_warning(pcbinfo->ipi_zone,
4886acd596eSPawel Jakub Dawidek 	    "kern.ipc.maxsockets limit reached");
4899bcd427bSRobert Watson }
4909bcd427bSRobert Watson 
4919bcd427bSRobert Watson /*
4929bcd427bSRobert Watson  * Destroy an inpcbinfo.
4939bcd427bSRobert Watson  */
4949bcd427bSRobert Watson void
4959bcd427bSRobert Watson in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
4969bcd427bSRobert Watson {
4979bcd427bSRobert Watson 
498fa046d87SRobert Watson 	KASSERT(pcbinfo->ipi_count == 0,
499fa046d87SRobert Watson 	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
500fa046d87SRobert Watson 
5019bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
5029bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
5039bcd427bSRobert Watson 	    pcbinfo->ipi_porthashmask);
5041a43cff9SSean Bruno 	hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
5051a43cff9SSean Bruno 	    pcbinfo->ipi_lbgrouphashmask);
50652cd27cbSRobert Watson #ifdef PCBGROUP
50752cd27cbSRobert Watson 	in_pcbgroup_destroy(pcbinfo);
50852cd27cbSRobert Watson #endif
5099bcd427bSRobert Watson 	uma_zdestroy(pcbinfo->ipi_zone);
510ff9b006dSJulien Charbon 	INP_LIST_LOCK_DESTROY(pcbinfo);
511fa046d87SRobert Watson 	INP_HASH_LOCK_DESTROY(pcbinfo);
5129bcd427bSRobert Watson 	INP_INFO_LOCK_DESTROY(pcbinfo);
5139bcd427bSRobert Watson }
5149bcd427bSRobert Watson 
5159bcd427bSRobert Watson /*
516c3229e05SDavid Greenman  * Allocate a PCB and associate it with the socket.
517d915b280SStephan Uphoff  * On success return with the PCB locked.
518c3229e05SDavid Greenman  */
519df8bae1dSRodney W. Grimes int
520d915b280SStephan Uphoff in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
521df8bae1dSRodney W. Grimes {
522136d4f1cSRobert Watson 	struct inpcb *inp;
52313cf67f3SHajimu UMEMOTO 	int error;
524a557af22SRobert Watson 
525a557af22SRobert Watson 	error = 0;
526d915b280SStephan Uphoff 	inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
527df8bae1dSRodney W. Grimes 	if (inp == NULL)
528df8bae1dSRodney W. Grimes 		return (ENOBUFS);
5296a6cefacSGleb Smirnoff 	bzero(&inp->inp_start_zero, inp_zero_size);
53050575ce1SAndrew Gallatin #ifdef NUMA
53150575ce1SAndrew Gallatin 	inp->inp_numa_domain = M_NODOM;
53250575ce1SAndrew Gallatin #endif
53315bd2b43SDavid Greenman 	inp->inp_pcbinfo = pcbinfo;
534df8bae1dSRodney W. Grimes 	inp->inp_socket = so;
53586d02c5cSBjoern A. Zeeb 	inp->inp_cred = crhold(so->so_cred);
5368b07e49aSJulian Elischer 	inp->inp_inc.inc_fibnum = so->so_fibnum;
537a557af22SRobert Watson #ifdef MAC
53830d239bcSRobert Watson 	error = mac_inpcb_init(inp, M_NOWAIT);
539a557af22SRobert Watson 	if (error != 0)
540a557af22SRobert Watson 		goto out;
54130d239bcSRobert Watson 	mac_inpcb_create(so, inp);
542a557af22SRobert Watson #endif
543fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
544fcf59617SAndrey V. Elsukov 	error = ipsec_init_pcbpolicy(inp);
5450bffde27SRobert Watson 	if (error != 0) {
5460bffde27SRobert Watson #ifdef MAC
5470bffde27SRobert Watson 		mac_inpcb_destroy(inp);
5480bffde27SRobert Watson #endif
549a557af22SRobert Watson 		goto out;
5500bffde27SRobert Watson 	}
551b2630c29SGeorge V. Neville-Neil #endif /*IPSEC*/
552e3fd5ffdSRobert Watson #ifdef INET6
553340c35deSJonathan Lemon 	if (INP_SOCKAF(so) == AF_INET6) {
554340c35deSJonathan Lemon 		inp->inp_vflag |= INP_IPV6PROTO;
555603724d3SBjoern A. Zeeb 		if (V_ip6_v6only)
55633841545SHajimu UMEMOTO 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
557340c35deSJonathan Lemon 	}
55875daea93SPaul Saab #endif
559ff9b006dSJulien Charbon 	INP_WLOCK(inp);
560ff9b006dSJulien Charbon 	INP_LIST_WLOCK(pcbinfo);
561b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
5623d4d47f3SGarrett Wollman 	pcbinfo->ipi_count++;
563df8bae1dSRodney W. Grimes 	so->so_pcb = (caddr_t)inp;
56433841545SHajimu UMEMOTO #ifdef INET6
565603724d3SBjoern A. Zeeb 	if (V_ip6_auto_flowlabel)
56633841545SHajimu UMEMOTO 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
56733841545SHajimu UMEMOTO #endif
568d915b280SStephan Uphoff 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
56979bdc6e5SRobert Watson 	refcount_init(&inp->inp_refcount, 1);	/* Reference from inpcbinfo */
5708c1960d5SMike Karels 
5718c1960d5SMike Karels 	/*
5728c1960d5SMike Karels 	 * Routes in inpcb's can cache L2 as well; they are guaranteed
5738c1960d5SMike Karels 	 * to be cleaned up.
5748c1960d5SMike Karels 	 */
5758c1960d5SMike Karels 	inp->inp_route.ro_flags = RT_LLE_CACHE;
576ff9b006dSJulien Charbon 	INP_LIST_WUNLOCK(pcbinfo);
5777a60a910SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
578a557af22SRobert Watson out:
57986d02c5cSBjoern A. Zeeb 	if (error != 0) {
58086d02c5cSBjoern A. Zeeb 		crfree(inp->inp_cred);
581a557af22SRobert Watson 		uma_zfree(pcbinfo->ipi_zone, inp);
58286d02c5cSBjoern A. Zeeb 	}
583a557af22SRobert Watson #endif
584a557af22SRobert Watson 	return (error);
585df8bae1dSRodney W. Grimes }
586df8bae1dSRodney W. Grimes 
58767107f45SBjoern A. Zeeb #ifdef INET
588df8bae1dSRodney W. Grimes int
589136d4f1cSRobert Watson in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
590df8bae1dSRodney W. Grimes {
5914b932371SIan Dowse 	int anonport, error;
5924b932371SIan Dowse 
5938501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
594fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
59559daba27SSam Leffler 
5964b932371SIan Dowse 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
5974b932371SIan Dowse 		return (EINVAL);
5985cd3dcaaSNavdeep Parhar 	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
5994b932371SIan Dowse 	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
600b0330ed9SPawel Jakub Dawidek 	    &inp->inp_lport, cred);
6014b932371SIan Dowse 	if (error)
6024b932371SIan Dowse 		return (error);
6034b932371SIan Dowse 	if (in_pcbinshash(inp) != 0) {
6044b932371SIan Dowse 		inp->inp_laddr.s_addr = INADDR_ANY;
6054b932371SIan Dowse 		inp->inp_lport = 0;
6064b932371SIan Dowse 		return (EAGAIN);
6074b932371SIan Dowse 	}
6084b932371SIan Dowse 	if (anonport)
6094b932371SIan Dowse 		inp->inp_flags |= INP_ANONPORT;
6104b932371SIan Dowse 	return (0);
6114b932371SIan Dowse }
61267107f45SBjoern A. Zeeb #endif
6134b932371SIan Dowse 
614efc76f72SBjoern A. Zeeb #if defined(INET) || defined(INET6)
61525102351SMike Karels /*
61625102351SMike Karels  * Assign a local port like in_pcb_lport(), but also used with connect()
61725102351SMike Karels  * and a foreign address and port.  If fsa is non-NULL, choose a local port
61825102351SMike Karels  * that is unused with those, otherwise one that is completely unused.
6192fdbcbeaSMike Karels  * lsa can be NULL for IPv6.
62025102351SMike Karels  */
621efc76f72SBjoern A. Zeeb int
62225102351SMike Karels in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
62325102351SMike Karels     struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
624efc76f72SBjoern A. Zeeb {
625efc76f72SBjoern A. Zeeb 	struct inpcbinfo *pcbinfo;
626efc76f72SBjoern A. Zeeb 	struct inpcb *tmpinp;
627efc76f72SBjoern A. Zeeb 	unsigned short *lastport;
628efc76f72SBjoern A. Zeeb 	int count, dorandom, error;
629efc76f72SBjoern A. Zeeb 	u_short aux, first, last, lport;
630efc76f72SBjoern A. Zeeb #ifdef INET
63125102351SMike Karels 	struct in_addr laddr, faddr;
63225102351SMike Karels #endif
63325102351SMike Karels #ifdef INET6
63425102351SMike Karels 	struct in6_addr *laddr6, *faddr6;
635efc76f72SBjoern A. Zeeb #endif
636efc76f72SBjoern A. Zeeb 
637efc76f72SBjoern A. Zeeb 	pcbinfo = inp->inp_pcbinfo;
638efc76f72SBjoern A. Zeeb 
639efc76f72SBjoern A. Zeeb 	/*
640efc76f72SBjoern A. Zeeb 	 * Because no actual state changes occur here, a global write lock on
641efc76f72SBjoern A. Zeeb 	 * the pcbinfo isn't required.
642efc76f72SBjoern A. Zeeb 	 */
643efc76f72SBjoern A. Zeeb 	INP_LOCK_ASSERT(inp);
644fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
645efc76f72SBjoern A. Zeeb 
646efc76f72SBjoern A. Zeeb 	if (inp->inp_flags & INP_HIGHPORT) {
647efc76f72SBjoern A. Zeeb 		first = V_ipport_hifirstauto;	/* sysctl */
648efc76f72SBjoern A. Zeeb 		last  = V_ipport_hilastauto;
649efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lasthi;
650efc76f72SBjoern A. Zeeb 	} else if (inp->inp_flags & INP_LOWPORT) {
651cc426dd3SMateusz Guzik 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
652efc76f72SBjoern A. Zeeb 		if (error)
653efc76f72SBjoern A. Zeeb 			return (error);
654efc76f72SBjoern A. Zeeb 		first = V_ipport_lowfirstauto;	/* 1023 */
655efc76f72SBjoern A. Zeeb 		last  = V_ipport_lowlastauto;	/* 600 */
656efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastlow;
657efc76f72SBjoern A. Zeeb 	} else {
658efc76f72SBjoern A. Zeeb 		first = V_ipport_firstauto;	/* sysctl */
659efc76f72SBjoern A. Zeeb 		last  = V_ipport_lastauto;
660efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastport;
661efc76f72SBjoern A. Zeeb 	}
662efc76f72SBjoern A. Zeeb 	/*
663e06e816fSKevin Lo 	 * For UDP(-Lite), use random port allocation as long as the user
664efc76f72SBjoern A. Zeeb 	 * allows it.  For TCP (and as of yet unknown) connections,
665efc76f72SBjoern A. Zeeb 	 * use random port allocation only if the user allows it AND
666efc76f72SBjoern A. Zeeb 	 * ipport_tick() allows it.
667efc76f72SBjoern A. Zeeb 	 */
668efc76f72SBjoern A. Zeeb 	if (V_ipport_randomized &&
669e06e816fSKevin Lo 		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
670e06e816fSKevin Lo 		pcbinfo == &V_ulitecbinfo))
671efc76f72SBjoern A. Zeeb 		dorandom = 1;
672efc76f72SBjoern A. Zeeb 	else
673efc76f72SBjoern A. Zeeb 		dorandom = 0;
674efc76f72SBjoern A. Zeeb 	/*
675efc76f72SBjoern A. Zeeb 	 * It makes no sense to do random port allocation if
676efc76f72SBjoern A. Zeeb 	 * we have the only port available.
677efc76f72SBjoern A. Zeeb 	 */
678efc76f72SBjoern A. Zeeb 	if (first == last)
679efc76f72SBjoern A. Zeeb 		dorandom = 0;
680e06e816fSKevin Lo 	/* Make sure to not include UDP(-Lite) packets in the count. */
681e06e816fSKevin Lo 	if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
682efc76f72SBjoern A. Zeeb 		V_ipport_tcpallocs++;
683efc76f72SBjoern A. Zeeb 	/*
684efc76f72SBjoern A. Zeeb 	 * Instead of having two loops further down counting up or down
685efc76f72SBjoern A. Zeeb 	 * make sure that first is always <= last and go with only one
686efc76f72SBjoern A. Zeeb 	 * code path implementing all logic.
687efc76f72SBjoern A. Zeeb 	 */
688efc76f72SBjoern A. Zeeb 	if (first > last) {
689efc76f72SBjoern A. Zeeb 		aux = first;
690efc76f72SBjoern A. Zeeb 		first = last;
691efc76f72SBjoern A. Zeeb 		last = aux;
692efc76f72SBjoern A. Zeeb 	}
693efc76f72SBjoern A. Zeeb 
694efc76f72SBjoern A. Zeeb #ifdef INET
69525102351SMike Karels 	laddr.s_addr = INADDR_ANY;
6964d457387SBjoern A. Zeeb 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
6972fdbcbeaSMike Karels 		if (lsa != NULL)
69825102351SMike Karels 			laddr = ((struct sockaddr_in *)lsa)->sin_addr;
69925102351SMike Karels 		if (fsa != NULL)
70025102351SMike Karels 			faddr = ((struct sockaddr_in *)fsa)->sin_addr;
701efc76f72SBjoern A. Zeeb 	}
702efc76f72SBjoern A. Zeeb #endif
70325102351SMike Karels #ifdef INET6
7042fdbcbeaSMike Karels 	laddr6 = NULL;
7052fdbcbeaSMike Karels 	if ((inp->inp_vflag & INP_IPV6) != 0) {
7062fdbcbeaSMike Karels 		if (lsa != NULL)
70725102351SMike Karels 			laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
70825102351SMike Karels 		if (fsa != NULL)
70925102351SMike Karels 			faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
71025102351SMike Karels 	}
71125102351SMike Karels #endif
71225102351SMike Karels 
71325102351SMike Karels 	tmpinp = NULL;
714efc76f72SBjoern A. Zeeb 	lport = *lportp;
715efc76f72SBjoern A. Zeeb 
716efc76f72SBjoern A. Zeeb 	if (dorandom)
717efc76f72SBjoern A. Zeeb 		*lastport = first + (arc4random() % (last - first));
718efc76f72SBjoern A. Zeeb 
719efc76f72SBjoern A. Zeeb 	count = last - first;
720efc76f72SBjoern A. Zeeb 
721efc76f72SBjoern A. Zeeb 	do {
722efc76f72SBjoern A. Zeeb 		if (count-- < 0)	/* completely used? */
723efc76f72SBjoern A. Zeeb 			return (EADDRNOTAVAIL);
724efc76f72SBjoern A. Zeeb 		++*lastport;
725efc76f72SBjoern A. Zeeb 		if (*lastport < first || *lastport > last)
726efc76f72SBjoern A. Zeeb 			*lastport = first;
727efc76f72SBjoern A. Zeeb 		lport = htons(*lastport);
728efc76f72SBjoern A. Zeeb 
72925102351SMike Karels 		if (fsa != NULL) {
73025102351SMike Karels #ifdef INET
73125102351SMike Karels 			if (lsa->sa_family == AF_INET) {
73225102351SMike Karels 				tmpinp = in_pcblookup_hash_locked(pcbinfo,
73325102351SMike Karels 				    faddr, fport, laddr, lport, lookupflags,
73425102351SMike Karels 				    NULL);
73525102351SMike Karels 			}
73625102351SMike Karels #endif
73725102351SMike Karels #ifdef INET6
73825102351SMike Karels 			if (lsa->sa_family == AF_INET6) {
73925102351SMike Karels 				tmpinp = in6_pcblookup_hash_locked(pcbinfo,
74025102351SMike Karels 				    faddr6, fport, laddr6, lport, lookupflags,
74125102351SMike Karels 				    NULL);
74225102351SMike Karels 			}
74325102351SMike Karels #endif
74425102351SMike Karels 		} else {
745efc76f72SBjoern A. Zeeb #ifdef INET6
7464616026fSErmal Luçi 			if ((inp->inp_vflag & INP_IPV6) != 0)
747efc76f72SBjoern A. Zeeb 				tmpinp = in6_pcblookup_local(pcbinfo,
74868e0d7e0SRobert Watson 				    &inp->in6p_laddr, lport, lookupflags, cred);
749efc76f72SBjoern A. Zeeb #endif
750efc76f72SBjoern A. Zeeb #if defined(INET) && defined(INET6)
751efc76f72SBjoern A. Zeeb 			else
752efc76f72SBjoern A. Zeeb #endif
753efc76f72SBjoern A. Zeeb #ifdef INET
754efc76f72SBjoern A. Zeeb 				tmpinp = in_pcblookup_local(pcbinfo, laddr,
75568e0d7e0SRobert Watson 				    lport, lookupflags, cred);
756efc76f72SBjoern A. Zeeb #endif
75725102351SMike Karels 		}
758efc76f72SBjoern A. Zeeb 	} while (tmpinp != NULL);
759efc76f72SBjoern A. Zeeb 
760efc76f72SBjoern A. Zeeb 	*lportp = lport;
761efc76f72SBjoern A. Zeeb 
762efc76f72SBjoern A. Zeeb 	return (0);
763efc76f72SBjoern A. Zeeb }
764efdf104bSMikolaj Golub 
765efdf104bSMikolaj Golub /*
76625102351SMike Karels  * Select a local port (number) to use.
76725102351SMike Karels  */
76825102351SMike Karels int
76925102351SMike Karels in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
77025102351SMike Karels     struct ucred *cred, int lookupflags)
77125102351SMike Karels {
77225102351SMike Karels 	struct sockaddr_in laddr;
77325102351SMike Karels 
77425102351SMike Karels 	if (laddrp) {
77525102351SMike Karels 		bzero(&laddr, sizeof(laddr));
77625102351SMike Karels 		laddr.sin_family = AF_INET;
77725102351SMike Karels 		laddr.sin_addr = *laddrp;
77825102351SMike Karels 	}
77925102351SMike Karels 	return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
78025102351SMike Karels 	    NULL, lportp, NULL, 0, cred, lookupflags));
78125102351SMike Karels }
78225102351SMike Karels 
78325102351SMike Karels /*
784efdf104bSMikolaj Golub  * Return cached socket options.
785efdf104bSMikolaj Golub  */
7861a43cff9SSean Bruno int
787efdf104bSMikolaj Golub inp_so_options(const struct inpcb *inp)
788efdf104bSMikolaj Golub {
7891a43cff9SSean Bruno 	int so_options;
790efdf104bSMikolaj Golub 
791efdf104bSMikolaj Golub 	so_options = 0;
792efdf104bSMikolaj Golub 
7931a43cff9SSean Bruno 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
7941a43cff9SSean Bruno 		so_options |= SO_REUSEPORT_LB;
795efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
796efdf104bSMikolaj Golub 		so_options |= SO_REUSEPORT;
797efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
798efdf104bSMikolaj Golub 		so_options |= SO_REUSEADDR;
799efdf104bSMikolaj Golub 	return (so_options);
800efdf104bSMikolaj Golub }
801efc76f72SBjoern A. Zeeb #endif /* INET || INET6 */
802efc76f72SBjoern A. Zeeb 
8034b932371SIan Dowse /*
8040a100a6fSAdrian Chadd  * Check if a new BINDMULTI socket is allowed to be created.
8050a100a6fSAdrian Chadd  *
8060a100a6fSAdrian Chadd  * ni points to the new inp.
8070a100a6fSAdrian Chadd  * oi points to the exisitng inp.
8080a100a6fSAdrian Chadd  *
8090a100a6fSAdrian Chadd  * This checks whether the existing inp also has BINDMULTI and
8100a100a6fSAdrian Chadd  * whether the credentials match.
8110a100a6fSAdrian Chadd  */
812d5bb8bd3SAdrian Chadd int
8130a100a6fSAdrian Chadd in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
8140a100a6fSAdrian Chadd {
8150a100a6fSAdrian Chadd 	/* Check permissions match */
8160a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
8170a100a6fSAdrian Chadd 	    (ni->inp_cred->cr_uid !=
8180a100a6fSAdrian Chadd 	    oi->inp_cred->cr_uid))
8190a100a6fSAdrian Chadd 		return (0);
8200a100a6fSAdrian Chadd 
8210a100a6fSAdrian Chadd 	/* Check the existing inp has BINDMULTI set */
8220a100a6fSAdrian Chadd 	if ((ni->inp_flags2 & INP_BINDMULTI) &&
8230a100a6fSAdrian Chadd 	    ((oi->inp_flags2 & INP_BINDMULTI) == 0))
8240a100a6fSAdrian Chadd 		return (0);
8250a100a6fSAdrian Chadd 
8260a100a6fSAdrian Chadd 	/*
8270a100a6fSAdrian Chadd 	 * We're okay - either INP_BINDMULTI isn't set on ni, or
8280a100a6fSAdrian Chadd 	 * it is and it matches the checks.
8290a100a6fSAdrian Chadd 	 */
8300a100a6fSAdrian Chadd 	return (1);
8310a100a6fSAdrian Chadd }
8320a100a6fSAdrian Chadd 
833d5bb8bd3SAdrian Chadd #ifdef INET
8340a100a6fSAdrian Chadd /*
8354b932371SIan Dowse  * Set up a bind operation on a PCB, performing port allocation
8364b932371SIan Dowse  * as required, but do not actually modify the PCB. Callers can
8374b932371SIan Dowse  * either complete the bind by setting inp_laddr/inp_lport and
8384b932371SIan Dowse  * calling in_pcbinshash(), or they can just use the resulting
8394b932371SIan Dowse  * port and address to authorise the sending of a once-off packet.
8404b932371SIan Dowse  *
8414b932371SIan Dowse  * On error, the values of *laddrp and *lportp are not changed.
8424b932371SIan Dowse  */
8434b932371SIan Dowse int
844136d4f1cSRobert Watson in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
845136d4f1cSRobert Watson     u_short *lportp, struct ucred *cred)
8464b932371SIan Dowse {
8474b932371SIan Dowse 	struct socket *so = inp->inp_socket;
84815bd2b43SDavid Greenman 	struct sockaddr_in *sin;
849c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
8504b932371SIan Dowse 	struct in_addr laddr;
851df8bae1dSRodney W. Grimes 	u_short lport = 0;
85268e0d7e0SRobert Watson 	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
853413628a7SBjoern A. Zeeb 	int error;
854df8bae1dSRodney W. Grimes 
8558501a69cSRobert Watson 	/*
8561a43cff9SSean Bruno 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
8571a43cff9SSean Bruno 	 * so that we don't have to add to the (already messy) code below.
8581a43cff9SSean Bruno 	 */
8591a43cff9SSean Bruno 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
8601a43cff9SSean Bruno 
8611a43cff9SSean Bruno 	/*
862fa046d87SRobert Watson 	 * No state changes, so read locks are sufficient here.
8638501a69cSRobert Watson 	 */
86459daba27SSam Leffler 	INP_LOCK_ASSERT(inp);
865fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
86659daba27SSam Leffler 
867d7c5a620SMatt Macy 	if (CK_STAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
868df8bae1dSRodney W. Grimes 		return (EADDRNOTAVAIL);
8694b932371SIan Dowse 	laddr.s_addr = *laddrp;
8704b932371SIan Dowse 	if (nam != NULL && laddr.s_addr != INADDR_ANY)
871df8bae1dSRodney W. Grimes 		return (EINVAL);
8721a43cff9SSean Bruno 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
87368e0d7e0SRobert Watson 		lookupflags = INPLOOKUP_WILDCARD;
8744616026fSErmal Luçi 	if (nam == NULL) {
8757c2f3cb9SJamie Gritton 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
8767c2f3cb9SJamie Gritton 			return (error);
8777c2f3cb9SJamie Gritton 	} else {
87857bf258eSGarrett Wollman 		sin = (struct sockaddr_in *)nam;
87957bf258eSGarrett Wollman 		if (nam->sa_len != sizeof (*sin))
880df8bae1dSRodney W. Grimes 			return (EINVAL);
881df8bae1dSRodney W. Grimes #ifdef notdef
882df8bae1dSRodney W. Grimes 		/*
883df8bae1dSRodney W. Grimes 		 * We should check the family, but old programs
884df8bae1dSRodney W. Grimes 		 * incorrectly fail to initialize it.
885df8bae1dSRodney W. Grimes 		 */
886df8bae1dSRodney W. Grimes 		if (sin->sin_family != AF_INET)
887df8bae1dSRodney W. Grimes 			return (EAFNOSUPPORT);
888df8bae1dSRodney W. Grimes #endif
889b89e82ddSJamie Gritton 		error = prison_local_ip4(cred, &sin->sin_addr);
890b89e82ddSJamie Gritton 		if (error)
891b89e82ddSJamie Gritton 			return (error);
8924b932371SIan Dowse 		if (sin->sin_port != *lportp) {
8934b932371SIan Dowse 			/* Don't allow the port to change. */
8944b932371SIan Dowse 			if (*lportp != 0)
8954b932371SIan Dowse 				return (EINVAL);
896df8bae1dSRodney W. Grimes 			lport = sin->sin_port;
8974b932371SIan Dowse 		}
8984b932371SIan Dowse 		/* NB: lport is left as 0 if the port isn't being changed. */
899df8bae1dSRodney W. Grimes 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
900df8bae1dSRodney W. Grimes 			/*
901df8bae1dSRodney W. Grimes 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
902df8bae1dSRodney W. Grimes 			 * allow complete duplication of binding if
903df8bae1dSRodney W. Grimes 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
904df8bae1dSRodney W. Grimes 			 * and a multicast address is bound on both
905df8bae1dSRodney W. Grimes 			 * new and duplicated sockets.
906df8bae1dSRodney W. Grimes 			 */
907f122b319SMikolaj Golub 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
908df8bae1dSRodney W. Grimes 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
9091a43cff9SSean Bruno 			/*
9101a43cff9SSean Bruno 			 * XXX: How to deal with SO_REUSEPORT_LB here?
9111a43cff9SSean Bruno 			 * Treat same as SO_REUSEPORT for now.
9121a43cff9SSean Bruno 			 */
9131a43cff9SSean Bruno 			if ((so->so_options &
9141a43cff9SSean Bruno 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
9151a43cff9SSean Bruno 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
916df8bae1dSRodney W. Grimes 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
917df8bae1dSRodney W. Grimes 			sin->sin_port = 0;		/* yech... */
91883103a73SAndrew R. Reiter 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
9194209e01aSAdrian Chadd 			/*
9204209e01aSAdrian Chadd 			 * Is the address a local IP address?
921f44270e7SPawel Jakub Dawidek 			 * If INP_BINDANY is set, then the socket may be bound
9228696873dSAdrian Chadd 			 * to any endpoint address, local or not.
9234209e01aSAdrian Chadd 			 */
924f44270e7SPawel Jakub Dawidek 			if ((inp->inp_flags & INP_BINDANY) == 0 &&
9258896f83aSRobert Watson 			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
926df8bae1dSRodney W. Grimes 				return (EADDRNOTAVAIL);
927df8bae1dSRodney W. Grimes 		}
9284b932371SIan Dowse 		laddr = sin->sin_addr;
929df8bae1dSRodney W. Grimes 		if (lport) {
930df8bae1dSRodney W. Grimes 			struct inpcb *t;
931ae0e7143SRobert Watson 			struct tcptw *tw;
932ae0e7143SRobert Watson 
933df8bae1dSRodney W. Grimes 			/* GROSS */
934603724d3SBjoern A. Zeeb 			if (ntohs(lport) <= V_ipport_reservedhigh &&
935603724d3SBjoern A. Zeeb 			    ntohs(lport) >= V_ipport_reservedlow &&
936cc426dd3SMateusz Guzik 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
9372469dd60SGarrett Wollman 				return (EACCES);
938835d4b89SPawel Jakub Dawidek 			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
939cc426dd3SMateusz Guzik 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
940078b7042SBjoern A. Zeeb 				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
941413628a7SBjoern A. Zeeb 				    lport, INPLOOKUP_WILDCARD, cred);
942340c35deSJonathan Lemon 	/*
943340c35deSJonathan Lemon 	 * XXX
944340c35deSJonathan Lemon 	 * This entire block sorely needs a rewrite.
945340c35deSJonathan Lemon 	 */
9464cc20ab1SSeigo Tanimura 				if (t &&
9470a100a6fSAdrian Chadd 				    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
948ad71fe3cSRobert Watson 				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
9494658dc83SYaroslav Tykhiy 				    (so->so_type != SOCK_STREAM ||
9504658dc83SYaroslav Tykhiy 				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
9514cc20ab1SSeigo Tanimura 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
95252b65dbeSBill Fenner 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
9531a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT) ||
9541a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
95586d02c5cSBjoern A. Zeeb 				    (inp->inp_cred->cr_uid !=
95686d02c5cSBjoern A. Zeeb 				     t->inp_cred->cr_uid))
9574049a042SGuido van Rooij 					return (EADDRINUSE);
9580a100a6fSAdrian Chadd 
9590a100a6fSAdrian Chadd 				/*
9600a100a6fSAdrian Chadd 				 * If the socket is a BINDMULTI socket, then
9610a100a6fSAdrian Chadd 				 * the credentials need to match and the
9620a100a6fSAdrian Chadd 				 * original socket also has to have been bound
9630a100a6fSAdrian Chadd 				 * with BINDMULTI.
9640a100a6fSAdrian Chadd 				 */
9650a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
9660a100a6fSAdrian Chadd 					return (EADDRINUSE);
9674049a042SGuido van Rooij 			}
968c3229e05SDavid Greenman 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
96968e0d7e0SRobert Watson 			    lport, lookupflags, cred);
970ad71fe3cSRobert Watson 			if (t && (t->inp_flags & INP_TIMEWAIT)) {
971ae0e7143SRobert Watson 				/*
972ae0e7143SRobert Watson 				 * XXXRW: If an incpb has had its timewait
973ae0e7143SRobert Watson 				 * state recycled, we treat the address as
974ae0e7143SRobert Watson 				 * being in use (for now).  This is better
975ae0e7143SRobert Watson 				 * than a panic, but not desirable.
976ae0e7143SRobert Watson 				 */
977ec95b709SMikolaj Golub 				tw = intotw(t);
978ae0e7143SRobert Watson 				if (tw == NULL ||
9791a43cff9SSean Bruno 				    ((reuseport & tw->tw_so_options) == 0 &&
9801a43cff9SSean Bruno 					(reuseport_lb &
9811a43cff9SSean Bruno 				            tw->tw_so_options) == 0)) {
982340c35deSJonathan Lemon 					return (EADDRINUSE);
9831a43cff9SSean Bruno 				}
9840a100a6fSAdrian Chadd 			} else if (t &&
9850a100a6fSAdrian Chadd 				   ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
9861a43cff9SSean Bruno 				   (reuseport & inp_so_options(t)) == 0 &&
9871a43cff9SSean Bruno 				   (reuseport_lb & inp_so_options(t)) == 0) {
988e3fd5ffdSRobert Watson #ifdef INET6
98933841545SHajimu UMEMOTO 				if (ntohl(sin->sin_addr.s_addr) !=
990cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
991cfa1ca9dSYoshinobu Inoue 				    ntohl(t->inp_laddr.s_addr) !=
992cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
993fc06cd42SMikolaj Golub 				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
994fc06cd42SMikolaj Golub 				    (t->inp_vflag & INP_IPV6PROTO) == 0)
995e3fd5ffdSRobert Watson #endif
996df8bae1dSRodney W. Grimes 						return (EADDRINUSE);
9970a100a6fSAdrian Chadd 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
9980a100a6fSAdrian Chadd 					return (EADDRINUSE);
999df8bae1dSRodney W. Grimes 			}
1000cfa1ca9dSYoshinobu Inoue 		}
1001df8bae1dSRodney W. Grimes 	}
10024b932371SIan Dowse 	if (*lportp != 0)
10034b932371SIan Dowse 		lport = *lportp;
100433b3ac06SPeter Wemm 	if (lport == 0) {
10054616026fSErmal Luçi 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1006efc76f72SBjoern A. Zeeb 		if (error != 0)
1007efc76f72SBjoern A. Zeeb 			return (error);
100833b3ac06SPeter Wemm 	}
10094b932371SIan Dowse 	*laddrp = laddr.s_addr;
10104b932371SIan Dowse 	*lportp = lport;
1011df8bae1dSRodney W. Grimes 	return (0);
1012df8bae1dSRodney W. Grimes }
1013df8bae1dSRodney W. Grimes 
1014999f1343SGarrett Wollman /*
10155200e00eSIan Dowse  * Connect from a socket to a specified address.
10165200e00eSIan Dowse  * Both address and port must be specified in argument sin.
10175200e00eSIan Dowse  * If don't have a local address for this socket yet,
10185200e00eSIan Dowse  * then pick one.
1019999f1343SGarrett Wollman  */
1020999f1343SGarrett Wollman int
1021d3c1f003SRobert Watson in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
1022fe1274eeSMichael Tuexen     struct ucred *cred, struct mbuf *m, bool rehash)
1023999f1343SGarrett Wollman {
10245200e00eSIan Dowse 	u_short lport, fport;
10255200e00eSIan Dowse 	in_addr_t laddr, faddr;
10265200e00eSIan Dowse 	int anonport, error;
1027df8bae1dSRodney W. Grimes 
10288501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1029fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
103027f74fd0SRobert Watson 
10315200e00eSIan Dowse 	lport = inp->inp_lport;
10325200e00eSIan Dowse 	laddr = inp->inp_laddr.s_addr;
10335200e00eSIan Dowse 	anonport = (lport == 0);
10345200e00eSIan Dowse 	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
1035b0330ed9SPawel Jakub Dawidek 	    NULL, cred);
10365200e00eSIan Dowse 	if (error)
10375200e00eSIan Dowse 		return (error);
10385200e00eSIan Dowse 
10395200e00eSIan Dowse 	/* Do the initial binding of the local address if required. */
10405200e00eSIan Dowse 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
1041fe1274eeSMichael Tuexen 		KASSERT(rehash == true,
1042fe1274eeSMichael Tuexen 		    ("Rehashing required for unbound inps"));
10435200e00eSIan Dowse 		inp->inp_lport = lport;
10445200e00eSIan Dowse 		inp->inp_laddr.s_addr = laddr;
10455200e00eSIan Dowse 		if (in_pcbinshash(inp) != 0) {
10465200e00eSIan Dowse 			inp->inp_laddr.s_addr = INADDR_ANY;
10475200e00eSIan Dowse 			inp->inp_lport = 0;
10485200e00eSIan Dowse 			return (EAGAIN);
10495200e00eSIan Dowse 		}
10505200e00eSIan Dowse 	}
10515200e00eSIan Dowse 
10525200e00eSIan Dowse 	/* Commit the remaining changes. */
10535200e00eSIan Dowse 	inp->inp_lport = lport;
10545200e00eSIan Dowse 	inp->inp_laddr.s_addr = laddr;
10555200e00eSIan Dowse 	inp->inp_faddr.s_addr = faddr;
10565200e00eSIan Dowse 	inp->inp_fport = fport;
1057fe1274eeSMichael Tuexen 	if (rehash) {
1058d3c1f003SRobert Watson 		in_pcbrehash_mbuf(inp, m);
1059fe1274eeSMichael Tuexen 	} else {
1060fe1274eeSMichael Tuexen 		in_pcbinshash_mbuf(inp, m);
1061fe1274eeSMichael Tuexen 	}
10622cb64cb2SGeorge V. Neville-Neil 
10635200e00eSIan Dowse 	if (anonport)
10645200e00eSIan Dowse 		inp->inp_flags |= INP_ANONPORT;
10655200e00eSIan Dowse 	return (0);
10665200e00eSIan Dowse }
10675200e00eSIan Dowse 
1068d3c1f003SRobert Watson int
1069d3c1f003SRobert Watson in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1070d3c1f003SRobert Watson {
1071d3c1f003SRobert Watson 
1072fe1274eeSMichael Tuexen 	return (in_pcbconnect_mbuf(inp, nam, cred, NULL, true));
1073d3c1f003SRobert Watson }
1074d3c1f003SRobert Watson 
10755200e00eSIan Dowse /*
10760895aec3SBjoern A. Zeeb  * Do proper source address selection on an unbound socket in case
10770895aec3SBjoern A. Zeeb  * of connect. Take jails into account as well.
10780895aec3SBjoern A. Zeeb  */
1079ae190832SSteven Hartland int
10800895aec3SBjoern A. Zeeb in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
10810895aec3SBjoern A. Zeeb     struct ucred *cred)
10820895aec3SBjoern A. Zeeb {
10830895aec3SBjoern A. Zeeb 	struct ifaddr *ifa;
10840895aec3SBjoern A. Zeeb 	struct sockaddr *sa;
10859ac7c6cfSAlexander V. Chernikov 	struct sockaddr_in *sin, dst;
10869ac7c6cfSAlexander V. Chernikov 	struct nhop_object *nh;
10870895aec3SBjoern A. Zeeb 	int error;
10880895aec3SBjoern A. Zeeb 
1089c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
1090413628a7SBjoern A. Zeeb 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1091592bcae8SBjoern A. Zeeb 	/*
1092592bcae8SBjoern A. Zeeb 	 * Bypass source address selection and use the primary jail IP
1093592bcae8SBjoern A. Zeeb 	 * if requested.
1094592bcae8SBjoern A. Zeeb 	 */
1095592bcae8SBjoern A. Zeeb 	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1096592bcae8SBjoern A. Zeeb 		return (0);
1097592bcae8SBjoern A. Zeeb 
10980895aec3SBjoern A. Zeeb 	error = 0;
10990895aec3SBjoern A. Zeeb 
11009ac7c6cfSAlexander V. Chernikov 	nh = NULL;
11019ac7c6cfSAlexander V. Chernikov 	bzero(&dst, sizeof(dst));
11029ac7c6cfSAlexander V. Chernikov 	sin = &dst;
11030895aec3SBjoern A. Zeeb 	sin->sin_family = AF_INET;
11040895aec3SBjoern A. Zeeb 	sin->sin_len = sizeof(struct sockaddr_in);
11050895aec3SBjoern A. Zeeb 	sin->sin_addr.s_addr = faddr->s_addr;
11060895aec3SBjoern A. Zeeb 
11070895aec3SBjoern A. Zeeb 	/*
11080895aec3SBjoern A. Zeeb 	 * If route is known our src addr is taken from the i/f,
11090895aec3SBjoern A. Zeeb 	 * else punt.
11100895aec3SBjoern A. Zeeb 	 *
11110895aec3SBjoern A. Zeeb 	 * Find out route to destination.
11120895aec3SBjoern A. Zeeb 	 */
11130895aec3SBjoern A. Zeeb 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
11149ac7c6cfSAlexander V. Chernikov 		nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
11159ac7c6cfSAlexander V. Chernikov 		    0, NHR_NONE, 0);
11160895aec3SBjoern A. Zeeb 
11170895aec3SBjoern A. Zeeb 	/*
11180895aec3SBjoern A. Zeeb 	 * If we found a route, use the address corresponding to
11190895aec3SBjoern A. Zeeb 	 * the outgoing interface.
11200895aec3SBjoern A. Zeeb 	 *
11210895aec3SBjoern A. Zeeb 	 * Otherwise assume faddr is reachable on a directly connected
11220895aec3SBjoern A. Zeeb 	 * network and try to find a corresponding interface to take
11230895aec3SBjoern A. Zeeb 	 * the source address from.
11240895aec3SBjoern A. Zeeb 	 */
11259ac7c6cfSAlexander V. Chernikov 	if (nh == NULL || nh->nh_ifp == NULL) {
11268c0fec80SRobert Watson 		struct in_ifaddr *ia;
11270895aec3SBjoern A. Zeeb 		struct ifnet *ifp;
11280895aec3SBjoern A. Zeeb 
11294f8585e0SAlan Somers 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
113058a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
11314f6c66ccSMatt Macy 		if (ia == NULL) {
11324f8585e0SAlan Somers 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
113358a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
11344f6c66ccSMatt Macy 		}
11350895aec3SBjoern A. Zeeb 		if (ia == NULL) {
11360895aec3SBjoern A. Zeeb 			error = ENETUNREACH;
11370895aec3SBjoern A. Zeeb 			goto done;
11380895aec3SBjoern A. Zeeb 		}
11390895aec3SBjoern A. Zeeb 
11400304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
11410895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11420895aec3SBjoern A. Zeeb 			goto done;
11430895aec3SBjoern A. Zeeb 		}
11440895aec3SBjoern A. Zeeb 
11450895aec3SBjoern A. Zeeb 		ifp = ia->ia_ifp;
11460895aec3SBjoern A. Zeeb 		ia = NULL;
1147d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
11480895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
11490895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
11500895aec3SBjoern A. Zeeb 				continue;
11510895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1152b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
11530895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
11540895aec3SBjoern A. Zeeb 				break;
11550895aec3SBjoern A. Zeeb 			}
11560895aec3SBjoern A. Zeeb 		}
11570895aec3SBjoern A. Zeeb 		if (ia != NULL) {
11580895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11590895aec3SBjoern A. Zeeb 			goto done;
11600895aec3SBjoern A. Zeeb 		}
11610895aec3SBjoern A. Zeeb 
11620895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1163b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
11640895aec3SBjoern A. Zeeb 		goto done;
11650895aec3SBjoern A. Zeeb 	}
11660895aec3SBjoern A. Zeeb 
11670895aec3SBjoern A. Zeeb 	/*
11680895aec3SBjoern A. Zeeb 	 * If the outgoing interface on the route found is not
11690895aec3SBjoern A. Zeeb 	 * a loopback interface, use the address from that interface.
11700895aec3SBjoern A. Zeeb 	 * In case of jails do those three steps:
11710895aec3SBjoern A. Zeeb 	 * 1. check if the interface address belongs to the jail. If so use it.
11720895aec3SBjoern A. Zeeb 	 * 2. check if we have any address on the outgoing interface
11730895aec3SBjoern A. Zeeb 	 *    belonging to this jail. If so use it.
11740895aec3SBjoern A. Zeeb 	 * 3. as a last resort return the 'default' jail address.
11750895aec3SBjoern A. Zeeb 	 */
11769ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
11778c0fec80SRobert Watson 		struct in_ifaddr *ia;
11789317b04eSRobert Watson 		struct ifnet *ifp;
11790895aec3SBjoern A. Zeeb 
11800895aec3SBjoern A. Zeeb 		/* If not jailed, use the default returned. */
11810304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
11829ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
11830895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11840895aec3SBjoern A. Zeeb 			goto done;
11850895aec3SBjoern A. Zeeb 		}
11860895aec3SBjoern A. Zeeb 
11870895aec3SBjoern A. Zeeb 		/* Jailed. */
11880895aec3SBjoern A. Zeeb 		/* 1. Check if the iface address belongs to the jail. */
11899ac7c6cfSAlexander V. Chernikov 		sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1190b89e82ddSJamie Gritton 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
11919ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
11920895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11930895aec3SBjoern A. Zeeb 			goto done;
11940895aec3SBjoern A. Zeeb 		}
11950895aec3SBjoern A. Zeeb 
11960895aec3SBjoern A. Zeeb 		/*
11970895aec3SBjoern A. Zeeb 		 * 2. Check if we have any address on the outgoing interface
11980895aec3SBjoern A. Zeeb 		 *    belonging to this jail.
11990895aec3SBjoern A. Zeeb 		 */
12008c0fec80SRobert Watson 		ia = NULL;
12019ac7c6cfSAlexander V. Chernikov 		ifp = nh->nh_ifp;
1202d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12030895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12040895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12050895aec3SBjoern A. Zeeb 				continue;
12060895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1207b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12080895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12090895aec3SBjoern A. Zeeb 				break;
12100895aec3SBjoern A. Zeeb 			}
12110895aec3SBjoern A. Zeeb 		}
12120895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12130895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12140895aec3SBjoern A. Zeeb 			goto done;
12150895aec3SBjoern A. Zeeb 		}
12160895aec3SBjoern A. Zeeb 
12170895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1218b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12190895aec3SBjoern A. Zeeb 		goto done;
12200895aec3SBjoern A. Zeeb 	}
12210895aec3SBjoern A. Zeeb 
12220895aec3SBjoern A. Zeeb 	/*
12230895aec3SBjoern A. Zeeb 	 * The outgoing interface is marked with 'loopback net', so a route
12240895aec3SBjoern A. Zeeb 	 * to ourselves is here.
12250895aec3SBjoern A. Zeeb 	 * Try to find the interface of the destination address and then
12260895aec3SBjoern A. Zeeb 	 * take the address from there. That interface is not necessarily
12270895aec3SBjoern A. Zeeb 	 * a loopback interface.
12280895aec3SBjoern A. Zeeb 	 * In case of jails, check that it is an address of the jail
12290895aec3SBjoern A. Zeeb 	 * and if we cannot find, fall back to the 'default' jail address.
12300895aec3SBjoern A. Zeeb 	 */
12319ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
12328c0fec80SRobert Watson 		struct in_ifaddr *ia;
12330895aec3SBjoern A. Zeeb 
12349ac7c6cfSAlexander V. Chernikov 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
123558a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
12360895aec3SBjoern A. Zeeb 		if (ia == NULL)
12379ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
123858a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
1239f0bb05fcSQing Li 		if (ia == NULL)
12409ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
12410895aec3SBjoern A. Zeeb 
12420304c731SJamie Gritton 		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
12430895aec3SBjoern A. Zeeb 			if (ia == NULL) {
12440895aec3SBjoern A. Zeeb 				error = ENETUNREACH;
12450895aec3SBjoern A. Zeeb 				goto done;
12460895aec3SBjoern A. Zeeb 			}
12470895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12480895aec3SBjoern A. Zeeb 			goto done;
12490895aec3SBjoern A. Zeeb 		}
12500895aec3SBjoern A. Zeeb 
12510895aec3SBjoern A. Zeeb 		/* Jailed. */
12520895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12530895aec3SBjoern A. Zeeb 			struct ifnet *ifp;
12540895aec3SBjoern A. Zeeb 
12550895aec3SBjoern A. Zeeb 			ifp = ia->ia_ifp;
12560895aec3SBjoern A. Zeeb 			ia = NULL;
1257d7c5a620SMatt Macy 			CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12580895aec3SBjoern A. Zeeb 				sa = ifa->ifa_addr;
12590895aec3SBjoern A. Zeeb 				if (sa->sa_family != AF_INET)
12600895aec3SBjoern A. Zeeb 					continue;
12610895aec3SBjoern A. Zeeb 				sin = (struct sockaddr_in *)sa;
1262b89e82ddSJamie Gritton 				if (prison_check_ip4(cred,
1263b89e82ddSJamie Gritton 				    &sin->sin_addr) == 0) {
12640895aec3SBjoern A. Zeeb 					ia = (struct in_ifaddr *)ifa;
12650895aec3SBjoern A. Zeeb 					break;
12660895aec3SBjoern A. Zeeb 				}
12670895aec3SBjoern A. Zeeb 			}
12680895aec3SBjoern A. Zeeb 			if (ia != NULL) {
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 		/* 3. As a last resort return the 'default' jail address. */
1275b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12760895aec3SBjoern A. Zeeb 		goto done;
12770895aec3SBjoern A. Zeeb 	}
12780895aec3SBjoern A. Zeeb 
12790895aec3SBjoern A. Zeeb done:
12800895aec3SBjoern A. Zeeb 	return (error);
12810895aec3SBjoern A. Zeeb }
12820895aec3SBjoern A. Zeeb 
12830895aec3SBjoern A. Zeeb /*
12845200e00eSIan Dowse  * Set up for a connect from a socket to the specified address.
12855200e00eSIan Dowse  * On entry, *laddrp and *lportp should contain the current local
12865200e00eSIan Dowse  * address and port for the PCB; these are updated to the values
12875200e00eSIan Dowse  * that should be placed in inp_laddr and inp_lport to complete
12885200e00eSIan Dowse  * the connect.
12895200e00eSIan Dowse  *
12905200e00eSIan Dowse  * On success, *faddrp and *fportp will be set to the remote address
12915200e00eSIan Dowse  * and port. These are not updated in the error case.
12925200e00eSIan Dowse  *
12935200e00eSIan Dowse  * If the operation fails because the connection already exists,
12945200e00eSIan Dowse  * *oinpp will be set to the PCB of that connection so that the
12955200e00eSIan Dowse  * caller can decide to override it. In all other cases, *oinpp
12965200e00eSIan Dowse  * is set to NULL.
12975200e00eSIan Dowse  */
12985200e00eSIan Dowse int
1299136d4f1cSRobert Watson in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1300136d4f1cSRobert Watson     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1301136d4f1cSRobert Watson     struct inpcb **oinpp, struct ucred *cred)
13025200e00eSIan Dowse {
1303cc0a3c8cSAndrey V. Elsukov 	struct rm_priotracker in_ifa_tracker;
13045200e00eSIan Dowse 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
13055200e00eSIan Dowse 	struct in_ifaddr *ia;
13065200e00eSIan Dowse 	struct inpcb *oinp;
1307b89e82ddSJamie Gritton 	struct in_addr laddr, faddr;
13085200e00eSIan Dowse 	u_short lport, fport;
13095200e00eSIan Dowse 	int error;
13105200e00eSIan Dowse 
13118501a69cSRobert Watson 	/*
13128501a69cSRobert Watson 	 * Because a global state change doesn't actually occur here, a read
13138501a69cSRobert Watson 	 * lock is sufficient.
13148501a69cSRobert Watson 	 */
1315c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
131627f74fd0SRobert Watson 	INP_LOCK_ASSERT(inp);
1317fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
131827f74fd0SRobert Watson 
13195200e00eSIan Dowse 	if (oinpp != NULL)
13205200e00eSIan Dowse 		*oinpp = NULL;
132157bf258eSGarrett Wollman 	if (nam->sa_len != sizeof (*sin))
1322df8bae1dSRodney W. Grimes 		return (EINVAL);
1323df8bae1dSRodney W. Grimes 	if (sin->sin_family != AF_INET)
1324df8bae1dSRodney W. Grimes 		return (EAFNOSUPPORT);
1325df8bae1dSRodney W. Grimes 	if (sin->sin_port == 0)
1326df8bae1dSRodney W. Grimes 		return (EADDRNOTAVAIL);
13275200e00eSIan Dowse 	laddr.s_addr = *laddrp;
13285200e00eSIan Dowse 	lport = *lportp;
13295200e00eSIan Dowse 	faddr = sin->sin_addr;
13305200e00eSIan Dowse 	fport = sin->sin_port;
13310c325f53SAlexander V. Chernikov #ifdef ROUTE_MPATH
13320c325f53SAlexander V. Chernikov 	if (CALC_FLOWID_OUTBOUND) {
13330c325f53SAlexander V. Chernikov 		uint32_t hash_val, hash_type;
13340895aec3SBjoern A. Zeeb 
13350c325f53SAlexander V. Chernikov 		hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
13360c325f53SAlexander V. Chernikov 		    inp->inp_socket->so_proto->pr_protocol, &hash_type);
13370c325f53SAlexander V. Chernikov 
13380c325f53SAlexander V. Chernikov 		inp->inp_flowid = hash_val;
13390c325f53SAlexander V. Chernikov 		inp->inp_flowtype = hash_type;
13400c325f53SAlexander V. Chernikov 	}
13410c325f53SAlexander V. Chernikov #endif
1342d7c5a620SMatt Macy 	if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1343df8bae1dSRodney W. Grimes 		/*
1344df8bae1dSRodney W. Grimes 		 * If the destination address is INADDR_ANY,
1345df8bae1dSRodney W. Grimes 		 * use the primary local address.
1346df8bae1dSRodney W. Grimes 		 * If the supplied address is INADDR_BROADCAST,
1347df8bae1dSRodney W. Grimes 		 * and the primary interface supports broadcast,
1348df8bae1dSRodney W. Grimes 		 * choose the broadcast address for that interface.
1349df8bae1dSRodney W. Grimes 		 */
1350413628a7SBjoern A. Zeeb 		if (faddr.s_addr == INADDR_ANY) {
1351cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RLOCK(&in_ifa_tracker);
1352413628a7SBjoern A. Zeeb 			faddr =
1353d7c5a620SMatt Macy 			    IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1354cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1355b89e82ddSJamie Gritton 			if (cred != NULL &&
1356b89e82ddSJamie Gritton 			    (error = prison_get_ip4(cred, &faddr)) != 0)
1357b89e82ddSJamie Gritton 				return (error);
13582d9cfabaSRobert Watson 		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1359cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RLOCK(&in_ifa_tracker);
1360d7c5a620SMatt Macy 			if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
13612d9cfabaSRobert Watson 			    IFF_BROADCAST)
1362d7c5a620SMatt Macy 				faddr = satosin(&CK_STAILQ_FIRST(
1363603724d3SBjoern A. Zeeb 				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1364cc0a3c8cSAndrey V. Elsukov 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
13652d9cfabaSRobert Watson 		}
1366df8bae1dSRodney W. Grimes 	}
13675200e00eSIan Dowse 	if (laddr.s_addr == INADDR_ANY) {
1368d79fdd98SDaniel Eischen 		error = in_pcbladdr(inp, &faddr, &laddr, cred);
1369df8bae1dSRodney W. Grimes 		/*
1370df8bae1dSRodney W. Grimes 		 * If the destination address is multicast and an outgoing
1371d79fdd98SDaniel Eischen 		 * interface has been set as a multicast option, prefer the
1372df8bae1dSRodney W. Grimes 		 * address of that interface as our source address.
1373df8bae1dSRodney W. Grimes 		 */
13745200e00eSIan Dowse 		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1375df8bae1dSRodney W. Grimes 		    inp->inp_moptions != NULL) {
1376df8bae1dSRodney W. Grimes 			struct ip_moptions *imo;
1377df8bae1dSRodney W. Grimes 			struct ifnet *ifp;
1378df8bae1dSRodney W. Grimes 
1379df8bae1dSRodney W. Grimes 			imo = inp->inp_moptions;
1380df8bae1dSRodney W. Grimes 			if (imo->imo_multicast_ifp != NULL) {
1381df8bae1dSRodney W. Grimes 				ifp = imo->imo_multicast_ifp;
1382cc0a3c8cSAndrey V. Elsukov 				IN_IFADDR_RLOCK(&in_ifa_tracker);
1383d7c5a620SMatt Macy 				CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1384e691be70SDaniel Eischen 					if ((ia->ia_ifp == ifp) &&
1385e691be70SDaniel Eischen 					    (cred == NULL ||
1386e691be70SDaniel Eischen 					    prison_check_ip4(cred,
1387e691be70SDaniel Eischen 					    &ia->ia_addr.sin_addr) == 0))
1388df8bae1dSRodney W. Grimes 						break;
1389e691be70SDaniel Eischen 				}
1390e691be70SDaniel Eischen 				if (ia == NULL)
1391d79fdd98SDaniel Eischen 					error = EADDRNOTAVAIL;
1392e691be70SDaniel Eischen 				else {
13935200e00eSIan Dowse 					laddr = ia->ia_addr.sin_addr;
1394d79fdd98SDaniel Eischen 					error = 0;
1395999f1343SGarrett Wollman 				}
1396cc0a3c8cSAndrey V. Elsukov 				IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1397d79fdd98SDaniel Eischen 			}
1398d79fdd98SDaniel Eischen 		}
139904215ed2SRandall Stewart 		if (error)
140004215ed2SRandall Stewart 			return (error);
14010895aec3SBjoern A. Zeeb 	}
140225102351SMike Karels 	if (lport != 0) {
140325102351SMike Karels 		oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
140425102351SMike Karels 		    fport, laddr, lport, 0, NULL);
14055200e00eSIan Dowse 		if (oinp != NULL) {
14065200e00eSIan Dowse 			if (oinpp != NULL)
14075200e00eSIan Dowse 				*oinpp = oinp;
1408df8bae1dSRodney W. Grimes 			return (EADDRINUSE);
1409c3229e05SDavid Greenman 		}
141025102351SMike Karels 	} else {
141125102351SMike Karels 		struct sockaddr_in lsin, fsin;
141225102351SMike Karels 
141325102351SMike Karels 		bzero(&lsin, sizeof(lsin));
141425102351SMike Karels 		bzero(&fsin, sizeof(fsin));
141525102351SMike Karels 		lsin.sin_family = AF_INET;
141625102351SMike Karels 		lsin.sin_addr = laddr;
141725102351SMike Karels 		fsin.sin_family = AF_INET;
141825102351SMike Karels 		fsin.sin_addr = faddr;
141925102351SMike Karels 		error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
142025102351SMike Karels 		    &lport, (struct sockaddr *)& fsin, fport, cred,
142125102351SMike Karels 		    INPLOOKUP_WILDCARD);
14225a903f8dSPierre Beyssac 		if (error)
14235a903f8dSPierre Beyssac 			return (error);
14245a903f8dSPierre Beyssac 	}
14255200e00eSIan Dowse 	*laddrp = laddr.s_addr;
14265200e00eSIan Dowse 	*lportp = lport;
14275200e00eSIan Dowse 	*faddrp = faddr.s_addr;
14285200e00eSIan Dowse 	*fportp = fport;
1429df8bae1dSRodney W. Grimes 	return (0);
1430df8bae1dSRodney W. Grimes }
1431df8bae1dSRodney W. Grimes 
143226f9a767SRodney W. Grimes void
1433136d4f1cSRobert Watson in_pcbdisconnect(struct inpcb *inp)
1434df8bae1dSRodney W. Grimes {
14356b348152SRobert Watson 
14368501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1437fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1438df8bae1dSRodney W. Grimes 
1439df8bae1dSRodney W. Grimes 	inp->inp_faddr.s_addr = INADDR_ANY;
1440df8bae1dSRodney W. Grimes 	inp->inp_fport = 0;
144115bd2b43SDavid Greenman 	in_pcbrehash(inp);
1442df8bae1dSRodney W. Grimes }
144383e521ecSBjoern A. Zeeb #endif /* INET */
1444df8bae1dSRodney W. Grimes 
14454c7c478dSRobert Watson /*
144628696211SRobert Watson  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1447c0a211c5SRobert Watson  * For most protocols, this will be invoked immediately prior to calling
144828696211SRobert Watson  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
144928696211SRobert Watson  * socket, in which case in_pcbfree() is deferred.
14504c7c478dSRobert Watson  */
145126f9a767SRodney W. Grimes void
1452136d4f1cSRobert Watson in_pcbdetach(struct inpcb *inp)
1453df8bae1dSRodney W. Grimes {
14544c7c478dSRobert Watson 
1455a7df09e8SBjoern A. Zeeb 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1456c0a211c5SRobert Watson 
1457f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
1458f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag != NULL)
1459f3e7afe2SHans Petter Selasky 		in_pcbdetach_txrtlmt(inp);
1460f3e7afe2SHans Petter Selasky #endif
14614c7c478dSRobert Watson 	inp->inp_socket->so_pcb = NULL;
14624c7c478dSRobert Watson 	inp->inp_socket = NULL;
14634c7c478dSRobert Watson }
14644c7c478dSRobert Watson 
1465c0a211c5SRobert Watson /*
146679bdc6e5SRobert Watson  * in_pcbref() bumps the reference count on an inpcb in order to maintain
146779bdc6e5SRobert Watson  * stability of an inpcb pointer despite the inpcb lock being released.  This
146879bdc6e5SRobert Watson  * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
146952cd27cbSRobert Watson  * but where the inpcb lock may already held, or when acquiring a reference
147052cd27cbSRobert Watson  * via a pcbgroup.
147179bdc6e5SRobert Watson  *
147279bdc6e5SRobert Watson  * in_pcbref() should be used only to provide brief memory stability, and
147379bdc6e5SRobert Watson  * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
147479bdc6e5SRobert Watson  * garbage collect the inpcb if it has been in_pcbfree()'d from another
147579bdc6e5SRobert Watson  * context.  Until in_pcbrele() has returned that the inpcb is still valid,
147679bdc6e5SRobert Watson  * lock and rele are the *only* safe operations that may be performed on the
147779bdc6e5SRobert Watson  * inpcb.
147879bdc6e5SRobert Watson  *
147979bdc6e5SRobert Watson  * While the inpcb will not be freed, releasing the inpcb lock means that the
148079bdc6e5SRobert Watson  * connection's state may change, so the caller should be careful to
148179bdc6e5SRobert Watson  * revalidate any cached state on reacquiring the lock.  Drop the reference
148279bdc6e5SRobert Watson  * using in_pcbrele().
1483c0a211c5SRobert Watson  */
148479bdc6e5SRobert Watson void
148579bdc6e5SRobert Watson in_pcbref(struct inpcb *inp)
14864c7c478dSRobert Watson {
1487df8bae1dSRodney W. Grimes 
148879bdc6e5SRobert Watson 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
148979bdc6e5SRobert Watson 
149079bdc6e5SRobert Watson 	refcount_acquire(&inp->inp_refcount);
149179bdc6e5SRobert Watson }
149279bdc6e5SRobert Watson 
149379bdc6e5SRobert Watson /*
149479bdc6e5SRobert Watson  * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
149579bdc6e5SRobert Watson  * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
149679bdc6e5SRobert Watson  * return a flag indicating whether or not the inpcb remains valid.  If it is
149779bdc6e5SRobert Watson  * valid, we return with the inpcb lock held.
149879bdc6e5SRobert Watson  *
149979bdc6e5SRobert Watson  * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
150079bdc6e5SRobert Watson  * reference on an inpcb.  Historically more work was done here (actually, in
150179bdc6e5SRobert Watson  * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
150279bdc6e5SRobert Watson  * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
150379bdc6e5SRobert Watson  * about memory stability (and continued use of the write lock).
150479bdc6e5SRobert Watson  */
150579bdc6e5SRobert Watson int
150679bdc6e5SRobert Watson in_pcbrele_rlocked(struct inpcb *inp)
150779bdc6e5SRobert Watson {
150879bdc6e5SRobert Watson 	struct inpcbinfo *pcbinfo;
150979bdc6e5SRobert Watson 
151079bdc6e5SRobert Watson 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
151179bdc6e5SRobert Watson 
151279bdc6e5SRobert Watson 	INP_RLOCK_ASSERT(inp);
151379bdc6e5SRobert Watson 
1514df4e91d3SGleb Smirnoff 	if (refcount_release(&inp->inp_refcount) == 0) {
1515df4e91d3SGleb Smirnoff 		/*
1516df4e91d3SGleb Smirnoff 		 * If the inpcb has been freed, let the caller know, even if
1517df4e91d3SGleb Smirnoff 		 * this isn't the last reference.
1518df4e91d3SGleb Smirnoff 		 */
1519df4e91d3SGleb Smirnoff 		if (inp->inp_flags2 & INP_FREED) {
1520df4e91d3SGleb Smirnoff 			INP_RUNLOCK(inp);
1521df4e91d3SGleb Smirnoff 			return (1);
1522df4e91d3SGleb Smirnoff 		}
152379bdc6e5SRobert Watson 		return (0);
1524df4e91d3SGleb Smirnoff 	}
152579bdc6e5SRobert Watson 
152679bdc6e5SRobert Watson 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
15273ee9c3c4SRandall Stewart #ifdef TCPHPTS
15283ee9c3c4SRandall Stewart 	if (inp->inp_in_hpts || inp->inp_in_input) {
15293ee9c3c4SRandall Stewart 		struct tcp_hpts_entry *hpts;
15303ee9c3c4SRandall Stewart 		/*
15313ee9c3c4SRandall Stewart 		 * We should not be on the hpts at
15323ee9c3c4SRandall Stewart 		 * this point in any form. we must
15333ee9c3c4SRandall Stewart 		 * get the lock to be sure.
15343ee9c3c4SRandall Stewart 		 */
15353ee9c3c4SRandall Stewart 		hpts = tcp_hpts_lock(inp);
15363ee9c3c4SRandall Stewart 		if (inp->inp_in_hpts)
15373ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on hpts",
15383ee9c3c4SRandall Stewart 			      hpts, inp);
15393ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
15403ee9c3c4SRandall Stewart 		hpts = tcp_input_lock(inp);
15413ee9c3c4SRandall Stewart 		if (inp->inp_in_input)
15423ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on input hpts",
15433ee9c3c4SRandall Stewart 			      hpts, inp);
15443ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
15453ee9c3c4SRandall Stewart 	}
15463ee9c3c4SRandall Stewart #endif
154779bdc6e5SRobert Watson 	INP_RUNLOCK(inp);
154879bdc6e5SRobert Watson 	pcbinfo = inp->inp_pcbinfo;
154979bdc6e5SRobert Watson 	uma_zfree(pcbinfo->ipi_zone, inp);
155079bdc6e5SRobert Watson 	return (1);
155179bdc6e5SRobert Watson }
155279bdc6e5SRobert Watson 
155379bdc6e5SRobert Watson int
155479bdc6e5SRobert Watson in_pcbrele_wlocked(struct inpcb *inp)
155579bdc6e5SRobert Watson {
155679bdc6e5SRobert Watson 	struct inpcbinfo *pcbinfo;
155779bdc6e5SRobert Watson 
155879bdc6e5SRobert Watson 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
155979bdc6e5SRobert Watson 
156079bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
156179bdc6e5SRobert Watson 
1562edd0e0b0SFabien Thomas 	if (refcount_release(&inp->inp_refcount) == 0) {
1563edd0e0b0SFabien Thomas 		/*
1564edd0e0b0SFabien Thomas 		 * If the inpcb has been freed, let the caller know, even if
1565edd0e0b0SFabien Thomas 		 * this isn't the last reference.
1566edd0e0b0SFabien Thomas 		 */
1567edd0e0b0SFabien Thomas 		if (inp->inp_flags2 & INP_FREED) {
1568edd0e0b0SFabien Thomas 			INP_WUNLOCK(inp);
1569edd0e0b0SFabien Thomas 			return (1);
1570edd0e0b0SFabien Thomas 		}
157179bdc6e5SRobert Watson 		return (0);
1572edd0e0b0SFabien Thomas 	}
157379bdc6e5SRobert Watson 
157479bdc6e5SRobert Watson 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
15753ee9c3c4SRandall Stewart #ifdef TCPHPTS
15763ee9c3c4SRandall Stewart 	if (inp->inp_in_hpts || inp->inp_in_input) {
15773ee9c3c4SRandall Stewart 		struct tcp_hpts_entry *hpts;
15783ee9c3c4SRandall Stewart 		/*
15793ee9c3c4SRandall Stewart 		 * We should not be on the hpts at
15803ee9c3c4SRandall Stewart 		 * this point in any form. we must
15813ee9c3c4SRandall Stewart 		 * get the lock to be sure.
15823ee9c3c4SRandall Stewart 		 */
15833ee9c3c4SRandall Stewart 		hpts = tcp_hpts_lock(inp);
15843ee9c3c4SRandall Stewart 		if (inp->inp_in_hpts)
15853ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on hpts",
15863ee9c3c4SRandall Stewart 			      hpts, inp);
15873ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
15883ee9c3c4SRandall Stewart 		hpts = tcp_input_lock(inp);
15893ee9c3c4SRandall Stewart 		if (inp->inp_in_input)
15903ee9c3c4SRandall Stewart 			panic("Hpts:%p inp:%p at free still on input hpts",
15913ee9c3c4SRandall Stewart 			      hpts, inp);
15923ee9c3c4SRandall Stewart 		mtx_unlock(&hpts->p_mtx);
15933ee9c3c4SRandall Stewart 	}
15943ee9c3c4SRandall Stewart #endif
159579bdc6e5SRobert Watson 	INP_WUNLOCK(inp);
159679bdc6e5SRobert Watson 	pcbinfo = inp->inp_pcbinfo;
159779bdc6e5SRobert Watson 	uma_zfree(pcbinfo->ipi_zone, inp);
159879bdc6e5SRobert Watson 	return (1);
159979bdc6e5SRobert Watson }
160079bdc6e5SRobert Watson 
160179bdc6e5SRobert Watson /*
160279bdc6e5SRobert Watson  * Temporary wrapper.
160379bdc6e5SRobert Watson  */
160479bdc6e5SRobert Watson int
160579bdc6e5SRobert Watson in_pcbrele(struct inpcb *inp)
160679bdc6e5SRobert Watson {
160779bdc6e5SRobert Watson 
160879bdc6e5SRobert Watson 	return (in_pcbrele_wlocked(inp));
160979bdc6e5SRobert Watson }
161079bdc6e5SRobert Watson 
1611ddece765SMatt Macy void
1612ddece765SMatt Macy in_pcblist_rele_rlocked(epoch_context_t ctx)
1613ddece765SMatt Macy {
1614ddece765SMatt Macy 	struct in_pcblist *il;
1615ddece765SMatt Macy 	struct inpcb *inp;
1616ddece765SMatt Macy 	struct inpcbinfo *pcbinfo;
1617ddece765SMatt Macy 	int i, n;
1618ddece765SMatt Macy 
1619ddece765SMatt Macy 	il = __containerof(ctx, struct in_pcblist, il_epoch_ctx);
1620ddece765SMatt Macy 	pcbinfo = il->il_pcbinfo;
1621ddece765SMatt Macy 	n = il->il_count;
1622ddece765SMatt Macy 	INP_INFO_WLOCK(pcbinfo);
1623ddece765SMatt Macy 	for (i = 0; i < n; i++) {
1624ddece765SMatt Macy 		inp = il->il_inp_list[i];
1625ddece765SMatt Macy 		INP_RLOCK(inp);
1626ddece765SMatt Macy 		if (!in_pcbrele_rlocked(inp))
1627ddece765SMatt Macy 			INP_RUNLOCK(inp);
1628ddece765SMatt Macy 	}
1629ddece765SMatt Macy 	INP_INFO_WUNLOCK(pcbinfo);
1630ddece765SMatt Macy 	free(il, M_TEMP);
1631ddece765SMatt Macy }
1632ddece765SMatt Macy 
1633addf2b20SMatt Macy static void
1634f09ee4fcSMatt Macy inpcbport_free(epoch_context_t ctx)
1635f09ee4fcSMatt Macy {
1636f09ee4fcSMatt Macy 	struct inpcbport *phd;
1637f09ee4fcSMatt Macy 
1638f09ee4fcSMatt Macy 	phd = __containerof(ctx, struct inpcbport, phd_epoch_ctx);
1639f09ee4fcSMatt Macy 	free(phd, M_PCB);
1640f09ee4fcSMatt Macy }
1641f09ee4fcSMatt Macy 
1642f09ee4fcSMatt Macy static void
1643addf2b20SMatt Macy in_pcbfree_deferred(epoch_context_t ctx)
1644addf2b20SMatt Macy {
1645addf2b20SMatt Macy 	struct inpcb *inp;
1646addf2b20SMatt Macy 	int released __unused;
1647addf2b20SMatt Macy 
1648addf2b20SMatt Macy 	inp = __containerof(ctx, struct inpcb, inp_epoch_ctx);
1649addf2b20SMatt Macy 
1650addf2b20SMatt Macy 	INP_WLOCK(inp);
1651c7ee62fcSAndrey V. Elsukov 	CURVNET_SET(inp->inp_vnet);
1652addf2b20SMatt Macy #ifdef INET
1653f9be0386SMatt Macy 	struct ip_moptions *imo = inp->inp_moptions;
1654addf2b20SMatt Macy 	inp->inp_moptions = NULL;
1655addf2b20SMatt Macy #endif
1656addf2b20SMatt Macy 	/* XXXRW: Do as much as possible here. */
1657addf2b20SMatt Macy #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1658addf2b20SMatt Macy 	if (inp->inp_sp != NULL)
1659addf2b20SMatt Macy 		ipsec_delete_pcbpolicy(inp);
1660addf2b20SMatt Macy #endif
1661addf2b20SMatt Macy #ifdef INET6
1662f9be0386SMatt Macy 	struct ip6_moptions *im6o = NULL;
1663addf2b20SMatt Macy 	if (inp->inp_vflag & INP_IPV6PROTO) {
1664addf2b20SMatt Macy 		ip6_freepcbopts(inp->in6p_outputopts);
1665f9be0386SMatt Macy 		im6o = inp->in6p_moptions;
1666addf2b20SMatt Macy 		inp->in6p_moptions = NULL;
1667addf2b20SMatt Macy 	}
1668addf2b20SMatt Macy #endif
1669addf2b20SMatt Macy 	if (inp->inp_options)
1670addf2b20SMatt Macy 		(void)m_free(inp->inp_options);
1671addf2b20SMatt Macy 	inp->inp_vflag = 0;
1672addf2b20SMatt Macy 	crfree(inp->inp_cred);
1673addf2b20SMatt Macy #ifdef MAC
1674addf2b20SMatt Macy 	mac_inpcb_destroy(inp);
1675addf2b20SMatt Macy #endif
1676addf2b20SMatt Macy 	released = in_pcbrele_wlocked(inp);
1677addf2b20SMatt Macy 	MPASS(released);
1678f9be0386SMatt Macy #ifdef INET6
1679f9be0386SMatt Macy 	ip6_freemoptions(im6o);
1680f9be0386SMatt Macy #endif
1681f9be0386SMatt Macy #ifdef INET
1682f9be0386SMatt Macy 	inp_freemoptions(imo);
1683f9be0386SMatt Macy #endif
1684c7ee62fcSAndrey V. Elsukov 	CURVNET_RESTORE();
1685addf2b20SMatt Macy }
1686addf2b20SMatt Macy 
168779bdc6e5SRobert Watson /*
168879bdc6e5SRobert Watson  * Unconditionally schedule an inpcb to be freed by decrementing its
168979bdc6e5SRobert Watson  * reference count, which should occur only after the inpcb has been detached
169079bdc6e5SRobert Watson  * from its socket.  If another thread holds a temporary reference (acquired
169179bdc6e5SRobert Watson  * using in_pcbref()) then the free is deferred until that reference is
169279bdc6e5SRobert Watson  * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
169379bdc6e5SRobert Watson  * work, including removal from global lists, is done in this context, where
169479bdc6e5SRobert Watson  * the pcbinfo lock is held.
169579bdc6e5SRobert Watson  */
169679bdc6e5SRobert Watson void
169779bdc6e5SRobert Watson in_pcbfree(struct inpcb *inp)
169879bdc6e5SRobert Watson {
1699f42a83f2SMatt Macy 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1700f42a83f2SMatt Macy 
170179bdc6e5SRobert Watson 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
170245a48d07SJonathan T. Looney 	KASSERT((inp->inp_flags2 & INP_FREED) == 0,
170345a48d07SJonathan T. Looney 	    ("%s: called twice for pcb %p", __func__, inp));
170445a48d07SJonathan T. Looney 	if (inp->inp_flags2 & INP_FREED) {
170545a48d07SJonathan T. Looney 		INP_WUNLOCK(inp);
170645a48d07SJonathan T. Looney 		return;
170745a48d07SJonathan T. Looney 	}
170845a48d07SJonathan T. Looney 
170979bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
1710f42a83f2SMatt Macy 	INP_LIST_WLOCK(pcbinfo);
1711f42a83f2SMatt Macy 	in_pcbremlists(inp);
1712f42a83f2SMatt Macy 	INP_LIST_WUNLOCK(pcbinfo);
1713fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
1714addf2b20SMatt Macy 	/* mark as destruction in progress */
1715f42a83f2SMatt Macy 	inp->inp_flags2 |= INP_FREED;
1716cb6bb230SMatt Macy 	INP_WUNLOCK(inp);
17172a4bd982SGleb Smirnoff 	NET_EPOCH_CALL(in_pcbfree_deferred, &inp->inp_epoch_ctx);
171828696211SRobert Watson }
171928696211SRobert Watson 
172028696211SRobert Watson /*
1721c0a211c5SRobert Watson  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1722c0a211c5SRobert Watson  * port reservation, and preventing it from being returned by inpcb lookups.
1723c0a211c5SRobert Watson  *
1724c0a211c5SRobert Watson  * It is used by TCP to mark an inpcb as unused and avoid future packet
1725c0a211c5SRobert Watson  * delivery or event notification when a socket remains open but TCP has
1726c0a211c5SRobert Watson  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1727c0a211c5SRobert Watson  * or a RST on the wire, and allows the port binding to be reused while still
1728c0a211c5SRobert Watson  * maintaining the invariant that so_pcb always points to a valid inpcb until
1729c0a211c5SRobert Watson  * in_pcbdetach().
1730c0a211c5SRobert Watson  *
1731c0a211c5SRobert Watson  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1732c0a211c5SRobert Watson  * in_pcbnotifyall() and in_pcbpurgeif0()?
173310702a28SRobert Watson  */
173410702a28SRobert Watson void
173510702a28SRobert Watson in_pcbdrop(struct inpcb *inp)
173610702a28SRobert Watson {
173710702a28SRobert Watson 
17388501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
17396573d758SMatt Macy #ifdef INVARIANTS
17406573d758SMatt Macy 	if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
17416573d758SMatt Macy 		MPASS(inp->inp_refcount > 1);
17426573d758SMatt Macy #endif
174310702a28SRobert Watson 
1744fa046d87SRobert Watson 	/*
1745fa046d87SRobert Watson 	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1746fa046d87SRobert Watson 	 * the hash lock...?
1747fa046d87SRobert Watson 	 */
1748ad71fe3cSRobert Watson 	inp->inp_flags |= INP_DROPPED;
1749111d57a6SRobert Watson 	if (inp->inp_flags & INP_INHASHLIST) {
175010702a28SRobert Watson 		struct inpcbport *phd = inp->inp_phd;
175110702a28SRobert Watson 
1752fa046d87SRobert Watson 		INP_HASH_WLOCK(inp->inp_pcbinfo);
17531a43cff9SSean Bruno 		in_pcbremlbgrouphash(inp);
1754b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_hash);
1755b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_portlist);
1756b872626dSMatt Macy 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1757b872626dSMatt Macy 			CK_LIST_REMOVE(phd, phd_hash);
17582a4bd982SGleb Smirnoff 			NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
175910702a28SRobert Watson 		}
1760fa046d87SRobert Watson 		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1761111d57a6SRobert Watson 		inp->inp_flags &= ~INP_INHASHLIST;
176252cd27cbSRobert Watson #ifdef PCBGROUP
176352cd27cbSRobert Watson 		in_pcbgroup_remove(inp);
176452cd27cbSRobert Watson #endif
176510702a28SRobert Watson 	}
176610702a28SRobert Watson }
176710702a28SRobert Watson 
176867107f45SBjoern A. Zeeb #ifdef INET
176954d642bbSRobert Watson /*
177054d642bbSRobert Watson  * Common routines to return the socket addresses associated with inpcbs.
177154d642bbSRobert Watson  */
177226ef6ac4SDon Lewis struct sockaddr *
1773136d4f1cSRobert Watson in_sockaddr(in_port_t port, struct in_addr *addr_p)
177426ef6ac4SDon Lewis {
177526ef6ac4SDon Lewis 	struct sockaddr_in *sin;
177626ef6ac4SDon Lewis 
17771ede983cSDag-Erling Smørgrav 	sin = malloc(sizeof *sin, M_SONAME,
1778a163d034SWarner Losh 		M_WAITOK | M_ZERO);
177926ef6ac4SDon Lewis 	sin->sin_family = AF_INET;
178026ef6ac4SDon Lewis 	sin->sin_len = sizeof(*sin);
178126ef6ac4SDon Lewis 	sin->sin_addr = *addr_p;
178226ef6ac4SDon Lewis 	sin->sin_port = port;
178326ef6ac4SDon Lewis 
178426ef6ac4SDon Lewis 	return (struct sockaddr *)sin;
178526ef6ac4SDon Lewis }
178626ef6ac4SDon Lewis 
1787117bcae7SGarrett Wollman int
178854d642bbSRobert Watson in_getsockaddr(struct socket *so, struct sockaddr **nam)
1789df8bae1dSRodney W. Grimes {
1790136d4f1cSRobert Watson 	struct inpcb *inp;
179126ef6ac4SDon Lewis 	struct in_addr addr;
179226ef6ac4SDon Lewis 	in_port_t port;
179342fa505bSDavid Greenman 
1794fdc984f7STor Egge 	inp = sotoinpcb(so);
179554d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
17966466b28aSRobert Watson 
1797a69042a5SRobert Watson 	INP_RLOCK(inp);
179826ef6ac4SDon Lewis 	port = inp->inp_lport;
179926ef6ac4SDon Lewis 	addr = inp->inp_laddr;
1800a69042a5SRobert Watson 	INP_RUNLOCK(inp);
180142fa505bSDavid Greenman 
180226ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
1803117bcae7SGarrett Wollman 	return 0;
1804df8bae1dSRodney W. Grimes }
1805df8bae1dSRodney W. Grimes 
1806117bcae7SGarrett Wollman int
180754d642bbSRobert Watson in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1808df8bae1dSRodney W. Grimes {
1809136d4f1cSRobert Watson 	struct inpcb *inp;
181026ef6ac4SDon Lewis 	struct in_addr addr;
181126ef6ac4SDon Lewis 	in_port_t port;
181242fa505bSDavid Greenman 
1813fdc984f7STor Egge 	inp = sotoinpcb(so);
181454d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
18156466b28aSRobert Watson 
1816a69042a5SRobert Watson 	INP_RLOCK(inp);
181726ef6ac4SDon Lewis 	port = inp->inp_fport;
181826ef6ac4SDon Lewis 	addr = inp->inp_faddr;
1819a69042a5SRobert Watson 	INP_RUNLOCK(inp);
182042fa505bSDavid Greenman 
182126ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
1822117bcae7SGarrett Wollman 	return 0;
1823df8bae1dSRodney W. Grimes }
1824df8bae1dSRodney W. Grimes 
182526f9a767SRodney W. Grimes void
1826136d4f1cSRobert Watson in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1827136d4f1cSRobert Watson     struct inpcb *(*notify)(struct inpcb *, int))
1828d1c54148SJesper Skriver {
1829f457d580SRobert Watson 	struct inpcb *inp, *inp_temp;
1830d1c54148SJesper Skriver 
18313dc7ebf9SJeffrey Hsu 	INP_INFO_WLOCK(pcbinfo);
1832b872626dSMatt Macy 	CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
18338501a69cSRobert Watson 		INP_WLOCK(inp);
1834d1c54148SJesper Skriver #ifdef INET6
1835f76fcf6dSJeffrey Hsu 		if ((inp->inp_vflag & INP_IPV4) == 0) {
18368501a69cSRobert Watson 			INP_WUNLOCK(inp);
1837d1c54148SJesper Skriver 			continue;
1838f76fcf6dSJeffrey Hsu 		}
1839d1c54148SJesper Skriver #endif
1840d1c54148SJesper Skriver 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1841f76fcf6dSJeffrey Hsu 		    inp->inp_socket == NULL) {
18428501a69cSRobert Watson 			INP_WUNLOCK(inp);
1843d1c54148SJesper Skriver 			continue;
1844d1c54148SJesper Skriver 		}
18453dc7ebf9SJeffrey Hsu 		if ((*notify)(inp, errno))
18468501a69cSRobert Watson 			INP_WUNLOCK(inp);
1847f76fcf6dSJeffrey Hsu 	}
18483dc7ebf9SJeffrey Hsu 	INP_INFO_WUNLOCK(pcbinfo);
1849d1c54148SJesper Skriver }
1850d1c54148SJesper Skriver 
1851e43cc4aeSHajimu UMEMOTO void
1852136d4f1cSRobert Watson in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1853e43cc4aeSHajimu UMEMOTO {
1854e43cc4aeSHajimu UMEMOTO 	struct inpcb *inp;
185559854ecfSHans Petter Selasky 	struct in_multi *inm;
185659854ecfSHans Petter Selasky 	struct in_mfilter *imf;
1857e43cc4aeSHajimu UMEMOTO 	struct ip_moptions *imo;
1858e43cc4aeSHajimu UMEMOTO 
1859ff9b006dSJulien Charbon 	INP_INFO_WLOCK(pcbinfo);
1860b872626dSMatt Macy 	CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
18618501a69cSRobert Watson 		INP_WLOCK(inp);
1862e43cc4aeSHajimu UMEMOTO 		imo = inp->inp_moptions;
1863e43cc4aeSHajimu UMEMOTO 		if ((inp->inp_vflag & INP_IPV4) &&
1864e43cc4aeSHajimu UMEMOTO 		    imo != NULL) {
1865e43cc4aeSHajimu UMEMOTO 			/*
1866e43cc4aeSHajimu UMEMOTO 			 * Unselect the outgoing interface if it is being
1867e43cc4aeSHajimu UMEMOTO 			 * detached.
1868e43cc4aeSHajimu UMEMOTO 			 */
1869e43cc4aeSHajimu UMEMOTO 			if (imo->imo_multicast_ifp == ifp)
1870e43cc4aeSHajimu UMEMOTO 				imo->imo_multicast_ifp = NULL;
1871e43cc4aeSHajimu UMEMOTO 
1872e43cc4aeSHajimu UMEMOTO 			/*
1873e43cc4aeSHajimu UMEMOTO 			 * Drop multicast group membership if we joined
1874e43cc4aeSHajimu UMEMOTO 			 * through the interface being detached.
1875cb6bb230SMatt Macy 			 *
1876cb6bb230SMatt Macy 			 * XXX This can all be deferred to an epoch_call
1877e43cc4aeSHajimu UMEMOTO 			 */
187859854ecfSHans Petter Selasky restart:
187959854ecfSHans Petter Selasky 			IP_MFILTER_FOREACH(imf, &imo->imo_head) {
188059854ecfSHans Petter Selasky 				if ((inm = imf->imf_inm) == NULL)
188159854ecfSHans Petter Selasky 					continue;
188259854ecfSHans Petter Selasky 				if (inm->inm_ifp != ifp)
188359854ecfSHans Petter Selasky 					continue;
188459854ecfSHans Petter Selasky 				ip_mfilter_remove(&imo->imo_head, imf);
1885f3e1324bSStephen Hurd 				IN_MULTI_LOCK_ASSERT();
188659854ecfSHans Petter Selasky 				in_leavegroup_locked(inm, NULL);
188759854ecfSHans Petter Selasky 				ip_mfilter_free(imf);
188859854ecfSHans Petter Selasky 				goto restart;
1889e43cc4aeSHajimu UMEMOTO 			}
1890e43cc4aeSHajimu UMEMOTO 		}
18918501a69cSRobert Watson 		INP_WUNLOCK(inp);
1892e43cc4aeSHajimu UMEMOTO 	}
1893ff9b006dSJulien Charbon 	INP_INFO_WUNLOCK(pcbinfo);
1894e43cc4aeSHajimu UMEMOTO }
1895e43cc4aeSHajimu UMEMOTO 
1896df8bae1dSRodney W. Grimes /*
1897fa046d87SRobert Watson  * Lookup a PCB based on the local address and port.  Caller must hold the
1898fa046d87SRobert Watson  * hash lock.  No inpcb locks or references are acquired.
1899c3229e05SDavid Greenman  */
1900d5e8a67eSHajimu UMEMOTO #define INP_LOOKUP_MAPPED_PCB_COST	3
1901df8bae1dSRodney W. Grimes struct inpcb *
1902136d4f1cSRobert Watson in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
190368e0d7e0SRobert Watson     u_short lport, int lookupflags, struct ucred *cred)
1904df8bae1dSRodney W. Grimes {
1905136d4f1cSRobert Watson 	struct inpcb *inp;
1906d5e8a67eSHajimu UMEMOTO #ifdef INET6
1907d5e8a67eSHajimu UMEMOTO 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1908d5e8a67eSHajimu UMEMOTO #else
1909d5e8a67eSHajimu UMEMOTO 	int matchwild = 3;
1910d5e8a67eSHajimu UMEMOTO #endif
1911d5e8a67eSHajimu UMEMOTO 	int wildcard;
19127bc4aca7SDavid Greenman 
191368e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
191468e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
191568e0d7e0SRobert Watson 
1916fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
19171b73ca0bSSam Leffler 
191868e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1919c3229e05SDavid Greenman 		struct inpcbhead *head;
1920c3229e05SDavid Greenman 		/*
1921c3229e05SDavid Greenman 		 * Look for an unconnected (wildcard foreign addr) PCB that
1922c3229e05SDavid Greenman 		 * matches the local address and port we're looking for.
1923c3229e05SDavid Greenman 		 */
1924712fc218SRobert Watson 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1925712fc218SRobert Watson 		    0, pcbinfo->ipi_hashmask)];
1926b872626dSMatt Macy 		CK_LIST_FOREACH(inp, head, inp_hash) {
1927cfa1ca9dSYoshinobu Inoue #ifdef INET6
1928413628a7SBjoern A. Zeeb 			/* XXX inp locking */
1929369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
1930cfa1ca9dSYoshinobu Inoue 				continue;
1931cfa1ca9dSYoshinobu Inoue #endif
1932c3229e05SDavid Greenman 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1933c3229e05SDavid Greenman 			    inp->inp_laddr.s_addr == laddr.s_addr &&
1934c3229e05SDavid Greenman 			    inp->inp_lport == lport) {
1935c3229e05SDavid Greenman 				/*
1936413628a7SBjoern A. Zeeb 				 * Found?
1937c3229e05SDavid Greenman 				 */
1938413628a7SBjoern A. Zeeb 				if (cred == NULL ||
19390304c731SJamie Gritton 				    prison_equal_ip4(cred->cr_prison,
19400304c731SJamie Gritton 					inp->inp_cred->cr_prison))
1941c3229e05SDavid Greenman 					return (inp);
1942df8bae1dSRodney W. Grimes 			}
1943c3229e05SDavid Greenman 		}
1944c3229e05SDavid Greenman 		/*
1945c3229e05SDavid Greenman 		 * Not found.
1946c3229e05SDavid Greenman 		 */
1947c3229e05SDavid Greenman 		return (NULL);
1948c3229e05SDavid Greenman 	} else {
1949c3229e05SDavid Greenman 		struct inpcbporthead *porthash;
1950c3229e05SDavid Greenman 		struct inpcbport *phd;
1951c3229e05SDavid Greenman 		struct inpcb *match = NULL;
1952c3229e05SDavid Greenman 		/*
1953c3229e05SDavid Greenman 		 * Best fit PCB lookup.
1954c3229e05SDavid Greenman 		 *
1955c3229e05SDavid Greenman 		 * First see if this local port is in use by looking on the
1956c3229e05SDavid Greenman 		 * port hash list.
1957c3229e05SDavid Greenman 		 */
1958712fc218SRobert Watson 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1959712fc218SRobert Watson 		    pcbinfo->ipi_porthashmask)];
1960b872626dSMatt Macy 		CK_LIST_FOREACH(phd, porthash, phd_hash) {
1961c3229e05SDavid Greenman 			if (phd->phd_port == lport)
1962c3229e05SDavid Greenman 				break;
1963c3229e05SDavid Greenman 		}
1964c3229e05SDavid Greenman 		if (phd != NULL) {
1965c3229e05SDavid Greenman 			/*
1966c3229e05SDavid Greenman 			 * Port is in use by one or more PCBs. Look for best
1967c3229e05SDavid Greenman 			 * fit.
1968c3229e05SDavid Greenman 			 */
1969b872626dSMatt Macy 			CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1970c3229e05SDavid Greenman 				wildcard = 0;
1971413628a7SBjoern A. Zeeb 				if (cred != NULL &&
19720304c731SJamie Gritton 				    !prison_equal_ip4(inp->inp_cred->cr_prison,
19730304c731SJamie Gritton 					cred->cr_prison))
1974413628a7SBjoern A. Zeeb 					continue;
1975cfa1ca9dSYoshinobu Inoue #ifdef INET6
1976413628a7SBjoern A. Zeeb 				/* XXX inp locking */
1977369dc8ceSEivind Eklund 				if ((inp->inp_vflag & INP_IPV4) == 0)
1978cfa1ca9dSYoshinobu Inoue 					continue;
1979d5e8a67eSHajimu UMEMOTO 				/*
1980d5e8a67eSHajimu UMEMOTO 				 * We never select the PCB that has
1981d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag and is bound to :: if
1982d5e8a67eSHajimu UMEMOTO 				 * we have another PCB which is bound
1983d5e8a67eSHajimu UMEMOTO 				 * to 0.0.0.0.  If a PCB has the
1984d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag, then we set its cost
1985d5e8a67eSHajimu UMEMOTO 				 * higher than IPv4 only PCBs.
1986d5e8a67eSHajimu UMEMOTO 				 *
1987d5e8a67eSHajimu UMEMOTO 				 * Note that the case only happens
1988d5e8a67eSHajimu UMEMOTO 				 * when a socket is bound to ::, under
1989d5e8a67eSHajimu UMEMOTO 				 * the condition that the use of the
1990d5e8a67eSHajimu UMEMOTO 				 * mapped address is allowed.
1991d5e8a67eSHajimu UMEMOTO 				 */
1992d5e8a67eSHajimu UMEMOTO 				if ((inp->inp_vflag & INP_IPV6) != 0)
1993d5e8a67eSHajimu UMEMOTO 					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1994cfa1ca9dSYoshinobu Inoue #endif
1995c3229e05SDavid Greenman 				if (inp->inp_faddr.s_addr != INADDR_ANY)
1996c3229e05SDavid Greenman 					wildcard++;
199715bd2b43SDavid Greenman 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
199815bd2b43SDavid Greenman 					if (laddr.s_addr == INADDR_ANY)
199915bd2b43SDavid Greenman 						wildcard++;
200015bd2b43SDavid Greenman 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
200115bd2b43SDavid Greenman 						continue;
200215bd2b43SDavid Greenman 				} else {
200315bd2b43SDavid Greenman 					if (laddr.s_addr != INADDR_ANY)
200415bd2b43SDavid Greenman 						wildcard++;
200515bd2b43SDavid Greenman 				}
2006df8bae1dSRodney W. Grimes 				if (wildcard < matchwild) {
2007df8bae1dSRodney W. Grimes 					match = inp;
2008df8bae1dSRodney W. Grimes 					matchwild = wildcard;
2009413628a7SBjoern A. Zeeb 					if (matchwild == 0)
2010df8bae1dSRodney W. Grimes 						break;
2011df8bae1dSRodney W. Grimes 				}
2012df8bae1dSRodney W. Grimes 			}
20133dbdc25cSDavid Greenman 		}
2014df8bae1dSRodney W. Grimes 		return (match);
2015df8bae1dSRodney W. Grimes 	}
2016c3229e05SDavid Greenman }
2017d5e8a67eSHajimu UMEMOTO #undef INP_LOOKUP_MAPPED_PCB_COST
201815bd2b43SDavid Greenman 
20191a43cff9SSean Bruno static struct inpcb *
20201a43cff9SSean Bruno in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
20211a43cff9SSean Bruno     const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
20221a43cff9SSean Bruno     uint16_t fport, int lookupflags)
20231a43cff9SSean Bruno {
20248be02ee4SMark Johnston 	struct inpcb *local_wild;
20251a43cff9SSean Bruno 	const struct inpcblbgrouphead *hdr;
20261a43cff9SSean Bruno 	struct inpcblbgroup *grp;
20278be02ee4SMark Johnston 	uint32_t idx;
20281a43cff9SSean Bruno 
20291a43cff9SSean Bruno 	INP_HASH_LOCK_ASSERT(pcbinfo);
20301a43cff9SSean Bruno 
20319d2877fcSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[
20329d2877fcSMark Johnston 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
20331a43cff9SSean Bruno 
20341a43cff9SSean Bruno 	/*
20351a43cff9SSean Bruno 	 * Order of socket selection:
20361a43cff9SSean Bruno 	 * 1. non-wild.
20371a43cff9SSean Bruno 	 * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
20381a43cff9SSean Bruno 	 *
20391a43cff9SSean Bruno 	 * NOTE:
20401a43cff9SSean Bruno 	 * - Load balanced group does not contain jailed sockets
20411a43cff9SSean Bruno 	 * - Load balanced group does not contain IPv4 mapped INET6 wild sockets
20421a43cff9SSean Bruno 	 */
20438be02ee4SMark Johnston 	local_wild = NULL;
204454af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
20451a43cff9SSean Bruno #ifdef INET6
20461a43cff9SSean Bruno 		if (!(grp->il_vflag & INP_IPV4))
20471a43cff9SSean Bruno 			continue;
20481a43cff9SSean Bruno #endif
20498be02ee4SMark Johnston 		if (grp->il_lport != lport)
20508be02ee4SMark Johnston 			continue;
20511a43cff9SSean Bruno 
20528be02ee4SMark Johnston 		idx = INP_PCBLBGROUP_PKTHASH(faddr->s_addr, lport, fport) %
20538be02ee4SMark Johnston 		    grp->il_inpcnt;
20548be02ee4SMark Johnston 		if (grp->il_laddr.s_addr == laddr->s_addr)
20551a43cff9SSean Bruno 			return (grp->il_inp[idx]);
20561a43cff9SSean Bruno 		if (grp->il_laddr.s_addr == INADDR_ANY &&
20578be02ee4SMark Johnston 		    (lookupflags & INPLOOKUP_WILDCARD) != 0)
20581a43cff9SSean Bruno 			local_wild = grp->il_inp[idx];
20591a43cff9SSean Bruno 	}
20601a43cff9SSean Bruno 	return (local_wild);
20611a43cff9SSean Bruno }
20621a43cff9SSean Bruno 
206352cd27cbSRobert Watson #ifdef PCBGROUP
206452cd27cbSRobert Watson /*
206552cd27cbSRobert Watson  * Lookup PCB in hash list, using pcbgroup tables.
206652cd27cbSRobert Watson  */
206752cd27cbSRobert Watson static struct inpcb *
206852cd27cbSRobert Watson in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
206952cd27cbSRobert Watson     struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
207052cd27cbSRobert Watson     u_int lport_arg, int lookupflags, struct ifnet *ifp)
207152cd27cbSRobert Watson {
207252cd27cbSRobert Watson 	struct inpcbhead *head;
207352cd27cbSRobert Watson 	struct inpcb *inp, *tmpinp;
207452cd27cbSRobert Watson 	u_short fport = fport_arg, lport = lport_arg;
20757fb2986fSJonathan T. Looney 	bool locked;
207652cd27cbSRobert Watson 
207752cd27cbSRobert Watson 	/*
207852cd27cbSRobert Watson 	 * First look for an exact match.
207952cd27cbSRobert Watson 	 */
208052cd27cbSRobert Watson 	tmpinp = NULL;
208152cd27cbSRobert Watson 	INP_GROUP_LOCK(pcbgroup);
208252cd27cbSRobert Watson 	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
208352cd27cbSRobert Watson 	    pcbgroup->ipg_hashmask)];
2084feeef850SMatt Macy 	CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
208552cd27cbSRobert Watson #ifdef INET6
208652cd27cbSRobert Watson 		/* XXX inp locking */
208752cd27cbSRobert Watson 		if ((inp->inp_vflag & INP_IPV4) == 0)
208852cd27cbSRobert Watson 			continue;
208952cd27cbSRobert Watson #endif
209052cd27cbSRobert Watson 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
209152cd27cbSRobert Watson 		    inp->inp_laddr.s_addr == laddr.s_addr &&
209252cd27cbSRobert Watson 		    inp->inp_fport == fport &&
209352cd27cbSRobert Watson 		    inp->inp_lport == lport) {
209452cd27cbSRobert Watson 			/*
209552cd27cbSRobert Watson 			 * XXX We should be able to directly return
209652cd27cbSRobert Watson 			 * the inp here, without any checks.
209752cd27cbSRobert Watson 			 * Well unless both bound with SO_REUSEPORT?
209852cd27cbSRobert Watson 			 */
209952cd27cbSRobert Watson 			if (prison_flag(inp->inp_cred, PR_IP4))
210052cd27cbSRobert Watson 				goto found;
210152cd27cbSRobert Watson 			if (tmpinp == NULL)
210252cd27cbSRobert Watson 				tmpinp = inp;
210352cd27cbSRobert Watson 		}
210452cd27cbSRobert Watson 	}
210552cd27cbSRobert Watson 	if (tmpinp != NULL) {
210652cd27cbSRobert Watson 		inp = tmpinp;
210752cd27cbSRobert Watson 		goto found;
210852cd27cbSRobert Watson 	}
210952cd27cbSRobert Watson 
21100a100a6fSAdrian Chadd #ifdef	RSS
21110a100a6fSAdrian Chadd 	/*
21120a100a6fSAdrian Chadd 	 * For incoming connections, we may wish to do a wildcard
21130a100a6fSAdrian Chadd 	 * match for an RSS-local socket.
21140a100a6fSAdrian Chadd 	 */
21150a100a6fSAdrian Chadd 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
21160a100a6fSAdrian Chadd 		struct inpcb *local_wild = NULL, *local_exact = NULL;
21170a100a6fSAdrian Chadd #ifdef INET6
21180a100a6fSAdrian Chadd 		struct inpcb *local_wild_mapped = NULL;
21190a100a6fSAdrian Chadd #endif
21200a100a6fSAdrian Chadd 		struct inpcb *jail_wild = NULL;
21210a100a6fSAdrian Chadd 		struct inpcbhead *head;
21220a100a6fSAdrian Chadd 		int injail;
21230a100a6fSAdrian Chadd 
21240a100a6fSAdrian Chadd 		/*
21250a100a6fSAdrian Chadd 		 * Order of socket selection - we always prefer jails.
21260a100a6fSAdrian Chadd 		 *      1. jailed, non-wild.
21270a100a6fSAdrian Chadd 		 *      2. jailed, wild.
21280a100a6fSAdrian Chadd 		 *      3. non-jailed, non-wild.
21290a100a6fSAdrian Chadd 		 *      4. non-jailed, wild.
21300a100a6fSAdrian Chadd 		 */
21310a100a6fSAdrian Chadd 
21320a100a6fSAdrian Chadd 		head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
21330a100a6fSAdrian Chadd 		    lport, 0, pcbgroup->ipg_hashmask)];
2134feeef850SMatt Macy 		CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
21350a100a6fSAdrian Chadd #ifdef INET6
21360a100a6fSAdrian Chadd 			/* XXX inp locking */
21370a100a6fSAdrian Chadd 			if ((inp->inp_vflag & INP_IPV4) == 0)
21380a100a6fSAdrian Chadd 				continue;
21390a100a6fSAdrian Chadd #endif
21400a100a6fSAdrian Chadd 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
21410a100a6fSAdrian Chadd 			    inp->inp_lport != lport)
21420a100a6fSAdrian Chadd 				continue;
21430a100a6fSAdrian Chadd 
21440a100a6fSAdrian Chadd 			injail = prison_flag(inp->inp_cred, PR_IP4);
21450a100a6fSAdrian Chadd 			if (injail) {
21460a100a6fSAdrian Chadd 				if (prison_check_ip4(inp->inp_cred,
21470a100a6fSAdrian Chadd 				    &laddr) != 0)
21480a100a6fSAdrian Chadd 					continue;
21490a100a6fSAdrian Chadd 			} else {
21500a100a6fSAdrian Chadd 				if (local_exact != NULL)
21510a100a6fSAdrian Chadd 					continue;
21520a100a6fSAdrian Chadd 			}
21530a100a6fSAdrian Chadd 
21540a100a6fSAdrian Chadd 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
21550a100a6fSAdrian Chadd 				if (injail)
21560a100a6fSAdrian Chadd 					goto found;
21570a100a6fSAdrian Chadd 				else
21580a100a6fSAdrian Chadd 					local_exact = inp;
21590a100a6fSAdrian Chadd 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
21600a100a6fSAdrian Chadd #ifdef INET6
21610a100a6fSAdrian Chadd 				/* XXX inp locking, NULL check */
21620a100a6fSAdrian Chadd 				if (inp->inp_vflag & INP_IPV6PROTO)
21630a100a6fSAdrian Chadd 					local_wild_mapped = inp;
21640a100a6fSAdrian Chadd 				else
21650a100a6fSAdrian Chadd #endif
21660a100a6fSAdrian Chadd 					if (injail)
21670a100a6fSAdrian Chadd 						jail_wild = inp;
21680a100a6fSAdrian Chadd 					else
21690a100a6fSAdrian Chadd 						local_wild = inp;
21700a100a6fSAdrian Chadd 			}
21710a100a6fSAdrian Chadd 		} /* LIST_FOREACH */
21720a100a6fSAdrian Chadd 
21730a100a6fSAdrian Chadd 		inp = jail_wild;
21740a100a6fSAdrian Chadd 		if (inp == NULL)
21750a100a6fSAdrian Chadd 			inp = local_exact;
21760a100a6fSAdrian Chadd 		if (inp == NULL)
21770a100a6fSAdrian Chadd 			inp = local_wild;
21780a100a6fSAdrian Chadd #ifdef INET6
21790a100a6fSAdrian Chadd 		if (inp == NULL)
21800a100a6fSAdrian Chadd 			inp = local_wild_mapped;
21810a100a6fSAdrian Chadd #endif
21820a100a6fSAdrian Chadd 		if (inp != NULL)
21830a100a6fSAdrian Chadd 			goto found;
21840a100a6fSAdrian Chadd 	}
21850a100a6fSAdrian Chadd #endif
21860a100a6fSAdrian Chadd 
218752cd27cbSRobert Watson 	/*
218852cd27cbSRobert Watson 	 * Then look for a wildcard match, if requested.
218952cd27cbSRobert Watson 	 */
219052cd27cbSRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
219152cd27cbSRobert Watson 		struct inpcb *local_wild = NULL, *local_exact = NULL;
219252cd27cbSRobert Watson #ifdef INET6
219352cd27cbSRobert Watson 		struct inpcb *local_wild_mapped = NULL;
219452cd27cbSRobert Watson #endif
219552cd27cbSRobert Watson 		struct inpcb *jail_wild = NULL;
219652cd27cbSRobert Watson 		struct inpcbhead *head;
219752cd27cbSRobert Watson 		int injail;
219852cd27cbSRobert Watson 
219952cd27cbSRobert Watson 		/*
220052cd27cbSRobert Watson 		 * Order of socket selection - we always prefer jails.
220152cd27cbSRobert Watson 		 *      1. jailed, non-wild.
220252cd27cbSRobert Watson 		 *      2. jailed, wild.
220352cd27cbSRobert Watson 		 *      3. non-jailed, non-wild.
220452cd27cbSRobert Watson 		 *      4. non-jailed, wild.
220552cd27cbSRobert Watson 		 */
220652cd27cbSRobert Watson 		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
220752cd27cbSRobert Watson 		    0, pcbinfo->ipi_wildmask)];
2208feeef850SMatt Macy 		CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
220952cd27cbSRobert Watson #ifdef INET6
221052cd27cbSRobert Watson 			/* XXX inp locking */
221152cd27cbSRobert Watson 			if ((inp->inp_vflag & INP_IPV4) == 0)
221252cd27cbSRobert Watson 				continue;
221352cd27cbSRobert Watson #endif
221452cd27cbSRobert Watson 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
221552cd27cbSRobert Watson 			    inp->inp_lport != lport)
221652cd27cbSRobert Watson 				continue;
221752cd27cbSRobert Watson 
221852cd27cbSRobert Watson 			injail = prison_flag(inp->inp_cred, PR_IP4);
221952cd27cbSRobert Watson 			if (injail) {
222052cd27cbSRobert Watson 				if (prison_check_ip4(inp->inp_cred,
222152cd27cbSRobert Watson 				    &laddr) != 0)
222252cd27cbSRobert Watson 					continue;
222352cd27cbSRobert Watson 			} else {
222452cd27cbSRobert Watson 				if (local_exact != NULL)
222552cd27cbSRobert Watson 					continue;
222652cd27cbSRobert Watson 			}
222752cd27cbSRobert Watson 
222852cd27cbSRobert Watson 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
222952cd27cbSRobert Watson 				if (injail)
223052cd27cbSRobert Watson 					goto found;
223152cd27cbSRobert Watson 				else
223252cd27cbSRobert Watson 					local_exact = inp;
223352cd27cbSRobert Watson 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
223452cd27cbSRobert Watson #ifdef INET6
223552cd27cbSRobert Watson 				/* XXX inp locking, NULL check */
223652cd27cbSRobert Watson 				if (inp->inp_vflag & INP_IPV6PROTO)
223752cd27cbSRobert Watson 					local_wild_mapped = inp;
223852cd27cbSRobert Watson 				else
223983e521ecSBjoern A. Zeeb #endif
224052cd27cbSRobert Watson 					if (injail)
224152cd27cbSRobert Watson 						jail_wild = inp;
224252cd27cbSRobert Watson 					else
224352cd27cbSRobert Watson 						local_wild = inp;
224452cd27cbSRobert Watson 			}
224552cd27cbSRobert Watson 		} /* LIST_FOREACH */
224652cd27cbSRobert Watson 		inp = jail_wild;
224752cd27cbSRobert Watson 		if (inp == NULL)
224852cd27cbSRobert Watson 			inp = local_exact;
224952cd27cbSRobert Watson 		if (inp == NULL)
225052cd27cbSRobert Watson 			inp = local_wild;
225152cd27cbSRobert Watson #ifdef INET6
225252cd27cbSRobert Watson 		if (inp == NULL)
225352cd27cbSRobert Watson 			inp = local_wild_mapped;
225483e521ecSBjoern A. Zeeb #endif
225552cd27cbSRobert Watson 		if (inp != NULL)
225652cd27cbSRobert Watson 			goto found;
225752cd27cbSRobert Watson 	} /* if (lookupflags & INPLOOKUP_WILDCARD) */
225852cd27cbSRobert Watson 	INP_GROUP_UNLOCK(pcbgroup);
225952cd27cbSRobert Watson 	return (NULL);
226052cd27cbSRobert Watson 
226152cd27cbSRobert Watson found:
22627fb2986fSJonathan T. Looney 	if (lookupflags & INPLOOKUP_WLOCKPCB)
2263b9a9e8e9SNavdeep Parhar 		locked = INP_TRY_WLOCK(inp);
22647fb2986fSJonathan T. Looney 	else if (lookupflags & INPLOOKUP_RLOCKPCB)
2265b9a9e8e9SNavdeep Parhar 		locked = INP_TRY_RLOCK(inp);
22667fb2986fSJonathan T. Looney 	else
22677fb2986fSJonathan T. Looney 		panic("%s: locking bug", __func__);
2268483305b9SMatt Macy 	if (__predict_false(locked && (inp->inp_flags2 & INP_FREED))) {
2269483305b9SMatt Macy 		if (lookupflags & INPLOOKUP_WLOCKPCB)
2270483305b9SMatt Macy 			INP_WUNLOCK(inp);
2271483305b9SMatt Macy 		else
2272483305b9SMatt Macy 			INP_RUNLOCK(inp);
2273483305b9SMatt Macy 		return (NULL);
2274483305b9SMatt Macy 	} else if (!locked)
227552cd27cbSRobert Watson 		in_pcbref(inp);
227652cd27cbSRobert Watson 	INP_GROUP_UNLOCK(pcbgroup);
22777fb2986fSJonathan T. Looney 	if (!locked) {
227852cd27cbSRobert Watson 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
227952cd27cbSRobert Watson 			INP_WLOCK(inp);
228052cd27cbSRobert Watson 			if (in_pcbrele_wlocked(inp))
228152cd27cbSRobert Watson 				return (NULL);
22827fb2986fSJonathan T. Looney 		} else {
228352cd27cbSRobert Watson 			INP_RLOCK(inp);
228452cd27cbSRobert Watson 			if (in_pcbrele_rlocked(inp))
228552cd27cbSRobert Watson 				return (NULL);
22867fb2986fSJonathan T. Looney 		}
22877fb2986fSJonathan T. Looney 	}
22887fb2986fSJonathan T. Looney #ifdef INVARIANTS
22897fb2986fSJonathan T. Looney 	if (lookupflags & INPLOOKUP_WLOCKPCB)
22907fb2986fSJonathan T. Looney 		INP_WLOCK_ASSERT(inp);
22917fb2986fSJonathan T. Looney 	else
22927fb2986fSJonathan T. Looney 		INP_RLOCK_ASSERT(inp);
22937fb2986fSJonathan T. Looney #endif
229452cd27cbSRobert Watson 	return (inp);
229552cd27cbSRobert Watson }
229652cd27cbSRobert Watson #endif /* PCBGROUP */
229752cd27cbSRobert Watson 
229815bd2b43SDavid Greenman /*
2299fa046d87SRobert Watson  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
2300fa046d87SRobert Watson  * that the caller has locked the hash list, and will not perform any further
2301fa046d87SRobert Watson  * locking or reference operations on either the hash list or the connection.
230215bd2b43SDavid Greenman  */
2303fa046d87SRobert Watson static struct inpcb *
2304fa046d87SRobert Watson in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
230568e0d7e0SRobert Watson     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2306136d4f1cSRobert Watson     struct ifnet *ifp)
230715bd2b43SDavid Greenman {
230815bd2b43SDavid Greenman 	struct inpcbhead *head;
2309413628a7SBjoern A. Zeeb 	struct inpcb *inp, *tmpinp;
231015bd2b43SDavid Greenman 	u_short fport = fport_arg, lport = lport_arg;
231115bd2b43SDavid Greenman 
231268e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
231368e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2314d797164aSGleb Smirnoff 	INP_HASH_LOCK_ASSERT(pcbinfo);
2315d797164aSGleb Smirnoff 
231615bd2b43SDavid Greenman 	/*
231715bd2b43SDavid Greenman 	 * First look for an exact match.
231815bd2b43SDavid Greenman 	 */
2319413628a7SBjoern A. Zeeb 	tmpinp = NULL;
2320712fc218SRobert Watson 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2321712fc218SRobert Watson 	    pcbinfo->ipi_hashmask)];
2322b872626dSMatt Macy 	CK_LIST_FOREACH(inp, head, inp_hash) {
2323cfa1ca9dSYoshinobu Inoue #ifdef INET6
2324413628a7SBjoern A. Zeeb 		/* XXX inp locking */
2325369dc8ceSEivind Eklund 		if ((inp->inp_vflag & INP_IPV4) == 0)
2326cfa1ca9dSYoshinobu Inoue 			continue;
2327cfa1ca9dSYoshinobu Inoue #endif
23286d6a026bSDavid Greenman 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
2329ca98b82cSDavid Greenman 		    inp->inp_laddr.s_addr == laddr.s_addr &&
2330ca98b82cSDavid Greenman 		    inp->inp_fport == fport &&
2331413628a7SBjoern A. Zeeb 		    inp->inp_lport == lport) {
2332413628a7SBjoern A. Zeeb 			/*
2333413628a7SBjoern A. Zeeb 			 * XXX We should be able to directly return
2334413628a7SBjoern A. Zeeb 			 * the inp here, without any checks.
2335413628a7SBjoern A. Zeeb 			 * Well unless both bound with SO_REUSEPORT?
2336413628a7SBjoern A. Zeeb 			 */
23370304c731SJamie Gritton 			if (prison_flag(inp->inp_cred, PR_IP4))
2338c3229e05SDavid Greenman 				return (inp);
2339413628a7SBjoern A. Zeeb 			if (tmpinp == NULL)
2340413628a7SBjoern A. Zeeb 				tmpinp = inp;
2341c3229e05SDavid Greenman 		}
2342413628a7SBjoern A. Zeeb 	}
2343413628a7SBjoern A. Zeeb 	if (tmpinp != NULL)
2344413628a7SBjoern A. Zeeb 		return (tmpinp);
2345e3fd5ffdSRobert Watson 
2346e3fd5ffdSRobert Watson 	/*
23471a43cff9SSean Bruno 	 * Then look in lb group (for wildcard match).
23481a43cff9SSean Bruno 	 */
2349d9ff5789SMark Johnston 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
23501a43cff9SSean Bruno 		inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
23511a43cff9SSean Bruno 		    fport, lookupflags);
2352d9ff5789SMark Johnston 		if (inp != NULL)
23531a43cff9SSean Bruno 			return (inp);
23541a43cff9SSean Bruno 	}
23551a43cff9SSean Bruno 
23561a43cff9SSean Bruno 	/*
2357e3fd5ffdSRobert Watson 	 * Then look for a wildcard match, if requested.
2358e3fd5ffdSRobert Watson 	 */
235968e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2360413628a7SBjoern A. Zeeb 		struct inpcb *local_wild = NULL, *local_exact = NULL;
2361e3fd5ffdSRobert Watson #ifdef INET6
2362cfa1ca9dSYoshinobu Inoue 		struct inpcb *local_wild_mapped = NULL;
2363e3fd5ffdSRobert Watson #endif
2364413628a7SBjoern A. Zeeb 		struct inpcb *jail_wild = NULL;
2365413628a7SBjoern A. Zeeb 		int injail;
2366413628a7SBjoern A. Zeeb 
2367413628a7SBjoern A. Zeeb 		/*
2368413628a7SBjoern A. Zeeb 		 * Order of socket selection - we always prefer jails.
2369413628a7SBjoern A. Zeeb 		 *      1. jailed, non-wild.
2370413628a7SBjoern A. Zeeb 		 *      2. jailed, wild.
2371413628a7SBjoern A. Zeeb 		 *      3. non-jailed, non-wild.
2372413628a7SBjoern A. Zeeb 		 *      4. non-jailed, wild.
2373413628a7SBjoern A. Zeeb 		 */
23746d6a026bSDavid Greenman 
2375712fc218SRobert Watson 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2376712fc218SRobert Watson 		    0, pcbinfo->ipi_hashmask)];
2377b872626dSMatt Macy 		CK_LIST_FOREACH(inp, head, inp_hash) {
2378cfa1ca9dSYoshinobu Inoue #ifdef INET6
2379413628a7SBjoern A. Zeeb 			/* XXX inp locking */
2380369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
2381cfa1ca9dSYoshinobu Inoue 				continue;
2382cfa1ca9dSYoshinobu Inoue #endif
2383413628a7SBjoern A. Zeeb 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
2384413628a7SBjoern A. Zeeb 			    inp->inp_lport != lport)
2385413628a7SBjoern A. Zeeb 				continue;
2386413628a7SBjoern A. Zeeb 
23870304c731SJamie Gritton 			injail = prison_flag(inp->inp_cred, PR_IP4);
2388413628a7SBjoern A. Zeeb 			if (injail) {
2389b89e82ddSJamie Gritton 				if (prison_check_ip4(inp->inp_cred,
2390b89e82ddSJamie Gritton 				    &laddr) != 0)
2391413628a7SBjoern A. Zeeb 					continue;
2392413628a7SBjoern A. Zeeb 			} else {
2393413628a7SBjoern A. Zeeb 				if (local_exact != NULL)
2394413628a7SBjoern A. Zeeb 					continue;
2395413628a7SBjoern A. Zeeb 			}
2396413628a7SBjoern A. Zeeb 
2397413628a7SBjoern A. Zeeb 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
2398413628a7SBjoern A. Zeeb 				if (injail)
2399c3229e05SDavid Greenman 					return (inp);
2400413628a7SBjoern A. Zeeb 				else
2401413628a7SBjoern A. Zeeb 					local_exact = inp;
2402413628a7SBjoern A. Zeeb 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2403e3fd5ffdSRobert Watson #ifdef INET6
2404413628a7SBjoern A. Zeeb 				/* XXX inp locking, NULL check */
24055cd54324SBjoern A. Zeeb 				if (inp->inp_vflag & INP_IPV6PROTO)
2406cfa1ca9dSYoshinobu Inoue 					local_wild_mapped = inp;
2407cfa1ca9dSYoshinobu Inoue 				else
240883e521ecSBjoern A. Zeeb #endif
2409413628a7SBjoern A. Zeeb 					if (injail)
2410413628a7SBjoern A. Zeeb 						jail_wild = inp;
2411413628a7SBjoern A. Zeeb 					else
24126d6a026bSDavid Greenman 						local_wild = inp;
24136d6a026bSDavid Greenman 			}
2414413628a7SBjoern A. Zeeb 		} /* LIST_FOREACH */
2415413628a7SBjoern A. Zeeb 		if (jail_wild != NULL)
2416413628a7SBjoern A. Zeeb 			return (jail_wild);
2417413628a7SBjoern A. Zeeb 		if (local_exact != NULL)
2418413628a7SBjoern A. Zeeb 			return (local_exact);
2419413628a7SBjoern A. Zeeb 		if (local_wild != NULL)
2420c3229e05SDavid Greenman 			return (local_wild);
2421413628a7SBjoern A. Zeeb #ifdef INET6
2422413628a7SBjoern A. Zeeb 		if (local_wild_mapped != NULL)
2423413628a7SBjoern A. Zeeb 			return (local_wild_mapped);
242483e521ecSBjoern A. Zeeb #endif
242568e0d7e0SRobert Watson 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2426413628a7SBjoern A. Zeeb 
24276d6a026bSDavid Greenman 	return (NULL);
242815bd2b43SDavid Greenman }
2429fa046d87SRobert Watson 
2430fa046d87SRobert Watson /*
2431fa046d87SRobert Watson  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
2432fa046d87SRobert Watson  * hash list lock, and will return the inpcb locked (i.e., requires
2433fa046d87SRobert Watson  * INPLOOKUP_LOCKPCB).
2434fa046d87SRobert Watson  */
2435fa046d87SRobert Watson static struct inpcb *
2436fa046d87SRobert Watson in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2437fa046d87SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2438fa046d87SRobert Watson     struct ifnet *ifp)
2439fa046d87SRobert Watson {
2440fa046d87SRobert Watson 	struct inpcb *inp;
2441fa046d87SRobert Watson 
2442fa046d87SRobert Watson 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2443fa046d87SRobert Watson 	    (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
2444fa046d87SRobert Watson 	if (inp != NULL) {
2445fa046d87SRobert Watson 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
2446fa046d87SRobert Watson 			INP_WLOCK(inp);
24473d348772SMatt Macy 			if (__predict_false(inp->inp_flags2 & INP_FREED)) {
24483d348772SMatt Macy 				INP_WUNLOCK(inp);
24493d348772SMatt Macy 				inp = NULL;
24503d348772SMatt Macy 			}
24513d348772SMatt Macy 		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2452fa046d87SRobert Watson 			INP_RLOCK(inp);
24533d348772SMatt Macy 			if (__predict_false(inp->inp_flags2 & INP_FREED)) {
24543d348772SMatt Macy 				INP_RUNLOCK(inp);
24553d348772SMatt Macy 				inp = NULL;
24567fb2986fSJonathan T. Looney 			}
24573d348772SMatt Macy 		} else
24583d348772SMatt Macy 			panic("%s: locking bug", __func__);
24597fb2986fSJonathan T. Looney #ifdef INVARIANTS
24603d348772SMatt Macy 		if (inp != NULL) {
24617fb2986fSJonathan T. Looney 			if (lookupflags & INPLOOKUP_WLOCKPCB)
24627fb2986fSJonathan T. Looney 				INP_WLOCK_ASSERT(inp);
24637fb2986fSJonathan T. Looney 			else
24647fb2986fSJonathan T. Looney 				INP_RLOCK_ASSERT(inp);
24653d348772SMatt Macy 		}
24667fb2986fSJonathan T. Looney #endif
24673d348772SMatt Macy 	}
2468d797164aSGleb Smirnoff 
2469fa046d87SRobert Watson 	return (inp);
2470fa046d87SRobert Watson }
2471fa046d87SRobert Watson 
2472fa046d87SRobert Watson /*
2473d3c1f003SRobert Watson  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2474d3c1f003SRobert Watson  * from which a pre-calculated hash value may be extracted.
247552cd27cbSRobert Watson  *
247652cd27cbSRobert Watson  * Possibly more of this logic should be in in_pcbgroup.c.
2477fa046d87SRobert Watson  */
2478fa046d87SRobert Watson struct inpcb *
2479fa046d87SRobert Watson in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2480fa046d87SRobert Watson     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2481fa046d87SRobert Watson {
24827527624eSRobert Watson #if defined(PCBGROUP) && !defined(RSS)
248352cd27cbSRobert Watson 	struct inpcbgroup *pcbgroup;
248452cd27cbSRobert Watson #endif
2485fa046d87SRobert Watson 
2486fa046d87SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2487fa046d87SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2488fa046d87SRobert Watson 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2489fa046d87SRobert Watson 	    ("%s: LOCKPCB not set", __func__));
2490fa046d87SRobert Watson 
24917527624eSRobert Watson 	/*
24927527624eSRobert Watson 	 * When not using RSS, use connection groups in preference to the
24937527624eSRobert Watson 	 * reservation table when looking up 4-tuples.  When using RSS, just
24947527624eSRobert Watson 	 * use the reservation table, due to the cost of the Toeplitz hash
24957527624eSRobert Watson 	 * in software.
24967527624eSRobert Watson 	 *
24977527624eSRobert Watson 	 * XXXRW: This policy belongs in the pcbgroup code, as in principle
24987527624eSRobert Watson 	 * we could be doing RSS with a non-Toeplitz hash that is affordable
24997527624eSRobert Watson 	 * in software.
25007527624eSRobert Watson 	 */
25017527624eSRobert Watson #if defined(PCBGROUP) && !defined(RSS)
250252cd27cbSRobert Watson 	if (in_pcbgroup_enabled(pcbinfo)) {
250352cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
250452cd27cbSRobert Watson 		    fport);
250552cd27cbSRobert Watson 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
250652cd27cbSRobert Watson 		    laddr, lport, lookupflags, ifp));
250752cd27cbSRobert Watson 	}
250852cd27cbSRobert Watson #endif
2509fa046d87SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2510fa046d87SRobert Watson 	    lookupflags, ifp));
2511fa046d87SRobert Watson }
2512d3c1f003SRobert Watson 
2513d3c1f003SRobert Watson struct inpcb *
2514d3c1f003SRobert Watson in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2515d3c1f003SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2516d3c1f003SRobert Watson     struct ifnet *ifp, struct mbuf *m)
2517d3c1f003SRobert Watson {
251852cd27cbSRobert Watson #ifdef PCBGROUP
251952cd27cbSRobert Watson 	struct inpcbgroup *pcbgroup;
252052cd27cbSRobert Watson #endif
2521d3c1f003SRobert Watson 
2522d3c1f003SRobert Watson 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2523d3c1f003SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2524d3c1f003SRobert Watson 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2525d3c1f003SRobert Watson 	    ("%s: LOCKPCB not set", __func__));
2526d3c1f003SRobert Watson 
252752cd27cbSRobert Watson #ifdef PCBGROUP
25287527624eSRobert Watson 	/*
25297527624eSRobert Watson 	 * If we can use a hardware-generated hash to look up the connection
25307527624eSRobert Watson 	 * group, use that connection group to find the inpcb.  Otherwise
25317527624eSRobert Watson 	 * fall back on a software hash -- or the reservation table if we're
25327527624eSRobert Watson 	 * using RSS.
25337527624eSRobert Watson 	 *
25347527624eSRobert Watson 	 * XXXRW: As above, that policy belongs in the pcbgroup code.
25357527624eSRobert Watson 	 */
25367527624eSRobert Watson 	if (in_pcbgroup_enabled(pcbinfo) &&
25377527624eSRobert Watson 	    !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
253852cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
253952cd27cbSRobert Watson 		    m->m_pkthdr.flowid);
254052cd27cbSRobert Watson 		if (pcbgroup != NULL)
254152cd27cbSRobert Watson 			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
254252cd27cbSRobert Watson 			    fport, laddr, lport, lookupflags, ifp));
25437527624eSRobert Watson #ifndef RSS
254452cd27cbSRobert Watson 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
254552cd27cbSRobert Watson 		    fport);
254652cd27cbSRobert Watson 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
254752cd27cbSRobert Watson 		    laddr, lport, lookupflags, ifp));
25487527624eSRobert Watson #endif
254952cd27cbSRobert Watson 	}
255052cd27cbSRobert Watson #endif
2551d3c1f003SRobert Watson 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2552d3c1f003SRobert Watson 	    lookupflags, ifp));
2553d3c1f003SRobert Watson }
255467107f45SBjoern A. Zeeb #endif /* INET */
255515bd2b43SDavid Greenman 
25567bc4aca7SDavid Greenman /*
2557c3229e05SDavid Greenman  * Insert PCB onto various hash lists.
25587bc4aca7SDavid Greenman  */
255952cd27cbSRobert Watson static int
2560fe1274eeSMichael Tuexen in_pcbinshash_internal(struct inpcb *inp, struct mbuf *m)
256115bd2b43SDavid Greenman {
2562c3229e05SDavid Greenman 	struct inpcbhead *pcbhash;
2563c3229e05SDavid Greenman 	struct inpcbporthead *pcbporthash;
2564c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2565c3229e05SDavid Greenman 	struct inpcbport *phd;
2566cfa1ca9dSYoshinobu Inoue 	u_int32_t hashkey_faddr;
25671a43cff9SSean Bruno 	int so_options;
256815bd2b43SDavid Greenman 
25698501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2570fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2571fa046d87SRobert Watson 
2572111d57a6SRobert Watson 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2573111d57a6SRobert Watson 	    ("in_pcbinshash: INP_INHASHLIST"));
2574602cc7f1SRobert Watson 
2575cfa1ca9dSYoshinobu Inoue #ifdef INET6
2576cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
25771b44e5ffSAndrey V. Elsukov 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2578cfa1ca9dSYoshinobu Inoue 	else
257983e521ecSBjoern A. Zeeb #endif
2580cfa1ca9dSYoshinobu Inoue 	hashkey_faddr = inp->inp_faddr.s_addr;
2581cfa1ca9dSYoshinobu Inoue 
2582712fc218SRobert Watson 	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2583712fc218SRobert Watson 		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
258415bd2b43SDavid Greenman 
2585712fc218SRobert Watson 	pcbporthash = &pcbinfo->ipi_porthashbase[
2586712fc218SRobert Watson 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2587c3229e05SDavid Greenman 
2588c3229e05SDavid Greenman 	/*
25891a43cff9SSean Bruno 	 * Add entry to load balance group.
25901a43cff9SSean Bruno 	 * Only do this if SO_REUSEPORT_LB is set.
25911a43cff9SSean Bruno 	 */
25921a43cff9SSean Bruno 	so_options = inp_so_options(inp);
25931a43cff9SSean Bruno 	if (so_options & SO_REUSEPORT_LB) {
25941a43cff9SSean Bruno 		int ret = in_pcbinslbgrouphash(inp);
25951a43cff9SSean Bruno 		if (ret) {
25961a43cff9SSean Bruno 			/* pcb lb group malloc fail (ret=ENOBUFS). */
25971a43cff9SSean Bruno 			return (ret);
25981a43cff9SSean Bruno 		}
25991a43cff9SSean Bruno 	}
26001a43cff9SSean Bruno 
26011a43cff9SSean Bruno 	/*
2602c3229e05SDavid Greenman 	 * Go through port list and look for a head for this lport.
2603c3229e05SDavid Greenman 	 */
2604b872626dSMatt Macy 	CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2605c3229e05SDavid Greenman 		if (phd->phd_port == inp->inp_lport)
2606c3229e05SDavid Greenman 			break;
2607c3229e05SDavid Greenman 	}
2608c3229e05SDavid Greenman 	/*
2609c3229e05SDavid Greenman 	 * If none exists, malloc one and tack it on.
2610c3229e05SDavid Greenman 	 */
2611c3229e05SDavid Greenman 	if (phd == NULL) {
26121ede983cSDag-Erling Smørgrav 		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2613c3229e05SDavid Greenman 		if (phd == NULL) {
2614c3229e05SDavid Greenman 			return (ENOBUFS); /* XXX */
2615c3229e05SDavid Greenman 		}
2616f09ee4fcSMatt Macy 		bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2617c3229e05SDavid Greenman 		phd->phd_port = inp->inp_lport;
2618b872626dSMatt Macy 		CK_LIST_INIT(&phd->phd_pcblist);
2619b872626dSMatt Macy 		CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2620c3229e05SDavid Greenman 	}
2621c3229e05SDavid Greenman 	inp->inp_phd = phd;
2622b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2623b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2624111d57a6SRobert Watson 	inp->inp_flags |= INP_INHASHLIST;
262552cd27cbSRobert Watson #ifdef PCBGROUP
2626fe1274eeSMichael Tuexen 	if (m != NULL) {
2627fe1274eeSMichael Tuexen 		in_pcbgroup_update_mbuf(inp, m);
2628fe1274eeSMichael Tuexen 	} else {
262952cd27cbSRobert Watson 		in_pcbgroup_update(inp);
2630fe1274eeSMichael Tuexen 	}
263152cd27cbSRobert Watson #endif
2632c3229e05SDavid Greenman 	return (0);
263315bd2b43SDavid Greenman }
263415bd2b43SDavid Greenman 
263552cd27cbSRobert Watson int
263652cd27cbSRobert Watson in_pcbinshash(struct inpcb *inp)
263752cd27cbSRobert Watson {
263852cd27cbSRobert Watson 
2639fe1274eeSMichael Tuexen 	return (in_pcbinshash_internal(inp, NULL));
264052cd27cbSRobert Watson }
264152cd27cbSRobert Watson 
264252cd27cbSRobert Watson int
2643fe1274eeSMichael Tuexen in_pcbinshash_mbuf(struct inpcb *inp, struct mbuf *m)
264452cd27cbSRobert Watson {
264552cd27cbSRobert Watson 
2646fe1274eeSMichael Tuexen 	return (in_pcbinshash_internal(inp, m));
264752cd27cbSRobert Watson }
264852cd27cbSRobert Watson 
264952cd27cbSRobert Watson /*
2650c3229e05SDavid Greenman  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2651c3229e05SDavid Greenman  * changed. NOTE: This does not handle the case of the lport changing (the
2652c3229e05SDavid Greenman  * hashed port list would have to be updated as well), so the lport must
2653c3229e05SDavid Greenman  * not change after in_pcbinshash() has been called.
2654c3229e05SDavid Greenman  */
265515bd2b43SDavid Greenman void
2656d3c1f003SRobert Watson in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
265715bd2b43SDavid Greenman {
265859daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
265915bd2b43SDavid Greenman 	struct inpcbhead *head;
2660cfa1ca9dSYoshinobu Inoue 	u_int32_t hashkey_faddr;
266115bd2b43SDavid Greenman 
26628501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2663fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2664fa046d87SRobert Watson 
2665111d57a6SRobert Watson 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2666111d57a6SRobert Watson 	    ("in_pcbrehash: !INP_INHASHLIST"));
2667602cc7f1SRobert Watson 
2668cfa1ca9dSYoshinobu Inoue #ifdef INET6
2669cfa1ca9dSYoshinobu Inoue 	if (inp->inp_vflag & INP_IPV6)
26701b44e5ffSAndrey V. Elsukov 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2671cfa1ca9dSYoshinobu Inoue 	else
267283e521ecSBjoern A. Zeeb #endif
2673cfa1ca9dSYoshinobu Inoue 	hashkey_faddr = inp->inp_faddr.s_addr;
2674cfa1ca9dSYoshinobu Inoue 
2675712fc218SRobert Watson 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2676712fc218SRobert Watson 		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
267715bd2b43SDavid Greenman 
2678b872626dSMatt Macy 	CK_LIST_REMOVE(inp, inp_hash);
2679b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(head, inp, inp_hash);
268052cd27cbSRobert Watson 
268152cd27cbSRobert Watson #ifdef PCBGROUP
268252cd27cbSRobert Watson 	if (m != NULL)
268352cd27cbSRobert Watson 		in_pcbgroup_update_mbuf(inp, m);
268452cd27cbSRobert Watson 	else
268552cd27cbSRobert Watson 		in_pcbgroup_update(inp);
268652cd27cbSRobert Watson #endif
2687c3229e05SDavid Greenman }
2688c3229e05SDavid Greenman 
2689d3c1f003SRobert Watson void
2690d3c1f003SRobert Watson in_pcbrehash(struct inpcb *inp)
2691d3c1f003SRobert Watson {
2692d3c1f003SRobert Watson 
2693d3c1f003SRobert Watson 	in_pcbrehash_mbuf(inp, NULL);
2694d3c1f003SRobert Watson }
2695d3c1f003SRobert Watson 
2696c3229e05SDavid Greenman /*
2697c3229e05SDavid Greenman  * Remove PCB from various lists.
2698c3229e05SDavid Greenman  */
26996d888973SRobert Watson static void
2700136d4f1cSRobert Watson in_pcbremlists(struct inpcb *inp)
2701c3229e05SDavid Greenman {
270259daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
270359daba27SSam Leffler 
27048501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2705ff9b006dSJulien Charbon 	INP_LIST_WLOCK_ASSERT(pcbinfo);
270659daba27SSam Leffler 
270759daba27SSam Leffler 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2708111d57a6SRobert Watson 	if (inp->inp_flags & INP_INHASHLIST) {
2709c3229e05SDavid Greenman 		struct inpcbport *phd = inp->inp_phd;
2710c3229e05SDavid Greenman 
2711fa046d87SRobert Watson 		INP_HASH_WLOCK(pcbinfo);
27121a43cff9SSean Bruno 
27131a43cff9SSean Bruno 		/* XXX: Only do if SO_REUSEPORT_LB set? */
27141a43cff9SSean Bruno 		in_pcbremlbgrouphash(inp);
27151a43cff9SSean Bruno 
2716b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_hash);
2717b872626dSMatt Macy 		CK_LIST_REMOVE(inp, inp_portlist);
2718b872626dSMatt Macy 		if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2719b872626dSMatt Macy 			CK_LIST_REMOVE(phd, phd_hash);
27202a4bd982SGleb Smirnoff 			NET_EPOCH_CALL(inpcbport_free, &phd->phd_epoch_ctx);
2721c3229e05SDavid Greenman 		}
2722fa046d87SRobert Watson 		INP_HASH_WUNLOCK(pcbinfo);
2723111d57a6SRobert Watson 		inp->inp_flags &= ~INP_INHASHLIST;
2724c3229e05SDavid Greenman 	}
2725b872626dSMatt Macy 	CK_LIST_REMOVE(inp, inp_list);
272659daba27SSam Leffler 	pcbinfo->ipi_count--;
272752cd27cbSRobert Watson #ifdef PCBGROUP
272852cd27cbSRobert Watson 	in_pcbgroup_remove(inp);
272952cd27cbSRobert Watson #endif
273015bd2b43SDavid Greenman }
273175c13541SPoul-Henning Kamp 
2732a557af22SRobert Watson /*
273384cc0778SGeorge V. Neville-Neil  * Check for alternatives when higher level complains
273484cc0778SGeorge V. Neville-Neil  * about service problems.  For now, invalidate cached
273584cc0778SGeorge V. Neville-Neil  * routing information.  If the route was created dynamically
273684cc0778SGeorge V. Neville-Neil  * (by a redirect), time to try a default gateway again.
273784cc0778SGeorge V. Neville-Neil  */
273884cc0778SGeorge V. Neville-Neil void
273984cc0778SGeorge V. Neville-Neil in_losing(struct inpcb *inp)
274084cc0778SGeorge V. Neville-Neil {
274184cc0778SGeorge V. Neville-Neil 
2742fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
274384cc0778SGeorge V. Neville-Neil 	return;
274484cc0778SGeorge V. Neville-Neil }
274584cc0778SGeorge V. Neville-Neil 
274684cc0778SGeorge V. Neville-Neil /*
2747a557af22SRobert Watson  * A set label operation has occurred at the socket layer, propagate the
2748a557af22SRobert Watson  * label change into the in_pcb for the socket.
2749a557af22SRobert Watson  */
2750a557af22SRobert Watson void
2751136d4f1cSRobert Watson in_pcbsosetlabel(struct socket *so)
2752a557af22SRobert Watson {
2753a557af22SRobert Watson #ifdef MAC
2754a557af22SRobert Watson 	struct inpcb *inp;
2755a557af22SRobert Watson 
27564c7c478dSRobert Watson 	inp = sotoinpcb(so);
27574c7c478dSRobert Watson 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2758602cc7f1SRobert Watson 
27598501a69cSRobert Watson 	INP_WLOCK(inp);
2760310e7cebSRobert Watson 	SOCK_LOCK(so);
2761a557af22SRobert Watson 	mac_inpcb_sosetlabel(so, inp);
2762310e7cebSRobert Watson 	SOCK_UNLOCK(so);
27638501a69cSRobert Watson 	INP_WUNLOCK(inp);
2764a557af22SRobert Watson #endif
2765a557af22SRobert Watson }
27665f311da2SMike Silbersack 
27675f311da2SMike Silbersack /*
2768ad3a630fSRobert Watson  * ipport_tick runs once per second, determining if random port allocation
2769ad3a630fSRobert Watson  * should be continued.  If more than ipport_randomcps ports have been
2770ad3a630fSRobert Watson  * allocated in the last second, then we return to sequential port
2771ad3a630fSRobert Watson  * allocation. We return to random allocation only once we drop below
2772ad3a630fSRobert Watson  * ipport_randomcps for at least ipport_randomtime seconds.
27735f311da2SMike Silbersack  */
2774aae49dd3SBjoern A. Zeeb static void
2775136d4f1cSRobert Watson ipport_tick(void *xtp)
27765f311da2SMike Silbersack {
27778b615593SMarko Zec 	VNET_ITERATOR_DECL(vnet_iter);
2778ad3a630fSRobert Watson 
27795ee847d3SRobert Watson 	VNET_LIST_RLOCK_NOSLEEP();
27808b615593SMarko Zec 	VNET_FOREACH(vnet_iter) {
27818b615593SMarko Zec 		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
27828b615593SMarko Zec 		if (V_ipport_tcpallocs <=
27838b615593SMarko Zec 		    V_ipport_tcplastcount + V_ipport_randomcps) {
2784603724d3SBjoern A. Zeeb 			if (V_ipport_stoprandom > 0)
2785603724d3SBjoern A. Zeeb 				V_ipport_stoprandom--;
2786ad3a630fSRobert Watson 		} else
2787603724d3SBjoern A. Zeeb 			V_ipport_stoprandom = V_ipport_randomtime;
2788603724d3SBjoern A. Zeeb 		V_ipport_tcplastcount = V_ipport_tcpallocs;
27898b615593SMarko Zec 		CURVNET_RESTORE();
27908b615593SMarko Zec 	}
27915ee847d3SRobert Watson 	VNET_LIST_RUNLOCK_NOSLEEP();
27925f311da2SMike Silbersack 	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
27935f311da2SMike Silbersack }
2794497057eeSRobert Watson 
2795aae49dd3SBjoern A. Zeeb static void
2796aae49dd3SBjoern A. Zeeb ip_fini(void *xtp)
2797aae49dd3SBjoern A. Zeeb {
2798aae49dd3SBjoern A. Zeeb 
2799aae49dd3SBjoern A. Zeeb 	callout_stop(&ipport_tick_callout);
2800aae49dd3SBjoern A. Zeeb }
2801aae49dd3SBjoern A. Zeeb 
2802aae49dd3SBjoern A. Zeeb /*
2803aae49dd3SBjoern A. Zeeb  * The ipport_callout should start running at about the time we attach the
2804aae49dd3SBjoern A. Zeeb  * inet or inet6 domains.
2805aae49dd3SBjoern A. Zeeb  */
2806aae49dd3SBjoern A. Zeeb static void
2807aae49dd3SBjoern A. Zeeb ipport_tick_init(const void *unused __unused)
2808aae49dd3SBjoern A. Zeeb {
2809aae49dd3SBjoern A. Zeeb 
2810aae49dd3SBjoern A. Zeeb 	/* Start ipport_tick. */
2811fd90e2edSJung-uk Kim 	callout_init(&ipport_tick_callout, 1);
2812aae49dd3SBjoern A. Zeeb 	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2813aae49dd3SBjoern A. Zeeb 	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2814aae49dd3SBjoern A. Zeeb 		SHUTDOWN_PRI_DEFAULT);
2815aae49dd3SBjoern A. Zeeb }
2816aae49dd3SBjoern A. Zeeb SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2817aae49dd3SBjoern A. Zeeb     ipport_tick_init, NULL);
2818aae49dd3SBjoern A. Zeeb 
28193d585327SKip Macy void
28203d585327SKip Macy inp_wlock(struct inpcb *inp)
28213d585327SKip Macy {
28223d585327SKip Macy 
28238501a69cSRobert Watson 	INP_WLOCK(inp);
28243d585327SKip Macy }
28253d585327SKip Macy 
28263d585327SKip Macy void
28273d585327SKip Macy inp_wunlock(struct inpcb *inp)
28283d585327SKip Macy {
28293d585327SKip Macy 
28308501a69cSRobert Watson 	INP_WUNLOCK(inp);
28313d585327SKip Macy }
28323d585327SKip Macy 
28333d585327SKip Macy void
28343d585327SKip Macy inp_rlock(struct inpcb *inp)
28353d585327SKip Macy {
28363d585327SKip Macy 
2837a69042a5SRobert Watson 	INP_RLOCK(inp);
28383d585327SKip Macy }
28393d585327SKip Macy 
28403d585327SKip Macy void
28413d585327SKip Macy inp_runlock(struct inpcb *inp)
28423d585327SKip Macy {
28433d585327SKip Macy 
2844a69042a5SRobert Watson 	INP_RUNLOCK(inp);
28453d585327SKip Macy }
28463d585327SKip Macy 
2847c75e2666SGleb Smirnoff #ifdef INVARIANT_SUPPORT
28483d585327SKip Macy void
2849e79dd20dSKip Macy inp_lock_assert(struct inpcb *inp)
28503d585327SKip Macy {
28513d585327SKip Macy 
28528501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
28533d585327SKip Macy }
28543d585327SKip Macy 
28553d585327SKip Macy void
2856e79dd20dSKip Macy inp_unlock_assert(struct inpcb *inp)
28573d585327SKip Macy {
28583d585327SKip Macy 
28593d585327SKip Macy 	INP_UNLOCK_ASSERT(inp);
28603d585327SKip Macy }
28613d585327SKip Macy #endif
28623d585327SKip Macy 
28639378e437SKip Macy void
28649378e437SKip Macy inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
28659378e437SKip Macy {
28669378e437SKip Macy 	struct inpcb *inp;
28679378e437SKip Macy 
2868ff9b006dSJulien Charbon 	INP_INFO_WLOCK(&V_tcbinfo);
2869b872626dSMatt Macy 	CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
28709378e437SKip Macy 		INP_WLOCK(inp);
28719378e437SKip Macy 		func(inp, arg);
28729378e437SKip Macy 		INP_WUNLOCK(inp);
28739378e437SKip Macy 	}
2874ff9b006dSJulien Charbon 	INP_INFO_WUNLOCK(&V_tcbinfo);
28759378e437SKip Macy }
28769378e437SKip Macy 
28779378e437SKip Macy struct socket *
28789378e437SKip Macy inp_inpcbtosocket(struct inpcb *inp)
28799378e437SKip Macy {
28809378e437SKip Macy 
28819378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
28829378e437SKip Macy 	return (inp->inp_socket);
28839378e437SKip Macy }
28849378e437SKip Macy 
28859378e437SKip Macy struct tcpcb *
28869378e437SKip Macy inp_inpcbtotcpcb(struct inpcb *inp)
28879378e437SKip Macy {
28889378e437SKip Macy 
28899378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
28909378e437SKip Macy 	return ((struct tcpcb *)inp->inp_ppcb);
28919378e437SKip Macy }
28929378e437SKip Macy 
28939378e437SKip Macy int
28949378e437SKip Macy inp_ip_tos_get(const struct inpcb *inp)
28959378e437SKip Macy {
28969378e437SKip Macy 
28979378e437SKip Macy 	return (inp->inp_ip_tos);
28989378e437SKip Macy }
28999378e437SKip Macy 
29009378e437SKip Macy void
29019378e437SKip Macy inp_ip_tos_set(struct inpcb *inp, int val)
29029378e437SKip Macy {
29039378e437SKip Macy 
29049378e437SKip Macy 	inp->inp_ip_tos = val;
29059378e437SKip Macy }
29069378e437SKip Macy 
29079378e437SKip Macy void
2908df9cf830STai-hwa Liang inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
29099d29c635SKip Macy     uint32_t *faddr, uint16_t *fp)
29109378e437SKip Macy {
29119378e437SKip Macy 
29129d29c635SKip Macy 	INP_LOCK_ASSERT(inp);
2913df9cf830STai-hwa Liang 	*laddr = inp->inp_laddr.s_addr;
2914df9cf830STai-hwa Liang 	*faddr = inp->inp_faddr.s_addr;
29159378e437SKip Macy 	*lp = inp->inp_lport;
29169378e437SKip Macy 	*fp = inp->inp_fport;
29179378e437SKip Macy }
29189378e437SKip Macy 
2919dd0e6c38SKip Macy struct inpcb *
2920dd0e6c38SKip Macy so_sotoinpcb(struct socket *so)
2921dd0e6c38SKip Macy {
2922dd0e6c38SKip Macy 
2923dd0e6c38SKip Macy 	return (sotoinpcb(so));
2924dd0e6c38SKip Macy }
2925dd0e6c38SKip Macy 
2926dd0e6c38SKip Macy struct tcpcb *
2927dd0e6c38SKip Macy so_sototcpcb(struct socket *so)
2928dd0e6c38SKip Macy {
2929dd0e6c38SKip Macy 
2930dd0e6c38SKip Macy 	return (sototcpcb(so));
2931dd0e6c38SKip Macy }
2932dd0e6c38SKip Macy 
2933cc65eb4eSGleb Smirnoff /*
2934cc65eb4eSGleb Smirnoff  * Create an external-format (``xinpcb'') structure using the information in
2935cc65eb4eSGleb Smirnoff  * the kernel-format in_pcb structure pointed to by inp.  This is done to
2936cc65eb4eSGleb Smirnoff  * reduce the spew of irrelevant information over this interface, to isolate
2937cc65eb4eSGleb Smirnoff  * user code from changes in the kernel structure, and potentially to provide
2938cc65eb4eSGleb Smirnoff  * information-hiding if we decide that some of this information should be
2939cc65eb4eSGleb Smirnoff  * hidden from users.
2940cc65eb4eSGleb Smirnoff  */
2941cc65eb4eSGleb Smirnoff void
2942cc65eb4eSGleb Smirnoff in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2943cc65eb4eSGleb Smirnoff {
2944cc65eb4eSGleb Smirnoff 
294579db6fe7SMark Johnston 	bzero(xi, sizeof(*xi));
2946cc65eb4eSGleb Smirnoff 	xi->xi_len = sizeof(struct xinpcb);
2947cc65eb4eSGleb Smirnoff 	if (inp->inp_socket)
2948cc65eb4eSGleb Smirnoff 		sotoxsocket(inp->inp_socket, &xi->xi_socket);
2949cc65eb4eSGleb Smirnoff 	bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2950cc65eb4eSGleb Smirnoff 	xi->inp_gencnt = inp->inp_gencnt;
29513a20f06aSBrooks Davis 	xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2952cc65eb4eSGleb Smirnoff 	xi->inp_flow = inp->inp_flow;
2953cc65eb4eSGleb Smirnoff 	xi->inp_flowid = inp->inp_flowid;
2954cc65eb4eSGleb Smirnoff 	xi->inp_flowtype = inp->inp_flowtype;
2955cc65eb4eSGleb Smirnoff 	xi->inp_flags = inp->inp_flags;
2956cc65eb4eSGleb Smirnoff 	xi->inp_flags2 = inp->inp_flags2;
2957cc65eb4eSGleb Smirnoff 	xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2958cc65eb4eSGleb Smirnoff 	xi->in6p_cksum = inp->in6p_cksum;
2959cc65eb4eSGleb Smirnoff 	xi->in6p_hops = inp->in6p_hops;
2960cc65eb4eSGleb Smirnoff 	xi->inp_ip_tos = inp->inp_ip_tos;
2961cc65eb4eSGleb Smirnoff 	xi->inp_vflag = inp->inp_vflag;
2962cc65eb4eSGleb Smirnoff 	xi->inp_ip_ttl = inp->inp_ip_ttl;
2963cc65eb4eSGleb Smirnoff 	xi->inp_ip_p = inp->inp_ip_p;
2964cc65eb4eSGleb Smirnoff 	xi->inp_ip_minttl = inp->inp_ip_minttl;
2965cc65eb4eSGleb Smirnoff }
2966cc65eb4eSGleb Smirnoff 
2967497057eeSRobert Watson #ifdef DDB
2968497057eeSRobert Watson static void
2969497057eeSRobert Watson db_print_indent(int indent)
2970497057eeSRobert Watson {
2971497057eeSRobert Watson 	int i;
2972497057eeSRobert Watson 
2973497057eeSRobert Watson 	for (i = 0; i < indent; i++)
2974497057eeSRobert Watson 		db_printf(" ");
2975497057eeSRobert Watson }
2976497057eeSRobert Watson 
2977497057eeSRobert Watson static void
2978497057eeSRobert Watson db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2979497057eeSRobert Watson {
2980497057eeSRobert Watson 	char faddr_str[48], laddr_str[48];
2981497057eeSRobert Watson 
2982497057eeSRobert Watson 	db_print_indent(indent);
2983497057eeSRobert Watson 	db_printf("%s at %p\n", name, inc);
2984497057eeSRobert Watson 
2985497057eeSRobert Watson 	indent += 2;
2986497057eeSRobert Watson 
298703dc38a4SRobert Watson #ifdef INET6
2988dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
2989497057eeSRobert Watson 		/* IPv6. */
2990497057eeSRobert Watson 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
2991497057eeSRobert Watson 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
299283e521ecSBjoern A. Zeeb 	} else
299303dc38a4SRobert Watson #endif
299483e521ecSBjoern A. Zeeb 	{
2995497057eeSRobert Watson 		/* IPv4. */
2996497057eeSRobert Watson 		inet_ntoa_r(inc->inc_laddr, laddr_str);
2997497057eeSRobert Watson 		inet_ntoa_r(inc->inc_faddr, faddr_str);
2998497057eeSRobert Watson 	}
2999497057eeSRobert Watson 	db_print_indent(indent);
3000497057eeSRobert Watson 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
3001497057eeSRobert Watson 	    ntohs(inc->inc_lport));
3002497057eeSRobert Watson 	db_print_indent(indent);
3003497057eeSRobert Watson 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
3004497057eeSRobert Watson 	    ntohs(inc->inc_fport));
3005497057eeSRobert Watson }
3006497057eeSRobert Watson 
3007497057eeSRobert Watson static void
3008497057eeSRobert Watson db_print_inpflags(int inp_flags)
3009497057eeSRobert Watson {
3010497057eeSRobert Watson 	int comma;
3011497057eeSRobert Watson 
3012497057eeSRobert Watson 	comma = 0;
3013497057eeSRobert Watson 	if (inp_flags & INP_RECVOPTS) {
3014497057eeSRobert Watson 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3015497057eeSRobert Watson 		comma = 1;
3016497057eeSRobert Watson 	}
3017497057eeSRobert Watson 	if (inp_flags & INP_RECVRETOPTS) {
3018497057eeSRobert Watson 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3019497057eeSRobert Watson 		comma = 1;
3020497057eeSRobert Watson 	}
3021497057eeSRobert Watson 	if (inp_flags & INP_RECVDSTADDR) {
3022497057eeSRobert Watson 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3023497057eeSRobert Watson 		comma = 1;
3024497057eeSRobert Watson 	}
3025dce33a45SErmal Luçi 	if (inp_flags & INP_ORIGDSTADDR) {
3026dce33a45SErmal Luçi 		db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3027dce33a45SErmal Luçi 		comma = 1;
3028dce33a45SErmal Luçi 	}
3029497057eeSRobert Watson 	if (inp_flags & INP_HDRINCL) {
3030497057eeSRobert Watson 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
3031497057eeSRobert Watson 		comma = 1;
3032497057eeSRobert Watson 	}
3033497057eeSRobert Watson 	if (inp_flags & INP_HIGHPORT) {
3034497057eeSRobert Watson 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3035497057eeSRobert Watson 		comma = 1;
3036497057eeSRobert Watson 	}
3037497057eeSRobert Watson 	if (inp_flags & INP_LOWPORT) {
3038497057eeSRobert Watson 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
3039497057eeSRobert Watson 		comma = 1;
3040497057eeSRobert Watson 	}
3041497057eeSRobert Watson 	if (inp_flags & INP_ANONPORT) {
3042497057eeSRobert Watson 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
3043497057eeSRobert Watson 		comma = 1;
3044497057eeSRobert Watson 	}
3045497057eeSRobert Watson 	if (inp_flags & INP_RECVIF) {
3046497057eeSRobert Watson 		db_printf("%sINP_RECVIF", comma ? ", " : "");
3047497057eeSRobert Watson 		comma = 1;
3048497057eeSRobert Watson 	}
3049497057eeSRobert Watson 	if (inp_flags & INP_MTUDISC) {
3050497057eeSRobert Watson 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
3051497057eeSRobert Watson 		comma = 1;
3052497057eeSRobert Watson 	}
3053497057eeSRobert Watson 	if (inp_flags & INP_RECVTTL) {
3054497057eeSRobert Watson 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
3055497057eeSRobert Watson 		comma = 1;
3056497057eeSRobert Watson 	}
3057497057eeSRobert Watson 	if (inp_flags & INP_DONTFRAG) {
3058497057eeSRobert Watson 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3059497057eeSRobert Watson 		comma = 1;
3060497057eeSRobert Watson 	}
30613cca425bSMichael Tuexen 	if (inp_flags & INP_RECVTOS) {
30623cca425bSMichael Tuexen 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
30633cca425bSMichael Tuexen 		comma = 1;
30643cca425bSMichael Tuexen 	}
3065497057eeSRobert Watson 	if (inp_flags & IN6P_IPV6_V6ONLY) {
3066497057eeSRobert Watson 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3067497057eeSRobert Watson 		comma = 1;
3068497057eeSRobert Watson 	}
3069497057eeSRobert Watson 	if (inp_flags & IN6P_PKTINFO) {
3070497057eeSRobert Watson 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3071497057eeSRobert Watson 		comma = 1;
3072497057eeSRobert Watson 	}
3073497057eeSRobert Watson 	if (inp_flags & IN6P_HOPLIMIT) {
3074497057eeSRobert Watson 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3075497057eeSRobert Watson 		comma = 1;
3076497057eeSRobert Watson 	}
3077497057eeSRobert Watson 	if (inp_flags & IN6P_HOPOPTS) {
3078497057eeSRobert Watson 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3079497057eeSRobert Watson 		comma = 1;
3080497057eeSRobert Watson 	}
3081497057eeSRobert Watson 	if (inp_flags & IN6P_DSTOPTS) {
3082497057eeSRobert Watson 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3083497057eeSRobert Watson 		comma = 1;
3084497057eeSRobert Watson 	}
3085497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDR) {
3086497057eeSRobert Watson 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3087497057eeSRobert Watson 		comma = 1;
3088497057eeSRobert Watson 	}
3089497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
3090497057eeSRobert Watson 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3091497057eeSRobert Watson 		comma = 1;
3092497057eeSRobert Watson 	}
3093497057eeSRobert Watson 	if (inp_flags & IN6P_TCLASS) {
3094497057eeSRobert Watson 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3095497057eeSRobert Watson 		comma = 1;
3096497057eeSRobert Watson 	}
3097497057eeSRobert Watson 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
3098497057eeSRobert Watson 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3099497057eeSRobert Watson 		comma = 1;
3100497057eeSRobert Watson 	}
3101ad71fe3cSRobert Watson 	if (inp_flags & INP_TIMEWAIT) {
3102ad71fe3cSRobert Watson 		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3103ad71fe3cSRobert Watson 		comma  = 1;
3104ad71fe3cSRobert Watson 	}
3105ad71fe3cSRobert Watson 	if (inp_flags & INP_ONESBCAST) {
3106ad71fe3cSRobert Watson 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3107ad71fe3cSRobert Watson 		comma  = 1;
3108ad71fe3cSRobert Watson 	}
3109ad71fe3cSRobert Watson 	if (inp_flags & INP_DROPPED) {
3110ad71fe3cSRobert Watson 		db_printf("%sINP_DROPPED", comma ? ", " : "");
3111ad71fe3cSRobert Watson 		comma  = 1;
3112ad71fe3cSRobert Watson 	}
3113ad71fe3cSRobert Watson 	if (inp_flags & INP_SOCKREF) {
3114ad71fe3cSRobert Watson 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
3115ad71fe3cSRobert Watson 		comma  = 1;
3116ad71fe3cSRobert Watson 	}
3117497057eeSRobert Watson 	if (inp_flags & IN6P_RFC2292) {
3118497057eeSRobert Watson 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3119497057eeSRobert Watson 		comma = 1;
3120497057eeSRobert Watson 	}
3121497057eeSRobert Watson 	if (inp_flags & IN6P_MTU) {
3122497057eeSRobert Watson 		db_printf("IN6P_MTU%s", comma ? ", " : "");
3123497057eeSRobert Watson 		comma = 1;
3124497057eeSRobert Watson 	}
3125497057eeSRobert Watson }
3126497057eeSRobert Watson 
3127497057eeSRobert Watson static void
3128497057eeSRobert Watson db_print_inpvflag(u_char inp_vflag)
3129497057eeSRobert Watson {
3130497057eeSRobert Watson 	int comma;
3131497057eeSRobert Watson 
3132497057eeSRobert Watson 	comma = 0;
3133497057eeSRobert Watson 	if (inp_vflag & INP_IPV4) {
3134497057eeSRobert Watson 		db_printf("%sINP_IPV4", comma ? ", " : "");
3135497057eeSRobert Watson 		comma  = 1;
3136497057eeSRobert Watson 	}
3137497057eeSRobert Watson 	if (inp_vflag & INP_IPV6) {
3138497057eeSRobert Watson 		db_printf("%sINP_IPV6", comma ? ", " : "");
3139497057eeSRobert Watson 		comma  = 1;
3140497057eeSRobert Watson 	}
3141497057eeSRobert Watson 	if (inp_vflag & INP_IPV6PROTO) {
3142497057eeSRobert Watson 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3143497057eeSRobert Watson 		comma  = 1;
3144497057eeSRobert Watson 	}
3145497057eeSRobert Watson }
3146497057eeSRobert Watson 
31476d888973SRobert Watson static void
3148497057eeSRobert Watson db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3149497057eeSRobert Watson {
3150497057eeSRobert Watson 
3151497057eeSRobert Watson 	db_print_indent(indent);
3152497057eeSRobert Watson 	db_printf("%s at %p\n", name, inp);
3153497057eeSRobert Watson 
3154497057eeSRobert Watson 	indent += 2;
3155497057eeSRobert Watson 
3156497057eeSRobert Watson 	db_print_indent(indent);
3157497057eeSRobert Watson 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3158497057eeSRobert Watson 
3159497057eeSRobert Watson 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3160497057eeSRobert Watson 
3161497057eeSRobert Watson 	db_print_indent(indent);
3162497057eeSRobert Watson 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
3163497057eeSRobert Watson 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3164497057eeSRobert Watson 
3165497057eeSRobert Watson 	db_print_indent(indent);
3166497057eeSRobert Watson 	db_printf("inp_label: %p   inp_flags: 0x%x (",
3167497057eeSRobert Watson 	   inp->inp_label, inp->inp_flags);
3168497057eeSRobert Watson 	db_print_inpflags(inp->inp_flags);
3169497057eeSRobert Watson 	db_printf(")\n");
3170497057eeSRobert Watson 
3171497057eeSRobert Watson 	db_print_indent(indent);
3172497057eeSRobert Watson 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3173497057eeSRobert Watson 	    inp->inp_vflag);
3174497057eeSRobert Watson 	db_print_inpvflag(inp->inp_vflag);
3175497057eeSRobert Watson 	db_printf(")\n");
3176497057eeSRobert Watson 
3177497057eeSRobert Watson 	db_print_indent(indent);
3178497057eeSRobert Watson 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3179497057eeSRobert Watson 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3180497057eeSRobert Watson 
3181497057eeSRobert Watson 	db_print_indent(indent);
3182497057eeSRobert Watson #ifdef INET6
3183497057eeSRobert Watson 	if (inp->inp_vflag & INP_IPV6) {
3184497057eeSRobert Watson 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
3185497057eeSRobert Watson 		    "in6p_moptions: %p\n", inp->in6p_options,
3186497057eeSRobert Watson 		    inp->in6p_outputopts, inp->in6p_moptions);
3187497057eeSRobert Watson 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3188497057eeSRobert Watson 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3189497057eeSRobert Watson 		    inp->in6p_hops);
3190497057eeSRobert Watson 	} else
3191497057eeSRobert Watson #endif
3192497057eeSRobert Watson 	{
3193497057eeSRobert Watson 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3194497057eeSRobert Watson 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3195497057eeSRobert Watson 		    inp->inp_options, inp->inp_moptions);
3196497057eeSRobert Watson 	}
3197497057eeSRobert Watson 
3198497057eeSRobert Watson 	db_print_indent(indent);
3199497057eeSRobert Watson 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
3200497057eeSRobert Watson 	    (uintmax_t)inp->inp_gencnt);
3201497057eeSRobert Watson }
3202497057eeSRobert Watson 
3203497057eeSRobert Watson DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3204497057eeSRobert Watson {
3205497057eeSRobert Watson 	struct inpcb *inp;
3206497057eeSRobert Watson 
3207497057eeSRobert Watson 	if (!have_addr) {
3208497057eeSRobert Watson 		db_printf("usage: show inpcb <addr>\n");
3209497057eeSRobert Watson 		return;
3210497057eeSRobert Watson 	}
3211497057eeSRobert Watson 	inp = (struct inpcb *)addr;
3212497057eeSRobert Watson 
3213497057eeSRobert Watson 	db_print_inpcb(inp, "inpcb", 0);
3214497057eeSRobert Watson }
321583e521ecSBjoern A. Zeeb #endif /* DDB */
3216f3e7afe2SHans Petter Selasky 
3217f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
3218f3e7afe2SHans Petter Selasky /*
3219f3e7afe2SHans Petter Selasky  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3220f3e7afe2SHans Petter Selasky  * if any.
3221f3e7afe2SHans Petter Selasky  */
3222f3e7afe2SHans Petter Selasky int
3223f3e7afe2SHans Petter Selasky in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3224f3e7afe2SHans Petter Selasky {
3225f3e7afe2SHans Petter Selasky 	union if_snd_tag_modify_params params = {
3226f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
322720abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3228f3e7afe2SHans Petter Selasky 	};
3229f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3230f3e7afe2SHans Petter Selasky 	struct ifnet *ifp;
3231f3e7afe2SHans Petter Selasky 	int error;
3232f3e7afe2SHans Petter Selasky 
3233f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3234f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3235f3e7afe2SHans Petter Selasky 		return (EINVAL);
3236f3e7afe2SHans Petter Selasky 
3237f3e7afe2SHans Petter Selasky 	ifp = mst->ifp;
3238f3e7afe2SHans Petter Selasky 	if (ifp == NULL)
3239f3e7afe2SHans Petter Selasky 		return (EINVAL);
3240f3e7afe2SHans Petter Selasky 
3241f3e7afe2SHans Petter Selasky 	if (ifp->if_snd_tag_modify == NULL) {
3242f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3243f3e7afe2SHans Petter Selasky 	} else {
3244f3e7afe2SHans Petter Selasky 		error = ifp->if_snd_tag_modify(mst, &params);
3245f3e7afe2SHans Petter Selasky 	}
3246f3e7afe2SHans Petter Selasky 	return (error);
3247f3e7afe2SHans Petter Selasky }
3248f3e7afe2SHans Petter Selasky 
3249f3e7afe2SHans Petter Selasky /*
3250f3e7afe2SHans Petter Selasky  * Query existing TX rate limit based on the existing
3251f3e7afe2SHans Petter Selasky  * "inp->inp_snd_tag", if any.
3252f3e7afe2SHans Petter Selasky  */
3253f3e7afe2SHans Petter Selasky int
3254f3e7afe2SHans Petter Selasky in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3255f3e7afe2SHans Petter Selasky {
3256f3e7afe2SHans Petter Selasky 	union if_snd_tag_query_params params = { };
3257f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3258f3e7afe2SHans Petter Selasky 	struct ifnet *ifp;
3259f3e7afe2SHans Petter Selasky 	int error;
3260f3e7afe2SHans Petter Selasky 
3261f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3262f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3263f3e7afe2SHans Petter Selasky 		return (EINVAL);
3264f3e7afe2SHans Petter Selasky 
3265f3e7afe2SHans Petter Selasky 	ifp = mst->ifp;
3266f3e7afe2SHans Petter Selasky 	if (ifp == NULL)
3267f3e7afe2SHans Petter Selasky 		return (EINVAL);
3268f3e7afe2SHans Petter Selasky 
3269f3e7afe2SHans Petter Selasky 	if (ifp->if_snd_tag_query == NULL) {
3270f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3271f3e7afe2SHans Petter Selasky 	} else {
3272f3e7afe2SHans Petter Selasky 		error = ifp->if_snd_tag_query(mst, &params);
3273f3e7afe2SHans Petter Selasky 		if (error == 0 &&  p_max_pacing_rate != NULL)
3274f3e7afe2SHans Petter Selasky 			*p_max_pacing_rate = params.rate_limit.max_rate;
3275f3e7afe2SHans Petter Selasky 	}
3276f3e7afe2SHans Petter Selasky 	return (error);
3277f3e7afe2SHans Petter Selasky }
3278f3e7afe2SHans Petter Selasky 
3279f3e7afe2SHans Petter Selasky /*
328095ed5015SHans Petter Selasky  * Query existing TX queue level based on the existing
328195ed5015SHans Petter Selasky  * "inp->inp_snd_tag", if any.
328295ed5015SHans Petter Selasky  */
328395ed5015SHans Petter Selasky int
328495ed5015SHans Petter Selasky in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
328595ed5015SHans Petter Selasky {
328695ed5015SHans Petter Selasky 	union if_snd_tag_query_params params = { };
328795ed5015SHans Petter Selasky 	struct m_snd_tag *mst;
328895ed5015SHans Petter Selasky 	struct ifnet *ifp;
328995ed5015SHans Petter Selasky 	int error;
329095ed5015SHans Petter Selasky 
329195ed5015SHans Petter Selasky 	mst = inp->inp_snd_tag;
329295ed5015SHans Petter Selasky 	if (mst == NULL)
329395ed5015SHans Petter Selasky 		return (EINVAL);
329495ed5015SHans Petter Selasky 
329595ed5015SHans Petter Selasky 	ifp = mst->ifp;
329695ed5015SHans Petter Selasky 	if (ifp == NULL)
329795ed5015SHans Petter Selasky 		return (EINVAL);
329895ed5015SHans Petter Selasky 
329995ed5015SHans Petter Selasky 	if (ifp->if_snd_tag_query == NULL)
330095ed5015SHans Petter Selasky 		return (EOPNOTSUPP);
330195ed5015SHans Petter Selasky 
330295ed5015SHans Petter Selasky 	error = ifp->if_snd_tag_query(mst, &params);
330395ed5015SHans Petter Selasky 	if (error == 0 &&  p_txqueue_level != NULL)
330495ed5015SHans Petter Selasky 		*p_txqueue_level = params.rate_limit.queue_level;
330595ed5015SHans Petter Selasky 	return (error);
330695ed5015SHans Petter Selasky }
330795ed5015SHans Petter Selasky 
330895ed5015SHans Petter Selasky /*
3309f3e7afe2SHans Petter Selasky  * Allocate a new TX rate limit send tag from the network interface
3310f3e7afe2SHans Petter Selasky  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3311f3e7afe2SHans Petter Selasky  */
3312f3e7afe2SHans Petter Selasky int
3313f3e7afe2SHans Petter Selasky in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
331420abea66SRandall Stewart     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
331520abea66SRandall Stewart 
3316f3e7afe2SHans Petter Selasky {
3317f3e7afe2SHans Petter Selasky 	union if_snd_tag_alloc_params params = {
331895ed5015SHans Petter Selasky 		.rate_limit.hdr.type = (max_pacing_rate == -1U) ?
331995ed5015SHans Petter Selasky 		    IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3320f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowid = flowid,
3321f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowtype = flowtype,
332298085baeSAndrew Gallatin 		.rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3323f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
332420abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3325f3e7afe2SHans Petter Selasky 	};
3326f3e7afe2SHans Petter Selasky 	int error;
3327f3e7afe2SHans Petter Selasky 
3328f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3329f3e7afe2SHans Petter Selasky 
333020abea66SRandall Stewart 	if (*st != NULL)
3331f3e7afe2SHans Petter Selasky 		return (EINVAL);
3332f3e7afe2SHans Petter Selasky 
3333f3e7afe2SHans Petter Selasky 	if (ifp->if_snd_tag_alloc == NULL) {
3334f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3335f3e7afe2SHans Petter Selasky 	} else {
3336aebfdc1fSJohn Baldwin 		error = ifp->if_snd_tag_alloc(ifp, &params, st);
333720abea66SRandall Stewart 
3338903c4ee6SXin LI #ifdef INET
333920abea66SRandall Stewart 		if (error == 0) {
334020abea66SRandall Stewart 			counter_u64_add(rate_limit_set_ok, 1);
334120abea66SRandall Stewart 			counter_u64_add(rate_limit_active, 1);
334220abea66SRandall Stewart 		} else
334320abea66SRandall Stewart 			counter_u64_add(rate_limit_alloc_fail, 1);
3344903c4ee6SXin LI #endif
3345f3e7afe2SHans Petter Selasky 	}
3346f3e7afe2SHans Petter Selasky 	return (error);
3347f3e7afe2SHans Petter Selasky }
3348f3e7afe2SHans Petter Selasky 
334920abea66SRandall Stewart void
3350*98d7a8d9SJohn Baldwin in_pcbdetach_tag(struct m_snd_tag *mst)
335120abea66SRandall Stewart {
335220abea66SRandall Stewart 
3353*98d7a8d9SJohn Baldwin 	m_snd_tag_rele(mst);
3354903c4ee6SXin LI #ifdef INET
335520abea66SRandall Stewart 	counter_u64_add(rate_limit_active, -1);
3356903c4ee6SXin LI #endif
335720abea66SRandall Stewart }
335820abea66SRandall Stewart 
3359f3e7afe2SHans Petter Selasky /*
3360f3e7afe2SHans Petter Selasky  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3361f3e7afe2SHans Petter Selasky  * if any:
3362f3e7afe2SHans Petter Selasky  */
3363f3e7afe2SHans Petter Selasky void
3364f3e7afe2SHans Petter Selasky in_pcbdetach_txrtlmt(struct inpcb *inp)
3365f3e7afe2SHans Petter Selasky {
3366f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3367f3e7afe2SHans Petter Selasky 
3368f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3369f3e7afe2SHans Petter Selasky 
3370f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3371f3e7afe2SHans Petter Selasky 	inp->inp_snd_tag = NULL;
3372f3e7afe2SHans Petter Selasky 
3373f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3374f3e7afe2SHans Petter Selasky 		return;
3375f3e7afe2SHans Petter Selasky 
3376fb3bc596SJohn Baldwin 	m_snd_tag_rele(mst);
3377f3e7afe2SHans Petter Selasky }
3378f3e7afe2SHans Petter Selasky 
337920abea66SRandall Stewart int
338020abea66SRandall Stewart in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
338120abea66SRandall Stewart {
338220abea66SRandall Stewart 	int error;
338320abea66SRandall Stewart 
338420abea66SRandall Stewart 	/*
338520abea66SRandall Stewart 	 * If the existing send tag is for the wrong interface due to
338620abea66SRandall Stewart 	 * a route change, first drop the existing tag.  Set the
338720abea66SRandall Stewart 	 * CHANGED flag so that we will keep trying to allocate a new
338820abea66SRandall Stewart 	 * tag if we fail to allocate one this time.
338920abea66SRandall Stewart 	 */
339020abea66SRandall Stewart 	if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
339120abea66SRandall Stewart 		in_pcbdetach_txrtlmt(inp);
339220abea66SRandall Stewart 		inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
339320abea66SRandall Stewart 	}
339420abea66SRandall Stewart 
339520abea66SRandall Stewart 	/*
339620abea66SRandall Stewart 	 * NOTE: When attaching to a network interface a reference is
339720abea66SRandall Stewart 	 * made to ensure the network interface doesn't go away until
339820abea66SRandall Stewart 	 * all ratelimit connections are gone. The network interface
339920abea66SRandall Stewart 	 * pointers compared below represent valid network interfaces,
340020abea66SRandall Stewart 	 * except when comparing towards NULL.
340120abea66SRandall Stewart 	 */
340220abea66SRandall Stewart 	if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
340320abea66SRandall Stewart 		error = 0;
340420abea66SRandall Stewart 	} else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
340520abea66SRandall Stewart 		if (inp->inp_snd_tag != NULL)
340620abea66SRandall Stewart 			in_pcbdetach_txrtlmt(inp);
340720abea66SRandall Stewart 		error = 0;
340820abea66SRandall Stewart 	} else if (inp->inp_snd_tag == NULL) {
340920abea66SRandall Stewart 		/*
341020abea66SRandall Stewart 		 * In order to utilize packet pacing with RSS, we need
341120abea66SRandall Stewart 		 * to wait until there is a valid RSS hash before we
341220abea66SRandall Stewart 		 * can proceed:
341320abea66SRandall Stewart 		 */
341420abea66SRandall Stewart 		if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
341520abea66SRandall Stewart 			error = EAGAIN;
341620abea66SRandall Stewart 		} else {
341720abea66SRandall Stewart 			error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
341820abea66SRandall Stewart 			    mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
341920abea66SRandall Stewart 		}
342020abea66SRandall Stewart 	} else {
342120abea66SRandall Stewart 		error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
342220abea66SRandall Stewart 	}
342320abea66SRandall Stewart 	if (error == 0 || error == EOPNOTSUPP)
342420abea66SRandall Stewart 		inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
342520abea66SRandall Stewart 
342620abea66SRandall Stewart 	return (error);
342720abea66SRandall Stewart }
342820abea66SRandall Stewart 
3429f3e7afe2SHans Petter Selasky /*
3430f3e7afe2SHans Petter Selasky  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3431f3e7afe2SHans Petter Selasky  * is set in the fast path and will attach/detach/modify the TX rate
3432f3e7afe2SHans Petter Selasky  * limit send tag based on the socket's so_max_pacing_rate value.
3433f3e7afe2SHans Petter Selasky  */
3434f3e7afe2SHans Petter Selasky void
3435f3e7afe2SHans Petter Selasky in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3436f3e7afe2SHans Petter Selasky {
3437f3e7afe2SHans Petter Selasky 	struct socket *socket;
3438f3e7afe2SHans Petter Selasky 	uint32_t max_pacing_rate;
3439f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3440f3e7afe2SHans Petter Selasky 	int error;
3441f3e7afe2SHans Petter Selasky 
3442f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3443f3e7afe2SHans Petter Selasky 		return;
3444f3e7afe2SHans Petter Selasky 
3445f3e7afe2SHans Petter Selasky 	socket = inp->inp_socket;
3446f3e7afe2SHans Petter Selasky 	if (socket == NULL)
3447f3e7afe2SHans Petter Selasky 		return;
3448f3e7afe2SHans Petter Selasky 
3449f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3450f3e7afe2SHans Petter Selasky 		/*
3451f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3452f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3453f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3454f3e7afe2SHans Petter Selasky 		 * write lock.
3455f3e7afe2SHans Petter Selasky 		 */
3456f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3457f3e7afe2SHans Petter Selasky 			return;
3458f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3459f3e7afe2SHans Petter Selasky 	} else {
3460f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3461f3e7afe2SHans Petter Selasky 	}
3462f3e7afe2SHans Petter Selasky 
3463f3e7afe2SHans Petter Selasky 	/*
3464f3e7afe2SHans Petter Selasky 	 * NOTE: The so_max_pacing_rate value is read unlocked,
3465f3e7afe2SHans Petter Selasky 	 * because atomic updates are not required since the variable
3466f3e7afe2SHans Petter Selasky 	 * is checked at every mbuf we send. It is assumed that the
3467f3e7afe2SHans Petter Selasky 	 * variable read itself will be atomic.
3468f3e7afe2SHans Petter Selasky 	 */
3469f3e7afe2SHans Petter Selasky 	max_pacing_rate = socket->so_max_pacing_rate;
3470f3e7afe2SHans Petter Selasky 
347120abea66SRandall Stewart 	error = in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3472fb3bc596SJohn Baldwin 
3473f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3474f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3475f3e7afe2SHans Petter Selasky }
3476f3e7afe2SHans Petter Selasky 
3477f3e7afe2SHans Petter Selasky /*
3478f3e7afe2SHans Petter Selasky  * Track route changes for TX rate limiting.
3479f3e7afe2SHans Petter Selasky  */
3480f3e7afe2SHans Petter Selasky void
3481f3e7afe2SHans Petter Selasky in_pcboutput_eagain(struct inpcb *inp)
3482f3e7afe2SHans Petter Selasky {
3483f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3484f3e7afe2SHans Petter Selasky 
3485f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3486f3e7afe2SHans Petter Selasky 		return;
3487f3e7afe2SHans Petter Selasky 
3488f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag == NULL)
3489f3e7afe2SHans Petter Selasky 		return;
3490f3e7afe2SHans Petter Selasky 
3491f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3492f3e7afe2SHans Petter Selasky 		/*
3493f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3494f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3495f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3496f3e7afe2SHans Petter Selasky 		 * write lock.
3497f3e7afe2SHans Petter Selasky 		 */
3498f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3499f3e7afe2SHans Petter Selasky 			return;
3500f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3501f3e7afe2SHans Petter Selasky 	} else {
3502f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3503f3e7afe2SHans Petter Selasky 	}
3504f3e7afe2SHans Petter Selasky 
3505f3e7afe2SHans Petter Selasky 	/* detach rate limiting */
3506f3e7afe2SHans Petter Selasky 	in_pcbdetach_txrtlmt(inp);
3507f3e7afe2SHans Petter Selasky 
3508f3e7afe2SHans Petter Selasky 	/* make sure new mbuf send tag allocation is made */
3509f3e7afe2SHans Petter Selasky 	inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3510f3e7afe2SHans Petter Selasky 
3511f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3512f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3513f3e7afe2SHans Petter Selasky }
351420abea66SRandall Stewart 
3515903c4ee6SXin LI #ifdef INET
351620abea66SRandall Stewart static void
351720abea66SRandall Stewart rl_init(void *st)
351820abea66SRandall Stewart {
351920abea66SRandall Stewart 	rate_limit_active = counter_u64_alloc(M_WAITOK);
352020abea66SRandall Stewart 	rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
352120abea66SRandall Stewart 	rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
352220abea66SRandall Stewart }
352320abea66SRandall Stewart 
352420abea66SRandall Stewart SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3525903c4ee6SXin LI #endif
3526f3e7afe2SHans Petter Selasky #endif /* RATELIMIT */
3527