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