xref: /freebsd/sys/netinet/in_pcb.c (revision c56e75390e33d31f4e3d1d9d8725b3c293e2feba)
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  */
38df8bae1dSRodney W. Grimes 
394b421e2dSMike Silbersack #include <sys/cdefs.h>
40497057eeSRobert Watson #include "opt_ddb.h"
416a800098SYoshinobu Inoue #include "opt_ipsec.h"
42efc76f72SBjoern A. Zeeb #include "opt_inet.h"
43cfa1ca9dSYoshinobu Inoue #include "opt_inet6.h"
44f3e7afe2SHans Petter Selasky #include "opt_ratelimit.h"
450c325f53SAlexander V. Chernikov #include "opt_route.h"
467527624eSRobert Watson #include "opt_rss.h"
47cfa1ca9dSYoshinobu Inoue 
48df8bae1dSRodney W. Grimes #include <sys/param.h>
49a0577692SGleb Smirnoff #include <sys/hash.h>
50df8bae1dSRodney W. Grimes #include <sys/systm.h>
51a0577692SGleb Smirnoff #include <sys/libkern.h>
52cc0a3c8cSAndrey V. Elsukov #include <sys/lock.h>
53df8bae1dSRodney W. Grimes #include <sys/malloc.h>
54df8bae1dSRodney W. Grimes #include <sys/mbuf.h>
55ea8d1492SAlexander V. Chernikov #include <sys/eventhandler.h>
56cfa1ca9dSYoshinobu Inoue #include <sys/domain.h>
57fdb987beSMark Johnston #include <sys/proc.h>
58df8bae1dSRodney W. Grimes #include <sys/protosw.h>
593ee9c3c4SRandall Stewart #include <sys/smp.h>
60fdb987beSMark Johnston #include <sys/smr.h>
61df8bae1dSRodney W. Grimes #include <sys/socket.h>
62df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
63f3e7afe2SHans Petter Selasky #include <sys/sockio.h>
64acd3428bSRobert Watson #include <sys/priv.h>
65df8bae1dSRodney W. Grimes #include <sys/proc.h>
6679bdc6e5SRobert Watson #include <sys/refcount.h>
6775c13541SPoul-Henning Kamp #include <sys/jail.h>
68101f9fc8SPeter Wemm #include <sys/kernel.h>
69101f9fc8SPeter Wemm #include <sys/sysctl.h>
708781d8e9SBruce Evans 
71497057eeSRobert Watson #ifdef DDB
72497057eeSRobert Watson #include <ddb/ddb.h>
73497057eeSRobert Watson #endif
74497057eeSRobert Watson 
7569c2d429SJeff Roberson #include <vm/uma.h>
76a034518aSAndrew Gallatin #include <vm/vm.h>
77df8bae1dSRodney W. Grimes 
78df8bae1dSRodney W. Grimes #include <net/if.h>
7976039bc8SGleb Smirnoff #include <net/if_var.h>
803d0d5b21SJustin Hibbits #include <net/if_private.h>
81cfa1ca9dSYoshinobu Inoue #include <net/if_types.h>
826d768226SGeorge V. Neville-Neil #include <net/if_llatbl.h>
83df8bae1dSRodney W. Grimes #include <net/route.h>
84b2bdc62aSAdrian Chadd #include <net/rss_config.h>
85530c0060SRobert Watson #include <net/vnet.h>
86df8bae1dSRodney W. Grimes 
8767107f45SBjoern A. Zeeb #if defined(INET) || defined(INET6)
88df8bae1dSRodney W. Grimes #include <netinet/in.h>
89df8bae1dSRodney W. Grimes #include <netinet/in_pcb.h>
900f617ae4SGleb Smirnoff #include <netinet/in_pcb_var.h>
9173bebcc5SGleb Smirnoff #include <netinet/tcp.h>
9259854ecfSHans Petter Selasky #ifdef INET
9359854ecfSHans Petter Selasky #include <netinet/in_var.h>
949ac7c6cfSAlexander V. Chernikov #include <netinet/in_fib.h>
9559854ecfSHans Petter Selasky #endif
96df8bae1dSRodney W. Grimes #include <netinet/ip_var.h>
97cfa1ca9dSYoshinobu Inoue #ifdef INET6
98cfa1ca9dSYoshinobu Inoue #include <netinet/ip6.h>
99efc76f72SBjoern A. Zeeb #include <netinet6/in6_pcb.h>
10067107f45SBjoern A. Zeeb #include <netinet6/in6_var.h>
10167107f45SBjoern A. Zeeb #include <netinet6/ip6_var.h>
102cfa1ca9dSYoshinobu Inoue #endif /* INET6 */
1039ac7c6cfSAlexander V. Chernikov #include <net/route/nhop.h>
10459854ecfSHans Petter Selasky #endif
105cfa1ca9dSYoshinobu Inoue 
106fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
107b9234fafSSam Leffler 
108aed55708SRobert Watson #include <security/mac/mac_framework.h>
109aed55708SRobert Watson 
1101a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMIN	8
1111a43cff9SSean Bruno #define	INPCBLBGROUP_SIZMAX	256
112a43e7a96SGleb Smirnoff 
113a43e7a96SGleb Smirnoff #define	INP_FREED	0x00000200	/* Went through in_pcbfree(). */
114a43e7a96SGleb Smirnoff #define	INP_INLBGROUP	0x01000000	/* Inserted into inpcblbgroup. */
1151a43cff9SSean Bruno 
116101f9fc8SPeter Wemm /*
117101f9fc8SPeter Wemm  * These configure the range of local port addresses assigned to
118101f9fc8SPeter Wemm  * "unspecified" outgoing connections/packets/whatever.
119101f9fc8SPeter Wemm  */
120eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
121eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
122eddfbb76SRobert Watson VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
123eddfbb76SRobert Watson VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
124eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
125eddfbb76SRobert Watson VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
126101f9fc8SPeter Wemm 
127b0d22693SCrist J. Clark /*
128b0d22693SCrist J. Clark  * Reserved ports accessible only to root. There are significant
129b0d22693SCrist J. Clark  * security considerations that must be accounted for when changing these,
130b0d22693SCrist J. Clark  * but the security benefits can be great. Please be careful.
131b0d22693SCrist J. Clark  */
132eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
133eddfbb76SRobert Watson VNET_DEFINE(int, ipport_reservedlow);
134b0d22693SCrist J. Clark 
13519acc506SGleb Smirnoff /* Enable random ephemeral port allocation by default. */
13619acc506SGleb Smirnoff VNET_DEFINE(int, ipport_randomized) = 1;
1376ac48b74SMike Silbersack 
138d2025bd0SBjoern A. Zeeb #ifdef INET
139fa046d87SRobert Watson static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
140fa046d87SRobert Watson 			    struct in_addr faddr, u_int fport_arg,
141fa046d87SRobert Watson 			    struct in_addr laddr, u_int lport_arg,
142da806e8dSMark Johnston 			    int lookupflags, uint8_t numa_domain, int fib);
14367107f45SBjoern A. Zeeb 
144bbd42ad0SPeter Wemm #define RANGECHK(var, min, max) \
145bbd42ad0SPeter Wemm 	if ((var) < (min)) { (var) = (min); } \
146bbd42ad0SPeter Wemm 	else if ((var) > (max)) { (var) = (max); }
147bbd42ad0SPeter Wemm 
148bbd42ad0SPeter Wemm static int
14982d9ae4eSPoul-Henning Kamp sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
150bbd42ad0SPeter Wemm {
15130a4ab08SBruce Evans 	int error;
15230a4ab08SBruce Evans 
153f6dfe47aSMarko Zec 	error = sysctl_handle_int(oidp, arg1, arg2, req);
15430a4ab08SBruce Evans 	if (error == 0) {
155603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
156603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
157603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
158603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
159603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
160603724d3SBjoern A. Zeeb 		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
161bbd42ad0SPeter Wemm 	}
16230a4ab08SBruce Evans 	return (error);
163bbd42ad0SPeter Wemm }
164bbd42ad0SPeter Wemm 
165bbd42ad0SPeter Wemm #undef RANGECHK
166bbd42ad0SPeter Wemm 
1677029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange,
1687029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1696472ac3dSEd Schouten     "IP Ports");
17033b3ac06SPeter Wemm 
1716df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
1727029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1737029da5cSPawel Biernacki     &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I",
1747029da5cSPawel Biernacki     "");
1756df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
1767029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1777029da5cSPawel Biernacki     &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I",
1787029da5cSPawel Biernacki     "");
1796df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
1807029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1817029da5cSPawel Biernacki     &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I",
1827029da5cSPawel Biernacki     "");
1836df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
1847029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1857029da5cSPawel Biernacki     &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I",
1867029da5cSPawel Biernacki     "");
1876df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
1887029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1897029da5cSPawel Biernacki     &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I",
1907029da5cSPawel Biernacki     "");
1916df8a710SGleb Smirnoff SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
1927029da5cSPawel Biernacki     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1937029da5cSPawel Biernacki     &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I",
1947029da5cSPawel Biernacki     "");
1956df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
1966df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
1976df8a710SGleb Smirnoff 	&VNET_NAME(ipport_reservedhigh), 0, "");
1986df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
199eddfbb76SRobert Watson 	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
2006df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
2016df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW,
202eddfbb76SRobert Watson 	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
20320abea66SRandall Stewart 
20420abea66SRandall Stewart #ifdef RATELIMIT
2051a714ff2SRandall Stewart counter_u64_t rate_limit_new;
2061a714ff2SRandall Stewart counter_u64_t rate_limit_chg;
20720abea66SRandall Stewart counter_u64_t rate_limit_active;
20820abea66SRandall Stewart counter_u64_t rate_limit_alloc_fail;
20920abea66SRandall Stewart counter_u64_t rate_limit_set_ok;
21020abea66SRandall Stewart 
2117029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_ip, OID_AUTO, rl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
21220abea66SRandall Stewart     "IP Rate Limiting");
21320abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, active, CTLFLAG_RD,
21420abea66SRandall Stewart     &rate_limit_active, "Active rate limited connections");
21520abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, alloc_fail, CTLFLAG_RD,
21620abea66SRandall Stewart    &rate_limit_alloc_fail, "Rate limited connection failures");
21720abea66SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, set_ok, CTLFLAG_RD,
21820abea66SRandall Stewart    &rate_limit_set_ok, "Rate limited setting succeeded");
2191a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, newrl, CTLFLAG_RD,
2201a714ff2SRandall Stewart    &rate_limit_new, "Total Rate limit new attempts");
2211a714ff2SRandall Stewart SYSCTL_COUNTER_U64(_net_inet_ip_rl, OID_AUTO, chgrl, CTLFLAG_RD,
2221a714ff2SRandall Stewart    &rate_limit_chg, "Total Rate limited change attempts");
22320abea66SRandall Stewart #endif /* RATELIMIT */
22420abea66SRandall Stewart 
22583e521ecSBjoern A. Zeeb #endif /* INET */
2260312fbe9SPoul-Henning Kamp 
227a0577692SGleb Smirnoff VNET_DEFINE(uint32_t, in_pcbhashseed);
228a0577692SGleb Smirnoff static void
229a0577692SGleb Smirnoff in_pcbhashseed_init(void)
230a0577692SGleb Smirnoff {
231a0577692SGleb Smirnoff 
232a0577692SGleb Smirnoff 	V_in_pcbhashseed = arc4random();
233a0577692SGleb Smirnoff }
234a0577692SGleb Smirnoff VNET_SYSINIT(in_pcbhashseed_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
235ec6e7677SZhenlei Huang     in_pcbhashseed_init, NULL);
236a0577692SGleb Smirnoff 
2373b62f335SKristof Provost #ifdef INET
238417b35a9SMark Johnston VNET_DEFINE_STATIC(int, connect_inaddr_wild) = 1;
239417b35a9SMark Johnston #define	V_connect_inaddr_wild	VNET(connect_inaddr_wild)
240417b35a9SMark Johnston SYSCTL_INT(_net_inet_ip, OID_AUTO, connect_inaddr_wild,
241417b35a9SMark Johnston     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(connect_inaddr_wild), 0,
242417b35a9SMark Johnston     "Allow connecting to INADDR_ANY or INADDR_BROADCAST for connect(2)");
2433b62f335SKristof Provost #endif
244417b35a9SMark Johnston 
2453ba34b07SGleb Smirnoff static void in_pcbremhash(struct inpcb *);
2463ba34b07SGleb Smirnoff 
247c3229e05SDavid Greenman /*
248c3229e05SDavid Greenman  * in_pcb.c: manage the Protocol Control Blocks.
249c3229e05SDavid Greenman  *
250de35559fSRobert Watson  * NOTE: It is assumed that most of these functions will be called with
251de35559fSRobert Watson  * the pcbinfo lock held, and often, the inpcb lock held, as these utility
252de35559fSRobert Watson  * functions often modify hash chains or addresses in pcbs.
253c3229e05SDavid Greenman  */
254c3229e05SDavid Greenman 
2551a43cff9SSean Bruno static struct inpcblbgroup *
256a600aabeSMark Johnston in_pcblbgroup_alloc(struct ucred *cred, u_char vflag, uint16_t port,
257bbd0084bSMark Johnston     const union in_dependaddr *addr, int size, uint8_t numa_domain, int fib)
2581a43cff9SSean Bruno {
2591a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2601a43cff9SSean Bruno 	size_t bytes;
2611a43cff9SSean Bruno 
2621a43cff9SSean Bruno 	bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
2631a43cff9SSean Bruno 	grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
264d93ec8cbSMark Johnston 	if (grp == NULL)
2651a43cff9SSean Bruno 		return (NULL);
2667cbb6b6eSMark Johnston 	LIST_INIT(&grp->il_pending);
267d93ec8cbSMark Johnston 	grp->il_cred = crhold(cred);
2681a43cff9SSean Bruno 	grp->il_vflag = vflag;
2691a43cff9SSean Bruno 	grp->il_lport = port;
270a034518aSAndrew Gallatin 	grp->il_numa_domain = numa_domain;
271bbd0084bSMark Johnston 	grp->il_fibnum = fib;
2721a43cff9SSean Bruno 	grp->il_dependladdr = *addr;
2731a43cff9SSean Bruno 	grp->il_inpsiz = size;
2741a43cff9SSean Bruno 	return (grp);
2751a43cff9SSean Bruno }
2761a43cff9SSean Bruno 
2771a43cff9SSean Bruno static void
27854af3d0dSMark Johnston in_pcblbgroup_free_deferred(epoch_context_t ctx)
27954af3d0dSMark Johnston {
28054af3d0dSMark Johnston 	struct inpcblbgroup *grp;
28154af3d0dSMark Johnston 
28254af3d0dSMark Johnston 	grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
283d93ec8cbSMark Johnston 	crfree(grp->il_cred);
28454af3d0dSMark Johnston 	free(grp, M_PCB);
28554af3d0dSMark Johnston }
28654af3d0dSMark Johnston 
28754af3d0dSMark Johnston static void
2881a43cff9SSean Bruno in_pcblbgroup_free(struct inpcblbgroup *grp)
2891a43cff9SSean Bruno {
2907cbb6b6eSMark Johnston 	KASSERT(LIST_EMPTY(&grp->il_pending),
2917cbb6b6eSMark Johnston 	    ("local group %p still has pending inps", grp));
2921a43cff9SSean Bruno 
29354af3d0dSMark Johnston 	CK_LIST_REMOVE(grp, il_list);
2942a4bd982SGleb Smirnoff 	NET_EPOCH_CALL(in_pcblbgroup_free_deferred, &grp->il_epoch_ctx);
2951a43cff9SSean Bruno }
2961a43cff9SSean Bruno 
2977cbb6b6eSMark Johnston static struct inpcblbgroup *
2987cbb6b6eSMark Johnston in_pcblbgroup_find(struct inpcb *inp)
2997cbb6b6eSMark Johnston {
3007cbb6b6eSMark Johnston 	struct inpcbinfo *pcbinfo;
3017cbb6b6eSMark Johnston 	struct inpcblbgroup *grp;
3027cbb6b6eSMark Johnston 	struct inpcblbgrouphead *hdr;
3037cbb6b6eSMark Johnston 
3047cbb6b6eSMark Johnston 	INP_LOCK_ASSERT(inp);
3057cbb6b6eSMark Johnston 
3067cbb6b6eSMark Johnston 	pcbinfo = inp->inp_pcbinfo;
3077cbb6b6eSMark Johnston 	INP_HASH_LOCK_ASSERT(pcbinfo);
3087cbb6b6eSMark Johnston 
3097cbb6b6eSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[
3107cbb6b6eSMark Johnston 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
3117cbb6b6eSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
3127cbb6b6eSMark Johnston 		struct inpcb *inp1;
3137cbb6b6eSMark Johnston 
3147cbb6b6eSMark Johnston 		for (unsigned int i = 0; i < grp->il_inpcnt; i++) {
3157cbb6b6eSMark Johnston 			if (inp == grp->il_inp[i])
3167cbb6b6eSMark Johnston 				goto found;
3177cbb6b6eSMark Johnston 		}
3187cbb6b6eSMark Johnston 		LIST_FOREACH(inp1, &grp->il_pending, inp_lbgroup_list) {
3197cbb6b6eSMark Johnston 			if (inp == inp1)
3207cbb6b6eSMark Johnston 				goto found;
3217cbb6b6eSMark Johnston 		}
3227cbb6b6eSMark Johnston 	}
3237cbb6b6eSMark Johnston found:
3247cbb6b6eSMark Johnston 	return (grp);
3257cbb6b6eSMark Johnston }
3267cbb6b6eSMark Johnston 
327a600aabeSMark Johnston static void
328a600aabeSMark Johnston in_pcblbgroup_insert(struct inpcblbgroup *grp, struct inpcb *inp)
329a600aabeSMark Johnston {
330a600aabeSMark Johnston 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
331a600aabeSMark Johnston 	    ("invalid local group size %d and count %d", grp->il_inpsiz,
332a600aabeSMark Johnston 	    grp->il_inpcnt));
333a600aabeSMark Johnston 	INP_WLOCK_ASSERT(inp);
334a600aabeSMark Johnston 
3357cbb6b6eSMark Johnston 	if (inp->inp_socket->so_proto->pr_listen != pr_listen_notsupp &&
3367cbb6b6eSMark Johnston 	    !SOLISTENING(inp->inp_socket)) {
3377cbb6b6eSMark Johnston 		/*
3387cbb6b6eSMark Johnston 		 * If this is a TCP socket, it should not be visible to lbgroup
3397cbb6b6eSMark Johnston 		 * lookups until listen() has been called.
3407cbb6b6eSMark Johnston 		 */
3417cbb6b6eSMark Johnston 		LIST_INSERT_HEAD(&grp->il_pending, inp, inp_lbgroup_list);
3428b3d2c19SMark Johnston 		grp->il_pendcnt++;
3437cbb6b6eSMark Johnston 	} else {
344a600aabeSMark Johnston 		grp->il_inp[grp->il_inpcnt] = inp;
345a600aabeSMark Johnston 
346a600aabeSMark Johnston 		/*
3477cbb6b6eSMark Johnston 		 * Synchronize with in_pcblookup_lbgroup(): make sure that we
3487cbb6b6eSMark Johnston 		 * don't expose a null slot to the lookup path.
349a600aabeSMark Johnston 		 */
350a600aabeSMark Johnston 		atomic_store_rel_int(&grp->il_inpcnt, grp->il_inpcnt + 1);
351a600aabeSMark Johnston 	}
352a600aabeSMark Johnston 
3537cbb6b6eSMark Johnston 	inp->inp_flags |= INP_INLBGROUP;
3547cbb6b6eSMark Johnston }
3557cbb6b6eSMark Johnston 
3561a43cff9SSean Bruno static struct inpcblbgroup *
3571a43cff9SSean Bruno in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
3581a43cff9SSean Bruno     struct inpcblbgroup *old_grp, int size)
3591a43cff9SSean Bruno {
3601a43cff9SSean Bruno 	struct inpcblbgroup *grp;
3611a43cff9SSean Bruno 	int i;
3621a43cff9SSean Bruno 
363a600aabeSMark Johnston 	grp = in_pcblbgroup_alloc(old_grp->il_cred, old_grp->il_vflag,
364a034518aSAndrew Gallatin 	    old_grp->il_lport, &old_grp->il_dependladdr, size,
365bbd0084bSMark Johnston 	    old_grp->il_numa_domain, old_grp->il_fibnum);
36679ee680bSMark Johnston 	if (grp == NULL)
3671a43cff9SSean Bruno 		return (NULL);
3681a43cff9SSean Bruno 
3691a43cff9SSean Bruno 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
3701a43cff9SSean Bruno 	    ("invalid new local group size %d and old local group count %d",
3711a43cff9SSean Bruno 	     grp->il_inpsiz, old_grp->il_inpcnt));
3721a43cff9SSean Bruno 
3731a43cff9SSean Bruno 	for (i = 0; i < old_grp->il_inpcnt; ++i)
3741a43cff9SSean Bruno 		grp->il_inp[i] = old_grp->il_inp[i];
3751a43cff9SSean Bruno 	grp->il_inpcnt = old_grp->il_inpcnt;
376a600aabeSMark Johnston 	CK_LIST_INSERT_HEAD(hdr, grp, il_list);
3777cbb6b6eSMark Johnston 	LIST_SWAP(&old_grp->il_pending, &grp->il_pending, inpcb,
3787cbb6b6eSMark Johnston 	    inp_lbgroup_list);
3798b3d2c19SMark Johnston 	grp->il_pendcnt = old_grp->il_pendcnt;
3808b3d2c19SMark Johnston 	old_grp->il_pendcnt = 0;
3811a43cff9SSean Bruno 	in_pcblbgroup_free(old_grp);
3821a43cff9SSean Bruno 	return (grp);
3831a43cff9SSean Bruno }
3841a43cff9SSean Bruno 
3851a43cff9SSean Bruno /*
3861a43cff9SSean Bruno  * Add PCB to load balance group for SO_REUSEPORT_LB option.
3871a43cff9SSean Bruno  */
3881a43cff9SSean Bruno static int
389a034518aSAndrew Gallatin in_pcbinslbgrouphash(struct inpcb *inp, uint8_t numa_domain)
3901a43cff9SSean Bruno {
391a7026c7fSMark Johnston 	const static struct timeval interval = { 60, 0 };
392a7026c7fSMark Johnston 	static struct timeval lastprint;
3931a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
3941a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
3951a43cff9SSean Bruno 	struct inpcblbgroup *grp;
39679ee680bSMark Johnston 	uint32_t idx;
397bbd0084bSMark Johnston 	int fib;
3981a43cff9SSean Bruno 
3991a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
4001a43cff9SSean Bruno 
4011a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
4021a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
4031a43cff9SSean Bruno 
404bbd0084bSMark Johnston 	fib = (inp->inp_flags & INP_BOUNDFIB) != 0 ?
405bbd0084bSMark Johnston 	    inp->inp_inc.inc_fibnum : RT_ALL_FIBS;
406bbd0084bSMark Johnston 
4071a43cff9SSean Bruno #ifdef INET6
4081a43cff9SSean Bruno 	/*
4091a43cff9SSean Bruno 	 * Don't allow IPv4 mapped INET6 wild socket.
4101a43cff9SSean Bruno 	 */
4111a43cff9SSean Bruno 	if ((inp->inp_vflag & INP_IPV4) &&
4121a43cff9SSean Bruno 	    inp->inp_laddr.s_addr == INADDR_ANY &&
4131a43cff9SSean Bruno 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
4141a43cff9SSean Bruno 		return (0);
4151a43cff9SSean Bruno 	}
4161a43cff9SSean Bruno #endif
4171a43cff9SSean Bruno 
4189d2877fcSMark Johnston 	idx = INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask);
41979ee680bSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
42054af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
421d93ec8cbSMark Johnston 		if (grp->il_cred->cr_prison == inp->inp_cred->cr_prison &&
422d93ec8cbSMark Johnston 		    grp->il_vflag == inp->inp_vflag &&
4231a43cff9SSean Bruno 		    grp->il_lport == inp->inp_lport &&
424a034518aSAndrew Gallatin 		    grp->il_numa_domain == numa_domain &&
425bbd0084bSMark Johnston 		    grp->il_fibnum == fib &&
4261a43cff9SSean Bruno 		    memcmp(&grp->il_dependladdr,
4271a43cff9SSean Bruno 		    &inp->inp_inc.inc_ie.ie_dependladdr,
428d93ec8cbSMark Johnston 		    sizeof(grp->il_dependladdr)) == 0) {
4291a43cff9SSean Bruno 			break;
4301a43cff9SSean Bruno 		}
431d93ec8cbSMark Johnston 	}
4321a43cff9SSean Bruno 	if (grp == NULL) {
4331a43cff9SSean Bruno 		/* Create new load balance group. */
434a600aabeSMark Johnston 		grp = in_pcblbgroup_alloc(inp->inp_cred, inp->inp_vflag,
4351a43cff9SSean Bruno 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
436bbd0084bSMark Johnston 		    INPCBLBGROUP_SIZMIN, numa_domain, fib);
43779ee680bSMark Johnston 		if (grp == NULL)
438136c5e17SGleb Smirnoff 			return (ENOMEM);
439a600aabeSMark Johnston 		in_pcblbgroup_insert(grp, inp);
440a600aabeSMark Johnston 		CK_LIST_INSERT_HEAD(hdr, grp, il_list);
4418b3d2c19SMark Johnston 	} else if (grp->il_inpcnt + grp->il_pendcnt == grp->il_inpsiz) {
4421a43cff9SSean Bruno 		if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
443a7026c7fSMark Johnston 			if (ratecheck(&lastprint, &interval))
4441a43cff9SSean Bruno 				printf("lb group port %d, limit reached\n",
4451a43cff9SSean Bruno 				    ntohs(grp->il_lport));
4461a43cff9SSean Bruno 			return (0);
4471a43cff9SSean Bruno 		}
4481a43cff9SSean Bruno 
4491a43cff9SSean Bruno 		/* Expand this local group. */
4501a43cff9SSean Bruno 		grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
45179ee680bSMark Johnston 		if (grp == NULL)
452136c5e17SGleb Smirnoff 			return (ENOMEM);
453a600aabeSMark Johnston 		in_pcblbgroup_insert(grp, inp);
454a600aabeSMark Johnston 	} else {
455a600aabeSMark Johnston 		in_pcblbgroup_insert(grp, inp);
4561a43cff9SSean Bruno 	}
4571a43cff9SSean Bruno 	return (0);
4581a43cff9SSean Bruno }
4591a43cff9SSean Bruno 
4601a43cff9SSean Bruno /*
4611a43cff9SSean Bruno  * Remove PCB from load balance group.
4621a43cff9SSean Bruno  */
4631a43cff9SSean Bruno static void
4641a43cff9SSean Bruno in_pcbremlbgrouphash(struct inpcb *inp)
4651a43cff9SSean Bruno {
4661a43cff9SSean Bruno 	struct inpcbinfo *pcbinfo;
4671a43cff9SSean Bruno 	struct inpcblbgrouphead *hdr;
4681a43cff9SSean Bruno 	struct inpcblbgroup *grp;
4697cbb6b6eSMark Johnston 	struct inpcb *inp1;
4701a43cff9SSean Bruno 	int i;
4711a43cff9SSean Bruno 
4721a43cff9SSean Bruno 	pcbinfo = inp->inp_pcbinfo;
4731a43cff9SSean Bruno 
4741a43cff9SSean Bruno 	INP_WLOCK_ASSERT(inp);
475a43e7a96SGleb Smirnoff 	MPASS(inp->inp_flags & INP_INLBGROUP);
4761a43cff9SSean Bruno 	INP_HASH_WLOCK_ASSERT(pcbinfo);
4771a43cff9SSean Bruno 
4781a43cff9SSean Bruno 	hdr = &pcbinfo->ipi_lbgrouphashbase[
4799d2877fcSMark Johnston 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_lbgrouphashmask)];
48054af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
4811a43cff9SSean Bruno 		for (i = 0; i < grp->il_inpcnt; ++i) {
4821a43cff9SSean Bruno 			if (grp->il_inp[i] != inp)
4831a43cff9SSean Bruno 				continue;
4841a43cff9SSean Bruno 
4857cbb6b6eSMark Johnston 			if (grp->il_inpcnt == 1 &&
4867cbb6b6eSMark Johnston 			    LIST_EMPTY(&grp->il_pending)) {
4871a43cff9SSean Bruno 				/* We are the last, free this local group. */
4881a43cff9SSean Bruno 				in_pcblbgroup_free(grp);
4891a43cff9SSean Bruno 			} else {
490a600aabeSMark Johnston 				grp->il_inp[i] =
491a600aabeSMark Johnston 				    grp->il_inp[grp->il_inpcnt - 1];
492a600aabeSMark Johnston 
493a600aabeSMark Johnston 				/*
494a600aabeSMark Johnston 				 * Synchronize with in_pcblookup_lbgroup().
495a600aabeSMark Johnston 				 */
496a600aabeSMark Johnston 				atomic_store_rel_int(&grp->il_inpcnt,
497a600aabeSMark Johnston 				    grp->il_inpcnt - 1);
4981a43cff9SSean Bruno 			}
499a43e7a96SGleb Smirnoff 			inp->inp_flags &= ~INP_INLBGROUP;
5001a43cff9SSean Bruno 			return;
5011a43cff9SSean Bruno 		}
5027cbb6b6eSMark Johnston 		LIST_FOREACH(inp1, &grp->il_pending, inp_lbgroup_list) {
5037cbb6b6eSMark Johnston 			if (inp == inp1) {
5047cbb6b6eSMark Johnston 				LIST_REMOVE(inp, inp_lbgroup_list);
5058b3d2c19SMark Johnston 				grp->il_pendcnt--;
5067cbb6b6eSMark Johnston 				inp->inp_flags &= ~INP_INLBGROUP;
5077cbb6b6eSMark Johnston 				return;
5081a43cff9SSean Bruno 			}
5097cbb6b6eSMark Johnston 		}
5107cbb6b6eSMark Johnston 	}
5117cbb6b6eSMark Johnston 	__assert_unreachable();
5121a43cff9SSean Bruno }
5131a43cff9SSean Bruno 
514a034518aSAndrew Gallatin int
515a034518aSAndrew Gallatin in_pcblbgroup_numa(struct inpcb *inp, int arg)
516a034518aSAndrew Gallatin {
517a034518aSAndrew Gallatin 	struct inpcbinfo *pcbinfo;
5187cbb6b6eSMark Johnston 	int error;
519a034518aSAndrew Gallatin 	uint8_t numa_domain;
520a034518aSAndrew Gallatin 
521a034518aSAndrew Gallatin 	switch (arg) {
522a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_NODOM:
523a034518aSAndrew Gallatin 		numa_domain = M_NODOM;
524a034518aSAndrew Gallatin 		break;
525a034518aSAndrew Gallatin 	case TCP_REUSPORT_LB_NUMA_CURDOM:
526a034518aSAndrew Gallatin 		numa_domain = PCPU_GET(domain);
527a034518aSAndrew Gallatin 		break;
528a034518aSAndrew Gallatin 	default:
529a034518aSAndrew Gallatin 		if (arg < 0 || arg >= vm_ndomains)
530a034518aSAndrew Gallatin 			return (EINVAL);
531a034518aSAndrew Gallatin 		numa_domain = arg;
532a034518aSAndrew Gallatin 	}
533a034518aSAndrew Gallatin 
534a034518aSAndrew Gallatin 	pcbinfo = inp->inp_pcbinfo;
535a034518aSAndrew Gallatin 	INP_WLOCK_ASSERT(inp);
536a034518aSAndrew Gallatin 	INP_HASH_WLOCK(pcbinfo);
5377cbb6b6eSMark Johnston 	if (in_pcblbgroup_find(inp) != NULL) {
538a034518aSAndrew Gallatin 		/* Remove it from the old group. */
539a034518aSAndrew Gallatin 		in_pcbremlbgrouphash(inp);
540a034518aSAndrew Gallatin 		/* Add it to the new group based on numa domain. */
541a034518aSAndrew Gallatin 		in_pcbinslbgrouphash(inp, numa_domain);
5427cbb6b6eSMark Johnston 		error = 0;
5437cbb6b6eSMark Johnston 	} else {
5447cbb6b6eSMark Johnston 		error = ENOENT;
545a034518aSAndrew Gallatin 	}
546a034518aSAndrew Gallatin 	INP_HASH_WUNLOCK(pcbinfo);
5477cbb6b6eSMark Johnston 	return (error);
548a034518aSAndrew Gallatin }
549a034518aSAndrew Gallatin 
550db0ac6deSCy Schubert /* Make sure it is safe to use hashinit(9) on CK_LIST. */
551db0ac6deSCy Schubert CTASSERT(sizeof(struct inpcbhead) == sizeof(LIST_HEAD(, inpcb)));
552db0ac6deSCy Schubert 
553cc487c16SGleb Smirnoff /*
554fec8a8c7SGleb Smirnoff  * Initialize an inpcbinfo - a per-VNET instance of connections db.
5559bcd427bSRobert Watson  */
5569bcd427bSRobert Watson void
557fec8a8c7SGleb Smirnoff in_pcbinfo_init(struct inpcbinfo *pcbinfo, struct inpcbstorage *pcbstor,
558fec8a8c7SGleb Smirnoff     u_int hash_nelements, u_int porthash_nelements)
5599bcd427bSRobert Watson {
5609bcd427bSRobert Watson 
561fec8a8c7SGleb Smirnoff 	mtx_init(&pcbinfo->ipi_lock, pcbstor->ips_infolock_name, NULL, MTX_DEF);
562fec8a8c7SGleb Smirnoff 	mtx_init(&pcbinfo->ipi_hash_lock, pcbstor->ips_hashlock_name,
563fec8a8c7SGleb Smirnoff 	    NULL, MTX_DEF);
5649bcd427bSRobert Watson #ifdef VIMAGE
5659bcd427bSRobert Watson 	pcbinfo->ipi_vnet = curvnet;
5669bcd427bSRobert Watson #endif
567db0ac6deSCy Schubert 	CK_LIST_INIT(&pcbinfo->ipi_listhead);
568fa046d87SRobert Watson 	pcbinfo->ipi_count = 0;
569fdb987beSMark Johnston 	pcbinfo->ipi_hash_exact = hashinit(hash_nelements, M_PCB,
570fdb987beSMark Johnston 	    &pcbinfo->ipi_hashmask);
571fdb987beSMark Johnston 	pcbinfo->ipi_hash_wild = hashinit(hash_nelements, M_PCB,
5729bcd427bSRobert Watson 	    &pcbinfo->ipi_hashmask);
573db0ac6deSCy Schubert 	porthash_nelements = imin(porthash_nelements, IPPORT_MAX + 1);
5749bcd427bSRobert Watson 	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
5759bcd427bSRobert Watson 	    &pcbinfo->ipi_porthashmask);
5769d2877fcSMark Johnston 	pcbinfo->ipi_lbgrouphashbase = hashinit(porthash_nelements, M_PCB,
5771a43cff9SSean Bruno 	    &pcbinfo->ipi_lbgrouphashmask);
578fec8a8c7SGleb Smirnoff 	pcbinfo->ipi_zone = pcbstor->ips_zone;
579db0ac6deSCy Schubert 	pcbinfo->ipi_smr = uma_zone_get_smr(pcbinfo->ipi_zone);
5809bcd427bSRobert Watson }
5819bcd427bSRobert Watson 
5829bcd427bSRobert Watson /*
5839bcd427bSRobert Watson  * Destroy an inpcbinfo.
5849bcd427bSRobert Watson  */
5859bcd427bSRobert Watson void
5869bcd427bSRobert Watson in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
5879bcd427bSRobert Watson {
5889bcd427bSRobert Watson 
589fa046d87SRobert Watson 	KASSERT(pcbinfo->ipi_count == 0,
590fa046d87SRobert Watson 	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
591fa046d87SRobert Watson 
592fdb987beSMark Johnston 	hashdestroy(pcbinfo->ipi_hash_exact, M_PCB, pcbinfo->ipi_hashmask);
593fdb987beSMark Johnston 	hashdestroy(pcbinfo->ipi_hash_wild, M_PCB, pcbinfo->ipi_hashmask);
5949bcd427bSRobert Watson 	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
5959bcd427bSRobert Watson 	    pcbinfo->ipi_porthashmask);
5961a43cff9SSean Bruno 	hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
5971a43cff9SSean Bruno 	    pcbinfo->ipi_lbgrouphashmask);
598db0ac6deSCy Schubert 	mtx_destroy(&pcbinfo->ipi_hash_lock);
599db0ac6deSCy Schubert 	mtx_destroy(&pcbinfo->ipi_lock);
6009bcd427bSRobert Watson }
6019bcd427bSRobert Watson 
6029bcd427bSRobert Watson /*
603fec8a8c7SGleb Smirnoff  * Initialize a pcbstorage - per protocol zones to allocate inpcbs.
604fec8a8c7SGleb Smirnoff  */
605fec8a8c7SGleb Smirnoff static void inpcb_fini(void *, int);
606fec8a8c7SGleb Smirnoff void
607fec8a8c7SGleb Smirnoff in_pcbstorage_init(void *arg)
608fec8a8c7SGleb Smirnoff {
609fec8a8c7SGleb Smirnoff 	struct inpcbstorage *pcbstor = arg;
610fec8a8c7SGleb Smirnoff 
611fec8a8c7SGleb Smirnoff 	pcbstor->ips_zone = uma_zcreate(pcbstor->ips_zone_name,
6125fd1a67eSMark Johnston 	    pcbstor->ips_size, NULL, NULL, pcbstor->ips_pcbinit,
613c4a4b263SAndrew Gallatin 	    inpcb_fini, UMA_ALIGN_CACHE, UMA_ZONE_SMR);
614fec8a8c7SGleb Smirnoff }
615fec8a8c7SGleb Smirnoff 
616fec8a8c7SGleb Smirnoff /*
617fec8a8c7SGleb Smirnoff  * Destroy a pcbstorage - used by unloadable protocols.
618fec8a8c7SGleb Smirnoff  */
619fec8a8c7SGleb Smirnoff void
620fec8a8c7SGleb Smirnoff in_pcbstorage_destroy(void *arg)
621fec8a8c7SGleb Smirnoff {
622fec8a8c7SGleb Smirnoff 	struct inpcbstorage *pcbstor = arg;
623fec8a8c7SGleb Smirnoff 
624fec8a8c7SGleb Smirnoff 	uma_zdestroy(pcbstor->ips_zone);
625fec8a8c7SGleb Smirnoff }
626fec8a8c7SGleb Smirnoff 
627fec8a8c7SGleb Smirnoff /*
628c3229e05SDavid Greenman  * Allocate a PCB and associate it with the socket.
629d915b280SStephan Uphoff  * On success return with the PCB locked.
630c3229e05SDavid Greenman  */
631df8bae1dSRodney W. Grimes int
632d915b280SStephan Uphoff in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
633df8bae1dSRodney W. Grimes {
634136d4f1cSRobert Watson 	struct inpcb *inp;
635fe5324acSJohn Baldwin #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
63613cf67f3SHajimu UMEMOTO 	int error;
637fe5324acSJohn Baldwin #endif
638a557af22SRobert Watson 
639db0ac6deSCy Schubert 	inp = uma_zalloc_smr(pcbinfo->ipi_zone, M_NOWAIT);
640df8bae1dSRodney W. Grimes 	if (inp == NULL)
641df8bae1dSRodney W. Grimes 		return (ENOBUFS);
6426a6cefacSGleb Smirnoff 	bzero(&inp->inp_start_zero, inp_zero_size);
64350575ce1SAndrew Gallatin #ifdef NUMA
64450575ce1SAndrew Gallatin 	inp->inp_numa_domain = M_NODOM;
64550575ce1SAndrew Gallatin #endif
64615bd2b43SDavid Greenman 	inp->inp_pcbinfo = pcbinfo;
647df8bae1dSRodney W. Grimes 	inp->inp_socket = so;
64886d02c5cSBjoern A. Zeeb 	inp->inp_cred = crhold(so->so_cred);
6498b07e49aSJulian Elischer 	inp->inp_inc.inc_fibnum = so->so_fibnum;
650a557af22SRobert Watson #ifdef MAC
65130d239bcSRobert Watson 	error = mac_inpcb_init(inp, M_NOWAIT);
652a557af22SRobert Watson 	if (error != 0)
653a557af22SRobert Watson 		goto out;
65430d239bcSRobert Watson 	mac_inpcb_create(so, inp);
655a557af22SRobert Watson #endif
656fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
657fcf59617SAndrey V. Elsukov 	error = ipsec_init_pcbpolicy(inp);
6580bffde27SRobert Watson 	if (error != 0) {
6590bffde27SRobert Watson #ifdef MAC
6600bffde27SRobert Watson 		mac_inpcb_destroy(inp);
6610bffde27SRobert Watson #endif
662a557af22SRobert Watson 		goto out;
6630bffde27SRobert Watson 	}
664b2630c29SGeorge V. Neville-Neil #endif /*IPSEC*/
665e3fd5ffdSRobert Watson #ifdef INET6
666340c35deSJonathan Lemon 	if (INP_SOCKAF(so) == AF_INET6) {
667c7a62c92SGleb Smirnoff 		inp->inp_vflag |= INP_IPV6PROTO | INP_IPV6;
668603724d3SBjoern A. Zeeb 		if (V_ip6_v6only)
66933841545SHajimu UMEMOTO 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
670c7a62c92SGleb Smirnoff #ifdef INET
671c7a62c92SGleb Smirnoff 		else
672c7a62c92SGleb Smirnoff 			inp->inp_vflag |= INP_IPV4;
673c7a62c92SGleb Smirnoff #endif
674603724d3SBjoern A. Zeeb 		if (V_ip6_auto_flowlabel)
67533841545SHajimu UMEMOTO 			inp->inp_flags |= IN6P_AUTOFLOWLABEL;
676c7a62c92SGleb Smirnoff 		inp->in6p_hops = -1;	/* use kernel default */
677c7a62c92SGleb Smirnoff 	}
678c7a62c92SGleb Smirnoff #endif
679c7a62c92SGleb Smirnoff #if defined(INET) && defined(INET6)
680c7a62c92SGleb Smirnoff 	else
681c7a62c92SGleb Smirnoff #endif
682c7a62c92SGleb Smirnoff #ifdef INET
683c7a62c92SGleb Smirnoff 		inp->inp_vflag |= INP_IPV4;
68433841545SHajimu UMEMOTO #endif
685fdb987beSMark Johnston 	inp->inp_smr = SMR_SEQ_INVALID;
686fdb987beSMark Johnston 
6878c1960d5SMike Karels 	/*
6888c1960d5SMike Karels 	 * Routes in inpcb's can cache L2 as well; they are guaranteed
6898c1960d5SMike Karels 	 * to be cleaned up.
6908c1960d5SMike Karels 	 */
6918c1960d5SMike Karels 	inp->inp_route.ro_flags = RT_LLE_CACHE;
692db0ac6deSCy Schubert 	refcount_init(&inp->inp_refcount, 1);   /* Reference from socket. */
693db0ac6deSCy Schubert 	INP_WLOCK(inp);
694db0ac6deSCy Schubert 	INP_INFO_WLOCK(pcbinfo);
695db0ac6deSCy Schubert 	pcbinfo->ipi_count++;
696db0ac6deSCy Schubert 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
697db0ac6deSCy Schubert 	CK_LIST_INSERT_HEAD(&pcbinfo->ipi_listhead, inp, inp_list);
698db0ac6deSCy Schubert 	INP_INFO_WUNLOCK(pcbinfo);
699db0ac6deSCy Schubert 	so->so_pcb = inp;
700db0ac6deSCy Schubert 
701db0ac6deSCy Schubert 	return (0);
702db0ac6deSCy Schubert 
7037a60a910SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
704a557af22SRobert Watson out:
70530cf0fbfSRichard Scheffenegger 	crfree(inp->inp_cred);
70630cf0fbfSRichard Scheffenegger #ifdef INVARIANTS
70730cf0fbfSRichard Scheffenegger 	inp->inp_cred = NULL;
70830cf0fbfSRichard Scheffenegger #endif
709db0ac6deSCy Schubert 	uma_zfree_smr(pcbinfo->ipi_zone, inp);
710266f97b5SCy Schubert 	return (error);
711db0ac6deSCy Schubert #endif
712df8bae1dSRodney W. Grimes }
713df8bae1dSRodney W. Grimes 
71467107f45SBjoern A. Zeeb #ifdef INET
715df8bae1dSRodney W. Grimes int
716bbd0084bSMark Johnston in_pcbbind(struct inpcb *inp, struct sockaddr_in *sin, int flags,
717bbd0084bSMark Johnston     struct ucred *cred)
718df8bae1dSRodney W. Grimes {
7194b932371SIan Dowse 	int anonport, error;
7204b932371SIan Dowse 
72196871af0SGleb Smirnoff 	KASSERT(sin == NULL || sin->sin_family == AF_INET,
72296871af0SGleb Smirnoff 	    ("%s: invalid address family for %p", __func__, sin));
72396871af0SGleb Smirnoff 	KASSERT(sin == NULL || sin->sin_len == sizeof(struct sockaddr_in),
72496871af0SGleb Smirnoff 	    ("%s: invalid address length for %p", __func__, sin));
7258501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
726fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
72759daba27SSam Leffler 
7284b932371SIan Dowse 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
7294b932371SIan Dowse 		return (EINVAL);
73096871af0SGleb Smirnoff 	anonport = sin == NULL || sin->sin_port == 0;
73196871af0SGleb Smirnoff 	error = in_pcbbind_setup(inp, sin, &inp->inp_laddr.s_addr,
732bbd0084bSMark Johnston 	    &inp->inp_lport, flags, cred);
7334b932371SIan Dowse 	if (error)
7344b932371SIan Dowse 		return (error);
735136c5e17SGleb Smirnoff 	if (__predict_false((error = in_pcbinshash(inp)) != 0)) {
736136c5e17SGleb Smirnoff 		MPASS(inp->inp_socket->so_options & SO_REUSEPORT_LB);
7374b932371SIan Dowse 		inp->inp_laddr.s_addr = INADDR_ANY;
7384b932371SIan Dowse 		inp->inp_lport = 0;
739bbd0084bSMark Johnston 		inp->inp_flags &= ~INP_BOUNDFIB;
740136c5e17SGleb Smirnoff 		return (error);
7414b932371SIan Dowse 	}
7424b932371SIan Dowse 	if (anonport)
7434b932371SIan Dowse 		inp->inp_flags |= INP_ANONPORT;
7444b932371SIan Dowse 	return (0);
7454b932371SIan Dowse }
74667107f45SBjoern A. Zeeb #endif
7474b932371SIan Dowse 
748efc76f72SBjoern A. Zeeb #if defined(INET) || defined(INET6)
74925102351SMike Karels /*
75025102351SMike Karels  * Assign a local port like in_pcb_lport(), but also used with connect()
75125102351SMike Karels  * and a foreign address and port.  If fsa is non-NULL, choose a local port
75225102351SMike Karels  * that is unused with those, otherwise one that is completely unused.
7532fdbcbeaSMike Karels  * lsa can be NULL for IPv6.
75425102351SMike Karels  */
755efc76f72SBjoern A. Zeeb int
756bafe022bSGleb Smirnoff in_pcb_lport_dest(const struct inpcb *inp, struct sockaddr *lsa,
757bafe022bSGleb Smirnoff     u_short *lportp, struct sockaddr *fsa, u_short fport, struct ucred *cred,
758bafe022bSGleb Smirnoff     int lookupflags)
759efc76f72SBjoern A. Zeeb {
760efc76f72SBjoern A. Zeeb 	struct inpcbinfo *pcbinfo;
761efc76f72SBjoern A. Zeeb 	struct inpcb *tmpinp;
762efc76f72SBjoern A. Zeeb 	unsigned short *lastport;
76319acc506SGleb Smirnoff 	int count, error;
764efc76f72SBjoern A. Zeeb 	u_short aux, first, last, lport;
765efc76f72SBjoern A. Zeeb #ifdef INET
76625102351SMike Karels 	struct in_addr laddr, faddr;
76725102351SMike Karels #endif
76825102351SMike Karels #ifdef INET6
76925102351SMike Karels 	struct in6_addr *laddr6, *faddr6;
770efc76f72SBjoern A. Zeeb #endif
771efc76f72SBjoern A. Zeeb 
772efc76f72SBjoern A. Zeeb 	pcbinfo = inp->inp_pcbinfo;
773efc76f72SBjoern A. Zeeb 
774efc76f72SBjoern A. Zeeb 	/*
775efc76f72SBjoern A. Zeeb 	 * Because no actual state changes occur here, a global write lock on
776efc76f72SBjoern A. Zeeb 	 * the pcbinfo isn't required.
777efc76f72SBjoern A. Zeeb 	 */
778efc76f72SBjoern A. Zeeb 	INP_LOCK_ASSERT(inp);
779fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
780efc76f72SBjoern A. Zeeb 
781efc76f72SBjoern A. Zeeb 	if (inp->inp_flags & INP_HIGHPORT) {
782efc76f72SBjoern A. Zeeb 		first = V_ipport_hifirstauto;	/* sysctl */
783efc76f72SBjoern A. Zeeb 		last  = V_ipport_hilastauto;
784efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lasthi;
785efc76f72SBjoern A. Zeeb 	} else if (inp->inp_flags & INP_LOWPORT) {
786cc426dd3SMateusz Guzik 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT);
787efc76f72SBjoern A. Zeeb 		if (error)
788efc76f72SBjoern A. Zeeb 			return (error);
789efc76f72SBjoern A. Zeeb 		first = V_ipport_lowfirstauto;	/* 1023 */
790efc76f72SBjoern A. Zeeb 		last  = V_ipport_lowlastauto;	/* 600 */
791efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastlow;
792efc76f72SBjoern A. Zeeb 	} else {
793efc76f72SBjoern A. Zeeb 		first = V_ipport_firstauto;	/* sysctl */
794efc76f72SBjoern A. Zeeb 		last  = V_ipport_lastauto;
795efc76f72SBjoern A. Zeeb 		lastport = &pcbinfo->ipi_lastport;
796efc76f72SBjoern A. Zeeb 	}
79719acc506SGleb Smirnoff 
798efc76f72SBjoern A. Zeeb 	/*
799efc76f72SBjoern A. Zeeb 	 * Instead of having two loops further down counting up or down
800efc76f72SBjoern A. Zeeb 	 * make sure that first is always <= last and go with only one
801efc76f72SBjoern A. Zeeb 	 * code path implementing all logic.
802efc76f72SBjoern A. Zeeb 	 */
803efc76f72SBjoern A. Zeeb 	if (first > last) {
804efc76f72SBjoern A. Zeeb 		aux = first;
805efc76f72SBjoern A. Zeeb 		first = last;
806efc76f72SBjoern A. Zeeb 		last = aux;
807efc76f72SBjoern A. Zeeb 	}
808efc76f72SBjoern A. Zeeb 
809efc76f72SBjoern A. Zeeb #ifdef INET
810637f317cSMike Karels 	laddr.s_addr = INADDR_ANY;	/* used by INET6+INET below too */
8114d457387SBjoern A. Zeeb 	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
8122fdbcbeaSMike Karels 		if (lsa != NULL)
81325102351SMike Karels 			laddr = ((struct sockaddr_in *)lsa)->sin_addr;
81425102351SMike Karels 		if (fsa != NULL)
81525102351SMike Karels 			faddr = ((struct sockaddr_in *)fsa)->sin_addr;
816efc76f72SBjoern A. Zeeb 	}
817efc76f72SBjoern A. Zeeb #endif
81825102351SMike Karels #ifdef INET6
8192fdbcbeaSMike Karels 	laddr6 = NULL;
8202fdbcbeaSMike Karels 	if ((inp->inp_vflag & INP_IPV6) != 0) {
8212fdbcbeaSMike Karels 		if (lsa != NULL)
82225102351SMike Karels 			laddr6 = &((struct sockaddr_in6 *)lsa)->sin6_addr;
82325102351SMike Karels 		if (fsa != NULL)
82425102351SMike Karels 			faddr6 = &((struct sockaddr_in6 *)fsa)->sin6_addr;
82525102351SMike Karels 	}
82625102351SMike Karels #endif
82725102351SMike Karels 
82825102351SMike Karels 	tmpinp = NULL;
829efc76f72SBjoern A. Zeeb 
83019acc506SGleb Smirnoff 	if (V_ipport_randomized)
831efc76f72SBjoern A. Zeeb 		*lastport = first + (arc4random() % (last - first));
832efc76f72SBjoern A. Zeeb 
833efc76f72SBjoern A. Zeeb 	count = last - first;
834efc76f72SBjoern A. Zeeb 
835efc76f72SBjoern A. Zeeb 	do {
836efc76f72SBjoern A. Zeeb 		if (count-- < 0)	/* completely used? */
837efc76f72SBjoern A. Zeeb 			return (EADDRNOTAVAIL);
838efc76f72SBjoern A. Zeeb 		++*lastport;
839efc76f72SBjoern A. Zeeb 		if (*lastport < first || *lastport > last)
840efc76f72SBjoern A. Zeeb 			*lastport = first;
841efc76f72SBjoern A. Zeeb 		lport = htons(*lastport);
842efc76f72SBjoern A. Zeeb 
84325102351SMike Karels 		if (fsa != NULL) {
84425102351SMike Karels #ifdef INET
84525102351SMike Karels 			if (lsa->sa_family == AF_INET) {
84625102351SMike Karels 				tmpinp = in_pcblookup_hash_locked(pcbinfo,
84725102351SMike Karels 				    faddr, fport, laddr, lport, lookupflags,
848da806e8dSMark Johnston 				    M_NODOM, RT_ALL_FIBS);
84925102351SMike Karels 			}
85025102351SMike Karels #endif
85125102351SMike Karels #ifdef INET6
85225102351SMike Karels 			if (lsa->sa_family == AF_INET6) {
85325102351SMike Karels 				tmpinp = in6_pcblookup_hash_locked(pcbinfo,
85425102351SMike Karels 				    faddr6, fport, laddr6, lport, lookupflags,
855da806e8dSMark Johnston 				    M_NODOM, RT_ALL_FIBS);
85625102351SMike Karels 			}
85725102351SMike Karels #endif
85825102351SMike Karels 		} else {
859efc76f72SBjoern A. Zeeb #ifdef INET6
860637f317cSMike Karels 			if ((inp->inp_vflag & INP_IPV6) != 0) {
861efc76f72SBjoern A. Zeeb 				tmpinp = in6_pcblookup_local(pcbinfo,
8629a413162SMark Johnston 				    &inp->in6p_laddr, lport, RT_ALL_FIBS,
8639a413162SMark Johnston 				    lookupflags, cred);
864637f317cSMike Karels #ifdef INET
865637f317cSMike Karels 				if (tmpinp == NULL &&
866637f317cSMike Karels 				    (inp->inp_vflag & INP_IPV4))
867637f317cSMike Karels 					tmpinp = in_pcblookup_local(pcbinfo,
8689a413162SMark Johnston 					    laddr, lport, RT_ALL_FIBS,
8699a413162SMark Johnston 					    lookupflags, cred);
870637f317cSMike Karels #endif
871637f317cSMike Karels 			}
872efc76f72SBjoern A. Zeeb #endif
873efc76f72SBjoern A. Zeeb #if defined(INET) && defined(INET6)
874efc76f72SBjoern A. Zeeb 			else
875efc76f72SBjoern A. Zeeb #endif
876efc76f72SBjoern A. Zeeb #ifdef INET
877efc76f72SBjoern A. Zeeb 				tmpinp = in_pcblookup_local(pcbinfo, laddr,
8789a413162SMark Johnston 				    lport, RT_ALL_FIBS, lookupflags, cred);
879efc76f72SBjoern A. Zeeb #endif
88025102351SMike Karels 		}
881efc76f72SBjoern A. Zeeb 	} while (tmpinp != NULL);
882efc76f72SBjoern A. Zeeb 
883efc76f72SBjoern A. Zeeb 	*lportp = lport;
884efc76f72SBjoern A. Zeeb 
885efc76f72SBjoern A. Zeeb 	return (0);
886efc76f72SBjoern A. Zeeb }
887efdf104bSMikolaj Golub 
888efdf104bSMikolaj Golub /*
88925102351SMike Karels  * Select a local port (number) to use.
89025102351SMike Karels  */
89125102351SMike Karels int
89225102351SMike Karels in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
89325102351SMike Karels     struct ucred *cred, int lookupflags)
89425102351SMike Karels {
89525102351SMike Karels 	struct sockaddr_in laddr;
89625102351SMike Karels 
89725102351SMike Karels 	if (laddrp) {
89825102351SMike Karels 		bzero(&laddr, sizeof(laddr));
89925102351SMike Karels 		laddr.sin_family = AF_INET;
90025102351SMike Karels 		laddr.sin_addr = *laddrp;
90125102351SMike Karels 	}
90225102351SMike Karels 	return (in_pcb_lport_dest(inp, laddrp ? (struct sockaddr *) &laddr :
90325102351SMike Karels 	    NULL, lportp, NULL, 0, cred, lookupflags));
90425102351SMike Karels }
905efc76f72SBjoern A. Zeeb #endif /* INET || INET6 */
906efc76f72SBjoern A. Zeeb 
907d5bb8bd3SAdrian Chadd #ifdef INET
9080a100a6fSAdrian Chadd /*
90901f8ce83SMark Johnston  * Determine whether the inpcb can be bound to the specified address/port tuple.
91001f8ce83SMark Johnston  */
91101f8ce83SMark Johnston static int
91201f8ce83SMark Johnston in_pcbbind_avail(struct inpcb *inp, const struct in_addr laddr,
913bbd0084bSMark Johnston     const u_short lport, const int fib, int sooptions, int lookupflags,
914bbd0084bSMark Johnston     struct ucred *cred)
91501f8ce83SMark Johnston {
91601f8ce83SMark Johnston 	int reuseport, reuseport_lb;
91701f8ce83SMark Johnston 
91801f8ce83SMark Johnston 	INP_LOCK_ASSERT(inp);
91901f8ce83SMark Johnston 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
92001f8ce83SMark Johnston 
92101f8ce83SMark Johnston 	reuseport = (sooptions & SO_REUSEPORT);
92201f8ce83SMark Johnston 	reuseport_lb = (sooptions & SO_REUSEPORT_LB);
92301f8ce83SMark Johnston 
92401f8ce83SMark Johnston 	if (IN_MULTICAST(ntohl(laddr.s_addr))) {
92501f8ce83SMark Johnston 		/*
92601f8ce83SMark Johnston 		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
92701f8ce83SMark Johnston 		 * allow complete duplication of binding if
92801f8ce83SMark Johnston 		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
92901f8ce83SMark Johnston 		 * and a multicast address is bound on both
93001f8ce83SMark Johnston 		 * new and duplicated sockets.
93101f8ce83SMark Johnston 		 */
93201f8ce83SMark Johnston 		if ((sooptions & (SO_REUSEADDR | SO_REUSEPORT)) != 0)
93301f8ce83SMark Johnston 			reuseport = SO_REUSEADDR | SO_REUSEPORT;
93401f8ce83SMark Johnston 		/*
93501f8ce83SMark Johnston 		 * XXX: How to deal with SO_REUSEPORT_LB here?
93601f8ce83SMark Johnston 		 * Treat same as SO_REUSEPORT for now.
93701f8ce83SMark Johnston 		 */
93801f8ce83SMark Johnston 		if ((sooptions & (SO_REUSEADDR | SO_REUSEPORT_LB)) != 0)
93901f8ce83SMark Johnston 			reuseport_lb = SO_REUSEADDR | SO_REUSEPORT_LB;
94001f8ce83SMark Johnston 	} else if (!in_nullhost(laddr)) {
94101f8ce83SMark Johnston 		struct sockaddr_in sin;
94201f8ce83SMark Johnston 
94301f8ce83SMark Johnston 		memset(&sin, 0, sizeof(sin));
94401f8ce83SMark Johnston 		sin.sin_family = AF_INET;
94501f8ce83SMark Johnston 		sin.sin_len = sizeof(sin);
94601f8ce83SMark Johnston 		sin.sin_addr = laddr;
94701f8ce83SMark Johnston 
94801f8ce83SMark Johnston 		/*
94901f8ce83SMark Johnston 		 * Is the address a local IP address?
95001f8ce83SMark Johnston 		 * If INP_BINDANY is set, then the socket may be bound
95101f8ce83SMark Johnston 		 * to any endpoint address, local or not.
95201f8ce83SMark Johnston 		 */
95301f8ce83SMark Johnston 		if ((inp->inp_flags & INP_BINDANY) == 0 &&
95401f8ce83SMark Johnston 		    ifa_ifwithaddr_check((const struct sockaddr *)&sin) == 0)
95501f8ce83SMark Johnston 			return (EADDRNOTAVAIL);
95601f8ce83SMark Johnston 	}
95701f8ce83SMark Johnston 
95801f8ce83SMark Johnston 	if (lport != 0) {
95901f8ce83SMark Johnston 		struct inpcb *t;
96001f8ce83SMark Johnston 
96101f8ce83SMark Johnston 		if (ntohs(lport) <= V_ipport_reservedhigh &&
96201f8ce83SMark Johnston 		    ntohs(lport) >= V_ipport_reservedlow &&
96301f8ce83SMark Johnston 		    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
96401f8ce83SMark Johnston 			return (EACCES);
96501f8ce83SMark Johnston 
96601f8ce83SMark Johnston 		if (!IN_MULTICAST(ntohl(laddr.s_addr)) &&
96701f8ce83SMark Johnston 		    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
968c9756953SMark Johnston 			/*
969c9756953SMark Johnston 			 * If a socket owned by a different user is already
970c9756953SMark Johnston 			 * bound to this port, fail.  In particular, SO_REUSE*
971c9756953SMark Johnston 			 * can only be used to share a port among sockets owned
972c9756953SMark Johnston 			 * by the same user.
973c9756953SMark Johnston 			 *
974c9756953SMark Johnston 			 * However, we can share a port with a connected socket
975c9756953SMark Johnston 			 * which has a unique 4-tuple.
976c9756953SMark Johnston 			 */
97701f8ce83SMark Johnston 			t = in_pcblookup_local(inp->inp_pcbinfo, laddr, lport,
9789a413162SMark Johnston 			    RT_ALL_FIBS, INPLOOKUP_WILDCARD, cred);
97901f8ce83SMark Johnston 			if (t != NULL &&
98001f8ce83SMark Johnston 			    (inp->inp_socket->so_type != SOCK_STREAM ||
98101f8ce83SMark Johnston 			     in_nullhost(t->inp_faddr)) &&
98201f8ce83SMark Johnston 			    (inp->inp_cred->cr_uid != t->inp_cred->cr_uid))
98301f8ce83SMark Johnston 				return (EADDRINUSE);
98401f8ce83SMark Johnston 		}
985bbd0084bSMark Johnston 		t = in_pcblookup_local(inp->inp_pcbinfo, laddr, lport, fib,
986bbd0084bSMark Johnston 		    lookupflags, cred);
98701f8ce83SMark Johnston 		if (t != NULL && ((reuseport | reuseport_lb) &
98801f8ce83SMark Johnston 		    t->inp_socket->so_options) == 0) {
98901f8ce83SMark Johnston #ifdef INET6
99001f8ce83SMark Johnston 			if (!in_nullhost(laddr) ||
99101f8ce83SMark Johnston 			    !in_nullhost(t->inp_laddr) ||
99201f8ce83SMark Johnston 			    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
99301f8ce83SMark Johnston 			    (t->inp_vflag & INP_IPV6PROTO) == 0)
99401f8ce83SMark Johnston #endif
99501f8ce83SMark Johnston 				return (EADDRINUSE);
99601f8ce83SMark Johnston 		}
99701f8ce83SMark Johnston 	}
99801f8ce83SMark Johnston 	return (0);
99901f8ce83SMark Johnston }
100001f8ce83SMark Johnston 
100101f8ce83SMark Johnston /*
10024b932371SIan Dowse  * Set up a bind operation on a PCB, performing port allocation
10034b932371SIan Dowse  * as required, but do not actually modify the PCB. Callers can
10044b932371SIan Dowse  * either complete the bind by setting inp_laddr/inp_lport and
10054b932371SIan Dowse  * calling in_pcbinshash(), or they can just use the resulting
10064b932371SIan Dowse  * port and address to authorise the sending of a once-off packet.
10074b932371SIan Dowse  *
10084b932371SIan Dowse  * On error, the values of *laddrp and *lportp are not changed.
10094b932371SIan Dowse  */
10104b932371SIan Dowse int
101196871af0SGleb Smirnoff in_pcbbind_setup(struct inpcb *inp, struct sockaddr_in *sin, in_addr_t *laddrp,
1012bbd0084bSMark Johnston     u_short *lportp, int flags, struct ucred *cred)
10134b932371SIan Dowse {
10144b932371SIan Dowse 	struct socket *so = inp->inp_socket;
10154b932371SIan Dowse 	struct in_addr laddr;
1016df8bae1dSRodney W. Grimes 	u_short lport = 0;
1017bbd0084bSMark Johnston 	int error, fib, lookupflags, sooptions;
1018df8bae1dSRodney W. Grimes 
10198501a69cSRobert Watson 	/*
1020fa046d87SRobert Watson 	 * No state changes, so read locks are sufficient here.
10218501a69cSRobert Watson 	 */
102259daba27SSam Leffler 	INP_LOCK_ASSERT(inp);
1023ffb3d384SMark Johnston 	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
102459daba27SSam Leffler 
10254b932371SIan Dowse 	laddr.s_addr = *laddrp;
102696871af0SGleb Smirnoff 	if (sin != NULL && laddr.s_addr != INADDR_ANY)
1027df8bae1dSRodney W. Grimes 		return (EINVAL);
102801f8ce83SMark Johnston 
102901f8ce83SMark Johnston 	lookupflags = 0;
103001f8ce83SMark Johnston 	sooptions = atomic_load_int(&so->so_options);
103101f8ce83SMark Johnston 	if ((sooptions & (SO_REUSEADDR | SO_REUSEPORT | SO_REUSEPORT_LB)) == 0)
103268e0d7e0SRobert Watson 		lookupflags = INPLOOKUP_WILDCARD;
103396871af0SGleb Smirnoff 	if (sin == NULL) {
10347c2f3cb9SJamie Gritton 		if ((error = prison_local_ip4(cred, &laddr)) != 0)
10357c2f3cb9SJamie Gritton 			return (error);
10367c2f3cb9SJamie Gritton 	} else {
1037f161d294SMark Johnston 		KASSERT(sin->sin_family == AF_INET,
1038f161d294SMark Johnston 		    ("%s: invalid family for address %p", __func__, sin));
1039f161d294SMark Johnston 		KASSERT(sin->sin_len == sizeof(*sin),
1040f161d294SMark Johnston 		    ("%s: invalid length for address %p", __func__, sin));
1041f161d294SMark Johnston 
1042b89e82ddSJamie Gritton 		error = prison_local_ip4(cred, &sin->sin_addr);
1043b89e82ddSJamie Gritton 		if (error)
1044b89e82ddSJamie Gritton 			return (error);
10454b932371SIan Dowse 		if (sin->sin_port != *lportp) {
10464b932371SIan Dowse 			/* Don't allow the port to change. */
10474b932371SIan Dowse 			if (*lportp != 0)
10484b932371SIan Dowse 				return (EINVAL);
1049df8bae1dSRodney W. Grimes 			lport = sin->sin_port;
10504b932371SIan Dowse 		}
105145a77bf2SMark Johnston 		laddr = sin->sin_addr;
105245a77bf2SMark Johnston 
1053bbd0084bSMark Johnston 		fib = (flags & INPBIND_FIB) != 0 ? inp->inp_inc.inc_fibnum :
1054bbd0084bSMark Johnston 		    RT_ALL_FIBS;
1055bbd0084bSMark Johnston 
105601f8ce83SMark Johnston 		/* See if this address/port combo is available. */
1057bbd0084bSMark Johnston 		error = in_pcbbind_avail(inp, laddr, lport, fib, sooptions,
105845a77bf2SMark Johnston 		    lookupflags, cred);
105901f8ce83SMark Johnston 		if (error != 0)
106001f8ce83SMark Johnston 			return (error);
1061df8bae1dSRodney W. Grimes 	}
10624b932371SIan Dowse 	if (*lportp != 0)
10634b932371SIan Dowse 		lport = *lportp;
106433b3ac06SPeter Wemm 	if (lport == 0) {
10654616026fSErmal Luçi 		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
1066efc76f72SBjoern A. Zeeb 		if (error != 0)
1067efc76f72SBjoern A. Zeeb 			return (error);
106833b3ac06SPeter Wemm 	}
10694b932371SIan Dowse 	*laddrp = laddr.s_addr;
10704b932371SIan Dowse 	*lportp = lport;
1071bbd0084bSMark Johnston 	if ((flags & INPBIND_FIB) != 0)
1072bbd0084bSMark Johnston 		inp->inp_flags |= INP_BOUNDFIB;
1073df8bae1dSRodney W. Grimes 	return (0);
1074df8bae1dSRodney W. Grimes }
1075df8bae1dSRodney W. Grimes 
1076999f1343SGarrett Wollman /*
10775200e00eSIan Dowse  * Connect from a socket to a specified address.
10785200e00eSIan Dowse  * Both address and port must be specified in argument sin.
10795200e00eSIan Dowse  * If don't have a local address for this socket yet,
10805200e00eSIan Dowse  * then pick one.
1081999f1343SGarrett Wollman  */
1082999f1343SGarrett Wollman int
10830b4539eeSGleb Smirnoff in_pcbconnect(struct inpcb *inp, struct sockaddr_in *sin, struct ucred *cred)
1084999f1343SGarrett Wollman {
10852af953b1SGleb Smirnoff 	struct in_addr laddr, faddr;
10862af953b1SGleb Smirnoff 	u_short lport;
10872af953b1SGleb Smirnoff 	int error;
10882af953b1SGleb Smirnoff 	bool anonport;
1089df8bae1dSRodney W. Grimes 
10908501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1091fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1092fdb987beSMark Johnston 	KASSERT(in_nullhost(inp->inp_faddr),
1093fdb987beSMark Johnston 	    ("%s: inp is already connected", __func__));
10942af953b1SGleb Smirnoff 	KASSERT(sin->sin_family == AF_INET,
10952af953b1SGleb Smirnoff 	    ("%s: invalid address family for %p", __func__, sin));
10962af953b1SGleb Smirnoff 	KASSERT(sin->sin_len == sizeof(*sin),
10972af953b1SGleb Smirnoff 	    ("%s: invalid address length for %p", __func__, sin));
109827f74fd0SRobert Watson 
10992af953b1SGleb Smirnoff 	if (sin->sin_port == 0)
11002af953b1SGleb Smirnoff 		return (EADDRNOTAVAIL);
11012af953b1SGleb Smirnoff 
11022af953b1SGleb Smirnoff 	anonport = (inp->inp_lport == 0);
11032af953b1SGleb Smirnoff 
11042af953b1SGleb Smirnoff 	if (__predict_false(in_broadcast(sin->sin_addr))) {
11052af953b1SGleb Smirnoff 		if (!V_connect_inaddr_wild || CK_STAILQ_EMPTY(&V_in_ifaddrhead))
11062af953b1SGleb Smirnoff 			return (ENETUNREACH);
11072af953b1SGleb Smirnoff 		/*
11082af953b1SGleb Smirnoff 		 * If the destination address is INADDR_ANY, use the primary
11092af953b1SGleb Smirnoff 		 * local address.  If the supplied address is INADDR_BROADCAST,
11102af953b1SGleb Smirnoff 		 * and the primary interface supports broadcast, choose the
11112af953b1SGleb Smirnoff 		 * broadcast address for that interface.
11122af953b1SGleb Smirnoff 		 */
11132af953b1SGleb Smirnoff 		if (in_nullhost(sin->sin_addr)) {
11142af953b1SGleb Smirnoff 			faddr =
11152af953b1SGleb Smirnoff 			    IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
11162af953b1SGleb Smirnoff 			if ((error = prison_get_ip4(cred, &faddr)) != 0)
11172af953b1SGleb Smirnoff 				return (error);
1118*c56e7539SGleb Smirnoff 		} else if (sin->sin_addr.s_addr == INADDR_BROADCAST &&
1119*c56e7539SGleb Smirnoff 		    CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags
1120*c56e7539SGleb Smirnoff 		    & IFF_BROADCAST) {
11212af953b1SGleb Smirnoff 			faddr = satosin(&CK_STAILQ_FIRST(
11222af953b1SGleb Smirnoff 			    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1123*c56e7539SGleb Smirnoff 		} else
11242af953b1SGleb Smirnoff 			faddr = sin->sin_addr;
11252af953b1SGleb Smirnoff 	} else
11262af953b1SGleb Smirnoff 		faddr = sin->sin_addr;
11272af953b1SGleb Smirnoff 
11282af953b1SGleb Smirnoff 	if (in_nullhost(inp->inp_laddr)) {
11292af953b1SGleb Smirnoff 		error = in_pcbladdr(inp, &faddr, &laddr, cred);
11302af953b1SGleb Smirnoff 		/*
11312af953b1SGleb Smirnoff 		 * If the destination address is multicast and an outgoing
11322af953b1SGleb Smirnoff 		 * interface has been set as a multicast option, prefer the
11332af953b1SGleb Smirnoff 		 * address of that interface as our source address.
11342af953b1SGleb Smirnoff 		 */
11352af953b1SGleb Smirnoff 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
11362af953b1SGleb Smirnoff 		    inp->inp_moptions != NULL &&
11372af953b1SGleb Smirnoff 		    inp->inp_moptions->imo_multicast_ifp != NULL) {
11382af953b1SGleb Smirnoff 			struct ifnet *ifp =
11392af953b1SGleb Smirnoff 			    inp->inp_moptions->imo_multicast_ifp;
11402af953b1SGleb Smirnoff 			struct in_ifaddr *ia;
11412af953b1SGleb Smirnoff 
11422af953b1SGleb Smirnoff 			CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
11432af953b1SGleb Smirnoff 				if (ia->ia_ifp == ifp &&
11442af953b1SGleb Smirnoff 				    prison_check_ip4(cred,
11452af953b1SGleb Smirnoff 				    &ia->ia_addr.sin_addr) == 0)
11462af953b1SGleb Smirnoff 					break;
11472af953b1SGleb Smirnoff 			}
11482af953b1SGleb Smirnoff 			if (ia == NULL)
11492af953b1SGleb Smirnoff 				return (EADDRNOTAVAIL);
11502af953b1SGleb Smirnoff 			laddr = ia->ia_addr.sin_addr;
11512af953b1SGleb Smirnoff 			error = 0;
11522af953b1SGleb Smirnoff 		}
11535200e00eSIan Dowse 		if (error)
11545200e00eSIan Dowse 			return (error);
11552af953b1SGleb Smirnoff 	} else
11562af953b1SGleb Smirnoff 		laddr = inp->inp_laddr;
11575200e00eSIan Dowse 
11582af953b1SGleb Smirnoff 	if (anonport) {
11592af953b1SGleb Smirnoff 		struct sockaddr_in lsin = {
11602af953b1SGleb Smirnoff 			.sin_family = AF_INET,
11612af953b1SGleb Smirnoff 			.sin_addr = laddr,
11622af953b1SGleb Smirnoff 		};
11632af953b1SGleb Smirnoff 		struct sockaddr_in fsin = {
11642af953b1SGleb Smirnoff 			.sin_family = AF_INET,
11652af953b1SGleb Smirnoff 			.sin_addr = faddr,
11662af953b1SGleb Smirnoff 		};
11672af953b1SGleb Smirnoff 
11682af953b1SGleb Smirnoff 		error = in_pcb_lport_dest(inp, (struct sockaddr *)&lsin,
11692af953b1SGleb Smirnoff 		    &lport, (struct sockaddr *)&fsin, sin->sin_port, cred,
11702af953b1SGleb Smirnoff 		    INPLOOKUP_WILDCARD);
11712af953b1SGleb Smirnoff 		if (error)
11722af953b1SGleb Smirnoff 			return (error);
11732af953b1SGleb Smirnoff 	} else if (in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr,
11742af953b1SGleb Smirnoff 	    sin->sin_port, laddr, inp->inp_lport, 0, M_NODOM, RT_ALL_FIBS) !=
11752af953b1SGleb Smirnoff 	    NULL)
11762af953b1SGleb Smirnoff 		return (EADDRINUSE);
11772af953b1SGleb Smirnoff 	else
11782af953b1SGleb Smirnoff 		lport = inp->inp_lport;
11792af953b1SGleb Smirnoff 
1180452187b6SGleb Smirnoff 	MPASS(!in_nullhost(inp->inp_laddr) || inp->inp_lport != 0 ||
1181452187b6SGleb Smirnoff 	    !(inp->inp_flags & INP_INHASHLIST));
1182452187b6SGleb Smirnoff 
11832af953b1SGleb Smirnoff 	inp->inp_faddr = faddr;
11842af953b1SGleb Smirnoff 	inp->inp_fport = sin->sin_port;
1185452187b6SGleb Smirnoff 	inp->inp_laddr = laddr;
1186452187b6SGleb Smirnoff 	inp->inp_lport = lport;
1187fdb987beSMark Johnston 
1188452187b6SGleb Smirnoff 	if ((inp->inp_flags & INP_INHASHLIST) == 0) {
1189452187b6SGleb Smirnoff 		error = in_pcbinshash(inp);
1190452187b6SGleb Smirnoff 		MPASS(error == 0);
1191452187b6SGleb Smirnoff 	} else
1192db0ac6deSCy Schubert 		in_pcbrehash(inp);
119324e5c2eeSGleb Smirnoff #ifdef ROUTE_MPATH
119424e5c2eeSGleb Smirnoff 	if (CALC_FLOWID_OUTBOUND) {
119524e5c2eeSGleb Smirnoff 		uint32_t hash_val, hash_type;
11962cb64cb2SGeorge V. Neville-Neil 
119724e5c2eeSGleb Smirnoff 		hash_val = fib4_calc_software_hash(inp->inp_laddr,
11982af953b1SGleb Smirnoff 		    inp->inp_faddr, 0, sin->sin_port,
119924e5c2eeSGleb Smirnoff 		    inp->inp_socket->so_proto->pr_protocol, &hash_type);
120024e5c2eeSGleb Smirnoff 
120124e5c2eeSGleb Smirnoff 		inp->inp_flowid = hash_val;
120224e5c2eeSGleb Smirnoff 		inp->inp_flowtype = hash_type;
120324e5c2eeSGleb Smirnoff 	}
120424e5c2eeSGleb Smirnoff #endif
12055200e00eSIan Dowse 	if (anonport)
12065200e00eSIan Dowse 		inp->inp_flags |= INP_ANONPORT;
12075200e00eSIan Dowse 	return (0);
12085200e00eSIan Dowse }
12095200e00eSIan Dowse 
12105200e00eSIan Dowse /*
12110895aec3SBjoern A. Zeeb  * Do proper source address selection on an unbound socket in case
12120895aec3SBjoern A. Zeeb  * of connect. Take jails into account as well.
12130895aec3SBjoern A. Zeeb  */
1214ae190832SSteven Hartland int
1215bafe022bSGleb Smirnoff in_pcbladdr(const struct inpcb *inp, struct in_addr *faddr,
1216bafe022bSGleb Smirnoff     struct in_addr *laddr, struct ucred *cred)
12170895aec3SBjoern A. Zeeb {
12180895aec3SBjoern A. Zeeb 	struct ifaddr *ifa;
12190895aec3SBjoern A. Zeeb 	struct sockaddr *sa;
12209ac7c6cfSAlexander V. Chernikov 	struct sockaddr_in *sin, dst;
12219ac7c6cfSAlexander V. Chernikov 	struct nhop_object *nh;
12220895aec3SBjoern A. Zeeb 	int error;
12230895aec3SBjoern A. Zeeb 
1224c1604fe4SGleb Smirnoff 	NET_EPOCH_ASSERT();
1225413628a7SBjoern A. Zeeb 	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1226ac1750ddSMark Johnston 
1227592bcae8SBjoern A. Zeeb 	/*
1228592bcae8SBjoern A. Zeeb 	 * Bypass source address selection and use the primary jail IP
1229592bcae8SBjoern A. Zeeb 	 * if requested.
1230592bcae8SBjoern A. Zeeb 	 */
1231ac1750ddSMark Johnston 	if (!prison_saddrsel_ip4(cred, laddr))
1232592bcae8SBjoern A. Zeeb 		return (0);
1233592bcae8SBjoern A. Zeeb 
12340895aec3SBjoern A. Zeeb 	error = 0;
12350895aec3SBjoern A. Zeeb 
12369ac7c6cfSAlexander V. Chernikov 	nh = NULL;
12379ac7c6cfSAlexander V. Chernikov 	bzero(&dst, sizeof(dst));
12389ac7c6cfSAlexander V. Chernikov 	sin = &dst;
12390895aec3SBjoern A. Zeeb 	sin->sin_family = AF_INET;
12400895aec3SBjoern A. Zeeb 	sin->sin_len = sizeof(struct sockaddr_in);
12410895aec3SBjoern A. Zeeb 	sin->sin_addr.s_addr = faddr->s_addr;
12420895aec3SBjoern A. Zeeb 
12430895aec3SBjoern A. Zeeb 	/*
12440895aec3SBjoern A. Zeeb 	 * If route is known our src addr is taken from the i/f,
12450895aec3SBjoern A. Zeeb 	 * else punt.
12460895aec3SBjoern A. Zeeb 	 *
12470895aec3SBjoern A. Zeeb 	 * Find out route to destination.
12480895aec3SBjoern A. Zeeb 	 */
12490895aec3SBjoern A. Zeeb 	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
12509ac7c6cfSAlexander V. Chernikov 		nh = fib4_lookup(inp->inp_inc.inc_fibnum, *faddr,
12519ac7c6cfSAlexander V. Chernikov 		    0, NHR_NONE, 0);
12520895aec3SBjoern A. Zeeb 
12530895aec3SBjoern A. Zeeb 	/*
12540895aec3SBjoern A. Zeeb 	 * If we found a route, use the address corresponding to
12550895aec3SBjoern A. Zeeb 	 * the outgoing interface.
12560895aec3SBjoern A. Zeeb 	 *
12570895aec3SBjoern A. Zeeb 	 * Otherwise assume faddr is reachable on a directly connected
12580895aec3SBjoern A. Zeeb 	 * network and try to find a corresponding interface to take
12590895aec3SBjoern A. Zeeb 	 * the source address from.
12600895aec3SBjoern A. Zeeb 	 */
12619ac7c6cfSAlexander V. Chernikov 	if (nh == NULL || nh->nh_ifp == NULL) {
12628c0fec80SRobert Watson 		struct in_ifaddr *ia;
12630895aec3SBjoern A. Zeeb 		struct ifnet *ifp;
12640895aec3SBjoern A. Zeeb 
12654f8585e0SAlan Somers 		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
126658a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
12674f6c66ccSMatt Macy 		if (ia == NULL) {
12684f8585e0SAlan Somers 			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
126958a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
12704f6c66ccSMatt Macy 		}
12710895aec3SBjoern A. Zeeb 		if (ia == NULL) {
12720895aec3SBjoern A. Zeeb 			error = ENETUNREACH;
12730895aec3SBjoern A. Zeeb 			goto done;
12740895aec3SBjoern A. Zeeb 		}
12750895aec3SBjoern A. Zeeb 
1276ac1750ddSMark Johnston 		if (!prison_flag(cred, PR_IP4)) {
12770895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12780895aec3SBjoern A. Zeeb 			goto done;
12790895aec3SBjoern A. Zeeb 		}
12800895aec3SBjoern A. Zeeb 
12810895aec3SBjoern A. Zeeb 		ifp = ia->ia_ifp;
12820895aec3SBjoern A. Zeeb 		ia = NULL;
1283d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
12840895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
12850895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
12860895aec3SBjoern A. Zeeb 				continue;
12870895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1288b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
12890895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
12900895aec3SBjoern A. Zeeb 				break;
12910895aec3SBjoern A. Zeeb 			}
12920895aec3SBjoern A. Zeeb 		}
12930895aec3SBjoern A. Zeeb 		if (ia != NULL) {
12940895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
12950895aec3SBjoern A. Zeeb 			goto done;
12960895aec3SBjoern A. Zeeb 		}
12970895aec3SBjoern A. Zeeb 
12980895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1299b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
13000895aec3SBjoern A. Zeeb 		goto done;
13010895aec3SBjoern A. Zeeb 	}
13020895aec3SBjoern A. Zeeb 
13030895aec3SBjoern A. Zeeb 	/*
13040895aec3SBjoern A. Zeeb 	 * If the outgoing interface on the route found is not
13050895aec3SBjoern A. Zeeb 	 * a loopback interface, use the address from that interface.
13060895aec3SBjoern A. Zeeb 	 * In case of jails do those three steps:
13070895aec3SBjoern A. Zeeb 	 * 1. check if the interface address belongs to the jail. If so use it.
13080895aec3SBjoern A. Zeeb 	 * 2. check if we have any address on the outgoing interface
13090895aec3SBjoern A. Zeeb 	 *    belonging to this jail. If so use it.
13100895aec3SBjoern A. Zeeb 	 * 3. as a last resort return the 'default' jail address.
13110895aec3SBjoern A. Zeeb 	 */
13129ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) == 0) {
13138c0fec80SRobert Watson 		struct in_ifaddr *ia;
13149317b04eSRobert Watson 		struct ifnet *ifp;
13150895aec3SBjoern A. Zeeb 
13160895aec3SBjoern A. Zeeb 		/* If not jailed, use the default returned. */
1317ac1750ddSMark Johnston 		if (!prison_flag(cred, PR_IP4)) {
13189ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
13190895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13200895aec3SBjoern A. Zeeb 			goto done;
13210895aec3SBjoern A. Zeeb 		}
13220895aec3SBjoern A. Zeeb 
13230895aec3SBjoern A. Zeeb 		/* Jailed. */
13240895aec3SBjoern A. Zeeb 		/* 1. Check if the iface address belongs to the jail. */
13259ac7c6cfSAlexander V. Chernikov 		sin = (struct sockaddr_in *)nh->nh_ifa->ifa_addr;
1326b89e82ddSJamie Gritton 		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
13279ac7c6cfSAlexander V. Chernikov 			ia = (struct in_ifaddr *)nh->nh_ifa;
13280895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13290895aec3SBjoern A. Zeeb 			goto done;
13300895aec3SBjoern A. Zeeb 		}
13310895aec3SBjoern A. Zeeb 
13320895aec3SBjoern A. Zeeb 		/*
13330895aec3SBjoern A. Zeeb 		 * 2. Check if we have any address on the outgoing interface
13340895aec3SBjoern A. Zeeb 		 *    belonging to this jail.
13350895aec3SBjoern A. Zeeb 		 */
13368c0fec80SRobert Watson 		ia = NULL;
13379ac7c6cfSAlexander V. Chernikov 		ifp = nh->nh_ifp;
1338d7c5a620SMatt Macy 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
13390895aec3SBjoern A. Zeeb 			sa = ifa->ifa_addr;
13400895aec3SBjoern A. Zeeb 			if (sa->sa_family != AF_INET)
13410895aec3SBjoern A. Zeeb 				continue;
13420895aec3SBjoern A. Zeeb 			sin = (struct sockaddr_in *)sa;
1343b89e82ddSJamie Gritton 			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
13440895aec3SBjoern A. Zeeb 				ia = (struct in_ifaddr *)ifa;
13450895aec3SBjoern A. Zeeb 				break;
13460895aec3SBjoern A. Zeeb 			}
13470895aec3SBjoern A. Zeeb 		}
13480895aec3SBjoern A. Zeeb 		if (ia != NULL) {
13490895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13500895aec3SBjoern A. Zeeb 			goto done;
13510895aec3SBjoern A. Zeeb 		}
13520895aec3SBjoern A. Zeeb 
13530895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1354b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
13550895aec3SBjoern A. Zeeb 		goto done;
13560895aec3SBjoern A. Zeeb 	}
13570895aec3SBjoern A. Zeeb 
13580895aec3SBjoern A. Zeeb 	/*
13590895aec3SBjoern A. Zeeb 	 * The outgoing interface is marked with 'loopback net', so a route
13600895aec3SBjoern A. Zeeb 	 * to ourselves is here.
13610895aec3SBjoern A. Zeeb 	 * Try to find the interface of the destination address and then
13620895aec3SBjoern A. Zeeb 	 * take the address from there. That interface is not necessarily
13630895aec3SBjoern A. Zeeb 	 * a loopback interface.
13640895aec3SBjoern A. Zeeb 	 * In case of jails, check that it is an address of the jail
13650895aec3SBjoern A. Zeeb 	 * and if we cannot find, fall back to the 'default' jail address.
13660895aec3SBjoern A. Zeeb 	 */
13679ac7c6cfSAlexander V. Chernikov 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) != 0) {
13688c0fec80SRobert Watson 		struct in_ifaddr *ia;
13690895aec3SBjoern A. Zeeb 
13709ac7c6cfSAlexander V. Chernikov 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&dst),
137158a39d8cSAlan Somers 					inp->inp_socket->so_fibnum));
13720895aec3SBjoern A. Zeeb 		if (ia == NULL)
13739ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithnet(sintosa(&dst), 0,
137458a39d8cSAlan Somers 						inp->inp_socket->so_fibnum));
1375f0bb05fcSQing Li 		if (ia == NULL)
13769ac7c6cfSAlexander V. Chernikov 			ia = ifatoia(ifa_ifwithaddr(sintosa(&dst)));
13770895aec3SBjoern A. Zeeb 
1378ac1750ddSMark Johnston 		if (!prison_flag(cred, PR_IP4)) {
13790895aec3SBjoern A. Zeeb 			if (ia == NULL) {
13800895aec3SBjoern A. Zeeb 				error = ENETUNREACH;
13810895aec3SBjoern A. Zeeb 				goto done;
13820895aec3SBjoern A. Zeeb 			}
13830895aec3SBjoern A. Zeeb 			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
13840895aec3SBjoern A. Zeeb 			goto done;
13850895aec3SBjoern A. Zeeb 		}
13860895aec3SBjoern A. Zeeb 
13870895aec3SBjoern A. Zeeb 		/* Jailed. */
13880895aec3SBjoern A. Zeeb 		if (ia != NULL) {
13890895aec3SBjoern A. Zeeb 			struct ifnet *ifp;
13900895aec3SBjoern A. Zeeb 
13910895aec3SBjoern A. Zeeb 			ifp = ia->ia_ifp;
13920895aec3SBjoern A. Zeeb 			ia = NULL;
1393d7c5a620SMatt Macy 			CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
13940895aec3SBjoern A. Zeeb 				sa = ifa->ifa_addr;
13950895aec3SBjoern A. Zeeb 				if (sa->sa_family != AF_INET)
13960895aec3SBjoern A. Zeeb 					continue;
13970895aec3SBjoern A. Zeeb 				sin = (struct sockaddr_in *)sa;
1398b89e82ddSJamie Gritton 				if (prison_check_ip4(cred,
1399b89e82ddSJamie Gritton 				    &sin->sin_addr) == 0) {
14000895aec3SBjoern A. Zeeb 					ia = (struct in_ifaddr *)ifa;
14010895aec3SBjoern A. Zeeb 					break;
14020895aec3SBjoern A. Zeeb 				}
14030895aec3SBjoern A. Zeeb 			}
14040895aec3SBjoern A. Zeeb 			if (ia != NULL) {
14050895aec3SBjoern A. Zeeb 				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
14060895aec3SBjoern A. Zeeb 				goto done;
14070895aec3SBjoern A. Zeeb 			}
14080895aec3SBjoern A. Zeeb 		}
14090895aec3SBjoern A. Zeeb 
14100895aec3SBjoern A. Zeeb 		/* 3. As a last resort return the 'default' jail address. */
1411b89e82ddSJamie Gritton 		error = prison_get_ip4(cred, laddr);
14120895aec3SBjoern A. Zeeb 		goto done;
14130895aec3SBjoern A. Zeeb 	}
14140895aec3SBjoern A. Zeeb 
14150895aec3SBjoern A. Zeeb done:
1416713264f6SMark Johnston 	if (error == 0 && laddr->s_addr == INADDR_ANY)
1417713264f6SMark Johnston 		return (EHOSTUNREACH);
14180895aec3SBjoern A. Zeeb 	return (error);
14190895aec3SBjoern A. Zeeb }
14200895aec3SBjoern A. Zeeb 
142126f9a767SRodney W. Grimes void
1422136d4f1cSRobert Watson in_pcbdisconnect(struct inpcb *inp)
1423df8bae1dSRodney W. Grimes {
14246b348152SRobert Watson 
14258501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
1426fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1427fdb987beSMark Johnston 	KASSERT(inp->inp_smr == SMR_SEQ_INVALID,
1428fdb987beSMark Johnston 	    ("%s: inp %p was already disconnected", __func__, inp));
1429df8bae1dSRodney W. Grimes 
1430fdb987beSMark Johnston 	in_pcbremhash_locked(inp);
1431fdb987beSMark Johnston 
1432fdb987beSMark Johnston 	/* See the comment in in_pcbinshash(). */
1433fdb987beSMark Johnston 	inp->inp_smr = smr_advance(inp->inp_pcbinfo->ipi_smr);
14342589ec0fSMark Johnston 	inp->inp_laddr.s_addr = INADDR_ANY;
1435df8bae1dSRodney W. Grimes 	inp->inp_faddr.s_addr = INADDR_ANY;
1436df8bae1dSRodney W. Grimes 	inp->inp_fport = 0;
1437df8bae1dSRodney W. Grimes }
143883e521ecSBjoern A. Zeeb #endif /* INET */
1439df8bae1dSRodney W. Grimes 
14407cbb6b6eSMark Johnston void
14417cbb6b6eSMark Johnston in_pcblisten(struct inpcb *inp)
14427cbb6b6eSMark Johnston {
14437cbb6b6eSMark Johnston 	struct inpcblbgroup *grp;
14447cbb6b6eSMark Johnston 
14457cbb6b6eSMark Johnston 	INP_WLOCK_ASSERT(inp);
14467cbb6b6eSMark Johnston 
14477cbb6b6eSMark Johnston 	if ((inp->inp_flags & INP_INLBGROUP) != 0) {
14487cbb6b6eSMark Johnston 		struct inpcbinfo *pcbinfo;
14497cbb6b6eSMark Johnston 
14507cbb6b6eSMark Johnston 		pcbinfo = inp->inp_pcbinfo;
14517cbb6b6eSMark Johnston 		INP_HASH_WLOCK(pcbinfo);
14527cbb6b6eSMark Johnston 		grp = in_pcblbgroup_find(inp);
14537cbb6b6eSMark Johnston 		LIST_REMOVE(inp, inp_lbgroup_list);
14548b3d2c19SMark Johnston 		grp->il_pendcnt--;
14557cbb6b6eSMark Johnston 		in_pcblbgroup_insert(grp, inp);
14567cbb6b6eSMark Johnston 		INP_HASH_WUNLOCK(pcbinfo);
14577cbb6b6eSMark Johnston 	}
14587cbb6b6eSMark Johnston }
14597cbb6b6eSMark Johnston 
14604c7c478dSRobert Watson /*
1461db0ac6deSCy Schubert  * inpcb hash lookups are protected by SMR section.
1462db0ac6deSCy Schubert  *
1463db0ac6deSCy Schubert  * Once desired pcb has been found, switching from SMR section to a pcb
1464db0ac6deSCy Schubert  * lock is performed with inp_smr_lock(). We can not use INP_(W|R)LOCK
1465db0ac6deSCy Schubert  * here because SMR is a critical section.
1466db0ac6deSCy Schubert  * In 99%+ cases inp_smr_lock() would obtain the lock immediately.
1467db0ac6deSCy Schubert  */
14687b92493aSMark Johnston void
1469db0ac6deSCy Schubert inp_lock(struct inpcb *inp, const inp_lookup_t lock)
1470db0ac6deSCy Schubert {
1471db0ac6deSCy Schubert 
1472db0ac6deSCy Schubert 	lock == INPLOOKUP_RLOCKPCB ?
1473db0ac6deSCy Schubert 	    rw_rlock(&inp->inp_lock) : rw_wlock(&inp->inp_lock);
1474db0ac6deSCy Schubert }
1475db0ac6deSCy Schubert 
14767b92493aSMark Johnston void
1477db0ac6deSCy Schubert inp_unlock(struct inpcb *inp, const inp_lookup_t lock)
1478db0ac6deSCy Schubert {
1479db0ac6deSCy Schubert 
1480db0ac6deSCy Schubert 	lock == INPLOOKUP_RLOCKPCB ?
1481db0ac6deSCy Schubert 	    rw_runlock(&inp->inp_lock) : rw_wunlock(&inp->inp_lock);
1482db0ac6deSCy Schubert }
1483db0ac6deSCy Schubert 
14847b92493aSMark Johnston int
1485db0ac6deSCy Schubert inp_trylock(struct inpcb *inp, const inp_lookup_t lock)
1486db0ac6deSCy Schubert {
1487db0ac6deSCy Schubert 
1488db0ac6deSCy Schubert 	return (lock == INPLOOKUP_RLOCKPCB ?
1489db0ac6deSCy Schubert 	    rw_try_rlock(&inp->inp_lock) : rw_try_wlock(&inp->inp_lock));
1490db0ac6deSCy Schubert }
1491db0ac6deSCy Schubert 
1492db0ac6deSCy Schubert static inline bool
1493f567d55fSGleb Smirnoff _inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock, const int ignflags)
1494db0ac6deSCy Schubert {
1495db0ac6deSCy Schubert 
1496db0ac6deSCy Schubert 	MPASS(lock == INPLOOKUP_RLOCKPCB || lock == INPLOOKUP_WLOCKPCB);
1497db0ac6deSCy Schubert 	SMR_ASSERT_ENTERED(inp->inp_pcbinfo->ipi_smr);
1498db0ac6deSCy Schubert 
1499db0ac6deSCy Schubert 	if (__predict_true(inp_trylock(inp, lock))) {
1500f567d55fSGleb Smirnoff 		if (__predict_false(inp->inp_flags & ignflags)) {
1501db0ac6deSCy Schubert 			smr_exit(inp->inp_pcbinfo->ipi_smr);
1502db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1503db0ac6deSCy Schubert 			return (false);
1504db0ac6deSCy Schubert 		}
1505db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1506db0ac6deSCy Schubert 		return (true);
1507db0ac6deSCy Schubert 	}
1508db0ac6deSCy Schubert 
1509db0ac6deSCy Schubert 	if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1510db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1511db0ac6deSCy Schubert 		inp_lock(inp, lock);
1512db0ac6deSCy Schubert 		if (__predict_false(in_pcbrele(inp, lock)))
1513db0ac6deSCy Schubert 			return (false);
1514db0ac6deSCy Schubert 		/*
1515db0ac6deSCy Schubert 		 * inp acquired through refcount & lock for sure didn't went
1516db0ac6deSCy Schubert 		 * through uma_zfree().  However, it may have already went
1517db0ac6deSCy Schubert 		 * through in_pcbfree() and has another reference, that
1518db0ac6deSCy Schubert 		 * prevented its release by our in_pcbrele().
1519db0ac6deSCy Schubert 		 */
1520f567d55fSGleb Smirnoff 		if (__predict_false(inp->inp_flags & ignflags)) {
1521db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1522db0ac6deSCy Schubert 			return (false);
1523db0ac6deSCy Schubert 		}
1524db0ac6deSCy Schubert 		return (true);
1525db0ac6deSCy Schubert 	} else {
1526db0ac6deSCy Schubert 		smr_exit(inp->inp_pcbinfo->ipi_smr);
1527db0ac6deSCy Schubert 		return (false);
1528db0ac6deSCy Schubert 	}
1529db0ac6deSCy Schubert }
1530db0ac6deSCy Schubert 
1531f567d55fSGleb Smirnoff bool
1532f567d55fSGleb Smirnoff inp_smr_lock(struct inpcb *inp, const inp_lookup_t lock)
1533f567d55fSGleb Smirnoff {
1534f567d55fSGleb Smirnoff 
1535f567d55fSGleb Smirnoff 	/*
1536f567d55fSGleb Smirnoff 	 * in_pcblookup() family of functions ignore not only freed entries,
1537f567d55fSGleb Smirnoff 	 * that may be found due to lockless access to the hash, but dropped
1538f567d55fSGleb Smirnoff 	 * entries, too.
1539f567d55fSGleb Smirnoff 	 */
1540f567d55fSGleb Smirnoff 	return (_inp_smr_lock(inp, lock, INP_FREED | INP_DROPPED));
1541f567d55fSGleb Smirnoff }
1542f567d55fSGleb Smirnoff 
1543db0ac6deSCy Schubert /*
1544db0ac6deSCy Schubert  * inp_next() - inpcb hash/list traversal iterator
1545db0ac6deSCy Schubert  *
1546db0ac6deSCy Schubert  * Requires initialized struct inpcb_iterator for context.
1547db0ac6deSCy Schubert  * The structure can be initialized with INP_ITERATOR() or INP_ALL_ITERATOR().
1548db0ac6deSCy Schubert  *
1549db0ac6deSCy Schubert  * - Iterator can have either write-lock or read-lock semantics, that can not
1550db0ac6deSCy Schubert  *   be changed later.
1551db0ac6deSCy Schubert  * - Iterator can iterate either over all pcbs list (INP_ALL_LIST), or through
1552db0ac6deSCy Schubert  *   a single hash slot.  Note: only rip_input() does the latter.
1553db0ac6deSCy Schubert  * - Iterator may have optional bool matching function.  The matching function
1554db0ac6deSCy Schubert  *   will be executed for each inpcb in the SMR context, so it can not acquire
1555db0ac6deSCy Schubert  *   locks and can safely access only immutable fields of inpcb.
1556db0ac6deSCy Schubert  *
1557db0ac6deSCy Schubert  * A fresh initialized iterator has NULL inpcb in its context and that
1558db0ac6deSCy Schubert  * means that inp_next() call would return the very first inpcb on the list
1559db0ac6deSCy Schubert  * locked with desired semantic.  In all following calls the context pointer
1560db0ac6deSCy Schubert  * shall hold the current inpcb pointer.  The KPI user is not supposed to
1561db0ac6deSCy Schubert  * unlock the current inpcb!  Upon end of traversal inp_next() will return NULL
1562db0ac6deSCy Schubert  * and write NULL to its context.  After end of traversal an iterator can be
1563db0ac6deSCy Schubert  * reused.
1564db0ac6deSCy Schubert  *
1565db0ac6deSCy Schubert  * List traversals have the following features/constraints:
1566db0ac6deSCy Schubert  * - New entries won't be seen, as they are always added to the head of a list.
1567db0ac6deSCy Schubert  * - Removed entries won't stop traversal as long as they are not added to
1568db0ac6deSCy Schubert  *   a different list. This is violated by in_pcbrehash().
1569db0ac6deSCy Schubert  */
1570db0ac6deSCy Schubert #define	II_LIST_FIRST(ipi, hash)					\
1571db0ac6deSCy Schubert 		(((hash) == INP_ALL_LIST) ?				\
1572db0ac6deSCy Schubert 		    CK_LIST_FIRST(&(ipi)->ipi_listhead) :		\
1573fdb987beSMark Johnston 		    CK_LIST_FIRST(&(ipi)->ipi_hash_exact[(hash)]))
1574db0ac6deSCy Schubert #define	II_LIST_NEXT(inp, hash)						\
1575db0ac6deSCy Schubert 		(((hash) == INP_ALL_LIST) ?				\
1576db0ac6deSCy Schubert 		    CK_LIST_NEXT((inp), inp_list) :			\
1577fdb987beSMark Johnston 		    CK_LIST_NEXT((inp), inp_hash_exact))
1578db0ac6deSCy Schubert #define	II_LOCK_ASSERT(inp, lock)					\
1579db0ac6deSCy Schubert 		rw_assert(&(inp)->inp_lock,				\
1580db0ac6deSCy Schubert 		    (lock) == INPLOOKUP_RLOCKPCB ?  RA_RLOCKED : RA_WLOCKED )
1581db0ac6deSCy Schubert struct inpcb *
1582db0ac6deSCy Schubert inp_next(struct inpcb_iterator *ii)
1583db0ac6deSCy Schubert {
1584db0ac6deSCy Schubert 	const struct inpcbinfo *ipi = ii->ipi;
1585db0ac6deSCy Schubert 	inp_match_t *match = ii->match;
1586db0ac6deSCy Schubert 	void *ctx = ii->ctx;
1587db0ac6deSCy Schubert 	inp_lookup_t lock = ii->lock;
1588db0ac6deSCy Schubert 	int hash = ii->hash;
1589db0ac6deSCy Schubert 	struct inpcb *inp;
1590db0ac6deSCy Schubert 
1591db0ac6deSCy Schubert 	if (ii->inp == NULL) {		/* First call. */
1592db0ac6deSCy Schubert 		smr_enter(ipi->ipi_smr);
1593db0ac6deSCy Schubert 		/* This is unrolled CK_LIST_FOREACH(). */
1594db0ac6deSCy Schubert 		for (inp = II_LIST_FIRST(ipi, hash);
1595db0ac6deSCy Schubert 		    inp != NULL;
1596db0ac6deSCy Schubert 		    inp = II_LIST_NEXT(inp, hash)) {
1597db0ac6deSCy Schubert 			if (match != NULL && (match)(inp, ctx) == false)
1598db0ac6deSCy Schubert 				continue;
1599f567d55fSGleb Smirnoff 			if (__predict_true(_inp_smr_lock(inp, lock, INP_FREED)))
1600db0ac6deSCy Schubert 				break;
1601db0ac6deSCy Schubert 			else {
1602db0ac6deSCy Schubert 				smr_enter(ipi->ipi_smr);
1603db0ac6deSCy Schubert 				MPASS(inp != II_LIST_FIRST(ipi, hash));
1604db0ac6deSCy Schubert 				inp = II_LIST_FIRST(ipi, hash);
1605430df2abSMichael Tuexen 				if (inp == NULL)
1606430df2abSMichael Tuexen 					break;
1607db0ac6deSCy Schubert 			}
1608db0ac6deSCy Schubert 		}
1609db0ac6deSCy Schubert 
1610db0ac6deSCy Schubert 		if (inp == NULL)
1611db0ac6deSCy Schubert 			smr_exit(ipi->ipi_smr);
1612db0ac6deSCy Schubert 		else
1613db0ac6deSCy Schubert 			ii->inp = inp;
1614db0ac6deSCy Schubert 
1615db0ac6deSCy Schubert 		return (inp);
1616db0ac6deSCy Schubert 	}
1617db0ac6deSCy Schubert 
1618db0ac6deSCy Schubert 	/* Not a first call. */
1619db0ac6deSCy Schubert 	smr_enter(ipi->ipi_smr);
1620db0ac6deSCy Schubert restart:
1621db0ac6deSCy Schubert 	inp = ii->inp;
1622db0ac6deSCy Schubert 	II_LOCK_ASSERT(inp, lock);
1623db0ac6deSCy Schubert next:
1624db0ac6deSCy Schubert 	inp = II_LIST_NEXT(inp, hash);
1625db0ac6deSCy Schubert 	if (inp == NULL) {
1626db0ac6deSCy Schubert 		smr_exit(ipi->ipi_smr);
1627db0ac6deSCy Schubert 		goto found;
1628db0ac6deSCy Schubert 	}
1629db0ac6deSCy Schubert 
1630db0ac6deSCy Schubert 	if (match != NULL && (match)(inp, ctx) == false)
1631db0ac6deSCy Schubert 		goto next;
1632db0ac6deSCy Schubert 
1633db0ac6deSCy Schubert 	if (__predict_true(inp_trylock(inp, lock))) {
1634db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1635db0ac6deSCy Schubert 			/*
1636db0ac6deSCy Schubert 			 * Entries are never inserted in middle of a list, thus
1637db0ac6deSCy Schubert 			 * as long as we are in SMR, we can continue traversal.
1638db0ac6deSCy Schubert 			 * Jump to 'restart' should yield in the same result,
1639db0ac6deSCy Schubert 			 * but could produce unnecessary looping.  Could this
1640db0ac6deSCy Schubert 			 * looping be unbound?
1641db0ac6deSCy Schubert 			 */
1642db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1643db0ac6deSCy Schubert 			goto next;
1644db0ac6deSCy Schubert 		} else {
1645db0ac6deSCy Schubert 			smr_exit(ipi->ipi_smr);
1646db0ac6deSCy Schubert 			goto found;
1647db0ac6deSCy Schubert 		}
1648db0ac6deSCy Schubert 	}
1649db0ac6deSCy Schubert 
1650db0ac6deSCy Schubert 	/*
1651db0ac6deSCy Schubert 	 * Can't obtain lock immediately, thus going hard.  Once we exit the
1652db0ac6deSCy Schubert 	 * SMR section we can no longer jump to 'next', and our only stable
1653db0ac6deSCy Schubert 	 * anchoring point is ii->inp, which we keep locked for this case, so
1654db0ac6deSCy Schubert 	 * we jump to 'restart'.
1655db0ac6deSCy Schubert 	 */
1656db0ac6deSCy Schubert 	if (__predict_true(refcount_acquire_if_not_zero(&inp->inp_refcount))) {
1657db0ac6deSCy Schubert 		smr_exit(ipi->ipi_smr);
1658db0ac6deSCy Schubert 		inp_lock(inp, lock);
1659db0ac6deSCy Schubert 		if (__predict_false(in_pcbrele(inp, lock))) {
1660db0ac6deSCy Schubert 			smr_enter(ipi->ipi_smr);
1661db0ac6deSCy Schubert 			goto restart;
1662db0ac6deSCy Schubert 		}
1663db0ac6deSCy Schubert 		/*
1664db0ac6deSCy Schubert 		 * See comment in inp_smr_lock().
1665db0ac6deSCy Schubert 		 */
1666db0ac6deSCy Schubert 		if (__predict_false(inp->inp_flags & INP_FREED)) {
1667db0ac6deSCy Schubert 			inp_unlock(inp, lock);
1668db0ac6deSCy Schubert 			smr_enter(ipi->ipi_smr);
1669db0ac6deSCy Schubert 			goto restart;
1670db0ac6deSCy Schubert 		}
1671db0ac6deSCy Schubert 	} else
1672db0ac6deSCy Schubert 		goto next;
1673db0ac6deSCy Schubert 
1674db0ac6deSCy Schubert found:
1675db0ac6deSCy Schubert 	inp_unlock(ii->inp, lock);
1676db0ac6deSCy Schubert 	ii->inp = inp;
1677db0ac6deSCy Schubert 
1678db0ac6deSCy Schubert 	return (ii->inp);
1679db0ac6deSCy Schubert }
1680db0ac6deSCy Schubert 
1681db0ac6deSCy Schubert /*
168279bdc6e5SRobert Watson  * in_pcbref() bumps the reference count on an inpcb in order to maintain
1683db0ac6deSCy Schubert  * stability of an inpcb pointer despite the inpcb lock being released or
1684db0ac6deSCy Schubert  * SMR section exited.
168579bdc6e5SRobert Watson  *
1686db0ac6deSCy Schubert  * To free a reference later in_pcbrele_(r|w)locked() must be performed.
1687c0a211c5SRobert Watson  */
168879bdc6e5SRobert Watson void
168979bdc6e5SRobert Watson in_pcbref(struct inpcb *inp)
16904c7c478dSRobert Watson {
1691db0ac6deSCy Schubert 	u_int old __diagused;
1692df8bae1dSRodney W. Grimes 
1693db0ac6deSCy Schubert 	old = refcount_acquire(&inp->inp_refcount);
1694db0ac6deSCy Schubert 	KASSERT(old > 0, ("%s: refcount 0", __func__));
169579bdc6e5SRobert Watson }
169679bdc6e5SRobert Watson 
169779bdc6e5SRobert Watson /*
1698db0ac6deSCy Schubert  * Drop a refcount on an inpcb elevated using in_pcbref(), potentially
1699db0ac6deSCy Schubert  * freeing the pcb, if the reference was very last.
170079bdc6e5SRobert Watson  */
1701db0ac6deSCy Schubert bool
170279bdc6e5SRobert Watson in_pcbrele_rlocked(struct inpcb *inp)
170379bdc6e5SRobert Watson {
170479bdc6e5SRobert Watson 
170579bdc6e5SRobert Watson 	INP_RLOCK_ASSERT(inp);
170679bdc6e5SRobert Watson 
1707c7ea65ecSMark Johnston 	if (!refcount_release(&inp->inp_refcount))
1708db0ac6deSCy Schubert 		return (false);
1709db0ac6deSCy Schubert 
1710db0ac6deSCy Schubert 	MPASS(inp->inp_flags & INP_FREED);
1711db0ac6deSCy Schubert 	MPASS(inp->inp_socket == NULL);
17125fd1a67eSMark Johnston 	crfree(inp->inp_cred);
17135fd1a67eSMark Johnston #ifdef INVARIANTS
17145fd1a67eSMark Johnston 	inp->inp_cred = NULL;
17155fd1a67eSMark Johnston #endif
1716df4e91d3SGleb Smirnoff 	INP_RUNLOCK(inp);
1717db0ac6deSCy Schubert 	uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1718db0ac6deSCy Schubert 	return (true);
1719df4e91d3SGleb Smirnoff }
172079bdc6e5SRobert Watson 
1721db0ac6deSCy Schubert bool
172279bdc6e5SRobert Watson in_pcbrele_wlocked(struct inpcb *inp)
172379bdc6e5SRobert Watson {
172479bdc6e5SRobert Watson 
172579bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
172679bdc6e5SRobert Watson 
1727c7ea65ecSMark Johnston 	if (!refcount_release(&inp->inp_refcount))
1728db0ac6deSCy Schubert 		return (false);
1729db0ac6deSCy Schubert 
1730db0ac6deSCy Schubert 	MPASS(inp->inp_flags & INP_FREED);
1731db0ac6deSCy Schubert 	MPASS(inp->inp_socket == NULL);
17325fd1a67eSMark Johnston 	crfree(inp->inp_cred);
17335fd1a67eSMark Johnston #ifdef INVARIANTS
17345fd1a67eSMark Johnston 	inp->inp_cred = NULL;
17355fd1a67eSMark Johnston #endif
1736edd0e0b0SFabien Thomas 	INP_WUNLOCK(inp);
1737db0ac6deSCy Schubert 	uma_zfree_smr(inp->inp_pcbinfo->ipi_zone, inp);
1738db0ac6deSCy Schubert 	return (true);
1739addf2b20SMatt Macy }
1740addf2b20SMatt Macy 
17417b92493aSMark Johnston bool
17427b92493aSMark Johnston in_pcbrele(struct inpcb *inp, const inp_lookup_t lock)
17437b92493aSMark Johnston {
17447b92493aSMark Johnston 
17457b92493aSMark Johnston 	return (lock == INPLOOKUP_RLOCKPCB ?
17467b92493aSMark Johnston 	    in_pcbrele_rlocked(inp) : in_pcbrele_wlocked(inp));
17477b92493aSMark Johnston }
17487b92493aSMark Johnston 
174979bdc6e5SRobert Watson /*
175079bdc6e5SRobert Watson  * Unconditionally schedule an inpcb to be freed by decrementing its
175179bdc6e5SRobert Watson  * reference count, which should occur only after the inpcb has been detached
175279bdc6e5SRobert Watson  * from its socket.  If another thread holds a temporary reference (acquired
175379bdc6e5SRobert Watson  * using in_pcbref()) then the free is deferred until that reference is
1754db0ac6deSCy Schubert  * released using in_pcbrele_(r|w)locked(), but the inpcb is still unlocked.
1755db0ac6deSCy Schubert  *  Almost all work, including removal from global lists, is done in this
1756db0ac6deSCy Schubert  * context, where the pcbinfo lock is held.
175779bdc6e5SRobert Watson  */
175879bdc6e5SRobert Watson void
175979bdc6e5SRobert Watson in_pcbfree(struct inpcb *inp)
176079bdc6e5SRobert Watson {
1761f42a83f2SMatt Macy 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1762db0ac6deSCy Schubert #ifdef INET
1763db0ac6deSCy Schubert 	struct ip_moptions *imo;
1764db0ac6deSCy Schubert #endif
1765db0ac6deSCy Schubert #ifdef INET6
1766db0ac6deSCy Schubert 	struct ip6_moptions *im6o;
1767db0ac6deSCy Schubert #endif
176845a48d07SJonathan T. Looney 
176979bdc6e5SRobert Watson 	INP_WLOCK_ASSERT(inp);
1770a13039e2SGleb Smirnoff 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1771db0ac6deSCy Schubert 	KASSERT((inp->inp_flags & INP_FREED) == 0,
1772db0ac6deSCy Schubert 	    ("%s: called twice for pcb %p", __func__, inp));
1773db0ac6deSCy Schubert 
1774a13039e2SGleb Smirnoff 	/*
1775a13039e2SGleb Smirnoff 	 * in_pcblookup_local() and in6_pcblookup_local() may return an inpcb
1776a13039e2SGleb Smirnoff 	 * from the hash without acquiring inpcb lock, they rely on the hash
1777a13039e2SGleb Smirnoff 	 * lock, thus in_pcbremhash() should be the first action.
1778a13039e2SGleb Smirnoff 	 */
1779a13039e2SGleb Smirnoff 	if (inp->inp_flags & INP_INHASHLIST)
1780a13039e2SGleb Smirnoff 		in_pcbremhash(inp);
1781db0ac6deSCy Schubert 	INP_INFO_WLOCK(pcbinfo);
1782db0ac6deSCy Schubert 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1783db0ac6deSCy Schubert 	pcbinfo->ipi_count--;
1784db0ac6deSCy Schubert 	CK_LIST_REMOVE(inp, inp_list);
1785db0ac6deSCy Schubert 	INP_INFO_WUNLOCK(pcbinfo);
1786db0ac6deSCy Schubert 
1787a13039e2SGleb Smirnoff #ifdef RATELIMIT
1788a13039e2SGleb Smirnoff 	if (inp->inp_snd_tag != NULL)
1789a13039e2SGleb Smirnoff 		in_pcbdetach_txrtlmt(inp);
1790a13039e2SGleb Smirnoff #endif
1791a13039e2SGleb Smirnoff 	inp->inp_flags |= INP_FREED;
1792a13039e2SGleb Smirnoff 	inp->inp_socket->so_pcb = NULL;
1793a13039e2SGleb Smirnoff 	inp->inp_socket = NULL;
1794db0ac6deSCy Schubert 
1795fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
1796db0ac6deSCy Schubert #ifdef MAC
1797db0ac6deSCy Schubert 	mac_inpcb_destroy(inp);
1798db0ac6deSCy Schubert #endif
1799db0ac6deSCy Schubert #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1800db0ac6deSCy Schubert 	if (inp->inp_sp != NULL)
1801db0ac6deSCy Schubert 		ipsec_delete_pcbpolicy(inp);
1802db0ac6deSCy Schubert #endif
1803db0ac6deSCy Schubert #ifdef INET
1804db0ac6deSCy Schubert 	if (inp->inp_options)
1805db0ac6deSCy Schubert 		(void)m_free(inp->inp_options);
18064a0c6403SGleb Smirnoff 	DEBUG_POISON_POINTER(inp->inp_options);
1807db0ac6deSCy Schubert 	imo = inp->inp_moptions;
18084a0c6403SGleb Smirnoff 	DEBUG_POISON_POINTER(inp->inp_moptions);
1809db0ac6deSCy Schubert #endif
1810db0ac6deSCy Schubert #ifdef INET6
1811db0ac6deSCy Schubert 	if (inp->inp_vflag & INP_IPV6PROTO) {
1812db0ac6deSCy Schubert 		ip6_freepcbopts(inp->in6p_outputopts);
18134a0c6403SGleb Smirnoff 		DEBUG_POISON_POINTER(inp->in6p_outputopts);
1814db0ac6deSCy Schubert 		im6o = inp->in6p_moptions;
18154a0c6403SGleb Smirnoff 		DEBUG_POISON_POINTER(inp->in6p_moptions);
1816db0ac6deSCy Schubert 	} else
1817db0ac6deSCy Schubert 		im6o = NULL;
1818db0ac6deSCy Schubert #endif
1819db0ac6deSCy Schubert 
1820db0ac6deSCy Schubert 	if (__predict_false(in_pcbrele_wlocked(inp) == false)) {
1821cb6bb230SMatt Macy 		INP_WUNLOCK(inp);
1822db0ac6deSCy Schubert 	}
1823db0ac6deSCy Schubert #ifdef INET6
1824db0ac6deSCy Schubert 	ip6_freemoptions(im6o);
1825db0ac6deSCy Schubert #endif
1826db0ac6deSCy Schubert #ifdef INET
1827db0ac6deSCy Schubert 	inp_freemoptions(imo);
1828db0ac6deSCy Schubert #endif
1829eb93b99dSGleb Smirnoff }
1830eb93b99dSGleb Smirnoff 
1831eb93b99dSGleb Smirnoff /*
1832eb93b99dSGleb Smirnoff  * Different protocols initialize their inpcbs differently - giving
1833eb93b99dSGleb Smirnoff  * different name to the lock.  But they all are disposed the same.
1834eb93b99dSGleb Smirnoff  */
1835eb93b99dSGleb Smirnoff static void
1836eb93b99dSGleb Smirnoff inpcb_fini(void *mem, int size)
1837eb93b99dSGleb Smirnoff {
1838eb93b99dSGleb Smirnoff 	struct inpcb *inp = mem;
1839eb93b99dSGleb Smirnoff 
1840eb93b99dSGleb Smirnoff 	INP_LOCK_DESTROY(inp);
184128696211SRobert Watson }
184228696211SRobert Watson 
184328696211SRobert Watson /*
1844c0a211c5SRobert Watson  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1845c0a211c5SRobert Watson  * port reservation, and preventing it from being returned by inpcb lookups.
1846c0a211c5SRobert Watson  *
1847c0a211c5SRobert Watson  * It is used by TCP to mark an inpcb as unused and avoid future packet
1848c0a211c5SRobert Watson  * delivery or event notification when a socket remains open but TCP has
1849c0a211c5SRobert Watson  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1850c0a211c5SRobert Watson  * or a RST on the wire, and allows the port binding to be reused while still
1851c0a211c5SRobert Watson  * maintaining the invariant that so_pcb always points to a valid inpcb until
1852c0a211c5SRobert Watson  * in_pcbdetach().
1853c0a211c5SRobert Watson  *
1854c0a211c5SRobert Watson  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1855bbbd7aabSGleb Smirnoff  * in_pcbpurgeif0()?
185610702a28SRobert Watson  */
185710702a28SRobert Watson void
185810702a28SRobert Watson in_pcbdrop(struct inpcb *inp)
185910702a28SRobert Watson {
186010702a28SRobert Watson 
18618501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
186210702a28SRobert Watson 
1863ad71fe3cSRobert Watson 	inp->inp_flags |= INP_DROPPED;
18643ba34b07SGleb Smirnoff 	if (inp->inp_flags & INP_INHASHLIST)
18653ba34b07SGleb Smirnoff 		in_pcbremhash(inp);
186610702a28SRobert Watson }
186710702a28SRobert Watson 
186867107f45SBjoern A. Zeeb #ifdef INET
186954d642bbSRobert Watson /*
187054d642bbSRobert Watson  * Common routines to return the socket addresses associated with inpcbs.
187154d642bbSRobert Watson  */
1872117bcae7SGarrett Wollman int
18730fac350cSGleb Smirnoff in_getsockaddr(struct socket *so, struct sockaddr *sa)
1874df8bae1dSRodney W. Grimes {
1875136d4f1cSRobert Watson 	struct inpcb *inp;
187642fa505bSDavid Greenman 
1877fdc984f7STor Egge 	inp = sotoinpcb(so);
187854d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
18796466b28aSRobert Watson 
18800fac350cSGleb Smirnoff 	*(struct sockaddr_in *)sa = (struct sockaddr_in ){
18810fac350cSGleb Smirnoff 		.sin_len = sizeof(struct sockaddr_in),
18820fac350cSGleb Smirnoff 		.sin_family = AF_INET,
18830fac350cSGleb Smirnoff 		.sin_port = inp->inp_lport,
18840fac350cSGleb Smirnoff 		.sin_addr = inp->inp_laddr,
18850fac350cSGleb Smirnoff 	};
188642fa505bSDavid Greenman 
18870fac350cSGleb Smirnoff 	return (0);
1888df8bae1dSRodney W. Grimes }
1889df8bae1dSRodney W. Grimes 
1890117bcae7SGarrett Wollman int
18910fac350cSGleb Smirnoff in_getpeeraddr(struct socket *so, struct sockaddr *sa)
1892df8bae1dSRodney W. Grimes {
1893136d4f1cSRobert Watson 	struct inpcb *inp;
189442fa505bSDavid Greenman 
1895fdc984f7STor Egge 	inp = sotoinpcb(so);
189654d642bbSRobert Watson 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
18976466b28aSRobert Watson 
18980fac350cSGleb Smirnoff 	*(struct sockaddr_in *)sa = (struct sockaddr_in ){
18990fac350cSGleb Smirnoff 		.sin_len = sizeof(struct sockaddr_in),
19000fac350cSGleb Smirnoff 		.sin_family = AF_INET,
19010fac350cSGleb Smirnoff 		.sin_port = inp->inp_fport,
19020fac350cSGleb Smirnoff 		.sin_addr = inp->inp_faddr,
19030fac350cSGleb Smirnoff 	};
190442fa505bSDavid Greenman 
19050fac350cSGleb Smirnoff 	return (0);
1906df8bae1dSRodney W. Grimes }
1907df8bae1dSRodney W. Grimes 
1908db0ac6deSCy Schubert static bool
1909db0ac6deSCy Schubert inp_v4_multi_match(const struct inpcb *inp, void *v __unused)
1910db0ac6deSCy Schubert {
1911db0ac6deSCy Schubert 
1912db0ac6deSCy Schubert 	if ((inp->inp_vflag & INP_IPV4) && inp->inp_moptions != NULL)
1913db0ac6deSCy Schubert 		return (true);
1914db0ac6deSCy Schubert 	else
1915db0ac6deSCy Schubert 		return (false);
1916db0ac6deSCy Schubert }
1917db0ac6deSCy Schubert 
1918e43cc4aeSHajimu UMEMOTO void
1919136d4f1cSRobert Watson in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1920e43cc4aeSHajimu UMEMOTO {
1921db0ac6deSCy Schubert 	struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
1922db0ac6deSCy Schubert 	    inp_v4_multi_match, NULL);
1923e43cc4aeSHajimu UMEMOTO 	struct inpcb *inp;
192459854ecfSHans Petter Selasky 	struct in_multi *inm;
192559854ecfSHans Petter Selasky 	struct in_mfilter *imf;
1926e43cc4aeSHajimu UMEMOTO 	struct ip_moptions *imo;
1927e43cc4aeSHajimu UMEMOTO 
1928db0ac6deSCy Schubert 	IN_MULTI_LOCK_ASSERT();
1929db0ac6deSCy Schubert 
1930db0ac6deSCy Schubert 	while ((inp = inp_next(&inpi)) != NULL) {
1931db0ac6deSCy Schubert 		INP_WLOCK_ASSERT(inp);
1932db0ac6deSCy Schubert 
1933e43cc4aeSHajimu UMEMOTO 		imo = inp->inp_moptions;
1934e43cc4aeSHajimu UMEMOTO 		/*
1935e43cc4aeSHajimu UMEMOTO 		 * Unselect the outgoing interface if it is being
1936e43cc4aeSHajimu UMEMOTO 		 * detached.
1937e43cc4aeSHajimu UMEMOTO 		 */
1938e43cc4aeSHajimu UMEMOTO 		if (imo->imo_multicast_ifp == ifp)
1939e43cc4aeSHajimu UMEMOTO 			imo->imo_multicast_ifp = NULL;
1940e43cc4aeSHajimu UMEMOTO 
1941e43cc4aeSHajimu UMEMOTO 		/*
1942e43cc4aeSHajimu UMEMOTO 		 * Drop multicast group membership if we joined
1943e43cc4aeSHajimu UMEMOTO 		 * through the interface being detached.
1944cb6bb230SMatt Macy 		 *
1945cb6bb230SMatt Macy 		 * XXX This can all be deferred to an epoch_call
1946e43cc4aeSHajimu UMEMOTO 		 */
194759854ecfSHans Petter Selasky restart:
194859854ecfSHans Petter Selasky 		IP_MFILTER_FOREACH(imf, &imo->imo_head) {
194959854ecfSHans Petter Selasky 			if ((inm = imf->imf_inm) == NULL)
195059854ecfSHans Petter Selasky 				continue;
195159854ecfSHans Petter Selasky 			if (inm->inm_ifp != ifp)
195259854ecfSHans Petter Selasky 				continue;
195359854ecfSHans Petter Selasky 			ip_mfilter_remove(&imo->imo_head, imf);
195459854ecfSHans Petter Selasky 			in_leavegroup_locked(inm, NULL);
195559854ecfSHans Petter Selasky 			ip_mfilter_free(imf);
195659854ecfSHans Petter Selasky 			goto restart;
1957e43cc4aeSHajimu UMEMOTO 		}
1958e43cc4aeSHajimu UMEMOTO 	}
1959e43cc4aeSHajimu UMEMOTO }
1960e43cc4aeSHajimu UMEMOTO 
1961df8bae1dSRodney W. Grimes /*
1962fa046d87SRobert Watson  * Lookup a PCB based on the local address and port.  Caller must hold the
1963fa046d87SRobert Watson  * hash lock.  No inpcb locks or references are acquired.
1964c3229e05SDavid Greenman  */
1965d5e8a67eSHajimu UMEMOTO #define INP_LOOKUP_MAPPED_PCB_COST	3
1966df8bae1dSRodney W. Grimes struct inpcb *
1967136d4f1cSRobert Watson in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
19689a413162SMark Johnston     u_short lport, int fib, int lookupflags, struct ucred *cred)
1969df8bae1dSRodney W. Grimes {
1970136d4f1cSRobert Watson 	struct inpcb *inp;
1971d5e8a67eSHajimu UMEMOTO #ifdef INET6
1972d5e8a67eSHajimu UMEMOTO 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1973d5e8a67eSHajimu UMEMOTO #else
1974d5e8a67eSHajimu UMEMOTO 	int matchwild = 3;
1975d5e8a67eSHajimu UMEMOTO #endif
1976d5e8a67eSHajimu UMEMOTO 	int wildcard;
19777bc4aca7SDavid Greenman 
197868e0d7e0SRobert Watson 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
197968e0d7e0SRobert Watson 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
19809a413162SMark Johnston 	KASSERT(fib == RT_ALL_FIBS || (fib >= 0 && fib < V_rt_numfibs),
19819a413162SMark Johnston 	    ("%s: invalid fib %d", __func__, fib));
19829a413162SMark Johnston 
1983fa046d87SRobert Watson 	INP_HASH_LOCK_ASSERT(pcbinfo);
19841b73ca0bSSam Leffler 
198568e0d7e0SRobert Watson 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1986c3229e05SDavid Greenman 		struct inpcbhead *head;
1987c3229e05SDavid Greenman 		/*
1988c3229e05SDavid Greenman 		 * Look for an unconnected (wildcard foreign addr) PCB that
1989c3229e05SDavid Greenman 		 * matches the local address and port we're looking for.
1990c3229e05SDavid Greenman 		 */
1991fdb987beSMark Johnston 		head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
1992a0577692SGleb Smirnoff 		    pcbinfo->ipi_hashmask)];
1993fdb987beSMark Johnston 		CK_LIST_FOREACH(inp, head, inp_hash_wild) {
1994cfa1ca9dSYoshinobu Inoue #ifdef INET6
1995413628a7SBjoern A. Zeeb 			/* XXX inp locking */
1996369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
1997cfa1ca9dSYoshinobu Inoue 				continue;
1998cfa1ca9dSYoshinobu Inoue #endif
1999c3229e05SDavid Greenman 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
2000c3229e05SDavid Greenman 			    inp->inp_laddr.s_addr == laddr.s_addr &&
20019a413162SMark Johnston 			    inp->inp_lport == lport && (fib == RT_ALL_FIBS ||
20029a413162SMark Johnston 			    inp->inp_inc.inc_fibnum == fib)) {
2003c3229e05SDavid Greenman 				/*
2004413628a7SBjoern A. Zeeb 				 * Found?
2005c3229e05SDavid Greenman 				 */
2006ac1750ddSMark Johnston 				if (prison_equal_ip4(cred->cr_prison,
20070304c731SJamie Gritton 				    inp->inp_cred->cr_prison))
2008c3229e05SDavid Greenman 					return (inp);
2009df8bae1dSRodney W. Grimes 			}
2010c3229e05SDavid Greenman 		}
2011c3229e05SDavid Greenman 		/*
2012c3229e05SDavid Greenman 		 * Not found.
2013c3229e05SDavid Greenman 		 */
2014c3229e05SDavid Greenman 		return (NULL);
2015c3229e05SDavid Greenman 	} else {
20165f539170SGleb Smirnoff 		struct inpcbhead *porthash;
2017c3229e05SDavid Greenman 		struct inpcb *match = NULL;
20185f539170SGleb Smirnoff 
2019c3229e05SDavid Greenman 		/*
2020c3229e05SDavid Greenman 		 * Port is in use by one or more PCBs. Look for best
2021c3229e05SDavid Greenman 		 * fit.
2022c3229e05SDavid Greenman 		 */
20235f539170SGleb Smirnoff 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
20245f539170SGleb Smirnoff 		    pcbinfo->ipi_porthashmask)];
20255f539170SGleb Smirnoff 		CK_LIST_FOREACH(inp, porthash, inp_portlist) {
20265f539170SGleb Smirnoff 			if (inp->inp_lport != lport)
20275f539170SGleb Smirnoff 				continue;
2028ac1750ddSMark Johnston 			if (!prison_equal_ip4(inp->inp_cred->cr_prison,
20290304c731SJamie Gritton 			    cred->cr_prison))
2030413628a7SBjoern A. Zeeb 				continue;
20319a413162SMark Johnston 			if (fib != RT_ALL_FIBS &&
20329a413162SMark Johnston 			    inp->inp_inc.inc_fibnum != fib)
20339a413162SMark Johnston 				continue;
20345f539170SGleb Smirnoff 			wildcard = 0;
2035cfa1ca9dSYoshinobu Inoue #ifdef INET6
2036413628a7SBjoern A. Zeeb 			/* XXX inp locking */
2037369dc8ceSEivind Eklund 			if ((inp->inp_vflag & INP_IPV4) == 0)
2038cfa1ca9dSYoshinobu Inoue 				continue;
2039d5e8a67eSHajimu UMEMOTO 			/*
20405f539170SGleb Smirnoff 			 * We never select the PCB that has INP_IPV6 flag and
20415f539170SGleb Smirnoff 			 * is bound to :: if we have another PCB which is bound
20425f539170SGleb Smirnoff 			 * to 0.0.0.0.  If a PCB has the INP_IPV6 flag, then we
20435f539170SGleb Smirnoff 			 * set its cost higher than IPv4 only PCBs.
2044d5e8a67eSHajimu UMEMOTO 			 *
20455f539170SGleb Smirnoff 			 * Note that the case only happens when a socket is
20465f539170SGleb Smirnoff 			 * bound to ::, under the condition that the use of the
2047d5e8a67eSHajimu UMEMOTO 			 * mapped address is allowed.
2048d5e8a67eSHajimu UMEMOTO 			 */
2049d5e8a67eSHajimu UMEMOTO 			if ((inp->inp_vflag & INP_IPV6) != 0)
2050d5e8a67eSHajimu UMEMOTO 				wildcard += INP_LOOKUP_MAPPED_PCB_COST;
2051cfa1ca9dSYoshinobu Inoue #endif
2052c3229e05SDavid Greenman 			if (inp->inp_faddr.s_addr != INADDR_ANY)
2053c3229e05SDavid Greenman 				wildcard++;
205415bd2b43SDavid Greenman 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
205515bd2b43SDavid Greenman 				if (laddr.s_addr == INADDR_ANY)
205615bd2b43SDavid Greenman 					wildcard++;
205715bd2b43SDavid Greenman 				else if (inp->inp_laddr.s_addr != laddr.s_addr)
205815bd2b43SDavid Greenman 					continue;
205915bd2b43SDavid Greenman 			} else {
206015bd2b43SDavid Greenman 				if (laddr.s_addr != INADDR_ANY)
206115bd2b43SDavid Greenman 					wildcard++;
206215bd2b43SDavid Greenman 			}
2063df8bae1dSRodney W. Grimes 			if (wildcard < matchwild) {
2064df8bae1dSRodney W. Grimes 				match = inp;
2065df8bae1dSRodney W. Grimes 				matchwild = wildcard;
2066413628a7SBjoern A. Zeeb 				if (matchwild == 0)
2067df8bae1dSRodney W. Grimes 					break;
2068df8bae1dSRodney W. Grimes 			}
2069df8bae1dSRodney W. Grimes 		}
2070df8bae1dSRodney W. Grimes 		return (match);
2071df8bae1dSRodney W. Grimes 	}
2072c3229e05SDavid Greenman }
2073d5e8a67eSHajimu UMEMOTO #undef INP_LOOKUP_MAPPED_PCB_COST
207415bd2b43SDavid Greenman 
2075d93ec8cbSMark Johnston static bool
2076da806e8dSMark Johnston in_pcblookup_lb_match(const struct inpcblbgroup *grp, int domain, int fib)
2077d93ec8cbSMark Johnston {
2078da806e8dSMark Johnston 	return ((domain == M_NODOM || domain == grp->il_numa_domain) &&
2079da806e8dSMark Johnston 	    (fib == RT_ALL_FIBS || fib == grp->il_fibnum));
2080d93ec8cbSMark Johnston }
2081d93ec8cbSMark Johnston 
20821a43cff9SSean Bruno static struct inpcb *
20831a43cff9SSean Bruno in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
20844130ea61SMark Johnston     const struct in_addr *faddr, uint16_t fport, const struct in_addr *laddr,
2085da806e8dSMark Johnston     uint16_t lport, int domain, int fib)
20861a43cff9SSean Bruno {
20871a43cff9SSean Bruno 	const struct inpcblbgrouphead *hdr;
20881a43cff9SSean Bruno 	struct inpcblbgroup *grp;
2089d93ec8cbSMark Johnston 	struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
2090a600aabeSMark Johnston 	struct inpcb *inp;
2091a600aabeSMark Johnston 	u_int count;
20921a43cff9SSean Bruno 
20931a43cff9SSean Bruno 	INP_HASH_LOCK_ASSERT(pcbinfo);
2094a600aabeSMark Johnston 	NET_EPOCH_ASSERT();
20951a43cff9SSean Bruno 
20969d2877fcSMark Johnston 	hdr = &pcbinfo->ipi_lbgrouphashbase[
20979d2877fcSMark Johnston 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
20981a43cff9SSean Bruno 
20991a43cff9SSean Bruno 	/*
2100d93ec8cbSMark Johnston 	 * Search for an LB group match based on the following criteria:
2101d93ec8cbSMark Johnston 	 * - prefer jailed groups to non-jailed groups
2102d93ec8cbSMark Johnston 	 * - prefer exact source address matches to wildcard matches
2103d93ec8cbSMark Johnston 	 * - prefer groups bound to the specified NUMA domain
21041a43cff9SSean Bruno 	 */
2105d93ec8cbSMark Johnston 	jail_exact = jail_wild = local_exact = local_wild = NULL;
210654af3d0dSMark Johnston 	CK_LIST_FOREACH(grp, hdr, il_list) {
2107d93ec8cbSMark Johnston 		bool injail;
2108d93ec8cbSMark Johnston 
21091a43cff9SSean Bruno #ifdef INET6
21101a43cff9SSean Bruno 		if (!(grp->il_vflag & INP_IPV4))
21111a43cff9SSean Bruno 			continue;
21121a43cff9SSean Bruno #endif
21138be02ee4SMark Johnston 		if (grp->il_lport != lport)
21148be02ee4SMark Johnston 			continue;
21151a43cff9SSean Bruno 
2116d93ec8cbSMark Johnston 		injail = prison_flag(grp->il_cred, PR_IP4) != 0;
2117d93ec8cbSMark Johnston 		if (injail && prison_check_ip4_locked(grp->il_cred->cr_prison,
2118d93ec8cbSMark Johnston 		    laddr) != 0)
2119d93ec8cbSMark Johnston 			continue;
2120a034518aSAndrew Gallatin 
2121d93ec8cbSMark Johnston 		if (grp->il_laddr.s_addr == laddr->s_addr) {
2122d93ec8cbSMark Johnston 			if (injail) {
2123d93ec8cbSMark Johnston 				jail_exact = grp;
2124da806e8dSMark Johnston 				if (in_pcblookup_lb_match(grp, domain, fib))
2125d93ec8cbSMark Johnston 					/* This is a perfect match. */
2126d93ec8cbSMark Johnston 					goto out;
2127d93ec8cbSMark Johnston 			} else if (local_exact == NULL ||
2128da806e8dSMark Johnston 			    in_pcblookup_lb_match(grp, domain, fib)) {
2129d93ec8cbSMark Johnston 				local_exact = grp;
2130d93ec8cbSMark Johnston 			}
21314130ea61SMark Johnston 		} else if (grp->il_laddr.s_addr == INADDR_ANY) {
2132d93ec8cbSMark Johnston 			if (injail) {
2133d93ec8cbSMark Johnston 				if (jail_wild == NULL ||
2134da806e8dSMark Johnston 				    in_pcblookup_lb_match(grp, domain, fib))
2135d93ec8cbSMark Johnston 					jail_wild = grp;
2136d93ec8cbSMark Johnston 			} else if (local_wild == NULL ||
2137da806e8dSMark Johnston 			    in_pcblookup_lb_match(grp, domain, fib)) {
2138d93ec8cbSMark Johnston 				local_wild = grp;
2139d93ec8cbSMark Johnston 			}
2140d93ec8cbSMark Johnston 		}
2141d93ec8cbSMark Johnston 	}
2142d93ec8cbSMark Johnston 
2143d93ec8cbSMark Johnston 	if (jail_exact != NULL)
2144d93ec8cbSMark Johnston 		grp = jail_exact;
2145d93ec8cbSMark Johnston 	else if (jail_wild != NULL)
2146d93ec8cbSMark Johnston 		grp = jail_wild;
2147d93ec8cbSMark Johnston 	else if (local_exact != NULL)
2148d93ec8cbSMark Johnston 		grp = local_exact;
2149d93ec8cbSMark Johnston 	else
2150d93ec8cbSMark Johnston 		grp = local_wild;
2151d93ec8cbSMark Johnston 	if (grp == NULL)
2152d93ec8cbSMark Johnston 		return (NULL);
2153a600aabeSMark Johnston 
2154d93ec8cbSMark Johnston out:
2155a600aabeSMark Johnston 	/*
2156a600aabeSMark Johnston 	 * Synchronize with in_pcblbgroup_insert().
2157a600aabeSMark Johnston 	 */
2158a600aabeSMark Johnston 	count = atomic_load_acq_int(&grp->il_inpcnt);
2159a600aabeSMark Johnston 	if (count == 0)
2160a600aabeSMark Johnston 		return (NULL);
2161a600aabeSMark Johnston 	inp = grp->il_inp[INP_PCBLBGROUP_PKTHASH(faddr, lport, fport) % count];
2162a600aabeSMark Johnston 	KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
2163a600aabeSMark Johnston 	return (inp);
21641a43cff9SSean Bruno }
21651a43cff9SSean Bruno 
21663e98dcb3SMark Johnston static bool
21673e98dcb3SMark Johnston in_pcblookup_exact_match(const struct inpcb *inp, struct in_addr faddr,
21684130ea61SMark Johnston     u_short fport, struct in_addr laddr, u_short lport)
216915bd2b43SDavid Greenman {
2170cfa1ca9dSYoshinobu Inoue #ifdef INET6
2171413628a7SBjoern A. Zeeb 	/* XXX inp locking */
2172369dc8ceSEivind Eklund 	if ((inp->inp_vflag & INP_IPV4) == 0)
21733e98dcb3SMark Johnston 		return (false);
2174cfa1ca9dSYoshinobu Inoue #endif
21756d6a026bSDavid Greenman 	if (inp->inp_faddr.s_addr == faddr.s_addr &&
2176ca98b82cSDavid Greenman 	    inp->inp_laddr.s_addr == laddr.s_addr &&
2177ca98b82cSDavid Greenman 	    inp->inp_fport == fport &&
2178220d8921SGleb Smirnoff 	    inp->inp_lport == lport)
21793e98dcb3SMark Johnston 		return (true);
21803e98dcb3SMark Johnston 	return (false);
21813e98dcb3SMark Johnston }
21823e98dcb3SMark Johnston 
21833e98dcb3SMark Johnston static struct inpcb *
21843e98dcb3SMark Johnston in_pcblookup_hash_exact(struct inpcbinfo *pcbinfo, struct in_addr faddr,
21853e98dcb3SMark Johnston     u_short fport, struct in_addr laddr, u_short lport)
21863e98dcb3SMark Johnston {
21873e98dcb3SMark Johnston 	struct inpcbhead *head;
21883e98dcb3SMark Johnston 	struct inpcb *inp;
21893e98dcb3SMark Johnston 
21903e98dcb3SMark Johnston 	INP_HASH_LOCK_ASSERT(pcbinfo);
21913e98dcb3SMark Johnston 
21923e98dcb3SMark Johnston 	head = &pcbinfo->ipi_hash_exact[INP_PCBHASH(&faddr, lport, fport,
21933e98dcb3SMark Johnston 	    pcbinfo->ipi_hashmask)];
21943e98dcb3SMark Johnston 	CK_LIST_FOREACH(inp, head, inp_hash_exact) {
21953e98dcb3SMark Johnston 		if (in_pcblookup_exact_match(inp, faddr, fport, laddr, lport))
2196c3229e05SDavid Greenman 			return (inp);
2197c3229e05SDavid Greenman 	}
21983e98dcb3SMark Johnston 	return (NULL);
21993e98dcb3SMark Johnston }
22003e98dcb3SMark Johnston 
22013e98dcb3SMark Johnston typedef enum {
22023e98dcb3SMark Johnston 	INPLOOKUP_MATCH_NONE = 0,
22033e98dcb3SMark Johnston 	INPLOOKUP_MATCH_WILD = 1,
22043e98dcb3SMark Johnston 	INPLOOKUP_MATCH_LADDR = 2,
22053e98dcb3SMark Johnston } inp_lookup_match_t;
22063e98dcb3SMark Johnston 
22073e98dcb3SMark Johnston static inp_lookup_match_t
22083e98dcb3SMark Johnston in_pcblookup_wild_match(const struct inpcb *inp, struct in_addr laddr,
2209da806e8dSMark Johnston     u_short lport, int fib)
22103e98dcb3SMark Johnston {
22113e98dcb3SMark Johnston #ifdef INET6
22123e98dcb3SMark Johnston 	/* XXX inp locking */
22133e98dcb3SMark Johnston 	if ((inp->inp_vflag & INP_IPV4) == 0)
22143e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_NONE);
22153e98dcb3SMark Johnston #endif
22163e98dcb3SMark Johnston 	if (inp->inp_faddr.s_addr != INADDR_ANY || inp->inp_lport != lport)
22173e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_NONE);
2218da806e8dSMark Johnston 	if (fib != RT_ALL_FIBS && inp->inp_inc.inc_fibnum != fib)
2219da806e8dSMark Johnston 		return (INPLOOKUP_MATCH_NONE);
22203e98dcb3SMark Johnston 	if (inp->inp_laddr.s_addr == INADDR_ANY)
22213e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_WILD);
22223e98dcb3SMark Johnston 	if (inp->inp_laddr.s_addr == laddr.s_addr)
22233e98dcb3SMark Johnston 		return (INPLOOKUP_MATCH_LADDR);
22243e98dcb3SMark Johnston 	return (INPLOOKUP_MATCH_NONE);
22254130ea61SMark Johnston }
2226e3fd5ffdSRobert Watson 
22277b92493aSMark Johnston #define	INP_LOOKUP_AGAIN	((struct inpcb *)(uintptr_t)-1)
22287b92493aSMark Johnston 
22297b92493aSMark Johnston static struct inpcb *
223021d7ac8cSMark Johnston in_pcblookup_hash_wild_smr(struct inpcbinfo *pcbinfo, struct in_addr laddr,
2231da806e8dSMark Johnston     u_short lport, int fib, const inp_lookup_t lockflags)
22327b92493aSMark Johnston {
22337b92493aSMark Johnston 	struct inpcbhead *head;
22347b92493aSMark Johnston 	struct inpcb *inp;
22357b92493aSMark Johnston 
22367b92493aSMark Johnston 	KASSERT(SMR_ENTERED(pcbinfo->ipi_smr),
22377b92493aSMark Johnston 	    ("%s: not in SMR read section", __func__));
22387b92493aSMark Johnston 
22397b92493aSMark Johnston 	head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
22407b92493aSMark Johnston 	    pcbinfo->ipi_hashmask)];
22417b92493aSMark Johnston 	CK_LIST_FOREACH(inp, head, inp_hash_wild) {
22427b92493aSMark Johnston 		inp_lookup_match_t match;
22437b92493aSMark Johnston 
2244da806e8dSMark Johnston 		match = in_pcblookup_wild_match(inp, laddr, lport, fib);
22457b92493aSMark Johnston 		if (match == INPLOOKUP_MATCH_NONE)
22467b92493aSMark Johnston 			continue;
22477b92493aSMark Johnston 
22487b92493aSMark Johnston 		if (__predict_true(inp_smr_lock(inp, lockflags))) {
2249da806e8dSMark Johnston 			match = in_pcblookup_wild_match(inp, laddr, lport, fib);
2250a306ed50SMark Johnston 			if (match != INPLOOKUP_MATCH_NONE &&
2251a306ed50SMark Johnston 			    prison_check_ip4_locked(inp->inp_cred->cr_prison,
2252a306ed50SMark Johnston 			    &laddr) == 0)
22537b92493aSMark Johnston 				return (inp);
22547b92493aSMark Johnston 			inp_unlock(inp, lockflags);
22557b92493aSMark Johnston 		}
22567b92493aSMark Johnston 
22577b92493aSMark Johnston 		/*
22587b92493aSMark Johnston 		 * The matching socket disappeared out from under us.  Fall back
22597b92493aSMark Johnston 		 * to a serialized lookup.
22607b92493aSMark Johnston 		 */
22617b92493aSMark Johnston 		return (INP_LOOKUP_AGAIN);
22627b92493aSMark Johnston 	}
22637b92493aSMark Johnston 	return (NULL);
22647b92493aSMark Johnston }
22657b92493aSMark Johnston 
22664130ea61SMark Johnston static struct inpcb *
226721d7ac8cSMark Johnston in_pcblookup_hash_wild_locked(struct inpcbinfo *pcbinfo, struct in_addr laddr,
2268da806e8dSMark Johnston     u_short lport, int fib)
22694130ea61SMark Johnston {
22704130ea61SMark Johnston 	struct inpcbhead *head;
22714130ea61SMark Johnston 	struct inpcb *inp, *local_wild, *local_exact, *jail_wild;
2272e3fd5ffdSRobert Watson #ifdef INET6
22734130ea61SMark Johnston 	struct inpcb *local_wild_mapped;
2274e3fd5ffdSRobert Watson #endif
2275413628a7SBjoern A. Zeeb 
22764130ea61SMark Johnston 	INP_HASH_LOCK_ASSERT(pcbinfo);
2277d93ec8cbSMark Johnston 
2278d93ec8cbSMark Johnston 	/*
2279413628a7SBjoern A. Zeeb 	 * Order of socket selection - we always prefer jails.
2280413628a7SBjoern A. Zeeb 	 *      1. jailed, non-wild.
2281413628a7SBjoern A. Zeeb 	 *      2. jailed, wild.
2282413628a7SBjoern A. Zeeb 	 *      3. non-jailed, non-wild.
2283413628a7SBjoern A. Zeeb 	 *      4. non-jailed, wild.
2284413628a7SBjoern A. Zeeb 	 */
2285fdb987beSMark Johnston 	head = &pcbinfo->ipi_hash_wild[INP_PCBHASH_WILD(lport,
2286a0577692SGleb Smirnoff 	    pcbinfo->ipi_hashmask)];
22874130ea61SMark Johnston 	local_wild = local_exact = jail_wild = NULL;
22884130ea61SMark Johnston #ifdef INET6
22894130ea61SMark Johnston 	local_wild_mapped = NULL;
22904130ea61SMark Johnston #endif
2291fdb987beSMark Johnston 	CK_LIST_FOREACH(inp, head, inp_hash_wild) {
22923e98dcb3SMark Johnston 		inp_lookup_match_t match;
22934130ea61SMark Johnston 		bool injail;
22944130ea61SMark Johnston 
2295da806e8dSMark Johnston 		match = in_pcblookup_wild_match(inp, laddr, lport, fib);
22963e98dcb3SMark Johnston 		if (match == INPLOOKUP_MATCH_NONE)
2297413628a7SBjoern A. Zeeb 			continue;
2298413628a7SBjoern A. Zeeb 
22994130ea61SMark Johnston 		injail = prison_flag(inp->inp_cred, PR_IP4) != 0;
2300413628a7SBjoern A. Zeeb 		if (injail) {
23014130ea61SMark Johnston 			if (prison_check_ip4_locked(inp->inp_cred->cr_prison,
23024130ea61SMark Johnston 			    &laddr) != 0)
2303413628a7SBjoern A. Zeeb 				continue;
2304413628a7SBjoern A. Zeeb 		} else {
2305413628a7SBjoern A. Zeeb 			if (local_exact != NULL)
2306413628a7SBjoern A. Zeeb 				continue;
2307413628a7SBjoern A. Zeeb 		}
2308413628a7SBjoern A. Zeeb 
23093e98dcb3SMark Johnston 		if (match == INPLOOKUP_MATCH_LADDR) {
2310413628a7SBjoern A. Zeeb 			if (injail)
2311c3229e05SDavid Greenman 				return (inp);
2312413628a7SBjoern A. Zeeb 			local_exact = inp;
23133e98dcb3SMark Johnston 		} else {
2314e3fd5ffdSRobert Watson #ifdef INET6
2315413628a7SBjoern A. Zeeb 			/* XXX inp locking, NULL check */
23165cd54324SBjoern A. Zeeb 			if (inp->inp_vflag & INP_IPV6PROTO)
2317cfa1ca9dSYoshinobu Inoue 				local_wild_mapped = inp;
2318cfa1ca9dSYoshinobu Inoue 			else
231983e521ecSBjoern A. Zeeb #endif
2320413628a7SBjoern A. Zeeb 				if (injail)
2321413628a7SBjoern A. Zeeb 					jail_wild = inp;
2322413628a7SBjoern A. Zeeb 				else
23236d6a026bSDavid Greenman 					local_wild = inp;
23246d6a026bSDavid Greenman 		}
23254130ea61SMark Johnston 	}
2326413628a7SBjoern A. Zeeb 	if (jail_wild != NULL)
2327413628a7SBjoern A. Zeeb 		return (jail_wild);
2328413628a7SBjoern A. Zeeb 	if (local_exact != NULL)
2329413628a7SBjoern A. Zeeb 		return (local_exact);
2330413628a7SBjoern A. Zeeb 	if (local_wild != NULL)
2331c3229e05SDavid Greenman 		return (local_wild);
2332413628a7SBjoern A. Zeeb #ifdef INET6
2333413628a7SBjoern A. Zeeb 	if (local_wild_mapped != NULL)
2334413628a7SBjoern A. Zeeb 		return (local_wild_mapped);
233583e521ecSBjoern A. Zeeb #endif
23366d6a026bSDavid Greenman 	return (NULL);
233715bd2b43SDavid Greenman }
2338fa046d87SRobert Watson 
2339fa046d87SRobert Watson /*
23404130ea61SMark Johnston  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
23414130ea61SMark Johnston  * that the caller has either locked the hash list, which usually happens
23424130ea61SMark Johnston  * for bind(2) operations, or is in SMR section, which happens when sorting
23434130ea61SMark Johnston  * out incoming packets.
2344fa046d87SRobert Watson  */
2345fa046d87SRobert Watson static struct inpcb *
23464130ea61SMark Johnston in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
23474130ea61SMark Johnston     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2348da806e8dSMark Johnston     uint8_t numa_domain, int fib)
23494130ea61SMark Johnston {
23504130ea61SMark Johnston 	struct inpcb *inp;
23514130ea61SMark Johnston 	const u_short fport = fport_arg, lport = lport_arg;
23524130ea61SMark Johnston 
2353da806e8dSMark Johnston 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD | INPLOOKUP_FIB)) == 0,
23544130ea61SMark Johnston 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
23554130ea61SMark Johnston 	KASSERT(faddr.s_addr != INADDR_ANY,
23564130ea61SMark Johnston 	    ("%s: invalid foreign address", __func__));
23574130ea61SMark Johnston 	KASSERT(laddr.s_addr != INADDR_ANY,
23584130ea61SMark Johnston 	    ("%s: invalid local address", __func__));
23597b92493aSMark Johnston 	INP_HASH_WLOCK_ASSERT(pcbinfo);
23604130ea61SMark Johnston 
23614130ea61SMark Johnston 	inp = in_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
23624130ea61SMark Johnston 	if (inp != NULL)
23634130ea61SMark Johnston 		return (inp);
23644130ea61SMark Johnston 
23654130ea61SMark Johnston 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
23667b92493aSMark Johnston 		inp = in_pcblookup_lbgroup(pcbinfo, &faddr, fport,
2367da806e8dSMark Johnston 		    &laddr, lport, numa_domain, fib);
23684130ea61SMark Johnston 		if (inp == NULL) {
236921d7ac8cSMark Johnston 			inp = in_pcblookup_hash_wild_locked(pcbinfo, laddr,
2370da806e8dSMark Johnston 			    lport, fib);
23714130ea61SMark Johnston 		}
23724130ea61SMark Johnston 	}
23734130ea61SMark Johnston 
23744130ea61SMark Johnston 	return (inp);
23754130ea61SMark Johnston }
23764130ea61SMark Johnston 
23774130ea61SMark Johnston static struct inpcb *
23787b92493aSMark Johnston in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2379fa046d87SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2380da806e8dSMark Johnston     uint8_t numa_domain, int fib)
2381fa046d87SRobert Watson {
2382fa046d87SRobert Watson 	struct inpcb *inp;
23837b92493aSMark Johnston 	const inp_lookup_t lockflags = lookupflags & INPLOOKUP_LOCKMASK;
23847b92493aSMark Johnston 
23857b92493aSMark Johnston 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
23867b92493aSMark Johnston 	    ("%s: LOCKPCB not set", __func__));
23877b92493aSMark Johnston 
23887b92493aSMark Johnston 	INP_HASH_WLOCK(pcbinfo);
23897b92493aSMark Johnston 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2390da806e8dSMark Johnston 	    lookupflags & ~INPLOOKUP_LOCKMASK, numa_domain, fib);
23917b92493aSMark Johnston 	if (inp != NULL && !inp_trylock(inp, lockflags)) {
23927b92493aSMark Johnston 		in_pcbref(inp);
23937b92493aSMark Johnston 		INP_HASH_WUNLOCK(pcbinfo);
23947b92493aSMark Johnston 		inp_lock(inp, lockflags);
23957b92493aSMark Johnston 		if (in_pcbrele(inp, lockflags))
23967b92493aSMark Johnston 			/* XXX-MJ or retry until we get a negative match? */
23977b92493aSMark Johnston 			inp = NULL;
23987b92493aSMark Johnston 	} else {
23997b92493aSMark Johnston 		INP_HASH_WUNLOCK(pcbinfo);
24007b92493aSMark Johnston 	}
24017b92493aSMark Johnston 	return (inp);
24027b92493aSMark Johnston }
24037b92493aSMark Johnston 
24047b92493aSMark Johnston static struct inpcb *
24057b92493aSMark Johnston in_pcblookup_hash_smr(struct inpcbinfo *pcbinfo, struct in_addr faddr,
24067b92493aSMark Johnston     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2407da806e8dSMark Johnston     uint8_t numa_domain, int fib)
24087b92493aSMark Johnston {
24097b92493aSMark Johnston 	struct inpcb *inp;
24107b92493aSMark Johnston 	const inp_lookup_t lockflags = lookupflags & INPLOOKUP_LOCKMASK;
24117b92493aSMark Johnston 	const u_short fport = fport_arg, lport = lport_arg;
2412fa046d87SRobert Watson 
2413675e2618SMark Johnston 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2414675e2618SMark Johnston 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2415675e2618SMark Johnston 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2416675e2618SMark Johnston 	    ("%s: LOCKPCB not set", __func__));
2417675e2618SMark Johnston 
2418db0ac6deSCy Schubert 	smr_enter(pcbinfo->ipi_smr);
24197b92493aSMark Johnston 	inp = in_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
2420fa046d87SRobert Watson 	if (inp != NULL) {
24217b92493aSMark Johnston 		if (__predict_true(inp_smr_lock(inp, lockflags))) {
24227b92493aSMark Johnston 			/*
24237b92493aSMark Johnston 			 * Revalidate the 4-tuple, the socket could have been
24247b92493aSMark Johnston 			 * disconnected.
24257b92493aSMark Johnston 			 */
24267b92493aSMark Johnston 			if (__predict_true(in_pcblookup_exact_match(inp,
24277b92493aSMark Johnston 			    faddr, fport, laddr, lport)))
24287b92493aSMark Johnston 				return (inp);
24297b92493aSMark Johnston 			inp_unlock(inp, lockflags);
24307b92493aSMark Johnston 		}
24317b92493aSMark Johnston 
24327b92493aSMark Johnston 		/*
24337b92493aSMark Johnston 		 * We failed to lock the inpcb, or its connection state changed
24347b92493aSMark Johnston 		 * out from under us.  Fall back to a precise search.
24357b92493aSMark Johnston 		 */
24367b92493aSMark Johnston 		return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2437da806e8dSMark Johnston 		    lookupflags, numa_domain, fib));
24387b92493aSMark Johnston 	}
24397b92493aSMark Johnston 
24407b92493aSMark Johnston 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
24417b92493aSMark Johnston 		inp = in_pcblookup_lbgroup(pcbinfo, &faddr, fport,
2442da806e8dSMark Johnston 		    &laddr, lport, numa_domain, fib);
24437b92493aSMark Johnston 		if (inp != NULL) {
24447b92493aSMark Johnston 			if (__predict_true(inp_smr_lock(inp, lockflags))) {
24457b92493aSMark Johnston 				if (__predict_true(in_pcblookup_wild_match(inp,
2446da806e8dSMark Johnston 				    laddr, lport, fib) != INPLOOKUP_MATCH_NONE))
24477b92493aSMark Johnston 					return (inp);
24487b92493aSMark Johnston 				inp_unlock(inp, lockflags);
24497b92493aSMark Johnston 			}
24507b92493aSMark Johnston 			inp = INP_LOOKUP_AGAIN;
24517b92493aSMark Johnston 		} else {
245221d7ac8cSMark Johnston 			inp = in_pcblookup_hash_wild_smr(pcbinfo, laddr, lport,
2453da806e8dSMark Johnston 			    fib, lockflags);
24547b92493aSMark Johnston 		}
24557b92493aSMark Johnston 		if (inp == INP_LOOKUP_AGAIN) {
24567b92493aSMark Johnston 			return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr,
2457da806e8dSMark Johnston 			    lport, lookupflags, numa_domain, fib));
24587b92493aSMark Johnston 		}
24597b92493aSMark Johnston 	}
24607b92493aSMark Johnston 
24617b92493aSMark Johnston 	if (inp == NULL)
2462db0ac6deSCy Schubert 		smr_exit(pcbinfo->ipi_smr);
2463d797164aSGleb Smirnoff 
2464fa046d87SRobert Watson 	return (inp);
2465fa046d87SRobert Watson }
2466fa046d87SRobert Watson 
2467fa046d87SRobert Watson /*
2468d3c1f003SRobert Watson  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2469d3c1f003SRobert Watson  * from which a pre-calculated hash value may be extracted.
2470fa046d87SRobert Watson  */
2471fa046d87SRobert Watson struct inpcb *
2472fa046d87SRobert Watson in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
24734130ea61SMark Johnston     struct in_addr laddr, u_int lport, int lookupflags,
2474da806e8dSMark Johnston     struct ifnet *ifp)
2475fa046d87SRobert Watson {
2476da806e8dSMark Johnston 	int fib;
2477da806e8dSMark Johnston 
2478da806e8dSMark Johnston 	fib = (lookupflags & INPLOOKUP_FIB) ? if_getfib(ifp) : RT_ALL_FIBS;
24794130ea61SMark Johnston 	return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
2480da806e8dSMark Johnston 	    lookupflags, M_NODOM, fib));
2481fa046d87SRobert Watson }
2482d3c1f003SRobert Watson 
2483d3c1f003SRobert Watson struct inpcb *
2484d3c1f003SRobert Watson in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2485d3c1f003SRobert Watson     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
24864130ea61SMark Johnston     struct ifnet *ifp __unused, struct mbuf *m)
2487d3c1f003SRobert Watson {
2488da806e8dSMark Johnston 	int fib;
2489da806e8dSMark Johnston 
2490da806e8dSMark Johnston 	M_ASSERTPKTHDR(m);
2491da806e8dSMark Johnston 	fib = (lookupflags & INPLOOKUP_FIB) ? M_GETFIB(m) : RT_ALL_FIBS;
24924130ea61SMark Johnston 	return (in_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
2493da806e8dSMark Johnston 	    lookupflags, m->m_pkthdr.numa_domain, fib));
2494d3c1f003SRobert Watson }
249567107f45SBjoern A. Zeeb #endif /* INET */
249615bd2b43SDavid Greenman 
24977b92493aSMark Johnston static bool
24987b92493aSMark Johnston in_pcbjailed(const struct inpcb *inp, unsigned int flag)
24997b92493aSMark Johnston {
25007b92493aSMark Johnston 	return (prison_flag(inp->inp_cred, flag) != 0);
25017b92493aSMark Johnston }
25027b92493aSMark Johnston 
25037b92493aSMark Johnston /*
25047b92493aSMark Johnston  * Insert the PCB into a hash chain using ordering rules which ensure that
25057b92493aSMark Johnston  * in_pcblookup_hash_wild_*() always encounter the highest-ranking PCB first.
25067b92493aSMark Johnston  *
25077b92493aSMark Johnston  * Specifically, keep jailed PCBs in front of non-jailed PCBs, and keep PCBs
250893998d16SMark Johnston  * with exact local addresses ahead of wildcard PCBs.  Unbound v4-mapped v6 PCBs
250993998d16SMark Johnston  * always appear last no matter whether they are jailed.
25107b92493aSMark Johnston  */
25117b92493aSMark Johnston static void
25127b92493aSMark Johnston _in_pcbinshash_wild(struct inpcbhead *pcbhash, struct inpcb *inp)
25137b92493aSMark Johnston {
25147b92493aSMark Johnston 	struct inpcb *last;
25157b92493aSMark Johnston 	bool bound, injail;
25167b92493aSMark Johnston 
251793998d16SMark Johnston 	INP_LOCK_ASSERT(inp);
25187b92493aSMark Johnston 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
25197b92493aSMark Johnston 
25207b92493aSMark Johnston 	last = NULL;
25217b92493aSMark Johnston 	bound = inp->inp_laddr.s_addr != INADDR_ANY;
252293998d16SMark Johnston 	if (!bound && (inp->inp_vflag & INP_IPV6PROTO) != 0) {
252393998d16SMark Johnston 		CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
252493998d16SMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
252593998d16SMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
252693998d16SMark Johnston 				return;
252793998d16SMark Johnston 			}
252893998d16SMark Johnston 		}
252993998d16SMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
253093998d16SMark Johnston 		return;
253193998d16SMark Johnston 	}
253293998d16SMark Johnston 
25337b92493aSMark Johnston 	injail = in_pcbjailed(inp, PR_IP4);
25347b92493aSMark Johnston 	if (!injail) {
25357b92493aSMark Johnston 		CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
253693998d16SMark Johnston 			if (!in_pcbjailed(last, PR_IP4))
25377b92493aSMark Johnston 				break;
25387b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
25397b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
25407b92493aSMark Johnston 				return;
25417b92493aSMark Johnston 			}
25427b92493aSMark Johnston 		}
25437b92493aSMark Johnston 	} else if (!CK_LIST_EMPTY(pcbhash) &&
25447b92493aSMark Johnston 	    !in_pcbjailed(CK_LIST_FIRST(pcbhash), PR_IP4)) {
25457b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
25467b92493aSMark Johnston 		return;
25477b92493aSMark Johnston 	}
25487b92493aSMark Johnston 	if (!bound) {
25497b92493aSMark Johnston 		CK_LIST_FOREACH_FROM(last, pcbhash, inp_hash_wild) {
25507b92493aSMark Johnston 			if (last->inp_laddr.s_addr == INADDR_ANY)
25517b92493aSMark Johnston 				break;
25527b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
25537b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
25547b92493aSMark Johnston 				return;
25557b92493aSMark Johnston 			}
25567b92493aSMark Johnston 		}
25577b92493aSMark Johnston 	}
25587b92493aSMark Johnston 	if (last == NULL)
25597b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
25607b92493aSMark Johnston 	else
25617b92493aSMark Johnston 		CK_LIST_INSERT_BEFORE(last, inp, inp_hash_wild);
25627b92493aSMark Johnston }
25637b92493aSMark Johnston 
25647b92493aSMark Johnston #ifdef INET6
25657b92493aSMark Johnston /*
25667b92493aSMark Johnston  * See the comment above _in_pcbinshash_wild().
25677b92493aSMark Johnston  */
25687b92493aSMark Johnston static void
25697b92493aSMark Johnston _in6_pcbinshash_wild(struct inpcbhead *pcbhash, struct inpcb *inp)
25707b92493aSMark Johnston {
25717b92493aSMark Johnston 	struct inpcb *last;
25727b92493aSMark Johnston 	bool bound, injail;
25737b92493aSMark Johnston 
257493998d16SMark Johnston 	INP_LOCK_ASSERT(inp);
25757b92493aSMark Johnston 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
25767b92493aSMark Johnston 
25777b92493aSMark Johnston 	last = NULL;
25787b92493aSMark Johnston 	bound = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr);
25797b92493aSMark Johnston 	injail = in_pcbjailed(inp, PR_IP6);
25807b92493aSMark Johnston 	if (!injail) {
25817b92493aSMark Johnston 		CK_LIST_FOREACH(last, pcbhash, inp_hash_wild) {
258293998d16SMark Johnston 			if (!in_pcbjailed(last, PR_IP6))
25837b92493aSMark Johnston 				break;
25847b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
25857b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
25867b92493aSMark Johnston 				return;
25877b92493aSMark Johnston 			}
25887b92493aSMark Johnston 		}
25897b92493aSMark Johnston 	} else if (!CK_LIST_EMPTY(pcbhash) &&
25907b92493aSMark Johnston 	    !in_pcbjailed(CK_LIST_FIRST(pcbhash), PR_IP6)) {
25917b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
25927b92493aSMark Johnston 		return;
25937b92493aSMark Johnston 	}
25947b92493aSMark Johnston 	if (!bound) {
25957b92493aSMark Johnston 		CK_LIST_FOREACH_FROM(last, pcbhash, inp_hash_wild) {
25967b92493aSMark Johnston 			if (IN6_IS_ADDR_UNSPECIFIED(&last->in6p_laddr))
25977b92493aSMark Johnston 				break;
25987b92493aSMark Johnston 			if (CK_LIST_NEXT(last, inp_hash_wild) == NULL) {
25997b92493aSMark Johnston 				CK_LIST_INSERT_AFTER(last, inp, inp_hash_wild);
26007b92493aSMark Johnston 				return;
26017b92493aSMark Johnston 			}
26027b92493aSMark Johnston 		}
26037b92493aSMark Johnston 	}
26047b92493aSMark Johnston 	if (last == NULL)
26057b92493aSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_wild);
26067b92493aSMark Johnston 	else
26077b92493aSMark Johnston 		CK_LIST_INSERT_BEFORE(last, inp, inp_hash_wild);
26087b92493aSMark Johnston }
26097b92493aSMark Johnston #endif
26107b92493aSMark Johnston 
26117bc4aca7SDavid Greenman /*
2612c3229e05SDavid Greenman  * Insert PCB onto various hash lists.
2613136c5e17SGleb Smirnoff  *
2614136c5e17SGleb Smirnoff  * With normal sockets this function shall not fail, so it could return void.
2615136c5e17SGleb Smirnoff  * But for SO_REUSEPORT_LB it may need to allocate memory with locks held,
2616136c5e17SGleb Smirnoff  * that's the only condition when it can fail.
26177bc4aca7SDavid Greenman  */
2618db0ac6deSCy Schubert int
2619db0ac6deSCy Schubert in_pcbinshash(struct inpcb *inp)
262015bd2b43SDavid Greenman {
26215f539170SGleb Smirnoff 	struct inpcbhead *pcbhash, *pcbporthash;
2622c3229e05SDavid Greenman 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2623fdb987beSMark Johnston 	uint32_t hash;
2624fdb987beSMark Johnston 	bool connected;
262515bd2b43SDavid Greenman 
26268501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2627fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2628111d57a6SRobert Watson 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2629111d57a6SRobert Watson 	    ("in_pcbinshash: INP_INHASHLIST"));
2630602cc7f1SRobert Watson 
2631cfa1ca9dSYoshinobu Inoue #ifdef INET6
2632fdb987beSMark Johnston 	if (inp->inp_vflag & INP_IPV6) {
2633fdb987beSMark Johnston 		hash = INP6_PCBHASH(&inp->in6p_faddr, inp->inp_lport,
2634fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2635fdb987beSMark Johnston 		connected = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr);
2636fdb987beSMark Johnston 	} else
263783e521ecSBjoern A. Zeeb #endif
2638fdb987beSMark Johnston 	{
2639fdb987beSMark Johnston 		hash = INP_PCBHASH(&inp->inp_faddr, inp->inp_lport,
2640fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2641fdb987beSMark Johnston 		connected = !in_nullhost(inp->inp_faddr);
2642fdb987beSMark Johnston 	}
2643fdb987beSMark Johnston 
2644fdb987beSMark Johnston 	if (connected)
2645fdb987beSMark Johnston 		pcbhash = &pcbinfo->ipi_hash_exact[hash];
2646fdb987beSMark Johnston 	else
2647fdb987beSMark Johnston 		pcbhash = &pcbinfo->ipi_hash_wild[hash];
264815bd2b43SDavid Greenman 
2649712fc218SRobert Watson 	pcbporthash = &pcbinfo->ipi_porthashbase[
2650712fc218SRobert Watson 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2651c3229e05SDavid Greenman 
2652c3229e05SDavid Greenman 	/*
26531a43cff9SSean Bruno 	 * Add entry to load balance group.
26541a43cff9SSean Bruno 	 * Only do this if SO_REUSEPORT_LB is set.
26551a43cff9SSean Bruno 	 */
2656e3ba0d6aSGleb Smirnoff 	if ((inp->inp_socket->so_options & SO_REUSEPORT_LB) != 0) {
2657a152dd86SMark Johnston 		int error = in_pcbinslbgrouphash(inp, M_NODOM);
2658a152dd86SMark Johnston 		if (error != 0)
2659a152dd86SMark Johnston 			return (error);
26601a43cff9SSean Bruno 	}
26611a43cff9SSean Bruno 
26621a43cff9SSean Bruno 	/*
2663fdb987beSMark Johnston 	 * The PCB may have been disconnected in the past.  Before we can safely
2664fdb987beSMark Johnston 	 * make it visible in the hash table, we must wait for all readers which
2665fdb987beSMark Johnston 	 * may be traversing this PCB to finish.
2666fdb987beSMark Johnston 	 */
2667fdb987beSMark Johnston 	if (inp->inp_smr != SMR_SEQ_INVALID) {
2668fdb987beSMark Johnston 		smr_wait(pcbinfo->ipi_smr, inp->inp_smr);
2669fdb987beSMark Johnston 		inp->inp_smr = SMR_SEQ_INVALID;
2670fdb987beSMark Johnston 	}
2671fdb987beSMark Johnston 
2672fdb987beSMark Johnston 	if (connected)
2673fdb987beSMark Johnston 		CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash_exact);
26747b92493aSMark Johnston 	else {
26757b92493aSMark Johnston #ifdef INET6
26767b92493aSMark Johnston 		if ((inp->inp_vflag & INP_IPV6) != 0)
26777b92493aSMark Johnston 			_in6_pcbinshash_wild(pcbhash, inp);
2678fdb987beSMark Johnston 		else
26797b92493aSMark Johnston #endif
26807b92493aSMark Johnston 			_in_pcbinshash_wild(pcbhash, inp);
26817b92493aSMark Johnston 	}
26825f539170SGleb Smirnoff 	CK_LIST_INSERT_HEAD(pcbporthash, inp, inp_portlist);
2683111d57a6SRobert Watson 	inp->inp_flags |= INP_INHASHLIST;
2684db0ac6deSCy Schubert 
2685c3229e05SDavid Greenman 	return (0);
268615bd2b43SDavid Greenman }
268715bd2b43SDavid Greenman 
2688fdb987beSMark Johnston void
2689fdb987beSMark Johnston in_pcbremhash_locked(struct inpcb *inp)
26903ba34b07SGleb Smirnoff {
26913ba34b07SGleb Smirnoff 
26923ba34b07SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
2693fdb987beSMark Johnston 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
26943ba34b07SGleb Smirnoff 	MPASS(inp->inp_flags & INP_INHASHLIST);
26953ba34b07SGleb Smirnoff 
2696a43e7a96SGleb Smirnoff 	if ((inp->inp_flags & INP_INLBGROUP) != 0)
26973ba34b07SGleb Smirnoff 		in_pcbremlbgrouphash(inp);
2698fdb987beSMark Johnston #ifdef INET6
2699fdb987beSMark Johnston 	if (inp->inp_vflag & INP_IPV6) {
2700fdb987beSMark Johnston 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
2701fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_wild);
2702fdb987beSMark Johnston 		else
2703fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_exact);
2704fdb987beSMark Johnston 	} else
2705fdb987beSMark Johnston #endif
2706fdb987beSMark Johnston 	{
2707fdb987beSMark Johnston 		if (in_nullhost(inp->inp_faddr))
2708fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_wild);
2709fdb987beSMark Johnston 		else
2710fdb987beSMark Johnston 			CK_LIST_REMOVE(inp, inp_hash_exact);
2711fdb987beSMark Johnston 	}
27123ba34b07SGleb Smirnoff 	CK_LIST_REMOVE(inp, inp_portlist);
27133ba34b07SGleb Smirnoff 	inp->inp_flags &= ~INP_INHASHLIST;
27143ba34b07SGleb Smirnoff }
27153ba34b07SGleb Smirnoff 
2716fdb987beSMark Johnston static void
2717fdb987beSMark Johnston in_pcbremhash(struct inpcb *inp)
2718fdb987beSMark Johnston {
2719fdb987beSMark Johnston 	INP_HASH_WLOCK(inp->inp_pcbinfo);
2720fdb987beSMark Johnston 	in_pcbremhash_locked(inp);
2721fdb987beSMark Johnston 	INP_HASH_WUNLOCK(inp->inp_pcbinfo);
2722fdb987beSMark Johnston }
2723fdb987beSMark Johnston 
272452cd27cbSRobert Watson /*
2725c3229e05SDavid Greenman  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2726c3229e05SDavid Greenman  * changed. NOTE: This does not handle the case of the lport changing (the
2727c3229e05SDavid Greenman  * hashed port list would have to be updated as well), so the lport must
2728c3229e05SDavid Greenman  * not change after in_pcbinshash() has been called.
2729c3229e05SDavid Greenman  */
273015bd2b43SDavid Greenman void
2731db0ac6deSCy Schubert in_pcbrehash(struct inpcb *inp)
273215bd2b43SDavid Greenman {
273359daba27SSam Leffler 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
273415bd2b43SDavid Greenman 	struct inpcbhead *head;
2735fdb987beSMark Johnston 	uint32_t hash;
2736fdb987beSMark Johnston 	bool connected;
273715bd2b43SDavid Greenman 
27388501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
2739fa046d87SRobert Watson 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2740111d57a6SRobert Watson 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2741fdb987beSMark Johnston 	    ("%s: !INP_INHASHLIST", __func__));
2742fdb987beSMark Johnston 	KASSERT(inp->inp_smr == SMR_SEQ_INVALID,
2743fdb987beSMark Johnston 	    ("%s: inp was disconnected", __func__));
2744602cc7f1SRobert Watson 
2745cfa1ca9dSYoshinobu Inoue #ifdef INET6
2746fdb987beSMark Johnston 	if (inp->inp_vflag & INP_IPV6) {
2747fdb987beSMark Johnston 		hash = INP6_PCBHASH(&inp->in6p_faddr, inp->inp_lport,
2748fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2749fdb987beSMark Johnston 		connected = !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr);
2750fdb987beSMark Johnston 	} else
275183e521ecSBjoern A. Zeeb #endif
2752fdb987beSMark Johnston 	{
2753fdb987beSMark Johnston 		hash = INP_PCBHASH(&inp->inp_faddr, inp->inp_lport,
2754fdb987beSMark Johnston 		    inp->inp_fport, pcbinfo->ipi_hashmask);
2755fdb987beSMark Johnston 		connected = !in_nullhost(inp->inp_faddr);
2756fdb987beSMark Johnston 	}
275715bd2b43SDavid Greenman 
2758fdb987beSMark Johnston 	/*
2759fdb987beSMark Johnston 	 * When rehashing, the caller must ensure that either the new or the old
2760fdb987beSMark Johnston 	 * foreign address was unspecified.
2761fdb987beSMark Johnston 	 */
2762fdb987beSMark Johnston 	if (connected)
2763fdb987beSMark Johnston 		CK_LIST_REMOVE(inp, inp_hash_wild);
2764fdb987beSMark Johnston 	else
2765fdb987beSMark Johnston 		CK_LIST_REMOVE(inp, inp_hash_exact);
2766fdb987beSMark Johnston 
2767fdb987beSMark Johnston 	if (connected) {
2768fdb987beSMark Johnston 		head = &pcbinfo->ipi_hash_exact[hash];
2769fdb987beSMark Johnston 		CK_LIST_INSERT_HEAD(head, inp, inp_hash_exact);
2770fdb987beSMark Johnston 	} else {
2771fdb987beSMark Johnston 		head = &pcbinfo->ipi_hash_wild[hash];
2772fdb987beSMark Johnston 		CK_LIST_INSERT_HEAD(head, inp, inp_hash_wild);
2773fdb987beSMark Johnston 	}
2774c3229e05SDavid Greenman }
2775c3229e05SDavid Greenman 
2776c3229e05SDavid Greenman /*
277784cc0778SGeorge V. Neville-Neil  * Check for alternatives when higher level complains
277884cc0778SGeorge V. Neville-Neil  * about service problems.  For now, invalidate cached
277984cc0778SGeorge V. Neville-Neil  * routing information.  If the route was created dynamically
278084cc0778SGeorge V. Neville-Neil  * (by a redirect), time to try a default gateway again.
278184cc0778SGeorge V. Neville-Neil  */
278284cc0778SGeorge V. Neville-Neil void
278384cc0778SGeorge V. Neville-Neil in_losing(struct inpcb *inp)
278484cc0778SGeorge V. Neville-Neil {
278584cc0778SGeorge V. Neville-Neil 
2786fc21c53fSRyan Stone 	RO_INVALIDATE_CACHE(&inp->inp_route);
278784cc0778SGeorge V. Neville-Neil 	return;
278884cc0778SGeorge V. Neville-Neil }
278984cc0778SGeorge V. Neville-Neil 
279084cc0778SGeorge V. Neville-Neil /*
2791a557af22SRobert Watson  * A set label operation has occurred at the socket layer, propagate the
2792a557af22SRobert Watson  * label change into the in_pcb for the socket.
2793a557af22SRobert Watson  */
2794a557af22SRobert Watson void
2795136d4f1cSRobert Watson in_pcbsosetlabel(struct socket *so)
2796a557af22SRobert Watson {
2797a557af22SRobert Watson #ifdef MAC
2798a557af22SRobert Watson 	struct inpcb *inp;
2799a557af22SRobert Watson 
28004c7c478dSRobert Watson 	inp = sotoinpcb(so);
28014c7c478dSRobert Watson 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2802602cc7f1SRobert Watson 
28038501a69cSRobert Watson 	INP_WLOCK(inp);
2804310e7cebSRobert Watson 	SOCK_LOCK(so);
2805a557af22SRobert Watson 	mac_inpcb_sosetlabel(so, inp);
2806310e7cebSRobert Watson 	SOCK_UNLOCK(so);
28078501a69cSRobert Watson 	INP_WUNLOCK(inp);
2808a557af22SRobert Watson #endif
2809a557af22SRobert Watson }
28105f311da2SMike Silbersack 
28113d585327SKip Macy void
28123d585327SKip Macy inp_wlock(struct inpcb *inp)
28133d585327SKip Macy {
28143d585327SKip Macy 
28158501a69cSRobert Watson 	INP_WLOCK(inp);
28163d585327SKip Macy }
28173d585327SKip Macy 
28183d585327SKip Macy void
28193d585327SKip Macy inp_wunlock(struct inpcb *inp)
28203d585327SKip Macy {
28213d585327SKip Macy 
28228501a69cSRobert Watson 	INP_WUNLOCK(inp);
28233d585327SKip Macy }
28243d585327SKip Macy 
28253d585327SKip Macy void
28263d585327SKip Macy inp_rlock(struct inpcb *inp)
28273d585327SKip Macy {
28283d585327SKip Macy 
2829a69042a5SRobert Watson 	INP_RLOCK(inp);
28303d585327SKip Macy }
28313d585327SKip Macy 
28323d585327SKip Macy void
28333d585327SKip Macy inp_runlock(struct inpcb *inp)
28343d585327SKip Macy {
28353d585327SKip Macy 
2836a69042a5SRobert Watson 	INP_RUNLOCK(inp);
28373d585327SKip Macy }
28383d585327SKip Macy 
2839c75e2666SGleb Smirnoff #ifdef INVARIANT_SUPPORT
28403d585327SKip Macy void
2841e79dd20dSKip Macy inp_lock_assert(struct inpcb *inp)
28423d585327SKip Macy {
28433d585327SKip Macy 
28448501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
28453d585327SKip Macy }
28463d585327SKip Macy 
28473d585327SKip Macy void
2848e79dd20dSKip Macy inp_unlock_assert(struct inpcb *inp)
28493d585327SKip Macy {
28503d585327SKip Macy 
28513d585327SKip Macy 	INP_UNLOCK_ASSERT(inp);
28523d585327SKip Macy }
28533d585327SKip Macy #endif
28543d585327SKip Macy 
28559378e437SKip Macy void
285624cf7a8dSGleb Smirnoff inp_apply_all(struct inpcbinfo *pcbinfo,
285724cf7a8dSGleb Smirnoff     void (*func)(struct inpcb *, void *), void *arg)
28589378e437SKip Macy {
285924cf7a8dSGleb Smirnoff 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2860db0ac6deSCy Schubert 	    INPLOOKUP_WLOCKPCB);
28619378e437SKip Macy 	struct inpcb *inp;
28629378e437SKip Macy 
2863db0ac6deSCy Schubert 	while ((inp = inp_next(&inpi)) != NULL)
28649378e437SKip Macy 		func(inp, arg);
28659378e437SKip Macy }
28669378e437SKip Macy 
28679378e437SKip Macy struct socket *
28689378e437SKip Macy inp_inpcbtosocket(struct inpcb *inp)
28699378e437SKip Macy {
28709378e437SKip Macy 
28719378e437SKip Macy 	INP_WLOCK_ASSERT(inp);
28729378e437SKip Macy 	return (inp->inp_socket);
28739378e437SKip Macy }
28749378e437SKip Macy 
28759378e437SKip Macy void
2876df9cf830STai-hwa Liang inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
28779d29c635SKip Macy     uint32_t *faddr, uint16_t *fp)
28789378e437SKip Macy {
28799378e437SKip Macy 
28809d29c635SKip Macy 	INP_LOCK_ASSERT(inp);
2881df9cf830STai-hwa Liang 	*laddr = inp->inp_laddr.s_addr;
2882df9cf830STai-hwa Liang 	*faddr = inp->inp_faddr.s_addr;
28839378e437SKip Macy 	*lp = inp->inp_lport;
28849378e437SKip Macy 	*fp = inp->inp_fport;
28859378e437SKip Macy }
28869378e437SKip Macy 
2887cc65eb4eSGleb Smirnoff /*
2888cc65eb4eSGleb Smirnoff  * Create an external-format (``xinpcb'') structure using the information in
2889cc65eb4eSGleb Smirnoff  * the kernel-format in_pcb structure pointed to by inp.  This is done to
2890cc65eb4eSGleb Smirnoff  * reduce the spew of irrelevant information over this interface, to isolate
2891cc65eb4eSGleb Smirnoff  * user code from changes in the kernel structure, and potentially to provide
2892cc65eb4eSGleb Smirnoff  * information-hiding if we decide that some of this information should be
2893cc65eb4eSGleb Smirnoff  * hidden from users.
2894cc65eb4eSGleb Smirnoff  */
2895cc65eb4eSGleb Smirnoff void
2896cc65eb4eSGleb Smirnoff in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2897cc65eb4eSGleb Smirnoff {
2898cc65eb4eSGleb Smirnoff 
289979db6fe7SMark Johnston 	bzero(xi, sizeof(*xi));
2900cc65eb4eSGleb Smirnoff 	xi->xi_len = sizeof(struct xinpcb);
2901cc65eb4eSGleb Smirnoff 	if (inp->inp_socket)
2902cc65eb4eSGleb Smirnoff 		sotoxsocket(inp->inp_socket, &xi->xi_socket);
2903cc65eb4eSGleb Smirnoff 	bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2904cc65eb4eSGleb Smirnoff 	xi->inp_gencnt = inp->inp_gencnt;
2905cc65eb4eSGleb Smirnoff 	xi->inp_flow = inp->inp_flow;
2906cc65eb4eSGleb Smirnoff 	xi->inp_flowid = inp->inp_flowid;
2907cc65eb4eSGleb Smirnoff 	xi->inp_flowtype = inp->inp_flowtype;
2908cc65eb4eSGleb Smirnoff 	xi->inp_flags = inp->inp_flags;
2909cc65eb4eSGleb Smirnoff 	xi->inp_flags2 = inp->inp_flags2;
2910cc65eb4eSGleb Smirnoff 	xi->in6p_cksum = inp->in6p_cksum;
2911cc65eb4eSGleb Smirnoff 	xi->in6p_hops = inp->in6p_hops;
2912cc65eb4eSGleb Smirnoff 	xi->inp_ip_tos = inp->inp_ip_tos;
2913cc65eb4eSGleb Smirnoff 	xi->inp_vflag = inp->inp_vflag;
2914cc65eb4eSGleb Smirnoff 	xi->inp_ip_ttl = inp->inp_ip_ttl;
2915cc65eb4eSGleb Smirnoff 	xi->inp_ip_p = inp->inp_ip_p;
2916cc65eb4eSGleb Smirnoff 	xi->inp_ip_minttl = inp->inp_ip_minttl;
2917cc65eb4eSGleb Smirnoff }
2918cc65eb4eSGleb Smirnoff 
2919a35bdd44SMichael Tuexen int
2920a35bdd44SMichael Tuexen sysctl_setsockopt(SYSCTL_HANDLER_ARGS, struct inpcbinfo *pcbinfo,
2921a35bdd44SMichael Tuexen     int (*ctloutput_set)(struct inpcb *, struct sockopt *))
2922a35bdd44SMichael Tuexen {
2923a35bdd44SMichael Tuexen 	struct sockopt sopt;
2924a35bdd44SMichael Tuexen 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(pcbinfo,
2925a35bdd44SMichael Tuexen 	    INPLOOKUP_WLOCKPCB);
2926a35bdd44SMichael Tuexen 	struct inpcb *inp;
2927a35bdd44SMichael Tuexen 	struct sockopt_parameters *params;
2928a35bdd44SMichael Tuexen 	struct socket *so;
2929a35bdd44SMichael Tuexen 	int error;
2930a35bdd44SMichael Tuexen 	char buf[1024];
2931a35bdd44SMichael Tuexen 
2932a35bdd44SMichael Tuexen 	if (req->oldptr != NULL || req->oldlen != 0)
2933a35bdd44SMichael Tuexen 		return (EINVAL);
2934a35bdd44SMichael Tuexen 	if (req->newptr == NULL)
2935a35bdd44SMichael Tuexen 		return (EPERM);
2936a35bdd44SMichael Tuexen 	if (req->newlen > sizeof(buf))
2937a35bdd44SMichael Tuexen 		return (ENOMEM);
2938a35bdd44SMichael Tuexen 	error = SYSCTL_IN(req, buf, req->newlen);
2939a35bdd44SMichael Tuexen 	if (error != 0)
2940a35bdd44SMichael Tuexen 		return (error);
2941a35bdd44SMichael Tuexen 	if (req->newlen < sizeof(struct sockopt_parameters))
2942a35bdd44SMichael Tuexen 		return (EINVAL);
2943a35bdd44SMichael Tuexen 	params = (struct sockopt_parameters *)buf;
2944a35bdd44SMichael Tuexen 	sopt.sopt_level = params->sop_level;
2945a35bdd44SMichael Tuexen 	sopt.sopt_name = params->sop_optname;
2946a35bdd44SMichael Tuexen 	sopt.sopt_dir = SOPT_SET;
2947a35bdd44SMichael Tuexen 	sopt.sopt_val = params->sop_optval;
2948a35bdd44SMichael Tuexen 	sopt.sopt_valsize = req->newlen - sizeof(struct sockopt_parameters);
2949a35bdd44SMichael Tuexen 	sopt.sopt_td = NULL;
2950a0aeb1ceSMichael Tuexen #ifdef INET6
2951a35bdd44SMichael Tuexen 	if (params->sop_inc.inc_flags & INC_ISIPV6) {
2952a35bdd44SMichael Tuexen 		if (IN6_IS_SCOPE_LINKLOCAL(&params->sop_inc.inc6_laddr))
2953a35bdd44SMichael Tuexen 			params->sop_inc.inc6_laddr.s6_addr16[1] =
2954a35bdd44SMichael Tuexen 			    htons(params->sop_inc.inc6_zoneid & 0xffff);
2955a35bdd44SMichael Tuexen 		if (IN6_IS_SCOPE_LINKLOCAL(&params->sop_inc.inc6_faddr))
2956a35bdd44SMichael Tuexen 			params->sop_inc.inc6_faddr.s6_addr16[1] =
2957a35bdd44SMichael Tuexen 			    htons(params->sop_inc.inc6_zoneid & 0xffff);
2958a35bdd44SMichael Tuexen 	}
2959a0aeb1ceSMichael Tuexen #endif
296013720136SMichael Tuexen 	if (params->sop_inc.inc_lport != htons(0) &&
296113720136SMichael Tuexen 	    params->sop_inc.inc_fport != htons(0)) {
2962a0aeb1ceSMichael Tuexen #ifdef INET6
2963a35bdd44SMichael Tuexen 		if (params->sop_inc.inc_flags & INC_ISIPV6)
2964a35bdd44SMichael Tuexen 			inpi.hash = INP6_PCBHASH(
2965a35bdd44SMichael Tuexen 			    &params->sop_inc.inc6_faddr,
2966a35bdd44SMichael Tuexen 			    params->sop_inc.inc_lport,
2967a35bdd44SMichael Tuexen 			    params->sop_inc.inc_fport,
2968a35bdd44SMichael Tuexen 			    pcbinfo->ipi_hashmask);
2969a35bdd44SMichael Tuexen 		else
2970a0aeb1ceSMichael Tuexen #endif
2971a35bdd44SMichael Tuexen 			inpi.hash = INP_PCBHASH(
2972a35bdd44SMichael Tuexen 			    &params->sop_inc.inc_faddr,
2973a35bdd44SMichael Tuexen 			    params->sop_inc.inc_lport,
2974a35bdd44SMichael Tuexen 			    params->sop_inc.inc_fport,
2975a35bdd44SMichael Tuexen 			    pcbinfo->ipi_hashmask);
2976a35bdd44SMichael Tuexen 	}
2977a35bdd44SMichael Tuexen 	while ((inp = inp_next(&inpi)) != NULL)
2978a35bdd44SMichael Tuexen 		if (inp->inp_gencnt == params->sop_id) {
297953af6903SGleb Smirnoff 			if (inp->inp_flags & INP_DROPPED) {
2980a35bdd44SMichael Tuexen 				INP_WUNLOCK(inp);
2981a35bdd44SMichael Tuexen 				return (ECONNRESET);
2982a35bdd44SMichael Tuexen 			}
2983a35bdd44SMichael Tuexen 			so = inp->inp_socket;
2984a35bdd44SMichael Tuexen 			KASSERT(so != NULL, ("inp_socket == NULL"));
2985a35bdd44SMichael Tuexen 			soref(so);
2986bed7633bSMichael Tuexen 			if (params->sop_level == SOL_SOCKET) {
2987bed7633bSMichael Tuexen 				INP_WUNLOCK(inp);
2988bed7633bSMichael Tuexen 				error = sosetopt(so, &sopt);
2989bed7633bSMichael Tuexen 			} else
2990a35bdd44SMichael Tuexen 				error = (*ctloutput_set)(inp, &sopt);
2991a35bdd44SMichael Tuexen 			sorele(so);
2992a35bdd44SMichael Tuexen 			break;
2993a35bdd44SMichael Tuexen 		}
2994a35bdd44SMichael Tuexen 	if (inp == NULL)
2995a35bdd44SMichael Tuexen 		error = ESRCH;
2996a35bdd44SMichael Tuexen 	return (error);
2997a35bdd44SMichael Tuexen }
2998a35bdd44SMichael Tuexen 
2999497057eeSRobert Watson #ifdef DDB
3000497057eeSRobert Watson static void
3001497057eeSRobert Watson db_print_indent(int indent)
3002497057eeSRobert Watson {
3003497057eeSRobert Watson 	int i;
3004497057eeSRobert Watson 
3005497057eeSRobert Watson 	for (i = 0; i < indent; i++)
3006497057eeSRobert Watson 		db_printf(" ");
3007497057eeSRobert Watson }
3008497057eeSRobert Watson 
3009497057eeSRobert Watson static void
3010497057eeSRobert Watson db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
3011497057eeSRobert Watson {
3012497057eeSRobert Watson 	char faddr_str[48], laddr_str[48];
3013497057eeSRobert Watson 
3014497057eeSRobert Watson 	db_print_indent(indent);
3015497057eeSRobert Watson 	db_printf("%s at %p\n", name, inc);
3016497057eeSRobert Watson 
3017497057eeSRobert Watson 	indent += 2;
3018497057eeSRobert Watson 
301903dc38a4SRobert Watson #ifdef INET6
3020dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
3021497057eeSRobert Watson 		/* IPv6. */
3022497057eeSRobert Watson 		ip6_sprintf(laddr_str, &inc->inc6_laddr);
3023497057eeSRobert Watson 		ip6_sprintf(faddr_str, &inc->inc6_faddr);
302483e521ecSBjoern A. Zeeb 	} else
302503dc38a4SRobert Watson #endif
302683e521ecSBjoern A. Zeeb 	{
3027497057eeSRobert Watson 		/* IPv4. */
3028497057eeSRobert Watson 		inet_ntoa_r(inc->inc_laddr, laddr_str);
3029497057eeSRobert Watson 		inet_ntoa_r(inc->inc_faddr, faddr_str);
3030497057eeSRobert Watson 	}
3031497057eeSRobert Watson 	db_print_indent(indent);
3032497057eeSRobert Watson 	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
3033497057eeSRobert Watson 	    ntohs(inc->inc_lport));
3034497057eeSRobert Watson 	db_print_indent(indent);
3035497057eeSRobert Watson 	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
3036497057eeSRobert Watson 	    ntohs(inc->inc_fport));
3037497057eeSRobert Watson }
3038497057eeSRobert Watson 
3039497057eeSRobert Watson static void
3040497057eeSRobert Watson db_print_inpflags(int inp_flags)
3041497057eeSRobert Watson {
3042497057eeSRobert Watson 	int comma;
3043497057eeSRobert Watson 
3044497057eeSRobert Watson 	comma = 0;
3045497057eeSRobert Watson 	if (inp_flags & INP_RECVOPTS) {
3046497057eeSRobert Watson 		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
3047497057eeSRobert Watson 		comma = 1;
3048497057eeSRobert Watson 	}
3049497057eeSRobert Watson 	if (inp_flags & INP_RECVRETOPTS) {
3050497057eeSRobert Watson 		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
3051497057eeSRobert Watson 		comma = 1;
3052497057eeSRobert Watson 	}
3053497057eeSRobert Watson 	if (inp_flags & INP_RECVDSTADDR) {
3054497057eeSRobert Watson 		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
3055497057eeSRobert Watson 		comma = 1;
3056497057eeSRobert Watson 	}
3057dce33a45SErmal Luçi 	if (inp_flags & INP_ORIGDSTADDR) {
3058dce33a45SErmal Luçi 		db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
3059dce33a45SErmal Luçi 		comma = 1;
3060dce33a45SErmal Luçi 	}
3061497057eeSRobert Watson 	if (inp_flags & INP_HDRINCL) {
3062497057eeSRobert Watson 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
3063497057eeSRobert Watson 		comma = 1;
3064497057eeSRobert Watson 	}
3065497057eeSRobert Watson 	if (inp_flags & INP_HIGHPORT) {
3066497057eeSRobert Watson 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
3067497057eeSRobert Watson 		comma = 1;
3068497057eeSRobert Watson 	}
3069497057eeSRobert Watson 	if (inp_flags & INP_LOWPORT) {
3070497057eeSRobert Watson 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
3071497057eeSRobert Watson 		comma = 1;
3072497057eeSRobert Watson 	}
3073497057eeSRobert Watson 	if (inp_flags & INP_ANONPORT) {
3074497057eeSRobert Watson 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
3075497057eeSRobert Watson 		comma = 1;
3076497057eeSRobert Watson 	}
3077497057eeSRobert Watson 	if (inp_flags & INP_RECVIF) {
3078497057eeSRobert Watson 		db_printf("%sINP_RECVIF", comma ? ", " : "");
3079497057eeSRobert Watson 		comma = 1;
3080497057eeSRobert Watson 	}
3081497057eeSRobert Watson 	if (inp_flags & INP_MTUDISC) {
3082497057eeSRobert Watson 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
3083497057eeSRobert Watson 		comma = 1;
3084497057eeSRobert Watson 	}
3085497057eeSRobert Watson 	if (inp_flags & INP_RECVTTL) {
3086497057eeSRobert Watson 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
3087497057eeSRobert Watson 		comma = 1;
3088497057eeSRobert Watson 	}
3089497057eeSRobert Watson 	if (inp_flags & INP_DONTFRAG) {
3090497057eeSRobert Watson 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3091497057eeSRobert Watson 		comma = 1;
3092497057eeSRobert Watson 	}
30933cca425bSMichael Tuexen 	if (inp_flags & INP_RECVTOS) {
30943cca425bSMichael Tuexen 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
30953cca425bSMichael Tuexen 		comma = 1;
30963cca425bSMichael Tuexen 	}
3097497057eeSRobert Watson 	if (inp_flags & IN6P_IPV6_V6ONLY) {
3098497057eeSRobert Watson 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3099497057eeSRobert Watson 		comma = 1;
3100497057eeSRobert Watson 	}
3101497057eeSRobert Watson 	if (inp_flags & IN6P_PKTINFO) {
3102497057eeSRobert Watson 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3103497057eeSRobert Watson 		comma = 1;
3104497057eeSRobert Watson 	}
3105497057eeSRobert Watson 	if (inp_flags & IN6P_HOPLIMIT) {
3106497057eeSRobert Watson 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3107497057eeSRobert Watson 		comma = 1;
3108497057eeSRobert Watson 	}
3109497057eeSRobert Watson 	if (inp_flags & IN6P_HOPOPTS) {
3110497057eeSRobert Watson 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3111497057eeSRobert Watson 		comma = 1;
3112497057eeSRobert Watson 	}
3113497057eeSRobert Watson 	if (inp_flags & IN6P_DSTOPTS) {
3114497057eeSRobert Watson 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3115497057eeSRobert Watson 		comma = 1;
3116497057eeSRobert Watson 	}
3117497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDR) {
3118497057eeSRobert Watson 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3119497057eeSRobert Watson 		comma = 1;
3120497057eeSRobert Watson 	}
3121497057eeSRobert Watson 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
3122497057eeSRobert Watson 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3123497057eeSRobert Watson 		comma = 1;
3124497057eeSRobert Watson 	}
3125497057eeSRobert Watson 	if (inp_flags & IN6P_TCLASS) {
3126497057eeSRobert Watson 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3127497057eeSRobert Watson 		comma = 1;
3128497057eeSRobert Watson 	}
3129497057eeSRobert Watson 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
3130497057eeSRobert Watson 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3131497057eeSRobert Watson 		comma = 1;
3132497057eeSRobert Watson 	}
3133ad71fe3cSRobert Watson 	if (inp_flags & INP_ONESBCAST) {
3134ad71fe3cSRobert Watson 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3135ad71fe3cSRobert Watson 		comma  = 1;
3136ad71fe3cSRobert Watson 	}
3137ad71fe3cSRobert Watson 	if (inp_flags & INP_DROPPED) {
3138ad71fe3cSRobert Watson 		db_printf("%sINP_DROPPED", comma ? ", " : "");
3139ad71fe3cSRobert Watson 		comma  = 1;
3140ad71fe3cSRobert Watson 	}
3141ad71fe3cSRobert Watson 	if (inp_flags & INP_SOCKREF) {
3142ad71fe3cSRobert Watson 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
3143ad71fe3cSRobert Watson 		comma  = 1;
3144ad71fe3cSRobert Watson 	}
3145497057eeSRobert Watson 	if (inp_flags & IN6P_RFC2292) {
3146497057eeSRobert Watson 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3147497057eeSRobert Watson 		comma = 1;
3148497057eeSRobert Watson 	}
3149497057eeSRobert Watson 	if (inp_flags & IN6P_MTU) {
3150497057eeSRobert Watson 		db_printf("IN6P_MTU%s", comma ? ", " : "");
3151497057eeSRobert Watson 		comma = 1;
3152497057eeSRobert Watson 	}
3153497057eeSRobert Watson }
3154497057eeSRobert Watson 
3155497057eeSRobert Watson static void
3156497057eeSRobert Watson db_print_inpvflag(u_char inp_vflag)
3157497057eeSRobert Watson {
3158497057eeSRobert Watson 	int comma;
3159497057eeSRobert Watson 
3160497057eeSRobert Watson 	comma = 0;
3161497057eeSRobert Watson 	if (inp_vflag & INP_IPV4) {
3162497057eeSRobert Watson 		db_printf("%sINP_IPV4", comma ? ", " : "");
3163497057eeSRobert Watson 		comma  = 1;
3164497057eeSRobert Watson 	}
3165497057eeSRobert Watson 	if (inp_vflag & INP_IPV6) {
3166497057eeSRobert Watson 		db_printf("%sINP_IPV6", comma ? ", " : "");
3167497057eeSRobert Watson 		comma  = 1;
3168497057eeSRobert Watson 	}
3169497057eeSRobert Watson 	if (inp_vflag & INP_IPV6PROTO) {
3170497057eeSRobert Watson 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3171497057eeSRobert Watson 		comma  = 1;
3172497057eeSRobert Watson 	}
3173497057eeSRobert Watson }
3174497057eeSRobert Watson 
31756d888973SRobert Watson static void
3176497057eeSRobert Watson db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3177497057eeSRobert Watson {
3178497057eeSRobert Watson 
3179497057eeSRobert Watson 	db_print_indent(indent);
3180497057eeSRobert Watson 	db_printf("%s at %p\n", name, inp);
3181497057eeSRobert Watson 
3182497057eeSRobert Watson 	indent += 2;
3183497057eeSRobert Watson 
3184497057eeSRobert Watson 	db_print_indent(indent);
3185497057eeSRobert Watson 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3186497057eeSRobert Watson 
3187497057eeSRobert Watson 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3188497057eeSRobert Watson 
3189497057eeSRobert Watson 	db_print_indent(indent);
3190497057eeSRobert Watson 	db_printf("inp_label: %p   inp_flags: 0x%x (",
3191497057eeSRobert Watson 	   inp->inp_label, inp->inp_flags);
3192497057eeSRobert Watson 	db_print_inpflags(inp->inp_flags);
3193497057eeSRobert Watson 	db_printf(")\n");
3194497057eeSRobert Watson 
3195497057eeSRobert Watson 	db_print_indent(indent);
3196497057eeSRobert Watson 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3197497057eeSRobert Watson 	    inp->inp_vflag);
3198497057eeSRobert Watson 	db_print_inpvflag(inp->inp_vflag);
3199497057eeSRobert Watson 	db_printf(")\n");
3200497057eeSRobert Watson 
3201497057eeSRobert Watson 	db_print_indent(indent);
3202497057eeSRobert Watson 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3203497057eeSRobert Watson 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3204497057eeSRobert Watson 
3205497057eeSRobert Watson 	db_print_indent(indent);
3206497057eeSRobert Watson #ifdef INET6
3207497057eeSRobert Watson 	if (inp->inp_vflag & INP_IPV6) {
3208497057eeSRobert Watson 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
3209497057eeSRobert Watson 		    "in6p_moptions: %p\n", inp->in6p_options,
3210497057eeSRobert Watson 		    inp->in6p_outputopts, inp->in6p_moptions);
3211497057eeSRobert Watson 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3212497057eeSRobert Watson 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3213497057eeSRobert Watson 		    inp->in6p_hops);
3214497057eeSRobert Watson 	} else
3215497057eeSRobert Watson #endif
3216497057eeSRobert Watson 	{
3217497057eeSRobert Watson 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3218497057eeSRobert Watson 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3219497057eeSRobert Watson 		    inp->inp_options, inp->inp_moptions);
3220497057eeSRobert Watson 	}
3221497057eeSRobert Watson 
3222497057eeSRobert Watson 	db_print_indent(indent);
32235f539170SGleb Smirnoff 	db_printf("inp_gencnt: %ju\n", (uintmax_t)inp->inp_gencnt);
3224497057eeSRobert Watson }
3225497057eeSRobert Watson 
3226497057eeSRobert Watson DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3227497057eeSRobert Watson {
3228497057eeSRobert Watson 	struct inpcb *inp;
3229497057eeSRobert Watson 
3230497057eeSRobert Watson 	if (!have_addr) {
3231497057eeSRobert Watson 		db_printf("usage: show inpcb <addr>\n");
3232497057eeSRobert Watson 		return;
3233497057eeSRobert Watson 	}
3234497057eeSRobert Watson 	inp = (struct inpcb *)addr;
3235497057eeSRobert Watson 
3236497057eeSRobert Watson 	db_print_inpcb(inp, "inpcb", 0);
3237497057eeSRobert Watson }
323883e521ecSBjoern A. Zeeb #endif /* DDB */
3239f3e7afe2SHans Petter Selasky 
3240f3e7afe2SHans Petter Selasky #ifdef RATELIMIT
3241f3e7afe2SHans Petter Selasky /*
3242f3e7afe2SHans Petter Selasky  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3243f3e7afe2SHans Petter Selasky  * if any.
3244f3e7afe2SHans Petter Selasky  */
3245f3e7afe2SHans Petter Selasky int
3246f3e7afe2SHans Petter Selasky in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3247f3e7afe2SHans Petter Selasky {
3248f3e7afe2SHans Petter Selasky 	union if_snd_tag_modify_params params = {
3249f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
325020abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3251f3e7afe2SHans Petter Selasky 	};
3252f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3253f3e7afe2SHans Petter Selasky 	int error;
3254f3e7afe2SHans Petter Selasky 
3255f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3256f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3257f3e7afe2SHans Petter Selasky 		return (EINVAL);
3258f3e7afe2SHans Petter Selasky 
3259c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_modify == NULL) {
3260f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3261f3e7afe2SHans Petter Selasky 	} else {
3262c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_modify(mst, &params);
3263f3e7afe2SHans Petter Selasky 	}
3264f3e7afe2SHans Petter Selasky 	return (error);
3265f3e7afe2SHans Petter Selasky }
3266f3e7afe2SHans Petter Selasky 
3267f3e7afe2SHans Petter Selasky /*
3268f3e7afe2SHans Petter Selasky  * Query existing TX rate limit based on the existing
3269f3e7afe2SHans Petter Selasky  * "inp->inp_snd_tag", if any.
3270f3e7afe2SHans Petter Selasky  */
3271f3e7afe2SHans Petter Selasky int
3272f3e7afe2SHans Petter Selasky in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3273f3e7afe2SHans Petter Selasky {
3274f3e7afe2SHans Petter Selasky 	union if_snd_tag_query_params params = { };
3275f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3276f3e7afe2SHans Petter Selasky 	int error;
3277f3e7afe2SHans Petter Selasky 
3278f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3279f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3280f3e7afe2SHans Petter Selasky 		return (EINVAL);
3281f3e7afe2SHans Petter Selasky 
3282c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL) {
3283f3e7afe2SHans Petter Selasky 		error = EOPNOTSUPP;
3284f3e7afe2SHans Petter Selasky 	} else {
3285c782ea8bSJohn Baldwin 		error = mst->sw->snd_tag_query(mst, &params);
3286f3e7afe2SHans Petter Selasky 		if (error == 0 && p_max_pacing_rate != NULL)
3287f3e7afe2SHans Petter Selasky 			*p_max_pacing_rate = params.rate_limit.max_rate;
3288f3e7afe2SHans Petter Selasky 	}
3289f3e7afe2SHans Petter Selasky 	return (error);
3290f3e7afe2SHans Petter Selasky }
3291f3e7afe2SHans Petter Selasky 
3292f3e7afe2SHans Petter Selasky /*
329395ed5015SHans Petter Selasky  * Query existing TX queue level based on the existing
329495ed5015SHans Petter Selasky  * "inp->inp_snd_tag", if any.
329595ed5015SHans Petter Selasky  */
329695ed5015SHans Petter Selasky int
329795ed5015SHans Petter Selasky in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
329895ed5015SHans Petter Selasky {
329995ed5015SHans Petter Selasky 	union if_snd_tag_query_params params = { };
330095ed5015SHans Petter Selasky 	struct m_snd_tag *mst;
330195ed5015SHans Petter Selasky 	int error;
330295ed5015SHans Petter Selasky 
330395ed5015SHans Petter Selasky 	mst = inp->inp_snd_tag;
330495ed5015SHans Petter Selasky 	if (mst == NULL)
330595ed5015SHans Petter Selasky 		return (EINVAL);
330695ed5015SHans Petter Selasky 
3307c782ea8bSJohn Baldwin 	if (mst->sw->snd_tag_query == NULL)
330895ed5015SHans Petter Selasky 		return (EOPNOTSUPP);
330995ed5015SHans Petter Selasky 
3310c782ea8bSJohn Baldwin 	error = mst->sw->snd_tag_query(mst, &params);
331195ed5015SHans Petter Selasky 	if (error == 0 && p_txqueue_level != NULL)
331295ed5015SHans Petter Selasky 		*p_txqueue_level = params.rate_limit.queue_level;
331395ed5015SHans Petter Selasky 	return (error);
331495ed5015SHans Petter Selasky }
331595ed5015SHans Petter Selasky 
331695ed5015SHans Petter Selasky /*
3317f3e7afe2SHans Petter Selasky  * Allocate a new TX rate limit send tag from the network interface
3318f3e7afe2SHans Petter Selasky  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3319f3e7afe2SHans Petter Selasky  */
3320f3e7afe2SHans Petter Selasky int
3321f3e7afe2SHans Petter Selasky in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
332220abea66SRandall Stewart     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate, struct m_snd_tag **st)
332320abea66SRandall Stewart 
3324f3e7afe2SHans Petter Selasky {
3325f3e7afe2SHans Petter Selasky 	union if_snd_tag_alloc_params params = {
332695ed5015SHans Petter Selasky 		.rate_limit.hdr.type = (max_pacing_rate == -1U) ?
332795ed5015SHans Petter Selasky 		    IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3328f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowid = flowid,
3329f3e7afe2SHans Petter Selasky 		.rate_limit.hdr.flowtype = flowtype,
333098085baeSAndrew Gallatin 		.rate_limit.hdr.numa_domain = inp->inp_numa_domain,
3331f3e7afe2SHans Petter Selasky 		.rate_limit.max_rate = max_pacing_rate,
333220abea66SRandall Stewart 		.rate_limit.flags = M_NOWAIT,
3333f3e7afe2SHans Petter Selasky 	};
3334f3e7afe2SHans Petter Selasky 	int error;
3335f3e7afe2SHans Petter Selasky 
3336f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3337f3e7afe2SHans Petter Selasky 
333885d8d30fSHans Petter Selasky 	/*
333985d8d30fSHans Petter Selasky 	 * If there is already a send tag, or the INP is being torn
334085d8d30fSHans Petter Selasky 	 * down, allocating a new send tag is not allowed. Else send
334185d8d30fSHans Petter Selasky 	 * tags may leak.
334285d8d30fSHans Petter Selasky 	 */
334353af6903SGleb Smirnoff 	if (*st != NULL || (inp->inp_flags & INP_DROPPED) != 0)
3344f3e7afe2SHans Petter Selasky 		return (EINVAL);
3345f3e7afe2SHans Petter Selasky 
334636e0a362SJohn Baldwin 	error = m_snd_tag_alloc(ifp, &params, st);
3347903c4ee6SXin LI #ifdef INET
334820abea66SRandall Stewart 	if (error == 0) {
334920abea66SRandall Stewart 		counter_u64_add(rate_limit_set_ok, 1);
335020abea66SRandall Stewart 		counter_u64_add(rate_limit_active, 1);
335136e0a362SJohn Baldwin 	} else if (error != EOPNOTSUPP)
335220abea66SRandall Stewart 		  counter_u64_add(rate_limit_alloc_fail, 1);
3353903c4ee6SXin LI #endif
3354f3e7afe2SHans Petter Selasky 	return (error);
3355f3e7afe2SHans Petter Selasky }
3356f3e7afe2SHans Petter Selasky 
335720abea66SRandall Stewart void
335898d7a8d9SJohn Baldwin in_pcbdetach_tag(struct m_snd_tag *mst)
335920abea66SRandall Stewart {
336020abea66SRandall Stewart 
336198d7a8d9SJohn Baldwin 	m_snd_tag_rele(mst);
3362903c4ee6SXin LI #ifdef INET
336320abea66SRandall Stewart 	counter_u64_add(rate_limit_active, -1);
3364903c4ee6SXin LI #endif
336520abea66SRandall Stewart }
336620abea66SRandall Stewart 
3367f3e7afe2SHans Petter Selasky /*
3368f3e7afe2SHans Petter Selasky  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3369f3e7afe2SHans Petter Selasky  * if any:
3370f3e7afe2SHans Petter Selasky  */
3371f3e7afe2SHans Petter Selasky void
3372f3e7afe2SHans Petter Selasky in_pcbdetach_txrtlmt(struct inpcb *inp)
3373f3e7afe2SHans Petter Selasky {
3374f3e7afe2SHans Petter Selasky 	struct m_snd_tag *mst;
3375f3e7afe2SHans Petter Selasky 
3376f3e7afe2SHans Petter Selasky 	INP_WLOCK_ASSERT(inp);
3377f3e7afe2SHans Petter Selasky 
3378f3e7afe2SHans Petter Selasky 	mst = inp->inp_snd_tag;
3379f3e7afe2SHans Petter Selasky 	inp->inp_snd_tag = NULL;
3380f3e7afe2SHans Petter Selasky 
3381f3e7afe2SHans Petter Selasky 	if (mst == NULL)
3382f3e7afe2SHans Petter Selasky 		return;
3383f3e7afe2SHans Petter Selasky 
3384fb3bc596SJohn Baldwin 	m_snd_tag_rele(mst);
3385093e7231SHans Petter Selasky #ifdef INET
3386093e7231SHans Petter Selasky 	counter_u64_add(rate_limit_active, -1);
3387093e7231SHans Petter Selasky #endif
3388f3e7afe2SHans Petter Selasky }
3389f3e7afe2SHans Petter Selasky 
339020abea66SRandall Stewart int
339120abea66SRandall Stewart in_pcboutput_txrtlmt_locked(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb, uint32_t max_pacing_rate)
339220abea66SRandall Stewart {
339320abea66SRandall Stewart 	int error;
339420abea66SRandall Stewart 
339520abea66SRandall Stewart 	/*
339620abea66SRandall Stewart 	 * If the existing send tag is for the wrong interface due to
339720abea66SRandall Stewart 	 * a route change, first drop the existing tag.  Set the
339820abea66SRandall Stewart 	 * CHANGED flag so that we will keep trying to allocate a new
339920abea66SRandall Stewart 	 * tag if we fail to allocate one this time.
340020abea66SRandall Stewart 	 */
340120abea66SRandall Stewart 	if (inp->inp_snd_tag != NULL && inp->inp_snd_tag->ifp != ifp) {
340220abea66SRandall Stewart 		in_pcbdetach_txrtlmt(inp);
340320abea66SRandall Stewart 		inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
340420abea66SRandall Stewart 	}
340520abea66SRandall Stewart 
340620abea66SRandall Stewart 	/*
340720abea66SRandall Stewart 	 * NOTE: When attaching to a network interface a reference is
340820abea66SRandall Stewart 	 * made to ensure the network interface doesn't go away until
340920abea66SRandall Stewart 	 * all ratelimit connections are gone. The network interface
341020abea66SRandall Stewart 	 * pointers compared below represent valid network interfaces,
341120abea66SRandall Stewart 	 * except when comparing towards NULL.
341220abea66SRandall Stewart 	 */
341320abea66SRandall Stewart 	if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
341420abea66SRandall Stewart 		error = 0;
341520abea66SRandall Stewart 	} else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
341620abea66SRandall Stewart 		if (inp->inp_snd_tag != NULL)
341720abea66SRandall Stewart 			in_pcbdetach_txrtlmt(inp);
341820abea66SRandall Stewart 		error = 0;
341920abea66SRandall Stewart 	} else if (inp->inp_snd_tag == NULL) {
342020abea66SRandall Stewart 		/*
342120abea66SRandall Stewart 		 * In order to utilize packet pacing with RSS, we need
342220abea66SRandall Stewart 		 * to wait until there is a valid RSS hash before we
342320abea66SRandall Stewart 		 * can proceed:
342420abea66SRandall Stewart 		 */
342520abea66SRandall Stewart 		if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
342620abea66SRandall Stewart 			error = EAGAIN;
342720abea66SRandall Stewart 		} else {
342820abea66SRandall Stewart 			error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
342920abea66SRandall Stewart 			    mb->m_pkthdr.flowid, max_pacing_rate, &inp->inp_snd_tag);
343020abea66SRandall Stewart 		}
343120abea66SRandall Stewart 	} else {
343220abea66SRandall Stewart 		error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
343320abea66SRandall Stewart 	}
343420abea66SRandall Stewart 	if (error == 0 || error == EOPNOTSUPP)
343520abea66SRandall Stewart 		inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
343620abea66SRandall Stewart 
343720abea66SRandall Stewart 	return (error);
343820abea66SRandall Stewart }
343920abea66SRandall Stewart 
3440f3e7afe2SHans Petter Selasky /*
3441f3e7afe2SHans Petter Selasky  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3442f3e7afe2SHans Petter Selasky  * is set in the fast path and will attach/detach/modify the TX rate
3443f3e7afe2SHans Petter Selasky  * limit send tag based on the socket's so_max_pacing_rate value.
3444f3e7afe2SHans Petter Selasky  */
3445f3e7afe2SHans Petter Selasky void
3446f3e7afe2SHans Petter Selasky in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3447f3e7afe2SHans Petter Selasky {
3448f3e7afe2SHans Petter Selasky 	struct socket *socket;
3449f3e7afe2SHans Petter Selasky 	uint32_t max_pacing_rate;
3450f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3451f3e7afe2SHans Petter Selasky 
3452f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3453f3e7afe2SHans Petter Selasky 		return;
3454f3e7afe2SHans Petter Selasky 
3455f3e7afe2SHans Petter Selasky 	socket = inp->inp_socket;
3456f3e7afe2SHans Petter Selasky 	if (socket == NULL)
3457f3e7afe2SHans Petter Selasky 		return;
3458f3e7afe2SHans Petter Selasky 
3459f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3460f3e7afe2SHans Petter Selasky 		/*
3461f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3462f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3463f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3464f3e7afe2SHans Petter Selasky 		 * write lock.
3465f3e7afe2SHans Petter Selasky 		 */
3466f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3467f3e7afe2SHans Petter Selasky 			return;
3468f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3469f3e7afe2SHans Petter Selasky 	} else {
3470f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3471f3e7afe2SHans Petter Selasky 	}
3472f3e7afe2SHans Petter Selasky 
3473f3e7afe2SHans Petter Selasky 	/*
3474f3e7afe2SHans Petter Selasky 	 * NOTE: The so_max_pacing_rate value is read unlocked,
3475f3e7afe2SHans Petter Selasky 	 * because atomic updates are not required since the variable
3476f3e7afe2SHans Petter Selasky 	 * is checked at every mbuf we send. It is assumed that the
3477f3e7afe2SHans Petter Selasky 	 * variable read itself will be atomic.
3478f3e7afe2SHans Petter Selasky 	 */
3479f3e7afe2SHans Petter Selasky 	max_pacing_rate = socket->so_max_pacing_rate;
3480f3e7afe2SHans Petter Selasky 
3481bab34d63SJohn Baldwin 	in_pcboutput_txrtlmt_locked(inp, ifp, mb, max_pacing_rate);
3482fb3bc596SJohn Baldwin 
3483f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3484f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3485f3e7afe2SHans Petter Selasky }
3486f3e7afe2SHans Petter Selasky 
3487f3e7afe2SHans Petter Selasky /*
3488f3e7afe2SHans Petter Selasky  * Track route changes for TX rate limiting.
3489f3e7afe2SHans Petter Selasky  */
3490f3e7afe2SHans Petter Selasky void
3491f3e7afe2SHans Petter Selasky in_pcboutput_eagain(struct inpcb *inp)
3492f3e7afe2SHans Petter Selasky {
3493f3e7afe2SHans Petter Selasky 	bool did_upgrade;
3494f3e7afe2SHans Petter Selasky 
3495f3e7afe2SHans Petter Selasky 	if (inp == NULL)
3496f3e7afe2SHans Petter Selasky 		return;
3497f3e7afe2SHans Petter Selasky 
3498f3e7afe2SHans Petter Selasky 	if (inp->inp_snd_tag == NULL)
3499f3e7afe2SHans Petter Selasky 		return;
3500f3e7afe2SHans Petter Selasky 
3501f3e7afe2SHans Petter Selasky 	if (!INP_WLOCKED(inp)) {
3502f3e7afe2SHans Petter Selasky 		/*
3503f3e7afe2SHans Petter Selasky 		 * NOTE: If the write locking fails, we need to bail
3504f3e7afe2SHans Petter Selasky 		 * out and use the non-ratelimited ring for the
3505f3e7afe2SHans Petter Selasky 		 * transmit until there is a new chance to get the
3506f3e7afe2SHans Petter Selasky 		 * write lock.
3507f3e7afe2SHans Petter Selasky 		 */
3508f3e7afe2SHans Petter Selasky 		if (!INP_TRY_UPGRADE(inp))
3509f3e7afe2SHans Petter Selasky 			return;
3510f3e7afe2SHans Petter Selasky 		did_upgrade = 1;
3511f3e7afe2SHans Petter Selasky 	} else {
3512f3e7afe2SHans Petter Selasky 		did_upgrade = 0;
3513f3e7afe2SHans Petter Selasky 	}
3514f3e7afe2SHans Petter Selasky 
3515f3e7afe2SHans Petter Selasky 	/* detach rate limiting */
3516f3e7afe2SHans Petter Selasky 	in_pcbdetach_txrtlmt(inp);
3517f3e7afe2SHans Petter Selasky 
3518f3e7afe2SHans Petter Selasky 	/* make sure new mbuf send tag allocation is made */
3519f3e7afe2SHans Petter Selasky 	inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3520f3e7afe2SHans Petter Selasky 
3521f3e7afe2SHans Petter Selasky 	if (did_upgrade)
3522f3e7afe2SHans Petter Selasky 		INP_DOWNGRADE(inp);
3523f3e7afe2SHans Petter Selasky }
352420abea66SRandall Stewart 
3525903c4ee6SXin LI #ifdef INET
352620abea66SRandall Stewart static void
352720abea66SRandall Stewart rl_init(void *st)
352820abea66SRandall Stewart {
35291a714ff2SRandall Stewart 	rate_limit_new = counter_u64_alloc(M_WAITOK);
35301a714ff2SRandall Stewart 	rate_limit_chg = counter_u64_alloc(M_WAITOK);
353120abea66SRandall Stewart 	rate_limit_active = counter_u64_alloc(M_WAITOK);
353220abea66SRandall Stewart 	rate_limit_alloc_fail = counter_u64_alloc(M_WAITOK);
353320abea66SRandall Stewart 	rate_limit_set_ok = counter_u64_alloc(M_WAITOK);
353420abea66SRandall Stewart }
353520abea66SRandall Stewart 
353620abea66SRandall Stewart SYSINIT(rl, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, rl_init, NULL);
3537903c4ee6SXin LI #endif
3538f3e7afe2SHans Petter Selasky #endif /* RATELIMIT */
3539