xref: /freebsd/sys/netinet/in_pcb.c (revision a306ed50ecd57f060a549c14bc53a60b34aaa6bb)
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.
85ebea466SGleb Smirnoff  * Copyright (c) 2021-2022 Gleb Smirnoff <glebius@FreeBSD.org>
9497057eeSRobert Watson  * All rights reserved.
10df8bae1dSRodney W. Grimes  *
1179bdc6e5SRobert Watson  * Portions of this software were developed by Robert N. M. Watson under
1279bdc6e5SRobert Watson  * contract to Juniper Networks, Inc.
1379bdc6e5SRobert Watson  *
14df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
15df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
16df8bae1dSRodney W. Grimes  * are met:
17df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
18df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
19df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
20df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
21df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
22fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
23df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
24df8bae1dSRodney W. Grimes  *    without specific prior written permission.
25df8bae1dSRodney W. Grimes  *
26df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
37df8bae1dSRodney W. Grimes  *
382469dd60SGarrett Wollman  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
39df8bae1dSRodney W. Grimes  */
40df8bae1dSRodney W. Grimes 
414b421e2dSMike Silbersack #include <sys/cdefs.h>
424b421e2dSMike Silbersack __FBSDID("$FreeBSD$");
434b421e2dSMike Silbersack 
44497057eeSRobert Watson #include "opt_ddb.h"
456a800098SYoshinobu Inoue #include "opt_ipsec.h"
46efc76f72SBjoern A. Zeeb #include "opt_inet.h"
47cfa1ca9dSYoshinobu Inoue #include "opt_inet6.h"
48f3e7afe2SHans Petter Selasky #include "opt_ratelimit.h"
490c325f53SAlexander V. Chernikov #include "opt_route.h"
507527624eSRobert Watson #include "opt_rss.h"
51cfa1ca9dSYoshinobu Inoue 
52df8bae1dSRodney W. Grimes #include <sys/param.h>
53a0577692SGleb Smirnoff #include <sys/hash.h>
54df8bae1dSRodney W. Grimes #include <sys/systm.h>
55a0577692SGleb Smirnoff #include <sys/libkern.h>
56cc0a3c8cSAndrey V. Elsukov #include <sys/lock.h>
57df8bae1dSRodney W. Grimes #include <sys/malloc.h>
58df8bae1dSRodney W. Grimes #include <sys/mbuf.h>
59ea8d1492SAlexander V. Chernikov #include <sys/eventhandler.h>
60cfa1ca9dSYoshinobu Inoue #include <sys/domain.h>
61fdb987beSMark Johnston #include <sys/proc.h>
62df8bae1dSRodney W. Grimes #include <sys/protosw.h>
633ee9c3c4SRandall Stewart #include <sys/smp.h>
64fdb987beSMark Johnston #include <sys/smr.h>
65df8bae1dSRodney W. Grimes #include <sys/socket.h>
66df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
67f3e7afe2SHans Petter Selasky #include <sys/sockio.h>
68acd3428bSRobert Watson #include <sys/priv.h>
69df8bae1dSRodney W. Grimes #include <sys/proc.h>
7079bdc6e5SRobert Watson #include <sys/refcount.h>
7175c13541SPoul-Henning Kamp #include <sys/jail.h>
72101f9fc8SPeter Wemm #include <sys/kernel.h>
73101f9fc8SPeter Wemm #include <sys/sysctl.h>
748781d8e9SBruce Evans 
75497057eeSRobert Watson #ifdef DDB
76497057eeSRobert Watson #include <ddb/ddb.h>
77497057eeSRobert Watson #endif
78497057eeSRobert Watson 
7969c2d429SJeff Roberson #include <vm/uma.h>
80a034518aSAndrew Gallatin #include <vm/vm.h>
81df8bae1dSRodney W. Grimes 
82df8bae1dSRodney W. Grimes #include <net/if.h>
8376039bc8SGleb Smirnoff #include <net/if_var.h>
843d0d5b21SJustin Hibbits #include <net/if_private.h>
85cfa1ca9dSYoshinobu Inoue #include <net/if_types.h>
866d768226SGeorge V. Neville-Neil #include <net/if_llatbl.h>
87df8bae1dSRodney W. Grimes #include <net/route.h>
88b2bdc62aSAdrian Chadd #include <net/rss_config.h>
89530c0060SRobert Watson #include <net/vnet.h>
90df8bae1dSRodney W. Grimes 
9167107f45SBjoern A. Zeeb #if defined(INET) || defined(INET6)
92df8bae1dSRodney W. Grimes #include <netinet/in.h>
93df8bae1dSRodney W. Grimes #include <netinet/in_pcb.h>
940f617ae4SGleb Smirnoff #include <netinet/in_pcb_var.h>
9573bebcc5SGleb Smirnoff #include <netinet/tcp.h>
9659854ecfSHans Petter Selasky #ifdef INET
9759854ecfSHans Petter Selasky #include <netinet/in_var.h>
989ac7c6cfSAlexander V. Chernikov #include <netinet/in_fib.h>
9959854ecfSHans Petter Selasky #endif
100df8bae1dSRodney W. Grimes #include <netinet/ip_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
116db0ac6deSCy Schubert #define	INP_FREED	0x00000200	/* See in_pcb.h. */
1171a43cff9SSean Bruno 
118101f9fc8SPeter Wemm /*
119101f9fc8SPeter Wemm  * These configure the range of local port addresses assigned to
120101f9fc8SPeter Wemm  * "unspecified" outgoing connections/packets/whatever.
121101f9fc8SPeter Wemm  */
122eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
123eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
124eddfbb76SRobert Watson VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
125eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
126eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
127eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
128101f9fc8SPeter Wemm 
129b0d22693SCrist J. Clark /*
130b0d22693SCrist J. Clark  * Reserved ports accessible only to root. There are significant
131b0d22693SCrist J. Clark  * security considerations that must be accounted for when changing these,
132b0d22693SCrist J. Clark  * but the security benefits can be great. Please be careful.
133b0d22693SCrist J. Clark  */
134eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
135eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedlow);
136b0d22693SCrist J. Clark 
13719acc506SGleb Smirnoff /* Enable random ephemeral port allocation by default. */
13819acc506SGleb Smirnoff VNET_DEFINE(int, ipport_randomized) = 1;
1396ac48b74SMike Silbersack 
140d2025bd0SBjoern A. Zeeb #ifdef INET
141fa046d87SRobert Watson static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
142fa046d87SRobert Watson 			    struct in_addr faddr, u_int fport_arg,
143fa046d87SRobert Watson 			    struct in_addr laddr, u_int lport_arg,
1444130ea61SMark Johnston 			    int lookupflags, uint8_t numa_domain);
14567107f45SBjoern A. Zeeb 
146bbd42ad0SPeter Wemm #define RANGECHK(var, min, max) \
147bbd42ad0SPeter Wemm 	if ((var) < (min)) { (var) = (min); } \
148bbd42ad0SPeter Wemm 	else if ((var) > (max)) { (var) = (max); }
149bbd42ad0SPeter Wemm 
150bbd42ad0SPeter Wemm static int
15182d9ae4eSPoul-Henning Kamp sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
152bbd42ad0SPeter Wemm {
15330a4ab08SBruce Evans 	int error;
15430a4ab08SBruce Evans 
155f6dfe47aSMarko Zec 	error = sysctl_handle_int(oidp, arg1, arg2, req);
15630a4ab08SBruce Evans 	if (error == 0) {
157603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
158603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
159603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
160603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
161603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
162603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
163bbd42ad0SPeter Wemm 	}
16430a4ab08SBruce Evans 	return (error);
165bbd42ad0SPeter Wemm }
166bbd42ad0SPeter Wemm 
167bbd42ad0SPeter Wemm #undef RANGECHK
168bbd42ad0SPeter Wemm 
1697029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
1707029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1716472ac3dSEd Schouten     "IP Ports");
17233b3ac06SPeter Wemm 
1736df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
1747029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1757029da5cSPawel Biernacki     &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
1767029da5cSPawel Biernacki     "");
1776df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
1787029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1797029da5cSPawel Biernacki     &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
1807029da5cSPawel Biernacki     "");
1816df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
1827029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1837029da5cSPawel Biernacki     &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
1847029da5cSPawel Biernacki     "");
1856df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
1867029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1877029da5cSPawel Biernacki     &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
1887029da5cSPawel Biernacki     "");
1896df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
1907029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1917029da5cSPawel Biernacki     &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
1927029da5cSPawel Biernacki     "");
1936df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
1947029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1957029da5cSPawel Biernacki     &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
1967029da5cSPawel Biernacki     "");
1976df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
1986df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
1996df8a710SGleb Smirnoff 	&VNET_NAME(ipport_reservedhigh), 0, "");
2006df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
201eddfbb76SRobert Watson 	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
2026df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
2036df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
204eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
20520abea66SRandall Stewart 
20620abea66SRandall Stewart #ifdef RATELIMIT
2071a714ff2SRandall Stewart counter_u64_t rate_limit_new;
2081a714ff2SRandall Stewart counter_u64_t rate_limit_chg;
20920abea66SRandall Stewart counter_u64_t rate_limit_active;
21020abea66SRandall Stewart counter_u64_t rate_limit_alloc_fail;
21120abea66SRandall Stewart counter_u64_t rate_limit_set_ok;
21220abea66SRandall Stewart 
2137029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
21420abea66SRandall Stewart     "IP Rate Limiting");
21520abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
21620abea66SRandall Stewart     &rate_limit_active, "Active rate limited connections");
21720abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
21820abea66SRandall Stewart    &rate_limit_alloc_fail, "Rate limited connection failures");
21920abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
22020abea66SRandall Stewart    &rate_limit_set_ok, "Rate limited setting succeeded");
2211a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
2221a714ff2SRandall Stewart    &rate_limit_new, "Total Rate limit new attempts");
2231a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
2241a714ff2SRandall Stewart    &rate_limit_chg, "Total Rate limited change attempts");
22520abea66SRandall Stewart #endif /* RATELIMIT */
22620abea66SRandall Stewart 
22783e521ecSBjoern A. Zeeb #endif /* INET */
2280312fbe9SPoul-Henning Kamp 
229a0577692SGleb Smirnoff VNET_DEFINE(uint32_t, in_pcbhashseed);
230a0577692SGleb Smirnoff static void
231a0577692SGleb Smirnoff in_pcbhashseed_init(void)
232a0577692SGleb Smirnoff {
233a0577692SGleb Smirnoff 
234a0577692SGleb Smirnoff 	V_in_pcbhashseed = arc4random();
235a0577692SGleb Smirnoff }
236a0577692SGleb Smirnoff VNET_SYSINIT(in_pcbhashseed_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
237a0577692SGleb Smirnoff     in_pcbhashseed_init, 0);
238a0577692SGleb Smirnoff 
2393ba34b07SGleb Smirnoff static void in_pcbremhash(struct inpcb *);
2403ba34b07SGleb Smirnoff 
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 *
250d93ec8cbSMark Johnston in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, struct ucred *cred,
251d93ec8cbSMark Johnston     u_char vflag, uint16_t port, const union in_dependaddr *addr, int size,
252a034518aSAndrew Gallatin     uint8_t numa_domain)
2531a43cff9SSean Bruno {
2541a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2551a43cff9SSean Bruno 	size_t bytes;
2561a43cff9SSean Bruno 
2571a43cff9SSean Bruno 	bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
2581a43cff9SSean Bruno 	grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
259d93ec8cbSMark Johnston 	if (grp == NULL)
2601a43cff9SSean Bruno 		return (NULL);
261d93ec8cbSMark Johnston 	grp->il_cred = crhold(cred);
2621a43cff9SSean Bruno 	grp->il_vflag = vflag;
2631a43cff9SSean Bruno 	grp->il_lport = port;
264a034518aSAndrew Gallatin 	grp->il_numa_domain = numa_domain;
2651a43cff9SSean Bruno 	grp->il_dependladdr = *addr;
2661a43cff9SSean Bruno 	grp->il_inpsiz = size;
26754af3d0dSMark Johnston 	CK_LIST_INSERT_HEAD(hdr, grp, il_list);
2681a43cff9SSean Bruno 	return (grp);
2691a43cff9SSean Bruno }
2701a43cff9SSean Bruno 
2711a43cff9SSean Bruno static void
27254af3d0dSMark Johnston in_pcblbgroup_free_deferred(epoch_context_t ctx)
27354af3d0dSMark Johnston {
27454af3d0dSMark Johnston 	struct inpcblbgroup *grp;
27554af3d0dSMark Johnston 
27654af3d0dSMark Johnston 	grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
277d93ec8cbSMark Johnston 	crfree(grp->il_cred);
27854af3d0dSMark Johnston 	free(grp, M_PCB);
27954af3d0dSMark Johnston }
28054af3d0dSMark Johnston 
28154af3d0dSMark Johnston static void
2821a43cff9SSean Bruno in_pcblbgroup_free(struct inpcblbgroup *grp)
2831a43cff9SSean Bruno {
2841a43cff9SSean Bruno 
28554af3d0dSMark Johnston 	CK_LIST_REMOVE(grp, il_list);
2862a4bd982SGleb Smirnoff 	NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
2871a43cff9SSean Bruno }
2881a43cff9SSean Bruno 
2891a43cff9SSean Bruno static struct inpcblbgroup *
2901a43cff9SSean Bruno in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
2911a43cff9SSean Bruno     struct inpcblbgroup *old_grp, int size)
2921a43cff9SSean Bruno {
2931a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2941a43cff9SSean Bruno 	int i;
2951a43cff9SSean Bruno 
296d93ec8cbSMark Johnston 	grp = in_pcblbgroup_alloc(hdr, old_grp->il_cred, old_grp->il_vflag,
297a034518aSAndrew Gallatin 	    old_grp->il_lport, &old_grp->il_dependladdr, size,
298a034518aSAndrew Gallatin 	    old_grp->il_numa_domain);
29979ee680bSMark Johnston 	if (grp == NULL)
3001a43cff9SSean Bruno 		return (NULL);
3011a43cff9SSean Bruno 
3021a43cff9SSean Bruno 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
3031a43cff9SSean Bruno 	    ("invalid new local group size %d and old local group count %d",
3041a43cff9SSean Bruno 	     grp->il_inpsiz, old_grp->il_inpcnt));
3051a43cff9SSean Bruno 
3061a43cff9SSean Bruno 	for (i = 0; i < old_grp->il_inpcnt; ++i)
3071a43cff9SSean Bruno 		grp->il_inp[i] = old_grp->il_inp[i];
3081a43cff9SSean Bruno 	grp->il_inpcnt = old_grp->il_inpcnt;
3091a43cff9SSean Bruno 	in_pcblbgroup_free(old_grp);
3101a43cff9SSean Bruno 	return (grp);
3111a43cff9SSean Bruno }
3121a43cff9SSean Bruno 
3131a43cff9SSean Bruno /*
3141a43cff9SSean Bruno  * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
3151a43cff9SSean Bruno  * and shrink group if possible.
3161a43cff9SSean Bruno  */
3171a43cff9SSean Bruno static void
3181a43cff9SSean Bruno in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
3191a43cff9SSean Bruno     int i)
3201a43cff9SSean Bruno {
32179ee680bSMark Johnston 	struct inpcblbgroup *grp, *new_grp;
3221a43cff9SSean Bruno 
32379ee680bSMark Johnston 	grp = *grpp;
3241a43cff9SSean Bruno 	for (; i + 1 < grp->il_inpcnt; ++i)
3251a43cff9SSean Bruno 		grp->il_inp[i] = grp->il_inp[i + 1];
3261a43cff9SSean Bruno 	grp->il_inpcnt--;
3271a43cff9SSean Bruno 
3281a43cff9SSean Bruno 	if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
32979ee680bSMark Johnston 	    grp->il_inpcnt <= grp->il_inpsiz / 4) {
3301a43cff9SSean Bruno 		/* Shrink this group. */
33179ee680bSMark Johnston 		new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
33279ee680bSMark Johnston 		if (new_grp != NULL)
3331a43cff9SSean Bruno 			*grpp = new_grp;
3341a43cff9SSean Bruno 	}
3351a43cff9SSean Bruno }
3361a43cff9SSean Bruno 
3371a43cff9SSean Bruno /*
3381a43cff9SSean Bruno  * Add PCB to load balance group for SO_REUSEPORT_LB option.
3391a43cff9SSean Bruno  */
3401a43cff9SSean Bruno static int
341a034518aSAndrew Gallatin in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
3421a43cff9SSean Bruno {
343a7026c7fSMark Johnston 	const static struct timeval interval = { 60, 0 };
344a7026c7fSMark Johnston 	static struct timeval lastprint;
3451a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
3461a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
3471a43cff9SSean Bruno 	struct inpcblbgroup *grp;
34879ee680bSMark Johnston 	uint32_t idx;
3491a43cff9SSean Bruno 
3501a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
3511a43cff9SSean Bruno 
3521a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
3531a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
3541a43cff9SSean Bruno 
3551a43cff9SSean Bruno #ifdef INET6
3561a43cff9SSean Bruno 	/*
3571a43cff9SSean Bruno 	 * Don't allow IPv4 mapped INET6 wild socket.
3581a43cff9SSean Bruno 	 */
3591a43cff9SSean Bruno 	if ((inp->inp_vflag & INP_IPV4) &&
3601a43cff9SSean Bruno 	    inp->inp_laddr.s_addr == INADDR_ANY &&
3611a43cff9SSean Bruno 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
3621a43cff9SSean Bruno 		return (0);
3631a43cff9SSean Bruno 	}
3641a43cff9SSean Bruno #endif
3651a43cff9SSean Bruno 
3669d2877fcSMark Johnston 	idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
36779ee680bSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
36854af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
369d93ec8cbSMark Johnston 		if (grp->il_cred->cr_prison == inp->inp_cred->cr_prison &&
370d93ec8cbSMark Johnston 		    grp->il_vflag == inp->inp_vflag &&
3711a43cff9SSean Bruno 		    grp->il_lport == inp->inp_lport &&
372a034518aSAndrew Gallatin 		    grp->il_numa_domain == numa_domain &&
3731a43cff9SSean Bruno 		    memcmp(&grp->il_dependladdr,
3741a43cff9SSean Bruno 		    &inp->inp_inc.inc_ie.ie_dependladdr,
375d93ec8cbSMark Johnston 		    sizeof(grp->il_dependladdr)) == 0) {
3761a43cff9SSean Bruno 			break;
3771a43cff9SSean Bruno 		}
378d93ec8cbSMark Johnston 	}
3791a43cff9SSean Bruno 	if (grp == NULL) {
3801a43cff9SSean Bruno 		/* Create new load balance group. */
381d93ec8cbSMark Johnston 		grp = in_pcblbgroup_alloc(hdr, inp->inp_cred, inp->inp_vflag,
3821a43cff9SSean Bruno 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
383a034518aSAndrew Gallatin 		    INPCBLBGROUP_SIZMIN, numa_domain);
38479ee680bSMark Johnston 		if (grp == NULL)
3851a43cff9SSean Bruno 			return (ENOBUFS);
3861a43cff9SSean Bruno 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
3871a43cff9SSean Bruno 		if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
388a7026c7fSMark Johnston 			if (ratecheck(&lastprint, &interval))
3891a43cff9SSean Bruno 				printf("lb group port %d, limit reached\n",
3901a43cff9SSean Bruno 				    ntohs(grp->il_lport));
3911a43cff9SSean Bruno 			return (0);
3921a43cff9SSean Bruno 		}
3931a43cff9SSean Bruno 
3941a43cff9SSean Bruno 		/* Expand this local group. */
3951a43cff9SSean Bruno 		grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
39679ee680bSMark Johnston 		if (grp == NULL)
3971a43cff9SSean Bruno 			return (ENOBUFS);
3981a43cff9SSean Bruno 	}
3991a43cff9SSean Bruno 
4001a43cff9SSean Bruno 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
40179ee680bSMark Johnston 	    ("invalid local group size %d and count %d", grp->il_inpsiz,
40279ee680bSMark Johnston 	    grp->il_inpcnt));
4031a43cff9SSean Bruno 
4041a43cff9SSean Bruno 	grp->il_inp[grp->il_inpcnt] = inp;
4051a43cff9SSean Bruno 	grp->il_inpcnt++;
4061a43cff9SSean Bruno 	return (0);
4071a43cff9SSean Bruno }
4081a43cff9SSean Bruno 
4091a43cff9SSean Bruno /*
4101a43cff9SSean Bruno  * Remove PCB from load balance group.
4111a43cff9SSean Bruno  */
4121a43cff9SSean Bruno static void
4131a43cff9SSean Bruno in_pcbremlbgrouphash(struct inpcb *inp)
4141a43cff9SSean Bruno {
4151a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
4161a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
4171a43cff9SSean Bruno 	struct inpcblbgroup *grp;
4181a43cff9SSean Bruno 	int i;
4191a43cff9SSean Bruno 
4201a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
4211a43cff9SSean Bruno 
4221a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
4231a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
4241a43cff9SSean Bruno 
4251a43cff9SSean Bruno 	hdr = &pcbinfo->ipi_lbgrouphashbase[
4269d2877fcSMark Johnston 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
42754af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
4281a43cff9SSean Bruno 		for (i = 0; i < grp->il_inpcnt; ++i) {
4291a43cff9SSean Bruno 			if (grp->il_inp[i] != inp)
4301a43cff9SSean Bruno 				continue;
4311a43cff9SSean Bruno 
4321a43cff9SSean Bruno 			if (grp->il_inpcnt == 1) {
4331a43cff9SSean Bruno 				/* We are the last, free this local group. */
4341a43cff9SSean Bruno 				in_pcblbgroup_free(grp);
4351a43cff9SSean Bruno 			} else {
4361a43cff9SSean Bruno 				/* Pull up inpcbs, shrink group if possible. */
4371a43cff9SSean Bruno 				in_pcblbgroup_reorder(hdr, &grp, i);
4381a43cff9SSean Bruno 			}
4391a43cff9SSean Bruno 			return;
4401a43cff9SSean Bruno 		}
4411a43cff9SSean Bruno 	}
4421a43cff9SSean Bruno }
4431a43cff9SSean Bruno 
444a034518aSAndrew Gallatin int
445a034518aSAndrew Gallatin in_pcblbgroup_numa(struct inpcb *inp, int arg)
446a034518aSAndrew Gallatin {
447a034518aSAndrew Gallatin 	struct inpcbinfo *pcbinfo;
448a034518aSAndrew Gallatin 	struct inpcblbgrouphead *hdr;
449a034518aSAndrew Gallatin 	struct inpcblbgroup *grp;
450a034518aSAndrew Gallatin 	int err, i;
451a034518aSAndrew Gallatin 	uint8_t numa_domain;
452a034518aSAndrew Gallatin 
453a034518aSAndrew Gallatin 	switch (arg) {
454a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_NODOM:
455a034518aSAndrew Gallatin 		numa_domain = M_NODOM;
456a034518aSAndrew Gallatin 		break;
457a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_CURDOM:
458a034518aSAndrew Gallatin 		numa_domain = PCPU_GET(domain);
459a034518aSAndrew Gallatin 		break;
460a034518aSAndrew Gallatin 	default:
461a034518aSAndrew Gallatin 		if (arg < 0 || arg >= vm_ndomains)
462a034518aSAndrew Gallatin 			return (EINVAL);
463a034518aSAndrew Gallatin 		numa_domain = arg;
464a034518aSAndrew Gallatin 	}
465a034518aSAndrew Gallatin 
466a034518aSAndrew Gallatin 	err = 0;
467a034518aSAndrew Gallatin 	pcbinfo = inp->inp_pcbinfo;
468a034518aSAndrew Gallatin 	INP_WLOCK_ASSERT(inp);
469a034518aSAndrew Gallatin 	INP_HASH_WLOCK(pcbinfo);
470a034518aSAndrew Gallatin 	hdr = &pcbinfo->ipi_lbgrouphashbase[
471a034518aSAndrew Gallatin 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
472a034518aSAndrew Gallatin 	CK_LIST_FOREACH(grp, hdr, il_list) {
473a034518aSAndrew Gallatin 		for (i = 0; i < grp->il_inpcnt; ++i) {
474a034518aSAndrew Gallatin 			if (grp->il_inp[i] != inp)
475a034518aSAndrew Gallatin 				continue;
476a034518aSAndrew Gallatin 
477a034518aSAndrew Gallatin 			if (grp->il_numa_domain == numa_domain) {
478a034518aSAndrew Gallatin 				goto abort_with_hash_wlock;
479a034518aSAndrew Gallatin 			}
480a034518aSAndrew Gallatin 
481a034518aSAndrew Gallatin 			/* Remove it from the old group. */
482a034518aSAndrew Gallatin 			in_pcbremlbgrouphash(inp);
483a034518aSAndrew Gallatin 
484a034518aSAndrew Gallatin 			/* Add it to the new group based on numa domain. */
485a034518aSAndrew Gallatin 			in_pcbinslbgrouphash(inp, numa_domain);
486a034518aSAndrew Gallatin 			goto abort_with_hash_wlock;
487a034518aSAndrew Gallatin 		}
488a034518aSAndrew Gallatin 	}
489a034518aSAndrew Gallatin 	err = ENOENT;
490a034518aSAndrew Gallatin abort_with_hash_wlock:
491a034518aSAndrew Gallatin 	INP_HASH_WUNLOCK(pcbinfo);
492a034518aSAndrew Gallatin 	return (err);
493a034518aSAndrew Gallatin }
494a034518aSAndrew Gallatin 
495db0ac6deSCy Schubert /* Make sure it is safe to use hashinit(9) on CK_LIST. */
496db0ac6deSCy Schubert CTASSERT(sizeof(struct inpcbhead) == sizeof(LIST_HEAD(, inpcb)));
497db0ac6deSCy Schubert 
498cc487c16SGleb Smirnoff /*
499fec8a8c7SGleb Smirnoff  * Initialize an inpcbinfo - a per-VNET instance of connections db.
5009bcd427bSRobert Watson  */
5019bcd427bSRobert Watson void
502fec8a8c7SGleb Smirnoff in_pcbinfo_init(struct inpcbinfo *pcbinfo, struct inpcbstorage *pcbstor,
503fec8a8c7SGleb Smirnoff     u_int hash_nelements, u_int porthash_nelements)
5049bcd427bSRobert Watson {
5059bcd427bSRobert Watson 
506fec8a8c7SGleb Smirnoff 	mtx_init(&pcbinfo->ipi_lock, pcbstor->ips_infolock_name, NULL, MTX_DEF);
507fec8a8c7SGleb Smirnoff 	mtx_init(&pcbinfo->ipi_hash_lock, pcbstor->ips_hashlock_name,
508fec8a8c7SGleb Smirnoff 	    NULL, MTX_DEF);
5099bcd427bSRobert Watson #ifdef VIMAGE
5109bcd427bSRobert Watson 	pcbinfo->ipi_vnet = curvnet;
5119bcd427bSRobert Watson #endif
512db0ac6deSCy Schubert 	CK_LIST_INIT(&pcbinfo->ipi_listhead);
513fa046d87SRobert Watson 	pcbinfo->ipi_count = 0;
514fdb987beSMark Johnston 	pcbinfo->ipi_hash_exact = hashinit(hash_nelements, M_PCB,
515fdb987beSMark Johnston 	    &pcbinfo->ipi_hashmask);
516fdb987beSMark Johnston 	pcbinfo->ipi_hash_wild = hashinit(hash_nelements, M_PCB,
5179bcd427bSRobert Watson 	    &pcbinfo->ipi_hashmask);
518db0ac6deSCy Schubert 	porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
5199bcd427bSRobert Watson 	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
5209bcd427bSRobert Watson 	    &pcbinfo->ipi_porthashmask);
5219d2877fcSMark Johnston 	pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
5221a43cff9SSean Bruno 	    &pcbinfo->ipi_lbgrouphashmask);
523fec8a8c7SGleb Smirnoff 	pcbinfo->ipi_zone = pcbstor->ips_zone;
524fec8a8c7SGleb Smirnoff 	pcbinfo->ipi_portzone = pcbstor->ips_portzone;
525db0ac6deSCy Schubert 	pcbinfo->ipi_smr = uma_zone_get_smr(pcbinfo->ipi_zone);
5269bcd427bSRobert Watson }
5279bcd427bSRobert Watson 
5289bcd427bSRobert Watson /*
5299bcd427bSRobert Watson  * Destroy an inpcbinfo.
5309bcd427bSRobert Watson  */
5319bcd427bSRobert Watson void
5329bcd427bSRobert Watson in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
5339bcd427bSRobert Watson {
5349bcd427bSRobert Watson 
535fa046d87SRobert Watson 	KASSERT(pcbinfo->ipi_count == 0,
536fa046d87SRobert Watson 	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
537fa046d87SRobert Watson 
538fdb987beSMark Johnston 	hashdestroy(pcbinfo->ipi_hash_exact, M_PCB, pcbinfo->ipi_hashmask);
539fdb987beSMark Johnston 	hashdestroy(pcbinfo->ipi_hash_wild, M_PCB, pcbinfo->ipi_hashmask);
5409bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
5419bcd427bSRobert Watson 	    pcbinfo->ipi_porthashmask);
5421a43cff9SSean Bruno 	hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
5431a43cff9SSean Bruno 	    pcbinfo->ipi_lbgrouphashmask);
544db0ac6deSCy Schubert 	mtx_destroy(&pcbinfo->ipi_hash_lock);
545db0ac6deSCy Schubert 	mtx_destroy(&pcbinfo->ipi_lock);
5469bcd427bSRobert Watson }
5479bcd427bSRobert Watson 
5489bcd427bSRobert Watson /*
549fec8a8c7SGleb Smirnoff  * Initialize a pcbstorage - per protocol zones to allocate inpcbs.
550fec8a8c7SGleb Smirnoff  */
551fec8a8c7SGleb Smirnoff static void inpcb_fini(void *, int);
552fec8a8c7SGleb Smirnoff void
553fec8a8c7SGleb Smirnoff in_pcbstorage_init(void *arg)
554fec8a8c7SGleb Smirnoff {
555fec8a8c7SGleb Smirnoff 	struct inpcbstorage *pcbstor = arg;
556fec8a8c7SGleb Smirnoff 
557fec8a8c7SGleb Smirnoff 	pcbstor->ips_zone = uma_zcreate(pcbstor->ips_zone_name,
5585fd1a67eSMark Johnston 	    pcbstor->ips_size, NULL, NULL, pcbstor->ips_pcbinit,
559c4a4b263SAndrew Gallatin 	    inpcb_fini, UMA_ALIGN_CACHE, UMA_ZONE_SMR);
560fec8a8c7SGleb Smirnoff 	pcbstor->ips_portzone = uma_zcreate(pcbstor->ips_portzone_name,
561fec8a8c7SGleb Smirnoff 	    sizeof(struct inpcbport), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
562fec8a8c7SGleb Smirnoff 	uma_zone_set_smr(pcbstor->ips_portzone,
563fec8a8c7SGleb Smirnoff 	    uma_zone_get_smr(pcbstor->ips_zone));
564fec8a8c7SGleb Smirnoff }
565fec8a8c7SGleb Smirnoff 
566fec8a8c7SGleb Smirnoff /*
567fec8a8c7SGleb Smirnoff  * Destroy a pcbstorage - used by unloadable protocols.
568fec8a8c7SGleb Smirnoff  */
569fec8a8c7SGleb Smirnoff void
570fec8a8c7SGleb Smirnoff in_pcbstorage_destroy(void *arg)
571fec8a8c7SGleb Smirnoff {
572fec8a8c7SGleb Smirnoff 	struct inpcbstorage *pcbstor = arg;
573fec8a8c7SGleb Smirnoff 
574fec8a8c7SGleb Smirnoff 	uma_zdestroy(pcbstor->ips_zone);
575fec8a8c7SGleb Smirnoff 	uma_zdestroy(pcbstor->ips_portzone);
576fec8a8c7SGleb Smirnoff }
577fec8a8c7SGleb Smirnoff 
578fec8a8c7SGleb Smirnoff /*
579c3229e05SDavid Greenman  * Allocate a PCB and associate it with the socket.
580d915b280SStephan Uphoff  * On success return with the PCB locked.
581c3229e05SDavid Greenman  */
582df8bae1dSRodney W. Grimes int
583d915b280SStephan Uphoff in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
584df8bae1dSRodney W. Grimes {
585136d4f1cSRobert Watson 	struct inpcb *inp;
586fe5324acSJohn Baldwin #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
58713cf67f3SHajimu UMEMOTO 	int error;
588fe5324acSJohn Baldwin #endif
589a557af22SRobert Watson 
590db0ac6deSCy Schubert 	inp = uma_zalloc_smr(pcbinfo->ipi_zone, M_NOWAIT);
591df8bae1dSRodney W. Grimes 	if (inp == NULL)
592df8bae1dSRodney W. Grimes 		return (ENOBUFS);
5936a6cefacSGleb Smirnoff 	bzero(&inp->inp_start_zero, inp_zero_size);
59450575ce1SAndrew Gallatin #ifdef NUMA
59550575ce1SAndrew Gallatin 	inp->inp_numa_domain = M_NODOM;
59650575ce1SAndrew Gallatin #endif
59715bd2b43SDavid Greenman 	inp->inp_pcbinfo = pcbinfo;
598df8bae1dSRodney W. Grimes 	inp->inp_socket = so;
59986d02c5cSBjoern A. Zeeb 	inp->inp_cred = crhold(so->so_cred);
6008b07e49aSJulian Elischer 	inp->inp_inc.inc_fibnum = so->so_fibnum;
601a557af22SRobert Watson #ifdef MAC
60230d239bcSRobert Watson 	error = mac_inpcb_init(inp, M_NOWAIT);
603a557af22SRobert Watson 	if (error != 0)
604a557af22SRobert Watson 		goto out;
60530d239bcSRobert Watson 	mac_inpcb_create(so, inp);
606a557af22SRobert Watson #endif
607fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
608fcf59617SAndrey V. Elsukov 	error = ipsec_init_pcbpolicy(inp);
6090bffde27SRobert Watson 	if (error != 0) {
6100bffde27SRobert Watson #ifdef MAC
6110bffde27SRobert Watson 		mac_inpcb_destroy(inp);
6120bffde27SRobert Watson #endif
613a557af22SRobert Watson 		goto out;
6140bffde27SRobert Watson 	}
615b2630c29SGeorge V. Neville-Neil #endif /*IPSEC*/
616e3fd5ffdSRobert Watson #ifdef INET6
617340c35deSJonathan Lemon 	if (INP_SOCKAF(so) == AF_INET6) {
618c7a62c92SGleb Smirnoff 		inp->inp_vflag |= INP_IPV6PROTO | INP_IPV6;
619603724d3SBjoern A. Zeeb 		if (V_ip6_v6only)
62033841545SHajimu UMEMOTO 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
621c7a62c92SGleb Smirnoff #ifdef INET
622c7a62c92SGleb Smirnoff 		else
623c7a62c92SGleb Smirnoff 			inp->inp_vflag |= INP_IPV4;
624c7a62c92SGleb Smirnoff #endif
625603724d3SBjoern A. Zeeb 		if (V_ip6_auto_flowlabel)
62633841545SHajimu UMEMOTO 			inp->inp_flags |= IN6P_AUTOFLOWLABEL;
627c7a62c92SGleb Smirnoff 		inp->in6p_hops = -1;	/* use kernel default */
628c7a62c92SGleb Smirnoff 	}
629c7a62c92SGleb Smirnoff #endif
630c7a62c92SGleb Smirnoff #if defined(INET) && defined(INET6)
631c7a62c92SGleb Smirnoff 	else
632c7a62c92SGleb Smirnoff #endif
633c7a62c92SGleb Smirnoff #ifdef INET
634c7a62c92SGleb Smirnoff 		inp->inp_vflag |= INP_IPV4;
63533841545SHajimu UMEMOTO #endif
636fdb987beSMark Johnston 	inp->inp_smr = SMR_SEQ_INVALID;
637fdb987beSMark Johnston 
6388c1960d5SMike Karels 	/*
6398c1960d5SMike Karels 	 * Routes in inpcb's can cache L2 as well; they are guaranteed
6408c1960d5SMike Karels 	 * to be cleaned up.
6418c1960d5SMike Karels 	 */
6428c1960d5SMike Karels 	inp->inp_route.ro_flags = RT_LLE_CACHE;
643db0ac6deSCy Schubert 	refcount_init(&inp->inp_refcount, 1);   /* Reference from socket. */
644db0ac6deSCy Schubert 	INP_WLOCK(inp);
645db0ac6deSCy Schubert 	INP_INFO_WLOCK(pcbinfo);
646db0ac6deSCy Schubert 	pcbinfo->ipi_count++;
647db0ac6deSCy Schubert 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
648db0ac6deSCy Schubert 	CK_LIST_INSERT_HEAD(&pcbinfo->ipi_listhead, inp, inp_list);
649db0ac6deSCy Schubert 	INP_INFO_WUNLOCK(pcbinfo);
650db0ac6deSCy Schubert 	so->so_pcb = inp;
651db0ac6deSCy Schubert 
652db0ac6deSCy Schubert 	return (0);
653db0ac6deSCy Schubert 
6547a60a910SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
655a557af22SRobert Watson out:
656db0ac6deSCy Schubert 	uma_zfree_smr(pcbinfo->ipi_zone, inp);
657266f97b5SCy Schubert 	return (error);
658db0ac6deSCy Schubert #endif
659df8bae1dSRodney W. Grimes }
660df8bae1dSRodney W. Grimes 
66167107f45SBjoern A. Zeeb #ifdef INET
662df8bae1dSRodney W. Grimes int
66396871af0SGleb Smirnoff in_pcbbind(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred)
664df8bae1dSRodney W. Grimes {
6654b932371SIan Dowse 	int anonport, error;
6664b932371SIan Dowse 
66796871af0SGleb Smirnoff 	KASSERT(sin == NULL || sin->sin_family == AF_INET,
66896871af0SGleb Smirnoff 	    ("%s: invalid address family for %p", __func__, sin));
66996871af0SGleb Smirnoff 	KASSERT(sin == NULL || sin->sin_len == sizeof(struct sockaddr_in),
67096871af0SGleb Smirnoff 	    ("%s: invalid address length for %p", __func__, sin));
6718501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
672fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
67359daba27SSam Leffler 
6744b932371SIan Dowse 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
6754b932371SIan Dowse 		return (EINVAL);
67696871af0SGleb Smirnoff 	anonport = sin == NULL || sin->sin_port == 0;
67796871af0SGleb Smirnoff 	error = in_pcbbind_setup(inp, sin, &inp->inp_laddr.s_addr,
678b0330ed9SPawel Jakub Dawidek 	    &inp->inp_lport, cred);
6794b932371SIan Dowse 	if (error)
6804b932371SIan Dowse 		return (error);
6814b932371SIan Dowse 	if (in_pcbinshash(inp) != 0) {
6824b932371SIan Dowse 		inp->inp_laddr.s_addr = INADDR_ANY;
6834b932371SIan Dowse 		inp->inp_lport = 0;
6844b932371SIan Dowse 		return (EAGAIN);
6854b932371SIan Dowse 	}
6864b932371SIan Dowse 	if (anonport)
6874b932371SIan Dowse 		inp->inp_flags |= INP_ANONPORT;
6884b932371SIan Dowse 	return (0);
6894b932371SIan Dowse }
69067107f45SBjoern A. Zeeb #endif
6914b932371SIan Dowse 
692efc76f72SBjoern A. Zeeb #if defined(INET) || defined(INET6)
69325102351SMike Karels /*
69425102351SMike Karels  * Assign a local port like in_pcb_lport(), but also used with connect()
69525102351SMike Karels  * and a foreign address and port.  If fsa is non-NULL, choose a local port
69625102351SMike Karels  * that is unused with those, otherwise one that is completely unused.
6972fdbcbeaSMike Karels  * lsa can be NULL for IPv6.
69825102351SMike Karels  */
699efc76f72SBjoern A. Zeeb int
70025102351SMike Karels in_pcb_lport_dest(struct inpcb *inp, struct sockaddr *lsa, u_short *lportp,
70125102351SMike Karels     struct sockaddr *fsa, u_short fport, struct ucred *cred, int lookupflags)
702efc76f72SBjoern A. Zeeb {
703efc76f72SBjoern A. Zeeb 	struct inpcbinfo *pcbinfo;
704efc76f72SBjoern A. Zeeb 	struct inpcb *tmpinp;
705efc76f72SBjoern A. Zeeb 	unsigned short *lastport;
70619acc506SGleb Smirnoff 	int count, error;
707efc76f72SBjoern A. Zeeb 	u_short aux, first, last, lport;
708efc76f72SBjoern A. Zeeb #ifdef INET
70925102351SMike Karels 	struct in_addr laddr, faddr;
71025102351SMike Karels #endif
71125102351SMike Karels #ifdef INET6
71225102351SMike Karels 	struct in6_addr *laddr6, *faddr6;
713efc76f72SBjoern A. Zeeb #endif
714efc76f72SBjoern A. Zeeb 
715efc76f72SBjoern A. Zeeb 	pcbinfo = inp->inp_pcbinfo;
716efc76f72SBjoern A. Zeeb 
717efc76f72SBjoern A. Zeeb 	/*
718efc76f72SBjoern A. Zeeb 	 * Because no actual state changes occur here, a global write lock on
719efc76f72SBjoern A. Zeeb 	 * the pcbinfo isn't required.
720efc76f72SBjoern A. Zeeb 	 */
721efc76f72SBjoern A. Zeeb 	INP_LOCK_ASSERT(inp);
722fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
723efc76f72SBjoern A. Zeeb 
724efc76f72SBjoern A. Zeeb 	if (inp->inp_flags & INP_HIGHPORT) {
725efc76f72SBjoern A. Zeeb 		first = V_ipport_hifirstauto;	/* sysctl */
726efc76f72SBjoern A. Zeeb 		last  = V_ipport_hilastauto;
727efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lasthi;
728efc76f72SBjoern A. Zeeb 	} else if (inp->inp_flags & INP_LOWPORT) {
729cc426dd3SMateusz Guzik 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
730efc76f72SBjoern A. Zeeb 		if (error)
731efc76f72SBjoern A. Zeeb 			return (error);
732efc76f72SBjoern A. Zeeb 		first = V_ipport_lowfirstauto;	/* 1023 */
733efc76f72SBjoern A. Zeeb 		last  = V_ipport_lowlastauto;	/* 600 */
734efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastlow;
735efc76f72SBjoern A. Zeeb 	} else {
736efc76f72SBjoern A. Zeeb 		first = V_ipport_firstauto;	/* sysctl */
737efc76f72SBjoern A. Zeeb 		last  = V_ipport_lastauto;
738efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastport;
739efc76f72SBjoern A. Zeeb 	}
74019acc506SGleb Smirnoff 
741efc76f72SBjoern A. Zeeb 	/*
742efc76f72SBjoern A. Zeeb 	 * Instead of having two loops further down counting up or down
743efc76f72SBjoern A. Zeeb 	 * make sure that first is always <= last and go with only one
744efc76f72SBjoern A. Zeeb 	 * code path implementing all logic.
745efc76f72SBjoern A. Zeeb 	 */
746efc76f72SBjoern A. Zeeb 	if (first > last) {
747efc76f72SBjoern A. Zeeb 		aux = first;
748efc76f72SBjoern A. Zeeb 		first = last;
749efc76f72SBjoern A. Zeeb 		last = aux;
750efc76f72SBjoern A. Zeeb 	}
751efc76f72SBjoern A. Zeeb 
752efc76f72SBjoern A. Zeeb #ifdef INET
753637f317cSMike Karels 	laddr.s_addr = INADDR_ANY;	/* used by INET6+INET below too */
7544d457387SBjoern A. Zeeb 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
7552fdbcbeaSMike Karels 		if (lsa != NULL)
75625102351SMike Karels 			laddr = ((struct sockaddr_in *)lsa)->sin_addr;
75725102351SMike Karels 		if (fsa != NULL)
75825102351SMike Karels 			faddr = ((struct sockaddr_in *)fsa)->sin_addr;
759efc76f72SBjoern A. Zeeb 	}
760efc76f72SBjoern A. Zeeb #endif
76125102351SMike Karels #ifdef INET6
7622fdbcbeaSMike Karels 	laddr6 = NULL;
7632fdbcbeaSMike Karels 	if ((inp->inp_vflag & INP_IPV6) != 0) {
7642fdbcbeaSMike Karels 		if (lsa != NULL)
76525102351SMike Karels 			laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
76625102351SMike Karels 		if (fsa != NULL)
76725102351SMike Karels 			faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
76825102351SMike Karels 	}
76925102351SMike Karels #endif
77025102351SMike Karels 
77125102351SMike Karels 	tmpinp = NULL;
772efc76f72SBjoern A. Zeeb 	lport = *lportp;
773efc76f72SBjoern A. Zeeb 
77419acc506SGleb Smirnoff 	if (V_ipport_randomized)
775efc76f72SBjoern A. Zeeb 		*lastport = first + (arc4random() % (last - first));
776efc76f72SBjoern A. Zeeb 
777efc76f72SBjoern A. Zeeb 	count = last - first;
778efc76f72SBjoern A. Zeeb 
779efc76f72SBjoern A. Zeeb 	do {
780efc76f72SBjoern A. Zeeb 		if (count-- < 0)	/* completely used? */
781efc76f72SBjoern A. Zeeb 			return (EADDRNOTAVAIL);
782efc76f72SBjoern A. Zeeb 		++*lastport;
783efc76f72SBjoern A. Zeeb 		if (*lastport < first || *lastport > last)
784efc76f72SBjoern A. Zeeb 			*lastport = first;
785efc76f72SBjoern A. Zeeb 		lport = htons(*lastport);
786efc76f72SBjoern A. Zeeb 
78725102351SMike Karels 		if (fsa != NULL) {
78825102351SMike Karels #ifdef INET
78925102351SMike Karels 			if (lsa->sa_family == AF_INET) {
79025102351SMike Karels 				tmpinp = in_pcblookup_hash_locked(pcbinfo,
79125102351SMike Karels 				    faddr, fport, laddr, lport, lookupflags,
7924130ea61SMark Johnston 				    M_NODOM);
79325102351SMike Karels 			}
79425102351SMike Karels #endif
79525102351SMike Karels #ifdef INET6
79625102351SMike Karels 			if (lsa->sa_family == AF_INET6) {
79725102351SMike Karels 				tmpinp = in6_pcblookup_hash_locked(pcbinfo,
79825102351SMike Karels 				    faddr6, fport, laddr6, lport, lookupflags,
7994130ea61SMark Johnston 				    M_NODOM);
80025102351SMike Karels 			}
80125102351SMike Karels #endif
80225102351SMike Karels 		} else {
803efc76f72SBjoern A. Zeeb #ifdef INET6
804637f317cSMike Karels 			if ((inp->inp_vflag & INP_IPV6) != 0) {
805efc76f72SBjoern A. Zeeb 				tmpinp = in6_pcblookup_local(pcbinfo,
80668e0d7e0SRobert Watson 				    &inp->in6p_laddr, lport, lookupflags, cred);
807637f317cSMike Karels #ifdef INET
808637f317cSMike Karels 				if (tmpinp == NULL &&
809637f317cSMike Karels 				    (inp->inp_vflag & INP_IPV4))
810637f317cSMike Karels 					tmpinp = in_pcblookup_local(pcbinfo,
811637f317cSMike Karels 					    laddr, lport, lookupflags, cred);
812637f317cSMike Karels #endif
813637f317cSMike Karels 			}
814efc76f72SBjoern A. Zeeb #endif
815efc76f72SBjoern A. Zeeb #if defined(INET) && defined(INET6)
816efc76f72SBjoern A. Zeeb 			else
817efc76f72SBjoern A. Zeeb #endif
818efc76f72SBjoern A. Zeeb #ifdef INET
819efc76f72SBjoern A. Zeeb 				tmpinp = in_pcblookup_local(pcbinfo, laddr,
82068e0d7e0SRobert Watson 				    lport, lookupflags, cred);
821efc76f72SBjoern A. Zeeb #endif
82225102351SMike Karels 		}
823efc76f72SBjoern A. Zeeb 	} while (tmpinp != NULL);
824efc76f72SBjoern A. Zeeb 
825efc76f72SBjoern A. Zeeb 	*lportp = lport;
826efc76f72SBjoern A. Zeeb 
827efc76f72SBjoern A. Zeeb 	return (0);
828efc76f72SBjoern A. Zeeb }
829efdf104bSMikolaj Golub 
830efdf104bSMikolaj Golub /*
83125102351SMike Karels  * Select a local port (number) to use.
83225102351SMike Karels  */
83325102351SMike Karels int
83425102351SMike Karels in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
83525102351SMike Karels     struct ucred *cred, int lookupflags)
83625102351SMike Karels {
83725102351SMike Karels 	struct sockaddr_in laddr;
83825102351SMike Karels 
83925102351SMike Karels 	if (laddrp) {
84025102351SMike Karels 		bzero(&laddr, sizeof(laddr));
84125102351SMike Karels 		laddr.sin_family = AF_INET;
84225102351SMike Karels 		laddr.sin_addr = *laddrp;
84325102351SMike Karels 	}
84425102351SMike Karels 	return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
84525102351SMike Karels 	    NULL, lportp, NULL, 0, cred, lookupflags));
84625102351SMike Karels }
84725102351SMike Karels 
84825102351SMike Karels /*
849efdf104bSMikolaj Golub  * Return cached socket options.
850efdf104bSMikolaj Golub  */
8511a43cff9SSean Bruno int
852efdf104bSMikolaj Golub inp_so_options(const struct inpcb *inp)
853efdf104bSMikolaj Golub {
8541a43cff9SSean Bruno 	int so_options;
855efdf104bSMikolaj Golub 
856efdf104bSMikolaj Golub 	so_options = 0;
857efdf104bSMikolaj Golub 
8581a43cff9SSean Bruno 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
8591a43cff9SSean Bruno 		so_options |= SO_REUSEPORT_LB;
860efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
861efdf104bSMikolaj Golub 		so_options |= SO_REUSEPORT;
862efdf104bSMikolaj Golub 	if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
863efdf104bSMikolaj Golub 		so_options |= SO_REUSEADDR;
864efdf104bSMikolaj Golub 	return (so_options);
865efdf104bSMikolaj Golub }
866efc76f72SBjoern A. Zeeb #endif /* INET || INET6 */
867efc76f72SBjoern A. Zeeb 
868d5bb8bd3SAdrian Chadd #ifdef INET
8690a100a6fSAdrian Chadd /*
8704b932371SIan Dowse  * Set up a bind operation on a PCB, performing port allocation
8714b932371SIan Dowse  * as required, but do not actually modify the PCB. Callers can
8724b932371SIan Dowse  * either complete the bind by setting inp_laddr/inp_lport and
8734b932371SIan Dowse  * calling in_pcbinshash(), or they can just use the resulting
8744b932371SIan Dowse  * port and address to authorise the sending of a once-off packet.
8754b932371SIan Dowse  *
8764b932371SIan Dowse  * On error, the values of *laddrp and *lportp are not changed.
8774b932371SIan Dowse  */
8784b932371SIan Dowse int
87996871af0SGleb Smirnoff in_pcbbind_setup(struct inpcb *inp, struct sockaddr_in *sin, in_addr_t *laddrp,
880136d4f1cSRobert Watson     u_short *lportp, struct ucred *cred)
8814b932371SIan Dowse {
8824b932371SIan Dowse 	struct socket *so = inp->inp_socket;
883c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
8844b932371SIan Dowse 	struct in_addr laddr;
885df8bae1dSRodney W. Grimes 	u_short lport = 0;
88668e0d7e0SRobert Watson 	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
887413628a7SBjoern A. Zeeb 	int error;
888df8bae1dSRodney W. Grimes 
8898501a69cSRobert Watson 	/*
8901a43cff9SSean Bruno 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
8911a43cff9SSean Bruno 	 * so that we don't have to add to the (already messy) code below.
8921a43cff9SSean Bruno 	 */
8931a43cff9SSean Bruno 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
8941a43cff9SSean Bruno 
8951a43cff9SSean Bruno 	/*
896fa046d87SRobert Watson 	 * No state changes, so read locks are sufficient here.
8978501a69cSRobert Watson 	 */
89859daba27SSam Leffler 	INP_LOCK_ASSERT(inp);
899fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
90059daba27SSam Leffler 
9014b932371SIan Dowse 	laddr.s_addr = *laddrp;
90296871af0SGleb Smirnoff 	if (sin != NULL && laddr.s_addr != INADDR_ANY)
903df8bae1dSRodney W. Grimes 		return (EINVAL);
9041a43cff9SSean Bruno 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
90568e0d7e0SRobert Watson 		lookupflags = INPLOOKUP_WILDCARD;
90696871af0SGleb Smirnoff 	if (sin == NULL) {
9077c2f3cb9SJamie Gritton 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
9087c2f3cb9SJamie Gritton 			return (error);
9097c2f3cb9SJamie Gritton 	} else {
910f161d294SMark Johnston 		KASSERT(sin->sin_family == AF_INET,
911f161d294SMark Johnston 		    ("%s: invalid family for address %p", __func__, sin));
912f161d294SMark Johnston 		KASSERT(sin->sin_len == sizeof(*sin),
913f161d294SMark Johnston 		    ("%s: invalid length for address %p", __func__, sin));
914f161d294SMark Johnston 
915b89e82ddSJamie Gritton 		error = prison_local_ip4(cred, &sin->sin_addr);
916b89e82ddSJamie Gritton 		if (error)
917b89e82ddSJamie Gritton 			return (error);
9184b932371SIan Dowse 		if (sin->sin_port != *lportp) {
9194b932371SIan Dowse 			/* Don't allow the port to change. */
9204b932371SIan Dowse 			if (*lportp != 0)
9214b932371SIan Dowse 				return (EINVAL);
922df8bae1dSRodney W. Grimes 			lport = sin->sin_port;
9234b932371SIan Dowse 		}
9244b932371SIan Dowse 		/* NB: lport is left as 0 if the port isn't being changed. */
925df8bae1dSRodney W. Grimes 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
926df8bae1dSRodney W. Grimes 			/*
927df8bae1dSRodney W. Grimes 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
928df8bae1dSRodney W. Grimes 			 * allow complete duplication of binding if
929df8bae1dSRodney W. Grimes 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
930df8bae1dSRodney W. Grimes 			 * and a multicast address is bound on both
931df8bae1dSRodney W. Grimes 			 * new and duplicated sockets.
932df8bae1dSRodney W. Grimes 			 */
933f122b319SMikolaj Golub 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
934df8bae1dSRodney W. Grimes 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
9351a43cff9SSean Bruno 			/*
9361a43cff9SSean Bruno 			 * XXX: How to deal with SO_REUSEPORT_LB here?
9371a43cff9SSean Bruno 			 * Treat same as SO_REUSEPORT for now.
9381a43cff9SSean Bruno 			 */
9391a43cff9SSean Bruno 			if ((so->so_options &
9401a43cff9SSean Bruno 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
9411a43cff9SSean Bruno 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
942df8bae1dSRodney W. Grimes 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
943df8bae1dSRodney W. Grimes 			sin->sin_port = 0;		/* yech... */
94483103a73SAndrew R. Reiter 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
9454209e01aSAdrian Chadd 			/*
9464209e01aSAdrian Chadd 			 * Is the address a local IP address?
947f44270e7SPawel Jakub Dawidek 			 * If INP_BINDANY is set, then the socket may be bound
9488696873dSAdrian Chadd 			 * to any endpoint address, local or not.
9494209e01aSAdrian Chadd 			 */
950f44270e7SPawel Jakub Dawidek 			if ((inp->inp_flags & INP_BINDANY) == 0 &&
9518896f83aSRobert Watson 			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
952df8bae1dSRodney W. Grimes 				return (EADDRNOTAVAIL);
953df8bae1dSRodney W. Grimes 		}
9544b932371SIan Dowse 		laddr = sin->sin_addr;
955df8bae1dSRodney W. Grimes 		if (lport) {
956df8bae1dSRodney W. Grimes 			struct inpcb *t;
957ae0e7143SRobert Watson 
958df8bae1dSRodney W. Grimes 			/* GROSS */
959603724d3SBjoern A. Zeeb 			if (ntohs(lport) <= V_ipport_reservedhigh &&
960603724d3SBjoern A. Zeeb 			    ntohs(lport) >= V_ipport_reservedlow &&
961cc426dd3SMateusz Guzik 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
9622469dd60SGarrett Wollman 				return (EACCES);
963835d4b89SPawel Jakub Dawidek 			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
964cc426dd3SMateusz Guzik 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
965078b7042SBjoern A. Zeeb 				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
966413628a7SBjoern A. Zeeb 				    lport, INPLOOKUP_WILDCARD, cred);
967340c35deSJonathan Lemon 	/*
968340c35deSJonathan Lemon 	 * XXX
969340c35deSJonathan Lemon 	 * This entire block sorely needs a rewrite.
970340c35deSJonathan Lemon 	 */
9713aff4ccdSMark Johnston 				if (t != NULL &&
9724658dc83SYaroslav Tykhiy 				    (so->so_type != SOCK_STREAM ||
9734658dc83SYaroslav Tykhiy 				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
9744cc20ab1SSeigo Tanimura 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
97552b65dbeSBill Fenner 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
9761a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT) ||
9771a43cff9SSean Bruno 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
97886d02c5cSBjoern A. Zeeb 				    (inp->inp_cred->cr_uid !=
97986d02c5cSBjoern A. Zeeb 				     t->inp_cred->cr_uid))
9804049a042SGuido van Rooij 					return (EADDRINUSE);
9814049a042SGuido van Rooij 			}
982c3229e05SDavid Greenman 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
98368e0d7e0SRobert Watson 			    lport, lookupflags, cred);
9843aff4ccdSMark Johnston 			if (t != NULL && (reuseport & inp_so_options(t)) == 0 &&
9851a43cff9SSean Bruno 			    (reuseport_lb & inp_so_options(t)) == 0) {
986e3fd5ffdSRobert Watson #ifdef INET6
98733841545SHajimu UMEMOTO 				if (ntohl(sin->sin_addr.s_addr) !=
988cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
989cfa1ca9dSYoshinobu Inoue 				    ntohl(t->inp_laddr.s_addr) !=
990cfa1ca9dSYoshinobu Inoue 				    INADDR_ANY ||
991fc06cd42SMikolaj Golub 				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
992fc06cd42SMikolaj Golub 				    (t->inp_vflag & INP_IPV6PROTO) == 0)
993e3fd5ffdSRobert Watson #endif
994df8bae1dSRodney W. Grimes 						return (EADDRINUSE);
995df8bae1dSRodney W. Grimes 			}
996cfa1ca9dSYoshinobu Inoue 		}
997df8bae1dSRodney W. Grimes 	}
9984b932371SIan Dowse 	if (*lportp != 0)
9994b932371SIan Dowse 		lport = *lportp;
100033b3ac06SPeter Wemm 	if (lport == 0) {
10014616026fSErmal Luçi 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1002efc76f72SBjoern A. Zeeb 		if (error != 0)
1003efc76f72SBjoern A. Zeeb 			return (error);
100433b3ac06SPeter Wemm 	}
10054b932371SIan Dowse 	*laddrp = laddr.s_addr;
10064b932371SIan Dowse 	*lportp = lport;
1007df8bae1dSRodney W. Grimes 	return (0);
1008df8bae1dSRodney W. Grimes }
1009df8bae1dSRodney W. Grimes 
1010999f1343SGarrett Wollman /*
10115200e00eSIan Dowse  * Connect from a socket to a specified address.
10125200e00eSIan Dowse  * Both address and port must be specified in argument sin.
10135200e00eSIan Dowse  * If don't have a local address for this socket yet,
10145200e00eSIan Dowse  * then pick one.
1015999f1343SGarrett Wollman  */
1016999f1343SGarrett Wollman int
1017a9d22cceSGleb Smirnoff in_pcbconnect(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred,
1018fdb987beSMark Johnston     bool rehash __unused)
1019999f1343SGarrett Wollman {
10205200e00eSIan Dowse 	u_short lport, fport;
10215200e00eSIan Dowse 	in_addr_t laddr, faddr;
10225200e00eSIan Dowse 	int anonport, error;
1023df8bae1dSRodney W. Grimes 
10248501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1025fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1026fdb987beSMark Johnston 	KASSERT(in_nullhost(inp->inp_faddr),
1027fdb987beSMark Johnston 	    ("%s: inp is already connected", __func__));
102827f74fd0SRobert Watson 
10295200e00eSIan Dowse 	lport = inp->inp_lport;
10305200e00eSIan Dowse 	laddr = inp->inp_laddr.s_addr;
10315200e00eSIan Dowse 	anonport = (lport == 0);
1032a9d22cceSGleb Smirnoff 	error = in_pcbconnect_setup(inp, sin, &laddr, &lport, &faddr, &fport,
10339e46ff4dSGleb Smirnoff 	    cred);
10345200e00eSIan Dowse 	if (error)
10355200e00eSIan Dowse 		return (error);
10365200e00eSIan Dowse 
1037fdb987beSMark Johnston 	inp->inp_faddr.s_addr = faddr;
1038fdb987beSMark Johnston 	inp->inp_fport = fport;
1039fdb987beSMark Johnston 
10405200e00eSIan Dowse 	/* Do the initial binding of the local address if required. */
10415200e00eSIan Dowse 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
10425200e00eSIan Dowse 		inp->inp_lport = lport;
10435200e00eSIan Dowse 		inp->inp_laddr.s_addr = laddr;
10445200e00eSIan Dowse 		if (in_pcbinshash(inp) != 0) {
1045fdb987beSMark Johnston 			inp->inp_laddr.s_addr = inp->inp_faddr.s_addr =
1046fdb987beSMark Johnston 			    INADDR_ANY;
1047fdb987beSMark Johnston 			inp->inp_lport = inp->inp_fport = 0;
10485200e00eSIan Dowse 			return (EAGAIN);
10495200e00eSIan Dowse 		}
1050fdb987beSMark Johnston 	} else {
10515200e00eSIan Dowse 		inp->inp_lport = lport;
10525200e00eSIan Dowse 		inp->inp_laddr.s_addr = laddr;
1053fdb987beSMark Johnston 		if ((inp->inp_flags & INP_INHASHLIST) != 0)
1054db0ac6deSCy Schubert 			in_pcbrehash(inp);
1055fdb987beSMark Johnston 		else
1056db0ac6deSCy Schubert 			in_pcbinshash(inp);
1057fe1274eeSMichael Tuexen 	}
10582cb64cb2SGeorge V. Neville-Neil 
10595200e00eSIan Dowse 	if (anonport)
10605200e00eSIan Dowse 		inp->inp_flags |= INP_ANONPORT;
10615200e00eSIan Dowse 	return (0);
10625200e00eSIan Dowse }
10635200e00eSIan Dowse 
10645200e00eSIan Dowse /*
10650895aec3SBjoern A. Zeeb  * Do proper source address selection on an unbound socket in case
10660895aec3SBjoern A. Zeeb  * of connect. Take jails into account as well.
10670895aec3SBjoern A. Zeeb  */
1068ae190832SSteven Hartland int
10690895aec3SBjoern A. Zeeb in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
10700895aec3SBjoern A. Zeeb     struct ucred *cred)
10710895aec3SBjoern A. Zeeb {
10720895aec3SBjoern A. Zeeb 	struct ifaddr *ifa;
10730895aec3SBjoern A. Zeeb 	struct sockaddr *sa;
10749ac7c6cfSAlexander V. Chernikov 	struct sockaddr_in *sin, dst;
10759ac7c6cfSAlexander V. Chernikov 	struct nhop_object *nh;
10760895aec3SBjoern A. Zeeb 	int error;
10770895aec3SBjoern A. Zeeb 
1078c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
1079413628a7SBjoern A. Zeeb 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1080ac1750ddSMark Johnston 
1081592bcae8SBjoern A. Zeeb 	/*
1082592bcae8SBjoern A. Zeeb 	 * Bypass source address selection and use the primary jail IP
1083592bcae8SBjoern A. Zeeb 	 * if requested.
1084592bcae8SBjoern A. Zeeb 	 */
1085ac1750ddSMark Johnston 	if (!prison_saddrsel_ip4(cred, laddr))
1086592bcae8SBjoern A. Zeeb 		return (0);
1087592bcae8SBjoern A. Zeeb 
10880895aec3SBjoern A. Zeeb 	error = 0;
10890895aec3SBjoern A. Zeeb 
10909ac7c6cfSAlexander V. Chernikov 	nh = NULL;
10919ac7c6cfSAlexander V. Chernikov 	bzero(&dst, sizeof(dst));
10929ac7c6cfSAlexander V. Chernikov 	sin = &dst;
10930895aec3SBjoern A. Zeeb 	sin->sin_family = AF_INET;
10940895aec3SBjoern A. Zeeb 	sin->sin_len = sizeof(struct sockaddr_in);
10950895aec3SBjoern A. Zeeb 	sin->sin_addr.s_addr = faddr->s_addr;
10960895aec3SBjoern A. Zeeb 
10970895aec3SBjoern A. Zeeb 	/*
10980895aec3SBjoern A. Zeeb 	 * If route is known our src addr is taken from the i/f,
10990895aec3SBjoern A. Zeeb 	 * else punt.
11000895aec3SBjoern A. Zeeb 	 *
11010895aec3SBjoern A. Zeeb 	 * Find out route to destination.
11020895aec3SBjoern A. Zeeb 	 */
11030895aec3SBjoern A. Zeeb 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
11049ac7c6cfSAlexander V. Chernikov 		nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
11059ac7c6cfSAlexander V. Chernikov 		    0, NHR_NONE, 0);
11060895aec3SBjoern A. Zeeb 
11070895aec3SBjoern A. Zeeb 	/*
11080895aec3SBjoern A. Zeeb 	 * If we found a route, use the address corresponding to
11090895aec3SBjoern A. Zeeb 	 * the outgoing interface.
11100895aec3SBjoern A. Zeeb 	 *
11110895aec3SBjoern A. Zeeb 	 * Otherwise assume faddr is reachable on a directly connected
11120895aec3SBjoern A. Zeeb 	 * network and try to find a corresponding interface to take
11130895aec3SBjoern A. Zeeb 	 * the source address from.
11140895aec3SBjoern A. Zeeb 	 */
11159ac7c6cfSAlexander V. Chernikov 	if (nh == NULL || nh->nh_ifp == NULL) {
11168c0fec80SRobert Watson 		struct in_ifaddr *ia;
11170895aec3SBjoern A. Zeeb 		struct ifnet *ifp;
11180895aec3SBjoern A. Zeeb 
11194f8585e0SAlan Somers 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
112058a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
11214f6c66ccSMatt Macy 		if (ia == NULL) {
11224f8585e0SAlan Somers 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
112358a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
11244f6c66ccSMatt Macy 		}
11250895aec3SBjoern A. Zeeb 		if (ia == NULL) {
11260895aec3SBjoern A. Zeeb 			error = ENETUNREACH;
11270895aec3SBjoern A. Zeeb 			goto done;
11280895aec3SBjoern A. Zeeb 		}
11290895aec3SBjoern A. Zeeb 
1130ac1750ddSMark Johnston 		if (!prison_flag(cred, PR_IP4)) {
11310895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11320895aec3SBjoern A. Zeeb 			goto done;
11330895aec3SBjoern A. Zeeb 		}
11340895aec3SBjoern A. Zeeb 
11350895aec3SBjoern A. Zeeb 		ifp = ia->ia_ifp;
11360895aec3SBjoern A. Zeeb 		ia = NULL;
1137d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
11380895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
11390895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
11400895aec3SBjoern A. Zeeb 				continue;
11410895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1142b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
11430895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
11440895aec3SBjoern A. Zeeb 				break;
11450895aec3SBjoern A. Zeeb 			}
11460895aec3SBjoern A. Zeeb 		}
11470895aec3SBjoern A. Zeeb 		if (ia != NULL) {
11480895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11490895aec3SBjoern A. Zeeb 			goto done;
11500895aec3SBjoern A. Zeeb 		}
11510895aec3SBjoern A. Zeeb 
11520895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1153b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
11540895aec3SBjoern A. Zeeb 		goto done;
11550895aec3SBjoern A. Zeeb 	}
11560895aec3SBjoern A. Zeeb 
11570895aec3SBjoern A. Zeeb 	/*
11580895aec3SBjoern A. Zeeb 	 * If the outgoing interface on the route found is not
11590895aec3SBjoern A. Zeeb 	 * a loopback interface, use the address from that interface.
11600895aec3SBjoern A. Zeeb 	 * In case of jails do those three steps:
11610895aec3SBjoern A. Zeeb 	 * 1. check if the interface address belongs to the jail. If so use it.
11620895aec3SBjoern A. Zeeb 	 * 2. check if we have any address on the outgoing interface
11630895aec3SBjoern A. Zeeb 	 *    belonging to this jail. If so use it.
11640895aec3SBjoern A. Zeeb 	 * 3. as a last resort return the 'default' jail address.
11650895aec3SBjoern A. Zeeb 	 */
11669ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
11678c0fec80SRobert Watson 		struct in_ifaddr *ia;
11689317b04eSRobert Watson 		struct ifnet *ifp;
11690895aec3SBjoern A. Zeeb 
11700895aec3SBjoern A. Zeeb 		/* If not jailed, use the default returned. */
1171ac1750ddSMark Johnston 		if (!prison_flag(cred, PR_IP4)) {
11729ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
11730895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11740895aec3SBjoern A. Zeeb 			goto done;
11750895aec3SBjoern A. Zeeb 		}
11760895aec3SBjoern A. Zeeb 
11770895aec3SBjoern A. Zeeb 		/* Jailed. */
11780895aec3SBjoern A. Zeeb 		/* 1. Check if the iface address belongs to the jail. */
11799ac7c6cfSAlexander V. Chernikov 		sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1180b89e82ddSJamie Gritton 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
11819ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
11820895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
11830895aec3SBjoern A. Zeeb 			goto done;
11840895aec3SBjoern A. Zeeb 		}
11850895aec3SBjoern A. Zeeb 
11860895aec3SBjoern A. Zeeb 		/*
11870895aec3SBjoern A. Zeeb 		 * 2. Check if we have any address on the outgoing interface
11880895aec3SBjoern A. Zeeb 		 *    belonging to this jail.
11890895aec3SBjoern A. Zeeb 		 */
11908c0fec80SRobert Watson 		ia = NULL;
11919ac7c6cfSAlexander V. Chernikov 		ifp = nh->nh_ifp;
1192d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
11930895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
11940895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
11950895aec3SBjoern A. Zeeb 				continue;
11960895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1197b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
11980895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
11990895aec3SBjoern A. Zeeb 				break;
12000895aec3SBjoern A. Zeeb 			}
12010895aec3SBjoern A. Zeeb 		}
12020895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12030895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12040895aec3SBjoern A. Zeeb 			goto done;
12050895aec3SBjoern A. Zeeb 		}
12060895aec3SBjoern A. Zeeb 
12070895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1208b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12090895aec3SBjoern A. Zeeb 		goto done;
12100895aec3SBjoern A. Zeeb 	}
12110895aec3SBjoern A. Zeeb 
12120895aec3SBjoern A. Zeeb 	/*
12130895aec3SBjoern A. Zeeb 	 * The outgoing interface is marked with 'loopback net', so a route
12140895aec3SBjoern A. Zeeb 	 * to ourselves is here.
12150895aec3SBjoern A. Zeeb 	 * Try to find the interface of the destination address and then
12160895aec3SBjoern A. Zeeb 	 * take the address from there. That interface is not necessarily
12170895aec3SBjoern A. Zeeb 	 * a loopback interface.
12180895aec3SBjoern A. Zeeb 	 * In case of jails, check that it is an address of the jail
12190895aec3SBjoern A. Zeeb 	 * and if we cannot find, fall back to the 'default' jail address.
12200895aec3SBjoern A. Zeeb 	 */
12219ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
12228c0fec80SRobert Watson 		struct in_ifaddr *ia;
12230895aec3SBjoern A. Zeeb 
12249ac7c6cfSAlexander V. Chernikov 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
122558a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
12260895aec3SBjoern A. Zeeb 		if (ia == NULL)
12279ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
122858a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
1229f0bb05fcSQing Li 		if (ia == NULL)
12309ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
12310895aec3SBjoern A. Zeeb 
1232ac1750ddSMark Johnston 		if (!prison_flag(cred, PR_IP4)) {
12330895aec3SBjoern A. Zeeb 			if (ia == NULL) {
12340895aec3SBjoern A. Zeeb 				error = ENETUNREACH;
12350895aec3SBjoern A. Zeeb 				goto done;
12360895aec3SBjoern A. Zeeb 			}
12370895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12380895aec3SBjoern A. Zeeb 			goto done;
12390895aec3SBjoern A. Zeeb 		}
12400895aec3SBjoern A. Zeeb 
12410895aec3SBjoern A. Zeeb 		/* Jailed. */
12420895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12430895aec3SBjoern A. Zeeb 			struct ifnet *ifp;
12440895aec3SBjoern A. Zeeb 
12450895aec3SBjoern A. Zeeb 			ifp = ia->ia_ifp;
12460895aec3SBjoern A. Zeeb 			ia = NULL;
1247d7c5a620SMatt Macy 			CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12480895aec3SBjoern A. Zeeb 				sa = ifa->ifa_addr;
12490895aec3SBjoern A. Zeeb 				if (sa->sa_family != AF_INET)
12500895aec3SBjoern A. Zeeb 					continue;
12510895aec3SBjoern A. Zeeb 				sin = (struct sockaddr_in *)sa;
1252b89e82ddSJamie Gritton 				if (prison_check_ip4(cred,
1253b89e82ddSJamie Gritton 				    &sin->sin_addr) == 0) {
12540895aec3SBjoern A. Zeeb 					ia = (struct in_ifaddr *)ifa;
12550895aec3SBjoern A. Zeeb 					break;
12560895aec3SBjoern A. Zeeb 				}
12570895aec3SBjoern A. Zeeb 			}
12580895aec3SBjoern A. Zeeb 			if (ia != NULL) {
12590895aec3SBjoern A. Zeeb 				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12600895aec3SBjoern A. Zeeb 				goto done;
12610895aec3SBjoern A. Zeeb 			}
12620895aec3SBjoern A. Zeeb 		}
12630895aec3SBjoern A. Zeeb 
12640895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1265b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
12660895aec3SBjoern A. Zeeb 		goto done;
12670895aec3SBjoern A. Zeeb 	}
12680895aec3SBjoern A. Zeeb 
12690895aec3SBjoern A. Zeeb done:
1270713264f6SMark Johnston 	if (error == 0 && laddr->s_addr == INADDR_ANY)
1271713264f6SMark Johnston 		return (EHOSTUNREACH);
12720895aec3SBjoern A. Zeeb 	return (error);
12730895aec3SBjoern A. Zeeb }
12740895aec3SBjoern A. Zeeb 
12750895aec3SBjoern A. Zeeb /*
12765200e00eSIan Dowse  * Set up for a connect from a socket to the specified address.
12775200e00eSIan Dowse  * On entry, *laddrp and *lportp should contain the current local
12785200e00eSIan Dowse  * address and port for the PCB; these are updated to the values
12795200e00eSIan Dowse  * that should be placed in inp_laddr and inp_lport to complete
12805200e00eSIan Dowse  * the connect.
12815200e00eSIan Dowse  *
12825200e00eSIan Dowse  * On success, *faddrp and *fportp will be set to the remote address
12835200e00eSIan Dowse  * and port. These are not updated in the error case.
12845200e00eSIan Dowse  */
12855200e00eSIan Dowse int
1286a9d22cceSGleb Smirnoff in_pcbconnect_setup(struct inpcb *inp, struct sockaddr_in *sin,
1287136d4f1cSRobert Watson     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
12889e46ff4dSGleb Smirnoff     struct ucred *cred)
12895200e00eSIan Dowse {
12905200e00eSIan Dowse 	struct in_ifaddr *ia;
1291b89e82ddSJamie Gritton 	struct in_addr laddr, faddr;
12925200e00eSIan Dowse 	u_short lport, fport;
12935200e00eSIan Dowse 	int error;
12945200e00eSIan Dowse 
1295f161d294SMark Johnston 	KASSERT(sin->sin_family == AF_INET,
1296f161d294SMark Johnston 	    ("%s: invalid address family for %p", __func__, sin));
1297f161d294SMark Johnston 	KASSERT(sin->sin_len == sizeof(*sin),
1298f161d294SMark Johnston 	    ("%s: invalid address length for %p", __func__, sin));
1299f161d294SMark Johnston 
13008501a69cSRobert Watson 	/*
13018501a69cSRobert Watson 	 * Because a global state change doesn't actually occur here, a read
13028501a69cSRobert Watson 	 * lock is sufficient.
13038501a69cSRobert Watson 	 */
1304c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
130527f74fd0SRobert Watson 	INP_LOCK_ASSERT(inp);
1306fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
130727f74fd0SRobert Watson 
1308df8bae1dSRodney W. Grimes 	if (sin->sin_port == 0)
1309df8bae1dSRodney W. Grimes 		return (EADDRNOTAVAIL);
13105200e00eSIan Dowse 	laddr.s_addr = *laddrp;
13115200e00eSIan Dowse 	lport = *lportp;
13125200e00eSIan Dowse 	faddr = sin->sin_addr;
13135200e00eSIan Dowse 	fport = sin->sin_port;
13140c325f53SAlexander V. Chernikov #ifdef ROUTE_MPATH
13150c325f53SAlexander V. Chernikov 	if (CALC_FLOWID_OUTBOUND) {
13160c325f53SAlexander V. Chernikov 		uint32_t hash_val, hash_type;
13170895aec3SBjoern A. Zeeb 
13180c325f53SAlexander V. Chernikov 		hash_val = fib4_calc_software_hash(laddr, faddr, 0, fport,
13190c325f53SAlexander V. Chernikov 		    inp->inp_socket->so_proto->pr_protocol, &hash_type);
13200c325f53SAlexander V. Chernikov 
13210c325f53SAlexander V. Chernikov 		inp->inp_flowid = hash_val;
13220c325f53SAlexander V. Chernikov 		inp->inp_flowtype = hash_type;
13230c325f53SAlexander V. Chernikov 	}
13240c325f53SAlexander V. Chernikov #endif
1325d7c5a620SMatt Macy 	if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1326df8bae1dSRodney W. Grimes 		/*
1327df8bae1dSRodney W. Grimes 		 * If the destination address is INADDR_ANY,
1328df8bae1dSRodney W. Grimes 		 * use the primary local address.
1329df8bae1dSRodney W. Grimes 		 * If the supplied address is INADDR_BROADCAST,
1330df8bae1dSRodney W. Grimes 		 * and the primary interface supports broadcast,
1331df8bae1dSRodney W. Grimes 		 * choose the broadcast address for that interface.
1332df8bae1dSRodney W. Grimes 		 */
1333413628a7SBjoern A. Zeeb 		if (faddr.s_addr == INADDR_ANY) {
1334413628a7SBjoern A. Zeeb 			faddr =
1335d7c5a620SMatt Macy 			    IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1336ac1750ddSMark Johnston 			if ((error = prison_get_ip4(cred, &faddr)) != 0)
1337b89e82ddSJamie Gritton 				return (error);
13382d9cfabaSRobert Watson 		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1339d7c5a620SMatt Macy 			if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
13402d9cfabaSRobert Watson 			    IFF_BROADCAST)
1341d7c5a620SMatt Macy 				faddr = satosin(&CK_STAILQ_FIRST(
1342603724d3SBjoern A. Zeeb 				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
13432d9cfabaSRobert Watson 		}
1344df8bae1dSRodney W. Grimes 	}
13455200e00eSIan Dowse 	if (laddr.s_addr == INADDR_ANY) {
1346d79fdd98SDaniel Eischen 		error = in_pcbladdr(inp, &faddr, &laddr, cred);
1347df8bae1dSRodney W. Grimes 		/*
1348df8bae1dSRodney W. Grimes 		 * If the destination address is multicast and an outgoing
1349d79fdd98SDaniel Eischen 		 * interface has been set as a multicast option, prefer the
1350df8bae1dSRodney W. Grimes 		 * address of that interface as our source address.
1351df8bae1dSRodney W. Grimes 		 */
13525200e00eSIan Dowse 		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1353df8bae1dSRodney W. Grimes 		    inp->inp_moptions != NULL) {
1354df8bae1dSRodney W. Grimes 			struct ip_moptions *imo;
1355df8bae1dSRodney W. Grimes 			struct ifnet *ifp;
1356df8bae1dSRodney W. Grimes 
1357df8bae1dSRodney W. Grimes 			imo = inp->inp_moptions;
1358df8bae1dSRodney W. Grimes 			if (imo->imo_multicast_ifp != NULL) {
1359df8bae1dSRodney W. Grimes 				ifp = imo->imo_multicast_ifp;
1360d7c5a620SMatt Macy 				CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1361ac1750ddSMark Johnston 					if (ia->ia_ifp == ifp &&
1362e691be70SDaniel Eischen 					    prison_check_ip4(cred,
1363ac1750ddSMark Johnston 					    &ia->ia_addr.sin_addr) == 0)
1364df8bae1dSRodney W. Grimes 						break;
1365e691be70SDaniel Eischen 				}
1366e691be70SDaniel Eischen 				if (ia == NULL)
1367d79fdd98SDaniel Eischen 					error = EADDRNOTAVAIL;
1368e691be70SDaniel Eischen 				else {
13695200e00eSIan Dowse 					laddr = ia->ia_addr.sin_addr;
1370d79fdd98SDaniel Eischen 					error = 0;
1371999f1343SGarrett Wollman 				}
1372d79fdd98SDaniel Eischen 			}
1373d79fdd98SDaniel Eischen 		}
137404215ed2SRandall Stewart 		if (error)
137504215ed2SRandall Stewart 			return (error);
13760895aec3SBjoern A. Zeeb 	}
1377a034518aSAndrew Gallatin 
137825102351SMike Karels 	if (lport != 0) {
13799e46ff4dSGleb Smirnoff 		if (in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
13804130ea61SMark Johnston 		    fport, laddr, lport, 0, M_NODOM) != NULL)
1381df8bae1dSRodney W. Grimes 			return (EADDRINUSE);
138225102351SMike Karels 	} else {
138325102351SMike Karels 		struct sockaddr_in lsin, fsin;
138425102351SMike Karels 
138525102351SMike Karels 		bzero(&lsin, sizeof(lsin));
138625102351SMike Karels 		bzero(&fsin, sizeof(fsin));
138725102351SMike Karels 		lsin.sin_family = AF_INET;
138825102351SMike Karels 		lsin.sin_addr = laddr;
138925102351SMike Karels 		fsin.sin_family = AF_INET;
139025102351SMike Karels 		fsin.sin_addr = faddr;
139125102351SMike Karels 		error = in_pcb_lport_dest(inp, (struct sockaddr *) &lsin,
139225102351SMike Karels 		    &lport, (struct sockaddr *)& fsin, fport, cred,
139325102351SMike Karels 		    INPLOOKUP_WILDCARD);
13945a903f8dSPierre Beyssac 		if (error)
13955a903f8dSPierre Beyssac 			return (error);
13965a903f8dSPierre Beyssac 	}
13975200e00eSIan Dowse 	*laddrp = laddr.s_addr;
13985200e00eSIan Dowse 	*lportp = lport;
13995200e00eSIan Dowse 	*faddrp = faddr.s_addr;
14005200e00eSIan Dowse 	*fportp = fport;
1401df8bae1dSRodney W. Grimes 	return (0);
1402df8bae1dSRodney W. Grimes }
1403df8bae1dSRodney W. Grimes 
140426f9a767SRodney W. Grimes void
1405136d4f1cSRobert Watson in_pcbdisconnect(struct inpcb *inp)
1406df8bae1dSRodney W. Grimes {
14076b348152SRobert Watson 
14088501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1409fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1410fdb987beSMark Johnston 	KASSERT(inp->inp_smr == SMR_SEQ_INVALID,
1411fdb987beSMark Johnston 	    ("%s: inp %p was already disconnected", __func__, inp));
1412df8bae1dSRodney W. Grimes 
1413fdb987beSMark Johnston 	in_pcbremhash_locked(inp);
1414fdb987beSMark Johnston 
1415fdb987beSMark Johnston 	/* See the comment in in_pcbinshash(). */
1416fdb987beSMark Johnston 	inp->inp_smr = smr_advance(inp->inp_pcbinfo->ipi_smr);
14172589ec0fSMark Johnston 	inp->inp_laddr.s_addr = INADDR_ANY;
1418df8bae1dSRodney W. Grimes 	inp->inp_faddr.s_addr = INADDR_ANY;
1419df8bae1dSRodney W. Grimes 	inp->inp_fport = 0;
1420df8bae1dSRodney W. Grimes }
142183e521ecSBjoern A. Zeeb #endif /* INET */
1422df8bae1dSRodney W. Grimes 
14234c7c478dSRobert Watson /*
142428696211SRobert Watson  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1425c0a211c5SRobert Watson  * For most protocols, this will be invoked immediately prior to calling
142628696211SRobert Watson  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
142728696211SRobert Watson  * socket, in which case in_pcbfree() is deferred.
14284c7c478dSRobert Watson  */
142926f9a767SRodney W. Grimes void
1430136d4f1cSRobert Watson in_pcbdetach(struct inpcb *inp)
1431df8bae1dSRodney W. Grimes {
14324c7c478dSRobert Watson 
1433a7df09e8SBjoern A. Zeeb 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1434c0a211c5SRobert Watson 
1435f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
1436f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag != NULL)
1437f3e7afe2SHans Petter Selasky 		in_pcbdetach_txrtlmt(inp);
1438f3e7afe2SHans Petter Selasky #endif
14394c7c478dSRobert Watson 	inp->inp_socket->so_pcb = NULL;
14404c7c478dSRobert Watson 	inp->inp_socket = NULL;
14414c7c478dSRobert Watson }
14424c7c478dSRobert Watson 
1443c0a211c5SRobert Watson /*
1444db0ac6deSCy Schubert  * inpcb hash lookups are protected by SMR section.
1445db0ac6deSCy Schubert  *
1446db0ac6deSCy Schubert  * Once desired pcb has been found, switching from SMR section to a pcb
1447db0ac6deSCy Schubert  * lock is performed with inp_smr_lock(). We can not use INP_(W|R)LOCK
1448db0ac6deSCy Schubert  * here because SMR is a critical section.
1449db0ac6deSCy Schubert  * In 99%+ cases inp_smr_lock() would obtain the lock immediately.
1450db0ac6deSCy Schubert  */
14517b92493aSMark Johnston void
1452db0ac6deSCy Schubert inp_lock(struct inpcb *inp, const inp_lookup_t lock)
1453db0ac6deSCy Schubert {
1454db0ac6deSCy Schubert 
1455db0ac6deSCy Schubert 	lock == INPLOOKUP_RLOCKPCB ?
1456db0ac6deSCy Schubert 	    rw_rlock(&inp->inp_lock) : rw_wlock(&inp->inp_lock);
1457db0ac6deSCy Schubert }
1458db0ac6deSCy Schubert 
14597b92493aSMark Johnston void
1460db0ac6deSCy Schubert inp_unlock(struct inpcb *inp, const inp_lookup_t lock)
1461db0ac6deSCy Schubert {
1462db0ac6deSCy Schubert 
1463db0ac6deSCy Schubert 	lock == INPLOOKUP_RLOCKPCB ?
1464db0ac6deSCy Schubert 	    rw_runlock(&inp->inp_lock) : rw_wunlock(&inp->inp_lock);
1465db0ac6deSCy Schubert }
1466db0ac6deSCy Schubert 
14677b92493aSMark Johnston int
1468db0ac6deSCy Schubert inp_trylock(struct inpcb *inp, const inp_lookup_t lock)
1469db0ac6deSCy Schubert {
1470db0ac6deSCy Schubert 
1471db0ac6deSCy Schubert 	return (lock == INPLOOKUP_RLOCKPCB ?
1472db0ac6deSCy Schubert 	    rw_try_rlock(&inp->inp_lock) : rw_try_wlock(&inp->inp_lock));
1473db0ac6deSCy Schubert }
1474db0ac6deSCy Schubert 
1475db0ac6deSCy Schubert static inline bool
1476f567d55fSGleb Smirnoff _inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock, const int ignflags)
1477db0ac6deSCy Schubert {
1478db0ac6deSCy Schubert 
1479db0ac6deSCy Schubert 	MPASS(lock == INPLOOKUP_RLOCKPCB || lock == INPLOOKUP_WLOCKPCB);
1480db0ac6deSCy Schubert 	SMR_ASSERT_ENTERED(inp->inp_pcbinfo->ipi_smr);
1481db0ac6deSCy Schubert 
1482db0ac6deSCy Schubert 	if (__predict_true(inp_trylock(inp, lock))) {
1483f567d55fSGleb Smirnoff 		if (__predict_false(inp->inp_flags & ignflags)) {
1484db0ac6deSCy Schubert 			smr_exit(inp->inp_pcbinfo->ipi_smr);
1485db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1486db0ac6deSCy Schubert 			return (false);
1487db0ac6deSCy Schubert 		}
1488db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1489db0ac6deSCy Schubert 		return (true);
1490db0ac6deSCy Schubert 	}
1491db0ac6deSCy Schubert 
1492db0ac6deSCy Schubert 	if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1493db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1494db0ac6deSCy Schubert 		inp_lock(inp, lock);
1495db0ac6deSCy Schubert 		if (__predict_false(in_pcbrele(inp, lock)))
1496db0ac6deSCy Schubert 			return (false);
1497db0ac6deSCy Schubert 		/*
1498db0ac6deSCy Schubert 		 * inp acquired through refcount & lock for sure didn't went
1499db0ac6deSCy Schubert 		 * through uma_zfree().  However, it may have already went
1500db0ac6deSCy Schubert 		 * through in_pcbfree() and has another reference, that
1501db0ac6deSCy Schubert 		 * prevented its release by our in_pcbrele().
1502db0ac6deSCy Schubert 		 */
1503f567d55fSGleb Smirnoff 		if (__predict_false(inp->inp_flags & ignflags)) {
1504db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1505db0ac6deSCy Schubert 			return (false);
1506db0ac6deSCy Schubert 		}
1507db0ac6deSCy Schubert 		return (true);
1508db0ac6deSCy Schubert 	} else {
1509db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1510db0ac6deSCy Schubert 		return (false);
1511db0ac6deSCy Schubert 	}
1512db0ac6deSCy Schubert }
1513db0ac6deSCy Schubert 
1514f567d55fSGleb Smirnoff bool
1515f567d55fSGleb Smirnoff inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock)
1516f567d55fSGleb Smirnoff {
1517f567d55fSGleb Smirnoff 
1518f567d55fSGleb Smirnoff 	/*
1519f567d55fSGleb Smirnoff 	 * in_pcblookup() family of functions ignore not only freed entries,
1520f567d55fSGleb Smirnoff 	 * that may be found due to lockless access to the hash, but dropped
1521f567d55fSGleb Smirnoff 	 * entries, too.
1522f567d55fSGleb Smirnoff 	 */
1523f567d55fSGleb Smirnoff 	return (_inp_smr_lock(inp, lock, INP_FREED | INP_DROPPED));
1524f567d55fSGleb Smirnoff }
1525f567d55fSGleb Smirnoff 
1526db0ac6deSCy Schubert /*
1527db0ac6deSCy Schubert  * inp_next() - inpcb hash/list traversal iterator
1528db0ac6deSCy Schubert  *
1529db0ac6deSCy Schubert  * Requires initialized struct inpcb_iterator for context.
1530db0ac6deSCy Schubert  * The structure can be initialized with INP_ITERATOR() or INP_ALL_ITERATOR().
1531db0ac6deSCy Schubert  *
1532db0ac6deSCy Schubert  * - Iterator can have either write-lock or read-lock semantics, that can not
1533db0ac6deSCy Schubert  *   be changed later.
1534db0ac6deSCy Schubert  * - Iterator can iterate either over all pcbs list (INP_ALL_LIST), or through
1535db0ac6deSCy Schubert  *   a single hash slot.  Note: only rip_input() does the latter.
1536db0ac6deSCy Schubert  * - Iterator may have optional bool matching function.  The matching function
1537db0ac6deSCy Schubert  *   will be executed for each inpcb in the SMR context, so it can not acquire
1538db0ac6deSCy Schubert  *   locks and can safely access only immutable fields of inpcb.
1539db0ac6deSCy Schubert  *
1540db0ac6deSCy Schubert  * A fresh initialized iterator has NULL inpcb in its context and that
1541db0ac6deSCy Schubert  * means that inp_next() call would return the very first inpcb on the list
1542db0ac6deSCy Schubert  * locked with desired semantic.  In all following calls the context pointer
1543db0ac6deSCy Schubert  * shall hold the current inpcb pointer.  The KPI user is not supposed to
1544db0ac6deSCy Schubert  * unlock the current inpcb!  Upon end of traversal inp_next() will return NULL
1545db0ac6deSCy Schubert  * and write NULL to its context.  After end of traversal an iterator can be
1546db0ac6deSCy Schubert  * reused.
1547db0ac6deSCy Schubert  *
1548db0ac6deSCy Schubert  * List traversals have the following features/constraints:
1549db0ac6deSCy Schubert  * - New entries won't be seen, as they are always added to the head of a list.
1550db0ac6deSCy Schubert  * - Removed entries won't stop traversal as long as they are not added to
1551db0ac6deSCy Schubert  *   a different list. This is violated by in_pcbrehash().
1552db0ac6deSCy Schubert  */
1553db0ac6deSCy Schubert #define	II_LIST_FIRST(ipi, hash)					\
1554db0ac6deSCy Schubert 		(((hash) == INP_ALL_LIST) ?				\
1555db0ac6deSCy Schubert 		    CK_LIST_FIRST(&(ipi)->ipi_listhead) :		\
1556fdb987beSMark Johnston 		    CK_LIST_FIRST(&(ipi)->ipi_hash_exact[(hash)]))
1557db0ac6deSCy Schubert #define	II_LIST_NEXT(inp, hash)						\
1558db0ac6deSCy Schubert 		(((hash) == INP_ALL_LIST) ?				\
1559db0ac6deSCy Schubert 		    CK_LIST_NEXT((inp), inp_list) :			\
1560fdb987beSMark Johnston 		    CK_LIST_NEXT((inp), inp_hash_exact))
1561db0ac6deSCy Schubert #define	II_LOCK_ASSERT(inp, lock)					\
1562db0ac6deSCy Schubert 		rw_assert(&(inp)->inp_lock,				\
1563db0ac6deSCy Schubert 		    (lock) == INPLOOKUP_RLOCKPCB ?  RA_RLOCKED : RA_WLOCKED )
1564db0ac6deSCy Schubert struct inpcb *
1565db0ac6deSCy Schubert inp_next(struct inpcb_iterator *ii)
1566db0ac6deSCy Schubert {
1567db0ac6deSCy Schubert 	const struct inpcbinfo *ipi = ii->ipi;
1568db0ac6deSCy Schubert 	inp_match_t *match = ii->match;
1569db0ac6deSCy Schubert 	void *ctx = ii->ctx;
1570db0ac6deSCy Schubert 	inp_lookup_t lock = ii->lock;
1571db0ac6deSCy Schubert 	int hash = ii->hash;
1572db0ac6deSCy Schubert 	struct inpcb *inp;
1573db0ac6deSCy Schubert 
1574db0ac6deSCy Schubert 	if (ii->inp == NULL) {		/* First call. */
1575db0ac6deSCy Schubert 		smr_enter(ipi->ipi_smr);
1576db0ac6deSCy Schubert 		/* This is unrolled CK_LIST_FOREACH(). */
1577db0ac6deSCy Schubert 		for (inp = II_LIST_FIRST(ipi, hash);
1578db0ac6deSCy Schubert 		    inp != NULL;
1579db0ac6deSCy Schubert 		    inp = II_LIST_NEXT(inp, hash)) {
1580db0ac6deSCy Schubert 			if (match != NULL && (match)(inp, ctx) == false)
1581db0ac6deSCy Schubert 				continue;
1582f567d55fSGleb Smirnoff 			if (__predict_true(_inp_smr_lock(inp, lock, INP_FREED)))
1583db0ac6deSCy Schubert 				break;
1584db0ac6deSCy Schubert 			else {
1585db0ac6deSCy Schubert 				smr_enter(ipi->ipi_smr);
1586db0ac6deSCy Schubert 				MPASS(inp != II_LIST_FIRST(ipi, hash));
1587db0ac6deSCy Schubert 				inp = II_LIST_FIRST(ipi, hash);
1588430df2abSMichael Tuexen 				if (inp == NULL)
1589430df2abSMichael Tuexen 					break;
1590db0ac6deSCy Schubert 			}
1591db0ac6deSCy Schubert 		}
1592db0ac6deSCy Schubert 
1593db0ac6deSCy Schubert 		if (inp == NULL)
1594db0ac6deSCy Schubert 			smr_exit(ipi->ipi_smr);
1595db0ac6deSCy Schubert 		else
1596db0ac6deSCy Schubert 			ii->inp = inp;
1597db0ac6deSCy Schubert 
1598db0ac6deSCy Schubert 		return (inp);
1599db0ac6deSCy Schubert 	}
1600db0ac6deSCy Schubert 
1601db0ac6deSCy Schubert 	/* Not a first call. */
1602db0ac6deSCy Schubert 	smr_enter(ipi->ipi_smr);
1603db0ac6deSCy Schubert restart:
1604db0ac6deSCy Schubert 	inp = ii->inp;
1605db0ac6deSCy Schubert 	II_LOCK_ASSERT(inp, lock);
1606db0ac6deSCy Schubert next:
1607db0ac6deSCy Schubert 	inp = II_LIST_NEXT(inp, hash);
1608db0ac6deSCy Schubert 	if (inp == NULL) {
1609db0ac6deSCy Schubert 		smr_exit(ipi->ipi_smr);
1610db0ac6deSCy Schubert 		goto found;
1611db0ac6deSCy Schubert 	}
1612db0ac6deSCy Schubert 
1613db0ac6deSCy Schubert 	if (match != NULL && (match)(inp, ctx) == false)
1614db0ac6deSCy Schubert 		goto next;
1615db0ac6deSCy Schubert 
1616db0ac6deSCy Schubert 	if (__predict_true(inp_trylock(inp, lock))) {
1617db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1618db0ac6deSCy Schubert 			/*
1619db0ac6deSCy Schubert 			 * Entries are never inserted in middle of a list, thus
1620db0ac6deSCy Schubert 			 * as long as we are in SMR, we can continue traversal.
1621db0ac6deSCy Schubert 			 * Jump to 'restart' should yield in the same result,
1622db0ac6deSCy Schubert 			 * but could produce unnecessary looping.  Could this
1623db0ac6deSCy Schubert 			 * looping be unbound?
1624db0ac6deSCy Schubert 			 */
1625db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1626db0ac6deSCy Schubert 			goto next;
1627db0ac6deSCy Schubert 		} else {
1628db0ac6deSCy Schubert 			smr_exit(ipi->ipi_smr);
1629db0ac6deSCy Schubert 			goto found;
1630db0ac6deSCy Schubert 		}
1631db0ac6deSCy Schubert 	}
1632db0ac6deSCy Schubert 
1633db0ac6deSCy Schubert 	/*
1634db0ac6deSCy Schubert 	 * Can't obtain lock immediately, thus going hard.  Once we exit the
1635db0ac6deSCy Schubert 	 * SMR section we can no longer jump to 'next', and our only stable
1636db0ac6deSCy Schubert 	 * anchoring point is ii->inp, which we keep locked for this case, so
1637db0ac6deSCy Schubert 	 * we jump to 'restart'.
1638db0ac6deSCy Schubert 	 */
1639db0ac6deSCy Schubert 	if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1640db0ac6deSCy Schubert 		smr_exit(ipi->ipi_smr);
1641db0ac6deSCy Schubert 		inp_lock(inp, lock);
1642db0ac6deSCy Schubert 		if (__predict_false(in_pcbrele(inp, lock))) {
1643db0ac6deSCy Schubert 			smr_enter(ipi->ipi_smr);
1644db0ac6deSCy Schubert 			goto restart;
1645db0ac6deSCy Schubert 		}
1646db0ac6deSCy Schubert 		/*
1647db0ac6deSCy Schubert 		 * See comment in inp_smr_lock().
1648db0ac6deSCy Schubert 		 */
1649db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1650db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1651db0ac6deSCy Schubert 			smr_enter(ipi->ipi_smr);
1652db0ac6deSCy Schubert 			goto restart;
1653db0ac6deSCy Schubert 		}
1654db0ac6deSCy Schubert 	} else
1655db0ac6deSCy Schubert 		goto next;
1656db0ac6deSCy Schubert 
1657db0ac6deSCy Schubert found:
1658db0ac6deSCy Schubert 	inp_unlock(ii->inp, lock);
1659db0ac6deSCy Schubert 	ii->inp = inp;
1660db0ac6deSCy Schubert 
1661db0ac6deSCy Schubert 	return (ii->inp);
1662db0ac6deSCy Schubert }
1663db0ac6deSCy Schubert 
1664db0ac6deSCy Schubert /*
166579bdc6e5SRobert Watson  * in_pcbref() bumps the reference count on an inpcb in order to maintain
1666db0ac6deSCy Schubert  * stability of an inpcb pointer despite the inpcb lock being released or
1667db0ac6deSCy Schubert  * SMR section exited.
166879bdc6e5SRobert Watson  *
1669db0ac6deSCy Schubert  * To free a reference later in_pcbrele_(r|w)locked() must be performed.
1670c0a211c5SRobert Watson  */
167179bdc6e5SRobert Watson void
167279bdc6e5SRobert Watson in_pcbref(struct inpcb *inp)
16734c7c478dSRobert Watson {
1674db0ac6deSCy Schubert 	u_int old __diagused;
1675df8bae1dSRodney W. Grimes 
1676db0ac6deSCy Schubert 	old = refcount_acquire(&inp->inp_refcount);
1677db0ac6deSCy Schubert 	KASSERT(old > 0, ("%s: refcount 0", __func__));
167879bdc6e5SRobert Watson }
167979bdc6e5SRobert Watson 
168079bdc6e5SRobert Watson /*
1681db0ac6deSCy Schubert  * Drop a refcount on an inpcb elevated using in_pcbref(), potentially
1682db0ac6deSCy Schubert  * freeing the pcb, if the reference was very last.
168379bdc6e5SRobert Watson  */
1684db0ac6deSCy Schubert bool
168579bdc6e5SRobert Watson in_pcbrele_rlocked(struct inpcb *inp)
168679bdc6e5SRobert Watson {
168779bdc6e5SRobert Watson 
168879bdc6e5SRobert Watson 	INP_RLOCK_ASSERT(inp);
168979bdc6e5SRobert Watson 
1690c7ea65ecSMark Johnston 	if (!refcount_release(&inp->inp_refcount))
1691db0ac6deSCy Schubert 		return (false);
1692db0ac6deSCy Schubert 
1693db0ac6deSCy Schubert 	MPASS(inp->inp_flags & INP_FREED);
1694db0ac6deSCy Schubert 	MPASS(inp->inp_socket == NULL);
16955fd1a67eSMark Johnston 	crfree(inp->inp_cred);
16965fd1a67eSMark Johnston #ifdef INVARIANTS
16975fd1a67eSMark Johnston 	inp->inp_cred = NULL;
16985fd1a67eSMark Johnston #endif
1699df4e91d3SGleb Smirnoff 	INP_RUNLOCK(inp);
1700db0ac6deSCy Schubert 	uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1701db0ac6deSCy Schubert 	return (true);
1702df4e91d3SGleb Smirnoff }
170379bdc6e5SRobert Watson 
1704db0ac6deSCy Schubert bool
170579bdc6e5SRobert Watson in_pcbrele_wlocked(struct inpcb *inp)
170679bdc6e5SRobert Watson {
170779bdc6e5SRobert Watson 
170879bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
170979bdc6e5SRobert Watson 
1710c7ea65ecSMark Johnston 	if (!refcount_release(&inp->inp_refcount))
1711db0ac6deSCy Schubert 		return (false);
1712db0ac6deSCy Schubert 
1713db0ac6deSCy Schubert 	MPASS(inp->inp_flags & INP_FREED);
1714db0ac6deSCy Schubert 	MPASS(inp->inp_socket == NULL);
17155fd1a67eSMark Johnston 	crfree(inp->inp_cred);
17165fd1a67eSMark Johnston #ifdef INVARIANTS
17175fd1a67eSMark Johnston 	inp->inp_cred = NULL;
17185fd1a67eSMark Johnston #endif
1719edd0e0b0SFabien Thomas 	INP_WUNLOCK(inp);
1720db0ac6deSCy Schubert 	uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1721db0ac6deSCy Schubert 	return (true);
1722addf2b20SMatt Macy }
1723addf2b20SMatt Macy 
17247b92493aSMark Johnston bool
17257b92493aSMark Johnston in_pcbrele(struct inpcb *inp, const inp_lookup_t lock)
17267b92493aSMark Johnston {
17277b92493aSMark Johnston 
17287b92493aSMark Johnston 	return (lock == INPLOOKUP_RLOCKPCB ?
17297b92493aSMark Johnston 	    in_pcbrele_rlocked(inp) : in_pcbrele_wlocked(inp));
17307b92493aSMark Johnston }
17317b92493aSMark Johnston 
173279bdc6e5SRobert Watson /*
173379bdc6e5SRobert Watson  * Unconditionally schedule an inpcb to be freed by decrementing its
173479bdc6e5SRobert Watson  * reference count, which should occur only after the inpcb has been detached
173579bdc6e5SRobert Watson  * from its socket.  If another thread holds a temporary reference (acquired
173679bdc6e5SRobert Watson  * using in_pcbref()) then the free is deferred until that reference is
1737db0ac6deSCy Schubert  * released using in_pcbrele_(r|w)locked(), but the inpcb is still unlocked.
1738db0ac6deSCy Schubert  *  Almost all work, including removal from global lists, is done in this
1739db0ac6deSCy Schubert  * context, where the pcbinfo lock is held.
174079bdc6e5SRobert Watson  */
174179bdc6e5SRobert Watson void
174279bdc6e5SRobert Watson in_pcbfree(struct inpcb *inp)
174379bdc6e5SRobert Watson {
1744f42a83f2SMatt Macy 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1745db0ac6deSCy Schubert #ifdef INET
1746db0ac6deSCy Schubert 	struct ip_moptions *imo;
1747db0ac6deSCy Schubert #endif
1748db0ac6deSCy Schubert #ifdef INET6
1749db0ac6deSCy Schubert 	struct ip6_moptions *im6o;
1750db0ac6deSCy Schubert #endif
175145a48d07SJonathan T. Looney 
175279bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
1753db0ac6deSCy Schubert 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1754db0ac6deSCy Schubert 	KASSERT((inp->inp_flags & INP_FREED) == 0,
1755db0ac6deSCy Schubert 	    ("%s: called twice for pcb %p", __func__, inp));
1756db0ac6deSCy Schubert 
1757db0ac6deSCy Schubert 	inp->inp_flags |= INP_FREED;
1758db0ac6deSCy Schubert 	INP_INFO_WLOCK(pcbinfo);
1759db0ac6deSCy Schubert 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1760db0ac6deSCy Schubert 	pcbinfo->ipi_count--;
1761db0ac6deSCy Schubert 	CK_LIST_REMOVE(inp, inp_list);
1762db0ac6deSCy Schubert 	INP_INFO_WUNLOCK(pcbinfo);
1763db0ac6deSCy Schubert 
17643ba34b07SGleb Smirnoff 	if (inp->inp_flags & INP_INHASHLIST)
17653ba34b07SGleb Smirnoff 		in_pcbremhash(inp);
1766db0ac6deSCy Schubert 
1767fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
1768db0ac6deSCy Schubert #ifdef MAC
1769db0ac6deSCy Schubert 	mac_inpcb_destroy(inp);
1770db0ac6deSCy Schubert #endif
1771db0ac6deSCy Schubert #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1772db0ac6deSCy Schubert 	if (inp->inp_sp != NULL)
1773db0ac6deSCy Schubert 		ipsec_delete_pcbpolicy(inp);
1774db0ac6deSCy Schubert #endif
1775db0ac6deSCy Schubert #ifdef INET
1776db0ac6deSCy Schubert 	if (inp->inp_options)
1777db0ac6deSCy Schubert 		(void)m_free(inp->inp_options);
1778db0ac6deSCy Schubert 	imo = inp->inp_moptions;
1779db0ac6deSCy Schubert #endif
1780db0ac6deSCy Schubert #ifdef INET6
1781db0ac6deSCy Schubert 	if (inp->inp_vflag & INP_IPV6PROTO) {
1782db0ac6deSCy Schubert 		ip6_freepcbopts(inp->in6p_outputopts);
1783db0ac6deSCy Schubert 		im6o = inp->in6p_moptions;
1784db0ac6deSCy Schubert 	} else
1785db0ac6deSCy Schubert 		im6o = NULL;
1786db0ac6deSCy Schubert #endif
1787db0ac6deSCy Schubert 
1788db0ac6deSCy Schubert 	if (__predict_false(in_pcbrele_wlocked(inp) == false)) {
1789cb6bb230SMatt Macy 		INP_WUNLOCK(inp);
1790db0ac6deSCy Schubert 	}
1791db0ac6deSCy Schubert #ifdef INET6
1792db0ac6deSCy Schubert 	ip6_freemoptions(im6o);
1793db0ac6deSCy Schubert #endif
1794db0ac6deSCy Schubert #ifdef INET
1795db0ac6deSCy Schubert 	inp_freemoptions(imo);
1796db0ac6deSCy Schubert #endif
1797eb93b99dSGleb Smirnoff }
1798eb93b99dSGleb Smirnoff 
1799eb93b99dSGleb Smirnoff /*
1800eb93b99dSGleb Smirnoff  * Different protocols initialize their inpcbs differently - giving
1801eb93b99dSGleb Smirnoff  * different name to the lock.  But they all are disposed the same.
1802eb93b99dSGleb Smirnoff  */
1803eb93b99dSGleb Smirnoff static void
1804eb93b99dSGleb Smirnoff inpcb_fini(void *mem, int size)
1805eb93b99dSGleb Smirnoff {
1806eb93b99dSGleb Smirnoff 	struct inpcb *inp = mem;
1807eb93b99dSGleb Smirnoff 
1808eb93b99dSGleb Smirnoff 	INP_LOCK_DESTROY(inp);
180928696211SRobert Watson }
181028696211SRobert Watson 
181128696211SRobert Watson /*
1812c0a211c5SRobert Watson  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1813c0a211c5SRobert Watson  * port reservation, and preventing it from being returned by inpcb lookups.
1814c0a211c5SRobert Watson  *
1815c0a211c5SRobert Watson  * It is used by TCP to mark an inpcb as unused and avoid future packet
1816c0a211c5SRobert Watson  * delivery or event notification when a socket remains open but TCP has
1817c0a211c5SRobert Watson  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1818c0a211c5SRobert Watson  * or a RST on the wire, and allows the port binding to be reused while still
1819c0a211c5SRobert Watson  * maintaining the invariant that so_pcb always points to a valid inpcb until
1820c0a211c5SRobert Watson  * in_pcbdetach().
1821c0a211c5SRobert Watson  *
1822c0a211c5SRobert Watson  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1823c0a211c5SRobert Watson  * in_pcbnotifyall() and in_pcbpurgeif0()?
182410702a28SRobert Watson  */
182510702a28SRobert Watson void
182610702a28SRobert Watson in_pcbdrop(struct inpcb *inp)
182710702a28SRobert Watson {
182810702a28SRobert Watson 
18298501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
18306573d758SMatt Macy #ifdef INVARIANTS
18316573d758SMatt Macy 	if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
18326573d758SMatt Macy 		MPASS(inp->inp_refcount > 1);
18336573d758SMatt Macy #endif
183410702a28SRobert Watson 
1835ad71fe3cSRobert Watson 	inp->inp_flags |= INP_DROPPED;
18363ba34b07SGleb Smirnoff 	if (inp->inp_flags & INP_INHASHLIST)
18373ba34b07SGleb Smirnoff 		in_pcbremhash(inp);
183810702a28SRobert Watson }
183910702a28SRobert Watson 
184067107f45SBjoern A. Zeeb #ifdef INET
184154d642bbSRobert Watson /*
184254d642bbSRobert Watson  * Common routines to return the socket addresses associated with inpcbs.
184354d642bbSRobert Watson  */
184426ef6ac4SDon Lewis struct sockaddr *
1845136d4f1cSRobert Watson in_sockaddr(in_port_t port, struct in_addr *addr_p)
184626ef6ac4SDon Lewis {
184726ef6ac4SDon Lewis 	struct sockaddr_in *sin;
184826ef6ac4SDon Lewis 
18491ede983cSDag-Erling Smørgrav 	sin = malloc(sizeof *sin, M_SONAME,
1850a163d034SWarner Losh 		M_WAITOK | M_ZERO);
185126ef6ac4SDon Lewis 	sin->sin_family = AF_INET;
185226ef6ac4SDon Lewis 	sin->sin_len = sizeof(*sin);
185326ef6ac4SDon Lewis 	sin->sin_addr = *addr_p;
185426ef6ac4SDon Lewis 	sin->sin_port = port;
185526ef6ac4SDon Lewis 
185626ef6ac4SDon Lewis 	return (struct sockaddr *)sin;
185726ef6ac4SDon Lewis }
185826ef6ac4SDon Lewis 
1859117bcae7SGarrett Wollman int
186054d642bbSRobert Watson in_getsockaddr(struct socket *so, struct sockaddr **nam)
1861df8bae1dSRodney W. Grimes {
1862136d4f1cSRobert Watson 	struct inpcb *inp;
186326ef6ac4SDon Lewis 	struct in_addr addr;
186426ef6ac4SDon Lewis 	in_port_t port;
186542fa505bSDavid Greenman 
1866fdc984f7STor Egge 	inp = sotoinpcb(so);
186754d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
18686466b28aSRobert Watson 
1869a69042a5SRobert Watson 	INP_RLOCK(inp);
187026ef6ac4SDon Lewis 	port = inp->inp_lport;
187126ef6ac4SDon Lewis 	addr = inp->inp_laddr;
1872a69042a5SRobert Watson 	INP_RUNLOCK(inp);
187342fa505bSDavid Greenman 
187426ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
1875117bcae7SGarrett Wollman 	return 0;
1876df8bae1dSRodney W. Grimes }
1877df8bae1dSRodney W. Grimes 
1878117bcae7SGarrett Wollman int
187954d642bbSRobert Watson in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1880df8bae1dSRodney W. Grimes {
1881136d4f1cSRobert Watson 	struct inpcb *inp;
188226ef6ac4SDon Lewis 	struct in_addr addr;
188326ef6ac4SDon Lewis 	in_port_t port;
188442fa505bSDavid Greenman 
1885fdc984f7STor Egge 	inp = sotoinpcb(so);
188654d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
18876466b28aSRobert Watson 
1888a69042a5SRobert Watson 	INP_RLOCK(inp);
188926ef6ac4SDon Lewis 	port = inp->inp_fport;
189026ef6ac4SDon Lewis 	addr = inp->inp_faddr;
1891a69042a5SRobert Watson 	INP_RUNLOCK(inp);
189242fa505bSDavid Greenman 
189326ef6ac4SDon Lewis 	*nam = in_sockaddr(port, &addr);
1894117bcae7SGarrett Wollman 	return 0;
1895df8bae1dSRodney W. Grimes }
1896df8bae1dSRodney W. Grimes 
189726f9a767SRodney W. Grimes void
1898136d4f1cSRobert Watson in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1899136d4f1cSRobert Watson     struct inpcb *(*notify)(struct inpcb *, int))
1900d1c54148SJesper Skriver {
1901f457d580SRobert Watson 	struct inpcb *inp, *inp_temp;
1902d1c54148SJesper Skriver 
19033dc7ebf9SJeffrey Hsu 	INP_INFO_WLOCK(pcbinfo);
1904db0ac6deSCy Schubert 	CK_LIST_FOREACH_SAFE(inp, &pcbinfo->ipi_listhead, inp_list, inp_temp) {
19058501a69cSRobert Watson 		INP_WLOCK(inp);
1906d1c54148SJesper Skriver #ifdef INET6
1907f76fcf6dSJeffrey Hsu 		if ((inp->inp_vflag & INP_IPV4) == 0) {
19088501a69cSRobert Watson 			INP_WUNLOCK(inp);
1909d1c54148SJesper Skriver 			continue;
1910f76fcf6dSJeffrey Hsu 		}
1911d1c54148SJesper Skriver #endif
1912d1c54148SJesper Skriver 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1913f76fcf6dSJeffrey Hsu 		    inp->inp_socket == NULL) {
19148501a69cSRobert Watson 			INP_WUNLOCK(inp);
1915d1c54148SJesper Skriver 			continue;
1916d1c54148SJesper Skriver 		}
19173dc7ebf9SJeffrey Hsu 		if ((*notify)(inp, errno))
19188501a69cSRobert Watson 			INP_WUNLOCK(inp);
1919f76fcf6dSJeffrey Hsu 	}
19203dc7ebf9SJeffrey Hsu 	INP_INFO_WUNLOCK(pcbinfo);
1921d1c54148SJesper Skriver }
1922d1c54148SJesper Skriver 
1923db0ac6deSCy Schubert static bool
1924db0ac6deSCy Schubert inp_v4_multi_match(const struct inpcb *inp, void *v __unused)
1925db0ac6deSCy Schubert {
1926db0ac6deSCy Schubert 
1927db0ac6deSCy Schubert 	if ((inp->inp_vflag & INP_IPV4) && inp->inp_moptions != NULL)
1928db0ac6deSCy Schubert 		return (true);
1929db0ac6deSCy Schubert 	else
1930db0ac6deSCy Schubert 		return (false);
1931db0ac6deSCy Schubert }
1932db0ac6deSCy Schubert 
1933e43cc4aeSHajimu UMEMOTO void
1934136d4f1cSRobert Watson in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1935e43cc4aeSHajimu UMEMOTO {
1936db0ac6deSCy Schubert 	struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
1937db0ac6deSCy Schubert 	    inp_v4_multi_match, NULL);
1938e43cc4aeSHajimu UMEMOTO 	struct inpcb *inp;
193959854ecfSHans Petter Selasky 	struct in_multi *inm;
194059854ecfSHans Petter Selasky 	struct in_mfilter *imf;
1941e43cc4aeSHajimu UMEMOTO 	struct ip_moptions *imo;
1942e43cc4aeSHajimu UMEMOTO 
1943db0ac6deSCy Schubert 	IN_MULTI_LOCK_ASSERT();
1944db0ac6deSCy Schubert 
1945db0ac6deSCy Schubert 	while ((inp = inp_next(&inpi)) != NULL) {
1946db0ac6deSCy Schubert 		INP_WLOCK_ASSERT(inp);
1947db0ac6deSCy Schubert 
1948e43cc4aeSHajimu UMEMOTO 		imo = inp->inp_moptions;
1949e43cc4aeSHajimu UMEMOTO 		/*
1950e43cc4aeSHajimu UMEMOTO 		 * Unselect the outgoing interface if it is being
1951e43cc4aeSHajimu UMEMOTO 		 * detached.
1952e43cc4aeSHajimu UMEMOTO 		 */
1953e43cc4aeSHajimu UMEMOTO 		if (imo->imo_multicast_ifp == ifp)
1954e43cc4aeSHajimu UMEMOTO 			imo->imo_multicast_ifp = NULL;
1955e43cc4aeSHajimu UMEMOTO 
1956e43cc4aeSHajimu UMEMOTO 		/*
1957e43cc4aeSHajimu UMEMOTO 		 * Drop multicast group membership if we joined
1958e43cc4aeSHajimu UMEMOTO 		 * through the interface being detached.
1959cb6bb230SMatt Macy 		 *
1960cb6bb230SMatt Macy 		 * XXX This can all be deferred to an epoch_call
1961e43cc4aeSHajimu UMEMOTO 		 */
196259854ecfSHans Petter Selasky restart:
196359854ecfSHans Petter Selasky 		IP_MFILTER_FOREACH(imf, &imo->imo_head) {
196459854ecfSHans Petter Selasky 			if ((inm = imf->imf_inm) == NULL)
196559854ecfSHans Petter Selasky 				continue;
196659854ecfSHans Petter Selasky 			if (inm->inm_ifp != ifp)
196759854ecfSHans Petter Selasky 				continue;
196859854ecfSHans Petter Selasky 			ip_mfilter_remove(&imo->imo_head, imf);
196959854ecfSHans Petter Selasky 			in_leavegroup_locked(inm, NULL);
197059854ecfSHans Petter Selasky 			ip_mfilter_free(imf);
197159854ecfSHans Petter Selasky 			goto restart;
1972e43cc4aeSHajimu UMEMOTO 		}
1973e43cc4aeSHajimu UMEMOTO 	}
1974e43cc4aeSHajimu UMEMOTO }
1975e43cc4aeSHajimu UMEMOTO 
1976df8bae1dSRodney W. Grimes /*
1977fa046d87SRobert Watson  * Lookup a PCB based on the local address and port.  Caller must hold the
1978fa046d87SRobert Watson  * hash lock.  No inpcb locks or references are acquired.
1979c3229e05SDavid Greenman  */
1980d5e8a67eSHajimu UMEMOTO #define INP_LOOKUP_MAPPED_PCB_COST	3
1981df8bae1dSRodney W. Grimes struct inpcb *
1982136d4f1cSRobert Watson in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
198368e0d7e0SRobert Watson     u_short lport, int lookupflags, struct ucred *cred)
1984df8bae1dSRodney W. Grimes {
1985136d4f1cSRobert Watson 	struct inpcb *inp;
1986d5e8a67eSHajimu UMEMOTO #ifdef INET6
1987d5e8a67eSHajimu UMEMOTO 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1988d5e8a67eSHajimu UMEMOTO #else
1989d5e8a67eSHajimu UMEMOTO 	int matchwild = 3;
1990d5e8a67eSHajimu UMEMOTO #endif
1991d5e8a67eSHajimu UMEMOTO 	int wildcard;
19927bc4aca7SDavid Greenman 
199368e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
199468e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1995fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
19961b73ca0bSSam Leffler 
199768e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1998c3229e05SDavid Greenman 		struct inpcbhead *head;
1999c3229e05SDavid Greenman 		/*
2000c3229e05SDavid Greenman 		 * Look for an unconnected (wildcard foreign addr) PCB that
2001c3229e05SDavid Greenman 		 * matches the local address and port we're looking for.
2002c3229e05SDavid Greenman 		 */
2003fdb987beSMark Johnston 		head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
2004a0577692SGleb Smirnoff 		    pcbinfo->ipi_hashmask)];
2005fdb987beSMark Johnston 		CK_LIST_FOREACH(inp, head, inp_hash_wild) {
2006cfa1ca9dSYoshinobu Inoue #ifdef INET6
2007413628a7SBjoern A. Zeeb 			/* XXX inp locking */
2008369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
2009cfa1ca9dSYoshinobu Inoue 				continue;
2010cfa1ca9dSYoshinobu Inoue #endif
2011c3229e05SDavid Greenman 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
2012c3229e05SDavid Greenman 			    inp->inp_laddr.s_addr == laddr.s_addr &&
2013c3229e05SDavid Greenman 			    inp->inp_lport == lport) {
2014c3229e05SDavid Greenman 				/*
2015413628a7SBjoern A. Zeeb 				 * Found?
2016c3229e05SDavid Greenman 				 */
2017ac1750ddSMark Johnston 				if (prison_equal_ip4(cred->cr_prison,
20180304c731SJamie Gritton 				    inp->inp_cred->cr_prison))
2019c3229e05SDavid Greenman 					return (inp);
2020df8bae1dSRodney W. Grimes 			}
2021c3229e05SDavid Greenman 		}
2022c3229e05SDavid Greenman 		/*
2023c3229e05SDavid Greenman 		 * Not found.
2024c3229e05SDavid Greenman 		 */
2025c3229e05SDavid Greenman 		return (NULL);
2026c3229e05SDavid Greenman 	} else {
2027c3229e05SDavid Greenman 		struct inpcbporthead *porthash;
2028c3229e05SDavid Greenman 		struct inpcbport *phd;
2029c3229e05SDavid Greenman 		struct inpcb *match = NULL;
2030c3229e05SDavid Greenman 		/*
2031c3229e05SDavid Greenman 		 * Best fit PCB lookup.
2032c3229e05SDavid Greenman 		 *
2033c3229e05SDavid Greenman 		 * First see if this local port is in use by looking on the
2034c3229e05SDavid Greenman 		 * port hash list.
2035c3229e05SDavid Greenman 		 */
2036712fc218SRobert Watson 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
2037712fc218SRobert Watson 		    pcbinfo->ipi_porthashmask)];
2038b872626dSMatt Macy 		CK_LIST_FOREACH(phd, porthash, phd_hash) {
2039c3229e05SDavid Greenman 			if (phd->phd_port == lport)
2040c3229e05SDavid Greenman 				break;
2041c3229e05SDavid Greenman 		}
2042c3229e05SDavid Greenman 		if (phd != NULL) {
2043c3229e05SDavid Greenman 			/*
2044c3229e05SDavid Greenman 			 * Port is in use by one or more PCBs. Look for best
2045c3229e05SDavid Greenman 			 * fit.
2046c3229e05SDavid Greenman 			 */
2047b872626dSMatt Macy 			CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
2048c3229e05SDavid Greenman 				wildcard = 0;
2049ac1750ddSMark Johnston 				if (!prison_equal_ip4(inp->inp_cred->cr_prison,
20500304c731SJamie Gritton 				    cred->cr_prison))
2051413628a7SBjoern A. Zeeb 					continue;
2052cfa1ca9dSYoshinobu Inoue #ifdef INET6
2053413628a7SBjoern A. Zeeb 				/* XXX inp locking */
2054369dc8ceSEivind Eklund 				if ((inp->inp_vflag & INP_IPV4) == 0)
2055cfa1ca9dSYoshinobu Inoue 					continue;
2056d5e8a67eSHajimu UMEMOTO 				/*
2057d5e8a67eSHajimu UMEMOTO 				 * We never select the PCB that has
2058d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag and is bound to :: if
2059d5e8a67eSHajimu UMEMOTO 				 * we have another PCB which is bound
2060d5e8a67eSHajimu UMEMOTO 				 * to 0.0.0.0.  If a PCB has the
2061d5e8a67eSHajimu UMEMOTO 				 * INP_IPV6 flag, then we set its cost
2062d5e8a67eSHajimu UMEMOTO 				 * higher than IPv4 only PCBs.
2063d5e8a67eSHajimu UMEMOTO 				 *
2064d5e8a67eSHajimu UMEMOTO 				 * Note that the case only happens
2065d5e8a67eSHajimu UMEMOTO 				 * when a socket is bound to ::, under
2066d5e8a67eSHajimu UMEMOTO 				 * the condition that the use of the
2067d5e8a67eSHajimu UMEMOTO 				 * mapped address is allowed.
2068d5e8a67eSHajimu UMEMOTO 				 */
2069d5e8a67eSHajimu UMEMOTO 				if ((inp->inp_vflag & INP_IPV6) != 0)
2070d5e8a67eSHajimu UMEMOTO 					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2071cfa1ca9dSYoshinobu Inoue #endif
2072c3229e05SDavid Greenman 				if (inp->inp_faddr.s_addr != INADDR_ANY)
2073c3229e05SDavid Greenman 					wildcard++;
207415bd2b43SDavid Greenman 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
207515bd2b43SDavid Greenman 					if (laddr.s_addr == INADDR_ANY)
207615bd2b43SDavid Greenman 						wildcard++;
207715bd2b43SDavid Greenman 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
207815bd2b43SDavid Greenman 						continue;
207915bd2b43SDavid Greenman 				} else {
208015bd2b43SDavid Greenman 					if (laddr.s_addr != INADDR_ANY)
208115bd2b43SDavid Greenman 						wildcard++;
208215bd2b43SDavid Greenman 				}
2083df8bae1dSRodney W. Grimes 				if (wildcard < matchwild) {
2084df8bae1dSRodney W. Grimes 					match = inp;
2085df8bae1dSRodney W. Grimes 					matchwild = wildcard;
2086413628a7SBjoern A. Zeeb 					if (matchwild == 0)
2087df8bae1dSRodney W. Grimes 						break;
2088df8bae1dSRodney W. Grimes 				}
2089df8bae1dSRodney W. Grimes 			}
20903dbdc25cSDavid Greenman 		}
2091df8bae1dSRodney W. Grimes 		return (match);
2092df8bae1dSRodney W. Grimes 	}
2093c3229e05SDavid Greenman }
2094d5e8a67eSHajimu UMEMOTO #undef INP_LOOKUP_MAPPED_PCB_COST
209515bd2b43SDavid Greenman 
2096d93ec8cbSMark Johnston static bool
2097d93ec8cbSMark Johnston in_pcblookup_lb_numa_match(const struct inpcblbgroup *grp, int domain)
2098d93ec8cbSMark Johnston {
2099d93ec8cbSMark Johnston 	return (domain == M_NODOM || domain == grp->il_numa_domain);
2100d93ec8cbSMark Johnston }
2101d93ec8cbSMark Johnston 
21021a43cff9SSean Bruno static struct inpcb *
21031a43cff9SSean Bruno in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
21044130ea61SMark Johnston     const struct in_addr *faddr, uint16_t fport, const struct in_addr *laddr,
21054130ea61SMark Johnston     uint16_t lport, int domain)
21061a43cff9SSean Bruno {
21071a43cff9SSean Bruno 	const struct inpcblbgrouphead *hdr;
21081a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2109d93ec8cbSMark Johnston 	struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
21101a43cff9SSean Bruno 
21111a43cff9SSean Bruno 	INP_HASH_LOCK_ASSERT(pcbinfo);
21121a43cff9SSean Bruno 
21139d2877fcSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[
21149d2877fcSMark Johnston 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
21151a43cff9SSean Bruno 
21161a43cff9SSean Bruno 	/*
2117d93ec8cbSMark Johnston 	 * Search for an LB group match based on the following criteria:
2118d93ec8cbSMark Johnston 	 * - prefer jailed groups to non-jailed groups
2119d93ec8cbSMark Johnston 	 * - prefer exact source address matches to wildcard matches
2120d93ec8cbSMark Johnston 	 * - prefer groups bound to the specified NUMA domain
21211a43cff9SSean Bruno 	 */
2122d93ec8cbSMark Johnston 	jail_exact = jail_wild = local_exact = local_wild = NULL;
212354af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
2124d93ec8cbSMark Johnston 		bool injail;
2125d93ec8cbSMark Johnston 
21261a43cff9SSean Bruno #ifdef INET6
21271a43cff9SSean Bruno 		if (!(grp->il_vflag & INP_IPV4))
21281a43cff9SSean Bruno 			continue;
21291a43cff9SSean Bruno #endif
21308be02ee4SMark Johnston 		if (grp->il_lport != lport)
21318be02ee4SMark Johnston 			continue;
21321a43cff9SSean Bruno 
2133d93ec8cbSMark Johnston 		injail = prison_flag(grp->il_cred, PR_IP4) != 0;
2134d93ec8cbSMark Johnston 		if (injail && prison_check_ip4_locked(grp->il_cred->cr_prison,
2135d93ec8cbSMark Johnston 		    laddr) != 0)
2136d93ec8cbSMark Johnston 			continue;
2137a034518aSAndrew Gallatin 
2138d93ec8cbSMark Johnston 		if (grp->il_laddr.s_addr == laddr->s_addr) {
2139d93ec8cbSMark Johnston 			if (injail) {
2140d93ec8cbSMark Johnston 				jail_exact = grp;
2141d93ec8cbSMark Johnston 				if (in_pcblookup_lb_numa_match(grp, domain))
2142d93ec8cbSMark Johnston 					/* This is a perfect match. */
2143d93ec8cbSMark Johnston 					goto out;
2144d93ec8cbSMark Johnston 			} else if (local_exact == NULL ||
2145d93ec8cbSMark Johnston 			    in_pcblookup_lb_numa_match(grp, domain)) {
2146d93ec8cbSMark Johnston 				local_exact = grp;
2147d93ec8cbSMark Johnston 			}
21484130ea61SMark Johnston 		} else if (grp->il_laddr.s_addr == INADDR_ANY) {
2149d93ec8cbSMark Johnston 			if (injail) {
2150d93ec8cbSMark Johnston 				if (jail_wild == NULL ||
2151d93ec8cbSMark Johnston 				    in_pcblookup_lb_numa_match(grp, domain))
2152d93ec8cbSMark Johnston 					jail_wild = grp;
2153d93ec8cbSMark Johnston 			} else if (local_wild == NULL ||
2154d93ec8cbSMark Johnston 			    in_pcblookup_lb_numa_match(grp, domain)) {
2155d93ec8cbSMark Johnston 				local_wild = grp;
2156d93ec8cbSMark Johnston 			}
2157d93ec8cbSMark Johnston 		}
2158d93ec8cbSMark Johnston 	}
2159d93ec8cbSMark Johnston 
2160d93ec8cbSMark Johnston 	if (jail_exact != NULL)
2161d93ec8cbSMark Johnston 		grp = jail_exact;
2162d93ec8cbSMark Johnston 	else if (jail_wild != NULL)
2163d93ec8cbSMark Johnston 		grp = jail_wild;
2164d93ec8cbSMark Johnston 	else if (local_exact != NULL)
2165d93ec8cbSMark Johnston 		grp = local_exact;
2166d93ec8cbSMark Johnston 	else
2167d93ec8cbSMark Johnston 		grp = local_wild;
2168d93ec8cbSMark Johnston 	if (grp == NULL)
2169d93ec8cbSMark Johnston 		return (NULL);
2170d93ec8cbSMark Johnston out:
2171d93ec8cbSMark Johnston 	return (grp->il_inp[INP_PCBLBGROUP_PKTHASH(faddr, lport, fport) %
2172d93ec8cbSMark Johnston 	    grp->il_inpcnt]);
21731a43cff9SSean Bruno }
21741a43cff9SSean Bruno 
21753e98dcb3SMark Johnston static bool
21763e98dcb3SMark Johnston in_pcblookup_exact_match(const struct inpcb *inp, struct in_addr faddr,
21774130ea61SMark Johnston     u_short fport, struct in_addr laddr, u_short lport)
217815bd2b43SDavid Greenman {
2179cfa1ca9dSYoshinobu Inoue #ifdef INET6
2180413628a7SBjoern A. Zeeb 	/* XXX inp locking */
2181369dc8ceSEivind Eklund 	if ((inp->inp_vflag & INP_IPV4) == 0)
21823e98dcb3SMark Johnston 		return (false);
2183cfa1ca9dSYoshinobu Inoue #endif
21846d6a026bSDavid Greenman 	if (inp->inp_faddr.s_addr == faddr.s_addr &&
2185ca98b82cSDavid Greenman 	    inp->inp_laddr.s_addr == laddr.s_addr &&
2186ca98b82cSDavid Greenman 	    inp->inp_fport == fport &&
2187220d8921SGleb Smirnoff 	    inp->inp_lport == lport)
21883e98dcb3SMark Johnston 		return (true);
21893e98dcb3SMark Johnston 	return (false);
21903e98dcb3SMark Johnston }
21913e98dcb3SMark Johnston 
21923e98dcb3SMark Johnston static struct inpcb *
21933e98dcb3SMark Johnston in_pcblookup_hash_exact(struct inpcbinfo *pcbinfo, struct in_addr faddr,
21943e98dcb3SMark Johnston     u_short fport, struct in_addr laddr, u_short lport)
21953e98dcb3SMark Johnston {
21963e98dcb3SMark Johnston 	struct inpcbhead *head;
21973e98dcb3SMark Johnston 	struct inpcb *inp;
21983e98dcb3SMark Johnston 
21993e98dcb3SMark Johnston 	INP_HASH_LOCK_ASSERT(pcbinfo);
22003e98dcb3SMark Johnston 
22013e98dcb3SMark Johnston 	head = &pcbinfo->ipi_hash_exact[INP_PCBHASH(&faddr, lport, fport,
22023e98dcb3SMark Johnston 	    pcbinfo->ipi_hashmask)];
22033e98dcb3SMark Johnston 	CK_LIST_FOREACH(inp, head, inp_hash_exact) {
22043e98dcb3SMark Johnston 		if (in_pcblookup_exact_match(inp, faddr, fport, laddr, lport))
2205c3229e05SDavid Greenman 			return (inp);
2206c3229e05SDavid Greenman 	}
22073e98dcb3SMark Johnston 	return (NULL);
22083e98dcb3SMark Johnston }
22093e98dcb3SMark Johnston 
22103e98dcb3SMark Johnston typedef enum {
22113e98dcb3SMark Johnston 	INPLOOKUP_MATCH_NONE = 0,
22123e98dcb3SMark Johnston 	INPLOOKUP_MATCH_WILD = 1,
22133e98dcb3SMark Johnston 	INPLOOKUP_MATCH_LADDR = 2,
22143e98dcb3SMark Johnston } inp_lookup_match_t;
22153e98dcb3SMark Johnston 
22163e98dcb3SMark Johnston static inp_lookup_match_t
22173e98dcb3SMark Johnston in_pcblookup_wild_match(const struct inpcb *inp, struct in_addr laddr,
22183e98dcb3SMark Johnston     u_short lport)
22193e98dcb3SMark Johnston {
22203e98dcb3SMark Johnston #ifdef INET6
22213e98dcb3SMark Johnston 	/* XXX inp locking */
22223e98dcb3SMark Johnston 	if ((inp->inp_vflag & INP_IPV4) == 0)
22233e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_NONE);
22243e98dcb3SMark Johnston #endif
22253e98dcb3SMark Johnston 	if (inp->inp_faddr.s_addr != INADDR_ANY || inp->inp_lport != lport)
22263e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_NONE);
22273e98dcb3SMark Johnston 	if (inp->inp_laddr.s_addr == INADDR_ANY)
22283e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_WILD);
22293e98dcb3SMark Johnston 	if (inp->inp_laddr.s_addr == laddr.s_addr)
22303e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_LADDR);
22313e98dcb3SMark Johnston 	return (INPLOOKUP_MATCH_NONE);
22324130ea61SMark Johnston }
2233e3fd5ffdSRobert Watson 
22347b92493aSMark Johnston #define	INP_LOOKUP_AGAIN	((struct inpcb *)(uintptr_t)-1)
22357b92493aSMark Johnston 
22367b92493aSMark Johnston static struct inpcb *
22377b92493aSMark Johnston in_pcblookup_hash_wild_smr(struct inpcbinfo *pcbinfo, struct in_addr faddr,
22387b92493aSMark Johnston     u_short fport, struct in_addr laddr, u_short lport,
22397b92493aSMark Johnston     const inp_lookup_t lockflags)
22407b92493aSMark Johnston {
22417b92493aSMark Johnston 	struct inpcbhead *head;
22427b92493aSMark Johnston 	struct inpcb *inp;
22437b92493aSMark Johnston 
22447b92493aSMark Johnston 	KASSERT(SMR_ENTERED(pcbinfo->ipi_smr),
22457b92493aSMark Johnston 	    ("%s: not in SMR read section", __func__));
22467b92493aSMark Johnston 
22477b92493aSMark Johnston 	head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
22487b92493aSMark Johnston 	    pcbinfo->ipi_hashmask)];
22497b92493aSMark Johnston 	CK_LIST_FOREACH(inp, head, inp_hash_wild) {
22507b92493aSMark Johnston 		inp_lookup_match_t match;
22517b92493aSMark Johnston 
22527b92493aSMark Johnston 		match = in_pcblookup_wild_match(inp, laddr, lport);
22537b92493aSMark Johnston 		if (match == INPLOOKUP_MATCH_NONE)
22547b92493aSMark Johnston 			continue;
22557b92493aSMark Johnston 
22567b92493aSMark Johnston 		if (__predict_true(inp_smr_lock(inp, lockflags))) {
2257*a306ed50SMark Johnston 			match = in_pcblookup_wild_match(inp, laddr, lport);
2258*a306ed50SMark Johnston 			if (match != INPLOOKUP_MATCH_NONE &&
2259*a306ed50SMark Johnston 			    prison_check_ip4_locked(inp->inp_cred->cr_prison,
2260*a306ed50SMark Johnston 			    &laddr) == 0)
22617b92493aSMark Johnston 				return (inp);
22627b92493aSMark Johnston 			inp_unlock(inp, lockflags);
22637b92493aSMark Johnston 		}
22647b92493aSMark Johnston 
22657b92493aSMark Johnston 		/*
22667b92493aSMark Johnston 		 * The matching socket disappeared out from under us.  Fall back
22677b92493aSMark Johnston 		 * to a serialized lookup.
22687b92493aSMark Johnston 		 */
22697b92493aSMark Johnston 		return (INP_LOOKUP_AGAIN);
22707b92493aSMark Johnston 	}
22717b92493aSMark Johnston 	return (NULL);
22727b92493aSMark Johnston }
22737b92493aSMark Johnston 
22744130ea61SMark Johnston static struct inpcb *
22754130ea61SMark Johnston in_pcblookup_hash_wild_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
22764130ea61SMark Johnston     u_short fport, struct in_addr laddr, u_short lport)
22774130ea61SMark Johnston {
22784130ea61SMark Johnston 	struct inpcbhead *head;
22794130ea61SMark Johnston 	struct inpcb *inp, *local_wild, *local_exact, *jail_wild;
2280e3fd5ffdSRobert Watson #ifdef INET6
22814130ea61SMark Johnston 	struct inpcb *local_wild_mapped;
2282e3fd5ffdSRobert Watson #endif
2283413628a7SBjoern A. Zeeb 
22844130ea61SMark Johnston 	INP_HASH_LOCK_ASSERT(pcbinfo);
2285d93ec8cbSMark Johnston 
2286d93ec8cbSMark Johnston 	/*
2287413628a7SBjoern A. Zeeb 	 * Order of socket selection - we always prefer jails.
2288413628a7SBjoern A. Zeeb 	 *      1. jailed, non-wild.
2289413628a7SBjoern A. Zeeb 	 *      2. jailed, wild.
2290413628a7SBjoern A. Zeeb 	 *      3. non-jailed, non-wild.
2291413628a7SBjoern A. Zeeb 	 *      4. non-jailed, wild.
2292413628a7SBjoern A. Zeeb 	 */
2293fdb987beSMark Johnston 	head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
2294a0577692SGleb Smirnoff 	    pcbinfo->ipi_hashmask)];
22954130ea61SMark Johnston 	local_wild = local_exact = jail_wild = NULL;
22964130ea61SMark Johnston #ifdef INET6
22974130ea61SMark Johnston 	local_wild_mapped = NULL;
22984130ea61SMark Johnston #endif
2299fdb987beSMark Johnston 	CK_LIST_FOREACH(inp, head, inp_hash_wild) {
23003e98dcb3SMark Johnston 		inp_lookup_match_t match;
23014130ea61SMark Johnston 		bool injail;
23024130ea61SMark Johnston 
23033e98dcb3SMark Johnston 		match = in_pcblookup_wild_match(inp, laddr, lport);
23043e98dcb3SMark Johnston 		if (match == INPLOOKUP_MATCH_NONE)
2305413628a7SBjoern A. Zeeb 			continue;
2306413628a7SBjoern A. Zeeb 
23074130ea61SMark Johnston 		injail = prison_flag(inp->inp_cred, PR_IP4) != 0;
2308413628a7SBjoern A. Zeeb 		if (injail) {
23094130ea61SMark Johnston 			if (prison_check_ip4_locked(inp->inp_cred->cr_prison,
23104130ea61SMark Johnston 			    &laddr) != 0)
2311413628a7SBjoern A. Zeeb 				continue;
2312413628a7SBjoern A. Zeeb 		} else {
2313413628a7SBjoern A. Zeeb 			if (local_exact != NULL)
2314413628a7SBjoern A. Zeeb 				continue;
2315413628a7SBjoern A. Zeeb 		}
2316413628a7SBjoern A. Zeeb 
23173e98dcb3SMark Johnston 		if (match == INPLOOKUP_MATCH_LADDR) {
2318413628a7SBjoern A. Zeeb 			if (injail)
2319c3229e05SDavid Greenman 				return (inp);
2320413628a7SBjoern A. Zeeb 			local_exact = inp;
23213e98dcb3SMark Johnston 		} else {
2322e3fd5ffdSRobert Watson #ifdef INET6
2323413628a7SBjoern A. Zeeb 			/* XXX inp locking, NULL check */
23245cd54324SBjoern A. Zeeb 			if (inp->inp_vflag & INP_IPV6PROTO)
2325cfa1ca9dSYoshinobu Inoue 				local_wild_mapped = inp;
2326cfa1ca9dSYoshinobu Inoue 			else
232783e521ecSBjoern A. Zeeb #endif
2328413628a7SBjoern A. Zeeb 				if (injail)
2329413628a7SBjoern A. Zeeb 					jail_wild = inp;
2330413628a7SBjoern A. Zeeb 				else
23316d6a026bSDavid Greenman 					local_wild = inp;
23326d6a026bSDavid Greenman 		}
23334130ea61SMark Johnston 	}
2334413628a7SBjoern A. Zeeb 	if (jail_wild != NULL)
2335413628a7SBjoern A. Zeeb 		return (jail_wild);
2336413628a7SBjoern A. Zeeb 	if (local_exact != NULL)
2337413628a7SBjoern A. Zeeb 		return (local_exact);
2338413628a7SBjoern A. Zeeb 	if (local_wild != NULL)
2339c3229e05SDavid Greenman 		return (local_wild);
2340413628a7SBjoern A. Zeeb #ifdef INET6
2341413628a7SBjoern A. Zeeb 	if (local_wild_mapped != NULL)
2342413628a7SBjoern A. Zeeb 		return (local_wild_mapped);
234383e521ecSBjoern A. Zeeb #endif
23446d6a026bSDavid Greenman 	return (NULL);
234515bd2b43SDavid Greenman }
2346fa046d87SRobert Watson 
2347fa046d87SRobert Watson /*
23484130ea61SMark Johnston  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
23494130ea61SMark Johnston  * that the caller has either locked the hash list, which usually happens
23504130ea61SMark Johnston  * for bind(2) operations, or is in SMR section, which happens when sorting
23514130ea61SMark Johnston  * out incoming packets.
2352fa046d87SRobert Watson  */
2353fa046d87SRobert Watson static struct inpcb *
23544130ea61SMark Johnston in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
23554130ea61SMark Johnston     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
23564130ea61SMark Johnston     uint8_t numa_domain)
23574130ea61SMark Johnston {
23584130ea61SMark Johnston 	struct inpcb *inp;
23594130ea61SMark Johnston 	const u_short fport = fport_arg, lport = lport_arg;
23604130ea61SMark Johnston 
23614130ea61SMark Johnston 	KASSERT((lookupflags & ~INPLOOKUP_WILDCARD) == 0,
23624130ea61SMark Johnston 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
23634130ea61SMark Johnston 	KASSERT(faddr.s_addr != INADDR_ANY,
23644130ea61SMark Johnston 	    ("%s: invalid foreign address", __func__));
23654130ea61SMark Johnston 	KASSERT(laddr.s_addr != INADDR_ANY,
23664130ea61SMark Johnston 	    ("%s: invalid local address", __func__));
23677b92493aSMark Johnston 	INP_HASH_WLOCK_ASSERT(pcbinfo);
23684130ea61SMark Johnston 
23694130ea61SMark Johnston 	inp = in_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
23704130ea61SMark Johnston 	if (inp != NULL)
23714130ea61SMark Johnston 		return (inp);
23724130ea61SMark Johnston 
23734130ea61SMark Johnston 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
23747b92493aSMark Johnston 		inp = in_pcblookup_lbgroup(pcbinfo, &faddr, fport,
23757b92493aSMark Johnston 		    &laddr, lport, numa_domain);
23764130ea61SMark Johnston 		if (inp == NULL) {
23774130ea61SMark Johnston 			inp = in_pcblookup_hash_wild_locked(pcbinfo, faddr,
23784130ea61SMark Johnston 			    fport, laddr, lport);
23794130ea61SMark Johnston 		}
23804130ea61SMark Johnston 	}
23814130ea61SMark Johnston 
23824130ea61SMark Johnston 	return (inp);
23834130ea61SMark Johnston }
23844130ea61SMark Johnston 
23854130ea61SMark Johnston static struct inpcb *
23867b92493aSMark Johnston in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2387fa046d87SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
23884130ea61SMark Johnston     uint8_t numa_domain)
2389fa046d87SRobert Watson {
2390fa046d87SRobert Watson 	struct inpcb *inp;
23917b92493aSMark Johnston 	const inp_lookup_t lockflags = lookupflags & INPLOOKUP_LOCKMASK;
23927b92493aSMark Johnston 
23937b92493aSMark Johnston 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
23947b92493aSMark Johnston 	    ("%s: LOCKPCB not set", __func__));
23957b92493aSMark Johnston 
23967b92493aSMark Johnston 	INP_HASH_WLOCK(pcbinfo);
23977b92493aSMark Johnston 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
23987b92493aSMark Johnston 	    lookupflags & ~INPLOOKUP_LOCKMASK, numa_domain);
23997b92493aSMark Johnston 	if (inp != NULL && !inp_trylock(inp, lockflags)) {
24007b92493aSMark Johnston 		in_pcbref(inp);
24017b92493aSMark Johnston 		INP_HASH_WUNLOCK(pcbinfo);
24027b92493aSMark Johnston 		inp_lock(inp, lockflags);
24037b92493aSMark Johnston 		if (in_pcbrele(inp, lockflags))
24047b92493aSMark Johnston 			/* XXX-MJ or retry until we get a negative match? */
24057b92493aSMark Johnston 			inp = NULL;
24067b92493aSMark Johnston 	} else {
24077b92493aSMark Johnston 		INP_HASH_WUNLOCK(pcbinfo);
24087b92493aSMark Johnston 	}
24097b92493aSMark Johnston 	return (inp);
24107b92493aSMark Johnston }
24117b92493aSMark Johnston 
24127b92493aSMark Johnston static struct inpcb *
24137b92493aSMark Johnston in_pcblookup_hash_smr(struct inpcbinfo *pcbinfo, struct in_addr faddr,
24147b92493aSMark Johnston     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
24157b92493aSMark Johnston     uint8_t numa_domain)
24167b92493aSMark Johnston {
24177b92493aSMark Johnston 	struct inpcb *inp;
24187b92493aSMark Johnston 	const inp_lookup_t lockflags = lookupflags & INPLOOKUP_LOCKMASK;
24197b92493aSMark Johnston 	const u_short fport = fport_arg, lport = lport_arg;
2420fa046d87SRobert Watson 
2421675e2618SMark Johnston 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2422675e2618SMark Johnston 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2423675e2618SMark Johnston 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2424675e2618SMark Johnston 	    ("%s: LOCKPCB not set", __func__));
2425675e2618SMark Johnston 
2426db0ac6deSCy Schubert 	smr_enter(pcbinfo->ipi_smr);
24277b92493aSMark Johnston 	inp = in_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
2428fa046d87SRobert Watson 	if (inp != NULL) {
24297b92493aSMark Johnston 		if (__predict_true(inp_smr_lock(inp, lockflags))) {
24307b92493aSMark Johnston 			/*
24317b92493aSMark Johnston 			 * Revalidate the 4-tuple, the socket could have been
24327b92493aSMark Johnston 			 * disconnected.
24337b92493aSMark Johnston 			 */
24347b92493aSMark Johnston 			if (__predict_true(in_pcblookup_exact_match(inp,
24357b92493aSMark Johnston 			    faddr, fport, laddr, lport)))
24367b92493aSMark Johnston 				return (inp);
24377b92493aSMark Johnston 			inp_unlock(inp, lockflags);
24387b92493aSMark Johnston 		}
24397b92493aSMark Johnston 
24407b92493aSMark Johnston 		/*
24417b92493aSMark Johnston 		 * We failed to lock the inpcb, or its connection state changed
24427b92493aSMark Johnston 		 * out from under us.  Fall back to a precise search.
24437b92493aSMark Johnston 		 */
24447b92493aSMark Johnston 		return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
24457b92493aSMark Johnston 		    lookupflags, numa_domain));
24467b92493aSMark Johnston 	}
24477b92493aSMark Johnston 
24487b92493aSMark Johnston 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
24497b92493aSMark Johnston 		inp = in_pcblookup_lbgroup(pcbinfo, &faddr, fport,
24507b92493aSMark Johnston 		    &laddr, lport, numa_domain);
24517b92493aSMark Johnston 		if (inp != NULL) {
24527b92493aSMark Johnston 			if (__predict_true(inp_smr_lock(inp, lockflags))) {
24537b92493aSMark Johnston 				if (__predict_true(in_pcblookup_wild_match(inp,
24547b92493aSMark Johnston 				    laddr, lport) != INPLOOKUP_MATCH_NONE))
24557b92493aSMark Johnston 					return (inp);
24567b92493aSMark Johnston 				inp_unlock(inp, lockflags);
24577b92493aSMark Johnston 			}
24587b92493aSMark Johnston 			inp = INP_LOOKUP_AGAIN;
24597b92493aSMark Johnston 		} else {
24607b92493aSMark Johnston 			inp = in_pcblookup_hash_wild_smr(pcbinfo, faddr, fport,
24617b92493aSMark Johnston 			    laddr, lport, lockflags);
24627b92493aSMark Johnston 		}
24637b92493aSMark Johnston 		if (inp == INP_LOOKUP_AGAIN) {
24647b92493aSMark Johnston 			return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr,
24657b92493aSMark Johnston 			    lport, lookupflags, numa_domain));
24667b92493aSMark Johnston 		}
24677b92493aSMark Johnston 	}
24687b92493aSMark Johnston 
24697b92493aSMark Johnston 	if (inp == NULL)
2470db0ac6deSCy Schubert 		smr_exit(pcbinfo->ipi_smr);
2471d797164aSGleb Smirnoff 
2472fa046d87SRobert Watson 	return (inp);
2473fa046d87SRobert Watson }
2474fa046d87SRobert Watson 
2475fa046d87SRobert Watson /*
2476d3c1f003SRobert Watson  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2477d3c1f003SRobert Watson  * from which a pre-calculated hash value may be extracted.
2478fa046d87SRobert Watson  */
2479fa046d87SRobert Watson struct inpcb *
2480fa046d87SRobert Watson in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
24814130ea61SMark Johnston     struct in_addr laddr, u_int lport, int lookupflags,
24824130ea61SMark Johnston     struct ifnet *ifp __unused)
2483fa046d87SRobert Watson {
24844130ea61SMark Johnston 	return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
24854130ea61SMark Johnston 	    lookupflags, M_NODOM));
2486fa046d87SRobert Watson }
2487d3c1f003SRobert Watson 
2488d3c1f003SRobert Watson struct inpcb *
2489d3c1f003SRobert Watson in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2490d3c1f003SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
24914130ea61SMark Johnston     struct ifnet *ifp __unused, struct mbuf *m)
2492d3c1f003SRobert Watson {
24934130ea61SMark Johnston 	return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
24944130ea61SMark Johnston 	    lookupflags, m->m_pkthdr.numa_domain));
2495d3c1f003SRobert Watson }
249667107f45SBjoern A. Zeeb #endif /* INET */
249715bd2b43SDavid Greenman 
24987b92493aSMark Johnston static bool
24997b92493aSMark Johnston in_pcbjailed(const struct inpcb *inp, unsigned int flag)
25007b92493aSMark Johnston {
25017b92493aSMark Johnston 	return (prison_flag(inp->inp_cred, flag) != 0);
25027b92493aSMark Johnston }
25037b92493aSMark Johnston 
25047b92493aSMark Johnston /*
25057b92493aSMark Johnston  * Insert the PCB into a hash chain using ordering rules which ensure that
25067b92493aSMark Johnston  * in_pcblookup_hash_wild_*() always encounter the highest-ranking PCB first.
25077b92493aSMark Johnston  *
25087b92493aSMark Johnston  * Specifically, keep jailed PCBs in front of non-jailed PCBs, and keep PCBs
250993998d16SMark Johnston  * with exact local addresses ahead of wildcard PCBs.  Unbound v4-mapped v6 PCBs
251093998d16SMark Johnston  * always appear last no matter whether they are jailed.
25117b92493aSMark Johnston  */
25127b92493aSMark Johnston static void
25137b92493aSMark Johnston _in_pcbinshash_wild(struct inpcbhead *pcbhash, struct inpcb *inp)
25147b92493aSMark Johnston {
25157b92493aSMark Johnston 	struct inpcb *last;
25167b92493aSMark Johnston 	bool bound, injail;
25177b92493aSMark Johnston 
251893998d16SMark Johnston 	INP_LOCK_ASSERT(inp);
25197b92493aSMark Johnston 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
25207b92493aSMark Johnston 
25217b92493aSMark Johnston 	last = NULL;
25227b92493aSMark Johnston 	bound = inp->inp_laddr.s_addr != INADDR_ANY;
252393998d16SMark Johnston 	if (!bound && (inp->inp_vflag & INP_IPV6PROTO) != 0) {
252493998d16SMark Johnston 		CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
252593998d16SMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
252693998d16SMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
252793998d16SMark Johnston 				return;
252893998d16SMark Johnston 			}
252993998d16SMark Johnston 		}
253093998d16SMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
253193998d16SMark Johnston 		return;
253293998d16SMark Johnston 	}
253393998d16SMark Johnston 
25347b92493aSMark Johnston 	injail = in_pcbjailed(inp, PR_IP4);
25357b92493aSMark Johnston 	if (!injail) {
25367b92493aSMark Johnston 		CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
253793998d16SMark Johnston 			if (!in_pcbjailed(last, PR_IP4))
25387b92493aSMark Johnston 				break;
25397b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
25407b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
25417b92493aSMark Johnston 				return;
25427b92493aSMark Johnston 			}
25437b92493aSMark Johnston 		}
25447b92493aSMark Johnston 	} else if (!CK_LIST_EMPTY(pcbhash) &&
25457b92493aSMark Johnston 	    !in_pcbjailed(CK_LIST_FIRST(pcbhash), PR_IP4)) {
25467b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
25477b92493aSMark Johnston 		return;
25487b92493aSMark Johnston 	}
25497b92493aSMark Johnston 	if (!bound) {
25507b92493aSMark Johnston 		CK_LIST_FOREACH_FROM(last, pcbhash, inp_hash_wild) {
25517b92493aSMark Johnston 			if (last->inp_laddr.s_addr == INADDR_ANY)
25527b92493aSMark Johnston 				break;
25537b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
25547b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
25557b92493aSMark Johnston 				return;
25567b92493aSMark Johnston 			}
25577b92493aSMark Johnston 		}
25587b92493aSMark Johnston 	}
25597b92493aSMark Johnston 	if (last == NULL)
25607b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
25617b92493aSMark Johnston 	else
25627b92493aSMark Johnston 		CK_LIST_INSERT_BEFORE(last, inp, inp_hash_wild);
25637b92493aSMark Johnston }
25647b92493aSMark Johnston 
25657b92493aSMark Johnston #ifdef INET6
25667b92493aSMark Johnston /*
25677b92493aSMark Johnston  * See the comment above _in_pcbinshash_wild().
25687b92493aSMark Johnston  */
25697b92493aSMark Johnston static void
25707b92493aSMark Johnston _in6_pcbinshash_wild(struct inpcbhead *pcbhash, struct inpcb *inp)
25717b92493aSMark Johnston {
25727b92493aSMark Johnston 	struct inpcb *last;
25737b92493aSMark Johnston 	bool bound, injail;
25747b92493aSMark Johnston 
257593998d16SMark Johnston 	INP_LOCK_ASSERT(inp);
25767b92493aSMark Johnston 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
25777b92493aSMark Johnston 
25787b92493aSMark Johnston 	last = NULL;
25797b92493aSMark Johnston 	bound = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr);
25807b92493aSMark Johnston 	injail = in_pcbjailed(inp, PR_IP6);
25817b92493aSMark Johnston 	if (!injail) {
25827b92493aSMark Johnston 		CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
258393998d16SMark Johnston 			if (!in_pcbjailed(last, PR_IP6))
25847b92493aSMark Johnston 				break;
25857b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
25867b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
25877b92493aSMark Johnston 				return;
25887b92493aSMark Johnston 			}
25897b92493aSMark Johnston 		}
25907b92493aSMark Johnston 	} else if (!CK_LIST_EMPTY(pcbhash) &&
25917b92493aSMark Johnston 	    !in_pcbjailed(CK_LIST_FIRST(pcbhash), PR_IP6)) {
25927b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
25937b92493aSMark Johnston 		return;
25947b92493aSMark Johnston 	}
25957b92493aSMark Johnston 	if (!bound) {
25967b92493aSMark Johnston 		CK_LIST_FOREACH_FROM(last, pcbhash, inp_hash_wild) {
25977b92493aSMark Johnston 			if (IN6_IS_ADDR_UNSPECIFIED(&last->in6p_laddr))
25987b92493aSMark Johnston 				break;
25997b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
26007b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
26017b92493aSMark Johnston 				return;
26027b92493aSMark Johnston 			}
26037b92493aSMark Johnston 		}
26047b92493aSMark Johnston 	}
26057b92493aSMark Johnston 	if (last == NULL)
26067b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
26077b92493aSMark Johnston 	else
26087b92493aSMark Johnston 		CK_LIST_INSERT_BEFORE(last, inp, inp_hash_wild);
26097b92493aSMark Johnston }
26107b92493aSMark Johnston #endif
26117b92493aSMark Johnston 
26127bc4aca7SDavid Greenman /*
2613c3229e05SDavid Greenman  * Insert PCB onto various hash lists.
26147bc4aca7SDavid Greenman  */
2615db0ac6deSCy Schubert int
2616db0ac6deSCy Schubert in_pcbinshash(struct inpcb *inp)
261715bd2b43SDavid Greenman {
2618c3229e05SDavid Greenman 	struct inpcbhead *pcbhash;
2619c3229e05SDavid Greenman 	struct inpcbporthead *pcbporthash;
2620c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2621c3229e05SDavid Greenman 	struct inpcbport *phd;
2622fdb987beSMark Johnston 	uint32_t hash;
2623fdb987beSMark Johnston 	bool connected;
262415bd2b43SDavid Greenman 
26258501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2626fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2627111d57a6SRobert Watson 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2628111d57a6SRobert Watson 	    ("in_pcbinshash: INP_INHASHLIST"));
2629602cc7f1SRobert Watson 
2630cfa1ca9dSYoshinobu Inoue #ifdef INET6
2631fdb987beSMark Johnston 	if (inp->inp_vflag & INP_IPV6) {
2632fdb987beSMark Johnston 		hash = INP6_PCBHASH(&inp->in6p_faddr, inp->inp_lport,
2633fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2634fdb987beSMark Johnston 		connected = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr);
2635fdb987beSMark Johnston 	} else
263683e521ecSBjoern A. Zeeb #endif
2637fdb987beSMark Johnston 	{
2638fdb987beSMark Johnston 		hash = INP_PCBHASH(&inp->inp_faddr, inp->inp_lport,
2639fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2640fdb987beSMark Johnston 		connected = !in_nullhost(inp->inp_faddr);
2641fdb987beSMark Johnston 	}
2642fdb987beSMark Johnston 
2643fdb987beSMark Johnston 	if (connected)
2644fdb987beSMark Johnston 		pcbhash = &pcbinfo->ipi_hash_exact[hash];
2645fdb987beSMark Johnston 	else
2646fdb987beSMark Johnston 		pcbhash = &pcbinfo->ipi_hash_wild[hash];
264715bd2b43SDavid Greenman 
2648712fc218SRobert Watson 	pcbporthash = &pcbinfo->ipi_porthashbase[
2649712fc218SRobert Watson 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2650c3229e05SDavid Greenman 
2651c3229e05SDavid Greenman 	/*
26521a43cff9SSean Bruno 	 * Add entry to load balance group.
26531a43cff9SSean Bruno 	 * Only do this if SO_REUSEPORT_LB is set.
26541a43cff9SSean Bruno 	 */
2655a152dd86SMark Johnston 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0) {
2656a152dd86SMark Johnston 		int error = in_pcbinslbgrouphash(inp, M_NODOM);
2657a152dd86SMark Johnston 		if (error != 0)
2658a152dd86SMark Johnston 			return (error);
26591a43cff9SSean Bruno 	}
26601a43cff9SSean Bruno 
26611a43cff9SSean Bruno 	/*
2662c3229e05SDavid Greenman 	 * Go through port list and look for a head for this lport.
2663c3229e05SDavid Greenman 	 */
2664b872626dSMatt Macy 	CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2665c3229e05SDavid Greenman 		if (phd->phd_port == inp->inp_lport)
2666c3229e05SDavid Greenman 			break;
2667c3229e05SDavid Greenman 	}
2668a152dd86SMark Johnston 
2669c3229e05SDavid Greenman 	/*
2670c3229e05SDavid Greenman 	 * If none exists, malloc one and tack it on.
2671c3229e05SDavid Greenman 	 */
2672c3229e05SDavid Greenman 	if (phd == NULL) {
2673db0ac6deSCy Schubert 		phd = uma_zalloc_smr(pcbinfo->ipi_portzone, M_NOWAIT);
2674c3229e05SDavid Greenman 		if (phd == NULL) {
2675a152dd86SMark Johnston 			if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
2676a152dd86SMark Johnston 				in_pcbremlbgrouphash(inp);
2677a152dd86SMark Johnston 			return (ENOMEM);
2678c3229e05SDavid Greenman 		}
2679c3229e05SDavid Greenman 		phd->phd_port = inp->inp_lport;
2680b872626dSMatt Macy 		CK_LIST_INIT(&phd->phd_pcblist);
2681b872626dSMatt Macy 		CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2682c3229e05SDavid Greenman 	}
2683c3229e05SDavid Greenman 	inp->inp_phd = phd;
2684b872626dSMatt Macy 	CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2685fdb987beSMark Johnston 
2686fdb987beSMark Johnston 	/*
2687fdb987beSMark Johnston 	 * The PCB may have been disconnected in the past.  Before we can safely
2688fdb987beSMark Johnston 	 * make it visible in the hash table, we must wait for all readers which
2689fdb987beSMark Johnston 	 * may be traversing this PCB to finish.
2690fdb987beSMark Johnston 	 */
2691fdb987beSMark Johnston 	if (inp->inp_smr != SMR_SEQ_INVALID) {
2692fdb987beSMark Johnston 		smr_wait(pcbinfo->ipi_smr, inp->inp_smr);
2693fdb987beSMark Johnston 		inp->inp_smr = SMR_SEQ_INVALID;
2694fdb987beSMark Johnston 	}
2695fdb987beSMark Johnston 
2696fdb987beSMark Johnston 	if (connected)
2697fdb987beSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_exact);
26987b92493aSMark Johnston 	else {
26997b92493aSMark Johnston #ifdef INET6
27007b92493aSMark Johnston 		if ((inp->inp_vflag & INP_IPV6) != 0)
27017b92493aSMark Johnston 			_in6_pcbinshash_wild(pcbhash, inp);
2702fdb987beSMark Johnston 		else
27037b92493aSMark Johnston #endif
27047b92493aSMark Johnston 			_in_pcbinshash_wild(pcbhash, inp);
27057b92493aSMark Johnston 	}
2706111d57a6SRobert Watson 	inp->inp_flags |= INP_INHASHLIST;
2707db0ac6deSCy Schubert 
2708c3229e05SDavid Greenman 	return (0);
270915bd2b43SDavid Greenman }
271015bd2b43SDavid Greenman 
2711fdb987beSMark Johnston void
2712fdb987beSMark Johnston in_pcbremhash_locked(struct inpcb *inp)
27133ba34b07SGleb Smirnoff {
27143ba34b07SGleb Smirnoff 	struct inpcbport *phd = inp->inp_phd;
27153ba34b07SGleb Smirnoff 
27163ba34b07SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
2717fdb987beSMark Johnston 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
27183ba34b07SGleb Smirnoff 	MPASS(inp->inp_flags & INP_INHASHLIST);
27193ba34b07SGleb Smirnoff 
2720d93ec8cbSMark Johnston 	if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
27213ba34b07SGleb Smirnoff 		in_pcbremlbgrouphash(inp);
2722fdb987beSMark Johnston #ifdef INET6
2723fdb987beSMark Johnston 	if (inp->inp_vflag & INP_IPV6) {
2724fdb987beSMark Johnston 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
2725fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_wild);
2726fdb987beSMark Johnston 		else
2727fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_exact);
2728fdb987beSMark Johnston 	} else
2729fdb987beSMark Johnston #endif
2730fdb987beSMark Johnston 	{
2731fdb987beSMark Johnston 		if (in_nullhost(inp->inp_faddr))
2732fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_wild);
2733fdb987beSMark Johnston 		else
2734fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_exact);
2735fdb987beSMark Johnston 	}
27363ba34b07SGleb Smirnoff 	CK_LIST_REMOVE(inp, inp_portlist);
27373ba34b07SGleb Smirnoff 	if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
27383ba34b07SGleb Smirnoff 		CK_LIST_REMOVE(phd, phd_hash);
27393ba34b07SGleb Smirnoff 		uma_zfree_smr(inp->inp_pcbinfo->ipi_portzone, phd);
27403ba34b07SGleb Smirnoff 	}
27413ba34b07SGleb Smirnoff 	inp->inp_flags &= ~INP_INHASHLIST;
27423ba34b07SGleb Smirnoff }
27433ba34b07SGleb Smirnoff 
2744fdb987beSMark Johnston static void
2745fdb987beSMark Johnston in_pcbremhash(struct inpcb *inp)
2746fdb987beSMark Johnston {
2747fdb987beSMark Johnston 	INP_HASH_WLOCK(inp->inp_pcbinfo);
2748fdb987beSMark Johnston 	in_pcbremhash_locked(inp);
2749fdb987beSMark Johnston 	INP_HASH_WUNLOCK(inp->inp_pcbinfo);
2750fdb987beSMark Johnston }
2751fdb987beSMark Johnston 
275252cd27cbSRobert Watson /*
2753c3229e05SDavid Greenman  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2754c3229e05SDavid Greenman  * changed. NOTE: This does not handle the case of the lport changing (the
2755c3229e05SDavid Greenman  * hashed port list would have to be updated as well), so the lport must
2756c3229e05SDavid Greenman  * not change after in_pcbinshash() has been called.
2757c3229e05SDavid Greenman  */
275815bd2b43SDavid Greenman void
2759db0ac6deSCy Schubert in_pcbrehash(struct inpcb *inp)
276015bd2b43SDavid Greenman {
276159daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
276215bd2b43SDavid Greenman 	struct inpcbhead *head;
2763fdb987beSMark Johnston 	uint32_t hash;
2764fdb987beSMark Johnston 	bool connected;
276515bd2b43SDavid Greenman 
27668501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2767fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2768111d57a6SRobert Watson 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2769fdb987beSMark Johnston 	    ("%s: !INP_INHASHLIST", __func__));
2770fdb987beSMark Johnston 	KASSERT(inp->inp_smr == SMR_SEQ_INVALID,
2771fdb987beSMark Johnston 	    ("%s: inp was disconnected", __func__));
2772602cc7f1SRobert Watson 
2773cfa1ca9dSYoshinobu Inoue #ifdef INET6
2774fdb987beSMark Johnston 	if (inp->inp_vflag & INP_IPV6) {
2775fdb987beSMark Johnston 		hash = INP6_PCBHASH(&inp->in6p_faddr, inp->inp_lport,
2776fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2777fdb987beSMark Johnston 		connected = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr);
2778fdb987beSMark Johnston 	} else
277983e521ecSBjoern A. Zeeb #endif
2780fdb987beSMark Johnston 	{
2781fdb987beSMark Johnston 		hash = INP_PCBHASH(&inp->inp_faddr, inp->inp_lport,
2782fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2783fdb987beSMark Johnston 		connected = !in_nullhost(inp->inp_faddr);
2784fdb987beSMark Johnston 	}
278515bd2b43SDavid Greenman 
2786fdb987beSMark Johnston 	/*
2787fdb987beSMark Johnston 	 * When rehashing, the caller must ensure that either the new or the old
2788fdb987beSMark Johnston 	 * foreign address was unspecified.
2789fdb987beSMark Johnston 	 */
2790fdb987beSMark Johnston 	if (connected)
2791fdb987beSMark Johnston 		CK_LIST_REMOVE(inp, inp_hash_wild);
2792fdb987beSMark Johnston 	else
2793fdb987beSMark Johnston 		CK_LIST_REMOVE(inp, inp_hash_exact);
2794fdb987beSMark Johnston 
2795fdb987beSMark Johnston 	if (connected) {
2796fdb987beSMark Johnston 		head = &pcbinfo->ipi_hash_exact[hash];
2797fdb987beSMark Johnston 		CK_LIST_INSERT_HEAD(head, inp, inp_hash_exact);
2798fdb987beSMark Johnston 	} else {
2799fdb987beSMark Johnston 		head = &pcbinfo->ipi_hash_wild[hash];
2800fdb987beSMark Johnston 		CK_LIST_INSERT_HEAD(head, inp, inp_hash_wild);
2801fdb987beSMark Johnston 	}
2802c3229e05SDavid Greenman }
2803c3229e05SDavid Greenman 
2804c3229e05SDavid Greenman /*
280584cc0778SGeorge V. Neville-Neil  * Check for alternatives when higher level complains
280684cc0778SGeorge V. Neville-Neil  * about service problems.  For now, invalidate cached
280784cc0778SGeorge V. Neville-Neil  * routing information.  If the route was created dynamically
280884cc0778SGeorge V. Neville-Neil  * (by a redirect), time to try a default gateway again.
280984cc0778SGeorge V. Neville-Neil  */
281084cc0778SGeorge V. Neville-Neil void
281184cc0778SGeorge V. Neville-Neil in_losing(struct inpcb *inp)
281284cc0778SGeorge V. Neville-Neil {
281384cc0778SGeorge V. Neville-Neil 
2814fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
281584cc0778SGeorge V. Neville-Neil 	return;
281684cc0778SGeorge V. Neville-Neil }
281784cc0778SGeorge V. Neville-Neil 
281884cc0778SGeorge V. Neville-Neil /*
2819a557af22SRobert Watson  * A set label operation has occurred at the socket layer, propagate the
2820a557af22SRobert Watson  * label change into the in_pcb for the socket.
2821a557af22SRobert Watson  */
2822a557af22SRobert Watson void
2823136d4f1cSRobert Watson in_pcbsosetlabel(struct socket *so)
2824a557af22SRobert Watson {
2825a557af22SRobert Watson #ifdef MAC
2826a557af22SRobert Watson 	struct inpcb *inp;
2827a557af22SRobert Watson 
28284c7c478dSRobert Watson 	inp = sotoinpcb(so);
28294c7c478dSRobert Watson 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2830602cc7f1SRobert Watson 
28318501a69cSRobert Watson 	INP_WLOCK(inp);
2832310e7cebSRobert Watson 	SOCK_LOCK(so);
2833a557af22SRobert Watson 	mac_inpcb_sosetlabel(so, inp);
2834310e7cebSRobert Watson 	SOCK_UNLOCK(so);
28358501a69cSRobert Watson 	INP_WUNLOCK(inp);
2836a557af22SRobert Watson #endif
2837a557af22SRobert Watson }
28385f311da2SMike Silbersack 
28393d585327SKip Macy void
28403d585327SKip Macy inp_wlock(struct inpcb *inp)
28413d585327SKip Macy {
28423d585327SKip Macy 
28438501a69cSRobert Watson 	INP_WLOCK(inp);
28443d585327SKip Macy }
28453d585327SKip Macy 
28463d585327SKip Macy void
28473d585327SKip Macy inp_wunlock(struct inpcb *inp)
28483d585327SKip Macy {
28493d585327SKip Macy 
28508501a69cSRobert Watson 	INP_WUNLOCK(inp);
28513d585327SKip Macy }
28523d585327SKip Macy 
28533d585327SKip Macy void
28543d585327SKip Macy inp_rlock(struct inpcb *inp)
28553d585327SKip Macy {
28563d585327SKip Macy 
2857a69042a5SRobert Watson 	INP_RLOCK(inp);
28583d585327SKip Macy }
28593d585327SKip Macy 
28603d585327SKip Macy void
28613d585327SKip Macy inp_runlock(struct inpcb *inp)
28623d585327SKip Macy {
28633d585327SKip Macy 
2864a69042a5SRobert Watson 	INP_RUNLOCK(inp);
28653d585327SKip Macy }
28663d585327SKip Macy 
2867c75e2666SGleb Smirnoff #ifdef INVARIANT_SUPPORT
28683d585327SKip Macy void
2869e79dd20dSKip Macy inp_lock_assert(struct inpcb *inp)
28703d585327SKip Macy {
28713d585327SKip Macy 
28728501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
28733d585327SKip Macy }
28743d585327SKip Macy 
28753d585327SKip Macy void
2876e79dd20dSKip Macy inp_unlock_assert(struct inpcb *inp)
28773d585327SKip Macy {
28783d585327SKip Macy 
28793d585327SKip Macy 	INP_UNLOCK_ASSERT(inp);
28803d585327SKip Macy }
28813d585327SKip Macy #endif
28823d585327SKip Macy 
28839378e437SKip Macy void
288424cf7a8dSGleb Smirnoff inp_apply_all(struct inpcbinfo *pcbinfo,
288524cf7a8dSGleb Smirnoff     void (*func)(struct inpcb *, void *), void *arg)
28869378e437SKip Macy {
288724cf7a8dSGleb Smirnoff 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2888db0ac6deSCy Schubert 	    INPLOOKUP_WLOCKPCB);
28899378e437SKip Macy 	struct inpcb *inp;
28909378e437SKip Macy 
2891db0ac6deSCy Schubert 	while ((inp = inp_next(&inpi)) != NULL)
28929378e437SKip Macy 		func(inp, arg);
28939378e437SKip Macy }
28949378e437SKip Macy 
28959378e437SKip Macy struct socket *
28969378e437SKip Macy inp_inpcbtosocket(struct inpcb *inp)
28979378e437SKip Macy {
28989378e437SKip Macy 
28999378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
29009378e437SKip Macy 	return (inp->inp_socket);
29019378e437SKip Macy }
29029378e437SKip Macy 
29039378e437SKip Macy struct tcpcb *
29049378e437SKip Macy inp_inpcbtotcpcb(struct inpcb *inp)
29059378e437SKip Macy {
29069378e437SKip Macy 
29079378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
29089378e437SKip Macy 	return ((struct tcpcb *)inp->inp_ppcb);
29099378e437SKip Macy }
29109378e437SKip Macy 
29119378e437SKip Macy int
29129378e437SKip Macy inp_ip_tos_get(const struct inpcb *inp)
29139378e437SKip Macy {
29149378e437SKip Macy 
29159378e437SKip Macy 	return (inp->inp_ip_tos);
29169378e437SKip Macy }
29179378e437SKip Macy 
29189378e437SKip Macy void
29199378e437SKip Macy inp_ip_tos_set(struct inpcb *inp, int val)
29209378e437SKip Macy {
29219378e437SKip Macy 
29229378e437SKip Macy 	inp->inp_ip_tos = val;
29239378e437SKip Macy }
29249378e437SKip Macy 
29259378e437SKip Macy void
2926df9cf830STai-hwa Liang inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
29279d29c635SKip Macy     uint32_t *faddr, uint16_t *fp)
29289378e437SKip Macy {
29299378e437SKip Macy 
29309d29c635SKip Macy 	INP_LOCK_ASSERT(inp);
2931df9cf830STai-hwa Liang 	*laddr = inp->inp_laddr.s_addr;
2932df9cf830STai-hwa Liang 	*faddr = inp->inp_faddr.s_addr;
29339378e437SKip Macy 	*lp = inp->inp_lport;
29349378e437SKip Macy 	*fp = inp->inp_fport;
29359378e437SKip Macy }
29369378e437SKip Macy 
2937dd0e6c38SKip Macy struct inpcb *
2938dd0e6c38SKip Macy so_sotoinpcb(struct socket *so)
2939dd0e6c38SKip Macy {
2940dd0e6c38SKip Macy 
2941dd0e6c38SKip Macy 	return (sotoinpcb(so));
2942dd0e6c38SKip Macy }
2943dd0e6c38SKip Macy 
2944cc65eb4eSGleb Smirnoff /*
2945cc65eb4eSGleb Smirnoff  * Create an external-format (``xinpcb'') structure using the information in
2946cc65eb4eSGleb Smirnoff  * the kernel-format in_pcb structure pointed to by inp.  This is done to
2947cc65eb4eSGleb Smirnoff  * reduce the spew of irrelevant information over this interface, to isolate
2948cc65eb4eSGleb Smirnoff  * user code from changes in the kernel structure, and potentially to provide
2949cc65eb4eSGleb Smirnoff  * information-hiding if we decide that some of this information should be
2950cc65eb4eSGleb Smirnoff  * hidden from users.
2951cc65eb4eSGleb Smirnoff  */
2952cc65eb4eSGleb Smirnoff void
2953cc65eb4eSGleb Smirnoff in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2954cc65eb4eSGleb Smirnoff {
2955cc65eb4eSGleb Smirnoff 
295679db6fe7SMark Johnston 	bzero(xi, sizeof(*xi));
2957cc65eb4eSGleb Smirnoff 	xi->xi_len = sizeof(struct xinpcb);
2958cc65eb4eSGleb Smirnoff 	if (inp->inp_socket)
2959cc65eb4eSGleb Smirnoff 		sotoxsocket(inp->inp_socket, &xi->xi_socket);
2960cc65eb4eSGleb Smirnoff 	bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2961cc65eb4eSGleb Smirnoff 	xi->inp_gencnt = inp->inp_gencnt;
29623a20f06aSBrooks Davis 	xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2963cc65eb4eSGleb Smirnoff 	xi->inp_flow = inp->inp_flow;
2964cc65eb4eSGleb Smirnoff 	xi->inp_flowid = inp->inp_flowid;
2965cc65eb4eSGleb Smirnoff 	xi->inp_flowtype = inp->inp_flowtype;
2966cc65eb4eSGleb Smirnoff 	xi->inp_flags = inp->inp_flags;
2967cc65eb4eSGleb Smirnoff 	xi->inp_flags2 = inp->inp_flags2;
2968cc65eb4eSGleb Smirnoff 	xi->in6p_cksum = inp->in6p_cksum;
2969cc65eb4eSGleb Smirnoff 	xi->in6p_hops = inp->in6p_hops;
2970cc65eb4eSGleb Smirnoff 	xi->inp_ip_tos = inp->inp_ip_tos;
2971cc65eb4eSGleb Smirnoff 	xi->inp_vflag = inp->inp_vflag;
2972cc65eb4eSGleb Smirnoff 	xi->inp_ip_ttl = inp->inp_ip_ttl;
2973cc65eb4eSGleb Smirnoff 	xi->inp_ip_p = inp->inp_ip_p;
2974cc65eb4eSGleb Smirnoff 	xi->inp_ip_minttl = inp->inp_ip_minttl;
2975cc65eb4eSGleb Smirnoff }
2976cc65eb4eSGleb Smirnoff 
2977a35bdd44SMichael Tuexen int
2978a35bdd44SMichael Tuexen sysctl_setsockopt(SYSCTL_HANDLER_ARGS, struct inpcbinfo *pcbinfo,
2979a35bdd44SMichael Tuexen     int (*ctloutput_set)(struct inpcb *, struct sockopt *))
2980a35bdd44SMichael Tuexen {
2981a35bdd44SMichael Tuexen 	struct sockopt sopt;
2982a35bdd44SMichael Tuexen 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2983a35bdd44SMichael Tuexen 	    INPLOOKUP_WLOCKPCB);
2984a35bdd44SMichael Tuexen 	struct inpcb *inp;
2985a35bdd44SMichael Tuexen 	struct sockopt_parameters *params;
2986a35bdd44SMichael Tuexen 	struct socket *so;
2987a35bdd44SMichael Tuexen 	int error;
2988a35bdd44SMichael Tuexen 	char buf[1024];
2989a35bdd44SMichael Tuexen 
2990a35bdd44SMichael Tuexen 	if (req->oldptr != NULL || req->oldlen != 0)
2991a35bdd44SMichael Tuexen 		return (EINVAL);
2992a35bdd44SMichael Tuexen 	if (req->newptr == NULL)
2993a35bdd44SMichael Tuexen 		return (EPERM);
2994a35bdd44SMichael Tuexen 	if (req->newlen > sizeof(buf))
2995a35bdd44SMichael Tuexen 		return (ENOMEM);
2996a35bdd44SMichael Tuexen 	error = SYSCTL_IN(req, buf, req->newlen);
2997a35bdd44SMichael Tuexen 	if (error != 0)
2998a35bdd44SMichael Tuexen 		return (error);
2999a35bdd44SMichael Tuexen 	if (req->newlen < sizeof(struct sockopt_parameters))
3000a35bdd44SMichael Tuexen 		return (EINVAL);
3001a35bdd44SMichael Tuexen 	params = (struct sockopt_parameters *)buf;
3002a35bdd44SMichael Tuexen 	sopt.sopt_level = params->sop_level;
3003a35bdd44SMichael Tuexen 	sopt.sopt_name = params->sop_optname;
3004a35bdd44SMichael Tuexen 	sopt.sopt_dir = SOPT_SET;
3005a35bdd44SMichael Tuexen 	sopt.sopt_val = params->sop_optval;
3006a35bdd44SMichael Tuexen 	sopt.sopt_valsize = req->newlen - sizeof(struct sockopt_parameters);
3007a35bdd44SMichael Tuexen 	sopt.sopt_td = NULL;
3008a0aeb1ceSMichael Tuexen #ifdef INET6
3009a35bdd44SMichael Tuexen 	if (params->sop_inc.inc_flags & INC_ISIPV6) {
3010a35bdd44SMichael Tuexen 		if (IN6_IS_SCOPE_LINKLOCAL(&params->sop_inc.inc6_laddr))
3011a35bdd44SMichael Tuexen 			params->sop_inc.inc6_laddr.s6_addr16[1] =
3012a35bdd44SMichael Tuexen 			    htons(params->sop_inc.inc6_zoneid & 0xffff);
3013a35bdd44SMichael Tuexen 		if (IN6_IS_SCOPE_LINKLOCAL(&params->sop_inc.inc6_faddr))
3014a35bdd44SMichael Tuexen 			params->sop_inc.inc6_faddr.s6_addr16[1] =
3015a35bdd44SMichael Tuexen 			    htons(params->sop_inc.inc6_zoneid & 0xffff);
3016a35bdd44SMichael Tuexen 	}
3017a0aeb1ceSMichael Tuexen #endif
3018a35bdd44SMichael Tuexen 	if (params->sop_inc.inc_lport != htons(0)) {
3019a35bdd44SMichael Tuexen 		if (params->sop_inc.inc_fport == htons(0))
3020a35bdd44SMichael Tuexen 			inpi.hash = INP_PCBHASH_WILD(params->sop_inc.inc_lport,
3021a35bdd44SMichael Tuexen 			    pcbinfo->ipi_hashmask);
3022a35bdd44SMichael Tuexen 		else
3023a0aeb1ceSMichael Tuexen #ifdef INET6
3024a35bdd44SMichael Tuexen 			if (params->sop_inc.inc_flags & INC_ISIPV6)
3025a35bdd44SMichael Tuexen 				inpi.hash = INP6_PCBHASH(
3026a35bdd44SMichael Tuexen 				    &params->sop_inc.inc6_faddr,
3027a35bdd44SMichael Tuexen 				    params->sop_inc.inc_lport,
3028a35bdd44SMichael Tuexen 				    params->sop_inc.inc_fport,
3029a35bdd44SMichael Tuexen 				    pcbinfo->ipi_hashmask);
3030a35bdd44SMichael Tuexen 			else
3031a0aeb1ceSMichael Tuexen #endif
3032a35bdd44SMichael Tuexen 				inpi.hash = INP_PCBHASH(
3033a35bdd44SMichael Tuexen 				    &params->sop_inc.inc_faddr,
3034a35bdd44SMichael Tuexen 				    params->sop_inc.inc_lport,
3035a35bdd44SMichael Tuexen 				    params->sop_inc.inc_fport,
3036a35bdd44SMichael Tuexen 				    pcbinfo->ipi_hashmask);
3037a35bdd44SMichael Tuexen 	}
3038a35bdd44SMichael Tuexen 	while ((inp = inp_next(&inpi)) != NULL)
3039a35bdd44SMichael Tuexen 		if (inp->inp_gencnt == params->sop_id) {
304053af6903SGleb Smirnoff 			if (inp->inp_flags & INP_DROPPED) {
3041a35bdd44SMichael Tuexen 				INP_WUNLOCK(inp);
3042a35bdd44SMichael Tuexen 				return (ECONNRESET);
3043a35bdd44SMichael Tuexen 			}
3044a35bdd44SMichael Tuexen 			so = inp->inp_socket;
3045a35bdd44SMichael Tuexen 			KASSERT(so != NULL, ("inp_socket == NULL"));
3046a35bdd44SMichael Tuexen 			soref(so);
3047a35bdd44SMichael Tuexen 			error = (*ctloutput_set)(inp, &sopt);
3048a35bdd44SMichael Tuexen 			sorele(so);
3049a35bdd44SMichael Tuexen 			break;
3050a35bdd44SMichael Tuexen 		}
3051a35bdd44SMichael Tuexen 	if (inp == NULL)
3052a35bdd44SMichael Tuexen 		error = ESRCH;
3053a35bdd44SMichael Tuexen 	return (error);
3054a35bdd44SMichael Tuexen }
3055a35bdd44SMichael Tuexen 
3056497057eeSRobert Watson #ifdef DDB
3057497057eeSRobert Watson static void
3058497057eeSRobert Watson db_print_indent(int indent)
3059497057eeSRobert Watson {
3060497057eeSRobert Watson 	int i;
3061497057eeSRobert Watson 
3062497057eeSRobert Watson 	for (i = 0; i < indent; i++)
3063497057eeSRobert Watson 		db_printf(" ");
3064497057eeSRobert Watson }
3065497057eeSRobert Watson 
3066497057eeSRobert Watson static void
3067497057eeSRobert Watson db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3068497057eeSRobert Watson {
3069497057eeSRobert Watson 	char faddr_str[48], laddr_str[48];
3070497057eeSRobert Watson 
3071497057eeSRobert Watson 	db_print_indent(indent);
3072497057eeSRobert Watson 	db_printf("%s at %p\n", name, inc);
3073497057eeSRobert Watson 
3074497057eeSRobert Watson 	indent += 2;
3075497057eeSRobert Watson 
307603dc38a4SRobert Watson #ifdef INET6
3077dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
3078497057eeSRobert Watson 		/* IPv6. */
3079497057eeSRobert Watson 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
3080497057eeSRobert Watson 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
308183e521ecSBjoern A. Zeeb 	} else
308203dc38a4SRobert Watson #endif
308383e521ecSBjoern A. Zeeb 	{
3084497057eeSRobert Watson 		/* IPv4. */
3085497057eeSRobert Watson 		inet_ntoa_r(inc->inc_laddr, laddr_str);
3086497057eeSRobert Watson 		inet_ntoa_r(inc->inc_faddr, faddr_str);
3087497057eeSRobert Watson 	}
3088497057eeSRobert Watson 	db_print_indent(indent);
3089497057eeSRobert Watson 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
3090497057eeSRobert Watson 	    ntohs(inc->inc_lport));
3091497057eeSRobert Watson 	db_print_indent(indent);
3092497057eeSRobert Watson 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
3093497057eeSRobert Watson 	    ntohs(inc->inc_fport));
3094497057eeSRobert Watson }
3095497057eeSRobert Watson 
3096497057eeSRobert Watson static void
3097497057eeSRobert Watson db_print_inpflags(int inp_flags)
3098497057eeSRobert Watson {
3099497057eeSRobert Watson 	int comma;
3100497057eeSRobert Watson 
3101497057eeSRobert Watson 	comma = 0;
3102497057eeSRobert Watson 	if (inp_flags & INP_RECVOPTS) {
3103497057eeSRobert Watson 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3104497057eeSRobert Watson 		comma = 1;
3105497057eeSRobert Watson 	}
3106497057eeSRobert Watson 	if (inp_flags & INP_RECVRETOPTS) {
3107497057eeSRobert Watson 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3108497057eeSRobert Watson 		comma = 1;
3109497057eeSRobert Watson 	}
3110497057eeSRobert Watson 	if (inp_flags & INP_RECVDSTADDR) {
3111497057eeSRobert Watson 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3112497057eeSRobert Watson 		comma = 1;
3113497057eeSRobert Watson 	}
3114dce33a45SErmal Luçi 	if (inp_flags & INP_ORIGDSTADDR) {
3115dce33a45SErmal Luçi 		db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3116dce33a45SErmal Luçi 		comma = 1;
3117dce33a45SErmal Luçi 	}
3118497057eeSRobert Watson 	if (inp_flags & INP_HDRINCL) {
3119497057eeSRobert Watson 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
3120497057eeSRobert Watson 		comma = 1;
3121497057eeSRobert Watson 	}
3122497057eeSRobert Watson 	if (inp_flags & INP_HIGHPORT) {
3123497057eeSRobert Watson 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3124497057eeSRobert Watson 		comma = 1;
3125497057eeSRobert Watson 	}
3126497057eeSRobert Watson 	if (inp_flags & INP_LOWPORT) {
3127497057eeSRobert Watson 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
3128497057eeSRobert Watson 		comma = 1;
3129497057eeSRobert Watson 	}
3130497057eeSRobert Watson 	if (inp_flags & INP_ANONPORT) {
3131497057eeSRobert Watson 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
3132497057eeSRobert Watson 		comma = 1;
3133497057eeSRobert Watson 	}
3134497057eeSRobert Watson 	if (inp_flags & INP_RECVIF) {
3135497057eeSRobert Watson 		db_printf("%sINP_RECVIF", comma ? ", " : "");
3136497057eeSRobert Watson 		comma = 1;
3137497057eeSRobert Watson 	}
3138497057eeSRobert Watson 	if (inp_flags & INP_MTUDISC) {
3139497057eeSRobert Watson 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
3140497057eeSRobert Watson 		comma = 1;
3141497057eeSRobert Watson 	}
3142497057eeSRobert Watson 	if (inp_flags & INP_RECVTTL) {
3143497057eeSRobert Watson 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
3144497057eeSRobert Watson 		comma = 1;
3145497057eeSRobert Watson 	}
3146497057eeSRobert Watson 	if (inp_flags & INP_DONTFRAG) {
3147497057eeSRobert Watson 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3148497057eeSRobert Watson 		comma = 1;
3149497057eeSRobert Watson 	}
31503cca425bSMichael Tuexen 	if (inp_flags & INP_RECVTOS) {
31513cca425bSMichael Tuexen 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
31523cca425bSMichael Tuexen 		comma = 1;
31533cca425bSMichael Tuexen 	}
3154497057eeSRobert Watson 	if (inp_flags & IN6P_IPV6_V6ONLY) {
3155497057eeSRobert Watson 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3156497057eeSRobert Watson 		comma = 1;
3157497057eeSRobert Watson 	}
3158497057eeSRobert Watson 	if (inp_flags & IN6P_PKTINFO) {
3159497057eeSRobert Watson 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3160497057eeSRobert Watson 		comma = 1;
3161497057eeSRobert Watson 	}
3162497057eeSRobert Watson 	if (inp_flags & IN6P_HOPLIMIT) {
3163497057eeSRobert Watson 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3164497057eeSRobert Watson 		comma = 1;
3165497057eeSRobert Watson 	}
3166497057eeSRobert Watson 	if (inp_flags & IN6P_HOPOPTS) {
3167497057eeSRobert Watson 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3168497057eeSRobert Watson 		comma = 1;
3169497057eeSRobert Watson 	}
3170497057eeSRobert Watson 	if (inp_flags & IN6P_DSTOPTS) {
3171497057eeSRobert Watson 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3172497057eeSRobert Watson 		comma = 1;
3173497057eeSRobert Watson 	}
3174497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDR) {
3175497057eeSRobert Watson 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3176497057eeSRobert Watson 		comma = 1;
3177497057eeSRobert Watson 	}
3178497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
3179497057eeSRobert Watson 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3180497057eeSRobert Watson 		comma = 1;
3181497057eeSRobert Watson 	}
3182497057eeSRobert Watson 	if (inp_flags & IN6P_TCLASS) {
3183497057eeSRobert Watson 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3184497057eeSRobert Watson 		comma = 1;
3185497057eeSRobert Watson 	}
3186497057eeSRobert Watson 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
3187497057eeSRobert Watson 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3188497057eeSRobert Watson 		comma = 1;
3189497057eeSRobert Watson 	}
3190ad71fe3cSRobert Watson 	if (inp_flags & INP_ONESBCAST) {
3191ad71fe3cSRobert Watson 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3192ad71fe3cSRobert Watson 		comma  = 1;
3193ad71fe3cSRobert Watson 	}
3194ad71fe3cSRobert Watson 	if (inp_flags & INP_DROPPED) {
3195ad71fe3cSRobert Watson 		db_printf("%sINP_DROPPED", comma ? ", " : "");
3196ad71fe3cSRobert Watson 		comma  = 1;
3197ad71fe3cSRobert Watson 	}
3198ad71fe3cSRobert Watson 	if (inp_flags & INP_SOCKREF) {
3199ad71fe3cSRobert Watson 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
3200ad71fe3cSRobert Watson 		comma  = 1;
3201ad71fe3cSRobert Watson 	}
3202497057eeSRobert Watson 	if (inp_flags & IN6P_RFC2292) {
3203497057eeSRobert Watson 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3204497057eeSRobert Watson 		comma = 1;
3205497057eeSRobert Watson 	}
3206497057eeSRobert Watson 	if (inp_flags & IN6P_MTU) {
3207497057eeSRobert Watson 		db_printf("IN6P_MTU%s", comma ? ", " : "");
3208497057eeSRobert Watson 		comma = 1;
3209497057eeSRobert Watson 	}
3210497057eeSRobert Watson }
3211497057eeSRobert Watson 
3212497057eeSRobert Watson static void
3213497057eeSRobert Watson db_print_inpvflag(u_char inp_vflag)
3214497057eeSRobert Watson {
3215497057eeSRobert Watson 	int comma;
3216497057eeSRobert Watson 
3217497057eeSRobert Watson 	comma = 0;
3218497057eeSRobert Watson 	if (inp_vflag & INP_IPV4) {
3219497057eeSRobert Watson 		db_printf("%sINP_IPV4", comma ? ", " : "");
3220497057eeSRobert Watson 		comma  = 1;
3221497057eeSRobert Watson 	}
3222497057eeSRobert Watson 	if (inp_vflag & INP_IPV6) {
3223497057eeSRobert Watson 		db_printf("%sINP_IPV6", comma ? ", " : "");
3224497057eeSRobert Watson 		comma  = 1;
3225497057eeSRobert Watson 	}
3226497057eeSRobert Watson 	if (inp_vflag & INP_IPV6PROTO) {
3227497057eeSRobert Watson 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3228497057eeSRobert Watson 		comma  = 1;
3229497057eeSRobert Watson 	}
3230497057eeSRobert Watson }
3231497057eeSRobert Watson 
32326d888973SRobert Watson static void
3233497057eeSRobert Watson db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3234497057eeSRobert Watson {
3235497057eeSRobert Watson 
3236497057eeSRobert Watson 	db_print_indent(indent);
3237497057eeSRobert Watson 	db_printf("%s at %p\n", name, inp);
3238497057eeSRobert Watson 
3239497057eeSRobert Watson 	indent += 2;
3240497057eeSRobert Watson 
3241497057eeSRobert Watson 	db_print_indent(indent);
3242497057eeSRobert Watson 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3243497057eeSRobert Watson 
3244497057eeSRobert Watson 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3245497057eeSRobert Watson 
3246497057eeSRobert Watson 	db_print_indent(indent);
3247497057eeSRobert Watson 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
3248497057eeSRobert Watson 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3249497057eeSRobert Watson 
3250497057eeSRobert Watson 	db_print_indent(indent);
3251497057eeSRobert Watson 	db_printf("inp_label: %p   inp_flags: 0x%x (",
3252497057eeSRobert Watson 	   inp->inp_label, inp->inp_flags);
3253497057eeSRobert Watson 	db_print_inpflags(inp->inp_flags);
3254497057eeSRobert Watson 	db_printf(")\n");
3255497057eeSRobert Watson 
3256497057eeSRobert Watson 	db_print_indent(indent);
3257497057eeSRobert Watson 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3258497057eeSRobert Watson 	    inp->inp_vflag);
3259497057eeSRobert Watson 	db_print_inpvflag(inp->inp_vflag);
3260497057eeSRobert Watson 	db_printf(")\n");
3261497057eeSRobert Watson 
3262497057eeSRobert Watson 	db_print_indent(indent);
3263497057eeSRobert Watson 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3264497057eeSRobert Watson 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3265497057eeSRobert Watson 
3266497057eeSRobert Watson 	db_print_indent(indent);
3267497057eeSRobert Watson #ifdef INET6
3268497057eeSRobert Watson 	if (inp->inp_vflag & INP_IPV6) {
3269497057eeSRobert Watson 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
3270497057eeSRobert Watson 		    "in6p_moptions: %p\n", inp->in6p_options,
3271497057eeSRobert Watson 		    inp->in6p_outputopts, inp->in6p_moptions);
3272497057eeSRobert Watson 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3273497057eeSRobert Watson 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3274497057eeSRobert Watson 		    inp->in6p_hops);
3275497057eeSRobert Watson 	} else
3276497057eeSRobert Watson #endif
3277497057eeSRobert Watson 	{
3278497057eeSRobert Watson 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3279497057eeSRobert Watson 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3280497057eeSRobert Watson 		    inp->inp_options, inp->inp_moptions);
3281497057eeSRobert Watson 	}
3282497057eeSRobert Watson 
3283497057eeSRobert Watson 	db_print_indent(indent);
3284497057eeSRobert Watson 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
3285497057eeSRobert Watson 	    (uintmax_t)inp->inp_gencnt);
3286497057eeSRobert Watson }
3287497057eeSRobert Watson 
3288497057eeSRobert Watson DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3289497057eeSRobert Watson {
3290497057eeSRobert Watson 	struct inpcb *inp;
3291497057eeSRobert Watson 
3292497057eeSRobert Watson 	if (!have_addr) {
3293497057eeSRobert Watson 		db_printf("usage: show inpcb <addr>\n");
3294497057eeSRobert Watson 		return;
3295497057eeSRobert Watson 	}
3296497057eeSRobert Watson 	inp = (struct inpcb *)addr;
3297497057eeSRobert Watson 
3298497057eeSRobert Watson 	db_print_inpcb(inp, "inpcb", 0);
3299497057eeSRobert Watson }
330083e521ecSBjoern A. Zeeb #endif /* DDB */
3301f3e7afe2SHans Petter Selasky 
3302f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
3303f3e7afe2SHans Petter Selasky /*
3304f3e7afe2SHans Petter Selasky  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3305f3e7afe2SHans Petter Selasky  * if any.
3306f3e7afe2SHans Petter Selasky  */
3307f3e7afe2SHans Petter Selasky int
3308f3e7afe2SHans Petter Selasky in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3309f3e7afe2SHans Petter Selasky {
3310f3e7afe2SHans Petter Selasky 	union if_snd_tag_modify_params params = {
3311f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
331220abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3313f3e7afe2SHans Petter Selasky 	};
3314f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3315f3e7afe2SHans Petter Selasky 	int error;
3316f3e7afe2SHans Petter Selasky 
3317f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3318f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3319f3e7afe2SHans Petter Selasky 		return (EINVAL);
3320f3e7afe2SHans Petter Selasky 
3321c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_modify == NULL) {
3322f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3323f3e7afe2SHans Petter Selasky 	} else {
3324c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_modify(mst, &params);
3325f3e7afe2SHans Petter Selasky 	}
3326f3e7afe2SHans Petter Selasky 	return (error);
3327f3e7afe2SHans Petter Selasky }
3328f3e7afe2SHans Petter Selasky 
3329f3e7afe2SHans Petter Selasky /*
3330f3e7afe2SHans Petter Selasky  * Query existing TX rate limit based on the existing
3331f3e7afe2SHans Petter Selasky  * "inp->inp_snd_tag", if any.
3332f3e7afe2SHans Petter Selasky  */
3333f3e7afe2SHans Petter Selasky int
3334f3e7afe2SHans Petter Selasky in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3335f3e7afe2SHans Petter Selasky {
3336f3e7afe2SHans Petter Selasky 	union if_snd_tag_query_params params = { };
3337f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3338f3e7afe2SHans Petter Selasky 	int error;
3339f3e7afe2SHans Petter Selasky 
3340f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3341f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3342f3e7afe2SHans Petter Selasky 		return (EINVAL);
3343f3e7afe2SHans Petter Selasky 
3344c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL) {
3345f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3346f3e7afe2SHans Petter Selasky 	} else {
3347c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_query(mst, &params);
3348f3e7afe2SHans Petter Selasky 		if (error == 0 && p_max_pacing_rate != NULL)
3349f3e7afe2SHans Petter Selasky 			*p_max_pacing_rate = params.rate_limit.max_rate;
3350f3e7afe2SHans Petter Selasky 	}
3351f3e7afe2SHans Petter Selasky 	return (error);
3352f3e7afe2SHans Petter Selasky }
3353f3e7afe2SHans Petter Selasky 
3354f3e7afe2SHans Petter Selasky /*
335595ed5015SHans Petter Selasky  * Query existing TX queue level based on the existing
335695ed5015SHans Petter Selasky  * "inp->inp_snd_tag", if any.
335795ed5015SHans Petter Selasky  */
335895ed5015SHans Petter Selasky int
335995ed5015SHans Petter Selasky in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
336095ed5015SHans Petter Selasky {
336195ed5015SHans Petter Selasky 	union if_snd_tag_query_params params = { };
336295ed5015SHans Petter Selasky 	struct m_snd_tag *mst;
336395ed5015SHans Petter Selasky 	int error;
336495ed5015SHans Petter Selasky 
336595ed5015SHans Petter Selasky 	mst = inp->inp_snd_tag;
336695ed5015SHans Petter Selasky 	if (mst == NULL)
336795ed5015SHans Petter Selasky 		return (EINVAL);
336895ed5015SHans Petter Selasky 
3369c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL)
337095ed5015SHans Petter Selasky 		return (EOPNOTSUPP);
337195ed5015SHans Petter Selasky 
3372c782ea8bSJohn Baldwin 	error = mst->sw->snd_tag_query(mst, &params);
337395ed5015SHans Petter Selasky 	if (error == 0 && p_txqueue_level != NULL)
337495ed5015SHans Petter Selasky 		*p_txqueue_level = params.rate_limit.queue_level;
337595ed5015SHans Petter Selasky 	return (error);
337695ed5015SHans Petter Selasky }
337795ed5015SHans Petter Selasky 
337895ed5015SHans Petter Selasky /*
3379f3e7afe2SHans Petter Selasky  * Allocate a new TX rate limit send tag from the network interface
3380f3e7afe2SHans Petter Selasky  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3381f3e7afe2SHans Petter Selasky  */
3382f3e7afe2SHans Petter Selasky int
3383f3e7afe2SHans Petter Selasky in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
338420abea66SRandall Stewart     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
338520abea66SRandall Stewart 
3386f3e7afe2SHans Petter Selasky {
3387f3e7afe2SHans Petter Selasky 	union if_snd_tag_alloc_params params = {
338895ed5015SHans Petter Selasky 		.rate_limit.hdr.type = (max_pacing_rate == -1U) ?
338995ed5015SHans Petter Selasky 		    IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3390f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowid = flowid,
3391f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowtype = flowtype,
339298085baeSAndrew Gallatin 		.rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3393f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
339420abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3395f3e7afe2SHans Petter Selasky 	};
3396f3e7afe2SHans Petter Selasky 	int error;
3397f3e7afe2SHans Petter Selasky 
3398f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3399f3e7afe2SHans Petter Selasky 
340085d8d30fSHans Petter Selasky 	/*
340185d8d30fSHans Petter Selasky 	 * If there is already a send tag, or the INP is being torn
340285d8d30fSHans Petter Selasky 	 * down, allocating a new send tag is not allowed. Else send
340385d8d30fSHans Petter Selasky 	 * tags may leak.
340485d8d30fSHans Petter Selasky 	 */
340553af6903SGleb Smirnoff 	if (*st != NULL || (inp->inp_flags & INP_DROPPED) != 0)
3406f3e7afe2SHans Petter Selasky 		return (EINVAL);
3407f3e7afe2SHans Petter Selasky 
340836e0a362SJohn Baldwin 	error = m_snd_tag_alloc(ifp, &params, st);
3409903c4ee6SXin LI #ifdef INET
341020abea66SRandall Stewart 	if (error == 0) {
341120abea66SRandall Stewart 		counter_u64_add(rate_limit_set_ok, 1);
341220abea66SRandall Stewart 		counter_u64_add(rate_limit_active, 1);
341336e0a362SJohn Baldwin 	} else if (error != EOPNOTSUPP)
341420abea66SRandall Stewart 		  counter_u64_add(rate_limit_alloc_fail, 1);
3415903c4ee6SXin LI #endif
3416f3e7afe2SHans Petter Selasky 	return (error);
3417f3e7afe2SHans Petter Selasky }
3418f3e7afe2SHans Petter Selasky 
341920abea66SRandall Stewart void
342098d7a8d9SJohn Baldwin in_pcbdetach_tag(struct m_snd_tag *mst)
342120abea66SRandall Stewart {
342220abea66SRandall Stewart 
342398d7a8d9SJohn Baldwin 	m_snd_tag_rele(mst);
3424903c4ee6SXin LI #ifdef INET
342520abea66SRandall Stewart 	counter_u64_add(rate_limit_active, -1);
3426903c4ee6SXin LI #endif
342720abea66SRandall Stewart }
342820abea66SRandall Stewart 
3429f3e7afe2SHans Petter Selasky /*
3430f3e7afe2SHans Petter Selasky  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3431f3e7afe2SHans Petter Selasky  * if any:
3432f3e7afe2SHans Petter Selasky  */
3433f3e7afe2SHans Petter Selasky void
3434f3e7afe2SHans Petter Selasky in_pcbdetach_txrtlmt(struct inpcb *inp)
3435f3e7afe2SHans Petter Selasky {
3436f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3437f3e7afe2SHans Petter Selasky 
3438f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3439f3e7afe2SHans Petter Selasky 
3440f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3441f3e7afe2SHans Petter Selasky 	inp->inp_snd_tag = NULL;
3442f3e7afe2SHans Petter Selasky 
3443f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3444f3e7afe2SHans Petter Selasky 		return;
3445f3e7afe2SHans Petter Selasky 
3446fb3bc596SJohn Baldwin 	m_snd_tag_rele(mst);
3447093e7231SHans Petter Selasky #ifdef INET
3448093e7231SHans Petter Selasky 	counter_u64_add(rate_limit_active, -1);
3449093e7231SHans Petter Selasky #endif
3450f3e7afe2SHans Petter Selasky }
3451f3e7afe2SHans Petter Selasky 
345220abea66SRandall Stewart int
345320abea66SRandall Stewart in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
345420abea66SRandall Stewart {
345520abea66SRandall Stewart 	int error;
345620abea66SRandall Stewart 
345720abea66SRandall Stewart 	/*
345820abea66SRandall Stewart 	 * If the existing send tag is for the wrong interface due to
345920abea66SRandall Stewart 	 * a route change, first drop the existing tag.  Set the
346020abea66SRandall Stewart 	 * CHANGED flag so that we will keep trying to allocate a new
346120abea66SRandall Stewart 	 * tag if we fail to allocate one this time.
346220abea66SRandall Stewart 	 */
346320abea66SRandall Stewart 	if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
346420abea66SRandall Stewart 		in_pcbdetach_txrtlmt(inp);
346520abea66SRandall Stewart 		inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
346620abea66SRandall Stewart 	}
346720abea66SRandall Stewart 
346820abea66SRandall Stewart 	/*
346920abea66SRandall Stewart 	 * NOTE: When attaching to a network interface a reference is
347020abea66SRandall Stewart 	 * made to ensure the network interface doesn't go away until
347120abea66SRandall Stewart 	 * all ratelimit connections are gone. The network interface
347220abea66SRandall Stewart 	 * pointers compared below represent valid network interfaces,
347320abea66SRandall Stewart 	 * except when comparing towards NULL.
347420abea66SRandall Stewart 	 */
347520abea66SRandall Stewart 	if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
347620abea66SRandall Stewart 		error = 0;
347720abea66SRandall Stewart 	} else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
347820abea66SRandall Stewart 		if (inp->inp_snd_tag != NULL)
347920abea66SRandall Stewart 			in_pcbdetach_txrtlmt(inp);
348020abea66SRandall Stewart 		error = 0;
348120abea66SRandall Stewart 	} else if (inp->inp_snd_tag == NULL) {
348220abea66SRandall Stewart 		/*
348320abea66SRandall Stewart 		 * In order to utilize packet pacing with RSS, we need
348420abea66SRandall Stewart 		 * to wait until there is a valid RSS hash before we
348520abea66SRandall Stewart 		 * can proceed:
348620abea66SRandall Stewart 		 */
348720abea66SRandall Stewart 		if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
348820abea66SRandall Stewart 			error = EAGAIN;
348920abea66SRandall Stewart 		} else {
349020abea66SRandall Stewart 			error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
349120abea66SRandall Stewart 			    mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
349220abea66SRandall Stewart 		}
349320abea66SRandall Stewart 	} else {
349420abea66SRandall Stewart 		error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
349520abea66SRandall Stewart 	}
349620abea66SRandall Stewart 	if (error == 0 || error == EOPNOTSUPP)
349720abea66SRandall Stewart 		inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
349820abea66SRandall Stewart 
349920abea66SRandall Stewart 	return (error);
350020abea66SRandall Stewart }
350120abea66SRandall Stewart 
3502f3e7afe2SHans Petter Selasky /*
3503f3e7afe2SHans Petter Selasky  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3504f3e7afe2SHans Petter Selasky  * is set in the fast path and will attach/detach/modify the TX rate
3505f3e7afe2SHans Petter Selasky  * limit send tag based on the socket's so_max_pacing_rate value.
3506f3e7afe2SHans Petter Selasky  */
3507f3e7afe2SHans Petter Selasky void
3508f3e7afe2SHans Petter Selasky in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3509f3e7afe2SHans Petter Selasky {
3510f3e7afe2SHans Petter Selasky 	struct socket *socket;
3511f3e7afe2SHans Petter Selasky 	uint32_t max_pacing_rate;
3512f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3513f3e7afe2SHans Petter Selasky 
3514f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3515f3e7afe2SHans Petter Selasky 		return;
3516f3e7afe2SHans Petter Selasky 
3517f3e7afe2SHans Petter Selasky 	socket = inp->inp_socket;
3518f3e7afe2SHans Petter Selasky 	if (socket == NULL)
3519f3e7afe2SHans Petter Selasky 		return;
3520f3e7afe2SHans Petter Selasky 
3521f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3522f3e7afe2SHans Petter Selasky 		/*
3523f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3524f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3525f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3526f3e7afe2SHans Petter Selasky 		 * write lock.
3527f3e7afe2SHans Petter Selasky 		 */
3528f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3529f3e7afe2SHans Petter Selasky 			return;
3530f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3531f3e7afe2SHans Petter Selasky 	} else {
3532f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3533f3e7afe2SHans Petter Selasky 	}
3534f3e7afe2SHans Petter Selasky 
3535f3e7afe2SHans Petter Selasky 	/*
3536f3e7afe2SHans Petter Selasky 	 * NOTE: The so_max_pacing_rate value is read unlocked,
3537f3e7afe2SHans Petter Selasky 	 * because atomic updates are not required since the variable
3538f3e7afe2SHans Petter Selasky 	 * is checked at every mbuf we send. It is assumed that the
3539f3e7afe2SHans Petter Selasky 	 * variable read itself will be atomic.
3540f3e7afe2SHans Petter Selasky 	 */
3541f3e7afe2SHans Petter Selasky 	max_pacing_rate = socket->so_max_pacing_rate;
3542f3e7afe2SHans Petter Selasky 
3543bab34d63SJohn Baldwin 	in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3544fb3bc596SJohn Baldwin 
3545f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3546f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3547f3e7afe2SHans Petter Selasky }
3548f3e7afe2SHans Petter Selasky 
3549f3e7afe2SHans Petter Selasky /*
3550f3e7afe2SHans Petter Selasky  * Track route changes for TX rate limiting.
3551f3e7afe2SHans Petter Selasky  */
3552f3e7afe2SHans Petter Selasky void
3553f3e7afe2SHans Petter Selasky in_pcboutput_eagain(struct inpcb *inp)
3554f3e7afe2SHans Petter Selasky {
3555f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3556f3e7afe2SHans Petter Selasky 
3557f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3558f3e7afe2SHans Petter Selasky 		return;
3559f3e7afe2SHans Petter Selasky 
3560f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag == NULL)
3561f3e7afe2SHans Petter Selasky 		return;
3562f3e7afe2SHans Petter Selasky 
3563f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3564f3e7afe2SHans Petter Selasky 		/*
3565f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3566f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3567f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3568f3e7afe2SHans Petter Selasky 		 * write lock.
3569f3e7afe2SHans Petter Selasky 		 */
3570f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3571f3e7afe2SHans Petter Selasky 			return;
3572f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3573f3e7afe2SHans Petter Selasky 	} else {
3574f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3575f3e7afe2SHans Petter Selasky 	}
3576f3e7afe2SHans Petter Selasky 
3577f3e7afe2SHans Petter Selasky 	/* detach rate limiting */
3578f3e7afe2SHans Petter Selasky 	in_pcbdetach_txrtlmt(inp);
3579f3e7afe2SHans Petter Selasky 
3580f3e7afe2SHans Petter Selasky 	/* make sure new mbuf send tag allocation is made */
3581f3e7afe2SHans Petter Selasky 	inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3582f3e7afe2SHans Petter Selasky 
3583f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3584f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3585f3e7afe2SHans Petter Selasky }
358620abea66SRandall Stewart 
3587903c4ee6SXin LI #ifdef INET
358820abea66SRandall Stewart static void
358920abea66SRandall Stewart rl_init(void *st)
359020abea66SRandall Stewart {
35911a714ff2SRandall Stewart 	rate_limit_new = counter_u64_alloc(M_WAITOK);
35921a714ff2SRandall Stewart 	rate_limit_chg = counter_u64_alloc(M_WAITOK);
359320abea66SRandall Stewart 	rate_limit_active = counter_u64_alloc(M_WAITOK);
359420abea66SRandall Stewart 	rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
359520abea66SRandall Stewart 	rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
359620abea66SRandall Stewart }
359720abea66SRandall Stewart 
359820abea66SRandall Stewart SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3599903c4ee6SXin LI #endif
3600f3e7afe2SHans Petter Selasky #endif /* RATELIMIT */
3601