in_pcb.c revision 266718
1/*-
2 * Copyright (c) 1982, 1986, 1991, 1993, 1995
3 *	The Regents of the University of California.
4 * Copyright (c) 2007-2009 Robert N. M. Watson
5 * Copyright (c) 2010-2011 Juniper Networks, Inc.
6 * All rights reserved.
7 *
8 * Portions of this software were developed by Robert N. M. Watson under
9 * contract to Juniper Networks, Inc.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 * 4. Neither the name of the University nor the names of its contributors
20 *    may be used to endorse or promote products derived from this software
21 *    without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
36 */
37
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: stable/10/sys/netinet/in_pcb.c 266718 2014-05-26 22:54:15Z smh $");
40
41#include "opt_ddb.h"
42#include "opt_ipsec.h"
43#include "opt_inet.h"
44#include "opt_inet6.h"
45#include "opt_pcbgroup.h"
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/malloc.h>
50#include <sys/mbuf.h>
51#include <sys/callout.h>
52#include <sys/domain.h>
53#include <sys/protosw.h>
54#include <sys/socket.h>
55#include <sys/socketvar.h>
56#include <sys/priv.h>
57#include <sys/proc.h>
58#include <sys/refcount.h>
59#include <sys/jail.h>
60#include <sys/kernel.h>
61#include <sys/sysctl.h>
62
63#ifdef DDB
64#include <ddb/ddb.h>
65#endif
66
67#include <vm/uma.h>
68
69#include <net/if.h>
70#include <net/if_types.h>
71#include <net/route.h>
72#include <net/vnet.h>
73
74#if defined(INET) || defined(INET6)
75#include <netinet/in.h>
76#include <netinet/in_pcb.h>
77#include <netinet/ip_var.h>
78#include <netinet/tcp_var.h>
79#include <netinet/udp.h>
80#include <netinet/udp_var.h>
81#endif
82#ifdef INET
83#include <netinet/in_var.h>
84#endif
85#ifdef INET6
86#include <netinet/ip6.h>
87#include <netinet6/in6_pcb.h>
88#include <netinet6/in6_var.h>
89#include <netinet6/ip6_var.h>
90#endif /* INET6 */
91
92
93#ifdef IPSEC
94#include <netipsec/ipsec.h>
95#include <netipsec/key.h>
96#endif /* IPSEC */
97
98#include <security/mac/mac_framework.h>
99
100static struct callout	ipport_tick_callout;
101
102/*
103 * These configure the range of local port addresses assigned to
104 * "unspecified" outgoing connections/packets/whatever.
105 */
106VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
107VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
108VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
109VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
110VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
111VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
112
113/*
114 * Reserved ports accessible only to root. There are significant
115 * security considerations that must be accounted for when changing these,
116 * but the security benefits can be great. Please be careful.
117 */
118VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
119VNET_DEFINE(int, ipport_reservedlow);
120
121/* Variables dealing with random ephemeral port allocation. */
122VNET_DEFINE(int, ipport_randomized) = 1;	/* user controlled via sysctl */
123VNET_DEFINE(int, ipport_randomcps) = 10;	/* user controlled via sysctl */
124VNET_DEFINE(int, ipport_randomtime) = 45;	/* user controlled via sysctl */
125VNET_DEFINE(int, ipport_stoprandom);		/* toggled by ipport_tick */
126VNET_DEFINE(int, ipport_tcpallocs);
127static VNET_DEFINE(int, ipport_tcplastcount);
128
129#define	V_ipport_tcplastcount		VNET(ipport_tcplastcount)
130
131static void	in_pcbremlists(struct inpcb *inp);
132#ifdef INET
133static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
134			    struct in_addr faddr, u_int fport_arg,
135			    struct in_addr laddr, u_int lport_arg,
136			    int lookupflags, struct ifnet *ifp);
137
138#define RANGECHK(var, min, max) \
139	if ((var) < (min)) { (var) = (min); } \
140	else if ((var) > (max)) { (var) = (max); }
141
142static int
143sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
144{
145	int error;
146
147	error = sysctl_handle_int(oidp, arg1, arg2, req);
148	if (error == 0) {
149		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
150		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
151		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
152		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
153		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
154		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
155	}
156	return (error);
157}
158
159#undef RANGECHK
160
161static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0,
162    "IP Ports");
163
164SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
165	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_lowfirstauto), 0,
166	&sysctl_net_ipport_check, "I", "");
167SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
168	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_lowlastauto), 0,
169	&sysctl_net_ipport_check, "I", "");
170SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, first,
171	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_firstauto), 0,
172	&sysctl_net_ipport_check, "I", "");
173SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, last,
174	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_lastauto), 0,
175	&sysctl_net_ipport_check, "I", "");
176SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
177	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_hifirstauto), 0,
178	&sysctl_net_ipport_check, "I", "");
179SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
180	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_hilastauto), 0,
181	&sysctl_net_ipport_check, "I", "");
182SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
183	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedhigh), 0, "");
184SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
185	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
186SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, randomized, CTLFLAG_RW,
187	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
188SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, randomcps, CTLFLAG_RW,
189	&VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
190	"allocations before switching to a sequental one");
191SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, randomtime, CTLFLAG_RW,
192	&VNET_NAME(ipport_randomtime), 0,
193	"Minimum time to keep sequental port "
194	"allocation before switching to a random one");
195#endif /* INET */
196
197/*
198 * in_pcb.c: manage the Protocol Control Blocks.
199 *
200 * NOTE: It is assumed that most of these functions will be called with
201 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
202 * functions often modify hash chains or addresses in pcbs.
203 */
204
205/*
206 * Initialize an inpcbinfo -- we should be able to reduce the number of
207 * arguments in time.
208 */
209void
210in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
211    struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
212    char *inpcbzone_name, uma_init inpcbzone_init, uma_fini inpcbzone_fini,
213    uint32_t inpcbzone_flags, u_int hashfields)
214{
215
216	INP_INFO_LOCK_INIT(pcbinfo, name);
217	INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash");	/* XXXRW: argument? */
218#ifdef VIMAGE
219	pcbinfo->ipi_vnet = curvnet;
220#endif
221	pcbinfo->ipi_listhead = listhead;
222	LIST_INIT(pcbinfo->ipi_listhead);
223	pcbinfo->ipi_count = 0;
224	pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
225	    &pcbinfo->ipi_hashmask);
226	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
227	    &pcbinfo->ipi_porthashmask);
228#ifdef PCBGROUP
229	in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
230#endif
231	pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
232	    NULL, NULL, inpcbzone_init, inpcbzone_fini, UMA_ALIGN_PTR,
233	    inpcbzone_flags);
234	uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
235	uma_zone_set_warning(pcbinfo->ipi_zone,
236	    "kern.ipc.maxsockets limit reached");
237}
238
239/*
240 * Destroy an inpcbinfo.
241 */
242void
243in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
244{
245
246	KASSERT(pcbinfo->ipi_count == 0,
247	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
248
249	hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
250	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
251	    pcbinfo->ipi_porthashmask);
252#ifdef PCBGROUP
253	in_pcbgroup_destroy(pcbinfo);
254#endif
255	uma_zdestroy(pcbinfo->ipi_zone);
256	INP_HASH_LOCK_DESTROY(pcbinfo);
257	INP_INFO_LOCK_DESTROY(pcbinfo);
258}
259
260/*
261 * Allocate a PCB and associate it with the socket.
262 * On success return with the PCB locked.
263 */
264int
265in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
266{
267	struct inpcb *inp;
268	int error;
269
270	INP_INFO_WLOCK_ASSERT(pcbinfo);
271	error = 0;
272	inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
273	if (inp == NULL)
274		return (ENOBUFS);
275	bzero(inp, inp_zero_size);
276	inp->inp_pcbinfo = pcbinfo;
277	inp->inp_socket = so;
278	inp->inp_cred = crhold(so->so_cred);
279	inp->inp_inc.inc_fibnum = so->so_fibnum;
280#ifdef MAC
281	error = mac_inpcb_init(inp, M_NOWAIT);
282	if (error != 0)
283		goto out;
284	mac_inpcb_create(so, inp);
285#endif
286#ifdef IPSEC
287	error = ipsec_init_policy(so, &inp->inp_sp);
288	if (error != 0) {
289#ifdef MAC
290		mac_inpcb_destroy(inp);
291#endif
292		goto out;
293	}
294#endif /*IPSEC*/
295#ifdef INET6
296	if (INP_SOCKAF(so) == AF_INET6) {
297		inp->inp_vflag |= INP_IPV6PROTO;
298		if (V_ip6_v6only)
299			inp->inp_flags |= IN6P_IPV6_V6ONLY;
300	}
301#endif
302	LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
303	pcbinfo->ipi_count++;
304	so->so_pcb = (caddr_t)inp;
305#ifdef INET6
306	if (V_ip6_auto_flowlabel)
307		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
308#endif
309	INP_WLOCK(inp);
310	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
311	refcount_init(&inp->inp_refcount, 1);	/* Reference from inpcbinfo */
312#if defined(IPSEC) || defined(MAC)
313out:
314	if (error != 0) {
315		crfree(inp->inp_cred);
316		uma_zfree(pcbinfo->ipi_zone, inp);
317	}
318#endif
319	return (error);
320}
321
322#ifdef INET
323int
324in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
325{
326	int anonport, error;
327
328	INP_WLOCK_ASSERT(inp);
329	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
330
331	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
332		return (EINVAL);
333	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
334	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
335	    &inp->inp_lport, cred);
336	if (error)
337		return (error);
338	if (in_pcbinshash(inp) != 0) {
339		inp->inp_laddr.s_addr = INADDR_ANY;
340		inp->inp_lport = 0;
341		return (EAGAIN);
342	}
343	if (anonport)
344		inp->inp_flags |= INP_ANONPORT;
345	return (0);
346}
347#endif
348
349#if defined(INET) || defined(INET6)
350int
351in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
352    struct ucred *cred, int lookupflags)
353{
354	struct inpcbinfo *pcbinfo;
355	struct inpcb *tmpinp;
356	unsigned short *lastport;
357	int count, dorandom, error;
358	u_short aux, first, last, lport;
359#ifdef INET
360	struct in_addr laddr;
361#endif
362
363	pcbinfo = inp->inp_pcbinfo;
364
365	/*
366	 * Because no actual state changes occur here, a global write lock on
367	 * the pcbinfo isn't required.
368	 */
369	INP_LOCK_ASSERT(inp);
370	INP_HASH_LOCK_ASSERT(pcbinfo);
371
372	if (inp->inp_flags & INP_HIGHPORT) {
373		first = V_ipport_hifirstauto;	/* sysctl */
374		last  = V_ipport_hilastauto;
375		lastport = &pcbinfo->ipi_lasthi;
376	} else if (inp->inp_flags & INP_LOWPORT) {
377		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
378		if (error)
379			return (error);
380		first = V_ipport_lowfirstauto;	/* 1023 */
381		last  = V_ipport_lowlastauto;	/* 600 */
382		lastport = &pcbinfo->ipi_lastlow;
383	} else {
384		first = V_ipport_firstauto;	/* sysctl */
385		last  = V_ipport_lastauto;
386		lastport = &pcbinfo->ipi_lastport;
387	}
388	/*
389	 * For UDP(-Lite), use random port allocation as long as the user
390	 * allows it.  For TCP (and as of yet unknown) connections,
391	 * use random port allocation only if the user allows it AND
392	 * ipport_tick() allows it.
393	 */
394	if (V_ipport_randomized &&
395		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
396		pcbinfo == &V_ulitecbinfo))
397		dorandom = 1;
398	else
399		dorandom = 0;
400	/*
401	 * It makes no sense to do random port allocation if
402	 * we have the only port available.
403	 */
404	if (first == last)
405		dorandom = 0;
406	/* Make sure to not include UDP(-Lite) packets in the count. */
407	if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
408		V_ipport_tcpallocs++;
409	/*
410	 * Instead of having two loops further down counting up or down
411	 * make sure that first is always <= last and go with only one
412	 * code path implementing all logic.
413	 */
414	if (first > last) {
415		aux = first;
416		first = last;
417		last = aux;
418	}
419
420#ifdef INET
421	/* Make the compiler happy. */
422	laddr.s_addr = 0;
423	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
424		KASSERT(laddrp != NULL, ("%s: laddrp NULL for v4 inp %p",
425		    __func__, inp));
426		laddr = *laddrp;
427	}
428#endif
429	tmpinp = NULL;	/* Make compiler happy. */
430	lport = *lportp;
431
432	if (dorandom)
433		*lastport = first + (arc4random() % (last - first));
434
435	count = last - first;
436
437	do {
438		if (count-- < 0)	/* completely used? */
439			return (EADDRNOTAVAIL);
440		++*lastport;
441		if (*lastport < first || *lastport > last)
442			*lastport = first;
443		lport = htons(*lastport);
444
445#ifdef INET6
446		if ((inp->inp_vflag & INP_IPV6) != 0)
447			tmpinp = in6_pcblookup_local(pcbinfo,
448			    &inp->in6p_laddr, lport, lookupflags, cred);
449#endif
450#if defined(INET) && defined(INET6)
451		else
452#endif
453#ifdef INET
454			tmpinp = in_pcblookup_local(pcbinfo, laddr,
455			    lport, lookupflags, cred);
456#endif
457	} while (tmpinp != NULL);
458
459#ifdef INET
460	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4)
461		laddrp->s_addr = laddr.s_addr;
462#endif
463	*lportp = lport;
464
465	return (0);
466}
467
468/*
469 * Return cached socket options.
470 */
471short
472inp_so_options(const struct inpcb *inp)
473{
474   short so_options;
475
476   so_options = 0;
477
478   if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
479	   so_options |= SO_REUSEPORT;
480   if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
481	   so_options |= SO_REUSEADDR;
482   return (so_options);
483}
484#endif /* INET || INET6 */
485
486#ifdef INET
487/*
488 * Set up a bind operation on a PCB, performing port allocation
489 * as required, but do not actually modify the PCB. Callers can
490 * either complete the bind by setting inp_laddr/inp_lport and
491 * calling in_pcbinshash(), or they can just use the resulting
492 * port and address to authorise the sending of a once-off packet.
493 *
494 * On error, the values of *laddrp and *lportp are not changed.
495 */
496int
497in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
498    u_short *lportp, struct ucred *cred)
499{
500	struct socket *so = inp->inp_socket;
501	struct sockaddr_in *sin;
502	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
503	struct in_addr laddr;
504	u_short lport = 0;
505	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
506	int error;
507
508	/*
509	 * No state changes, so read locks are sufficient here.
510	 */
511	INP_LOCK_ASSERT(inp);
512	INP_HASH_LOCK_ASSERT(pcbinfo);
513
514	if (TAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
515		return (EADDRNOTAVAIL);
516	laddr.s_addr = *laddrp;
517	if (nam != NULL && laddr.s_addr != INADDR_ANY)
518		return (EINVAL);
519	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
520		lookupflags = INPLOOKUP_WILDCARD;
521	if (nam == NULL) {
522		if ((error = prison_local_ip4(cred, &laddr)) != 0)
523			return (error);
524	} else {
525		sin = (struct sockaddr_in *)nam;
526		if (nam->sa_len != sizeof (*sin))
527			return (EINVAL);
528#ifdef notdef
529		/*
530		 * We should check the family, but old programs
531		 * incorrectly fail to initialize it.
532		 */
533		if (sin->sin_family != AF_INET)
534			return (EAFNOSUPPORT);
535#endif
536		error = prison_local_ip4(cred, &sin->sin_addr);
537		if (error)
538			return (error);
539		if (sin->sin_port != *lportp) {
540			/* Don't allow the port to change. */
541			if (*lportp != 0)
542				return (EINVAL);
543			lport = sin->sin_port;
544		}
545		/* NB: lport is left as 0 if the port isn't being changed. */
546		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
547			/*
548			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
549			 * allow complete duplication of binding if
550			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
551			 * and a multicast address is bound on both
552			 * new and duplicated sockets.
553			 */
554			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
555				reuseport = SO_REUSEADDR|SO_REUSEPORT;
556		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
557			sin->sin_port = 0;		/* yech... */
558			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
559			/*
560			 * Is the address a local IP address?
561			 * If INP_BINDANY is set, then the socket may be bound
562			 * to any endpoint address, local or not.
563			 */
564			if ((inp->inp_flags & INP_BINDANY) == 0 &&
565			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
566				return (EADDRNOTAVAIL);
567		}
568		laddr = sin->sin_addr;
569		if (lport) {
570			struct inpcb *t;
571			struct tcptw *tw;
572
573			/* GROSS */
574			if (ntohs(lport) <= V_ipport_reservedhigh &&
575			    ntohs(lport) >= V_ipport_reservedlow &&
576			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
577			    0))
578				return (EACCES);
579			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
580			    priv_check_cred(inp->inp_cred,
581			    PRIV_NETINET_REUSEPORT, 0) != 0) {
582				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
583				    lport, INPLOOKUP_WILDCARD, cred);
584	/*
585	 * XXX
586	 * This entire block sorely needs a rewrite.
587	 */
588				if (t &&
589				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
590				    (so->so_type != SOCK_STREAM ||
591				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
592				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
593				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
594				     (t->inp_flags2 & INP_REUSEPORT) == 0) &&
595				    (inp->inp_cred->cr_uid !=
596				     t->inp_cred->cr_uid))
597					return (EADDRINUSE);
598			}
599			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
600			    lport, lookupflags, cred);
601			if (t && (t->inp_flags & INP_TIMEWAIT)) {
602				/*
603				 * XXXRW: If an incpb has had its timewait
604				 * state recycled, we treat the address as
605				 * being in use (for now).  This is better
606				 * than a panic, but not desirable.
607				 */
608				tw = intotw(t);
609				if (tw == NULL ||
610				    (reuseport & tw->tw_so_options) == 0)
611					return (EADDRINUSE);
612			} else if (t && (reuseport & inp_so_options(t)) == 0) {
613#ifdef INET6
614				if (ntohl(sin->sin_addr.s_addr) !=
615				    INADDR_ANY ||
616				    ntohl(t->inp_laddr.s_addr) !=
617				    INADDR_ANY ||
618				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
619				    (t->inp_vflag & INP_IPV6PROTO) == 0)
620#endif
621				return (EADDRINUSE);
622			}
623		}
624	}
625	if (*lportp != 0)
626		lport = *lportp;
627	if (lport == 0) {
628		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
629		if (error != 0)
630			return (error);
631
632	}
633	*laddrp = laddr.s_addr;
634	*lportp = lport;
635	return (0);
636}
637
638/*
639 * Connect from a socket to a specified address.
640 * Both address and port must be specified in argument sin.
641 * If don't have a local address for this socket yet,
642 * then pick one.
643 */
644int
645in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
646    struct ucred *cred, struct mbuf *m)
647{
648	u_short lport, fport;
649	in_addr_t laddr, faddr;
650	int anonport, error;
651
652	INP_WLOCK_ASSERT(inp);
653	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
654
655	lport = inp->inp_lport;
656	laddr = inp->inp_laddr.s_addr;
657	anonport = (lport == 0);
658	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
659	    NULL, cred);
660	if (error)
661		return (error);
662
663	/* Do the initial binding of the local address if required. */
664	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
665		inp->inp_lport = lport;
666		inp->inp_laddr.s_addr = laddr;
667		if (in_pcbinshash(inp) != 0) {
668			inp->inp_laddr.s_addr = INADDR_ANY;
669			inp->inp_lport = 0;
670			return (EAGAIN);
671		}
672	}
673
674	/* Commit the remaining changes. */
675	inp->inp_lport = lport;
676	inp->inp_laddr.s_addr = laddr;
677	inp->inp_faddr.s_addr = faddr;
678	inp->inp_fport = fport;
679	in_pcbrehash_mbuf(inp, m);
680
681	if (anonport)
682		inp->inp_flags |= INP_ANONPORT;
683	return (0);
684}
685
686int
687in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
688{
689
690	return (in_pcbconnect_mbuf(inp, nam, cred, NULL));
691}
692
693/*
694 * Do proper source address selection on an unbound socket in case
695 * of connect. Take jails into account as well.
696 */
697int
698in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
699    struct ucred *cred)
700{
701	struct ifaddr *ifa;
702	struct sockaddr *sa;
703	struct sockaddr_in *sin;
704	struct route sro;
705	int error;
706
707	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
708
709	/*
710	 * Bypass source address selection and use the primary jail IP
711	 * if requested.
712	 */
713	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
714		return (0);
715
716	error = 0;
717	bzero(&sro, sizeof(sro));
718
719	sin = (struct sockaddr_in *)&sro.ro_dst;
720	sin->sin_family = AF_INET;
721	sin->sin_len = sizeof(struct sockaddr_in);
722	sin->sin_addr.s_addr = faddr->s_addr;
723
724	/*
725	 * If route is known our src addr is taken from the i/f,
726	 * else punt.
727	 *
728	 * Find out route to destination.
729	 */
730	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
731		in_rtalloc_ign(&sro, 0, inp->inp_inc.inc_fibnum);
732
733	/*
734	 * If we found a route, use the address corresponding to
735	 * the outgoing interface.
736	 *
737	 * Otherwise assume faddr is reachable on a directly connected
738	 * network and try to find a corresponding interface to take
739	 * the source address from.
740	 */
741	if (sro.ro_rt == NULL || sro.ro_rt->rt_ifp == NULL) {
742		struct in_ifaddr *ia;
743		struct ifnet *ifp;
744
745		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin));
746		if (ia == NULL)
747			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0));
748		if (ia == NULL) {
749			error = ENETUNREACH;
750			goto done;
751		}
752
753		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
754			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
755			ifa_free(&ia->ia_ifa);
756			goto done;
757		}
758
759		ifp = ia->ia_ifp;
760		ifa_free(&ia->ia_ifa);
761		ia = NULL;
762		IF_ADDR_RLOCK(ifp);
763		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
764
765			sa = ifa->ifa_addr;
766			if (sa->sa_family != AF_INET)
767				continue;
768			sin = (struct sockaddr_in *)sa;
769			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
770				ia = (struct in_ifaddr *)ifa;
771				break;
772			}
773		}
774		if (ia != NULL) {
775			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
776			IF_ADDR_RUNLOCK(ifp);
777			goto done;
778		}
779		IF_ADDR_RUNLOCK(ifp);
780
781		/* 3. As a last resort return the 'default' jail address. */
782		error = prison_get_ip4(cred, laddr);
783		goto done;
784	}
785
786	/*
787	 * If the outgoing interface on the route found is not
788	 * a loopback interface, use the address from that interface.
789	 * In case of jails do those three steps:
790	 * 1. check if the interface address belongs to the jail. If so use it.
791	 * 2. check if we have any address on the outgoing interface
792	 *    belonging to this jail. If so use it.
793	 * 3. as a last resort return the 'default' jail address.
794	 */
795	if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
796		struct in_ifaddr *ia;
797		struct ifnet *ifp;
798
799		/* If not jailed, use the default returned. */
800		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
801			ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
802			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
803			goto done;
804		}
805
806		/* Jailed. */
807		/* 1. Check if the iface address belongs to the jail. */
808		sin = (struct sockaddr_in *)sro.ro_rt->rt_ifa->ifa_addr;
809		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
810			ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
811			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
812			goto done;
813		}
814
815		/*
816		 * 2. Check if we have any address on the outgoing interface
817		 *    belonging to this jail.
818		 */
819		ia = NULL;
820		ifp = sro.ro_rt->rt_ifp;
821		IF_ADDR_RLOCK(ifp);
822		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
823			sa = ifa->ifa_addr;
824			if (sa->sa_family != AF_INET)
825				continue;
826			sin = (struct sockaddr_in *)sa;
827			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
828				ia = (struct in_ifaddr *)ifa;
829				break;
830			}
831		}
832		if (ia != NULL) {
833			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
834			IF_ADDR_RUNLOCK(ifp);
835			goto done;
836		}
837		IF_ADDR_RUNLOCK(ifp);
838
839		/* 3. As a last resort return the 'default' jail address. */
840		error = prison_get_ip4(cred, laddr);
841		goto done;
842	}
843
844	/*
845	 * The outgoing interface is marked with 'loopback net', so a route
846	 * to ourselves is here.
847	 * Try to find the interface of the destination address and then
848	 * take the address from there. That interface is not necessarily
849	 * a loopback interface.
850	 * In case of jails, check that it is an address of the jail
851	 * and if we cannot find, fall back to the 'default' jail address.
852	 */
853	if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
854		struct sockaddr_in sain;
855		struct in_ifaddr *ia;
856
857		bzero(&sain, sizeof(struct sockaddr_in));
858		sain.sin_family = AF_INET;
859		sain.sin_len = sizeof(struct sockaddr_in);
860		sain.sin_addr.s_addr = faddr->s_addr;
861
862		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sain)));
863		if (ia == NULL)
864			ia = ifatoia(ifa_ifwithnet(sintosa(&sain), 0));
865		if (ia == NULL)
866			ia = ifatoia(ifa_ifwithaddr(sintosa(&sain)));
867
868		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
869			if (ia == NULL) {
870				error = ENETUNREACH;
871				goto done;
872			}
873			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
874			ifa_free(&ia->ia_ifa);
875			goto done;
876		}
877
878		/* Jailed. */
879		if (ia != NULL) {
880			struct ifnet *ifp;
881
882			ifp = ia->ia_ifp;
883			ifa_free(&ia->ia_ifa);
884			ia = NULL;
885			IF_ADDR_RLOCK(ifp);
886			TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
887
888				sa = ifa->ifa_addr;
889				if (sa->sa_family != AF_INET)
890					continue;
891				sin = (struct sockaddr_in *)sa;
892				if (prison_check_ip4(cred,
893				    &sin->sin_addr) == 0) {
894					ia = (struct in_ifaddr *)ifa;
895					break;
896				}
897			}
898			if (ia != NULL) {
899				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
900				IF_ADDR_RUNLOCK(ifp);
901				goto done;
902			}
903			IF_ADDR_RUNLOCK(ifp);
904		}
905
906		/* 3. As a last resort return the 'default' jail address. */
907		error = prison_get_ip4(cred, laddr);
908		goto done;
909	}
910
911done:
912	if (sro.ro_rt != NULL)
913		RTFREE(sro.ro_rt);
914	return (error);
915}
916
917/*
918 * Set up for a connect from a socket to the specified address.
919 * On entry, *laddrp and *lportp should contain the current local
920 * address and port for the PCB; these are updated to the values
921 * that should be placed in inp_laddr and inp_lport to complete
922 * the connect.
923 *
924 * On success, *faddrp and *fportp will be set to the remote address
925 * and port. These are not updated in the error case.
926 *
927 * If the operation fails because the connection already exists,
928 * *oinpp will be set to the PCB of that connection so that the
929 * caller can decide to override it. In all other cases, *oinpp
930 * is set to NULL.
931 */
932int
933in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
934    in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
935    struct inpcb **oinpp, struct ucred *cred)
936{
937	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
938	struct in_ifaddr *ia;
939	struct inpcb *oinp;
940	struct in_addr laddr, faddr;
941	u_short lport, fport;
942	int error;
943
944	/*
945	 * Because a global state change doesn't actually occur here, a read
946	 * lock is sufficient.
947	 */
948	INP_LOCK_ASSERT(inp);
949	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
950
951	if (oinpp != NULL)
952		*oinpp = NULL;
953	if (nam->sa_len != sizeof (*sin))
954		return (EINVAL);
955	if (sin->sin_family != AF_INET)
956		return (EAFNOSUPPORT);
957	if (sin->sin_port == 0)
958		return (EADDRNOTAVAIL);
959	laddr.s_addr = *laddrp;
960	lport = *lportp;
961	faddr = sin->sin_addr;
962	fport = sin->sin_port;
963
964	if (!TAILQ_EMPTY(&V_in_ifaddrhead)) {
965		/*
966		 * If the destination address is INADDR_ANY,
967		 * use the primary local address.
968		 * If the supplied address is INADDR_BROADCAST,
969		 * and the primary interface supports broadcast,
970		 * choose the broadcast address for that interface.
971		 */
972		if (faddr.s_addr == INADDR_ANY) {
973			IN_IFADDR_RLOCK();
974			faddr =
975			    IA_SIN(TAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
976			IN_IFADDR_RUNLOCK();
977			if (cred != NULL &&
978			    (error = prison_get_ip4(cred, &faddr)) != 0)
979				return (error);
980		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
981			IN_IFADDR_RLOCK();
982			if (TAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
983			    IFF_BROADCAST)
984				faddr = satosin(&TAILQ_FIRST(
985				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
986			IN_IFADDR_RUNLOCK();
987		}
988	}
989	if (laddr.s_addr == INADDR_ANY) {
990		error = in_pcbladdr(inp, &faddr, &laddr, cred);
991		/*
992		 * If the destination address is multicast and an outgoing
993		 * interface has been set as a multicast option, prefer the
994		 * address of that interface as our source address.
995		 */
996		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
997		    inp->inp_moptions != NULL) {
998			struct ip_moptions *imo;
999			struct ifnet *ifp;
1000
1001			imo = inp->inp_moptions;
1002			if (imo->imo_multicast_ifp != NULL) {
1003				ifp = imo->imo_multicast_ifp;
1004				IN_IFADDR_RLOCK();
1005				TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1006					if ((ia->ia_ifp == ifp) &&
1007					    (cred == NULL ||
1008					    prison_check_ip4(cred,
1009					    &ia->ia_addr.sin_addr) == 0))
1010						break;
1011				}
1012				if (ia == NULL)
1013					error = EADDRNOTAVAIL;
1014				else {
1015					laddr = ia->ia_addr.sin_addr;
1016					error = 0;
1017				}
1018				IN_IFADDR_RUNLOCK();
1019			}
1020		}
1021		if (error)
1022			return (error);
1023	}
1024	oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr, fport,
1025	    laddr, lport, 0, NULL);
1026	if (oinp != NULL) {
1027		if (oinpp != NULL)
1028			*oinpp = oinp;
1029		return (EADDRINUSE);
1030	}
1031	if (lport == 0) {
1032		error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1033		    cred);
1034		if (error)
1035			return (error);
1036	}
1037	*laddrp = laddr.s_addr;
1038	*lportp = lport;
1039	*faddrp = faddr.s_addr;
1040	*fportp = fport;
1041	return (0);
1042}
1043
1044void
1045in_pcbdisconnect(struct inpcb *inp)
1046{
1047
1048	INP_WLOCK_ASSERT(inp);
1049	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1050
1051	inp->inp_faddr.s_addr = INADDR_ANY;
1052	inp->inp_fport = 0;
1053	in_pcbrehash(inp);
1054}
1055#endif /* INET */
1056
1057/*
1058 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1059 * For most protocols, this will be invoked immediately prior to calling
1060 * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
1061 * socket, in which case in_pcbfree() is deferred.
1062 */
1063void
1064in_pcbdetach(struct inpcb *inp)
1065{
1066
1067	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1068
1069	inp->inp_socket->so_pcb = NULL;
1070	inp->inp_socket = NULL;
1071}
1072
1073/*
1074 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1075 * stability of an inpcb pointer despite the inpcb lock being released.  This
1076 * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1077 * but where the inpcb lock may already held, or when acquiring a reference
1078 * via a pcbgroup.
1079 *
1080 * in_pcbref() should be used only to provide brief memory stability, and
1081 * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1082 * garbage collect the inpcb if it has been in_pcbfree()'d from another
1083 * context.  Until in_pcbrele() has returned that the inpcb is still valid,
1084 * lock and rele are the *only* safe operations that may be performed on the
1085 * inpcb.
1086 *
1087 * While the inpcb will not be freed, releasing the inpcb lock means that the
1088 * connection's state may change, so the caller should be careful to
1089 * revalidate any cached state on reacquiring the lock.  Drop the reference
1090 * using in_pcbrele().
1091 */
1092void
1093in_pcbref(struct inpcb *inp)
1094{
1095
1096	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1097
1098	refcount_acquire(&inp->inp_refcount);
1099}
1100
1101/*
1102 * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1103 * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1104 * return a flag indicating whether or not the inpcb remains valid.  If it is
1105 * valid, we return with the inpcb lock held.
1106 *
1107 * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1108 * reference on an inpcb.  Historically more work was done here (actually, in
1109 * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1110 * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
1111 * about memory stability (and continued use of the write lock).
1112 */
1113int
1114in_pcbrele_rlocked(struct inpcb *inp)
1115{
1116	struct inpcbinfo *pcbinfo;
1117
1118	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1119
1120	INP_RLOCK_ASSERT(inp);
1121
1122	if (refcount_release(&inp->inp_refcount) == 0) {
1123		/*
1124		 * If the inpcb has been freed, let the caller know, even if
1125		 * this isn't the last reference.
1126		 */
1127		if (inp->inp_flags2 & INP_FREED) {
1128			INP_RUNLOCK(inp);
1129			return (1);
1130		}
1131		return (0);
1132	}
1133
1134	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1135
1136	INP_RUNLOCK(inp);
1137	pcbinfo = inp->inp_pcbinfo;
1138	uma_zfree(pcbinfo->ipi_zone, inp);
1139	return (1);
1140}
1141
1142int
1143in_pcbrele_wlocked(struct inpcb *inp)
1144{
1145	struct inpcbinfo *pcbinfo;
1146
1147	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1148
1149	INP_WLOCK_ASSERT(inp);
1150
1151	if (refcount_release(&inp->inp_refcount) == 0)
1152		return (0);
1153
1154	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1155
1156	INP_WUNLOCK(inp);
1157	pcbinfo = inp->inp_pcbinfo;
1158	uma_zfree(pcbinfo->ipi_zone, inp);
1159	return (1);
1160}
1161
1162/*
1163 * Temporary wrapper.
1164 */
1165int
1166in_pcbrele(struct inpcb *inp)
1167{
1168
1169	return (in_pcbrele_wlocked(inp));
1170}
1171
1172/*
1173 * Unconditionally schedule an inpcb to be freed by decrementing its
1174 * reference count, which should occur only after the inpcb has been detached
1175 * from its socket.  If another thread holds a temporary reference (acquired
1176 * using in_pcbref()) then the free is deferred until that reference is
1177 * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
1178 * work, including removal from global lists, is done in this context, where
1179 * the pcbinfo lock is held.
1180 */
1181void
1182in_pcbfree(struct inpcb *inp)
1183{
1184	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1185
1186	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1187
1188	INP_INFO_WLOCK_ASSERT(pcbinfo);
1189	INP_WLOCK_ASSERT(inp);
1190
1191	/* XXXRW: Do as much as possible here. */
1192#ifdef IPSEC
1193	if (inp->inp_sp != NULL)
1194		ipsec_delete_pcbpolicy(inp);
1195#endif
1196	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1197	in_pcbremlists(inp);
1198#ifdef INET6
1199	if (inp->inp_vflag & INP_IPV6PROTO) {
1200		ip6_freepcbopts(inp->in6p_outputopts);
1201		if (inp->in6p_moptions != NULL)
1202			ip6_freemoptions(inp->in6p_moptions);
1203	}
1204#endif
1205	if (inp->inp_options)
1206		(void)m_free(inp->inp_options);
1207#ifdef INET
1208	if (inp->inp_moptions != NULL)
1209		inp_freemoptions(inp->inp_moptions);
1210#endif
1211	inp->inp_vflag = 0;
1212	inp->inp_flags2 |= INP_FREED;
1213	crfree(inp->inp_cred);
1214#ifdef MAC
1215	mac_inpcb_destroy(inp);
1216#endif
1217	if (!in_pcbrele_wlocked(inp))
1218		INP_WUNLOCK(inp);
1219}
1220
1221/*
1222 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1223 * port reservation, and preventing it from being returned by inpcb lookups.
1224 *
1225 * It is used by TCP to mark an inpcb as unused and avoid future packet
1226 * delivery or event notification when a socket remains open but TCP has
1227 * closed.  This might occur as a result of a shutdown()-initiated TCP close
1228 * or a RST on the wire, and allows the port binding to be reused while still
1229 * maintaining the invariant that so_pcb always points to a valid inpcb until
1230 * in_pcbdetach().
1231 *
1232 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1233 * in_pcbnotifyall() and in_pcbpurgeif0()?
1234 */
1235void
1236in_pcbdrop(struct inpcb *inp)
1237{
1238
1239	INP_WLOCK_ASSERT(inp);
1240
1241	/*
1242	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1243	 * the hash lock...?
1244	 */
1245	inp->inp_flags |= INP_DROPPED;
1246	if (inp->inp_flags & INP_INHASHLIST) {
1247		struct inpcbport *phd = inp->inp_phd;
1248
1249		INP_HASH_WLOCK(inp->inp_pcbinfo);
1250		LIST_REMOVE(inp, inp_hash);
1251		LIST_REMOVE(inp, inp_portlist);
1252		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1253			LIST_REMOVE(phd, phd_hash);
1254			free(phd, M_PCB);
1255		}
1256		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1257		inp->inp_flags &= ~INP_INHASHLIST;
1258#ifdef PCBGROUP
1259		in_pcbgroup_remove(inp);
1260#endif
1261	}
1262}
1263
1264#ifdef INET
1265/*
1266 * Common routines to return the socket addresses associated with inpcbs.
1267 */
1268struct sockaddr *
1269in_sockaddr(in_port_t port, struct in_addr *addr_p)
1270{
1271	struct sockaddr_in *sin;
1272
1273	sin = malloc(sizeof *sin, M_SONAME,
1274		M_WAITOK | M_ZERO);
1275	sin->sin_family = AF_INET;
1276	sin->sin_len = sizeof(*sin);
1277	sin->sin_addr = *addr_p;
1278	sin->sin_port = port;
1279
1280	return (struct sockaddr *)sin;
1281}
1282
1283int
1284in_getsockaddr(struct socket *so, struct sockaddr **nam)
1285{
1286	struct inpcb *inp;
1287	struct in_addr addr;
1288	in_port_t port;
1289
1290	inp = sotoinpcb(so);
1291	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1292
1293	INP_RLOCK(inp);
1294	port = inp->inp_lport;
1295	addr = inp->inp_laddr;
1296	INP_RUNLOCK(inp);
1297
1298	*nam = in_sockaddr(port, &addr);
1299	return 0;
1300}
1301
1302int
1303in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1304{
1305	struct inpcb *inp;
1306	struct in_addr addr;
1307	in_port_t port;
1308
1309	inp = sotoinpcb(so);
1310	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1311
1312	INP_RLOCK(inp);
1313	port = inp->inp_fport;
1314	addr = inp->inp_faddr;
1315	INP_RUNLOCK(inp);
1316
1317	*nam = in_sockaddr(port, &addr);
1318	return 0;
1319}
1320
1321void
1322in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1323    struct inpcb *(*notify)(struct inpcb *, int))
1324{
1325	struct inpcb *inp, *inp_temp;
1326
1327	INP_INFO_WLOCK(pcbinfo);
1328	LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1329		INP_WLOCK(inp);
1330#ifdef INET6
1331		if ((inp->inp_vflag & INP_IPV4) == 0) {
1332			INP_WUNLOCK(inp);
1333			continue;
1334		}
1335#endif
1336		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1337		    inp->inp_socket == NULL) {
1338			INP_WUNLOCK(inp);
1339			continue;
1340		}
1341		if ((*notify)(inp, errno))
1342			INP_WUNLOCK(inp);
1343	}
1344	INP_INFO_WUNLOCK(pcbinfo);
1345}
1346
1347void
1348in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1349{
1350	struct inpcb *inp;
1351	struct ip_moptions *imo;
1352	int i, gap;
1353
1354	INP_INFO_RLOCK(pcbinfo);
1355	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1356		INP_WLOCK(inp);
1357		imo = inp->inp_moptions;
1358		if ((inp->inp_vflag & INP_IPV4) &&
1359		    imo != NULL) {
1360			/*
1361			 * Unselect the outgoing interface if it is being
1362			 * detached.
1363			 */
1364			if (imo->imo_multicast_ifp == ifp)
1365				imo->imo_multicast_ifp = NULL;
1366
1367			/*
1368			 * Drop multicast group membership if we joined
1369			 * through the interface being detached.
1370			 */
1371			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1372			    i++) {
1373				if (imo->imo_membership[i]->inm_ifp == ifp) {
1374					in_delmulti(imo->imo_membership[i]);
1375					gap++;
1376				} else if (gap != 0)
1377					imo->imo_membership[i - gap] =
1378					    imo->imo_membership[i];
1379			}
1380			imo->imo_num_memberships -= gap;
1381		}
1382		INP_WUNLOCK(inp);
1383	}
1384	INP_INFO_RUNLOCK(pcbinfo);
1385}
1386
1387/*
1388 * Lookup a PCB based on the local address and port.  Caller must hold the
1389 * hash lock.  No inpcb locks or references are acquired.
1390 */
1391#define INP_LOOKUP_MAPPED_PCB_COST	3
1392struct inpcb *
1393in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1394    u_short lport, int lookupflags, struct ucred *cred)
1395{
1396	struct inpcb *inp;
1397#ifdef INET6
1398	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1399#else
1400	int matchwild = 3;
1401#endif
1402	int wildcard;
1403
1404	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1405	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1406
1407	INP_HASH_LOCK_ASSERT(pcbinfo);
1408
1409	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1410		struct inpcbhead *head;
1411		/*
1412		 * Look for an unconnected (wildcard foreign addr) PCB that
1413		 * matches the local address and port we're looking for.
1414		 */
1415		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1416		    0, pcbinfo->ipi_hashmask)];
1417		LIST_FOREACH(inp, head, inp_hash) {
1418#ifdef INET6
1419			/* XXX inp locking */
1420			if ((inp->inp_vflag & INP_IPV4) == 0)
1421				continue;
1422#endif
1423			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1424			    inp->inp_laddr.s_addr == laddr.s_addr &&
1425			    inp->inp_lport == lport) {
1426				/*
1427				 * Found?
1428				 */
1429				if (cred == NULL ||
1430				    prison_equal_ip4(cred->cr_prison,
1431					inp->inp_cred->cr_prison))
1432					return (inp);
1433			}
1434		}
1435		/*
1436		 * Not found.
1437		 */
1438		return (NULL);
1439	} else {
1440		struct inpcbporthead *porthash;
1441		struct inpcbport *phd;
1442		struct inpcb *match = NULL;
1443		/*
1444		 * Best fit PCB lookup.
1445		 *
1446		 * First see if this local port is in use by looking on the
1447		 * port hash list.
1448		 */
1449		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1450		    pcbinfo->ipi_porthashmask)];
1451		LIST_FOREACH(phd, porthash, phd_hash) {
1452			if (phd->phd_port == lport)
1453				break;
1454		}
1455		if (phd != NULL) {
1456			/*
1457			 * Port is in use by one or more PCBs. Look for best
1458			 * fit.
1459			 */
1460			LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1461				wildcard = 0;
1462				if (cred != NULL &&
1463				    !prison_equal_ip4(inp->inp_cred->cr_prison,
1464					cred->cr_prison))
1465					continue;
1466#ifdef INET6
1467				/* XXX inp locking */
1468				if ((inp->inp_vflag & INP_IPV4) == 0)
1469					continue;
1470				/*
1471				 * We never select the PCB that has
1472				 * INP_IPV6 flag and is bound to :: if
1473				 * we have another PCB which is bound
1474				 * to 0.0.0.0.  If a PCB has the
1475				 * INP_IPV6 flag, then we set its cost
1476				 * higher than IPv4 only PCBs.
1477				 *
1478				 * Note that the case only happens
1479				 * when a socket is bound to ::, under
1480				 * the condition that the use of the
1481				 * mapped address is allowed.
1482				 */
1483				if ((inp->inp_vflag & INP_IPV6) != 0)
1484					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1485#endif
1486				if (inp->inp_faddr.s_addr != INADDR_ANY)
1487					wildcard++;
1488				if (inp->inp_laddr.s_addr != INADDR_ANY) {
1489					if (laddr.s_addr == INADDR_ANY)
1490						wildcard++;
1491					else if (inp->inp_laddr.s_addr != laddr.s_addr)
1492						continue;
1493				} else {
1494					if (laddr.s_addr != INADDR_ANY)
1495						wildcard++;
1496				}
1497				if (wildcard < matchwild) {
1498					match = inp;
1499					matchwild = wildcard;
1500					if (matchwild == 0)
1501						break;
1502				}
1503			}
1504		}
1505		return (match);
1506	}
1507}
1508#undef INP_LOOKUP_MAPPED_PCB_COST
1509
1510#ifdef PCBGROUP
1511/*
1512 * Lookup PCB in hash list, using pcbgroup tables.
1513 */
1514static struct inpcb *
1515in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1516    struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1517    u_int lport_arg, int lookupflags, struct ifnet *ifp)
1518{
1519	struct inpcbhead *head;
1520	struct inpcb *inp, *tmpinp;
1521	u_short fport = fport_arg, lport = lport_arg;
1522
1523	/*
1524	 * First look for an exact match.
1525	 */
1526	tmpinp = NULL;
1527	INP_GROUP_LOCK(pcbgroup);
1528	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1529	    pcbgroup->ipg_hashmask)];
1530	LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1531#ifdef INET6
1532		/* XXX inp locking */
1533		if ((inp->inp_vflag & INP_IPV4) == 0)
1534			continue;
1535#endif
1536		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1537		    inp->inp_laddr.s_addr == laddr.s_addr &&
1538		    inp->inp_fport == fport &&
1539		    inp->inp_lport == lport) {
1540			/*
1541			 * XXX We should be able to directly return
1542			 * the inp here, without any checks.
1543			 * Well unless both bound with SO_REUSEPORT?
1544			 */
1545			if (prison_flag(inp->inp_cred, PR_IP4))
1546				goto found;
1547			if (tmpinp == NULL)
1548				tmpinp = inp;
1549		}
1550	}
1551	if (tmpinp != NULL) {
1552		inp = tmpinp;
1553		goto found;
1554	}
1555
1556	/*
1557	 * Then look for a wildcard match, if requested.
1558	 */
1559	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1560		struct inpcb *local_wild = NULL, *local_exact = NULL;
1561#ifdef INET6
1562		struct inpcb *local_wild_mapped = NULL;
1563#endif
1564		struct inpcb *jail_wild = NULL;
1565		struct inpcbhead *head;
1566		int injail;
1567
1568		/*
1569		 * Order of socket selection - we always prefer jails.
1570		 *      1. jailed, non-wild.
1571		 *      2. jailed, wild.
1572		 *      3. non-jailed, non-wild.
1573		 *      4. non-jailed, wild.
1574		 */
1575		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
1576		    0, pcbinfo->ipi_wildmask)];
1577		LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
1578#ifdef INET6
1579			/* XXX inp locking */
1580			if ((inp->inp_vflag & INP_IPV4) == 0)
1581				continue;
1582#endif
1583			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1584			    inp->inp_lport != lport)
1585				continue;
1586
1587			/* XXX inp locking */
1588			if (ifp && ifp->if_type == IFT_FAITH &&
1589			    (inp->inp_flags & INP_FAITH) == 0)
1590				continue;
1591
1592			injail = prison_flag(inp->inp_cred, PR_IP4);
1593			if (injail) {
1594				if (prison_check_ip4(inp->inp_cred,
1595				    &laddr) != 0)
1596					continue;
1597			} else {
1598				if (local_exact != NULL)
1599					continue;
1600			}
1601
1602			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1603				if (injail)
1604					goto found;
1605				else
1606					local_exact = inp;
1607			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1608#ifdef INET6
1609				/* XXX inp locking, NULL check */
1610				if (inp->inp_vflag & INP_IPV6PROTO)
1611					local_wild_mapped = inp;
1612				else
1613#endif
1614					if (injail)
1615						jail_wild = inp;
1616					else
1617						local_wild = inp;
1618			}
1619		} /* LIST_FOREACH */
1620		inp = jail_wild;
1621		if (inp == NULL)
1622			inp = local_exact;
1623		if (inp == NULL)
1624			inp = local_wild;
1625#ifdef INET6
1626		if (inp == NULL)
1627			inp = local_wild_mapped;
1628#endif
1629		if (inp != NULL)
1630			goto found;
1631	} /* if (lookupflags & INPLOOKUP_WILDCARD) */
1632	INP_GROUP_UNLOCK(pcbgroup);
1633	return (NULL);
1634
1635found:
1636	in_pcbref(inp);
1637	INP_GROUP_UNLOCK(pcbgroup);
1638	if (lookupflags & INPLOOKUP_WLOCKPCB) {
1639		INP_WLOCK(inp);
1640		if (in_pcbrele_wlocked(inp))
1641			return (NULL);
1642	} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1643		INP_RLOCK(inp);
1644		if (in_pcbrele_rlocked(inp))
1645			return (NULL);
1646	} else
1647		panic("%s: locking bug", __func__);
1648	return (inp);
1649}
1650#endif /* PCBGROUP */
1651
1652/*
1653 * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
1654 * that the caller has locked the hash list, and will not perform any further
1655 * locking or reference operations on either the hash list or the connection.
1656 */
1657static struct inpcb *
1658in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1659    u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
1660    struct ifnet *ifp)
1661{
1662	struct inpcbhead *head;
1663	struct inpcb *inp, *tmpinp;
1664	u_short fport = fport_arg, lport = lport_arg;
1665
1666	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1667	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1668
1669	INP_HASH_LOCK_ASSERT(pcbinfo);
1670
1671	/*
1672	 * First look for an exact match.
1673	 */
1674	tmpinp = NULL;
1675	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1676	    pcbinfo->ipi_hashmask)];
1677	LIST_FOREACH(inp, head, inp_hash) {
1678#ifdef INET6
1679		/* XXX inp locking */
1680		if ((inp->inp_vflag & INP_IPV4) == 0)
1681			continue;
1682#endif
1683		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1684		    inp->inp_laddr.s_addr == laddr.s_addr &&
1685		    inp->inp_fport == fport &&
1686		    inp->inp_lport == lport) {
1687			/*
1688			 * XXX We should be able to directly return
1689			 * the inp here, without any checks.
1690			 * Well unless both bound with SO_REUSEPORT?
1691			 */
1692			if (prison_flag(inp->inp_cred, PR_IP4))
1693				return (inp);
1694			if (tmpinp == NULL)
1695				tmpinp = inp;
1696		}
1697	}
1698	if (tmpinp != NULL)
1699		return (tmpinp);
1700
1701	/*
1702	 * Then look for a wildcard match, if requested.
1703	 */
1704	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1705		struct inpcb *local_wild = NULL, *local_exact = NULL;
1706#ifdef INET6
1707		struct inpcb *local_wild_mapped = NULL;
1708#endif
1709		struct inpcb *jail_wild = NULL;
1710		int injail;
1711
1712		/*
1713		 * Order of socket selection - we always prefer jails.
1714		 *      1. jailed, non-wild.
1715		 *      2. jailed, wild.
1716		 *      3. non-jailed, non-wild.
1717		 *      4. non-jailed, wild.
1718		 */
1719
1720		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1721		    0, pcbinfo->ipi_hashmask)];
1722		LIST_FOREACH(inp, head, inp_hash) {
1723#ifdef INET6
1724			/* XXX inp locking */
1725			if ((inp->inp_vflag & INP_IPV4) == 0)
1726				continue;
1727#endif
1728			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1729			    inp->inp_lport != lport)
1730				continue;
1731
1732			/* XXX inp locking */
1733			if (ifp && ifp->if_type == IFT_FAITH &&
1734			    (inp->inp_flags & INP_FAITH) == 0)
1735				continue;
1736
1737			injail = prison_flag(inp->inp_cred, PR_IP4);
1738			if (injail) {
1739				if (prison_check_ip4(inp->inp_cred,
1740				    &laddr) != 0)
1741					continue;
1742			} else {
1743				if (local_exact != NULL)
1744					continue;
1745			}
1746
1747			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1748				if (injail)
1749					return (inp);
1750				else
1751					local_exact = inp;
1752			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1753#ifdef INET6
1754				/* XXX inp locking, NULL check */
1755				if (inp->inp_vflag & INP_IPV6PROTO)
1756					local_wild_mapped = inp;
1757				else
1758#endif
1759					if (injail)
1760						jail_wild = inp;
1761					else
1762						local_wild = inp;
1763			}
1764		} /* LIST_FOREACH */
1765		if (jail_wild != NULL)
1766			return (jail_wild);
1767		if (local_exact != NULL)
1768			return (local_exact);
1769		if (local_wild != NULL)
1770			return (local_wild);
1771#ifdef INET6
1772		if (local_wild_mapped != NULL)
1773			return (local_wild_mapped);
1774#endif
1775	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
1776
1777	return (NULL);
1778}
1779
1780/*
1781 * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
1782 * hash list lock, and will return the inpcb locked (i.e., requires
1783 * INPLOOKUP_LOCKPCB).
1784 */
1785static struct inpcb *
1786in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1787    u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
1788    struct ifnet *ifp)
1789{
1790	struct inpcb *inp;
1791
1792	INP_HASH_RLOCK(pcbinfo);
1793	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
1794	    (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
1795	if (inp != NULL) {
1796		in_pcbref(inp);
1797		INP_HASH_RUNLOCK(pcbinfo);
1798		if (lookupflags & INPLOOKUP_WLOCKPCB) {
1799			INP_WLOCK(inp);
1800			if (in_pcbrele_wlocked(inp))
1801				return (NULL);
1802		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1803			INP_RLOCK(inp);
1804			if (in_pcbrele_rlocked(inp))
1805				return (NULL);
1806		} else
1807			panic("%s: locking bug", __func__);
1808	} else
1809		INP_HASH_RUNLOCK(pcbinfo);
1810	return (inp);
1811}
1812
1813/*
1814 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
1815 * from which a pre-calculated hash value may be extracted.
1816 *
1817 * Possibly more of this logic should be in in_pcbgroup.c.
1818 */
1819struct inpcb *
1820in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
1821    struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
1822{
1823#if defined(PCBGROUP)
1824	struct inpcbgroup *pcbgroup;
1825#endif
1826
1827	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1828	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1829	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1830	    ("%s: LOCKPCB not set", __func__));
1831
1832#if defined(PCBGROUP)
1833	if (in_pcbgroup_enabled(pcbinfo)) {
1834		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
1835		    fport);
1836		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
1837		    laddr, lport, lookupflags, ifp));
1838	}
1839#endif
1840	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
1841	    lookupflags, ifp));
1842}
1843
1844struct inpcb *
1845in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1846    u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
1847    struct ifnet *ifp, struct mbuf *m)
1848{
1849#ifdef PCBGROUP
1850	struct inpcbgroup *pcbgroup;
1851#endif
1852
1853	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1854	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1855	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1856	    ("%s: LOCKPCB not set", __func__));
1857
1858#ifdef PCBGROUP
1859	if (in_pcbgroup_enabled(pcbinfo)) {
1860		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
1861		    m->m_pkthdr.flowid);
1862		if (pcbgroup != NULL)
1863			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
1864			    fport, laddr, lport, lookupflags, ifp));
1865		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
1866		    fport);
1867		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
1868		    laddr, lport, lookupflags, ifp));
1869	}
1870#endif
1871	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
1872	    lookupflags, ifp));
1873}
1874#endif /* INET */
1875
1876/*
1877 * Insert PCB onto various hash lists.
1878 */
1879static int
1880in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
1881{
1882	struct inpcbhead *pcbhash;
1883	struct inpcbporthead *pcbporthash;
1884	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1885	struct inpcbport *phd;
1886	u_int32_t hashkey_faddr;
1887
1888	INP_WLOCK_ASSERT(inp);
1889	INP_HASH_WLOCK_ASSERT(pcbinfo);
1890
1891	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
1892	    ("in_pcbinshash: INP_INHASHLIST"));
1893
1894#ifdef INET6
1895	if (inp->inp_vflag & INP_IPV6)
1896		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
1897	else
1898#endif
1899	hashkey_faddr = inp->inp_faddr.s_addr;
1900
1901	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
1902		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
1903
1904	pcbporthash = &pcbinfo->ipi_porthashbase[
1905	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
1906
1907	/*
1908	 * Go through port list and look for a head for this lport.
1909	 */
1910	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1911		if (phd->phd_port == inp->inp_lport)
1912			break;
1913	}
1914	/*
1915	 * If none exists, malloc one and tack it on.
1916	 */
1917	if (phd == NULL) {
1918		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
1919		if (phd == NULL) {
1920			return (ENOBUFS); /* XXX */
1921		}
1922		phd->phd_port = inp->inp_lport;
1923		LIST_INIT(&phd->phd_pcblist);
1924		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1925	}
1926	inp->inp_phd = phd;
1927	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1928	LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
1929	inp->inp_flags |= INP_INHASHLIST;
1930#ifdef PCBGROUP
1931	if (do_pcbgroup_update)
1932		in_pcbgroup_update(inp);
1933#endif
1934	return (0);
1935}
1936
1937/*
1938 * For now, there are two public interfaces to insert an inpcb into the hash
1939 * lists -- one that does update pcbgroups, and one that doesn't.  The latter
1940 * is used only in the TCP syncache, where in_pcbinshash is called before the
1941 * full 4-tuple is set for the inpcb, and we don't want to install in the
1942 * pcbgroup until later.
1943 *
1944 * XXXRW: This seems like a misfeature.  in_pcbinshash should always update
1945 * connection groups, and partially initialised inpcbs should not be exposed
1946 * to either reservation hash tables or pcbgroups.
1947 */
1948int
1949in_pcbinshash(struct inpcb *inp)
1950{
1951
1952	return (in_pcbinshash_internal(inp, 1));
1953}
1954
1955int
1956in_pcbinshash_nopcbgroup(struct inpcb *inp)
1957{
1958
1959	return (in_pcbinshash_internal(inp, 0));
1960}
1961
1962/*
1963 * Move PCB to the proper hash bucket when { faddr, fport } have  been
1964 * changed. NOTE: This does not handle the case of the lport changing (the
1965 * hashed port list would have to be updated as well), so the lport must
1966 * not change after in_pcbinshash() has been called.
1967 */
1968void
1969in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
1970{
1971	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1972	struct inpcbhead *head;
1973	u_int32_t hashkey_faddr;
1974
1975	INP_WLOCK_ASSERT(inp);
1976	INP_HASH_WLOCK_ASSERT(pcbinfo);
1977
1978	KASSERT(inp->inp_flags & INP_INHASHLIST,
1979	    ("in_pcbrehash: !INP_INHASHLIST"));
1980
1981#ifdef INET6
1982	if (inp->inp_vflag & INP_IPV6)
1983		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
1984	else
1985#endif
1986	hashkey_faddr = inp->inp_faddr.s_addr;
1987
1988	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
1989		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
1990
1991	LIST_REMOVE(inp, inp_hash);
1992	LIST_INSERT_HEAD(head, inp, inp_hash);
1993
1994#ifdef PCBGROUP
1995	if (m != NULL)
1996		in_pcbgroup_update_mbuf(inp, m);
1997	else
1998		in_pcbgroup_update(inp);
1999#endif
2000}
2001
2002void
2003in_pcbrehash(struct inpcb *inp)
2004{
2005
2006	in_pcbrehash_mbuf(inp, NULL);
2007}
2008
2009/*
2010 * Remove PCB from various lists.
2011 */
2012static void
2013in_pcbremlists(struct inpcb *inp)
2014{
2015	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2016
2017	INP_INFO_WLOCK_ASSERT(pcbinfo);
2018	INP_WLOCK_ASSERT(inp);
2019
2020	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2021	if (inp->inp_flags & INP_INHASHLIST) {
2022		struct inpcbport *phd = inp->inp_phd;
2023
2024		INP_HASH_WLOCK(pcbinfo);
2025		LIST_REMOVE(inp, inp_hash);
2026		LIST_REMOVE(inp, inp_portlist);
2027		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
2028			LIST_REMOVE(phd, phd_hash);
2029			free(phd, M_PCB);
2030		}
2031		INP_HASH_WUNLOCK(pcbinfo);
2032		inp->inp_flags &= ~INP_INHASHLIST;
2033	}
2034	LIST_REMOVE(inp, inp_list);
2035	pcbinfo->ipi_count--;
2036#ifdef PCBGROUP
2037	in_pcbgroup_remove(inp);
2038#endif
2039}
2040
2041/*
2042 * A set label operation has occurred at the socket layer, propagate the
2043 * label change into the in_pcb for the socket.
2044 */
2045void
2046in_pcbsosetlabel(struct socket *so)
2047{
2048#ifdef MAC
2049	struct inpcb *inp;
2050
2051	inp = sotoinpcb(so);
2052	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2053
2054	INP_WLOCK(inp);
2055	SOCK_LOCK(so);
2056	mac_inpcb_sosetlabel(so, inp);
2057	SOCK_UNLOCK(so);
2058	INP_WUNLOCK(inp);
2059#endif
2060}
2061
2062/*
2063 * ipport_tick runs once per second, determining if random port allocation
2064 * should be continued.  If more than ipport_randomcps ports have been
2065 * allocated in the last second, then we return to sequential port
2066 * allocation. We return to random allocation only once we drop below
2067 * ipport_randomcps for at least ipport_randomtime seconds.
2068 */
2069static void
2070ipport_tick(void *xtp)
2071{
2072	VNET_ITERATOR_DECL(vnet_iter);
2073
2074	VNET_LIST_RLOCK_NOSLEEP();
2075	VNET_FOREACH(vnet_iter) {
2076		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
2077		if (V_ipport_tcpallocs <=
2078		    V_ipport_tcplastcount + V_ipport_randomcps) {
2079			if (V_ipport_stoprandom > 0)
2080				V_ipport_stoprandom--;
2081		} else
2082			V_ipport_stoprandom = V_ipport_randomtime;
2083		V_ipport_tcplastcount = V_ipport_tcpallocs;
2084		CURVNET_RESTORE();
2085	}
2086	VNET_LIST_RUNLOCK_NOSLEEP();
2087	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2088}
2089
2090static void
2091ip_fini(void *xtp)
2092{
2093
2094	callout_stop(&ipport_tick_callout);
2095}
2096
2097/*
2098 * The ipport_callout should start running at about the time we attach the
2099 * inet or inet6 domains.
2100 */
2101static void
2102ipport_tick_init(const void *unused __unused)
2103{
2104
2105	/* Start ipport_tick. */
2106	callout_init(&ipport_tick_callout, CALLOUT_MPSAFE);
2107	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2108	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2109		SHUTDOWN_PRI_DEFAULT);
2110}
2111SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2112    ipport_tick_init, NULL);
2113
2114void
2115inp_wlock(struct inpcb *inp)
2116{
2117
2118	INP_WLOCK(inp);
2119}
2120
2121void
2122inp_wunlock(struct inpcb *inp)
2123{
2124
2125	INP_WUNLOCK(inp);
2126}
2127
2128void
2129inp_rlock(struct inpcb *inp)
2130{
2131
2132	INP_RLOCK(inp);
2133}
2134
2135void
2136inp_runlock(struct inpcb *inp)
2137{
2138
2139	INP_RUNLOCK(inp);
2140}
2141
2142#ifdef INVARIANTS
2143void
2144inp_lock_assert(struct inpcb *inp)
2145{
2146
2147	INP_WLOCK_ASSERT(inp);
2148}
2149
2150void
2151inp_unlock_assert(struct inpcb *inp)
2152{
2153
2154	INP_UNLOCK_ASSERT(inp);
2155}
2156#endif
2157
2158void
2159inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2160{
2161	struct inpcb *inp;
2162
2163	INP_INFO_RLOCK(&V_tcbinfo);
2164	LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2165		INP_WLOCK(inp);
2166		func(inp, arg);
2167		INP_WUNLOCK(inp);
2168	}
2169	INP_INFO_RUNLOCK(&V_tcbinfo);
2170}
2171
2172struct socket *
2173inp_inpcbtosocket(struct inpcb *inp)
2174{
2175
2176	INP_WLOCK_ASSERT(inp);
2177	return (inp->inp_socket);
2178}
2179
2180struct tcpcb *
2181inp_inpcbtotcpcb(struct inpcb *inp)
2182{
2183
2184	INP_WLOCK_ASSERT(inp);
2185	return ((struct tcpcb *)inp->inp_ppcb);
2186}
2187
2188int
2189inp_ip_tos_get(const struct inpcb *inp)
2190{
2191
2192	return (inp->inp_ip_tos);
2193}
2194
2195void
2196inp_ip_tos_set(struct inpcb *inp, int val)
2197{
2198
2199	inp->inp_ip_tos = val;
2200}
2201
2202void
2203inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2204    uint32_t *faddr, uint16_t *fp)
2205{
2206
2207	INP_LOCK_ASSERT(inp);
2208	*laddr = inp->inp_laddr.s_addr;
2209	*faddr = inp->inp_faddr.s_addr;
2210	*lp = inp->inp_lport;
2211	*fp = inp->inp_fport;
2212}
2213
2214struct inpcb *
2215so_sotoinpcb(struct socket *so)
2216{
2217
2218	return (sotoinpcb(so));
2219}
2220
2221struct tcpcb *
2222so_sototcpcb(struct socket *so)
2223{
2224
2225	return (sototcpcb(so));
2226}
2227
2228#ifdef DDB
2229static void
2230db_print_indent(int indent)
2231{
2232	int i;
2233
2234	for (i = 0; i < indent; i++)
2235		db_printf(" ");
2236}
2237
2238static void
2239db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2240{
2241	char faddr_str[48], laddr_str[48];
2242
2243	db_print_indent(indent);
2244	db_printf("%s at %p\n", name, inc);
2245
2246	indent += 2;
2247
2248#ifdef INET6
2249	if (inc->inc_flags & INC_ISIPV6) {
2250		/* IPv6. */
2251		ip6_sprintf(laddr_str, &inc->inc6_laddr);
2252		ip6_sprintf(faddr_str, &inc->inc6_faddr);
2253	} else
2254#endif
2255	{
2256		/* IPv4. */
2257		inet_ntoa_r(inc->inc_laddr, laddr_str);
2258		inet_ntoa_r(inc->inc_faddr, faddr_str);
2259	}
2260	db_print_indent(indent);
2261	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
2262	    ntohs(inc->inc_lport));
2263	db_print_indent(indent);
2264	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
2265	    ntohs(inc->inc_fport));
2266}
2267
2268static void
2269db_print_inpflags(int inp_flags)
2270{
2271	int comma;
2272
2273	comma = 0;
2274	if (inp_flags & INP_RECVOPTS) {
2275		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2276		comma = 1;
2277	}
2278	if (inp_flags & INP_RECVRETOPTS) {
2279		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2280		comma = 1;
2281	}
2282	if (inp_flags & INP_RECVDSTADDR) {
2283		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2284		comma = 1;
2285	}
2286	if (inp_flags & INP_HDRINCL) {
2287		db_printf("%sINP_HDRINCL", comma ? ", " : "");
2288		comma = 1;
2289	}
2290	if (inp_flags & INP_HIGHPORT) {
2291		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2292		comma = 1;
2293	}
2294	if (inp_flags & INP_LOWPORT) {
2295		db_printf("%sINP_LOWPORT", comma ? ", " : "");
2296		comma = 1;
2297	}
2298	if (inp_flags & INP_ANONPORT) {
2299		db_printf("%sINP_ANONPORT", comma ? ", " : "");
2300		comma = 1;
2301	}
2302	if (inp_flags & INP_RECVIF) {
2303		db_printf("%sINP_RECVIF", comma ? ", " : "");
2304		comma = 1;
2305	}
2306	if (inp_flags & INP_MTUDISC) {
2307		db_printf("%sINP_MTUDISC", comma ? ", " : "");
2308		comma = 1;
2309	}
2310	if (inp_flags & INP_FAITH) {
2311		db_printf("%sINP_FAITH", comma ? ", " : "");
2312		comma = 1;
2313	}
2314	if (inp_flags & INP_RECVTTL) {
2315		db_printf("%sINP_RECVTTL", comma ? ", " : "");
2316		comma = 1;
2317	}
2318	if (inp_flags & INP_DONTFRAG) {
2319		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2320		comma = 1;
2321	}
2322	if (inp_flags & INP_RECVTOS) {
2323		db_printf("%sINP_RECVTOS", comma ? ", " : "");
2324		comma = 1;
2325	}
2326	if (inp_flags & IN6P_IPV6_V6ONLY) {
2327		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2328		comma = 1;
2329	}
2330	if (inp_flags & IN6P_PKTINFO) {
2331		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2332		comma = 1;
2333	}
2334	if (inp_flags & IN6P_HOPLIMIT) {
2335		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2336		comma = 1;
2337	}
2338	if (inp_flags & IN6P_HOPOPTS) {
2339		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2340		comma = 1;
2341	}
2342	if (inp_flags & IN6P_DSTOPTS) {
2343		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2344		comma = 1;
2345	}
2346	if (inp_flags & IN6P_RTHDR) {
2347		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2348		comma = 1;
2349	}
2350	if (inp_flags & IN6P_RTHDRDSTOPTS) {
2351		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2352		comma = 1;
2353	}
2354	if (inp_flags & IN6P_TCLASS) {
2355		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2356		comma = 1;
2357	}
2358	if (inp_flags & IN6P_AUTOFLOWLABEL) {
2359		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2360		comma = 1;
2361	}
2362	if (inp_flags & INP_TIMEWAIT) {
2363		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
2364		comma  = 1;
2365	}
2366	if (inp_flags & INP_ONESBCAST) {
2367		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2368		comma  = 1;
2369	}
2370	if (inp_flags & INP_DROPPED) {
2371		db_printf("%sINP_DROPPED", comma ? ", " : "");
2372		comma  = 1;
2373	}
2374	if (inp_flags & INP_SOCKREF) {
2375		db_printf("%sINP_SOCKREF", comma ? ", " : "");
2376		comma  = 1;
2377	}
2378	if (inp_flags & IN6P_RFC2292) {
2379		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2380		comma = 1;
2381	}
2382	if (inp_flags & IN6P_MTU) {
2383		db_printf("IN6P_MTU%s", comma ? ", " : "");
2384		comma = 1;
2385	}
2386}
2387
2388static void
2389db_print_inpvflag(u_char inp_vflag)
2390{
2391	int comma;
2392
2393	comma = 0;
2394	if (inp_vflag & INP_IPV4) {
2395		db_printf("%sINP_IPV4", comma ? ", " : "");
2396		comma  = 1;
2397	}
2398	if (inp_vflag & INP_IPV6) {
2399		db_printf("%sINP_IPV6", comma ? ", " : "");
2400		comma  = 1;
2401	}
2402	if (inp_vflag & INP_IPV6PROTO) {
2403		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2404		comma  = 1;
2405	}
2406}
2407
2408static void
2409db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2410{
2411
2412	db_print_indent(indent);
2413	db_printf("%s at %p\n", name, inp);
2414
2415	indent += 2;
2416
2417	db_print_indent(indent);
2418	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2419
2420	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2421
2422	db_print_indent(indent);
2423	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
2424	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2425
2426	db_print_indent(indent);
2427	db_printf("inp_label: %p   inp_flags: 0x%x (",
2428	   inp->inp_label, inp->inp_flags);
2429	db_print_inpflags(inp->inp_flags);
2430	db_printf(")\n");
2431
2432	db_print_indent(indent);
2433	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
2434	    inp->inp_vflag);
2435	db_print_inpvflag(inp->inp_vflag);
2436	db_printf(")\n");
2437
2438	db_print_indent(indent);
2439	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
2440	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2441
2442	db_print_indent(indent);
2443#ifdef INET6
2444	if (inp->inp_vflag & INP_IPV6) {
2445		db_printf("in6p_options: %p   in6p_outputopts: %p   "
2446		    "in6p_moptions: %p\n", inp->in6p_options,
2447		    inp->in6p_outputopts, inp->in6p_moptions);
2448		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
2449		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2450		    inp->in6p_hops);
2451	} else
2452#endif
2453	{
2454		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
2455		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2456		    inp->inp_options, inp->inp_moptions);
2457	}
2458
2459	db_print_indent(indent);
2460	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
2461	    (uintmax_t)inp->inp_gencnt);
2462}
2463
2464DB_SHOW_COMMAND(inpcb, db_show_inpcb)
2465{
2466	struct inpcb *inp;
2467
2468	if (!have_addr) {
2469		db_printf("usage: show inpcb <addr>\n");
2470		return;
2471	}
2472	inp = (struct inpcb *)addr;
2473
2474	db_print_inpcb(inp, "inpcb", 0);
2475}
2476#endif /* DDB */
2477