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